aframe-master.js 2.4 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997399983999940000400014000240003400044000540006400074000840009400104001140012400134001440015400164001740018400194002040021400224002340024400254002640027400284002940030400314003240033400344003540036400374003840039400404004140042400434004440045400464004740048400494005040051400524005340054400554005640057400584005940060400614006240063400644006540066400674006840069400704007140072400734007440075400764007740078400794008040081400824008340084400854008640087400884008940090400914009240093400944009540096400974009840099401004010140102401034010440105401064010740108401094011040111401124011340114401154011640117401184011940120401214012240123401244012540126401274012840129401304013140132401334013440135401364013740138401394014040141401424014340144401454014640147401484014940150401514015240153401544015540156401574015840159401604016140162401634016440165401664016740168401694017040171401724017340174401754017640177401784017940180401814018240183401844018540186401874018840189401904019140192401934019440195401964019740198401994020040201402024020340204402054020640207402084020940210402114021240213402144021540216402174021840219402204022140222402234022440225402264022740228402294023040231402324023340234402354023640237402384023940240402414024240243402444024540246402474024840249402504025140252402534025440255402564025740258402594026040261402624026340264402654026640267402684026940270402714027240273402744027540276402774027840279402804028140282402834028440285402864028740288402894029040291402924029340294402954029640297402984029940300403014030240303403044030540306403074030840309403104031140312403134031440315403164031740318403194032040321403224032340324403254032640327403284032940330403314033240333403344033540336403374033840339403404034140342403434034440345403464034740348403494035040351403524035340354403554035640357403584035940360403614036240363403644036540366403674036840369403704037140372403734037440375403764037740378403794038040381403824038340384403854038640387403884038940390403914039240393403944039540396403974039840399404004040140402404034040440405404064040740408404094041040411404124041340414404154041640417404184041940420404214042240423404244042540426404274042840429404304043140432404334043440435404364043740438404394044040441404424044340444404454044640447404484044940450404514045240453404544045540456404574045840459404604046140462404634046440465404664046740468404694047040471404724047340474404754047640477404784047940480404814048240483404844048540486404874048840489404904049140492404934049440495404964049740498404994050040501405024050340504405054050640507405084050940510405114051240513405144051540516405174051840519405204052140522405234052440525405264052740528405294053040531405324053340534405354053640537405384053940540405414054240543405444054540546405474054840549405504055140552405534055440555405564055740558405594056040561405624056340564405654056640567405684056940570405714057240573405744057540576405774057840579405804058140582405834058440585405864058740588405894059040591405924059340594405954059640597405984059940600406014060240603406044060540606406074060840609406104061140612406134061440615406164061740618406194062040621406224062340624406254062640627406284062940630406314063240633406344063540636406374063840639406404064140642406434064440645406464064740648406494065040651406524065340654406554065640657406584065940660406614066240663406644066540666406674066840669406704067140672406734067440675406764067740678406794068040681406824068340684406854068640687406884068940690406914069240693406944069540696406974069840699407004070140702407034070440705407064070740708407094071040711407124071340714407154071640717407184071940720407214072240723407244072540726407274072840729407304073140732407334073440735407364073740738407394074040741407424074340744407454074640747407484074940750407514075240753407544075540756407574075840759407604076140762407634076440765407664076740768407694077040771407724077340774407754077640777407784077940780407814078240783407844078540786407874078840789407904079140792407934079440795407964079740798407994080040801408024080340804408054080640807408084080940810408114081240813408144081540816408174081840819408204082140822408234082440825408264082740828408294083040831408324083340834408354083640837408384083940840408414084240843408444084540846408474084840849408504085140852408534085440855408564085740858408594086040861408624086340864408654086640867408684086940870408714087240873408744087540876408774087840879408804088140882408834088440885408864088740888408894089040891408924089340894408954089640897408984089940900409014090240903409044090540906409074090840909409104091140912409134091440915409164091740918409194092040921409224092340924409254092640927409284092940930409314093240933409344093540936409374093840939409404094140942409434094440945409464094740948409494095040951409524095340954409554095640957409584095940960409614096240963409644096540966409674096840969409704097140972409734097440975409764097740978409794098040981409824098340984409854098640987409884098940990409914099240993409944099540996409974099840999410004100141002410034100441005410064100741008410094101041011410124101341014410154101641017410184101941020410214102241023410244102541026410274102841029410304103141032410334103441035410364103741038410394104041041410424104341044410454104641047410484104941050410514105241053410544105541056410574105841059410604106141062410634106441065410664106741068410694107041071410724107341074410754107641077410784107941080410814108241083410844108541086410874108841089410904109141092410934109441095410964109741098410994110041101411024110341104411054110641107411084110941110411114111241113411144111541116411174111841119411204112141122411234112441125411264112741128411294113041131411324113341134411354113641137411384113941140411414114241143411444114541146411474114841149411504115141152411534115441155411564115741158411594116041161411624116341164411654116641167411684116941170411714117241173411744117541176411774117841179411804118141182411834118441185411864118741188411894119041191411924119341194411954119641197411984119941200412014120241203412044120541206412074120841209412104121141212412134121441215412164121741218412194122041221412224122341224412254122641227412284122941230412314123241233412344123541236412374123841239412404124141242412434124441245412464124741248412494125041251412524125341254412554125641257412584125941260412614126241263412644126541266412674126841269412704127141272412734127441275412764127741278412794128041281412824128341284412854128641287412884128941290412914129241293412944129541296412974129841299413004130141302413034130441305413064130741308413094131041311413124131341314413154131641317413184131941320413214132241323413244132541326413274132841329413304133141332413334133441335413364133741338413394134041341413424134341344413454134641347413484134941350413514135241353413544135541356413574135841359413604136141362413634136441365413664136741368413694137041371413724137341374413754137641377413784137941380413814138241383413844138541386413874138841389413904139141392413934139441395413964139741398413994140041401414024140341404414054140641407414084140941410414114141241413414144141541416414174141841419414204142141422414234142441425414264142741428414294143041431414324143341434414354143641437414384143941440414414144241443414444144541446414474144841449414504145141452414534145441455414564145741458414594146041461414624146341464414654146641467414684146941470414714147241473414744147541476414774147841479414804148141482414834148441485414864148741488414894149041491414924149341494414954149641497414984149941500415014150241503415044150541506415074150841509415104151141512415134151441515415164151741518415194152041521415224152341524415254152641527415284152941530415314153241533415344153541536415374153841539415404154141542415434154441545415464154741548415494155041551415524155341554415554155641557415584155941560415614156241563415644156541566415674156841569415704157141572415734157441575415764157741578415794158041581415824158341584415854158641587415884158941590415914159241593415944159541596415974159841599416004160141602416034160441605416064160741608416094161041611416124161341614416154161641617416184161941620416214162241623416244162541626416274162841629416304163141632416334163441635416364163741638416394164041641416424164341644416454164641647416484164941650416514165241653416544165541656416574165841659416604166141662416634166441665416664166741668416694167041671416724167341674416754167641677416784167941680416814168241683416844168541686416874168841689416904169141692416934169441695416964169741698416994170041701417024170341704417054170641707417084170941710417114171241713417144171541716417174171841719417204172141722417234172441725417264172741728417294173041731417324173341734417354173641737417384173941740417414174241743417444174541746417474174841749417504175141752417534175441755417564175741758417594176041761417624176341764417654176641767417684176941770417714177241773417744177541776417774177841779417804178141782417834178441785417864178741788417894179041791417924179341794417954179641797417984179941800418014180241803418044180541806418074180841809418104181141812418134181441815418164181741818418194182041821418224182341824418254182641827418284182941830418314183241833418344183541836418374183841839418404184141842418434184441845418464184741848418494185041851418524185341854418554185641857418584185941860418614186241863418644186541866418674186841869418704187141872418734187441875418764187741878418794188041881418824188341884418854188641887418884188941890418914189241893418944189541896418974189841899419004190141902419034190441905419064190741908419094191041911419124191341914419154191641917419184191941920419214192241923419244192541926419274192841929419304193141932419334193441935419364193741938419394194041941419424194341944419454194641947419484194941950419514195241953419544195541956419574195841959419604196141962419634196441965419664196741968419694197041971419724197341974419754197641977419784197941980419814198241983419844198541986419874198841989419904199141992419934199441995419964199741998419994200042001420024200342004420054200642007420084200942010420114201242013420144201542016420174201842019420204202142022420234202442025420264202742028420294203042031420324203342034420354203642037420384203942040420414204242043420444204542046420474204842049420504205142052420534205442055420564205742058420594206042061420624206342064420654206642067420684206942070420714207242073420744207542076420774207842079420804208142082420834208442085420864208742088420894209042091420924209342094420954209642097420984209942100421014210242103421044210542106421074210842109421104211142112421134211442115421164211742118421194212042121421224212342124421254212642127421284212942130421314213242133421344213542136421374213842139421404214142142421434214442145421464214742148421494215042151421524215342154421554215642157421584215942160421614216242163421644216542166421674216842169421704217142172421734217442175421764217742178421794218042181421824218342184421854218642187421884218942190421914219242193421944219542196421974219842199422004220142202422034220442205422064220742208422094221042211422124221342214422154221642217422184221942220422214222242223422244222542226422274222842229422304223142232422334223442235422364223742238422394224042241422424224342244422454224642247422484224942250422514225242253422544225542256422574225842259422604226142262422634226442265422664226742268422694227042271422724227342274422754227642277422784227942280422814228242283422844228542286422874228842289422904229142292422934229442295422964229742298422994230042301423024230342304423054230642307423084230942310423114231242313423144231542316423174231842319423204232142322423234232442325423264232742328423294233042331423324233342334423354233642337423384233942340423414234242343423444234542346423474234842349423504235142352423534235442355423564235742358423594236042361423624236342364423654236642367423684236942370423714237242373423744237542376423774237842379423804238142382423834238442385423864238742388423894239042391423924239342394423954239642397423984239942400424014240242403424044240542406424074240842409424104241142412424134241442415424164241742418424194242042421424224242342424424254242642427424284242942430424314243242433424344243542436424374243842439424404244142442424434244442445424464244742448424494245042451424524245342454424554245642457424584245942460424614246242463424644246542466424674246842469424704247142472424734247442475424764247742478424794248042481424824248342484424854248642487424884248942490424914249242493424944249542496424974249842499425004250142502425034250442505425064250742508425094251042511425124251342514425154251642517425184251942520425214252242523425244252542526425274252842529425304253142532425334253442535425364253742538425394254042541425424254342544425454254642547425484254942550425514255242553425544255542556425574255842559425604256142562425634256442565425664256742568425694257042571425724257342574425754257642577425784257942580425814258242583425844258542586425874258842589425904259142592425934259442595425964259742598425994260042601426024260342604426054260642607426084260942610426114261242613426144261542616426174261842619426204262142622426234262442625426264262742628426294263042631426324263342634426354263642637426384263942640426414264242643426444264542646426474264842649426504265142652426534265442655426564265742658426594266042661426624266342664426654266642667426684266942670426714267242673426744267542676426774267842679426804268142682426834268442685426864268742688426894269042691426924269342694426954269642697426984269942700427014270242703427044270542706427074270842709427104271142712427134271442715427164271742718427194272042721427224272342724427254272642727427284272942730427314273242733427344273542736427374273842739427404274142742427434274442745427464274742748427494275042751427524275342754427554275642757427584275942760427614276242763427644276542766427674276842769427704277142772427734277442775427764277742778427794278042781427824278342784427854278642787427884278942790427914279242793427944279542796427974279842799428004280142802428034280442805428064280742808428094281042811428124281342814428154281642817428184281942820428214282242823428244282542826428274282842829428304283142832428334283442835428364283742838428394284042841428424284342844428454284642847428484284942850428514285242853428544285542856428574285842859428604286142862428634286442865428664286742868428694287042871428724287342874428754287642877428784287942880428814288242883428844288542886428874288842889428904289142892428934289442895428964289742898428994290042901429024290342904429054290642907429084290942910429114291242913429144291542916429174291842919429204292142922429234292442925429264292742928429294293042931429324293342934429354293642937429384293942940429414294242943429444294542946429474294842949429504295142952429534295442955429564295742958429594296042961429624296342964429654296642967429684296942970429714297242973429744297542976429774297842979429804298142982429834298442985429864298742988429894299042991429924299342994429954299642997429984299943000430014300243003430044300543006430074300843009430104301143012430134301443015430164301743018430194302043021430224302343024430254302643027430284302943030430314303243033430344303543036430374303843039430404304143042430434304443045430464304743048430494305043051430524305343054430554305643057430584305943060430614306243063430644306543066430674306843069430704307143072430734307443075430764307743078430794308043081430824308343084430854308643087430884308943090430914309243093430944309543096430974309843099431004310143102431034310443105431064310743108431094311043111431124311343114431154311643117431184311943120431214312243123431244312543126431274312843129431304313143132431334313443135431364313743138431394314043141431424314343144431454314643147431484314943150431514315243153431544315543156431574315843159431604316143162431634316443165431664316743168431694317043171431724317343174431754317643177431784317943180431814318243183431844318543186431874318843189431904319143192431934319443195431964319743198431994320043201432024320343204432054320643207432084320943210432114321243213432144321543216432174321843219432204322143222432234322443225432264322743228432294323043231432324323343234432354323643237432384323943240432414324243243432444324543246432474324843249432504325143252432534325443255432564325743258432594326043261432624326343264432654326643267432684326943270432714327243273432744327543276432774327843279432804328143282432834328443285432864328743288432894329043291432924329343294432954329643297432984329943300433014330243303433044330543306433074330843309433104331143312433134331443315433164331743318433194332043321433224332343324433254332643327433284332943330433314333243333433344333543336433374333843339433404334143342433434334443345433464334743348433494335043351433524335343354433554335643357433584335943360433614336243363433644336543366433674336843369433704337143372433734337443375433764337743378433794338043381433824338343384433854338643387433884338943390433914339243393433944339543396433974339843399434004340143402434034340443405434064340743408434094341043411434124341343414434154341643417434184341943420434214342243423434244342543426434274342843429434304343143432434334343443435434364343743438434394344043441434424344343444434454344643447434484344943450434514345243453434544345543456434574345843459434604346143462434634346443465434664346743468434694347043471434724347343474434754347643477434784347943480434814348243483434844348543486434874348843489434904349143492434934349443495434964349743498434994350043501435024350343504435054350643507435084350943510435114351243513435144351543516435174351843519435204352143522435234352443525435264352743528435294353043531435324353343534435354353643537435384353943540435414354243543435444354543546435474354843549435504355143552435534355443555435564355743558435594356043561435624356343564435654356643567435684356943570435714357243573435744357543576435774357843579435804358143582435834358443585435864358743588435894359043591435924359343594435954359643597435984359943600436014360243603436044360543606436074360843609436104361143612436134361443615436164361743618436194362043621436224362343624436254362643627436284362943630436314363243633436344363543636436374363843639436404364143642436434364443645436464364743648436494365043651436524365343654436554365643657436584365943660436614366243663436644366543666436674366843669436704367143672436734367443675436764367743678436794368043681436824368343684436854368643687436884368943690436914369243693436944369543696436974369843699437004370143702437034370443705437064370743708437094371043711437124371343714437154371643717437184371943720437214372243723437244372543726437274372843729437304373143732437334373443735437364373743738437394374043741437424374343744437454374643747437484374943750437514375243753437544375543756437574375843759437604376143762437634376443765437664376743768437694377043771437724377343774437754377643777437784377943780437814378243783437844378543786437874378843789437904379143792437934379443795437964379743798437994380043801438024380343804438054380643807438084380943810438114381243813438144381543816438174381843819438204382143822438234382443825438264382743828438294383043831438324383343834438354383643837438384383943840438414384243843438444384543846438474384843849438504385143852438534385443855438564385743858438594386043861438624386343864438654386643867438684386943870438714387243873438744387543876438774387843879438804388143882438834388443885438864388743888438894389043891438924389343894438954389643897438984389943900439014390243903439044390543906439074390843909439104391143912439134391443915439164391743918439194392043921439224392343924439254392643927439284392943930439314393243933439344393543936439374393843939439404394143942439434394443945439464394743948439494395043951439524395343954439554395643957439584395943960439614396243963439644396543966439674396843969439704397143972439734397443975439764397743978439794398043981439824398343984439854398643987439884398943990439914399243993439944399543996439974399843999440004400144002440034400444005440064400744008440094401044011440124401344014440154401644017440184401944020440214402244023440244402544026440274402844029440304403144032440334403444035440364403744038440394404044041440424404344044440454404644047440484404944050440514405244053440544405544056440574405844059440604406144062440634406444065440664406744068440694407044071440724407344074440754407644077440784407944080440814408244083440844408544086440874408844089440904409144092440934409444095440964409744098440994410044101441024410344104441054410644107441084410944110441114411244113441144411544116441174411844119441204412144122441234412444125441264412744128441294413044131441324413344134441354413644137441384413944140441414414244143441444414544146441474414844149441504415144152441534415444155441564415744158441594416044161441624416344164441654416644167441684416944170441714417244173441744417544176441774417844179441804418144182441834418444185441864418744188441894419044191441924419344194441954419644197441984419944200442014420244203442044420544206442074420844209442104421144212442134421444215442164421744218442194422044221442224422344224442254422644227442284422944230442314423244233442344423544236442374423844239442404424144242442434424444245442464424744248442494425044251442524425344254442554425644257442584425944260442614426244263442644426544266442674426844269442704427144272442734427444275442764427744278442794428044281442824428344284442854428644287442884428944290442914429244293442944429544296442974429844299443004430144302443034430444305443064430744308443094431044311443124431344314443154431644317443184431944320443214432244323443244432544326443274432844329443304433144332443334433444335443364433744338443394434044341443424434344344443454434644347443484434944350443514435244353443544435544356443574435844359443604436144362443634436444365443664436744368443694437044371443724437344374443754437644377443784437944380443814438244383443844438544386443874438844389443904439144392443934439444395443964439744398443994440044401444024440344404444054440644407444084440944410444114441244413444144441544416444174441844419444204442144422444234442444425444264442744428444294443044431444324443344434444354443644437444384443944440444414444244443444444444544446444474444844449444504445144452444534445444455444564445744458444594446044461444624446344464444654446644467444684446944470444714447244473444744447544476444774447844479444804448144482444834448444485444864448744488444894449044491444924449344494444954449644497444984449944500445014450244503445044450544506445074450844509445104451144512445134451444515445164451744518445194452044521445224452344524445254452644527445284452944530445314453244533445344453544536445374453844539445404454144542445434454444545445464454744548445494455044551445524455344554445554455644557445584455944560445614456244563445644456544566445674456844569445704457144572445734457444575445764457744578445794458044581445824458344584445854458644587445884458944590445914459244593445944459544596445974459844599446004460144602446034460444605446064460744608446094461044611446124461344614446154461644617446184461944620446214462244623446244462544626446274462844629446304463144632446334463444635446364463744638446394464044641446424464344644446454464644647446484464944650446514465244653446544465544656446574465844659446604466144662446634466444665446664466744668446694467044671446724467344674446754467644677446784467944680446814468244683446844468544686446874468844689446904469144692446934469444695446964469744698446994470044701447024470344704447054470644707447084470944710447114471244713447144471544716447174471844719447204472144722447234472444725447264472744728447294473044731447324473344734447354473644737447384473944740447414474244743447444474544746447474474844749447504475144752447534475444755447564475744758447594476044761447624476344764447654476644767447684476944770447714477244773447744477544776447774477844779447804478144782447834478444785447864478744788447894479044791447924479344794447954479644797447984479944800448014480244803448044480544806448074480844809448104481144812448134481444815448164481744818448194482044821448224482344824448254482644827448284482944830448314483244833448344483544836448374483844839448404484144842448434484444845448464484744848448494485044851448524485344854448554485644857448584485944860448614486244863448644486544866448674486844869448704487144872448734487444875448764487744878448794488044881448824488344884448854488644887448884488944890448914489244893448944489544896448974489844899449004490144902449034490444905449064490744908449094491044911449124491344914449154491644917449184491944920449214492244923449244492544926449274492844929449304493144932449334493444935449364493744938449394494044941449424494344944449454494644947449484494944950449514495244953449544495544956449574495844959449604496144962449634496444965449664496744968449694497044971449724497344974449754497644977449784497944980449814498244983449844498544986449874498844989449904499144992449934499444995449964499744998449994500045001450024500345004450054500645007450084500945010450114501245013450144501545016450174501845019450204502145022450234502445025450264502745028450294503045031450324503345034450354503645037450384503945040450414504245043450444504545046450474504845049450504505145052450534505445055450564505745058450594506045061450624506345064450654506645067450684506945070450714507245073450744507545076450774507845079450804508145082450834508445085450864508745088450894509045091450924509345094450954509645097450984509945100451014510245103451044510545106451074510845109451104511145112451134511445115451164511745118451194512045121451224512345124451254512645127451284512945130451314513245133451344513545136451374513845139451404514145142451434514445145451464514745148451494515045151451524515345154451554515645157451584515945160451614516245163451644516545166451674516845169451704517145172451734517445175451764517745178451794518045181451824518345184451854518645187451884518945190451914519245193451944519545196451974519845199452004520145202452034520445205452064520745208452094521045211452124521345214452154521645217452184521945220452214522245223452244522545226452274522845229452304523145232452334523445235452364523745238452394524045241452424524345244452454524645247452484524945250452514525245253452544525545256452574525845259452604526145262452634526445265452664526745268452694527045271452724527345274452754527645277452784527945280452814528245283452844528545286452874528845289452904529145292452934529445295452964529745298452994530045301453024530345304453054530645307453084530945310453114531245313453144531545316453174531845319453204532145322453234532445325453264532745328453294533045331453324533345334453354533645337453384533945340453414534245343453444534545346453474534845349453504535145352453534535445355453564535745358453594536045361453624536345364453654536645367453684536945370453714537245373453744537545376453774537845379453804538145382453834538445385453864538745388453894539045391453924539345394453954539645397453984539945400454014540245403454044540545406454074540845409454104541145412454134541445415454164541745418454194542045421454224542345424454254542645427454284542945430454314543245433454344543545436454374543845439454404544145442454434544445445454464544745448454494545045451454524545345454454554545645457454584545945460454614546245463454644546545466454674546845469454704547145472454734547445475454764547745478454794548045481454824548345484454854548645487454884548945490454914549245493454944549545496454974549845499455004550145502455034550445505455064550745508455094551045511455124551345514455154551645517455184551945520455214552245523455244552545526455274552845529455304553145532455334553445535455364553745538455394554045541455424554345544455454554645547455484554945550455514555245553455544555545556455574555845559455604556145562455634556445565455664556745568455694557045571455724557345574455754557645577455784557945580455814558245583455844558545586455874558845589455904559145592455934559445595455964559745598455994560045601456024560345604456054560645607456084560945610456114561245613456144561545616456174561845619456204562145622456234562445625456264562745628456294563045631456324563345634456354563645637456384563945640456414564245643456444564545646456474564845649456504565145652456534565445655456564565745658456594566045661456624566345664456654566645667456684566945670456714567245673456744567545676456774567845679456804568145682456834568445685456864568745688456894569045691456924569345694456954569645697456984569945700457014570245703457044570545706457074570845709457104571145712457134571445715457164571745718457194572045721457224572345724457254572645727457284572945730457314573245733457344573545736457374573845739457404574145742457434574445745457464574745748457494575045751457524575345754457554575645757457584575945760457614576245763457644576545766457674576845769457704577145772457734577445775457764577745778457794578045781457824578345784457854578645787457884578945790457914579245793457944579545796457974579845799458004580145802458034580445805458064580745808458094581045811458124581345814458154581645817458184581945820458214582245823458244582545826458274582845829458304583145832458334583445835458364583745838458394584045841458424584345844458454584645847458484584945850458514585245853458544585545856458574585845859458604586145862458634586445865458664586745868458694587045871458724587345874458754587645877458784587945880458814588245883458844588545886458874588845889458904589145892458934589445895458964589745898458994590045901459024590345904459054590645907459084590945910459114591245913459144591545916459174591845919459204592145922459234592445925459264592745928459294593045931459324593345934459354593645937459384593945940459414594245943459444594545946459474594845949459504595145952459534595445955459564595745958459594596045961459624596345964459654596645967459684596945970459714597245973459744597545976459774597845979459804598145982459834598445985459864598745988459894599045991459924599345994459954599645997459984599946000460014600246003460044600546006460074600846009460104601146012460134601446015460164601746018460194602046021460224602346024460254602646027460284602946030460314603246033460344603546036460374603846039460404604146042460434604446045460464604746048460494605046051460524605346054460554605646057460584605946060460614606246063460644606546066460674606846069460704607146072460734607446075460764607746078460794608046081460824608346084460854608646087460884608946090460914609246093460944609546096460974609846099461004610146102461034610446105461064610746108461094611046111461124611346114461154611646117461184611946120461214612246123461244612546126461274612846129461304613146132461334613446135461364613746138461394614046141461424614346144461454614646147461484614946150461514615246153461544615546156461574615846159461604616146162461634616446165461664616746168461694617046171461724617346174461754617646177461784617946180461814618246183461844618546186461874618846189461904619146192461934619446195461964619746198461994620046201462024620346204462054620646207462084620946210462114621246213462144621546216462174621846219462204622146222462234622446225462264622746228462294623046231462324623346234462354623646237462384623946240462414624246243462444624546246462474624846249462504625146252462534625446255462564625746258462594626046261462624626346264462654626646267462684626946270462714627246273462744627546276462774627846279462804628146282462834628446285462864628746288462894629046291462924629346294462954629646297462984629946300463014630246303463044630546306463074630846309463104631146312463134631446315463164631746318463194632046321463224632346324463254632646327463284632946330463314633246333463344633546336463374633846339463404634146342463434634446345463464634746348463494635046351463524635346354463554635646357463584635946360463614636246363463644636546366463674636846369463704637146372463734637446375463764637746378463794638046381463824638346384463854638646387463884638946390463914639246393463944639546396463974639846399464004640146402464034640446405464064640746408464094641046411464124641346414464154641646417464184641946420464214642246423464244642546426464274642846429464304643146432464334643446435464364643746438464394644046441464424644346444464454644646447464484644946450464514645246453464544645546456464574645846459464604646146462464634646446465464664646746468464694647046471464724647346474464754647646477464784647946480464814648246483464844648546486464874648846489464904649146492464934649446495464964649746498464994650046501465024650346504465054650646507465084650946510465114651246513465144651546516465174651846519465204652146522465234652446525465264652746528465294653046531465324653346534465354653646537465384653946540465414654246543465444654546546465474654846549465504655146552465534655446555465564655746558465594656046561465624656346564465654656646567465684656946570465714657246573465744657546576465774657846579465804658146582465834658446585465864658746588465894659046591465924659346594465954659646597465984659946600466014660246603466044660546606466074660846609466104661146612466134661446615466164661746618466194662046621466224662346624466254662646627466284662946630466314663246633466344663546636466374663846639466404664146642466434664446645466464664746648466494665046651466524665346654466554665646657466584665946660466614666246663466644666546666466674666846669466704667146672466734667446675466764667746678466794668046681466824668346684466854668646687466884668946690466914669246693466944669546696466974669846699467004670146702467034670446705467064670746708467094671046711467124671346714467154671646717467184671946720467214672246723467244672546726467274672846729467304673146732467334673446735467364673746738467394674046741467424674346744467454674646747467484674946750467514675246753467544675546756467574675846759467604676146762467634676446765467664676746768467694677046771467724677346774467754677646777467784677946780467814678246783467844678546786467874678846789467904679146792467934679446795467964679746798467994680046801468024680346804468054680646807468084680946810468114681246813468144681546816468174681846819468204682146822468234682446825468264682746828468294683046831468324683346834468354683646837468384683946840468414684246843468444684546846468474684846849468504685146852468534685446855468564685746858468594686046861468624686346864468654686646867468684686946870468714687246873468744687546876468774687846879468804688146882468834688446885468864688746888468894689046891468924689346894468954689646897468984689946900469014690246903469044690546906469074690846909469104691146912469134691446915469164691746918469194692046921469224692346924469254692646927469284692946930469314693246933469344693546936469374693846939469404694146942469434694446945469464694746948469494695046951469524695346954469554695646957469584695946960469614696246963469644696546966469674696846969469704697146972469734697446975469764697746978469794698046981469824698346984469854698646987469884698946990469914699246993469944699546996469974699846999470004700147002470034700447005470064700747008470094701047011470124701347014470154701647017470184701947020470214702247023470244702547026470274702847029470304703147032470334703447035470364703747038470394704047041470424704347044470454704647047470484704947050470514705247053470544705547056470574705847059470604706147062470634706447065470664706747068470694707047071470724707347074470754707647077470784707947080470814708247083470844708547086470874708847089470904709147092470934709447095470964709747098470994710047101471024710347104471054710647107471084710947110471114711247113471144711547116471174711847119471204712147122471234712447125471264712747128471294713047131471324713347134471354713647137471384713947140471414714247143471444714547146471474714847149471504715147152471534715447155471564715747158471594716047161471624716347164471654716647167471684716947170471714717247173471744717547176471774717847179471804718147182471834718447185471864718747188471894719047191471924719347194471954719647197471984719947200472014720247203472044720547206472074720847209472104721147212472134721447215472164721747218472194722047221472224722347224472254722647227472284722947230472314723247233472344723547236472374723847239472404724147242472434724447245472464724747248472494725047251472524725347254472554725647257472584725947260472614726247263472644726547266472674726847269472704727147272472734727447275472764727747278472794728047281472824728347284472854728647287472884728947290472914729247293472944729547296472974729847299473004730147302473034730447305473064730747308473094731047311473124731347314473154731647317473184731947320473214732247323473244732547326473274732847329473304733147332473334733447335473364733747338473394734047341473424734347344473454734647347473484734947350473514735247353473544735547356473574735847359473604736147362473634736447365473664736747368473694737047371473724737347374473754737647377473784737947380473814738247383473844738547386473874738847389473904739147392473934739447395473964739747398473994740047401474024740347404474054740647407474084740947410474114741247413474144741547416474174741847419474204742147422474234742447425474264742747428474294743047431474324743347434474354743647437474384743947440474414744247443474444744547446474474744847449474504745147452474534745447455474564745747458474594746047461474624746347464474654746647467474684746947470474714747247473474744747547476474774747847479474804748147482474834748447485474864748747488474894749047491474924749347494474954749647497474984749947500475014750247503475044750547506475074750847509475104751147512475134751447515475164751747518475194752047521475224752347524475254752647527475284752947530475314753247533475344753547536475374753847539475404754147542475434754447545475464754747548475494755047551475524755347554475554755647557475584755947560475614756247563475644756547566475674756847569475704757147572475734757447575475764757747578475794758047581475824758347584475854758647587475884758947590475914759247593475944759547596475974759847599476004760147602476034760447605476064760747608476094761047611476124761347614476154761647617476184761947620476214762247623476244762547626476274762847629476304763147632476334763447635476364763747638476394764047641476424764347644476454764647647476484764947650476514765247653476544765547656476574765847659476604766147662476634766447665476664766747668476694767047671476724767347674476754767647677476784767947680476814768247683476844768547686476874768847689476904769147692476934769447695476964769747698476994770047701477024770347704477054770647707477084770947710477114771247713477144771547716477174771847719477204772147722477234772447725477264772747728477294773047731477324773347734477354773647737477384773947740477414774247743477444774547746477474774847749477504775147752477534775447755477564775747758477594776047761477624776347764477654776647767477684776947770477714777247773477744777547776477774777847779477804778147782477834778447785477864778747788477894779047791477924779347794477954779647797477984779947800478014780247803478044780547806478074780847809478104781147812478134781447815478164781747818478194782047821478224782347824478254782647827478284782947830478314783247833478344783547836478374783847839478404784147842478434784447845478464784747848478494785047851478524785347854478554785647857478584785947860478614786247863478644786547866478674786847869478704787147872478734787447875478764787747878478794788047881478824788347884478854788647887478884788947890478914789247893478944789547896478974789847899479004790147902479034790447905479064790747908479094791047911479124791347914479154791647917479184791947920479214792247923479244792547926479274792847929479304793147932479334793447935479364793747938479394794047941479424794347944479454794647947479484794947950479514795247953479544795547956479574795847959479604796147962479634796447965479664796747968479694797047971479724797347974479754797647977479784797947980479814798247983479844798547986479874798847989479904799147992479934799447995479964799747998479994800048001480024800348004480054800648007480084800948010480114801248013480144801548016480174801848019480204802148022480234802448025480264802748028480294803048031480324803348034480354803648037480384803948040480414804248043480444804548046480474804848049480504805148052480534805448055480564805748058480594806048061480624806348064480654806648067480684806948070480714807248073480744807548076480774807848079480804808148082480834808448085480864808748088480894809048091480924809348094480954809648097480984809948100481014810248103481044810548106481074810848109481104811148112481134811448115481164811748118481194812048121481224812348124481254812648127481284812948130481314813248133481344813548136481374813848139481404814148142481434814448145481464814748148481494815048151481524815348154481554815648157481584815948160481614816248163481644816548166481674816848169481704817148172481734817448175481764817748178481794818048181481824818348184481854818648187481884818948190481914819248193481944819548196481974819848199482004820148202482034820448205482064820748208482094821048211482124821348214482154821648217482184821948220482214822248223482244822548226482274822848229482304823148232482334823448235482364823748238482394824048241482424824348244482454824648247482484824948250482514825248253482544825548256482574825848259482604826148262482634826448265482664826748268482694827048271482724827348274482754827648277482784827948280482814828248283482844828548286482874828848289482904829148292482934829448295482964829748298482994830048301483024830348304483054830648307483084830948310483114831248313483144831548316483174831848319483204832148322483234832448325483264832748328483294833048331483324833348334483354833648337483384833948340483414834248343483444834548346483474834848349483504835148352483534835448355483564835748358483594836048361483624836348364483654836648367483684836948370483714837248373483744837548376483774837848379483804838148382483834838448385483864838748388483894839048391483924839348394483954839648397483984839948400484014840248403484044840548406484074840848409484104841148412484134841448415484164841748418484194842048421484224842348424484254842648427484284842948430484314843248433484344843548436484374843848439484404844148442484434844448445484464844748448484494845048451484524845348454484554845648457484584845948460484614846248463484644846548466484674846848469484704847148472484734847448475484764847748478484794848048481484824848348484484854848648487484884848948490484914849248493484944849548496484974849848499485004850148502485034850448505485064850748508485094851048511485124851348514485154851648517485184851948520485214852248523485244852548526485274852848529485304853148532485334853448535485364853748538485394854048541485424854348544485454854648547485484854948550485514855248553485544855548556485574855848559485604856148562485634856448565485664856748568485694857048571485724857348574485754857648577485784857948580485814858248583485844858548586485874858848589485904859148592485934859448595485964859748598485994860048601486024860348604486054860648607486084860948610486114861248613486144861548616486174861848619486204862148622486234862448625486264862748628486294863048631486324863348634486354863648637486384863948640486414864248643486444864548646486474864848649486504865148652486534865448655486564865748658486594866048661486624866348664486654866648667486684866948670486714867248673486744867548676486774867848679486804868148682486834868448685486864868748688486894869048691486924869348694486954869648697486984869948700487014870248703487044870548706487074870848709487104871148712487134871448715487164871748718487194872048721487224872348724487254872648727487284872948730487314873248733487344873548736487374873848739487404874148742487434874448745487464874748748487494875048751487524875348754487554875648757487584875948760487614876248763487644876548766487674876848769487704877148772487734877448775487764877748778487794878048781487824878348784487854878648787487884878948790487914879248793487944879548796487974879848799488004880148802488034880448805488064880748808488094881048811488124881348814488154881648817488184881948820488214882248823488244882548826488274882848829488304883148832488334883448835488364883748838488394884048841488424884348844488454884648847488484884948850488514885248853488544885548856488574885848859488604886148862488634886448865488664886748868488694887048871488724887348874488754887648877488784887948880488814888248883488844888548886488874888848889488904889148892488934889448895488964889748898488994890048901489024890348904489054890648907489084890948910489114891248913489144891548916489174891848919489204892148922489234892448925489264892748928489294893048931489324893348934489354893648937489384893948940489414894248943489444894548946489474894848949489504895148952489534895448955489564895748958489594896048961489624896348964489654896648967489684896948970489714897248973489744897548976489774897848979489804898148982489834898448985489864898748988489894899048991489924899348994489954899648997489984899949000490014900249003490044900549006490074900849009490104901149012490134901449015490164901749018490194902049021490224902349024490254902649027490284902949030490314903249033490344903549036490374903849039490404904149042490434904449045490464904749048490494905049051490524905349054490554905649057490584905949060490614906249063490644906549066490674906849069490704907149072490734907449075490764907749078490794908049081490824908349084490854908649087490884908949090490914909249093490944909549096490974909849099491004910149102491034910449105491064910749108491094911049111491124911349114491154911649117491184911949120491214912249123491244912549126491274912849129491304913149132491334913449135491364913749138491394914049141491424914349144491454914649147491484914949150491514915249153491544915549156491574915849159491604916149162491634916449165491664916749168491694917049171491724917349174491754917649177491784917949180491814918249183491844918549186491874918849189491904919149192491934919449195491964919749198491994920049201492024920349204492054920649207492084920949210492114921249213492144921549216492174921849219492204922149222492234922449225492264922749228492294923049231492324923349234492354923649237492384923949240492414924249243492444924549246492474924849249492504925149252492534925449255492564925749258492594926049261492624926349264492654926649267492684926949270492714927249273492744927549276492774927849279492804928149282492834928449285492864928749288492894929049291492924929349294492954929649297492984929949300493014930249303493044930549306493074930849309493104931149312493134931449315493164931749318493194932049321493224932349324493254932649327493284932949330493314933249333493344933549336493374933849339493404934149342493434934449345493464934749348493494935049351493524935349354493554935649357493584935949360493614936249363493644936549366493674936849369493704937149372493734937449375493764937749378493794938049381493824938349384493854938649387493884938949390493914939249393493944939549396493974939849399494004940149402494034940449405494064940749408494094941049411494124941349414494154941649417494184941949420494214942249423494244942549426494274942849429494304943149432494334943449435494364943749438494394944049441494424944349444494454944649447494484944949450494514945249453494544945549456494574945849459494604946149462494634946449465494664946749468494694947049471494724947349474494754947649477494784947949480494814948249483494844948549486494874948849489494904949149492494934949449495494964949749498494994950049501495024950349504495054950649507495084950949510495114951249513495144951549516495174951849519495204952149522495234952449525495264952749528495294953049531495324953349534495354953649537495384953949540495414954249543495444954549546495474954849549495504955149552495534955449555495564955749558495594956049561495624956349564495654956649567495684956949570495714957249573495744957549576495774957849579495804958149582495834958449585495864958749588495894959049591495924959349594495954959649597495984959949600496014960249603496044960549606496074960849609496104961149612496134961449615496164961749618496194962049621496224962349624496254962649627496284962949630496314963249633496344963549636496374963849639496404964149642496434964449645496464964749648496494965049651496524965349654496554965649657496584965949660496614966249663496644966549666496674966849669496704967149672496734967449675496764967749678496794968049681496824968349684496854968649687496884968949690496914969249693496944969549696496974969849699497004970149702497034970449705497064970749708497094971049711497124971349714497154971649717497184971949720497214972249723497244972549726497274972849729497304973149732497334973449735497364973749738497394974049741497424974349744497454974649747497484974949750497514975249753497544975549756497574975849759497604976149762497634976449765497664976749768497694977049771497724977349774497754977649777497784977949780497814978249783497844978549786497874978849789497904979149792497934979449795497964979749798497994980049801498024980349804498054980649807498084980949810498114981249813498144981549816498174981849819498204982149822498234982449825498264982749828498294983049831498324983349834498354983649837498384983949840498414984249843498444984549846498474984849849498504985149852498534985449855498564985749858498594986049861498624986349864498654986649867498684986949870498714987249873498744987549876498774987849879498804988149882498834988449885498864988749888498894989049891498924989349894498954989649897498984989949900499014990249903499044990549906499074990849909499104991149912499134991449915499164991749918499194992049921499224992349924499254992649927499284992949930499314993249933499344993549936499374993849939499404994149942499434994449945499464994749948499494995049951499524995349954499554995649957499584995949960499614996249963499644996549966499674996849969499704997149972499734997449975499764997749978499794998049981499824998349984499854998649987499884998949990499914999249993499944999549996499974999849999500005000150002500035000450005500065000750008500095001050011500125001350014500155001650017500185001950020500215002250023500245002550026500275002850029500305003150032500335003450035500365003750038500395004050041500425004350044500455004650047500485004950050500515005250053500545005550056500575005850059500605006150062500635006450065500665006750068500695007050071500725007350074500755007650077500785007950080500815008250083500845008550086500875008850089500905009150092500935009450095500965009750098500995010050101501025010350104501055010650107501085010950110501115011250113501145011550116501175011850119501205012150122501235012450125501265012750128501295013050131501325013350134501355013650137501385013950140501415014250143501445014550146501475014850149501505015150152501535015450155501565015750158501595016050161501625016350164501655016650167501685016950170501715017250173501745017550176501775017850179501805018150182501835018450185501865018750188501895019050191501925019350194501955019650197501985019950200502015020250203502045020550206502075020850209502105021150212502135021450215502165021750218502195022050221502225022350224502255022650227502285022950230502315023250233502345023550236502375023850239502405024150242502435024450245502465024750248502495025050251502525025350254502555025650257502585025950260502615026250263502645026550266502675026850269502705027150272502735027450275502765027750278502795028050281502825028350284502855028650287502885028950290502915029250293502945029550296502975029850299503005030150302503035030450305503065030750308503095031050311503125031350314503155031650317503185031950320503215032250323503245032550326503275032850329503305033150332503335033450335503365033750338503395034050341503425034350344503455034650347503485034950350503515035250353503545035550356503575035850359503605036150362503635036450365503665036750368503695037050371503725037350374503755037650377503785037950380503815038250383503845038550386503875038850389503905039150392503935039450395503965039750398503995040050401504025040350404504055040650407504085040950410504115041250413504145041550416504175041850419504205042150422504235042450425504265042750428504295043050431504325043350434504355043650437504385043950440504415044250443504445044550446504475044850449504505045150452504535045450455504565045750458504595046050461504625046350464504655046650467504685046950470504715047250473504745047550476504775047850479504805048150482504835048450485504865048750488504895049050491504925049350494504955049650497504985049950500505015050250503505045050550506505075050850509505105051150512505135051450515505165051750518505195052050521505225052350524505255052650527505285052950530505315053250533505345053550536505375053850539505405054150542505435054450545505465054750548505495055050551505525055350554505555055650557505585055950560505615056250563505645056550566505675056850569505705057150572505735057450575505765057750578505795058050581505825058350584505855058650587505885058950590505915059250593505945059550596505975059850599506005060150602506035060450605506065060750608506095061050611506125061350614506155061650617506185061950620506215062250623506245062550626506275062850629506305063150632506335063450635506365063750638506395064050641506425064350644506455064650647506485064950650506515065250653506545065550656506575065850659506605066150662506635066450665506665066750668506695067050671506725067350674506755067650677506785067950680506815068250683506845068550686506875068850689506905069150692506935069450695506965069750698506995070050701507025070350704507055070650707507085070950710507115071250713507145071550716507175071850719507205072150722507235072450725507265072750728507295073050731507325073350734507355073650737507385073950740507415074250743507445074550746507475074850749507505075150752507535075450755507565075750758507595076050761507625076350764507655076650767507685076950770507715077250773507745077550776507775077850779507805078150782507835078450785507865078750788507895079050791507925079350794507955079650797507985079950800508015080250803508045080550806508075080850809508105081150812508135081450815508165081750818508195082050821508225082350824508255082650827508285082950830508315083250833508345083550836508375083850839508405084150842508435084450845508465084750848508495085050851508525085350854508555085650857508585085950860508615086250863508645086550866508675086850869508705087150872508735087450875508765087750878508795088050881508825088350884508855088650887508885088950890508915089250893508945089550896508975089850899509005090150902509035090450905509065090750908509095091050911509125091350914509155091650917509185091950920509215092250923509245092550926509275092850929509305093150932509335093450935509365093750938509395094050941509425094350944509455094650947509485094950950509515095250953509545095550956509575095850959509605096150962509635096450965509665096750968509695097050971509725097350974509755097650977509785097950980509815098250983509845098550986509875098850989509905099150992509935099450995509965099750998509995100051001510025100351004510055100651007510085100951010510115101251013510145101551016510175101851019510205102151022510235102451025510265102751028510295103051031510325103351034510355103651037510385103951040510415104251043510445104551046510475104851049510505105151052510535105451055510565105751058510595106051061510625106351064510655106651067510685106951070510715107251073510745107551076510775107851079510805108151082510835108451085510865108751088510895109051091510925109351094510955109651097510985109951100511015110251103511045110551106511075110851109511105111151112511135111451115511165111751118511195112051121511225112351124511255112651127511285112951130511315113251133511345113551136511375113851139511405114151142511435114451145511465114751148511495115051151511525115351154511555115651157511585115951160511615116251163511645116551166511675116851169511705117151172511735117451175511765117751178511795118051181511825118351184511855118651187511885118951190511915119251193511945119551196511975119851199512005120151202512035120451205512065120751208512095121051211512125121351214512155121651217512185121951220512215122251223512245122551226512275122851229512305123151232512335123451235512365123751238512395124051241512425124351244512455124651247512485124951250512515125251253512545125551256512575125851259512605126151262512635126451265512665126751268512695127051271512725127351274512755127651277512785127951280512815128251283512845128551286512875128851289512905129151292512935129451295512965129751298512995130051301513025130351304513055130651307513085130951310513115131251313513145131551316513175131851319513205132151322513235132451325513265132751328513295133051331513325133351334513355133651337513385133951340513415134251343513445134551346513475134851349513505135151352513535135451355513565135751358513595136051361513625136351364513655136651367513685136951370513715137251373513745137551376513775137851379513805138151382513835138451385513865138751388513895139051391513925139351394513955139651397513985139951400514015140251403514045140551406514075140851409514105141151412514135141451415514165141751418514195142051421514225142351424514255142651427514285142951430514315143251433514345143551436514375143851439514405144151442514435144451445514465144751448514495145051451514525145351454514555145651457514585145951460514615146251463514645146551466514675146851469514705147151472514735147451475514765147751478514795148051481514825148351484514855148651487514885148951490514915149251493514945149551496514975149851499515005150151502515035150451505515065150751508515095151051511515125151351514515155151651517515185151951520515215152251523515245152551526515275152851529515305153151532515335153451535515365153751538515395154051541515425154351544515455154651547515485154951550515515155251553515545155551556515575155851559515605156151562515635156451565515665156751568515695157051571515725157351574515755157651577515785157951580515815158251583515845158551586515875158851589515905159151592515935159451595515965159751598515995160051601516025160351604516055160651607516085160951610516115161251613516145161551616516175161851619516205162151622516235162451625516265162751628516295163051631516325163351634516355163651637516385163951640516415164251643516445164551646516475164851649516505165151652516535165451655516565165751658516595166051661516625166351664516655166651667516685166951670516715167251673516745167551676516775167851679516805168151682516835168451685516865168751688516895169051691516925169351694516955169651697516985169951700517015170251703517045170551706517075170851709517105171151712517135171451715517165171751718517195172051721517225172351724517255172651727517285172951730517315173251733517345173551736517375173851739517405174151742517435174451745517465174751748517495175051751517525175351754517555175651757517585175951760517615176251763517645176551766517675176851769517705177151772517735177451775517765177751778517795178051781517825178351784517855178651787517885178951790517915179251793517945179551796517975179851799518005180151802518035180451805518065180751808518095181051811518125181351814518155181651817518185181951820518215182251823518245182551826518275182851829518305183151832518335183451835518365183751838518395184051841518425184351844518455184651847518485184951850518515185251853518545185551856518575185851859518605186151862518635186451865518665186751868518695187051871518725187351874518755187651877518785187951880518815188251883518845188551886518875188851889518905189151892518935189451895518965189751898518995190051901519025190351904519055190651907519085190951910519115191251913519145191551916519175191851919519205192151922519235192451925519265192751928519295193051931519325193351934519355193651937519385193951940519415194251943519445194551946519475194851949519505195151952519535195451955519565195751958519595196051961519625196351964519655196651967519685196951970519715197251973519745197551976519775197851979519805198151982519835198451985519865198751988519895199051991519925199351994519955199651997519985199952000520015200252003520045200552006520075200852009520105201152012520135201452015520165201752018520195202052021520225202352024520255202652027520285202952030520315203252033520345203552036520375203852039520405204152042520435204452045520465204752048520495205052051520525205352054520555205652057520585205952060520615206252063520645206552066520675206852069520705207152072520735207452075520765207752078520795208052081520825208352084520855208652087520885208952090520915209252093520945209552096520975209852099521005210152102521035210452105521065210752108521095211052111521125211352114521155211652117521185211952120521215212252123521245212552126521275212852129521305213152132521335213452135521365213752138521395214052141521425214352144521455214652147521485214952150521515215252153521545215552156521575215852159521605216152162521635216452165521665216752168521695217052171521725217352174521755217652177521785217952180521815218252183521845218552186521875218852189521905219152192521935219452195521965219752198521995220052201522025220352204522055220652207522085220952210522115221252213522145221552216522175221852219522205222152222522235222452225522265222752228522295223052231522325223352234522355223652237522385223952240522415224252243522445224552246522475224852249522505225152252522535225452255522565225752258522595226052261522625226352264522655226652267522685226952270522715227252273522745227552276522775227852279522805228152282522835228452285522865228752288522895229052291522925229352294522955229652297522985229952300523015230252303523045230552306523075230852309523105231152312523135231452315523165231752318523195232052321523225232352324523255232652327523285232952330523315233252333523345233552336523375233852339523405234152342523435234452345523465234752348523495235052351523525235352354523555235652357523585235952360523615236252363523645236552366523675236852369523705237152372523735237452375523765237752378523795238052381523825238352384523855238652387523885238952390523915239252393523945239552396523975239852399524005240152402524035240452405524065240752408524095241052411524125241352414524155241652417524185241952420524215242252423524245242552426524275242852429524305243152432524335243452435524365243752438524395244052441524425244352444524455244652447524485244952450524515245252453524545245552456524575245852459524605246152462524635246452465524665246752468524695247052471524725247352474524755247652477524785247952480524815248252483524845248552486524875248852489524905249152492524935249452495524965249752498524995250052501525025250352504525055250652507525085250952510525115251252513525145251552516525175251852519525205252152522525235252452525525265252752528525295253052531525325253352534525355253652537525385253952540525415254252543525445254552546525475254852549525505255152552525535255452555525565255752558525595256052561525625256352564525655256652567525685256952570525715257252573525745257552576525775257852579525805258152582525835258452585525865258752588525895259052591525925259352594525955259652597525985259952600526015260252603526045260552606526075260852609526105261152612526135261452615526165261752618526195262052621526225262352624526255262652627526285262952630526315263252633526345263552636526375263852639526405264152642526435264452645526465264752648526495265052651526525265352654526555265652657526585265952660526615266252663526645266552666526675266852669526705267152672526735267452675526765267752678526795268052681526825268352684526855268652687526885268952690526915269252693526945269552696526975269852699527005270152702527035270452705527065270752708527095271052711527125271352714527155271652717527185271952720527215272252723527245272552726527275272852729527305273152732527335273452735527365273752738527395274052741527425274352744527455274652747527485274952750527515275252753527545275552756527575275852759527605276152762527635276452765527665276752768527695277052771527725277352774527755277652777527785277952780527815278252783527845278552786527875278852789527905279152792527935279452795527965279752798527995280052801528025280352804528055280652807528085280952810528115281252813528145281552816528175281852819528205282152822528235282452825528265282752828528295283052831528325283352834528355283652837528385283952840528415284252843528445284552846528475284852849528505285152852528535285452855528565285752858528595286052861528625286352864528655286652867528685286952870528715287252873528745287552876528775287852879528805288152882528835288452885528865288752888528895289052891528925289352894528955289652897528985289952900529015290252903529045290552906529075290852909529105291152912529135291452915529165291752918529195292052921529225292352924529255292652927529285292952930529315293252933529345293552936529375293852939529405294152942529435294452945529465294752948529495295052951529525295352954529555295652957529585295952960529615296252963529645296552966529675296852969529705297152972529735297452975529765297752978529795298052981529825298352984529855298652987529885298952990529915299252993529945299552996529975299852999530005300153002530035300453005530065300753008530095301053011530125301353014530155301653017530185301953020530215302253023530245302553026530275302853029530305303153032530335303453035530365303753038530395304053041530425304353044530455304653047530485304953050530515305253053530545305553056530575305853059530605306153062530635306453065530665306753068530695307053071530725307353074530755307653077530785307953080530815308253083530845308553086530875308853089530905309153092530935309453095530965309753098530995310053101531025310353104531055310653107531085310953110531115311253113531145311553116531175311853119531205312153122531235312453125531265312753128531295313053131531325313353134531355313653137531385313953140531415314253143531445314553146531475314853149531505315153152531535315453155531565315753158531595316053161531625316353164531655316653167531685316953170531715317253173531745317553176531775317853179531805318153182531835318453185531865318753188531895319053191531925319353194531955319653197531985319953200532015320253203532045320553206532075320853209532105321153212532135321453215532165321753218532195322053221532225322353224532255322653227532285322953230532315323253233532345323553236532375323853239532405324153242532435324453245532465324753248532495325053251532525325353254532555325653257532585325953260532615326253263532645326553266532675326853269532705327153272532735327453275532765327753278532795328053281532825328353284532855328653287532885328953290532915329253293532945329553296532975329853299533005330153302533035330453305533065330753308533095331053311533125331353314533155331653317533185331953320533215332253323533245332553326533275332853329533305333153332533335333453335533365333753338533395334053341533425334353344533455334653347533485334953350533515335253353533545335553356533575335853359533605336153362533635336453365533665336753368533695337053371533725337353374533755337653377533785337953380533815338253383533845338553386533875338853389533905339153392533935339453395533965339753398533995340053401534025340353404534055340653407534085340953410534115341253413534145341553416534175341853419534205342153422534235342453425534265342753428534295343053431534325343353434534355343653437534385343953440534415344253443534445344553446534475344853449534505345153452534535345453455534565345753458534595346053461534625346353464534655346653467534685346953470534715347253473534745347553476534775347853479534805348153482534835348453485534865348753488534895349053491534925349353494534955349653497534985349953500535015350253503535045350553506535075350853509535105351153512535135351453515535165351753518535195352053521535225352353524535255352653527535285352953530535315353253533535345353553536535375353853539535405354153542535435354453545535465354753548535495355053551535525355353554535555355653557535585355953560535615356253563535645356553566535675356853569535705357153572535735357453575535765357753578535795358053581535825358353584535855358653587535885358953590535915359253593535945359553596535975359853599536005360153602536035360453605536065360753608536095361053611536125361353614536155361653617536185361953620536215362253623536245362553626536275362853629536305363153632536335363453635536365363753638536395364053641536425364353644536455364653647536485364953650536515365253653536545365553656536575365853659536605366153662536635366453665536665366753668536695367053671536725367353674536755367653677536785367953680536815368253683536845368553686536875368853689536905369153692536935369453695536965369753698536995370053701537025370353704537055370653707537085370953710537115371253713537145371553716537175371853719537205372153722537235372453725537265372753728537295373053731537325373353734537355373653737537385373953740537415374253743537445374553746537475374853749537505375153752537535375453755537565375753758537595376053761537625376353764537655376653767537685376953770537715377253773537745377553776537775377853779537805378153782537835378453785537865378753788537895379053791537925379353794537955379653797537985379953800538015380253803538045380553806538075380853809538105381153812538135381453815538165381753818538195382053821538225382353824538255382653827538285382953830538315383253833538345383553836538375383853839538405384153842538435384453845538465384753848538495385053851538525385353854538555385653857538585385953860538615386253863538645386553866538675386853869538705387153872538735387453875538765387753878538795388053881538825388353884538855388653887538885388953890538915389253893538945389553896538975389853899539005390153902539035390453905539065390753908539095391053911539125391353914539155391653917539185391953920539215392253923539245392553926539275392853929539305393153932539335393453935539365393753938539395394053941539425394353944539455394653947539485394953950539515395253953539545395553956539575395853959539605396153962539635396453965539665396753968539695397053971539725397353974539755397653977539785397953980539815398253983539845398553986539875398853989539905399153992539935399453995539965399753998539995400054001540025400354004540055400654007540085400954010540115401254013540145401554016540175401854019540205402154022540235402454025540265402754028540295403054031540325403354034540355403654037540385403954040540415404254043540445404554046540475404854049540505405154052540535405454055540565405754058540595406054061540625406354064540655406654067540685406954070540715407254073540745407554076540775407854079540805408154082540835408454085540865408754088540895409054091540925409354094540955409654097540985409954100541015410254103541045410554106541075410854109541105411154112541135411454115541165411754118541195412054121541225412354124541255412654127541285412954130541315413254133541345413554136541375413854139541405414154142541435414454145541465414754148541495415054151541525415354154541555415654157541585415954160541615416254163541645416554166541675416854169541705417154172541735417454175541765417754178541795418054181541825418354184541855418654187541885418954190541915419254193541945419554196541975419854199542005420154202542035420454205542065420754208542095421054211542125421354214542155421654217542185421954220542215422254223542245422554226542275422854229542305423154232542335423454235542365423754238542395424054241542425424354244542455424654247542485424954250542515425254253542545425554256542575425854259542605426154262542635426454265542665426754268542695427054271542725427354274542755427654277542785427954280542815428254283542845428554286542875428854289542905429154292542935429454295542965429754298542995430054301543025430354304543055430654307543085430954310543115431254313543145431554316543175431854319543205432154322543235432454325543265432754328543295433054331543325433354334543355433654337543385433954340543415434254343543445434554346543475434854349543505435154352543535435454355543565435754358543595436054361543625436354364543655436654367543685436954370543715437254373543745437554376543775437854379543805438154382543835438454385543865438754388543895439054391543925439354394543955439654397543985439954400544015440254403544045440554406544075440854409544105441154412544135441454415544165441754418544195442054421544225442354424544255442654427544285442954430544315443254433544345443554436544375443854439544405444154442544435444454445544465444754448544495445054451544525445354454544555445654457544585445954460544615446254463544645446554466544675446854469544705447154472544735447454475544765447754478544795448054481544825448354484544855448654487544885448954490544915449254493544945449554496544975449854499545005450154502545035450454505545065450754508545095451054511545125451354514545155451654517545185451954520545215452254523545245452554526545275452854529545305453154532545335453454535545365453754538545395454054541545425454354544545455454654547545485454954550545515455254553545545455554556545575455854559545605456154562545635456454565545665456754568545695457054571545725457354574545755457654577545785457954580545815458254583545845458554586545875458854589545905459154592545935459454595545965459754598545995460054601546025460354604546055460654607546085460954610546115461254613546145461554616546175461854619546205462154622546235462454625546265462754628546295463054631546325463354634546355463654637546385463954640546415464254643546445464554646546475464854649546505465154652546535465454655546565465754658546595466054661546625466354664546655466654667546685466954670546715467254673546745467554676546775467854679546805468154682546835468454685546865468754688546895469054691546925469354694546955469654697546985469954700547015470254703547045470554706547075470854709547105471154712547135471454715547165471754718547195472054721547225472354724547255472654727547285472954730547315473254733547345473554736547375473854739547405474154742547435474454745547465474754748547495475054751547525475354754547555475654757547585475954760547615476254763547645476554766547675476854769547705477154772547735477454775547765477754778547795478054781547825478354784547855478654787547885478954790547915479254793547945479554796547975479854799548005480154802548035480454805548065480754808548095481054811548125481354814548155481654817548185481954820548215482254823548245482554826548275482854829548305483154832548335483454835548365483754838548395484054841548425484354844548455484654847548485484954850548515485254853548545485554856548575485854859548605486154862548635486454865548665486754868548695487054871548725487354874548755487654877548785487954880548815488254883548845488554886548875488854889548905489154892548935489454895548965489754898548995490054901549025490354904549055490654907549085490954910549115491254913549145491554916549175491854919549205492154922549235492454925549265492754928549295493054931549325493354934549355493654937549385493954940549415494254943549445494554946549475494854949549505495154952549535495454955549565495754958549595496054961549625496354964549655496654967549685496954970549715497254973549745497554976549775497854979549805498154982549835498454985549865498754988549895499054991549925499354994549955499654997549985499955000550015500255003550045500555006550075500855009550105501155012550135501455015550165501755018550195502055021550225502355024550255502655027550285502955030550315503255033550345503555036550375503855039550405504155042550435504455045550465504755048550495505055051550525505355054550555505655057550585505955060550615506255063550645506555066550675506855069550705507155072550735507455075550765507755078550795508055081550825508355084550855508655087550885508955090550915509255093550945509555096550975509855099551005510155102551035510455105551065510755108551095511055111551125511355114551155511655117551185511955120551215512255123551245512555126551275512855129551305513155132551335513455135551365513755138551395514055141551425514355144551455514655147551485514955150551515515255153551545515555156551575515855159551605516155162551635516455165551665516755168551695517055171551725517355174551755517655177551785517955180551815518255183551845518555186551875518855189551905519155192551935519455195551965519755198551995520055201552025520355204552055520655207552085520955210552115521255213552145521555216552175521855219552205522155222552235522455225552265522755228552295523055231552325523355234552355523655237552385523955240552415524255243552445524555246552475524855249552505525155252552535525455255552565525755258552595526055261552625526355264552655526655267552685526955270552715527255273552745527555276552775527855279552805528155282552835528455285552865528755288552895529055291552925529355294552955529655297552985529955300553015530255303553045530555306553075530855309553105531155312553135531455315553165531755318553195532055321553225532355324553255532655327553285532955330553315533255333553345533555336553375533855339553405534155342553435534455345553465534755348553495535055351553525535355354553555535655357553585535955360553615536255363553645536555366553675536855369553705537155372553735537455375553765537755378553795538055381553825538355384553855538655387553885538955390553915539255393553945539555396553975539855399554005540155402554035540455405554065540755408554095541055411554125541355414554155541655417554185541955420554215542255423554245542555426554275542855429554305543155432554335543455435554365543755438554395544055441554425544355444554455544655447554485544955450554515545255453554545545555456554575545855459554605546155462554635546455465554665546755468554695547055471554725547355474554755547655477554785547955480554815548255483554845548555486554875548855489554905549155492554935549455495554965549755498554995550055501555025550355504555055550655507555085550955510555115551255513555145551555516555175551855519555205552155522555235552455525555265552755528555295553055531555325553355534555355553655537555385553955540555415554255543555445554555546555475554855549555505555155552555535555455555555565555755558555595556055561555625556355564555655556655567555685556955570555715557255573555745557555576555775557855579555805558155582555835558455585555865558755588555895559055591555925559355594555955559655597555985559955600556015560255603556045560555606556075560855609556105561155612556135561455615556165561755618556195562055621556225562355624556255562655627556285562955630556315563255633556345563555636556375563855639556405564155642556435564455645556465564755648556495565055651556525565355654556555565655657556585565955660556615566255663556645566555666556675566855669556705567155672556735567455675556765567755678556795568055681556825568355684556855568655687556885568955690556915569255693556945569555696556975569855699557005570155702557035570455705557065570755708557095571055711557125571355714557155571655717557185571955720557215572255723557245572555726557275572855729557305573155732557335573455735557365573755738557395574055741557425574355744557455574655747557485574955750557515575255753557545575555756557575575855759557605576155762557635576455765557665576755768557695577055771557725577355774557755577655777557785577955780557815578255783557845578555786557875578855789557905579155792557935579455795557965579755798557995580055801558025580355804558055580655807558085580955810558115581255813558145581555816558175581855819558205582155822558235582455825558265582755828558295583055831558325583355834558355583655837558385583955840558415584255843558445584555846558475584855849558505585155852558535585455855558565585755858558595586055861558625586355864558655586655867558685586955870558715587255873558745587555876558775587855879558805588155882558835588455885558865588755888558895589055891558925589355894558955589655897558985589955900559015590255903559045590555906559075590855909559105591155912559135591455915559165591755918559195592055921559225592355924559255592655927559285592955930559315593255933559345593555936559375593855939559405594155942559435594455945559465594755948559495595055951559525595355954559555595655957559585595955960559615596255963559645596555966559675596855969559705597155972559735597455975559765597755978559795598055981559825598355984559855598655987559885598955990559915599255993559945599555996559975599855999560005600156002560035600456005560065600756008560095601056011560125601356014560155601656017560185601956020560215602256023560245602556026560275602856029560305603156032560335603456035560365603756038560395604056041560425604356044560455604656047560485604956050560515605256053560545605556056560575605856059560605606156062560635606456065560665606756068560695607056071560725607356074560755607656077560785607956080560815608256083560845608556086560875608856089560905609156092560935609456095560965609756098560995610056101561025610356104561055610656107561085610956110561115611256113561145611556116561175611856119561205612156122561235612456125561265612756128561295613056131561325613356134561355613656137561385613956140561415614256143561445614556146561475614856149561505615156152561535615456155561565615756158561595616056161561625616356164561655616656167561685616956170561715617256173561745617556176561775617856179561805618156182561835618456185561865618756188561895619056191561925619356194561955619656197561985619956200562015620256203562045620556206562075620856209562105621156212562135621456215562165621756218562195622056221562225622356224562255622656227562285622956230562315623256233562345623556236562375623856239562405624156242562435624456245562465624756248562495625056251562525625356254562555625656257562585625956260562615626256263562645626556266562675626856269562705627156272562735627456275562765627756278562795628056281562825628356284562855628656287562885628956290562915629256293562945629556296562975629856299563005630156302563035630456305563065630756308563095631056311563125631356314563155631656317563185631956320563215632256323563245632556326563275632856329563305633156332563335633456335563365633756338563395634056341563425634356344563455634656347563485634956350563515635256353563545635556356563575635856359563605636156362563635636456365563665636756368563695637056371563725637356374563755637656377563785637956380563815638256383563845638556386563875638856389563905639156392563935639456395563965639756398563995640056401564025640356404564055640656407564085640956410564115641256413564145641556416564175641856419564205642156422564235642456425564265642756428564295643056431564325643356434564355643656437564385643956440564415644256443564445644556446564475644856449564505645156452564535645456455564565645756458564595646056461564625646356464564655646656467564685646956470564715647256473564745647556476564775647856479564805648156482564835648456485564865648756488564895649056491564925649356494564955649656497564985649956500565015650256503565045650556506565075650856509565105651156512565135651456515565165651756518565195652056521565225652356524565255652656527565285652956530565315653256533565345653556536565375653856539565405654156542565435654456545565465654756548565495655056551565525655356554565555655656557565585655956560565615656256563565645656556566565675656856569565705657156572565735657456575565765657756578565795658056581565825658356584565855658656587565885658956590565915659256593565945659556596565975659856599566005660156602566035660456605566065660756608566095661056611566125661356614566155661656617566185661956620566215662256623566245662556626566275662856629566305663156632566335663456635566365663756638566395664056641566425664356644566455664656647566485664956650566515665256653566545665556656566575665856659566605666156662566635666456665566665666756668566695667056671566725667356674566755667656677566785667956680566815668256683566845668556686566875668856689566905669156692566935669456695566965669756698566995670056701567025670356704567055670656707567085670956710567115671256713567145671556716567175671856719567205672156722567235672456725567265672756728567295673056731567325673356734567355673656737567385673956740567415674256743567445674556746567475674856749567505675156752567535675456755567565675756758567595676056761567625676356764567655676656767567685676956770567715677256773567745677556776567775677856779567805678156782567835678456785567865678756788567895679056791567925679356794567955679656797567985679956800568015680256803568045680556806568075680856809568105681156812568135681456815568165681756818568195682056821568225682356824568255682656827568285682956830568315683256833568345683556836568375683856839568405684156842568435684456845568465684756848568495685056851568525685356854568555685656857568585685956860568615686256863568645686556866568675686856869568705687156872568735687456875568765687756878568795688056881568825688356884568855688656887568885688956890568915689256893568945689556896568975689856899569005690156902569035690456905569065690756908569095691056911569125691356914569155691656917569185691956920569215692256923569245692556926569275692856929569305693156932569335693456935569365693756938569395694056941569425694356944569455694656947569485694956950569515695256953569545695556956569575695856959569605696156962569635696456965569665696756968569695697056971569725697356974569755697656977569785697956980569815698256983569845698556986569875698856989569905699156992569935699456995569965699756998569995700057001570025700357004570055700657007570085700957010570115701257013570145701557016570175701857019570205702157022570235702457025570265702757028570295703057031570325703357034570355703657037570385703957040570415704257043570445704557046570475704857049570505705157052570535705457055570565705757058570595706057061570625706357064570655706657067570685706957070570715707257073570745707557076570775707857079570805708157082570835708457085570865708757088570895709057091570925709357094570955709657097570985709957100571015710257103571045710557106571075710857109571105711157112571135711457115571165711757118571195712057121571225712357124571255712657127571285712957130571315713257133571345713557136571375713857139571405714157142571435714457145571465714757148571495715057151571525715357154571555715657157571585715957160571615716257163571645716557166571675716857169571705717157172571735717457175571765717757178571795718057181571825718357184571855718657187571885718957190571915719257193571945719557196571975719857199572005720157202572035720457205572065720757208572095721057211572125721357214572155721657217572185721957220572215722257223572245722557226572275722857229572305723157232572335723457235572365723757238572395724057241572425724357244572455724657247572485724957250572515725257253572545725557256572575725857259572605726157262572635726457265572665726757268572695727057271572725727357274572755727657277572785727957280572815728257283572845728557286572875728857289572905729157292572935729457295572965729757298572995730057301573025730357304573055730657307573085730957310573115731257313573145731557316573175731857319573205732157322573235732457325573265732757328573295733057331573325733357334573355733657337573385733957340573415734257343573445734557346573475734857349573505735157352573535735457355573565735757358573595736057361573625736357364573655736657367573685736957370573715737257373573745737557376573775737857379573805738157382573835738457385573865738757388573895739057391573925739357394573955739657397573985739957400574015740257403574045740557406574075740857409574105741157412574135741457415574165741757418574195742057421574225742357424574255742657427574285742957430574315743257433574345743557436574375743857439574405744157442574435744457445574465744757448574495745057451574525745357454574555745657457574585745957460574615746257463574645746557466574675746857469574705747157472574735747457475574765747757478574795748057481574825748357484574855748657487574885748957490574915749257493574945749557496574975749857499575005750157502575035750457505575065750757508575095751057511575125751357514575155751657517575185751957520575215752257523575245752557526575275752857529575305753157532575335753457535575365753757538575395754057541575425754357544575455754657547575485754957550575515755257553575545755557556575575755857559575605756157562575635756457565575665756757568575695757057571575725757357574575755757657577575785757957580575815758257583575845758557586575875758857589575905759157592575935759457595575965759757598575995760057601576025760357604576055760657607576085760957610576115761257613576145761557616576175761857619576205762157622576235762457625576265762757628576295763057631576325763357634576355763657637576385763957640576415764257643576445764557646576475764857649576505765157652576535765457655576565765757658576595766057661576625766357664576655766657667576685766957670576715767257673576745767557676576775767857679576805768157682576835768457685576865768757688576895769057691576925769357694576955769657697576985769957700577015770257703577045770557706577075770857709577105771157712577135771457715577165771757718577195772057721577225772357724577255772657727577285772957730577315773257733577345773557736577375773857739577405774157742577435774457745577465774757748577495775057751577525775357754577555775657757577585775957760577615776257763577645776557766577675776857769577705777157772577735777457775577765777757778577795778057781577825778357784577855778657787577885778957790577915779257793577945779557796577975779857799578005780157802578035780457805578065780757808578095781057811578125781357814578155781657817578185781957820578215782257823578245782557826578275782857829578305783157832578335783457835578365783757838578395784057841578425784357844578455784657847578485784957850578515785257853578545785557856578575785857859578605786157862578635786457865578665786757868578695787057871578725787357874578755787657877578785787957880578815788257883578845788557886578875788857889578905789157892578935789457895578965789757898578995790057901579025790357904579055790657907579085790957910579115791257913579145791557916579175791857919579205792157922579235792457925579265792757928579295793057931579325793357934579355793657937579385793957940579415794257943579445794557946579475794857949579505795157952579535795457955579565795757958579595796057961579625796357964579655796657967579685796957970579715797257973579745797557976579775797857979579805798157982579835798457985579865798757988579895799057991579925799357994579955799657997579985799958000580015800258003580045800558006580075800858009580105801158012580135801458015580165801758018580195802058021580225802358024580255802658027580285802958030580315803258033580345803558036580375803858039580405804158042580435804458045580465804758048580495805058051580525805358054580555805658057580585805958060580615806258063580645806558066580675806858069580705807158072580735807458075580765807758078580795808058081580825808358084580855808658087580885808958090580915809258093580945809558096580975809858099581005810158102581035810458105581065810758108581095811058111581125811358114581155811658117581185811958120581215812258123581245812558126581275812858129581305813158132581335813458135581365813758138581395814058141581425814358144581455814658147581485814958150581515815258153581545815558156581575815858159581605816158162581635816458165581665816758168581695817058171581725817358174581755817658177581785817958180581815818258183581845818558186581875818858189581905819158192581935819458195581965819758198581995820058201582025820358204582055820658207582085820958210582115821258213582145821558216582175821858219582205822158222582235822458225582265822758228582295823058231582325823358234582355823658237582385823958240582415824258243582445824558246582475824858249582505825158252582535825458255582565825758258582595826058261582625826358264582655826658267582685826958270582715827258273582745827558276582775827858279582805828158282582835828458285582865828758288582895829058291582925829358294582955829658297582985829958300583015830258303583045830558306583075830858309583105831158312583135831458315583165831758318583195832058321583225832358324583255832658327583285832958330583315833258333583345833558336583375833858339583405834158342583435834458345583465834758348583495835058351583525835358354583555835658357583585835958360583615836258363583645836558366583675836858369583705837158372583735837458375583765837758378583795838058381583825838358384583855838658387583885838958390583915839258393583945839558396583975839858399584005840158402584035840458405584065840758408584095841058411584125841358414584155841658417584185841958420584215842258423584245842558426584275842858429584305843158432584335843458435584365843758438584395844058441584425844358444584455844658447584485844958450584515845258453584545845558456584575845858459584605846158462584635846458465584665846758468584695847058471584725847358474584755847658477584785847958480584815848258483584845848558486584875848858489584905849158492584935849458495584965849758498584995850058501585025850358504585055850658507585085850958510585115851258513585145851558516585175851858519585205852158522585235852458525585265852758528585295853058531585325853358534585355853658537585385853958540585415854258543585445854558546585475854858549585505855158552585535855458555585565855758558585595856058561585625856358564585655856658567585685856958570585715857258573585745857558576585775857858579585805858158582585835858458585585865858758588585895859058591585925859358594585955859658597585985859958600586015860258603586045860558606586075860858609586105861158612586135861458615586165861758618586195862058621586225862358624586255862658627586285862958630586315863258633586345863558636586375863858639586405864158642586435864458645586465864758648586495865058651586525865358654586555865658657586585865958660586615866258663586645866558666586675866858669586705867158672586735867458675586765867758678586795868058681586825868358684586855868658687586885868958690586915869258693586945869558696586975869858699587005870158702587035870458705587065870758708587095871058711587125871358714587155871658717587185871958720587215872258723587245872558726587275872858729587305873158732587335873458735587365873758738587395874058741587425874358744587455874658747587485874958750587515875258753587545875558756587575875858759587605876158762587635876458765587665876758768587695877058771587725877358774587755877658777587785877958780587815878258783587845878558786587875878858789587905879158792587935879458795587965879758798587995880058801588025880358804588055880658807588085880958810588115881258813588145881558816588175881858819588205882158822588235882458825588265882758828588295883058831588325883358834588355883658837588385883958840588415884258843588445884558846588475884858849588505885158852588535885458855588565885758858588595886058861588625886358864588655886658867588685886958870588715887258873588745887558876588775887858879588805888158882588835888458885588865888758888588895889058891588925889358894588955889658897588985889958900589015890258903589045890558906589075890858909589105891158912589135891458915589165891758918589195892058921589225892358924589255892658927589285892958930589315893258933589345893558936589375893858939589405894158942589435894458945589465894758948589495895058951589525895358954589555895658957589585895958960589615896258963589645896558966589675896858969589705897158972589735897458975589765897758978589795898058981589825898358984589855898658987589885898958990589915899258993589945899558996589975899858999590005900159002590035900459005590065900759008590095901059011590125901359014590155901659017590185901959020590215902259023590245902559026590275902859029590305903159032590335903459035590365903759038590395904059041590425904359044590455904659047590485904959050590515905259053590545905559056590575905859059590605906159062590635906459065590665906759068590695907059071590725907359074590755907659077590785907959080590815908259083590845908559086590875908859089590905909159092590935909459095590965909759098590995910059101591025910359104591055910659107591085910959110591115911259113591145911559116591175911859119591205912159122591235912459125591265912759128591295913059131591325913359134591355913659137591385913959140591415914259143591445914559146591475914859149591505915159152591535915459155591565915759158591595916059161591625916359164591655916659167591685916959170591715917259173591745917559176591775917859179591805918159182591835918459185591865918759188591895919059191591925919359194591955919659197591985919959200592015920259203592045920559206592075920859209592105921159212592135921459215592165921759218592195922059221592225922359224592255922659227592285922959230592315923259233592345923559236592375923859239592405924159242592435924459245592465924759248592495925059251592525925359254592555925659257592585925959260592615926259263592645926559266592675926859269592705927159272592735927459275592765927759278592795928059281592825928359284592855928659287592885928959290592915929259293592945929559296592975929859299593005930159302593035930459305593065930759308593095931059311593125931359314593155931659317593185931959320593215932259323593245932559326593275932859329593305933159332593335933459335593365933759338593395934059341593425934359344593455934659347593485934959350593515935259353593545935559356593575935859359593605936159362593635936459365593665936759368593695937059371593725937359374593755937659377593785937959380593815938259383593845938559386593875938859389593905939159392593935939459395593965939759398593995940059401594025940359404594055940659407594085940959410594115941259413594145941559416594175941859419594205942159422594235942459425594265942759428594295943059431594325943359434594355943659437594385943959440594415944259443594445944559446594475944859449594505945159452594535945459455594565945759458594595946059461594625946359464594655946659467594685946959470594715947259473594745947559476594775947859479594805948159482594835948459485594865948759488594895949059491594925949359494594955949659497594985949959500595015950259503595045950559506595075950859509595105951159512595135951459515595165951759518595195952059521595225952359524595255952659527595285952959530595315953259533595345953559536595375953859539595405954159542595435954459545595465954759548595495955059551595525955359554595555955659557595585955959560595615956259563595645956559566595675956859569595705957159572595735957459575595765957759578595795958059581595825958359584595855958659587595885958959590595915959259593595945959559596595975959859599596005960159602596035960459605596065960759608596095961059611596125961359614596155961659617596185961959620596215962259623596245962559626596275962859629596305963159632596335963459635596365963759638596395964059641596425964359644596455964659647596485964959650596515965259653596545965559656596575965859659596605966159662596635966459665596665966759668596695967059671596725967359674596755967659677596785967959680596815968259683596845968559686596875968859689596905969159692596935969459695596965969759698596995970059701597025970359704597055970659707597085970959710597115971259713597145971559716597175971859719597205972159722597235972459725597265972759728597295973059731597325973359734597355973659737597385973959740597415974259743597445974559746597475974859749597505975159752597535975459755597565975759758597595976059761597625976359764597655976659767597685976959770597715977259773597745977559776597775977859779597805978159782597835978459785597865978759788597895979059791597925979359794597955979659797597985979959800598015980259803598045980559806598075980859809598105981159812598135981459815598165981759818598195982059821598225982359824598255982659827598285982959830598315983259833598345983559836598375983859839598405984159842598435984459845598465984759848598495985059851598525985359854598555985659857598585985959860598615986259863598645986559866598675986859869598705987159872598735987459875598765987759878598795988059881598825988359884598855988659887598885988959890598915989259893598945989559896598975989859899599005990159902599035990459905599065990759908599095991059911599125991359914599155991659917599185991959920599215992259923599245992559926599275992859929599305993159932599335993459935599365993759938599395994059941599425994359944599455994659947599485994959950599515995259953599545995559956599575995859959599605996159962599635996459965599665996759968599695997059971599725997359974599755997659977599785997959980599815998259983599845998559986599875998859989599905999159992599935999459995599965999759998599996000060001600026000360004600056000660007600086000960010600116001260013600146001560016600176001860019600206002160022600236002460025600266002760028600296003060031600326003360034600356003660037600386003960040600416004260043600446004560046600476004860049600506005160052600536005460055600566005760058600596006060061600626006360064600656006660067600686006960070600716007260073600746007560076600776007860079600806008160082600836008460085600866008760088600896009060091600926009360094600956009660097600986009960100601016010260103601046010560106601076010860109601106011160112601136011460115601166011760118601196012060121601226012360124601256012660127601286012960130601316013260133601346013560136601376013860139601406014160142601436014460145601466014760148601496015060151601526015360154601556015660157601586015960160601616016260163601646016560166601676016860169601706017160172601736017460175601766017760178601796018060181601826018360184601856018660187601886018960190601916019260193601946019560196601976019860199602006020160202602036020460205602066020760208602096021060211602126021360214602156021660217602186021960220602216022260223602246022560226602276022860229602306023160232602336023460235602366023760238602396024060241602426024360244602456024660247602486024960250602516025260253602546025560256602576025860259602606026160262602636026460265602666026760268602696027060271602726027360274602756027660277602786027960280602816028260283602846028560286602876028860289602906029160292602936029460295602966029760298602996030060301603026030360304603056030660307603086030960310603116031260313603146031560316603176031860319603206032160322603236032460325603266032760328603296033060331603326033360334603356033660337603386033960340603416034260343603446034560346603476034860349603506035160352603536035460355603566035760358603596036060361603626036360364603656036660367603686036960370603716037260373603746037560376603776037860379603806038160382603836038460385603866038760388603896039060391603926039360394603956039660397603986039960400604016040260403604046040560406604076040860409604106041160412604136041460415604166041760418604196042060421604226042360424604256042660427604286042960430604316043260433604346043560436604376043860439604406044160442604436044460445604466044760448604496045060451604526045360454604556045660457604586045960460604616046260463604646046560466604676046860469604706047160472604736047460475604766047760478604796048060481604826048360484604856048660487604886048960490604916049260493604946049560496604976049860499605006050160502605036050460505605066050760508605096051060511605126051360514605156051660517605186051960520605216052260523605246052560526605276052860529605306053160532605336053460535605366053760538605396054060541605426054360544605456054660547605486054960550605516055260553605546055560556605576055860559605606056160562605636056460565605666056760568605696057060571605726057360574605756057660577605786057960580605816058260583605846058560586605876058860589605906059160592605936059460595605966059760598605996060060601606026060360604606056060660607606086060960610606116061260613606146061560616606176061860619606206062160622606236062460625606266062760628606296063060631606326063360634606356063660637606386063960640606416064260643606446064560646606476064860649606506065160652606536065460655606566065760658606596066060661606626066360664606656066660667606686066960670606716067260673606746067560676606776067860679606806068160682606836068460685606866068760688606896069060691606926069360694606956069660697606986069960700607016070260703607046070560706607076070860709607106071160712607136071460715607166071760718607196072060721607226072360724607256072660727607286072960730607316073260733607346073560736607376073860739607406074160742607436074460745607466074760748607496075060751607526075360754607556075660757607586075960760607616076260763607646076560766607676076860769607706077160772607736077460775607766077760778607796078060781607826078360784607856078660787607886078960790607916079260793607946079560796607976079860799608006080160802608036080460805608066080760808608096081060811608126081360814608156081660817608186081960820608216082260823608246082560826608276082860829608306083160832608336083460835608366083760838608396084060841608426084360844608456084660847608486084960850608516085260853608546085560856608576085860859608606086160862608636086460865608666086760868608696087060871608726087360874608756087660877608786087960880608816088260883608846088560886608876088860889608906089160892608936089460895608966089760898608996090060901609026090360904609056090660907609086090960910609116091260913609146091560916609176091860919609206092160922609236092460925609266092760928609296093060931609326093360934609356093660937609386093960940609416094260943609446094560946609476094860949609506095160952609536095460955609566095760958609596096060961609626096360964609656096660967609686096960970609716097260973609746097560976609776097860979609806098160982609836098460985609866098760988609896099060991609926099360994609956099660997609986099961000610016100261003610046100561006610076100861009610106101161012610136101461015610166101761018610196102061021610226102361024610256102661027610286102961030610316103261033610346103561036610376103861039610406104161042610436104461045610466104761048610496105061051610526105361054610556105661057610586105961060610616106261063610646106561066610676106861069610706107161072610736107461075610766107761078610796108061081610826108361084610856108661087610886108961090610916109261093610946109561096610976109861099611006110161102611036110461105611066110761108611096111061111611126111361114611156111661117611186111961120611216112261123611246112561126611276112861129611306113161132611336113461135611366113761138611396114061141611426114361144611456114661147611486114961150611516115261153611546115561156611576115861159611606116161162611636116461165611666116761168611696117061171611726117361174611756117661177611786117961180611816118261183611846118561186611876118861189611906119161192611936119461195611966119761198611996120061201612026120361204612056120661207612086120961210612116121261213612146121561216612176121861219612206122161222612236122461225612266122761228612296123061231612326123361234612356123661237612386123961240612416124261243612446124561246612476124861249612506125161252612536125461255612566125761258612596126061261612626126361264612656126661267612686126961270612716127261273612746127561276612776127861279612806128161282612836128461285612866128761288612896129061291612926129361294612956129661297612986129961300613016130261303613046130561306613076130861309613106131161312613136131461315613166131761318613196132061321613226132361324613256132661327613286132961330613316133261333613346133561336613376133861339613406134161342613436134461345613466134761348613496135061351613526135361354613556135661357613586135961360613616136261363613646136561366613676136861369613706137161372613736137461375613766137761378613796138061381613826138361384613856138661387613886138961390613916139261393613946139561396613976139861399614006140161402614036140461405614066140761408614096141061411614126141361414614156141661417614186141961420614216142261423614246142561426614276142861429614306143161432614336143461435614366143761438614396144061441614426144361444614456144661447614486144961450614516145261453614546145561456614576145861459614606146161462614636146461465614666146761468614696147061471614726147361474614756147661477614786147961480614816148261483614846148561486614876148861489614906149161492614936149461495614966149761498614996150061501615026150361504615056150661507615086150961510615116151261513615146151561516615176151861519615206152161522615236152461525615266152761528615296153061531615326153361534615356153661537615386153961540615416154261543615446154561546615476154861549615506155161552615536155461555615566155761558615596156061561615626156361564615656156661567615686156961570615716157261573615746157561576615776157861579615806158161582615836158461585615866158761588615896159061591615926159361594615956159661597615986159961600616016160261603616046160561606616076160861609616106161161612616136161461615616166161761618616196162061621616226162361624616256162661627616286162961630616316163261633616346163561636616376163861639616406164161642616436164461645616466164761648616496165061651616526165361654616556165661657616586165961660616616166261663616646166561666616676166861669616706167161672616736167461675616766167761678616796168061681616826168361684616856168661687616886168961690616916169261693616946169561696616976169861699617006170161702617036170461705617066170761708617096171061711617126171361714617156171661717617186171961720617216172261723617246172561726617276172861729617306173161732617336173461735617366173761738617396174061741617426174361744617456174661747617486174961750617516175261753617546175561756617576175861759617606176161762617636176461765617666176761768617696177061771617726177361774617756177661777617786177961780617816178261783617846178561786617876178861789617906179161792617936179461795617966179761798617996180061801618026180361804618056180661807618086180961810618116181261813618146181561816618176181861819618206182161822618236182461825618266182761828618296183061831618326183361834618356183661837618386183961840618416184261843618446184561846618476184861849618506185161852618536185461855618566185761858618596186061861618626186361864618656186661867618686186961870618716187261873618746187561876618776187861879618806188161882618836188461885618866188761888618896189061891618926189361894618956189661897618986189961900619016190261903619046190561906619076190861909619106191161912619136191461915619166191761918619196192061921619226192361924619256192661927619286192961930619316193261933619346193561936619376193861939619406194161942619436194461945619466194761948619496195061951619526195361954619556195661957619586195961960619616196261963619646196561966619676196861969619706197161972619736197461975619766197761978619796198061981619826198361984619856198661987619886198961990619916199261993619946199561996619976199861999620006200162002620036200462005620066200762008620096201062011620126201362014620156201662017620186201962020620216202262023620246202562026620276202862029620306203162032620336203462035620366203762038620396204062041620426204362044620456204662047620486204962050620516205262053620546205562056620576205862059620606206162062620636206462065620666206762068620696207062071620726207362074620756207662077620786207962080620816208262083620846208562086620876208862089620906209162092620936209462095620966209762098620996210062101621026210362104621056210662107621086210962110621116211262113621146211562116621176211862119621206212162122621236212462125621266212762128621296213062131621326213362134621356213662137621386213962140621416214262143621446214562146621476214862149621506215162152621536215462155621566215762158621596216062161621626216362164621656216662167621686216962170621716217262173621746217562176621776217862179621806218162182621836218462185621866218762188621896219062191621926219362194621956219662197621986219962200622016220262203622046220562206622076220862209622106221162212622136221462215622166221762218622196222062221622226222362224622256222662227622286222962230622316223262233622346223562236622376223862239622406224162242622436224462245622466224762248622496225062251622526225362254622556225662257622586225962260622616226262263622646226562266622676226862269622706227162272622736227462275622766227762278622796228062281622826228362284622856228662287622886228962290622916229262293622946229562296622976229862299623006230162302623036230462305623066230762308623096231062311623126231362314623156231662317623186231962320623216232262323623246232562326623276232862329623306233162332623336233462335623366233762338623396234062341623426234362344623456234662347623486234962350623516235262353623546235562356623576235862359623606236162362623636236462365623666236762368623696237062371623726237362374623756237662377623786237962380623816238262383623846238562386623876238862389623906239162392623936239462395623966239762398623996240062401624026240362404624056240662407624086240962410624116241262413624146241562416624176241862419624206242162422624236242462425624266242762428624296243062431624326243362434624356243662437624386243962440624416244262443624446244562446624476244862449624506245162452624536245462455624566245762458624596246062461624626246362464624656246662467624686246962470624716247262473624746247562476624776247862479624806248162482624836248462485624866248762488624896249062491624926249362494624956249662497624986249962500625016250262503625046250562506625076250862509625106251162512625136251462515625166251762518625196252062521625226252362524625256252662527625286252962530625316253262533625346253562536625376253862539625406254162542625436254462545625466254762548625496255062551625526255362554625556255662557625586255962560625616256262563625646256562566625676256862569625706257162572625736257462575625766257762578625796258062581625826258362584625856258662587625886258962590625916259262593625946259562596625976259862599626006260162602626036260462605626066260762608626096261062611626126261362614626156261662617626186261962620626216262262623626246262562626626276262862629626306263162632626336263462635626366263762638626396264062641626426264362644626456264662647626486264962650626516265262653626546265562656626576265862659626606266162662626636266462665626666266762668626696267062671626726267362674626756267662677626786267962680626816268262683626846268562686626876268862689626906269162692626936269462695626966269762698626996270062701627026270362704627056270662707627086270962710627116271262713627146271562716627176271862719627206272162722627236272462725627266272762728627296273062731627326273362734627356273662737627386273962740627416274262743627446274562746627476274862749627506275162752627536275462755627566275762758627596276062761627626276362764627656276662767627686276962770627716277262773627746277562776627776277862779627806278162782627836278462785627866278762788627896279062791627926279362794627956279662797627986279962800628016280262803628046280562806628076280862809628106281162812628136281462815628166281762818628196282062821628226282362824628256282662827628286282962830628316283262833628346283562836628376283862839628406284162842628436284462845628466284762848628496285062851628526285362854628556285662857628586285962860628616286262863628646286562866628676286862869628706287162872628736287462875628766287762878628796288062881628826288362884628856288662887628886288962890628916289262893628946289562896628976289862899629006290162902629036290462905629066290762908629096291062911629126291362914629156291662917629186291962920629216292262923629246292562926629276292862929629306293162932629336293462935629366293762938629396294062941629426294362944629456294662947629486294962950629516295262953629546295562956629576295862959629606296162962629636296462965629666296762968629696297062971629726297362974629756297662977629786297962980629816298262983629846298562986629876298862989629906299162992629936299462995629966299762998629996300063001630026300363004630056300663007630086300963010630116301263013630146301563016630176301863019630206302163022630236302463025630266302763028630296303063031630326303363034630356303663037630386303963040630416304263043630446304563046630476304863049630506305163052630536305463055630566305763058630596306063061630626306363064630656306663067630686306963070630716307263073630746307563076630776307863079630806308163082630836308463085630866308763088630896309063091630926309363094630956309663097630986309963100631016310263103631046310563106631076310863109631106311163112631136311463115631166311763118631196312063121631226312363124631256312663127631286312963130631316313263133631346313563136631376313863139631406314163142631436314463145631466314763148631496315063151631526315363154631556315663157631586315963160631616316263163631646316563166631676316863169631706317163172631736317463175631766317763178631796318063181631826318363184631856318663187631886318963190631916319263193631946319563196631976319863199632006320163202632036320463205632066320763208632096321063211632126321363214632156321663217632186321963220632216322263223632246322563226632276322863229632306323163232632336323463235632366323763238632396324063241632426324363244632456324663247632486324963250632516325263253632546325563256632576325863259632606326163262632636326463265632666326763268632696327063271632726327363274632756327663277632786327963280632816328263283632846328563286632876328863289632906329163292632936329463295632966329763298632996330063301633026330363304633056330663307633086330963310633116331263313633146331563316633176331863319633206332163322633236332463325633266332763328633296333063331633326333363334633356333663337633386333963340633416334263343633446334563346633476334863349633506335163352633536335463355633566335763358633596336063361633626336363364633656336663367633686336963370633716337263373633746337563376633776337863379633806338163382633836338463385633866338763388633896339063391633926339363394633956339663397633986339963400634016340263403634046340563406634076340863409634106341163412634136341463415634166341763418634196342063421634226342363424634256342663427634286342963430634316343263433634346343563436634376343863439634406344163442634436344463445634466344763448634496345063451634526345363454634556345663457634586345963460634616346263463634646346563466634676346863469634706347163472634736347463475634766347763478634796348063481634826348363484634856348663487634886348963490634916349263493634946349563496634976349863499635006350163502635036350463505635066350763508635096351063511635126351363514635156351663517635186351963520635216352263523635246352563526635276352863529635306353163532635336353463535635366353763538635396354063541635426354363544635456354663547635486354963550635516355263553635546355563556635576355863559635606356163562635636356463565635666356763568635696357063571635726357363574635756357663577635786357963580635816358263583635846358563586635876358863589635906359163592635936359463595635966359763598635996360063601636026360363604636056360663607636086360963610636116361263613636146361563616636176361863619636206362163622636236362463625636266362763628636296363063631636326363363634636356363663637636386363963640636416364263643636446364563646636476364863649636506365163652636536365463655636566365763658636596366063661636626366363664636656366663667636686366963670636716367263673636746367563676636776367863679636806368163682636836368463685636866368763688636896369063691636926369363694636956369663697636986369963700637016370263703637046370563706637076370863709637106371163712637136371463715637166371763718637196372063721637226372363724637256372663727637286372963730637316373263733637346373563736637376373863739637406374163742637436374463745637466374763748637496375063751637526375363754637556375663757637586375963760637616376263763637646376563766637676376863769637706377163772637736377463775637766377763778637796378063781637826378363784637856378663787637886378963790637916379263793637946379563796637976379863799638006380163802638036380463805638066380763808638096381063811638126381363814638156381663817638186381963820638216382263823638246382563826638276382863829638306383163832638336383463835638366383763838638396384063841638426384363844638456384663847638486384963850638516385263853638546385563856638576385863859638606386163862638636386463865638666386763868638696387063871638726387363874638756387663877638786387963880638816388263883638846388563886638876388863889638906389163892638936389463895638966389763898638996390063901639026390363904639056390663907639086390963910639116391263913639146391563916639176391863919639206392163922639236392463925639266392763928639296393063931639326393363934639356393663937639386393963940639416394263943639446394563946639476394863949639506395163952639536395463955639566395763958639596396063961639626396363964639656396663967639686396963970639716397263973639746397563976639776397863979639806398163982639836398463985639866398763988639896399063991639926399363994639956399663997639986399964000640016400264003640046400564006640076400864009640106401164012640136401464015640166401764018640196402064021640226402364024640256402664027640286402964030640316403264033640346403564036640376403864039640406404164042640436404464045640466404764048640496405064051640526405364054640556405664057640586405964060640616406264063640646406564066640676406864069640706407164072640736407464075640766407764078640796408064081640826408364084640856408664087640886408964090640916409264093640946409564096640976409864099641006410164102641036410464105641066410764108641096411064111641126411364114641156411664117641186411964120641216412264123641246412564126641276412864129641306413164132641336413464135641366413764138641396414064141641426414364144641456414664147641486414964150641516415264153641546415564156641576415864159641606416164162641636416464165641666416764168641696417064171641726417364174641756417664177641786417964180641816418264183641846418564186641876418864189641906419164192641936419464195641966419764198641996420064201642026420364204642056420664207642086420964210642116421264213642146421564216642176421864219642206422164222642236422464225642266422764228642296423064231642326423364234642356423664237642386423964240642416424264243642446424564246642476424864249642506425164252642536425464255642566425764258642596426064261642626426364264642656426664267642686426964270642716427264273642746427564276642776427864279642806428164282642836428464285642866428764288642896429064291642926429364294642956429664297642986429964300643016430264303643046430564306643076430864309643106431164312643136431464315643166431764318643196432064321643226432364324643256432664327643286432964330643316433264333643346433564336643376433864339643406434164342643436434464345643466434764348643496435064351643526435364354643556435664357643586435964360643616436264363643646436564366643676436864369643706437164372643736437464375643766437764378643796438064381643826438364384643856438664387643886438964390643916439264393643946439564396643976439864399644006440164402644036440464405644066440764408644096441064411644126441364414644156441664417644186441964420644216442264423644246442564426644276442864429644306443164432644336443464435644366443764438644396444064441644426444364444644456444664447644486444964450644516445264453644546445564456644576445864459644606446164462644636446464465644666446764468644696447064471644726447364474644756447664477644786447964480644816448264483644846448564486644876448864489644906449164492644936449464495644966449764498644996450064501645026450364504645056450664507645086450964510645116451264513645146451564516645176451864519645206452164522645236452464525645266452764528645296453064531645326453364534645356453664537645386453964540645416454264543645446454564546645476454864549645506455164552645536455464555645566455764558645596456064561645626456364564645656456664567645686456964570645716457264573645746457564576645776457864579645806458164582645836458464585645866458764588645896459064591645926459364594645956459664597645986459964600646016460264603646046460564606646076460864609646106461164612646136461464615646166461764618646196462064621646226462364624646256462664627646286462964630646316463264633646346463564636646376463864639646406464164642646436464464645646466464764648646496465064651646526465364654646556465664657646586465964660646616466264663646646466564666646676466864669646706467164672646736467464675646766467764678646796468064681646826468364684646856468664687646886468964690646916469264693646946469564696646976469864699647006470164702647036470464705647066470764708647096471064711647126471364714647156471664717647186471964720647216472264723647246472564726647276472864729647306473164732647336473464735647366473764738647396474064741647426474364744647456474664747647486474964750647516475264753647546475564756647576475864759647606476164762647636476464765647666476764768647696477064771647726477364774647756477664777647786477964780647816478264783647846478564786647876478864789647906479164792647936479464795647966479764798647996480064801648026480364804648056480664807648086480964810648116481264813648146481564816648176481864819648206482164822648236482464825648266482764828648296483064831648326483364834648356483664837648386483964840648416484264843648446484564846648476484864849648506485164852648536485464855648566485764858648596486064861648626486364864648656486664867648686486964870648716487264873648746487564876648776487864879648806488164882648836488464885648866488764888648896489064891648926489364894648956489664897648986489964900649016490264903649046490564906649076490864909649106491164912649136491464915649166491764918649196492064921649226492364924649256492664927649286492964930649316493264933649346493564936649376493864939649406494164942649436494464945649466494764948649496495064951649526495364954649556495664957649586495964960649616496264963649646496564966649676496864969649706497164972649736497464975649766497764978649796498064981649826498364984649856498664987649886498964990649916499264993649946499564996649976499864999650006500165002650036500465005650066500765008650096501065011650126501365014650156501665017650186501965020650216502265023650246502565026650276502865029650306503165032650336503465035650366503765038650396504065041650426504365044650456504665047650486504965050650516505265053650546505565056650576505865059650606506165062650636506465065650666506765068650696507065071650726507365074650756507665077650786507965080650816508265083650846508565086650876508865089650906509165092650936509465095650966509765098650996510065101651026510365104651056510665107651086510965110651116511265113651146511565116651176511865119651206512165122651236512465125651266512765128651296513065131651326513365134651356513665137651386513965140651416514265143651446514565146651476514865149651506515165152651536515465155651566515765158651596516065161651626516365164651656516665167651686516965170651716517265173651746517565176651776517865179651806518165182651836518465185651866518765188651896519065191651926519365194651956519665197651986519965200652016520265203652046520565206652076520865209652106521165212652136521465215652166521765218652196522065221652226522365224652256522665227652286522965230652316523265233652346523565236652376523865239652406524165242652436524465245652466524765248652496525065251652526525365254652556525665257652586525965260652616526265263652646526565266652676526865269652706527165272652736527465275652766527765278652796528065281652826528365284652856528665287652886528965290652916529265293652946529565296652976529865299653006530165302653036530465305653066530765308653096531065311653126531365314653156531665317653186531965320653216532265323653246532565326653276532865329653306533165332653336533465335653366533765338653396534065341653426534365344653456534665347653486534965350653516535265353653546535565356653576535865359653606536165362653636536465365653666536765368653696537065371653726537365374653756537665377653786537965380653816538265383653846538565386653876538865389653906539165392653936539465395653966539765398653996540065401654026540365404654056540665407654086540965410654116541265413654146541565416654176541865419654206542165422654236542465425654266542765428654296543065431654326543365434654356543665437654386543965440654416544265443654446544565446654476544865449654506545165452654536545465455654566545765458654596546065461654626546365464654656546665467654686546965470654716547265473654746547565476654776547865479654806548165482654836548465485654866548765488654896549065491654926549365494654956549665497654986549965500655016550265503655046550565506655076550865509655106551165512655136551465515655166551765518655196552065521655226552365524655256552665527655286552965530655316553265533655346553565536655376553865539655406554165542655436554465545655466554765548655496555065551655526555365554655556555665557655586555965560655616556265563655646556565566655676556865569655706557165572655736557465575655766557765578655796558065581655826558365584655856558665587655886558965590655916559265593655946559565596655976559865599656006560165602656036560465605656066560765608656096561065611656126561365614656156561665617656186561965620656216562265623656246562565626656276562865629656306563165632656336563465635656366563765638656396564065641656426564365644656456564665647656486564965650656516565265653656546565565656656576565865659656606566165662656636566465665656666566765668656696567065671656726567365674656756567665677656786567965680656816568265683656846568565686656876568865689656906569165692656936569465695656966569765698656996570065701657026570365704657056570665707657086570965710657116571265713657146571565716657176571865719657206572165722657236572465725657266572765728657296573065731657326573365734657356573665737657386573965740657416574265743657446574565746657476574865749657506575165752657536575465755657566575765758657596576065761657626576365764657656576665767657686576965770657716577265773657746577565776657776577865779657806578165782657836578465785657866578765788657896579065791657926579365794657956579665797657986579965800658016580265803658046580565806658076580865809658106581165812658136581465815658166581765818658196582065821658226582365824658256582665827658286582965830658316583265833658346583565836658376583865839658406584165842658436584465845658466584765848658496585065851658526585365854658556585665857658586585965860658616586265863658646586565866658676586865869658706587165872658736587465875658766587765878658796588065881658826588365884658856588665887658886588965890658916589265893658946589565896658976589865899659006590165902659036590465905659066590765908659096591065911659126591365914659156591665917659186591965920659216592265923659246592565926659276592865929659306593165932659336593465935659366593765938659396594065941659426594365944659456594665947659486594965950659516595265953659546595565956659576595865959659606596165962659636596465965659666596765968659696597065971659726597365974659756597665977659786597965980659816598265983659846598565986659876598865989659906599165992659936599465995659966599765998659996600066001660026600366004660056600666007660086600966010660116601266013660146601566016660176601866019660206602166022660236602466025660266602766028660296603066031660326603366034660356603666037660386603966040660416604266043660446604566046660476604866049660506605166052660536605466055660566605766058660596606066061660626606366064660656606666067660686606966070660716607266073660746607566076660776607866079660806608166082660836608466085660866608766088660896609066091660926609366094660956609666097660986609966100661016610266103661046610566106661076610866109661106611166112661136611466115661166611766118661196612066121661226612366124661256612666127661286612966130661316613266133661346613566136661376613866139661406614166142661436614466145661466614766148661496615066151661526615366154661556615666157661586615966160661616616266163661646616566166661676616866169661706617166172661736617466175661766617766178661796618066181661826618366184661856618666187661886618966190661916619266193661946619566196661976619866199662006620166202662036620466205662066620766208662096621066211662126621366214662156621666217662186621966220662216622266223662246622566226662276622866229662306623166232662336623466235662366623766238662396624066241662426624366244662456624666247662486624966250662516625266253662546625566256662576625866259662606626166262662636626466265662666626766268662696627066271662726627366274662756627666277662786627966280662816628266283662846628566286662876628866289662906629166292662936629466295662966629766298662996630066301663026630366304663056630666307663086630966310663116631266313663146631566316663176631866319663206632166322663236632466325663266632766328663296633066331663326633366334663356633666337663386633966340663416634266343663446634566346663476634866349663506635166352663536635466355663566635766358663596636066361663626636366364663656636666367663686636966370663716637266373663746637566376663776637866379663806638166382663836638466385663866638766388663896639066391663926639366394663956639666397663986639966400664016640266403664046640566406664076640866409664106641166412664136641466415664166641766418664196642066421664226642366424664256642666427664286642966430664316643266433664346643566436664376643866439664406644166442664436644466445664466644766448664496645066451664526645366454664556645666457664586645966460664616646266463664646646566466664676646866469664706647166472664736647466475664766647766478664796648066481664826648366484664856648666487664886648966490664916649266493664946649566496664976649866499665006650166502665036650466505665066650766508665096651066511665126651366514665156651666517665186651966520665216652266523665246652566526665276652866529665306653166532665336653466535665366653766538665396654066541665426654366544665456654666547665486654966550665516655266553665546655566556665576655866559665606656166562665636656466565665666656766568665696657066571665726657366574665756657666577665786657966580665816658266583665846658566586665876658866589665906659166592665936659466595665966659766598665996660066601666026660366604666056660666607666086660966610666116661266613666146661566616666176661866619666206662166622666236662466625666266662766628666296663066631666326663366634666356663666637666386663966640666416664266643666446664566646666476664866649666506665166652666536665466655666566665766658666596666066661666626666366664666656666666667666686666966670666716667266673666746667566676666776667866679666806668166682666836668466685666866668766688666896669066691666926669366694666956669666697666986669966700667016670266703667046670566706667076670866709667106671166712667136671466715667166671766718667196672066721667226672366724667256672666727667286672966730667316673266733667346673566736667376673866739667406674166742667436674466745667466674766748667496675066751667526675366754667556675666757667586675966760667616676266763667646676566766667676676866769667706677166772667736677466775667766677766778667796678066781667826678366784667856678666787667886678966790667916679266793667946679566796667976679866799668006680166802668036680466805668066680766808668096681066811668126681366814668156681666817668186681966820668216682266823668246682566826668276682866829668306683166832668336683466835668366683766838668396684066841668426684366844668456684666847668486684966850668516685266853668546685566856668576685866859668606686166862668636686466865668666686766868668696687066871668726687366874668756687666877668786687966880668816688266883668846688566886668876688866889668906689166892668936689466895668966689766898668996690066901669026690366904669056690666907669086690966910669116691266913669146691566916669176691866919669206692166922669236692466925669266692766928669296693066931669326693366934669356693666937669386693966940669416694266943669446694566946669476694866949669506695166952669536695466955669566695766958669596696066961669626696366964669656696666967669686696966970669716697266973669746697566976669776697866979669806698166982669836698466985669866698766988669896699066991669926699366994669956699666997669986699967000670016700267003670046700567006670076700867009670106701167012670136701467015670166701767018670196702067021670226702367024670256702667027670286702967030670316703267033670346703567036670376703867039670406704167042670436704467045670466704767048670496705067051670526705367054670556705667057670586705967060670616706267063670646706567066670676706867069670706707167072670736707467075670766707767078670796708067081670826708367084670856708667087670886708967090670916709267093670946709567096670976709867099671006710167102671036710467105671066710767108671096711067111671126711367114671156711667117671186711967120671216712267123671246712567126671276712867129671306713167132671336713467135671366713767138671396714067141671426714367144671456714667147671486714967150671516715267153671546715567156671576715867159671606716167162671636716467165671666716767168671696717067171671726717367174671756717667177671786717967180671816718267183671846718567186671876718867189671906719167192671936719467195671966719767198671996720067201672026720367204672056720667207672086720967210672116721267213672146721567216672176721867219672206722167222672236722467225672266722767228672296723067231672326723367234672356723667237672386723967240672416724267243672446724567246672476724867249672506725167252672536725467255672566725767258672596726067261672626726367264672656726667267672686726967270672716727267273672746727567276672776727867279672806728167282672836728467285672866728767288672896729067291672926729367294672956729667297672986729967300673016730267303673046730567306673076730867309673106731167312673136731467315673166731767318673196732067321673226732367324673256732667327673286732967330673316733267333673346733567336673376733867339673406734167342673436734467345673466734767348673496735067351673526735367354673556735667357673586735967360673616736267363673646736567366673676736867369673706737167372673736737467375673766737767378673796738067381673826738367384673856738667387673886738967390673916739267393673946739567396673976739867399674006740167402674036740467405674066740767408674096741067411674126741367414674156741667417674186741967420674216742267423674246742567426674276742867429674306743167432674336743467435674366743767438674396744067441674426744367444674456744667447674486744967450674516745267453674546745567456674576745867459674606746167462674636746467465674666746767468674696747067471674726747367474674756747667477674786747967480674816748267483674846748567486674876748867489674906749167492674936749467495674966749767498674996750067501675026750367504675056750667507675086750967510675116751267513675146751567516675176751867519675206752167522675236752467525675266752767528675296753067531675326753367534675356753667537675386753967540675416754267543675446754567546675476754867549675506755167552675536755467555675566755767558675596756067561675626756367564675656756667567675686756967570675716757267573675746757567576675776757867579675806758167582675836758467585675866758767588675896759067591675926759367594675956759667597675986759967600676016760267603676046760567606676076760867609676106761167612676136761467615676166761767618676196762067621676226762367624676256762667627676286762967630676316763267633676346763567636676376763867639676406764167642676436764467645676466764767648676496765067651676526765367654676556765667657676586765967660676616766267663676646766567666676676766867669676706767167672676736767467675676766767767678676796768067681676826768367684676856768667687676886768967690676916769267693676946769567696676976769867699677006770167702677036770467705677066770767708677096771067711677126771367714677156771667717677186771967720677216772267723677246772567726677276772867729677306773167732677336773467735677366773767738677396774067741677426774367744677456774667747677486774967750677516775267753677546775567756677576775867759677606776167762677636776467765677666776767768677696777067771677726777367774677756777667777677786777967780677816778267783677846778567786677876778867789677906779167792677936779467795677966779767798677996780067801678026780367804678056780667807678086780967810678116781267813678146781567816678176781867819678206782167822678236782467825678266782767828678296783067831678326783367834678356783667837678386783967840678416784267843678446784567846678476784867849678506785167852678536785467855678566785767858678596786067861678626786367864678656786667867678686786967870678716787267873678746787567876678776787867879678806788167882678836788467885678866788767888678896789067891678926789367894678956789667897678986789967900679016790267903679046790567906679076790867909679106791167912679136791467915679166791767918679196792067921679226792367924679256792667927679286792967930679316793267933679346793567936679376793867939679406794167942679436794467945679466794767948679496795067951679526795367954679556795667957679586795967960679616796267963679646796567966679676796867969679706797167972679736797467975679766797767978679796798067981679826798367984679856798667987679886798967990679916799267993679946799567996679976799867999680006800168002680036800468005680066800768008680096801068011680126801368014680156801668017680186801968020680216802268023680246802568026680276802868029680306803168032680336803468035680366803768038680396804068041680426804368044680456804668047680486804968050680516805268053680546805568056680576805868059680606806168062680636806468065680666806768068680696807068071680726807368074680756807668077680786807968080680816808268083680846808568086680876808868089680906809168092680936809468095680966809768098680996810068101681026810368104681056810668107681086810968110681116811268113681146811568116681176811868119681206812168122681236812468125681266812768128681296813068131681326813368134681356813668137681386813968140681416814268143681446814568146681476814868149681506815168152681536815468155681566815768158681596816068161681626816368164681656816668167681686816968170681716817268173681746817568176681776817868179681806818168182681836818468185681866818768188681896819068191681926819368194681956819668197681986819968200682016820268203682046820568206682076820868209682106821168212682136821468215682166821768218682196822068221682226822368224682256822668227682286822968230682316823268233682346823568236682376823868239682406824168242682436824468245682466824768248682496825068251682526825368254682556825668257682586825968260682616826268263682646826568266682676826868269682706827168272682736827468275682766827768278682796828068281682826828368284682856828668287682886828968290682916829268293682946829568296682976829868299683006830168302683036830468305683066830768308683096831068311683126831368314683156831668317683186831968320683216832268323683246832568326683276832868329683306833168332683336833468335683366833768338683396834068341683426834368344683456834668347683486834968350683516835268353683546835568356683576835868359683606836168362683636836468365683666836768368683696837068371683726837368374683756837668377683786837968380683816838268383683846838568386683876838868389683906839168392683936839468395683966839768398683996840068401684026840368404684056840668407684086840968410684116841268413684146841568416684176841868419684206842168422684236842468425684266842768428684296843068431684326843368434684356843668437684386843968440684416844268443684446844568446684476844868449684506845168452684536845468455684566845768458684596846068461684626846368464684656846668467684686846968470684716847268473684746847568476684776847868479684806848168482684836848468485684866848768488684896849068491684926849368494684956849668497684986849968500685016850268503685046850568506685076850868509685106851168512685136851468515685166851768518685196852068521685226852368524685256852668527685286852968530685316853268533685346853568536685376853868539685406854168542685436854468545685466854768548685496855068551685526855368554685556855668557685586855968560685616856268563685646856568566685676856868569685706857168572685736857468575685766857768578685796858068581685826858368584685856858668587685886858968590685916859268593685946859568596685976859868599686006860168602686036860468605686066860768608686096861068611686126861368614686156861668617686186861968620686216862268623686246862568626686276862868629686306863168632686336863468635686366863768638686396864068641686426864368644686456864668647686486864968650686516865268653686546865568656686576865868659686606866168662686636866468665686666866768668686696867068671686726867368674686756867668677686786867968680686816868268683686846868568686686876868868689686906869168692686936869468695686966869768698686996870068701687026870368704687056870668707687086870968710687116871268713687146871568716687176871868719687206872168722687236872468725687266872768728687296873068731687326873368734687356873668737687386873968740687416874268743687446874568746687476874868749687506875168752687536875468755687566875768758687596876068761687626876368764687656876668767687686876968770687716877268773687746877568776687776877868779687806878168782687836878468785687866878768788687896879068791687926879368794687956879668797687986879968800688016880268803688046880568806688076880868809688106881168812688136881468815688166881768818688196882068821688226882368824688256882668827688286882968830688316883268833688346883568836688376883868839688406884168842688436884468845688466884768848688496885068851688526885368854688556885668857688586885968860688616886268863688646886568866688676886868869688706887168872688736887468875688766887768878688796888068881688826888368884688856888668887688886888968890688916889268893688946889568896688976889868899689006890168902689036890468905689066890768908689096891068911689126891368914689156891668917689186891968920689216892268923689246892568926689276892868929689306893168932689336893468935689366893768938689396894068941689426894368944689456894668947689486894968950689516895268953689546895568956689576895868959689606896168962689636896468965689666896768968689696897068971689726897368974689756897668977689786897968980689816898268983689846898568986689876898868989689906899168992689936899468995689966899768998689996900069001690026900369004690056900669007690086900969010690116901269013690146901569016690176901869019690206902169022690236902469025690266902769028690296903069031690326903369034690356903669037690386903969040690416904269043690446904569046690476904869049690506905169052690536905469055690566905769058690596906069061690626906369064690656906669067690686906969070690716907269073690746907569076690776907869079690806908169082690836908469085690866908769088690896909069091690926909369094690956909669097690986909969100691016910269103691046910569106691076910869109691106911169112691136911469115691166911769118691196912069121691226912369124691256912669127691286912969130691316913269133691346913569136691376913869139691406914169142691436914469145691466914769148691496915069151691526915369154691556915669157691586915969160691616916269163691646916569166691676916869169691706917169172691736917469175691766917769178691796918069181691826918369184691856918669187691886918969190691916919269193691946919569196691976919869199692006920169202692036920469205692066920769208692096921069211692126921369214692156921669217692186921969220692216922269223692246922569226692276922869229692306923169232692336923469235692366923769238692396924069241692426924369244692456924669247692486924969250692516925269253692546925569256692576925869259692606926169262692636926469265692666926769268692696927069271692726927369274692756927669277692786927969280692816928269283692846928569286692876928869289692906929169292692936929469295692966929769298692996930069301693026930369304693056930669307693086930969310693116931269313693146931569316693176931869319693206932169322693236932469325693266932769328693296933069331693326933369334693356933669337693386933969340693416934269343693446934569346693476934869349693506935169352693536935469355693566935769358693596936069361693626936369364693656936669367693686936969370693716937269373693746937569376693776937869379693806938169382693836938469385693866938769388693896939069391693926939369394693956939669397693986939969400694016940269403694046940569406694076940869409694106941169412694136941469415694166941769418694196942069421694226942369424694256942669427694286942969430694316943269433694346943569436694376943869439694406944169442694436944469445694466944769448694496945069451694526945369454694556945669457694586945969460694616946269463694646946569466694676946869469694706947169472694736947469475694766947769478694796948069481694826948369484694856948669487694886948969490694916949269493694946949569496694976949869499695006950169502695036950469505695066950769508695096951069511695126951369514695156951669517695186951969520695216952269523695246952569526695276952869529695306953169532695336953469535695366953769538695396954069541695426954369544695456954669547695486954969550695516955269553695546955569556695576955869559695606956169562695636956469565695666956769568695696957069571695726957369574695756957669577695786957969580695816958269583695846958569586695876958869589695906959169592695936959469595695966959769598695996960069601696026960369604696056960669607696086960969610696116961269613696146961569616696176961869619696206962169622696236962469625696266962769628696296963069631696326963369634696356963669637696386963969640696416964269643696446964569646696476964869649696506965169652696536965469655696566965769658696596966069661696626966369664696656966669667696686966969670696716967269673696746967569676696776967869679696806968169682696836968469685696866968769688696896969069691696926969369694696956969669697696986969969700697016970269703697046970569706697076970869709697106971169712697136971469715697166971769718697196972069721697226972369724697256972669727697286972969730697316973269733697346973569736697376973869739697406974169742697436974469745697466974769748697496975069751697526975369754697556975669757697586975969760697616976269763697646976569766697676976869769697706977169772697736977469775697766977769778697796978069781697826978369784697856978669787697886978969790697916979269793697946979569796697976979869799698006980169802698036980469805698066980769808698096981069811698126981369814698156981669817698186981969820698216982269823698246982569826698276982869829698306983169832698336983469835698366983769838698396984069841698426984369844698456984669847698486984969850698516985269853698546985569856698576985869859698606986169862698636986469865698666986769868698696987069871698726987369874698756987669877698786987969880698816988269883698846988569886698876988869889698906989169892698936989469895698966989769898698996990069901699026990369904699056990669907699086990969910699116991269913699146991569916699176991869919699206992169922699236992469925699266992769928699296993069931699326993369934699356993669937699386993969940699416994269943699446994569946699476994869949699506995169952699536995469955699566995769958699596996069961699626996369964699656996669967699686996969970699716997269973699746997569976699776997869979699806998169982699836998469985699866998769988699896999069991699926999369994699956999669997699986999970000700017000270003700047000570006700077000870009700107001170012700137001470015700167001770018700197002070021700227002370024700257002670027700287002970030700317003270033700347003570036700377003870039700407004170042700437004470045700467004770048700497005070051700527005370054700557005670057700587005970060700617006270063700647006570066700677006870069700707007170072700737007470075700767007770078700797008070081700827008370084700857008670087700887008970090700917009270093700947009570096700977009870099701007010170102701037010470105701067010770108701097011070111701127011370114701157011670117701187011970120701217012270123701247012570126701277012870129701307013170132701337013470135701367013770138701397014070141701427014370144701457014670147701487014970150701517015270153701547015570156701577015870159701607016170162701637016470165701667016770168701697017070171701727017370174701757017670177701787017970180701817018270183701847018570186701877018870189701907019170192701937019470195701967019770198701997020070201702027020370204702057020670207702087020970210702117021270213702147021570216702177021870219702207022170222702237022470225702267022770228702297023070231702327023370234702357023670237702387023970240702417024270243702447024570246702477024870249702507025170252702537025470255702567025770258702597026070261702627026370264702657026670267702687026970270702717027270273702747027570276702777027870279702807028170282702837028470285702867028770288702897029070291702927029370294702957029670297702987029970300703017030270303703047030570306703077030870309703107031170312703137031470315703167031770318703197032070321703227032370324703257032670327703287032970330703317033270333703347033570336703377033870339703407034170342703437034470345703467034770348703497035070351703527035370354703557035670357703587035970360703617036270363703647036570366703677036870369703707037170372703737037470375703767037770378703797038070381703827038370384703857038670387703887038970390703917039270393703947039570396703977039870399704007040170402704037040470405704067040770408704097041070411704127041370414704157041670417704187041970420704217042270423704247042570426704277042870429704307043170432704337043470435704367043770438704397044070441704427044370444704457044670447704487044970450704517045270453704547045570456704577045870459704607046170462704637046470465704667046770468704697047070471704727047370474704757047670477704787047970480704817048270483704847048570486704877048870489704907049170492704937049470495704967049770498704997050070501705027050370504705057050670507705087050970510705117051270513705147051570516705177051870519705207052170522705237052470525705267052770528705297053070531705327053370534705357053670537705387053970540705417054270543705447054570546705477054870549705507055170552705537055470555705567055770558705597056070561705627056370564705657056670567705687056970570705717057270573705747057570576705777057870579705807058170582705837058470585705867058770588705897059070591705927059370594705957059670597705987059970600706017060270603706047060570606706077060870609706107061170612706137061470615706167061770618706197062070621706227062370624706257062670627706287062970630706317063270633706347063570636706377063870639706407064170642706437064470645706467064770648706497065070651706527065370654706557065670657706587065970660706617066270663706647066570666706677066870669706707067170672706737067470675706767067770678706797068070681706827068370684706857068670687706887068970690706917069270693706947069570696706977069870699707007070170702707037070470705707067070770708707097071070711707127071370714707157071670717707187071970720707217072270723707247072570726707277072870729707307073170732707337073470735707367073770738707397074070741707427074370744707457074670747707487074970750707517075270753707547075570756707577075870759707607076170762707637076470765707667076770768707697077070771707727077370774707757077670777707787077970780707817078270783707847078570786707877078870789707907079170792707937079470795707967079770798707997080070801708027080370804708057080670807708087080970810708117081270813708147081570816708177081870819708207082170822708237082470825708267082770828708297083070831708327083370834708357083670837708387083970840708417084270843708447084570846708477084870849708507085170852708537085470855708567085770858708597086070861708627086370864708657086670867708687086970870708717087270873708747087570876708777087870879708807088170882708837088470885708867088770888708897089070891708927089370894708957089670897708987089970900709017090270903709047090570906709077090870909709107091170912709137091470915709167091770918709197092070921709227092370924709257092670927709287092970930709317093270933709347093570936709377093870939709407094170942709437094470945709467094770948709497095070951709527095370954709557095670957709587095970960709617096270963709647096570966709677096870969709707097170972709737097470975709767097770978709797098070981709827098370984709857098670987709887098970990709917099270993709947099570996709977099870999710007100171002710037100471005710067100771008710097101071011710127101371014710157101671017710187101971020710217102271023710247102571026710277102871029710307103171032710337103471035710367103771038710397104071041710427104371044710457104671047710487104971050710517105271053710547105571056710577105871059710607106171062710637106471065710667106771068710697107071071710727107371074710757107671077710787107971080710817108271083710847108571086710877108871089710907109171092710937109471095710967109771098710997110071101711027110371104711057110671107711087110971110711117111271113711147111571116711177111871119711207112171122711237112471125711267112771128711297113071131711327113371134711357113671137711387113971140711417114271143711447114571146711477114871149711507115171152711537115471155711567115771158711597116071161711627116371164711657116671167711687116971170711717117271173711747117571176711777117871179711807118171182711837118471185711867118771188711897119071191711927119371194711957119671197711987119971200712017120271203712047120571206712077120871209712107121171212712137121471215712167121771218712197122071221712227122371224712257122671227712287122971230712317123271233712347123571236712377123871239712407124171242712437124471245712467124771248712497125071251712527125371254712557125671257712587125971260712617126271263712647126571266712677126871269712707127171272712737127471275712767127771278712797128071281712827128371284712857128671287712887128971290712917129271293712947129571296712977129871299713007130171302713037130471305713067130771308713097131071311713127131371314713157131671317713187131971320713217132271323713247132571326713277132871329713307133171332713337133471335713367133771338713397134071341713427134371344713457134671347713487134971350713517135271353713547135571356713577135871359713607136171362713637136471365713667136771368713697137071371713727137371374713757137671377713787137971380713817138271383713847138571386713877138871389713907139171392713937139471395713967139771398713997140071401714027140371404714057140671407714087140971410714117141271413714147141571416714177141871419714207142171422714237142471425714267142771428714297143071431714327143371434714357143671437714387143971440714417144271443714447144571446714477144871449714507145171452714537145471455714567145771458714597146071461714627146371464714657146671467714687146971470714717147271473714747147571476714777147871479714807148171482714837148471485714867148771488714897149071491714927149371494714957149671497714987149971500715017150271503715047150571506715077150871509715107151171512715137151471515715167151771518715197152071521715227152371524715257152671527715287152971530715317153271533715347153571536715377153871539715407154171542715437154471545715467154771548715497155071551715527155371554715557155671557715587155971560715617156271563715647156571566715677156871569715707157171572715737157471575715767157771578715797158071581715827158371584715857158671587715887158971590715917159271593715947159571596715977159871599716007160171602716037160471605716067160771608716097161071611716127161371614716157161671617716187161971620716217162271623716247162571626716277162871629716307163171632716337163471635716367163771638716397164071641716427164371644716457164671647716487164971650716517165271653716547165571656716577165871659716607166171662716637166471665716667166771668716697167071671716727167371674716757167671677716787167971680716817168271683716847168571686716877168871689716907169171692716937169471695716967169771698716997170071701717027170371704717057170671707717087170971710717117171271713717147171571716717177171871719717207172171722717237172471725717267172771728717297173071731717327173371734717357173671737717387173971740717417174271743717447174571746717477174871749717507175171752717537175471755717567175771758717597176071761717627176371764717657176671767717687176971770717717177271773717747177571776717777177871779717807178171782717837178471785717867178771788717897179071791717927179371794717957179671797717987179971800718017180271803718047180571806718077180871809718107181171812718137181471815718167181771818718197182071821718227182371824718257182671827718287182971830718317183271833718347183571836718377183871839718407184171842718437184471845718467184771848718497185071851718527185371854718557185671857718587185971860718617186271863718647186571866718677186871869718707187171872718737187471875718767187771878718797188071881718827188371884718857188671887718887188971890718917189271893718947189571896718977189871899719007190171902719037190471905719067190771908719097191071911719127191371914719157191671917719187191971920719217192271923719247192571926719277192871929719307193171932719337193471935719367193771938719397194071941719427194371944719457194671947719487194971950719517195271953719547195571956719577195871959719607196171962719637196471965719667196771968719697197071971719727197371974719757197671977719787197971980719817198271983719847198571986719877198871989719907199171992719937199471995719967199771998719997200072001720027200372004720057200672007720087200972010720117201272013720147201572016720177201872019720207202172022720237202472025720267202772028720297203072031720327203372034720357203672037720387203972040720417204272043720447204572046720477204872049720507205172052720537205472055720567205772058720597206072061720627206372064720657206672067720687206972070720717207272073720747207572076720777207872079720807208172082720837208472085720867208772088720897209072091720927209372094720957209672097720987209972100721017210272103721047210572106721077210872109721107211172112721137211472115721167211772118721197212072121721227212372124721257212672127721287212972130721317213272133721347213572136721377213872139721407214172142721437214472145721467214772148721497215072151721527215372154721557215672157721587215972160721617216272163721647216572166721677216872169721707217172172721737217472175721767217772178721797218072181721827218372184721857218672187721887218972190721917219272193721947219572196721977219872199722007220172202722037220472205722067220772208722097221072211722127221372214722157221672217722187221972220722217222272223722247222572226722277222872229722307223172232722337223472235722367223772238722397224072241722427224372244722457224672247722487224972250722517225272253722547225572256722577225872259722607226172262722637226472265722667226772268722697227072271722727227372274722757227672277722787227972280722817228272283722847228572286722877228872289722907229172292722937229472295722967229772298722997230072301723027230372304723057230672307723087230972310723117231272313723147231572316723177231872319723207232172322723237232472325723267232772328723297233072331723327233372334723357233672337723387233972340723417234272343723447234572346723477234872349723507235172352723537235472355723567235772358723597236072361723627236372364723657236672367723687236972370723717237272373723747237572376723777237872379723807238172382723837238472385723867238772388723897239072391723927239372394723957239672397723987239972400724017240272403724047240572406724077240872409724107241172412724137241472415724167241772418724197242072421724227242372424724257242672427724287242972430724317243272433724347243572436724377243872439724407244172442724437244472445724467244772448724497245072451724527245372454724557245672457724587245972460724617246272463724647246572466724677246872469724707247172472724737247472475724767247772478724797248072481724827248372484724857248672487724887248972490724917249272493724947249572496724977249872499725007250172502725037250472505725067250772508725097251072511725127251372514725157251672517725187251972520725217252272523725247252572526725277252872529725307253172532725337253472535725367253772538725397254072541725427254372544725457254672547725487254972550725517255272553725547255572556725577255872559725607256172562725637256472565725667256772568725697257072571725727257372574725757257672577725787257972580725817258272583725847258572586725877258872589725907259172592725937259472595725967259772598725997260072601726027260372604726057260672607726087260972610726117261272613726147261572616726177261872619726207262172622726237262472625726267262772628726297263072631726327263372634726357263672637726387263972640726417264272643726447264572646726477264872649726507265172652726537265472655726567265772658726597266072661726627266372664726657266672667726687266972670726717267272673726747267572676726777267872679726807268172682726837268472685726867268772688726897269072691726927269372694726957269672697726987269972700727017270272703727047270572706727077270872709727107271172712727137271472715727167271772718727197272072721727227272372724727257272672727727287272972730727317273272733727347273572736727377273872739727407274172742727437274472745727467274772748727497275072751727527275372754727557275672757727587275972760727617276272763727647276572766727677276872769727707277172772727737277472775727767277772778727797278072781727827278372784727857278672787727887278972790727917279272793727947279572796727977279872799728007280172802728037280472805728067280772808728097281072811728127281372814728157281672817728187281972820728217282272823728247282572826728277282872829728307283172832728337283472835728367283772838728397284072841728427284372844728457284672847728487284972850728517285272853728547285572856728577285872859728607286172862728637286472865728667286772868728697287072871728727287372874728757287672877728787287972880728817288272883728847288572886728877288872889728907289172892728937289472895728967289772898728997290072901729027290372904729057290672907729087290972910729117291272913729147291572916729177291872919729207292172922729237292472925729267292772928729297293072931729327293372934729357293672937729387293972940729417294272943729447294572946729477294872949729507295172952729537295472955729567295772958729597296072961729627296372964729657296672967729687296972970729717297272973729747297572976729777297872979729807298172982729837298472985729867298772988729897299072991729927299372994729957299672997729987299973000730017300273003730047300573006730077300873009730107301173012730137301473015730167301773018730197302073021730227302373024730257302673027730287302973030730317303273033730347303573036730377303873039730407304173042730437304473045730467304773048730497305073051730527305373054730557305673057730587305973060730617306273063730647306573066730677306873069730707307173072730737307473075730767307773078730797308073081730827308373084730857308673087730887308973090730917309273093730947309573096730977309873099731007310173102731037310473105731067310773108731097311073111731127311373114731157311673117731187311973120731217312273123731247312573126731277312873129731307313173132731337313473135731367313773138731397314073141731427314373144731457314673147731487314973150731517315273153731547315573156731577315873159731607316173162731637316473165731667316773168731697317073171731727317373174731757317673177731787317973180731817318273183731847318573186731877318873189731907319173192731937319473195731967319773198731997320073201732027320373204732057320673207732087320973210732117321273213732147321573216732177321873219732207322173222732237322473225732267322773228732297323073231732327323373234732357323673237732387323973240732417324273243732447324573246732477324873249732507325173252732537325473255732567325773258732597326073261732627326373264732657326673267732687326973270732717327273273732747327573276732777327873279732807328173282732837328473285732867328773288732897329073291732927329373294732957329673297732987329973300733017330273303733047330573306733077330873309733107331173312733137331473315733167331773318733197332073321733227332373324733257332673327733287332973330733317333273333733347333573336733377333873339733407334173342733437334473345733467334773348733497335073351733527335373354733557335673357733587335973360733617336273363733647336573366733677336873369733707337173372733737337473375733767337773378733797338073381733827338373384733857338673387733887338973390733917339273393733947339573396733977339873399734007340173402734037340473405734067340773408734097341073411734127341373414734157341673417734187341973420734217342273423734247342573426734277342873429734307343173432734337343473435734367343773438734397344073441734427344373444734457344673447734487344973450734517345273453734547345573456734577345873459734607346173462734637346473465734667346773468734697347073471734727347373474734757347673477734787347973480734817348273483734847348573486734877348873489734907349173492734937349473495734967349773498734997350073501735027350373504735057350673507735087350973510735117351273513735147351573516735177351873519735207352173522735237352473525735267352773528735297353073531735327353373534735357353673537735387353973540735417354273543735447354573546735477354873549735507355173552735537355473555735567355773558735597356073561735627356373564735657356673567735687356973570735717357273573735747357573576735777357873579735807358173582735837358473585735867358773588735897359073591735927359373594735957359673597735987359973600736017360273603736047360573606736077360873609736107361173612736137361473615736167361773618736197362073621736227362373624736257362673627736287362973630736317363273633736347363573636736377363873639736407364173642736437364473645736467364773648736497365073651736527365373654736557365673657736587365973660736617366273663736647366573666736677366873669736707367173672736737367473675736767367773678736797368073681736827368373684736857368673687736887368973690736917369273693736947369573696736977369873699737007370173702737037370473705737067370773708737097371073711737127371373714737157371673717737187371973720737217372273723737247372573726737277372873729737307373173732737337373473735737367373773738737397374073741737427374373744737457374673747737487374973750737517375273753737547375573756737577375873759737607376173762737637376473765737667376773768737697377073771737727377373774737757377673777737787377973780737817378273783737847378573786737877378873789737907379173792737937379473795737967379773798737997380073801738027380373804738057380673807738087380973810738117381273813738147381573816738177381873819738207382173822738237382473825738267382773828738297383073831738327383373834738357383673837738387383973840738417384273843738447384573846738477384873849738507385173852738537385473855738567385773858738597386073861738627386373864738657386673867738687386973870738717387273873738747387573876738777387873879738807388173882738837388473885738867388773888738897389073891738927389373894738957389673897738987389973900739017390273903739047390573906739077390873909739107391173912739137391473915739167391773918739197392073921739227392373924739257392673927739287392973930739317393273933739347393573936739377393873939739407394173942739437394473945739467394773948739497395073951739527395373954739557395673957739587395973960739617396273963739647396573966739677396873969739707397173972739737397473975739767397773978739797398073981739827398373984739857398673987739887398973990739917399273993739947399573996739977399873999740007400174002740037400474005740067400774008740097401074011740127401374014740157401674017740187401974020740217402274023740247402574026740277402874029740307403174032740337403474035740367403774038740397404074041740427404374044740457404674047740487404974050740517405274053740547405574056740577405874059740607406174062740637406474065740667406774068740697407074071740727407374074740757407674077740787407974080740817408274083740847408574086740877408874089740907409174092740937409474095740967409774098740997410074101741027410374104741057410674107741087410974110741117411274113741147411574116741177411874119741207412174122741237412474125741267412774128741297413074131741327413374134741357413674137741387413974140741417414274143741447414574146741477414874149741507415174152741537415474155741567415774158741597416074161741627416374164741657416674167741687416974170741717417274173741747417574176741777417874179741807418174182741837418474185741867418774188741897419074191741927419374194741957419674197741987419974200742017420274203742047420574206742077420874209742107421174212742137421474215742167421774218742197422074221742227422374224742257422674227742287422974230742317423274233742347423574236742377423874239742407424174242742437424474245742467424774248742497425074251742527425374254742557425674257742587425974260742617426274263742647426574266742677426874269742707427174272742737427474275742767427774278742797428074281742827428374284742857428674287742887428974290742917429274293742947429574296742977429874299743007430174302743037430474305743067430774308743097431074311743127431374314743157431674317743187431974320743217432274323743247432574326743277432874329743307433174332743337433474335743367433774338743397434074341743427434374344743457434674347743487434974350743517435274353743547435574356743577435874359743607436174362743637436474365743667436774368743697437074371743727437374374743757437674377743787437974380743817438274383743847438574386743877438874389743907439174392743937439474395743967439774398743997440074401744027440374404744057440674407744087440974410744117441274413744147441574416744177441874419744207442174422744237442474425744267442774428744297443074431744327443374434744357443674437744387443974440744417444274443744447444574446744477444874449744507445174452744537445474455744567445774458744597446074461744627446374464744657446674467744687446974470744717447274473744747447574476744777447874479744807448174482744837448474485744867448774488744897449074491744927449374494744957449674497744987449974500745017450274503745047450574506745077450874509745107451174512745137451474515745167451774518745197452074521745227452374524745257452674527745287452974530745317453274533745347453574536745377453874539745407454174542745437454474545745467454774548745497455074551745527455374554745557455674557745587455974560745617456274563745647456574566745677456874569745707457174572745737457474575745767457774578745797458074581745827458374584745857458674587745887458974590745917459274593745947459574596745977459874599746007460174602746037460474605746067460774608746097461074611746127461374614746157461674617746187461974620746217462274623746247462574626746277462874629746307463174632746337463474635746367463774638746397464074641746427464374644746457464674647746487464974650746517465274653746547465574656746577465874659746607466174662746637466474665746667466774668746697467074671746727467374674746757467674677746787467974680746817468274683746847468574686746877468874689746907469174692746937469474695746967469774698746997470074701747027470374704747057470674707747087470974710747117471274713747147471574716747177471874719747207472174722747237472474725747267472774728747297473074731747327473374734747357473674737747387473974740747417474274743747447474574746747477474874749747507475174752747537475474755747567475774758747597476074761747627476374764747657476674767747687476974770747717477274773747747477574776747777477874779747807478174782747837478474785747867478774788747897479074791747927479374794747957479674797747987479974800748017480274803748047480574806748077480874809748107481174812748137481474815748167481774818748197482074821748227482374824748257482674827748287482974830748317483274833748347483574836748377483874839748407484174842748437484474845748467484774848748497485074851748527485374854748557485674857748587485974860748617486274863748647486574866748677486874869748707487174872748737487474875748767487774878748797488074881748827488374884748857488674887748887488974890748917489274893748947489574896748977489874899749007490174902749037490474905749067490774908749097491074911749127491374914749157491674917749187491974920749217492274923749247492574926749277492874929749307493174932749337493474935749367493774938749397494074941749427494374944749457494674947749487494974950749517495274953749547495574956749577495874959749607496174962749637496474965749667496774968749697497074971749727497374974749757497674977749787497974980749817498274983749847498574986749877498874989749907499174992749937499474995749967499774998749997500075001750027500375004750057500675007750087500975010750117501275013750147501575016750177501875019750207502175022750237502475025750267502775028750297503075031750327503375034750357503675037750387503975040750417504275043750447504575046750477504875049750507505175052750537505475055750567505775058750597506075061750627506375064750657506675067750687506975070750717507275073750747507575076750777507875079750807508175082750837508475085750867508775088750897509075091750927509375094750957509675097750987509975100751017510275103751047510575106751077510875109751107511175112751137511475115751167511775118751197512075121751227512375124751257512675127751287512975130751317513275133751347513575136751377513875139751407514175142751437514475145751467514775148751497515075151751527515375154751557515675157751587515975160751617516275163751647516575166751677516875169751707517175172751737517475175751767517775178751797518075181751827518375184751857518675187751887518975190751917519275193751947519575196751977519875199752007520175202752037520475205752067520775208752097521075211752127521375214752157521675217752187521975220752217522275223752247522575226752277522875229752307523175232752337523475235752367523775238752397524075241752427524375244752457524675247752487524975250752517525275253752547525575256752577525875259752607526175262752637526475265752667526775268752697527075271752727527375274752757527675277752787527975280752817528275283752847528575286752877528875289752907529175292752937529475295752967529775298752997530075301753027530375304753057530675307753087530975310753117531275313753147531575316753177531875319753207532175322753237532475325753267532775328753297533075331753327533375334753357533675337753387533975340753417534275343753447534575346753477534875349753507535175352753537535475355753567535775358753597536075361753627536375364753657536675367753687536975370753717537275373753747537575376753777537875379753807538175382753837538475385753867538775388753897539075391753927539375394753957539675397753987539975400754017540275403754047540575406754077540875409754107541175412754137541475415754167541775418754197542075421754227542375424754257542675427754287542975430754317543275433754347543575436754377543875439754407544175442754437544475445754467544775448754497545075451754527545375454754557545675457754587545975460754617546275463754647546575466754677546875469754707547175472754737547475475754767547775478754797548075481754827548375484754857548675487754887548975490754917549275493754947549575496754977549875499755007550175502755037550475505755067550775508755097551075511755127551375514755157551675517755187551975520755217552275523755247552575526755277552875529755307553175532755337553475535755367553775538755397554075541755427554375544755457554675547755487554975550755517555275553755547555575556755577555875559755607556175562755637556475565755667556775568755697557075571755727557375574755757557675577755787557975580755817558275583755847558575586755877558875589755907559175592755937559475595755967559775598755997560075601756027560375604756057560675607756087560975610756117561275613756147561575616756177561875619756207562175622756237562475625756267562775628756297563075631756327563375634756357563675637756387563975640756417564275643756447564575646756477564875649756507565175652756537565475655756567565775658756597566075661756627566375664756657566675667756687566975670756717567275673756747567575676756777567875679756807568175682756837568475685756867568775688756897569075691756927569375694756957569675697756987569975700757017570275703757047570575706757077570875709757107571175712757137571475715757167571775718757197572075721757227572375724757257572675727757287572975730757317573275733757347573575736757377573875739757407574175742757437574475745757467574775748757497575075751757527575375754757557575675757757587575975760757617576275763757647576575766757677576875769757707577175772757737577475775757767577775778757797578075781757827578375784757857578675787757887578975790757917579275793757947579575796757977579875799758007580175802758037580475805758067580775808758097581075811758127581375814758157581675817758187581975820758217582275823758247582575826758277582875829758307583175832758337583475835758367583775838758397584075841758427584375844758457584675847758487584975850758517585275853758547585575856758577585875859758607586175862758637586475865758667586775868758697587075871758727587375874758757587675877758787587975880758817588275883758847588575886758877588875889758907589175892758937589475895758967589775898758997590075901759027590375904759057590675907759087590975910759117591275913759147591575916759177591875919759207592175922759237592475925759267592775928759297593075931759327593375934759357593675937759387593975940759417594275943759447594575946759477594875949759507595175952759537595475955759567595775958759597596075961759627596375964759657596675967759687596975970759717597275973759747597575976759777597875979759807598175982759837598475985759867598775988759897599075991759927599375994759957599675997759987599976000760017600276003760047600576006760077600876009760107601176012760137601476015760167601776018760197602076021760227602376024760257602676027760287602976030760317603276033760347603576036760377603876039760407604176042760437604476045760467604776048760497605076051760527605376054760557605676057760587605976060760617606276063760647606576066760677606876069760707607176072760737607476075760767607776078760797608076081760827608376084760857608676087760887608976090760917609276093760947609576096760977609876099761007610176102761037610476105761067610776108761097611076111761127611376114761157611676117761187611976120761217612276123761247612576126761277612876129761307613176132761337613476135761367613776138761397614076141761427614376144761457614676147761487614976150761517615276153761547615576156761577615876159761607616176162761637616476165761667616776168761697617076171761727617376174761757617676177761787617976180761817618276183761847618576186761877618876189761907619176192761937619476195761967619776198761997620076201762027620376204762057620676207762087620976210762117621276213762147621576216762177621876219762207622176222762237622476225762267622776228762297623076231762327623376234762357623676237762387623976240762417624276243762447624576246762477624876249762507625176252762537625476255762567625776258762597626076261762627626376264762657626676267762687626976270762717627276273762747627576276762777627876279762807628176282762837628476285762867628776288
  1. (function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.AFRAME = f()}})(function(){var define,module,exports;return (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(_dereq_,module,exports){
  2. var str = Object.prototype.toString
  3. module.exports = anArray
  4. function anArray(arr) {
  5. return (
  6. arr.BYTES_PER_ELEMENT
  7. && str.call(arr.buffer) === '[object ArrayBuffer]'
  8. || Array.isArray(arr)
  9. )
  10. }
  11. },{}],2:[function(_dereq_,module,exports){
  12. module.exports = function numtype(num, def) {
  13. return typeof num === 'number'
  14. ? num
  15. : (typeof def === 'number' ? def : 0)
  16. }
  17. },{}],3:[function(_dereq_,module,exports){
  18. 'use strict'
  19. exports.byteLength = byteLength
  20. exports.toByteArray = toByteArray
  21. exports.fromByteArray = fromByteArray
  22. var lookup = []
  23. var revLookup = []
  24. var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array
  25. var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
  26. for (var i = 0, len = code.length; i < len; ++i) {
  27. lookup[i] = code[i]
  28. revLookup[code.charCodeAt(i)] = i
  29. }
  30. // Support decoding URL-safe base64 strings, as Node.js does.
  31. // See: https://en.wikipedia.org/wiki/Base64#URL_applications
  32. revLookup['-'.charCodeAt(0)] = 62
  33. revLookup['_'.charCodeAt(0)] = 63
  34. function getLens (b64) {
  35. var len = b64.length
  36. if (len % 4 > 0) {
  37. throw new Error('Invalid string. Length must be a multiple of 4')
  38. }
  39. // Trim off extra bytes after placeholder bytes are found
  40. // See: https://github.com/beatgammit/base64-js/issues/42
  41. var validLen = b64.indexOf('=')
  42. if (validLen === -1) validLen = len
  43. var placeHoldersLen = validLen === len
  44. ? 0
  45. : 4 - (validLen % 4)
  46. return [validLen, placeHoldersLen]
  47. }
  48. // base64 is 4/3 + up to two characters of the original data
  49. function byteLength (b64) {
  50. var lens = getLens(b64)
  51. var validLen = lens[0]
  52. var placeHoldersLen = lens[1]
  53. return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
  54. }
  55. function _byteLength (b64, validLen, placeHoldersLen) {
  56. return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
  57. }
  58. function toByteArray (b64) {
  59. var tmp
  60. var lens = getLens(b64)
  61. var validLen = lens[0]
  62. var placeHoldersLen = lens[1]
  63. var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen))
  64. var curByte = 0
  65. // if there are placeholders, only get up to the last complete 4 chars
  66. var len = placeHoldersLen > 0
  67. ? validLen - 4
  68. : validLen
  69. for (var i = 0; i < len; i += 4) {
  70. tmp =
  71. (revLookup[b64.charCodeAt(i)] << 18) |
  72. (revLookup[b64.charCodeAt(i + 1)] << 12) |
  73. (revLookup[b64.charCodeAt(i + 2)] << 6) |
  74. revLookup[b64.charCodeAt(i + 3)]
  75. arr[curByte++] = (tmp >> 16) & 0xFF
  76. arr[curByte++] = (tmp >> 8) & 0xFF
  77. arr[curByte++] = tmp & 0xFF
  78. }
  79. if (placeHoldersLen === 2) {
  80. tmp =
  81. (revLookup[b64.charCodeAt(i)] << 2) |
  82. (revLookup[b64.charCodeAt(i + 1)] >> 4)
  83. arr[curByte++] = tmp & 0xFF
  84. }
  85. if (placeHoldersLen === 1) {
  86. tmp =
  87. (revLookup[b64.charCodeAt(i)] << 10) |
  88. (revLookup[b64.charCodeAt(i + 1)] << 4) |
  89. (revLookup[b64.charCodeAt(i + 2)] >> 2)
  90. arr[curByte++] = (tmp >> 8) & 0xFF
  91. arr[curByte++] = tmp & 0xFF
  92. }
  93. return arr
  94. }
  95. function tripletToBase64 (num) {
  96. return lookup[num >> 18 & 0x3F] +
  97. lookup[num >> 12 & 0x3F] +
  98. lookup[num >> 6 & 0x3F] +
  99. lookup[num & 0x3F]
  100. }
  101. function encodeChunk (uint8, start, end) {
  102. var tmp
  103. var output = []
  104. for (var i = start; i < end; i += 3) {
  105. tmp =
  106. ((uint8[i] << 16) & 0xFF0000) +
  107. ((uint8[i + 1] << 8) & 0xFF00) +
  108. (uint8[i + 2] & 0xFF)
  109. output.push(tripletToBase64(tmp))
  110. }
  111. return output.join('')
  112. }
  113. function fromByteArray (uint8) {
  114. var tmp
  115. var len = uint8.length
  116. var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes
  117. var parts = []
  118. var maxChunkLength = 16383 // must be multiple of 3
  119. // go through the array every three bytes, we'll deal with trailing stuff later
  120. for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
  121. parts.push(encodeChunk(
  122. uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)
  123. ))
  124. }
  125. // pad the end with zeros, but make sure to not forget the extra bytes
  126. if (extraBytes === 1) {
  127. tmp = uint8[len - 1]
  128. parts.push(
  129. lookup[tmp >> 2] +
  130. lookup[(tmp << 4) & 0x3F] +
  131. '=='
  132. )
  133. } else if (extraBytes === 2) {
  134. tmp = (uint8[len - 2] << 8) + uint8[len - 1]
  135. parts.push(
  136. lookup[tmp >> 10] +
  137. lookup[(tmp >> 4) & 0x3F] +
  138. lookup[(tmp << 2) & 0x3F] +
  139. '='
  140. )
  141. }
  142. return parts.join('')
  143. }
  144. },{}],4:[function(_dereq_,module,exports){
  145. 'use strict';
  146. // For more information about browser field, check out the browser field at https://github.com/substack/browserify-handbook#browser-field.
  147. module.exports = {
  148. // Create a <link> tag with optional data attributes
  149. createLink: function(href, attributes) {
  150. var head = document.head || document.getElementsByTagName('head')[0];
  151. var link = document.createElement('link');
  152. link.href = href;
  153. link.rel = 'stylesheet';
  154. for (var key in attributes) {
  155. if ( ! attributes.hasOwnProperty(key)) {
  156. continue;
  157. }
  158. var value = attributes[key];
  159. link.setAttribute('data-' + key, value);
  160. }
  161. head.appendChild(link);
  162. },
  163. // Create a <style> tag with optional data attributes
  164. createStyle: function(cssText, attributes) {
  165. var head = document.head || document.getElementsByTagName('head')[0],
  166. style = document.createElement('style');
  167. style.type = 'text/css';
  168. for (var key in attributes) {
  169. if ( ! attributes.hasOwnProperty(key)) {
  170. continue;
  171. }
  172. var value = attributes[key];
  173. style.setAttribute('data-' + key, value);
  174. }
  175. if (style.sheet) { // for jsdom and IE9+
  176. style.innerHTML = cssText;
  177. style.sheet.cssText = cssText;
  178. head.appendChild(style);
  179. } else if (style.styleSheet) { // for IE8 and below
  180. head.appendChild(style);
  181. style.styleSheet.cssText = cssText;
  182. } else { // for Chrome, Firefox, and Safari
  183. style.appendChild(document.createTextNode(cssText));
  184. head.appendChild(style);
  185. }
  186. }
  187. };
  188. },{}],5:[function(_dereq_,module,exports){
  189. var Buffer = _dereq_('buffer').Buffer; // for use with browserify
  190. module.exports = function (a, b) {
  191. if (!Buffer.isBuffer(a)) return undefined;
  192. if (!Buffer.isBuffer(b)) return undefined;
  193. if (typeof a.equals === 'function') return a.equals(b);
  194. if (a.length !== b.length) return false;
  195. for (var i = 0; i < a.length; i++) {
  196. if (a[i] !== b[i]) return false;
  197. }
  198. return true;
  199. };
  200. },{"buffer":6}],6:[function(_dereq_,module,exports){
  201. (function (global,Buffer){
  202. /*!
  203. * The buffer module from node.js, for the browser.
  204. *
  205. * @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
  206. * @license MIT
  207. */
  208. /* eslint-disable no-proto */
  209. 'use strict'
  210. var base64 = _dereq_('base64-js')
  211. var ieee754 = _dereq_('ieee754')
  212. var isArray = _dereq_('isarray')
  213. exports.Buffer = Buffer
  214. exports.SlowBuffer = SlowBuffer
  215. exports.INSPECT_MAX_BYTES = 50
  216. /**
  217. * If `Buffer.TYPED_ARRAY_SUPPORT`:
  218. * === true Use Uint8Array implementation (fastest)
  219. * === false Use Object implementation (most compatible, even IE6)
  220. *
  221. * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
  222. * Opera 11.6+, iOS 4.2+.
  223. *
  224. * Due to various browser bugs, sometimes the Object implementation will be used even
  225. * when the browser supports typed arrays.
  226. *
  227. * Note:
  228. *
  229. * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances,
  230. * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438.
  231. *
  232. * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function.
  233. *
  234. * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of
  235. * incorrect length in some situations.
  236. * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they
  237. * get the Object implementation, which is slower but behaves correctly.
  238. */
  239. Buffer.TYPED_ARRAY_SUPPORT = global.TYPED_ARRAY_SUPPORT !== undefined
  240. ? global.TYPED_ARRAY_SUPPORT
  241. : typedArraySupport()
  242. /*
  243. * Export kMaxLength after typed array support is determined.
  244. */
  245. exports.kMaxLength = kMaxLength()
  246. function typedArraySupport () {
  247. try {
  248. var arr = new Uint8Array(1)
  249. arr.__proto__ = {__proto__: Uint8Array.prototype, foo: function () { return 42 }}
  250. return arr.foo() === 42 && // typed array instances can be augmented
  251. typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray`
  252. arr.subarray(1, 1).byteLength === 0 // ie10 has broken `subarray`
  253. } catch (e) {
  254. return false
  255. }
  256. }
  257. function kMaxLength () {
  258. return Buffer.TYPED_ARRAY_SUPPORT
  259. ? 0x7fffffff
  260. : 0x3fffffff
  261. }
  262. function createBuffer (that, length) {
  263. if (kMaxLength() < length) {
  264. throw new RangeError('Invalid typed array length')
  265. }
  266. if (Buffer.TYPED_ARRAY_SUPPORT) {
  267. // Return an augmented `Uint8Array` instance, for best performance
  268. that = new Uint8Array(length)
  269. that.__proto__ = Buffer.prototype
  270. } else {
  271. // Fallback: Return an object instance of the Buffer class
  272. if (that === null) {
  273. that = new Buffer(length)
  274. }
  275. that.length = length
  276. }
  277. return that
  278. }
  279. /**
  280. * The Buffer constructor returns instances of `Uint8Array` that have their
  281. * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
  282. * `Uint8Array`, so the returned instances will have all the node `Buffer` methods
  283. * and the `Uint8Array` methods. Square bracket notation works as expected -- it
  284. * returns a single octet.
  285. *
  286. * The `Uint8Array` prototype remains unmodified.
  287. */
  288. function Buffer (arg, encodingOrOffset, length) {
  289. if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) {
  290. return new Buffer(arg, encodingOrOffset, length)
  291. }
  292. // Common case.
  293. if (typeof arg === 'number') {
  294. if (typeof encodingOrOffset === 'string') {
  295. throw new Error(
  296. 'If encoding is specified then the first argument must be a string'
  297. )
  298. }
  299. return allocUnsafe(this, arg)
  300. }
  301. return from(this, arg, encodingOrOffset, length)
  302. }
  303. Buffer.poolSize = 8192 // not used by this implementation
  304. // TODO: Legacy, not needed anymore. Remove in next major version.
  305. Buffer._augment = function (arr) {
  306. arr.__proto__ = Buffer.prototype
  307. return arr
  308. }
  309. function from (that, value, encodingOrOffset, length) {
  310. if (typeof value === 'number') {
  311. throw new TypeError('"value" argument must not be a number')
  312. }
  313. if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) {
  314. return fromArrayBuffer(that, value, encodingOrOffset, length)
  315. }
  316. if (typeof value === 'string') {
  317. return fromString(that, value, encodingOrOffset)
  318. }
  319. return fromObject(that, value)
  320. }
  321. /**
  322. * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
  323. * if value is a number.
  324. * Buffer.from(str[, encoding])
  325. * Buffer.from(array)
  326. * Buffer.from(buffer)
  327. * Buffer.from(arrayBuffer[, byteOffset[, length]])
  328. **/
  329. Buffer.from = function (value, encodingOrOffset, length) {
  330. return from(null, value, encodingOrOffset, length)
  331. }
  332. if (Buffer.TYPED_ARRAY_SUPPORT) {
  333. Buffer.prototype.__proto__ = Uint8Array.prototype
  334. Buffer.__proto__ = Uint8Array
  335. if (typeof Symbol !== 'undefined' && Symbol.species &&
  336. Buffer[Symbol.species] === Buffer) {
  337. // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97
  338. Object.defineProperty(Buffer, Symbol.species, {
  339. value: null,
  340. configurable: true
  341. })
  342. }
  343. }
  344. function assertSize (size) {
  345. if (typeof size !== 'number') {
  346. throw new TypeError('"size" argument must be a number')
  347. } else if (size < 0) {
  348. throw new RangeError('"size" argument must not be negative')
  349. }
  350. }
  351. function alloc (that, size, fill, encoding) {
  352. assertSize(size)
  353. if (size <= 0) {
  354. return createBuffer(that, size)
  355. }
  356. if (fill !== undefined) {
  357. // Only pay attention to encoding if it's a string. This
  358. // prevents accidentally sending in a number that would
  359. // be interpretted as a start offset.
  360. return typeof encoding === 'string'
  361. ? createBuffer(that, size).fill(fill, encoding)
  362. : createBuffer(that, size).fill(fill)
  363. }
  364. return createBuffer(that, size)
  365. }
  366. /**
  367. * Creates a new filled Buffer instance.
  368. * alloc(size[, fill[, encoding]])
  369. **/
  370. Buffer.alloc = function (size, fill, encoding) {
  371. return alloc(null, size, fill, encoding)
  372. }
  373. function allocUnsafe (that, size) {
  374. assertSize(size)
  375. that = createBuffer(that, size < 0 ? 0 : checked(size) | 0)
  376. if (!Buffer.TYPED_ARRAY_SUPPORT) {
  377. for (var i = 0; i < size; ++i) {
  378. that[i] = 0
  379. }
  380. }
  381. return that
  382. }
  383. /**
  384. * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
  385. * */
  386. Buffer.allocUnsafe = function (size) {
  387. return allocUnsafe(null, size)
  388. }
  389. /**
  390. * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
  391. */
  392. Buffer.allocUnsafeSlow = function (size) {
  393. return allocUnsafe(null, size)
  394. }
  395. function fromString (that, string, encoding) {
  396. if (typeof encoding !== 'string' || encoding === '') {
  397. encoding = 'utf8'
  398. }
  399. if (!Buffer.isEncoding(encoding)) {
  400. throw new TypeError('"encoding" must be a valid string encoding')
  401. }
  402. var length = byteLength(string, encoding) | 0
  403. that = createBuffer(that, length)
  404. var actual = that.write(string, encoding)
  405. if (actual !== length) {
  406. // Writing a hex string, for example, that contains invalid characters will
  407. // cause everything after the first invalid character to be ignored. (e.g.
  408. // 'abxxcd' will be treated as 'ab')
  409. that = that.slice(0, actual)
  410. }
  411. return that
  412. }
  413. function fromArrayLike (that, array) {
  414. var length = array.length < 0 ? 0 : checked(array.length) | 0
  415. that = createBuffer(that, length)
  416. for (var i = 0; i < length; i += 1) {
  417. that[i] = array[i] & 255
  418. }
  419. return that
  420. }
  421. function fromArrayBuffer (that, array, byteOffset, length) {
  422. array.byteLength // this throws if `array` is not a valid ArrayBuffer
  423. if (byteOffset < 0 || array.byteLength < byteOffset) {
  424. throw new RangeError('\'offset\' is out of bounds')
  425. }
  426. if (array.byteLength < byteOffset + (length || 0)) {
  427. throw new RangeError('\'length\' is out of bounds')
  428. }
  429. if (byteOffset === undefined && length === undefined) {
  430. array = new Uint8Array(array)
  431. } else if (length === undefined) {
  432. array = new Uint8Array(array, byteOffset)
  433. } else {
  434. array = new Uint8Array(array, byteOffset, length)
  435. }
  436. if (Buffer.TYPED_ARRAY_SUPPORT) {
  437. // Return an augmented `Uint8Array` instance, for best performance
  438. that = array
  439. that.__proto__ = Buffer.prototype
  440. } else {
  441. // Fallback: Return an object instance of the Buffer class
  442. that = fromArrayLike(that, array)
  443. }
  444. return that
  445. }
  446. function fromObject (that, obj) {
  447. if (Buffer.isBuffer(obj)) {
  448. var len = checked(obj.length) | 0
  449. that = createBuffer(that, len)
  450. if (that.length === 0) {
  451. return that
  452. }
  453. obj.copy(that, 0, 0, len)
  454. return that
  455. }
  456. if (obj) {
  457. if ((typeof ArrayBuffer !== 'undefined' &&
  458. obj.buffer instanceof ArrayBuffer) || 'length' in obj) {
  459. if (typeof obj.length !== 'number' || isnan(obj.length)) {
  460. return createBuffer(that, 0)
  461. }
  462. return fromArrayLike(that, obj)
  463. }
  464. if (obj.type === 'Buffer' && isArray(obj.data)) {
  465. return fromArrayLike(that, obj.data)
  466. }
  467. }
  468. throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.')
  469. }
  470. function checked (length) {
  471. // Note: cannot use `length < kMaxLength()` here because that fails when
  472. // length is NaN (which is otherwise coerced to zero.)
  473. if (length >= kMaxLength()) {
  474. throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
  475. 'size: 0x' + kMaxLength().toString(16) + ' bytes')
  476. }
  477. return length | 0
  478. }
  479. function SlowBuffer (length) {
  480. if (+length != length) { // eslint-disable-line eqeqeq
  481. length = 0
  482. }
  483. return Buffer.alloc(+length)
  484. }
  485. Buffer.isBuffer = function isBuffer (b) {
  486. return !!(b != null && b._isBuffer)
  487. }
  488. Buffer.compare = function compare (a, b) {
  489. if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
  490. throw new TypeError('Arguments must be Buffers')
  491. }
  492. if (a === b) return 0
  493. var x = a.length
  494. var y = b.length
  495. for (var i = 0, len = Math.min(x, y); i < len; ++i) {
  496. if (a[i] !== b[i]) {
  497. x = a[i]
  498. y = b[i]
  499. break
  500. }
  501. }
  502. if (x < y) return -1
  503. if (y < x) return 1
  504. return 0
  505. }
  506. Buffer.isEncoding = function isEncoding (encoding) {
  507. switch (String(encoding).toLowerCase()) {
  508. case 'hex':
  509. case 'utf8':
  510. case 'utf-8':
  511. case 'ascii':
  512. case 'latin1':
  513. case 'binary':
  514. case 'base64':
  515. case 'ucs2':
  516. case 'ucs-2':
  517. case 'utf16le':
  518. case 'utf-16le':
  519. return true
  520. default:
  521. return false
  522. }
  523. }
  524. Buffer.concat = function concat (list, length) {
  525. if (!isArray(list)) {
  526. throw new TypeError('"list" argument must be an Array of Buffers')
  527. }
  528. if (list.length === 0) {
  529. return Buffer.alloc(0)
  530. }
  531. var i
  532. if (length === undefined) {
  533. length = 0
  534. for (i = 0; i < list.length; ++i) {
  535. length += list[i].length
  536. }
  537. }
  538. var buffer = Buffer.allocUnsafe(length)
  539. var pos = 0
  540. for (i = 0; i < list.length; ++i) {
  541. var buf = list[i]
  542. if (!Buffer.isBuffer(buf)) {
  543. throw new TypeError('"list" argument must be an Array of Buffers')
  544. }
  545. buf.copy(buffer, pos)
  546. pos += buf.length
  547. }
  548. return buffer
  549. }
  550. function byteLength (string, encoding) {
  551. if (Buffer.isBuffer(string)) {
  552. return string.length
  553. }
  554. if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' &&
  555. (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) {
  556. return string.byteLength
  557. }
  558. if (typeof string !== 'string') {
  559. string = '' + string
  560. }
  561. var len = string.length
  562. if (len === 0) return 0
  563. // Use a for loop to avoid recursion
  564. var loweredCase = false
  565. for (;;) {
  566. switch (encoding) {
  567. case 'ascii':
  568. case 'latin1':
  569. case 'binary':
  570. return len
  571. case 'utf8':
  572. case 'utf-8':
  573. case undefined:
  574. return utf8ToBytes(string).length
  575. case 'ucs2':
  576. case 'ucs-2':
  577. case 'utf16le':
  578. case 'utf-16le':
  579. return len * 2
  580. case 'hex':
  581. return len >>> 1
  582. case 'base64':
  583. return base64ToBytes(string).length
  584. default:
  585. if (loweredCase) return utf8ToBytes(string).length // assume utf8
  586. encoding = ('' + encoding).toLowerCase()
  587. loweredCase = true
  588. }
  589. }
  590. }
  591. Buffer.byteLength = byteLength
  592. function slowToString (encoding, start, end) {
  593. var loweredCase = false
  594. // No need to verify that "this.length <= MAX_UINT32" since it's a read-only
  595. // property of a typed array.
  596. // This behaves neither like String nor Uint8Array in that we set start/end
  597. // to their upper/lower bounds if the value passed is out of range.
  598. // undefined is handled specially as per ECMA-262 6th Edition,
  599. // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
  600. if (start === undefined || start < 0) {
  601. start = 0
  602. }
  603. // Return early if start > this.length. Done here to prevent potential uint32
  604. // coercion fail below.
  605. if (start > this.length) {
  606. return ''
  607. }
  608. if (end === undefined || end > this.length) {
  609. end = this.length
  610. }
  611. if (end <= 0) {
  612. return ''
  613. }
  614. // Force coersion to uint32. This will also coerce falsey/NaN values to 0.
  615. end >>>= 0
  616. start >>>= 0
  617. if (end <= start) {
  618. return ''
  619. }
  620. if (!encoding) encoding = 'utf8'
  621. while (true) {
  622. switch (encoding) {
  623. case 'hex':
  624. return hexSlice(this, start, end)
  625. case 'utf8':
  626. case 'utf-8':
  627. return utf8Slice(this, start, end)
  628. case 'ascii':
  629. return asciiSlice(this, start, end)
  630. case 'latin1':
  631. case 'binary':
  632. return latin1Slice(this, start, end)
  633. case 'base64':
  634. return base64Slice(this, start, end)
  635. case 'ucs2':
  636. case 'ucs-2':
  637. case 'utf16le':
  638. case 'utf-16le':
  639. return utf16leSlice(this, start, end)
  640. default:
  641. if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
  642. encoding = (encoding + '').toLowerCase()
  643. loweredCase = true
  644. }
  645. }
  646. }
  647. // The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect
  648. // Buffer instances.
  649. Buffer.prototype._isBuffer = true
  650. function swap (b, n, m) {
  651. var i = b[n]
  652. b[n] = b[m]
  653. b[m] = i
  654. }
  655. Buffer.prototype.swap16 = function swap16 () {
  656. var len = this.length
  657. if (len % 2 !== 0) {
  658. throw new RangeError('Buffer size must be a multiple of 16-bits')
  659. }
  660. for (var i = 0; i < len; i += 2) {
  661. swap(this, i, i + 1)
  662. }
  663. return this
  664. }
  665. Buffer.prototype.swap32 = function swap32 () {
  666. var len = this.length
  667. if (len % 4 !== 0) {
  668. throw new RangeError('Buffer size must be a multiple of 32-bits')
  669. }
  670. for (var i = 0; i < len; i += 4) {
  671. swap(this, i, i + 3)
  672. swap(this, i + 1, i + 2)
  673. }
  674. return this
  675. }
  676. Buffer.prototype.swap64 = function swap64 () {
  677. var len = this.length
  678. if (len % 8 !== 0) {
  679. throw new RangeError('Buffer size must be a multiple of 64-bits')
  680. }
  681. for (var i = 0; i < len; i += 8) {
  682. swap(this, i, i + 7)
  683. swap(this, i + 1, i + 6)
  684. swap(this, i + 2, i + 5)
  685. swap(this, i + 3, i + 4)
  686. }
  687. return this
  688. }
  689. Buffer.prototype.toString = function toString () {
  690. var length = this.length | 0
  691. if (length === 0) return ''
  692. if (arguments.length === 0) return utf8Slice(this, 0, length)
  693. return slowToString.apply(this, arguments)
  694. }
  695. Buffer.prototype.equals = function equals (b) {
  696. if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
  697. if (this === b) return true
  698. return Buffer.compare(this, b) === 0
  699. }
  700. Buffer.prototype.inspect = function inspect () {
  701. var str = ''
  702. var max = exports.INSPECT_MAX_BYTES
  703. if (this.length > 0) {
  704. str = this.toString('hex', 0, max).match(/.{2}/g).join(' ')
  705. if (this.length > max) str += ' ... '
  706. }
  707. return '<Buffer ' + str + '>'
  708. }
  709. Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
  710. if (!Buffer.isBuffer(target)) {
  711. throw new TypeError('Argument must be a Buffer')
  712. }
  713. if (start === undefined) {
  714. start = 0
  715. }
  716. if (end === undefined) {
  717. end = target ? target.length : 0
  718. }
  719. if (thisStart === undefined) {
  720. thisStart = 0
  721. }
  722. if (thisEnd === undefined) {
  723. thisEnd = this.length
  724. }
  725. if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
  726. throw new RangeError('out of range index')
  727. }
  728. if (thisStart >= thisEnd && start >= end) {
  729. return 0
  730. }
  731. if (thisStart >= thisEnd) {
  732. return -1
  733. }
  734. if (start >= end) {
  735. return 1
  736. }
  737. start >>>= 0
  738. end >>>= 0
  739. thisStart >>>= 0
  740. thisEnd >>>= 0
  741. if (this === target) return 0
  742. var x = thisEnd - thisStart
  743. var y = end - start
  744. var len = Math.min(x, y)
  745. var thisCopy = this.slice(thisStart, thisEnd)
  746. var targetCopy = target.slice(start, end)
  747. for (var i = 0; i < len; ++i) {
  748. if (thisCopy[i] !== targetCopy[i]) {
  749. x = thisCopy[i]
  750. y = targetCopy[i]
  751. break
  752. }
  753. }
  754. if (x < y) return -1
  755. if (y < x) return 1
  756. return 0
  757. }
  758. // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
  759. // OR the last index of `val` in `buffer` at offset <= `byteOffset`.
  760. //
  761. // Arguments:
  762. // - buffer - a Buffer to search
  763. // - val - a string, Buffer, or number
  764. // - byteOffset - an index into `buffer`; will be clamped to an int32
  765. // - encoding - an optional encoding, relevant is val is a string
  766. // - dir - true for indexOf, false for lastIndexOf
  767. function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {
  768. // Empty buffer means no match
  769. if (buffer.length === 0) return -1
  770. // Normalize byteOffset
  771. if (typeof byteOffset === 'string') {
  772. encoding = byteOffset
  773. byteOffset = 0
  774. } else if (byteOffset > 0x7fffffff) {
  775. byteOffset = 0x7fffffff
  776. } else if (byteOffset < -0x80000000) {
  777. byteOffset = -0x80000000
  778. }
  779. byteOffset = +byteOffset // Coerce to Number.
  780. if (isNaN(byteOffset)) {
  781. // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
  782. byteOffset = dir ? 0 : (buffer.length - 1)
  783. }
  784. // Normalize byteOffset: negative offsets start from the end of the buffer
  785. if (byteOffset < 0) byteOffset = buffer.length + byteOffset
  786. if (byteOffset >= buffer.length) {
  787. if (dir) return -1
  788. else byteOffset = buffer.length - 1
  789. } else if (byteOffset < 0) {
  790. if (dir) byteOffset = 0
  791. else return -1
  792. }
  793. // Normalize val
  794. if (typeof val === 'string') {
  795. val = Buffer.from(val, encoding)
  796. }
  797. // Finally, search either indexOf (if dir is true) or lastIndexOf
  798. if (Buffer.isBuffer(val)) {
  799. // Special case: looking for empty string/buffer always fails
  800. if (val.length === 0) {
  801. return -1
  802. }
  803. return arrayIndexOf(buffer, val, byteOffset, encoding, dir)
  804. } else if (typeof val === 'number') {
  805. val = val & 0xFF // Search for a byte value [0-255]
  806. if (Buffer.TYPED_ARRAY_SUPPORT &&
  807. typeof Uint8Array.prototype.indexOf === 'function') {
  808. if (dir) {
  809. return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)
  810. } else {
  811. return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)
  812. }
  813. }
  814. return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)
  815. }
  816. throw new TypeError('val must be string, number or Buffer')
  817. }
  818. function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
  819. var indexSize = 1
  820. var arrLength = arr.length
  821. var valLength = val.length
  822. if (encoding !== undefined) {
  823. encoding = String(encoding).toLowerCase()
  824. if (encoding === 'ucs2' || encoding === 'ucs-2' ||
  825. encoding === 'utf16le' || encoding === 'utf-16le') {
  826. if (arr.length < 2 || val.length < 2) {
  827. return -1
  828. }
  829. indexSize = 2
  830. arrLength /= 2
  831. valLength /= 2
  832. byteOffset /= 2
  833. }
  834. }
  835. function read (buf, i) {
  836. if (indexSize === 1) {
  837. return buf[i]
  838. } else {
  839. return buf.readUInt16BE(i * indexSize)
  840. }
  841. }
  842. var i
  843. if (dir) {
  844. var foundIndex = -1
  845. for (i = byteOffset; i < arrLength; i++) {
  846. if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
  847. if (foundIndex === -1) foundIndex = i
  848. if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
  849. } else {
  850. if (foundIndex !== -1) i -= i - foundIndex
  851. foundIndex = -1
  852. }
  853. }
  854. } else {
  855. if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength
  856. for (i = byteOffset; i >= 0; i--) {
  857. var found = true
  858. for (var j = 0; j < valLength; j++) {
  859. if (read(arr, i + j) !== read(val, j)) {
  860. found = false
  861. break
  862. }
  863. }
  864. if (found) return i
  865. }
  866. }
  867. return -1
  868. }
  869. Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
  870. return this.indexOf(val, byteOffset, encoding) !== -1
  871. }
  872. Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
  873. return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
  874. }
  875. Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
  876. return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
  877. }
  878. function hexWrite (buf, string, offset, length) {
  879. offset = Number(offset) || 0
  880. var remaining = buf.length - offset
  881. if (!length) {
  882. length = remaining
  883. } else {
  884. length = Number(length)
  885. if (length > remaining) {
  886. length = remaining
  887. }
  888. }
  889. // must be an even number of digits
  890. var strLen = string.length
  891. if (strLen % 2 !== 0) throw new TypeError('Invalid hex string')
  892. if (length > strLen / 2) {
  893. length = strLen / 2
  894. }
  895. for (var i = 0; i < length; ++i) {
  896. var parsed = parseInt(string.substr(i * 2, 2), 16)
  897. if (isNaN(parsed)) return i
  898. buf[offset + i] = parsed
  899. }
  900. return i
  901. }
  902. function utf8Write (buf, string, offset, length) {
  903. return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
  904. }
  905. function asciiWrite (buf, string, offset, length) {
  906. return blitBuffer(asciiToBytes(string), buf, offset, length)
  907. }
  908. function latin1Write (buf, string, offset, length) {
  909. return asciiWrite(buf, string, offset, length)
  910. }
  911. function base64Write (buf, string, offset, length) {
  912. return blitBuffer(base64ToBytes(string), buf, offset, length)
  913. }
  914. function ucs2Write (buf, string, offset, length) {
  915. return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
  916. }
  917. Buffer.prototype.write = function write (string, offset, length, encoding) {
  918. // Buffer#write(string)
  919. if (offset === undefined) {
  920. encoding = 'utf8'
  921. length = this.length
  922. offset = 0
  923. // Buffer#write(string, encoding)
  924. } else if (length === undefined && typeof offset === 'string') {
  925. encoding = offset
  926. length = this.length
  927. offset = 0
  928. // Buffer#write(string, offset[, length][, encoding])
  929. } else if (isFinite(offset)) {
  930. offset = offset | 0
  931. if (isFinite(length)) {
  932. length = length | 0
  933. if (encoding === undefined) encoding = 'utf8'
  934. } else {
  935. encoding = length
  936. length = undefined
  937. }
  938. // legacy write(string, encoding, offset, length) - remove in v0.13
  939. } else {
  940. throw new Error(
  941. 'Buffer.write(string, encoding, offset[, length]) is no longer supported'
  942. )
  943. }
  944. var remaining = this.length - offset
  945. if (length === undefined || length > remaining) length = remaining
  946. if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
  947. throw new RangeError('Attempt to write outside buffer bounds')
  948. }
  949. if (!encoding) encoding = 'utf8'
  950. var loweredCase = false
  951. for (;;) {
  952. switch (encoding) {
  953. case 'hex':
  954. return hexWrite(this, string, offset, length)
  955. case 'utf8':
  956. case 'utf-8':
  957. return utf8Write(this, string, offset, length)
  958. case 'ascii':
  959. return asciiWrite(this, string, offset, length)
  960. case 'latin1':
  961. case 'binary':
  962. return latin1Write(this, string, offset, length)
  963. case 'base64':
  964. // Warning: maxLength not taken into account in base64Write
  965. return base64Write(this, string, offset, length)
  966. case 'ucs2':
  967. case 'ucs-2':
  968. case 'utf16le':
  969. case 'utf-16le':
  970. return ucs2Write(this, string, offset, length)
  971. default:
  972. if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
  973. encoding = ('' + encoding).toLowerCase()
  974. loweredCase = true
  975. }
  976. }
  977. }
  978. Buffer.prototype.toJSON = function toJSON () {
  979. return {
  980. type: 'Buffer',
  981. data: Array.prototype.slice.call(this._arr || this, 0)
  982. }
  983. }
  984. function base64Slice (buf, start, end) {
  985. if (start === 0 && end === buf.length) {
  986. return base64.fromByteArray(buf)
  987. } else {
  988. return base64.fromByteArray(buf.slice(start, end))
  989. }
  990. }
  991. function utf8Slice (buf, start, end) {
  992. end = Math.min(buf.length, end)
  993. var res = []
  994. var i = start
  995. while (i < end) {
  996. var firstByte = buf[i]
  997. var codePoint = null
  998. var bytesPerSequence = (firstByte > 0xEF) ? 4
  999. : (firstByte > 0xDF) ? 3
  1000. : (firstByte > 0xBF) ? 2
  1001. : 1
  1002. if (i + bytesPerSequence <= end) {
  1003. var secondByte, thirdByte, fourthByte, tempCodePoint
  1004. switch (bytesPerSequence) {
  1005. case 1:
  1006. if (firstByte < 0x80) {
  1007. codePoint = firstByte
  1008. }
  1009. break
  1010. case 2:
  1011. secondByte = buf[i + 1]
  1012. if ((secondByte & 0xC0) === 0x80) {
  1013. tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)
  1014. if (tempCodePoint > 0x7F) {
  1015. codePoint = tempCodePoint
  1016. }
  1017. }
  1018. break
  1019. case 3:
  1020. secondByte = buf[i + 1]
  1021. thirdByte = buf[i + 2]
  1022. if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
  1023. tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)
  1024. if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
  1025. codePoint = tempCodePoint
  1026. }
  1027. }
  1028. break
  1029. case 4:
  1030. secondByte = buf[i + 1]
  1031. thirdByte = buf[i + 2]
  1032. fourthByte = buf[i + 3]
  1033. if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
  1034. tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)
  1035. if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
  1036. codePoint = tempCodePoint
  1037. }
  1038. }
  1039. }
  1040. }
  1041. if (codePoint === null) {
  1042. // we did not generate a valid codePoint so insert a
  1043. // replacement char (U+FFFD) and advance only 1 byte
  1044. codePoint = 0xFFFD
  1045. bytesPerSequence = 1
  1046. } else if (codePoint > 0xFFFF) {
  1047. // encode to utf16 (surrogate pair dance)
  1048. codePoint -= 0x10000
  1049. res.push(codePoint >>> 10 & 0x3FF | 0xD800)
  1050. codePoint = 0xDC00 | codePoint & 0x3FF
  1051. }
  1052. res.push(codePoint)
  1053. i += bytesPerSequence
  1054. }
  1055. return decodeCodePointsArray(res)
  1056. }
  1057. // Based on http://stackoverflow.com/a/22747272/680742, the browser with
  1058. // the lowest limit is Chrome, with 0x10000 args.
  1059. // We go 1 magnitude less, for safety
  1060. var MAX_ARGUMENTS_LENGTH = 0x1000
  1061. function decodeCodePointsArray (codePoints) {
  1062. var len = codePoints.length
  1063. if (len <= MAX_ARGUMENTS_LENGTH) {
  1064. return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
  1065. }
  1066. // Decode in chunks to avoid "call stack size exceeded".
  1067. var res = ''
  1068. var i = 0
  1069. while (i < len) {
  1070. res += String.fromCharCode.apply(
  1071. String,
  1072. codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
  1073. )
  1074. }
  1075. return res
  1076. }
  1077. function asciiSlice (buf, start, end) {
  1078. var ret = ''
  1079. end = Math.min(buf.length, end)
  1080. for (var i = start; i < end; ++i) {
  1081. ret += String.fromCharCode(buf[i] & 0x7F)
  1082. }
  1083. return ret
  1084. }
  1085. function latin1Slice (buf, start, end) {
  1086. var ret = ''
  1087. end = Math.min(buf.length, end)
  1088. for (var i = start; i < end; ++i) {
  1089. ret += String.fromCharCode(buf[i])
  1090. }
  1091. return ret
  1092. }
  1093. function hexSlice (buf, start, end) {
  1094. var len = buf.length
  1095. if (!start || start < 0) start = 0
  1096. if (!end || end < 0 || end > len) end = len
  1097. var out = ''
  1098. for (var i = start; i < end; ++i) {
  1099. out += toHex(buf[i])
  1100. }
  1101. return out
  1102. }
  1103. function utf16leSlice (buf, start, end) {
  1104. var bytes = buf.slice(start, end)
  1105. var res = ''
  1106. for (var i = 0; i < bytes.length; i += 2) {
  1107. res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256)
  1108. }
  1109. return res
  1110. }
  1111. Buffer.prototype.slice = function slice (start, end) {
  1112. var len = this.length
  1113. start = ~~start
  1114. end = end === undefined ? len : ~~end
  1115. if (start < 0) {
  1116. start += len
  1117. if (start < 0) start = 0
  1118. } else if (start > len) {
  1119. start = len
  1120. }
  1121. if (end < 0) {
  1122. end += len
  1123. if (end < 0) end = 0
  1124. } else if (end > len) {
  1125. end = len
  1126. }
  1127. if (end < start) end = start
  1128. var newBuf
  1129. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1130. newBuf = this.subarray(start, end)
  1131. newBuf.__proto__ = Buffer.prototype
  1132. } else {
  1133. var sliceLen = end - start
  1134. newBuf = new Buffer(sliceLen, undefined)
  1135. for (var i = 0; i < sliceLen; ++i) {
  1136. newBuf[i] = this[i + start]
  1137. }
  1138. }
  1139. return newBuf
  1140. }
  1141. /*
  1142. * Need to make sure that buffer isn't trying to write out of bounds.
  1143. */
  1144. function checkOffset (offset, ext, length) {
  1145. if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
  1146. if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
  1147. }
  1148. Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
  1149. offset = offset | 0
  1150. byteLength = byteLength | 0
  1151. if (!noAssert) checkOffset(offset, byteLength, this.length)
  1152. var val = this[offset]
  1153. var mul = 1
  1154. var i = 0
  1155. while (++i < byteLength && (mul *= 0x100)) {
  1156. val += this[offset + i] * mul
  1157. }
  1158. return val
  1159. }
  1160. Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
  1161. offset = offset | 0
  1162. byteLength = byteLength | 0
  1163. if (!noAssert) {
  1164. checkOffset(offset, byteLength, this.length)
  1165. }
  1166. var val = this[offset + --byteLength]
  1167. var mul = 1
  1168. while (byteLength > 0 && (mul *= 0x100)) {
  1169. val += this[offset + --byteLength] * mul
  1170. }
  1171. return val
  1172. }
  1173. Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
  1174. if (!noAssert) checkOffset(offset, 1, this.length)
  1175. return this[offset]
  1176. }
  1177. Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
  1178. if (!noAssert) checkOffset(offset, 2, this.length)
  1179. return this[offset] | (this[offset + 1] << 8)
  1180. }
  1181. Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
  1182. if (!noAssert) checkOffset(offset, 2, this.length)
  1183. return (this[offset] << 8) | this[offset + 1]
  1184. }
  1185. Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
  1186. if (!noAssert) checkOffset(offset, 4, this.length)
  1187. return ((this[offset]) |
  1188. (this[offset + 1] << 8) |
  1189. (this[offset + 2] << 16)) +
  1190. (this[offset + 3] * 0x1000000)
  1191. }
  1192. Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
  1193. if (!noAssert) checkOffset(offset, 4, this.length)
  1194. return (this[offset] * 0x1000000) +
  1195. ((this[offset + 1] << 16) |
  1196. (this[offset + 2] << 8) |
  1197. this[offset + 3])
  1198. }
  1199. Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
  1200. offset = offset | 0
  1201. byteLength = byteLength | 0
  1202. if (!noAssert) checkOffset(offset, byteLength, this.length)
  1203. var val = this[offset]
  1204. var mul = 1
  1205. var i = 0
  1206. while (++i < byteLength && (mul *= 0x100)) {
  1207. val += this[offset + i] * mul
  1208. }
  1209. mul *= 0x80
  1210. if (val >= mul) val -= Math.pow(2, 8 * byteLength)
  1211. return val
  1212. }
  1213. Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
  1214. offset = offset | 0
  1215. byteLength = byteLength | 0
  1216. if (!noAssert) checkOffset(offset, byteLength, this.length)
  1217. var i = byteLength
  1218. var mul = 1
  1219. var val = this[offset + --i]
  1220. while (i > 0 && (mul *= 0x100)) {
  1221. val += this[offset + --i] * mul
  1222. }
  1223. mul *= 0x80
  1224. if (val >= mul) val -= Math.pow(2, 8 * byteLength)
  1225. return val
  1226. }
  1227. Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
  1228. if (!noAssert) checkOffset(offset, 1, this.length)
  1229. if (!(this[offset] & 0x80)) return (this[offset])
  1230. return ((0xff - this[offset] + 1) * -1)
  1231. }
  1232. Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
  1233. if (!noAssert) checkOffset(offset, 2, this.length)
  1234. var val = this[offset] | (this[offset + 1] << 8)
  1235. return (val & 0x8000) ? val | 0xFFFF0000 : val
  1236. }
  1237. Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
  1238. if (!noAssert) checkOffset(offset, 2, this.length)
  1239. var val = this[offset + 1] | (this[offset] << 8)
  1240. return (val & 0x8000) ? val | 0xFFFF0000 : val
  1241. }
  1242. Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
  1243. if (!noAssert) checkOffset(offset, 4, this.length)
  1244. return (this[offset]) |
  1245. (this[offset + 1] << 8) |
  1246. (this[offset + 2] << 16) |
  1247. (this[offset + 3] << 24)
  1248. }
  1249. Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
  1250. if (!noAssert) checkOffset(offset, 4, this.length)
  1251. return (this[offset] << 24) |
  1252. (this[offset + 1] << 16) |
  1253. (this[offset + 2] << 8) |
  1254. (this[offset + 3])
  1255. }
  1256. Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
  1257. if (!noAssert) checkOffset(offset, 4, this.length)
  1258. return ieee754.read(this, offset, true, 23, 4)
  1259. }
  1260. Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
  1261. if (!noAssert) checkOffset(offset, 4, this.length)
  1262. return ieee754.read(this, offset, false, 23, 4)
  1263. }
  1264. Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
  1265. if (!noAssert) checkOffset(offset, 8, this.length)
  1266. return ieee754.read(this, offset, true, 52, 8)
  1267. }
  1268. Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
  1269. if (!noAssert) checkOffset(offset, 8, this.length)
  1270. return ieee754.read(this, offset, false, 52, 8)
  1271. }
  1272. function checkInt (buf, value, offset, ext, max, min) {
  1273. if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance')
  1274. if (value > max || value < min) throw new RangeError('"value" argument is out of bounds')
  1275. if (offset + ext > buf.length) throw new RangeError('Index out of range')
  1276. }
  1277. Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
  1278. value = +value
  1279. offset = offset | 0
  1280. byteLength = byteLength | 0
  1281. if (!noAssert) {
  1282. var maxBytes = Math.pow(2, 8 * byteLength) - 1
  1283. checkInt(this, value, offset, byteLength, maxBytes, 0)
  1284. }
  1285. var mul = 1
  1286. var i = 0
  1287. this[offset] = value & 0xFF
  1288. while (++i < byteLength && (mul *= 0x100)) {
  1289. this[offset + i] = (value / mul) & 0xFF
  1290. }
  1291. return offset + byteLength
  1292. }
  1293. Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
  1294. value = +value
  1295. offset = offset | 0
  1296. byteLength = byteLength | 0
  1297. if (!noAssert) {
  1298. var maxBytes = Math.pow(2, 8 * byteLength) - 1
  1299. checkInt(this, value, offset, byteLength, maxBytes, 0)
  1300. }
  1301. var i = byteLength - 1
  1302. var mul = 1
  1303. this[offset + i] = value & 0xFF
  1304. while (--i >= 0 && (mul *= 0x100)) {
  1305. this[offset + i] = (value / mul) & 0xFF
  1306. }
  1307. return offset + byteLength
  1308. }
  1309. Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
  1310. value = +value
  1311. offset = offset | 0
  1312. if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)
  1313. if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
  1314. this[offset] = (value & 0xff)
  1315. return offset + 1
  1316. }
  1317. function objectWriteUInt16 (buf, value, offset, littleEndian) {
  1318. if (value < 0) value = 0xffff + value + 1
  1319. for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) {
  1320. buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>>
  1321. (littleEndian ? i : 1 - i) * 8
  1322. }
  1323. }
  1324. Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
  1325. value = +value
  1326. offset = offset | 0
  1327. if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
  1328. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1329. this[offset] = (value & 0xff)
  1330. this[offset + 1] = (value >>> 8)
  1331. } else {
  1332. objectWriteUInt16(this, value, offset, true)
  1333. }
  1334. return offset + 2
  1335. }
  1336. Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
  1337. value = +value
  1338. offset = offset | 0
  1339. if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
  1340. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1341. this[offset] = (value >>> 8)
  1342. this[offset + 1] = (value & 0xff)
  1343. } else {
  1344. objectWriteUInt16(this, value, offset, false)
  1345. }
  1346. return offset + 2
  1347. }
  1348. function objectWriteUInt32 (buf, value, offset, littleEndian) {
  1349. if (value < 0) value = 0xffffffff + value + 1
  1350. for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) {
  1351. buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff
  1352. }
  1353. }
  1354. Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
  1355. value = +value
  1356. offset = offset | 0
  1357. if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
  1358. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1359. this[offset + 3] = (value >>> 24)
  1360. this[offset + 2] = (value >>> 16)
  1361. this[offset + 1] = (value >>> 8)
  1362. this[offset] = (value & 0xff)
  1363. } else {
  1364. objectWriteUInt32(this, value, offset, true)
  1365. }
  1366. return offset + 4
  1367. }
  1368. Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
  1369. value = +value
  1370. offset = offset | 0
  1371. if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
  1372. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1373. this[offset] = (value >>> 24)
  1374. this[offset + 1] = (value >>> 16)
  1375. this[offset + 2] = (value >>> 8)
  1376. this[offset + 3] = (value & 0xff)
  1377. } else {
  1378. objectWriteUInt32(this, value, offset, false)
  1379. }
  1380. return offset + 4
  1381. }
  1382. Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
  1383. value = +value
  1384. offset = offset | 0
  1385. if (!noAssert) {
  1386. var limit = Math.pow(2, 8 * byteLength - 1)
  1387. checkInt(this, value, offset, byteLength, limit - 1, -limit)
  1388. }
  1389. var i = 0
  1390. var mul = 1
  1391. var sub = 0
  1392. this[offset] = value & 0xFF
  1393. while (++i < byteLength && (mul *= 0x100)) {
  1394. if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
  1395. sub = 1
  1396. }
  1397. this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
  1398. }
  1399. return offset + byteLength
  1400. }
  1401. Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
  1402. value = +value
  1403. offset = offset | 0
  1404. if (!noAssert) {
  1405. var limit = Math.pow(2, 8 * byteLength - 1)
  1406. checkInt(this, value, offset, byteLength, limit - 1, -limit)
  1407. }
  1408. var i = byteLength - 1
  1409. var mul = 1
  1410. var sub = 0
  1411. this[offset + i] = value & 0xFF
  1412. while (--i >= 0 && (mul *= 0x100)) {
  1413. if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
  1414. sub = 1
  1415. }
  1416. this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
  1417. }
  1418. return offset + byteLength
  1419. }
  1420. Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
  1421. value = +value
  1422. offset = offset | 0
  1423. if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)
  1424. if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
  1425. if (value < 0) value = 0xff + value + 1
  1426. this[offset] = (value & 0xff)
  1427. return offset + 1
  1428. }
  1429. Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
  1430. value = +value
  1431. offset = offset | 0
  1432. if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
  1433. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1434. this[offset] = (value & 0xff)
  1435. this[offset + 1] = (value >>> 8)
  1436. } else {
  1437. objectWriteUInt16(this, value, offset, true)
  1438. }
  1439. return offset + 2
  1440. }
  1441. Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
  1442. value = +value
  1443. offset = offset | 0
  1444. if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
  1445. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1446. this[offset] = (value >>> 8)
  1447. this[offset + 1] = (value & 0xff)
  1448. } else {
  1449. objectWriteUInt16(this, value, offset, false)
  1450. }
  1451. return offset + 2
  1452. }
  1453. Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
  1454. value = +value
  1455. offset = offset | 0
  1456. if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
  1457. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1458. this[offset] = (value & 0xff)
  1459. this[offset + 1] = (value >>> 8)
  1460. this[offset + 2] = (value >>> 16)
  1461. this[offset + 3] = (value >>> 24)
  1462. } else {
  1463. objectWriteUInt32(this, value, offset, true)
  1464. }
  1465. return offset + 4
  1466. }
  1467. Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
  1468. value = +value
  1469. offset = offset | 0
  1470. if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
  1471. if (value < 0) value = 0xffffffff + value + 1
  1472. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1473. this[offset] = (value >>> 24)
  1474. this[offset + 1] = (value >>> 16)
  1475. this[offset + 2] = (value >>> 8)
  1476. this[offset + 3] = (value & 0xff)
  1477. } else {
  1478. objectWriteUInt32(this, value, offset, false)
  1479. }
  1480. return offset + 4
  1481. }
  1482. function checkIEEE754 (buf, value, offset, ext, max, min) {
  1483. if (offset + ext > buf.length) throw new RangeError('Index out of range')
  1484. if (offset < 0) throw new RangeError('Index out of range')
  1485. }
  1486. function writeFloat (buf, value, offset, littleEndian, noAssert) {
  1487. if (!noAssert) {
  1488. checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
  1489. }
  1490. ieee754.write(buf, value, offset, littleEndian, 23, 4)
  1491. return offset + 4
  1492. }
  1493. Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
  1494. return writeFloat(this, value, offset, true, noAssert)
  1495. }
  1496. Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
  1497. return writeFloat(this, value, offset, false, noAssert)
  1498. }
  1499. function writeDouble (buf, value, offset, littleEndian, noAssert) {
  1500. if (!noAssert) {
  1501. checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
  1502. }
  1503. ieee754.write(buf, value, offset, littleEndian, 52, 8)
  1504. return offset + 8
  1505. }
  1506. Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
  1507. return writeDouble(this, value, offset, true, noAssert)
  1508. }
  1509. Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
  1510. return writeDouble(this, value, offset, false, noAssert)
  1511. }
  1512. // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
  1513. Buffer.prototype.copy = function copy (target, targetStart, start, end) {
  1514. if (!start) start = 0
  1515. if (!end && end !== 0) end = this.length
  1516. if (targetStart >= target.length) targetStart = target.length
  1517. if (!targetStart) targetStart = 0
  1518. if (end > 0 && end < start) end = start
  1519. // Copy 0 bytes; we're done
  1520. if (end === start) return 0
  1521. if (target.length === 0 || this.length === 0) return 0
  1522. // Fatal error conditions
  1523. if (targetStart < 0) {
  1524. throw new RangeError('targetStart out of bounds')
  1525. }
  1526. if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds')
  1527. if (end < 0) throw new RangeError('sourceEnd out of bounds')
  1528. // Are we oob?
  1529. if (end > this.length) end = this.length
  1530. if (target.length - targetStart < end - start) {
  1531. end = target.length - targetStart + start
  1532. }
  1533. var len = end - start
  1534. var i
  1535. if (this === target && start < targetStart && targetStart < end) {
  1536. // descending copy from end
  1537. for (i = len - 1; i >= 0; --i) {
  1538. target[i + targetStart] = this[i + start]
  1539. }
  1540. } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) {
  1541. // ascending copy from start
  1542. for (i = 0; i < len; ++i) {
  1543. target[i + targetStart] = this[i + start]
  1544. }
  1545. } else {
  1546. Uint8Array.prototype.set.call(
  1547. target,
  1548. this.subarray(start, start + len),
  1549. targetStart
  1550. )
  1551. }
  1552. return len
  1553. }
  1554. // Usage:
  1555. // buffer.fill(number[, offset[, end]])
  1556. // buffer.fill(buffer[, offset[, end]])
  1557. // buffer.fill(string[, offset[, end]][, encoding])
  1558. Buffer.prototype.fill = function fill (val, start, end, encoding) {
  1559. // Handle string cases:
  1560. if (typeof val === 'string') {
  1561. if (typeof start === 'string') {
  1562. encoding = start
  1563. start = 0
  1564. end = this.length
  1565. } else if (typeof end === 'string') {
  1566. encoding = end
  1567. end = this.length
  1568. }
  1569. if (val.length === 1) {
  1570. var code = val.charCodeAt(0)
  1571. if (code < 256) {
  1572. val = code
  1573. }
  1574. }
  1575. if (encoding !== undefined && typeof encoding !== 'string') {
  1576. throw new TypeError('encoding must be a string')
  1577. }
  1578. if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
  1579. throw new TypeError('Unknown encoding: ' + encoding)
  1580. }
  1581. } else if (typeof val === 'number') {
  1582. val = val & 255
  1583. }
  1584. // Invalid ranges are not set to a default, so can range check early.
  1585. if (start < 0 || this.length < start || this.length < end) {
  1586. throw new RangeError('Out of range index')
  1587. }
  1588. if (end <= start) {
  1589. return this
  1590. }
  1591. start = start >>> 0
  1592. end = end === undefined ? this.length : end >>> 0
  1593. if (!val) val = 0
  1594. var i
  1595. if (typeof val === 'number') {
  1596. for (i = start; i < end; ++i) {
  1597. this[i] = val
  1598. }
  1599. } else {
  1600. var bytes = Buffer.isBuffer(val)
  1601. ? val
  1602. : utf8ToBytes(new Buffer(val, encoding).toString())
  1603. var len = bytes.length
  1604. for (i = 0; i < end - start; ++i) {
  1605. this[i + start] = bytes[i % len]
  1606. }
  1607. }
  1608. return this
  1609. }
  1610. // HELPER FUNCTIONS
  1611. // ================
  1612. var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g
  1613. function base64clean (str) {
  1614. // Node strips out invalid characters like \n and \t from the string, base64-js does not
  1615. str = stringtrim(str).replace(INVALID_BASE64_RE, '')
  1616. // Node converts strings with length < 2 to ''
  1617. if (str.length < 2) return ''
  1618. // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
  1619. while (str.length % 4 !== 0) {
  1620. str = str + '='
  1621. }
  1622. return str
  1623. }
  1624. function stringtrim (str) {
  1625. if (str.trim) return str.trim()
  1626. return str.replace(/^\s+|\s+$/g, '')
  1627. }
  1628. function toHex (n) {
  1629. if (n < 16) return '0' + n.toString(16)
  1630. return n.toString(16)
  1631. }
  1632. function utf8ToBytes (string, units) {
  1633. units = units || Infinity
  1634. var codePoint
  1635. var length = string.length
  1636. var leadSurrogate = null
  1637. var bytes = []
  1638. for (var i = 0; i < length; ++i) {
  1639. codePoint = string.charCodeAt(i)
  1640. // is surrogate component
  1641. if (codePoint > 0xD7FF && codePoint < 0xE000) {
  1642. // last char was a lead
  1643. if (!leadSurrogate) {
  1644. // no lead yet
  1645. if (codePoint > 0xDBFF) {
  1646. // unexpected trail
  1647. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  1648. continue
  1649. } else if (i + 1 === length) {
  1650. // unpaired lead
  1651. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  1652. continue
  1653. }
  1654. // valid lead
  1655. leadSurrogate = codePoint
  1656. continue
  1657. }
  1658. // 2 leads in a row
  1659. if (codePoint < 0xDC00) {
  1660. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  1661. leadSurrogate = codePoint
  1662. continue
  1663. }
  1664. // valid surrogate pair
  1665. codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000
  1666. } else if (leadSurrogate) {
  1667. // valid bmp char, but last char was a lead
  1668. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  1669. }
  1670. leadSurrogate = null
  1671. // encode utf8
  1672. if (codePoint < 0x80) {
  1673. if ((units -= 1) < 0) break
  1674. bytes.push(codePoint)
  1675. } else if (codePoint < 0x800) {
  1676. if ((units -= 2) < 0) break
  1677. bytes.push(
  1678. codePoint >> 0x6 | 0xC0,
  1679. codePoint & 0x3F | 0x80
  1680. )
  1681. } else if (codePoint < 0x10000) {
  1682. if ((units -= 3) < 0) break
  1683. bytes.push(
  1684. codePoint >> 0xC | 0xE0,
  1685. codePoint >> 0x6 & 0x3F | 0x80,
  1686. codePoint & 0x3F | 0x80
  1687. )
  1688. } else if (codePoint < 0x110000) {
  1689. if ((units -= 4) < 0) break
  1690. bytes.push(
  1691. codePoint >> 0x12 | 0xF0,
  1692. codePoint >> 0xC & 0x3F | 0x80,
  1693. codePoint >> 0x6 & 0x3F | 0x80,
  1694. codePoint & 0x3F | 0x80
  1695. )
  1696. } else {
  1697. throw new Error('Invalid code point')
  1698. }
  1699. }
  1700. return bytes
  1701. }
  1702. function asciiToBytes (str) {
  1703. var byteArray = []
  1704. for (var i = 0; i < str.length; ++i) {
  1705. // Node's code seems to be doing this and not & 0x7F..
  1706. byteArray.push(str.charCodeAt(i) & 0xFF)
  1707. }
  1708. return byteArray
  1709. }
  1710. function utf16leToBytes (str, units) {
  1711. var c, hi, lo
  1712. var byteArray = []
  1713. for (var i = 0; i < str.length; ++i) {
  1714. if ((units -= 2) < 0) break
  1715. c = str.charCodeAt(i)
  1716. hi = c >> 8
  1717. lo = c % 256
  1718. byteArray.push(lo)
  1719. byteArray.push(hi)
  1720. }
  1721. return byteArray
  1722. }
  1723. function base64ToBytes (str) {
  1724. return base64.toByteArray(base64clean(str))
  1725. }
  1726. function blitBuffer (src, dst, offset, length) {
  1727. for (var i = 0; i < length; ++i) {
  1728. if ((i + offset >= dst.length) || (i >= src.length)) break
  1729. dst[i + offset] = src[i]
  1730. }
  1731. return i
  1732. }
  1733. function isnan (val) {
  1734. return val !== val // eslint-disable-line no-self-compare
  1735. }
  1736. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},_dereq_("buffer").Buffer)
  1737. },{"base64-js":3,"buffer":6,"ieee754":29,"isarray":35}],7:[function(_dereq_,module,exports){
  1738. // Polyfill for creating CustomEvents on IE9/10/11
  1739. // code pulled from:
  1740. // https://github.com/d4tocchini/customevent-polyfill
  1741. // https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent#Polyfill
  1742. (function() {
  1743. if (typeof window === 'undefined') {
  1744. return;
  1745. }
  1746. try {
  1747. var ce = new window.CustomEvent('test', { cancelable: true });
  1748. ce.preventDefault();
  1749. if (ce.defaultPrevented !== true) {
  1750. // IE has problems with .preventDefault() on custom events
  1751. // http://stackoverflow.com/questions/23349191
  1752. throw new Error('Could not prevent default');
  1753. }
  1754. } catch (e) {
  1755. var CustomEvent = function(event, params) {
  1756. var evt, origPrevent;
  1757. params = params || {};
  1758. params.bubbles = !!params.bubbles;
  1759. params.cancelable = !!params.cancelable;
  1760. evt = document.createEvent('CustomEvent');
  1761. evt.initCustomEvent(
  1762. event,
  1763. params.bubbles,
  1764. params.cancelable,
  1765. params.detail
  1766. );
  1767. origPrevent = evt.preventDefault;
  1768. evt.preventDefault = function() {
  1769. origPrevent.call(this);
  1770. try {
  1771. Object.defineProperty(this, 'defaultPrevented', {
  1772. get: function() {
  1773. return true;
  1774. }
  1775. });
  1776. } catch (e) {
  1777. this.defaultPrevented = true;
  1778. }
  1779. };
  1780. return evt;
  1781. };
  1782. CustomEvent.prototype = window.Event.prototype;
  1783. window.CustomEvent = CustomEvent; // expose definition to window
  1784. }
  1785. })();
  1786. },{}],8:[function(_dereq_,module,exports){
  1787. /**
  1788. * This is the web browser implementation of `debug()`.
  1789. *
  1790. * Expose `debug()` as the module.
  1791. */
  1792. exports = module.exports = _dereq_('./debug');
  1793. exports.log = log;
  1794. exports.formatArgs = formatArgs;
  1795. exports.save = save;
  1796. exports.load = load;
  1797. exports.useColors = useColors;
  1798. exports.storage = 'undefined' != typeof chrome
  1799. && 'undefined' != typeof chrome.storage
  1800. ? chrome.storage.local
  1801. : localstorage();
  1802. /**
  1803. * Colors.
  1804. */
  1805. exports.colors = [
  1806. 'lightseagreen',
  1807. 'forestgreen',
  1808. 'goldenrod',
  1809. 'dodgerblue',
  1810. 'darkorchid',
  1811. 'crimson'
  1812. ];
  1813. /**
  1814. * Currently only WebKit-based Web Inspectors, Firefox >= v31,
  1815. * and the Firebug extension (any Firefox version) are known
  1816. * to support "%c" CSS customizations.
  1817. *
  1818. * TODO: add a `localStorage` variable to explicitly enable/disable colors
  1819. */
  1820. function useColors() {
  1821. // is webkit? http://stackoverflow.com/a/16459606/376773
  1822. return ('WebkitAppearance' in document.documentElement.style) ||
  1823. // is firebug? http://stackoverflow.com/a/398120/376773
  1824. (window.console && (console.firebug || (console.exception && console.table))) ||
  1825. // is firefox >= v31?
  1826. // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
  1827. (navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31);
  1828. }
  1829. /**
  1830. * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
  1831. */
  1832. exports.formatters.j = function(v) {
  1833. return JSON.stringify(v);
  1834. };
  1835. /**
  1836. * Colorize log arguments if enabled.
  1837. *
  1838. * @api public
  1839. */
  1840. function formatArgs() {
  1841. var args = arguments;
  1842. var useColors = this.useColors;
  1843. args[0] = (useColors ? '%c' : '')
  1844. + this.namespace
  1845. + (useColors ? ' %c' : ' ')
  1846. + args[0]
  1847. + (useColors ? '%c ' : ' ');
  1848. if (!useColors) return args;
  1849. var c = 'color: ' + this.color;
  1850. args = [args[0], c, 'color: inherit'].concat(Array.prototype.slice.call(args, 1));
  1851. // the final "%c" is somewhat tricky, because there could be other
  1852. // arguments passed either before or after the %c, so we need to
  1853. // figure out the correct index to insert the CSS into
  1854. var index = 0;
  1855. var lastC = 0;
  1856. args[0].replace(/%[a-z%]/g, function(match) {
  1857. if ('%%' === match) return;
  1858. index++;
  1859. if ('%c' === match) {
  1860. // we only are interested in the *last* %c
  1861. // (the user may have provided their own)
  1862. lastC = index;
  1863. }
  1864. });
  1865. args.splice(lastC, 0, c);
  1866. return args;
  1867. }
  1868. /**
  1869. * Invokes `console.log()` when available.
  1870. * No-op when `console.log` is not a "function".
  1871. *
  1872. * @api public
  1873. */
  1874. function log() {
  1875. // this hackery is required for IE8/9, where
  1876. // the `console.log` function doesn't have 'apply'
  1877. return 'object' === typeof console
  1878. && console.log
  1879. && Function.prototype.apply.call(console.log, console, arguments);
  1880. }
  1881. /**
  1882. * Save `namespaces`.
  1883. *
  1884. * @param {String} namespaces
  1885. * @api private
  1886. */
  1887. function save(namespaces) {
  1888. try {
  1889. if (null == namespaces) {
  1890. exports.storage.removeItem('debug');
  1891. } else {
  1892. exports.storage.debug = namespaces;
  1893. }
  1894. } catch(e) {}
  1895. }
  1896. /**
  1897. * Load `namespaces`.
  1898. *
  1899. * @return {String} returns the previously persisted debug modes
  1900. * @api private
  1901. */
  1902. function load() {
  1903. var r;
  1904. try {
  1905. r = exports.storage.debug;
  1906. } catch(e) {}
  1907. return r;
  1908. }
  1909. /**
  1910. * Enable namespaces listed in `localStorage.debug` initially.
  1911. */
  1912. exports.enable(load());
  1913. /**
  1914. * Localstorage attempts to return the localstorage.
  1915. *
  1916. * This is necessary because safari throws
  1917. * when a user disables cookies/localstorage
  1918. * and you attempt to access it.
  1919. *
  1920. * @return {LocalStorage}
  1921. * @api private
  1922. */
  1923. function localstorage(){
  1924. try {
  1925. return window.localStorage;
  1926. } catch (e) {}
  1927. }
  1928. },{"./debug":9}],9:[function(_dereq_,module,exports){
  1929. /**
  1930. * This is the common logic for both the Node.js and web browser
  1931. * implementations of `debug()`.
  1932. *
  1933. * Expose `debug()` as the module.
  1934. */
  1935. exports = module.exports = debug;
  1936. exports.coerce = coerce;
  1937. exports.disable = disable;
  1938. exports.enable = enable;
  1939. exports.enabled = enabled;
  1940. /**
  1941. * The currently active debug mode names, and names to skip.
  1942. */
  1943. exports.names = [];
  1944. exports.skips = [];
  1945. /**
  1946. * Map of special "%n" handling functions, for the debug "format" argument.
  1947. *
  1948. * Valid key names are a single, lowercased letter, i.e. "n".
  1949. */
  1950. exports.formatters = {};
  1951. /**
  1952. * Previously assigned color.
  1953. */
  1954. var prevColor = 0;
  1955. /**
  1956. * Select a color.
  1957. *
  1958. * @return {Number}
  1959. * @api private
  1960. */
  1961. function selectColor() {
  1962. return exports.colors[prevColor++ % exports.colors.length];
  1963. }
  1964. /**
  1965. * Create a debugger with the given `namespace`.
  1966. *
  1967. * @param {String} namespace
  1968. * @return {Function}
  1969. * @api public
  1970. */
  1971. function debug(namespace) {
  1972. // define the `disabled` version
  1973. function disabled() {
  1974. }
  1975. disabled.enabled = false;
  1976. // define the `enabled` version
  1977. function enabled() {
  1978. var self = enabled;
  1979. // add the `color` if not set
  1980. if (null == self.useColors) self.useColors = exports.useColors();
  1981. if (null == self.color && self.useColors) self.color = selectColor();
  1982. var args = Array.prototype.slice.call(arguments);
  1983. args[0] = exports.coerce(args[0]);
  1984. if ('string' !== typeof args[0]) {
  1985. // anything else let's inspect with %o
  1986. args = ['%o'].concat(args);
  1987. }
  1988. // apply any `formatters` transformations
  1989. var index = 0;
  1990. args[0] = args[0].replace(/%([a-z%])/g, function(match, format) {
  1991. // if we encounter an escaped % then don't increase the array index
  1992. if (match === '%%') return match;
  1993. index++;
  1994. var formatter = exports.formatters[format];
  1995. if ('function' === typeof formatter) {
  1996. var val = args[index];
  1997. match = formatter.call(self, val);
  1998. // now we need to remove `args[index]` since it's inlined in the `format`
  1999. args.splice(index, 1);
  2000. index--;
  2001. }
  2002. return match;
  2003. });
  2004. if ('function' === typeof exports.formatArgs) {
  2005. args = exports.formatArgs.apply(self, args);
  2006. }
  2007. var logFn = enabled.log || exports.log || console.log.bind(console);
  2008. logFn.apply(self, args);
  2009. }
  2010. enabled.enabled = true;
  2011. var fn = exports.enabled(namespace) ? enabled : disabled;
  2012. fn.namespace = namespace;
  2013. return fn;
  2014. }
  2015. /**
  2016. * Enables a debug mode by namespaces. This can include modes
  2017. * separated by a colon and wildcards.
  2018. *
  2019. * @param {String} namespaces
  2020. * @api public
  2021. */
  2022. function enable(namespaces) {
  2023. exports.save(namespaces);
  2024. var split = (namespaces || '').split(/[\s,]+/);
  2025. var len = split.length;
  2026. for (var i = 0; i < len; i++) {
  2027. if (!split[i]) continue; // ignore empty strings
  2028. namespaces = split[i].replace(/\*/g, '.*?');
  2029. if (namespaces[0] === '-') {
  2030. exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));
  2031. } else {
  2032. exports.names.push(new RegExp('^' + namespaces + '$'));
  2033. }
  2034. }
  2035. }
  2036. /**
  2037. * Disable debug output.
  2038. *
  2039. * @api public
  2040. */
  2041. function disable() {
  2042. exports.enable('');
  2043. }
  2044. /**
  2045. * Returns true if the given mode name is enabled, false otherwise.
  2046. *
  2047. * @param {String} name
  2048. * @return {Boolean}
  2049. * @api public
  2050. */
  2051. function enabled(name) {
  2052. var i, len;
  2053. for (i = 0, len = exports.skips.length; i < len; i++) {
  2054. if (exports.skips[i].test(name)) {
  2055. return false;
  2056. }
  2057. }
  2058. for (i = 0, len = exports.names.length; i < len; i++) {
  2059. if (exports.names[i].test(name)) {
  2060. return true;
  2061. }
  2062. }
  2063. return false;
  2064. }
  2065. /**
  2066. * Coerce `val`.
  2067. *
  2068. * @param {Mixed} val
  2069. * @return {Mixed}
  2070. * @api private
  2071. */
  2072. function coerce(val) {
  2073. if (val instanceof Error) return val.stack || val.message;
  2074. return val;
  2075. }
  2076. },{}],10:[function(_dereq_,module,exports){
  2077. 'use strict';
  2078. var isObj = _dereq_('is-obj');
  2079. var hasOwnProperty = Object.prototype.hasOwnProperty;
  2080. var propIsEnumerable = Object.prototype.propertyIsEnumerable;
  2081. function toObject(val) {
  2082. if (val === null || val === undefined) {
  2083. throw new TypeError('Sources cannot be null or undefined');
  2084. }
  2085. return Object(val);
  2086. }
  2087. function assignKey(to, from, key) {
  2088. var val = from[key];
  2089. if (val === undefined || val === null) {
  2090. return;
  2091. }
  2092. if (hasOwnProperty.call(to, key)) {
  2093. if (to[key] === undefined || to[key] === null) {
  2094. throw new TypeError('Cannot convert undefined or null to object (' + key + ')');
  2095. }
  2096. }
  2097. if (!hasOwnProperty.call(to, key) || !isObj(val)) {
  2098. to[key] = val;
  2099. } else {
  2100. to[key] = assign(Object(to[key]), from[key]);
  2101. }
  2102. }
  2103. function assign(to, from) {
  2104. if (to === from) {
  2105. return to;
  2106. }
  2107. from = Object(from);
  2108. for (var key in from) {
  2109. if (hasOwnProperty.call(from, key)) {
  2110. assignKey(to, from, key);
  2111. }
  2112. }
  2113. if (Object.getOwnPropertySymbols) {
  2114. var symbols = Object.getOwnPropertySymbols(from);
  2115. for (var i = 0; i < symbols.length; i++) {
  2116. if (propIsEnumerable.call(from, symbols[i])) {
  2117. assignKey(to, from, symbols[i]);
  2118. }
  2119. }
  2120. }
  2121. return to;
  2122. }
  2123. module.exports = function deepAssign(target) {
  2124. target = toObject(target);
  2125. for (var s = 1; s < arguments.length; s++) {
  2126. assign(target, arguments[s]);
  2127. }
  2128. return target;
  2129. };
  2130. },{"is-obj":34}],11:[function(_dereq_,module,exports){
  2131. 'use strict';
  2132. var keys = _dereq_('object-keys');
  2133. var hasSymbols = typeof Symbol === 'function' && typeof Symbol('foo') === 'symbol';
  2134. var toStr = Object.prototype.toString;
  2135. var concat = Array.prototype.concat;
  2136. var origDefineProperty = Object.defineProperty;
  2137. var isFunction = function (fn) {
  2138. return typeof fn === 'function' && toStr.call(fn) === '[object Function]';
  2139. };
  2140. var arePropertyDescriptorsSupported = function () {
  2141. var obj = {};
  2142. try {
  2143. origDefineProperty(obj, 'x', { enumerable: false, value: obj });
  2144. // eslint-disable-next-line no-unused-vars, no-restricted-syntax
  2145. for (var _ in obj) { // jscs:ignore disallowUnusedVariables
  2146. return false;
  2147. }
  2148. return obj.x === obj;
  2149. } catch (e) { /* this is IE 8. */
  2150. return false;
  2151. }
  2152. };
  2153. var supportsDescriptors = origDefineProperty && arePropertyDescriptorsSupported();
  2154. var defineProperty = function (object, name, value, predicate) {
  2155. if (name in object && (!isFunction(predicate) || !predicate())) {
  2156. return;
  2157. }
  2158. if (supportsDescriptors) {
  2159. origDefineProperty(object, name, {
  2160. configurable: true,
  2161. enumerable: false,
  2162. value: value,
  2163. writable: true
  2164. });
  2165. } else {
  2166. object[name] = value;
  2167. }
  2168. };
  2169. var defineProperties = function (object, map) {
  2170. var predicates = arguments.length > 2 ? arguments[2] : {};
  2171. var props = keys(map);
  2172. if (hasSymbols) {
  2173. props = concat.call(props, Object.getOwnPropertySymbols(map));
  2174. }
  2175. for (var i = 0; i < props.length; i += 1) {
  2176. defineProperty(object, props[i], map[props[i]], predicates[props[i]]);
  2177. }
  2178. };
  2179. defineProperties.supportsDescriptors = !!supportsDescriptors;
  2180. module.exports = defineProperties;
  2181. },{"object-keys":41}],12:[function(_dereq_,module,exports){
  2182. /*! (C) WebReflection Mit Style License */
  2183. (function(t,n,r,i){"use strict";function st(e,t){for(var n=0,r=e.length;n<r;n++)gt(e[n],t)}function ot(e){for(var t=0,n=e.length,r;t<n;t++)r=e[t],it(r,w[at(r)])}function ut(e){return function(t){F(t)&&(gt(t,e),st(t.querySelectorAll(E),e))}}function at(e){var t=R.call(e,"is"),n=e.nodeName.toUpperCase(),r=x.call(b,t?m+t.toUpperCase():v+n);return t&&-1<r&&!ft(n,t)?-1:r}function ft(e,t){return-1<E.indexOf(e+'[is="'+t+'"]')}function lt(e){var t=e.currentTarget,n=e.attrChange,r=e.attrName,i=e.target;Y&&(!i||i===t)&&t.attributeChangedCallback&&r!=="style"&&e.prevValue!==e.newValue&&t.attributeChangedCallback(r,n===e[f]?null:e.prevValue,n===e[c]?null:e.newValue)}function ct(e){var t=ut(e);return function(e){$.push(t,e.target)}}function ht(e){G&&(G=!1,e.currentTarget.removeEventListener(p,ht)),st((e.target||n).querySelectorAll(E),e.detail===u?u:o),j&&vt()}function pt(e,t){var n=this;U.call(n,e,t),Z.call(n,{target:n})}function dt(e,t){P(e,t),nt?nt.observe(e,X):(Q&&(e.setAttribute=pt,e[s]=tt(e),e.addEventListener(d,Z)),e.addEventListener(h,lt)),e.createdCallback&&Y&&(e.created=!0,e.createdCallback(),e.created=!1)}function vt(){for(var e,t=0,n=I.length;t<n;t++)e=I[t],S.contains(e)||(n--,I.splice(t--,1),gt(e,u))}function mt(e){throw new Error("A "+e+" type is already registered")}function gt(e,t){var n,r=at(e);-1<r&&(rt(e,w[r]),r=0,t===o&&!e[o]?(e[u]=!1,e[o]=!0,r=1,j&&x.call(I,e)<0&&I.push(e)):t===u&&!e[u]&&(e[o]=!1,e[u]=!0,r=1),r&&(n=e[t+"Callback"])&&n.call(e))}if(i in n)return;var s="__"+i+(Math.random()*1e5>>0),o="attached",u="detached",a="extends",f="ADDITION",l="MODIFICATION",c="REMOVAL",h="DOMAttrModified",p="DOMContentLoaded",d="DOMSubtreeModified",v="<",m="=",g=/^[A-Z][A-Z0-9]*(?:-[A-Z0-9]+)+$/,y=["ANNOTATION-XML","COLOR-PROFILE","FONT-FACE","FONT-FACE-SRC","FONT-FACE-URI","FONT-FACE-FORMAT","FONT-FACE-NAME","MISSING-GLYPH"],b=[],w=[],E="",S=n.documentElement,x=b.indexOf||function(e){for(var t=this.length;t--&&this[t]!==e;);return t},T=r.prototype,N=T.hasOwnProperty,C=T.isPrototypeOf,k=r.defineProperty,L=r.getOwnPropertyDescriptor,A=r.getOwnPropertyNames,O=r.getPrototypeOf,M=r.setPrototypeOf,_=!!r.__proto__,D=r.create||function yt(e){return e?(yt.prototype=e,new yt):this},P=M||(_?function(e,t){return e.__proto__=t,e}:A&&L?function(){function e(e,t){for(var n,r=A(t),i=0,s=r.length;i<s;i++)n=r[i],N.call(e,n)||k(e,n,L(t,n))}return function(t,n){do e(t,n);while((n=O(n))&&!C.call(n,t));return t}}():function(e,t){for(var n in t)e[n]=t[n];return e}),H=t.MutationObserver||t.WebKitMutationObserver,B=(t.HTMLElement||t.Element||t.Node).prototype,j=!C.call(B,S),F=j?function(e){return e.nodeType===1}:function(e){return C.call(B,e)},I=j&&[],q=B.cloneNode,R=B.getAttribute,U=B.setAttribute,z=B.removeAttribute,W=n.createElement,X=H&&{attributes:!0,characterData:!0,attributeOldValue:!0},V=H||function(e){Q=!1,S.removeEventListener(h,V)},$,J=t.requestAnimationFrame||t.webkitRequestAnimationFrame||t.mozRequestAnimationFrame||t.msRequestAnimationFrame||function(e){setTimeout(e,10)},K=!1,Q=!0,G=!0,Y=!0,Z,et,tt,nt,rt,it;M||_?(rt=function(e,t){C.call(t,e)||dt(e,t)},it=dt):(rt=function(e,t){e[s]||(e[s]=r(!0),dt(e,t))},it=rt),j?(Q=!1,function(){var t=L(B,"addEventListener"),n=t.value,r=function(e){var t=new CustomEvent(h,{bubbles:!0});t.attrName=e,t.prevValue=R.call(this,e),t.newValue=null,t[c]=t.attrChange=2,z.call(this,e),this.dispatchEvent(t)},i=function(t,n){var r=this.hasAttribute(t),i=r&&R.call(this,t);e=new CustomEvent(h,{bubbles:!0}),U.call(this,t,n),e.attrName=t,e.prevValue=r?i:null,e.newValue=n,r?e[l]=e.attrChange=1:e[f]=e.attrChange=0,this.dispatchEvent(e)},o=function(e){var t=e.currentTarget,n=t[s],r=e.propertyName,i;n.hasOwnProperty(r)&&(n=n[r],i=new CustomEvent(h,{bubbles:!0}),i.attrName=n.name,i.prevValue=n.value||null,i.newValue=n.value=t[r]||null,i.prevValue==null?i[f]=i.attrChange=0:i[l]=i.attrChange=1,t.dispatchEvent(i))};t.value=function(e,t,u){e===h&&this.attributeChangedCallback&&this.setAttribute!==i&&(this[s]={className:{name:"class",value:this.className}},this.setAttribute=i,this.removeAttribute=r,n.call(this,"propertychange",o)),n.call(this,e,t,u)},k(B,"addEventListener",t)}()):H||(S.addEventListener(h,V),S.setAttribute(s,1),S.removeAttribute(s),Q&&(Z=function(e){var t=this,n,r,i;if(t===e.target){n=t[s],t[s]=r=tt(t);for(i in r){if(!(i in n))return et(0,t,i,n[i],r[i],f);if(r[i]!==n[i])return et(1,t,i,n[i],r[i],l)}for(i in n)if(!(i in r))return et(2,t,i,n[i],r[i],c)}},et=function(e,t,n,r,i,s){var o={attrChange:e,currentTarget:t,attrName:n,prevValue:r,newValue:i};o[s]=e,lt(o)},tt=function(e){for(var t,n,r={},i=e.attributes,s=0,o=i.length;s<o;s++)t=i[s],n=t.name,n!=="setAttribute"&&(r[n]=t.value);return r})),n[i]=function(t,r){c=t.toUpperCase(),K||(K=!0,H?(nt=function(e,t){function n(e,t){for(var n=0,r=e.length;n<r;t(e[n++]));}return new H(function(r){for(var i,s,o,u=0,a=r.length;u<a;u++)i=r[u],i.type==="childList"?(n(i.addedNodes,e),n(i.removedNodes,t)):(s=i.target,Y&&s.attributeChangedCallback&&i.attributeName!=="style"&&(o=R.call(s,i.attributeName),o!==i.oldValue&&s.attributeChangedCallback(i.attributeName,i.oldValue,o)))})}(ut(o),ut(u)),nt.observe(n,{childList:!0,subtree:!0})):($=[],J(function d(){while($.length)$.shift().call(null,$.shift());J(d)}),n.addEventListener("DOMNodeInserted",ct(o)),n.addEventListener("DOMNodeRemoved",ct(u))),n.addEventListener(p,ht),n.addEventListener("readystatechange",ht),n.createElement=function(e,t){var r=W.apply(n,arguments),i=""+e,s=x.call(b,(t?m:v)+(t||i).toUpperCase()),o=-1<s;return t&&(r.setAttribute("is",t=t.toLowerCase()),o&&(o=ft(i.toUpperCase(),t))),Y=!n.createElement.innerHTMLHelper,o&&it(r,w[s]),r},B.cloneNode=function(e){var t=q.call(this,!!e),n=at(t);return-1<n&&it(t,w[n]),e&&ot(t.querySelectorAll(E)),t}),-2<x.call(b,m+c)+x.call(b,v+c)&&mt(t);if(!g.test(c)||-1<x.call(y,c))throw new Error("The type "+t+" is invalid");var i=function(){return f?n.createElement(l,c):n.createElement(l)},s=r||T,f=N.call(s,a),l=f?r[a].toUpperCase():c,c,h;return f&&-1<x.call(b,v+l)&&mt(l),h=b.push((f?m:v)+c)-1,E=E.concat(E.length?",":"",f?l+'[is="'+t.toLowerCase()+'"]':l),i.prototype=w[h]=N.call(s,"prototype")?s.prototype:D(B),st(n.querySelectorAll(E),o),i}})(window,document,Object,"registerElement");
  2184. },{}],13:[function(_dereq_,module,exports){
  2185. module.exports = function(dtype) {
  2186. switch (dtype) {
  2187. case 'int8':
  2188. return Int8Array
  2189. case 'int16':
  2190. return Int16Array
  2191. case 'int32':
  2192. return Int32Array
  2193. case 'uint8':
  2194. return Uint8Array
  2195. case 'uint16':
  2196. return Uint16Array
  2197. case 'uint32':
  2198. return Uint32Array
  2199. case 'float32':
  2200. return Float32Array
  2201. case 'float64':
  2202. return Float64Array
  2203. case 'array':
  2204. return Array
  2205. case 'uint8_clamped':
  2206. return Uint8ClampedArray
  2207. }
  2208. }
  2209. },{}],14:[function(_dereq_,module,exports){
  2210. 'use strict';
  2211. /* globals
  2212. Set,
  2213. Map,
  2214. WeakSet,
  2215. WeakMap,
  2216. Promise,
  2217. Symbol,
  2218. Proxy,
  2219. Atomics,
  2220. SharedArrayBuffer,
  2221. ArrayBuffer,
  2222. DataView,
  2223. Uint8Array,
  2224. Float32Array,
  2225. Float64Array,
  2226. Int8Array,
  2227. Int16Array,
  2228. Int32Array,
  2229. Uint8ClampedArray,
  2230. Uint16Array,
  2231. Uint32Array,
  2232. */
  2233. var undefined; // eslint-disable-line no-shadow-restricted-names
  2234. var ThrowTypeError = Object.getOwnPropertyDescriptor
  2235. ? (function () { return Object.getOwnPropertyDescriptor(arguments, 'callee').get; }())
  2236. : function () { throw new TypeError(); };
  2237. var hasSymbols = typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol';
  2238. var getProto = Object.getPrototypeOf || function (x) { return x.__proto__; }; // eslint-disable-line no-proto
  2239. var generator; // = function * () {};
  2240. var generatorFunction = generator ? getProto(generator) : undefined;
  2241. var asyncFn; // async function() {};
  2242. var asyncFunction = asyncFn ? asyncFn.constructor : undefined;
  2243. var asyncGen; // async function * () {};
  2244. var asyncGenFunction = asyncGen ? getProto(asyncGen) : undefined;
  2245. var asyncGenIterator = asyncGen ? asyncGen() : undefined;
  2246. var TypedArray = typeof Uint8Array === 'undefined' ? undefined : getProto(Uint8Array);
  2247. var INTRINSICS = {
  2248. '$ %Array%': Array,
  2249. '$ %ArrayBuffer%': typeof ArrayBuffer === 'undefined' ? undefined : ArrayBuffer,
  2250. '$ %ArrayBufferPrototype%': typeof ArrayBuffer === 'undefined' ? undefined : ArrayBuffer.prototype,
  2251. '$ %ArrayIteratorPrototype%': hasSymbols ? getProto([][Symbol.iterator]()) : undefined,
  2252. '$ %ArrayPrototype%': Array.prototype,
  2253. '$ %ArrayProto_entries%': Array.prototype.entries,
  2254. '$ %ArrayProto_forEach%': Array.prototype.forEach,
  2255. '$ %ArrayProto_keys%': Array.prototype.keys,
  2256. '$ %ArrayProto_values%': Array.prototype.values,
  2257. '$ %AsyncFromSyncIteratorPrototype%': undefined,
  2258. '$ %AsyncFunction%': asyncFunction,
  2259. '$ %AsyncFunctionPrototype%': asyncFunction ? asyncFunction.prototype : undefined,
  2260. '$ %AsyncGenerator%': asyncGen ? getProto(asyncGenIterator) : undefined,
  2261. '$ %AsyncGeneratorFunction%': asyncGenFunction,
  2262. '$ %AsyncGeneratorPrototype%': asyncGenFunction ? asyncGenFunction.prototype : undefined,
  2263. '$ %AsyncIteratorPrototype%': asyncGenIterator && hasSymbols && Symbol.asyncIterator ? asyncGenIterator[Symbol.asyncIterator]() : undefined,
  2264. '$ %Atomics%': typeof Atomics === 'undefined' ? undefined : Atomics,
  2265. '$ %Boolean%': Boolean,
  2266. '$ %BooleanPrototype%': Boolean.prototype,
  2267. '$ %DataView%': typeof DataView === 'undefined' ? undefined : DataView,
  2268. '$ %DataViewPrototype%': typeof DataView === 'undefined' ? undefined : DataView.prototype,
  2269. '$ %Date%': Date,
  2270. '$ %DatePrototype%': Date.prototype,
  2271. '$ %decodeURI%': decodeURI,
  2272. '$ %decodeURIComponent%': decodeURIComponent,
  2273. '$ %encodeURI%': encodeURI,
  2274. '$ %encodeURIComponent%': encodeURIComponent,
  2275. '$ %Error%': Error,
  2276. '$ %ErrorPrototype%': Error.prototype,
  2277. '$ %eval%': eval, // eslint-disable-line no-eval
  2278. '$ %EvalError%': EvalError,
  2279. '$ %EvalErrorPrototype%': EvalError.prototype,
  2280. '$ %Float32Array%': typeof Float32Array === 'undefined' ? undefined : Float32Array,
  2281. '$ %Float32ArrayPrototype%': typeof Float32Array === 'undefined' ? undefined : Float32Array.prototype,
  2282. '$ %Float64Array%': typeof Float64Array === 'undefined' ? undefined : Float64Array,
  2283. '$ %Float64ArrayPrototype%': typeof Float64Array === 'undefined' ? undefined : Float64Array.prototype,
  2284. '$ %Function%': Function,
  2285. '$ %FunctionPrototype%': Function.prototype,
  2286. '$ %Generator%': generator ? getProto(generator()) : undefined,
  2287. '$ %GeneratorFunction%': generatorFunction,
  2288. '$ %GeneratorPrototype%': generatorFunction ? generatorFunction.prototype : undefined,
  2289. '$ %Int8Array%': typeof Int8Array === 'undefined' ? undefined : Int8Array,
  2290. '$ %Int8ArrayPrototype%': typeof Int8Array === 'undefined' ? undefined : Int8Array.prototype,
  2291. '$ %Int16Array%': typeof Int16Array === 'undefined' ? undefined : Int16Array,
  2292. '$ %Int16ArrayPrototype%': typeof Int16Array === 'undefined' ? undefined : Int8Array.prototype,
  2293. '$ %Int32Array%': typeof Int32Array === 'undefined' ? undefined : Int32Array,
  2294. '$ %Int32ArrayPrototype%': typeof Int32Array === 'undefined' ? undefined : Int32Array.prototype,
  2295. '$ %isFinite%': isFinite,
  2296. '$ %isNaN%': isNaN,
  2297. '$ %IteratorPrototype%': hasSymbols ? getProto(getProto([][Symbol.iterator]())) : undefined,
  2298. '$ %JSON%': JSON,
  2299. '$ %JSONParse%': JSON.parse,
  2300. '$ %Map%': typeof Map === 'undefined' ? undefined : Map,
  2301. '$ %MapIteratorPrototype%': typeof Map === 'undefined' || !hasSymbols ? undefined : getProto(new Map()[Symbol.iterator]()),
  2302. '$ %MapPrototype%': typeof Map === 'undefined' ? undefined : Map.prototype,
  2303. '$ %Math%': Math,
  2304. '$ %Number%': Number,
  2305. '$ %NumberPrototype%': Number.prototype,
  2306. '$ %Object%': Object,
  2307. '$ %ObjectPrototype%': Object.prototype,
  2308. '$ %ObjProto_toString%': Object.prototype.toString,
  2309. '$ %ObjProto_valueOf%': Object.prototype.valueOf,
  2310. '$ %parseFloat%': parseFloat,
  2311. '$ %parseInt%': parseInt,
  2312. '$ %Promise%': typeof Promise === 'undefined' ? undefined : Promise,
  2313. '$ %PromisePrototype%': typeof Promise === 'undefined' ? undefined : Promise.prototype,
  2314. '$ %PromiseProto_then%': typeof Promise === 'undefined' ? undefined : Promise.prototype.then,
  2315. '$ %Promise_all%': typeof Promise === 'undefined' ? undefined : Promise.all,
  2316. '$ %Promise_reject%': typeof Promise === 'undefined' ? undefined : Promise.reject,
  2317. '$ %Promise_resolve%': typeof Promise === 'undefined' ? undefined : Promise.resolve,
  2318. '$ %Proxy%': typeof Proxy === 'undefined' ? undefined : Proxy,
  2319. '$ %RangeError%': RangeError,
  2320. '$ %RangeErrorPrototype%': RangeError.prototype,
  2321. '$ %ReferenceError%': ReferenceError,
  2322. '$ %ReferenceErrorPrototype%': ReferenceError.prototype,
  2323. '$ %Reflect%': typeof Reflect === 'undefined' ? undefined : Reflect,
  2324. '$ %RegExp%': RegExp,
  2325. '$ %RegExpPrototype%': RegExp.prototype,
  2326. '$ %Set%': typeof Set === 'undefined' ? undefined : Set,
  2327. '$ %SetIteratorPrototype%': typeof Set === 'undefined' || !hasSymbols ? undefined : getProto(new Set()[Symbol.iterator]()),
  2328. '$ %SetPrototype%': typeof Set === 'undefined' ? undefined : Set.prototype,
  2329. '$ %SharedArrayBuffer%': typeof SharedArrayBuffer === 'undefined' ? undefined : SharedArrayBuffer,
  2330. '$ %SharedArrayBufferPrototype%': typeof SharedArrayBuffer === 'undefined' ? undefined : SharedArrayBuffer.prototype,
  2331. '$ %String%': String,
  2332. '$ %StringIteratorPrototype%': hasSymbols ? getProto(''[Symbol.iterator]()) : undefined,
  2333. '$ %StringPrototype%': String.prototype,
  2334. '$ %Symbol%': hasSymbols ? Symbol : undefined,
  2335. '$ %SymbolPrototype%': hasSymbols ? Symbol.prototype : undefined,
  2336. '$ %SyntaxError%': SyntaxError,
  2337. '$ %SyntaxErrorPrototype%': SyntaxError.prototype,
  2338. '$ %ThrowTypeError%': ThrowTypeError,
  2339. '$ %TypedArray%': TypedArray,
  2340. '$ %TypedArrayPrototype%': TypedArray ? TypedArray.prototype : undefined,
  2341. '$ %TypeError%': TypeError,
  2342. '$ %TypeErrorPrototype%': TypeError.prototype,
  2343. '$ %Uint8Array%': typeof Uint8Array === 'undefined' ? undefined : Uint8Array,
  2344. '$ %Uint8ArrayPrototype%': typeof Uint8Array === 'undefined' ? undefined : Uint8Array.prototype,
  2345. '$ %Uint8ClampedArray%': typeof Uint8ClampedArray === 'undefined' ? undefined : Uint8ClampedArray,
  2346. '$ %Uint8ClampedArrayPrototype%': typeof Uint8ClampedArray === 'undefined' ? undefined : Uint8ClampedArray.prototype,
  2347. '$ %Uint16Array%': typeof Uint16Array === 'undefined' ? undefined : Uint16Array,
  2348. '$ %Uint16ArrayPrototype%': typeof Uint16Array === 'undefined' ? undefined : Uint16Array.prototype,
  2349. '$ %Uint32Array%': typeof Uint32Array === 'undefined' ? undefined : Uint32Array,
  2350. '$ %Uint32ArrayPrototype%': typeof Uint32Array === 'undefined' ? undefined : Uint32Array.prototype,
  2351. '$ %URIError%': URIError,
  2352. '$ %URIErrorPrototype%': URIError.prototype,
  2353. '$ %WeakMap%': typeof WeakMap === 'undefined' ? undefined : WeakMap,
  2354. '$ %WeakMapPrototype%': typeof WeakMap === 'undefined' ? undefined : WeakMap.prototype,
  2355. '$ %WeakSet%': typeof WeakSet === 'undefined' ? undefined : WeakSet,
  2356. '$ %WeakSetPrototype%': typeof WeakSet === 'undefined' ? undefined : WeakSet.prototype
  2357. };
  2358. module.exports = function GetIntrinsic(name, allowMissing) {
  2359. if (arguments.length > 1 && typeof allowMissing !== 'boolean') {
  2360. throw new TypeError('"allowMissing" argument must be a boolean');
  2361. }
  2362. var key = '$ ' + name;
  2363. if (!(key in INTRINSICS)) {
  2364. throw new SyntaxError('intrinsic ' + name + ' does not exist!');
  2365. }
  2366. // istanbul ignore if // hopefully this is impossible to test :-)
  2367. if (typeof INTRINSICS[key] === 'undefined' && !allowMissing) {
  2368. throw new TypeError('intrinsic ' + name + ' exists, but is not available. Please file an issue!');
  2369. }
  2370. return INTRINSICS[key];
  2371. };
  2372. },{}],15:[function(_dereq_,module,exports){
  2373. 'use strict';
  2374. var GetIntrinsic = _dereq_('./GetIntrinsic');
  2375. var $Object = GetIntrinsic('%Object%');
  2376. var $TypeError = GetIntrinsic('%TypeError%');
  2377. var $String = GetIntrinsic('%String%');
  2378. var assertRecord = _dereq_('./helpers/assertRecord');
  2379. var $isNaN = _dereq_('./helpers/isNaN');
  2380. var $isFinite = _dereq_('./helpers/isFinite');
  2381. var sign = _dereq_('./helpers/sign');
  2382. var mod = _dereq_('./helpers/mod');
  2383. var IsCallable = _dereq_('is-callable');
  2384. var toPrimitive = _dereq_('es-to-primitive/es5');
  2385. var has = _dereq_('has');
  2386. // https://es5.github.io/#x9
  2387. var ES5 = {
  2388. ToPrimitive: toPrimitive,
  2389. ToBoolean: function ToBoolean(value) {
  2390. return !!value;
  2391. },
  2392. ToNumber: function ToNumber(value) {
  2393. return +value; // eslint-disable-line no-implicit-coercion
  2394. },
  2395. ToInteger: function ToInteger(value) {
  2396. var number = this.ToNumber(value);
  2397. if ($isNaN(number)) { return 0; }
  2398. if (number === 0 || !$isFinite(number)) { return number; }
  2399. return sign(number) * Math.floor(Math.abs(number));
  2400. },
  2401. ToInt32: function ToInt32(x) {
  2402. return this.ToNumber(x) >> 0;
  2403. },
  2404. ToUint32: function ToUint32(x) {
  2405. return this.ToNumber(x) >>> 0;
  2406. },
  2407. ToUint16: function ToUint16(value) {
  2408. var number = this.ToNumber(value);
  2409. if ($isNaN(number) || number === 0 || !$isFinite(number)) { return 0; }
  2410. var posInt = sign(number) * Math.floor(Math.abs(number));
  2411. return mod(posInt, 0x10000);
  2412. },
  2413. ToString: function ToString(value) {
  2414. return $String(value);
  2415. },
  2416. ToObject: function ToObject(value) {
  2417. this.CheckObjectCoercible(value);
  2418. return $Object(value);
  2419. },
  2420. CheckObjectCoercible: function CheckObjectCoercible(value, optMessage) {
  2421. /* jshint eqnull:true */
  2422. if (value == null) {
  2423. throw new $TypeError(optMessage || 'Cannot call method on ' + value);
  2424. }
  2425. return value;
  2426. },
  2427. IsCallable: IsCallable,
  2428. SameValue: function SameValue(x, y) {
  2429. if (x === y) { // 0 === -0, but they are not identical.
  2430. if (x === 0) { return 1 / x === 1 / y; }
  2431. return true;
  2432. }
  2433. return $isNaN(x) && $isNaN(y);
  2434. },
  2435. // https://www.ecma-international.org/ecma-262/5.1/#sec-8
  2436. Type: function Type(x) {
  2437. if (x === null) {
  2438. return 'Null';
  2439. }
  2440. if (typeof x === 'undefined') {
  2441. return 'Undefined';
  2442. }
  2443. if (typeof x === 'function' || typeof x === 'object') {
  2444. return 'Object';
  2445. }
  2446. if (typeof x === 'number') {
  2447. return 'Number';
  2448. }
  2449. if (typeof x === 'boolean') {
  2450. return 'Boolean';
  2451. }
  2452. if (typeof x === 'string') {
  2453. return 'String';
  2454. }
  2455. },
  2456. // https://ecma-international.org/ecma-262/6.0/#sec-property-descriptor-specification-type
  2457. IsPropertyDescriptor: function IsPropertyDescriptor(Desc) {
  2458. if (this.Type(Desc) !== 'Object') {
  2459. return false;
  2460. }
  2461. var allowed = {
  2462. '[[Configurable]]': true,
  2463. '[[Enumerable]]': true,
  2464. '[[Get]]': true,
  2465. '[[Set]]': true,
  2466. '[[Value]]': true,
  2467. '[[Writable]]': true
  2468. };
  2469. for (var key in Desc) { // eslint-disable-line
  2470. if (has(Desc, key) && !allowed[key]) {
  2471. return false;
  2472. }
  2473. }
  2474. var isData = has(Desc, '[[Value]]');
  2475. var IsAccessor = has(Desc, '[[Get]]') || has(Desc, '[[Set]]');
  2476. if (isData && IsAccessor) {
  2477. throw new $TypeError('Property Descriptors may not be both accessor and data descriptors');
  2478. }
  2479. return true;
  2480. },
  2481. // https://ecma-international.org/ecma-262/5.1/#sec-8.10.1
  2482. IsAccessorDescriptor: function IsAccessorDescriptor(Desc) {
  2483. if (typeof Desc === 'undefined') {
  2484. return false;
  2485. }
  2486. assertRecord(this, 'Property Descriptor', 'Desc', Desc);
  2487. if (!has(Desc, '[[Get]]') && !has(Desc, '[[Set]]')) {
  2488. return false;
  2489. }
  2490. return true;
  2491. },
  2492. // https://ecma-international.org/ecma-262/5.1/#sec-8.10.2
  2493. IsDataDescriptor: function IsDataDescriptor(Desc) {
  2494. if (typeof Desc === 'undefined') {
  2495. return false;
  2496. }
  2497. assertRecord(this, 'Property Descriptor', 'Desc', Desc);
  2498. if (!has(Desc, '[[Value]]') && !has(Desc, '[[Writable]]')) {
  2499. return false;
  2500. }
  2501. return true;
  2502. },
  2503. // https://ecma-international.org/ecma-262/5.1/#sec-8.10.3
  2504. IsGenericDescriptor: function IsGenericDescriptor(Desc) {
  2505. if (typeof Desc === 'undefined') {
  2506. return false;
  2507. }
  2508. assertRecord(this, 'Property Descriptor', 'Desc', Desc);
  2509. if (!this.IsAccessorDescriptor(Desc) && !this.IsDataDescriptor(Desc)) {
  2510. return true;
  2511. }
  2512. return false;
  2513. },
  2514. // https://ecma-international.org/ecma-262/5.1/#sec-8.10.4
  2515. FromPropertyDescriptor: function FromPropertyDescriptor(Desc) {
  2516. if (typeof Desc === 'undefined') {
  2517. return Desc;
  2518. }
  2519. assertRecord(this, 'Property Descriptor', 'Desc', Desc);
  2520. if (this.IsDataDescriptor(Desc)) {
  2521. return {
  2522. value: Desc['[[Value]]'],
  2523. writable: !!Desc['[[Writable]]'],
  2524. enumerable: !!Desc['[[Enumerable]]'],
  2525. configurable: !!Desc['[[Configurable]]']
  2526. };
  2527. } else if (this.IsAccessorDescriptor(Desc)) {
  2528. return {
  2529. get: Desc['[[Get]]'],
  2530. set: Desc['[[Set]]'],
  2531. enumerable: !!Desc['[[Enumerable]]'],
  2532. configurable: !!Desc['[[Configurable]]']
  2533. };
  2534. } else {
  2535. throw new $TypeError('FromPropertyDescriptor must be called with a fully populated Property Descriptor');
  2536. }
  2537. },
  2538. // https://ecma-international.org/ecma-262/5.1/#sec-8.10.5
  2539. ToPropertyDescriptor: function ToPropertyDescriptor(Obj) {
  2540. if (this.Type(Obj) !== 'Object') {
  2541. throw new $TypeError('ToPropertyDescriptor requires an object');
  2542. }
  2543. var desc = {};
  2544. if (has(Obj, 'enumerable')) {
  2545. desc['[[Enumerable]]'] = this.ToBoolean(Obj.enumerable);
  2546. }
  2547. if (has(Obj, 'configurable')) {
  2548. desc['[[Configurable]]'] = this.ToBoolean(Obj.configurable);
  2549. }
  2550. if (has(Obj, 'value')) {
  2551. desc['[[Value]]'] = Obj.value;
  2552. }
  2553. if (has(Obj, 'writable')) {
  2554. desc['[[Writable]]'] = this.ToBoolean(Obj.writable);
  2555. }
  2556. if (has(Obj, 'get')) {
  2557. var getter = Obj.get;
  2558. if (typeof getter !== 'undefined' && !this.IsCallable(getter)) {
  2559. throw new TypeError('getter must be a function');
  2560. }
  2561. desc['[[Get]]'] = getter;
  2562. }
  2563. if (has(Obj, 'set')) {
  2564. var setter = Obj.set;
  2565. if (typeof setter !== 'undefined' && !this.IsCallable(setter)) {
  2566. throw new $TypeError('setter must be a function');
  2567. }
  2568. desc['[[Set]]'] = setter;
  2569. }
  2570. if ((has(desc, '[[Get]]') || has(desc, '[[Set]]')) && (has(desc, '[[Value]]') || has(desc, '[[Writable]]'))) {
  2571. throw new $TypeError('Invalid property descriptor. Cannot both specify accessors and a value or writable attribute');
  2572. }
  2573. return desc;
  2574. }
  2575. };
  2576. module.exports = ES5;
  2577. },{"./GetIntrinsic":14,"./helpers/assertRecord":16,"./helpers/isFinite":17,"./helpers/isNaN":18,"./helpers/mod":19,"./helpers/sign":20,"es-to-primitive/es5":21,"has":28,"is-callable":32}],16:[function(_dereq_,module,exports){
  2578. 'use strict';
  2579. var GetIntrinsic = _dereq_('../GetIntrinsic');
  2580. var $TypeError = GetIntrinsic('%TypeError%');
  2581. var $SyntaxError = GetIntrinsic('%SyntaxError%');
  2582. var has = _dereq_('has');
  2583. var predicates = {
  2584. // https://ecma-international.org/ecma-262/6.0/#sec-property-descriptor-specification-type
  2585. 'Property Descriptor': function isPropertyDescriptor(ES, Desc) {
  2586. if (ES.Type(Desc) !== 'Object') {
  2587. return false;
  2588. }
  2589. var allowed = {
  2590. '[[Configurable]]': true,
  2591. '[[Enumerable]]': true,
  2592. '[[Get]]': true,
  2593. '[[Set]]': true,
  2594. '[[Value]]': true,
  2595. '[[Writable]]': true
  2596. };
  2597. for (var key in Desc) { // eslint-disable-line
  2598. if (has(Desc, key) && !allowed[key]) {
  2599. return false;
  2600. }
  2601. }
  2602. var isData = has(Desc, '[[Value]]');
  2603. var IsAccessor = has(Desc, '[[Get]]') || has(Desc, '[[Set]]');
  2604. if (isData && IsAccessor) {
  2605. throw new $TypeError('Property Descriptors may not be both accessor and data descriptors');
  2606. }
  2607. return true;
  2608. }
  2609. };
  2610. module.exports = function assertRecord(ES, recordType, argumentName, value) {
  2611. var predicate = predicates[recordType];
  2612. if (typeof predicate !== 'function') {
  2613. throw new $SyntaxError('unknown record type: ' + recordType);
  2614. }
  2615. if (!predicate(ES, value)) {
  2616. throw new $TypeError(argumentName + ' must be a ' + recordType);
  2617. }
  2618. console.log(predicate(ES, value), value);
  2619. };
  2620. },{"../GetIntrinsic":14,"has":28}],17:[function(_dereq_,module,exports){
  2621. var $isNaN = Number.isNaN || function (a) { return a !== a; };
  2622. module.exports = Number.isFinite || function (x) { return typeof x === 'number' && !$isNaN(x) && x !== Infinity && x !== -Infinity; };
  2623. },{}],18:[function(_dereq_,module,exports){
  2624. module.exports = Number.isNaN || function isNaN(a) {
  2625. return a !== a;
  2626. };
  2627. },{}],19:[function(_dereq_,module,exports){
  2628. module.exports = function mod(number, modulo) {
  2629. var remain = number % modulo;
  2630. return Math.floor(remain >= 0 ? remain : remain + modulo);
  2631. };
  2632. },{}],20:[function(_dereq_,module,exports){
  2633. module.exports = function sign(number) {
  2634. return number >= 0 ? 1 : -1;
  2635. };
  2636. },{}],21:[function(_dereq_,module,exports){
  2637. 'use strict';
  2638. var toStr = Object.prototype.toString;
  2639. var isPrimitive = _dereq_('./helpers/isPrimitive');
  2640. var isCallable = _dereq_('is-callable');
  2641. // http://ecma-international.org/ecma-262/5.1/#sec-8.12.8
  2642. var ES5internalSlots = {
  2643. '[[DefaultValue]]': function (O) {
  2644. var actualHint;
  2645. if (arguments.length > 1) {
  2646. actualHint = arguments[1];
  2647. } else {
  2648. actualHint = toStr.call(O) === '[object Date]' ? String : Number;
  2649. }
  2650. if (actualHint === String || actualHint === Number) {
  2651. var methods = actualHint === String ? ['toString', 'valueOf'] : ['valueOf', 'toString'];
  2652. var value, i;
  2653. for (i = 0; i < methods.length; ++i) {
  2654. if (isCallable(O[methods[i]])) {
  2655. value = O[methods[i]]();
  2656. if (isPrimitive(value)) {
  2657. return value;
  2658. }
  2659. }
  2660. }
  2661. throw new TypeError('No default value');
  2662. }
  2663. throw new TypeError('invalid [[DefaultValue]] hint supplied');
  2664. }
  2665. };
  2666. // http://ecma-international.org/ecma-262/5.1/#sec-9.1
  2667. module.exports = function ToPrimitive(input) {
  2668. if (isPrimitive(input)) {
  2669. return input;
  2670. }
  2671. if (arguments.length > 1) {
  2672. return ES5internalSlots['[[DefaultValue]]'](input, arguments[1]);
  2673. }
  2674. return ES5internalSlots['[[DefaultValue]]'](input);
  2675. };
  2676. },{"./helpers/isPrimitive":22,"is-callable":32}],22:[function(_dereq_,module,exports){
  2677. module.exports = function isPrimitive(value) {
  2678. return value === null || (typeof value !== 'function' && typeof value !== 'object');
  2679. };
  2680. },{}],23:[function(_dereq_,module,exports){
  2681. /*eslint new-cap:0*/
  2682. var dtype = _dereq_('dtype')
  2683. module.exports = flattenVertexData
  2684. function flattenVertexData (data, output, offset) {
  2685. if (!data) throw new TypeError('must specify data as first parameter')
  2686. offset = +(offset || 0) | 0
  2687. if (Array.isArray(data) && (data[0] && typeof data[0][0] === 'number')) {
  2688. var dim = data[0].length
  2689. var length = data.length * dim
  2690. var i, j, k, l
  2691. // no output specified, create a new typed array
  2692. if (!output || typeof output === 'string') {
  2693. output = new (dtype(output || 'float32'))(length + offset)
  2694. }
  2695. var dstLength = output.length - offset
  2696. if (length !== dstLength) {
  2697. throw new Error('source length ' + length + ' (' + dim + 'x' + data.length + ')' +
  2698. ' does not match destination length ' + dstLength)
  2699. }
  2700. for (i = 0, k = offset; i < data.length; i++) {
  2701. for (j = 0; j < dim; j++) {
  2702. output[k++] = data[i][j] === null ? NaN : data[i][j]
  2703. }
  2704. }
  2705. } else {
  2706. if (!output || typeof output === 'string') {
  2707. // no output, create a new one
  2708. var Ctor = dtype(output || 'float32')
  2709. // handle arrays separately due to possible nulls
  2710. if (Array.isArray(data) || output === 'array') {
  2711. output = new Ctor(data.length + offset)
  2712. for (i = 0, k = offset, l = output.length; k < l; k++, i++) {
  2713. output[k] = data[i] === null ? NaN : data[i]
  2714. }
  2715. } else {
  2716. if (offset === 0) {
  2717. output = new Ctor(data)
  2718. } else {
  2719. output = new Ctor(data.length + offset)
  2720. output.set(data, offset)
  2721. }
  2722. }
  2723. } else {
  2724. // store output in existing array
  2725. output.set(data, offset)
  2726. }
  2727. }
  2728. return output
  2729. }
  2730. },{"dtype":13}],24:[function(_dereq_,module,exports){
  2731. 'use strict';
  2732. var isCallable = _dereq_('is-callable');
  2733. var toStr = Object.prototype.toString;
  2734. var hasOwnProperty = Object.prototype.hasOwnProperty;
  2735. var forEachArray = function forEachArray(array, iterator, receiver) {
  2736. for (var i = 0, len = array.length; i < len; i++) {
  2737. if (hasOwnProperty.call(array, i)) {
  2738. if (receiver == null) {
  2739. iterator(array[i], i, array);
  2740. } else {
  2741. iterator.call(receiver, array[i], i, array);
  2742. }
  2743. }
  2744. }
  2745. };
  2746. var forEachString = function forEachString(string, iterator, receiver) {
  2747. for (var i = 0, len = string.length; i < len; i++) {
  2748. // no such thing as a sparse string.
  2749. if (receiver == null) {
  2750. iterator(string.charAt(i), i, string);
  2751. } else {
  2752. iterator.call(receiver, string.charAt(i), i, string);
  2753. }
  2754. }
  2755. };
  2756. var forEachObject = function forEachObject(object, iterator, receiver) {
  2757. for (var k in object) {
  2758. if (hasOwnProperty.call(object, k)) {
  2759. if (receiver == null) {
  2760. iterator(object[k], k, object);
  2761. } else {
  2762. iterator.call(receiver, object[k], k, object);
  2763. }
  2764. }
  2765. }
  2766. };
  2767. var forEach = function forEach(list, iterator, thisArg) {
  2768. if (!isCallable(iterator)) {
  2769. throw new TypeError('iterator must be a function');
  2770. }
  2771. var receiver;
  2772. if (arguments.length >= 3) {
  2773. receiver = thisArg;
  2774. }
  2775. if (toStr.call(list) === '[object Array]') {
  2776. forEachArray(list, iterator, receiver);
  2777. } else if (typeof list === 'string') {
  2778. forEachString(list, iterator, receiver);
  2779. } else {
  2780. forEachObject(list, iterator, receiver);
  2781. }
  2782. };
  2783. module.exports = forEach;
  2784. },{"is-callable":32}],25:[function(_dereq_,module,exports){
  2785. 'use strict';
  2786. /* eslint no-invalid-this: 1 */
  2787. var ERROR_MESSAGE = 'Function.prototype.bind called on incompatible ';
  2788. var slice = Array.prototype.slice;
  2789. var toStr = Object.prototype.toString;
  2790. var funcType = '[object Function]';
  2791. module.exports = function bind(that) {
  2792. var target = this;
  2793. if (typeof target !== 'function' || toStr.call(target) !== funcType) {
  2794. throw new TypeError(ERROR_MESSAGE + target);
  2795. }
  2796. var args = slice.call(arguments, 1);
  2797. var bound;
  2798. var binder = function () {
  2799. if (this instanceof bound) {
  2800. var result = target.apply(
  2801. this,
  2802. args.concat(slice.call(arguments))
  2803. );
  2804. if (Object(result) === result) {
  2805. return result;
  2806. }
  2807. return this;
  2808. } else {
  2809. return target.apply(
  2810. that,
  2811. args.concat(slice.call(arguments))
  2812. );
  2813. }
  2814. };
  2815. var boundLength = Math.max(0, target.length - args.length);
  2816. var boundArgs = [];
  2817. for (var i = 0; i < boundLength; i++) {
  2818. boundArgs.push('$' + i);
  2819. }
  2820. bound = Function('binder', 'return function (' + boundArgs.join(',') + '){ return binder.apply(this,arguments); }')(binder);
  2821. if (target.prototype) {
  2822. var Empty = function Empty() {};
  2823. Empty.prototype = target.prototype;
  2824. bound.prototype = new Empty();
  2825. Empty.prototype = null;
  2826. }
  2827. return bound;
  2828. };
  2829. },{}],26:[function(_dereq_,module,exports){
  2830. 'use strict';
  2831. var implementation = _dereq_('./implementation');
  2832. module.exports = Function.prototype.bind || implementation;
  2833. },{"./implementation":25}],27:[function(_dereq_,module,exports){
  2834. (function (global){
  2835. var win;
  2836. if (typeof window !== "undefined") {
  2837. win = window;
  2838. } else if (typeof global !== "undefined") {
  2839. win = global;
  2840. } else if (typeof self !== "undefined"){
  2841. win = self;
  2842. } else {
  2843. win = {};
  2844. }
  2845. module.exports = win;
  2846. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  2847. },{}],28:[function(_dereq_,module,exports){
  2848. 'use strict';
  2849. var bind = _dereq_('function-bind');
  2850. module.exports = bind.call(Function.call, Object.prototype.hasOwnProperty);
  2851. },{"function-bind":26}],29:[function(_dereq_,module,exports){
  2852. exports.read = function (buffer, offset, isLE, mLen, nBytes) {
  2853. var e, m
  2854. var eLen = (nBytes * 8) - mLen - 1
  2855. var eMax = (1 << eLen) - 1
  2856. var eBias = eMax >> 1
  2857. var nBits = -7
  2858. var i = isLE ? (nBytes - 1) : 0
  2859. var d = isLE ? -1 : 1
  2860. var s = buffer[offset + i]
  2861. i += d
  2862. e = s & ((1 << (-nBits)) - 1)
  2863. s >>= (-nBits)
  2864. nBits += eLen
  2865. for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {}
  2866. m = e & ((1 << (-nBits)) - 1)
  2867. e >>= (-nBits)
  2868. nBits += mLen
  2869. for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {}
  2870. if (e === 0) {
  2871. e = 1 - eBias
  2872. } else if (e === eMax) {
  2873. return m ? NaN : ((s ? -1 : 1) * Infinity)
  2874. } else {
  2875. m = m + Math.pow(2, mLen)
  2876. e = e - eBias
  2877. }
  2878. return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
  2879. }
  2880. exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
  2881. var e, m, c
  2882. var eLen = (nBytes * 8) - mLen - 1
  2883. var eMax = (1 << eLen) - 1
  2884. var eBias = eMax >> 1
  2885. var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)
  2886. var i = isLE ? 0 : (nBytes - 1)
  2887. var d = isLE ? 1 : -1
  2888. var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0
  2889. value = Math.abs(value)
  2890. if (isNaN(value) || value === Infinity) {
  2891. m = isNaN(value) ? 1 : 0
  2892. e = eMax
  2893. } else {
  2894. e = Math.floor(Math.log(value) / Math.LN2)
  2895. if (value * (c = Math.pow(2, -e)) < 1) {
  2896. e--
  2897. c *= 2
  2898. }
  2899. if (e + eBias >= 1) {
  2900. value += rt / c
  2901. } else {
  2902. value += rt * Math.pow(2, 1 - eBias)
  2903. }
  2904. if (value * c >= 2) {
  2905. e++
  2906. c /= 2
  2907. }
  2908. if (e + eBias >= eMax) {
  2909. m = 0
  2910. e = eMax
  2911. } else if (e + eBias >= 1) {
  2912. m = ((value * c) - 1) * Math.pow(2, mLen)
  2913. e = e + eBias
  2914. } else {
  2915. m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
  2916. e = 0
  2917. }
  2918. }
  2919. for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
  2920. e = (e << mLen) | m
  2921. eLen += mLen
  2922. for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
  2923. buffer[offset + i - d] |= s * 128
  2924. }
  2925. },{}],30:[function(_dereq_,module,exports){
  2926. if (typeof Object.create === 'function') {
  2927. // implementation from standard node.js 'util' module
  2928. module.exports = function inherits(ctor, superCtor) {
  2929. if (superCtor) {
  2930. ctor.super_ = superCtor
  2931. ctor.prototype = Object.create(superCtor.prototype, {
  2932. constructor: {
  2933. value: ctor,
  2934. enumerable: false,
  2935. writable: true,
  2936. configurable: true
  2937. }
  2938. })
  2939. }
  2940. };
  2941. } else {
  2942. // old school shim for old browsers
  2943. module.exports = function inherits(ctor, superCtor) {
  2944. if (superCtor) {
  2945. ctor.super_ = superCtor
  2946. var TempCtor = function () {}
  2947. TempCtor.prototype = superCtor.prototype
  2948. ctor.prototype = new TempCtor()
  2949. ctor.prototype.constructor = ctor
  2950. }
  2951. }
  2952. }
  2953. },{}],31:[function(_dereq_,module,exports){
  2954. /*!
  2955. * Determine if an object is a Buffer
  2956. *
  2957. * @author Feross Aboukhadijeh <https://feross.org>
  2958. * @license MIT
  2959. */
  2960. // The _isBuffer check is for Safari 5-7 support, because it's missing
  2961. // Object.prototype.constructor. Remove this eventually
  2962. module.exports = function (obj) {
  2963. return obj != null && (isBuffer(obj) || isSlowBuffer(obj) || !!obj._isBuffer)
  2964. }
  2965. function isBuffer (obj) {
  2966. return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj)
  2967. }
  2968. // For Node v0.10 support. Remove this eventually.
  2969. function isSlowBuffer (obj) {
  2970. return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isBuffer(obj.slice(0, 0))
  2971. }
  2972. },{}],32:[function(_dereq_,module,exports){
  2973. 'use strict';
  2974. var fnToStr = Function.prototype.toString;
  2975. var constructorRegex = /^\s*class\b/;
  2976. var isES6ClassFn = function isES6ClassFunction(value) {
  2977. try {
  2978. var fnStr = fnToStr.call(value);
  2979. return constructorRegex.test(fnStr);
  2980. } catch (e) {
  2981. return false; // not a function
  2982. }
  2983. };
  2984. var tryFunctionObject = function tryFunctionToStr(value) {
  2985. try {
  2986. if (isES6ClassFn(value)) { return false; }
  2987. fnToStr.call(value);
  2988. return true;
  2989. } catch (e) {
  2990. return false;
  2991. }
  2992. };
  2993. var toStr = Object.prototype.toString;
  2994. var fnClass = '[object Function]';
  2995. var genClass = '[object GeneratorFunction]';
  2996. var hasToStringTag = typeof Symbol === 'function' && typeof Symbol.toStringTag === 'symbol';
  2997. module.exports = function isCallable(value) {
  2998. if (!value) { return false; }
  2999. if (typeof value !== 'function' && typeof value !== 'object') { return false; }
  3000. if (typeof value === 'function' && !value.prototype) { return true; }
  3001. if (hasToStringTag) { return tryFunctionObject(value); }
  3002. if (isES6ClassFn(value)) { return false; }
  3003. var strClass = toStr.call(value);
  3004. return strClass === fnClass || strClass === genClass;
  3005. };
  3006. },{}],33:[function(_dereq_,module,exports){
  3007. module.exports = isFunction
  3008. var toString = Object.prototype.toString
  3009. function isFunction (fn) {
  3010. var string = toString.call(fn)
  3011. return string === '[object Function]' ||
  3012. (typeof fn === 'function' && string !== '[object RegExp]') ||
  3013. (typeof window !== 'undefined' &&
  3014. // IE8 and below
  3015. (fn === window.setTimeout ||
  3016. fn === window.alert ||
  3017. fn === window.confirm ||
  3018. fn === window.prompt))
  3019. };
  3020. },{}],34:[function(_dereq_,module,exports){
  3021. 'use strict';
  3022. module.exports = function (x) {
  3023. var type = typeof x;
  3024. return x !== null && (type === 'object' || type === 'function');
  3025. };
  3026. },{}],35:[function(_dereq_,module,exports){
  3027. var toString = {}.toString;
  3028. module.exports = Array.isArray || function (arr) {
  3029. return toString.call(arr) == '[object Array]';
  3030. };
  3031. },{}],36:[function(_dereq_,module,exports){
  3032. var wordWrap = _dereq_('word-wrapper')
  3033. var xtend = _dereq_('xtend')
  3034. var number = _dereq_('as-number')
  3035. var X_HEIGHTS = ['x', 'e', 'a', 'o', 'n', 's', 'r', 'c', 'u', 'm', 'v', 'w', 'z']
  3036. var M_WIDTHS = ['m', 'w']
  3037. var CAP_HEIGHTS = ['H', 'I', 'N', 'E', 'F', 'K', 'L', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
  3038. var TAB_ID = '\t'.charCodeAt(0)
  3039. var SPACE_ID = ' '.charCodeAt(0)
  3040. var ALIGN_LEFT = 0,
  3041. ALIGN_CENTER = 1,
  3042. ALIGN_RIGHT = 2
  3043. module.exports = function createLayout(opt) {
  3044. return new TextLayout(opt)
  3045. }
  3046. function TextLayout(opt) {
  3047. this.glyphs = []
  3048. this._measure = this.computeMetrics.bind(this)
  3049. this.update(opt)
  3050. }
  3051. TextLayout.prototype.update = function(opt) {
  3052. opt = xtend({
  3053. measure: this._measure
  3054. }, opt)
  3055. this._opt = opt
  3056. this._opt.tabSize = number(this._opt.tabSize, 4)
  3057. if (!opt.font)
  3058. throw new Error('must provide a valid bitmap font')
  3059. var glyphs = this.glyphs
  3060. var text = opt.text||''
  3061. var font = opt.font
  3062. this._setupSpaceGlyphs(font)
  3063. var lines = wordWrap.lines(text, opt)
  3064. var minWidth = opt.width || 0
  3065. //clear glyphs
  3066. glyphs.length = 0
  3067. //get max line width
  3068. var maxLineWidth = lines.reduce(function(prev, line) {
  3069. return Math.max(prev, line.width, minWidth)
  3070. }, 0)
  3071. //the pen position
  3072. var x = 0
  3073. var y = 0
  3074. var lineHeight = number(opt.lineHeight, font.common.lineHeight)
  3075. var baseline = font.common.base
  3076. var descender = lineHeight-baseline
  3077. var letterSpacing = opt.letterSpacing || 0
  3078. var height = lineHeight * lines.length - descender
  3079. var align = getAlignType(this._opt.align)
  3080. //draw text along baseline
  3081. y -= height
  3082. //the metrics for this text layout
  3083. this._width = maxLineWidth
  3084. this._height = height
  3085. this._descender = lineHeight - baseline
  3086. this._baseline = baseline
  3087. this._xHeight = getXHeight(font)
  3088. this._capHeight = getCapHeight(font)
  3089. this._lineHeight = lineHeight
  3090. this._ascender = lineHeight - descender - this._xHeight
  3091. //layout each glyph
  3092. var self = this
  3093. lines.forEach(function(line, lineIndex) {
  3094. var start = line.start
  3095. var end = line.end
  3096. var lineWidth = line.width
  3097. var lastGlyph
  3098. //for each glyph in that line...
  3099. for (var i=start; i<end; i++) {
  3100. var id = text.charCodeAt(i)
  3101. var glyph = self.getGlyph(font, id)
  3102. if (glyph) {
  3103. if (lastGlyph)
  3104. x += getKerning(font, lastGlyph.id, glyph.id)
  3105. var tx = x
  3106. if (align === ALIGN_CENTER)
  3107. tx += (maxLineWidth-lineWidth)/2
  3108. else if (align === ALIGN_RIGHT)
  3109. tx += (maxLineWidth-lineWidth)
  3110. glyphs.push({
  3111. position: [tx, y],
  3112. data: glyph,
  3113. index: i,
  3114. line: lineIndex
  3115. })
  3116. //move pen forward
  3117. x += glyph.xadvance + letterSpacing
  3118. lastGlyph = glyph
  3119. }
  3120. }
  3121. //next line down
  3122. y += lineHeight
  3123. x = 0
  3124. })
  3125. this._linesTotal = lines.length;
  3126. }
  3127. TextLayout.prototype._setupSpaceGlyphs = function(font) {
  3128. //These are fallbacks, when the font doesn't include
  3129. //' ' or '\t' glyphs
  3130. this._fallbackSpaceGlyph = null
  3131. this._fallbackTabGlyph = null
  3132. if (!font.chars || font.chars.length === 0)
  3133. return
  3134. //try to get space glyph
  3135. //then fall back to the 'm' or 'w' glyphs
  3136. //then fall back to the first glyph available
  3137. var space = getGlyphById(font, SPACE_ID)
  3138. || getMGlyph(font)
  3139. || font.chars[0]
  3140. //and create a fallback for tab
  3141. var tabWidth = this._opt.tabSize * space.xadvance
  3142. this._fallbackSpaceGlyph = space
  3143. this._fallbackTabGlyph = xtend(space, {
  3144. x: 0, y: 0, xadvance: tabWidth, id: TAB_ID,
  3145. xoffset: 0, yoffset: 0, width: 0, height: 0
  3146. })
  3147. }
  3148. TextLayout.prototype.getGlyph = function(font, id) {
  3149. var glyph = getGlyphById(font, id)
  3150. if (glyph)
  3151. return glyph
  3152. else if (id === TAB_ID)
  3153. return this._fallbackTabGlyph
  3154. else if (id === SPACE_ID)
  3155. return this._fallbackSpaceGlyph
  3156. return null
  3157. }
  3158. TextLayout.prototype.computeMetrics = function(text, start, end, width) {
  3159. var letterSpacing = this._opt.letterSpacing || 0
  3160. var font = this._opt.font
  3161. var curPen = 0
  3162. var curWidth = 0
  3163. var count = 0
  3164. var glyph
  3165. var lastGlyph
  3166. if (!font.chars || font.chars.length === 0) {
  3167. return {
  3168. start: start,
  3169. end: start,
  3170. width: 0
  3171. }
  3172. }
  3173. end = Math.min(text.length, end)
  3174. for (var i=start; i < end; i++) {
  3175. var id = text.charCodeAt(i)
  3176. var glyph = this.getGlyph(font, id)
  3177. if (glyph) {
  3178. //move pen forward
  3179. var xoff = glyph.xoffset
  3180. var kern = lastGlyph ? getKerning(font, lastGlyph.id, glyph.id) : 0
  3181. curPen += kern
  3182. var nextPen = curPen + glyph.xadvance + letterSpacing
  3183. var nextWidth = curPen + glyph.width
  3184. //we've hit our limit; we can't move onto the next glyph
  3185. if (nextWidth >= width || nextPen >= width)
  3186. break
  3187. //otherwise continue along our line
  3188. curPen = nextPen
  3189. curWidth = nextWidth
  3190. lastGlyph = glyph
  3191. }
  3192. count++
  3193. }
  3194. //make sure rightmost edge lines up with rendered glyphs
  3195. if (lastGlyph)
  3196. curWidth += lastGlyph.xoffset
  3197. return {
  3198. start: start,
  3199. end: start + count,
  3200. width: curWidth
  3201. }
  3202. }
  3203. //getters for the private vars
  3204. ;['width', 'height',
  3205. 'descender', 'ascender',
  3206. 'xHeight', 'baseline',
  3207. 'capHeight',
  3208. 'lineHeight' ].forEach(addGetter)
  3209. function addGetter(name) {
  3210. Object.defineProperty(TextLayout.prototype, name, {
  3211. get: wrapper(name),
  3212. configurable: true
  3213. })
  3214. }
  3215. //create lookups for private vars
  3216. function wrapper(name) {
  3217. return (new Function([
  3218. 'return function '+name+'() {',
  3219. ' return this._'+name,
  3220. '}'
  3221. ].join('\n')))()
  3222. }
  3223. function getGlyphById(font, id) {
  3224. if (!font.chars || font.chars.length === 0)
  3225. return null
  3226. var glyphIdx = findChar(font.chars, id)
  3227. if (glyphIdx >= 0)
  3228. return font.chars[glyphIdx]
  3229. return null
  3230. }
  3231. function getXHeight(font) {
  3232. for (var i=0; i<X_HEIGHTS.length; i++) {
  3233. var id = X_HEIGHTS[i].charCodeAt(0)
  3234. var idx = findChar(font.chars, id)
  3235. if (idx >= 0)
  3236. return font.chars[idx].height
  3237. }
  3238. return 0
  3239. }
  3240. function getMGlyph(font) {
  3241. for (var i=0; i<M_WIDTHS.length; i++) {
  3242. var id = M_WIDTHS[i].charCodeAt(0)
  3243. var idx = findChar(font.chars, id)
  3244. if (idx >= 0)
  3245. return font.chars[idx]
  3246. }
  3247. return 0
  3248. }
  3249. function getCapHeight(font) {
  3250. for (var i=0; i<CAP_HEIGHTS.length; i++) {
  3251. var id = CAP_HEIGHTS[i].charCodeAt(0)
  3252. var idx = findChar(font.chars, id)
  3253. if (idx >= 0)
  3254. return font.chars[idx].height
  3255. }
  3256. return 0
  3257. }
  3258. function getKerning(font, left, right) {
  3259. if (!font.kernings || font.kernings.length === 0)
  3260. return 0
  3261. var table = font.kernings
  3262. for (var i=0; i<table.length; i++) {
  3263. var kern = table[i]
  3264. if (kern.first === left && kern.second === right)
  3265. return kern.amount
  3266. }
  3267. return 0
  3268. }
  3269. function getAlignType(align) {
  3270. if (align === 'center')
  3271. return ALIGN_CENTER
  3272. else if (align === 'right')
  3273. return ALIGN_RIGHT
  3274. return ALIGN_LEFT
  3275. }
  3276. function findChar (array, value, start) {
  3277. start = start || 0
  3278. for (var i = start; i < array.length; i++) {
  3279. if (array[i].id === value) {
  3280. return i
  3281. }
  3282. }
  3283. return -1
  3284. }
  3285. },{"as-number":2,"word-wrapper":69,"xtend":72}],37:[function(_dereq_,module,exports){
  3286. (function (Buffer){
  3287. var xhr = _dereq_('xhr')
  3288. var noop = function(){}
  3289. var parseASCII = _dereq_('parse-bmfont-ascii')
  3290. var parseXML = _dereq_('parse-bmfont-xml')
  3291. var readBinary = _dereq_('parse-bmfont-binary')
  3292. var isBinaryFormat = _dereq_('./lib/is-binary')
  3293. var xtend = _dereq_('xtend')
  3294. var xml2 = (function hasXML2() {
  3295. return self.XMLHttpRequest && "withCredentials" in new XMLHttpRequest
  3296. })()
  3297. module.exports = function(opt, cb) {
  3298. cb = typeof cb === 'function' ? cb : noop
  3299. if (typeof opt === 'string')
  3300. opt = { uri: opt }
  3301. else if (!opt)
  3302. opt = {}
  3303. var expectBinary = opt.binary
  3304. if (expectBinary)
  3305. opt = getBinaryOpts(opt)
  3306. xhr(opt, function(err, res, body) {
  3307. if (err)
  3308. return cb(err)
  3309. if (!/^2/.test(res.statusCode))
  3310. return cb(new Error('http status code: '+res.statusCode))
  3311. if (!body)
  3312. return cb(new Error('no body result'))
  3313. var binary = false
  3314. //if the response type is an array buffer,
  3315. //we need to convert it into a regular Buffer object
  3316. if (isArrayBuffer(body)) {
  3317. var array = new Uint8Array(body)
  3318. body = new Buffer(array, 'binary')
  3319. }
  3320. //now check the string/Buffer response
  3321. //and see if it has a binary BMF header
  3322. if (isBinaryFormat(body)) {
  3323. binary = true
  3324. //if we have a string, turn it into a Buffer
  3325. if (typeof body === 'string')
  3326. body = new Buffer(body, 'binary')
  3327. }
  3328. //we are not parsing a binary format, just ASCII/XML/etc
  3329. if (!binary) {
  3330. //might still be a buffer if responseType is 'arraybuffer'
  3331. if (Buffer.isBuffer(body))
  3332. body = body.toString(opt.encoding)
  3333. body = body.trim()
  3334. }
  3335. var result
  3336. try {
  3337. var type = res.headers['content-type']
  3338. if (binary)
  3339. result = readBinary(body)
  3340. else if (/json/.test(type) || body.charAt(0) === '{')
  3341. result = JSON.parse(body)
  3342. else if (/xml/.test(type) || body.charAt(0) === '<')
  3343. result = parseXML(body)
  3344. else
  3345. result = parseASCII(body)
  3346. } catch (e) {
  3347. cb(new Error('error parsing font '+e.message))
  3348. cb = noop
  3349. }
  3350. cb(null, result)
  3351. })
  3352. }
  3353. function isArrayBuffer(arr) {
  3354. var str = Object.prototype.toString
  3355. return str.call(arr) === '[object ArrayBuffer]'
  3356. }
  3357. function getBinaryOpts(opt) {
  3358. //IE10+ and other modern browsers support array buffers
  3359. if (xml2)
  3360. return xtend(opt, { responseType: 'arraybuffer' })
  3361. if (typeof self.XMLHttpRequest === 'undefined')
  3362. throw new Error('your browser does not support XHR loading')
  3363. //IE9 and XML1 browsers could still use an override
  3364. var req = new self.XMLHttpRequest()
  3365. req.overrideMimeType('text/plain; charset=x-user-defined')
  3366. return xtend({
  3367. xhr: req
  3368. }, opt)
  3369. }
  3370. }).call(this,_dereq_("buffer").Buffer)
  3371. },{"./lib/is-binary":38,"buffer":6,"parse-bmfont-ascii":43,"parse-bmfont-binary":44,"parse-bmfont-xml":45,"xhr":70,"xtend":72}],38:[function(_dereq_,module,exports){
  3372. (function (Buffer){
  3373. var equal = _dereq_('buffer-equal')
  3374. var HEADER = new Buffer([66, 77, 70, 3])
  3375. module.exports = function(buf) {
  3376. if (typeof buf === 'string')
  3377. return buf.substring(0, 3) === 'BMF'
  3378. return buf.length > 4 && equal(buf.slice(0, 4), HEADER)
  3379. }
  3380. }).call(this,_dereq_("buffer").Buffer)
  3381. },{"buffer":6,"buffer-equal":5}],39:[function(_dereq_,module,exports){
  3382. /*
  3383. object-assign
  3384. (c) Sindre Sorhus
  3385. @license MIT
  3386. */
  3387. 'use strict';
  3388. /* eslint-disable no-unused-vars */
  3389. var getOwnPropertySymbols = Object.getOwnPropertySymbols;
  3390. var hasOwnProperty = Object.prototype.hasOwnProperty;
  3391. var propIsEnumerable = Object.prototype.propertyIsEnumerable;
  3392. function toObject(val) {
  3393. if (val === null || val === undefined) {
  3394. throw new TypeError('Object.assign cannot be called with null or undefined');
  3395. }
  3396. return Object(val);
  3397. }
  3398. function shouldUseNative() {
  3399. try {
  3400. if (!Object.assign) {
  3401. return false;
  3402. }
  3403. // Detect buggy property enumeration order in older V8 versions.
  3404. // https://bugs.chromium.org/p/v8/issues/detail?id=4118
  3405. var test1 = new String('abc'); // eslint-disable-line no-new-wrappers
  3406. test1[5] = 'de';
  3407. if (Object.getOwnPropertyNames(test1)[0] === '5') {
  3408. return false;
  3409. }
  3410. // https://bugs.chromium.org/p/v8/issues/detail?id=3056
  3411. var test2 = {};
  3412. for (var i = 0; i < 10; i++) {
  3413. test2['_' + String.fromCharCode(i)] = i;
  3414. }
  3415. var order2 = Object.getOwnPropertyNames(test2).map(function (n) {
  3416. return test2[n];
  3417. });
  3418. if (order2.join('') !== '0123456789') {
  3419. return false;
  3420. }
  3421. // https://bugs.chromium.org/p/v8/issues/detail?id=3056
  3422. var test3 = {};
  3423. 'abcdefghijklmnopqrst'.split('').forEach(function (letter) {
  3424. test3[letter] = letter;
  3425. });
  3426. if (Object.keys(Object.assign({}, test3)).join('') !==
  3427. 'abcdefghijklmnopqrst') {
  3428. return false;
  3429. }
  3430. return true;
  3431. } catch (err) {
  3432. // We don't expect any of the above to throw, but better to be safe.
  3433. return false;
  3434. }
  3435. }
  3436. module.exports = shouldUseNative() ? Object.assign : function (target, source) {
  3437. var from;
  3438. var to = toObject(target);
  3439. var symbols;
  3440. for (var s = 1; s < arguments.length; s++) {
  3441. from = Object(arguments[s]);
  3442. for (var key in from) {
  3443. if (hasOwnProperty.call(from, key)) {
  3444. to[key] = from[key];
  3445. }
  3446. }
  3447. if (getOwnPropertySymbols) {
  3448. symbols = getOwnPropertySymbols(from);
  3449. for (var i = 0; i < symbols.length; i++) {
  3450. if (propIsEnumerable.call(from, symbols[i])) {
  3451. to[symbols[i]] = from[symbols[i]];
  3452. }
  3453. }
  3454. }
  3455. }
  3456. return to;
  3457. };
  3458. },{}],40:[function(_dereq_,module,exports){
  3459. 'use strict';
  3460. var keysShim;
  3461. if (!Object.keys) {
  3462. // modified from https://github.com/es-shims/es5-shim
  3463. var has = Object.prototype.hasOwnProperty;
  3464. var toStr = Object.prototype.toString;
  3465. var isArgs = _dereq_('./isArguments'); // eslint-disable-line global-require
  3466. var isEnumerable = Object.prototype.propertyIsEnumerable;
  3467. var hasDontEnumBug = !isEnumerable.call({ toString: null }, 'toString');
  3468. var hasProtoEnumBug = isEnumerable.call(function () {}, 'prototype');
  3469. var dontEnums = [
  3470. 'toString',
  3471. 'toLocaleString',
  3472. 'valueOf',
  3473. 'hasOwnProperty',
  3474. 'isPrototypeOf',
  3475. 'propertyIsEnumerable',
  3476. 'constructor'
  3477. ];
  3478. var equalsConstructorPrototype = function (o) {
  3479. var ctor = o.constructor;
  3480. return ctor && ctor.prototype === o;
  3481. };
  3482. var excludedKeys = {
  3483. $applicationCache: true,
  3484. $console: true,
  3485. $external: true,
  3486. $frame: true,
  3487. $frameElement: true,
  3488. $frames: true,
  3489. $innerHeight: true,
  3490. $innerWidth: true,
  3491. $onmozfullscreenchange: true,
  3492. $onmozfullscreenerror: true,
  3493. $outerHeight: true,
  3494. $outerWidth: true,
  3495. $pageXOffset: true,
  3496. $pageYOffset: true,
  3497. $parent: true,
  3498. $scrollLeft: true,
  3499. $scrollTop: true,
  3500. $scrollX: true,
  3501. $scrollY: true,
  3502. $self: true,
  3503. $webkitIndexedDB: true,
  3504. $webkitStorageInfo: true,
  3505. $window: true
  3506. };
  3507. var hasAutomationEqualityBug = (function () {
  3508. /* global window */
  3509. if (typeof window === 'undefined') { return false; }
  3510. for (var k in window) {
  3511. try {
  3512. if (!excludedKeys['$' + k] && has.call(window, k) && window[k] !== null && typeof window[k] === 'object') {
  3513. try {
  3514. equalsConstructorPrototype(window[k]);
  3515. } catch (e) {
  3516. return true;
  3517. }
  3518. }
  3519. } catch (e) {
  3520. return true;
  3521. }
  3522. }
  3523. return false;
  3524. }());
  3525. var equalsConstructorPrototypeIfNotBuggy = function (o) {
  3526. /* global window */
  3527. if (typeof window === 'undefined' || !hasAutomationEqualityBug) {
  3528. return equalsConstructorPrototype(o);
  3529. }
  3530. try {
  3531. return equalsConstructorPrototype(o);
  3532. } catch (e) {
  3533. return false;
  3534. }
  3535. };
  3536. keysShim = function keys(object) {
  3537. var isObject = object !== null && typeof object === 'object';
  3538. var isFunction = toStr.call(object) === '[object Function]';
  3539. var isArguments = isArgs(object);
  3540. var isString = isObject && toStr.call(object) === '[object String]';
  3541. var theKeys = [];
  3542. if (!isObject && !isFunction && !isArguments) {
  3543. throw new TypeError('Object.keys called on a non-object');
  3544. }
  3545. var skipProto = hasProtoEnumBug && isFunction;
  3546. if (isString && object.length > 0 && !has.call(object, 0)) {
  3547. for (var i = 0; i < object.length; ++i) {
  3548. theKeys.push(String(i));
  3549. }
  3550. }
  3551. if (isArguments && object.length > 0) {
  3552. for (var j = 0; j < object.length; ++j) {
  3553. theKeys.push(String(j));
  3554. }
  3555. } else {
  3556. for (var name in object) {
  3557. if (!(skipProto && name === 'prototype') && has.call(object, name)) {
  3558. theKeys.push(String(name));
  3559. }
  3560. }
  3561. }
  3562. if (hasDontEnumBug) {
  3563. var skipConstructor = equalsConstructorPrototypeIfNotBuggy(object);
  3564. for (var k = 0; k < dontEnums.length; ++k) {
  3565. if (!(skipConstructor && dontEnums[k] === 'constructor') && has.call(object, dontEnums[k])) {
  3566. theKeys.push(dontEnums[k]);
  3567. }
  3568. }
  3569. }
  3570. return theKeys;
  3571. };
  3572. }
  3573. module.exports = keysShim;
  3574. },{"./isArguments":42}],41:[function(_dereq_,module,exports){
  3575. 'use strict';
  3576. var slice = Array.prototype.slice;
  3577. var isArgs = _dereq_('./isArguments');
  3578. var origKeys = Object.keys;
  3579. var keysShim = origKeys ? function keys(o) { return origKeys(o); } : _dereq_('./implementation');
  3580. var originalKeys = Object.keys;
  3581. keysShim.shim = function shimObjectKeys() {
  3582. if (Object.keys) {
  3583. var keysWorksWithArguments = (function () {
  3584. // Safari 5.0 bug
  3585. var args = Object.keys(arguments);
  3586. return args && args.length === arguments.length;
  3587. }(1, 2));
  3588. if (!keysWorksWithArguments) {
  3589. Object.keys = function keys(object) { // eslint-disable-line func-name-matching
  3590. if (isArgs(object)) {
  3591. return originalKeys(slice.call(object));
  3592. }
  3593. return originalKeys(object);
  3594. };
  3595. }
  3596. } else {
  3597. Object.keys = keysShim;
  3598. }
  3599. return Object.keys || keysShim;
  3600. };
  3601. module.exports = keysShim;
  3602. },{"./implementation":40,"./isArguments":42}],42:[function(_dereq_,module,exports){
  3603. 'use strict';
  3604. var toStr = Object.prototype.toString;
  3605. module.exports = function isArguments(value) {
  3606. var str = toStr.call(value);
  3607. var isArgs = str === '[object Arguments]';
  3608. if (!isArgs) {
  3609. isArgs = str !== '[object Array]' &&
  3610. value !== null &&
  3611. typeof value === 'object' &&
  3612. typeof value.length === 'number' &&
  3613. value.length >= 0 &&
  3614. toStr.call(value.callee) === '[object Function]';
  3615. }
  3616. return isArgs;
  3617. };
  3618. },{}],43:[function(_dereq_,module,exports){
  3619. module.exports = function parseBMFontAscii(data) {
  3620. if (!data)
  3621. throw new Error('no data provided')
  3622. data = data.toString().trim()
  3623. var output = {
  3624. pages: [],
  3625. chars: [],
  3626. kernings: []
  3627. }
  3628. var lines = data.split(/\r\n?|\n/g)
  3629. if (lines.length === 0)
  3630. throw new Error('no data in BMFont file')
  3631. for (var i = 0; i < lines.length; i++) {
  3632. var lineData = splitLine(lines[i], i)
  3633. if (!lineData) //skip empty lines
  3634. continue
  3635. if (lineData.key === 'page') {
  3636. if (typeof lineData.data.id !== 'number')
  3637. throw new Error('malformed file at line ' + i + ' -- needs page id=N')
  3638. if (typeof lineData.data.file !== 'string')
  3639. throw new Error('malformed file at line ' + i + ' -- needs page file="path"')
  3640. output.pages[lineData.data.id] = lineData.data.file
  3641. } else if (lineData.key === 'chars' || lineData.key === 'kernings') {
  3642. //... do nothing for these two ...
  3643. } else if (lineData.key === 'char') {
  3644. output.chars.push(lineData.data)
  3645. } else if (lineData.key === 'kerning') {
  3646. output.kernings.push(lineData.data)
  3647. } else {
  3648. output[lineData.key] = lineData.data
  3649. }
  3650. }
  3651. return output
  3652. }
  3653. function splitLine(line, idx) {
  3654. line = line.replace(/\t+/g, ' ').trim()
  3655. if (!line)
  3656. return null
  3657. var space = line.indexOf(' ')
  3658. if (space === -1)
  3659. throw new Error("no named row at line " + idx)
  3660. var key = line.substring(0, space)
  3661. line = line.substring(space + 1)
  3662. //clear "letter" field as it is non-standard and
  3663. //requires additional complexity to parse " / = symbols
  3664. line = line.replace(/letter=[\'\"]\S+[\'\"]/gi, '')
  3665. line = line.split("=")
  3666. line = line.map(function(str) {
  3667. return str.trim().match((/(".*?"|[^"\s]+)+(?=\s*|\s*$)/g))
  3668. })
  3669. var data = []
  3670. for (var i = 0; i < line.length; i++) {
  3671. var dt = line[i]
  3672. if (i === 0) {
  3673. data.push({
  3674. key: dt[0],
  3675. data: ""
  3676. })
  3677. } else if (i === line.length - 1) {
  3678. data[data.length - 1].data = parseData(dt[0])
  3679. } else {
  3680. data[data.length - 1].data = parseData(dt[0])
  3681. data.push({
  3682. key: dt[1],
  3683. data: ""
  3684. })
  3685. }
  3686. }
  3687. var out = {
  3688. key: key,
  3689. data: {}
  3690. }
  3691. data.forEach(function(v) {
  3692. out.data[v.key] = v.data;
  3693. })
  3694. return out
  3695. }
  3696. function parseData(data) {
  3697. if (!data || data.length === 0)
  3698. return ""
  3699. if (data.indexOf('"') === 0 || data.indexOf("'") === 0)
  3700. return data.substring(1, data.length - 1)
  3701. if (data.indexOf(',') !== -1)
  3702. return parseIntList(data)
  3703. return parseInt(data, 10)
  3704. }
  3705. function parseIntList(data) {
  3706. return data.split(',').map(function(val) {
  3707. return parseInt(val, 10)
  3708. })
  3709. }
  3710. },{}],44:[function(_dereq_,module,exports){
  3711. var HEADER = [66, 77, 70]
  3712. module.exports = function readBMFontBinary(buf) {
  3713. if (buf.length < 6)
  3714. throw new Error('invalid buffer length for BMFont')
  3715. var header = HEADER.every(function(byte, i) {
  3716. return buf.readUInt8(i) === byte
  3717. })
  3718. if (!header)
  3719. throw new Error('BMFont missing BMF byte header')
  3720. var i = 3
  3721. var vers = buf.readUInt8(i++)
  3722. if (vers > 3)
  3723. throw new Error('Only supports BMFont Binary v3 (BMFont App v1.10)')
  3724. var target = { kernings: [], chars: [] }
  3725. for (var b=0; b<5; b++)
  3726. i += readBlock(target, buf, i)
  3727. return target
  3728. }
  3729. function readBlock(target, buf, i) {
  3730. if (i > buf.length-1)
  3731. return 0
  3732. var blockID = buf.readUInt8(i++)
  3733. var blockSize = buf.readInt32LE(i)
  3734. i += 4
  3735. switch(blockID) {
  3736. case 1:
  3737. target.info = readInfo(buf, i)
  3738. break
  3739. case 2:
  3740. target.common = readCommon(buf, i)
  3741. break
  3742. case 3:
  3743. target.pages = readPages(buf, i, blockSize)
  3744. break
  3745. case 4:
  3746. target.chars = readChars(buf, i, blockSize)
  3747. break
  3748. case 5:
  3749. target.kernings = readKernings(buf, i, blockSize)
  3750. break
  3751. }
  3752. return 5 + blockSize
  3753. }
  3754. function readInfo(buf, i) {
  3755. var info = {}
  3756. info.size = buf.readInt16LE(i)
  3757. var bitField = buf.readUInt8(i+2)
  3758. info.smooth = (bitField >> 7) & 1
  3759. info.unicode = (bitField >> 6) & 1
  3760. info.italic = (bitField >> 5) & 1
  3761. info.bold = (bitField >> 4) & 1
  3762. //fixedHeight is only mentioned in binary spec
  3763. if ((bitField >> 3) & 1)
  3764. info.fixedHeight = 1
  3765. info.charset = buf.readUInt8(i+3) || ''
  3766. info.stretchH = buf.readUInt16LE(i+4)
  3767. info.aa = buf.readUInt8(i+6)
  3768. info.padding = [
  3769. buf.readInt8(i+7),
  3770. buf.readInt8(i+8),
  3771. buf.readInt8(i+9),
  3772. buf.readInt8(i+10)
  3773. ]
  3774. info.spacing = [
  3775. buf.readInt8(i+11),
  3776. buf.readInt8(i+12)
  3777. ]
  3778. info.outline = buf.readUInt8(i+13)
  3779. info.face = readStringNT(buf, i+14)
  3780. return info
  3781. }
  3782. function readCommon(buf, i) {
  3783. var common = {}
  3784. common.lineHeight = buf.readUInt16LE(i)
  3785. common.base = buf.readUInt16LE(i+2)
  3786. common.scaleW = buf.readUInt16LE(i+4)
  3787. common.scaleH = buf.readUInt16LE(i+6)
  3788. common.pages = buf.readUInt16LE(i+8)
  3789. var bitField = buf.readUInt8(i+10)
  3790. common.packed = 0
  3791. common.alphaChnl = buf.readUInt8(i+11)
  3792. common.redChnl = buf.readUInt8(i+12)
  3793. common.greenChnl = buf.readUInt8(i+13)
  3794. common.blueChnl = buf.readUInt8(i+14)
  3795. return common
  3796. }
  3797. function readPages(buf, i, size) {
  3798. var pages = []
  3799. var text = readNameNT(buf, i)
  3800. var len = text.length+1
  3801. var count = size / len
  3802. for (var c=0; c<count; c++) {
  3803. pages[c] = buf.slice(i, i+text.length).toString('utf8')
  3804. i += len
  3805. }
  3806. return pages
  3807. }
  3808. function readChars(buf, i, blockSize) {
  3809. var chars = []
  3810. var count = blockSize / 20
  3811. for (var c=0; c<count; c++) {
  3812. var char = {}
  3813. var off = c*20
  3814. char.id = buf.readUInt32LE(i + 0 + off)
  3815. char.x = buf.readUInt16LE(i + 4 + off)
  3816. char.y = buf.readUInt16LE(i + 6 + off)
  3817. char.width = buf.readUInt16LE(i + 8 + off)
  3818. char.height = buf.readUInt16LE(i + 10 + off)
  3819. char.xoffset = buf.readInt16LE(i + 12 + off)
  3820. char.yoffset = buf.readInt16LE(i + 14 + off)
  3821. char.xadvance = buf.readInt16LE(i + 16 + off)
  3822. char.page = buf.readUInt8(i + 18 + off)
  3823. char.chnl = buf.readUInt8(i + 19 + off)
  3824. chars[c] = char
  3825. }
  3826. return chars
  3827. }
  3828. function readKernings(buf, i, blockSize) {
  3829. var kernings = []
  3830. var count = blockSize / 10
  3831. for (var c=0; c<count; c++) {
  3832. var kern = {}
  3833. var off = c*10
  3834. kern.first = buf.readUInt32LE(i + 0 + off)
  3835. kern.second = buf.readUInt32LE(i + 4 + off)
  3836. kern.amount = buf.readInt16LE(i + 8 + off)
  3837. kernings[c] = kern
  3838. }
  3839. return kernings
  3840. }
  3841. function readNameNT(buf, offset) {
  3842. var pos=offset
  3843. for (; pos<buf.length; pos++) {
  3844. if (buf[pos] === 0x00)
  3845. break
  3846. }
  3847. return buf.slice(offset, pos)
  3848. }
  3849. function readStringNT(buf, offset) {
  3850. return readNameNT(buf, offset).toString('utf8')
  3851. }
  3852. },{}],45:[function(_dereq_,module,exports){
  3853. var parseAttributes = _dereq_('./parse-attribs')
  3854. var parseFromString = _dereq_('xml-parse-from-string')
  3855. //In some cases element.attribute.nodeName can return
  3856. //all lowercase values.. so we need to map them to the correct
  3857. //case
  3858. var NAME_MAP = {
  3859. scaleh: 'scaleH',
  3860. scalew: 'scaleW',
  3861. stretchh: 'stretchH',
  3862. lineheight: 'lineHeight',
  3863. alphachnl: 'alphaChnl',
  3864. redchnl: 'redChnl',
  3865. greenchnl: 'greenChnl',
  3866. bluechnl: 'blueChnl'
  3867. }
  3868. module.exports = function parse(data) {
  3869. data = data.toString()
  3870. var xmlRoot = parseFromString(data)
  3871. var output = {
  3872. pages: [],
  3873. chars: [],
  3874. kernings: []
  3875. }
  3876. //get config settings
  3877. ;['info', 'common'].forEach(function(key) {
  3878. var element = xmlRoot.getElementsByTagName(key)[0]
  3879. if (element)
  3880. output[key] = parseAttributes(getAttribs(element))
  3881. })
  3882. //get page info
  3883. var pageRoot = xmlRoot.getElementsByTagName('pages')[0]
  3884. if (!pageRoot)
  3885. throw new Error('malformed file -- no <pages> element')
  3886. var pages = pageRoot.getElementsByTagName('page')
  3887. for (var i=0; i<pages.length; i++) {
  3888. var p = pages[i]
  3889. var id = parseInt(p.getAttribute('id'), 10)
  3890. var file = p.getAttribute('file')
  3891. if (isNaN(id))
  3892. throw new Error('malformed file -- page "id" attribute is NaN')
  3893. if (!file)
  3894. throw new Error('malformed file -- needs page "file" attribute')
  3895. output.pages[parseInt(id, 10)] = file
  3896. }
  3897. //get kernings / chars
  3898. ;['chars', 'kernings'].forEach(function(key) {
  3899. var element = xmlRoot.getElementsByTagName(key)[0]
  3900. if (!element)
  3901. return
  3902. var childTag = key.substring(0, key.length-1)
  3903. var children = element.getElementsByTagName(childTag)
  3904. for (var i=0; i<children.length; i++) {
  3905. var child = children[i]
  3906. output[key].push(parseAttributes(getAttribs(child)))
  3907. }
  3908. })
  3909. return output
  3910. }
  3911. function getAttribs(element) {
  3912. var attribs = getAttribList(element)
  3913. return attribs.reduce(function(dict, attrib) {
  3914. var key = mapName(attrib.nodeName)
  3915. dict[key] = attrib.nodeValue
  3916. return dict
  3917. }, {})
  3918. }
  3919. function getAttribList(element) {
  3920. //IE8+ and modern browsers
  3921. var attribs = []
  3922. for (var i=0; i<element.attributes.length; i++)
  3923. attribs.push(element.attributes[i])
  3924. return attribs
  3925. }
  3926. function mapName(nodeName) {
  3927. return NAME_MAP[nodeName.toLowerCase()] || nodeName
  3928. }
  3929. },{"./parse-attribs":46,"xml-parse-from-string":71}],46:[function(_dereq_,module,exports){
  3930. //Some versions of GlyphDesigner have a typo
  3931. //that causes some bugs with parsing.
  3932. //Need to confirm with recent version of the software
  3933. //to see whether this is still an issue or not.
  3934. var GLYPH_DESIGNER_ERROR = 'chasrset'
  3935. module.exports = function parseAttributes(obj) {
  3936. if (GLYPH_DESIGNER_ERROR in obj) {
  3937. obj['charset'] = obj[GLYPH_DESIGNER_ERROR]
  3938. delete obj[GLYPH_DESIGNER_ERROR]
  3939. }
  3940. for (var k in obj) {
  3941. if (k === 'face' || k === 'charset')
  3942. continue
  3943. else if (k === 'padding' || k === 'spacing')
  3944. obj[k] = parseIntList(obj[k])
  3945. else
  3946. obj[k] = parseInt(obj[k], 10)
  3947. }
  3948. return obj
  3949. }
  3950. function parseIntList(data) {
  3951. return data.split(',').map(function(val) {
  3952. return parseInt(val, 10)
  3953. })
  3954. }
  3955. },{}],47:[function(_dereq_,module,exports){
  3956. var trim = _dereq_('string.prototype.trim')
  3957. , forEach = _dereq_('for-each')
  3958. , isArray = function(arg) {
  3959. return Object.prototype.toString.call(arg) === '[object Array]';
  3960. }
  3961. module.exports = function (headers) {
  3962. if (!headers)
  3963. return {}
  3964. var result = {}
  3965. forEach(
  3966. trim(headers).split('\n')
  3967. , function (row) {
  3968. var index = row.indexOf(':')
  3969. , key = trim(row.slice(0, index)).toLowerCase()
  3970. , value = trim(row.slice(index + 1))
  3971. if (typeof(result[key]) === 'undefined') {
  3972. result[key] = value
  3973. } else if (isArray(result[key])) {
  3974. result[key].push(value)
  3975. } else {
  3976. result[key] = [ result[key], value ]
  3977. }
  3978. }
  3979. )
  3980. return result
  3981. }
  3982. },{"for-each":24,"string.prototype.trim":53}],48:[function(_dereq_,module,exports){
  3983. (function (global){
  3984. var performance = global.performance || {};
  3985. var present = (function () {
  3986. var names = ['now', 'webkitNow', 'msNow', 'mozNow', 'oNow'];
  3987. while (names.length) {
  3988. var name = names.shift();
  3989. if (name in performance) {
  3990. return performance[name].bind(performance);
  3991. }
  3992. }
  3993. var dateNow = Date.now || function () { return new Date().getTime(); };
  3994. var navigationStart = (performance.timing || {}).navigationStart || dateNow();
  3995. return function () {
  3996. return dateNow() - navigationStart;
  3997. };
  3998. }());
  3999. present.performanceNow = performance.now;
  4000. present.noConflict = function () {
  4001. performance.now = present.performanceNow;
  4002. };
  4003. present.conflict = function () {
  4004. performance.now = present;
  4005. };
  4006. present.conflict();
  4007. module.exports = present;
  4008. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  4009. },{}],49:[function(_dereq_,module,exports){
  4010. // shim for using process in browser
  4011. var process = module.exports = {};
  4012. // cached from whatever global is present so that test runners that stub it
  4013. // don't break things. But we need to wrap it in a try catch in case it is
  4014. // wrapped in strict mode code which doesn't define any globals. It's inside a
  4015. // function because try/catches deoptimize in certain engines.
  4016. var cachedSetTimeout;
  4017. var cachedClearTimeout;
  4018. function defaultSetTimout() {
  4019. throw new Error('setTimeout has not been defined');
  4020. }
  4021. function defaultClearTimeout () {
  4022. throw new Error('clearTimeout has not been defined');
  4023. }
  4024. (function () {
  4025. try {
  4026. if (typeof setTimeout === 'function') {
  4027. cachedSetTimeout = setTimeout;
  4028. } else {
  4029. cachedSetTimeout = defaultSetTimout;
  4030. }
  4031. } catch (e) {
  4032. cachedSetTimeout = defaultSetTimout;
  4033. }
  4034. try {
  4035. if (typeof clearTimeout === 'function') {
  4036. cachedClearTimeout = clearTimeout;
  4037. } else {
  4038. cachedClearTimeout = defaultClearTimeout;
  4039. }
  4040. } catch (e) {
  4041. cachedClearTimeout = defaultClearTimeout;
  4042. }
  4043. } ())
  4044. function runTimeout(fun) {
  4045. if (cachedSetTimeout === setTimeout) {
  4046. //normal enviroments in sane situations
  4047. return setTimeout(fun, 0);
  4048. }
  4049. // if setTimeout wasn't available but was latter defined
  4050. if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
  4051. cachedSetTimeout = setTimeout;
  4052. return setTimeout(fun, 0);
  4053. }
  4054. try {
  4055. // when when somebody has screwed with setTimeout but no I.E. maddness
  4056. return cachedSetTimeout(fun, 0);
  4057. } catch(e){
  4058. try {
  4059. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  4060. return cachedSetTimeout.call(null, fun, 0);
  4061. } catch(e){
  4062. // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
  4063. return cachedSetTimeout.call(this, fun, 0);
  4064. }
  4065. }
  4066. }
  4067. function runClearTimeout(marker) {
  4068. if (cachedClearTimeout === clearTimeout) {
  4069. //normal enviroments in sane situations
  4070. return clearTimeout(marker);
  4071. }
  4072. // if clearTimeout wasn't available but was latter defined
  4073. if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
  4074. cachedClearTimeout = clearTimeout;
  4075. return clearTimeout(marker);
  4076. }
  4077. try {
  4078. // when when somebody has screwed with setTimeout but no I.E. maddness
  4079. return cachedClearTimeout(marker);
  4080. } catch (e){
  4081. try {
  4082. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  4083. return cachedClearTimeout.call(null, marker);
  4084. } catch (e){
  4085. // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
  4086. // Some versions of I.E. have different rules for clearTimeout vs setTimeout
  4087. return cachedClearTimeout.call(this, marker);
  4088. }
  4089. }
  4090. }
  4091. var queue = [];
  4092. var draining = false;
  4093. var currentQueue;
  4094. var queueIndex = -1;
  4095. function cleanUpNextTick() {
  4096. if (!draining || !currentQueue) {
  4097. return;
  4098. }
  4099. draining = false;
  4100. if (currentQueue.length) {
  4101. queue = currentQueue.concat(queue);
  4102. } else {
  4103. queueIndex = -1;
  4104. }
  4105. if (queue.length) {
  4106. drainQueue();
  4107. }
  4108. }
  4109. function drainQueue() {
  4110. if (draining) {
  4111. return;
  4112. }
  4113. var timeout = runTimeout(cleanUpNextTick);
  4114. draining = true;
  4115. var len = queue.length;
  4116. while(len) {
  4117. currentQueue = queue;
  4118. queue = [];
  4119. while (++queueIndex < len) {
  4120. if (currentQueue) {
  4121. currentQueue[queueIndex].run();
  4122. }
  4123. }
  4124. queueIndex = -1;
  4125. len = queue.length;
  4126. }
  4127. currentQueue = null;
  4128. draining = false;
  4129. runClearTimeout(timeout);
  4130. }
  4131. process.nextTick = function (fun) {
  4132. var args = new Array(arguments.length - 1);
  4133. if (arguments.length > 1) {
  4134. for (var i = 1; i < arguments.length; i++) {
  4135. args[i - 1] = arguments[i];
  4136. }
  4137. }
  4138. queue.push(new Item(fun, args));
  4139. if (queue.length === 1 && !draining) {
  4140. runTimeout(drainQueue);
  4141. }
  4142. };
  4143. // v8 likes predictible objects
  4144. function Item(fun, array) {
  4145. this.fun = fun;
  4146. this.array = array;
  4147. }
  4148. Item.prototype.run = function () {
  4149. this.fun.apply(null, this.array);
  4150. };
  4151. process.title = 'browser';
  4152. process.browser = true;
  4153. process.env = {};
  4154. process.argv = [];
  4155. process.version = ''; // empty string to avoid regexp issues
  4156. process.versions = {};
  4157. function noop() {}
  4158. process.on = noop;
  4159. process.addListener = noop;
  4160. process.once = noop;
  4161. process.off = noop;
  4162. process.removeListener = noop;
  4163. process.removeAllListeners = noop;
  4164. process.emit = noop;
  4165. process.prependListener = noop;
  4166. process.prependOnceListener = noop;
  4167. process.listeners = function (name) { return [] }
  4168. process.binding = function (name) {
  4169. throw new Error('process.binding is not supported');
  4170. };
  4171. process.cwd = function () { return '/' };
  4172. process.chdir = function (dir) {
  4173. throw new Error('process.chdir is not supported');
  4174. };
  4175. process.umask = function() { return 0; };
  4176. },{}],50:[function(_dereq_,module,exports){
  4177. (function (setImmediate){
  4178. (function(root) {
  4179. // Store setTimeout reference so promise-polyfill will be unaffected by
  4180. // other code modifying setTimeout (like sinon.useFakeTimers())
  4181. var setTimeoutFunc = setTimeout;
  4182. // Use polyfill for setImmediate for performance gains
  4183. var asap = (typeof setImmediate === 'function' && setImmediate) ||
  4184. function(fn) { setTimeoutFunc(fn, 1); };
  4185. // Polyfill for Function.prototype.bind
  4186. function bind(fn, thisArg) {
  4187. return function() {
  4188. fn.apply(thisArg, arguments);
  4189. }
  4190. }
  4191. var isArray = Array.isArray || function(value) { return Object.prototype.toString.call(value) === "[object Array]" };
  4192. function Promise(fn) {
  4193. if (typeof this !== 'object') throw new TypeError('Promises must be constructed via new');
  4194. if (typeof fn !== 'function') throw new TypeError('not a function');
  4195. this._state = null;
  4196. this._value = null;
  4197. this._deferreds = []
  4198. doResolve(fn, bind(resolve, this), bind(reject, this))
  4199. }
  4200. function handle(deferred) {
  4201. var me = this;
  4202. if (this._state === null) {
  4203. this._deferreds.push(deferred);
  4204. return
  4205. }
  4206. asap(function() {
  4207. var cb = me._state ? deferred.onFulfilled : deferred.onRejected
  4208. if (cb === null) {
  4209. (me._state ? deferred.resolve : deferred.reject)(me._value);
  4210. return;
  4211. }
  4212. var ret;
  4213. try {
  4214. ret = cb(me._value);
  4215. }
  4216. catch (e) {
  4217. deferred.reject(e);
  4218. return;
  4219. }
  4220. deferred.resolve(ret);
  4221. })
  4222. }
  4223. function resolve(newValue) {
  4224. try { //Promise Resolution Procedure: https://github.com/promises-aplus/promises-spec#the-promise-resolution-procedure
  4225. if (newValue === this) throw new TypeError('A promise cannot be resolved with itself.');
  4226. if (newValue && (typeof newValue === 'object' || typeof newValue === 'function')) {
  4227. var then = newValue.then;
  4228. if (typeof then === 'function') {
  4229. doResolve(bind(then, newValue), bind(resolve, this), bind(reject, this));
  4230. return;
  4231. }
  4232. }
  4233. this._state = true;
  4234. this._value = newValue;
  4235. finale.call(this);
  4236. } catch (e) { reject.call(this, e); }
  4237. }
  4238. function reject(newValue) {
  4239. this._state = false;
  4240. this._value = newValue;
  4241. finale.call(this);
  4242. }
  4243. function finale() {
  4244. for (var i = 0, len = this._deferreds.length; i < len; i++) {
  4245. handle.call(this, this._deferreds[i]);
  4246. }
  4247. this._deferreds = null;
  4248. }
  4249. function Handler(onFulfilled, onRejected, resolve, reject){
  4250. this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null;
  4251. this.onRejected = typeof onRejected === 'function' ? onRejected : null;
  4252. this.resolve = resolve;
  4253. this.reject = reject;
  4254. }
  4255. /**
  4256. * Take a potentially misbehaving resolver function and make sure
  4257. * onFulfilled and onRejected are only called once.
  4258. *
  4259. * Makes no guarantees about asynchrony.
  4260. */
  4261. function doResolve(fn, onFulfilled, onRejected) {
  4262. var done = false;
  4263. try {
  4264. fn(function (value) {
  4265. if (done) return;
  4266. done = true;
  4267. onFulfilled(value);
  4268. }, function (reason) {
  4269. if (done) return;
  4270. done = true;
  4271. onRejected(reason);
  4272. })
  4273. } catch (ex) {
  4274. if (done) return;
  4275. done = true;
  4276. onRejected(ex);
  4277. }
  4278. }
  4279. Promise.prototype['catch'] = function (onRejected) {
  4280. return this.then(null, onRejected);
  4281. };
  4282. Promise.prototype.then = function(onFulfilled, onRejected) {
  4283. var me = this;
  4284. return new Promise(function(resolve, reject) {
  4285. handle.call(me, new Handler(onFulfilled, onRejected, resolve, reject));
  4286. })
  4287. };
  4288. Promise.all = function () {
  4289. var args = Array.prototype.slice.call(arguments.length === 1 && isArray(arguments[0]) ? arguments[0] : arguments);
  4290. return new Promise(function (resolve, reject) {
  4291. if (args.length === 0) return resolve([]);
  4292. var remaining = args.length;
  4293. function res(i, val) {
  4294. try {
  4295. if (val && (typeof val === 'object' || typeof val === 'function')) {
  4296. var then = val.then;
  4297. if (typeof then === 'function') {
  4298. then.call(val, function (val) { res(i, val) }, reject);
  4299. return;
  4300. }
  4301. }
  4302. args[i] = val;
  4303. if (--remaining === 0) {
  4304. resolve(args);
  4305. }
  4306. } catch (ex) {
  4307. reject(ex);
  4308. }
  4309. }
  4310. for (var i = 0; i < args.length; i++) {
  4311. res(i, args[i]);
  4312. }
  4313. });
  4314. };
  4315. Promise.resolve = function (value) {
  4316. if (value && typeof value === 'object' && value.constructor === Promise) {
  4317. return value;
  4318. }
  4319. return new Promise(function (resolve) {
  4320. resolve(value);
  4321. });
  4322. };
  4323. Promise.reject = function (value) {
  4324. return new Promise(function (resolve, reject) {
  4325. reject(value);
  4326. });
  4327. };
  4328. Promise.race = function (values) {
  4329. return new Promise(function (resolve, reject) {
  4330. for(var i = 0, len = values.length; i < len; i++) {
  4331. values[i].then(resolve, reject);
  4332. }
  4333. });
  4334. };
  4335. /**
  4336. * Set the immediate function to execute callbacks
  4337. * @param fn {function} Function to execute
  4338. * @private
  4339. */
  4340. Promise._setImmediateFn = function _setImmediateFn(fn) {
  4341. asap = fn;
  4342. };
  4343. if (typeof module !== 'undefined' && module.exports) {
  4344. module.exports = Promise;
  4345. } else if (!root.Promise) {
  4346. root.Promise = Promise;
  4347. }
  4348. })(this);
  4349. }).call(this,_dereq_("timers").setImmediate)
  4350. },{"timers":67}],51:[function(_dereq_,module,exports){
  4351. var dtype = _dereq_('dtype')
  4352. var anArray = _dereq_('an-array')
  4353. var isBuffer = _dereq_('is-buffer')
  4354. var CW = [0, 2, 3]
  4355. var CCW = [2, 1, 3]
  4356. module.exports = function createQuadElements(array, opt) {
  4357. //if user didn't specify an output array
  4358. if (!array || !(anArray(array) || isBuffer(array))) {
  4359. opt = array || {}
  4360. array = null
  4361. }
  4362. if (typeof opt === 'number') //backwards-compatible
  4363. opt = { count: opt }
  4364. else
  4365. opt = opt || {}
  4366. var type = typeof opt.type === 'string' ? opt.type : 'uint16'
  4367. var count = typeof opt.count === 'number' ? opt.count : 1
  4368. var start = (opt.start || 0)
  4369. var dir = opt.clockwise !== false ? CW : CCW,
  4370. a = dir[0],
  4371. b = dir[1],
  4372. c = dir[2]
  4373. var numIndices = count * 6
  4374. var indices = array || new (dtype(type))(numIndices)
  4375. for (var i = 0, j = 0; i < numIndices; i += 6, j += 4) {
  4376. var x = i + start
  4377. indices[x + 0] = j + 0
  4378. indices[x + 1] = j + 1
  4379. indices[x + 2] = j + 2
  4380. indices[x + 3] = j + a
  4381. indices[x + 4] = j + b
  4382. indices[x + 5] = j + c
  4383. }
  4384. return indices
  4385. }
  4386. },{"an-array":1,"dtype":13,"is-buffer":31}],52:[function(_dereq_,module,exports){
  4387. 'use strict';
  4388. var bind = _dereq_('function-bind');
  4389. var ES = _dereq_('es-abstract/es5');
  4390. var replace = bind.call(Function.call, String.prototype.replace);
  4391. /* eslint-disable no-control-regex */
  4392. var leftWhitespace = /^[\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF]+/;
  4393. var rightWhitespace = /[\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF]+$/;
  4394. /* eslint-enable no-control-regex */
  4395. module.exports = function trim() {
  4396. var S = ES.ToString(ES.CheckObjectCoercible(this));
  4397. return replace(replace(S, leftWhitespace, ''), rightWhitespace, '');
  4398. };
  4399. },{"es-abstract/es5":15,"function-bind":26}],53:[function(_dereq_,module,exports){
  4400. 'use strict';
  4401. var bind = _dereq_('function-bind');
  4402. var define = _dereq_('define-properties');
  4403. var implementation = _dereq_('./implementation');
  4404. var getPolyfill = _dereq_('./polyfill');
  4405. var shim = _dereq_('./shim');
  4406. var boundTrim = bind.call(Function.call, getPolyfill());
  4407. define(boundTrim, {
  4408. getPolyfill: getPolyfill,
  4409. implementation: implementation,
  4410. shim: shim
  4411. });
  4412. module.exports = boundTrim;
  4413. },{"./implementation":52,"./polyfill":54,"./shim":55,"define-properties":11,"function-bind":26}],54:[function(_dereq_,module,exports){
  4414. 'use strict';
  4415. var implementation = _dereq_('./implementation');
  4416. var zeroWidthSpace = '\u200b';
  4417. module.exports = function getPolyfill() {
  4418. if (String.prototype.trim && zeroWidthSpace.trim() === zeroWidthSpace) {
  4419. return String.prototype.trim;
  4420. }
  4421. return implementation;
  4422. };
  4423. },{"./implementation":52}],55:[function(_dereq_,module,exports){
  4424. 'use strict';
  4425. var define = _dereq_('define-properties');
  4426. var getPolyfill = _dereq_('./polyfill');
  4427. module.exports = function shimStringTrim() {
  4428. var polyfill = getPolyfill();
  4429. define(String.prototype, { trim: polyfill }, {
  4430. trim: function testTrim() {
  4431. return String.prototype.trim !== polyfill;
  4432. }
  4433. });
  4434. return polyfill;
  4435. };
  4436. },{"./polyfill":54,"define-properties":11}],56:[function(_dereq_,module,exports){
  4437. /*
  4438. * anime.js v3.0.0
  4439. * (c) 2019 Julian Garnier
  4440. * Released under the MIT license
  4441. * animejs.com
  4442. */
  4443. 'use strict';
  4444. // Defaults
  4445. var defaultInstanceSettings = {
  4446. update: null,
  4447. begin: null,
  4448. loopBegin: null,
  4449. changeBegin: null,
  4450. change: null,
  4451. changeComplete: null,
  4452. loopComplete: null,
  4453. complete: null,
  4454. loop: 1,
  4455. direction: 'normal',
  4456. autoplay: true,
  4457. timelineOffset: 0
  4458. };
  4459. var defaultTweenSettings = {
  4460. duration: 1000,
  4461. delay: 0,
  4462. endDelay: 0,
  4463. easing: 'easeOutElastic(1, .5)',
  4464. round: 0
  4465. };
  4466. var validTransforms = ['translateX', 'translateY', 'translateZ', 'rotate', 'rotateX', 'rotateY', 'rotateZ', 'scale', 'scaleX', 'scaleY', 'scaleZ', 'skew', 'skewX', 'skewY', 'perspective'];
  4467. // Caching
  4468. var cache = {
  4469. CSS: {},
  4470. springs: {}
  4471. };
  4472. // Utils
  4473. function minMax(val, min, max) {
  4474. return Math.min(Math.max(val, min), max);
  4475. }
  4476. function stringContains(str, text) {
  4477. return str.indexOf(text) > -1;
  4478. }
  4479. function applyArguments(func, args) {
  4480. return func.apply(null, args);
  4481. }
  4482. var hexRegex = /(^#[0-9A-F]{6}$)|(^#[0-9A-F]{3}$)/i;
  4483. var rgbPrefixRegex = /^rgb/;
  4484. var hslRegex = /^hsl/;
  4485. var is = {
  4486. arr: function (a) { return Array.isArray(a); },
  4487. obj: function (a) { return stringContains(Object.prototype.toString.call(a), 'Object'); },
  4488. pth: function (a) { return is.obj(a) && a.hasOwnProperty('totalLength'); },
  4489. svg: function (a) { return a instanceof SVGElement; },
  4490. inp: function (a) { return a instanceof HTMLInputElement; },
  4491. dom: function (a) { return a.nodeType || is.svg(a); },
  4492. str: function (a) { return typeof a === 'string'; },
  4493. fnc: function (a) { return typeof a === 'function'; },
  4494. und: function (a) { return typeof a === 'undefined'; },
  4495. hex: function (a) { return hexRegex.test(a); },
  4496. rgb: function (a) { return rgbPrefixRegex.test(a); },
  4497. hsl: function (a) { return hslRegex.test(a); },
  4498. col: function (a) { return (is.hex(a) || is.rgb(a) || is.hsl(a)); },
  4499. key: function (a) { return !defaultInstanceSettings.hasOwnProperty(a) && !defaultTweenSettings.hasOwnProperty(a) && a !== 'targets' && a !== 'keyframes'; }
  4500. };
  4501. // Easings
  4502. var easingFunctionRegex = /\(([^)]+)\)/;
  4503. function parseEasingParameters(string) {
  4504. var match = easingFunctionRegex.exec(string);
  4505. return match ? match[1].split(',').map(function (p) { return parseFloat(p); }) : [];
  4506. }
  4507. // Spring solver inspired by Webkit Copyright © 2016 Apple Inc. All rights reserved. https://webkit.org/demos/spring/spring.js
  4508. function spring(string, duration) {
  4509. var params = parseEasingParameters(string);
  4510. var mass = minMax(is.und(params[0]) ? 1 : params[0], .1, 100);
  4511. var stiffness = minMax(is.und(params[1]) ? 100 : params[1], .1, 100);
  4512. var damping = minMax(is.und(params[2]) ? 10 : params[2], .1, 100);
  4513. var velocity = minMax(is.und(params[3]) ? 0 : params[3], .1, 100);
  4514. var w0 = Math.sqrt(stiffness / mass);
  4515. var zeta = damping / (2 * Math.sqrt(stiffness * mass));
  4516. var wd = zeta < 1 ? w0 * Math.sqrt(1 - zeta * zeta) : 0;
  4517. var a = 1;
  4518. var b = zeta < 1 ? (zeta * w0 + -velocity) / wd : -velocity + w0;
  4519. function solver(t) {
  4520. var progress = duration ? (duration * t) / 1000 : t;
  4521. if (zeta < 1) {
  4522. progress = Math.exp(-progress * zeta * w0) * (a * Math.cos(wd * progress) + b * Math.sin(wd * progress));
  4523. } else {
  4524. progress = (a + b * progress) * Math.exp(-progress * w0);
  4525. }
  4526. if (t === 0 || t === 1) { return t; }
  4527. return 1 - progress;
  4528. }
  4529. function getDuration() {
  4530. var cached = cache.springs[string];
  4531. if (cached) { return cached; }
  4532. var frame = 1/6;
  4533. var elapsed = 0;
  4534. var rest = 0;
  4535. while(true) {
  4536. elapsed += frame;
  4537. if (solver(elapsed) === 1) {
  4538. rest++;
  4539. if (rest >= 16) { break; }
  4540. } else {
  4541. rest = 0;
  4542. }
  4543. }
  4544. var duration = elapsed * frame * 1000;
  4545. cache.springs[string] = duration;
  4546. return duration;
  4547. }
  4548. return duration ? solver : getDuration;
  4549. }
  4550. // Elastic easing adapted from jQueryUI http://api.jqueryui.com/easings/
  4551. function elastic(amplitude, period) {
  4552. if ( amplitude === void 0 ) amplitude = 1;
  4553. if ( period === void 0 ) period = .5;
  4554. var a = minMax(amplitude, 1, 10);
  4555. var p = minMax(period, .1, 2);
  4556. return function (t) {
  4557. return (t === 0 || t === 1) ? t :
  4558. -a * Math.pow(2, 10 * (t - 1)) * Math.sin((((t - 1) - (p / (Math.PI * 2) * Math.asin(1 / a))) * (Math.PI * 2)) / p);
  4559. }
  4560. }
  4561. // Basic steps easing implementation https://developer.mozilla.org/fr/docs/Web/CSS/transition-timing-function
  4562. function steps(steps) {
  4563. if ( steps === void 0 ) steps = 10;
  4564. return function (t) { return Math.round(t * steps) * (1 / steps); };
  4565. }
  4566. // BezierEasing https://github.com/gre/bezier-easing
  4567. var bezier = (function () {
  4568. var kSplineTableSize = 11;
  4569. var kSampleStepSize = 1.0 / (kSplineTableSize - 1.0);
  4570. function A(aA1, aA2) { return 1.0 - 3.0 * aA2 + 3.0 * aA1 }
  4571. function B(aA1, aA2) { return 3.0 * aA2 - 6.0 * aA1 }
  4572. function C(aA1) { return 3.0 * aA1 }
  4573. function calcBezier(aT, aA1, aA2) { return ((A(aA1, aA2) * aT + B(aA1, aA2)) * aT + C(aA1)) * aT }
  4574. function getSlope(aT, aA1, aA2) { return 3.0 * A(aA1, aA2) * aT * aT + 2.0 * B(aA1, aA2) * aT + C(aA1) }
  4575. function binarySubdivide(aX, aA, aB, mX1, mX2) {
  4576. var currentX, currentT, i = 0;
  4577. do {
  4578. currentT = aA + (aB - aA) / 2.0;
  4579. currentX = calcBezier(currentT, mX1, mX2) - aX;
  4580. if (currentX > 0.0) { aB = currentT; } else { aA = currentT; }
  4581. } while (Math.abs(currentX) > 0.0000001 && ++i < 10);
  4582. return currentT;
  4583. }
  4584. function newtonRaphsonIterate(aX, aGuessT, mX1, mX2) {
  4585. for (var i = 0; i < 4; ++i) {
  4586. var currentSlope = getSlope(aGuessT, mX1, mX2);
  4587. if (currentSlope === 0.0) { return aGuessT; }
  4588. var currentX = calcBezier(aGuessT, mX1, mX2) - aX;
  4589. aGuessT -= currentX / currentSlope;
  4590. }
  4591. return aGuessT;
  4592. }
  4593. function bezier(mX1, mY1, mX2, mY2) {
  4594. if (!(0 <= mX1 && mX1 <= 1 && 0 <= mX2 && mX2 <= 1)) { return; }
  4595. var sampleValues = new Float32Array(kSplineTableSize);
  4596. if (mX1 !== mY1 || mX2 !== mY2) {
  4597. for (var i = 0; i < kSplineTableSize; ++i) {
  4598. sampleValues[i] = calcBezier(i * kSampleStepSize, mX1, mX2);
  4599. }
  4600. }
  4601. function getTForX(aX) {
  4602. var intervalStart = 0;
  4603. var currentSample = 1;
  4604. var lastSample = kSplineTableSize - 1;
  4605. for (; currentSample !== lastSample && sampleValues[currentSample] <= aX; ++currentSample) {
  4606. intervalStart += kSampleStepSize;
  4607. }
  4608. --currentSample;
  4609. var dist = (aX - sampleValues[currentSample]) / (sampleValues[currentSample + 1] - sampleValues[currentSample]);
  4610. var guessForT = intervalStart + dist * kSampleStepSize;
  4611. var initialSlope = getSlope(guessForT, mX1, mX2);
  4612. if (initialSlope >= 0.001) {
  4613. return newtonRaphsonIterate(aX, guessForT, mX1, mX2);
  4614. } else if (initialSlope === 0.0) {
  4615. return guessForT;
  4616. } else {
  4617. return binarySubdivide(aX, intervalStart, intervalStart + kSampleStepSize, mX1, mX2);
  4618. }
  4619. }
  4620. return function (x) {
  4621. if (mX1 === mY1 && mX2 === mY2) { return x; }
  4622. if (x === 0 || x === 1) { return x; }
  4623. return calcBezier(getTForX(x), mY1, mY2);
  4624. }
  4625. }
  4626. return bezier;
  4627. })();
  4628. var penner = (function () {
  4629. var names = ['Quad', 'Cubic', 'Quart', 'Quint', 'Sine', 'Expo', 'Circ', 'Back', 'Elastic'];
  4630. // Approximated Penner equations http://matthewlein.com/ceaser/
  4631. var curves = {
  4632. In: [
  4633. [0.550, 0.085, 0.680, 0.530], /* inQuad */
  4634. [0.550, 0.055, 0.675, 0.190], /* inCubic */
  4635. [0.895, 0.030, 0.685, 0.220], /* inQuart */
  4636. [0.755, 0.050, 0.855, 0.060], /* inQuint */
  4637. [0.470, 0.000, 0.745, 0.715], /* inSine */
  4638. [0.950, 0.050, 0.795, 0.035], /* inExpo */
  4639. [0.600, 0.040, 0.980, 0.335], /* inCirc */
  4640. [0.600,-0.280, 0.735, 0.045], /* inBack */
  4641. elastic /* inElastic */
  4642. ],
  4643. Out: [
  4644. [0.250, 0.460, 0.450, 0.940], /* outQuad */
  4645. [0.215, 0.610, 0.355, 1.000], /* outCubic */
  4646. [0.165, 0.840, 0.440, 1.000], /* outQuart */
  4647. [0.230, 1.000, 0.320, 1.000], /* outQuint */
  4648. [0.390, 0.575, 0.565, 1.000], /* outSine */
  4649. [0.190, 1.000, 0.220, 1.000], /* outExpo */
  4650. [0.075, 0.820, 0.165, 1.000], /* outCirc */
  4651. [0.175, 0.885, 0.320, 1.275], /* outBack */
  4652. function (a, p) { return function (t) { return 1 - elastic(a, p)(1 - t); }; } /* outElastic */
  4653. ],
  4654. InOut: [
  4655. [0.455, 0.030, 0.515, 0.955], /* inOutQuad */
  4656. [0.645, 0.045, 0.355, 1.000], /* inOutCubic */
  4657. [0.770, 0.000, 0.175, 1.000], /* inOutQuart */
  4658. [0.860, 0.000, 0.070, 1.000], /* inOutQuint */
  4659. [0.445, 0.050, 0.550, 0.950], /* inOutSine */
  4660. [1.000, 0.000, 0.000, 1.000], /* inOutExpo */
  4661. [0.785, 0.135, 0.150, 0.860], /* inOutCirc */
  4662. [0.680,-0.550, 0.265, 1.550], /* inOutBack */
  4663. function (a, p) { return function (t) { return t < .5 ? elastic(a, p)(t * 2) / 2 : 1 - elastic(a, p)(t * -2 + 2) / 2; }; } /* inOutElastic */
  4664. ]
  4665. };
  4666. var eases = {
  4667. linear: [0.250, 0.250, 0.750, 0.750]
  4668. };
  4669. for (var coords in curves) {
  4670. for (var i = 0, len = curves[coords].length; i < len; i++) {
  4671. eases['ease'+coords+names[i]] = curves[coords][i];
  4672. }
  4673. }
  4674. return eases;
  4675. })();
  4676. function parseEasings(easing, duration) {
  4677. if (is.fnc(easing)) { return easing; }
  4678. var name = easing.split('(')[0];
  4679. var ease = penner[name];
  4680. var args = parseEasingParameters(easing);
  4681. switch (name) {
  4682. case 'spring' : return spring(easing, duration);
  4683. case 'cubicBezier' : return applyArguments(bezier, args);
  4684. case 'steps' : return applyArguments(steps, args);
  4685. default : return is.fnc(ease) ? applyArguments(ease, args) : applyArguments(bezier, ease);
  4686. }
  4687. }
  4688. // Strings
  4689. function selectString(str) {
  4690. try {
  4691. var nodes = document.querySelectorAll(str);
  4692. return nodes;
  4693. } catch(e) {
  4694. return;
  4695. }
  4696. }
  4697. // Arrays
  4698. var auxArrayFilter = [];
  4699. function filterArray(arr, callback) {
  4700. var result = auxArrayFilter;
  4701. var len = arr.length;
  4702. var thisArg = arguments.length >= 2 ? arguments[1] : void 0;
  4703. for (var i = 0; i < len; i++) {
  4704. if (i in arr) {
  4705. var val = arr[i];
  4706. if (callback.call(thisArg, val, i, arr)) {
  4707. result.push(val);
  4708. }
  4709. }
  4710. }
  4711. // arr turns into the auxArray and we return the previously aux array.
  4712. auxArrayFilter = arr;
  4713. auxArrayFilter.length = 0;
  4714. return result;
  4715. }
  4716. function flattenArray (arr, result) {
  4717. if (!result) { result = []; }
  4718. for (var i = 0, length = arr.length; i < length; i++) {
  4719. var value = arr[i];
  4720. if (Array.isArray(value)) {
  4721. flattenArray(value, result);
  4722. } else {
  4723. result.push(value);
  4724. }
  4725. }
  4726. return result;
  4727. }
  4728. function toArray(o) {
  4729. if (is.arr(o)) { return o; }
  4730. if (is.str(o)) { o = selectString(o) || o; }
  4731. if (o instanceof NodeList || o instanceof HTMLCollection) { return [].slice.call(o); }
  4732. return [o];
  4733. }
  4734. function arrayContains(arr, val) {
  4735. return arr.some(function (a) { return a === val; });
  4736. }
  4737. // Objects
  4738. function cloneObject(o) {
  4739. var clone = {};
  4740. for (var p in o) { clone[p] = o[p]; }
  4741. return clone;
  4742. }
  4743. function replaceObjectProps(o1, o2) {
  4744. var o = cloneObject(o1);
  4745. for (var p in o1) { o[p] = o2.hasOwnProperty(p) ? o2[p] : o1[p]; }
  4746. return o;
  4747. }
  4748. function mergeObjects(o1, o2) {
  4749. var o = cloneObject(o1);
  4750. for (var p in o2) { o[p] = is.und(o1[p]) ? o2[p] : o1[p]; }
  4751. return o;
  4752. }
  4753. // Colors
  4754. var rgbRegex = /rgb\((\d+,\s*[\d]+,\s*[\d]+)\)/g;
  4755. function rgbToRgba(rgbValue) {
  4756. var rgb = rgbRegex.exec(rgbValue);
  4757. return rgb ? ("rgba(" + (rgb[1]) + ",1)") : rgbValue;
  4758. }
  4759. var hexToRgbaHexRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
  4760. var hexToRgbaRgbRegex = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i;
  4761. function hexToRgba(hexValue) {
  4762. var hex = hexValue.replace(hexToRgbaHexRegex, function (m, r, g, b) { return r + r + g + g + b + b; } );
  4763. var rgb = hexToRgbaRgbRegex.exec(hex);
  4764. var r = parseInt(rgb[1], 16);
  4765. var g = parseInt(rgb[2], 16);
  4766. var b = parseInt(rgb[3], 16);
  4767. return ("rgba(" + r + "," + g + "," + b + ",1)");
  4768. }
  4769. var hslToRgbaHsl1Regex = /hsl\((\d+),\s*([\d.]+)%,\s*([\d.]+)%\)/g;
  4770. var hslToRgbaHsl2Regex = /hsla\((\d+),\s*([\d.]+)%,\s*([\d.]+)%,\s*([\d.]+)\)/g;
  4771. function hslToRgba(hslValue) {
  4772. var hsl = hslToRgbaHsl1Regex.exec(hslValue) || hslToRgbaHsl2Regex.exec(hslValue);
  4773. var h = parseInt(hsl[1], 10) / 360;
  4774. var s = parseInt(hsl[2], 10) / 100;
  4775. var l = parseInt(hsl[3], 10) / 100;
  4776. var a = hsl[4] || 1;
  4777. function hue2rgb(p, q, t) {
  4778. if (t < 0) { t += 1; }
  4779. if (t > 1) { t -= 1; }
  4780. if (t < 1/6) { return p + (q - p) * 6 * t; }
  4781. if (t < 1/2) { return q; }
  4782. if (t < 2/3) { return p + (q - p) * (2/3 - t) * 6; }
  4783. return p;
  4784. }
  4785. var r, g, b;
  4786. if (s == 0) {
  4787. r = g = b = l;
  4788. } else {
  4789. var q = l < 0.5 ? l * (1 + s) : l + s - l * s;
  4790. var p = 2 * l - q;
  4791. r = hue2rgb(p, q, h + 1/3);
  4792. g = hue2rgb(p, q, h);
  4793. b = hue2rgb(p, q, h - 1/3);
  4794. }
  4795. return ("rgba(" + (r * 255) + "," + (g * 255) + "," + (b * 255) + "," + a + ")");
  4796. }
  4797. function colorToRgb(val) {
  4798. if (is.rgb(val)) { return rgbToRgba(val); }
  4799. if (is.hex(val)) { return hexToRgba(val); }
  4800. if (is.hsl(val)) { return hslToRgba(val); }
  4801. }
  4802. // Units
  4803. var unitRegex = /([\+\-]?[0-9#\.]+)(%|px|pt|em|rem|in|cm|mm|ex|ch|pc|vw|vh|vmin|vmax|deg|rad|turn)?$/;
  4804. function getUnit(val) {
  4805. var split = unitRegex.exec(val);
  4806. if (split) { return split[2]; }
  4807. }
  4808. function getTransformUnit(propName) {
  4809. if (stringContains(propName, 'translate') || propName === 'perspective') { return 'px'; }
  4810. if (stringContains(propName, 'rotate') || stringContains(propName, 'skew')) { return 'deg'; }
  4811. }
  4812. // Values
  4813. function getFunctionValue(val, animatable) {
  4814. if (!is.fnc(val)) { return val; }
  4815. return val(animatable.target, animatable.id, animatable.total);
  4816. }
  4817. function getAttribute(el, prop) {
  4818. return el.getAttribute(prop);
  4819. }
  4820. function convertPxToUnit(el, value, unit) {
  4821. var valueUnit = getUnit(value);
  4822. if (arrayContains([unit, 'deg', 'rad', 'turn'], valueUnit)) { return value; }
  4823. var cached = cache.CSS[value + unit];
  4824. if (!is.und(cached)) { return cached; }
  4825. var baseline = 100;
  4826. var tempEl = document.createElement(el.tagName);
  4827. var parentEl = (el.parentNode && (el.parentNode !== document)) ? el.parentNode : document.body;
  4828. parentEl.appendChild(tempEl);
  4829. tempEl.style.position = 'absolute';
  4830. tempEl.style.width = baseline + unit;
  4831. var factor = baseline / tempEl.offsetWidth;
  4832. parentEl.removeChild(tempEl);
  4833. var convertedUnit = factor * parseFloat(value);
  4834. cache.CSS[value + unit] = convertedUnit;
  4835. return convertedUnit;
  4836. }
  4837. function getCSSValue(el, prop, unit) {
  4838. if (prop in el.style) {
  4839. var uppercasePropName = prop.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();
  4840. var value = el.style[prop] || getComputedStyle(el).getPropertyValue(uppercasePropName) || '0';
  4841. return unit ? convertPxToUnit(el, value, unit) : value;
  4842. }
  4843. }
  4844. function getAnimationType(el, prop) {
  4845. if (is.dom(el) && !is.inp(el) && (getAttribute(el, prop) || (is.svg(el) && el[prop]))) { return 'attribute'; }
  4846. if (is.dom(el) && arrayContains(validTransforms, prop)) { return 'transform'; }
  4847. if (is.dom(el) && (prop !== 'transform' && getCSSValue(el, prop))) { return 'css'; }
  4848. if (el[prop] != null) { return 'object'; }
  4849. }
  4850. var transformRegex = /(\w+)\(([^)]*)\)/g;
  4851. function getElementTransforms(el) {
  4852. if (!is.dom(el)) { return; }
  4853. var str = el.style.transform || '';
  4854. var transforms = new Map();
  4855. var m; while (m = transformRegex.exec(str)) { transforms.set(m[1], m[2]); }
  4856. return transforms;
  4857. }
  4858. function getTransformValue(el, propName, animatable, unit) {
  4859. var defaultVal = stringContains(propName, 'scale') ? 1 : 0 + getTransformUnit(propName);
  4860. var value = getElementTransforms(el).get(propName) || defaultVal;
  4861. if (animatable) {
  4862. animatable.transforms.list.set(propName, value);
  4863. animatable.transforms['last'] = propName;
  4864. }
  4865. return unit ? convertPxToUnit(el, value, unit) : value;
  4866. }
  4867. function getOriginalTargetValue(target, propName, unit, animatable) {
  4868. switch (getAnimationType(target, propName)) {
  4869. case 'transform': return getTransformValue(target, propName, animatable, unit);
  4870. case 'css': return getCSSValue(target, propName, unit);
  4871. case 'attribute': return getAttribute(target, propName);
  4872. default: return target[propName] || 0;
  4873. }
  4874. }
  4875. var operatorRegex = /^(\*=|\+=|-=)/;
  4876. function getRelativeValue(to, from) {
  4877. var operator = operatorRegex.exec(to);
  4878. if (!operator) { return to; }
  4879. var u = getUnit(to) || 0;
  4880. var x = parseFloat(from);
  4881. var y = parseFloat(to.replace(operator[0], ''));
  4882. switch (operator[0][0]) {
  4883. case '+': return x + y + u;
  4884. case '-': return x - y + u;
  4885. case '*': return x * y + u;
  4886. }
  4887. }
  4888. var whitespaceRegex = /\s/g;
  4889. function validateValue(val, unit) {
  4890. if (is.col(val)) { return colorToRgb(val); }
  4891. var originalUnit = getUnit(val);
  4892. var unitLess = originalUnit ? val.substr(0, val.length - originalUnit.length) : val;
  4893. return unit && !whitespaceRegex.test(val) ? unitLess + unit : unitLess;
  4894. }
  4895. // getTotalLength() equivalent for circle, rect, polyline, polygon and line shapes
  4896. // adapted from https://gist.github.com/SebLambla/3e0550c496c236709744
  4897. function getDistance(p1, p2) {
  4898. return Math.sqrt(Math.pow(p2.x - p1.x, 2) + Math.pow(p2.y - p1.y, 2));
  4899. }
  4900. function getCircleLength(el) {
  4901. return Math.PI * 2 * getAttribute(el, 'r');
  4902. }
  4903. function getRectLength(el) {
  4904. return (getAttribute(el, 'width') * 2) + (getAttribute(el, 'height') * 2);
  4905. }
  4906. function getLineLength(el) {
  4907. return getDistance(
  4908. {x: getAttribute(el, 'x1'), y: getAttribute(el, 'y1')},
  4909. {x: getAttribute(el, 'x2'), y: getAttribute(el, 'y2')}
  4910. );
  4911. }
  4912. function getPolylineLength(el) {
  4913. var points = el.points;
  4914. var totalLength = 0;
  4915. var previousPos;
  4916. for (var i = 0 ; i < points.numberOfItems; i++) {
  4917. var currentPos = points.getItem(i);
  4918. if (i > 0) { totalLength += getDistance(previousPos, currentPos); }
  4919. previousPos = currentPos;
  4920. }
  4921. return totalLength;
  4922. }
  4923. function getPolygonLength(el) {
  4924. var points = el.points;
  4925. return getPolylineLength(el) + getDistance(points.getItem(points.numberOfItems - 1), points.getItem(0));
  4926. }
  4927. // Path animation
  4928. function getTotalLength(el) {
  4929. if (el.getTotalLength) { return el.getTotalLength(); }
  4930. switch(el.tagName.toLowerCase()) {
  4931. case 'circle': return getCircleLength(el);
  4932. case 'rect': return getRectLength(el);
  4933. case 'line': return getLineLength(el);
  4934. case 'polyline': return getPolylineLength(el);
  4935. case 'polygon': return getPolygonLength(el);
  4936. }
  4937. }
  4938. function setDashoffset(el) {
  4939. var pathLength = getTotalLength(el);
  4940. el.setAttribute('stroke-dasharray', pathLength);
  4941. return pathLength;
  4942. }
  4943. // Motion path
  4944. function getParentSvgEl(el) {
  4945. var parentEl = el.parentNode;
  4946. while (is.svg(parentEl)) {
  4947. parentEl = parentEl.parentNode;
  4948. if (!is.svg(parentEl.parentNode)) { break; }
  4949. }
  4950. return parentEl;
  4951. }
  4952. function getParentSvg(pathEl, svgData) {
  4953. var svg = svgData || {};
  4954. var parentSvgEl = svg.el || getParentSvgEl(pathEl);
  4955. var rect = parentSvgEl.getBoundingClientRect();
  4956. var viewBoxAttr = getAttribute(parentSvgEl, 'viewBox');
  4957. var width = rect.width;
  4958. var height = rect.height;
  4959. var viewBox = svg.viewBox || (viewBoxAttr ? viewBoxAttr.split(' ') : [0, 0, width, height]);
  4960. return {
  4961. el: parentSvgEl,
  4962. viewBox: viewBox,
  4963. x: viewBox[0] / 1,
  4964. y: viewBox[1] / 1,
  4965. w: width / viewBox[2],
  4966. h: height / viewBox[3]
  4967. }
  4968. }
  4969. function getPath(path, percent) {
  4970. var pathEl = is.str(path) ? selectString(path)[0] : path;
  4971. var p = percent || 100;
  4972. return function(property) {
  4973. return {
  4974. property: property,
  4975. el: pathEl,
  4976. svg: getParentSvg(pathEl),
  4977. totalLength: getTotalLength(pathEl) * (p / 100)
  4978. }
  4979. }
  4980. }
  4981. function getPathProgress(path, progress) {
  4982. function point(offset) {
  4983. if ( offset === void 0 ) offset = 0;
  4984. var l = progress + offset >= 1 ? progress + offset : 0;
  4985. return path.el.getPointAtLength(l);
  4986. }
  4987. var svg = getParentSvg(path.el, path.svg);
  4988. var p = point();
  4989. var p0 = point(-1);
  4990. var p1 = point(+1);
  4991. switch (path.property) {
  4992. case 'x': return (p.x - svg.x) * svg.w;
  4993. case 'y': return (p.y - svg.y) * svg.h;
  4994. case 'angle': return Math.atan2(p1.y - p0.y, p1.x - p0.x) * 180 / Math.PI;
  4995. }
  4996. }
  4997. // Decompose value
  4998. var valueRegex = /-?\d*\.?\d+/g;
  4999. function decomposeValue(val, unit) {
  5000. var value = validateValue((is.pth(val) ? val.totalLength : val), unit) + '';
  5001. return {
  5002. original: value,
  5003. numbers: value.match(valueRegex) ? value.match(valueRegex).map(Number) : [0],
  5004. strings: (is.str(val) || unit) ? value.split(valueRegex) : []
  5005. }
  5006. }
  5007. // Animatables
  5008. function parseTargets(targets) {
  5009. var targetsArray = targets ? (flattenArray(is.arr(targets) ? targets.map(toArray) : toArray(targets))) : [];
  5010. return filterArray(targetsArray, function (item, pos, self) { return self.indexOf(item) === pos; });
  5011. }
  5012. function getAnimatables(targets) {
  5013. var parsed = parseTargets(targets);
  5014. return parsed.map(function (t, i) {
  5015. return {target: t, id: i, total: parsed.length, transforms: { list: getElementTransforms(t) } };
  5016. });
  5017. }
  5018. // Properties
  5019. var springRegex = /^spring/;
  5020. function normalizePropertyTweens(prop, tweenSettings) {
  5021. var settings = cloneObject(tweenSettings);
  5022. // Override duration if easing is a spring
  5023. if (springRegex.test(settings.easing)) { settings.duration = spring(settings.easing); }
  5024. if (is.arr(prop)) {
  5025. var l = prop.length;
  5026. var isFromTo = (l === 2 && !is.obj(prop[0]));
  5027. if (!isFromTo) {
  5028. // Duration divided by the number of tweens
  5029. if (!is.fnc(tweenSettings.duration)) { settings.duration = tweenSettings.duration / l; }
  5030. } else {
  5031. // Transform [from, to] values shorthand to a valid tween value
  5032. prop = {value: prop};
  5033. }
  5034. }
  5035. var propArray = is.arr(prop) ? prop : [prop];
  5036. return propArray.map(function (v, i) {
  5037. var obj = (is.obj(v) && !is.pth(v)) ? v : {value: v};
  5038. // Default delay value should only be applied to the first tween
  5039. if (is.und(obj.delay)) { obj.delay = !i ? tweenSettings.delay : 0; }
  5040. // Default endDelay value should only be applied to the last tween
  5041. if (is.und(obj.endDelay)) { obj.endDelay = i === propArray.length - 1 ? tweenSettings.endDelay : 0; }
  5042. return obj;
  5043. }).map(function (k) { return mergeObjects(k, settings); });
  5044. }
  5045. function flattenKeyframes(keyframes) {
  5046. var propertyNames = filterArray(flattenArray(keyframes.map(function (key) { return Object.keys(key); })), function (p) { return is.key(p); })
  5047. .reduce(function (a,b) { if (a.indexOf(b) < 0) { a.push(b); } return a; }, []);
  5048. var properties = {};
  5049. var loop = function ( i ) {
  5050. var propName = propertyNames[i];
  5051. properties[propName] = keyframes.map(function (key) {
  5052. var newKey = {};
  5053. for (var p in key) {
  5054. if (is.key(p)) {
  5055. if (p == propName) { newKey.value = key[p]; }
  5056. } else {
  5057. newKey[p] = key[p];
  5058. }
  5059. }
  5060. return newKey;
  5061. });
  5062. };
  5063. for (var i = 0; i < propertyNames.length; i++) loop( i );
  5064. return properties;
  5065. }
  5066. function getProperties(tweenSettings, params) {
  5067. var properties = [];
  5068. var keyframes = params.keyframes;
  5069. if (keyframes) { params = mergeObjects(flattenKeyframes(keyframes), params); }
  5070. for (var p in params) {
  5071. if (is.key(p)) {
  5072. properties.push({
  5073. name: p,
  5074. tweens: normalizePropertyTweens(params[p], tweenSettings)
  5075. });
  5076. }
  5077. }
  5078. return properties;
  5079. }
  5080. // Tweens
  5081. function normalizeTweenValues(tween, animatable) {
  5082. var t = {};
  5083. for (var p in tween) {
  5084. var value = getFunctionValue(tween[p], animatable);
  5085. if (is.arr(value)) {
  5086. value = value.map(function (v) { return getFunctionValue(v, animatable); });
  5087. if (value.length === 1) { value = value[0]; }
  5088. }
  5089. t[p] = value;
  5090. }
  5091. t.duration = parseFloat(t.duration);
  5092. t.delay = parseFloat(t.delay);
  5093. return t;
  5094. }
  5095. function normalizeTweens(prop, animatable) {
  5096. var previousTween;
  5097. return prop.tweens.map(function (t) {
  5098. var tween = normalizeTweenValues(t, animatable);
  5099. var tweenValue = tween.value;
  5100. var to = is.arr(tweenValue) ? tweenValue[1] : tweenValue;
  5101. var toUnit = getUnit(to);
  5102. var originalValue = getOriginalTargetValue(animatable.target, prop.name, toUnit, animatable);
  5103. var previousValue = previousTween ? previousTween.to.original : originalValue;
  5104. var from = is.arr(tweenValue) ? tweenValue[0] : previousValue;
  5105. var fromUnit = getUnit(from) || getUnit(originalValue);
  5106. var unit = toUnit || fromUnit;
  5107. if (is.und(to)) { to = previousValue; }
  5108. tween.from = decomposeValue(from, unit);
  5109. tween.to = decomposeValue(getRelativeValue(to, from), unit);
  5110. tween.start = previousTween ? previousTween.end : 0;
  5111. tween.end = tween.start + tween.delay + tween.duration + tween.endDelay;
  5112. tween.easing = parseEasings(tween.easing, tween.duration);
  5113. tween.isPath = is.pth(tweenValue);
  5114. tween.isColor = is.col(tween.from.original);
  5115. if (tween.isColor) { tween.round = 1; }
  5116. previousTween = tween;
  5117. return tween;
  5118. });
  5119. }
  5120. // Tween progress
  5121. var setProgressValue = {
  5122. css: function (t, p, v) { return t.style[p] = v; },
  5123. attribute: function (t, p, v) { return t.setAttribute(p, v); },
  5124. object: function (t, p, v) { return t[p] = v; },
  5125. transform: function (t, p, v, transforms, manual) {
  5126. transforms.list.set(p, v);
  5127. if (p === transforms.last || manual) {
  5128. var str = '';
  5129. transforms.list.forEach(function (value, prop) { str += prop + "(" + value + ") "; });
  5130. t.style.transform = str;
  5131. }
  5132. }
  5133. };
  5134. // Set Value helper
  5135. function setTargetsValue(targets, properties) {
  5136. var animatables = getAnimatables(targets);
  5137. for (var i = 0, len = animatables.length; i < len; i++) {
  5138. var animatable = animatables[i];
  5139. for (var property in properties) {
  5140. var value = getFunctionValue(properties[property], animatable);
  5141. var target = animatable.target;
  5142. var valueUnit = getUnit(value);
  5143. var originalValue = getOriginalTargetValue(target, property, valueUnit, animatable);
  5144. var unit = valueUnit || getUnit(originalValue);
  5145. var to = getRelativeValue(validateValue(value, unit), originalValue);
  5146. var animType = getAnimationType(target, property);
  5147. setProgressValue[animType](target, property, to, animatable.transforms, true);
  5148. }
  5149. }
  5150. }
  5151. // Animations
  5152. function createAnimation(animatable, prop) {
  5153. var animType = getAnimationType(animatable.target, prop.name);
  5154. if (animType) {
  5155. var tweens = normalizeTweens(prop, animatable);
  5156. var lastTween = tweens[tweens.length - 1];
  5157. return {
  5158. type: animType,
  5159. property: prop.name,
  5160. animatable: animatable,
  5161. tweens: tweens,
  5162. duration: lastTween.end,
  5163. delay: tweens[0].delay,
  5164. endDelay: lastTween.endDelay
  5165. }
  5166. }
  5167. }
  5168. function getAnimations(animatables, properties) {
  5169. return filterArray(flattenArray(animatables.map(function (animatable) {
  5170. return properties.map(function (prop) {
  5171. return createAnimation(animatable, prop);
  5172. });
  5173. })), function (a) { return !is.und(a); });
  5174. }
  5175. // Create Instance
  5176. function getInstanceTimings(animations, tweenSettings) {
  5177. var animLength = animations.length;
  5178. var getTlOffset = function (anim) { return anim.timelineOffset ? anim.timelineOffset : 0; };
  5179. var timings = {};
  5180. timings.duration = animLength ? Math.max.apply(Math, animations.map(function (anim) { return getTlOffset(anim) + anim.duration; })) : tweenSettings.duration;
  5181. timings.delay = animLength ? Math.min.apply(Math, animations.map(function (anim) { return getTlOffset(anim) + anim.delay; })) : tweenSettings.delay;
  5182. timings.endDelay = animLength ? timings.duration - Math.max.apply(Math, animations.map(function (anim) { return getTlOffset(anim) + anim.duration - anim.endDelay; })) : tweenSettings.endDelay;
  5183. return timings;
  5184. }
  5185. var instanceID = 0;
  5186. function createNewInstance(params) {
  5187. var instanceSettings = replaceObjectProps(defaultInstanceSettings, params);
  5188. var tweenSettings = replaceObjectProps(defaultTweenSettings, params);
  5189. var properties = getProperties(tweenSettings, params);
  5190. var animatables = getAnimatables(params.targets);
  5191. var animations = getAnimations(animatables, properties);
  5192. var timings = getInstanceTimings(animations, tweenSettings);
  5193. var id = instanceID;
  5194. instanceID++;
  5195. return mergeObjects(instanceSettings, {
  5196. id: id,
  5197. children: [],
  5198. animatables: animatables,
  5199. animations: animations,
  5200. duration: timings.duration,
  5201. delay: timings.delay,
  5202. endDelay: timings.endDelay
  5203. });
  5204. }
  5205. // Core
  5206. var activeInstances = [];
  5207. var pausedInstances = [];
  5208. var raf;
  5209. var engine = (function () {
  5210. function play() {
  5211. raf = requestAnimationFrame(step);
  5212. }
  5213. function step(t) {
  5214. var activeInstancesLength = activeInstances.length;
  5215. if (activeInstancesLength) {
  5216. var i = 0;
  5217. while (i < activeInstancesLength) {
  5218. var activeInstance = activeInstances[i];
  5219. if (!activeInstance.paused) {
  5220. activeInstance.tick(t);
  5221. } else {
  5222. var instanceIndex = activeInstances.indexOf(activeInstance);
  5223. if (instanceIndex > -1) {
  5224. activeInstances.splice(instanceIndex, 1);
  5225. activeInstancesLength = activeInstances.length;
  5226. }
  5227. }
  5228. i++;
  5229. }
  5230. play();
  5231. } else {
  5232. raf = cancelAnimationFrame(raf);
  5233. }
  5234. }
  5235. return play;
  5236. })();
  5237. function handleVisibilityChange() {
  5238. if (document.hidden) {
  5239. for (var i = 0, len = activeInstances.length; i < len; i++) {
  5240. activeInstance[i].pause();
  5241. }
  5242. pausedInstances = activeInstances.slice(0);
  5243. activeInstances = [];
  5244. } else {
  5245. for (var i$1 = 0, len$1 = pausedInstances.length; i$1 < len$1; i$1++) {
  5246. pausedInstances[i$1].play();
  5247. }
  5248. }
  5249. }
  5250. document.addEventListener('visibilitychange', handleVisibilityChange);
  5251. // Public Instance
  5252. function anime(params) {
  5253. if ( params === void 0 ) params = {};
  5254. var startTime = 0, lastTime = 0, now = 0;
  5255. var children, childrenLength = 0;
  5256. var resolve = null;
  5257. function makePromise() {
  5258. return window.Promise && new Promise(function (_resolve) { return resolve = _resolve; });
  5259. }
  5260. var promise = makePromise();
  5261. var instance = createNewInstance(params);
  5262. function toggleInstanceDirection() {
  5263. instance.reversed = !instance.reversed;
  5264. for (var i = 0, len = children.length; i < len; i++) {
  5265. children[i].reversed = instance.reversed;
  5266. }
  5267. }
  5268. function adjustTime(time) {
  5269. return instance.reversed ? instance.duration - time : time;
  5270. }
  5271. function resetTime() {
  5272. startTime = 0;
  5273. lastTime = adjustTime(instance.currentTime) * (1 / anime.speed);
  5274. }
  5275. function seekCild(time, child) {
  5276. if (child) { child.seek(time - child.timelineOffset); }
  5277. }
  5278. function syncInstanceChildren(time) {
  5279. if (!instance.reversePlayback) {
  5280. for (var i = 0; i < childrenLength; i++) { seekCild(time, children[i]); }
  5281. } else {
  5282. for (var i$1 = childrenLength; i$1--;) { seekCild(time, children[i$1]); }
  5283. }
  5284. }
  5285. function setAnimationsProgress(insTime) {
  5286. var i = 0;
  5287. var animations = instance.animations;
  5288. var animationsLength = animations.length;
  5289. while (i < animationsLength) {
  5290. var anim = animations[i];
  5291. var animatable = anim.animatable;
  5292. var tweens = anim.tweens;
  5293. var tweenLength = tweens.length - 1;
  5294. var tween = tweens[tweenLength];
  5295. // Only check for keyframes if there is more than one tween
  5296. if (tweenLength) { tween = filterArray(tweens, function (t) { return (insTime < t.end); })[0] || tween; }
  5297. var elapsed = minMax(insTime - tween.start - tween.delay, 0, tween.duration) / tween.duration;
  5298. var eased = isNaN(elapsed) ? 1 : tween.easing(elapsed);
  5299. var strings = tween.to.strings;
  5300. var round = tween.round;
  5301. var numbers = [];
  5302. var toNumbersLength = tween.to.numbers.length;
  5303. var progress = (void 0);
  5304. for (var n = 0; n < toNumbersLength; n++) {
  5305. var value = (void 0);
  5306. var toNumber = tween.to.numbers[n];
  5307. var fromNumber = tween.from.numbers[n] || 0;
  5308. if (!tween.isPath) {
  5309. value = fromNumber + (eased * (toNumber - fromNumber));
  5310. } else {
  5311. value = getPathProgress(tween.value, eased * toNumber);
  5312. }
  5313. if (round) {
  5314. if (!(tween.isColor && n > 2)) {
  5315. value = Math.round(value * round) / round;
  5316. }
  5317. }
  5318. numbers.push(value);
  5319. }
  5320. // Manual Array.reduce for better performances
  5321. var stringsLength = strings.length;
  5322. if (!stringsLength) {
  5323. progress = numbers[0];
  5324. } else {
  5325. progress = strings[0];
  5326. for (var s = 0; s < stringsLength; s++) {
  5327. var a = strings[s];
  5328. var b = strings[s + 1];
  5329. var n$1 = numbers[s];
  5330. if (!isNaN(n$1)) {
  5331. if (!b) {
  5332. progress += n$1 + ' ';
  5333. } else {
  5334. progress += n$1 + b;
  5335. }
  5336. }
  5337. }
  5338. }
  5339. setProgressValue[anim.type](animatable.target, anim.property, progress, animatable.transforms);
  5340. anim.currentValue = progress;
  5341. i++;
  5342. }
  5343. }
  5344. function setCallback(cb) {
  5345. if (instance[cb] && !instance.passThrough) { instance[cb](instance); }
  5346. }
  5347. function countIteration() {
  5348. if (instance.remaining && instance.remaining !== true) {
  5349. instance.remaining--;
  5350. }
  5351. }
  5352. function setInstanceProgress(engineTime) {
  5353. var insDuration = instance.duration;
  5354. var insDelay = instance.delay;
  5355. var insEndDelay = insDuration - instance.endDelay;
  5356. var insTime = adjustTime(engineTime);
  5357. instance.progress = minMax((insTime / insDuration) * 100, 0, 100);
  5358. instance.reversePlayback = insTime < instance.currentTime;
  5359. if (children) { syncInstanceChildren(insTime); }
  5360. if (!instance.began && instance.currentTime > 0) {
  5361. instance.began = true;
  5362. setCallback('begin');
  5363. setCallback('loopBegin');
  5364. }
  5365. if (insTime <= insDelay && instance.currentTime !== 0) {
  5366. setAnimationsProgress(0);
  5367. }
  5368. if ((insTime >= insEndDelay && instance.currentTime !== insDuration) || !insDuration) {
  5369. setAnimationsProgress(insDuration);
  5370. }
  5371. if (insTime > insDelay && insTime < insEndDelay) {
  5372. if (!instance.changeBegan) {
  5373. instance.changeBegan = true;
  5374. instance.changeCompleted = false;
  5375. setCallback('changeBegin');
  5376. }
  5377. setCallback('change');
  5378. setAnimationsProgress(insTime);
  5379. } else {
  5380. if (instance.changeBegan) {
  5381. instance.changeCompleted = true;
  5382. instance.changeBegan = false;
  5383. setCallback('changeComplete');
  5384. }
  5385. }
  5386. instance.currentTime = minMax(insTime, 0, insDuration);
  5387. if (instance.began) { setCallback('update'); }
  5388. if (engineTime >= insDuration) {
  5389. lastTime = 0;
  5390. countIteration();
  5391. if (instance.remaining) {
  5392. startTime = now;
  5393. setCallback('loopComplete');
  5394. setCallback('loopBegin');
  5395. if (instance.direction === 'alternate') { toggleInstanceDirection(); }
  5396. } else {
  5397. instance.paused = true;
  5398. if (!instance.completed) {
  5399. instance.completed = true;
  5400. setCallback('loopComplete');
  5401. setCallback('complete');
  5402. if ('Promise' in window) {
  5403. resolve();
  5404. promise = makePromise();
  5405. }
  5406. }
  5407. }
  5408. }
  5409. }
  5410. instance.reset = function() {
  5411. var direction = instance.direction;
  5412. instance.passThrough = false;
  5413. instance.currentTime = 0;
  5414. instance.progress = 0;
  5415. instance.paused = true;
  5416. instance.began = false;
  5417. instance.changeBegan = false;
  5418. instance.completed = false;
  5419. instance.changeCompleted = false;
  5420. instance.reversePlayback = false;
  5421. instance.reversed = direction === 'reverse';
  5422. instance.remaining = instance.loop;
  5423. children = instance.children;
  5424. childrenLength = children.length;
  5425. for (var i = childrenLength; i--;) { instance.children[i].reset(); }
  5426. if (instance.reversed && instance.loop !== true || (direction === 'alternate' && instance.loop === 1)) { instance.remaining++; }
  5427. setAnimationsProgress(0);
  5428. };
  5429. // Set Value helper
  5430. instance.set = function(targets, properties) {
  5431. setTargetsValue(targets, properties);
  5432. return instance;
  5433. };
  5434. instance.tick = function(t) {
  5435. now = t;
  5436. if (!startTime) { startTime = now; }
  5437. setInstanceProgress((now + (lastTime - startTime)) * anime.speed);
  5438. };
  5439. instance.seek = function(time) {
  5440. setInstanceProgress(adjustTime(time));
  5441. };
  5442. instance.pause = function() {
  5443. instance.paused = true;
  5444. resetTime();
  5445. };
  5446. instance.play = function() {
  5447. if (!instance.paused) { return; }
  5448. instance.paused = false;
  5449. activeInstances.push(instance);
  5450. resetTime();
  5451. if (!raf) { engine(); }
  5452. };
  5453. instance.reverse = function() {
  5454. toggleInstanceDirection();
  5455. resetTime();
  5456. };
  5457. instance.restart = function() {
  5458. instance.reset();
  5459. instance.play();
  5460. };
  5461. instance.finished = promise;
  5462. instance.reset();
  5463. if (instance.autoplay) { instance.play(); }
  5464. return instance;
  5465. }
  5466. // Remove targets from animation
  5467. function removeTargetsFromAnimations(targetsArray, animations) {
  5468. for (var a = animations.length; a--;) {
  5469. if (arrayContains(targetsArray, animations[a].animatable.target)) {
  5470. animations.splice(a, 1);
  5471. }
  5472. }
  5473. }
  5474. function removeTargets(targets) {
  5475. var targetsArray = parseTargets(targets);
  5476. for (var i = activeInstances.length; i--;) {
  5477. var instance = activeInstances[i];
  5478. var animations = instance.animations;
  5479. var children = instance.children;
  5480. removeTargetsFromAnimations(targetsArray, animations);
  5481. for (var c = children.length; c--;) {
  5482. var child = children[c];
  5483. var childAnimations = child.animations;
  5484. removeTargetsFromAnimations(targetsArray, childAnimations);
  5485. if (!childAnimations.length && !child.children.length) { children.splice(c, 1); }
  5486. }
  5487. if (!animations.length && !children.length) { instance.pause(); }
  5488. }
  5489. }
  5490. // Stagger helpers
  5491. function stagger(val, params) {
  5492. if ( params === void 0 ) params = {};
  5493. var direction = params.direction || 'normal';
  5494. var easing = params.easing ? parseEasings(params.easing) : null;
  5495. var grid = params.grid;
  5496. var axis = params.axis;
  5497. var fromIndex = params.from || 0;
  5498. var fromFirst = fromIndex === 'first';
  5499. var fromCenter = fromIndex === 'center';
  5500. var fromLast = fromIndex === 'last';
  5501. var isRange = is.arr(val);
  5502. var val1 = isRange ? parseFloat(val[0]) : parseFloat(val);
  5503. var val2 = isRange ? parseFloat(val[1]) : 0;
  5504. var unit = getUnit(isRange ? val[1] : val) || 0;
  5505. var start = params.start || 0 + (isRange ? val1 : 0);
  5506. var values = [];
  5507. var maxValue = 0;
  5508. return function (el, i, t) {
  5509. if (fromFirst) { fromIndex = 0; }
  5510. if (fromCenter) { fromIndex = (t - 1) / 2; }
  5511. if (fromLast) { fromIndex = t - 1; }
  5512. if (!values.length) {
  5513. for (var index = 0; index < t; index++) {
  5514. if (!grid) {
  5515. values.push(Math.abs(fromIndex - index));
  5516. } else {
  5517. var fromX = !fromCenter ? fromIndex%grid[0] : (grid[0]-1)/2;
  5518. var fromY = !fromCenter ? Math.floor(fromIndex/grid[0]) : (grid[1]-1)/2;
  5519. var toX = index%grid[0];
  5520. var toY = Math.floor(index/grid[0]);
  5521. var distanceX = fromX - toX;
  5522. var distanceY = fromY - toY;
  5523. var value = Math.sqrt(distanceX * distanceX + distanceY * distanceY);
  5524. if (axis === 'x') { value = -distanceX; }
  5525. if (axis === 'y') { value = -distanceY; }
  5526. values.push(value);
  5527. }
  5528. maxValue = Math.max.apply(Math, values);
  5529. }
  5530. if (easing) { values = values.map(function (val) { return easing(val / maxValue) * maxValue; }); }
  5531. if (direction === 'reverse') { values = values.map(function (val) { return axis ? (val < 0) ? val * -1 : -val : Math.abs(maxValue - val); }); }
  5532. }
  5533. var spacing = isRange ? (val2 - val1) / maxValue : val1;
  5534. return start + (spacing * (Math.round(values[i] * 100) / 100)) + unit;
  5535. }
  5536. }
  5537. // Timeline
  5538. function timeline(params) {
  5539. if ( params === void 0 ) params = {};
  5540. var tl = anime(params);
  5541. tl.duration = 0;
  5542. tl.add = function(instanceParams, timelineOffset) {
  5543. var tlIndex = activeInstances.indexOf(tl);
  5544. var children = tl.children;
  5545. if (tlIndex > -1) { activeInstances.splice(tlIndex, 1); }
  5546. function passThrough(ins) { ins.passThrough = true; }
  5547. for (var i = 0; i < children.length; i++) { passThrough(children[i]); }
  5548. var insParams = mergeObjects(instanceParams, replaceObjectProps(defaultTweenSettings, params));
  5549. insParams.targets = insParams.targets || params.targets;
  5550. var tlDuration = tl.duration;
  5551. insParams.autoplay = false;
  5552. insParams.direction = tl.direction;
  5553. insParams.timelineOffset = is.und(timelineOffset) ? tlDuration : getRelativeValue(timelineOffset, tlDuration);
  5554. passThrough(tl);
  5555. tl.seek(insParams.timelineOffset);
  5556. var ins = anime(insParams);
  5557. passThrough(ins);
  5558. children.push(ins);
  5559. var timings = getInstanceTimings(children, params);
  5560. tl.delay = timings.delay;
  5561. tl.endDelay = timings.endDelay;
  5562. tl.duration = timings.duration;
  5563. tl.seek(0);
  5564. tl.reset();
  5565. if (tl.autoplay) { tl.play(); }
  5566. return tl;
  5567. };
  5568. return tl;
  5569. }
  5570. anime.version = '3.0.0';
  5571. anime.speed = 1;
  5572. anime.running = activeInstances;
  5573. anime.remove = removeTargets;
  5574. anime.get = getOriginalTargetValue;
  5575. anime.set = setTargetsValue;
  5576. anime.convertPx = convertPxToUnit;
  5577. anime.path = getPath;
  5578. anime.setDashoffset = setDashoffset;
  5579. anime.stagger = stagger;
  5580. anime.timeline = timeline;
  5581. anime.easing = parseEasings;
  5582. anime.penner = penner;
  5583. anime.random = function (min, max) { return Math.floor(Math.random() * (max - min + 1)) + min; };
  5584. module.exports = anime;
  5585. },{}],57:[function(_dereq_,module,exports){
  5586. // threejs.org/license
  5587. (function (global, factory) {
  5588. typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
  5589. typeof define === 'function' && define.amd ? define(['exports'], factory) :
  5590. (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.THREE = {}));
  5591. }(this, (function (exports) { 'use strict';
  5592. // Polyfills
  5593. if (Number.EPSILON === undefined) {
  5594. Number.EPSILON = Math.pow(2, -52);
  5595. }
  5596. if (Number.isInteger === undefined) {
  5597. // Missing in IE
  5598. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isInteger
  5599. Number.isInteger = function (value) {
  5600. return typeof value === 'number' && isFinite(value) && Math.floor(value) === value;
  5601. };
  5602. } //
  5603. if (Math.sign === undefined) {
  5604. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sign
  5605. Math.sign = function (x) {
  5606. return x < 0 ? -1 : x > 0 ? 1 : +x;
  5607. };
  5608. }
  5609. if ('name' in Function.prototype === false) {
  5610. // Missing in IE
  5611. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name
  5612. Object.defineProperty(Function.prototype, 'name', {
  5613. get: function get() {
  5614. return this.toString().match(/^\s*function\s*([^\(\s]*)/)[1];
  5615. }
  5616. });
  5617. }
  5618. if (Object.assign === undefined) {
  5619. // Missing in IE
  5620. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
  5621. Object.assign = function (target) {
  5622. if (target === undefined || target === null) {
  5623. throw new TypeError('Cannot convert undefined or null to object');
  5624. }
  5625. var output = Object(target);
  5626. for (var index = 1; index < arguments.length; index++) {
  5627. var source = arguments[index];
  5628. if (source !== undefined && source !== null) {
  5629. for (var nextKey in source) {
  5630. if (Object.prototype.hasOwnProperty.call(source, nextKey)) {
  5631. output[nextKey] = source[nextKey];
  5632. }
  5633. }
  5634. }
  5635. }
  5636. return output;
  5637. };
  5638. }
  5639. /**
  5640. * Copyright (c) 2014-present, Facebook, Inc.
  5641. *
  5642. * This source code is licensed under the MIT license found in the
  5643. * LICENSE file in the root directory of this source tree.
  5644. */
  5645. var runtime = function (exports) {
  5646. var Op = Object.prototype;
  5647. var hasOwn = Op.hasOwnProperty;
  5648. var undefined$1; // More compressible than void 0.
  5649. var $Symbol = typeof Symbol === "function" ? Symbol : {};
  5650. var iteratorSymbol = $Symbol.iterator || "@@iterator";
  5651. var asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator";
  5652. var toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag";
  5653. function define(obj, key, value) {
  5654. Object.defineProperty(obj, key, {
  5655. value: value,
  5656. enumerable: true,
  5657. configurable: true,
  5658. writable: true
  5659. });
  5660. return obj[key];
  5661. }
  5662. try {
  5663. // IE 8 has a broken Object.defineProperty that only works on DOM objects.
  5664. define({}, "");
  5665. } catch (err) {
  5666. define = function define(obj, key, value) {
  5667. return obj[key] = value;
  5668. };
  5669. }
  5670. function wrap(innerFn, outerFn, self, tryLocsList) {
  5671. // If outerFn provided and outerFn.prototype is a Generator, then outerFn.prototype instanceof Generator.
  5672. var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator;
  5673. var generator = Object.create(protoGenerator.prototype);
  5674. var context = new Context(tryLocsList || []); // The ._invoke method unifies the implementations of the .next,
  5675. // .throw, and .return methods.
  5676. generator._invoke = makeInvokeMethod(innerFn, self, context);
  5677. return generator;
  5678. }
  5679. exports.wrap = wrap; // Try/catch helper to minimize deoptimizations. Returns a completion
  5680. // record like context.tryEntries[i].completion. This interface could
  5681. // have been (and was previously) designed to take a closure to be
  5682. // invoked without arguments, but in all the cases we care about we
  5683. // already have an existing method we want to call, so there's no need
  5684. // to create a new function object. We can even get away with assuming
  5685. // the method takes exactly one argument, since that happens to be true
  5686. // in every case, so we don't have to touch the arguments object. The
  5687. // only additional allocation required is the completion record, which
  5688. // has a stable shape and so hopefully should be cheap to allocate.
  5689. function tryCatch(fn, obj, arg) {
  5690. try {
  5691. return {
  5692. type: "normal",
  5693. arg: fn.call(obj, arg)
  5694. };
  5695. } catch (err) {
  5696. return {
  5697. type: "throw",
  5698. arg: err
  5699. };
  5700. }
  5701. }
  5702. var GenStateSuspendedStart = "suspendedStart";
  5703. var GenStateSuspendedYield = "suspendedYield";
  5704. var GenStateExecuting = "executing";
  5705. var GenStateCompleted = "completed"; // Returning this object from the innerFn has the same effect as
  5706. // breaking out of the dispatch switch statement.
  5707. var ContinueSentinel = {}; // Dummy constructor functions that we use as the .constructor and
  5708. // .constructor.prototype properties for functions that return Generator
  5709. // objects. For full spec compliance, you may wish to configure your
  5710. // minifier not to mangle the names of these two functions.
  5711. function Generator() {}
  5712. function GeneratorFunction() {}
  5713. function GeneratorFunctionPrototype() {} // This is a polyfill for %IteratorPrototype% for environments that
  5714. // don't natively support it.
  5715. var IteratorPrototype = {};
  5716. IteratorPrototype[iteratorSymbol] = function () {
  5717. return this;
  5718. };
  5719. var getProto = Object.getPrototypeOf;
  5720. var NativeIteratorPrototype = getProto && getProto(getProto(values([])));
  5721. if (NativeIteratorPrototype && NativeIteratorPrototype !== Op && hasOwn.call(NativeIteratorPrototype, iteratorSymbol)) {
  5722. // This environment has a native %IteratorPrototype%; use it instead
  5723. // of the polyfill.
  5724. IteratorPrototype = NativeIteratorPrototype;
  5725. }
  5726. var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(IteratorPrototype);
  5727. GeneratorFunction.prototype = Gp.constructor = GeneratorFunctionPrototype;
  5728. GeneratorFunctionPrototype.constructor = GeneratorFunction;
  5729. GeneratorFunction.displayName = define(GeneratorFunctionPrototype, toStringTagSymbol, "GeneratorFunction"); // Helper for defining the .next, .throw, and .return methods of the
  5730. // Iterator interface in terms of a single ._invoke method.
  5731. function defineIteratorMethods(prototype) {
  5732. ["next", "throw", "return"].forEach(function (method) {
  5733. define(prototype, method, function (arg) {
  5734. return this._invoke(method, arg);
  5735. });
  5736. });
  5737. }
  5738. exports.isGeneratorFunction = function (genFun) {
  5739. var ctor = typeof genFun === "function" && genFun.constructor;
  5740. return ctor ? ctor === GeneratorFunction || // For the native GeneratorFunction constructor, the best we can
  5741. // do is to check its .name property.
  5742. (ctor.displayName || ctor.name) === "GeneratorFunction" : false;
  5743. };
  5744. exports.mark = function (genFun) {
  5745. if (Object.setPrototypeOf) {
  5746. Object.setPrototypeOf(genFun, GeneratorFunctionPrototype);
  5747. } else {
  5748. genFun.__proto__ = GeneratorFunctionPrototype;
  5749. define(genFun, toStringTagSymbol, "GeneratorFunction");
  5750. }
  5751. genFun.prototype = Object.create(Gp);
  5752. return genFun;
  5753. }; // Within the body of any async function, `await x` is transformed to
  5754. // `yield regeneratorRuntime.awrap(x)`, so that the runtime can test
  5755. // `hasOwn.call(value, "__await")` to determine if the yielded value is
  5756. // meant to be awaited.
  5757. exports.awrap = function (arg) {
  5758. return {
  5759. __await: arg
  5760. };
  5761. };
  5762. function AsyncIterator(generator, PromiseImpl) {
  5763. function invoke(method, arg, resolve, reject) {
  5764. var record = tryCatch(generator[method], generator, arg);
  5765. if (record.type === "throw") {
  5766. reject(record.arg);
  5767. } else {
  5768. var result = record.arg;
  5769. var value = result.value;
  5770. if (value && typeof value === "object" && hasOwn.call(value, "__await")) {
  5771. return PromiseImpl.resolve(value.__await).then(function (value) {
  5772. invoke("next", value, resolve, reject);
  5773. }, function (err) {
  5774. invoke("throw", err, resolve, reject);
  5775. });
  5776. }
  5777. return PromiseImpl.resolve(value).then(function (unwrapped) {
  5778. // When a yielded Promise is resolved, its final value becomes
  5779. // the .value of the Promise<{value,done}> result for the
  5780. // current iteration.
  5781. result.value = unwrapped;
  5782. resolve(result);
  5783. }, function (error) {
  5784. // If a rejected Promise was yielded, throw the rejection back
  5785. // into the async generator function so it can be handled there.
  5786. return invoke("throw", error, resolve, reject);
  5787. });
  5788. }
  5789. }
  5790. var previousPromise;
  5791. function enqueue(method, arg) {
  5792. function callInvokeWithMethodAndArg() {
  5793. return new PromiseImpl(function (resolve, reject) {
  5794. invoke(method, arg, resolve, reject);
  5795. });
  5796. }
  5797. return previousPromise = // If enqueue has been called before, then we want to wait until
  5798. // all previous Promises have been resolved before calling invoke,
  5799. // so that results are always delivered in the correct order. If
  5800. // enqueue has not been called before, then it is important to
  5801. // call invoke immediately, without waiting on a callback to fire,
  5802. // so that the async generator function has the opportunity to do
  5803. // any necessary setup in a predictable way. This predictability
  5804. // is why the Promise constructor synchronously invokes its
  5805. // executor callback, and why async functions synchronously
  5806. // execute code before the first await. Since we implement simple
  5807. // async functions in terms of async generators, it is especially
  5808. // important to get this right, even though it requires care.
  5809. previousPromise ? previousPromise.then(callInvokeWithMethodAndArg, // Avoid propagating failures to Promises returned by later
  5810. // invocations of the iterator.
  5811. callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg();
  5812. } // Define the unified helper method that is used to implement .next,
  5813. // .throw, and .return (see defineIteratorMethods).
  5814. this._invoke = enqueue;
  5815. }
  5816. defineIteratorMethods(AsyncIterator.prototype);
  5817. AsyncIterator.prototype[asyncIteratorSymbol] = function () {
  5818. return this;
  5819. };
  5820. exports.AsyncIterator = AsyncIterator; // Note that simple async functions are implemented on top of
  5821. // AsyncIterator objects; they just return a Promise for the value of
  5822. // the final result produced by the iterator.
  5823. exports.async = function (innerFn, outerFn, self, tryLocsList, PromiseImpl) {
  5824. if (PromiseImpl === void 0) PromiseImpl = Promise;
  5825. var iter = new AsyncIterator(wrap(innerFn, outerFn, self, tryLocsList), PromiseImpl);
  5826. return exports.isGeneratorFunction(outerFn) ? iter // If outerFn is a generator, return the full iterator.
  5827. : iter.next().then(function (result) {
  5828. return result.done ? result.value : iter.next();
  5829. });
  5830. };
  5831. function makeInvokeMethod(innerFn, self, context) {
  5832. var state = GenStateSuspendedStart;
  5833. return function invoke(method, arg) {
  5834. if (state === GenStateExecuting) {
  5835. throw new Error("Generator is already running");
  5836. }
  5837. if (state === GenStateCompleted) {
  5838. if (method === "throw") {
  5839. throw arg;
  5840. } // Be forgiving, per 25.3.3.3.3 of the spec:
  5841. // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generatorresume
  5842. return doneResult();
  5843. }
  5844. context.method = method;
  5845. context.arg = arg;
  5846. while (true) {
  5847. var delegate = context.delegate;
  5848. if (delegate) {
  5849. var delegateResult = maybeInvokeDelegate(delegate, context);
  5850. if (delegateResult) {
  5851. if (delegateResult === ContinueSentinel) continue;
  5852. return delegateResult;
  5853. }
  5854. }
  5855. if (context.method === "next") {
  5856. // Setting context._sent for legacy support of Babel's
  5857. // function.sent implementation.
  5858. context.sent = context._sent = context.arg;
  5859. } else if (context.method === "throw") {
  5860. if (state === GenStateSuspendedStart) {
  5861. state = GenStateCompleted;
  5862. throw context.arg;
  5863. }
  5864. context.dispatchException(context.arg);
  5865. } else if (context.method === "return") {
  5866. context.abrupt("return", context.arg);
  5867. }
  5868. state = GenStateExecuting;
  5869. var record = tryCatch(innerFn, self, context);
  5870. if (record.type === "normal") {
  5871. // If an exception is thrown from innerFn, we leave state ===
  5872. // GenStateExecuting and loop back for another invocation.
  5873. state = context.done ? GenStateCompleted : GenStateSuspendedYield;
  5874. if (record.arg === ContinueSentinel) {
  5875. continue;
  5876. }
  5877. return {
  5878. value: record.arg,
  5879. done: context.done
  5880. };
  5881. } else if (record.type === "throw") {
  5882. state = GenStateCompleted; // Dispatch the exception by looping back around to the
  5883. // context.dispatchException(context.arg) call above.
  5884. context.method = "throw";
  5885. context.arg = record.arg;
  5886. }
  5887. }
  5888. };
  5889. } // Call delegate.iterator[context.method](context.arg) and handle the
  5890. // result, either by returning a { value, done } result from the
  5891. // delegate iterator, or by modifying context.method and context.arg,
  5892. // setting context.delegate to null, and returning the ContinueSentinel.
  5893. function maybeInvokeDelegate(delegate, context) {
  5894. var method = delegate.iterator[context.method];
  5895. if (method === undefined$1) {
  5896. // A .throw or .return when the delegate iterator has no .throw
  5897. // method always terminates the yield* loop.
  5898. context.delegate = null;
  5899. if (context.method === "throw") {
  5900. // Note: ["return"] must be used for ES3 parsing compatibility.
  5901. if (delegate.iterator["return"]) {
  5902. // If the delegate iterator has a return method, give it a
  5903. // chance to clean up.
  5904. context.method = "return";
  5905. context.arg = undefined$1;
  5906. maybeInvokeDelegate(delegate, context);
  5907. if (context.method === "throw") {
  5908. // If maybeInvokeDelegate(context) changed context.method from
  5909. // "return" to "throw", let that override the TypeError below.
  5910. return ContinueSentinel;
  5911. }
  5912. }
  5913. context.method = "throw";
  5914. context.arg = new TypeError("The iterator does not provide a 'throw' method");
  5915. }
  5916. return ContinueSentinel;
  5917. }
  5918. var record = tryCatch(method, delegate.iterator, context.arg);
  5919. if (record.type === "throw") {
  5920. context.method = "throw";
  5921. context.arg = record.arg;
  5922. context.delegate = null;
  5923. return ContinueSentinel;
  5924. }
  5925. var info = record.arg;
  5926. if (!info) {
  5927. context.method = "throw";
  5928. context.arg = new TypeError("iterator result is not an object");
  5929. context.delegate = null;
  5930. return ContinueSentinel;
  5931. }
  5932. if (info.done) {
  5933. // Assign the result of the finished delegate to the temporary
  5934. // variable specified by delegate.resultName (see delegateYield).
  5935. context[delegate.resultName] = info.value; // Resume execution at the desired location (see delegateYield).
  5936. context.next = delegate.nextLoc; // If context.method was "throw" but the delegate handled the
  5937. // exception, let the outer generator proceed normally. If
  5938. // context.method was "next", forget context.arg since it has been
  5939. // "consumed" by the delegate iterator. If context.method was
  5940. // "return", allow the original .return call to continue in the
  5941. // outer generator.
  5942. if (context.method !== "return") {
  5943. context.method = "next";
  5944. context.arg = undefined$1;
  5945. }
  5946. } else {
  5947. // Re-yield the result returned by the delegate method.
  5948. return info;
  5949. } // The delegate iterator is finished, so forget it and continue with
  5950. // the outer generator.
  5951. context.delegate = null;
  5952. return ContinueSentinel;
  5953. } // Define Generator.prototype.{next,throw,return} in terms of the
  5954. // unified ._invoke helper method.
  5955. defineIteratorMethods(Gp);
  5956. define(Gp, toStringTagSymbol, "Generator"); // A Generator should always return itself as the iterator object when the
  5957. // @@iterator function is called on it. Some browsers' implementations of the
  5958. // iterator prototype chain incorrectly implement this, causing the Generator
  5959. // object to not be returned from this call. This ensures that doesn't happen.
  5960. // See https://github.com/facebook/regenerator/issues/274 for more details.
  5961. Gp[iteratorSymbol] = function () {
  5962. return this;
  5963. };
  5964. Gp.toString = function () {
  5965. return "[object Generator]";
  5966. };
  5967. function pushTryEntry(locs) {
  5968. var entry = {
  5969. tryLoc: locs[0]
  5970. };
  5971. if (1 in locs) {
  5972. entry.catchLoc = locs[1];
  5973. }
  5974. if (2 in locs) {
  5975. entry.finallyLoc = locs[2];
  5976. entry.afterLoc = locs[3];
  5977. }
  5978. this.tryEntries.push(entry);
  5979. }
  5980. function resetTryEntry(entry) {
  5981. var record = entry.completion || {};
  5982. record.type = "normal";
  5983. delete record.arg;
  5984. entry.completion = record;
  5985. }
  5986. function Context(tryLocsList) {
  5987. // The root entry object (effectively a try statement without a catch
  5988. // or a finally block) gives us a place to store values thrown from
  5989. // locations where there is no enclosing try statement.
  5990. this.tryEntries = [{
  5991. tryLoc: "root"
  5992. }];
  5993. tryLocsList.forEach(pushTryEntry, this);
  5994. this.reset(true);
  5995. }
  5996. exports.keys = function (object) {
  5997. var keys = [];
  5998. for (var key in object) {
  5999. keys.push(key);
  6000. }
  6001. keys.reverse(); // Rather than returning an object with a next method, we keep
  6002. // things simple and return the next function itself.
  6003. return function next() {
  6004. while (keys.length) {
  6005. var key = keys.pop();
  6006. if (key in object) {
  6007. next.value = key;
  6008. next.done = false;
  6009. return next;
  6010. }
  6011. } // To avoid creating an additional object, we just hang the .value
  6012. // and .done properties off the next function object itself. This
  6013. // also ensures that the minifier will not anonymize the function.
  6014. next.done = true;
  6015. return next;
  6016. };
  6017. };
  6018. function values(iterable) {
  6019. if (iterable) {
  6020. var iteratorMethod = iterable[iteratorSymbol];
  6021. if (iteratorMethod) {
  6022. return iteratorMethod.call(iterable);
  6023. }
  6024. if (typeof iterable.next === "function") {
  6025. return iterable;
  6026. }
  6027. if (!isNaN(iterable.length)) {
  6028. var i = -1,
  6029. next = function next() {
  6030. while (++i < iterable.length) {
  6031. if (hasOwn.call(iterable, i)) {
  6032. next.value = iterable[i];
  6033. next.done = false;
  6034. return next;
  6035. }
  6036. }
  6037. next.value = undefined$1;
  6038. next.done = true;
  6039. return next;
  6040. };
  6041. return next.next = next;
  6042. }
  6043. } // Return an iterator with no values.
  6044. return {
  6045. next: doneResult
  6046. };
  6047. }
  6048. exports.values = values;
  6049. function doneResult() {
  6050. return {
  6051. value: undefined$1,
  6052. done: true
  6053. };
  6054. }
  6055. Context.prototype = {
  6056. constructor: Context,
  6057. reset: function reset(skipTempReset) {
  6058. this.prev = 0;
  6059. this.next = 0; // Resetting context._sent for legacy support of Babel's
  6060. // function.sent implementation.
  6061. this.sent = this._sent = undefined$1;
  6062. this.done = false;
  6063. this.delegate = null;
  6064. this.method = "next";
  6065. this.arg = undefined$1;
  6066. this.tryEntries.forEach(resetTryEntry);
  6067. if (!skipTempReset) {
  6068. for (var name in this) {
  6069. // Not sure about the optimal order of these conditions:
  6070. if (name.charAt(0) === "t" && hasOwn.call(this, name) && !isNaN(+name.slice(1))) {
  6071. this[name] = undefined$1;
  6072. }
  6073. }
  6074. }
  6075. },
  6076. stop: function stop() {
  6077. this.done = true;
  6078. var rootEntry = this.tryEntries[0];
  6079. var rootRecord = rootEntry.completion;
  6080. if (rootRecord.type === "throw") {
  6081. throw rootRecord.arg;
  6082. }
  6083. return this.rval;
  6084. },
  6085. dispatchException: function dispatchException(exception) {
  6086. if (this.done) {
  6087. throw exception;
  6088. }
  6089. var context = this;
  6090. function handle(loc, caught) {
  6091. record.type = "throw";
  6092. record.arg = exception;
  6093. context.next = loc;
  6094. if (caught) {
  6095. // If the dispatched exception was caught by a catch block,
  6096. // then let that catch block handle the exception normally.
  6097. context.method = "next";
  6098. context.arg = undefined$1;
  6099. }
  6100. return !!caught;
  6101. }
  6102. for (var i = this.tryEntries.length - 1; i >= 0; --i) {
  6103. var entry = this.tryEntries[i];
  6104. var record = entry.completion;
  6105. if (entry.tryLoc === "root") {
  6106. // Exception thrown outside of any try block that could handle
  6107. // it, so set the completion value of the entire function to
  6108. // throw the exception.
  6109. return handle("end");
  6110. }
  6111. if (entry.tryLoc <= this.prev) {
  6112. var hasCatch = hasOwn.call(entry, "catchLoc");
  6113. var hasFinally = hasOwn.call(entry, "finallyLoc");
  6114. if (hasCatch && hasFinally) {
  6115. if (this.prev < entry.catchLoc) {
  6116. return handle(entry.catchLoc, true);
  6117. } else if (this.prev < entry.finallyLoc) {
  6118. return handle(entry.finallyLoc);
  6119. }
  6120. } else if (hasCatch) {
  6121. if (this.prev < entry.catchLoc) {
  6122. return handle(entry.catchLoc, true);
  6123. }
  6124. } else if (hasFinally) {
  6125. if (this.prev < entry.finallyLoc) {
  6126. return handle(entry.finallyLoc);
  6127. }
  6128. } else {
  6129. throw new Error("try statement without catch or finally");
  6130. }
  6131. }
  6132. }
  6133. },
  6134. abrupt: function abrupt(type, arg) {
  6135. for (var i = this.tryEntries.length - 1; i >= 0; --i) {
  6136. var entry = this.tryEntries[i];
  6137. if (entry.tryLoc <= this.prev && hasOwn.call(entry, "finallyLoc") && this.prev < entry.finallyLoc) {
  6138. var finallyEntry = entry;
  6139. break;
  6140. }
  6141. }
  6142. if (finallyEntry && (type === "break" || type === "continue") && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc) {
  6143. // Ignore the finally entry if control is not jumping to a
  6144. // location outside the try/catch block.
  6145. finallyEntry = null;
  6146. }
  6147. var record = finallyEntry ? finallyEntry.completion : {};
  6148. record.type = type;
  6149. record.arg = arg;
  6150. if (finallyEntry) {
  6151. this.method = "next";
  6152. this.next = finallyEntry.finallyLoc;
  6153. return ContinueSentinel;
  6154. }
  6155. return this.complete(record);
  6156. },
  6157. complete: function complete(record, afterLoc) {
  6158. if (record.type === "throw") {
  6159. throw record.arg;
  6160. }
  6161. if (record.type === "break" || record.type === "continue") {
  6162. this.next = record.arg;
  6163. } else if (record.type === "return") {
  6164. this.rval = this.arg = record.arg;
  6165. this.method = "return";
  6166. this.next = "end";
  6167. } else if (record.type === "normal" && afterLoc) {
  6168. this.next = afterLoc;
  6169. }
  6170. return ContinueSentinel;
  6171. },
  6172. finish: function finish(finallyLoc) {
  6173. for (var i = this.tryEntries.length - 1; i >= 0; --i) {
  6174. var entry = this.tryEntries[i];
  6175. if (entry.finallyLoc === finallyLoc) {
  6176. this.complete(entry.completion, entry.afterLoc);
  6177. resetTryEntry(entry);
  6178. return ContinueSentinel;
  6179. }
  6180. }
  6181. },
  6182. "catch": function _catch(tryLoc) {
  6183. for (var i = this.tryEntries.length - 1; i >= 0; --i) {
  6184. var entry = this.tryEntries[i];
  6185. if (entry.tryLoc === tryLoc) {
  6186. var record = entry.completion;
  6187. if (record.type === "throw") {
  6188. var thrown = record.arg;
  6189. resetTryEntry(entry);
  6190. }
  6191. return thrown;
  6192. }
  6193. } // The context.catch method must only be called with a location
  6194. // argument that corresponds to a known catch block.
  6195. throw new Error("illegal catch attempt");
  6196. },
  6197. delegateYield: function delegateYield(iterable, resultName, nextLoc) {
  6198. this.delegate = {
  6199. iterator: values(iterable),
  6200. resultName: resultName,
  6201. nextLoc: nextLoc
  6202. };
  6203. if (this.method === "next") {
  6204. // Deliberately forget the last sent value so that we don't
  6205. // accidentally pass it on to the delegate.
  6206. this.arg = undefined$1;
  6207. }
  6208. return ContinueSentinel;
  6209. }
  6210. }; // Regardless of whether this script is executing as a CommonJS module
  6211. // or not, return the runtime object so that we can declare the variable
  6212. // regeneratorRuntime in the outer scope, which allows this module to be
  6213. // injected easily by `bin/regenerator --include-runtime script.js`.
  6214. return exports;
  6215. }( // If this script is executing as a CommonJS module, use module.exports
  6216. // as the regeneratorRuntime namespace. Otherwise create a new empty
  6217. // object. Either way, the resulting object will be used to initialize
  6218. // the regeneratorRuntime variable at the top of this file.
  6219. typeof module === "object" ? module.exports : {});
  6220. try {
  6221. regeneratorRuntime = runtime;
  6222. } catch (accidentalStrictMode) {
  6223. // This module should not be running in strict mode, so the above
  6224. // assignment should always work unless something is misconfigured. Just
  6225. // in case runtime.js accidentally runs in strict mode, we can escape
  6226. // strict mode using a global Function call. This could conceivably fail
  6227. // if a Content Security Policy forbids using Function, but in that case
  6228. // the proper solution is to fix the accidental strict mode problem. If
  6229. // you've misconfigured your bundler to force strict mode and applied a
  6230. // CSP to forbid Function, and you're not willing to fix either of those
  6231. // problems, please detail your unique predicament in a GitHub issue.
  6232. Function("r", "regeneratorRuntime = r")(runtime);
  6233. }
  6234. var REVISION = '125';
  6235. var MOUSE = {
  6236. LEFT: 0,
  6237. MIDDLE: 1,
  6238. RIGHT: 2,
  6239. ROTATE: 0,
  6240. DOLLY: 1,
  6241. PAN: 2
  6242. };
  6243. var TOUCH = {
  6244. ROTATE: 0,
  6245. PAN: 1,
  6246. DOLLY_PAN: 2,
  6247. DOLLY_ROTATE: 3
  6248. };
  6249. var CullFaceNone = 0;
  6250. var CullFaceBack = 1;
  6251. var CullFaceFront = 2;
  6252. var CullFaceFrontBack = 3;
  6253. var BasicShadowMap = 0;
  6254. var PCFShadowMap = 1;
  6255. var PCFSoftShadowMap = 2;
  6256. var VSMShadowMap = 3;
  6257. var FrontSide = 0;
  6258. var BackSide = 1;
  6259. var DoubleSide = 2;
  6260. var FlatShading = 1;
  6261. var SmoothShading = 2;
  6262. var NoBlending = 0;
  6263. var NormalBlending = 1;
  6264. var AdditiveBlending = 2;
  6265. var SubtractiveBlending = 3;
  6266. var MultiplyBlending = 4;
  6267. var CustomBlending = 5;
  6268. var AddEquation = 100;
  6269. var SubtractEquation = 101;
  6270. var ReverseSubtractEquation = 102;
  6271. var MinEquation = 103;
  6272. var MaxEquation = 104;
  6273. var ZeroFactor = 200;
  6274. var OneFactor = 201;
  6275. var SrcColorFactor = 202;
  6276. var OneMinusSrcColorFactor = 203;
  6277. var SrcAlphaFactor = 204;
  6278. var OneMinusSrcAlphaFactor = 205;
  6279. var DstAlphaFactor = 206;
  6280. var OneMinusDstAlphaFactor = 207;
  6281. var DstColorFactor = 208;
  6282. var OneMinusDstColorFactor = 209;
  6283. var SrcAlphaSaturateFactor = 210;
  6284. var NeverDepth = 0;
  6285. var AlwaysDepth = 1;
  6286. var LessDepth = 2;
  6287. var LessEqualDepth = 3;
  6288. var EqualDepth = 4;
  6289. var GreaterEqualDepth = 5;
  6290. var GreaterDepth = 6;
  6291. var NotEqualDepth = 7;
  6292. var MultiplyOperation = 0;
  6293. var MixOperation = 1;
  6294. var AddOperation = 2;
  6295. var NoToneMapping = 0;
  6296. var LinearToneMapping = 1;
  6297. var ReinhardToneMapping = 2;
  6298. var CineonToneMapping = 3;
  6299. var ACESFilmicToneMapping = 4;
  6300. var CustomToneMapping = 5;
  6301. var UVMapping = 300;
  6302. var CubeReflectionMapping = 301;
  6303. var CubeRefractionMapping = 302;
  6304. var EquirectangularReflectionMapping = 303;
  6305. var EquirectangularRefractionMapping = 304;
  6306. var CubeUVReflectionMapping = 306;
  6307. var CubeUVRefractionMapping = 307;
  6308. var RepeatWrapping = 1000;
  6309. var ClampToEdgeWrapping = 1001;
  6310. var MirroredRepeatWrapping = 1002;
  6311. var NearestFilter = 1003;
  6312. var NearestMipmapNearestFilter = 1004;
  6313. var NearestMipMapNearestFilter = 1004;
  6314. var NearestMipmapLinearFilter = 1005;
  6315. var NearestMipMapLinearFilter = 1005;
  6316. var LinearFilter = 1006;
  6317. var LinearMipmapNearestFilter = 1007;
  6318. var LinearMipMapNearestFilter = 1007;
  6319. var LinearMipmapLinearFilter = 1008;
  6320. var LinearMipMapLinearFilter = 1008;
  6321. var UnsignedByteType = 1009;
  6322. var ByteType = 1010;
  6323. var ShortType = 1011;
  6324. var UnsignedShortType = 1012;
  6325. var IntType = 1013;
  6326. var UnsignedIntType = 1014;
  6327. var FloatType = 1015;
  6328. var HalfFloatType = 1016;
  6329. var UnsignedShort4444Type = 1017;
  6330. var UnsignedShort5551Type = 1018;
  6331. var UnsignedShort565Type = 1019;
  6332. var UnsignedInt248Type = 1020;
  6333. var AlphaFormat = 1021;
  6334. var RGBFormat = 1022;
  6335. var RGBAFormat = 1023;
  6336. var LuminanceFormat = 1024;
  6337. var LuminanceAlphaFormat = 1025;
  6338. var RGBEFormat = RGBAFormat;
  6339. var DepthFormat = 1026;
  6340. var DepthStencilFormat = 1027;
  6341. var RedFormat = 1028;
  6342. var RedIntegerFormat = 1029;
  6343. var RGFormat = 1030;
  6344. var RGIntegerFormat = 1031;
  6345. var RGBIntegerFormat = 1032;
  6346. var RGBAIntegerFormat = 1033;
  6347. var RGB_S3TC_DXT1_Format = 33776;
  6348. var RGBA_S3TC_DXT1_Format = 33777;
  6349. var RGBA_S3TC_DXT3_Format = 33778;
  6350. var RGBA_S3TC_DXT5_Format = 33779;
  6351. var RGB_PVRTC_4BPPV1_Format = 35840;
  6352. var RGB_PVRTC_2BPPV1_Format = 35841;
  6353. var RGBA_PVRTC_4BPPV1_Format = 35842;
  6354. var RGBA_PVRTC_2BPPV1_Format = 35843;
  6355. var RGB_ETC1_Format = 36196;
  6356. var RGB_ETC2_Format = 37492;
  6357. var RGBA_ETC2_EAC_Format = 37496;
  6358. var RGBA_ASTC_4x4_Format = 37808;
  6359. var RGBA_ASTC_5x4_Format = 37809;
  6360. var RGBA_ASTC_5x5_Format = 37810;
  6361. var RGBA_ASTC_6x5_Format = 37811;
  6362. var RGBA_ASTC_6x6_Format = 37812;
  6363. var RGBA_ASTC_8x5_Format = 37813;
  6364. var RGBA_ASTC_8x6_Format = 37814;
  6365. var RGBA_ASTC_8x8_Format = 37815;
  6366. var RGBA_ASTC_10x5_Format = 37816;
  6367. var RGBA_ASTC_10x6_Format = 37817;
  6368. var RGBA_ASTC_10x8_Format = 37818;
  6369. var RGBA_ASTC_10x10_Format = 37819;
  6370. var RGBA_ASTC_12x10_Format = 37820;
  6371. var RGBA_ASTC_12x12_Format = 37821;
  6372. var RGBA_BPTC_Format = 36492;
  6373. var SRGB8_ALPHA8_ASTC_4x4_Format = 37840;
  6374. var SRGB8_ALPHA8_ASTC_5x4_Format = 37841;
  6375. var SRGB8_ALPHA8_ASTC_5x5_Format = 37842;
  6376. var SRGB8_ALPHA8_ASTC_6x5_Format = 37843;
  6377. var SRGB8_ALPHA8_ASTC_6x6_Format = 37844;
  6378. var SRGB8_ALPHA8_ASTC_8x5_Format = 37845;
  6379. var SRGB8_ALPHA8_ASTC_8x6_Format = 37846;
  6380. var SRGB8_ALPHA8_ASTC_8x8_Format = 37847;
  6381. var SRGB8_ALPHA8_ASTC_10x5_Format = 37848;
  6382. var SRGB8_ALPHA8_ASTC_10x6_Format = 37849;
  6383. var SRGB8_ALPHA8_ASTC_10x8_Format = 37850;
  6384. var SRGB8_ALPHA8_ASTC_10x10_Format = 37851;
  6385. var SRGB8_ALPHA8_ASTC_12x10_Format = 37852;
  6386. var SRGB8_ALPHA8_ASTC_12x12_Format = 37853;
  6387. var LoopOnce = 2200;
  6388. var LoopRepeat = 2201;
  6389. var LoopPingPong = 2202;
  6390. var InterpolateDiscrete = 2300;
  6391. var InterpolateLinear = 2301;
  6392. var InterpolateSmooth = 2302;
  6393. var ZeroCurvatureEnding = 2400;
  6394. var ZeroSlopeEnding = 2401;
  6395. var WrapAroundEnding = 2402;
  6396. var NormalAnimationBlendMode = 2500;
  6397. var AdditiveAnimationBlendMode = 2501;
  6398. var TrianglesDrawMode = 0;
  6399. var TriangleStripDrawMode = 1;
  6400. var TriangleFanDrawMode = 2;
  6401. var LinearEncoding = 3000;
  6402. var sRGBEncoding = 3001;
  6403. var GammaEncoding = 3007;
  6404. var RGBEEncoding = 3002;
  6405. var LogLuvEncoding = 3003;
  6406. var RGBM7Encoding = 3004;
  6407. var RGBM16Encoding = 3005;
  6408. var RGBDEncoding = 3006;
  6409. var BasicDepthPacking = 3200;
  6410. var RGBADepthPacking = 3201;
  6411. var TangentSpaceNormalMap = 0;
  6412. var ObjectSpaceNormalMap = 1;
  6413. var ZeroStencilOp = 0;
  6414. var KeepStencilOp = 7680;
  6415. var ReplaceStencilOp = 7681;
  6416. var IncrementStencilOp = 7682;
  6417. var DecrementStencilOp = 7683;
  6418. var IncrementWrapStencilOp = 34055;
  6419. var DecrementWrapStencilOp = 34056;
  6420. var InvertStencilOp = 5386;
  6421. var NeverStencilFunc = 512;
  6422. var LessStencilFunc = 513;
  6423. var EqualStencilFunc = 514;
  6424. var LessEqualStencilFunc = 515;
  6425. var GreaterStencilFunc = 516;
  6426. var NotEqualStencilFunc = 517;
  6427. var GreaterEqualStencilFunc = 518;
  6428. var AlwaysStencilFunc = 519;
  6429. var StaticDrawUsage = 35044;
  6430. var DynamicDrawUsage = 35048;
  6431. var StreamDrawUsage = 35040;
  6432. var StaticReadUsage = 35045;
  6433. var DynamicReadUsage = 35049;
  6434. var StreamReadUsage = 35041;
  6435. var StaticCopyUsage = 35046;
  6436. var DynamicCopyUsage = 35050;
  6437. var StreamCopyUsage = 35042;
  6438. var GLSL1 = '100';
  6439. var GLSL3 = '300 es';
  6440. function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
  6441. try {
  6442. var info = gen[key](arg);
  6443. var value = info.value;
  6444. } catch (error) {
  6445. reject(error);
  6446. return;
  6447. }
  6448. if (info.done) {
  6449. resolve(value);
  6450. } else {
  6451. Promise.resolve(value).then(_next, _throw);
  6452. }
  6453. }
  6454. function _asyncToGenerator(fn) {
  6455. return function () {
  6456. var self = this,
  6457. args = arguments;
  6458. return new Promise(function (resolve, reject) {
  6459. var gen = fn.apply(self, args);
  6460. function _next(value) {
  6461. asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
  6462. }
  6463. function _throw(err) {
  6464. asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
  6465. }
  6466. _next(undefined);
  6467. });
  6468. };
  6469. }
  6470. function _defineProperties(target, props) {
  6471. for (var i = 0; i < props.length; i++) {
  6472. var descriptor = props[i];
  6473. descriptor.enumerable = descriptor.enumerable || false;
  6474. descriptor.configurable = true;
  6475. if ("value" in descriptor) descriptor.writable = true;
  6476. Object.defineProperty(target, descriptor.key, descriptor);
  6477. }
  6478. }
  6479. function _createClass(Constructor, protoProps, staticProps) {
  6480. if (protoProps) _defineProperties(Constructor.prototype, protoProps);
  6481. if (staticProps) _defineProperties(Constructor, staticProps);
  6482. return Constructor;
  6483. }
  6484. function _inheritsLoose(subClass, superClass) {
  6485. subClass.prototype = Object.create(superClass.prototype);
  6486. subClass.prototype.constructor = subClass;
  6487. subClass.__proto__ = superClass;
  6488. }
  6489. function _assertThisInitialized(self) {
  6490. if (self === void 0) {
  6491. throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  6492. }
  6493. return self;
  6494. }
  6495. function _unsupportedIterableToArray(o, minLen) {
  6496. if (!o) return;
  6497. if (typeof o === "string") return _arrayLikeToArray(o, minLen);
  6498. var n = Object.prototype.toString.call(o).slice(8, -1);
  6499. if (n === "Object" && o.constructor) n = o.constructor.name;
  6500. if (n === "Map" || n === "Set") return Array.from(o);
  6501. if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
  6502. }
  6503. function _arrayLikeToArray(arr, len) {
  6504. if (len == null || len > arr.length) len = arr.length;
  6505. for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
  6506. return arr2;
  6507. }
  6508. function _createForOfIteratorHelperLoose(o, allowArrayLike) {
  6509. var it;
  6510. if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) {
  6511. if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") {
  6512. if (it) o = it;
  6513. var i = 0;
  6514. return function () {
  6515. if (i >= o.length) return {
  6516. done: true
  6517. };
  6518. return {
  6519. done: false,
  6520. value: o[i++]
  6521. };
  6522. };
  6523. }
  6524. throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
  6525. }
  6526. it = o[Symbol.iterator]();
  6527. return it.next.bind(it);
  6528. }
  6529. /**
  6530. * https://github.com/mrdoob/eventdispatcher.js/
  6531. */
  6532. function EventDispatcher() {}
  6533. Object.assign(EventDispatcher.prototype, {
  6534. addEventListener: function addEventListener(type, listener) {
  6535. if (this._listeners === undefined) this._listeners = {};
  6536. var listeners = this._listeners;
  6537. if (listeners[type] === undefined) {
  6538. listeners[type] = [];
  6539. }
  6540. if (listeners[type].indexOf(listener) === -1) {
  6541. listeners[type].push(listener);
  6542. }
  6543. },
  6544. hasEventListener: function hasEventListener(type, listener) {
  6545. if (this._listeners === undefined) return false;
  6546. var listeners = this._listeners;
  6547. return listeners[type] !== undefined && listeners[type].indexOf(listener) !== -1;
  6548. },
  6549. removeEventListener: function removeEventListener(type, listener) {
  6550. if (this._listeners === undefined) return;
  6551. var listeners = this._listeners;
  6552. var listenerArray = listeners[type];
  6553. if (listenerArray !== undefined) {
  6554. var index = listenerArray.indexOf(listener);
  6555. if (index !== -1) {
  6556. listenerArray.splice(index, 1);
  6557. }
  6558. }
  6559. },
  6560. dispatchEvent: function dispatchEvent(event) {
  6561. if (this._listeners === undefined) return;
  6562. var listeners = this._listeners;
  6563. var listenerArray = listeners[event.type];
  6564. if (listenerArray !== undefined) {
  6565. event.target = this; // Make a copy, in case listeners are removed while iterating.
  6566. var array = listenerArray.slice(0);
  6567. for (var i = 0, l = array.length; i < l; i++) {
  6568. array[i].call(this, event);
  6569. }
  6570. }
  6571. }
  6572. });
  6573. var _lut = [];
  6574. for (var i = 0; i < 256; i++) {
  6575. _lut[i] = (i < 16 ? '0' : '') + i.toString(16);
  6576. }
  6577. var _seed = 1234567;
  6578. var MathUtils = {
  6579. DEG2RAD: Math.PI / 180,
  6580. RAD2DEG: 180 / Math.PI,
  6581. generateUUID: function generateUUID() {
  6582. // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/21963136#21963136
  6583. var d0 = Math.random() * 0xffffffff | 0;
  6584. var d1 = Math.random() * 0xffffffff | 0;
  6585. var d2 = Math.random() * 0xffffffff | 0;
  6586. var d3 = Math.random() * 0xffffffff | 0;
  6587. var uuid = _lut[d0 & 0xff] + _lut[d0 >> 8 & 0xff] + _lut[d0 >> 16 & 0xff] + _lut[d0 >> 24 & 0xff] + '-' + _lut[d1 & 0xff] + _lut[d1 >> 8 & 0xff] + '-' + _lut[d1 >> 16 & 0x0f | 0x40] + _lut[d1 >> 24 & 0xff] + '-' + _lut[d2 & 0x3f | 0x80] + _lut[d2 >> 8 & 0xff] + '-' + _lut[d2 >> 16 & 0xff] + _lut[d2 >> 24 & 0xff] + _lut[d3 & 0xff] + _lut[d3 >> 8 & 0xff] + _lut[d3 >> 16 & 0xff] + _lut[d3 >> 24 & 0xff]; // .toUpperCase() here flattens concatenated strings to save heap memory space.
  6588. return uuid.toUpperCase();
  6589. },
  6590. clamp: function clamp(value, min, max) {
  6591. return Math.max(min, Math.min(max, value));
  6592. },
  6593. // compute euclidian modulo of m % n
  6594. // https://en.wikipedia.org/wiki/Modulo_operation
  6595. euclideanModulo: function euclideanModulo(n, m) {
  6596. return (n % m + m) % m;
  6597. },
  6598. // Linear mapping from range <a1, a2> to range <b1, b2>
  6599. mapLinear: function mapLinear(x, a1, a2, b1, b2) {
  6600. return b1 + (x - a1) * (b2 - b1) / (a2 - a1);
  6601. },
  6602. // https://en.wikipedia.org/wiki/Linear_interpolation
  6603. lerp: function lerp(x, y, t) {
  6604. return (1 - t) * x + t * y;
  6605. },
  6606. // http://www.rorydriscoll.com/2016/03/07/frame-rate-independent-damping-using-lerp/
  6607. damp: function damp(x, y, lambda, dt) {
  6608. return MathUtils.lerp(x, y, 1 - Math.exp(-lambda * dt));
  6609. },
  6610. // https://www.desmos.com/calculator/vcsjnyz7x4
  6611. pingpong: function pingpong(x, length) {
  6612. if (length === void 0) {
  6613. length = 1;
  6614. }
  6615. return length - Math.abs(MathUtils.euclideanModulo(x, length * 2) - length);
  6616. },
  6617. // http://en.wikipedia.org/wiki/Smoothstep
  6618. smoothstep: function smoothstep(x, min, max) {
  6619. if (x <= min) return 0;
  6620. if (x >= max) return 1;
  6621. x = (x - min) / (max - min);
  6622. return x * x * (3 - 2 * x);
  6623. },
  6624. smootherstep: function smootherstep(x, min, max) {
  6625. if (x <= min) return 0;
  6626. if (x >= max) return 1;
  6627. x = (x - min) / (max - min);
  6628. return x * x * x * (x * (x * 6 - 15) + 10);
  6629. },
  6630. // Random integer from <low, high> interval
  6631. randInt: function randInt(low, high) {
  6632. return low + Math.floor(Math.random() * (high - low + 1));
  6633. },
  6634. // Random float from <low, high> interval
  6635. randFloat: function randFloat(low, high) {
  6636. return low + Math.random() * (high - low);
  6637. },
  6638. // Random float from <-range/2, range/2> interval
  6639. randFloatSpread: function randFloatSpread(range) {
  6640. return range * (0.5 - Math.random());
  6641. },
  6642. // Deterministic pseudo-random float in the interval [ 0, 1 ]
  6643. seededRandom: function seededRandom(s) {
  6644. if (s !== undefined) _seed = s % 2147483647; // Park-Miller algorithm
  6645. _seed = _seed * 16807 % 2147483647;
  6646. return (_seed - 1) / 2147483646;
  6647. },
  6648. degToRad: function degToRad(degrees) {
  6649. return degrees * MathUtils.DEG2RAD;
  6650. },
  6651. radToDeg: function radToDeg(radians) {
  6652. return radians * MathUtils.RAD2DEG;
  6653. },
  6654. isPowerOfTwo: function isPowerOfTwo(value) {
  6655. return (value & value - 1) === 0 && value !== 0;
  6656. },
  6657. ceilPowerOfTwo: function ceilPowerOfTwo(value) {
  6658. return Math.pow(2, Math.ceil(Math.log(value) / Math.LN2));
  6659. },
  6660. floorPowerOfTwo: function floorPowerOfTwo(value) {
  6661. return Math.pow(2, Math.floor(Math.log(value) / Math.LN2));
  6662. },
  6663. setQuaternionFromProperEuler: function setQuaternionFromProperEuler(q, a, b, c, order) {
  6664. // Intrinsic Proper Euler Angles - see https://en.wikipedia.org/wiki/Euler_angles
  6665. // rotations are applied to the axes in the order specified by 'order'
  6666. // rotation by angle 'a' is applied first, then by angle 'b', then by angle 'c'
  6667. // angles are in radians
  6668. var cos = Math.cos;
  6669. var sin = Math.sin;
  6670. var c2 = cos(b / 2);
  6671. var s2 = sin(b / 2);
  6672. var c13 = cos((a + c) / 2);
  6673. var s13 = sin((a + c) / 2);
  6674. var c1_3 = cos((a - c) / 2);
  6675. var s1_3 = sin((a - c) / 2);
  6676. var c3_1 = cos((c - a) / 2);
  6677. var s3_1 = sin((c - a) / 2);
  6678. switch (order) {
  6679. case 'XYX':
  6680. q.set(c2 * s13, s2 * c1_3, s2 * s1_3, c2 * c13);
  6681. break;
  6682. case 'YZY':
  6683. q.set(s2 * s1_3, c2 * s13, s2 * c1_3, c2 * c13);
  6684. break;
  6685. case 'ZXZ':
  6686. q.set(s2 * c1_3, s2 * s1_3, c2 * s13, c2 * c13);
  6687. break;
  6688. case 'XZX':
  6689. q.set(c2 * s13, s2 * s3_1, s2 * c3_1, c2 * c13);
  6690. break;
  6691. case 'YXY':
  6692. q.set(s2 * c3_1, c2 * s13, s2 * s3_1, c2 * c13);
  6693. break;
  6694. case 'ZYZ':
  6695. q.set(s2 * s3_1, s2 * c3_1, c2 * s13, c2 * c13);
  6696. break;
  6697. default:
  6698. console.warn('THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: ' + order);
  6699. }
  6700. }
  6701. };
  6702. var Vector2 = /*#__PURE__*/function () {
  6703. function Vector2(x, y) {
  6704. if (x === void 0) {
  6705. x = 0;
  6706. }
  6707. if (y === void 0) {
  6708. y = 0;
  6709. }
  6710. Object.defineProperty(this, 'isVector2', {
  6711. value: true
  6712. });
  6713. this.x = x;
  6714. this.y = y;
  6715. }
  6716. var _proto = Vector2.prototype;
  6717. _proto.set = function set(x, y) {
  6718. this.x = x;
  6719. this.y = y;
  6720. return this;
  6721. };
  6722. _proto.setScalar = function setScalar(scalar) {
  6723. this.x = scalar;
  6724. this.y = scalar;
  6725. return this;
  6726. };
  6727. _proto.setX = function setX(x) {
  6728. this.x = x;
  6729. return this;
  6730. };
  6731. _proto.setY = function setY(y) {
  6732. this.y = y;
  6733. return this;
  6734. };
  6735. _proto.setComponent = function setComponent(index, value) {
  6736. switch (index) {
  6737. case 0:
  6738. this.x = value;
  6739. break;
  6740. case 1:
  6741. this.y = value;
  6742. break;
  6743. default:
  6744. throw new Error('index is out of range: ' + index);
  6745. }
  6746. return this;
  6747. };
  6748. _proto.getComponent = function getComponent(index) {
  6749. switch (index) {
  6750. case 0:
  6751. return this.x;
  6752. case 1:
  6753. return this.y;
  6754. default:
  6755. throw new Error('index is out of range: ' + index);
  6756. }
  6757. };
  6758. _proto.clone = function clone() {
  6759. return new this.constructor(this.x, this.y);
  6760. };
  6761. _proto.copy = function copy(v) {
  6762. this.x = v.x;
  6763. this.y = v.y;
  6764. return this;
  6765. };
  6766. _proto.add = function add(v, w) {
  6767. if (w !== undefined) {
  6768. console.warn('THREE.Vector2: .add() now only accepts one argument. Use .addVectors( a, b ) instead.');
  6769. return this.addVectors(v, w);
  6770. }
  6771. this.x += v.x;
  6772. this.y += v.y;
  6773. return this;
  6774. };
  6775. _proto.addScalar = function addScalar(s) {
  6776. this.x += s;
  6777. this.y += s;
  6778. return this;
  6779. };
  6780. _proto.addVectors = function addVectors(a, b) {
  6781. this.x = a.x + b.x;
  6782. this.y = a.y + b.y;
  6783. return this;
  6784. };
  6785. _proto.addScaledVector = function addScaledVector(v, s) {
  6786. this.x += v.x * s;
  6787. this.y += v.y * s;
  6788. return this;
  6789. };
  6790. _proto.sub = function sub(v, w) {
  6791. if (w !== undefined) {
  6792. console.warn('THREE.Vector2: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.');
  6793. return this.subVectors(v, w);
  6794. }
  6795. this.x -= v.x;
  6796. this.y -= v.y;
  6797. return this;
  6798. };
  6799. _proto.subScalar = function subScalar(s) {
  6800. this.x -= s;
  6801. this.y -= s;
  6802. return this;
  6803. };
  6804. _proto.subVectors = function subVectors(a, b) {
  6805. this.x = a.x - b.x;
  6806. this.y = a.y - b.y;
  6807. return this;
  6808. };
  6809. _proto.multiply = function multiply(v) {
  6810. this.x *= v.x;
  6811. this.y *= v.y;
  6812. return this;
  6813. };
  6814. _proto.multiplyScalar = function multiplyScalar(scalar) {
  6815. this.x *= scalar;
  6816. this.y *= scalar;
  6817. return this;
  6818. };
  6819. _proto.divide = function divide(v) {
  6820. this.x /= v.x;
  6821. this.y /= v.y;
  6822. return this;
  6823. };
  6824. _proto.divideScalar = function divideScalar(scalar) {
  6825. return this.multiplyScalar(1 / scalar);
  6826. };
  6827. _proto.applyMatrix3 = function applyMatrix3(m) {
  6828. var x = this.x,
  6829. y = this.y;
  6830. var e = m.elements;
  6831. this.x = e[0] * x + e[3] * y + e[6];
  6832. this.y = e[1] * x + e[4] * y + e[7];
  6833. return this;
  6834. };
  6835. _proto.min = function min(v) {
  6836. this.x = Math.min(this.x, v.x);
  6837. this.y = Math.min(this.y, v.y);
  6838. return this;
  6839. };
  6840. _proto.max = function max(v) {
  6841. this.x = Math.max(this.x, v.x);
  6842. this.y = Math.max(this.y, v.y);
  6843. return this;
  6844. };
  6845. _proto.clamp = function clamp(min, max) {
  6846. // assumes min < max, componentwise
  6847. this.x = Math.max(min.x, Math.min(max.x, this.x));
  6848. this.y = Math.max(min.y, Math.min(max.y, this.y));
  6849. return this;
  6850. };
  6851. _proto.clampScalar = function clampScalar(minVal, maxVal) {
  6852. this.x = Math.max(minVal, Math.min(maxVal, this.x));
  6853. this.y = Math.max(minVal, Math.min(maxVal, this.y));
  6854. return this;
  6855. };
  6856. _proto.clampLength = function clampLength(min, max) {
  6857. var length = this.length();
  6858. return this.divideScalar(length || 1).multiplyScalar(Math.max(min, Math.min(max, length)));
  6859. };
  6860. _proto.floor = function floor() {
  6861. this.x = Math.floor(this.x);
  6862. this.y = Math.floor(this.y);
  6863. return this;
  6864. };
  6865. _proto.ceil = function ceil() {
  6866. this.x = Math.ceil(this.x);
  6867. this.y = Math.ceil(this.y);
  6868. return this;
  6869. };
  6870. _proto.round = function round() {
  6871. this.x = Math.round(this.x);
  6872. this.y = Math.round(this.y);
  6873. return this;
  6874. };
  6875. _proto.roundToZero = function roundToZero() {
  6876. this.x = this.x < 0 ? Math.ceil(this.x) : Math.floor(this.x);
  6877. this.y = this.y < 0 ? Math.ceil(this.y) : Math.floor(this.y);
  6878. return this;
  6879. };
  6880. _proto.negate = function negate() {
  6881. this.x = -this.x;
  6882. this.y = -this.y;
  6883. return this;
  6884. };
  6885. _proto.dot = function dot(v) {
  6886. return this.x * v.x + this.y * v.y;
  6887. };
  6888. _proto.cross = function cross(v) {
  6889. return this.x * v.y - this.y * v.x;
  6890. };
  6891. _proto.lengthSq = function lengthSq() {
  6892. return this.x * this.x + this.y * this.y;
  6893. };
  6894. _proto.length = function length() {
  6895. return Math.sqrt(this.x * this.x + this.y * this.y);
  6896. };
  6897. _proto.manhattanLength = function manhattanLength() {
  6898. return Math.abs(this.x) + Math.abs(this.y);
  6899. };
  6900. _proto.normalize = function normalize() {
  6901. return this.divideScalar(this.length() || 1);
  6902. };
  6903. _proto.angle = function angle() {
  6904. // computes the angle in radians with respect to the positive x-axis
  6905. var angle = Math.atan2(-this.y, -this.x) + Math.PI;
  6906. return angle;
  6907. };
  6908. _proto.distanceTo = function distanceTo(v) {
  6909. return Math.sqrt(this.distanceToSquared(v));
  6910. };
  6911. _proto.distanceToSquared = function distanceToSquared(v) {
  6912. var dx = this.x - v.x,
  6913. dy = this.y - v.y;
  6914. return dx * dx + dy * dy;
  6915. };
  6916. _proto.manhattanDistanceTo = function manhattanDistanceTo(v) {
  6917. return Math.abs(this.x - v.x) + Math.abs(this.y - v.y);
  6918. };
  6919. _proto.setLength = function setLength(length) {
  6920. return this.normalize().multiplyScalar(length);
  6921. };
  6922. _proto.lerp = function lerp(v, alpha) {
  6923. this.x += (v.x - this.x) * alpha;
  6924. this.y += (v.y - this.y) * alpha;
  6925. return this;
  6926. };
  6927. _proto.lerpVectors = function lerpVectors(v1, v2, alpha) {
  6928. this.x = v1.x + (v2.x - v1.x) * alpha;
  6929. this.y = v1.y + (v2.y - v1.y) * alpha;
  6930. return this;
  6931. };
  6932. _proto.equals = function equals(v) {
  6933. return v.x === this.x && v.y === this.y;
  6934. };
  6935. _proto.fromArray = function fromArray(array, offset) {
  6936. if (offset === void 0) {
  6937. offset = 0;
  6938. }
  6939. this.x = array[offset];
  6940. this.y = array[offset + 1];
  6941. return this;
  6942. };
  6943. _proto.toArray = function toArray(array, offset) {
  6944. if (array === void 0) {
  6945. array = [];
  6946. }
  6947. if (offset === void 0) {
  6948. offset = 0;
  6949. }
  6950. array[offset] = this.x;
  6951. array[offset + 1] = this.y;
  6952. return array;
  6953. };
  6954. _proto.fromBufferAttribute = function fromBufferAttribute(attribute, index, offset) {
  6955. if (offset !== undefined) {
  6956. console.warn('THREE.Vector2: offset has been removed from .fromBufferAttribute().');
  6957. }
  6958. this.x = attribute.getX(index);
  6959. this.y = attribute.getY(index);
  6960. return this;
  6961. };
  6962. _proto.rotateAround = function rotateAround(center, angle) {
  6963. var c = Math.cos(angle),
  6964. s = Math.sin(angle);
  6965. var x = this.x - center.x;
  6966. var y = this.y - center.y;
  6967. this.x = x * c - y * s + center.x;
  6968. this.y = x * s + y * c + center.y;
  6969. return this;
  6970. };
  6971. _proto.random = function random() {
  6972. this.x = Math.random();
  6973. this.y = Math.random();
  6974. return this;
  6975. };
  6976. _createClass(Vector2, [{
  6977. key: "width",
  6978. get: function get() {
  6979. return this.x;
  6980. },
  6981. set: function set(value) {
  6982. this.x = value;
  6983. }
  6984. }, {
  6985. key: "height",
  6986. get: function get() {
  6987. return this.y;
  6988. },
  6989. set: function set(value) {
  6990. this.y = value;
  6991. }
  6992. }]);
  6993. return Vector2;
  6994. }();
  6995. var Matrix3 = /*#__PURE__*/function () {
  6996. function Matrix3() {
  6997. Object.defineProperty(this, 'isMatrix3', {
  6998. value: true
  6999. });
  7000. this.elements = [1, 0, 0, 0, 1, 0, 0, 0, 1];
  7001. if (arguments.length > 0) {
  7002. console.error('THREE.Matrix3: the constructor no longer reads arguments. use .set() instead.');
  7003. }
  7004. }
  7005. var _proto = Matrix3.prototype;
  7006. _proto.set = function set(n11, n12, n13, n21, n22, n23, n31, n32, n33) {
  7007. var te = this.elements;
  7008. te[0] = n11;
  7009. te[1] = n21;
  7010. te[2] = n31;
  7011. te[3] = n12;
  7012. te[4] = n22;
  7013. te[5] = n32;
  7014. te[6] = n13;
  7015. te[7] = n23;
  7016. te[8] = n33;
  7017. return this;
  7018. };
  7019. _proto.identity = function identity() {
  7020. this.set(1, 0, 0, 0, 1, 0, 0, 0, 1);
  7021. return this;
  7022. };
  7023. _proto.clone = function clone() {
  7024. return new this.constructor().fromArray(this.elements);
  7025. };
  7026. _proto.copy = function copy(m) {
  7027. var te = this.elements;
  7028. var me = m.elements;
  7029. te[0] = me[0];
  7030. te[1] = me[1];
  7031. te[2] = me[2];
  7032. te[3] = me[3];
  7033. te[4] = me[4];
  7034. te[5] = me[5];
  7035. te[6] = me[6];
  7036. te[7] = me[7];
  7037. te[8] = me[8];
  7038. return this;
  7039. };
  7040. _proto.extractBasis = function extractBasis(xAxis, yAxis, zAxis) {
  7041. xAxis.setFromMatrix3Column(this, 0);
  7042. yAxis.setFromMatrix3Column(this, 1);
  7043. zAxis.setFromMatrix3Column(this, 2);
  7044. return this;
  7045. };
  7046. _proto.setFromMatrix4 = function setFromMatrix4(m) {
  7047. var me = m.elements;
  7048. this.set(me[0], me[4], me[8], me[1], me[5], me[9], me[2], me[6], me[10]);
  7049. return this;
  7050. };
  7051. _proto.multiply = function multiply(m) {
  7052. return this.multiplyMatrices(this, m);
  7053. };
  7054. _proto.premultiply = function premultiply(m) {
  7055. return this.multiplyMatrices(m, this);
  7056. };
  7057. _proto.multiplyMatrices = function multiplyMatrices(a, b) {
  7058. var ae = a.elements;
  7059. var be = b.elements;
  7060. var te = this.elements;
  7061. var a11 = ae[0],
  7062. a12 = ae[3],
  7063. a13 = ae[6];
  7064. var a21 = ae[1],
  7065. a22 = ae[4],
  7066. a23 = ae[7];
  7067. var a31 = ae[2],
  7068. a32 = ae[5],
  7069. a33 = ae[8];
  7070. var b11 = be[0],
  7071. b12 = be[3],
  7072. b13 = be[6];
  7073. var b21 = be[1],
  7074. b22 = be[4],
  7075. b23 = be[7];
  7076. var b31 = be[2],
  7077. b32 = be[5],
  7078. b33 = be[8];
  7079. te[0] = a11 * b11 + a12 * b21 + a13 * b31;
  7080. te[3] = a11 * b12 + a12 * b22 + a13 * b32;
  7081. te[6] = a11 * b13 + a12 * b23 + a13 * b33;
  7082. te[1] = a21 * b11 + a22 * b21 + a23 * b31;
  7083. te[4] = a21 * b12 + a22 * b22 + a23 * b32;
  7084. te[7] = a21 * b13 + a22 * b23 + a23 * b33;
  7085. te[2] = a31 * b11 + a32 * b21 + a33 * b31;
  7086. te[5] = a31 * b12 + a32 * b22 + a33 * b32;
  7087. te[8] = a31 * b13 + a32 * b23 + a33 * b33;
  7088. return this;
  7089. };
  7090. _proto.multiplyScalar = function multiplyScalar(s) {
  7091. var te = this.elements;
  7092. te[0] *= s;
  7093. te[3] *= s;
  7094. te[6] *= s;
  7095. te[1] *= s;
  7096. te[4] *= s;
  7097. te[7] *= s;
  7098. te[2] *= s;
  7099. te[5] *= s;
  7100. te[8] *= s;
  7101. return this;
  7102. };
  7103. _proto.determinant = function determinant() {
  7104. var te = this.elements;
  7105. var a = te[0],
  7106. b = te[1],
  7107. c = te[2],
  7108. d = te[3],
  7109. e = te[4],
  7110. f = te[5],
  7111. g = te[6],
  7112. h = te[7],
  7113. i = te[8];
  7114. return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;
  7115. };
  7116. _proto.invert = function invert() {
  7117. var te = this.elements,
  7118. n11 = te[0],
  7119. n21 = te[1],
  7120. n31 = te[2],
  7121. n12 = te[3],
  7122. n22 = te[4],
  7123. n32 = te[5],
  7124. n13 = te[6],
  7125. n23 = te[7],
  7126. n33 = te[8],
  7127. t11 = n33 * n22 - n32 * n23,
  7128. t12 = n32 * n13 - n33 * n12,
  7129. t13 = n23 * n12 - n22 * n13,
  7130. det = n11 * t11 + n21 * t12 + n31 * t13;
  7131. if (det === 0) return this.set(0, 0, 0, 0, 0, 0, 0, 0, 0);
  7132. var detInv = 1 / det;
  7133. te[0] = t11 * detInv;
  7134. te[1] = (n31 * n23 - n33 * n21) * detInv;
  7135. te[2] = (n32 * n21 - n31 * n22) * detInv;
  7136. te[3] = t12 * detInv;
  7137. te[4] = (n33 * n11 - n31 * n13) * detInv;
  7138. te[5] = (n31 * n12 - n32 * n11) * detInv;
  7139. te[6] = t13 * detInv;
  7140. te[7] = (n21 * n13 - n23 * n11) * detInv;
  7141. te[8] = (n22 * n11 - n21 * n12) * detInv;
  7142. return this;
  7143. };
  7144. _proto.transpose = function transpose() {
  7145. var tmp;
  7146. var m = this.elements;
  7147. tmp = m[1];
  7148. m[1] = m[3];
  7149. m[3] = tmp;
  7150. tmp = m[2];
  7151. m[2] = m[6];
  7152. m[6] = tmp;
  7153. tmp = m[5];
  7154. m[5] = m[7];
  7155. m[7] = tmp;
  7156. return this;
  7157. };
  7158. _proto.getNormalMatrix = function getNormalMatrix(matrix4) {
  7159. return this.setFromMatrix4(matrix4).copy(this).invert().transpose();
  7160. };
  7161. _proto.transposeIntoArray = function transposeIntoArray(r) {
  7162. var m = this.elements;
  7163. r[0] = m[0];
  7164. r[1] = m[3];
  7165. r[2] = m[6];
  7166. r[3] = m[1];
  7167. r[4] = m[4];
  7168. r[5] = m[7];
  7169. r[6] = m[2];
  7170. r[7] = m[5];
  7171. r[8] = m[8];
  7172. return this;
  7173. };
  7174. _proto.setUvTransform = function setUvTransform(tx, ty, sx, sy, rotation, cx, cy) {
  7175. var c = Math.cos(rotation);
  7176. var s = Math.sin(rotation);
  7177. this.set(sx * c, sx * s, -sx * (c * cx + s * cy) + cx + tx, -sy * s, sy * c, -sy * (-s * cx + c * cy) + cy + ty, 0, 0, 1);
  7178. return this;
  7179. };
  7180. _proto.scale = function scale(sx, sy) {
  7181. var te = this.elements;
  7182. te[0] *= sx;
  7183. te[3] *= sx;
  7184. te[6] *= sx;
  7185. te[1] *= sy;
  7186. te[4] *= sy;
  7187. te[7] *= sy;
  7188. return this;
  7189. };
  7190. _proto.rotate = function rotate(theta) {
  7191. var c = Math.cos(theta);
  7192. var s = Math.sin(theta);
  7193. var te = this.elements;
  7194. var a11 = te[0],
  7195. a12 = te[3],
  7196. a13 = te[6];
  7197. var a21 = te[1],
  7198. a22 = te[4],
  7199. a23 = te[7];
  7200. te[0] = c * a11 + s * a21;
  7201. te[3] = c * a12 + s * a22;
  7202. te[6] = c * a13 + s * a23;
  7203. te[1] = -s * a11 + c * a21;
  7204. te[4] = -s * a12 + c * a22;
  7205. te[7] = -s * a13 + c * a23;
  7206. return this;
  7207. };
  7208. _proto.translate = function translate(tx, ty) {
  7209. var te = this.elements;
  7210. te[0] += tx * te[2];
  7211. te[3] += tx * te[5];
  7212. te[6] += tx * te[8];
  7213. te[1] += ty * te[2];
  7214. te[4] += ty * te[5];
  7215. te[7] += ty * te[8];
  7216. return this;
  7217. };
  7218. _proto.equals = function equals(matrix) {
  7219. var te = this.elements;
  7220. var me = matrix.elements;
  7221. for (var i = 0; i < 9; i++) {
  7222. if (te[i] !== me[i]) return false;
  7223. }
  7224. return true;
  7225. };
  7226. _proto.fromArray = function fromArray(array, offset) {
  7227. if (offset === void 0) {
  7228. offset = 0;
  7229. }
  7230. for (var i = 0; i < 9; i++) {
  7231. this.elements[i] = array[i + offset];
  7232. }
  7233. return this;
  7234. };
  7235. _proto.toArray = function toArray(array, offset) {
  7236. if (array === void 0) {
  7237. array = [];
  7238. }
  7239. if (offset === void 0) {
  7240. offset = 0;
  7241. }
  7242. var te = this.elements;
  7243. array[offset] = te[0];
  7244. array[offset + 1] = te[1];
  7245. array[offset + 2] = te[2];
  7246. array[offset + 3] = te[3];
  7247. array[offset + 4] = te[4];
  7248. array[offset + 5] = te[5];
  7249. array[offset + 6] = te[6];
  7250. array[offset + 7] = te[7];
  7251. array[offset + 8] = te[8];
  7252. return array;
  7253. };
  7254. return Matrix3;
  7255. }();
  7256. var _canvas;
  7257. var ImageUtils = {
  7258. getDataURL: function getDataURL(image) {
  7259. if (/^data:/i.test(image.src)) {
  7260. return image.src;
  7261. }
  7262. if (typeof HTMLCanvasElement == 'undefined') {
  7263. return image.src;
  7264. }
  7265. var canvas;
  7266. if (image instanceof HTMLCanvasElement) {
  7267. canvas = image;
  7268. } else {
  7269. if (_canvas === undefined) _canvas = document.createElementNS('http://www.w3.org/1999/xhtml', 'canvas');
  7270. _canvas.width = image.width;
  7271. _canvas.height = image.height;
  7272. var context = _canvas.getContext('2d');
  7273. if (image instanceof ImageData) {
  7274. context.putImageData(image, 0, 0);
  7275. } else {
  7276. context.drawImage(image, 0, 0, image.width, image.height);
  7277. }
  7278. canvas = _canvas;
  7279. }
  7280. if (canvas.width > 2048 || canvas.height > 2048) {
  7281. return canvas.toDataURL('image/jpeg', 0.6);
  7282. } else {
  7283. return canvas.toDataURL('image/png');
  7284. }
  7285. }
  7286. };
  7287. var textureId = 0;
  7288. function Texture(image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding) {
  7289. if (image === void 0) {
  7290. image = Texture.DEFAULT_IMAGE;
  7291. }
  7292. if (mapping === void 0) {
  7293. mapping = Texture.DEFAULT_MAPPING;
  7294. }
  7295. if (wrapS === void 0) {
  7296. wrapS = ClampToEdgeWrapping;
  7297. }
  7298. if (wrapT === void 0) {
  7299. wrapT = ClampToEdgeWrapping;
  7300. }
  7301. if (magFilter === void 0) {
  7302. magFilter = LinearFilter;
  7303. }
  7304. if (minFilter === void 0) {
  7305. minFilter = LinearMipmapLinearFilter;
  7306. }
  7307. if (format === void 0) {
  7308. format = RGBAFormat;
  7309. }
  7310. if (type === void 0) {
  7311. type = UnsignedByteType;
  7312. }
  7313. if (anisotropy === void 0) {
  7314. anisotropy = 1;
  7315. }
  7316. if (encoding === void 0) {
  7317. encoding = LinearEncoding;
  7318. }
  7319. Object.defineProperty(this, 'id', {
  7320. value: textureId++
  7321. });
  7322. this.uuid = MathUtils.generateUUID();
  7323. this.name = '';
  7324. this.image = image;
  7325. this.mipmaps = [];
  7326. this.mapping = mapping;
  7327. this.wrapS = wrapS;
  7328. this.wrapT = wrapT;
  7329. this.magFilter = magFilter;
  7330. this.minFilter = minFilter;
  7331. this.anisotropy = anisotropy;
  7332. this.format = format;
  7333. this.internalFormat = null;
  7334. this.type = type;
  7335. this.offset = new Vector2(0, 0);
  7336. this.repeat = new Vector2(1, 1);
  7337. this.center = new Vector2(0, 0);
  7338. this.rotation = 0;
  7339. this.matrixAutoUpdate = true;
  7340. this.matrix = new Matrix3();
  7341. this.generateMipmaps = true;
  7342. this.premultiplyAlpha = false;
  7343. this.flipY = true;
  7344. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  7345. // Values of encoding !== THREE.LinearEncoding only supported on map, envMap and emissiveMap.
  7346. //
  7347. // Also changing the encoding after already used by a Material will not automatically make the Material
  7348. // update. You need to explicitly call Material.needsUpdate to trigger it to recompile.
  7349. this.encoding = encoding;
  7350. this.version = 0;
  7351. this.onUpdate = null;
  7352. }
  7353. Texture.DEFAULT_IMAGE = undefined;
  7354. Texture.DEFAULT_MAPPING = UVMapping;
  7355. Texture.prototype = Object.assign(Object.create(EventDispatcher.prototype), {
  7356. constructor: Texture,
  7357. isTexture: true,
  7358. updateMatrix: function updateMatrix() {
  7359. this.matrix.setUvTransform(this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y);
  7360. },
  7361. clone: function clone() {
  7362. return new this.constructor().copy(this);
  7363. },
  7364. copy: function copy(source) {
  7365. this.name = source.name;
  7366. this.image = source.image;
  7367. this.mipmaps = source.mipmaps.slice(0);
  7368. this.mapping = source.mapping;
  7369. this.wrapS = source.wrapS;
  7370. this.wrapT = source.wrapT;
  7371. this.magFilter = source.magFilter;
  7372. this.minFilter = source.minFilter;
  7373. this.anisotropy = source.anisotropy;
  7374. this.format = source.format;
  7375. this.internalFormat = source.internalFormat;
  7376. this.type = source.type;
  7377. this.offset.copy(source.offset);
  7378. this.repeat.copy(source.repeat);
  7379. this.center.copy(source.center);
  7380. this.rotation = source.rotation;
  7381. this.matrixAutoUpdate = source.matrixAutoUpdate;
  7382. this.matrix.copy(source.matrix);
  7383. this.generateMipmaps = source.generateMipmaps;
  7384. this.premultiplyAlpha = source.premultiplyAlpha;
  7385. this.flipY = source.flipY;
  7386. this.unpackAlignment = source.unpackAlignment;
  7387. this.encoding = source.encoding;
  7388. return this;
  7389. },
  7390. toJSON: function toJSON(meta) {
  7391. var isRootObject = meta === undefined || typeof meta === 'string';
  7392. if (!isRootObject && meta.textures[this.uuid] !== undefined) {
  7393. return meta.textures[this.uuid];
  7394. }
  7395. var output = {
  7396. metadata: {
  7397. version: 4.5,
  7398. type: 'Texture',
  7399. generator: 'Texture.toJSON'
  7400. },
  7401. uuid: this.uuid,
  7402. name: this.name,
  7403. mapping: this.mapping,
  7404. repeat: [this.repeat.x, this.repeat.y],
  7405. offset: [this.offset.x, this.offset.y],
  7406. center: [this.center.x, this.center.y],
  7407. rotation: this.rotation,
  7408. wrap: [this.wrapS, this.wrapT],
  7409. format: this.format,
  7410. type: this.type,
  7411. encoding: this.encoding,
  7412. minFilter: this.minFilter,
  7413. magFilter: this.magFilter,
  7414. anisotropy: this.anisotropy,
  7415. flipY: this.flipY,
  7416. premultiplyAlpha: this.premultiplyAlpha,
  7417. unpackAlignment: this.unpackAlignment
  7418. };
  7419. if (this.image !== undefined) {
  7420. // TODO: Move to THREE.Image
  7421. var image = this.image;
  7422. if (image.uuid === undefined) {
  7423. image.uuid = MathUtils.generateUUID(); // UGH
  7424. }
  7425. if (!isRootObject && meta.images[image.uuid] === undefined) {
  7426. var url;
  7427. if (Array.isArray(image)) {
  7428. // process array of images e.g. CubeTexture
  7429. url = [];
  7430. for (var i = 0, l = image.length; i < l; i++) {
  7431. // check cube texture with data textures
  7432. if (image[i].isDataTexture) {
  7433. url.push(serializeImage(image[i].image));
  7434. } else {
  7435. url.push(serializeImage(image[i]));
  7436. }
  7437. }
  7438. } else {
  7439. // process single image
  7440. url = serializeImage(image);
  7441. }
  7442. meta.images[image.uuid] = {
  7443. uuid: image.uuid,
  7444. url: url
  7445. };
  7446. }
  7447. output.image = image.uuid;
  7448. }
  7449. if (!isRootObject) {
  7450. meta.textures[this.uuid] = output;
  7451. }
  7452. return output;
  7453. },
  7454. dispose: function dispose() {
  7455. this.dispatchEvent({
  7456. type: 'dispose'
  7457. });
  7458. },
  7459. transformUv: function transformUv(uv) {
  7460. if (this.mapping !== UVMapping) return uv;
  7461. uv.applyMatrix3(this.matrix);
  7462. if (uv.x < 0 || uv.x > 1) {
  7463. switch (this.wrapS) {
  7464. case RepeatWrapping:
  7465. uv.x = uv.x - Math.floor(uv.x);
  7466. break;
  7467. case ClampToEdgeWrapping:
  7468. uv.x = uv.x < 0 ? 0 : 1;
  7469. break;
  7470. case MirroredRepeatWrapping:
  7471. if (Math.abs(Math.floor(uv.x) % 2) === 1) {
  7472. uv.x = Math.ceil(uv.x) - uv.x;
  7473. } else {
  7474. uv.x = uv.x - Math.floor(uv.x);
  7475. }
  7476. break;
  7477. }
  7478. }
  7479. if (uv.y < 0 || uv.y > 1) {
  7480. switch (this.wrapT) {
  7481. case RepeatWrapping:
  7482. uv.y = uv.y - Math.floor(uv.y);
  7483. break;
  7484. case ClampToEdgeWrapping:
  7485. uv.y = uv.y < 0 ? 0 : 1;
  7486. break;
  7487. case MirroredRepeatWrapping:
  7488. if (Math.abs(Math.floor(uv.y) % 2) === 1) {
  7489. uv.y = Math.ceil(uv.y) - uv.y;
  7490. } else {
  7491. uv.y = uv.y - Math.floor(uv.y);
  7492. }
  7493. break;
  7494. }
  7495. }
  7496. if (this.flipY) {
  7497. uv.y = 1 - uv.y;
  7498. }
  7499. return uv;
  7500. }
  7501. });
  7502. Object.defineProperty(Texture.prototype, 'needsUpdate', {
  7503. set: function set(value) {
  7504. if (value === true) this.version++;
  7505. }
  7506. });
  7507. function serializeImage(image) {
  7508. if (typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement || typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement || typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap) {
  7509. // default images
  7510. return ImageUtils.getDataURL(image);
  7511. } else {
  7512. if (image.data) {
  7513. // images of DataTexture
  7514. return {
  7515. data: Array.prototype.slice.call(image.data),
  7516. width: image.width,
  7517. height: image.height,
  7518. type: image.data.constructor.name
  7519. };
  7520. } else {
  7521. console.warn('THREE.Texture: Unable to serialize Texture.');
  7522. return {};
  7523. }
  7524. }
  7525. }
  7526. var Vector4 = /*#__PURE__*/function () {
  7527. function Vector4(x, y, z, w) {
  7528. if (x === void 0) {
  7529. x = 0;
  7530. }
  7531. if (y === void 0) {
  7532. y = 0;
  7533. }
  7534. if (z === void 0) {
  7535. z = 0;
  7536. }
  7537. if (w === void 0) {
  7538. w = 1;
  7539. }
  7540. Object.defineProperty(this, 'isVector4', {
  7541. value: true
  7542. });
  7543. this.x = x;
  7544. this.y = y;
  7545. this.z = z;
  7546. this.w = w;
  7547. }
  7548. var _proto = Vector4.prototype;
  7549. _proto.set = function set(x, y, z, w) {
  7550. this.x = x;
  7551. this.y = y;
  7552. this.z = z;
  7553. this.w = w;
  7554. return this;
  7555. };
  7556. _proto.setScalar = function setScalar(scalar) {
  7557. this.x = scalar;
  7558. this.y = scalar;
  7559. this.z = scalar;
  7560. this.w = scalar;
  7561. return this;
  7562. };
  7563. _proto.setX = function setX(x) {
  7564. this.x = x;
  7565. return this;
  7566. };
  7567. _proto.setY = function setY(y) {
  7568. this.y = y;
  7569. return this;
  7570. };
  7571. _proto.setZ = function setZ(z) {
  7572. this.z = z;
  7573. return this;
  7574. };
  7575. _proto.setW = function setW(w) {
  7576. this.w = w;
  7577. return this;
  7578. };
  7579. _proto.setComponent = function setComponent(index, value) {
  7580. switch (index) {
  7581. case 0:
  7582. this.x = value;
  7583. break;
  7584. case 1:
  7585. this.y = value;
  7586. break;
  7587. case 2:
  7588. this.z = value;
  7589. break;
  7590. case 3:
  7591. this.w = value;
  7592. break;
  7593. default:
  7594. throw new Error('index is out of range: ' + index);
  7595. }
  7596. return this;
  7597. };
  7598. _proto.getComponent = function getComponent(index) {
  7599. switch (index) {
  7600. case 0:
  7601. return this.x;
  7602. case 1:
  7603. return this.y;
  7604. case 2:
  7605. return this.z;
  7606. case 3:
  7607. return this.w;
  7608. default:
  7609. throw new Error('index is out of range: ' + index);
  7610. }
  7611. };
  7612. _proto.clone = function clone() {
  7613. return new this.constructor(this.x, this.y, this.z, this.w);
  7614. };
  7615. _proto.copy = function copy(v) {
  7616. this.x = v.x;
  7617. this.y = v.y;
  7618. this.z = v.z;
  7619. this.w = v.w !== undefined ? v.w : 1;
  7620. return this;
  7621. };
  7622. _proto.add = function add(v, w) {
  7623. if (w !== undefined) {
  7624. console.warn('THREE.Vector4: .add() now only accepts one argument. Use .addVectors( a, b ) instead.');
  7625. return this.addVectors(v, w);
  7626. }
  7627. this.x += v.x;
  7628. this.y += v.y;
  7629. this.z += v.z;
  7630. this.w += v.w;
  7631. return this;
  7632. };
  7633. _proto.addScalar = function addScalar(s) {
  7634. this.x += s;
  7635. this.y += s;
  7636. this.z += s;
  7637. this.w += s;
  7638. return this;
  7639. };
  7640. _proto.addVectors = function addVectors(a, b) {
  7641. this.x = a.x + b.x;
  7642. this.y = a.y + b.y;
  7643. this.z = a.z + b.z;
  7644. this.w = a.w + b.w;
  7645. return this;
  7646. };
  7647. _proto.addScaledVector = function addScaledVector(v, s) {
  7648. this.x += v.x * s;
  7649. this.y += v.y * s;
  7650. this.z += v.z * s;
  7651. this.w += v.w * s;
  7652. return this;
  7653. };
  7654. _proto.sub = function sub(v, w) {
  7655. if (w !== undefined) {
  7656. console.warn('THREE.Vector4: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.');
  7657. return this.subVectors(v, w);
  7658. }
  7659. this.x -= v.x;
  7660. this.y -= v.y;
  7661. this.z -= v.z;
  7662. this.w -= v.w;
  7663. return this;
  7664. };
  7665. _proto.subScalar = function subScalar(s) {
  7666. this.x -= s;
  7667. this.y -= s;
  7668. this.z -= s;
  7669. this.w -= s;
  7670. return this;
  7671. };
  7672. _proto.subVectors = function subVectors(a, b) {
  7673. this.x = a.x - b.x;
  7674. this.y = a.y - b.y;
  7675. this.z = a.z - b.z;
  7676. this.w = a.w - b.w;
  7677. return this;
  7678. };
  7679. _proto.multiply = function multiply(v) {
  7680. this.x *= v.x;
  7681. this.y *= v.y;
  7682. this.z *= v.z;
  7683. this.w *= v.w;
  7684. return this;
  7685. };
  7686. _proto.multiplyScalar = function multiplyScalar(scalar) {
  7687. this.x *= scalar;
  7688. this.y *= scalar;
  7689. this.z *= scalar;
  7690. this.w *= scalar;
  7691. return this;
  7692. };
  7693. _proto.applyMatrix4 = function applyMatrix4(m) {
  7694. var x = this.x,
  7695. y = this.y,
  7696. z = this.z,
  7697. w = this.w;
  7698. var e = m.elements;
  7699. this.x = e[0] * x + e[4] * y + e[8] * z + e[12] * w;
  7700. this.y = e[1] * x + e[5] * y + e[9] * z + e[13] * w;
  7701. this.z = e[2] * x + e[6] * y + e[10] * z + e[14] * w;
  7702. this.w = e[3] * x + e[7] * y + e[11] * z + e[15] * w;
  7703. return this;
  7704. };
  7705. _proto.divideScalar = function divideScalar(scalar) {
  7706. return this.multiplyScalar(1 / scalar);
  7707. };
  7708. _proto.setAxisAngleFromQuaternion = function setAxisAngleFromQuaternion(q) {
  7709. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  7710. // q is assumed to be normalized
  7711. this.w = 2 * Math.acos(q.w);
  7712. var s = Math.sqrt(1 - q.w * q.w);
  7713. if (s < 0.0001) {
  7714. this.x = 1;
  7715. this.y = 0;
  7716. this.z = 0;
  7717. } else {
  7718. this.x = q.x / s;
  7719. this.y = q.y / s;
  7720. this.z = q.z / s;
  7721. }
  7722. return this;
  7723. };
  7724. _proto.setAxisAngleFromRotationMatrix = function setAxisAngleFromRotationMatrix(m) {
  7725. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  7726. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  7727. var angle, x, y, z; // variables for result
  7728. var epsilon = 0.01,
  7729. // margin to allow for rounding errors
  7730. epsilon2 = 0.1,
  7731. // margin to distinguish between 0 and 180 degrees
  7732. te = m.elements,
  7733. m11 = te[0],
  7734. m12 = te[4],
  7735. m13 = te[8],
  7736. m21 = te[1],
  7737. m22 = te[5],
  7738. m23 = te[9],
  7739. m31 = te[2],
  7740. m32 = te[6],
  7741. m33 = te[10];
  7742. if (Math.abs(m12 - m21) < epsilon && Math.abs(m13 - m31) < epsilon && Math.abs(m23 - m32) < epsilon) {
  7743. // singularity found
  7744. // first check for identity matrix which must have +1 for all terms
  7745. // in leading diagonal and zero in other terms
  7746. if (Math.abs(m12 + m21) < epsilon2 && Math.abs(m13 + m31) < epsilon2 && Math.abs(m23 + m32) < epsilon2 && Math.abs(m11 + m22 + m33 - 3) < epsilon2) {
  7747. // this singularity is identity matrix so angle = 0
  7748. this.set(1, 0, 0, 0);
  7749. return this; // zero angle, arbitrary axis
  7750. } // otherwise this singularity is angle = 180
  7751. angle = Math.PI;
  7752. var xx = (m11 + 1) / 2;
  7753. var yy = (m22 + 1) / 2;
  7754. var zz = (m33 + 1) / 2;
  7755. var xy = (m12 + m21) / 4;
  7756. var xz = (m13 + m31) / 4;
  7757. var yz = (m23 + m32) / 4;
  7758. if (xx > yy && xx > zz) {
  7759. // m11 is the largest diagonal term
  7760. if (xx < epsilon) {
  7761. x = 0;
  7762. y = 0.707106781;
  7763. z = 0.707106781;
  7764. } else {
  7765. x = Math.sqrt(xx);
  7766. y = xy / x;
  7767. z = xz / x;
  7768. }
  7769. } else if (yy > zz) {
  7770. // m22 is the largest diagonal term
  7771. if (yy < epsilon) {
  7772. x = 0.707106781;
  7773. y = 0;
  7774. z = 0.707106781;
  7775. } else {
  7776. y = Math.sqrt(yy);
  7777. x = xy / y;
  7778. z = yz / y;
  7779. }
  7780. } else {
  7781. // m33 is the largest diagonal term so base result on this
  7782. if (zz < epsilon) {
  7783. x = 0.707106781;
  7784. y = 0.707106781;
  7785. z = 0;
  7786. } else {
  7787. z = Math.sqrt(zz);
  7788. x = xz / z;
  7789. y = yz / z;
  7790. }
  7791. }
  7792. this.set(x, y, z, angle);
  7793. return this; // return 180 deg rotation
  7794. } // as we have reached here there are no singularities so we can handle normally
  7795. var s = Math.sqrt((m32 - m23) * (m32 - m23) + (m13 - m31) * (m13 - m31) + (m21 - m12) * (m21 - m12)); // used to normalize
  7796. if (Math.abs(s) < 0.001) s = 1; // prevent divide by zero, should not happen if matrix is orthogonal and should be
  7797. // caught by singularity test above, but I've left it in just in case
  7798. this.x = (m32 - m23) / s;
  7799. this.y = (m13 - m31) / s;
  7800. this.z = (m21 - m12) / s;
  7801. this.w = Math.acos((m11 + m22 + m33 - 1) / 2);
  7802. return this;
  7803. };
  7804. _proto.min = function min(v) {
  7805. this.x = Math.min(this.x, v.x);
  7806. this.y = Math.min(this.y, v.y);
  7807. this.z = Math.min(this.z, v.z);
  7808. this.w = Math.min(this.w, v.w);
  7809. return this;
  7810. };
  7811. _proto.max = function max(v) {
  7812. this.x = Math.max(this.x, v.x);
  7813. this.y = Math.max(this.y, v.y);
  7814. this.z = Math.max(this.z, v.z);
  7815. this.w = Math.max(this.w, v.w);
  7816. return this;
  7817. };
  7818. _proto.clamp = function clamp(min, max) {
  7819. // assumes min < max, componentwise
  7820. this.x = Math.max(min.x, Math.min(max.x, this.x));
  7821. this.y = Math.max(min.y, Math.min(max.y, this.y));
  7822. this.z = Math.max(min.z, Math.min(max.z, this.z));
  7823. this.w = Math.max(min.w, Math.min(max.w, this.w));
  7824. return this;
  7825. };
  7826. _proto.clampScalar = function clampScalar(minVal, maxVal) {
  7827. this.x = Math.max(minVal, Math.min(maxVal, this.x));
  7828. this.y = Math.max(minVal, Math.min(maxVal, this.y));
  7829. this.z = Math.max(minVal, Math.min(maxVal, this.z));
  7830. this.w = Math.max(minVal, Math.min(maxVal, this.w));
  7831. return this;
  7832. };
  7833. _proto.clampLength = function clampLength(min, max) {
  7834. var length = this.length();
  7835. return this.divideScalar(length || 1).multiplyScalar(Math.max(min, Math.min(max, length)));
  7836. };
  7837. _proto.floor = function floor() {
  7838. this.x = Math.floor(this.x);
  7839. this.y = Math.floor(this.y);
  7840. this.z = Math.floor(this.z);
  7841. this.w = Math.floor(this.w);
  7842. return this;
  7843. };
  7844. _proto.ceil = function ceil() {
  7845. this.x = Math.ceil(this.x);
  7846. this.y = Math.ceil(this.y);
  7847. this.z = Math.ceil(this.z);
  7848. this.w = Math.ceil(this.w);
  7849. return this;
  7850. };
  7851. _proto.round = function round() {
  7852. this.x = Math.round(this.x);
  7853. this.y = Math.round(this.y);
  7854. this.z = Math.round(this.z);
  7855. this.w = Math.round(this.w);
  7856. return this;
  7857. };
  7858. _proto.roundToZero = function roundToZero() {
  7859. this.x = this.x < 0 ? Math.ceil(this.x) : Math.floor(this.x);
  7860. this.y = this.y < 0 ? Math.ceil(this.y) : Math.floor(this.y);
  7861. this.z = this.z < 0 ? Math.ceil(this.z) : Math.floor(this.z);
  7862. this.w = this.w < 0 ? Math.ceil(this.w) : Math.floor(this.w);
  7863. return this;
  7864. };
  7865. _proto.negate = function negate() {
  7866. this.x = -this.x;
  7867. this.y = -this.y;
  7868. this.z = -this.z;
  7869. this.w = -this.w;
  7870. return this;
  7871. };
  7872. _proto.dot = function dot(v) {
  7873. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  7874. };
  7875. _proto.lengthSq = function lengthSq() {
  7876. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  7877. };
  7878. _proto.length = function length() {
  7879. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  7880. };
  7881. _proto.manhattanLength = function manhattanLength() {
  7882. return Math.abs(this.x) + Math.abs(this.y) + Math.abs(this.z) + Math.abs(this.w);
  7883. };
  7884. _proto.normalize = function normalize() {
  7885. return this.divideScalar(this.length() || 1);
  7886. };
  7887. _proto.setLength = function setLength(length) {
  7888. return this.normalize().multiplyScalar(length);
  7889. };
  7890. _proto.lerp = function lerp(v, alpha) {
  7891. this.x += (v.x - this.x) * alpha;
  7892. this.y += (v.y - this.y) * alpha;
  7893. this.z += (v.z - this.z) * alpha;
  7894. this.w += (v.w - this.w) * alpha;
  7895. return this;
  7896. };
  7897. _proto.lerpVectors = function lerpVectors(v1, v2, alpha) {
  7898. this.x = v1.x + (v2.x - v1.x) * alpha;
  7899. this.y = v1.y + (v2.y - v1.y) * alpha;
  7900. this.z = v1.z + (v2.z - v1.z) * alpha;
  7901. this.w = v1.w + (v2.w - v1.w) * alpha;
  7902. return this;
  7903. };
  7904. _proto.equals = function equals(v) {
  7905. return v.x === this.x && v.y === this.y && v.z === this.z && v.w === this.w;
  7906. };
  7907. _proto.fromArray = function fromArray(array, offset) {
  7908. if (offset === void 0) {
  7909. offset = 0;
  7910. }
  7911. this.x = array[offset];
  7912. this.y = array[offset + 1];
  7913. this.z = array[offset + 2];
  7914. this.w = array[offset + 3];
  7915. return this;
  7916. };
  7917. _proto.toArray = function toArray(array, offset) {
  7918. if (array === void 0) {
  7919. array = [];
  7920. }
  7921. if (offset === void 0) {
  7922. offset = 0;
  7923. }
  7924. array[offset] = this.x;
  7925. array[offset + 1] = this.y;
  7926. array[offset + 2] = this.z;
  7927. array[offset + 3] = this.w;
  7928. return array;
  7929. };
  7930. _proto.fromBufferAttribute = function fromBufferAttribute(attribute, index, offset) {
  7931. if (offset !== undefined) {
  7932. console.warn('THREE.Vector4: offset has been removed from .fromBufferAttribute().');
  7933. }
  7934. this.x = attribute.getX(index);
  7935. this.y = attribute.getY(index);
  7936. this.z = attribute.getZ(index);
  7937. this.w = attribute.getW(index);
  7938. return this;
  7939. };
  7940. _proto.random = function random() {
  7941. this.x = Math.random();
  7942. this.y = Math.random();
  7943. this.z = Math.random();
  7944. this.w = Math.random();
  7945. return this;
  7946. };
  7947. _createClass(Vector4, [{
  7948. key: "width",
  7949. get: function get() {
  7950. return this.z;
  7951. },
  7952. set: function set(value) {
  7953. this.z = value;
  7954. }
  7955. }, {
  7956. key: "height",
  7957. get: function get() {
  7958. return this.w;
  7959. },
  7960. set: function set(value) {
  7961. this.w = value;
  7962. }
  7963. }]);
  7964. return Vector4;
  7965. }();
  7966. /*
  7967. In options, we can specify:
  7968. * Texture parameters for an auto-generated target texture
  7969. * depthBuffer/stencilBuffer: Booleans to indicate if we should generate these buffers
  7970. */
  7971. var WebGLRenderTarget = /*#__PURE__*/function (_EventDispatcher) {
  7972. _inheritsLoose(WebGLRenderTarget, _EventDispatcher);
  7973. function WebGLRenderTarget(width, height, options) {
  7974. var _this;
  7975. _this = _EventDispatcher.call(this) || this;
  7976. Object.defineProperty(_assertThisInitialized(_this), 'isWebGLRenderTarget', {
  7977. value: true
  7978. });
  7979. _this.width = width;
  7980. _this.height = height;
  7981. _this.scissor = new Vector4(0, 0, width, height);
  7982. _this.scissorTest = false;
  7983. _this.viewport = new Vector4(0, 0, width, height);
  7984. options = options || {};
  7985. _this.texture = new Texture(undefined, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding);
  7986. _this.texture.image = {};
  7987. _this.texture.image.width = width;
  7988. _this.texture.image.height = height;
  7989. _this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
  7990. _this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
  7991. _this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  7992. _this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : false;
  7993. _this.depthTexture = options.depthTexture !== undefined ? options.depthTexture : null;
  7994. return _this;
  7995. }
  7996. var _proto = WebGLRenderTarget.prototype;
  7997. _proto.setSize = function setSize(width, height) {
  7998. if (this.width !== width || this.height !== height) {
  7999. this.width = width;
  8000. this.height = height;
  8001. this.texture.image.width = width;
  8002. this.texture.image.height = height;
  8003. this.dispose();
  8004. }
  8005. this.viewport.set(0, 0, width, height);
  8006. this.scissor.set(0, 0, width, height);
  8007. };
  8008. _proto.clone = function clone() {
  8009. return new this.constructor().copy(this);
  8010. };
  8011. _proto.copy = function copy(source) {
  8012. this.width = source.width;
  8013. this.height = source.height;
  8014. this.viewport.copy(source.viewport);
  8015. this.texture = source.texture.clone();
  8016. this.depthBuffer = source.depthBuffer;
  8017. this.stencilBuffer = source.stencilBuffer;
  8018. this.depthTexture = source.depthTexture;
  8019. return this;
  8020. };
  8021. _proto.dispose = function dispose() {
  8022. this.dispatchEvent({
  8023. type: 'dispose'
  8024. });
  8025. };
  8026. return WebGLRenderTarget;
  8027. }(EventDispatcher);
  8028. var WebGLMultisampleRenderTarget = /*#__PURE__*/function (_WebGLRenderTarget) {
  8029. _inheritsLoose(WebGLMultisampleRenderTarget, _WebGLRenderTarget);
  8030. function WebGLMultisampleRenderTarget(width, height, options) {
  8031. var _this;
  8032. _this = _WebGLRenderTarget.call(this, width, height, options) || this;
  8033. Object.defineProperty(_assertThisInitialized(_this), 'isWebGLMultisampleRenderTarget', {
  8034. value: true
  8035. });
  8036. _this.samples = 4;
  8037. return _this;
  8038. }
  8039. var _proto = WebGLMultisampleRenderTarget.prototype;
  8040. _proto.copy = function copy(source) {
  8041. _WebGLRenderTarget.prototype.copy.call(this, source);
  8042. this.samples = source.samples;
  8043. return this;
  8044. };
  8045. return WebGLMultisampleRenderTarget;
  8046. }(WebGLRenderTarget);
  8047. var Quaternion = /*#__PURE__*/function () {
  8048. function Quaternion(x, y, z, w) {
  8049. if (x === void 0) {
  8050. x = 0;
  8051. }
  8052. if (y === void 0) {
  8053. y = 0;
  8054. }
  8055. if (z === void 0) {
  8056. z = 0;
  8057. }
  8058. if (w === void 0) {
  8059. w = 1;
  8060. }
  8061. Object.defineProperty(this, 'isQuaternion', {
  8062. value: true
  8063. });
  8064. this._x = x;
  8065. this._y = y;
  8066. this._z = z;
  8067. this._w = w;
  8068. }
  8069. Quaternion.slerp = function slerp(qa, qb, qm, t) {
  8070. return qm.copy(qa).slerp(qb, t);
  8071. };
  8072. Quaternion.slerpFlat = function slerpFlat(dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t) {
  8073. // fuzz-free, array-based Quaternion SLERP operation
  8074. var x0 = src0[srcOffset0 + 0],
  8075. y0 = src0[srcOffset0 + 1],
  8076. z0 = src0[srcOffset0 + 2],
  8077. w0 = src0[srcOffset0 + 3];
  8078. var x1 = src1[srcOffset1 + 0],
  8079. y1 = src1[srcOffset1 + 1],
  8080. z1 = src1[srcOffset1 + 2],
  8081. w1 = src1[srcOffset1 + 3];
  8082. if (w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1) {
  8083. var s = 1 - t;
  8084. var cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1,
  8085. dir = cos >= 0 ? 1 : -1,
  8086. sqrSin = 1 - cos * cos; // Skip the Slerp for tiny steps to avoid numeric problems:
  8087. if (sqrSin > Number.EPSILON) {
  8088. var sin = Math.sqrt(sqrSin),
  8089. len = Math.atan2(sin, cos * dir);
  8090. s = Math.sin(s * len) / sin;
  8091. t = Math.sin(t * len) / sin;
  8092. }
  8093. var tDir = t * dir;
  8094. x0 = x0 * s + x1 * tDir;
  8095. y0 = y0 * s + y1 * tDir;
  8096. z0 = z0 * s + z1 * tDir;
  8097. w0 = w0 * s + w1 * tDir; // Normalize in case we just did a lerp:
  8098. if (s === 1 - t) {
  8099. var f = 1 / Math.sqrt(x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0);
  8100. x0 *= f;
  8101. y0 *= f;
  8102. z0 *= f;
  8103. w0 *= f;
  8104. }
  8105. }
  8106. dst[dstOffset] = x0;
  8107. dst[dstOffset + 1] = y0;
  8108. dst[dstOffset + 2] = z0;
  8109. dst[dstOffset + 3] = w0;
  8110. };
  8111. Quaternion.multiplyQuaternionsFlat = function multiplyQuaternionsFlat(dst, dstOffset, src0, srcOffset0, src1, srcOffset1) {
  8112. var x0 = src0[srcOffset0];
  8113. var y0 = src0[srcOffset0 + 1];
  8114. var z0 = src0[srcOffset0 + 2];
  8115. var w0 = src0[srcOffset0 + 3];
  8116. var x1 = src1[srcOffset1];
  8117. var y1 = src1[srcOffset1 + 1];
  8118. var z1 = src1[srcOffset1 + 2];
  8119. var w1 = src1[srcOffset1 + 3];
  8120. dst[dstOffset] = x0 * w1 + w0 * x1 + y0 * z1 - z0 * y1;
  8121. dst[dstOffset + 1] = y0 * w1 + w0 * y1 + z0 * x1 - x0 * z1;
  8122. dst[dstOffset + 2] = z0 * w1 + w0 * z1 + x0 * y1 - y0 * x1;
  8123. dst[dstOffset + 3] = w0 * w1 - x0 * x1 - y0 * y1 - z0 * z1;
  8124. return dst;
  8125. };
  8126. var _proto = Quaternion.prototype;
  8127. _proto.set = function set(x, y, z, w) {
  8128. this._x = x;
  8129. this._y = y;
  8130. this._z = z;
  8131. this._w = w;
  8132. this._onChangeCallback();
  8133. return this;
  8134. };
  8135. _proto.clone = function clone() {
  8136. return new this.constructor(this._x, this._y, this._z, this._w);
  8137. };
  8138. _proto.copy = function copy(quaternion) {
  8139. this._x = quaternion.x;
  8140. this._y = quaternion.y;
  8141. this._z = quaternion.z;
  8142. this._w = quaternion.w;
  8143. this._onChangeCallback();
  8144. return this;
  8145. };
  8146. _proto.setFromEuler = function setFromEuler(euler, update) {
  8147. if (!(euler && euler.isEuler)) {
  8148. throw new Error('THREE.Quaternion: .setFromEuler() now expects an Euler rotation rather than a Vector3 and order.');
  8149. }
  8150. var x = euler._x,
  8151. y = euler._y,
  8152. z = euler._z,
  8153. order = euler._order; // http://www.mathworks.com/matlabcentral/fileexchange/
  8154. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  8155. // content/SpinCalc.m
  8156. var cos = Math.cos;
  8157. var sin = Math.sin;
  8158. var c1 = cos(x / 2);
  8159. var c2 = cos(y / 2);
  8160. var c3 = cos(z / 2);
  8161. var s1 = sin(x / 2);
  8162. var s2 = sin(y / 2);
  8163. var s3 = sin(z / 2);
  8164. switch (order) {
  8165. case 'XYZ':
  8166. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  8167. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  8168. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  8169. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  8170. break;
  8171. case 'YXZ':
  8172. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  8173. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  8174. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  8175. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  8176. break;
  8177. case 'ZXY':
  8178. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  8179. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  8180. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  8181. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  8182. break;
  8183. case 'ZYX':
  8184. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  8185. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  8186. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  8187. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  8188. break;
  8189. case 'YZX':
  8190. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  8191. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  8192. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  8193. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  8194. break;
  8195. case 'XZY':
  8196. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  8197. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  8198. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  8199. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  8200. break;
  8201. default:
  8202. console.warn('THREE.Quaternion: .setFromEuler() encountered an unknown order: ' + order);
  8203. }
  8204. if (update !== false) this._onChangeCallback();
  8205. return this;
  8206. };
  8207. _proto.setFromAxisAngle = function setFromAxisAngle(axis, angle) {
  8208. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  8209. // assumes axis is normalized
  8210. var halfAngle = angle / 2,
  8211. s = Math.sin(halfAngle);
  8212. this._x = axis.x * s;
  8213. this._y = axis.y * s;
  8214. this._z = axis.z * s;
  8215. this._w = Math.cos(halfAngle);
  8216. this._onChangeCallback();
  8217. return this;
  8218. };
  8219. _proto.setFromRotationMatrix = function setFromRotationMatrix(m) {
  8220. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  8221. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  8222. var te = m.elements,
  8223. m11 = te[0],
  8224. m12 = te[4],
  8225. m13 = te[8],
  8226. m21 = te[1],
  8227. m22 = te[5],
  8228. m23 = te[9],
  8229. m31 = te[2],
  8230. m32 = te[6],
  8231. m33 = te[10],
  8232. trace = m11 + m22 + m33;
  8233. if (trace > 0) {
  8234. var s = 0.5 / Math.sqrt(trace + 1.0);
  8235. this._w = 0.25 / s;
  8236. this._x = (m32 - m23) * s;
  8237. this._y = (m13 - m31) * s;
  8238. this._z = (m21 - m12) * s;
  8239. } else if (m11 > m22 && m11 > m33) {
  8240. var _s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  8241. this._w = (m32 - m23) / _s;
  8242. this._x = 0.25 * _s;
  8243. this._y = (m12 + m21) / _s;
  8244. this._z = (m13 + m31) / _s;
  8245. } else if (m22 > m33) {
  8246. var _s2 = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  8247. this._w = (m13 - m31) / _s2;
  8248. this._x = (m12 + m21) / _s2;
  8249. this._y = 0.25 * _s2;
  8250. this._z = (m23 + m32) / _s2;
  8251. } else {
  8252. var _s3 = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  8253. this._w = (m21 - m12) / _s3;
  8254. this._x = (m13 + m31) / _s3;
  8255. this._y = (m23 + m32) / _s3;
  8256. this._z = 0.25 * _s3;
  8257. }
  8258. this._onChangeCallback();
  8259. return this;
  8260. };
  8261. _proto.setFromUnitVectors = function setFromUnitVectors(vFrom, vTo) {
  8262. // assumes direction vectors vFrom and vTo are normalized
  8263. var EPS = 0.000001;
  8264. var r = vFrom.dot(vTo) + 1;
  8265. if (r < EPS) {
  8266. r = 0;
  8267. if (Math.abs(vFrom.x) > Math.abs(vFrom.z)) {
  8268. this._x = -vFrom.y;
  8269. this._y = vFrom.x;
  8270. this._z = 0;
  8271. this._w = r;
  8272. } else {
  8273. this._x = 0;
  8274. this._y = -vFrom.z;
  8275. this._z = vFrom.y;
  8276. this._w = r;
  8277. }
  8278. } else {
  8279. // crossVectors( vFrom, vTo ); // inlined to avoid cyclic dependency on Vector3
  8280. this._x = vFrom.y * vTo.z - vFrom.z * vTo.y;
  8281. this._y = vFrom.z * vTo.x - vFrom.x * vTo.z;
  8282. this._z = vFrom.x * vTo.y - vFrom.y * vTo.x;
  8283. this._w = r;
  8284. }
  8285. return this.normalize();
  8286. };
  8287. _proto.angleTo = function angleTo(q) {
  8288. return 2 * Math.acos(Math.abs(MathUtils.clamp(this.dot(q), -1, 1)));
  8289. };
  8290. _proto.rotateTowards = function rotateTowards(q, step) {
  8291. var angle = this.angleTo(q);
  8292. if (angle === 0) return this;
  8293. var t = Math.min(1, step / angle);
  8294. this.slerp(q, t);
  8295. return this;
  8296. };
  8297. _proto.identity = function identity() {
  8298. return this.set(0, 0, 0, 1);
  8299. };
  8300. _proto.invert = function invert() {
  8301. // quaternion is assumed to have unit length
  8302. return this.conjugate();
  8303. };
  8304. _proto.conjugate = function conjugate() {
  8305. this._x *= -1;
  8306. this._y *= -1;
  8307. this._z *= -1;
  8308. this._onChangeCallback();
  8309. return this;
  8310. };
  8311. _proto.dot = function dot(v) {
  8312. return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
  8313. };
  8314. _proto.lengthSq = function lengthSq() {
  8315. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  8316. };
  8317. _proto.length = function length() {
  8318. return Math.sqrt(this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w);
  8319. };
  8320. _proto.normalize = function normalize() {
  8321. var l = this.length();
  8322. if (l === 0) {
  8323. this._x = 0;
  8324. this._y = 0;
  8325. this._z = 0;
  8326. this._w = 1;
  8327. } else {
  8328. l = 1 / l;
  8329. this._x = this._x * l;
  8330. this._y = this._y * l;
  8331. this._z = this._z * l;
  8332. this._w = this._w * l;
  8333. }
  8334. this._onChangeCallback();
  8335. return this;
  8336. };
  8337. _proto.multiply = function multiply(q, p) {
  8338. if (p !== undefined) {
  8339. console.warn('THREE.Quaternion: .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead.');
  8340. return this.multiplyQuaternions(q, p);
  8341. }
  8342. return this.multiplyQuaternions(this, q);
  8343. };
  8344. _proto.premultiply = function premultiply(q) {
  8345. return this.multiplyQuaternions(q, this);
  8346. };
  8347. _proto.multiplyQuaternions = function multiplyQuaternions(a, b) {
  8348. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  8349. var qax = a._x,
  8350. qay = a._y,
  8351. qaz = a._z,
  8352. qaw = a._w;
  8353. var qbx = b._x,
  8354. qby = b._y,
  8355. qbz = b._z,
  8356. qbw = b._w;
  8357. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  8358. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  8359. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  8360. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  8361. this._onChangeCallback();
  8362. return this;
  8363. };
  8364. _proto.slerp = function slerp(qb, t) {
  8365. if (t === 0) return this;
  8366. if (t === 1) return this.copy(qb);
  8367. var x = this._x,
  8368. y = this._y,
  8369. z = this._z,
  8370. w = this._w; // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  8371. var cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  8372. if (cosHalfTheta < 0) {
  8373. this._w = -qb._w;
  8374. this._x = -qb._x;
  8375. this._y = -qb._y;
  8376. this._z = -qb._z;
  8377. cosHalfTheta = -cosHalfTheta;
  8378. } else {
  8379. this.copy(qb);
  8380. }
  8381. if (cosHalfTheta >= 1.0) {
  8382. this._w = w;
  8383. this._x = x;
  8384. this._y = y;
  8385. this._z = z;
  8386. return this;
  8387. }
  8388. var sqrSinHalfTheta = 1.0 - cosHalfTheta * cosHalfTheta;
  8389. if (sqrSinHalfTheta <= Number.EPSILON) {
  8390. var s = 1 - t;
  8391. this._w = s * w + t * this._w;
  8392. this._x = s * x + t * this._x;
  8393. this._y = s * y + t * this._y;
  8394. this._z = s * z + t * this._z;
  8395. this.normalize();
  8396. this._onChangeCallback();
  8397. return this;
  8398. }
  8399. var sinHalfTheta = Math.sqrt(sqrSinHalfTheta);
  8400. var halfTheta = Math.atan2(sinHalfTheta, cosHalfTheta);
  8401. var ratioA = Math.sin((1 - t) * halfTheta) / sinHalfTheta,
  8402. ratioB = Math.sin(t * halfTheta) / sinHalfTheta;
  8403. this._w = w * ratioA + this._w * ratioB;
  8404. this._x = x * ratioA + this._x * ratioB;
  8405. this._y = y * ratioA + this._y * ratioB;
  8406. this._z = z * ratioA + this._z * ratioB;
  8407. this._onChangeCallback();
  8408. return this;
  8409. };
  8410. _proto.equals = function equals(quaternion) {
  8411. return quaternion._x === this._x && quaternion._y === this._y && quaternion._z === this._z && quaternion._w === this._w;
  8412. };
  8413. _proto.fromArray = function fromArray(array, offset) {
  8414. if (offset === void 0) {
  8415. offset = 0;
  8416. }
  8417. this._x = array[offset];
  8418. this._y = array[offset + 1];
  8419. this._z = array[offset + 2];
  8420. this._w = array[offset + 3];
  8421. this._onChangeCallback();
  8422. return this;
  8423. };
  8424. _proto.toArray = function toArray(array, offset) {
  8425. if (array === void 0) {
  8426. array = [];
  8427. }
  8428. if (offset === void 0) {
  8429. offset = 0;
  8430. }
  8431. array[offset] = this._x;
  8432. array[offset + 1] = this._y;
  8433. array[offset + 2] = this._z;
  8434. array[offset + 3] = this._w;
  8435. return array;
  8436. };
  8437. _proto.fromBufferAttribute = function fromBufferAttribute(attribute, index) {
  8438. this._x = attribute.getX(index);
  8439. this._y = attribute.getY(index);
  8440. this._z = attribute.getZ(index);
  8441. this._w = attribute.getW(index);
  8442. return this;
  8443. };
  8444. _proto._onChange = function _onChange(callback) {
  8445. this._onChangeCallback = callback;
  8446. return this;
  8447. };
  8448. _proto._onChangeCallback = function _onChangeCallback() {};
  8449. _createClass(Quaternion, [{
  8450. key: "x",
  8451. get: function get() {
  8452. return this._x;
  8453. },
  8454. set: function set(value) {
  8455. this._x = value;
  8456. this._onChangeCallback();
  8457. }
  8458. }, {
  8459. key: "y",
  8460. get: function get() {
  8461. return this._y;
  8462. },
  8463. set: function set(value) {
  8464. this._y = value;
  8465. this._onChangeCallback();
  8466. }
  8467. }, {
  8468. key: "z",
  8469. get: function get() {
  8470. return this._z;
  8471. },
  8472. set: function set(value) {
  8473. this._z = value;
  8474. this._onChangeCallback();
  8475. }
  8476. }, {
  8477. key: "w",
  8478. get: function get() {
  8479. return this._w;
  8480. },
  8481. set: function set(value) {
  8482. this._w = value;
  8483. this._onChangeCallback();
  8484. }
  8485. }]);
  8486. return Quaternion;
  8487. }();
  8488. var Vector3 = /*#__PURE__*/function () {
  8489. function Vector3(x, y, z) {
  8490. if (x === void 0) {
  8491. x = 0;
  8492. }
  8493. if (y === void 0) {
  8494. y = 0;
  8495. }
  8496. if (z === void 0) {
  8497. z = 0;
  8498. }
  8499. Object.defineProperty(this, 'isVector3', {
  8500. value: true
  8501. });
  8502. this.x = x;
  8503. this.y = y;
  8504. this.z = z;
  8505. }
  8506. var _proto = Vector3.prototype;
  8507. _proto.set = function set(x, y, z) {
  8508. if (z === undefined) z = this.z; // sprite.scale.set(x,y)
  8509. this.x = x;
  8510. this.y = y;
  8511. this.z = z;
  8512. return this;
  8513. };
  8514. _proto.setScalar = function setScalar(scalar) {
  8515. this.x = scalar;
  8516. this.y = scalar;
  8517. this.z = scalar;
  8518. return this;
  8519. };
  8520. _proto.setX = function setX(x) {
  8521. this.x = x;
  8522. return this;
  8523. };
  8524. _proto.setY = function setY(y) {
  8525. this.y = y;
  8526. return this;
  8527. };
  8528. _proto.setZ = function setZ(z) {
  8529. this.z = z;
  8530. return this;
  8531. };
  8532. _proto.setComponent = function setComponent(index, value) {
  8533. switch (index) {
  8534. case 0:
  8535. this.x = value;
  8536. break;
  8537. case 1:
  8538. this.y = value;
  8539. break;
  8540. case 2:
  8541. this.z = value;
  8542. break;
  8543. default:
  8544. throw new Error('index is out of range: ' + index);
  8545. }
  8546. return this;
  8547. };
  8548. _proto.getComponent = function getComponent(index) {
  8549. switch (index) {
  8550. case 0:
  8551. return this.x;
  8552. case 1:
  8553. return this.y;
  8554. case 2:
  8555. return this.z;
  8556. default:
  8557. throw new Error('index is out of range: ' + index);
  8558. }
  8559. };
  8560. _proto.clone = function clone() {
  8561. return new this.constructor(this.x, this.y, this.z);
  8562. };
  8563. _proto.copy = function copy(v) {
  8564. this.x = v.x;
  8565. this.y = v.y;
  8566. this.z = v.z;
  8567. return this;
  8568. };
  8569. _proto.add = function add(v, w) {
  8570. if (w !== undefined) {
  8571. console.warn('THREE.Vector3: .add() now only accepts one argument. Use .addVectors( a, b ) instead.');
  8572. return this.addVectors(v, w);
  8573. }
  8574. this.x += v.x;
  8575. this.y += v.y;
  8576. this.z += v.z;
  8577. return this;
  8578. };
  8579. _proto.addScalar = function addScalar(s) {
  8580. this.x += s;
  8581. this.y += s;
  8582. this.z += s;
  8583. return this;
  8584. };
  8585. _proto.addVectors = function addVectors(a, b) {
  8586. this.x = a.x + b.x;
  8587. this.y = a.y + b.y;
  8588. this.z = a.z + b.z;
  8589. return this;
  8590. };
  8591. _proto.addScaledVector = function addScaledVector(v, s) {
  8592. this.x += v.x * s;
  8593. this.y += v.y * s;
  8594. this.z += v.z * s;
  8595. return this;
  8596. };
  8597. _proto.sub = function sub(v, w) {
  8598. if (w !== undefined) {
  8599. console.warn('THREE.Vector3: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.');
  8600. return this.subVectors(v, w);
  8601. }
  8602. this.x -= v.x;
  8603. this.y -= v.y;
  8604. this.z -= v.z;
  8605. return this;
  8606. };
  8607. _proto.subScalar = function subScalar(s) {
  8608. this.x -= s;
  8609. this.y -= s;
  8610. this.z -= s;
  8611. return this;
  8612. };
  8613. _proto.subVectors = function subVectors(a, b) {
  8614. this.x = a.x - b.x;
  8615. this.y = a.y - b.y;
  8616. this.z = a.z - b.z;
  8617. return this;
  8618. };
  8619. _proto.multiply = function multiply(v, w) {
  8620. if (w !== undefined) {
  8621. console.warn('THREE.Vector3: .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead.');
  8622. return this.multiplyVectors(v, w);
  8623. }
  8624. this.x *= v.x;
  8625. this.y *= v.y;
  8626. this.z *= v.z;
  8627. return this;
  8628. };
  8629. _proto.multiplyScalar = function multiplyScalar(scalar) {
  8630. this.x *= scalar;
  8631. this.y *= scalar;
  8632. this.z *= scalar;
  8633. return this;
  8634. };
  8635. _proto.multiplyVectors = function multiplyVectors(a, b) {
  8636. this.x = a.x * b.x;
  8637. this.y = a.y * b.y;
  8638. this.z = a.z * b.z;
  8639. return this;
  8640. };
  8641. _proto.applyEuler = function applyEuler(euler) {
  8642. if (!(euler && euler.isEuler)) {
  8643. console.error('THREE.Vector3: .applyEuler() now expects an Euler rotation rather than a Vector3 and order.');
  8644. }
  8645. return this.applyQuaternion(_quaternion.setFromEuler(euler));
  8646. };
  8647. _proto.applyAxisAngle = function applyAxisAngle(axis, angle) {
  8648. return this.applyQuaternion(_quaternion.setFromAxisAngle(axis, angle));
  8649. };
  8650. _proto.applyMatrix3 = function applyMatrix3(m) {
  8651. var x = this.x,
  8652. y = this.y,
  8653. z = this.z;
  8654. var e = m.elements;
  8655. this.x = e[0] * x + e[3] * y + e[6] * z;
  8656. this.y = e[1] * x + e[4] * y + e[7] * z;
  8657. this.z = e[2] * x + e[5] * y + e[8] * z;
  8658. return this;
  8659. };
  8660. _proto.applyNormalMatrix = function applyNormalMatrix(m) {
  8661. return this.applyMatrix3(m).normalize();
  8662. };
  8663. _proto.applyMatrix4 = function applyMatrix4(m) {
  8664. var x = this.x,
  8665. y = this.y,
  8666. z = this.z;
  8667. var e = m.elements;
  8668. var w = 1 / (e[3] * x + e[7] * y + e[11] * z + e[15]);
  8669. this.x = (e[0] * x + e[4] * y + e[8] * z + e[12]) * w;
  8670. this.y = (e[1] * x + e[5] * y + e[9] * z + e[13]) * w;
  8671. this.z = (e[2] * x + e[6] * y + e[10] * z + e[14]) * w;
  8672. return this;
  8673. };
  8674. _proto.applyQuaternion = function applyQuaternion(q) {
  8675. var x = this.x,
  8676. y = this.y,
  8677. z = this.z;
  8678. var qx = q.x,
  8679. qy = q.y,
  8680. qz = q.z,
  8681. qw = q.w; // calculate quat * vector
  8682. var ix = qw * x + qy * z - qz * y;
  8683. var iy = qw * y + qz * x - qx * z;
  8684. var iz = qw * z + qx * y - qy * x;
  8685. var iw = -qx * x - qy * y - qz * z; // calculate result * inverse quat
  8686. this.x = ix * qw + iw * -qx + iy * -qz - iz * -qy;
  8687. this.y = iy * qw + iw * -qy + iz * -qx - ix * -qz;
  8688. this.z = iz * qw + iw * -qz + ix * -qy - iy * -qx;
  8689. return this;
  8690. };
  8691. _proto.project = function project(camera) {
  8692. return this.applyMatrix4(camera.matrixWorldInverse).applyMatrix4(camera.projectionMatrix);
  8693. };
  8694. _proto.unproject = function unproject(camera) {
  8695. return this.applyMatrix4(camera.projectionMatrixInverse).applyMatrix4(camera.matrixWorld);
  8696. };
  8697. _proto.transformDirection = function transformDirection(m) {
  8698. // input: THREE.Matrix4 affine matrix
  8699. // vector interpreted as a direction
  8700. var x = this.x,
  8701. y = this.y,
  8702. z = this.z;
  8703. var e = m.elements;
  8704. this.x = e[0] * x + e[4] * y + e[8] * z;
  8705. this.y = e[1] * x + e[5] * y + e[9] * z;
  8706. this.z = e[2] * x + e[6] * y + e[10] * z;
  8707. return this.normalize();
  8708. };
  8709. _proto.divide = function divide(v) {
  8710. this.x /= v.x;
  8711. this.y /= v.y;
  8712. this.z /= v.z;
  8713. return this;
  8714. };
  8715. _proto.divideScalar = function divideScalar(scalar) {
  8716. return this.multiplyScalar(1 / scalar);
  8717. };
  8718. _proto.min = function min(v) {
  8719. this.x = Math.min(this.x, v.x);
  8720. this.y = Math.min(this.y, v.y);
  8721. this.z = Math.min(this.z, v.z);
  8722. return this;
  8723. };
  8724. _proto.max = function max(v) {
  8725. this.x = Math.max(this.x, v.x);
  8726. this.y = Math.max(this.y, v.y);
  8727. this.z = Math.max(this.z, v.z);
  8728. return this;
  8729. };
  8730. _proto.clamp = function clamp(min, max) {
  8731. // assumes min < max, componentwise
  8732. this.x = Math.max(min.x, Math.min(max.x, this.x));
  8733. this.y = Math.max(min.y, Math.min(max.y, this.y));
  8734. this.z = Math.max(min.z, Math.min(max.z, this.z));
  8735. return this;
  8736. };
  8737. _proto.clampScalar = function clampScalar(minVal, maxVal) {
  8738. this.x = Math.max(minVal, Math.min(maxVal, this.x));
  8739. this.y = Math.max(minVal, Math.min(maxVal, this.y));
  8740. this.z = Math.max(minVal, Math.min(maxVal, this.z));
  8741. return this;
  8742. };
  8743. _proto.clampLength = function clampLength(min, max) {
  8744. var length = this.length();
  8745. return this.divideScalar(length || 1).multiplyScalar(Math.max(min, Math.min(max, length)));
  8746. };
  8747. _proto.floor = function floor() {
  8748. this.x = Math.floor(this.x);
  8749. this.y = Math.floor(this.y);
  8750. this.z = Math.floor(this.z);
  8751. return this;
  8752. };
  8753. _proto.ceil = function ceil() {
  8754. this.x = Math.ceil(this.x);
  8755. this.y = Math.ceil(this.y);
  8756. this.z = Math.ceil(this.z);
  8757. return this;
  8758. };
  8759. _proto.round = function round() {
  8760. this.x = Math.round(this.x);
  8761. this.y = Math.round(this.y);
  8762. this.z = Math.round(this.z);
  8763. return this;
  8764. };
  8765. _proto.roundToZero = function roundToZero() {
  8766. this.x = this.x < 0 ? Math.ceil(this.x) : Math.floor(this.x);
  8767. this.y = this.y < 0 ? Math.ceil(this.y) : Math.floor(this.y);
  8768. this.z = this.z < 0 ? Math.ceil(this.z) : Math.floor(this.z);
  8769. return this;
  8770. };
  8771. _proto.negate = function negate() {
  8772. this.x = -this.x;
  8773. this.y = -this.y;
  8774. this.z = -this.z;
  8775. return this;
  8776. };
  8777. _proto.dot = function dot(v) {
  8778. return this.x * v.x + this.y * v.y + this.z * v.z;
  8779. } // TODO lengthSquared?
  8780. ;
  8781. _proto.lengthSq = function lengthSq() {
  8782. return this.x * this.x + this.y * this.y + this.z * this.z;
  8783. };
  8784. _proto.length = function length() {
  8785. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  8786. };
  8787. _proto.manhattanLength = function manhattanLength() {
  8788. return Math.abs(this.x) + Math.abs(this.y) + Math.abs(this.z);
  8789. };
  8790. _proto.normalize = function normalize() {
  8791. return this.divideScalar(this.length() || 1);
  8792. };
  8793. _proto.setLength = function setLength(length) {
  8794. return this.normalize().multiplyScalar(length);
  8795. };
  8796. _proto.lerp = function lerp(v, alpha) {
  8797. this.x += (v.x - this.x) * alpha;
  8798. this.y += (v.y - this.y) * alpha;
  8799. this.z += (v.z - this.z) * alpha;
  8800. return this;
  8801. };
  8802. _proto.lerpVectors = function lerpVectors(v1, v2, alpha) {
  8803. this.x = v1.x + (v2.x - v1.x) * alpha;
  8804. this.y = v1.y + (v2.y - v1.y) * alpha;
  8805. this.z = v1.z + (v2.z - v1.z) * alpha;
  8806. return this;
  8807. };
  8808. _proto.cross = function cross(v, w) {
  8809. if (w !== undefined) {
  8810. console.warn('THREE.Vector3: .cross() now only accepts one argument. Use .crossVectors( a, b ) instead.');
  8811. return this.crossVectors(v, w);
  8812. }
  8813. return this.crossVectors(this, v);
  8814. };
  8815. _proto.crossVectors = function crossVectors(a, b) {
  8816. var ax = a.x,
  8817. ay = a.y,
  8818. az = a.z;
  8819. var bx = b.x,
  8820. by = b.y,
  8821. bz = b.z;
  8822. this.x = ay * bz - az * by;
  8823. this.y = az * bx - ax * bz;
  8824. this.z = ax * by - ay * bx;
  8825. return this;
  8826. };
  8827. _proto.projectOnVector = function projectOnVector(v) {
  8828. var denominator = v.lengthSq();
  8829. if (denominator === 0) return this.set(0, 0, 0);
  8830. var scalar = v.dot(this) / denominator;
  8831. return this.copy(v).multiplyScalar(scalar);
  8832. };
  8833. _proto.projectOnPlane = function projectOnPlane(planeNormal) {
  8834. _vector.copy(this).projectOnVector(planeNormal);
  8835. return this.sub(_vector);
  8836. };
  8837. _proto.reflect = function reflect(normal) {
  8838. // reflect incident vector off plane orthogonal to normal
  8839. // normal is assumed to have unit length
  8840. return this.sub(_vector.copy(normal).multiplyScalar(2 * this.dot(normal)));
  8841. };
  8842. _proto.angleTo = function angleTo(v) {
  8843. var denominator = Math.sqrt(this.lengthSq() * v.lengthSq());
  8844. if (denominator === 0) return Math.PI / 2;
  8845. var theta = this.dot(v) / denominator; // clamp, to handle numerical problems
  8846. return Math.acos(MathUtils.clamp(theta, -1, 1));
  8847. };
  8848. _proto.distanceTo = function distanceTo(v) {
  8849. return Math.sqrt(this.distanceToSquared(v));
  8850. };
  8851. _proto.distanceToSquared = function distanceToSquared(v) {
  8852. var dx = this.x - v.x,
  8853. dy = this.y - v.y,
  8854. dz = this.z - v.z;
  8855. return dx * dx + dy * dy + dz * dz;
  8856. };
  8857. _proto.manhattanDistanceTo = function manhattanDistanceTo(v) {
  8858. return Math.abs(this.x - v.x) + Math.abs(this.y - v.y) + Math.abs(this.z - v.z);
  8859. };
  8860. _proto.setFromSpherical = function setFromSpherical(s) {
  8861. return this.setFromSphericalCoords(s.radius, s.phi, s.theta);
  8862. };
  8863. _proto.setFromSphericalCoords = function setFromSphericalCoords(radius, phi, theta) {
  8864. var sinPhiRadius = Math.sin(phi) * radius;
  8865. this.x = sinPhiRadius * Math.sin(theta);
  8866. this.y = Math.cos(phi) * radius;
  8867. this.z = sinPhiRadius * Math.cos(theta);
  8868. return this;
  8869. };
  8870. _proto.setFromCylindrical = function setFromCylindrical(c) {
  8871. return this.setFromCylindricalCoords(c.radius, c.theta, c.y);
  8872. };
  8873. _proto.setFromCylindricalCoords = function setFromCylindricalCoords(radius, theta, y) {
  8874. this.x = radius * Math.sin(theta);
  8875. this.y = y;
  8876. this.z = radius * Math.cos(theta);
  8877. return this;
  8878. };
  8879. _proto.setFromMatrixPosition = function setFromMatrixPosition(m) {
  8880. var e = m.elements;
  8881. this.x = e[12];
  8882. this.y = e[13];
  8883. this.z = e[14];
  8884. return this;
  8885. };
  8886. _proto.setFromMatrixScale = function setFromMatrixScale(m) {
  8887. var sx = this.setFromMatrixColumn(m, 0).length();
  8888. var sy = this.setFromMatrixColumn(m, 1).length();
  8889. var sz = this.setFromMatrixColumn(m, 2).length();
  8890. this.x = sx;
  8891. this.y = sy;
  8892. this.z = sz;
  8893. return this;
  8894. };
  8895. _proto.setFromMatrixColumn = function setFromMatrixColumn(m, index) {
  8896. return this.fromArray(m.elements, index * 4);
  8897. };
  8898. _proto.setFromMatrix3Column = function setFromMatrix3Column(m, index) {
  8899. return this.fromArray(m.elements, index * 3);
  8900. };
  8901. _proto.equals = function equals(v) {
  8902. return v.x === this.x && v.y === this.y && v.z === this.z;
  8903. };
  8904. _proto.fromArray = function fromArray(array, offset) {
  8905. if (offset === void 0) {
  8906. offset = 0;
  8907. }
  8908. this.x = array[offset];
  8909. this.y = array[offset + 1];
  8910. this.z = array[offset + 2];
  8911. return this;
  8912. };
  8913. _proto.toArray = function toArray(array, offset) {
  8914. if (array === void 0) {
  8915. array = [];
  8916. }
  8917. if (offset === void 0) {
  8918. offset = 0;
  8919. }
  8920. array[offset] = this.x;
  8921. array[offset + 1] = this.y;
  8922. array[offset + 2] = this.z;
  8923. return array;
  8924. };
  8925. _proto.fromBufferAttribute = function fromBufferAttribute(attribute, index, offset) {
  8926. if (offset !== undefined) {
  8927. console.warn('THREE.Vector3: offset has been removed from .fromBufferAttribute().');
  8928. }
  8929. this.x = attribute.getX(index);
  8930. this.y = attribute.getY(index);
  8931. this.z = attribute.getZ(index);
  8932. return this;
  8933. };
  8934. _proto.random = function random() {
  8935. this.x = Math.random();
  8936. this.y = Math.random();
  8937. this.z = Math.random();
  8938. return this;
  8939. };
  8940. return Vector3;
  8941. }();
  8942. var _vector = /*@__PURE__*/new Vector3();
  8943. var _quaternion = /*@__PURE__*/new Quaternion();
  8944. var Box3 = /*#__PURE__*/function () {
  8945. function Box3(min, max) {
  8946. Object.defineProperty(this, 'isBox3', {
  8947. value: true
  8948. });
  8949. this.min = min !== undefined ? min : new Vector3(+Infinity, +Infinity, +Infinity);
  8950. this.max = max !== undefined ? max : new Vector3(-Infinity, -Infinity, -Infinity);
  8951. }
  8952. var _proto = Box3.prototype;
  8953. _proto.set = function set(min, max) {
  8954. this.min.copy(min);
  8955. this.max.copy(max);
  8956. return this;
  8957. };
  8958. _proto.setFromArray = function setFromArray(array) {
  8959. var minX = +Infinity;
  8960. var minY = +Infinity;
  8961. var minZ = +Infinity;
  8962. var maxX = -Infinity;
  8963. var maxY = -Infinity;
  8964. var maxZ = -Infinity;
  8965. for (var i = 0, l = array.length; i < l; i += 3) {
  8966. var x = array[i];
  8967. var y = array[i + 1];
  8968. var z = array[i + 2];
  8969. if (x < minX) minX = x;
  8970. if (y < minY) minY = y;
  8971. if (z < minZ) minZ = z;
  8972. if (x > maxX) maxX = x;
  8973. if (y > maxY) maxY = y;
  8974. if (z > maxZ) maxZ = z;
  8975. }
  8976. this.min.set(minX, minY, minZ);
  8977. this.max.set(maxX, maxY, maxZ);
  8978. return this;
  8979. };
  8980. _proto.setFromBufferAttribute = function setFromBufferAttribute(attribute) {
  8981. var minX = +Infinity;
  8982. var minY = +Infinity;
  8983. var minZ = +Infinity;
  8984. var maxX = -Infinity;
  8985. var maxY = -Infinity;
  8986. var maxZ = -Infinity;
  8987. for (var i = 0, l = attribute.count; i < l; i++) {
  8988. var x = attribute.getX(i);
  8989. var y = attribute.getY(i);
  8990. var z = attribute.getZ(i);
  8991. if (x < minX) minX = x;
  8992. if (y < minY) minY = y;
  8993. if (z < minZ) minZ = z;
  8994. if (x > maxX) maxX = x;
  8995. if (y > maxY) maxY = y;
  8996. if (z > maxZ) maxZ = z;
  8997. }
  8998. this.min.set(minX, minY, minZ);
  8999. this.max.set(maxX, maxY, maxZ);
  9000. return this;
  9001. };
  9002. _proto.setFromPoints = function setFromPoints(points) {
  9003. this.makeEmpty();
  9004. for (var i = 0, il = points.length; i < il; i++) {
  9005. this.expandByPoint(points[i]);
  9006. }
  9007. return this;
  9008. };
  9009. _proto.setFromCenterAndSize = function setFromCenterAndSize(center, size) {
  9010. var halfSize = _vector$1.copy(size).multiplyScalar(0.5);
  9011. this.min.copy(center).sub(halfSize);
  9012. this.max.copy(center).add(halfSize);
  9013. return this;
  9014. };
  9015. _proto.setFromObject = function setFromObject(object) {
  9016. this.makeEmpty();
  9017. return this.expandByObject(object);
  9018. };
  9019. _proto.clone = function clone() {
  9020. return new this.constructor().copy(this);
  9021. };
  9022. _proto.copy = function copy(box) {
  9023. this.min.copy(box.min);
  9024. this.max.copy(box.max);
  9025. return this;
  9026. };
  9027. _proto.makeEmpty = function makeEmpty() {
  9028. this.min.x = this.min.y = this.min.z = +Infinity;
  9029. this.max.x = this.max.y = this.max.z = -Infinity;
  9030. return this;
  9031. };
  9032. _proto.isEmpty = function isEmpty() {
  9033. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  9034. return this.max.x < this.min.x || this.max.y < this.min.y || this.max.z < this.min.z;
  9035. };
  9036. _proto.getCenter = function getCenter(target) {
  9037. if (target === undefined) {
  9038. console.warn('THREE.Box3: .getCenter() target is now required');
  9039. target = new Vector3();
  9040. }
  9041. return this.isEmpty() ? target.set(0, 0, 0) : target.addVectors(this.min, this.max).multiplyScalar(0.5);
  9042. };
  9043. _proto.getSize = function getSize(target) {
  9044. if (target === undefined) {
  9045. console.warn('THREE.Box3: .getSize() target is now required');
  9046. target = new Vector3();
  9047. }
  9048. return this.isEmpty() ? target.set(0, 0, 0) : target.subVectors(this.max, this.min);
  9049. };
  9050. _proto.expandByPoint = function expandByPoint(point) {
  9051. this.min.min(point);
  9052. this.max.max(point);
  9053. return this;
  9054. };
  9055. _proto.expandByVector = function expandByVector(vector) {
  9056. this.min.sub(vector);
  9057. this.max.add(vector);
  9058. return this;
  9059. };
  9060. _proto.expandByScalar = function expandByScalar(scalar) {
  9061. this.min.addScalar(-scalar);
  9062. this.max.addScalar(scalar);
  9063. return this;
  9064. };
  9065. _proto.expandByObject = function expandByObject(object) {
  9066. // Computes the world-axis-aligned bounding box of an object (including its children),
  9067. // accounting for both the object's, and children's, world transforms
  9068. object.updateWorldMatrix(false, false);
  9069. var geometry = object.geometry;
  9070. if (geometry !== undefined) {
  9071. if (geometry.boundingBox === null) {
  9072. geometry.computeBoundingBox();
  9073. }
  9074. _box.copy(geometry.boundingBox);
  9075. _box.applyMatrix4(object.matrixWorld);
  9076. this.union(_box);
  9077. }
  9078. var children = object.children;
  9079. for (var i = 0, l = children.length; i < l; i++) {
  9080. this.expandByObject(children[i]);
  9081. }
  9082. return this;
  9083. };
  9084. _proto.containsPoint = function containsPoint(point) {
  9085. return point.x < this.min.x || point.x > this.max.x || point.y < this.min.y || point.y > this.max.y || point.z < this.min.z || point.z > this.max.z ? false : true;
  9086. };
  9087. _proto.containsBox = function containsBox(box) {
  9088. return this.min.x <= box.min.x && box.max.x <= this.max.x && this.min.y <= box.min.y && box.max.y <= this.max.y && this.min.z <= box.min.z && box.max.z <= this.max.z;
  9089. };
  9090. _proto.getParameter = function getParameter(point, target) {
  9091. // This can potentially have a divide by zero if the box
  9092. // has a size dimension of 0.
  9093. if (target === undefined) {
  9094. console.warn('THREE.Box3: .getParameter() target is now required');
  9095. target = new Vector3();
  9096. }
  9097. return target.set((point.x - this.min.x) / (this.max.x - this.min.x), (point.y - this.min.y) / (this.max.y - this.min.y), (point.z - this.min.z) / (this.max.z - this.min.z));
  9098. };
  9099. _proto.intersectsBox = function intersectsBox(box) {
  9100. // using 6 splitting planes to rule out intersections.
  9101. return box.max.x < this.min.x || box.min.x > this.max.x || box.max.y < this.min.y || box.min.y > this.max.y || box.max.z < this.min.z || box.min.z > this.max.z ? false : true;
  9102. };
  9103. _proto.intersectsSphere = function intersectsSphere(sphere) {
  9104. // Find the point on the AABB closest to the sphere center.
  9105. this.clampPoint(sphere.center, _vector$1); // If that point is inside the sphere, the AABB and sphere intersect.
  9106. return _vector$1.distanceToSquared(sphere.center) <= sphere.radius * sphere.radius;
  9107. };
  9108. _proto.intersectsPlane = function intersectsPlane(plane) {
  9109. // We compute the minimum and maximum dot product values. If those values
  9110. // are on the same side (back or front) of the plane, then there is no intersection.
  9111. var min, max;
  9112. if (plane.normal.x > 0) {
  9113. min = plane.normal.x * this.min.x;
  9114. max = plane.normal.x * this.max.x;
  9115. } else {
  9116. min = plane.normal.x * this.max.x;
  9117. max = plane.normal.x * this.min.x;
  9118. }
  9119. if (plane.normal.y > 0) {
  9120. min += plane.normal.y * this.min.y;
  9121. max += plane.normal.y * this.max.y;
  9122. } else {
  9123. min += plane.normal.y * this.max.y;
  9124. max += plane.normal.y * this.min.y;
  9125. }
  9126. if (plane.normal.z > 0) {
  9127. min += plane.normal.z * this.min.z;
  9128. max += plane.normal.z * this.max.z;
  9129. } else {
  9130. min += plane.normal.z * this.max.z;
  9131. max += plane.normal.z * this.min.z;
  9132. }
  9133. return min <= -plane.constant && max >= -plane.constant;
  9134. };
  9135. _proto.intersectsTriangle = function intersectsTriangle(triangle) {
  9136. if (this.isEmpty()) {
  9137. return false;
  9138. } // compute box center and extents
  9139. this.getCenter(_center);
  9140. _extents.subVectors(this.max, _center); // translate triangle to aabb origin
  9141. _v0.subVectors(triangle.a, _center);
  9142. _v1.subVectors(triangle.b, _center);
  9143. _v2.subVectors(triangle.c, _center); // compute edge vectors for triangle
  9144. _f0.subVectors(_v1, _v0);
  9145. _f1.subVectors(_v2, _v1);
  9146. _f2.subVectors(_v0, _v2); // test against axes that are given by cross product combinations of the edges of the triangle and the edges of the aabb
  9147. // make an axis testing of each of the 3 sides of the aabb against each of the 3 sides of the triangle = 9 axis of separation
  9148. // axis_ij = u_i x f_j (u0, u1, u2 = face normals of aabb = x,y,z axes vectors since aabb is axis aligned)
  9149. var axes = [0, -_f0.z, _f0.y, 0, -_f1.z, _f1.y, 0, -_f2.z, _f2.y, _f0.z, 0, -_f0.x, _f1.z, 0, -_f1.x, _f2.z, 0, -_f2.x, -_f0.y, _f0.x, 0, -_f1.y, _f1.x, 0, -_f2.y, _f2.x, 0];
  9150. if (!satForAxes(axes, _v0, _v1, _v2, _extents)) {
  9151. return false;
  9152. } // test 3 face normals from the aabb
  9153. axes = [1, 0, 0, 0, 1, 0, 0, 0, 1];
  9154. if (!satForAxes(axes, _v0, _v1, _v2, _extents)) {
  9155. return false;
  9156. } // finally testing the face normal of the triangle
  9157. // use already existing triangle edge vectors here
  9158. _triangleNormal.crossVectors(_f0, _f1);
  9159. axes = [_triangleNormal.x, _triangleNormal.y, _triangleNormal.z];
  9160. return satForAxes(axes, _v0, _v1, _v2, _extents);
  9161. };
  9162. _proto.clampPoint = function clampPoint(point, target) {
  9163. if (target === undefined) {
  9164. console.warn('THREE.Box3: .clampPoint() target is now required');
  9165. target = new Vector3();
  9166. }
  9167. return target.copy(point).clamp(this.min, this.max);
  9168. };
  9169. _proto.distanceToPoint = function distanceToPoint(point) {
  9170. var clampedPoint = _vector$1.copy(point).clamp(this.min, this.max);
  9171. return clampedPoint.sub(point).length();
  9172. };
  9173. _proto.getBoundingSphere = function getBoundingSphere(target) {
  9174. if (target === undefined) {
  9175. console.error('THREE.Box3: .getBoundingSphere() target is now required'); //target = new Sphere(); // removed to avoid cyclic dependency
  9176. }
  9177. this.getCenter(target.center);
  9178. target.radius = this.getSize(_vector$1).length() * 0.5;
  9179. return target;
  9180. };
  9181. _proto.intersect = function intersect(box) {
  9182. this.min.max(box.min);
  9183. this.max.min(box.max); // ensure that if there is no overlap, the result is fully empty, not slightly empty with non-inf/+inf values that will cause subsequence intersects to erroneously return valid values.
  9184. if (this.isEmpty()) this.makeEmpty();
  9185. return this;
  9186. };
  9187. _proto.union = function union(box) {
  9188. this.min.min(box.min);
  9189. this.max.max(box.max);
  9190. return this;
  9191. };
  9192. _proto.applyMatrix4 = function applyMatrix4(matrix) {
  9193. // transform of empty box is an empty box.
  9194. if (this.isEmpty()) return this; // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  9195. _points[0].set(this.min.x, this.min.y, this.min.z).applyMatrix4(matrix); // 000
  9196. _points[1].set(this.min.x, this.min.y, this.max.z).applyMatrix4(matrix); // 001
  9197. _points[2].set(this.min.x, this.max.y, this.min.z).applyMatrix4(matrix); // 010
  9198. _points[3].set(this.min.x, this.max.y, this.max.z).applyMatrix4(matrix); // 011
  9199. _points[4].set(this.max.x, this.min.y, this.min.z).applyMatrix4(matrix); // 100
  9200. _points[5].set(this.max.x, this.min.y, this.max.z).applyMatrix4(matrix); // 101
  9201. _points[6].set(this.max.x, this.max.y, this.min.z).applyMatrix4(matrix); // 110
  9202. _points[7].set(this.max.x, this.max.y, this.max.z).applyMatrix4(matrix); // 111
  9203. this.setFromPoints(_points);
  9204. return this;
  9205. };
  9206. _proto.translate = function translate(offset) {
  9207. this.min.add(offset);
  9208. this.max.add(offset);
  9209. return this;
  9210. };
  9211. _proto.equals = function equals(box) {
  9212. return box.min.equals(this.min) && box.max.equals(this.max);
  9213. };
  9214. return Box3;
  9215. }();
  9216. function satForAxes(axes, v0, v1, v2, extents) {
  9217. for (var i = 0, j = axes.length - 3; i <= j; i += 3) {
  9218. _testAxis.fromArray(axes, i); // project the aabb onto the seperating axis
  9219. var r = extents.x * Math.abs(_testAxis.x) + extents.y * Math.abs(_testAxis.y) + extents.z * Math.abs(_testAxis.z); // project all 3 vertices of the triangle onto the seperating axis
  9220. var p0 = v0.dot(_testAxis);
  9221. var p1 = v1.dot(_testAxis);
  9222. var p2 = v2.dot(_testAxis); // actual test, basically see if either of the most extreme of the triangle points intersects r
  9223. if (Math.max(-Math.max(p0, p1, p2), Math.min(p0, p1, p2)) > r) {
  9224. // points of the projected triangle are outside the projected half-length of the aabb
  9225. // the axis is seperating and we can exit
  9226. return false;
  9227. }
  9228. }
  9229. return true;
  9230. }
  9231. var _points = [/*@__PURE__*/new Vector3(), /*@__PURE__*/new Vector3(), /*@__PURE__*/new Vector3(), /*@__PURE__*/new Vector3(), /*@__PURE__*/new Vector3(), /*@__PURE__*/new Vector3(), /*@__PURE__*/new Vector3(), /*@__PURE__*/new Vector3()];
  9232. var _vector$1 = /*@__PURE__*/new Vector3();
  9233. var _box = /*@__PURE__*/new Box3(); // triangle centered vertices
  9234. var _v0 = /*@__PURE__*/new Vector3();
  9235. var _v1 = /*@__PURE__*/new Vector3();
  9236. var _v2 = /*@__PURE__*/new Vector3(); // triangle edge vectors
  9237. var _f0 = /*@__PURE__*/new Vector3();
  9238. var _f1 = /*@__PURE__*/new Vector3();
  9239. var _f2 = /*@__PURE__*/new Vector3();
  9240. var _center = /*@__PURE__*/new Vector3();
  9241. var _extents = /*@__PURE__*/new Vector3();
  9242. var _triangleNormal = /*@__PURE__*/new Vector3();
  9243. var _testAxis = /*@__PURE__*/new Vector3();
  9244. var _box$1 = /*@__PURE__*/new Box3();
  9245. var Sphere = /*#__PURE__*/function () {
  9246. function Sphere(center, radius) {
  9247. this.center = center !== undefined ? center : new Vector3();
  9248. this.radius = radius !== undefined ? radius : -1;
  9249. }
  9250. var _proto = Sphere.prototype;
  9251. _proto.set = function set(center, radius) {
  9252. this.center.copy(center);
  9253. this.radius = radius;
  9254. return this;
  9255. };
  9256. _proto.setFromPoints = function setFromPoints(points, optionalCenter) {
  9257. var center = this.center;
  9258. if (optionalCenter !== undefined) {
  9259. center.copy(optionalCenter);
  9260. } else {
  9261. _box$1.setFromPoints(points).getCenter(center);
  9262. }
  9263. var maxRadiusSq = 0;
  9264. for (var i = 0, il = points.length; i < il; i++) {
  9265. maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(points[i]));
  9266. }
  9267. this.radius = Math.sqrt(maxRadiusSq);
  9268. return this;
  9269. };
  9270. _proto.clone = function clone() {
  9271. return new this.constructor().copy(this);
  9272. };
  9273. _proto.copy = function copy(sphere) {
  9274. this.center.copy(sphere.center);
  9275. this.radius = sphere.radius;
  9276. return this;
  9277. };
  9278. _proto.isEmpty = function isEmpty() {
  9279. return this.radius < 0;
  9280. };
  9281. _proto.makeEmpty = function makeEmpty() {
  9282. this.center.set(0, 0, 0);
  9283. this.radius = -1;
  9284. return this;
  9285. };
  9286. _proto.containsPoint = function containsPoint(point) {
  9287. return point.distanceToSquared(this.center) <= this.radius * this.radius;
  9288. };
  9289. _proto.distanceToPoint = function distanceToPoint(point) {
  9290. return point.distanceTo(this.center) - this.radius;
  9291. };
  9292. _proto.intersectsSphere = function intersectsSphere(sphere) {
  9293. var radiusSum = this.radius + sphere.radius;
  9294. return sphere.center.distanceToSquared(this.center) <= radiusSum * radiusSum;
  9295. };
  9296. _proto.intersectsBox = function intersectsBox(box) {
  9297. return box.intersectsSphere(this);
  9298. };
  9299. _proto.intersectsPlane = function intersectsPlane(plane) {
  9300. return Math.abs(plane.distanceToPoint(this.center)) <= this.radius;
  9301. };
  9302. _proto.clampPoint = function clampPoint(point, target) {
  9303. var deltaLengthSq = this.center.distanceToSquared(point);
  9304. if (target === undefined) {
  9305. console.warn('THREE.Sphere: .clampPoint() target is now required');
  9306. target = new Vector3();
  9307. }
  9308. target.copy(point);
  9309. if (deltaLengthSq > this.radius * this.radius) {
  9310. target.sub(this.center).normalize();
  9311. target.multiplyScalar(this.radius).add(this.center);
  9312. }
  9313. return target;
  9314. };
  9315. _proto.getBoundingBox = function getBoundingBox(target) {
  9316. if (target === undefined) {
  9317. console.warn('THREE.Sphere: .getBoundingBox() target is now required');
  9318. target = new Box3();
  9319. }
  9320. if (this.isEmpty()) {
  9321. // Empty sphere produces empty bounding box
  9322. target.makeEmpty();
  9323. return target;
  9324. }
  9325. target.set(this.center, this.center);
  9326. target.expandByScalar(this.radius);
  9327. return target;
  9328. };
  9329. _proto.applyMatrix4 = function applyMatrix4(matrix) {
  9330. this.center.applyMatrix4(matrix);
  9331. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  9332. return this;
  9333. };
  9334. _proto.translate = function translate(offset) {
  9335. this.center.add(offset);
  9336. return this;
  9337. };
  9338. _proto.equals = function equals(sphere) {
  9339. return sphere.center.equals(this.center) && sphere.radius === this.radius;
  9340. };
  9341. return Sphere;
  9342. }();
  9343. var _vector$2 = /*@__PURE__*/new Vector3();
  9344. var _segCenter = /*@__PURE__*/new Vector3();
  9345. var _segDir = /*@__PURE__*/new Vector3();
  9346. var _diff = /*@__PURE__*/new Vector3();
  9347. var _edge1 = /*@__PURE__*/new Vector3();
  9348. var _edge2 = /*@__PURE__*/new Vector3();
  9349. var _normal = /*@__PURE__*/new Vector3();
  9350. var Ray = /*#__PURE__*/function () {
  9351. function Ray(origin, direction) {
  9352. this.origin = origin !== undefined ? origin : new Vector3();
  9353. this.direction = direction !== undefined ? direction : new Vector3(0, 0, -1);
  9354. }
  9355. var _proto = Ray.prototype;
  9356. _proto.set = function set(origin, direction) {
  9357. this.origin.copy(origin);
  9358. this.direction.copy(direction);
  9359. return this;
  9360. };
  9361. _proto.clone = function clone() {
  9362. return new this.constructor().copy(this);
  9363. };
  9364. _proto.copy = function copy(ray) {
  9365. this.origin.copy(ray.origin);
  9366. this.direction.copy(ray.direction);
  9367. return this;
  9368. };
  9369. _proto.at = function at(t, target) {
  9370. if (target === undefined) {
  9371. console.warn('THREE.Ray: .at() target is now required');
  9372. target = new Vector3();
  9373. }
  9374. return target.copy(this.direction).multiplyScalar(t).add(this.origin);
  9375. };
  9376. _proto.lookAt = function lookAt(v) {
  9377. this.direction.copy(v).sub(this.origin).normalize();
  9378. return this;
  9379. };
  9380. _proto.recast = function recast(t) {
  9381. this.origin.copy(this.at(t, _vector$2));
  9382. return this;
  9383. };
  9384. _proto.closestPointToPoint = function closestPointToPoint(point, target) {
  9385. if (target === undefined) {
  9386. console.warn('THREE.Ray: .closestPointToPoint() target is now required');
  9387. target = new Vector3();
  9388. }
  9389. target.subVectors(point, this.origin);
  9390. var directionDistance = target.dot(this.direction);
  9391. if (directionDistance < 0) {
  9392. return target.copy(this.origin);
  9393. }
  9394. return target.copy(this.direction).multiplyScalar(directionDistance).add(this.origin);
  9395. };
  9396. _proto.distanceToPoint = function distanceToPoint(point) {
  9397. return Math.sqrt(this.distanceSqToPoint(point));
  9398. };
  9399. _proto.distanceSqToPoint = function distanceSqToPoint(point) {
  9400. var directionDistance = _vector$2.subVectors(point, this.origin).dot(this.direction); // point behind the ray
  9401. if (directionDistance < 0) {
  9402. return this.origin.distanceToSquared(point);
  9403. }
  9404. _vector$2.copy(this.direction).multiplyScalar(directionDistance).add(this.origin);
  9405. return _vector$2.distanceToSquared(point);
  9406. };
  9407. _proto.distanceSqToSegment = function distanceSqToSegment(v0, v1, optionalPointOnRay, optionalPointOnSegment) {
  9408. // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteDistRaySegment.h
  9409. // It returns the min distance between the ray and the segment
  9410. // defined by v0 and v1
  9411. // It can also set two optional targets :
  9412. // - The closest point on the ray
  9413. // - The closest point on the segment
  9414. _segCenter.copy(v0).add(v1).multiplyScalar(0.5);
  9415. _segDir.copy(v1).sub(v0).normalize();
  9416. _diff.copy(this.origin).sub(_segCenter);
  9417. var segExtent = v0.distanceTo(v1) * 0.5;
  9418. var a01 = -this.direction.dot(_segDir);
  9419. var b0 = _diff.dot(this.direction);
  9420. var b1 = -_diff.dot(_segDir);
  9421. var c = _diff.lengthSq();
  9422. var det = Math.abs(1 - a01 * a01);
  9423. var s0, s1, sqrDist, extDet;
  9424. if (det > 0) {
  9425. // The ray and segment are not parallel.
  9426. s0 = a01 * b1 - b0;
  9427. s1 = a01 * b0 - b1;
  9428. extDet = segExtent * det;
  9429. if (s0 >= 0) {
  9430. if (s1 >= -extDet) {
  9431. if (s1 <= extDet) {
  9432. // region 0
  9433. // Minimum at interior points of ray and segment.
  9434. var invDet = 1 / det;
  9435. s0 *= invDet;
  9436. s1 *= invDet;
  9437. sqrDist = s0 * (s0 + a01 * s1 + 2 * b0) + s1 * (a01 * s0 + s1 + 2 * b1) + c;
  9438. } else {
  9439. // region 1
  9440. s1 = segExtent;
  9441. s0 = Math.max(0, -(a01 * s1 + b0));
  9442. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  9443. }
  9444. } else {
  9445. // region 5
  9446. s1 = -segExtent;
  9447. s0 = Math.max(0, -(a01 * s1 + b0));
  9448. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  9449. }
  9450. } else {
  9451. if (s1 <= -extDet) {
  9452. // region 4
  9453. s0 = Math.max(0, -(-a01 * segExtent + b0));
  9454. s1 = s0 > 0 ? -segExtent : Math.min(Math.max(-segExtent, -b1), segExtent);
  9455. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  9456. } else if (s1 <= extDet) {
  9457. // region 3
  9458. s0 = 0;
  9459. s1 = Math.min(Math.max(-segExtent, -b1), segExtent);
  9460. sqrDist = s1 * (s1 + 2 * b1) + c;
  9461. } else {
  9462. // region 2
  9463. s0 = Math.max(0, -(a01 * segExtent + b0));
  9464. s1 = s0 > 0 ? segExtent : Math.min(Math.max(-segExtent, -b1), segExtent);
  9465. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  9466. }
  9467. }
  9468. } else {
  9469. // Ray and segment are parallel.
  9470. s1 = a01 > 0 ? -segExtent : segExtent;
  9471. s0 = Math.max(0, -(a01 * s1 + b0));
  9472. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  9473. }
  9474. if (optionalPointOnRay) {
  9475. optionalPointOnRay.copy(this.direction).multiplyScalar(s0).add(this.origin);
  9476. }
  9477. if (optionalPointOnSegment) {
  9478. optionalPointOnSegment.copy(_segDir).multiplyScalar(s1).add(_segCenter);
  9479. }
  9480. return sqrDist;
  9481. };
  9482. _proto.intersectSphere = function intersectSphere(sphere, target) {
  9483. _vector$2.subVectors(sphere.center, this.origin);
  9484. var tca = _vector$2.dot(this.direction);
  9485. var d2 = _vector$2.dot(_vector$2) - tca * tca;
  9486. var radius2 = sphere.radius * sphere.radius;
  9487. if (d2 > radius2) return null;
  9488. var thc = Math.sqrt(radius2 - d2); // t0 = first intersect point - entrance on front of sphere
  9489. var t0 = tca - thc; // t1 = second intersect point - exit point on back of sphere
  9490. var t1 = tca + thc; // test to see if both t0 and t1 are behind the ray - if so, return null
  9491. if (t0 < 0 && t1 < 0) return null; // test to see if t0 is behind the ray:
  9492. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  9493. // in order to always return an intersect point that is in front of the ray.
  9494. if (t0 < 0) return this.at(t1, target); // else t0 is in front of the ray, so return the first collision point scaled by t0
  9495. return this.at(t0, target);
  9496. };
  9497. _proto.intersectsSphere = function intersectsSphere(sphere) {
  9498. return this.distanceSqToPoint(sphere.center) <= sphere.radius * sphere.radius;
  9499. };
  9500. _proto.distanceToPlane = function distanceToPlane(plane) {
  9501. var denominator = plane.normal.dot(this.direction);
  9502. if (denominator === 0) {
  9503. // line is coplanar, return origin
  9504. if (plane.distanceToPoint(this.origin) === 0) {
  9505. return 0;
  9506. } // Null is preferable to undefined since undefined means.... it is undefined
  9507. return null;
  9508. }
  9509. var t = -(this.origin.dot(plane.normal) + plane.constant) / denominator; // Return if the ray never intersects the plane
  9510. return t >= 0 ? t : null;
  9511. };
  9512. _proto.intersectPlane = function intersectPlane(plane, target) {
  9513. var t = this.distanceToPlane(plane);
  9514. if (t === null) {
  9515. return null;
  9516. }
  9517. return this.at(t, target);
  9518. };
  9519. _proto.intersectsPlane = function intersectsPlane(plane) {
  9520. // check if the ray lies on the plane first
  9521. var distToPoint = plane.distanceToPoint(this.origin);
  9522. if (distToPoint === 0) {
  9523. return true;
  9524. }
  9525. var denominator = plane.normal.dot(this.direction);
  9526. if (denominator * distToPoint < 0) {
  9527. return true;
  9528. } // ray origin is behind the plane (and is pointing behind it)
  9529. return false;
  9530. };
  9531. _proto.intersectBox = function intersectBox(box, target) {
  9532. var tmin, tmax, tymin, tymax, tzmin, tzmax;
  9533. var invdirx = 1 / this.direction.x,
  9534. invdiry = 1 / this.direction.y,
  9535. invdirz = 1 / this.direction.z;
  9536. var origin = this.origin;
  9537. if (invdirx >= 0) {
  9538. tmin = (box.min.x - origin.x) * invdirx;
  9539. tmax = (box.max.x - origin.x) * invdirx;
  9540. } else {
  9541. tmin = (box.max.x - origin.x) * invdirx;
  9542. tmax = (box.min.x - origin.x) * invdirx;
  9543. }
  9544. if (invdiry >= 0) {
  9545. tymin = (box.min.y - origin.y) * invdiry;
  9546. tymax = (box.max.y - origin.y) * invdiry;
  9547. } else {
  9548. tymin = (box.max.y - origin.y) * invdiry;
  9549. tymax = (box.min.y - origin.y) * invdiry;
  9550. }
  9551. if (tmin > tymax || tymin > tmax) return null; // These lines also handle the case where tmin or tmax is NaN
  9552. // (result of 0 * Infinity). x !== x returns true if x is NaN
  9553. if (tymin > tmin || tmin !== tmin) tmin = tymin;
  9554. if (tymax < tmax || tmax !== tmax) tmax = tymax;
  9555. if (invdirz >= 0) {
  9556. tzmin = (box.min.z - origin.z) * invdirz;
  9557. tzmax = (box.max.z - origin.z) * invdirz;
  9558. } else {
  9559. tzmin = (box.max.z - origin.z) * invdirz;
  9560. tzmax = (box.min.z - origin.z) * invdirz;
  9561. }
  9562. if (tmin > tzmax || tzmin > tmax) return null;
  9563. if (tzmin > tmin || tmin !== tmin) tmin = tzmin;
  9564. if (tzmax < tmax || tmax !== tmax) tmax = tzmax; //return point closest to the ray (positive side)
  9565. if (tmax < 0) return null;
  9566. return this.at(tmin >= 0 ? tmin : tmax, target);
  9567. };
  9568. _proto.intersectsBox = function intersectsBox(box) {
  9569. return this.intersectBox(box, _vector$2) !== null;
  9570. };
  9571. _proto.intersectTriangle = function intersectTriangle(a, b, c, backfaceCulling, target) {
  9572. // Compute the offset origin, edges, and normal.
  9573. // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h
  9574. _edge1.subVectors(b, a);
  9575. _edge2.subVectors(c, a);
  9576. _normal.crossVectors(_edge1, _edge2); // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  9577. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  9578. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  9579. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  9580. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  9581. var DdN = this.direction.dot(_normal);
  9582. var sign;
  9583. if (DdN > 0) {
  9584. if (backfaceCulling) return null;
  9585. sign = 1;
  9586. } else if (DdN < 0) {
  9587. sign = -1;
  9588. DdN = -DdN;
  9589. } else {
  9590. return null;
  9591. }
  9592. _diff.subVectors(this.origin, a);
  9593. var DdQxE2 = sign * this.direction.dot(_edge2.crossVectors(_diff, _edge2)); // b1 < 0, no intersection
  9594. if (DdQxE2 < 0) {
  9595. return null;
  9596. }
  9597. var DdE1xQ = sign * this.direction.dot(_edge1.cross(_diff)); // b2 < 0, no intersection
  9598. if (DdE1xQ < 0) {
  9599. return null;
  9600. } // b1+b2 > 1, no intersection
  9601. if (DdQxE2 + DdE1xQ > DdN) {
  9602. return null;
  9603. } // Line intersects triangle, check if ray does.
  9604. var QdN = -sign * _diff.dot(_normal); // t < 0, no intersection
  9605. if (QdN < 0) {
  9606. return null;
  9607. } // Ray intersects triangle.
  9608. return this.at(QdN / DdN, target);
  9609. };
  9610. _proto.applyMatrix4 = function applyMatrix4(matrix4) {
  9611. this.origin.applyMatrix4(matrix4);
  9612. this.direction.transformDirection(matrix4);
  9613. return this;
  9614. };
  9615. _proto.equals = function equals(ray) {
  9616. return ray.origin.equals(this.origin) && ray.direction.equals(this.direction);
  9617. };
  9618. return Ray;
  9619. }();
  9620. var Matrix4 = /*#__PURE__*/function () {
  9621. function Matrix4() {
  9622. Object.defineProperty(this, 'isMatrix4', {
  9623. value: true
  9624. });
  9625. this.elements = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
  9626. if (arguments.length > 0) {
  9627. console.error('THREE.Matrix4: the constructor no longer reads arguments. use .set() instead.');
  9628. }
  9629. }
  9630. var _proto = Matrix4.prototype;
  9631. _proto.set = function set(n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44) {
  9632. var te = this.elements;
  9633. te[0] = n11;
  9634. te[4] = n12;
  9635. te[8] = n13;
  9636. te[12] = n14;
  9637. te[1] = n21;
  9638. te[5] = n22;
  9639. te[9] = n23;
  9640. te[13] = n24;
  9641. te[2] = n31;
  9642. te[6] = n32;
  9643. te[10] = n33;
  9644. te[14] = n34;
  9645. te[3] = n41;
  9646. te[7] = n42;
  9647. te[11] = n43;
  9648. te[15] = n44;
  9649. return this;
  9650. };
  9651. _proto.identity = function identity() {
  9652. this.set(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
  9653. return this;
  9654. };
  9655. _proto.clone = function clone() {
  9656. return new Matrix4().fromArray(this.elements);
  9657. };
  9658. _proto.copy = function copy(m) {
  9659. var te = this.elements;
  9660. var me = m.elements;
  9661. te[0] = me[0];
  9662. te[1] = me[1];
  9663. te[2] = me[2];
  9664. te[3] = me[3];
  9665. te[4] = me[4];
  9666. te[5] = me[5];
  9667. te[6] = me[6];
  9668. te[7] = me[7];
  9669. te[8] = me[8];
  9670. te[9] = me[9];
  9671. te[10] = me[10];
  9672. te[11] = me[11];
  9673. te[12] = me[12];
  9674. te[13] = me[13];
  9675. te[14] = me[14];
  9676. te[15] = me[15];
  9677. return this;
  9678. };
  9679. _proto.copyPosition = function copyPosition(m) {
  9680. var te = this.elements,
  9681. me = m.elements;
  9682. te[12] = me[12];
  9683. te[13] = me[13];
  9684. te[14] = me[14];
  9685. return this;
  9686. };
  9687. _proto.setFromMatrix3 = function setFromMatrix3(m) {
  9688. var me = m.elements;
  9689. this.set(me[0], me[3], me[6], 0, me[1], me[4], me[7], 0, me[2], me[5], me[8], 0, 0, 0, 0, 1);
  9690. return this;
  9691. };
  9692. _proto.extractBasis = function extractBasis(xAxis, yAxis, zAxis) {
  9693. xAxis.setFromMatrixColumn(this, 0);
  9694. yAxis.setFromMatrixColumn(this, 1);
  9695. zAxis.setFromMatrixColumn(this, 2);
  9696. return this;
  9697. };
  9698. _proto.makeBasis = function makeBasis(xAxis, yAxis, zAxis) {
  9699. this.set(xAxis.x, yAxis.x, zAxis.x, 0, xAxis.y, yAxis.y, zAxis.y, 0, xAxis.z, yAxis.z, zAxis.z, 0, 0, 0, 0, 1);
  9700. return this;
  9701. };
  9702. _proto.extractRotation = function extractRotation(m) {
  9703. // this method does not support reflection matrices
  9704. var te = this.elements;
  9705. var me = m.elements;
  9706. var scaleX = 1 / _v1$1.setFromMatrixColumn(m, 0).length();
  9707. var scaleY = 1 / _v1$1.setFromMatrixColumn(m, 1).length();
  9708. var scaleZ = 1 / _v1$1.setFromMatrixColumn(m, 2).length();
  9709. te[0] = me[0] * scaleX;
  9710. te[1] = me[1] * scaleX;
  9711. te[2] = me[2] * scaleX;
  9712. te[3] = 0;
  9713. te[4] = me[4] * scaleY;
  9714. te[5] = me[5] * scaleY;
  9715. te[6] = me[6] * scaleY;
  9716. te[7] = 0;
  9717. te[8] = me[8] * scaleZ;
  9718. te[9] = me[9] * scaleZ;
  9719. te[10] = me[10] * scaleZ;
  9720. te[11] = 0;
  9721. te[12] = 0;
  9722. te[13] = 0;
  9723. te[14] = 0;
  9724. te[15] = 1;
  9725. return this;
  9726. };
  9727. _proto.makeRotationFromEuler = function makeRotationFromEuler(euler) {
  9728. if (!(euler && euler.isEuler)) {
  9729. console.error('THREE.Matrix4: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.');
  9730. }
  9731. var te = this.elements;
  9732. var x = euler.x,
  9733. y = euler.y,
  9734. z = euler.z;
  9735. var a = Math.cos(x),
  9736. b = Math.sin(x);
  9737. var c = Math.cos(y),
  9738. d = Math.sin(y);
  9739. var e = Math.cos(z),
  9740. f = Math.sin(z);
  9741. if (euler.order === 'XYZ') {
  9742. var ae = a * e,
  9743. af = a * f,
  9744. be = b * e,
  9745. bf = b * f;
  9746. te[0] = c * e;
  9747. te[4] = -c * f;
  9748. te[8] = d;
  9749. te[1] = af + be * d;
  9750. te[5] = ae - bf * d;
  9751. te[9] = -b * c;
  9752. te[2] = bf - ae * d;
  9753. te[6] = be + af * d;
  9754. te[10] = a * c;
  9755. } else if (euler.order === 'YXZ') {
  9756. var ce = c * e,
  9757. cf = c * f,
  9758. de = d * e,
  9759. df = d * f;
  9760. te[0] = ce + df * b;
  9761. te[4] = de * b - cf;
  9762. te[8] = a * d;
  9763. te[1] = a * f;
  9764. te[5] = a * e;
  9765. te[9] = -b;
  9766. te[2] = cf * b - de;
  9767. te[6] = df + ce * b;
  9768. te[10] = a * c;
  9769. } else if (euler.order === 'ZXY') {
  9770. var _ce = c * e,
  9771. _cf = c * f,
  9772. _de = d * e,
  9773. _df = d * f;
  9774. te[0] = _ce - _df * b;
  9775. te[4] = -a * f;
  9776. te[8] = _de + _cf * b;
  9777. te[1] = _cf + _de * b;
  9778. te[5] = a * e;
  9779. te[9] = _df - _ce * b;
  9780. te[2] = -a * d;
  9781. te[6] = b;
  9782. te[10] = a * c;
  9783. } else if (euler.order === 'ZYX') {
  9784. var _ae = a * e,
  9785. _af = a * f,
  9786. _be = b * e,
  9787. _bf = b * f;
  9788. te[0] = c * e;
  9789. te[4] = _be * d - _af;
  9790. te[8] = _ae * d + _bf;
  9791. te[1] = c * f;
  9792. te[5] = _bf * d + _ae;
  9793. te[9] = _af * d - _be;
  9794. te[2] = -d;
  9795. te[6] = b * c;
  9796. te[10] = a * c;
  9797. } else if (euler.order === 'YZX') {
  9798. var ac = a * c,
  9799. ad = a * d,
  9800. bc = b * c,
  9801. bd = b * d;
  9802. te[0] = c * e;
  9803. te[4] = bd - ac * f;
  9804. te[8] = bc * f + ad;
  9805. te[1] = f;
  9806. te[5] = a * e;
  9807. te[9] = -b * e;
  9808. te[2] = -d * e;
  9809. te[6] = ad * f + bc;
  9810. te[10] = ac - bd * f;
  9811. } else if (euler.order === 'XZY') {
  9812. var _ac = a * c,
  9813. _ad = a * d,
  9814. _bc = b * c,
  9815. _bd = b * d;
  9816. te[0] = c * e;
  9817. te[4] = -f;
  9818. te[8] = d * e;
  9819. te[1] = _ac * f + _bd;
  9820. te[5] = a * e;
  9821. te[9] = _ad * f - _bc;
  9822. te[2] = _bc * f - _ad;
  9823. te[6] = b * e;
  9824. te[10] = _bd * f + _ac;
  9825. } // bottom row
  9826. te[3] = 0;
  9827. te[7] = 0;
  9828. te[11] = 0; // last column
  9829. te[12] = 0;
  9830. te[13] = 0;
  9831. te[14] = 0;
  9832. te[15] = 1;
  9833. return this;
  9834. };
  9835. _proto.makeRotationFromQuaternion = function makeRotationFromQuaternion(q) {
  9836. return this.compose(_zero, q, _one);
  9837. };
  9838. _proto.lookAt = function lookAt(eye, target, up) {
  9839. var te = this.elements;
  9840. _z.subVectors(eye, target);
  9841. if (_z.lengthSq() === 0) {
  9842. // eye and target are in the same position
  9843. _z.z = 1;
  9844. }
  9845. _z.normalize();
  9846. _x.crossVectors(up, _z);
  9847. if (_x.lengthSq() === 0) {
  9848. // up and z are parallel
  9849. if (Math.abs(up.z) === 1) {
  9850. _z.x += 0.0001;
  9851. } else {
  9852. _z.z += 0.0001;
  9853. }
  9854. _z.normalize();
  9855. _x.crossVectors(up, _z);
  9856. }
  9857. _x.normalize();
  9858. _y.crossVectors(_z, _x);
  9859. te[0] = _x.x;
  9860. te[4] = _y.x;
  9861. te[8] = _z.x;
  9862. te[1] = _x.y;
  9863. te[5] = _y.y;
  9864. te[9] = _z.y;
  9865. te[2] = _x.z;
  9866. te[6] = _y.z;
  9867. te[10] = _z.z;
  9868. return this;
  9869. };
  9870. _proto.multiply = function multiply(m, n) {
  9871. if (n !== undefined) {
  9872. console.warn('THREE.Matrix4: .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead.');
  9873. return this.multiplyMatrices(m, n);
  9874. }
  9875. return this.multiplyMatrices(this, m);
  9876. };
  9877. _proto.premultiply = function premultiply(m) {
  9878. return this.multiplyMatrices(m, this);
  9879. };
  9880. _proto.multiplyMatrices = function multiplyMatrices(a, b) {
  9881. var ae = a.elements;
  9882. var be = b.elements;
  9883. var te = this.elements;
  9884. var a11 = ae[0],
  9885. a12 = ae[4],
  9886. a13 = ae[8],
  9887. a14 = ae[12];
  9888. var a21 = ae[1],
  9889. a22 = ae[5],
  9890. a23 = ae[9],
  9891. a24 = ae[13];
  9892. var a31 = ae[2],
  9893. a32 = ae[6],
  9894. a33 = ae[10],
  9895. a34 = ae[14];
  9896. var a41 = ae[3],
  9897. a42 = ae[7],
  9898. a43 = ae[11],
  9899. a44 = ae[15];
  9900. var b11 = be[0],
  9901. b12 = be[4],
  9902. b13 = be[8],
  9903. b14 = be[12];
  9904. var b21 = be[1],
  9905. b22 = be[5],
  9906. b23 = be[9],
  9907. b24 = be[13];
  9908. var b31 = be[2],
  9909. b32 = be[6],
  9910. b33 = be[10],
  9911. b34 = be[14];
  9912. var b41 = be[3],
  9913. b42 = be[7],
  9914. b43 = be[11],
  9915. b44 = be[15];
  9916. te[0] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  9917. te[4] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  9918. te[8] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  9919. te[12] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  9920. te[1] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  9921. te[5] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  9922. te[9] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  9923. te[13] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  9924. te[2] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  9925. te[6] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  9926. te[10] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  9927. te[14] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  9928. te[3] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  9929. te[7] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  9930. te[11] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  9931. te[15] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  9932. return this;
  9933. };
  9934. _proto.multiplyScalar = function multiplyScalar(s) {
  9935. var te = this.elements;
  9936. te[0] *= s;
  9937. te[4] *= s;
  9938. te[8] *= s;
  9939. te[12] *= s;
  9940. te[1] *= s;
  9941. te[5] *= s;
  9942. te[9] *= s;
  9943. te[13] *= s;
  9944. te[2] *= s;
  9945. te[6] *= s;
  9946. te[10] *= s;
  9947. te[14] *= s;
  9948. te[3] *= s;
  9949. te[7] *= s;
  9950. te[11] *= s;
  9951. te[15] *= s;
  9952. return this;
  9953. };
  9954. _proto.determinant = function determinant() {
  9955. var te = this.elements;
  9956. var n11 = te[0],
  9957. n12 = te[4],
  9958. n13 = te[8],
  9959. n14 = te[12];
  9960. var n21 = te[1],
  9961. n22 = te[5],
  9962. n23 = te[9],
  9963. n24 = te[13];
  9964. var n31 = te[2],
  9965. n32 = te[6],
  9966. n33 = te[10],
  9967. n34 = te[14];
  9968. var n41 = te[3],
  9969. n42 = te[7],
  9970. n43 = te[11],
  9971. n44 = te[15]; //TODO: make this more efficient
  9972. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  9973. return n41 * (+n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34) + n42 * (+n11 * n23 * n34 - n11 * n24 * n33 + n14 * n21 * n33 - n13 * n21 * n34 + n13 * n24 * n31 - n14 * n23 * n31) + n43 * (+n11 * n24 * n32 - n11 * n22 * n34 - n14 * n21 * n32 + n12 * n21 * n34 + n14 * n22 * n31 - n12 * n24 * n31) + n44 * (-n13 * n22 * n31 - n11 * n23 * n32 + n11 * n22 * n33 + n13 * n21 * n32 - n12 * n21 * n33 + n12 * n23 * n31);
  9974. };
  9975. _proto.transpose = function transpose() {
  9976. var te = this.elements;
  9977. var tmp;
  9978. tmp = te[1];
  9979. te[1] = te[4];
  9980. te[4] = tmp;
  9981. tmp = te[2];
  9982. te[2] = te[8];
  9983. te[8] = tmp;
  9984. tmp = te[6];
  9985. te[6] = te[9];
  9986. te[9] = tmp;
  9987. tmp = te[3];
  9988. te[3] = te[12];
  9989. te[12] = tmp;
  9990. tmp = te[7];
  9991. te[7] = te[13];
  9992. te[13] = tmp;
  9993. tmp = te[11];
  9994. te[11] = te[14];
  9995. te[14] = tmp;
  9996. return this;
  9997. };
  9998. _proto.setPosition = function setPosition(x, y, z) {
  9999. var te = this.elements;
  10000. if (x.isVector3) {
  10001. te[12] = x.x;
  10002. te[13] = x.y;
  10003. te[14] = x.z;
  10004. } else {
  10005. te[12] = x;
  10006. te[13] = y;
  10007. te[14] = z;
  10008. }
  10009. return this;
  10010. };
  10011. _proto.invert = function invert() {
  10012. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  10013. var te = this.elements,
  10014. n11 = te[0],
  10015. n21 = te[1],
  10016. n31 = te[2],
  10017. n41 = te[3],
  10018. n12 = te[4],
  10019. n22 = te[5],
  10020. n32 = te[6],
  10021. n42 = te[7],
  10022. n13 = te[8],
  10023. n23 = te[9],
  10024. n33 = te[10],
  10025. n43 = te[11],
  10026. n14 = te[12],
  10027. n24 = te[13],
  10028. n34 = te[14],
  10029. n44 = te[15],
  10030. t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44,
  10031. t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44,
  10032. t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44,
  10033. t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;
  10034. var det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14;
  10035. if (det === 0) return this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  10036. var detInv = 1 / det;
  10037. te[0] = t11 * detInv;
  10038. te[1] = (n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44) * detInv;
  10039. te[2] = (n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44) * detInv;
  10040. te[3] = (n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43) * detInv;
  10041. te[4] = t12 * detInv;
  10042. te[5] = (n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44) * detInv;
  10043. te[6] = (n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44) * detInv;
  10044. te[7] = (n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43) * detInv;
  10045. te[8] = t13 * detInv;
  10046. te[9] = (n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44) * detInv;
  10047. te[10] = (n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44) * detInv;
  10048. te[11] = (n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43) * detInv;
  10049. te[12] = t14 * detInv;
  10050. te[13] = (n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34) * detInv;
  10051. te[14] = (n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34) * detInv;
  10052. te[15] = (n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33) * detInv;
  10053. return this;
  10054. };
  10055. _proto.scale = function scale(v) {
  10056. var te = this.elements;
  10057. var x = v.x,
  10058. y = v.y,
  10059. z = v.z;
  10060. te[0] *= x;
  10061. te[4] *= y;
  10062. te[8] *= z;
  10063. te[1] *= x;
  10064. te[5] *= y;
  10065. te[9] *= z;
  10066. te[2] *= x;
  10067. te[6] *= y;
  10068. te[10] *= z;
  10069. te[3] *= x;
  10070. te[7] *= y;
  10071. te[11] *= z;
  10072. return this;
  10073. };
  10074. _proto.getMaxScaleOnAxis = function getMaxScaleOnAxis() {
  10075. var te = this.elements;
  10076. var scaleXSq = te[0] * te[0] + te[1] * te[1] + te[2] * te[2];
  10077. var scaleYSq = te[4] * te[4] + te[5] * te[5] + te[6] * te[6];
  10078. var scaleZSq = te[8] * te[8] + te[9] * te[9] + te[10] * te[10];
  10079. return Math.sqrt(Math.max(scaleXSq, scaleYSq, scaleZSq));
  10080. };
  10081. _proto.makeTranslation = function makeTranslation(x, y, z) {
  10082. this.set(1, 0, 0, x, 0, 1, 0, y, 0, 0, 1, z, 0, 0, 0, 1);
  10083. return this;
  10084. };
  10085. _proto.makeRotationX = function makeRotationX(theta) {
  10086. var c = Math.cos(theta),
  10087. s = Math.sin(theta);
  10088. this.set(1, 0, 0, 0, 0, c, -s, 0, 0, s, c, 0, 0, 0, 0, 1);
  10089. return this;
  10090. };
  10091. _proto.makeRotationY = function makeRotationY(theta) {
  10092. var c = Math.cos(theta),
  10093. s = Math.sin(theta);
  10094. this.set(c, 0, s, 0, 0, 1, 0, 0, -s, 0, c, 0, 0, 0, 0, 1);
  10095. return this;
  10096. };
  10097. _proto.makeRotationZ = function makeRotationZ(theta) {
  10098. var c = Math.cos(theta),
  10099. s = Math.sin(theta);
  10100. this.set(c, -s, 0, 0, s, c, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
  10101. return this;
  10102. };
  10103. _proto.makeRotationAxis = function makeRotationAxis(axis, angle) {
  10104. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  10105. var c = Math.cos(angle);
  10106. var s = Math.sin(angle);
  10107. var t = 1 - c;
  10108. var x = axis.x,
  10109. y = axis.y,
  10110. z = axis.z;
  10111. var tx = t * x,
  10112. ty = t * y;
  10113. this.set(tx * x + c, tx * y - s * z, tx * z + s * y, 0, tx * y + s * z, ty * y + c, ty * z - s * x, 0, tx * z - s * y, ty * z + s * x, t * z * z + c, 0, 0, 0, 0, 1);
  10114. return this;
  10115. };
  10116. _proto.makeScale = function makeScale(x, y, z) {
  10117. this.set(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1);
  10118. return this;
  10119. };
  10120. _proto.makeShear = function makeShear(x, y, z) {
  10121. this.set(1, y, z, 0, x, 1, z, 0, x, y, 1, 0, 0, 0, 0, 1);
  10122. return this;
  10123. };
  10124. _proto.compose = function compose(position, quaternion, scale) {
  10125. var te = this.elements;
  10126. var x = quaternion._x,
  10127. y = quaternion._y,
  10128. z = quaternion._z,
  10129. w = quaternion._w;
  10130. var x2 = x + x,
  10131. y2 = y + y,
  10132. z2 = z + z;
  10133. var xx = x * x2,
  10134. xy = x * y2,
  10135. xz = x * z2;
  10136. var yy = y * y2,
  10137. yz = y * z2,
  10138. zz = z * z2;
  10139. var wx = w * x2,
  10140. wy = w * y2,
  10141. wz = w * z2;
  10142. var sx = scale.x,
  10143. sy = scale.y,
  10144. sz = scale.z;
  10145. te[0] = (1 - (yy + zz)) * sx;
  10146. te[1] = (xy + wz) * sx;
  10147. te[2] = (xz - wy) * sx;
  10148. te[3] = 0;
  10149. te[4] = (xy - wz) * sy;
  10150. te[5] = (1 - (xx + zz)) * sy;
  10151. te[6] = (yz + wx) * sy;
  10152. te[7] = 0;
  10153. te[8] = (xz + wy) * sz;
  10154. te[9] = (yz - wx) * sz;
  10155. te[10] = (1 - (xx + yy)) * sz;
  10156. te[11] = 0;
  10157. te[12] = position.x;
  10158. te[13] = position.y;
  10159. te[14] = position.z;
  10160. te[15] = 1;
  10161. return this;
  10162. };
  10163. _proto.decompose = function decompose(position, quaternion, scale) {
  10164. var te = this.elements;
  10165. var sx = _v1$1.set(te[0], te[1], te[2]).length();
  10166. var sy = _v1$1.set(te[4], te[5], te[6]).length();
  10167. var sz = _v1$1.set(te[8], te[9], te[10]).length(); // if determine is negative, we need to invert one scale
  10168. var det = this.determinant();
  10169. if (det < 0) sx = -sx;
  10170. position.x = te[12];
  10171. position.y = te[13];
  10172. position.z = te[14]; // scale the rotation part
  10173. _m1.copy(this);
  10174. var invSX = 1 / sx;
  10175. var invSY = 1 / sy;
  10176. var invSZ = 1 / sz;
  10177. _m1.elements[0] *= invSX;
  10178. _m1.elements[1] *= invSX;
  10179. _m1.elements[2] *= invSX;
  10180. _m1.elements[4] *= invSY;
  10181. _m1.elements[5] *= invSY;
  10182. _m1.elements[6] *= invSY;
  10183. _m1.elements[8] *= invSZ;
  10184. _m1.elements[9] *= invSZ;
  10185. _m1.elements[10] *= invSZ;
  10186. quaternion.setFromRotationMatrix(_m1);
  10187. scale.x = sx;
  10188. scale.y = sy;
  10189. scale.z = sz;
  10190. return this;
  10191. };
  10192. _proto.makePerspective = function makePerspective(left, right, top, bottom, near, far) {
  10193. if (far === undefined) {
  10194. console.warn('THREE.Matrix4: .makePerspective() has been redefined and has a new signature. Please check the docs.');
  10195. }
  10196. var te = this.elements;
  10197. var x = 2 * near / (right - left);
  10198. var y = 2 * near / (top - bottom);
  10199. var a = (right + left) / (right - left);
  10200. var b = (top + bottom) / (top - bottom);
  10201. var c = -(far + near) / (far - near);
  10202. var d = -2 * far * near / (far - near);
  10203. te[0] = x;
  10204. te[4] = 0;
  10205. te[8] = a;
  10206. te[12] = 0;
  10207. te[1] = 0;
  10208. te[5] = y;
  10209. te[9] = b;
  10210. te[13] = 0;
  10211. te[2] = 0;
  10212. te[6] = 0;
  10213. te[10] = c;
  10214. te[14] = d;
  10215. te[3] = 0;
  10216. te[7] = 0;
  10217. te[11] = -1;
  10218. te[15] = 0;
  10219. return this;
  10220. };
  10221. _proto.makeOrthographic = function makeOrthographic(left, right, top, bottom, near, far) {
  10222. var te = this.elements;
  10223. var w = 1.0 / (right - left);
  10224. var h = 1.0 / (top - bottom);
  10225. var p = 1.0 / (far - near);
  10226. var x = (right + left) * w;
  10227. var y = (top + bottom) * h;
  10228. var z = (far + near) * p;
  10229. te[0] = 2 * w;
  10230. te[4] = 0;
  10231. te[8] = 0;
  10232. te[12] = -x;
  10233. te[1] = 0;
  10234. te[5] = 2 * h;
  10235. te[9] = 0;
  10236. te[13] = -y;
  10237. te[2] = 0;
  10238. te[6] = 0;
  10239. te[10] = -2 * p;
  10240. te[14] = -z;
  10241. te[3] = 0;
  10242. te[7] = 0;
  10243. te[11] = 0;
  10244. te[15] = 1;
  10245. return this;
  10246. };
  10247. _proto.equals = function equals(matrix) {
  10248. var te = this.elements;
  10249. var me = matrix.elements;
  10250. for (var i = 0; i < 16; i++) {
  10251. if (te[i] !== me[i]) return false;
  10252. }
  10253. return true;
  10254. };
  10255. _proto.fromArray = function fromArray(array, offset) {
  10256. if (offset === void 0) {
  10257. offset = 0;
  10258. }
  10259. for (var i = 0; i < 16; i++) {
  10260. this.elements[i] = array[i + offset];
  10261. }
  10262. return this;
  10263. };
  10264. _proto.toArray = function toArray(array, offset) {
  10265. if (array === void 0) {
  10266. array = [];
  10267. }
  10268. if (offset === void 0) {
  10269. offset = 0;
  10270. }
  10271. var te = this.elements;
  10272. array[offset] = te[0];
  10273. array[offset + 1] = te[1];
  10274. array[offset + 2] = te[2];
  10275. array[offset + 3] = te[3];
  10276. array[offset + 4] = te[4];
  10277. array[offset + 5] = te[5];
  10278. array[offset + 6] = te[6];
  10279. array[offset + 7] = te[7];
  10280. array[offset + 8] = te[8];
  10281. array[offset + 9] = te[9];
  10282. array[offset + 10] = te[10];
  10283. array[offset + 11] = te[11];
  10284. array[offset + 12] = te[12];
  10285. array[offset + 13] = te[13];
  10286. array[offset + 14] = te[14];
  10287. array[offset + 15] = te[15];
  10288. return array;
  10289. };
  10290. return Matrix4;
  10291. }();
  10292. var _v1$1 = /*@__PURE__*/new Vector3();
  10293. var _m1 = /*@__PURE__*/new Matrix4();
  10294. var _zero = /*@__PURE__*/new Vector3(0, 0, 0);
  10295. var _one = /*@__PURE__*/new Vector3(1, 1, 1);
  10296. var _x = /*@__PURE__*/new Vector3();
  10297. var _y = /*@__PURE__*/new Vector3();
  10298. var _z = /*@__PURE__*/new Vector3();
  10299. var Euler = /*#__PURE__*/function () {
  10300. function Euler(x, y, z, order) {
  10301. if (x === void 0) {
  10302. x = 0;
  10303. }
  10304. if (y === void 0) {
  10305. y = 0;
  10306. }
  10307. if (z === void 0) {
  10308. z = 0;
  10309. }
  10310. if (order === void 0) {
  10311. order = Euler.DefaultOrder;
  10312. }
  10313. Object.defineProperty(this, 'isEuler', {
  10314. value: true
  10315. });
  10316. this._x = x;
  10317. this._y = y;
  10318. this._z = z;
  10319. this._order = order;
  10320. }
  10321. var _proto = Euler.prototype;
  10322. _proto.set = function set(x, y, z, order) {
  10323. this._x = x;
  10324. this._y = y;
  10325. this._z = z;
  10326. this._order = order || this._order;
  10327. this._onChangeCallback();
  10328. return this;
  10329. };
  10330. _proto.clone = function clone() {
  10331. return new this.constructor(this._x, this._y, this._z, this._order);
  10332. };
  10333. _proto.copy = function copy(euler) {
  10334. this._x = euler._x;
  10335. this._y = euler._y;
  10336. this._z = euler._z;
  10337. this._order = euler._order;
  10338. this._onChangeCallback();
  10339. return this;
  10340. };
  10341. _proto.setFromRotationMatrix = function setFromRotationMatrix(m, order, update) {
  10342. var clamp = MathUtils.clamp; // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  10343. var te = m.elements;
  10344. var m11 = te[0],
  10345. m12 = te[4],
  10346. m13 = te[8];
  10347. var m21 = te[1],
  10348. m22 = te[5],
  10349. m23 = te[9];
  10350. var m31 = te[2],
  10351. m32 = te[6],
  10352. m33 = te[10];
  10353. order = order || this._order;
  10354. switch (order) {
  10355. case 'XYZ':
  10356. this._y = Math.asin(clamp(m13, -1, 1));
  10357. if (Math.abs(m13) < 0.9999999) {
  10358. this._x = Math.atan2(-m23, m33);
  10359. this._z = Math.atan2(-m12, m11);
  10360. } else {
  10361. this._x = Math.atan2(m32, m22);
  10362. this._z = 0;
  10363. }
  10364. break;
  10365. case 'YXZ':
  10366. this._x = Math.asin(-clamp(m23, -1, 1));
  10367. if (Math.abs(m23) < 0.9999999) {
  10368. this._y = Math.atan2(m13, m33);
  10369. this._z = Math.atan2(m21, m22);
  10370. } else {
  10371. this._y = Math.atan2(-m31, m11);
  10372. this._z = 0;
  10373. }
  10374. break;
  10375. case 'ZXY':
  10376. this._x = Math.asin(clamp(m32, -1, 1));
  10377. if (Math.abs(m32) < 0.9999999) {
  10378. this._y = Math.atan2(-m31, m33);
  10379. this._z = Math.atan2(-m12, m22);
  10380. } else {
  10381. this._y = 0;
  10382. this._z = Math.atan2(m21, m11);
  10383. }
  10384. break;
  10385. case 'ZYX':
  10386. this._y = Math.asin(-clamp(m31, -1, 1));
  10387. if (Math.abs(m31) < 0.9999999) {
  10388. this._x = Math.atan2(m32, m33);
  10389. this._z = Math.atan2(m21, m11);
  10390. } else {
  10391. this._x = 0;
  10392. this._z = Math.atan2(-m12, m22);
  10393. }
  10394. break;
  10395. case 'YZX':
  10396. this._z = Math.asin(clamp(m21, -1, 1));
  10397. if (Math.abs(m21) < 0.9999999) {
  10398. this._x = Math.atan2(-m23, m22);
  10399. this._y = Math.atan2(-m31, m11);
  10400. } else {
  10401. this._x = 0;
  10402. this._y = Math.atan2(m13, m33);
  10403. }
  10404. break;
  10405. case 'XZY':
  10406. this._z = Math.asin(-clamp(m12, -1, 1));
  10407. if (Math.abs(m12) < 0.9999999) {
  10408. this._x = Math.atan2(m32, m22);
  10409. this._y = Math.atan2(m13, m11);
  10410. } else {
  10411. this._x = Math.atan2(-m23, m33);
  10412. this._y = 0;
  10413. }
  10414. break;
  10415. default:
  10416. console.warn('THREE.Euler: .setFromRotationMatrix() encountered an unknown order: ' + order);
  10417. }
  10418. this._order = order;
  10419. if (update !== false) this._onChangeCallback();
  10420. return this;
  10421. };
  10422. _proto.setFromQuaternion = function setFromQuaternion(q, order, update) {
  10423. _matrix.makeRotationFromQuaternion(q);
  10424. return this.setFromRotationMatrix(_matrix, order, update);
  10425. };
  10426. _proto.setFromVector3 = function setFromVector3(v, order) {
  10427. return this.set(v.x, v.y, v.z, order || this._order);
  10428. };
  10429. _proto.reorder = function reorder(newOrder) {
  10430. // WARNING: this discards revolution information -bhouston
  10431. _quaternion$1.setFromEuler(this);
  10432. return this.setFromQuaternion(_quaternion$1, newOrder);
  10433. };
  10434. _proto.equals = function equals(euler) {
  10435. return euler._x === this._x && euler._y === this._y && euler._z === this._z && euler._order === this._order;
  10436. };
  10437. _proto.fromArray = function fromArray(array) {
  10438. this._x = array[0];
  10439. this._y = array[1];
  10440. this._z = array[2];
  10441. if (array[3] !== undefined) this._order = array[3];
  10442. this._onChangeCallback();
  10443. return this;
  10444. };
  10445. _proto.toArray = function toArray(array, offset) {
  10446. if (array === void 0) {
  10447. array = [];
  10448. }
  10449. if (offset === void 0) {
  10450. offset = 0;
  10451. }
  10452. array[offset] = this._x;
  10453. array[offset + 1] = this._y;
  10454. array[offset + 2] = this._z;
  10455. array[offset + 3] = this._order;
  10456. return array;
  10457. };
  10458. _proto.toVector3 = function toVector3(optionalResult) {
  10459. if (optionalResult) {
  10460. return optionalResult.set(this._x, this._y, this._z);
  10461. } else {
  10462. return new Vector3(this._x, this._y, this._z);
  10463. }
  10464. };
  10465. _proto._onChange = function _onChange(callback) {
  10466. this._onChangeCallback = callback;
  10467. return this;
  10468. };
  10469. _proto._onChangeCallback = function _onChangeCallback() {};
  10470. _createClass(Euler, [{
  10471. key: "x",
  10472. get: function get() {
  10473. return this._x;
  10474. },
  10475. set: function set(value) {
  10476. this._x = value;
  10477. this._onChangeCallback();
  10478. }
  10479. }, {
  10480. key: "y",
  10481. get: function get() {
  10482. return this._y;
  10483. },
  10484. set: function set(value) {
  10485. this._y = value;
  10486. this._onChangeCallback();
  10487. }
  10488. }, {
  10489. key: "z",
  10490. get: function get() {
  10491. return this._z;
  10492. },
  10493. set: function set(value) {
  10494. this._z = value;
  10495. this._onChangeCallback();
  10496. }
  10497. }, {
  10498. key: "order",
  10499. get: function get() {
  10500. return this._order;
  10501. },
  10502. set: function set(value) {
  10503. this._order = value;
  10504. this._onChangeCallback();
  10505. }
  10506. }]);
  10507. return Euler;
  10508. }();
  10509. Euler.DefaultOrder = 'XYZ';
  10510. Euler.RotationOrders = ['XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX'];
  10511. var _matrix = /*@__PURE__*/new Matrix4();
  10512. var _quaternion$1 = /*@__PURE__*/new Quaternion();
  10513. var Layers = /*#__PURE__*/function () {
  10514. function Layers() {
  10515. this.mask = 1 | 0;
  10516. }
  10517. var _proto = Layers.prototype;
  10518. _proto.set = function set(channel) {
  10519. this.mask = 1 << channel | 0;
  10520. };
  10521. _proto.enable = function enable(channel) {
  10522. this.mask |= 1 << channel | 0;
  10523. };
  10524. _proto.enableAll = function enableAll() {
  10525. this.mask = 0xffffffff | 0;
  10526. };
  10527. _proto.toggle = function toggle(channel) {
  10528. this.mask ^= 1 << channel | 0;
  10529. };
  10530. _proto.disable = function disable(channel) {
  10531. this.mask &= ~(1 << channel | 0);
  10532. };
  10533. _proto.disableAll = function disableAll() {
  10534. this.mask = 0;
  10535. };
  10536. _proto.test = function test(layers) {
  10537. return (this.mask & layers.mask) !== 0;
  10538. };
  10539. return Layers;
  10540. }();
  10541. var _object3DId = 0;
  10542. var _v1$2 = new Vector3();
  10543. var _q1 = new Quaternion();
  10544. var _m1$1 = new Matrix4();
  10545. var _target = new Vector3();
  10546. var _position = new Vector3();
  10547. var _scale = new Vector3();
  10548. var _quaternion$2 = new Quaternion();
  10549. var _xAxis = new Vector3(1, 0, 0);
  10550. var _yAxis = new Vector3(0, 1, 0);
  10551. var _zAxis = new Vector3(0, 0, 1);
  10552. var _addedEvent = {
  10553. type: 'added'
  10554. };
  10555. var _removedEvent = {
  10556. type: 'removed'
  10557. };
  10558. function Object3D() {
  10559. Object.defineProperty(this, 'id', {
  10560. value: _object3DId++
  10561. });
  10562. this.uuid = MathUtils.generateUUID();
  10563. this.name = '';
  10564. this.type = 'Object3D';
  10565. this.parent = null;
  10566. this.children = [];
  10567. this.up = Object3D.DefaultUp.clone();
  10568. var position = new Vector3();
  10569. var rotation = new Euler();
  10570. var quaternion = new Quaternion();
  10571. var scale = new Vector3(1, 1, 1);
  10572. function onRotationChange() {
  10573. quaternion.setFromEuler(rotation, false);
  10574. }
  10575. function onQuaternionChange() {
  10576. rotation.setFromQuaternion(quaternion, undefined, false);
  10577. }
  10578. rotation._onChange(onRotationChange);
  10579. quaternion._onChange(onQuaternionChange);
  10580. Object.defineProperties(this, {
  10581. position: {
  10582. configurable: true,
  10583. enumerable: true,
  10584. value: position
  10585. },
  10586. rotation: {
  10587. configurable: true,
  10588. enumerable: true,
  10589. value: rotation
  10590. },
  10591. quaternion: {
  10592. configurable: true,
  10593. enumerable: true,
  10594. value: quaternion
  10595. },
  10596. scale: {
  10597. configurable: true,
  10598. enumerable: true,
  10599. value: scale
  10600. },
  10601. modelViewMatrix: {
  10602. value: new Matrix4()
  10603. },
  10604. normalMatrix: {
  10605. value: new Matrix3()
  10606. }
  10607. });
  10608. this.matrix = new Matrix4();
  10609. this.matrixWorld = new Matrix4();
  10610. this.matrixAutoUpdate = Object3D.DefaultMatrixAutoUpdate;
  10611. this.matrixWorldNeedsUpdate = false;
  10612. this.layers = new Layers();
  10613. this.visible = true;
  10614. this.castShadow = false;
  10615. this.receiveShadow = false;
  10616. this.frustumCulled = true;
  10617. this.renderOrder = 0;
  10618. this.animations = [];
  10619. this.userData = {};
  10620. }
  10621. Object3D.DefaultUp = new Vector3(0, 1, 0);
  10622. Object3D.DefaultMatrixAutoUpdate = true;
  10623. Object3D.prototype = Object.assign(Object.create(EventDispatcher.prototype), {
  10624. constructor: Object3D,
  10625. isObject3D: true,
  10626. onBeforeRender: function onBeforeRender() {},
  10627. onAfterRender: function onAfterRender() {},
  10628. applyMatrix4: function applyMatrix4(matrix) {
  10629. if (this.matrixAutoUpdate) this.updateMatrix();
  10630. this.matrix.premultiply(matrix);
  10631. this.matrix.decompose(this.position, this.quaternion, this.scale);
  10632. },
  10633. applyQuaternion: function applyQuaternion(q) {
  10634. this.quaternion.premultiply(q);
  10635. return this;
  10636. },
  10637. setRotationFromAxisAngle: function setRotationFromAxisAngle(axis, angle) {
  10638. // assumes axis is normalized
  10639. this.quaternion.setFromAxisAngle(axis, angle);
  10640. },
  10641. setRotationFromEuler: function setRotationFromEuler(euler) {
  10642. this.quaternion.setFromEuler(euler, true);
  10643. },
  10644. setRotationFromMatrix: function setRotationFromMatrix(m) {
  10645. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  10646. this.quaternion.setFromRotationMatrix(m);
  10647. },
  10648. setRotationFromQuaternion: function setRotationFromQuaternion(q) {
  10649. // assumes q is normalized
  10650. this.quaternion.copy(q);
  10651. },
  10652. rotateOnAxis: function rotateOnAxis(axis, angle) {
  10653. // rotate object on axis in object space
  10654. // axis is assumed to be normalized
  10655. _q1.setFromAxisAngle(axis, angle);
  10656. this.quaternion.multiply(_q1);
  10657. return this;
  10658. },
  10659. rotateOnWorldAxis: function rotateOnWorldAxis(axis, angle) {
  10660. // rotate object on axis in world space
  10661. // axis is assumed to be normalized
  10662. // method assumes no rotated parent
  10663. _q1.setFromAxisAngle(axis, angle);
  10664. this.quaternion.premultiply(_q1);
  10665. return this;
  10666. },
  10667. rotateX: function rotateX(angle) {
  10668. return this.rotateOnAxis(_xAxis, angle);
  10669. },
  10670. rotateY: function rotateY(angle) {
  10671. return this.rotateOnAxis(_yAxis, angle);
  10672. },
  10673. rotateZ: function rotateZ(angle) {
  10674. return this.rotateOnAxis(_zAxis, angle);
  10675. },
  10676. translateOnAxis: function translateOnAxis(axis, distance) {
  10677. // translate object by distance along axis in object space
  10678. // axis is assumed to be normalized
  10679. _v1$2.copy(axis).applyQuaternion(this.quaternion);
  10680. this.position.add(_v1$2.multiplyScalar(distance));
  10681. return this;
  10682. },
  10683. translateX: function translateX(distance) {
  10684. return this.translateOnAxis(_xAxis, distance);
  10685. },
  10686. translateY: function translateY(distance) {
  10687. return this.translateOnAxis(_yAxis, distance);
  10688. },
  10689. translateZ: function translateZ(distance) {
  10690. return this.translateOnAxis(_zAxis, distance);
  10691. },
  10692. localToWorld: function localToWorld(vector) {
  10693. return vector.applyMatrix4(this.matrixWorld);
  10694. },
  10695. worldToLocal: function worldToLocal(vector) {
  10696. return vector.applyMatrix4(_m1$1.copy(this.matrixWorld).invert());
  10697. },
  10698. lookAt: function lookAt(x, y, z) {
  10699. // This method does not support objects having non-uniformly-scaled parent(s)
  10700. if (x.isVector3) {
  10701. _target.copy(x);
  10702. } else {
  10703. _target.set(x, y, z);
  10704. }
  10705. var parent = this.parent;
  10706. this.updateWorldMatrix(true, false);
  10707. _position.setFromMatrixPosition(this.matrixWorld);
  10708. if (this.isCamera || this.isLight) {
  10709. _m1$1.lookAt(_position, _target, this.up);
  10710. } else {
  10711. _m1$1.lookAt(_target, _position, this.up);
  10712. }
  10713. this.quaternion.setFromRotationMatrix(_m1$1);
  10714. if (parent) {
  10715. _m1$1.extractRotation(parent.matrixWorld);
  10716. _q1.setFromRotationMatrix(_m1$1);
  10717. this.quaternion.premultiply(_q1.invert());
  10718. }
  10719. },
  10720. add: function add(object) {
  10721. if (arguments.length > 1) {
  10722. for (var i = 0; i < arguments.length; i++) {
  10723. this.add(arguments[i]);
  10724. }
  10725. return this;
  10726. }
  10727. if (object === this) {
  10728. console.error('THREE.Object3D.add: object can\'t be added as a child of itself.', object);
  10729. return this;
  10730. }
  10731. if (object && object.isObject3D) {
  10732. if (object.parent !== null) {
  10733. object.parent.remove(object);
  10734. }
  10735. object.parent = this;
  10736. this.children.push(object);
  10737. object.dispatchEvent(_addedEvent);
  10738. } else {
  10739. console.error('THREE.Object3D.add: object not an instance of THREE.Object3D.', object);
  10740. }
  10741. return this;
  10742. },
  10743. remove: function remove(object) {
  10744. if (arguments.length > 1) {
  10745. for (var i = 0; i < arguments.length; i++) {
  10746. this.remove(arguments[i]);
  10747. }
  10748. return this;
  10749. }
  10750. var index = this.children.indexOf(object);
  10751. if (index !== -1) {
  10752. object.parent = null;
  10753. this.children.splice(index, 1);
  10754. object.dispatchEvent(_removedEvent);
  10755. }
  10756. return this;
  10757. },
  10758. clear: function clear() {
  10759. for (var i = 0; i < this.children.length; i++) {
  10760. var object = this.children[i];
  10761. object.parent = null;
  10762. object.dispatchEvent(_removedEvent);
  10763. }
  10764. this.children.length = 0;
  10765. return this;
  10766. },
  10767. attach: function attach(object) {
  10768. // adds object as a child of this, while maintaining the object's world transform
  10769. this.updateWorldMatrix(true, false);
  10770. _m1$1.copy(this.matrixWorld).invert();
  10771. if (object.parent !== null) {
  10772. object.parent.updateWorldMatrix(true, false);
  10773. _m1$1.multiply(object.parent.matrixWorld);
  10774. }
  10775. object.applyMatrix4(_m1$1);
  10776. object.updateWorldMatrix(false, false);
  10777. this.add(object);
  10778. return this;
  10779. },
  10780. getObjectById: function getObjectById(id) {
  10781. return this.getObjectByProperty('id', id);
  10782. },
  10783. getObjectByName: function getObjectByName(name) {
  10784. return this.getObjectByProperty('name', name);
  10785. },
  10786. getObjectByProperty: function getObjectByProperty(name, value) {
  10787. if (this[name] === value) return this;
  10788. for (var i = 0, l = this.children.length; i < l; i++) {
  10789. var child = this.children[i];
  10790. var object = child.getObjectByProperty(name, value);
  10791. if (object !== undefined) {
  10792. return object;
  10793. }
  10794. }
  10795. return undefined;
  10796. },
  10797. getWorldPosition: function getWorldPosition(target) {
  10798. if (target === undefined) {
  10799. console.warn('THREE.Object3D: .getWorldPosition() target is now required');
  10800. target = new Vector3();
  10801. }
  10802. this.updateWorldMatrix(true, false);
  10803. return target.setFromMatrixPosition(this.matrixWorld);
  10804. },
  10805. getWorldQuaternion: function getWorldQuaternion(target) {
  10806. if (target === undefined) {
  10807. console.warn('THREE.Object3D: .getWorldQuaternion() target is now required');
  10808. target = new Quaternion();
  10809. }
  10810. this.updateWorldMatrix(true, false);
  10811. this.matrixWorld.decompose(_position, target, _scale);
  10812. return target;
  10813. },
  10814. getWorldScale: function getWorldScale(target) {
  10815. if (target === undefined) {
  10816. console.warn('THREE.Object3D: .getWorldScale() target is now required');
  10817. target = new Vector3();
  10818. }
  10819. this.updateWorldMatrix(true, false);
  10820. this.matrixWorld.decompose(_position, _quaternion$2, target);
  10821. return target;
  10822. },
  10823. getWorldDirection: function getWorldDirection(target) {
  10824. if (target === undefined) {
  10825. console.warn('THREE.Object3D: .getWorldDirection() target is now required');
  10826. target = new Vector3();
  10827. }
  10828. this.updateWorldMatrix(true, false);
  10829. var e = this.matrixWorld.elements;
  10830. return target.set(e[8], e[9], e[10]).normalize();
  10831. },
  10832. raycast: function raycast() {},
  10833. traverse: function traverse(callback) {
  10834. callback(this);
  10835. var children = this.children;
  10836. for (var i = 0, l = children.length; i < l; i++) {
  10837. children[i].traverse(callback);
  10838. }
  10839. },
  10840. traverseVisible: function traverseVisible(callback) {
  10841. if (this.visible === false) return;
  10842. callback(this);
  10843. var children = this.children;
  10844. for (var i = 0, l = children.length; i < l; i++) {
  10845. children[i].traverseVisible(callback);
  10846. }
  10847. },
  10848. traverseAncestors: function traverseAncestors(callback) {
  10849. var parent = this.parent;
  10850. if (parent !== null) {
  10851. callback(parent);
  10852. parent.traverseAncestors(callback);
  10853. }
  10854. },
  10855. updateMatrix: function updateMatrix() {
  10856. this.matrix.compose(this.position, this.quaternion, this.scale);
  10857. this.matrixWorldNeedsUpdate = true;
  10858. },
  10859. updateMatrixWorld: function updateMatrixWorld(force) {
  10860. if (this.matrixAutoUpdate) this.updateMatrix();
  10861. if (this.matrixWorldNeedsUpdate || force) {
  10862. if (this.parent === null) {
  10863. this.matrixWorld.copy(this.matrix);
  10864. } else {
  10865. this.matrixWorld.multiplyMatrices(this.parent.matrixWorld, this.matrix);
  10866. }
  10867. this.matrixWorldNeedsUpdate = false;
  10868. force = true;
  10869. } // update children
  10870. var children = this.children;
  10871. for (var i = 0, l = children.length; i < l; i++) {
  10872. children[i].updateMatrixWorld(force);
  10873. }
  10874. },
  10875. updateWorldMatrix: function updateWorldMatrix(updateParents, updateChildren) {
  10876. var parent = this.parent;
  10877. if (updateParents === true && parent !== null) {
  10878. parent.updateWorldMatrix(true, false);
  10879. }
  10880. if (this.matrixAutoUpdate) this.updateMatrix();
  10881. if (this.parent === null) {
  10882. this.matrixWorld.copy(this.matrix);
  10883. } else {
  10884. this.matrixWorld.multiplyMatrices(this.parent.matrixWorld, this.matrix);
  10885. } // update children
  10886. if (updateChildren === true) {
  10887. var children = this.children;
  10888. for (var i = 0, l = children.length; i < l; i++) {
  10889. children[i].updateWorldMatrix(false, true);
  10890. }
  10891. }
  10892. },
  10893. toJSON: function toJSON(meta) {
  10894. // meta is a string when called from JSON.stringify
  10895. var isRootObject = meta === undefined || typeof meta === 'string';
  10896. var output = {}; // meta is a hash used to collect geometries, materials.
  10897. // not providing it implies that this is the root object
  10898. // being serialized.
  10899. if (isRootObject) {
  10900. // initialize meta obj
  10901. meta = {
  10902. geometries: {},
  10903. materials: {},
  10904. textures: {},
  10905. images: {},
  10906. shapes: {},
  10907. skeletons: {},
  10908. animations: {}
  10909. };
  10910. output.metadata = {
  10911. version: 4.5,
  10912. type: 'Object',
  10913. generator: 'Object3D.toJSON'
  10914. };
  10915. } // standard Object3D serialization
  10916. var object = {};
  10917. object.uuid = this.uuid;
  10918. object.type = this.type;
  10919. if (this.name !== '') object.name = this.name;
  10920. if (this.castShadow === true) object.castShadow = true;
  10921. if (this.receiveShadow === true) object.receiveShadow = true;
  10922. if (this.visible === false) object.visible = false;
  10923. if (this.frustumCulled === false) object.frustumCulled = false;
  10924. if (this.renderOrder !== 0) object.renderOrder = this.renderOrder;
  10925. if (JSON.stringify(this.userData) !== '{}') object.userData = this.userData;
  10926. object.layers = this.layers.mask;
  10927. object.matrix = this.matrix.toArray();
  10928. if (this.matrixAutoUpdate === false) object.matrixAutoUpdate = false; // object specific properties
  10929. if (this.isInstancedMesh) {
  10930. object.type = 'InstancedMesh';
  10931. object.count = this.count;
  10932. object.instanceMatrix = this.instanceMatrix.toJSON();
  10933. } //
  10934. function serialize(library, element) {
  10935. if (library[element.uuid] === undefined) {
  10936. library[element.uuid] = element.toJSON(meta);
  10937. }
  10938. return element.uuid;
  10939. }
  10940. if (this.isMesh || this.isLine || this.isPoints) {
  10941. object.geometry = serialize(meta.geometries, this.geometry);
  10942. var parameters = this.geometry.parameters;
  10943. if (parameters !== undefined && parameters.shapes !== undefined) {
  10944. var shapes = parameters.shapes;
  10945. if (Array.isArray(shapes)) {
  10946. for (var i = 0, l = shapes.length; i < l; i++) {
  10947. var shape = shapes[i];
  10948. serialize(meta.shapes, shape);
  10949. }
  10950. } else {
  10951. serialize(meta.shapes, shapes);
  10952. }
  10953. }
  10954. }
  10955. if (this.isSkinnedMesh) {
  10956. object.bindMode = this.bindMode;
  10957. object.bindMatrix = this.bindMatrix.toArray();
  10958. if (this.skeleton !== undefined) {
  10959. serialize(meta.skeletons, this.skeleton);
  10960. object.skeleton = this.skeleton.uuid;
  10961. }
  10962. }
  10963. if (this.material !== undefined) {
  10964. if (Array.isArray(this.material)) {
  10965. var uuids = [];
  10966. for (var _i = 0, _l = this.material.length; _i < _l; _i++) {
  10967. uuids.push(serialize(meta.materials, this.material[_i]));
  10968. }
  10969. object.material = uuids;
  10970. } else {
  10971. object.material = serialize(meta.materials, this.material);
  10972. }
  10973. } //
  10974. if (this.children.length > 0) {
  10975. object.children = [];
  10976. for (var _i2 = 0; _i2 < this.children.length; _i2++) {
  10977. object.children.push(this.children[_i2].toJSON(meta).object);
  10978. }
  10979. } //
  10980. if (this.animations.length > 0) {
  10981. object.animations = [];
  10982. for (var _i3 = 0; _i3 < this.animations.length; _i3++) {
  10983. var animation = this.animations[_i3];
  10984. object.animations.push(serialize(meta.animations, animation));
  10985. }
  10986. }
  10987. if (isRootObject) {
  10988. var geometries = extractFromCache(meta.geometries);
  10989. var materials = extractFromCache(meta.materials);
  10990. var textures = extractFromCache(meta.textures);
  10991. var images = extractFromCache(meta.images);
  10992. var _shapes = extractFromCache(meta.shapes);
  10993. var skeletons = extractFromCache(meta.skeletons);
  10994. var animations = extractFromCache(meta.animations);
  10995. if (geometries.length > 0) output.geometries = geometries;
  10996. if (materials.length > 0) output.materials = materials;
  10997. if (textures.length > 0) output.textures = textures;
  10998. if (images.length > 0) output.images = images;
  10999. if (_shapes.length > 0) output.shapes = _shapes;
  11000. if (skeletons.length > 0) output.skeletons = skeletons;
  11001. if (animations.length > 0) output.animations = animations;
  11002. }
  11003. output.object = object;
  11004. return output; // extract data from the cache hash
  11005. // remove metadata on each item
  11006. // and return as array
  11007. function extractFromCache(cache) {
  11008. var values = [];
  11009. for (var key in cache) {
  11010. var data = cache[key];
  11011. delete data.metadata;
  11012. values.push(data);
  11013. }
  11014. return values;
  11015. }
  11016. },
  11017. clone: function clone(recursive) {
  11018. return new this.constructor().copy(this, recursive);
  11019. },
  11020. copy: function copy(source, recursive) {
  11021. if (recursive === void 0) {
  11022. recursive = true;
  11023. }
  11024. this.name = source.name;
  11025. this.up.copy(source.up);
  11026. this.position.copy(source.position);
  11027. this.rotation.order = source.rotation.order;
  11028. this.quaternion.copy(source.quaternion);
  11029. this.scale.copy(source.scale);
  11030. this.matrix.copy(source.matrix);
  11031. this.matrixWorld.copy(source.matrixWorld);
  11032. this.matrixAutoUpdate = source.matrixAutoUpdate;
  11033. this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  11034. this.layers.mask = source.layers.mask;
  11035. this.visible = source.visible;
  11036. this.castShadow = source.castShadow;
  11037. this.receiveShadow = source.receiveShadow;
  11038. this.frustumCulled = source.frustumCulled;
  11039. this.renderOrder = source.renderOrder;
  11040. this.userData = JSON.parse(JSON.stringify(source.userData));
  11041. if (recursive === true) {
  11042. for (var i = 0; i < source.children.length; i++) {
  11043. var child = source.children[i];
  11044. this.add(child.clone());
  11045. }
  11046. }
  11047. return this;
  11048. }
  11049. });
  11050. var _vector1 = /*@__PURE__*/new Vector3();
  11051. var _vector2 = /*@__PURE__*/new Vector3();
  11052. var _normalMatrix = /*@__PURE__*/new Matrix3();
  11053. var Plane = /*#__PURE__*/function () {
  11054. function Plane(normal, constant) {
  11055. Object.defineProperty(this, 'isPlane', {
  11056. value: true
  11057. }); // normal is assumed to be normalized
  11058. this.normal = normal !== undefined ? normal : new Vector3(1, 0, 0);
  11059. this.constant = constant !== undefined ? constant : 0;
  11060. }
  11061. var _proto = Plane.prototype;
  11062. _proto.set = function set(normal, constant) {
  11063. this.normal.copy(normal);
  11064. this.constant = constant;
  11065. return this;
  11066. };
  11067. _proto.setComponents = function setComponents(x, y, z, w) {
  11068. this.normal.set(x, y, z);
  11069. this.constant = w;
  11070. return this;
  11071. };
  11072. _proto.setFromNormalAndCoplanarPoint = function setFromNormalAndCoplanarPoint(normal, point) {
  11073. this.normal.copy(normal);
  11074. this.constant = -point.dot(this.normal);
  11075. return this;
  11076. };
  11077. _proto.setFromCoplanarPoints = function setFromCoplanarPoints(a, b, c) {
  11078. var normal = _vector1.subVectors(c, b).cross(_vector2.subVectors(a, b)).normalize(); // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  11079. this.setFromNormalAndCoplanarPoint(normal, a);
  11080. return this;
  11081. };
  11082. _proto.clone = function clone() {
  11083. return new this.constructor().copy(this);
  11084. };
  11085. _proto.copy = function copy(plane) {
  11086. this.normal.copy(plane.normal);
  11087. this.constant = plane.constant;
  11088. return this;
  11089. };
  11090. _proto.normalize = function normalize() {
  11091. // Note: will lead to a divide by zero if the plane is invalid.
  11092. var inverseNormalLength = 1.0 / this.normal.length();
  11093. this.normal.multiplyScalar(inverseNormalLength);
  11094. this.constant *= inverseNormalLength;
  11095. return this;
  11096. };
  11097. _proto.negate = function negate() {
  11098. this.constant *= -1;
  11099. this.normal.negate();
  11100. return this;
  11101. };
  11102. _proto.distanceToPoint = function distanceToPoint(point) {
  11103. return this.normal.dot(point) + this.constant;
  11104. };
  11105. _proto.distanceToSphere = function distanceToSphere(sphere) {
  11106. return this.distanceToPoint(sphere.center) - sphere.radius;
  11107. };
  11108. _proto.projectPoint = function projectPoint(point, target) {
  11109. if (target === undefined) {
  11110. console.warn('THREE.Plane: .projectPoint() target is now required');
  11111. target = new Vector3();
  11112. }
  11113. return target.copy(this.normal).multiplyScalar(-this.distanceToPoint(point)).add(point);
  11114. };
  11115. _proto.intersectLine = function intersectLine(line, target) {
  11116. if (target === undefined) {
  11117. console.warn('THREE.Plane: .intersectLine() target is now required');
  11118. target = new Vector3();
  11119. }
  11120. var direction = line.delta(_vector1);
  11121. var denominator = this.normal.dot(direction);
  11122. if (denominator === 0) {
  11123. // line is coplanar, return origin
  11124. if (this.distanceToPoint(line.start) === 0) {
  11125. return target.copy(line.start);
  11126. } // Unsure if this is the correct method to handle this case.
  11127. return undefined;
  11128. }
  11129. var t = -(line.start.dot(this.normal) + this.constant) / denominator;
  11130. if (t < 0 || t > 1) {
  11131. return undefined;
  11132. }
  11133. return target.copy(direction).multiplyScalar(t).add(line.start);
  11134. };
  11135. _proto.intersectsLine = function intersectsLine(line) {
  11136. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  11137. var startSign = this.distanceToPoint(line.start);
  11138. var endSign = this.distanceToPoint(line.end);
  11139. return startSign < 0 && endSign > 0 || endSign < 0 && startSign > 0;
  11140. };
  11141. _proto.intersectsBox = function intersectsBox(box) {
  11142. return box.intersectsPlane(this);
  11143. };
  11144. _proto.intersectsSphere = function intersectsSphere(sphere) {
  11145. return sphere.intersectsPlane(this);
  11146. };
  11147. _proto.coplanarPoint = function coplanarPoint(target) {
  11148. if (target === undefined) {
  11149. console.warn('THREE.Plane: .coplanarPoint() target is now required');
  11150. target = new Vector3();
  11151. }
  11152. return target.copy(this.normal).multiplyScalar(-this.constant);
  11153. };
  11154. _proto.applyMatrix4 = function applyMatrix4(matrix, optionalNormalMatrix) {
  11155. var normalMatrix = optionalNormalMatrix || _normalMatrix.getNormalMatrix(matrix);
  11156. var referencePoint = this.coplanarPoint(_vector1).applyMatrix4(matrix);
  11157. var normal = this.normal.applyMatrix3(normalMatrix).normalize();
  11158. this.constant = -referencePoint.dot(normal);
  11159. return this;
  11160. };
  11161. _proto.translate = function translate(offset) {
  11162. this.constant -= offset.dot(this.normal);
  11163. return this;
  11164. };
  11165. _proto.equals = function equals(plane) {
  11166. return plane.normal.equals(this.normal) && plane.constant === this.constant;
  11167. };
  11168. return Plane;
  11169. }();
  11170. var _v0$1 = /*@__PURE__*/new Vector3();
  11171. var _v1$3 = /*@__PURE__*/new Vector3();
  11172. var _v2$1 = /*@__PURE__*/new Vector3();
  11173. var _v3 = /*@__PURE__*/new Vector3();
  11174. var _vab = /*@__PURE__*/new Vector3();
  11175. var _vac = /*@__PURE__*/new Vector3();
  11176. var _vbc = /*@__PURE__*/new Vector3();
  11177. var _vap = /*@__PURE__*/new Vector3();
  11178. var _vbp = /*@__PURE__*/new Vector3();
  11179. var _vcp = /*@__PURE__*/new Vector3();
  11180. var Triangle = /*#__PURE__*/function () {
  11181. function Triangle(a, b, c) {
  11182. this.a = a !== undefined ? a : new Vector3();
  11183. this.b = b !== undefined ? b : new Vector3();
  11184. this.c = c !== undefined ? c : new Vector3();
  11185. }
  11186. Triangle.getNormal = function getNormal(a, b, c, target) {
  11187. if (target === undefined) {
  11188. console.warn('THREE.Triangle: .getNormal() target is now required');
  11189. target = new Vector3();
  11190. }
  11191. target.subVectors(c, b);
  11192. _v0$1.subVectors(a, b);
  11193. target.cross(_v0$1);
  11194. var targetLengthSq = target.lengthSq();
  11195. if (targetLengthSq > 0) {
  11196. return target.multiplyScalar(1 / Math.sqrt(targetLengthSq));
  11197. }
  11198. return target.set(0, 0, 0);
  11199. } // static/instance method to calculate barycentric coordinates
  11200. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  11201. ;
  11202. Triangle.getBarycoord = function getBarycoord(point, a, b, c, target) {
  11203. _v0$1.subVectors(c, a);
  11204. _v1$3.subVectors(b, a);
  11205. _v2$1.subVectors(point, a);
  11206. var dot00 = _v0$1.dot(_v0$1);
  11207. var dot01 = _v0$1.dot(_v1$3);
  11208. var dot02 = _v0$1.dot(_v2$1);
  11209. var dot11 = _v1$3.dot(_v1$3);
  11210. var dot12 = _v1$3.dot(_v2$1);
  11211. var denom = dot00 * dot11 - dot01 * dot01;
  11212. if (target === undefined) {
  11213. console.warn('THREE.Triangle: .getBarycoord() target is now required');
  11214. target = new Vector3();
  11215. } // collinear or singular triangle
  11216. if (denom === 0) {
  11217. // arbitrary location outside of triangle?
  11218. // not sure if this is the best idea, maybe should be returning undefined
  11219. return target.set(-2, -1, -1);
  11220. }
  11221. var invDenom = 1 / denom;
  11222. var u = (dot11 * dot02 - dot01 * dot12) * invDenom;
  11223. var v = (dot00 * dot12 - dot01 * dot02) * invDenom; // barycentric coordinates must always sum to 1
  11224. return target.set(1 - u - v, v, u);
  11225. };
  11226. Triangle.containsPoint = function containsPoint(point, a, b, c) {
  11227. this.getBarycoord(point, a, b, c, _v3);
  11228. return _v3.x >= 0 && _v3.y >= 0 && _v3.x + _v3.y <= 1;
  11229. };
  11230. Triangle.getUV = function getUV(point, p1, p2, p3, uv1, uv2, uv3, target) {
  11231. this.getBarycoord(point, p1, p2, p3, _v3);
  11232. target.set(0, 0);
  11233. target.addScaledVector(uv1, _v3.x);
  11234. target.addScaledVector(uv2, _v3.y);
  11235. target.addScaledVector(uv3, _v3.z);
  11236. return target;
  11237. };
  11238. Triangle.isFrontFacing = function isFrontFacing(a, b, c, direction) {
  11239. _v0$1.subVectors(c, b);
  11240. _v1$3.subVectors(a, b); // strictly front facing
  11241. return _v0$1.cross(_v1$3).dot(direction) < 0 ? true : false;
  11242. };
  11243. var _proto = Triangle.prototype;
  11244. _proto.set = function set(a, b, c) {
  11245. this.a.copy(a);
  11246. this.b.copy(b);
  11247. this.c.copy(c);
  11248. return this;
  11249. };
  11250. _proto.setFromPointsAndIndices = function setFromPointsAndIndices(points, i0, i1, i2) {
  11251. this.a.copy(points[i0]);
  11252. this.b.copy(points[i1]);
  11253. this.c.copy(points[i2]);
  11254. return this;
  11255. };
  11256. _proto.clone = function clone() {
  11257. return new this.constructor().copy(this);
  11258. };
  11259. _proto.copy = function copy(triangle) {
  11260. this.a.copy(triangle.a);
  11261. this.b.copy(triangle.b);
  11262. this.c.copy(triangle.c);
  11263. return this;
  11264. };
  11265. _proto.getArea = function getArea() {
  11266. _v0$1.subVectors(this.c, this.b);
  11267. _v1$3.subVectors(this.a, this.b);
  11268. return _v0$1.cross(_v1$3).length() * 0.5;
  11269. };
  11270. _proto.getMidpoint = function getMidpoint(target) {
  11271. if (target === undefined) {
  11272. console.warn('THREE.Triangle: .getMidpoint() target is now required');
  11273. target = new Vector3();
  11274. }
  11275. return target.addVectors(this.a, this.b).add(this.c).multiplyScalar(1 / 3);
  11276. };
  11277. _proto.getNormal = function getNormal(target) {
  11278. return Triangle.getNormal(this.a, this.b, this.c, target);
  11279. };
  11280. _proto.getPlane = function getPlane(target) {
  11281. if (target === undefined) {
  11282. console.warn('THREE.Triangle: .getPlane() target is now required');
  11283. target = new Plane();
  11284. }
  11285. return target.setFromCoplanarPoints(this.a, this.b, this.c);
  11286. };
  11287. _proto.getBarycoord = function getBarycoord(point, target) {
  11288. return Triangle.getBarycoord(point, this.a, this.b, this.c, target);
  11289. };
  11290. _proto.getUV = function getUV(point, uv1, uv2, uv3, target) {
  11291. return Triangle.getUV(point, this.a, this.b, this.c, uv1, uv2, uv3, target);
  11292. };
  11293. _proto.containsPoint = function containsPoint(point) {
  11294. return Triangle.containsPoint(point, this.a, this.b, this.c);
  11295. };
  11296. _proto.isFrontFacing = function isFrontFacing(direction) {
  11297. return Triangle.isFrontFacing(this.a, this.b, this.c, direction);
  11298. };
  11299. _proto.intersectsBox = function intersectsBox(box) {
  11300. return box.intersectsTriangle(this);
  11301. };
  11302. _proto.closestPointToPoint = function closestPointToPoint(p, target) {
  11303. if (target === undefined) {
  11304. console.warn('THREE.Triangle: .closestPointToPoint() target is now required');
  11305. target = new Vector3();
  11306. }
  11307. var a = this.a,
  11308. b = this.b,
  11309. c = this.c;
  11310. var v, w; // algorithm thanks to Real-Time Collision Detection by Christer Ericson,
  11311. // published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc.,
  11312. // under the accompanying license; see chapter 5.1.5 for detailed explanation.
  11313. // basically, we're distinguishing which of the voronoi regions of the triangle
  11314. // the point lies in with the minimum amount of redundant computation.
  11315. _vab.subVectors(b, a);
  11316. _vac.subVectors(c, a);
  11317. _vap.subVectors(p, a);
  11318. var d1 = _vab.dot(_vap);
  11319. var d2 = _vac.dot(_vap);
  11320. if (d1 <= 0 && d2 <= 0) {
  11321. // vertex region of A; barycentric coords (1, 0, 0)
  11322. return target.copy(a);
  11323. }
  11324. _vbp.subVectors(p, b);
  11325. var d3 = _vab.dot(_vbp);
  11326. var d4 = _vac.dot(_vbp);
  11327. if (d3 >= 0 && d4 <= d3) {
  11328. // vertex region of B; barycentric coords (0, 1, 0)
  11329. return target.copy(b);
  11330. }
  11331. var vc = d1 * d4 - d3 * d2;
  11332. if (vc <= 0 && d1 >= 0 && d3 <= 0) {
  11333. v = d1 / (d1 - d3); // edge region of AB; barycentric coords (1-v, v, 0)
  11334. return target.copy(a).addScaledVector(_vab, v);
  11335. }
  11336. _vcp.subVectors(p, c);
  11337. var d5 = _vab.dot(_vcp);
  11338. var d6 = _vac.dot(_vcp);
  11339. if (d6 >= 0 && d5 <= d6) {
  11340. // vertex region of C; barycentric coords (0, 0, 1)
  11341. return target.copy(c);
  11342. }
  11343. var vb = d5 * d2 - d1 * d6;
  11344. if (vb <= 0 && d2 >= 0 && d6 <= 0) {
  11345. w = d2 / (d2 - d6); // edge region of AC; barycentric coords (1-w, 0, w)
  11346. return target.copy(a).addScaledVector(_vac, w);
  11347. }
  11348. var va = d3 * d6 - d5 * d4;
  11349. if (va <= 0 && d4 - d3 >= 0 && d5 - d6 >= 0) {
  11350. _vbc.subVectors(c, b);
  11351. w = (d4 - d3) / (d4 - d3 + (d5 - d6)); // edge region of BC; barycentric coords (0, 1-w, w)
  11352. return target.copy(b).addScaledVector(_vbc, w); // edge region of BC
  11353. } // face region
  11354. var denom = 1 / (va + vb + vc); // u = va * denom
  11355. v = vb * denom;
  11356. w = vc * denom;
  11357. return target.copy(a).addScaledVector(_vab, v).addScaledVector(_vac, w);
  11358. };
  11359. _proto.equals = function equals(triangle) {
  11360. return triangle.a.equals(this.a) && triangle.b.equals(this.b) && triangle.c.equals(this.c);
  11361. };
  11362. return Triangle;
  11363. }();
  11364. var _colorKeywords = {
  11365. 'aliceblue': 0xF0F8FF,
  11366. 'antiquewhite': 0xFAEBD7,
  11367. 'aqua': 0x00FFFF,
  11368. 'aquamarine': 0x7FFFD4,
  11369. 'azure': 0xF0FFFF,
  11370. 'beige': 0xF5F5DC,
  11371. 'bisque': 0xFFE4C4,
  11372. 'black': 0x000000,
  11373. 'blanchedalmond': 0xFFEBCD,
  11374. 'blue': 0x0000FF,
  11375. 'blueviolet': 0x8A2BE2,
  11376. 'brown': 0xA52A2A,
  11377. 'burlywood': 0xDEB887,
  11378. 'cadetblue': 0x5F9EA0,
  11379. 'chartreuse': 0x7FFF00,
  11380. 'chocolate': 0xD2691E,
  11381. 'coral': 0xFF7F50,
  11382. 'cornflowerblue': 0x6495ED,
  11383. 'cornsilk': 0xFFF8DC,
  11384. 'crimson': 0xDC143C,
  11385. 'cyan': 0x00FFFF,
  11386. 'darkblue': 0x00008B,
  11387. 'darkcyan': 0x008B8B,
  11388. 'darkgoldenrod': 0xB8860B,
  11389. 'darkgray': 0xA9A9A9,
  11390. 'darkgreen': 0x006400,
  11391. 'darkgrey': 0xA9A9A9,
  11392. 'darkkhaki': 0xBDB76B,
  11393. 'darkmagenta': 0x8B008B,
  11394. 'darkolivegreen': 0x556B2F,
  11395. 'darkorange': 0xFF8C00,
  11396. 'darkorchid': 0x9932CC,
  11397. 'darkred': 0x8B0000,
  11398. 'darksalmon': 0xE9967A,
  11399. 'darkseagreen': 0x8FBC8F,
  11400. 'darkslateblue': 0x483D8B,
  11401. 'darkslategray': 0x2F4F4F,
  11402. 'darkslategrey': 0x2F4F4F,
  11403. 'darkturquoise': 0x00CED1,
  11404. 'darkviolet': 0x9400D3,
  11405. 'deeppink': 0xFF1493,
  11406. 'deepskyblue': 0x00BFFF,
  11407. 'dimgray': 0x696969,
  11408. 'dimgrey': 0x696969,
  11409. 'dodgerblue': 0x1E90FF,
  11410. 'firebrick': 0xB22222,
  11411. 'floralwhite': 0xFFFAF0,
  11412. 'forestgreen': 0x228B22,
  11413. 'fuchsia': 0xFF00FF,
  11414. 'gainsboro': 0xDCDCDC,
  11415. 'ghostwhite': 0xF8F8FF,
  11416. 'gold': 0xFFD700,
  11417. 'goldenrod': 0xDAA520,
  11418. 'gray': 0x808080,
  11419. 'green': 0x008000,
  11420. 'greenyellow': 0xADFF2F,
  11421. 'grey': 0x808080,
  11422. 'honeydew': 0xF0FFF0,
  11423. 'hotpink': 0xFF69B4,
  11424. 'indianred': 0xCD5C5C,
  11425. 'indigo': 0x4B0082,
  11426. 'ivory': 0xFFFFF0,
  11427. 'khaki': 0xF0E68C,
  11428. 'lavender': 0xE6E6FA,
  11429. 'lavenderblush': 0xFFF0F5,
  11430. 'lawngreen': 0x7CFC00,
  11431. 'lemonchiffon': 0xFFFACD,
  11432. 'lightblue': 0xADD8E6,
  11433. 'lightcoral': 0xF08080,
  11434. 'lightcyan': 0xE0FFFF,
  11435. 'lightgoldenrodyellow': 0xFAFAD2,
  11436. 'lightgray': 0xD3D3D3,
  11437. 'lightgreen': 0x90EE90,
  11438. 'lightgrey': 0xD3D3D3,
  11439. 'lightpink': 0xFFB6C1,
  11440. 'lightsalmon': 0xFFA07A,
  11441. 'lightseagreen': 0x20B2AA,
  11442. 'lightskyblue': 0x87CEFA,
  11443. 'lightslategray': 0x778899,
  11444. 'lightslategrey': 0x778899,
  11445. 'lightsteelblue': 0xB0C4DE,
  11446. 'lightyellow': 0xFFFFE0,
  11447. 'lime': 0x00FF00,
  11448. 'limegreen': 0x32CD32,
  11449. 'linen': 0xFAF0E6,
  11450. 'magenta': 0xFF00FF,
  11451. 'maroon': 0x800000,
  11452. 'mediumaquamarine': 0x66CDAA,
  11453. 'mediumblue': 0x0000CD,
  11454. 'mediumorchid': 0xBA55D3,
  11455. 'mediumpurple': 0x9370DB,
  11456. 'mediumseagreen': 0x3CB371,
  11457. 'mediumslateblue': 0x7B68EE,
  11458. 'mediumspringgreen': 0x00FA9A,
  11459. 'mediumturquoise': 0x48D1CC,
  11460. 'mediumvioletred': 0xC71585,
  11461. 'midnightblue': 0x191970,
  11462. 'mintcream': 0xF5FFFA,
  11463. 'mistyrose': 0xFFE4E1,
  11464. 'moccasin': 0xFFE4B5,
  11465. 'navajowhite': 0xFFDEAD,
  11466. 'navy': 0x000080,
  11467. 'oldlace': 0xFDF5E6,
  11468. 'olive': 0x808000,
  11469. 'olivedrab': 0x6B8E23,
  11470. 'orange': 0xFFA500,
  11471. 'orangered': 0xFF4500,
  11472. 'orchid': 0xDA70D6,
  11473. 'palegoldenrod': 0xEEE8AA,
  11474. 'palegreen': 0x98FB98,
  11475. 'paleturquoise': 0xAFEEEE,
  11476. 'palevioletred': 0xDB7093,
  11477. 'papayawhip': 0xFFEFD5,
  11478. 'peachpuff': 0xFFDAB9,
  11479. 'peru': 0xCD853F,
  11480. 'pink': 0xFFC0CB,
  11481. 'plum': 0xDDA0DD,
  11482. 'powderblue': 0xB0E0E6,
  11483. 'purple': 0x800080,
  11484. 'rebeccapurple': 0x663399,
  11485. 'red': 0xFF0000,
  11486. 'rosybrown': 0xBC8F8F,
  11487. 'royalblue': 0x4169E1,
  11488. 'saddlebrown': 0x8B4513,
  11489. 'salmon': 0xFA8072,
  11490. 'sandybrown': 0xF4A460,
  11491. 'seagreen': 0x2E8B57,
  11492. 'seashell': 0xFFF5EE,
  11493. 'sienna': 0xA0522D,
  11494. 'silver': 0xC0C0C0,
  11495. 'skyblue': 0x87CEEB,
  11496. 'slateblue': 0x6A5ACD,
  11497. 'slategray': 0x708090,
  11498. 'slategrey': 0x708090,
  11499. 'snow': 0xFFFAFA,
  11500. 'springgreen': 0x00FF7F,
  11501. 'steelblue': 0x4682B4,
  11502. 'tan': 0xD2B48C,
  11503. 'teal': 0x008080,
  11504. 'thistle': 0xD8BFD8,
  11505. 'tomato': 0xFF6347,
  11506. 'turquoise': 0x40E0D0,
  11507. 'violet': 0xEE82EE,
  11508. 'wheat': 0xF5DEB3,
  11509. 'white': 0xFFFFFF,
  11510. 'whitesmoke': 0xF5F5F5,
  11511. 'yellow': 0xFFFF00,
  11512. 'yellowgreen': 0x9ACD32
  11513. };
  11514. var _hslA = {
  11515. h: 0,
  11516. s: 0,
  11517. l: 0
  11518. };
  11519. var _hslB = {
  11520. h: 0,
  11521. s: 0,
  11522. l: 0
  11523. };
  11524. function hue2rgb(p, q, t) {
  11525. if (t < 0) t += 1;
  11526. if (t > 1) t -= 1;
  11527. if (t < 1 / 6) return p + (q - p) * 6 * t;
  11528. if (t < 1 / 2) return q;
  11529. if (t < 2 / 3) return p + (q - p) * 6 * (2 / 3 - t);
  11530. return p;
  11531. }
  11532. function SRGBToLinear(c) {
  11533. return c < 0.04045 ? c * 0.0773993808 : Math.pow(c * 0.9478672986 + 0.0521327014, 2.4);
  11534. }
  11535. function LinearToSRGB(c) {
  11536. return c < 0.0031308 ? c * 12.92 : 1.055 * Math.pow(c, 0.41666) - 0.055;
  11537. }
  11538. var Color = /*#__PURE__*/function () {
  11539. function Color(r, g, b) {
  11540. Object.defineProperty(this, 'isColor', {
  11541. value: true
  11542. });
  11543. if (g === undefined && b === undefined) {
  11544. // r is THREE.Color, hex or string
  11545. return this.set(r);
  11546. }
  11547. return this.setRGB(r, g, b);
  11548. }
  11549. var _proto = Color.prototype;
  11550. _proto.set = function set(value) {
  11551. if (value && value.isColor) {
  11552. this.copy(value);
  11553. } else if (typeof value === 'number') {
  11554. this.setHex(value);
  11555. } else if (typeof value === 'string') {
  11556. this.setStyle(value);
  11557. }
  11558. return this;
  11559. };
  11560. _proto.setScalar = function setScalar(scalar) {
  11561. this.r = scalar;
  11562. this.g = scalar;
  11563. this.b = scalar;
  11564. return this;
  11565. };
  11566. _proto.setHex = function setHex(hex) {
  11567. hex = Math.floor(hex);
  11568. this.r = (hex >> 16 & 255) / 255;
  11569. this.g = (hex >> 8 & 255) / 255;
  11570. this.b = (hex & 255) / 255;
  11571. return this;
  11572. };
  11573. _proto.setRGB = function setRGB(r, g, b) {
  11574. this.r = r;
  11575. this.g = g;
  11576. this.b = b;
  11577. return this;
  11578. };
  11579. _proto.setHSL = function setHSL(h, s, l) {
  11580. // h,s,l ranges are in 0.0 - 1.0
  11581. h = MathUtils.euclideanModulo(h, 1);
  11582. s = MathUtils.clamp(s, 0, 1);
  11583. l = MathUtils.clamp(l, 0, 1);
  11584. if (s === 0) {
  11585. this.r = this.g = this.b = l;
  11586. } else {
  11587. var p = l <= 0.5 ? l * (1 + s) : l + s - l * s;
  11588. var q = 2 * l - p;
  11589. this.r = hue2rgb(q, p, h + 1 / 3);
  11590. this.g = hue2rgb(q, p, h);
  11591. this.b = hue2rgb(q, p, h - 1 / 3);
  11592. }
  11593. return this;
  11594. };
  11595. _proto.setStyle = function setStyle(style) {
  11596. function handleAlpha(string) {
  11597. if (string === undefined) return;
  11598. if (parseFloat(string) < 1) {
  11599. console.warn('THREE.Color: Alpha component of ' + style + ' will be ignored.');
  11600. }
  11601. }
  11602. var m;
  11603. if (m = /^((?:rgb|hsl)a?)\(([^\)]*)\)/.exec(style)) {
  11604. // rgb / hsl
  11605. var color;
  11606. var name = m[1];
  11607. var components = m[2];
  11608. switch (name) {
  11609. case 'rgb':
  11610. case 'rgba':
  11611. if (color = /^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(components)) {
  11612. // rgb(255,0,0) rgba(255,0,0,0.5)
  11613. this.r = Math.min(255, parseInt(color[1], 10)) / 255;
  11614. this.g = Math.min(255, parseInt(color[2], 10)) / 255;
  11615. this.b = Math.min(255, parseInt(color[3], 10)) / 255;
  11616. handleAlpha(color[4]);
  11617. return this;
  11618. }
  11619. if (color = /^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(components)) {
  11620. // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
  11621. this.r = Math.min(100, parseInt(color[1], 10)) / 100;
  11622. this.g = Math.min(100, parseInt(color[2], 10)) / 100;
  11623. this.b = Math.min(100, parseInt(color[3], 10)) / 100;
  11624. handleAlpha(color[4]);
  11625. return this;
  11626. }
  11627. break;
  11628. case 'hsl':
  11629. case 'hsla':
  11630. if (color = /^\s*(\d*\.?\d+)\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(components)) {
  11631. // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
  11632. var h = parseFloat(color[1]) / 360;
  11633. var s = parseInt(color[2], 10) / 100;
  11634. var l = parseInt(color[3], 10) / 100;
  11635. handleAlpha(color[4]);
  11636. return this.setHSL(h, s, l);
  11637. }
  11638. break;
  11639. }
  11640. } else if (m = /^\#([A-Fa-f\d]+)$/.exec(style)) {
  11641. // hex color
  11642. var hex = m[1];
  11643. var size = hex.length;
  11644. if (size === 3) {
  11645. // #ff0
  11646. this.r = parseInt(hex.charAt(0) + hex.charAt(0), 16) / 255;
  11647. this.g = parseInt(hex.charAt(1) + hex.charAt(1), 16) / 255;
  11648. this.b = parseInt(hex.charAt(2) + hex.charAt(2), 16) / 255;
  11649. return this;
  11650. } else if (size === 6) {
  11651. // #ff0000
  11652. this.r = parseInt(hex.charAt(0) + hex.charAt(1), 16) / 255;
  11653. this.g = parseInt(hex.charAt(2) + hex.charAt(3), 16) / 255;
  11654. this.b = parseInt(hex.charAt(4) + hex.charAt(5), 16) / 255;
  11655. return this;
  11656. }
  11657. }
  11658. if (style && style.length > 0) {
  11659. return this.setColorName(style);
  11660. }
  11661. return this;
  11662. };
  11663. _proto.setColorName = function setColorName(style) {
  11664. // color keywords
  11665. var hex = _colorKeywords[style];
  11666. if (hex !== undefined) {
  11667. // red
  11668. this.setHex(hex);
  11669. } else {
  11670. // unknown color
  11671. console.warn('THREE.Color: Unknown color ' + style);
  11672. }
  11673. return this;
  11674. };
  11675. _proto.clone = function clone() {
  11676. return new this.constructor(this.r, this.g, this.b);
  11677. };
  11678. _proto.copy = function copy(color) {
  11679. this.r = color.r;
  11680. this.g = color.g;
  11681. this.b = color.b;
  11682. return this;
  11683. };
  11684. _proto.copyGammaToLinear = function copyGammaToLinear(color, gammaFactor) {
  11685. if (gammaFactor === void 0) {
  11686. gammaFactor = 2.0;
  11687. }
  11688. this.r = Math.pow(color.r, gammaFactor);
  11689. this.g = Math.pow(color.g, gammaFactor);
  11690. this.b = Math.pow(color.b, gammaFactor);
  11691. return this;
  11692. };
  11693. _proto.copyLinearToGamma = function copyLinearToGamma(color, gammaFactor) {
  11694. if (gammaFactor === void 0) {
  11695. gammaFactor = 2.0;
  11696. }
  11697. var safeInverse = gammaFactor > 0 ? 1.0 / gammaFactor : 1.0;
  11698. this.r = Math.pow(color.r, safeInverse);
  11699. this.g = Math.pow(color.g, safeInverse);
  11700. this.b = Math.pow(color.b, safeInverse);
  11701. return this;
  11702. };
  11703. _proto.convertGammaToLinear = function convertGammaToLinear(gammaFactor) {
  11704. this.copyGammaToLinear(this, gammaFactor);
  11705. return this;
  11706. };
  11707. _proto.convertLinearToGamma = function convertLinearToGamma(gammaFactor) {
  11708. this.copyLinearToGamma(this, gammaFactor);
  11709. return this;
  11710. };
  11711. _proto.copySRGBToLinear = function copySRGBToLinear(color) {
  11712. this.r = SRGBToLinear(color.r);
  11713. this.g = SRGBToLinear(color.g);
  11714. this.b = SRGBToLinear(color.b);
  11715. return this;
  11716. };
  11717. _proto.copyLinearToSRGB = function copyLinearToSRGB(color) {
  11718. this.r = LinearToSRGB(color.r);
  11719. this.g = LinearToSRGB(color.g);
  11720. this.b = LinearToSRGB(color.b);
  11721. return this;
  11722. };
  11723. _proto.convertSRGBToLinear = function convertSRGBToLinear() {
  11724. this.copySRGBToLinear(this);
  11725. return this;
  11726. };
  11727. _proto.convertLinearToSRGB = function convertLinearToSRGB() {
  11728. this.copyLinearToSRGB(this);
  11729. return this;
  11730. };
  11731. _proto.getHex = function getHex() {
  11732. return this.r * 255 << 16 ^ this.g * 255 << 8 ^ this.b * 255 << 0;
  11733. };
  11734. _proto.getHexString = function getHexString() {
  11735. return ('000000' + this.getHex().toString(16)).slice(-6);
  11736. };
  11737. _proto.getHSL = function getHSL(target) {
  11738. // h,s,l ranges are in 0.0 - 1.0
  11739. if (target === undefined) {
  11740. console.warn('THREE.Color: .getHSL() target is now required');
  11741. target = {
  11742. h: 0,
  11743. s: 0,
  11744. l: 0
  11745. };
  11746. }
  11747. var r = this.r,
  11748. g = this.g,
  11749. b = this.b;
  11750. var max = Math.max(r, g, b);
  11751. var min = Math.min(r, g, b);
  11752. var hue, saturation;
  11753. var lightness = (min + max) / 2.0;
  11754. if (min === max) {
  11755. hue = 0;
  11756. saturation = 0;
  11757. } else {
  11758. var delta = max - min;
  11759. saturation = lightness <= 0.5 ? delta / (max + min) : delta / (2 - max - min);
  11760. switch (max) {
  11761. case r:
  11762. hue = (g - b) / delta + (g < b ? 6 : 0);
  11763. break;
  11764. case g:
  11765. hue = (b - r) / delta + 2;
  11766. break;
  11767. case b:
  11768. hue = (r - g) / delta + 4;
  11769. break;
  11770. }
  11771. hue /= 6;
  11772. }
  11773. target.h = hue;
  11774. target.s = saturation;
  11775. target.l = lightness;
  11776. return target;
  11777. };
  11778. _proto.getStyle = function getStyle() {
  11779. return 'rgb(' + (this.r * 255 | 0) + ',' + (this.g * 255 | 0) + ',' + (this.b * 255 | 0) + ')';
  11780. };
  11781. _proto.offsetHSL = function offsetHSL(h, s, l) {
  11782. this.getHSL(_hslA);
  11783. _hslA.h += h;
  11784. _hslA.s += s;
  11785. _hslA.l += l;
  11786. this.setHSL(_hslA.h, _hslA.s, _hslA.l);
  11787. return this;
  11788. };
  11789. _proto.add = function add(color) {
  11790. this.r += color.r;
  11791. this.g += color.g;
  11792. this.b += color.b;
  11793. return this;
  11794. };
  11795. _proto.addColors = function addColors(color1, color2) {
  11796. this.r = color1.r + color2.r;
  11797. this.g = color1.g + color2.g;
  11798. this.b = color1.b + color2.b;
  11799. return this;
  11800. };
  11801. _proto.addScalar = function addScalar(s) {
  11802. this.r += s;
  11803. this.g += s;
  11804. this.b += s;
  11805. return this;
  11806. };
  11807. _proto.sub = function sub(color) {
  11808. this.r = Math.max(0, this.r - color.r);
  11809. this.g = Math.max(0, this.g - color.g);
  11810. this.b = Math.max(0, this.b - color.b);
  11811. return this;
  11812. };
  11813. _proto.multiply = function multiply(color) {
  11814. this.r *= color.r;
  11815. this.g *= color.g;
  11816. this.b *= color.b;
  11817. return this;
  11818. };
  11819. _proto.multiplyScalar = function multiplyScalar(s) {
  11820. this.r *= s;
  11821. this.g *= s;
  11822. this.b *= s;
  11823. return this;
  11824. };
  11825. _proto.lerp = function lerp(color, alpha) {
  11826. this.r += (color.r - this.r) * alpha;
  11827. this.g += (color.g - this.g) * alpha;
  11828. this.b += (color.b - this.b) * alpha;
  11829. return this;
  11830. };
  11831. _proto.lerpColors = function lerpColors(color1, color2, alpha) {
  11832. this.r = color1.r + (color2.r - color1.r) * alpha;
  11833. this.g = color1.g + (color2.g - color1.g) * alpha;
  11834. this.b = color1.b + (color2.b - color1.b) * alpha;
  11835. return this;
  11836. };
  11837. _proto.lerpHSL = function lerpHSL(color, alpha) {
  11838. this.getHSL(_hslA);
  11839. color.getHSL(_hslB);
  11840. var h = MathUtils.lerp(_hslA.h, _hslB.h, alpha);
  11841. var s = MathUtils.lerp(_hslA.s, _hslB.s, alpha);
  11842. var l = MathUtils.lerp(_hslA.l, _hslB.l, alpha);
  11843. this.setHSL(h, s, l);
  11844. return this;
  11845. };
  11846. _proto.equals = function equals(c) {
  11847. return c.r === this.r && c.g === this.g && c.b === this.b;
  11848. };
  11849. _proto.fromArray = function fromArray(array, offset) {
  11850. if (offset === void 0) {
  11851. offset = 0;
  11852. }
  11853. this.r = array[offset];
  11854. this.g = array[offset + 1];
  11855. this.b = array[offset + 2];
  11856. return this;
  11857. };
  11858. _proto.toArray = function toArray(array, offset) {
  11859. if (array === void 0) {
  11860. array = [];
  11861. }
  11862. if (offset === void 0) {
  11863. offset = 0;
  11864. }
  11865. array[offset] = this.r;
  11866. array[offset + 1] = this.g;
  11867. array[offset + 2] = this.b;
  11868. return array;
  11869. };
  11870. _proto.fromBufferAttribute = function fromBufferAttribute(attribute, index) {
  11871. this.r = attribute.getX(index);
  11872. this.g = attribute.getY(index);
  11873. this.b = attribute.getZ(index);
  11874. if (attribute.normalized === true) {
  11875. // assuming Uint8Array
  11876. this.r /= 255;
  11877. this.g /= 255;
  11878. this.b /= 255;
  11879. }
  11880. return this;
  11881. };
  11882. _proto.toJSON = function toJSON() {
  11883. return this.getHex();
  11884. };
  11885. return Color;
  11886. }();
  11887. Color.NAMES = _colorKeywords;
  11888. Color.prototype.r = 1;
  11889. Color.prototype.g = 1;
  11890. Color.prototype.b = 1;
  11891. var Face3 = /*#__PURE__*/function () {
  11892. function Face3(a, b, c, normal, color, materialIndex) {
  11893. if (materialIndex === void 0) {
  11894. materialIndex = 0;
  11895. }
  11896. this.a = a;
  11897. this.b = b;
  11898. this.c = c;
  11899. this.normal = normal && normal.isVector3 ? normal : new Vector3();
  11900. this.vertexNormals = Array.isArray(normal) ? normal : [];
  11901. this.color = color && color.isColor ? color : new Color();
  11902. this.vertexColors = Array.isArray(color) ? color : [];
  11903. this.materialIndex = materialIndex;
  11904. }
  11905. var _proto = Face3.prototype;
  11906. _proto.clone = function clone() {
  11907. return new this.constructor().copy(this);
  11908. };
  11909. _proto.copy = function copy(source) {
  11910. this.a = source.a;
  11911. this.b = source.b;
  11912. this.c = source.c;
  11913. this.normal.copy(source.normal);
  11914. this.color.copy(source.color);
  11915. this.materialIndex = source.materialIndex;
  11916. for (var i = 0, il = source.vertexNormals.length; i < il; i++) {
  11917. this.vertexNormals[i] = source.vertexNormals[i].clone();
  11918. }
  11919. for (var _i = 0, _il = source.vertexColors.length; _i < _il; _i++) {
  11920. this.vertexColors[_i] = source.vertexColors[_i].clone();
  11921. }
  11922. return this;
  11923. };
  11924. return Face3;
  11925. }();
  11926. var materialId = 0;
  11927. function Material() {
  11928. Object.defineProperty(this, 'id', {
  11929. value: materialId++
  11930. });
  11931. this.uuid = MathUtils.generateUUID();
  11932. this.name = '';
  11933. this.type = 'Material';
  11934. this.fog = true;
  11935. this.blending = NormalBlending;
  11936. this.side = FrontSide;
  11937. this.flatShading = false;
  11938. this.vertexColors = false;
  11939. this.opacity = 1;
  11940. this.transparent = false;
  11941. this.blendSrc = SrcAlphaFactor;
  11942. this.blendDst = OneMinusSrcAlphaFactor;
  11943. this.blendEquation = AddEquation;
  11944. this.blendSrcAlpha = null;
  11945. this.blendDstAlpha = null;
  11946. this.blendEquationAlpha = null;
  11947. this.depthFunc = LessEqualDepth;
  11948. this.depthTest = true;
  11949. this.depthWrite = true;
  11950. this.stencilWriteMask = 0xff;
  11951. this.stencilFunc = AlwaysStencilFunc;
  11952. this.stencilRef = 0;
  11953. this.stencilFuncMask = 0xff;
  11954. this.stencilFail = KeepStencilOp;
  11955. this.stencilZFail = KeepStencilOp;
  11956. this.stencilZPass = KeepStencilOp;
  11957. this.stencilWrite = false;
  11958. this.clippingPlanes = null;
  11959. this.clipIntersection = false;
  11960. this.clipShadows = false;
  11961. this.shadowSide = null;
  11962. this.colorWrite = true;
  11963. this.precision = null; // override the renderer's default precision for this material
  11964. this.polygonOffset = false;
  11965. this.polygonOffsetFactor = 0;
  11966. this.polygonOffsetUnits = 0;
  11967. this.dithering = false;
  11968. this.alphaTest = 0;
  11969. this.premultipliedAlpha = false;
  11970. this.visible = true;
  11971. this.toneMapped = true;
  11972. this.userData = {};
  11973. this.version = 0;
  11974. }
  11975. Material.prototype = Object.assign(Object.create(EventDispatcher.prototype), {
  11976. constructor: Material,
  11977. isMaterial: true,
  11978. onBeforeCompile: function onBeforeCompile()
  11979. /* shaderobject, renderer */
  11980. {},
  11981. customProgramCacheKey: function customProgramCacheKey() {
  11982. return this.onBeforeCompile.toString();
  11983. },
  11984. setValues: function setValues(values) {
  11985. if (values === undefined) return;
  11986. for (var key in values) {
  11987. var newValue = values[key];
  11988. if (newValue === undefined) {
  11989. console.warn('THREE.Material: \'' + key + '\' parameter is undefined.');
  11990. continue;
  11991. } // for backward compatability if shading is set in the constructor
  11992. if (key === 'shading') {
  11993. console.warn('THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.');
  11994. this.flatShading = newValue === FlatShading ? true : false;
  11995. continue;
  11996. }
  11997. var currentValue = this[key];
  11998. if (currentValue === undefined) {
  11999. console.warn('THREE.' + this.type + ': \'' + key + '\' is not a property of this material.');
  12000. continue;
  12001. }
  12002. if (currentValue && currentValue.isColor) {
  12003. currentValue.set(newValue);
  12004. } else if (currentValue && currentValue.isVector3 && newValue && newValue.isVector3) {
  12005. currentValue.copy(newValue);
  12006. } else {
  12007. this[key] = newValue;
  12008. }
  12009. }
  12010. },
  12011. toJSON: function toJSON(meta) {
  12012. var isRoot = meta === undefined || typeof meta === 'string';
  12013. if (isRoot) {
  12014. meta = {
  12015. textures: {},
  12016. images: {}
  12017. };
  12018. }
  12019. var data = {
  12020. metadata: {
  12021. version: 4.5,
  12022. type: 'Material',
  12023. generator: 'Material.toJSON'
  12024. }
  12025. }; // standard Material serialization
  12026. data.uuid = this.uuid;
  12027. data.type = this.type;
  12028. if (this.name !== '') data.name = this.name;
  12029. if (this.color && this.color.isColor) data.color = this.color.getHex();
  12030. if (this.roughness !== undefined) data.roughness = this.roughness;
  12031. if (this.metalness !== undefined) data.metalness = this.metalness;
  12032. if (this.sheen && this.sheen.isColor) data.sheen = this.sheen.getHex();
  12033. if (this.emissive && this.emissive.isColor) data.emissive = this.emissive.getHex();
  12034. if (this.emissiveIntensity && this.emissiveIntensity !== 1) data.emissiveIntensity = this.emissiveIntensity;
  12035. if (this.specular && this.specular.isColor) data.specular = this.specular.getHex();
  12036. if (this.shininess !== undefined) data.shininess = this.shininess;
  12037. if (this.clearcoat !== undefined) data.clearcoat = this.clearcoat;
  12038. if (this.clearcoatRoughness !== undefined) data.clearcoatRoughness = this.clearcoatRoughness;
  12039. if (this.clearcoatMap && this.clearcoatMap.isTexture) {
  12040. data.clearcoatMap = this.clearcoatMap.toJSON(meta).uuid;
  12041. }
  12042. if (this.clearcoatRoughnessMap && this.clearcoatRoughnessMap.isTexture) {
  12043. data.clearcoatRoughnessMap = this.clearcoatRoughnessMap.toJSON(meta).uuid;
  12044. }
  12045. if (this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture) {
  12046. data.clearcoatNormalMap = this.clearcoatNormalMap.toJSON(meta).uuid;
  12047. data.clearcoatNormalScale = this.clearcoatNormalScale.toArray();
  12048. }
  12049. if (this.map && this.map.isTexture) data.map = this.map.toJSON(meta).uuid;
  12050. if (this.matcap && this.matcap.isTexture) data.matcap = this.matcap.toJSON(meta).uuid;
  12051. if (this.alphaMap && this.alphaMap.isTexture) data.alphaMap = this.alphaMap.toJSON(meta).uuid;
  12052. if (this.lightMap && this.lightMap.isTexture) data.lightMap = this.lightMap.toJSON(meta).uuid;
  12053. if (this.aoMap && this.aoMap.isTexture) {
  12054. data.aoMap = this.aoMap.toJSON(meta).uuid;
  12055. data.aoMapIntensity = this.aoMapIntensity;
  12056. }
  12057. if (this.bumpMap && this.bumpMap.isTexture) {
  12058. data.bumpMap = this.bumpMap.toJSON(meta).uuid;
  12059. data.bumpScale = this.bumpScale;
  12060. }
  12061. if (this.normalMap && this.normalMap.isTexture) {
  12062. data.normalMap = this.normalMap.toJSON(meta).uuid;
  12063. data.normalMapType = this.normalMapType;
  12064. data.normalScale = this.normalScale.toArray();
  12065. }
  12066. if (this.displacementMap && this.displacementMap.isTexture) {
  12067. data.displacementMap = this.displacementMap.toJSON(meta).uuid;
  12068. data.displacementScale = this.displacementScale;
  12069. data.displacementBias = this.displacementBias;
  12070. }
  12071. if (this.roughnessMap && this.roughnessMap.isTexture) data.roughnessMap = this.roughnessMap.toJSON(meta).uuid;
  12072. if (this.metalnessMap && this.metalnessMap.isTexture) data.metalnessMap = this.metalnessMap.toJSON(meta).uuid;
  12073. if (this.emissiveMap && this.emissiveMap.isTexture) data.emissiveMap = this.emissiveMap.toJSON(meta).uuid;
  12074. if (this.specularMap && this.specularMap.isTexture) data.specularMap = this.specularMap.toJSON(meta).uuid;
  12075. if (this.envMap && this.envMap.isTexture) {
  12076. data.envMap = this.envMap.toJSON(meta).uuid;
  12077. data.reflectivity = this.reflectivity; // Scale behind envMap
  12078. data.refractionRatio = this.refractionRatio;
  12079. if (this.combine !== undefined) data.combine = this.combine;
  12080. if (this.envMapIntensity !== undefined) data.envMapIntensity = this.envMapIntensity;
  12081. }
  12082. if (this.gradientMap && this.gradientMap.isTexture) {
  12083. data.gradientMap = this.gradientMap.toJSON(meta).uuid;
  12084. }
  12085. if (this.size !== undefined) data.size = this.size;
  12086. if (this.sizeAttenuation !== undefined) data.sizeAttenuation = this.sizeAttenuation;
  12087. if (this.blending !== NormalBlending) data.blending = this.blending;
  12088. if (this.flatShading === true) data.flatShading = this.flatShading;
  12089. if (this.side !== FrontSide) data.side = this.side;
  12090. if (this.vertexColors) data.vertexColors = true;
  12091. if (this.opacity < 1) data.opacity = this.opacity;
  12092. if (this.transparent === true) data.transparent = this.transparent;
  12093. data.depthFunc = this.depthFunc;
  12094. data.depthTest = this.depthTest;
  12095. data.depthWrite = this.depthWrite;
  12096. data.stencilWrite = this.stencilWrite;
  12097. data.stencilWriteMask = this.stencilWriteMask;
  12098. data.stencilFunc = this.stencilFunc;
  12099. data.stencilRef = this.stencilRef;
  12100. data.stencilFuncMask = this.stencilFuncMask;
  12101. data.stencilFail = this.stencilFail;
  12102. data.stencilZFail = this.stencilZFail;
  12103. data.stencilZPass = this.stencilZPass; // rotation (SpriteMaterial)
  12104. if (this.rotation && this.rotation !== 0) data.rotation = this.rotation;
  12105. if (this.polygonOffset === true) data.polygonOffset = true;
  12106. if (this.polygonOffsetFactor !== 0) data.polygonOffsetFactor = this.polygonOffsetFactor;
  12107. if (this.polygonOffsetUnits !== 0) data.polygonOffsetUnits = this.polygonOffsetUnits;
  12108. if (this.linewidth && this.linewidth !== 1) data.linewidth = this.linewidth;
  12109. if (this.dashSize !== undefined) data.dashSize = this.dashSize;
  12110. if (this.gapSize !== undefined) data.gapSize = this.gapSize;
  12111. if (this.scale !== undefined) data.scale = this.scale;
  12112. if (this.dithering === true) data.dithering = true;
  12113. if (this.alphaTest > 0) data.alphaTest = this.alphaTest;
  12114. if (this.premultipliedAlpha === true) data.premultipliedAlpha = this.premultipliedAlpha;
  12115. if (this.wireframe === true) data.wireframe = this.wireframe;
  12116. if (this.wireframeLinewidth > 1) data.wireframeLinewidth = this.wireframeLinewidth;
  12117. if (this.wireframeLinecap !== 'round') data.wireframeLinecap = this.wireframeLinecap;
  12118. if (this.wireframeLinejoin !== 'round') data.wireframeLinejoin = this.wireframeLinejoin;
  12119. if (this.morphTargets === true) data.morphTargets = true;
  12120. if (this.morphNormals === true) data.morphNormals = true;
  12121. if (this.skinning === true) data.skinning = true;
  12122. if (this.visible === false) data.visible = false;
  12123. if (this.toneMapped === false) data.toneMapped = false;
  12124. if (JSON.stringify(this.userData) !== '{}') data.userData = this.userData; // TODO: Copied from Object3D.toJSON
  12125. function extractFromCache(cache) {
  12126. var values = [];
  12127. for (var key in cache) {
  12128. var _data = cache[key];
  12129. delete _data.metadata;
  12130. values.push(_data);
  12131. }
  12132. return values;
  12133. }
  12134. if (isRoot) {
  12135. var textures = extractFromCache(meta.textures);
  12136. var images = extractFromCache(meta.images);
  12137. if (textures.length > 0) data.textures = textures;
  12138. if (images.length > 0) data.images = images;
  12139. }
  12140. return data;
  12141. },
  12142. clone: function clone() {
  12143. return new this.constructor().copy(this);
  12144. },
  12145. copy: function copy(source) {
  12146. this.name = source.name;
  12147. this.fog = source.fog;
  12148. this.blending = source.blending;
  12149. this.side = source.side;
  12150. this.flatShading = source.flatShading;
  12151. this.vertexColors = source.vertexColors;
  12152. this.opacity = source.opacity;
  12153. this.transparent = source.transparent;
  12154. this.blendSrc = source.blendSrc;
  12155. this.blendDst = source.blendDst;
  12156. this.blendEquation = source.blendEquation;
  12157. this.blendSrcAlpha = source.blendSrcAlpha;
  12158. this.blendDstAlpha = source.blendDstAlpha;
  12159. this.blendEquationAlpha = source.blendEquationAlpha;
  12160. this.depthFunc = source.depthFunc;
  12161. this.depthTest = source.depthTest;
  12162. this.depthWrite = source.depthWrite;
  12163. this.stencilWriteMask = source.stencilWriteMask;
  12164. this.stencilFunc = source.stencilFunc;
  12165. this.stencilRef = source.stencilRef;
  12166. this.stencilFuncMask = source.stencilFuncMask;
  12167. this.stencilFail = source.stencilFail;
  12168. this.stencilZFail = source.stencilZFail;
  12169. this.stencilZPass = source.stencilZPass;
  12170. this.stencilWrite = source.stencilWrite;
  12171. var srcPlanes = source.clippingPlanes;
  12172. var dstPlanes = null;
  12173. if (srcPlanes !== null) {
  12174. var n = srcPlanes.length;
  12175. dstPlanes = new Array(n);
  12176. for (var i = 0; i !== n; ++i) {
  12177. dstPlanes[i] = srcPlanes[i].clone();
  12178. }
  12179. }
  12180. this.clippingPlanes = dstPlanes;
  12181. this.clipIntersection = source.clipIntersection;
  12182. this.clipShadows = source.clipShadows;
  12183. this.shadowSide = source.shadowSide;
  12184. this.colorWrite = source.colorWrite;
  12185. this.precision = source.precision;
  12186. this.polygonOffset = source.polygonOffset;
  12187. this.polygonOffsetFactor = source.polygonOffsetFactor;
  12188. this.polygonOffsetUnits = source.polygonOffsetUnits;
  12189. this.dithering = source.dithering;
  12190. this.alphaTest = source.alphaTest;
  12191. this.premultipliedAlpha = source.premultipliedAlpha;
  12192. this.visible = source.visible;
  12193. this.toneMapped = source.toneMapped;
  12194. this.userData = JSON.parse(JSON.stringify(source.userData));
  12195. return this;
  12196. },
  12197. dispose: function dispose() {
  12198. this.dispatchEvent({
  12199. type: 'dispose'
  12200. });
  12201. }
  12202. });
  12203. Object.defineProperty(Material.prototype, 'needsUpdate', {
  12204. set: function set(value) {
  12205. if (value === true) this.version++;
  12206. }
  12207. });
  12208. /**
  12209. * parameters = {
  12210. * color: <hex>,
  12211. * opacity: <float>,
  12212. * map: new THREE.Texture( <Image> ),
  12213. *
  12214. * lightMap: new THREE.Texture( <Image> ),
  12215. * lightMapIntensity: <float>
  12216. *
  12217. * aoMap: new THREE.Texture( <Image> ),
  12218. * aoMapIntensity: <float>
  12219. *
  12220. * specularMap: new THREE.Texture( <Image> ),
  12221. *
  12222. * alphaMap: new THREE.Texture( <Image> ),
  12223. *
  12224. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  12225. * combine: THREE.Multiply,
  12226. * reflectivity: <float>,
  12227. * refractionRatio: <float>,
  12228. *
  12229. * depthTest: <bool>,
  12230. * depthWrite: <bool>,
  12231. *
  12232. * wireframe: <boolean>,
  12233. * wireframeLinewidth: <float>,
  12234. *
  12235. * skinning: <bool>,
  12236. * morphTargets: <bool>
  12237. * }
  12238. */
  12239. function MeshBasicMaterial(parameters) {
  12240. Material.call(this);
  12241. this.type = 'MeshBasicMaterial';
  12242. this.color = new Color(0xffffff); // emissive
  12243. this.map = null;
  12244. this.lightMap = null;
  12245. this.lightMapIntensity = 1.0;
  12246. this.aoMap = null;
  12247. this.aoMapIntensity = 1.0;
  12248. this.specularMap = null;
  12249. this.alphaMap = null;
  12250. this.envMap = null;
  12251. this.combine = MultiplyOperation;
  12252. this.reflectivity = 1;
  12253. this.refractionRatio = 0.98;
  12254. this.wireframe = false;
  12255. this.wireframeLinewidth = 1;
  12256. this.wireframeLinecap = 'round';
  12257. this.wireframeLinejoin = 'round';
  12258. this.skinning = false;
  12259. this.morphTargets = false;
  12260. this.setValues(parameters);
  12261. }
  12262. MeshBasicMaterial.prototype = Object.create(Material.prototype);
  12263. MeshBasicMaterial.prototype.constructor = MeshBasicMaterial;
  12264. MeshBasicMaterial.prototype.isMeshBasicMaterial = true;
  12265. MeshBasicMaterial.prototype.copy = function (source) {
  12266. Material.prototype.copy.call(this, source);
  12267. this.color.copy(source.color);
  12268. this.map = source.map;
  12269. this.lightMap = source.lightMap;
  12270. this.lightMapIntensity = source.lightMapIntensity;
  12271. this.aoMap = source.aoMap;
  12272. this.aoMapIntensity = source.aoMapIntensity;
  12273. this.specularMap = source.specularMap;
  12274. this.alphaMap = source.alphaMap;
  12275. this.envMap = source.envMap;
  12276. this.combine = source.combine;
  12277. this.reflectivity = source.reflectivity;
  12278. this.refractionRatio = source.refractionRatio;
  12279. this.wireframe = source.wireframe;
  12280. this.wireframeLinewidth = source.wireframeLinewidth;
  12281. this.wireframeLinecap = source.wireframeLinecap;
  12282. this.wireframeLinejoin = source.wireframeLinejoin;
  12283. this.skinning = source.skinning;
  12284. this.morphTargets = source.morphTargets;
  12285. return this;
  12286. };
  12287. var _vector$3 = new Vector3();
  12288. var _vector2$1 = new Vector2();
  12289. function BufferAttribute(array, itemSize, normalized) {
  12290. if (Array.isArray(array)) {
  12291. throw new TypeError('THREE.BufferAttribute: array should be a Typed Array.');
  12292. }
  12293. this.name = '';
  12294. this.array = array;
  12295. this.itemSize = itemSize;
  12296. this.count = array !== undefined ? array.length / itemSize : 0;
  12297. this.normalized = normalized === true;
  12298. this.usage = StaticDrawUsage;
  12299. this.updateRange = {
  12300. offset: 0,
  12301. count: -1
  12302. };
  12303. this.version = 0;
  12304. }
  12305. Object.defineProperty(BufferAttribute.prototype, 'needsUpdate', {
  12306. set: function set(value) {
  12307. if (value === true) this.version++;
  12308. }
  12309. });
  12310. Object.assign(BufferAttribute.prototype, {
  12311. isBufferAttribute: true,
  12312. onUploadCallback: function onUploadCallback() {},
  12313. setUsage: function setUsage(value) {
  12314. this.usage = value;
  12315. return this;
  12316. },
  12317. copy: function copy(source) {
  12318. this.name = source.name;
  12319. this.array = new source.array.constructor(source.array);
  12320. this.itemSize = source.itemSize;
  12321. this.count = source.count;
  12322. this.normalized = source.normalized;
  12323. this.usage = source.usage;
  12324. return this;
  12325. },
  12326. copyAt: function copyAt(index1, attribute, index2) {
  12327. index1 *= this.itemSize;
  12328. index2 *= attribute.itemSize;
  12329. for (var i = 0, l = this.itemSize; i < l; i++) {
  12330. this.array[index1 + i] = attribute.array[index2 + i];
  12331. }
  12332. return this;
  12333. },
  12334. copyArray: function copyArray(array) {
  12335. this.array.set(array);
  12336. return this;
  12337. },
  12338. copyColorsArray: function copyColorsArray(colors) {
  12339. var array = this.array;
  12340. var offset = 0;
  12341. for (var i = 0, l = colors.length; i < l; i++) {
  12342. var color = colors[i];
  12343. if (color === undefined) {
  12344. console.warn('THREE.BufferAttribute.copyColorsArray(): color is undefined', i);
  12345. color = new Color();
  12346. }
  12347. array[offset++] = color.r;
  12348. array[offset++] = color.g;
  12349. array[offset++] = color.b;
  12350. }
  12351. return this;
  12352. },
  12353. copyVector2sArray: function copyVector2sArray(vectors) {
  12354. var array = this.array;
  12355. var offset = 0;
  12356. for (var i = 0, l = vectors.length; i < l; i++) {
  12357. var vector = vectors[i];
  12358. if (vector === undefined) {
  12359. console.warn('THREE.BufferAttribute.copyVector2sArray(): vector is undefined', i);
  12360. vector = new Vector2();
  12361. }
  12362. array[offset++] = vector.x;
  12363. array[offset++] = vector.y;
  12364. }
  12365. return this;
  12366. },
  12367. copyVector3sArray: function copyVector3sArray(vectors) {
  12368. var array = this.array;
  12369. var offset = 0;
  12370. for (var i = 0, l = vectors.length; i < l; i++) {
  12371. var vector = vectors[i];
  12372. if (vector === undefined) {
  12373. console.warn('THREE.BufferAttribute.copyVector3sArray(): vector is undefined', i);
  12374. vector = new Vector3();
  12375. }
  12376. array[offset++] = vector.x;
  12377. array[offset++] = vector.y;
  12378. array[offset++] = vector.z;
  12379. }
  12380. return this;
  12381. },
  12382. copyVector4sArray: function copyVector4sArray(vectors) {
  12383. var array = this.array;
  12384. var offset = 0;
  12385. for (var i = 0, l = vectors.length; i < l; i++) {
  12386. var vector = vectors[i];
  12387. if (vector === undefined) {
  12388. console.warn('THREE.BufferAttribute.copyVector4sArray(): vector is undefined', i);
  12389. vector = new Vector4();
  12390. }
  12391. array[offset++] = vector.x;
  12392. array[offset++] = vector.y;
  12393. array[offset++] = vector.z;
  12394. array[offset++] = vector.w;
  12395. }
  12396. return this;
  12397. },
  12398. applyMatrix3: function applyMatrix3(m) {
  12399. if (this.itemSize === 2) {
  12400. for (var i = 0, l = this.count; i < l; i++) {
  12401. _vector2$1.fromBufferAttribute(this, i);
  12402. _vector2$1.applyMatrix3(m);
  12403. this.setXY(i, _vector2$1.x, _vector2$1.y);
  12404. }
  12405. } else if (this.itemSize === 3) {
  12406. for (var _i = 0, _l = this.count; _i < _l; _i++) {
  12407. _vector$3.fromBufferAttribute(this, _i);
  12408. _vector$3.applyMatrix3(m);
  12409. this.setXYZ(_i, _vector$3.x, _vector$3.y, _vector$3.z);
  12410. }
  12411. }
  12412. return this;
  12413. },
  12414. applyMatrix4: function applyMatrix4(m) {
  12415. for (var i = 0, l = this.count; i < l; i++) {
  12416. _vector$3.x = this.getX(i);
  12417. _vector$3.y = this.getY(i);
  12418. _vector$3.z = this.getZ(i);
  12419. _vector$3.applyMatrix4(m);
  12420. this.setXYZ(i, _vector$3.x, _vector$3.y, _vector$3.z);
  12421. }
  12422. return this;
  12423. },
  12424. applyNormalMatrix: function applyNormalMatrix(m) {
  12425. for (var i = 0, l = this.count; i < l; i++) {
  12426. _vector$3.x = this.getX(i);
  12427. _vector$3.y = this.getY(i);
  12428. _vector$3.z = this.getZ(i);
  12429. _vector$3.applyNormalMatrix(m);
  12430. this.setXYZ(i, _vector$3.x, _vector$3.y, _vector$3.z);
  12431. }
  12432. return this;
  12433. },
  12434. transformDirection: function transformDirection(m) {
  12435. for (var i = 0, l = this.count; i < l; i++) {
  12436. _vector$3.x = this.getX(i);
  12437. _vector$3.y = this.getY(i);
  12438. _vector$3.z = this.getZ(i);
  12439. _vector$3.transformDirection(m);
  12440. this.setXYZ(i, _vector$3.x, _vector$3.y, _vector$3.z);
  12441. }
  12442. return this;
  12443. },
  12444. set: function set(value, offset) {
  12445. if (offset === void 0) {
  12446. offset = 0;
  12447. }
  12448. this.array.set(value, offset);
  12449. return this;
  12450. },
  12451. getX: function getX(index) {
  12452. return this.array[index * this.itemSize];
  12453. },
  12454. setX: function setX(index, x) {
  12455. this.array[index * this.itemSize] = x;
  12456. return this;
  12457. },
  12458. getY: function getY(index) {
  12459. return this.array[index * this.itemSize + 1];
  12460. },
  12461. setY: function setY(index, y) {
  12462. this.array[index * this.itemSize + 1] = y;
  12463. return this;
  12464. },
  12465. getZ: function getZ(index) {
  12466. return this.array[index * this.itemSize + 2];
  12467. },
  12468. setZ: function setZ(index, z) {
  12469. this.array[index * this.itemSize + 2] = z;
  12470. return this;
  12471. },
  12472. getW: function getW(index) {
  12473. return this.array[index * this.itemSize + 3];
  12474. },
  12475. setW: function setW(index, w) {
  12476. this.array[index * this.itemSize + 3] = w;
  12477. return this;
  12478. },
  12479. setXY: function setXY(index, x, y) {
  12480. index *= this.itemSize;
  12481. this.array[index + 0] = x;
  12482. this.array[index + 1] = y;
  12483. return this;
  12484. },
  12485. setXYZ: function setXYZ(index, x, y, z) {
  12486. index *= this.itemSize;
  12487. this.array[index + 0] = x;
  12488. this.array[index + 1] = y;
  12489. this.array[index + 2] = z;
  12490. return this;
  12491. },
  12492. setXYZW: function setXYZW(index, x, y, z, w) {
  12493. index *= this.itemSize;
  12494. this.array[index + 0] = x;
  12495. this.array[index + 1] = y;
  12496. this.array[index + 2] = z;
  12497. this.array[index + 3] = w;
  12498. return this;
  12499. },
  12500. onUpload: function onUpload(callback) {
  12501. this.onUploadCallback = callback;
  12502. return this;
  12503. },
  12504. clone: function clone() {
  12505. return new this.constructor(this.array, this.itemSize).copy(this);
  12506. },
  12507. toJSON: function toJSON() {
  12508. return {
  12509. itemSize: this.itemSize,
  12510. type: this.array.constructor.name,
  12511. array: Array.prototype.slice.call(this.array),
  12512. normalized: this.normalized
  12513. };
  12514. }
  12515. }); //
  12516. function Int8BufferAttribute(array, itemSize, normalized) {
  12517. BufferAttribute.call(this, new Int8Array(array), itemSize, normalized);
  12518. }
  12519. Int8BufferAttribute.prototype = Object.create(BufferAttribute.prototype);
  12520. Int8BufferAttribute.prototype.constructor = Int8BufferAttribute;
  12521. function Uint8BufferAttribute(array, itemSize, normalized) {
  12522. BufferAttribute.call(this, new Uint8Array(array), itemSize, normalized);
  12523. }
  12524. Uint8BufferAttribute.prototype = Object.create(BufferAttribute.prototype);
  12525. Uint8BufferAttribute.prototype.constructor = Uint8BufferAttribute;
  12526. function Uint8ClampedBufferAttribute(array, itemSize, normalized) {
  12527. BufferAttribute.call(this, new Uint8ClampedArray(array), itemSize, normalized);
  12528. }
  12529. Uint8ClampedBufferAttribute.prototype = Object.create(BufferAttribute.prototype);
  12530. Uint8ClampedBufferAttribute.prototype.constructor = Uint8ClampedBufferAttribute;
  12531. function Int16BufferAttribute(array, itemSize, normalized) {
  12532. BufferAttribute.call(this, new Int16Array(array), itemSize, normalized);
  12533. }
  12534. Int16BufferAttribute.prototype = Object.create(BufferAttribute.prototype);
  12535. Int16BufferAttribute.prototype.constructor = Int16BufferAttribute;
  12536. function Uint16BufferAttribute(array, itemSize, normalized) {
  12537. BufferAttribute.call(this, new Uint16Array(array), itemSize, normalized);
  12538. }
  12539. Uint16BufferAttribute.prototype = Object.create(BufferAttribute.prototype);
  12540. Uint16BufferAttribute.prototype.constructor = Uint16BufferAttribute;
  12541. function Int32BufferAttribute(array, itemSize, normalized) {
  12542. BufferAttribute.call(this, new Int32Array(array), itemSize, normalized);
  12543. }
  12544. Int32BufferAttribute.prototype = Object.create(BufferAttribute.prototype);
  12545. Int32BufferAttribute.prototype.constructor = Int32BufferAttribute;
  12546. function Uint32BufferAttribute(array, itemSize, normalized) {
  12547. BufferAttribute.call(this, new Uint32Array(array), itemSize, normalized);
  12548. }
  12549. Uint32BufferAttribute.prototype = Object.create(BufferAttribute.prototype);
  12550. Uint32BufferAttribute.prototype.constructor = Uint32BufferAttribute;
  12551. function Float16BufferAttribute(array, itemSize, normalized) {
  12552. BufferAttribute.call(this, new Uint16Array(array), itemSize, normalized);
  12553. }
  12554. Float16BufferAttribute.prototype = Object.create(BufferAttribute.prototype);
  12555. Float16BufferAttribute.prototype.constructor = Float16BufferAttribute;
  12556. Float16BufferAttribute.prototype.isFloat16BufferAttribute = true;
  12557. function Float32BufferAttribute(array, itemSize, normalized) {
  12558. BufferAttribute.call(this, new Float32Array(array), itemSize, normalized);
  12559. }
  12560. Float32BufferAttribute.prototype = Object.create(BufferAttribute.prototype);
  12561. Float32BufferAttribute.prototype.constructor = Float32BufferAttribute;
  12562. function Float64BufferAttribute(array, itemSize, normalized) {
  12563. BufferAttribute.call(this, new Float64Array(array), itemSize, normalized);
  12564. }
  12565. Float64BufferAttribute.prototype = Object.create(BufferAttribute.prototype);
  12566. Float64BufferAttribute.prototype.constructor = Float64BufferAttribute; //
  12567. function arrayMax(array) {
  12568. if (array.length === 0) return -Infinity;
  12569. var max = array[0];
  12570. for (var i = 1, l = array.length; i < l; ++i) {
  12571. if (array[i] > max) max = array[i];
  12572. }
  12573. return max;
  12574. }
  12575. var TYPED_ARRAYS = {
  12576. Int8Array: Int8Array,
  12577. Uint8Array: Uint8Array,
  12578. // Workaround for IE11 pre KB2929437. See #11440
  12579. Uint8ClampedArray: typeof Uint8ClampedArray !== 'undefined' ? Uint8ClampedArray : Uint8Array,
  12580. Int16Array: Int16Array,
  12581. Uint16Array: Uint16Array,
  12582. Int32Array: Int32Array,
  12583. Uint32Array: Uint32Array,
  12584. Float32Array: Float32Array,
  12585. Float64Array: Float64Array
  12586. };
  12587. function getTypedArray(type, buffer) {
  12588. return new TYPED_ARRAYS[type](buffer);
  12589. }
  12590. var _id = 0;
  12591. var _m1$2 = new Matrix4();
  12592. var _obj = new Object3D();
  12593. var _offset = new Vector3();
  12594. var _box$2 = new Box3();
  12595. var _boxMorphTargets = new Box3();
  12596. var _vector$4 = new Vector3();
  12597. function BufferGeometry() {
  12598. Object.defineProperty(this, 'id', {
  12599. value: _id++
  12600. });
  12601. this.uuid = MathUtils.generateUUID();
  12602. this.name = '';
  12603. this.type = 'BufferGeometry';
  12604. this.index = null;
  12605. this.attributes = {};
  12606. this.morphAttributes = {};
  12607. this.morphTargetsRelative = false;
  12608. this.groups = [];
  12609. this.boundingBox = null;
  12610. this.boundingSphere = null;
  12611. this.drawRange = {
  12612. start: 0,
  12613. count: Infinity
  12614. };
  12615. this.userData = {};
  12616. }
  12617. BufferGeometry.prototype = Object.assign(Object.create(EventDispatcher.prototype), {
  12618. constructor: BufferGeometry,
  12619. isBufferGeometry: true,
  12620. getIndex: function getIndex() {
  12621. return this.index;
  12622. },
  12623. setIndex: function setIndex(index) {
  12624. if (Array.isArray(index)) {
  12625. this.index = new (arrayMax(index) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute)(index, 1);
  12626. } else {
  12627. this.index = index;
  12628. }
  12629. return this;
  12630. },
  12631. getAttribute: function getAttribute(name) {
  12632. return this.attributes[name];
  12633. },
  12634. setAttribute: function setAttribute(name, attribute) {
  12635. this.attributes[name] = attribute;
  12636. return this;
  12637. },
  12638. deleteAttribute: function deleteAttribute(name) {
  12639. delete this.attributes[name];
  12640. return this;
  12641. },
  12642. hasAttribute: function hasAttribute(name) {
  12643. return this.attributes[name] !== undefined;
  12644. },
  12645. addGroup: function addGroup(start, count, materialIndex) {
  12646. if (materialIndex === void 0) {
  12647. materialIndex = 0;
  12648. }
  12649. this.groups.push({
  12650. start: start,
  12651. count: count,
  12652. materialIndex: materialIndex
  12653. });
  12654. },
  12655. clearGroups: function clearGroups() {
  12656. this.groups = [];
  12657. },
  12658. setDrawRange: function setDrawRange(start, count) {
  12659. this.drawRange.start = start;
  12660. this.drawRange.count = count;
  12661. },
  12662. applyMatrix4: function applyMatrix4(matrix) {
  12663. var position = this.attributes.position;
  12664. if (position !== undefined) {
  12665. position.applyMatrix4(matrix);
  12666. position.needsUpdate = true;
  12667. }
  12668. var normal = this.attributes.normal;
  12669. if (normal !== undefined) {
  12670. var normalMatrix = new Matrix3().getNormalMatrix(matrix);
  12671. normal.applyNormalMatrix(normalMatrix);
  12672. normal.needsUpdate = true;
  12673. }
  12674. var tangent = this.attributes.tangent;
  12675. if (tangent !== undefined) {
  12676. tangent.transformDirection(matrix);
  12677. tangent.needsUpdate = true;
  12678. }
  12679. if (this.boundingBox !== null) {
  12680. this.computeBoundingBox();
  12681. }
  12682. if (this.boundingSphere !== null) {
  12683. this.computeBoundingSphere();
  12684. }
  12685. return this;
  12686. },
  12687. rotateX: function rotateX(angle) {
  12688. // rotate geometry around world x-axis
  12689. _m1$2.makeRotationX(angle);
  12690. this.applyMatrix4(_m1$2);
  12691. return this;
  12692. },
  12693. rotateY: function rotateY(angle) {
  12694. // rotate geometry around world y-axis
  12695. _m1$2.makeRotationY(angle);
  12696. this.applyMatrix4(_m1$2);
  12697. return this;
  12698. },
  12699. rotateZ: function rotateZ(angle) {
  12700. // rotate geometry around world z-axis
  12701. _m1$2.makeRotationZ(angle);
  12702. this.applyMatrix4(_m1$2);
  12703. return this;
  12704. },
  12705. translate: function translate(x, y, z) {
  12706. // translate geometry
  12707. _m1$2.makeTranslation(x, y, z);
  12708. this.applyMatrix4(_m1$2);
  12709. return this;
  12710. },
  12711. scale: function scale(x, y, z) {
  12712. // scale geometry
  12713. _m1$2.makeScale(x, y, z);
  12714. this.applyMatrix4(_m1$2);
  12715. return this;
  12716. },
  12717. lookAt: function lookAt(vector) {
  12718. _obj.lookAt(vector);
  12719. _obj.updateMatrix();
  12720. this.applyMatrix4(_obj.matrix);
  12721. return this;
  12722. },
  12723. center: function center() {
  12724. this.computeBoundingBox();
  12725. this.boundingBox.getCenter(_offset).negate();
  12726. this.translate(_offset.x, _offset.y, _offset.z);
  12727. return this;
  12728. },
  12729. setFromPoints: function setFromPoints(points) {
  12730. var position = [];
  12731. for (var i = 0, l = points.length; i < l; i++) {
  12732. var point = points[i];
  12733. position.push(point.x, point.y, point.z || 0);
  12734. }
  12735. this.setAttribute('position', new Float32BufferAttribute(position, 3));
  12736. return this;
  12737. },
  12738. computeBoundingBox: function computeBoundingBox() {
  12739. if (this.boundingBox === null) {
  12740. this.boundingBox = new Box3();
  12741. }
  12742. var position = this.attributes.position;
  12743. var morphAttributesPosition = this.morphAttributes.position;
  12744. if (position && position.isGLBufferAttribute) {
  12745. console.error('THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box. Alternatively set "mesh.frustumCulled" to "false".', this);
  12746. this.boundingBox.set(new Vector3(-Infinity, -Infinity, -Infinity), new Vector3(+Infinity, +Infinity, +Infinity));
  12747. return;
  12748. }
  12749. if (position !== undefined) {
  12750. this.boundingBox.setFromBufferAttribute(position); // process morph attributes if present
  12751. if (morphAttributesPosition) {
  12752. for (var i = 0, il = morphAttributesPosition.length; i < il; i++) {
  12753. var morphAttribute = morphAttributesPosition[i];
  12754. _box$2.setFromBufferAttribute(morphAttribute);
  12755. if (this.morphTargetsRelative) {
  12756. _vector$4.addVectors(this.boundingBox.min, _box$2.min);
  12757. this.boundingBox.expandByPoint(_vector$4);
  12758. _vector$4.addVectors(this.boundingBox.max, _box$2.max);
  12759. this.boundingBox.expandByPoint(_vector$4);
  12760. } else {
  12761. this.boundingBox.expandByPoint(_box$2.min);
  12762. this.boundingBox.expandByPoint(_box$2.max);
  12763. }
  12764. }
  12765. }
  12766. } else {
  12767. this.boundingBox.makeEmpty();
  12768. }
  12769. if (isNaN(this.boundingBox.min.x) || isNaN(this.boundingBox.min.y) || isNaN(this.boundingBox.min.z)) {
  12770. console.error('THREE.BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this);
  12771. }
  12772. },
  12773. computeBoundingSphere: function computeBoundingSphere() {
  12774. if (this.boundingSphere === null) {
  12775. this.boundingSphere = new Sphere();
  12776. }
  12777. var position = this.attributes.position;
  12778. var morphAttributesPosition = this.morphAttributes.position;
  12779. if (position && position.isGLBufferAttribute) {
  12780. console.error('THREE.BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere. Alternatively set "mesh.frustumCulled" to "false".', this);
  12781. this.boundingSphere.set(new Vector3(), Infinity);
  12782. return;
  12783. }
  12784. if (position) {
  12785. // first, find the center of the bounding sphere
  12786. var center = this.boundingSphere.center;
  12787. _box$2.setFromBufferAttribute(position); // process morph attributes if present
  12788. if (morphAttributesPosition) {
  12789. for (var i = 0, il = morphAttributesPosition.length; i < il; i++) {
  12790. var morphAttribute = morphAttributesPosition[i];
  12791. _boxMorphTargets.setFromBufferAttribute(morphAttribute);
  12792. if (this.morphTargetsRelative) {
  12793. _vector$4.addVectors(_box$2.min, _boxMorphTargets.min);
  12794. _box$2.expandByPoint(_vector$4);
  12795. _vector$4.addVectors(_box$2.max, _boxMorphTargets.max);
  12796. _box$2.expandByPoint(_vector$4);
  12797. } else {
  12798. _box$2.expandByPoint(_boxMorphTargets.min);
  12799. _box$2.expandByPoint(_boxMorphTargets.max);
  12800. }
  12801. }
  12802. }
  12803. _box$2.getCenter(center); // second, try to find a boundingSphere with a radius smaller than the
  12804. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  12805. var maxRadiusSq = 0;
  12806. for (var _i = 0, _il = position.count; _i < _il; _i++) {
  12807. _vector$4.fromBufferAttribute(position, _i);
  12808. maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(_vector$4));
  12809. } // process morph attributes if present
  12810. if (morphAttributesPosition) {
  12811. for (var _i2 = 0, _il2 = morphAttributesPosition.length; _i2 < _il2; _i2++) {
  12812. var _morphAttribute = morphAttributesPosition[_i2];
  12813. var morphTargetsRelative = this.morphTargetsRelative;
  12814. for (var j = 0, jl = _morphAttribute.count; j < jl; j++) {
  12815. _vector$4.fromBufferAttribute(_morphAttribute, j);
  12816. if (morphTargetsRelative) {
  12817. _offset.fromBufferAttribute(position, j);
  12818. _vector$4.add(_offset);
  12819. }
  12820. maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(_vector$4));
  12821. }
  12822. }
  12823. }
  12824. this.boundingSphere.radius = Math.sqrt(maxRadiusSq);
  12825. if (isNaN(this.boundingSphere.radius)) {
  12826. console.error('THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this);
  12827. }
  12828. }
  12829. },
  12830. computeFaceNormals: function computeFaceNormals() {// backwards compatibility
  12831. },
  12832. computeTangents: function computeTangents() {
  12833. var index = this.index;
  12834. var attributes = this.attributes; // based on http://www.terathon.com/code/tangent.html
  12835. // (per vertex tangents)
  12836. if (index === null || attributes.position === undefined || attributes.normal === undefined || attributes.uv === undefined) {
  12837. console.error('THREE.BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)');
  12838. return;
  12839. }
  12840. var indices = index.array;
  12841. var positions = attributes.position.array;
  12842. var normals = attributes.normal.array;
  12843. var uvs = attributes.uv.array;
  12844. var nVertices = positions.length / 3;
  12845. if (attributes.tangent === undefined) {
  12846. this.setAttribute('tangent', new BufferAttribute(new Float32Array(4 * nVertices), 4));
  12847. }
  12848. var tangents = attributes.tangent.array;
  12849. var tan1 = [],
  12850. tan2 = [];
  12851. for (var i = 0; i < nVertices; i++) {
  12852. tan1[i] = new Vector3();
  12853. tan2[i] = new Vector3();
  12854. }
  12855. var vA = new Vector3(),
  12856. vB = new Vector3(),
  12857. vC = new Vector3(),
  12858. uvA = new Vector2(),
  12859. uvB = new Vector2(),
  12860. uvC = new Vector2(),
  12861. sdir = new Vector3(),
  12862. tdir = new Vector3();
  12863. function handleTriangle(a, b, c) {
  12864. vA.fromArray(positions, a * 3);
  12865. vB.fromArray(positions, b * 3);
  12866. vC.fromArray(positions, c * 3);
  12867. uvA.fromArray(uvs, a * 2);
  12868. uvB.fromArray(uvs, b * 2);
  12869. uvC.fromArray(uvs, c * 2);
  12870. vB.sub(vA);
  12871. vC.sub(vA);
  12872. uvB.sub(uvA);
  12873. uvC.sub(uvA);
  12874. var r = 1.0 / (uvB.x * uvC.y - uvC.x * uvB.y); // silently ignore degenerate uv triangles having coincident or colinear vertices
  12875. if (!isFinite(r)) return;
  12876. sdir.copy(vB).multiplyScalar(uvC.y).addScaledVector(vC, -uvB.y).multiplyScalar(r);
  12877. tdir.copy(vC).multiplyScalar(uvB.x).addScaledVector(vB, -uvC.x).multiplyScalar(r);
  12878. tan1[a].add(sdir);
  12879. tan1[b].add(sdir);
  12880. tan1[c].add(sdir);
  12881. tan2[a].add(tdir);
  12882. tan2[b].add(tdir);
  12883. tan2[c].add(tdir);
  12884. }
  12885. var groups = this.groups;
  12886. if (groups.length === 0) {
  12887. groups = [{
  12888. start: 0,
  12889. count: indices.length
  12890. }];
  12891. }
  12892. for (var _i3 = 0, il = groups.length; _i3 < il; ++_i3) {
  12893. var group = groups[_i3];
  12894. var start = group.start;
  12895. var count = group.count;
  12896. for (var j = start, jl = start + count; j < jl; j += 3) {
  12897. handleTriangle(indices[j + 0], indices[j + 1], indices[j + 2]);
  12898. }
  12899. }
  12900. var tmp = new Vector3(),
  12901. tmp2 = new Vector3();
  12902. var n = new Vector3(),
  12903. n2 = new Vector3();
  12904. function handleVertex(v) {
  12905. n.fromArray(normals, v * 3);
  12906. n2.copy(n);
  12907. var t = tan1[v]; // Gram-Schmidt orthogonalize
  12908. tmp.copy(t);
  12909. tmp.sub(n.multiplyScalar(n.dot(t))).normalize(); // Calculate handedness
  12910. tmp2.crossVectors(n2, t);
  12911. var test = tmp2.dot(tan2[v]);
  12912. var w = test < 0.0 ? -1.0 : 1.0;
  12913. tangents[v * 4] = tmp.x;
  12914. tangents[v * 4 + 1] = tmp.y;
  12915. tangents[v * 4 + 2] = tmp.z;
  12916. tangents[v * 4 + 3] = w;
  12917. }
  12918. for (var _i4 = 0, _il3 = groups.length; _i4 < _il3; ++_i4) {
  12919. var _group = groups[_i4];
  12920. var _start = _group.start;
  12921. var _count = _group.count;
  12922. for (var _j = _start, _jl = _start + _count; _j < _jl; _j += 3) {
  12923. handleVertex(indices[_j + 0]);
  12924. handleVertex(indices[_j + 1]);
  12925. handleVertex(indices[_j + 2]);
  12926. }
  12927. }
  12928. },
  12929. computeVertexNormals: function computeVertexNormals() {
  12930. var index = this.index;
  12931. var positionAttribute = this.getAttribute('position');
  12932. if (positionAttribute !== undefined) {
  12933. var normalAttribute = this.getAttribute('normal');
  12934. if (normalAttribute === undefined) {
  12935. normalAttribute = new BufferAttribute(new Float32Array(positionAttribute.count * 3), 3);
  12936. this.setAttribute('normal', normalAttribute);
  12937. } else {
  12938. // reset existing normals to zero
  12939. for (var i = 0, il = normalAttribute.count; i < il; i++) {
  12940. normalAttribute.setXYZ(i, 0, 0, 0);
  12941. }
  12942. }
  12943. var pA = new Vector3(),
  12944. pB = new Vector3(),
  12945. pC = new Vector3();
  12946. var nA = new Vector3(),
  12947. nB = new Vector3(),
  12948. nC = new Vector3();
  12949. var cb = new Vector3(),
  12950. ab = new Vector3(); // indexed elements
  12951. if (index) {
  12952. for (var _i5 = 0, _il4 = index.count; _i5 < _il4; _i5 += 3) {
  12953. var vA = index.getX(_i5 + 0);
  12954. var vB = index.getX(_i5 + 1);
  12955. var vC = index.getX(_i5 + 2);
  12956. pA.fromBufferAttribute(positionAttribute, vA);
  12957. pB.fromBufferAttribute(positionAttribute, vB);
  12958. pC.fromBufferAttribute(positionAttribute, vC);
  12959. cb.subVectors(pC, pB);
  12960. ab.subVectors(pA, pB);
  12961. cb.cross(ab);
  12962. nA.fromBufferAttribute(normalAttribute, vA);
  12963. nB.fromBufferAttribute(normalAttribute, vB);
  12964. nC.fromBufferAttribute(normalAttribute, vC);
  12965. nA.add(cb);
  12966. nB.add(cb);
  12967. nC.add(cb);
  12968. normalAttribute.setXYZ(vA, nA.x, nA.y, nA.z);
  12969. normalAttribute.setXYZ(vB, nB.x, nB.y, nB.z);
  12970. normalAttribute.setXYZ(vC, nC.x, nC.y, nC.z);
  12971. }
  12972. } else {
  12973. // non-indexed elements (unconnected triangle soup)
  12974. for (var _i6 = 0, _il5 = positionAttribute.count; _i6 < _il5; _i6 += 3) {
  12975. pA.fromBufferAttribute(positionAttribute, _i6 + 0);
  12976. pB.fromBufferAttribute(positionAttribute, _i6 + 1);
  12977. pC.fromBufferAttribute(positionAttribute, _i6 + 2);
  12978. cb.subVectors(pC, pB);
  12979. ab.subVectors(pA, pB);
  12980. cb.cross(ab);
  12981. normalAttribute.setXYZ(_i6 + 0, cb.x, cb.y, cb.z);
  12982. normalAttribute.setXYZ(_i6 + 1, cb.x, cb.y, cb.z);
  12983. normalAttribute.setXYZ(_i6 + 2, cb.x, cb.y, cb.z);
  12984. }
  12985. }
  12986. this.normalizeNormals();
  12987. normalAttribute.needsUpdate = true;
  12988. }
  12989. },
  12990. merge: function merge(geometry, offset) {
  12991. if (!(geometry && geometry.isBufferGeometry)) {
  12992. console.error('THREE.BufferGeometry.merge(): geometry not an instance of THREE.BufferGeometry.', geometry);
  12993. return;
  12994. }
  12995. if (offset === undefined) {
  12996. offset = 0;
  12997. console.warn('THREE.BufferGeometry.merge(): Overwriting original geometry, starting at offset=0. ' + 'Use BufferGeometryUtils.mergeBufferGeometries() for lossless merge.');
  12998. }
  12999. var attributes = this.attributes;
  13000. for (var key in attributes) {
  13001. if (geometry.attributes[key] === undefined) continue;
  13002. var attribute1 = attributes[key];
  13003. var attributeArray1 = attribute1.array;
  13004. var attribute2 = geometry.attributes[key];
  13005. var attributeArray2 = attribute2.array;
  13006. var attributeOffset = attribute2.itemSize * offset;
  13007. var length = Math.min(attributeArray2.length, attributeArray1.length - attributeOffset);
  13008. for (var i = 0, j = attributeOffset; i < length; i++, j++) {
  13009. attributeArray1[j] = attributeArray2[i];
  13010. }
  13011. }
  13012. return this;
  13013. },
  13014. normalizeNormals: function normalizeNormals() {
  13015. var normals = this.attributes.normal;
  13016. for (var i = 0, il = normals.count; i < il; i++) {
  13017. _vector$4.fromBufferAttribute(normals, i);
  13018. _vector$4.normalize();
  13019. normals.setXYZ(i, _vector$4.x, _vector$4.y, _vector$4.z);
  13020. }
  13021. },
  13022. toNonIndexed: function toNonIndexed() {
  13023. function convertBufferAttribute(attribute, indices) {
  13024. var array = attribute.array;
  13025. var itemSize = attribute.itemSize;
  13026. var normalized = attribute.normalized;
  13027. var array2 = new array.constructor(indices.length * itemSize);
  13028. var index = 0,
  13029. index2 = 0;
  13030. for (var i = 0, l = indices.length; i < l; i++) {
  13031. index = indices[i] * itemSize;
  13032. for (var j = 0; j < itemSize; j++) {
  13033. array2[index2++] = array[index++];
  13034. }
  13035. }
  13036. return new BufferAttribute(array2, itemSize, normalized);
  13037. } //
  13038. if (this.index === null) {
  13039. console.warn('THREE.BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed.');
  13040. return this;
  13041. }
  13042. var geometry2 = new BufferGeometry();
  13043. var indices = this.index.array;
  13044. var attributes = this.attributes; // attributes
  13045. for (var name in attributes) {
  13046. var attribute = attributes[name];
  13047. var newAttribute = convertBufferAttribute(attribute, indices);
  13048. geometry2.setAttribute(name, newAttribute);
  13049. } // morph attributes
  13050. var morphAttributes = this.morphAttributes;
  13051. for (var _name in morphAttributes) {
  13052. var morphArray = [];
  13053. var morphAttribute = morphAttributes[_name]; // morphAttribute: array of Float32BufferAttributes
  13054. for (var i = 0, il = morphAttribute.length; i < il; i++) {
  13055. var _attribute = morphAttribute[i];
  13056. var _newAttribute = convertBufferAttribute(_attribute, indices);
  13057. morphArray.push(_newAttribute);
  13058. }
  13059. geometry2.morphAttributes[_name] = morphArray;
  13060. }
  13061. geometry2.morphTargetsRelative = this.morphTargetsRelative; // groups
  13062. var groups = this.groups;
  13063. for (var _i7 = 0, l = groups.length; _i7 < l; _i7++) {
  13064. var group = groups[_i7];
  13065. geometry2.addGroup(group.start, group.count, group.materialIndex);
  13066. }
  13067. return geometry2;
  13068. },
  13069. toJSON: function toJSON() {
  13070. var data = {
  13071. metadata: {
  13072. version: 4.5,
  13073. type: 'BufferGeometry',
  13074. generator: 'BufferGeometry.toJSON'
  13075. }
  13076. }; // standard BufferGeometry serialization
  13077. data.uuid = this.uuid;
  13078. data.type = this.type;
  13079. if (this.name !== '') data.name = this.name;
  13080. if (Object.keys(this.userData).length > 0) data.userData = this.userData;
  13081. if (this.parameters !== undefined) {
  13082. var parameters = this.parameters;
  13083. for (var key in parameters) {
  13084. if (parameters[key] !== undefined) data[key] = parameters[key];
  13085. }
  13086. return data;
  13087. }
  13088. data.data = {
  13089. attributes: {}
  13090. };
  13091. var index = this.index;
  13092. if (index !== null) {
  13093. data.data.index = {
  13094. type: index.array.constructor.name,
  13095. array: Array.prototype.slice.call(index.array)
  13096. };
  13097. }
  13098. var attributes = this.attributes;
  13099. for (var _key in attributes) {
  13100. var attribute = attributes[_key];
  13101. var attributeData = attribute.toJSON(data.data);
  13102. if (attribute.name !== '') attributeData.name = attribute.name;
  13103. data.data.attributes[_key] = attributeData;
  13104. }
  13105. var morphAttributes = {};
  13106. var hasMorphAttributes = false;
  13107. for (var _key2 in this.morphAttributes) {
  13108. var attributeArray = this.morphAttributes[_key2];
  13109. var array = [];
  13110. for (var i = 0, il = attributeArray.length; i < il; i++) {
  13111. var _attribute2 = attributeArray[i];
  13112. var _attributeData = _attribute2.toJSON(data.data);
  13113. if (_attribute2.name !== '') _attributeData.name = _attribute2.name;
  13114. array.push(_attributeData);
  13115. }
  13116. if (array.length > 0) {
  13117. morphAttributes[_key2] = array;
  13118. hasMorphAttributes = true;
  13119. }
  13120. }
  13121. if (hasMorphAttributes) {
  13122. data.data.morphAttributes = morphAttributes;
  13123. data.data.morphTargetsRelative = this.morphTargetsRelative;
  13124. }
  13125. var groups = this.groups;
  13126. if (groups.length > 0) {
  13127. data.data.groups = JSON.parse(JSON.stringify(groups));
  13128. }
  13129. var boundingSphere = this.boundingSphere;
  13130. if (boundingSphere !== null) {
  13131. data.data.boundingSphere = {
  13132. center: boundingSphere.center.toArray(),
  13133. radius: boundingSphere.radius
  13134. };
  13135. }
  13136. return data;
  13137. },
  13138. clone: function clone() {
  13139. /*
  13140. // Handle primitives
  13141. const parameters = this.parameters;
  13142. if ( parameters !== undefined ) {
  13143. const values = [];
  13144. for ( const key in parameters ) {
  13145. values.push( parameters[ key ] );
  13146. }
  13147. const geometry = Object.create( this.constructor.prototype );
  13148. this.constructor.apply( geometry, values );
  13149. return geometry;
  13150. }
  13151. return new this.constructor().copy( this );
  13152. */
  13153. return new BufferGeometry().copy(this);
  13154. },
  13155. copy: function copy(source) {
  13156. // reset
  13157. this.index = null;
  13158. this.attributes = {};
  13159. this.morphAttributes = {};
  13160. this.groups = [];
  13161. this.boundingBox = null;
  13162. this.boundingSphere = null; // used for storing cloned, shared data
  13163. var data = {}; // name
  13164. this.name = source.name; // index
  13165. var index = source.index;
  13166. if (index !== null) {
  13167. this.setIndex(index.clone(data));
  13168. } // attributes
  13169. var attributes = source.attributes;
  13170. for (var name in attributes) {
  13171. var attribute = attributes[name];
  13172. this.setAttribute(name, attribute.clone(data));
  13173. } // morph attributes
  13174. var morphAttributes = source.morphAttributes;
  13175. for (var _name2 in morphAttributes) {
  13176. var array = [];
  13177. var morphAttribute = morphAttributes[_name2]; // morphAttribute: array of Float32BufferAttributes
  13178. for (var i = 0, l = morphAttribute.length; i < l; i++) {
  13179. array.push(morphAttribute[i].clone(data));
  13180. }
  13181. this.morphAttributes[_name2] = array;
  13182. }
  13183. this.morphTargetsRelative = source.morphTargetsRelative; // groups
  13184. var groups = source.groups;
  13185. for (var _i8 = 0, _l = groups.length; _i8 < _l; _i8++) {
  13186. var group = groups[_i8];
  13187. this.addGroup(group.start, group.count, group.materialIndex);
  13188. } // bounding box
  13189. var boundingBox = source.boundingBox;
  13190. if (boundingBox !== null) {
  13191. this.boundingBox = boundingBox.clone();
  13192. } // bounding sphere
  13193. var boundingSphere = source.boundingSphere;
  13194. if (boundingSphere !== null) {
  13195. this.boundingSphere = boundingSphere.clone();
  13196. } // draw range
  13197. this.drawRange.start = source.drawRange.start;
  13198. this.drawRange.count = source.drawRange.count; // user data
  13199. this.userData = source.userData;
  13200. return this;
  13201. },
  13202. dispose: function dispose() {
  13203. this.dispatchEvent({
  13204. type: 'dispose'
  13205. });
  13206. }
  13207. });
  13208. var _inverseMatrix = new Matrix4();
  13209. var _ray = new Ray();
  13210. var _sphere = new Sphere();
  13211. var _vA = new Vector3();
  13212. var _vB = new Vector3();
  13213. var _vC = new Vector3();
  13214. var _tempA = new Vector3();
  13215. var _tempB = new Vector3();
  13216. var _tempC = new Vector3();
  13217. var _morphA = new Vector3();
  13218. var _morphB = new Vector3();
  13219. var _morphC = new Vector3();
  13220. var _uvA = new Vector2();
  13221. var _uvB = new Vector2();
  13222. var _uvC = new Vector2();
  13223. var _intersectionPoint = new Vector3();
  13224. var _intersectionPointWorld = new Vector3();
  13225. function Mesh(geometry, material) {
  13226. if (geometry === void 0) {
  13227. geometry = new BufferGeometry();
  13228. }
  13229. if (material === void 0) {
  13230. material = new MeshBasicMaterial();
  13231. }
  13232. Object3D.call(this);
  13233. this.type = 'Mesh';
  13234. this.geometry = geometry;
  13235. this.material = material;
  13236. this.updateMorphTargets();
  13237. }
  13238. Mesh.prototype = Object.assign(Object.create(Object3D.prototype), {
  13239. constructor: Mesh,
  13240. isMesh: true,
  13241. copy: function copy(source) {
  13242. Object3D.prototype.copy.call(this, source);
  13243. if (source.morphTargetInfluences !== undefined) {
  13244. this.morphTargetInfluences = source.morphTargetInfluences.slice();
  13245. }
  13246. if (source.morphTargetDictionary !== undefined) {
  13247. this.morphTargetDictionary = Object.assign({}, source.morphTargetDictionary);
  13248. }
  13249. this.material = source.material;
  13250. this.geometry = source.geometry;
  13251. return this;
  13252. },
  13253. updateMorphTargets: function updateMorphTargets() {
  13254. var geometry = this.geometry;
  13255. if (geometry.isBufferGeometry) {
  13256. var morphAttributes = geometry.morphAttributes;
  13257. var keys = Object.keys(morphAttributes);
  13258. if (keys.length > 0) {
  13259. var morphAttribute = morphAttributes[keys[0]];
  13260. if (morphAttribute !== undefined) {
  13261. this.morphTargetInfluences = [];
  13262. this.morphTargetDictionary = {};
  13263. for (var m = 0, ml = morphAttribute.length; m < ml; m++) {
  13264. var name = morphAttribute[m].name || String(m);
  13265. this.morphTargetInfluences.push(0);
  13266. this.morphTargetDictionary[name] = m;
  13267. }
  13268. }
  13269. }
  13270. } else {
  13271. var morphTargets = geometry.morphTargets;
  13272. if (morphTargets !== undefined && morphTargets.length > 0) {
  13273. console.error('THREE.Mesh.updateMorphTargets() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  13274. }
  13275. }
  13276. },
  13277. raycast: function raycast(raycaster, intersects) {
  13278. var geometry = this.geometry;
  13279. var material = this.material;
  13280. var matrixWorld = this.matrixWorld;
  13281. if (material === undefined) return; // Checking boundingSphere distance to ray
  13282. if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
  13283. _sphere.copy(geometry.boundingSphere);
  13284. _sphere.applyMatrix4(matrixWorld);
  13285. if (raycaster.ray.intersectsSphere(_sphere) === false) return; //
  13286. _inverseMatrix.copy(matrixWorld).invert();
  13287. _ray.copy(raycaster.ray).applyMatrix4(_inverseMatrix); // Check boundingBox before continuing
  13288. if (geometry.boundingBox !== null) {
  13289. if (_ray.intersectsBox(geometry.boundingBox) === false) return;
  13290. }
  13291. var intersection;
  13292. if (geometry.isBufferGeometry) {
  13293. var index = geometry.index;
  13294. var position = geometry.attributes.position;
  13295. var morphPosition = geometry.morphAttributes.position;
  13296. var morphTargetsRelative = geometry.morphTargetsRelative;
  13297. var uv = geometry.attributes.uv;
  13298. var uv2 = geometry.attributes.uv2;
  13299. var groups = geometry.groups;
  13300. var drawRange = geometry.drawRange;
  13301. if (index !== null) {
  13302. // indexed buffer geometry
  13303. if (Array.isArray(material)) {
  13304. for (var i = 0, il = groups.length; i < il; i++) {
  13305. var group = groups[i];
  13306. var groupMaterial = material[group.materialIndex];
  13307. var start = Math.max(group.start, drawRange.start);
  13308. var end = Math.min(group.start + group.count, drawRange.start + drawRange.count);
  13309. for (var j = start, jl = end; j < jl; j += 3) {
  13310. var a = index.getX(j);
  13311. var b = index.getX(j + 1);
  13312. var c = index.getX(j + 2);
  13313. intersection = checkBufferGeometryIntersection(this, groupMaterial, raycaster, _ray, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c);
  13314. if (intersection) {
  13315. intersection.faceIndex = Math.floor(j / 3); // triangle number in indexed buffer semantics
  13316. intersection.face.materialIndex = group.materialIndex;
  13317. intersects.push(intersection);
  13318. }
  13319. }
  13320. }
  13321. } else {
  13322. var _start = Math.max(0, drawRange.start);
  13323. var _end = Math.min(index.count, drawRange.start + drawRange.count);
  13324. for (var _i = _start, _il = _end; _i < _il; _i += 3) {
  13325. var _a = index.getX(_i);
  13326. var _b = index.getX(_i + 1);
  13327. var _c = index.getX(_i + 2);
  13328. intersection = checkBufferGeometryIntersection(this, material, raycaster, _ray, position, morphPosition, morphTargetsRelative, uv, uv2, _a, _b, _c);
  13329. if (intersection) {
  13330. intersection.faceIndex = Math.floor(_i / 3); // triangle number in indexed buffer semantics
  13331. intersects.push(intersection);
  13332. }
  13333. }
  13334. }
  13335. } else if (position !== undefined) {
  13336. // non-indexed buffer geometry
  13337. if (Array.isArray(material)) {
  13338. for (var _i2 = 0, _il2 = groups.length; _i2 < _il2; _i2++) {
  13339. var _group = groups[_i2];
  13340. var _groupMaterial = material[_group.materialIndex];
  13341. var _start2 = Math.max(_group.start, drawRange.start);
  13342. var _end2 = Math.min(_group.start + _group.count, drawRange.start + drawRange.count);
  13343. for (var _j = _start2, _jl = _end2; _j < _jl; _j += 3) {
  13344. var _a2 = _j;
  13345. var _b2 = _j + 1;
  13346. var _c2 = _j + 2;
  13347. intersection = checkBufferGeometryIntersection(this, _groupMaterial, raycaster, _ray, position, morphPosition, morphTargetsRelative, uv, uv2, _a2, _b2, _c2);
  13348. if (intersection) {
  13349. intersection.faceIndex = Math.floor(_j / 3); // triangle number in non-indexed buffer semantics
  13350. intersection.face.materialIndex = _group.materialIndex;
  13351. intersects.push(intersection);
  13352. }
  13353. }
  13354. }
  13355. } else {
  13356. var _start3 = Math.max(0, drawRange.start);
  13357. var _end3 = Math.min(position.count, drawRange.start + drawRange.count);
  13358. for (var _i3 = _start3, _il3 = _end3; _i3 < _il3; _i3 += 3) {
  13359. var _a3 = _i3;
  13360. var _b3 = _i3 + 1;
  13361. var _c3 = _i3 + 2;
  13362. intersection = checkBufferGeometryIntersection(this, material, raycaster, _ray, position, morphPosition, morphTargetsRelative, uv, uv2, _a3, _b3, _c3);
  13363. if (intersection) {
  13364. intersection.faceIndex = Math.floor(_i3 / 3); // triangle number in non-indexed buffer semantics
  13365. intersects.push(intersection);
  13366. }
  13367. }
  13368. }
  13369. }
  13370. } else if (geometry.isGeometry) {
  13371. console.error('THREE.Mesh.raycast() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  13372. }
  13373. }
  13374. });
  13375. function checkIntersection(object, material, raycaster, ray, pA, pB, pC, point) {
  13376. var intersect;
  13377. if (material.side === BackSide) {
  13378. intersect = ray.intersectTriangle(pC, pB, pA, true, point);
  13379. } else {
  13380. intersect = ray.intersectTriangle(pA, pB, pC, material.side !== DoubleSide, point);
  13381. }
  13382. if (intersect === null) return null;
  13383. _intersectionPointWorld.copy(point);
  13384. _intersectionPointWorld.applyMatrix4(object.matrixWorld);
  13385. var distance = raycaster.ray.origin.distanceTo(_intersectionPointWorld);
  13386. if (distance < raycaster.near || distance > raycaster.far) return null;
  13387. return {
  13388. distance: distance,
  13389. point: _intersectionPointWorld.clone(),
  13390. object: object
  13391. };
  13392. }
  13393. function checkBufferGeometryIntersection(object, material, raycaster, ray, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c) {
  13394. _vA.fromBufferAttribute(position, a);
  13395. _vB.fromBufferAttribute(position, b);
  13396. _vC.fromBufferAttribute(position, c);
  13397. var morphInfluences = object.morphTargetInfluences;
  13398. if (material.morphTargets && morphPosition && morphInfluences) {
  13399. _morphA.set(0, 0, 0);
  13400. _morphB.set(0, 0, 0);
  13401. _morphC.set(0, 0, 0);
  13402. for (var i = 0, il = morphPosition.length; i < il; i++) {
  13403. var influence = morphInfluences[i];
  13404. var morphAttribute = morphPosition[i];
  13405. if (influence === 0) continue;
  13406. _tempA.fromBufferAttribute(morphAttribute, a);
  13407. _tempB.fromBufferAttribute(morphAttribute, b);
  13408. _tempC.fromBufferAttribute(morphAttribute, c);
  13409. if (morphTargetsRelative) {
  13410. _morphA.addScaledVector(_tempA, influence);
  13411. _morphB.addScaledVector(_tempB, influence);
  13412. _morphC.addScaledVector(_tempC, influence);
  13413. } else {
  13414. _morphA.addScaledVector(_tempA.sub(_vA), influence);
  13415. _morphB.addScaledVector(_tempB.sub(_vB), influence);
  13416. _morphC.addScaledVector(_tempC.sub(_vC), influence);
  13417. }
  13418. }
  13419. _vA.add(_morphA);
  13420. _vB.add(_morphB);
  13421. _vC.add(_morphC);
  13422. }
  13423. if (object.isSkinnedMesh) {
  13424. object.boneTransform(a, _vA);
  13425. object.boneTransform(b, _vB);
  13426. object.boneTransform(c, _vC);
  13427. }
  13428. var intersection = checkIntersection(object, material, raycaster, ray, _vA, _vB, _vC, _intersectionPoint);
  13429. if (intersection) {
  13430. if (uv) {
  13431. _uvA.fromBufferAttribute(uv, a);
  13432. _uvB.fromBufferAttribute(uv, b);
  13433. _uvC.fromBufferAttribute(uv, c);
  13434. intersection.uv = Triangle.getUV(_intersectionPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2());
  13435. }
  13436. if (uv2) {
  13437. _uvA.fromBufferAttribute(uv2, a);
  13438. _uvB.fromBufferAttribute(uv2, b);
  13439. _uvC.fromBufferAttribute(uv2, c);
  13440. intersection.uv2 = Triangle.getUV(_intersectionPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2());
  13441. }
  13442. var face = new Face3(a, b, c);
  13443. Triangle.getNormal(_vA, _vB, _vC, face.normal);
  13444. intersection.face = face;
  13445. }
  13446. return intersection;
  13447. }
  13448. var BoxGeometry = /*#__PURE__*/function (_BufferGeometry) {
  13449. _inheritsLoose(BoxGeometry, _BufferGeometry);
  13450. function BoxGeometry(width, height, depth, widthSegments, heightSegments, depthSegments) {
  13451. var _this;
  13452. if (width === void 0) {
  13453. width = 1;
  13454. }
  13455. if (height === void 0) {
  13456. height = 1;
  13457. }
  13458. if (depth === void 0) {
  13459. depth = 1;
  13460. }
  13461. if (widthSegments === void 0) {
  13462. widthSegments = 1;
  13463. }
  13464. if (heightSegments === void 0) {
  13465. heightSegments = 1;
  13466. }
  13467. if (depthSegments === void 0) {
  13468. depthSegments = 1;
  13469. }
  13470. _this = _BufferGeometry.call(this) || this;
  13471. _this.type = 'BoxGeometry';
  13472. _this.parameters = {
  13473. width: width,
  13474. height: height,
  13475. depth: depth,
  13476. widthSegments: widthSegments,
  13477. heightSegments: heightSegments,
  13478. depthSegments: depthSegments
  13479. };
  13480. var scope = _assertThisInitialized(_this); // segments
  13481. widthSegments = Math.floor(widthSegments);
  13482. heightSegments = Math.floor(heightSegments);
  13483. depthSegments = Math.floor(depthSegments); // buffers
  13484. var indices = [];
  13485. var vertices = [];
  13486. var normals = [];
  13487. var uvs = []; // helper variables
  13488. var numberOfVertices = 0;
  13489. var groupStart = 0; // build each side of the box geometry
  13490. buildPlane('z', 'y', 'x', -1, -1, depth, height, width, depthSegments, heightSegments, 0); // px
  13491. buildPlane('z', 'y', 'x', 1, -1, depth, height, -width, depthSegments, heightSegments, 1); // nx
  13492. buildPlane('x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2); // py
  13493. buildPlane('x', 'z', 'y', 1, -1, width, depth, -height, widthSegments, depthSegments, 3); // ny
  13494. buildPlane('x', 'y', 'z', 1, -1, width, height, depth, widthSegments, heightSegments, 4); // pz
  13495. buildPlane('x', 'y', 'z', -1, -1, width, height, -depth, widthSegments, heightSegments, 5); // nz
  13496. // build geometry
  13497. _this.setIndex(indices);
  13498. _this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  13499. _this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  13500. _this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  13501. function buildPlane(u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex) {
  13502. var segmentWidth = width / gridX;
  13503. var segmentHeight = height / gridY;
  13504. var widthHalf = width / 2;
  13505. var heightHalf = height / 2;
  13506. var depthHalf = depth / 2;
  13507. var gridX1 = gridX + 1;
  13508. var gridY1 = gridY + 1;
  13509. var vertexCounter = 0;
  13510. var groupCount = 0;
  13511. var vector = new Vector3(); // generate vertices, normals and uvs
  13512. for (var iy = 0; iy < gridY1; iy++) {
  13513. var y = iy * segmentHeight - heightHalf;
  13514. for (var ix = 0; ix < gridX1; ix++) {
  13515. var x = ix * segmentWidth - widthHalf; // set values to correct vector component
  13516. vector[u] = x * udir;
  13517. vector[v] = y * vdir;
  13518. vector[w] = depthHalf; // now apply vector to vertex buffer
  13519. vertices.push(vector.x, vector.y, vector.z); // set values to correct vector component
  13520. vector[u] = 0;
  13521. vector[v] = 0;
  13522. vector[w] = depth > 0 ? 1 : -1; // now apply vector to normal buffer
  13523. normals.push(vector.x, vector.y, vector.z); // uvs
  13524. uvs.push(ix / gridX);
  13525. uvs.push(1 - iy / gridY); // counters
  13526. vertexCounter += 1;
  13527. }
  13528. } // indices
  13529. // 1. you need three indices to draw a single face
  13530. // 2. a single segment consists of two faces
  13531. // 3. so we need to generate six (2*3) indices per segment
  13532. for (var _iy = 0; _iy < gridY; _iy++) {
  13533. for (var _ix = 0; _ix < gridX; _ix++) {
  13534. var a = numberOfVertices + _ix + gridX1 * _iy;
  13535. var b = numberOfVertices + _ix + gridX1 * (_iy + 1);
  13536. var c = numberOfVertices + (_ix + 1) + gridX1 * (_iy + 1);
  13537. var d = numberOfVertices + (_ix + 1) + gridX1 * _iy; // faces
  13538. indices.push(a, b, d);
  13539. indices.push(b, c, d); // increase counter
  13540. groupCount += 6;
  13541. }
  13542. } // add a group to the geometry. this will ensure multi material support
  13543. scope.addGroup(groupStart, groupCount, materialIndex); // calculate new start value for groups
  13544. groupStart += groupCount; // update total number of vertices
  13545. numberOfVertices += vertexCounter;
  13546. }
  13547. return _this;
  13548. }
  13549. return BoxGeometry;
  13550. }(BufferGeometry);
  13551. /**
  13552. * Uniform Utilities
  13553. */
  13554. function cloneUniforms(src) {
  13555. var dst = {};
  13556. for (var u in src) {
  13557. dst[u] = {};
  13558. for (var p in src[u]) {
  13559. var property = src[u][p];
  13560. if (property && (property.isColor || property.isMatrix3 || property.isMatrix4 || property.isVector2 || property.isVector3 || property.isVector4 || property.isTexture)) {
  13561. dst[u][p] = property.clone();
  13562. } else if (Array.isArray(property)) {
  13563. dst[u][p] = property.slice();
  13564. } else {
  13565. dst[u][p] = property;
  13566. }
  13567. }
  13568. }
  13569. return dst;
  13570. }
  13571. function mergeUniforms(uniforms) {
  13572. var merged = {};
  13573. for (var u = 0; u < uniforms.length; u++) {
  13574. var tmp = cloneUniforms(uniforms[u]);
  13575. for (var p in tmp) {
  13576. merged[p] = tmp[p];
  13577. }
  13578. }
  13579. return merged;
  13580. } // Legacy
  13581. var UniformsUtils = {
  13582. clone: cloneUniforms,
  13583. merge: mergeUniforms
  13584. };
  13585. var default_vertex = "void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}";
  13586. var default_fragment = "void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}";
  13587. /**
  13588. * parameters = {
  13589. * defines: { "label" : "value" },
  13590. * uniforms: { "parameter1": { value: 1.0 }, "parameter2": { value2: 2 } },
  13591. *
  13592. * fragmentShader: <string>,
  13593. * vertexShader: <string>,
  13594. *
  13595. * wireframe: <boolean>,
  13596. * wireframeLinewidth: <float>,
  13597. *
  13598. * lights: <bool>,
  13599. *
  13600. * skinning: <bool>,
  13601. * morphTargets: <bool>,
  13602. * morphNormals: <bool>
  13603. * }
  13604. */
  13605. function ShaderMaterial(parameters) {
  13606. Material.call(this);
  13607. this.type = 'ShaderMaterial';
  13608. this.defines = {};
  13609. this.uniforms = {};
  13610. this.vertexShader = default_vertex;
  13611. this.fragmentShader = default_fragment;
  13612. this.linewidth = 1;
  13613. this.wireframe = false;
  13614. this.wireframeLinewidth = 1;
  13615. this.fog = false; // set to use scene fog
  13616. this.lights = false; // set to use scene lights
  13617. this.clipping = false; // set to use user-defined clipping planes
  13618. this.skinning = false; // set to use skinning attribute streams
  13619. this.morphTargets = false; // set to use morph targets
  13620. this.morphNormals = false; // set to use morph normals
  13621. this.extensions = {
  13622. derivatives: false,
  13623. // set to use derivatives
  13624. fragDepth: false,
  13625. // set to use fragment depth values
  13626. drawBuffers: false,
  13627. // set to use draw buffers
  13628. shaderTextureLOD: false // set to use shader texture LOD
  13629. }; // When rendered geometry doesn't include these attributes but the material does,
  13630. // use these default values in WebGL. This avoids errors when buffer data is missing.
  13631. this.defaultAttributeValues = {
  13632. 'color': [1, 1, 1],
  13633. 'uv': [0, 0],
  13634. 'uv2': [0, 0]
  13635. };
  13636. this.index0AttributeName = undefined;
  13637. this.uniformsNeedUpdate = false;
  13638. this.glslVersion = null;
  13639. if (parameters !== undefined) {
  13640. if (parameters.attributes !== undefined) {
  13641. console.error('THREE.ShaderMaterial: attributes should now be defined in THREE.BufferGeometry instead.');
  13642. }
  13643. this.setValues(parameters);
  13644. }
  13645. }
  13646. ShaderMaterial.prototype = Object.create(Material.prototype);
  13647. ShaderMaterial.prototype.constructor = ShaderMaterial;
  13648. ShaderMaterial.prototype.isShaderMaterial = true;
  13649. ShaderMaterial.prototype.copy = function (source) {
  13650. Material.prototype.copy.call(this, source);
  13651. this.fragmentShader = source.fragmentShader;
  13652. this.vertexShader = source.vertexShader;
  13653. this.uniforms = cloneUniforms(source.uniforms);
  13654. this.defines = Object.assign({}, source.defines);
  13655. this.wireframe = source.wireframe;
  13656. this.wireframeLinewidth = source.wireframeLinewidth;
  13657. this.lights = source.lights;
  13658. this.clipping = source.clipping;
  13659. this.skinning = source.skinning;
  13660. this.morphTargets = source.morphTargets;
  13661. this.morphNormals = source.morphNormals;
  13662. this.extensions = Object.assign({}, source.extensions);
  13663. this.glslVersion = source.glslVersion;
  13664. return this;
  13665. };
  13666. ShaderMaterial.prototype.toJSON = function (meta) {
  13667. var data = Material.prototype.toJSON.call(this, meta);
  13668. data.glslVersion = this.glslVersion;
  13669. data.uniforms = {};
  13670. for (var name in this.uniforms) {
  13671. var uniform = this.uniforms[name];
  13672. var value = uniform.value;
  13673. if (value && value.isTexture) {
  13674. data.uniforms[name] = {
  13675. type: 't',
  13676. value: value.toJSON(meta).uuid
  13677. };
  13678. } else if (value && value.isColor) {
  13679. data.uniforms[name] = {
  13680. type: 'c',
  13681. value: value.getHex()
  13682. };
  13683. } else if (value && value.isVector2) {
  13684. data.uniforms[name] = {
  13685. type: 'v2',
  13686. value: value.toArray()
  13687. };
  13688. } else if (value && value.isVector3) {
  13689. data.uniforms[name] = {
  13690. type: 'v3',
  13691. value: value.toArray()
  13692. };
  13693. } else if (value && value.isVector4) {
  13694. data.uniforms[name] = {
  13695. type: 'v4',
  13696. value: value.toArray()
  13697. };
  13698. } else if (value && value.isMatrix3) {
  13699. data.uniforms[name] = {
  13700. type: 'm3',
  13701. value: value.toArray()
  13702. };
  13703. } else if (value && value.isMatrix4) {
  13704. data.uniforms[name] = {
  13705. type: 'm4',
  13706. value: value.toArray()
  13707. };
  13708. } else {
  13709. data.uniforms[name] = {
  13710. value: value
  13711. }; // note: the array variants v2v, v3v, v4v, m4v and tv are not supported so far
  13712. }
  13713. }
  13714. if (Object.keys(this.defines).length > 0) data.defines = this.defines;
  13715. data.vertexShader = this.vertexShader;
  13716. data.fragmentShader = this.fragmentShader;
  13717. var extensions = {};
  13718. for (var key in this.extensions) {
  13719. if (this.extensions[key] === true) extensions[key] = true;
  13720. }
  13721. if (Object.keys(extensions).length > 0) data.extensions = extensions;
  13722. return data;
  13723. };
  13724. function Camera() {
  13725. Object3D.call(this);
  13726. this.type = 'Camera';
  13727. this.matrixWorldInverse = new Matrix4();
  13728. this.projectionMatrix = new Matrix4();
  13729. this.projectionMatrixInverse = new Matrix4();
  13730. }
  13731. Camera.prototype = Object.assign(Object.create(Object3D.prototype), {
  13732. constructor: Camera,
  13733. isCamera: true,
  13734. copy: function copy(source, recursive) {
  13735. Object3D.prototype.copy.call(this, source, recursive);
  13736. this.matrixWorldInverse.copy(source.matrixWorldInverse);
  13737. this.projectionMatrix.copy(source.projectionMatrix);
  13738. this.projectionMatrixInverse.copy(source.projectionMatrixInverse);
  13739. return this;
  13740. },
  13741. getWorldDirection: function getWorldDirection(target) {
  13742. if (target === undefined) {
  13743. console.warn('THREE.Camera: .getWorldDirection() target is now required');
  13744. target = new Vector3();
  13745. }
  13746. this.updateWorldMatrix(true, false);
  13747. var e = this.matrixWorld.elements;
  13748. return target.set(-e[8], -e[9], -e[10]).normalize();
  13749. },
  13750. updateMatrixWorld: function updateMatrixWorld(force) {
  13751. Object3D.prototype.updateMatrixWorld.call(this, force);
  13752. this.matrixWorldInverse.copy(this.matrixWorld).invert();
  13753. },
  13754. updateWorldMatrix: function updateWorldMatrix(updateParents, updateChildren) {
  13755. Object3D.prototype.updateWorldMatrix.call(this, updateParents, updateChildren);
  13756. this.matrixWorldInverse.copy(this.matrixWorld).invert();
  13757. },
  13758. clone: function clone() {
  13759. return new this.constructor().copy(this);
  13760. }
  13761. });
  13762. function PerspectiveCamera(fov, aspect, near, far) {
  13763. if (fov === void 0) {
  13764. fov = 50;
  13765. }
  13766. if (aspect === void 0) {
  13767. aspect = 1;
  13768. }
  13769. if (near === void 0) {
  13770. near = 0.1;
  13771. }
  13772. if (far === void 0) {
  13773. far = 2000;
  13774. }
  13775. Camera.call(this);
  13776. this.type = 'PerspectiveCamera';
  13777. this.fov = fov;
  13778. this.zoom = 1;
  13779. this.near = near;
  13780. this.far = far;
  13781. this.focus = 10;
  13782. this.aspect = aspect;
  13783. this.view = null;
  13784. this.filmGauge = 35; // width of the film (default in millimeters)
  13785. this.filmOffset = 0; // horizontal film offset (same unit as gauge)
  13786. this.updateProjectionMatrix();
  13787. }
  13788. PerspectiveCamera.prototype = Object.assign(Object.create(Camera.prototype), {
  13789. constructor: PerspectiveCamera,
  13790. isPerspectiveCamera: true,
  13791. copy: function copy(source, recursive) {
  13792. Camera.prototype.copy.call(this, source, recursive);
  13793. this.fov = source.fov;
  13794. this.zoom = source.zoom;
  13795. this.near = source.near;
  13796. this.far = source.far;
  13797. this.focus = source.focus;
  13798. this.aspect = source.aspect;
  13799. this.view = source.view === null ? null : Object.assign({}, source.view);
  13800. this.filmGauge = source.filmGauge;
  13801. this.filmOffset = source.filmOffset;
  13802. return this;
  13803. },
  13804. /**
  13805. * Sets the FOV by focal length in respect to the current .filmGauge.
  13806. *
  13807. * The default film gauge is 35, so that the focal length can be specified for
  13808. * a 35mm (full frame) camera.
  13809. *
  13810. * Values for focal length and film gauge must have the same unit.
  13811. */
  13812. setFocalLength: function setFocalLength(focalLength) {
  13813. /** see {@link http://www.bobatkins.com/photography/technical/field_of_view.html} */
  13814. var vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
  13815. this.fov = MathUtils.RAD2DEG * 2 * Math.atan(vExtentSlope);
  13816. this.updateProjectionMatrix();
  13817. },
  13818. /**
  13819. * Calculates the focal length from the current .fov and .filmGauge.
  13820. */
  13821. getFocalLength: function getFocalLength() {
  13822. var vExtentSlope = Math.tan(MathUtils.DEG2RAD * 0.5 * this.fov);
  13823. return 0.5 * this.getFilmHeight() / vExtentSlope;
  13824. },
  13825. getEffectiveFOV: function getEffectiveFOV() {
  13826. return MathUtils.RAD2DEG * 2 * Math.atan(Math.tan(MathUtils.DEG2RAD * 0.5 * this.fov) / this.zoom);
  13827. },
  13828. getFilmWidth: function getFilmWidth() {
  13829. // film not completely covered in portrait format (aspect < 1)
  13830. return this.filmGauge * Math.min(this.aspect, 1);
  13831. },
  13832. getFilmHeight: function getFilmHeight() {
  13833. // film not completely covered in landscape format (aspect > 1)
  13834. return this.filmGauge / Math.max(this.aspect, 1);
  13835. },
  13836. /**
  13837. * Sets an offset in a larger frustum. This is useful for multi-window or
  13838. * multi-monitor/multi-machine setups.
  13839. *
  13840. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  13841. * the monitors are in grid like this
  13842. *
  13843. * +---+---+---+
  13844. * | A | B | C |
  13845. * +---+---+---+
  13846. * | D | E | F |
  13847. * +---+---+---+
  13848. *
  13849. * then for each monitor you would call it like this
  13850. *
  13851. * const w = 1920;
  13852. * const h = 1080;
  13853. * const fullWidth = w * 3;
  13854. * const fullHeight = h * 2;
  13855. *
  13856. * --A--
  13857. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  13858. * --B--
  13859. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  13860. * --C--
  13861. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  13862. * --D--
  13863. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  13864. * --E--
  13865. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  13866. * --F--
  13867. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  13868. *
  13869. * Note there is no reason monitors have to be the same size or in a grid.
  13870. */
  13871. setViewOffset: function setViewOffset(fullWidth, fullHeight, x, y, width, height) {
  13872. this.aspect = fullWidth / fullHeight;
  13873. if (this.view === null) {
  13874. this.view = {
  13875. enabled: true,
  13876. fullWidth: 1,
  13877. fullHeight: 1,
  13878. offsetX: 0,
  13879. offsetY: 0,
  13880. width: 1,
  13881. height: 1
  13882. };
  13883. }
  13884. this.view.enabled = true;
  13885. this.view.fullWidth = fullWidth;
  13886. this.view.fullHeight = fullHeight;
  13887. this.view.offsetX = x;
  13888. this.view.offsetY = y;
  13889. this.view.width = width;
  13890. this.view.height = height;
  13891. this.updateProjectionMatrix();
  13892. },
  13893. clearViewOffset: function clearViewOffset() {
  13894. if (this.view !== null) {
  13895. this.view.enabled = false;
  13896. }
  13897. this.updateProjectionMatrix();
  13898. },
  13899. updateProjectionMatrix: function updateProjectionMatrix() {
  13900. var near = this.near;
  13901. var top = near * Math.tan(MathUtils.DEG2RAD * 0.5 * this.fov) / this.zoom;
  13902. var height = 2 * top;
  13903. var width = this.aspect * height;
  13904. var left = -0.5 * width;
  13905. var view = this.view;
  13906. if (this.view !== null && this.view.enabled) {
  13907. var fullWidth = view.fullWidth,
  13908. fullHeight = view.fullHeight;
  13909. left += view.offsetX * width / fullWidth;
  13910. top -= view.offsetY * height / fullHeight;
  13911. width *= view.width / fullWidth;
  13912. height *= view.height / fullHeight;
  13913. }
  13914. var skew = this.filmOffset;
  13915. if (skew !== 0) left += near * skew / this.getFilmWidth();
  13916. this.projectionMatrix.makePerspective(left, left + width, top, top - height, near, this.far);
  13917. this.projectionMatrixInverse.copy(this.projectionMatrix).invert();
  13918. },
  13919. toJSON: function toJSON(meta) {
  13920. var data = Object3D.prototype.toJSON.call(this, meta);
  13921. data.object.fov = this.fov;
  13922. data.object.zoom = this.zoom;
  13923. data.object.near = this.near;
  13924. data.object.far = this.far;
  13925. data.object.focus = this.focus;
  13926. data.object.aspect = this.aspect;
  13927. if (this.view !== null) data.object.view = Object.assign({}, this.view);
  13928. data.object.filmGauge = this.filmGauge;
  13929. data.object.filmOffset = this.filmOffset;
  13930. return data;
  13931. }
  13932. });
  13933. var fov = 90,
  13934. aspect = 1;
  13935. function CubeCamera(near, far, renderTarget) {
  13936. Object3D.call(this);
  13937. this.type = 'CubeCamera';
  13938. if (renderTarget.isWebGLCubeRenderTarget !== true) {
  13939. console.error('THREE.CubeCamera: The constructor now expects an instance of WebGLCubeRenderTarget as third parameter.');
  13940. return;
  13941. }
  13942. this.renderTarget = renderTarget;
  13943. var cameraPX = new PerspectiveCamera(fov, aspect, near, far);
  13944. cameraPX.layers = this.layers;
  13945. cameraPX.up.set(0, -1, 0);
  13946. cameraPX.lookAt(new Vector3(1, 0, 0));
  13947. this.add(cameraPX);
  13948. var cameraNX = new PerspectiveCamera(fov, aspect, near, far);
  13949. cameraNX.layers = this.layers;
  13950. cameraNX.up.set(0, -1, 0);
  13951. cameraNX.lookAt(new Vector3(-1, 0, 0));
  13952. this.add(cameraNX);
  13953. var cameraPY = new PerspectiveCamera(fov, aspect, near, far);
  13954. cameraPY.layers = this.layers;
  13955. cameraPY.up.set(0, 0, 1);
  13956. cameraPY.lookAt(new Vector3(0, 1, 0));
  13957. this.add(cameraPY);
  13958. var cameraNY = new PerspectiveCamera(fov, aspect, near, far);
  13959. cameraNY.layers = this.layers;
  13960. cameraNY.up.set(0, 0, -1);
  13961. cameraNY.lookAt(new Vector3(0, -1, 0));
  13962. this.add(cameraNY);
  13963. var cameraPZ = new PerspectiveCamera(fov, aspect, near, far);
  13964. cameraPZ.layers = this.layers;
  13965. cameraPZ.up.set(0, -1, 0);
  13966. cameraPZ.lookAt(new Vector3(0, 0, 1));
  13967. this.add(cameraPZ);
  13968. var cameraNZ = new PerspectiveCamera(fov, aspect, near, far);
  13969. cameraNZ.layers = this.layers;
  13970. cameraNZ.up.set(0, -1, 0);
  13971. cameraNZ.lookAt(new Vector3(0, 0, -1));
  13972. this.add(cameraNZ);
  13973. this.update = function (renderer, scene) {
  13974. if (this.parent === null) this.updateMatrixWorld();
  13975. var currentXrEnabled = renderer.xr.enabled;
  13976. var currentRenderTarget = renderer.getRenderTarget();
  13977. renderer.xr.enabled = false;
  13978. var generateMipmaps = renderTarget.texture.generateMipmaps;
  13979. renderTarget.texture.generateMipmaps = false;
  13980. renderer.setRenderTarget(renderTarget, 0);
  13981. renderer.render(scene, cameraPX);
  13982. renderer.setRenderTarget(renderTarget, 1);
  13983. renderer.render(scene, cameraNX);
  13984. renderer.setRenderTarget(renderTarget, 2);
  13985. renderer.render(scene, cameraPY);
  13986. renderer.setRenderTarget(renderTarget, 3);
  13987. renderer.render(scene, cameraNY);
  13988. renderer.setRenderTarget(renderTarget, 4);
  13989. renderer.render(scene, cameraPZ);
  13990. renderTarget.texture.generateMipmaps = generateMipmaps;
  13991. renderer.setRenderTarget(renderTarget, 5);
  13992. renderer.render(scene, cameraNZ);
  13993. renderer.setRenderTarget(currentRenderTarget);
  13994. renderer.xr.enabled = currentXrEnabled;
  13995. };
  13996. }
  13997. CubeCamera.prototype = Object.create(Object3D.prototype);
  13998. CubeCamera.prototype.constructor = CubeCamera;
  13999. function CubeTexture(images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding) {
  14000. images = images !== undefined ? images : [];
  14001. mapping = mapping !== undefined ? mapping : CubeReflectionMapping;
  14002. format = format !== undefined ? format : RGBFormat;
  14003. Texture.call(this, images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding);
  14004. this.flipY = false; // Why CubeTexture._needsFlipEnvMap is necessary:
  14005. //
  14006. // By convention -- likely based on the RenderMan spec from the 1990's -- cube maps are specified by WebGL (and three.js)
  14007. // in a coordinate system in which positive-x is to the right when looking up the positive-z axis -- in other words,
  14008. // in a left-handed coordinate system. By continuing this convention, preexisting cube maps continued to render correctly.
  14009. // three.js uses a right-handed coordinate system. So environment maps used in three.js appear to have px and nx swapped
  14010. // and the flag _needsFlipEnvMap controls this conversion. The flip is not required (and thus _needsFlipEnvMap is set to false)
  14011. // when using WebGLCubeRenderTarget.texture as a cube texture.
  14012. this._needsFlipEnvMap = true;
  14013. }
  14014. CubeTexture.prototype = Object.create(Texture.prototype);
  14015. CubeTexture.prototype.constructor = CubeTexture;
  14016. CubeTexture.prototype.isCubeTexture = true;
  14017. Object.defineProperty(CubeTexture.prototype, 'images', {
  14018. get: function get() {
  14019. return this.image;
  14020. },
  14021. set: function set(value) {
  14022. this.image = value;
  14023. }
  14024. });
  14025. var WebGLCubeRenderTarget = /*#__PURE__*/function (_WebGLRenderTarget) {
  14026. _inheritsLoose(WebGLCubeRenderTarget, _WebGLRenderTarget);
  14027. function WebGLCubeRenderTarget(size, options, dummy) {
  14028. var _this;
  14029. if (Number.isInteger(options)) {
  14030. console.warn('THREE.WebGLCubeRenderTarget: constructor signature is now WebGLCubeRenderTarget( size, options )');
  14031. options = dummy;
  14032. }
  14033. _this = _WebGLRenderTarget.call(this, size, size, options) || this;
  14034. Object.defineProperty(_assertThisInitialized(_this), 'isWebGLCubeRenderTarget', {
  14035. value: true
  14036. });
  14037. options = options || {};
  14038. _this.texture = new CubeTexture(undefined, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding);
  14039. _this.texture._needsFlipEnvMap = false;
  14040. return _this;
  14041. }
  14042. var _proto = WebGLCubeRenderTarget.prototype;
  14043. _proto.fromEquirectangularTexture = function fromEquirectangularTexture(renderer, texture) {
  14044. this.texture.type = texture.type;
  14045. this.texture.format = RGBAFormat; // see #18859
  14046. this.texture.encoding = texture.encoding;
  14047. this.texture.generateMipmaps = texture.generateMipmaps;
  14048. this.texture.minFilter = texture.minFilter;
  14049. this.texture.magFilter = texture.magFilter;
  14050. var shader = {
  14051. uniforms: {
  14052. tEquirect: {
  14053. value: null
  14054. }
  14055. },
  14056. vertexShader:
  14057. /* glsl */
  14058. "\n\n\t\t\t\tvarying vec3 vWorldDirection;\n\n\t\t\t\tvec3 transformDirection( in vec3 dir, in mat4 matrix ) {\n\n\t\t\t\t\treturn normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\n\n\t\t\t\t}\n\n\t\t\t\tvoid main() {\n\n\t\t\t\t\tvWorldDirection = transformDirection( position, modelMatrix );\n\n\t\t\t\t\t#include <begin_vertex>\n\t\t\t\t\t#include <project_vertex>\n\n\t\t\t\t}\n\t\t\t",
  14059. fragmentShader:
  14060. /* glsl */
  14061. "\n\n\t\t\t\tuniform sampler2D tEquirect;\n\n\t\t\t\tvarying vec3 vWorldDirection;\n\n\t\t\t\t#include <common>\n\n\t\t\t\tvoid main() {\n\n\t\t\t\t\tvec3 direction = normalize( vWorldDirection );\n\n\t\t\t\t\tvec2 sampleUV = equirectUv( direction );\n\n\t\t\t\t\tgl_FragColor = texture2D( tEquirect, sampleUV );\n\n\t\t\t\t}\n\t\t\t"
  14062. };
  14063. var geometry = new BoxGeometry(5, 5, 5);
  14064. var material = new ShaderMaterial({
  14065. name: 'CubemapFromEquirect',
  14066. uniforms: cloneUniforms(shader.uniforms),
  14067. vertexShader: shader.vertexShader,
  14068. fragmentShader: shader.fragmentShader,
  14069. side: BackSide,
  14070. blending: NoBlending
  14071. });
  14072. material.uniforms.tEquirect.value = texture;
  14073. var mesh = new Mesh(geometry, material);
  14074. var currentMinFilter = texture.minFilter; // Avoid blurred poles
  14075. if (texture.minFilter === LinearMipmapLinearFilter) texture.minFilter = LinearFilter;
  14076. var camera = new CubeCamera(1, 10, this);
  14077. camera.update(renderer, mesh);
  14078. texture.minFilter = currentMinFilter;
  14079. mesh.geometry.dispose();
  14080. mesh.material.dispose();
  14081. return this;
  14082. };
  14083. _proto.clear = function clear(renderer, color, depth, stencil) {
  14084. var currentRenderTarget = renderer.getRenderTarget();
  14085. for (var i = 0; i < 6; i++) {
  14086. renderer.setRenderTarget(this, i);
  14087. renderer.clear(color, depth, stencil);
  14088. }
  14089. renderer.setRenderTarget(currentRenderTarget);
  14090. };
  14091. return WebGLCubeRenderTarget;
  14092. }(WebGLRenderTarget);
  14093. function DataTexture(data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding) {
  14094. Texture.call(this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding);
  14095. this.image = {
  14096. data: data || null,
  14097. width: width || 1,
  14098. height: height || 1
  14099. };
  14100. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  14101. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  14102. this.generateMipmaps = false;
  14103. this.flipY = false;
  14104. this.unpackAlignment = 1;
  14105. this.needsUpdate = true;
  14106. }
  14107. DataTexture.prototype = Object.create(Texture.prototype);
  14108. DataTexture.prototype.constructor = DataTexture;
  14109. DataTexture.prototype.isDataTexture = true;
  14110. var _sphere$1 = /*@__PURE__*/new Sphere();
  14111. var _vector$5 = /*@__PURE__*/new Vector3();
  14112. var Frustum = /*#__PURE__*/function () {
  14113. function Frustum(p0, p1, p2, p3, p4, p5) {
  14114. this.planes = [p0 !== undefined ? p0 : new Plane(), p1 !== undefined ? p1 : new Plane(), p2 !== undefined ? p2 : new Plane(), p3 !== undefined ? p3 : new Plane(), p4 !== undefined ? p4 : new Plane(), p5 !== undefined ? p5 : new Plane()];
  14115. }
  14116. var _proto = Frustum.prototype;
  14117. _proto.set = function set(p0, p1, p2, p3, p4, p5) {
  14118. var planes = this.planes;
  14119. planes[0].copy(p0);
  14120. planes[1].copy(p1);
  14121. planes[2].copy(p2);
  14122. planes[3].copy(p3);
  14123. planes[4].copy(p4);
  14124. planes[5].copy(p5);
  14125. return this;
  14126. };
  14127. _proto.clone = function clone() {
  14128. return new this.constructor().copy(this);
  14129. };
  14130. _proto.copy = function copy(frustum) {
  14131. var planes = this.planes;
  14132. for (var i = 0; i < 6; i++) {
  14133. planes[i].copy(frustum.planes[i]);
  14134. }
  14135. return this;
  14136. };
  14137. _proto.setFromProjectionMatrix = function setFromProjectionMatrix(m) {
  14138. var planes = this.planes;
  14139. var me = m.elements;
  14140. var me0 = me[0],
  14141. me1 = me[1],
  14142. me2 = me[2],
  14143. me3 = me[3];
  14144. var me4 = me[4],
  14145. me5 = me[5],
  14146. me6 = me[6],
  14147. me7 = me[7];
  14148. var me8 = me[8],
  14149. me9 = me[9],
  14150. me10 = me[10],
  14151. me11 = me[11];
  14152. var me12 = me[12],
  14153. me13 = me[13],
  14154. me14 = me[14],
  14155. me15 = me[15];
  14156. planes[0].setComponents(me3 - me0, me7 - me4, me11 - me8, me15 - me12).normalize();
  14157. planes[1].setComponents(me3 + me0, me7 + me4, me11 + me8, me15 + me12).normalize();
  14158. planes[2].setComponents(me3 + me1, me7 + me5, me11 + me9, me15 + me13).normalize();
  14159. planes[3].setComponents(me3 - me1, me7 - me5, me11 - me9, me15 - me13).normalize();
  14160. planes[4].setComponents(me3 - me2, me7 - me6, me11 - me10, me15 - me14).normalize();
  14161. planes[5].setComponents(me3 + me2, me7 + me6, me11 + me10, me15 + me14).normalize();
  14162. return this;
  14163. };
  14164. _proto.intersectsObject = function intersectsObject(object) {
  14165. var geometry = object.geometry;
  14166. if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
  14167. _sphere$1.copy(geometry.boundingSphere).applyMatrix4(object.matrixWorld);
  14168. return this.intersectsSphere(_sphere$1);
  14169. };
  14170. _proto.intersectsSprite = function intersectsSprite(sprite) {
  14171. _sphere$1.center.set(0, 0, 0);
  14172. _sphere$1.radius = 0.7071067811865476;
  14173. _sphere$1.applyMatrix4(sprite.matrixWorld);
  14174. return this.intersectsSphere(_sphere$1);
  14175. };
  14176. _proto.intersectsSphere = function intersectsSphere(sphere) {
  14177. var planes = this.planes;
  14178. var center = sphere.center;
  14179. var negRadius = -sphere.radius;
  14180. for (var i = 0; i < 6; i++) {
  14181. var distance = planes[i].distanceToPoint(center);
  14182. if (distance < negRadius) {
  14183. return false;
  14184. }
  14185. }
  14186. return true;
  14187. };
  14188. _proto.intersectsBox = function intersectsBox(box) {
  14189. var planes = this.planes;
  14190. for (var i = 0; i < 6; i++) {
  14191. var plane = planes[i]; // corner at max distance
  14192. _vector$5.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  14193. _vector$5.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  14194. _vector$5.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  14195. if (plane.distanceToPoint(_vector$5) < 0) {
  14196. return false;
  14197. }
  14198. }
  14199. return true;
  14200. };
  14201. _proto.containsPoint = function containsPoint(point) {
  14202. var planes = this.planes;
  14203. for (var i = 0; i < 6; i++) {
  14204. if (planes[i].distanceToPoint(point) < 0) {
  14205. return false;
  14206. }
  14207. }
  14208. return true;
  14209. };
  14210. return Frustum;
  14211. }();
  14212. function WebGLAnimation() {
  14213. var context = null;
  14214. var isAnimating = false;
  14215. var animationLoop = null;
  14216. var requestId = null;
  14217. function onAnimationFrame(time, frame) {
  14218. animationLoop(time, frame);
  14219. requestId = context.requestAnimationFrame(onAnimationFrame);
  14220. }
  14221. return {
  14222. start: function start() {
  14223. if (isAnimating === true) return;
  14224. if (animationLoop === null) return;
  14225. requestId = context.requestAnimationFrame(onAnimationFrame);
  14226. isAnimating = true;
  14227. },
  14228. stop: function stop() {
  14229. context.cancelAnimationFrame(requestId);
  14230. isAnimating = false;
  14231. },
  14232. setAnimationLoop: function setAnimationLoop(callback) {
  14233. animationLoop = callback;
  14234. },
  14235. setContext: function setContext(value) {
  14236. context = value;
  14237. }
  14238. };
  14239. }
  14240. function WebGLAttributes(gl, capabilities) {
  14241. var isWebGL2 = capabilities.isWebGL2;
  14242. var buffers = new WeakMap();
  14243. function createBuffer(attribute, bufferType) {
  14244. var array = attribute.array;
  14245. var usage = attribute.usage;
  14246. var buffer = gl.createBuffer();
  14247. gl.bindBuffer(bufferType, buffer);
  14248. gl.bufferData(bufferType, array, usage);
  14249. attribute.onUploadCallback();
  14250. var type = 5126;
  14251. if (array instanceof Float32Array) {
  14252. type = 5126;
  14253. } else if (array instanceof Float64Array) {
  14254. console.warn('THREE.WebGLAttributes: Unsupported data buffer format: Float64Array.');
  14255. } else if (array instanceof Uint16Array) {
  14256. if (attribute.isFloat16BufferAttribute) {
  14257. if (isWebGL2) {
  14258. type = 5131;
  14259. } else {
  14260. console.warn('THREE.WebGLAttributes: Usage of Float16BufferAttribute requires WebGL2.');
  14261. }
  14262. } else {
  14263. type = 5123;
  14264. }
  14265. } else if (array instanceof Int16Array) {
  14266. type = 5122;
  14267. } else if (array instanceof Uint32Array) {
  14268. type = 5125;
  14269. } else if (array instanceof Int32Array) {
  14270. type = 5124;
  14271. } else if (array instanceof Int8Array) {
  14272. type = 5120;
  14273. } else if (array instanceof Uint8Array) {
  14274. type = 5121;
  14275. }
  14276. return {
  14277. buffer: buffer,
  14278. type: type,
  14279. bytesPerElement: array.BYTES_PER_ELEMENT,
  14280. version: attribute.version
  14281. };
  14282. }
  14283. function updateBuffer(buffer, attribute, bufferType) {
  14284. var array = attribute.array;
  14285. var updateRange = attribute.updateRange;
  14286. gl.bindBuffer(bufferType, buffer);
  14287. if (updateRange.count === -1) {
  14288. // Not using update ranges
  14289. gl.bufferSubData(bufferType, 0, array);
  14290. } else {
  14291. if (isWebGL2) {
  14292. gl.bufferSubData(bufferType, updateRange.offset * array.BYTES_PER_ELEMENT, array, updateRange.offset, updateRange.count);
  14293. } else {
  14294. gl.bufferSubData(bufferType, updateRange.offset * array.BYTES_PER_ELEMENT, array.subarray(updateRange.offset, updateRange.offset + updateRange.count));
  14295. }
  14296. updateRange.count = -1; // reset range
  14297. }
  14298. } //
  14299. function get(attribute) {
  14300. if (attribute.isInterleavedBufferAttribute) attribute = attribute.data;
  14301. return buffers.get(attribute);
  14302. }
  14303. function remove(attribute) {
  14304. if (attribute.isInterleavedBufferAttribute) attribute = attribute.data;
  14305. var data = buffers.get(attribute);
  14306. if (data) {
  14307. gl.deleteBuffer(data.buffer);
  14308. buffers.delete(attribute);
  14309. }
  14310. }
  14311. function update(attribute, bufferType) {
  14312. if (attribute.isGLBufferAttribute) {
  14313. var cached = buffers.get(attribute);
  14314. if (!cached || cached.version < attribute.version) {
  14315. buffers.set(attribute, {
  14316. buffer: attribute.buffer,
  14317. type: attribute.type,
  14318. bytesPerElement: attribute.elementSize,
  14319. version: attribute.version
  14320. });
  14321. }
  14322. return;
  14323. }
  14324. if (attribute.isInterleavedBufferAttribute) attribute = attribute.data;
  14325. var data = buffers.get(attribute);
  14326. if (data === undefined) {
  14327. buffers.set(attribute, createBuffer(attribute, bufferType));
  14328. } else if (data.version < attribute.version) {
  14329. updateBuffer(data.buffer, attribute, bufferType);
  14330. data.version = attribute.version;
  14331. }
  14332. }
  14333. return {
  14334. get: get,
  14335. remove: remove,
  14336. update: update
  14337. };
  14338. }
  14339. var PlaneGeometry = /*#__PURE__*/function (_BufferGeometry) {
  14340. _inheritsLoose(PlaneGeometry, _BufferGeometry);
  14341. function PlaneGeometry(width, height, widthSegments, heightSegments) {
  14342. var _this;
  14343. if (width === void 0) {
  14344. width = 1;
  14345. }
  14346. if (height === void 0) {
  14347. height = 1;
  14348. }
  14349. if (widthSegments === void 0) {
  14350. widthSegments = 1;
  14351. }
  14352. if (heightSegments === void 0) {
  14353. heightSegments = 1;
  14354. }
  14355. _this = _BufferGeometry.call(this) || this;
  14356. _this.type = 'PlaneGeometry';
  14357. _this.parameters = {
  14358. width: width,
  14359. height: height,
  14360. widthSegments: widthSegments,
  14361. heightSegments: heightSegments
  14362. };
  14363. var width_half = width / 2;
  14364. var height_half = height / 2;
  14365. var gridX = Math.floor(widthSegments);
  14366. var gridY = Math.floor(heightSegments);
  14367. var gridX1 = gridX + 1;
  14368. var gridY1 = gridY + 1;
  14369. var segment_width = width / gridX;
  14370. var segment_height = height / gridY; //
  14371. var indices = [];
  14372. var vertices = [];
  14373. var normals = [];
  14374. var uvs = [];
  14375. for (var iy = 0; iy < gridY1; iy++) {
  14376. var y = iy * segment_height - height_half;
  14377. for (var ix = 0; ix < gridX1; ix++) {
  14378. var x = ix * segment_width - width_half;
  14379. vertices.push(x, -y, 0);
  14380. normals.push(0, 0, 1);
  14381. uvs.push(ix / gridX);
  14382. uvs.push(1 - iy / gridY);
  14383. }
  14384. }
  14385. for (var _iy = 0; _iy < gridY; _iy++) {
  14386. for (var _ix = 0; _ix < gridX; _ix++) {
  14387. var a = _ix + gridX1 * _iy;
  14388. var b = _ix + gridX1 * (_iy + 1);
  14389. var c = _ix + 1 + gridX1 * (_iy + 1);
  14390. var d = _ix + 1 + gridX1 * _iy;
  14391. indices.push(a, b, d);
  14392. indices.push(b, c, d);
  14393. }
  14394. }
  14395. _this.setIndex(indices);
  14396. _this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  14397. _this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  14398. _this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  14399. return _this;
  14400. }
  14401. return PlaneGeometry;
  14402. }(BufferGeometry);
  14403. var alphamap_fragment = "#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vUv ).g;\n#endif";
  14404. var alphamap_pars_fragment = "#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif";
  14405. var alphatest_fragment = "#ifdef ALPHATEST\n\tif ( diffuseColor.a < ALPHATEST ) discard;\n#endif";
  14406. var aomap_fragment = "#ifdef USE_AOMAP\n\tfloat ambientOcclusion = ( texture2D( aoMap, vUv2 ).r - 1.0 ) * aoMapIntensity + 1.0;\n\treflectedLight.indirectDiffuse *= ambientOcclusion;\n\t#if defined( USE_ENVMAP ) && defined( STANDARD )\n\t\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\t\treflectedLight.indirectSpecular *= computeSpecularOcclusion( dotNV, ambientOcclusion, material.specularRoughness );\n\t#endif\n#endif";
  14407. var aomap_pars_fragment = "#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif";
  14408. var begin_vertex = "vec3 transformed = vec3( position );";
  14409. var beginnormal_vertex = "vec3 objectNormal = vec3( normal );\n#ifdef USE_TANGENT\n\tvec3 objectTangent = vec3( tangent.xyz );\n#endif";
  14410. var bsdfs = "vec2 integrateSpecularBRDF( const in float dotNV, const in float roughness ) {\n\tconst vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );\n\tconst vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 );\n\tvec4 r = roughness * c0 + c1;\n\tfloat a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y;\n\treturn vec2( -1.04, 1.04 ) * a004 + r.zw;\n}\nfloat punctualLightIntensityToIrradianceFactor( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {\n#if defined ( PHYSICALLY_CORRECT_LIGHTS )\n\tfloat distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );\n\tif( cutoffDistance > 0.0 ) {\n\t\tdistanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );\n\t}\n\treturn distanceFalloff;\n#else\n\tif( cutoffDistance > 0.0 && decayExponent > 0.0 ) {\n\t\treturn pow( saturate( -lightDistance / cutoffDistance + 1.0 ), decayExponent );\n\t}\n\treturn 1.0;\n#endif\n}\nvec3 BRDF_Diffuse_Lambert( const in vec3 diffuseColor ) {\n\treturn RECIPROCAL_PI * diffuseColor;\n}\nvec3 F_Schlick( const in vec3 specularColor, const in float dotLH ) {\n\tfloat fresnel = exp2( ( -5.55473 * dotLH - 6.98316 ) * dotLH );\n\treturn ( 1.0 - specularColor ) * fresnel + specularColor;\n}\nvec3 F_Schlick_RoughnessDependent( const in vec3 F0, const in float dotNV, const in float roughness ) {\n\tfloat fresnel = exp2( ( -5.55473 * dotNV - 6.98316 ) * dotNV );\n\tvec3 Fr = max( vec3( 1.0 - roughness ), F0 ) - F0;\n\treturn Fr * fresnel + F0;\n}\nfloat G_GGX_Smith( const in float alpha, const in float dotNL, const in float dotNV ) {\n\tfloat a2 = pow2( alpha );\n\tfloat gl = dotNL + sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\tfloat gv = dotNV + sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\treturn 1.0 / ( gl * gv );\n}\nfloat G_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) {\n\tfloat a2 = pow2( alpha );\n\tfloat gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\tfloat gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\treturn 0.5 / max( gv + gl, EPSILON );\n}\nfloat D_GGX( const in float alpha, const in float dotNH ) {\n\tfloat a2 = pow2( alpha );\n\tfloat denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0;\n\treturn RECIPROCAL_PI * a2 / pow2( denom );\n}\nvec3 BRDF_Specular_GGX( const in IncidentLight incidentLight, const in vec3 viewDir, const in vec3 normal, const in vec3 specularColor, const in float roughness ) {\n\tfloat alpha = pow2( roughness );\n\tvec3 halfDir = normalize( incidentLight.direction + viewDir );\n\tfloat dotNL = saturate( dot( normal, incidentLight.direction ) );\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat dotLH = saturate( dot( incidentLight.direction, halfDir ) );\n\tvec3 F = F_Schlick( specularColor, dotLH );\n\tfloat G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\tfloat D = D_GGX( alpha, dotNH );\n\treturn F * ( G * D );\n}\nvec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) {\n\tconst float LUT_SIZE = 64.0;\n\tconst float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;\n\tconst float LUT_BIAS = 0.5 / LUT_SIZE;\n\tfloat dotNV = saturate( dot( N, V ) );\n\tvec2 uv = vec2( roughness, sqrt( 1.0 - dotNV ) );\n\tuv = uv * LUT_SCALE + LUT_BIAS;\n\treturn uv;\n}\nfloat LTC_ClippedSphereFormFactor( const in vec3 f ) {\n\tfloat l = length( f );\n\treturn max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 );\n}\nvec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) {\n\tfloat x = dot( v1, v2 );\n\tfloat y = abs( x );\n\tfloat a = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y;\n\tfloat b = 3.4175940 + ( 4.1616724 + y ) * y;\n\tfloat v = a / b;\n\tfloat theta_sintheta = ( x > 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v;\n\treturn cross( v1, v2 ) * theta_sintheta;\n}\nvec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) {\n\tvec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ];\n\tvec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ];\n\tvec3 lightNormal = cross( v1, v2 );\n\tif( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 );\n\tvec3 T1, T2;\n\tT1 = normalize( V - N * dot( V, N ) );\n\tT2 = - cross( N, T1 );\n\tmat3 mat = mInv * transposeMat3( mat3( T1, T2, N ) );\n\tvec3 coords[ 4 ];\n\tcoords[ 0 ] = mat * ( rectCoords[ 0 ] - P );\n\tcoords[ 1 ] = mat * ( rectCoords[ 1 ] - P );\n\tcoords[ 2 ] = mat * ( rectCoords[ 2 ] - P );\n\tcoords[ 3 ] = mat * ( rectCoords[ 3 ] - P );\n\tcoords[ 0 ] = normalize( coords[ 0 ] );\n\tcoords[ 1 ] = normalize( coords[ 1 ] );\n\tcoords[ 2 ] = normalize( coords[ 2 ] );\n\tcoords[ 3 ] = normalize( coords[ 3 ] );\n\tvec3 vectorFormFactor = vec3( 0.0 );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] );\n\tfloat result = LTC_ClippedSphereFormFactor( vectorFormFactor );\n\treturn vec3( result );\n}\nvec3 BRDF_Specular_GGX_Environment( const in vec3 viewDir, const in vec3 normal, const in vec3 specularColor, const in float roughness ) {\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tvec2 brdf = integrateSpecularBRDF( dotNV, roughness );\n\treturn specularColor * brdf.x + brdf.y;\n}\nvoid BRDF_Specular_Multiscattering_Environment( const in GeometricContext geometry, const in vec3 specularColor, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {\n\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\tvec3 F = F_Schlick_RoughnessDependent( specularColor, dotNV, roughness );\n\tvec2 brdf = integrateSpecularBRDF( dotNV, roughness );\n\tvec3 FssEss = F * brdf.x + brdf.y;\n\tfloat Ess = brdf.x + brdf.y;\n\tfloat Ems = 1.0 - Ess;\n\tvec3 Favg = specularColor + ( 1.0 - specularColor ) * 0.047619;\tvec3 Fms = FssEss * Favg / ( 1.0 - Ems * Favg );\n\tsingleScatter += FssEss;\n\tmultiScatter += Fms * Ems;\n}\nfloat G_BlinnPhong_Implicit( ) {\n\treturn 0.25;\n}\nfloat D_BlinnPhong( const in float shininess, const in float dotNH ) {\n\treturn RECIPROCAL_PI * ( shininess * 0.5 + 1.0 ) * pow( dotNH, shininess );\n}\nvec3 BRDF_Specular_BlinnPhong( const in IncidentLight incidentLight, const in GeometricContext geometry, const in vec3 specularColor, const in float shininess ) {\n\tvec3 halfDir = normalize( incidentLight.direction + geometry.viewDir );\n\tfloat dotNH = saturate( dot( geometry.normal, halfDir ) );\n\tfloat dotLH = saturate( dot( incidentLight.direction, halfDir ) );\n\tvec3 F = F_Schlick( specularColor, dotLH );\n\tfloat G = G_BlinnPhong_Implicit( );\n\tfloat D = D_BlinnPhong( shininess, dotNH );\n\treturn F * ( G * D );\n}\nfloat GGXRoughnessToBlinnExponent( const in float ggxRoughness ) {\n\treturn ( 2.0 / pow2( ggxRoughness + 0.0001 ) - 2.0 );\n}\nfloat BlinnExponentToGGXRoughness( const in float blinnExponent ) {\n\treturn sqrt( 2.0 / ( blinnExponent + 2.0 ) );\n}\n#if defined( USE_SHEEN )\nfloat D_Charlie(float roughness, float NoH) {\n\tfloat invAlpha = 1.0 / roughness;\n\tfloat cos2h = NoH * NoH;\n\tfloat sin2h = max(1.0 - cos2h, 0.0078125);\treturn (2.0 + invAlpha) * pow(sin2h, invAlpha * 0.5) / (2.0 * PI);\n}\nfloat V_Neubelt(float NoV, float NoL) {\n\treturn saturate(1.0 / (4.0 * (NoL + NoV - NoL * NoV)));\n}\nvec3 BRDF_Specular_Sheen( const in float roughness, const in vec3 L, const in GeometricContext geometry, vec3 specularColor ) {\n\tvec3 N = geometry.normal;\n\tvec3 V = geometry.viewDir;\n\tvec3 H = normalize( V + L );\n\tfloat dotNH = saturate( dot( N, H ) );\n\treturn specularColor * D_Charlie( roughness, dotNH ) * V_Neubelt( dot(N, V), dot(N, L) );\n}\n#endif";
  14411. var bumpmap_pars_fragment = "#ifdef USE_BUMPMAP\n\tuniform sampler2D bumpMap;\n\tuniform float bumpScale;\n\tvec2 dHdxy_fwd() {\n\t\tvec2 dSTdx = dFdx( vUv );\n\t\tvec2 dSTdy = dFdy( vUv );\n\t\tfloat Hll = bumpScale * texture2D( bumpMap, vUv ).x;\n\t\tfloat dBx = bumpScale * texture2D( bumpMap, vUv + dSTdx ).x - Hll;\n\t\tfloat dBy = bumpScale * texture2D( bumpMap, vUv + dSTdy ).x - Hll;\n\t\treturn vec2( dBx, dBy );\n\t}\n\tvec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy ) {\n\t\tvec3 vSigmaX = vec3( dFdx( surf_pos.x ), dFdx( surf_pos.y ), dFdx( surf_pos.z ) );\n\t\tvec3 vSigmaY = vec3( dFdy( surf_pos.x ), dFdy( surf_pos.y ), dFdy( surf_pos.z ) );\n\t\tvec3 vN = surf_norm;\n\t\tvec3 R1 = cross( vSigmaY, vN );\n\t\tvec3 R2 = cross( vN, vSigmaX );\n\t\tfloat fDet = dot( vSigmaX, R1 );\n\t\tfDet *= ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n\t\tvec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );\n\t\treturn normalize( abs( fDet ) * surf_norm - vGrad );\n\t}\n#endif";
  14412. var clipping_planes_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tvec4 plane;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {\n\t\tplane = clippingPlanes[ i ];\n\t\tif ( dot( vClipPosition, plane.xyz ) > plane.w ) discard;\n\t}\n\t#pragma unroll_loop_end\n\t#if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES\n\t\tbool clipped = true;\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {\n\t\t\tplane = clippingPlanes[ i ];\n\t\t\tclipped = ( dot( vClipPosition, plane.xyz ) > plane.w ) && clipped;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t\tif ( clipped ) discard;\n\t#endif\n#endif";
  14413. var clipping_planes_pars_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif";
  14414. var clipping_planes_pars_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n#endif";
  14415. var clipping_planes_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvClipPosition = - mvPosition.xyz;\n#endif";
  14416. var color_fragment = "#ifdef USE_COLOR\n\tdiffuseColor.rgb *= vColor;\n#endif";
  14417. var color_pars_fragment = "#ifdef USE_COLOR\n\tvarying vec3 vColor;\n#endif";
  14418. var color_pars_vertex = "#if defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR )\n\tvarying vec3 vColor;\n#endif";
  14419. var color_vertex = "#if defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR )\n\tvColor = vec3( 1.0 );\n#endif\n#ifdef USE_COLOR\n\tvColor.xyz *= color.xyz;\n#endif\n#ifdef USE_INSTANCING_COLOR\n\tvColor.xyz *= instanceColor.xyz;\n#endif";
  14420. var common = "#define PI 3.141592653589793\n#define PI2 6.283185307179586\n#define PI_HALF 1.5707963267948966\n#define RECIPROCAL_PI 0.3183098861837907\n#define RECIPROCAL_PI2 0.15915494309189535\n#define EPSILON 1e-6\n#ifndef saturate\n#define saturate(a) clamp( a, 0.0, 1.0 )\n#endif\n#define whiteComplement(a) ( 1.0 - saturate( a ) )\nfloat pow2( const in float x ) { return x*x; }\nfloat pow3( const in float x ) { return x*x*x; }\nfloat pow4( const in float x ) { float x2 = x*x; return x2*x2; }\nfloat average( const in vec3 color ) { return dot( color, vec3( 0.3333 ) ); }\nhighp float rand( const in vec2 uv ) {\n\tconst highp float a = 12.9898, b = 78.233, c = 43758.5453;\n\thighp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );\n\treturn fract(sin(sn) * c);\n}\n#ifdef HIGH_PRECISION\n\tfloat precisionSafeLength( vec3 v ) { return length( v ); }\n#else\n\tfloat max3( vec3 v ) { return max( max( v.x, v.y ), v.z ); }\n\tfloat precisionSafeLength( vec3 v ) {\n\t\tfloat maxComponent = max3( abs( v ) );\n\t\treturn length( v / maxComponent ) * maxComponent;\n\t}\n#endif\nstruct IncidentLight {\n\tvec3 color;\n\tvec3 direction;\n\tbool visible;\n};\nstruct ReflectedLight {\n\tvec3 directDiffuse;\n\tvec3 directSpecular;\n\tvec3 indirectDiffuse;\n\tvec3 indirectSpecular;\n};\nstruct GeometricContext {\n\tvec3 position;\n\tvec3 normal;\n\tvec3 viewDir;\n#ifdef CLEARCOAT\n\tvec3 clearcoatNormal;\n#endif\n};\nvec3 transformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\n}\nvec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );\n}\nvec3 projectOnPlane(in vec3 point, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\tfloat distance = dot( planeNormal, point - pointOnPlane );\n\treturn - distance * planeNormal + point;\n}\nfloat sideOfPlane( in vec3 point, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\treturn sign( dot( point - pointOnPlane, planeNormal ) );\n}\nvec3 linePlaneIntersect( in vec3 pointOnLine, in vec3 lineDirection, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\treturn lineDirection * ( dot( planeNormal, pointOnPlane - pointOnLine ) / dot( planeNormal, lineDirection ) ) + pointOnLine;\n}\nmat3 transposeMat3( const in mat3 m ) {\n\tmat3 tmp;\n\ttmp[ 0 ] = vec3( m[ 0 ].x, m[ 1 ].x, m[ 2 ].x );\n\ttmp[ 1 ] = vec3( m[ 0 ].y, m[ 1 ].y, m[ 2 ].y );\n\ttmp[ 2 ] = vec3( m[ 0 ].z, m[ 1 ].z, m[ 2 ].z );\n\treturn tmp;\n}\nfloat linearToRelativeLuminance( const in vec3 color ) {\n\tvec3 weights = vec3( 0.2126, 0.7152, 0.0722 );\n\treturn dot( weights, color.rgb );\n}\nbool isPerspectiveMatrix( mat4 m ) {\n\treturn m[ 2 ][ 3 ] == - 1.0;\n}\nvec2 equirectUv( in vec3 dir ) {\n\tfloat u = atan( dir.z, dir.x ) * RECIPROCAL_PI2 + 0.5;\n\tfloat v = asin( clamp( dir.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;\n\treturn vec2( u, v );\n}";
  14421. var cube_uv_reflection_fragment = "#ifdef ENVMAP_TYPE_CUBE_UV\n\t#define cubeUV_maxMipLevel 8.0\n\t#define cubeUV_minMipLevel 4.0\n\t#define cubeUV_maxTileSize 256.0\n\t#define cubeUV_minTileSize 16.0\n\tfloat getFace( vec3 direction ) {\n\t\tvec3 absDirection = abs( direction );\n\t\tfloat face = - 1.0;\n\t\tif ( absDirection.x > absDirection.z ) {\n\t\t\tif ( absDirection.x > absDirection.y )\n\t\t\t\tface = direction.x > 0.0 ? 0.0 : 3.0;\n\t\t\telse\n\t\t\t\tface = direction.y > 0.0 ? 1.0 : 4.0;\n\t\t} else {\n\t\t\tif ( absDirection.z > absDirection.y )\n\t\t\t\tface = direction.z > 0.0 ? 2.0 : 5.0;\n\t\t\telse\n\t\t\t\tface = direction.y > 0.0 ? 1.0 : 4.0;\n\t\t}\n\t\treturn face;\n\t}\n\tvec2 getUV( vec3 direction, float face ) {\n\t\tvec2 uv;\n\t\tif ( face == 0.0 ) {\n\t\t\tuv = vec2( direction.z, direction.y ) / abs( direction.x );\n\t\t} else if ( face == 1.0 ) {\n\t\t\tuv = vec2( - direction.x, - direction.z ) / abs( direction.y );\n\t\t} else if ( face == 2.0 ) {\n\t\t\tuv = vec2( - direction.x, direction.y ) / abs( direction.z );\n\t\t} else if ( face == 3.0 ) {\n\t\t\tuv = vec2( - direction.z, direction.y ) / abs( direction.x );\n\t\t} else if ( face == 4.0 ) {\n\t\t\tuv = vec2( - direction.x, direction.z ) / abs( direction.y );\n\t\t} else {\n\t\t\tuv = vec2( direction.x, direction.y ) / abs( direction.z );\n\t\t}\n\t\treturn 0.5 * ( uv + 1.0 );\n\t}\n\tvec3 bilinearCubeUV( sampler2D envMap, vec3 direction, float mipInt ) {\n\t\tfloat face = getFace( direction );\n\t\tfloat filterInt = max( cubeUV_minMipLevel - mipInt, 0.0 );\n\t\tmipInt = max( mipInt, cubeUV_minMipLevel );\n\t\tfloat faceSize = exp2( mipInt );\n\t\tfloat texelSize = 1.0 / ( 3.0 * cubeUV_maxTileSize );\n\t\tvec2 uv = getUV( direction, face ) * ( faceSize - 1.0 );\n\t\tvec2 f = fract( uv );\n\t\tuv += 0.5 - f;\n\t\tif ( face > 2.0 ) {\n\t\t\tuv.y += faceSize;\n\t\t\tface -= 3.0;\n\t\t}\n\t\tuv.x += face * faceSize;\n\t\tif ( mipInt < cubeUV_maxMipLevel ) {\n\t\t\tuv.y += 2.0 * cubeUV_maxTileSize;\n\t\t}\n\t\tuv.y += filterInt * 2.0 * cubeUV_minTileSize;\n\t\tuv.x += 3.0 * max( 0.0, cubeUV_maxTileSize - 2.0 * faceSize );\n\t\tuv *= texelSize;\n\t\tvec3 tl = envMapTexelToLinear( texture2D( envMap, uv ) ).rgb;\n\t\tuv.x += texelSize;\n\t\tvec3 tr = envMapTexelToLinear( texture2D( envMap, uv ) ).rgb;\n\t\tuv.y += texelSize;\n\t\tvec3 br = envMapTexelToLinear( texture2D( envMap, uv ) ).rgb;\n\t\tuv.x -= texelSize;\n\t\tvec3 bl = envMapTexelToLinear( texture2D( envMap, uv ) ).rgb;\n\t\tvec3 tm = mix( tl, tr, f.x );\n\t\tvec3 bm = mix( bl, br, f.x );\n\t\treturn mix( tm, bm, f.y );\n\t}\n\t#define r0 1.0\n\t#define v0 0.339\n\t#define m0 - 2.0\n\t#define r1 0.8\n\t#define v1 0.276\n\t#define m1 - 1.0\n\t#define r4 0.4\n\t#define v4 0.046\n\t#define m4 2.0\n\t#define r5 0.305\n\t#define v5 0.016\n\t#define m5 3.0\n\t#define r6 0.21\n\t#define v6 0.0038\n\t#define m6 4.0\n\tfloat roughnessToMip( float roughness ) {\n\t\tfloat mip = 0.0;\n\t\tif ( roughness >= r1 ) {\n\t\t\tmip = ( r0 - roughness ) * ( m1 - m0 ) / ( r0 - r1 ) + m0;\n\t\t} else if ( roughness >= r4 ) {\n\t\t\tmip = ( r1 - roughness ) * ( m4 - m1 ) / ( r1 - r4 ) + m1;\n\t\t} else if ( roughness >= r5 ) {\n\t\t\tmip = ( r4 - roughness ) * ( m5 - m4 ) / ( r4 - r5 ) + m4;\n\t\t} else if ( roughness >= r6 ) {\n\t\t\tmip = ( r5 - roughness ) * ( m6 - m5 ) / ( r5 - r6 ) + m5;\n\t\t} else {\n\t\t\tmip = - 2.0 * log2( 1.16 * roughness );\t\t}\n\t\treturn mip;\n\t}\n\tvec4 textureCubeUV( sampler2D envMap, vec3 sampleDir, float roughness ) {\n\t\tfloat mip = clamp( roughnessToMip( roughness ), m0, cubeUV_maxMipLevel );\n\t\tfloat mipF = fract( mip );\n\t\tfloat mipInt = floor( mip );\n\t\tvec3 color0 = bilinearCubeUV( envMap, sampleDir, mipInt );\n\t\tif ( mipF == 0.0 ) {\n\t\t\treturn vec4( color0, 1.0 );\n\t\t} else {\n\t\t\tvec3 color1 = bilinearCubeUV( envMap, sampleDir, mipInt + 1.0 );\n\t\t\treturn vec4( mix( color0, color1, mipF ), 1.0 );\n\t\t}\n\t}\n#endif";
  14422. var defaultnormal_vertex = "vec3 transformedNormal = objectNormal;\n#ifdef USE_INSTANCING\n\tmat3 m = mat3( instanceMatrix );\n\ttransformedNormal /= vec3( dot( m[ 0 ], m[ 0 ] ), dot( m[ 1 ], m[ 1 ] ), dot( m[ 2 ], m[ 2 ] ) );\n\ttransformedNormal = m * transformedNormal;\n#endif\ntransformedNormal = normalMatrix * transformedNormal;\n#ifdef FLIP_SIDED\n\ttransformedNormal = - transformedNormal;\n#endif\n#ifdef USE_TANGENT\n\tvec3 transformedTangent = ( modelViewMatrix * vec4( objectTangent, 0.0 ) ).xyz;\n\t#ifdef FLIP_SIDED\n\t\ttransformedTangent = - transformedTangent;\n\t#endif\n#endif";
  14423. var displacementmap_pars_vertex = "#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif";
  14424. var displacementmap_vertex = "#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normalize( objectNormal ) * ( texture2D( displacementMap, vUv ).x * displacementScale + displacementBias );\n#endif";
  14425. var emissivemap_fragment = "#ifdef USE_EMISSIVEMAP\n\tvec4 emissiveColor = texture2D( emissiveMap, vUv );\n\temissiveColor.rgb = emissiveMapTexelToLinear( emissiveColor ).rgb;\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n#endif";
  14426. var emissivemap_pars_fragment = "#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif";
  14427. var encodings_fragment = "gl_FragColor = linearToOutputTexel( gl_FragColor );";
  14428. var encodings_pars_fragment = "\nvec4 LinearToLinear( in vec4 value ) {\n\treturn value;\n}\nvec4 GammaToLinear( in vec4 value, in float gammaFactor ) {\n\treturn vec4( pow( value.rgb, vec3( gammaFactor ) ), value.a );\n}\nvec4 LinearToGamma( in vec4 value, in float gammaFactor ) {\n\treturn vec4( pow( value.rgb, vec3( 1.0 / gammaFactor ) ), value.a );\n}\nvec4 sRGBToLinear( in vec4 value ) {\n\treturn vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.a );\n}\nvec4 LinearTosRGB( in vec4 value ) {\n\treturn vec4( mix( pow( value.rgb, vec3( 0.41666 ) ) * 1.055 - vec3( 0.055 ), value.rgb * 12.92, vec3( lessThanEqual( value.rgb, vec3( 0.0031308 ) ) ) ), value.a );\n}\nvec4 RGBEToLinear( in vec4 value ) {\n\treturn vec4( value.rgb * exp2( value.a * 255.0 - 128.0 ), 1.0 );\n}\nvec4 LinearToRGBE( in vec4 value ) {\n\tfloat maxComponent = max( max( value.r, value.g ), value.b );\n\tfloat fExp = clamp( ceil( log2( maxComponent ) ), -128.0, 127.0 );\n\treturn vec4( value.rgb / exp2( fExp ), ( fExp + 128.0 ) / 255.0 );\n}\nvec4 RGBMToLinear( in vec4 value, in float maxRange ) {\n\treturn vec4( value.rgb * value.a * maxRange, 1.0 );\n}\nvec4 LinearToRGBM( in vec4 value, in float maxRange ) {\n\tfloat maxRGB = max( value.r, max( value.g, value.b ) );\n\tfloat M = clamp( maxRGB / maxRange, 0.0, 1.0 );\n\tM = ceil( M * 255.0 ) / 255.0;\n\treturn vec4( value.rgb / ( M * maxRange ), M );\n}\nvec4 RGBDToLinear( in vec4 value, in float maxRange ) {\n\treturn vec4( value.rgb * ( ( maxRange / 255.0 ) / value.a ), 1.0 );\n}\nvec4 LinearToRGBD( in vec4 value, in float maxRange ) {\n\tfloat maxRGB = max( value.r, max( value.g, value.b ) );\n\tfloat D = max( maxRange / maxRGB, 1.0 );\n\tD = clamp( floor( D ) / 255.0, 0.0, 1.0 );\n\treturn vec4( value.rgb * ( D * ( 255.0 / maxRange ) ), D );\n}\nconst mat3 cLogLuvM = mat3( 0.2209, 0.3390, 0.4184, 0.1138, 0.6780, 0.7319, 0.0102, 0.1130, 0.2969 );\nvec4 LinearToLogLuv( in vec4 value ) {\n\tvec3 Xp_Y_XYZp = cLogLuvM * value.rgb;\n\tXp_Y_XYZp = max( Xp_Y_XYZp, vec3( 1e-6, 1e-6, 1e-6 ) );\n\tvec4 vResult;\n\tvResult.xy = Xp_Y_XYZp.xy / Xp_Y_XYZp.z;\n\tfloat Le = 2.0 * log2(Xp_Y_XYZp.y) + 127.0;\n\tvResult.w = fract( Le );\n\tvResult.z = ( Le - ( floor( vResult.w * 255.0 ) ) / 255.0 ) / 255.0;\n\treturn vResult;\n}\nconst mat3 cLogLuvInverseM = mat3( 6.0014, -2.7008, -1.7996, -1.3320, 3.1029, -5.7721, 0.3008, -1.0882, 5.6268 );\nvec4 LogLuvToLinear( in vec4 value ) {\n\tfloat Le = value.z * 255.0 + value.w;\n\tvec3 Xp_Y_XYZp;\n\tXp_Y_XYZp.y = exp2( ( Le - 127.0 ) / 2.0 );\n\tXp_Y_XYZp.z = Xp_Y_XYZp.y / value.y;\n\tXp_Y_XYZp.x = value.x * Xp_Y_XYZp.z;\n\tvec3 vRGB = cLogLuvInverseM * Xp_Y_XYZp.rgb;\n\treturn vec4( max( vRGB, 0.0 ), 1.0 );\n}";
  14429. var envmap_fragment = "#ifdef USE_ENVMAP\n\t#ifdef ENV_WORLDPOS\n\t\tvec3 cameraToFrag;\n\t\tif ( isOrthographic ) {\n\t\t\tcameraToFrag = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );\n\t\t} else {\n\t\t\tcameraToFrag = normalize( vWorldPosition - cameraPosition );\n\t\t}\n\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvec3 reflectVec = reflect( cameraToFrag, worldNormal );\n\t\t#else\n\t\t\tvec3 reflectVec = refract( cameraToFrag, worldNormal, refractionRatio );\n\t\t#endif\n\t#else\n\t\tvec3 reflectVec = vReflect;\n\t#endif\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tvec4 envColor = textureCube( envMap, vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );\n\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\tvec4 envColor = textureCubeUV( envMap, reflectVec, 0.0 );\n\t#else\n\t\tvec4 envColor = vec4( 0.0 );\n\t#endif\n\t#ifndef ENVMAP_TYPE_CUBE_UV\n\t\tenvColor = envMapTexelToLinear( envColor );\n\t#endif\n\t#ifdef ENVMAP_BLENDING_MULTIPLY\n\t\toutgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_MIX )\n\t\toutgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_ADD )\n\t\toutgoingLight += envColor.xyz * specularStrength * reflectivity;\n\t#endif\n#endif";
  14430. var envmap_common_pars_fragment = "#ifdef USE_ENVMAP\n\tuniform float envMapIntensity;\n\tuniform float flipEnvMap;\n\tuniform int maxMipLevel;\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tuniform samplerCube envMap;\n\t#else\n\t\tuniform sampler2D envMap;\n\t#endif\n\t\n#endif";
  14431. var envmap_pars_fragment = "#ifdef USE_ENVMAP\n\tuniform float reflectivity;\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG )\n\t\t#define ENV_WORLDPOS\n\t#endif\n\t#ifdef ENV_WORLDPOS\n\t\tvarying vec3 vWorldPosition;\n\t\tuniform float refractionRatio;\n\t#else\n\t\tvarying vec3 vReflect;\n\t#endif\n#endif";
  14432. var envmap_pars_vertex = "#ifdef USE_ENVMAP\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) ||defined( PHONG )\n\t\t#define ENV_WORLDPOS\n\t#endif\n\t#ifdef ENV_WORLDPOS\n\t\t\n\t\tvarying vec3 vWorldPosition;\n\t#else\n\t\tvarying vec3 vReflect;\n\t\tuniform float refractionRatio;\n\t#endif\n#endif";
  14433. var envmap_vertex = "#ifdef USE_ENVMAP\n\t#ifdef ENV_WORLDPOS\n\t\tvWorldPosition = worldPosition.xyz;\n\t#else\n\t\tvec3 cameraToVertex;\n\t\tif ( isOrthographic ) {\n\t\t\tcameraToVertex = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );\n\t\t} else {\n\t\t\tcameraToVertex = normalize( worldPosition.xyz - cameraPosition );\n\t\t}\n\t\tvec3 worldNormal = inverseTransformDirection( transformedNormal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvReflect = reflect( cameraToVertex, worldNormal );\n\t\t#else\n\t\t\tvReflect = refract( cameraToVertex, worldNormal, refractionRatio );\n\t\t#endif\n\t#endif\n#endif";
  14434. var fog_vertex = "#ifdef USE_FOG\n\tfogDepth = - mvPosition.z;\n#endif";
  14435. var fog_pars_vertex = "#ifdef USE_FOG\n\tvarying float fogDepth;\n#endif";
  14436. var fog_fragment = "#ifdef USE_FOG\n\t#ifdef FOG_EXP2\n\t\tfloat fogFactor = 1.0 - exp( - fogDensity * fogDensity * fogDepth * fogDepth );\n\t#else\n\t\tfloat fogFactor = smoothstep( fogNear, fogFar, fogDepth );\n\t#endif\n\tgl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor );\n#endif";
  14437. var fog_pars_fragment = "#ifdef USE_FOG\n\tuniform vec3 fogColor;\n\tvarying float fogDepth;\n\t#ifdef FOG_EXP2\n\t\tuniform float fogDensity;\n\t#else\n\t\tuniform float fogNear;\n\t\tuniform float fogFar;\n\t#endif\n#endif";
  14438. var gradientmap_pars_fragment = "#ifdef USE_GRADIENTMAP\n\tuniform sampler2D gradientMap;\n#endif\nvec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) {\n\tfloat dotNL = dot( normal, lightDirection );\n\tvec2 coord = vec2( dotNL * 0.5 + 0.5, 0.0 );\n\t#ifdef USE_GRADIENTMAP\n\t\treturn texture2D( gradientMap, coord ).rgb;\n\t#else\n\t\treturn ( coord.x < 0.7 ) ? vec3( 0.7 ) : vec3( 1.0 );\n\t#endif\n}";
  14439. var lightmap_fragment = "#ifdef USE_LIGHTMAP\n\tvec4 lightMapTexel= texture2D( lightMap, vUv2 );\n\treflectedLight.indirectDiffuse += PI * lightMapTexelToLinear( lightMapTexel ).rgb * lightMapIntensity;\n#endif";
  14440. var lightmap_pars_fragment = "#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif";
  14441. var lights_lambert_vertex = "vec3 diffuse = vec3( 1.0 );\nGeometricContext geometry;\ngeometry.position = mvPosition.xyz;\ngeometry.normal = normalize( transformedNormal );\ngeometry.viewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( -mvPosition.xyz );\nGeometricContext backGeometry;\nbackGeometry.position = geometry.position;\nbackGeometry.normal = -geometry.normal;\nbackGeometry.viewDir = geometry.viewDir;\nvLightFront = vec3( 0.0 );\nvIndirectFront = vec3( 0.0 );\n#ifdef DOUBLE_SIDED\n\tvLightBack = vec3( 0.0 );\n\tvIndirectBack = vec3( 0.0 );\n#endif\nIncidentLight directLight;\nfloat dotNL;\nvec3 directLightColor_Diffuse;\nvIndirectFront += getAmbientLightIrradiance( ambientLightColor );\nvIndirectFront += getLightProbeIrradiance( lightProbe, geometry );\n#ifdef DOUBLE_SIDED\n\tvIndirectBack += getAmbientLightIrradiance( ambientLightColor );\n\tvIndirectBack += getLightProbeIrradiance( lightProbe, backGeometry );\n#endif\n#if NUM_POINT_LIGHTS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tgetPointDirectLightIrradiance( pointLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if NUM_SPOT_LIGHTS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tgetSpotDirectLightIrradiance( spotLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if NUM_DIR_LIGHTS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tgetDirectionalDirectLightIrradiance( directionalLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if NUM_HEMI_LIGHTS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\tvIndirectFront += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry );\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvIndirectBack += getHemisphereLightIrradiance( hemisphereLights[ i ], backGeometry );\n\t\t#endif\n\t}\n\t#pragma unroll_loop_end\n#endif";
  14442. var lights_pars_begin = "uniform bool receiveShadow;\nuniform vec3 ambientLightColor;\nuniform vec3 lightProbe[ 9 ];\nvec3 shGetIrradianceAt( in vec3 normal, in vec3 shCoefficients[ 9 ] ) {\n\tfloat x = normal.x, y = normal.y, z = normal.z;\n\tvec3 result = shCoefficients[ 0 ] * 0.886227;\n\tresult += shCoefficients[ 1 ] * 2.0 * 0.511664 * y;\n\tresult += shCoefficients[ 2 ] * 2.0 * 0.511664 * z;\n\tresult += shCoefficients[ 3 ] * 2.0 * 0.511664 * x;\n\tresult += shCoefficients[ 4 ] * 2.0 * 0.429043 * x * y;\n\tresult += shCoefficients[ 5 ] * 2.0 * 0.429043 * y * z;\n\tresult += shCoefficients[ 6 ] * ( 0.743125 * z * z - 0.247708 );\n\tresult += shCoefficients[ 7 ] * 2.0 * 0.429043 * x * z;\n\tresult += shCoefficients[ 8 ] * 0.429043 * ( x * x - y * y );\n\treturn result;\n}\nvec3 getLightProbeIrradiance( const in vec3 lightProbe[ 9 ], const in GeometricContext geometry ) {\n\tvec3 worldNormal = inverseTransformDirection( geometry.normal, viewMatrix );\n\tvec3 irradiance = shGetIrradianceAt( worldNormal, lightProbe );\n\treturn irradiance;\n}\nvec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) {\n\tvec3 irradiance = ambientLightColor;\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\treturn irradiance;\n}\n#if NUM_DIR_LIGHTS > 0\n\tstruct DirectionalLight {\n\t\tvec3 direction;\n\t\tvec3 color;\n\t};\n\tuniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ];\n\tvoid getDirectionalDirectLightIrradiance( const in DirectionalLight directionalLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\t\tdirectLight.color = directionalLight.color;\n\t\tdirectLight.direction = directionalLight.direction;\n\t\tdirectLight.visible = true;\n\t}\n#endif\n#if NUM_POINT_LIGHTS > 0\n\tstruct PointLight {\n\t\tvec3 position;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t};\n\tuniform PointLight pointLights[ NUM_POINT_LIGHTS ];\n\tvoid getPointDirectLightIrradiance( const in PointLight pointLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\t\tvec3 lVector = pointLight.position - geometry.position;\n\t\tdirectLight.direction = normalize( lVector );\n\t\tfloat lightDistance = length( lVector );\n\t\tdirectLight.color = pointLight.color;\n\t\tdirectLight.color *= punctualLightIntensityToIrradianceFactor( lightDistance, pointLight.distance, pointLight.decay );\n\t\tdirectLight.visible = ( directLight.color != vec3( 0.0 ) );\n\t}\n#endif\n#if NUM_SPOT_LIGHTS > 0\n\tstruct SpotLight {\n\t\tvec3 position;\n\t\tvec3 direction;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t\tfloat coneCos;\n\t\tfloat penumbraCos;\n\t};\n\tuniform SpotLight spotLights[ NUM_SPOT_LIGHTS ];\n\tvoid getSpotDirectLightIrradiance( const in SpotLight spotLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\t\tvec3 lVector = spotLight.position - geometry.position;\n\t\tdirectLight.direction = normalize( lVector );\n\t\tfloat lightDistance = length( lVector );\n\t\tfloat angleCos = dot( directLight.direction, spotLight.direction );\n\t\tif ( angleCos > spotLight.coneCos ) {\n\t\t\tfloat spotEffect = smoothstep( spotLight.coneCos, spotLight.penumbraCos, angleCos );\n\t\t\tdirectLight.color = spotLight.color;\n\t\t\tdirectLight.color *= spotEffect * punctualLightIntensityToIrradianceFactor( lightDistance, spotLight.distance, spotLight.decay );\n\t\t\tdirectLight.visible = true;\n\t\t} else {\n\t\t\tdirectLight.color = vec3( 0.0 );\n\t\t\tdirectLight.visible = false;\n\t\t}\n\t}\n#endif\n#if NUM_RECT_AREA_LIGHTS > 0\n\tstruct RectAreaLight {\n\t\tvec3 color;\n\t\tvec3 position;\n\t\tvec3 halfWidth;\n\t\tvec3 halfHeight;\n\t};\n\tuniform sampler2D ltc_1;\tuniform sampler2D ltc_2;\n\tuniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ];\n#endif\n#if NUM_HEMI_LIGHTS > 0\n\tstruct HemisphereLight {\n\t\tvec3 direction;\n\t\tvec3 skyColor;\n\t\tvec3 groundColor;\n\t};\n\tuniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ];\n\tvec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in GeometricContext geometry ) {\n\t\tfloat dotNL = dot( geometry.normal, hemiLight.direction );\n\t\tfloat hemiDiffuseWeight = 0.5 * dotNL + 0.5;\n\t\tvec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight );\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\t\tirradiance *= PI;\n\t\t#endif\n\t\treturn irradiance;\n\t}\n#endif";
  14443. var envmap_physical_pars_fragment = "#if defined( USE_ENVMAP )\n\t#ifdef ENVMAP_MODE_REFRACTION\n\t\tuniform float refractionRatio;\n\t#endif\n\tvec3 getLightProbeIndirectIrradiance( const in GeometricContext geometry, const in int maxMIPLevel ) {\n\t\tvec3 worldNormal = inverseTransformDirection( geometry.normal, viewMatrix );\n\t\t#ifdef ENVMAP_TYPE_CUBE\n\t\t\tvec3 queryVec = vec3( flipEnvMap * worldNormal.x, worldNormal.yz );\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = textureCubeLodEXT( envMap, queryVec, float( maxMIPLevel ) );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = textureCube( envMap, queryVec, float( maxMIPLevel ) );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, worldNormal, 1.0 );\n\t\t#else\n\t\t\tvec4 envMapColor = vec4( 0.0 );\n\t\t#endif\n\t\treturn PI * envMapColor.rgb * envMapIntensity;\n\t}\n\tfloat getSpecularMIPLevel( const in float roughness, const in int maxMIPLevel ) {\n\t\tfloat maxMIPLevelScalar = float( maxMIPLevel );\n\t\tfloat sigma = PI * roughness * roughness / ( 1.0 + roughness );\n\t\tfloat desiredMIPLevel = maxMIPLevelScalar + log2( sigma );\n\t\treturn clamp( desiredMIPLevel, 0.0, maxMIPLevelScalar );\n\t}\n\tvec3 getLightProbeIndirectRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness, const in int maxMIPLevel ) {\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvec3 reflectVec = reflect( -viewDir, normal );\n\t\t\treflectVec = normalize( mix( reflectVec, normal, roughness * roughness) );\n\t\t#else\n\t\t\tvec3 reflectVec = refract( -viewDir, normal, refractionRatio );\n\t\t#endif\n\t\treflectVec = inverseTransformDirection( reflectVec, viewMatrix );\n\t\tfloat specularMIPLevel = getSpecularMIPLevel( roughness, maxMIPLevel );\n\t\t#ifdef ENVMAP_TYPE_CUBE\n\t\t\tvec3 queryReflectVec = vec3( flipEnvMap * reflectVec.x, reflectVec.yz );\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = textureCubeLodEXT( envMap, queryReflectVec, specularMIPLevel );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = textureCube( envMap, queryReflectVec, specularMIPLevel );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, reflectVec, roughness );\n\t\t#endif\n\t\treturn envMapColor.rgb * envMapIntensity;\n\t}\n#endif";
  14444. var lights_toon_fragment = "ToonMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;";
  14445. var lights_toon_pars_fragment = "varying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\nstruct ToonMaterial {\n\tvec3 diffuseColor;\n};\nvoid RE_Direct_Toon( const in IncidentLight directLight, const in GeometricContext geometry, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {\n\tvec3 irradiance = getGradientIrradiance( geometry.normal, directLight.direction ) * directLight.color;\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\treflectedLight.directDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Toon( const in vec3 irradiance, const in GeometricContext geometry, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_Toon\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Toon\n#define Material_LightProbeLOD( material )\t(0)";
  14446. var lights_phong_fragment = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;";
  14447. var lights_phong_pars_fragment = "varying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\nstruct BlinnPhongMaterial {\n\tvec3 diffuseColor;\n\tvec3 specularColor;\n\tfloat specularShininess;\n\tfloat specularStrength;\n};\nvoid RE_Direct_BlinnPhong( const in IncidentLight directLight, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\treflectedLight.directDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n\treflectedLight.directSpecular += irradiance * BRDF_Specular_BlinnPhong( directLight, geometry, material.specularColor, material.specularShininess ) * material.specularStrength;\n}\nvoid RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_BlinnPhong\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_BlinnPhong\n#define Material_LightProbeLOD( material )\t(0)";
  14448. var lights_physical_fragment = "PhysicalMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor );\nvec3 dxy = max( abs( dFdx( geometryNormal ) ), abs( dFdy( geometryNormal ) ) );\nfloat geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z );\nmaterial.specularRoughness = max( roughnessFactor, 0.0525 );material.specularRoughness += geometryRoughness;\nmaterial.specularRoughness = min( material.specularRoughness, 1.0 );\n#ifdef REFLECTIVITY\n\tmaterial.specularColor = mix( vec3( MAXIMUM_SPECULAR_COEFFICIENT * pow2( reflectivity ) ), diffuseColor.rgb, metalnessFactor );\n#else\n\tmaterial.specularColor = mix( vec3( DEFAULT_SPECULAR_COEFFICIENT ), diffuseColor.rgb, metalnessFactor );\n#endif\n#ifdef CLEARCOAT\n\tmaterial.clearcoat = clearcoat;\n\tmaterial.clearcoatRoughness = clearcoatRoughness;\n\t#ifdef USE_CLEARCOATMAP\n\t\tmaterial.clearcoat *= texture2D( clearcoatMap, vUv ).x;\n\t#endif\n\t#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\t\tmaterial.clearcoatRoughness *= texture2D( clearcoatRoughnessMap, vUv ).y;\n\t#endif\n\tmaterial.clearcoat = saturate( material.clearcoat );\tmaterial.clearcoatRoughness = max( material.clearcoatRoughness, 0.0525 );\n\tmaterial.clearcoatRoughness += geometryRoughness;\n\tmaterial.clearcoatRoughness = min( material.clearcoatRoughness, 1.0 );\n#endif\n#ifdef USE_SHEEN\n\tmaterial.sheenColor = sheen;\n#endif";
  14449. var lights_physical_pars_fragment = "struct PhysicalMaterial {\n\tvec3 diffuseColor;\n\tfloat specularRoughness;\n\tvec3 specularColor;\n#ifdef CLEARCOAT\n\tfloat clearcoat;\n\tfloat clearcoatRoughness;\n#endif\n#ifdef USE_SHEEN\n\tvec3 sheenColor;\n#endif\n};\n#define MAXIMUM_SPECULAR_COEFFICIENT 0.16\n#define DEFAULT_SPECULAR_COEFFICIENT 0.04\nfloat clearcoatDHRApprox( const in float roughness, const in float dotNL ) {\n\treturn DEFAULT_SPECULAR_COEFFICIENT + ( 1.0 - DEFAULT_SPECULAR_COEFFICIENT ) * ( pow( 1.0 - dotNL, 5.0 ) * pow( 1.0 - roughness, 2.0 ) );\n}\n#if NUM_RECT_AREA_LIGHTS > 0\n\tvoid RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\t\tvec3 normal = geometry.normal;\n\t\tvec3 viewDir = geometry.viewDir;\n\t\tvec3 position = geometry.position;\n\t\tvec3 lightPos = rectAreaLight.position;\n\t\tvec3 halfWidth = rectAreaLight.halfWidth;\n\t\tvec3 halfHeight = rectAreaLight.halfHeight;\n\t\tvec3 lightColor = rectAreaLight.color;\n\t\tfloat roughness = material.specularRoughness;\n\t\tvec3 rectCoords[ 4 ];\n\t\trectCoords[ 0 ] = lightPos + halfWidth - halfHeight;\t\trectCoords[ 1 ] = lightPos - halfWidth - halfHeight;\n\t\trectCoords[ 2 ] = lightPos - halfWidth + halfHeight;\n\t\trectCoords[ 3 ] = lightPos + halfWidth + halfHeight;\n\t\tvec2 uv = LTC_Uv( normal, viewDir, roughness );\n\t\tvec4 t1 = texture2D( ltc_1, uv );\n\t\tvec4 t2 = texture2D( ltc_2, uv );\n\t\tmat3 mInv = mat3(\n\t\t\tvec3( t1.x, 0, t1.y ),\n\t\t\tvec3( 0, 1, 0 ),\n\t\t\tvec3( t1.z, 0, t1.w )\n\t\t);\n\t\tvec3 fresnel = ( material.specularColor * t2.x + ( vec3( 1.0 ) - material.specularColor ) * t2.y );\n\t\treflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords );\n\t\treflectedLight.directDiffuse += lightColor * material.diffuseColor * LTC_Evaluate( normal, viewDir, position, mat3( 1.0 ), rectCoords );\n\t}\n#endif\nvoid RE_Direct_Physical( const in IncidentLight directLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\t#ifdef CLEARCOAT\n\t\tfloat ccDotNL = saturate( dot( geometry.clearcoatNormal, directLight.direction ) );\n\t\tvec3 ccIrradiance = ccDotNL * directLight.color;\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\t\tccIrradiance *= PI;\n\t\t#endif\n\t\tfloat clearcoatDHR = material.clearcoat * clearcoatDHRApprox( material.clearcoatRoughness, ccDotNL );\n\t\treflectedLight.directSpecular += ccIrradiance * material.clearcoat * BRDF_Specular_GGX( directLight, geometry.viewDir, geometry.clearcoatNormal, vec3( DEFAULT_SPECULAR_COEFFICIENT ), material.clearcoatRoughness );\n\t#else\n\t\tfloat clearcoatDHR = 0.0;\n\t#endif\n\t#ifdef USE_SHEEN\n\t\treflectedLight.directSpecular += ( 1.0 - clearcoatDHR ) * irradiance * BRDF_Specular_Sheen(\n\t\t\tmaterial.specularRoughness,\n\t\t\tdirectLight.direction,\n\t\t\tgeometry,\n\t\t\tmaterial.sheenColor\n\t\t);\n\t#else\n\t\treflectedLight.directSpecular += ( 1.0 - clearcoatDHR ) * irradiance * BRDF_Specular_GGX( directLight, geometry.viewDir, geometry.normal, material.specularColor, material.specularRoughness);\n\t#endif\n\treflectedLight.directDiffuse += ( 1.0 - clearcoatDHR ) * irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 irradiance, const in vec3 clearcoatRadiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight) {\n\t#ifdef CLEARCOAT\n\t\tfloat ccDotNV = saturate( dot( geometry.clearcoatNormal, geometry.viewDir ) );\n\t\treflectedLight.indirectSpecular += clearcoatRadiance * material.clearcoat * BRDF_Specular_GGX_Environment( geometry.viewDir, geometry.clearcoatNormal, vec3( DEFAULT_SPECULAR_COEFFICIENT ), material.clearcoatRoughness );\n\t\tfloat ccDotNL = ccDotNV;\n\t\tfloat clearcoatDHR = material.clearcoat * clearcoatDHRApprox( material.clearcoatRoughness, ccDotNL );\n\t#else\n\t\tfloat clearcoatDHR = 0.0;\n\t#endif\n\tfloat clearcoatInv = 1.0 - clearcoatDHR;\n\tvec3 singleScattering = vec3( 0.0 );\n\tvec3 multiScattering = vec3( 0.0 );\n\tvec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI;\n\tBRDF_Specular_Multiscattering_Environment( geometry, material.specularColor, material.specularRoughness, singleScattering, multiScattering );\n\tvec3 diffuse = material.diffuseColor * ( 1.0 - ( singleScattering + multiScattering ) );\n\treflectedLight.indirectSpecular += clearcoatInv * radiance * singleScattering;\n\treflectedLight.indirectSpecular += multiScattering * cosineWeightedIrradiance;\n\treflectedLight.indirectDiffuse += diffuse * cosineWeightedIrradiance;\n}\n#define RE_Direct\t\t\t\tRE_Direct_Physical\n#define RE_Direct_RectArea\t\tRE_Direct_RectArea_Physical\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Physical\n#define RE_IndirectSpecular\t\tRE_IndirectSpecular_Physical\nfloat computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) {\n\treturn saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion );\n}";
  14450. var lights_fragment_begin = "\nGeometricContext geometry;\ngeometry.position = - vViewPosition;\ngeometry.normal = normal;\ngeometry.viewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition );\n#ifdef CLEARCOAT\n\tgeometry.clearcoatNormal = clearcoatNormal;\n#endif\nIncidentLight directLight;\n#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )\n\tPointLight pointLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0\n\tPointLightShadow pointLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tpointLight = pointLights[ i ];\n\t\tgetPointDirectLightIrradiance( pointLight, geometry, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS )\n\t\tpointLightShadow = pointLightShadows[ i ];\n\t\tdirectLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )\n\tSpotLight spotLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0\n\tSpotLightShadow spotLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tspotLight = spotLights[ i ];\n\t\tgetSpotDirectLightIrradiance( spotLight, geometry, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\tspotLightShadow = spotLightShadows[ i ];\n\t\tdirectLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )\n\tDirectionalLight directionalLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0\n\tDirectionalLightShadow directionalLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tdirectionalLight = directionalLights[ i ];\n\t\tgetDirectionalDirectLightIrradiance( directionalLight, geometry, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS )\n\t\tdirectionalLightShadow = directionalLightShadows[ i ];\n\t\tdirectLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea )\n\tRectAreaLight rectAreaLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) {\n\t\trectAreaLight = rectAreaLights[ i ];\n\t\tRE_Direct_RectArea( rectAreaLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if defined( RE_IndirectDiffuse )\n\tvec3 iblIrradiance = vec3( 0.0 );\n\tvec3 irradiance = getAmbientLightIrradiance( ambientLightColor );\n\tirradiance += getLightProbeIrradiance( lightProbe, geometry );\n\t#if ( NUM_HEMI_LIGHTS > 0 )\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\t\tirradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry );\n\t\t}\n\t\t#pragma unroll_loop_end\n\t#endif\n#endif\n#if defined( RE_IndirectSpecular )\n\tvec3 radiance = vec3( 0.0 );\n\tvec3 clearcoatRadiance = vec3( 0.0 );\n#endif";
  14451. var lights_fragment_maps = "#if defined( RE_IndirectDiffuse )\n\t#ifdef USE_LIGHTMAP\n\t\tvec4 lightMapTexel= texture2D( lightMap, vUv2 );\n\t\tvec3 lightMapIrradiance = lightMapTexelToLinear( lightMapTexel ).rgb * lightMapIntensity;\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\t\tlightMapIrradiance *= PI;\n\t\t#endif\n\t\tirradiance += lightMapIrradiance;\n\t#endif\n\t#if defined( USE_ENVMAP ) && defined( STANDARD ) && defined( ENVMAP_TYPE_CUBE_UV )\n\t\tiblIrradiance += getLightProbeIndirectIrradiance( geometry, maxMipLevel );\n\t#endif\n#endif\n#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )\n\tradiance += getLightProbeIndirectRadiance( geometry.viewDir, geometry.normal, material.specularRoughness, maxMipLevel );\n\t#ifdef CLEARCOAT\n\t\tclearcoatRadiance += getLightProbeIndirectRadiance( geometry.viewDir, geometry.clearcoatNormal, material.clearcoatRoughness, maxMipLevel );\n\t#endif\n#endif";
  14452. var lights_fragment_end = "#if defined( RE_IndirectDiffuse )\n\tRE_IndirectDiffuse( irradiance, geometry, material, reflectedLight );\n#endif\n#if defined( RE_IndirectSpecular )\n\tRE_IndirectSpecular( radiance, iblIrradiance, clearcoatRadiance, geometry, material, reflectedLight );\n#endif";
  14453. var logdepthbuf_fragment = "#if defined( USE_LOGDEPTHBUF ) && defined( USE_LOGDEPTHBUF_EXT )\n\tgl_FragDepthEXT = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;\n#endif";
  14454. var logdepthbuf_pars_fragment = "#if defined( USE_LOGDEPTHBUF ) && defined( USE_LOGDEPTHBUF_EXT )\n\tuniform float logDepthBufFC;\n\tvarying float vFragDepth;\n\tvarying float vIsPerspective;\n#endif";
  14455. var logdepthbuf_pars_vertex = "#ifdef USE_LOGDEPTHBUF\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvarying float vFragDepth;\n\t\tvarying float vIsPerspective;\n\t#else\n\t\tuniform float logDepthBufFC;\n\t#endif\n#endif";
  14456. var logdepthbuf_vertex = "#ifdef USE_LOGDEPTHBUF\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvFragDepth = 1.0 + gl_Position.w;\n\t\tvIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) );\n\t#else\n\t\tif ( isPerspectiveMatrix( projectionMatrix ) ) {\n\t\t\tgl_Position.z = log2( max( EPSILON, gl_Position.w + 1.0 ) ) * logDepthBufFC - 1.0;\n\t\t\tgl_Position.z *= gl_Position.w;\n\t\t}\n\t#endif\n#endif";
  14457. var map_fragment = "#ifdef USE_MAP\n\tvec4 texelColor = texture2D( map, vUv );\n\ttexelColor = mapTexelToLinear( texelColor );\n\tdiffuseColor *= texelColor;\n#endif";
  14458. var map_pars_fragment = "#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif";
  14459. var map_particle_fragment = "#if defined( USE_MAP ) || defined( USE_ALPHAMAP )\n\tvec2 uv = ( uvTransform * vec3( gl_PointCoord.x, 1.0 - gl_PointCoord.y, 1 ) ).xy;\n#endif\n#ifdef USE_MAP\n\tvec4 mapTexel = texture2D( map, uv );\n\tdiffuseColor *= mapTexelToLinear( mapTexel );\n#endif\n#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, uv ).g;\n#endif";
  14460. var map_particle_pars_fragment = "#if defined( USE_MAP ) || defined( USE_ALPHAMAP )\n\tuniform mat3 uvTransform;\n#endif\n#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif\n#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif";
  14461. var metalnessmap_fragment = "float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vUv );\n\tmetalnessFactor *= texelMetalness.b;\n#endif";
  14462. var metalnessmap_pars_fragment = "#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif";
  14463. var morphnormal_vertex = "#ifdef USE_MORPHNORMALS\n\tobjectNormal *= morphTargetBaseInfluence;\n\tobjectNormal += morphNormal0 * morphTargetInfluences[ 0 ];\n\tobjectNormal += morphNormal1 * morphTargetInfluences[ 1 ];\n\tobjectNormal += morphNormal2 * morphTargetInfluences[ 2 ];\n\tobjectNormal += morphNormal3 * morphTargetInfluences[ 3 ];\n#endif";
  14464. var morphtarget_pars_vertex = "#ifdef USE_MORPHTARGETS\n\tuniform float morphTargetBaseInfluence;\n\t#ifndef USE_MORPHNORMALS\n\t\tuniform float morphTargetInfluences[ 8 ];\n\t#else\n\t\tuniform float morphTargetInfluences[ 4 ];\n\t#endif\n#endif";
  14465. var morphtarget_vertex = "#ifdef USE_MORPHTARGETS\n\ttransformed *= morphTargetBaseInfluence;\n\ttransformed += morphTarget0 * morphTargetInfluences[ 0 ];\n\ttransformed += morphTarget1 * morphTargetInfluences[ 1 ];\n\ttransformed += morphTarget2 * morphTargetInfluences[ 2 ];\n\ttransformed += morphTarget3 * morphTargetInfluences[ 3 ];\n\t#ifndef USE_MORPHNORMALS\n\t\ttransformed += morphTarget4 * morphTargetInfluences[ 4 ];\n\t\ttransformed += morphTarget5 * morphTargetInfluences[ 5 ];\n\t\ttransformed += morphTarget6 * morphTargetInfluences[ 6 ];\n\t\ttransformed += morphTarget7 * morphTargetInfluences[ 7 ];\n\t#endif\n#endif";
  14466. var normal_fragment_begin = "#ifdef FLAT_SHADED\n\tvec3 fdx = vec3( dFdx( vViewPosition.x ), dFdx( vViewPosition.y ), dFdx( vViewPosition.z ) );\n\tvec3 fdy = vec3( dFdy( vViewPosition.x ), dFdy( vViewPosition.y ), dFdy( vViewPosition.z ) );\n\tvec3 normal = normalize( cross( fdx, fdy ) );\n#else\n\tvec3 normal = normalize( vNormal );\n\t#ifdef DOUBLE_SIDED\n\t\tnormal = normal * ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n\t#endif\n\t#ifdef USE_TANGENT\n\t\tvec3 tangent = normalize( vTangent );\n\t\tvec3 bitangent = normalize( vBitangent );\n\t\t#ifdef DOUBLE_SIDED\n\t\t\ttangent = tangent * ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n\t\t\tbitangent = bitangent * ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n\t\t#endif\n\t\t#if defined( TANGENTSPACE_NORMALMAP ) || defined( USE_CLEARCOAT_NORMALMAP )\n\t\t\tmat3 vTBN = mat3( tangent, bitangent, normal );\n\t\t#endif\n\t#endif\n#endif\nvec3 geometryNormal = normal;";
  14467. var normal_fragment_maps = "#ifdef OBJECTSPACE_NORMALMAP\n\tnormal = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;\n\t#ifdef FLIP_SIDED\n\t\tnormal = - normal;\n\t#endif\n\t#ifdef DOUBLE_SIDED\n\t\tnormal = normal * ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n\t#endif\n\tnormal = normalize( normalMatrix * normal );\n#elif defined( TANGENTSPACE_NORMALMAP )\n\tvec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;\n\tmapN.xy *= normalScale;\n\t#ifdef USE_TANGENT\n\t\tnormal = normalize( vTBN * mapN );\n\t#else\n\t\tnormal = perturbNormal2Arb( -vViewPosition, normal, mapN );\n\t#endif\n#elif defined( USE_BUMPMAP )\n\tnormal = perturbNormalArb( -vViewPosition, normal, dHdxy_fwd() );\n#endif";
  14468. var normalmap_pars_fragment = "#ifdef USE_NORMALMAP\n\tuniform sampler2D normalMap;\n\tuniform vec2 normalScale;\n#endif\n#ifdef OBJECTSPACE_NORMALMAP\n\tuniform mat3 normalMatrix;\n#endif\n#if ! defined ( USE_TANGENT ) && ( defined ( TANGENTSPACE_NORMALMAP ) || defined ( USE_CLEARCOAT_NORMALMAP ) )\n\tvec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm, vec3 mapN ) {\n\t\tvec3 q0 = vec3( dFdx( eye_pos.x ), dFdx( eye_pos.y ), dFdx( eye_pos.z ) );\n\t\tvec3 q1 = vec3( dFdy( eye_pos.x ), dFdy( eye_pos.y ), dFdy( eye_pos.z ) );\n\t\tvec2 st0 = dFdx( vUv.st );\n\t\tvec2 st1 = dFdy( vUv.st );\n\t\tfloat scale = sign( st1.t * st0.s - st0.t * st1.s );\n\t\tvec3 S = normalize( ( q0 * st1.t - q1 * st0.t ) * scale );\n\t\tvec3 T = normalize( ( - q0 * st1.s + q1 * st0.s ) * scale );\n\t\tvec3 N = normalize( surf_norm );\n\t\tmat3 tsn = mat3( S, T, N );\n\t\tmapN.xy *= ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n\t\treturn normalize( tsn * mapN );\n\t}\n#endif";
  14469. var clearcoat_normal_fragment_begin = "#ifdef CLEARCOAT\n\tvec3 clearcoatNormal = geometryNormal;\n#endif";
  14470. var clearcoat_normal_fragment_maps = "#ifdef USE_CLEARCOAT_NORMALMAP\n\tvec3 clearcoatMapN = texture2D( clearcoatNormalMap, vUv ).xyz * 2.0 - 1.0;\n\tclearcoatMapN.xy *= clearcoatNormalScale;\n\t#ifdef USE_TANGENT\n\t\tclearcoatNormal = normalize( vTBN * clearcoatMapN );\n\t#else\n\t\tclearcoatNormal = perturbNormal2Arb( - vViewPosition, clearcoatNormal, clearcoatMapN );\n\t#endif\n#endif";
  14471. var clearcoat_pars_fragment = "#ifdef USE_CLEARCOATMAP\n\tuniform sampler2D clearcoatMap;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\tuniform sampler2D clearcoatRoughnessMap;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\tuniform sampler2D clearcoatNormalMap;\n\tuniform vec2 clearcoatNormalScale;\n#endif";
  14472. var packing = "vec3 packNormalToRGB( const in vec3 normal ) {\n\treturn normalize( normal ) * 0.5 + 0.5;\n}\nvec3 unpackRGBToNormal( const in vec3 rgb ) {\n\treturn 2.0 * rgb.xyz - 1.0;\n}\nconst float PackUpscale = 256. / 255.;const float UnpackDownscale = 255. / 256.;\nconst vec3 PackFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );\nconst vec4 UnpackFactors = UnpackDownscale / vec4( PackFactors, 1. );\nconst float ShiftRight8 = 1. / 256.;\nvec4 packDepthToRGBA( const in float v ) {\n\tvec4 r = vec4( fract( v * PackFactors ), v );\n\tr.yzw -= r.xyz * ShiftRight8;\treturn r * PackUpscale;\n}\nfloat unpackRGBAToDepth( const in vec4 v ) {\n\treturn dot( v, UnpackFactors );\n}\nvec4 pack2HalfToRGBA( vec2 v ) {\n\tvec4 r = vec4( v.x, fract( v.x * 255.0 ), v.y, fract( v.y * 255.0 ));\n\treturn vec4( r.x - r.y / 255.0, r.y, r.z - r.w / 255.0, r.w);\n}\nvec2 unpackRGBATo2Half( vec4 v ) {\n\treturn vec2( v.x + ( v.y / 255.0 ), v.z + ( v.w / 255.0 ) );\n}\nfloat viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn ( viewZ + near ) / ( near - far );\n}\nfloat orthographicDepthToViewZ( const in float linearClipZ, const in float near, const in float far ) {\n\treturn linearClipZ * ( near - far ) - near;\n}\nfloat viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn (( near + viewZ ) * far ) / (( far - near ) * viewZ );\n}\nfloat perspectiveDepthToViewZ( const in float invClipZ, const in float near, const in float far ) {\n\treturn ( near * far ) / ( ( far - near ) * invClipZ - far );\n}";
  14473. var premultiplied_alpha_fragment = "#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif";
  14474. var project_vertex = "vec4 mvPosition = vec4( transformed, 1.0 );\n#ifdef USE_INSTANCING\n\tmvPosition = instanceMatrix * mvPosition;\n#endif\nmvPosition = modelViewMatrix * mvPosition;\ngl_Position = projectionMatrix * mvPosition;";
  14475. var dithering_fragment = "#ifdef DITHERING\n\tgl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif";
  14476. var dithering_pars_fragment = "#ifdef DITHERING\n\tvec3 dithering( vec3 color ) {\n\t\tfloat grid_position = rand( gl_FragCoord.xy );\n\t\tvec3 dither_shift_RGB = vec3( 0.25 / 255.0, -0.25 / 255.0, 0.25 / 255.0 );\n\t\tdither_shift_RGB = mix( 2.0 * dither_shift_RGB, -2.0 * dither_shift_RGB, grid_position );\n\t\treturn color + dither_shift_RGB;\n\t}\n#endif";
  14477. var roughnessmap_fragment = "float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vUv );\n\troughnessFactor *= texelRoughness.g;\n#endif";
  14478. var roughnessmap_pars_fragment = "#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif";
  14479. var shadowmap_pars_fragment = "#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tstruct DirectionalLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vSpotShadowCoord[ NUM_SPOT_LIGHT_SHADOWS ];\n\t\tstruct SpotLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tstruct PointLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t\tfloat shadowCameraNear;\n\t\t\tfloat shadowCameraFar;\n\t\t};\n\t\tuniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];\n\t#endif\n\tfloat texture2DCompare( sampler2D depths, vec2 uv, float compare ) {\n\t\treturn step( compare, unpackRGBAToDepth( texture2D( depths, uv ) ) );\n\t}\n\tvec2 texture2DDistribution( sampler2D shadow, vec2 uv ) {\n\t\treturn unpackRGBATo2Half( texture2D( shadow, uv ) );\n\t}\n\tfloat VSMShadow (sampler2D shadow, vec2 uv, float compare ){\n\t\tfloat occlusion = 1.0;\n\t\tvec2 distribution = texture2DDistribution( shadow, uv );\n\t\tfloat hard_shadow = step( compare , distribution.x );\n\t\tif (hard_shadow != 1.0 ) {\n\t\t\tfloat distance = compare - distribution.x ;\n\t\t\tfloat variance = max( 0.00000, distribution.y * distribution.y );\n\t\t\tfloat softness_probability = variance / (variance + distance * distance );\t\t\tsoftness_probability = clamp( ( softness_probability - 0.3 ) / ( 0.95 - 0.3 ), 0.0, 1.0 );\t\t\tocclusion = clamp( max( hard_shadow, softness_probability ), 0.0, 1.0 );\n\t\t}\n\t\treturn occlusion;\n\t}\n\tfloat getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\t\tfloat shadow = 1.0;\n\t\tshadowCoord.xyz /= shadowCoord.w;\n\t\tshadowCoord.z += shadowBias;\n\t\tbvec4 inFrustumVec = bvec4 ( shadowCoord.x >= 0.0, shadowCoord.x <= 1.0, shadowCoord.y >= 0.0, shadowCoord.y <= 1.0 );\n\t\tbool inFrustum = all( inFrustumVec );\n\t\tbvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 );\n\t\tbool frustumTest = all( frustumTestVec );\n\t\tif ( frustumTest ) {\n\t\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx0 = - texelSize.x * shadowRadius;\n\t\t\tfloat dy0 = - texelSize.y * shadowRadius;\n\t\t\tfloat dx1 = + texelSize.x * shadowRadius;\n\t\t\tfloat dy1 = + texelSize.y * shadowRadius;\n\t\t\tfloat dx2 = dx0 / 2.0;\n\t\t\tfloat dy2 = dy0 / 2.0;\n\t\t\tfloat dx3 = dx1 / 2.0;\n\t\t\tfloat dy3 = dy1 / 2.0;\n\t\t\tshadow = (\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )\n\t\t\t) * ( 1.0 / 17.0 );\n\t\t#elif defined( SHADOWMAP_TYPE_PCF_SOFT )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx = texelSize.x;\n\t\t\tfloat dy = texelSize.y;\n\t\t\tvec2 uv = shadowCoord.xy;\n\t\t\tvec2 f = fract( uv * shadowMapSize + 0.5 );\n\t\t\tuv -= f * texelSize;\n\t\t\tshadow = (\n\t\t\t\ttexture2DCompare( shadowMap, uv, shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + vec2( dx, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + vec2( 0.0, dy ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + texelSize, shadowCoord.z ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( -dx, 0.0 ), shadowCoord.z ), \n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 0.0 ), shadowCoord.z ),\n\t\t\t\t\t f.x ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( -dx, dy ), shadowCoord.z ), \n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, dy ), shadowCoord.z ),\n\t\t\t\t\t f.x ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( 0.0, -dy ), shadowCoord.z ), \n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 0.0, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t f.y ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( dx, -dy ), shadowCoord.z ), \n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( dx, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t f.y ) +\n\t\t\t\tmix( mix( texture2DCompare( shadowMap, uv + vec2( -dx, -dy ), shadowCoord.z ), \n\t\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, -dy ), shadowCoord.z ),\n\t\t\t\t\t\t f.x ),\n\t\t\t\t\t mix( texture2DCompare( shadowMap, uv + vec2( -dx, 2.0 * dy ), shadowCoord.z ), \n\t\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t\t f.x ),\n\t\t\t\t\t f.y )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#elif defined( SHADOWMAP_TYPE_VSM )\n\t\t\tshadow = VSMShadow( shadowMap, shadowCoord.xy, shadowCoord.z );\n\t\t#else\n\t\t\tshadow = texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z );\n\t\t#endif\n\t\t}\n\t\treturn shadow;\n\t}\n\tvec2 cubeToUV( vec3 v, float texelSizeY ) {\n\t\tvec3 absV = abs( v );\n\t\tfloat scaleToCube = 1.0 / max( absV.x, max( absV.y, absV.z ) );\n\t\tabsV *= scaleToCube;\n\t\tv *= scaleToCube * ( 1.0 - 2.0 * texelSizeY );\n\t\tvec2 planar = v.xy;\n\t\tfloat almostATexel = 1.5 * texelSizeY;\n\t\tfloat almostOne = 1.0 - almostATexel;\n\t\tif ( absV.z >= almostOne ) {\n\t\t\tif ( v.z > 0.0 )\n\t\t\t\tplanar.x = 4.0 - v.x;\n\t\t} else if ( absV.x >= almostOne ) {\n\t\t\tfloat signX = sign( v.x );\n\t\t\tplanar.x = v.z * signX + 2.0 * signX;\n\t\t} else if ( absV.y >= almostOne ) {\n\t\t\tfloat signY = sign( v.y );\n\t\t\tplanar.x = v.x + 2.0 * signY + 2.0;\n\t\t\tplanar.y = v.z * signY - 2.0;\n\t\t}\n\t\treturn vec2( 0.125, 0.25 ) * planar + vec2( 0.375, 0.75 );\n\t}\n\tfloat getPointShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) {\n\t\tvec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) );\n\t\tvec3 lightToPosition = shadowCoord.xyz;\n\t\tfloat dp = ( length( lightToPosition ) - shadowCameraNear ) / ( shadowCameraFar - shadowCameraNear );\t\tdp += shadowBias;\n\t\tvec3 bd3D = normalize( lightToPosition );\n\t\t#if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT ) || defined( SHADOWMAP_TYPE_VSM )\n\t\t\tvec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y;\n\t\t\treturn (\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxx, texelSize.y ), dp )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#else\n\t\t\treturn texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp );\n\t\t#endif\n\t}\n#endif";
  14480. var shadowmap_pars_vertex = "#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\tuniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tstruct DirectionalLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t\tuniform mat4 spotShadowMatrix[ NUM_SPOT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vSpotShadowCoord[ NUM_SPOT_LIGHT_SHADOWS ];\n\t\tstruct SpotLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\tuniform mat4 pointShadowMatrix[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tstruct PointLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t\tfloat shadowCameraNear;\n\t\t\tfloat shadowCameraFar;\n\t\t};\n\t\tuniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];\n\t#endif\n#endif";
  14481. var shadowmap_vertex = "#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0 || NUM_SPOT_LIGHT_SHADOWS > 0 || NUM_POINT_LIGHT_SHADOWS > 0\n\t\tvec3 shadowWorldNormal = inverseTransformDirection( transformedNormal, viewMatrix );\n\t\tvec4 shadowWorldPosition;\n\t#endif\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n\t\tshadowWorldPosition = worldPosition + vec4( shadowWorldNormal * directionalLightShadows[ i ].shadowNormalBias, 0 );\n\t\tvDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * shadowWorldPosition;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) {\n\t\tshadowWorldPosition = worldPosition + vec4( shadowWorldNormal * spotLightShadows[ i ].shadowNormalBias, 0 );\n\t\tvSpotShadowCoord[ i ] = spotShadowMatrix[ i ] * shadowWorldPosition;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\n\t\tshadowWorldPosition = worldPosition + vec4( shadowWorldNormal * pointLightShadows[ i ].shadowNormalBias, 0 );\n\t\tvPointShadowCoord[ i ] = pointShadowMatrix[ i ] * shadowWorldPosition;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n#endif";
  14482. var shadowmask_pars_fragment = "float getShadowMask() {\n\tfloat shadow = 1.0;\n\t#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\tDirectionalLightShadow directionalLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n\t\tdirectionalLight = directionalLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\tSpotLightShadow spotLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) {\n\t\tspotLight = spotLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowBias, spotLight.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\tPointLightShadow pointLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\n\t\tpointLight = pointLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#endif\n\treturn shadow;\n}";
  14483. var skinbase_vertex = "#ifdef USE_SKINNING\n\tmat4 boneMatX = getBoneMatrix( skinIndex.x );\n\tmat4 boneMatY = getBoneMatrix( skinIndex.y );\n\tmat4 boneMatZ = getBoneMatrix( skinIndex.z );\n\tmat4 boneMatW = getBoneMatrix( skinIndex.w );\n#endif";
  14484. var skinning_pars_vertex = "#ifdef USE_SKINNING\n\tuniform mat4 bindMatrix;\n\tuniform mat4 bindMatrixInverse;\n\t#ifdef BONE_TEXTURE\n\t\tuniform highp sampler2D boneTexture;\n\t\tuniform int boneTextureSize;\n\t\tmat4 getBoneMatrix( const in float i ) {\n\t\t\tfloat j = i * 4.0;\n\t\t\tfloat x = mod( j, float( boneTextureSize ) );\n\t\t\tfloat y = floor( j / float( boneTextureSize ) );\n\t\t\tfloat dx = 1.0 / float( boneTextureSize );\n\t\t\tfloat dy = 1.0 / float( boneTextureSize );\n\t\t\ty = dy * ( y + 0.5 );\n\t\t\tvec4 v1 = texture2D( boneTexture, vec2( dx * ( x + 0.5 ), y ) );\n\t\t\tvec4 v2 = texture2D( boneTexture, vec2( dx * ( x + 1.5 ), y ) );\n\t\t\tvec4 v3 = texture2D( boneTexture, vec2( dx * ( x + 2.5 ), y ) );\n\t\t\tvec4 v4 = texture2D( boneTexture, vec2( dx * ( x + 3.5 ), y ) );\n\t\t\tmat4 bone = mat4( v1, v2, v3, v4 );\n\t\t\treturn bone;\n\t\t}\n\t#else\n\t\tuniform mat4 boneMatrices[ MAX_BONES ];\n\t\tmat4 getBoneMatrix( const in float i ) {\n\t\t\tmat4 bone = boneMatrices[ int(i) ];\n\t\t\treturn bone;\n\t\t}\n\t#endif\n#endif";
  14485. var skinning_vertex = "#ifdef USE_SKINNING\n\tvec4 skinVertex = bindMatrix * vec4( transformed, 1.0 );\n\tvec4 skinned = vec4( 0.0 );\n\tskinned += boneMatX * skinVertex * skinWeight.x;\n\tskinned += boneMatY * skinVertex * skinWeight.y;\n\tskinned += boneMatZ * skinVertex * skinWeight.z;\n\tskinned += boneMatW * skinVertex * skinWeight.w;\n\ttransformed = ( bindMatrixInverse * skinned ).xyz;\n#endif";
  14486. var skinnormal_vertex = "#ifdef USE_SKINNING\n\tmat4 skinMatrix = mat4( 0.0 );\n\tskinMatrix += skinWeight.x * boneMatX;\n\tskinMatrix += skinWeight.y * boneMatY;\n\tskinMatrix += skinWeight.z * boneMatZ;\n\tskinMatrix += skinWeight.w * boneMatW;\n\tskinMatrix = bindMatrixInverse * skinMatrix * bindMatrix;\n\tobjectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz;\n\t#ifdef USE_TANGENT\n\t\tobjectTangent = vec4( skinMatrix * vec4( objectTangent, 0.0 ) ).xyz;\n\t#endif\n#endif";
  14487. var specularmap_fragment = "float specularStrength;\n#ifdef USE_SPECULARMAP\n\tvec4 texelSpecular = texture2D( specularMap, vUv );\n\tspecularStrength = texelSpecular.r;\n#else\n\tspecularStrength = 1.0;\n#endif";
  14488. var specularmap_pars_fragment = "#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif";
  14489. var tonemapping_fragment = "#if defined( TONE_MAPPING )\n\tgl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif";
  14490. var tonemapping_pars_fragment = "#ifndef saturate\n#define saturate(a) clamp( a, 0.0, 1.0 )\n#endif\nuniform float toneMappingExposure;\nvec3 LinearToneMapping( vec3 color ) {\n\treturn toneMappingExposure * color;\n}\nvec3 ReinhardToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\treturn saturate( color / ( vec3( 1.0 ) + color ) );\n}\nvec3 OptimizedCineonToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\tcolor = max( vec3( 0.0 ), color - 0.004 );\n\treturn pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) );\n}\nvec3 RRTAndODTFit( vec3 v ) {\n\tvec3 a = v * ( v + 0.0245786 ) - 0.000090537;\n\tvec3 b = v * ( 0.983729 * v + 0.4329510 ) + 0.238081;\n\treturn a / b;\n}\nvec3 ACESFilmicToneMapping( vec3 color ) {\n\tconst mat3 ACESInputMat = mat3(\n\t\tvec3( 0.59719, 0.07600, 0.02840 ),\t\tvec3( 0.35458, 0.90834, 0.13383 ),\n\t\tvec3( 0.04823, 0.01566, 0.83777 )\n\t);\n\tconst mat3 ACESOutputMat = mat3(\n\t\tvec3( 1.60475, -0.10208, -0.00327 ),\t\tvec3( -0.53108, 1.10813, -0.07276 ),\n\t\tvec3( -0.07367, -0.00605, 1.07602 )\n\t);\n\tcolor *= toneMappingExposure / 0.6;\n\tcolor = ACESInputMat * color;\n\tcolor = RRTAndODTFit( color );\n\tcolor = ACESOutputMat * color;\n\treturn saturate( color );\n}\nvec3 CustomToneMapping( vec3 color ) { return color; }";
  14491. var transmissionmap_fragment = "#ifdef USE_TRANSMISSIONMAP\n\ttotalTransmission *= texture2D( transmissionMap, vUv ).r;\n#endif";
  14492. var transmissionmap_pars_fragment = "#ifdef USE_TRANSMISSIONMAP\n\tuniform sampler2D transmissionMap;\n#endif";
  14493. var uv_pars_fragment = "#if ( defined( USE_UV ) && ! defined( UVS_VERTEX_ONLY ) )\n\tvarying vec2 vUv;\n#endif";
  14494. var uv_pars_vertex = "#ifdef USE_UV\n\t#ifdef UVS_VERTEX_ONLY\n\t\tvec2 vUv;\n\t#else\n\t\tvarying vec2 vUv;\n\t#endif\n\tuniform mat3 uvTransform;\n#endif";
  14495. var uv_vertex = "#ifdef USE_UV\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n#endif";
  14496. var uv2_pars_fragment = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvarying vec2 vUv2;\n#endif";
  14497. var uv2_pars_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tattribute vec2 uv2;\n\tvarying vec2 vUv2;\n\tuniform mat3 uv2Transform;\n#endif";
  14498. var uv2_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvUv2 = ( uv2Transform * vec3( uv2, 1 ) ).xy;\n#endif";
  14499. var worldpos_vertex = "#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP )\n\tvec4 worldPosition = vec4( transformed, 1.0 );\n\t#ifdef USE_INSTANCING\n\t\tworldPosition = instanceMatrix * worldPosition;\n\t#endif\n\tworldPosition = modelMatrix * worldPosition;\n#endif";
  14500. var background_frag = "uniform sampler2D t2D;\nvarying vec2 vUv;\nvoid main() {\n\tvec4 texColor = texture2D( t2D, vUv );\n\tgl_FragColor = mapTexelToLinear( texColor );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n}";
  14501. var background_vert = "varying vec2 vUv;\nuniform mat3 uvTransform;\nvoid main() {\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n\tgl_Position = vec4( position.xy, 1.0, 1.0 );\n}";
  14502. var cube_frag = "#include <envmap_common_pars_fragment>\nuniform float opacity;\nvarying vec3 vWorldDirection;\n#include <cube_uv_reflection_fragment>\nvoid main() {\n\tvec3 vReflect = vWorldDirection;\n\t#include <envmap_fragment>\n\tgl_FragColor = envColor;\n\tgl_FragColor.a *= opacity;\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n}";
  14503. var cube_vert = "varying vec3 vWorldDirection;\n#include <common>\nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include <begin_vertex>\n\t#include <project_vertex>\n\tgl_Position.z = gl_Position.w;\n}";
  14504. var depth_frag = "#if DEPTH_PACKING == 3200\n\tuniform float opacity;\n#endif\n#include <common>\n#include <packing>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvarying vec2 vHighPrecisionZW;\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( 1.0 );\n\t#if DEPTH_PACKING == 3200\n\t\tdiffuseColor.a = opacity;\n\t#endif\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <logdepthbuf_fragment>\n\tfloat fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;\n\t#if DEPTH_PACKING == 3200\n\t\tgl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity );\n\t#elif DEPTH_PACKING == 3201\n\t\tgl_FragColor = packDepthToRGBA( fragCoordZ );\n\t#endif\n}";
  14505. var depth_vert = "#include <common>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvarying vec2 vHighPrecisionZW;\nvoid main() {\n\t#include <uv_vertex>\n\t#include <skinbase_vertex>\n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include <beginnormal_vertex>\n\t\t#include <morphnormal_vertex>\n\t\t#include <skinnormal_vertex>\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvHighPrecisionZW = gl_Position.zw;\n}";
  14506. var distanceRGBA_frag = "#define DISTANCE\nuniform vec3 referencePosition;\nuniform float nearDistance;\nuniform float farDistance;\nvarying vec3 vWorldPosition;\n#include <common>\n#include <packing>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main () {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( 1.0 );\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\tfloat dist = length( vWorldPosition - referencePosition );\n\tdist = ( dist - nearDistance ) / ( farDistance - nearDistance );\n\tdist = saturate( dist );\n\tgl_FragColor = packDepthToRGBA( dist );\n}";
  14507. var distanceRGBA_vert = "#define DISTANCE\nvarying vec3 vWorldPosition;\n#include <common>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <skinbase_vertex>\n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include <beginnormal_vertex>\n\t\t#include <morphnormal_vertex>\n\t\t#include <skinnormal_vertex>\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <worldpos_vertex>\n\t#include <clipping_planes_vertex>\n\tvWorldPosition = worldPosition.xyz;\n}";
  14508. var equirect_frag = "uniform sampler2D tEquirect;\nvarying vec3 vWorldDirection;\n#include <common>\nvoid main() {\n\tvec3 direction = normalize( vWorldDirection );\n\tvec2 sampleUV = equirectUv( direction );\n\tvec4 texColor = texture2D( tEquirect, sampleUV );\n\tgl_FragColor = mapTexelToLinear( texColor );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n}";
  14509. var equirect_vert = "varying vec3 vWorldDirection;\n#include <common>\nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include <begin_vertex>\n\t#include <project_vertex>\n}";
  14510. var linedashed_frag = "uniform vec3 diffuse;\nuniform float opacity;\nuniform float dashSize;\nuniform float totalSize;\nvarying float vLineDistance;\n#include <common>\n#include <color_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tif ( mod( vLineDistance, totalSize ) > dashSize ) {\n\t\tdiscard;\n\t}\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <color_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n}";
  14511. var linedashed_vert = "uniform float scale;\nattribute float lineDistance;\nvarying float vLineDistance;\n#include <common>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\tvLineDistance = scale * lineDistance;\n\t#include <color_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <fog_vertex>\n}";
  14512. var meshbasic_frag = "uniform vec3 diffuse;\nuniform float opacity;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <cube_uv_reflection_fragment>\n#include <fog_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\t#ifdef USE_LIGHTMAP\n\t\n\t\tvec4 lightMapTexel= texture2D( lightMap, vUv2 );\n\t\treflectedLight.indirectDiffuse += lightMapTexelToLinear( lightMapTexel ).rgb * lightMapIntensity;\n\t#else\n\t\treflectedLight.indirectDiffuse += vec3( 1.0 );\n\t#endif\n\t#include <aomap_fragment>\n\treflectedLight.indirectDiffuse *= diffuseColor.rgb;\n\tvec3 outgoingLight = reflectedLight.indirectDiffuse;\n\t#include <envmap_fragment>\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  14513. var meshbasic_vert = "#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <skinbase_vertex>\n\t#ifdef USE_ENVMAP\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <worldpos_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <envmap_vertex>\n\t#include <fog_vertex>\n}";
  14514. var meshlambert_frag = "uniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\nvarying vec3 vLightFront;\nvarying vec3 vIndirectFront;\n#ifdef DOUBLE_SIDED\n\tvarying vec3 vLightBack;\n\tvarying vec3 vIndirectBack;\n#endif\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <cube_uv_reflection_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <fog_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <shadowmask_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\t#include <emissivemap_fragment>\n\t#ifdef DOUBLE_SIDED\n\t\treflectedLight.indirectDiffuse += ( gl_FrontFacing ) ? vIndirectFront : vIndirectBack;\n\t#else\n\t\treflectedLight.indirectDiffuse += vIndirectFront;\n\t#endif\n\t#include <lightmap_fragment>\n\treflectedLight.indirectDiffuse *= BRDF_Diffuse_Lambert( diffuseColor.rgb );\n\t#ifdef DOUBLE_SIDED\n\t\treflectedLight.directDiffuse = ( gl_FrontFacing ) ? vLightFront : vLightBack;\n\t#else\n\t\treflectedLight.directDiffuse = vLightFront;\n\t#endif\n\treflectedLight.directDiffuse *= BRDF_Diffuse_Lambert( diffuseColor.rgb ) * getShadowMask();\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\t#include <envmap_fragment>\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  14515. var meshlambert_vert = "#define LAMBERT\nvarying vec3 vLightFront;\nvarying vec3 vIndirectFront;\n#ifdef DOUBLE_SIDED\n\tvarying vec3 vLightBack;\n\tvarying vec3 vIndirectBack;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <envmap_pars_vertex>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <lights_lambert_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";
  14516. var meshmatcap_frag = "#define MATCAP\nuniform vec3 diffuse;\nuniform float opacity;\nuniform sampler2D matcap;\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <fog_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\tvec3 viewDir = normalize( vViewPosition );\n\tvec3 x = normalize( vec3( viewDir.z, 0.0, - viewDir.x ) );\n\tvec3 y = cross( viewDir, x );\n\tvec2 uv = vec2( dot( x, normal ), dot( y, normal ) ) * 0.495 + 0.5;\n\t#ifdef USE_MATCAP\n\t\tvec4 matcapColor = texture2D( matcap, uv );\n\t\tmatcapColor = matcapTexelToLinear( matcapColor );\n\t#else\n\t\tvec4 matcapColor = vec4( 1.0 );\n\t#endif\n\tvec3 outgoingLight = diffuseColor.rgb * matcapColor.rgb;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  14517. var meshmatcap_vert = "#define MATCAP\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <color_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#ifndef FLAT_SHADED\n\t\tvNormal = normalize( transformedNormal );\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <fog_vertex>\n\tvViewPosition = - mvPosition.xyz;\n}";
  14518. var meshtoon_frag = "#define TOON\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <gradientmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <lights_toon_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <lights_toon_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  14519. var meshtoon_vert = "#define TOON\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";
  14520. var meshphong_frag = "#define PHONG\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform vec3 specular;\nuniform float shininess;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <cube_uv_reflection_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <lights_phong_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <lights_phong_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\t#include <envmap_fragment>\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  14521. var meshphong_vert = "#define PHONG\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";
  14522. var meshphysical_frag = "#define STANDARD\n#ifdef PHYSICAL\n\t#define REFLECTIVITY\n\t#define CLEARCOAT\n\t#define TRANSMISSION\n#endif\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float roughness;\nuniform float metalness;\nuniform float opacity;\n#ifdef TRANSMISSION\n\tuniform float transmission;\n#endif\n#ifdef REFLECTIVITY\n\tuniform float reflectivity;\n#endif\n#ifdef CLEARCOAT\n\tuniform float clearcoat;\n\tuniform float clearcoatRoughness;\n#endif\n#ifdef USE_SHEEN\n\tuniform vec3 sheen;\n#endif\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <transmissionmap_pars_fragment>\n#include <bsdfs>\n#include <cube_uv_reflection_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_physical_pars_fragment>\n#include <fog_pars_fragment>\n#include <lights_pars_begin>\n#include <lights_physical_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <clearcoat_pars_fragment>\n#include <roughnessmap_pars_fragment>\n#include <metalnessmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#ifdef TRANSMISSION\n\t\tfloat totalTransmission = transmission;\n\t#endif\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <roughnessmap_fragment>\n\t#include <metalnessmap_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <clearcoat_normal_fragment_begin>\n\t#include <clearcoat_normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <transmissionmap_fragment>\n\t#include <lights_physical_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\t#ifdef TRANSMISSION\n\t\tdiffuseColor.a *= mix( saturate( 1. - totalTransmission + linearToRelativeLuminance( reflectedLight.directSpecular + reflectedLight.indirectSpecular ) ), 1.0, metalness );\n\t#endif\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  14523. var meshphysical_vert = "#define STANDARD\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n\t#ifdef USE_TANGENT\n\t\tvTangent = normalize( transformedTangent );\n\t\tvBitangent = normalize( cross( vNormal, vTangent ) * tangent.w );\n\t#endif\n#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";
  14524. var normal_frag = "#define NORMAL\nuniform float opacity;\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvarying vec3 vViewPosition;\n#endif\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif\n#include <packing>\n#include <uv_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\t#include <logdepthbuf_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\tgl_FragColor = vec4( packNormalToRGB( normal ), opacity );\n}";
  14525. var normal_vert = "#define NORMAL\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvarying vec3 vViewPosition;\n#endif\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n\t#ifdef USE_TANGENT\n\t\tvTangent = normalize( transformedTangent );\n\t\tvBitangent = normalize( cross( vNormal, vTangent ) * tangent.w );\n\t#endif\n#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvViewPosition = - mvPosition.xyz;\n#endif\n}";
  14526. var points_frag = "uniform vec3 diffuse;\nuniform float opacity;\n#include <common>\n#include <color_pars_fragment>\n#include <map_particle_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_particle_fragment>\n\t#include <color_fragment>\n\t#include <alphatest_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n}";
  14527. var points_vert = "uniform float size;\nuniform float scale;\n#include <common>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <color_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <project_vertex>\n\tgl_PointSize = size;\n\t#ifdef USE_SIZEATTENUATION\n\t\tbool isPerspective = isPerspectiveMatrix( projectionMatrix );\n\t\tif ( isPerspective ) gl_PointSize *= ( scale / - mvPosition.z );\n\t#endif\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <worldpos_vertex>\n\t#include <fog_vertex>\n}";
  14528. var shadow_frag = "uniform vec3 color;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <shadowmap_pars_fragment>\n#include <shadowmask_pars_fragment>\nvoid main() {\n\tgl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}";
  14529. var shadow_vert = "#include <common>\n#include <fog_pars_vertex>\n#include <shadowmap_pars_vertex>\nvoid main() {\n\t#include <begin_vertex>\n\t#include <project_vertex>\n\t#include <worldpos_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";
  14530. var sprite_frag = "uniform vec3 diffuse;\nuniform float opacity;\n#include <common>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}";
  14531. var sprite_vert = "uniform float rotation;\nuniform vec2 center;\n#include <common>\n#include <uv_pars_vertex>\n#include <fog_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\tvec4 mvPosition = modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );\n\tvec2 scale;\n\tscale.x = length( vec3( modelMatrix[ 0 ].x, modelMatrix[ 0 ].y, modelMatrix[ 0 ].z ) );\n\tscale.y = length( vec3( modelMatrix[ 1 ].x, modelMatrix[ 1 ].y, modelMatrix[ 1 ].z ) );\n\t#ifndef USE_SIZEATTENUATION\n\t\tbool isPerspective = isPerspectiveMatrix( projectionMatrix );\n\t\tif ( isPerspective ) scale *= - mvPosition.z;\n\t#endif\n\tvec2 alignedPosition = ( position.xy - ( center - vec2( 0.5 ) ) ) * scale;\n\tvec2 rotatedPosition;\n\trotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;\n\trotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;\n\tmvPosition.xy += rotatedPosition;\n\tgl_Position = projectionMatrix * mvPosition;\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <fog_vertex>\n}";
  14532. var ShaderChunk = {
  14533. alphamap_fragment: alphamap_fragment,
  14534. alphamap_pars_fragment: alphamap_pars_fragment,
  14535. alphatest_fragment: alphatest_fragment,
  14536. aomap_fragment: aomap_fragment,
  14537. aomap_pars_fragment: aomap_pars_fragment,
  14538. begin_vertex: begin_vertex,
  14539. beginnormal_vertex: beginnormal_vertex,
  14540. bsdfs: bsdfs,
  14541. bumpmap_pars_fragment: bumpmap_pars_fragment,
  14542. clipping_planes_fragment: clipping_planes_fragment,
  14543. clipping_planes_pars_fragment: clipping_planes_pars_fragment,
  14544. clipping_planes_pars_vertex: clipping_planes_pars_vertex,
  14545. clipping_planes_vertex: clipping_planes_vertex,
  14546. color_fragment: color_fragment,
  14547. color_pars_fragment: color_pars_fragment,
  14548. color_pars_vertex: color_pars_vertex,
  14549. color_vertex: color_vertex,
  14550. common: common,
  14551. cube_uv_reflection_fragment: cube_uv_reflection_fragment,
  14552. defaultnormal_vertex: defaultnormal_vertex,
  14553. displacementmap_pars_vertex: displacementmap_pars_vertex,
  14554. displacementmap_vertex: displacementmap_vertex,
  14555. emissivemap_fragment: emissivemap_fragment,
  14556. emissivemap_pars_fragment: emissivemap_pars_fragment,
  14557. encodings_fragment: encodings_fragment,
  14558. encodings_pars_fragment: encodings_pars_fragment,
  14559. envmap_fragment: envmap_fragment,
  14560. envmap_common_pars_fragment: envmap_common_pars_fragment,
  14561. envmap_pars_fragment: envmap_pars_fragment,
  14562. envmap_pars_vertex: envmap_pars_vertex,
  14563. envmap_physical_pars_fragment: envmap_physical_pars_fragment,
  14564. envmap_vertex: envmap_vertex,
  14565. fog_vertex: fog_vertex,
  14566. fog_pars_vertex: fog_pars_vertex,
  14567. fog_fragment: fog_fragment,
  14568. fog_pars_fragment: fog_pars_fragment,
  14569. gradientmap_pars_fragment: gradientmap_pars_fragment,
  14570. lightmap_fragment: lightmap_fragment,
  14571. lightmap_pars_fragment: lightmap_pars_fragment,
  14572. lights_lambert_vertex: lights_lambert_vertex,
  14573. lights_pars_begin: lights_pars_begin,
  14574. lights_toon_fragment: lights_toon_fragment,
  14575. lights_toon_pars_fragment: lights_toon_pars_fragment,
  14576. lights_phong_fragment: lights_phong_fragment,
  14577. lights_phong_pars_fragment: lights_phong_pars_fragment,
  14578. lights_physical_fragment: lights_physical_fragment,
  14579. lights_physical_pars_fragment: lights_physical_pars_fragment,
  14580. lights_fragment_begin: lights_fragment_begin,
  14581. lights_fragment_maps: lights_fragment_maps,
  14582. lights_fragment_end: lights_fragment_end,
  14583. logdepthbuf_fragment: logdepthbuf_fragment,
  14584. logdepthbuf_pars_fragment: logdepthbuf_pars_fragment,
  14585. logdepthbuf_pars_vertex: logdepthbuf_pars_vertex,
  14586. logdepthbuf_vertex: logdepthbuf_vertex,
  14587. map_fragment: map_fragment,
  14588. map_pars_fragment: map_pars_fragment,
  14589. map_particle_fragment: map_particle_fragment,
  14590. map_particle_pars_fragment: map_particle_pars_fragment,
  14591. metalnessmap_fragment: metalnessmap_fragment,
  14592. metalnessmap_pars_fragment: metalnessmap_pars_fragment,
  14593. morphnormal_vertex: morphnormal_vertex,
  14594. morphtarget_pars_vertex: morphtarget_pars_vertex,
  14595. morphtarget_vertex: morphtarget_vertex,
  14596. normal_fragment_begin: normal_fragment_begin,
  14597. normal_fragment_maps: normal_fragment_maps,
  14598. normalmap_pars_fragment: normalmap_pars_fragment,
  14599. clearcoat_normal_fragment_begin: clearcoat_normal_fragment_begin,
  14600. clearcoat_normal_fragment_maps: clearcoat_normal_fragment_maps,
  14601. clearcoat_pars_fragment: clearcoat_pars_fragment,
  14602. packing: packing,
  14603. premultiplied_alpha_fragment: premultiplied_alpha_fragment,
  14604. project_vertex: project_vertex,
  14605. dithering_fragment: dithering_fragment,
  14606. dithering_pars_fragment: dithering_pars_fragment,
  14607. roughnessmap_fragment: roughnessmap_fragment,
  14608. roughnessmap_pars_fragment: roughnessmap_pars_fragment,
  14609. shadowmap_pars_fragment: shadowmap_pars_fragment,
  14610. shadowmap_pars_vertex: shadowmap_pars_vertex,
  14611. shadowmap_vertex: shadowmap_vertex,
  14612. shadowmask_pars_fragment: shadowmask_pars_fragment,
  14613. skinbase_vertex: skinbase_vertex,
  14614. skinning_pars_vertex: skinning_pars_vertex,
  14615. skinning_vertex: skinning_vertex,
  14616. skinnormal_vertex: skinnormal_vertex,
  14617. specularmap_fragment: specularmap_fragment,
  14618. specularmap_pars_fragment: specularmap_pars_fragment,
  14619. tonemapping_fragment: tonemapping_fragment,
  14620. tonemapping_pars_fragment: tonemapping_pars_fragment,
  14621. transmissionmap_fragment: transmissionmap_fragment,
  14622. transmissionmap_pars_fragment: transmissionmap_pars_fragment,
  14623. uv_pars_fragment: uv_pars_fragment,
  14624. uv_pars_vertex: uv_pars_vertex,
  14625. uv_vertex: uv_vertex,
  14626. uv2_pars_fragment: uv2_pars_fragment,
  14627. uv2_pars_vertex: uv2_pars_vertex,
  14628. uv2_vertex: uv2_vertex,
  14629. worldpos_vertex: worldpos_vertex,
  14630. background_frag: background_frag,
  14631. background_vert: background_vert,
  14632. cube_frag: cube_frag,
  14633. cube_vert: cube_vert,
  14634. depth_frag: depth_frag,
  14635. depth_vert: depth_vert,
  14636. distanceRGBA_frag: distanceRGBA_frag,
  14637. distanceRGBA_vert: distanceRGBA_vert,
  14638. equirect_frag: equirect_frag,
  14639. equirect_vert: equirect_vert,
  14640. linedashed_frag: linedashed_frag,
  14641. linedashed_vert: linedashed_vert,
  14642. meshbasic_frag: meshbasic_frag,
  14643. meshbasic_vert: meshbasic_vert,
  14644. meshlambert_frag: meshlambert_frag,
  14645. meshlambert_vert: meshlambert_vert,
  14646. meshmatcap_frag: meshmatcap_frag,
  14647. meshmatcap_vert: meshmatcap_vert,
  14648. meshtoon_frag: meshtoon_frag,
  14649. meshtoon_vert: meshtoon_vert,
  14650. meshphong_frag: meshphong_frag,
  14651. meshphong_vert: meshphong_vert,
  14652. meshphysical_frag: meshphysical_frag,
  14653. meshphysical_vert: meshphysical_vert,
  14654. normal_frag: normal_frag,
  14655. normal_vert: normal_vert,
  14656. points_frag: points_frag,
  14657. points_vert: points_vert,
  14658. shadow_frag: shadow_frag,
  14659. shadow_vert: shadow_vert,
  14660. sprite_frag: sprite_frag,
  14661. sprite_vert: sprite_vert
  14662. };
  14663. /**
  14664. * Uniforms library for shared webgl shaders
  14665. */
  14666. var UniformsLib = {
  14667. common: {
  14668. diffuse: {
  14669. value: new Color(0xeeeeee)
  14670. },
  14671. opacity: {
  14672. value: 1.0
  14673. },
  14674. map: {
  14675. value: null
  14676. },
  14677. uvTransform: {
  14678. value: new Matrix3()
  14679. },
  14680. uv2Transform: {
  14681. value: new Matrix3()
  14682. },
  14683. alphaMap: {
  14684. value: null
  14685. }
  14686. },
  14687. specularmap: {
  14688. specularMap: {
  14689. value: null
  14690. }
  14691. },
  14692. envmap: {
  14693. envMap: {
  14694. value: null
  14695. },
  14696. flipEnvMap: {
  14697. value: -1
  14698. },
  14699. reflectivity: {
  14700. value: 1.0
  14701. },
  14702. refractionRatio: {
  14703. value: 0.98
  14704. },
  14705. maxMipLevel: {
  14706. value: 0
  14707. }
  14708. },
  14709. aomap: {
  14710. aoMap: {
  14711. value: null
  14712. },
  14713. aoMapIntensity: {
  14714. value: 1
  14715. }
  14716. },
  14717. lightmap: {
  14718. lightMap: {
  14719. value: null
  14720. },
  14721. lightMapIntensity: {
  14722. value: 1
  14723. }
  14724. },
  14725. emissivemap: {
  14726. emissiveMap: {
  14727. value: null
  14728. }
  14729. },
  14730. bumpmap: {
  14731. bumpMap: {
  14732. value: null
  14733. },
  14734. bumpScale: {
  14735. value: 1
  14736. }
  14737. },
  14738. normalmap: {
  14739. normalMap: {
  14740. value: null
  14741. },
  14742. normalScale: {
  14743. value: new Vector2(1, 1)
  14744. }
  14745. },
  14746. displacementmap: {
  14747. displacementMap: {
  14748. value: null
  14749. },
  14750. displacementScale: {
  14751. value: 1
  14752. },
  14753. displacementBias: {
  14754. value: 0
  14755. }
  14756. },
  14757. roughnessmap: {
  14758. roughnessMap: {
  14759. value: null
  14760. }
  14761. },
  14762. metalnessmap: {
  14763. metalnessMap: {
  14764. value: null
  14765. }
  14766. },
  14767. gradientmap: {
  14768. gradientMap: {
  14769. value: null
  14770. }
  14771. },
  14772. fog: {
  14773. fogDensity: {
  14774. value: 0.00025
  14775. },
  14776. fogNear: {
  14777. value: 1
  14778. },
  14779. fogFar: {
  14780. value: 2000
  14781. },
  14782. fogColor: {
  14783. value: new Color(0xffffff)
  14784. }
  14785. },
  14786. lights: {
  14787. ambientLightColor: {
  14788. value: []
  14789. },
  14790. lightProbe: {
  14791. value: []
  14792. },
  14793. directionalLights: {
  14794. value: [],
  14795. properties: {
  14796. direction: {},
  14797. color: {}
  14798. }
  14799. },
  14800. directionalLightShadows: {
  14801. value: [],
  14802. properties: {
  14803. shadowBias: {},
  14804. shadowNormalBias: {},
  14805. shadowRadius: {},
  14806. shadowMapSize: {}
  14807. }
  14808. },
  14809. directionalShadowMap: {
  14810. value: []
  14811. },
  14812. directionalShadowMatrix: {
  14813. value: []
  14814. },
  14815. spotLights: {
  14816. value: [],
  14817. properties: {
  14818. color: {},
  14819. position: {},
  14820. direction: {},
  14821. distance: {},
  14822. coneCos: {},
  14823. penumbraCos: {},
  14824. decay: {}
  14825. }
  14826. },
  14827. spotLightShadows: {
  14828. value: [],
  14829. properties: {
  14830. shadowBias: {},
  14831. shadowNormalBias: {},
  14832. shadowRadius: {},
  14833. shadowMapSize: {}
  14834. }
  14835. },
  14836. spotShadowMap: {
  14837. value: []
  14838. },
  14839. spotShadowMatrix: {
  14840. value: []
  14841. },
  14842. pointLights: {
  14843. value: [],
  14844. properties: {
  14845. color: {},
  14846. position: {},
  14847. decay: {},
  14848. distance: {}
  14849. }
  14850. },
  14851. pointLightShadows: {
  14852. value: [],
  14853. properties: {
  14854. shadowBias: {},
  14855. shadowNormalBias: {},
  14856. shadowRadius: {},
  14857. shadowMapSize: {},
  14858. shadowCameraNear: {},
  14859. shadowCameraFar: {}
  14860. }
  14861. },
  14862. pointShadowMap: {
  14863. value: []
  14864. },
  14865. pointShadowMatrix: {
  14866. value: []
  14867. },
  14868. hemisphereLights: {
  14869. value: [],
  14870. properties: {
  14871. direction: {},
  14872. skyColor: {},
  14873. groundColor: {}
  14874. }
  14875. },
  14876. // TODO (abelnation): RectAreaLight BRDF data needs to be moved from example to main src
  14877. rectAreaLights: {
  14878. value: [],
  14879. properties: {
  14880. color: {},
  14881. position: {},
  14882. width: {},
  14883. height: {}
  14884. }
  14885. },
  14886. ltc_1: {
  14887. value: null
  14888. },
  14889. ltc_2: {
  14890. value: null
  14891. }
  14892. },
  14893. points: {
  14894. diffuse: {
  14895. value: new Color(0xeeeeee)
  14896. },
  14897. opacity: {
  14898. value: 1.0
  14899. },
  14900. size: {
  14901. value: 1.0
  14902. },
  14903. scale: {
  14904. value: 1.0
  14905. },
  14906. map: {
  14907. value: null
  14908. },
  14909. alphaMap: {
  14910. value: null
  14911. },
  14912. uvTransform: {
  14913. value: new Matrix3()
  14914. }
  14915. },
  14916. sprite: {
  14917. diffuse: {
  14918. value: new Color(0xeeeeee)
  14919. },
  14920. opacity: {
  14921. value: 1.0
  14922. },
  14923. center: {
  14924. value: new Vector2(0.5, 0.5)
  14925. },
  14926. rotation: {
  14927. value: 0.0
  14928. },
  14929. map: {
  14930. value: null
  14931. },
  14932. alphaMap: {
  14933. value: null
  14934. },
  14935. uvTransform: {
  14936. value: new Matrix3()
  14937. }
  14938. }
  14939. };
  14940. var ShaderLib = {
  14941. basic: {
  14942. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.specularmap, UniformsLib.envmap, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.fog]),
  14943. vertexShader: ShaderChunk.meshbasic_vert,
  14944. fragmentShader: ShaderChunk.meshbasic_frag
  14945. },
  14946. lambert: {
  14947. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.specularmap, UniformsLib.envmap, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.emissivemap, UniformsLib.fog, UniformsLib.lights, {
  14948. emissive: {
  14949. value: new Color(0x000000)
  14950. }
  14951. }]),
  14952. vertexShader: ShaderChunk.meshlambert_vert,
  14953. fragmentShader: ShaderChunk.meshlambert_frag
  14954. },
  14955. phong: {
  14956. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.specularmap, UniformsLib.envmap, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.emissivemap, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, UniformsLib.fog, UniformsLib.lights, {
  14957. emissive: {
  14958. value: new Color(0x000000)
  14959. },
  14960. specular: {
  14961. value: new Color(0x111111)
  14962. },
  14963. shininess: {
  14964. value: 30
  14965. }
  14966. }]),
  14967. vertexShader: ShaderChunk.meshphong_vert,
  14968. fragmentShader: ShaderChunk.meshphong_frag
  14969. },
  14970. standard: {
  14971. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.envmap, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.emissivemap, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, UniformsLib.roughnessmap, UniformsLib.metalnessmap, UniformsLib.fog, UniformsLib.lights, {
  14972. emissive: {
  14973. value: new Color(0x000000)
  14974. },
  14975. roughness: {
  14976. value: 1.0
  14977. },
  14978. metalness: {
  14979. value: 0.0
  14980. },
  14981. envMapIntensity: {
  14982. value: 1
  14983. } // temporary
  14984. }]),
  14985. vertexShader: ShaderChunk.meshphysical_vert,
  14986. fragmentShader: ShaderChunk.meshphysical_frag
  14987. },
  14988. toon: {
  14989. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.emissivemap, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, UniformsLib.gradientmap, UniformsLib.fog, UniformsLib.lights, {
  14990. emissive: {
  14991. value: new Color(0x000000)
  14992. }
  14993. }]),
  14994. vertexShader: ShaderChunk.meshtoon_vert,
  14995. fragmentShader: ShaderChunk.meshtoon_frag
  14996. },
  14997. matcap: {
  14998. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, UniformsLib.fog, {
  14999. matcap: {
  15000. value: null
  15001. }
  15002. }]),
  15003. vertexShader: ShaderChunk.meshmatcap_vert,
  15004. fragmentShader: ShaderChunk.meshmatcap_frag
  15005. },
  15006. points: {
  15007. uniforms: mergeUniforms([UniformsLib.points, UniformsLib.fog]),
  15008. vertexShader: ShaderChunk.points_vert,
  15009. fragmentShader: ShaderChunk.points_frag
  15010. },
  15011. dashed: {
  15012. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.fog, {
  15013. scale: {
  15014. value: 1
  15015. },
  15016. dashSize: {
  15017. value: 1
  15018. },
  15019. totalSize: {
  15020. value: 2
  15021. }
  15022. }]),
  15023. vertexShader: ShaderChunk.linedashed_vert,
  15024. fragmentShader: ShaderChunk.linedashed_frag
  15025. },
  15026. depth: {
  15027. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.displacementmap]),
  15028. vertexShader: ShaderChunk.depth_vert,
  15029. fragmentShader: ShaderChunk.depth_frag
  15030. },
  15031. normal: {
  15032. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, {
  15033. opacity: {
  15034. value: 1.0
  15035. }
  15036. }]),
  15037. vertexShader: ShaderChunk.normal_vert,
  15038. fragmentShader: ShaderChunk.normal_frag
  15039. },
  15040. sprite: {
  15041. uniforms: mergeUniforms([UniformsLib.sprite, UniformsLib.fog]),
  15042. vertexShader: ShaderChunk.sprite_vert,
  15043. fragmentShader: ShaderChunk.sprite_frag
  15044. },
  15045. background: {
  15046. uniforms: {
  15047. uvTransform: {
  15048. value: new Matrix3()
  15049. },
  15050. t2D: {
  15051. value: null
  15052. }
  15053. },
  15054. vertexShader: ShaderChunk.background_vert,
  15055. fragmentShader: ShaderChunk.background_frag
  15056. },
  15057. /* -------------------------------------------------------------------------
  15058. // Cube map shader
  15059. ------------------------------------------------------------------------- */
  15060. cube: {
  15061. uniforms: mergeUniforms([UniformsLib.envmap, {
  15062. opacity: {
  15063. value: 1.0
  15064. }
  15065. }]),
  15066. vertexShader: ShaderChunk.cube_vert,
  15067. fragmentShader: ShaderChunk.cube_frag
  15068. },
  15069. equirect: {
  15070. uniforms: {
  15071. tEquirect: {
  15072. value: null
  15073. }
  15074. },
  15075. vertexShader: ShaderChunk.equirect_vert,
  15076. fragmentShader: ShaderChunk.equirect_frag
  15077. },
  15078. distanceRGBA: {
  15079. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.displacementmap, {
  15080. referencePosition: {
  15081. value: new Vector3()
  15082. },
  15083. nearDistance: {
  15084. value: 1
  15085. },
  15086. farDistance: {
  15087. value: 1000
  15088. }
  15089. }]),
  15090. vertexShader: ShaderChunk.distanceRGBA_vert,
  15091. fragmentShader: ShaderChunk.distanceRGBA_frag
  15092. },
  15093. shadow: {
  15094. uniforms: mergeUniforms([UniformsLib.lights, UniformsLib.fog, {
  15095. color: {
  15096. value: new Color(0x00000)
  15097. },
  15098. opacity: {
  15099. value: 1.0
  15100. }
  15101. }]),
  15102. vertexShader: ShaderChunk.shadow_vert,
  15103. fragmentShader: ShaderChunk.shadow_frag
  15104. }
  15105. };
  15106. ShaderLib.physical = {
  15107. uniforms: mergeUniforms([ShaderLib.standard.uniforms, {
  15108. clearcoat: {
  15109. value: 0
  15110. },
  15111. clearcoatMap: {
  15112. value: null
  15113. },
  15114. clearcoatRoughness: {
  15115. value: 0
  15116. },
  15117. clearcoatRoughnessMap: {
  15118. value: null
  15119. },
  15120. clearcoatNormalScale: {
  15121. value: new Vector2(1, 1)
  15122. },
  15123. clearcoatNormalMap: {
  15124. value: null
  15125. },
  15126. sheen: {
  15127. value: new Color(0x000000)
  15128. },
  15129. transmission: {
  15130. value: 0
  15131. },
  15132. transmissionMap: {
  15133. value: null
  15134. }
  15135. }]),
  15136. vertexShader: ShaderChunk.meshphysical_vert,
  15137. fragmentShader: ShaderChunk.meshphysical_frag
  15138. };
  15139. function WebGLBackground(renderer, cubemaps, state, objects, premultipliedAlpha) {
  15140. var clearColor = new Color(0x000000);
  15141. var clearAlpha = 0;
  15142. var planeMesh;
  15143. var boxMesh;
  15144. var currentBackground = null;
  15145. var currentBackgroundVersion = 0;
  15146. var currentTonemapping = null;
  15147. function render(renderList, scene, camera, forceClear) {
  15148. var background = scene.isScene === true ? scene.background : null;
  15149. if (background && background.isTexture) {
  15150. background = cubemaps.get(background);
  15151. } // Ignore background in AR
  15152. // TODO: Reconsider this.
  15153. var xr = renderer.xr;
  15154. var session = xr.getSession && xr.getSession();
  15155. if (session && session.environmentBlendMode === 'additive') {
  15156. background = null;
  15157. }
  15158. if (background === null) {
  15159. setClear(clearColor, clearAlpha);
  15160. } else if (background && background.isColor) {
  15161. setClear(background, 1);
  15162. forceClear = true;
  15163. }
  15164. if (renderer.autoClear || forceClear) {
  15165. renderer.clear(renderer.autoClearColor, renderer.autoClearDepth, renderer.autoClearStencil);
  15166. }
  15167. if (background && (background.isCubeTexture || background.isWebGLCubeRenderTarget || background.mapping === CubeUVReflectionMapping)) {
  15168. if (boxMesh === undefined) {
  15169. boxMesh = new Mesh(new BoxGeometry(1, 1, 1), new ShaderMaterial({
  15170. name: 'BackgroundCubeMaterial',
  15171. uniforms: cloneUniforms(ShaderLib.cube.uniforms),
  15172. vertexShader: ShaderLib.cube.vertexShader,
  15173. fragmentShader: ShaderLib.cube.fragmentShader,
  15174. side: BackSide,
  15175. depthTest: false,
  15176. depthWrite: false,
  15177. fog: false
  15178. }));
  15179. boxMesh.geometry.deleteAttribute('normal');
  15180. boxMesh.geometry.deleteAttribute('uv');
  15181. boxMesh.onBeforeRender = function (renderer, scene, camera) {
  15182. this.matrixWorld.copyPosition(camera.matrixWorld);
  15183. }; // enable code injection for non-built-in material
  15184. Object.defineProperty(boxMesh.material, 'envMap', {
  15185. get: function get() {
  15186. return this.uniforms.envMap.value;
  15187. }
  15188. });
  15189. objects.update(boxMesh);
  15190. }
  15191. if (background.isWebGLCubeRenderTarget) {
  15192. // TODO Deprecate
  15193. background = background.texture;
  15194. }
  15195. boxMesh.material.uniforms.envMap.value = background;
  15196. boxMesh.material.uniforms.flipEnvMap.value = background.isCubeTexture && background._needsFlipEnvMap ? -1 : 1;
  15197. if (currentBackground !== background || currentBackgroundVersion !== background.version || currentTonemapping !== renderer.toneMapping) {
  15198. boxMesh.material.needsUpdate = true;
  15199. currentBackground = background;
  15200. currentBackgroundVersion = background.version;
  15201. currentTonemapping = renderer.toneMapping;
  15202. } // push to the pre-sorted opaque render list
  15203. renderList.unshift(boxMesh, boxMesh.geometry, boxMesh.material, 0, 0, null);
  15204. } else if (background && background.isTexture) {
  15205. if (planeMesh === undefined) {
  15206. planeMesh = new Mesh(new PlaneGeometry(2, 2), new ShaderMaterial({
  15207. name: 'BackgroundMaterial',
  15208. uniforms: cloneUniforms(ShaderLib.background.uniforms),
  15209. vertexShader: ShaderLib.background.vertexShader,
  15210. fragmentShader: ShaderLib.background.fragmentShader,
  15211. side: FrontSide,
  15212. depthTest: false,
  15213. depthWrite: false,
  15214. fog: false
  15215. }));
  15216. planeMesh.geometry.deleteAttribute('normal'); // enable code injection for non-built-in material
  15217. Object.defineProperty(planeMesh.material, 'map', {
  15218. get: function get() {
  15219. return this.uniforms.t2D.value;
  15220. }
  15221. });
  15222. objects.update(planeMesh);
  15223. }
  15224. planeMesh.material.uniforms.t2D.value = background;
  15225. if (background.matrixAutoUpdate === true) {
  15226. background.updateMatrix();
  15227. }
  15228. planeMesh.material.uniforms.uvTransform.value.copy(background.matrix);
  15229. if (currentBackground !== background || currentBackgroundVersion !== background.version || currentTonemapping !== renderer.toneMapping) {
  15230. planeMesh.material.needsUpdate = true;
  15231. currentBackground = background;
  15232. currentBackgroundVersion = background.version;
  15233. currentTonemapping = renderer.toneMapping;
  15234. } // push to the pre-sorted opaque render list
  15235. renderList.unshift(planeMesh, planeMesh.geometry, planeMesh.material, 0, 0, null);
  15236. }
  15237. }
  15238. function setClear(color, alpha) {
  15239. state.buffers.color.setClear(color.r, color.g, color.b, alpha, premultipliedAlpha);
  15240. }
  15241. return {
  15242. getClearColor: function getClearColor() {
  15243. return clearColor;
  15244. },
  15245. setClearColor: function setClearColor(color, alpha) {
  15246. if (alpha === void 0) {
  15247. alpha = 1;
  15248. }
  15249. clearColor.set(color);
  15250. clearAlpha = alpha;
  15251. setClear(clearColor, clearAlpha);
  15252. },
  15253. getClearAlpha: function getClearAlpha() {
  15254. return clearAlpha;
  15255. },
  15256. setClearAlpha: function setClearAlpha(alpha) {
  15257. clearAlpha = alpha;
  15258. setClear(clearColor, clearAlpha);
  15259. },
  15260. render: render
  15261. };
  15262. }
  15263. function WebGLBindingStates(gl, extensions, attributes, capabilities) {
  15264. var maxVertexAttributes = gl.getParameter(34921);
  15265. var extension = capabilities.isWebGL2 ? null : extensions.get('OES_vertex_array_object');
  15266. var vaoAvailable = capabilities.isWebGL2 || extension !== null;
  15267. var bindingStates = {};
  15268. var defaultState = createBindingState(null);
  15269. var currentState = defaultState;
  15270. function setup(object, material, program, geometry, index) {
  15271. var updateBuffers = false;
  15272. if (vaoAvailable) {
  15273. var state = getBindingState(geometry, program, material);
  15274. if (currentState !== state) {
  15275. currentState = state;
  15276. bindVertexArrayObject(currentState.object);
  15277. }
  15278. updateBuffers = needsUpdate(geometry, index);
  15279. if (updateBuffers) saveCache(geometry, index);
  15280. } else {
  15281. var wireframe = material.wireframe === true;
  15282. if (currentState.geometry !== geometry.id || currentState.program !== program.id || currentState.wireframe !== wireframe) {
  15283. currentState.geometry = geometry.id;
  15284. currentState.program = program.id;
  15285. currentState.wireframe = wireframe;
  15286. updateBuffers = true;
  15287. }
  15288. }
  15289. if (object.isInstancedMesh === true) {
  15290. updateBuffers = true;
  15291. }
  15292. if (index !== null) {
  15293. attributes.update(index, 34963);
  15294. }
  15295. if (updateBuffers) {
  15296. setupVertexAttributes(object, material, program, geometry);
  15297. if (index !== null) {
  15298. gl.bindBuffer(34963, attributes.get(index).buffer);
  15299. }
  15300. }
  15301. }
  15302. function createVertexArrayObject() {
  15303. if (capabilities.isWebGL2) return gl.createVertexArray();
  15304. return extension.createVertexArrayOES();
  15305. }
  15306. function bindVertexArrayObject(vao) {
  15307. if (capabilities.isWebGL2) return gl.bindVertexArray(vao);
  15308. return extension.bindVertexArrayOES(vao);
  15309. }
  15310. function deleteVertexArrayObject(vao) {
  15311. if (capabilities.isWebGL2) return gl.deleteVertexArray(vao);
  15312. return extension.deleteVertexArrayOES(vao);
  15313. }
  15314. function getBindingState(geometry, program, material) {
  15315. var wireframe = material.wireframe === true;
  15316. var programMap = bindingStates[geometry.id];
  15317. if (programMap === undefined) {
  15318. programMap = {};
  15319. bindingStates[geometry.id] = programMap;
  15320. }
  15321. var stateMap = programMap[program.id];
  15322. if (stateMap === undefined) {
  15323. stateMap = {};
  15324. programMap[program.id] = stateMap;
  15325. }
  15326. var state = stateMap[wireframe];
  15327. if (state === undefined) {
  15328. state = createBindingState(createVertexArrayObject());
  15329. stateMap[wireframe] = state;
  15330. }
  15331. return state;
  15332. }
  15333. function createBindingState(vao) {
  15334. var newAttributes = [];
  15335. var enabledAttributes = [];
  15336. var attributeDivisors = [];
  15337. for (var i = 0; i < maxVertexAttributes; i++) {
  15338. newAttributes[i] = 0;
  15339. enabledAttributes[i] = 0;
  15340. attributeDivisors[i] = 0;
  15341. }
  15342. return {
  15343. // for backward compatibility on non-VAO support browser
  15344. geometry: null,
  15345. program: null,
  15346. wireframe: false,
  15347. newAttributes: newAttributes,
  15348. enabledAttributes: enabledAttributes,
  15349. attributeDivisors: attributeDivisors,
  15350. object: vao,
  15351. attributes: {},
  15352. index: null
  15353. };
  15354. }
  15355. function needsUpdate(geometry, index) {
  15356. var cachedAttributes = currentState.attributes;
  15357. var geometryAttributes = geometry.attributes;
  15358. var attributesNum = 0;
  15359. for (var key in geometryAttributes) {
  15360. var cachedAttribute = cachedAttributes[key];
  15361. var geometryAttribute = geometryAttributes[key];
  15362. if (cachedAttribute === undefined) return true;
  15363. if (cachedAttribute.attribute !== geometryAttribute) return true;
  15364. if (cachedAttribute.data !== geometryAttribute.data) return true;
  15365. attributesNum++;
  15366. }
  15367. if (currentState.attributesNum !== attributesNum) return true;
  15368. if (currentState.index !== index) return true;
  15369. return false;
  15370. }
  15371. function saveCache(geometry, index) {
  15372. var cache = {};
  15373. var attributes = geometry.attributes;
  15374. var attributesNum = 0;
  15375. for (var key in attributes) {
  15376. var attribute = attributes[key];
  15377. var data = {};
  15378. data.attribute = attribute;
  15379. if (attribute.data) {
  15380. data.data = attribute.data;
  15381. }
  15382. cache[key] = data;
  15383. attributesNum++;
  15384. }
  15385. currentState.attributes = cache;
  15386. currentState.attributesNum = attributesNum;
  15387. currentState.index = index;
  15388. }
  15389. function initAttributes() {
  15390. var newAttributes = currentState.newAttributes;
  15391. for (var i = 0, il = newAttributes.length; i < il; i++) {
  15392. newAttributes[i] = 0;
  15393. }
  15394. }
  15395. function enableAttribute(attribute) {
  15396. enableAttributeAndDivisor(attribute, 0);
  15397. }
  15398. function enableAttributeAndDivisor(attribute, meshPerAttribute) {
  15399. var newAttributes = currentState.newAttributes;
  15400. var enabledAttributes = currentState.enabledAttributes;
  15401. var attributeDivisors = currentState.attributeDivisors;
  15402. newAttributes[attribute] = 1;
  15403. if (enabledAttributes[attribute] === 0) {
  15404. gl.enableVertexAttribArray(attribute);
  15405. enabledAttributes[attribute] = 1;
  15406. }
  15407. if (attributeDivisors[attribute] !== meshPerAttribute) {
  15408. var _extension = capabilities.isWebGL2 ? gl : extensions.get('ANGLE_instanced_arrays');
  15409. _extension[capabilities.isWebGL2 ? 'vertexAttribDivisor' : 'vertexAttribDivisorANGLE'](attribute, meshPerAttribute);
  15410. attributeDivisors[attribute] = meshPerAttribute;
  15411. }
  15412. }
  15413. function disableUnusedAttributes() {
  15414. var newAttributes = currentState.newAttributes;
  15415. var enabledAttributes = currentState.enabledAttributes;
  15416. for (var i = 0, il = enabledAttributes.length; i < il; i++) {
  15417. if (enabledAttributes[i] !== newAttributes[i]) {
  15418. gl.disableVertexAttribArray(i);
  15419. enabledAttributes[i] = 0;
  15420. }
  15421. }
  15422. }
  15423. function vertexAttribPointer(index, size, type, normalized, stride, offset) {
  15424. if (capabilities.isWebGL2 === true && (type === 5124 || type === 5125)) {
  15425. gl.vertexAttribIPointer(index, size, type, stride, offset);
  15426. } else {
  15427. gl.vertexAttribPointer(index, size, type, normalized, stride, offset);
  15428. }
  15429. }
  15430. function setupVertexAttributes(object, material, program, geometry) {
  15431. if (capabilities.isWebGL2 === false && (object.isInstancedMesh || geometry.isInstancedBufferGeometry)) {
  15432. if (extensions.get('ANGLE_instanced_arrays') === null) return;
  15433. }
  15434. initAttributes();
  15435. var geometryAttributes = geometry.attributes;
  15436. var programAttributes = program.getAttributes();
  15437. var materialDefaultAttributeValues = material.defaultAttributeValues;
  15438. for (var name in programAttributes) {
  15439. var programAttribute = programAttributes[name];
  15440. if (programAttribute >= 0) {
  15441. var geometryAttribute = geometryAttributes[name];
  15442. if (geometryAttribute !== undefined) {
  15443. var normalized = geometryAttribute.normalized;
  15444. var size = geometryAttribute.itemSize;
  15445. var attribute = attributes.get(geometryAttribute); // TODO Attribute may not be available on context restore
  15446. if (attribute === undefined) continue;
  15447. var buffer = attribute.buffer;
  15448. var type = attribute.type;
  15449. var bytesPerElement = attribute.bytesPerElement;
  15450. if (geometryAttribute.isInterleavedBufferAttribute) {
  15451. var data = geometryAttribute.data;
  15452. var stride = data.stride;
  15453. var offset = geometryAttribute.offset;
  15454. if (data && data.isInstancedInterleavedBuffer) {
  15455. enableAttributeAndDivisor(programAttribute, data.meshPerAttribute);
  15456. if (geometry._maxInstanceCount === undefined) {
  15457. geometry._maxInstanceCount = data.meshPerAttribute * data.count;
  15458. }
  15459. } else {
  15460. enableAttribute(programAttribute);
  15461. }
  15462. gl.bindBuffer(34962, buffer);
  15463. vertexAttribPointer(programAttribute, size, type, normalized, stride * bytesPerElement, offset * bytesPerElement);
  15464. } else {
  15465. if (geometryAttribute.isInstancedBufferAttribute) {
  15466. enableAttributeAndDivisor(programAttribute, geometryAttribute.meshPerAttribute);
  15467. if (geometry._maxInstanceCount === undefined) {
  15468. geometry._maxInstanceCount = geometryAttribute.meshPerAttribute * geometryAttribute.count;
  15469. }
  15470. } else {
  15471. enableAttribute(programAttribute);
  15472. }
  15473. gl.bindBuffer(34962, buffer);
  15474. vertexAttribPointer(programAttribute, size, type, normalized, 0, 0);
  15475. }
  15476. } else if (name === 'instanceMatrix') {
  15477. var _attribute = attributes.get(object.instanceMatrix); // TODO Attribute may not be available on context restore
  15478. if (_attribute === undefined) continue;
  15479. var _buffer = _attribute.buffer;
  15480. var _type = _attribute.type;
  15481. enableAttributeAndDivisor(programAttribute + 0, 1);
  15482. enableAttributeAndDivisor(programAttribute + 1, 1);
  15483. enableAttributeAndDivisor(programAttribute + 2, 1);
  15484. enableAttributeAndDivisor(programAttribute + 3, 1);
  15485. gl.bindBuffer(34962, _buffer);
  15486. gl.vertexAttribPointer(programAttribute + 0, 4, _type, false, 64, 0);
  15487. gl.vertexAttribPointer(programAttribute + 1, 4, _type, false, 64, 16);
  15488. gl.vertexAttribPointer(programAttribute + 2, 4, _type, false, 64, 32);
  15489. gl.vertexAttribPointer(programAttribute + 3, 4, _type, false, 64, 48);
  15490. } else if (name === 'instanceColor') {
  15491. var _attribute2 = attributes.get(object.instanceColor); // TODO Attribute may not be available on context restore
  15492. if (_attribute2 === undefined) continue;
  15493. var _buffer2 = _attribute2.buffer;
  15494. var _type2 = _attribute2.type;
  15495. enableAttributeAndDivisor(programAttribute, 1);
  15496. gl.bindBuffer(34962, _buffer2);
  15497. gl.vertexAttribPointer(programAttribute, 3, _type2, false, 12, 0);
  15498. } else if (materialDefaultAttributeValues !== undefined) {
  15499. var value = materialDefaultAttributeValues[name];
  15500. if (value !== undefined) {
  15501. switch (value.length) {
  15502. case 2:
  15503. gl.vertexAttrib2fv(programAttribute, value);
  15504. break;
  15505. case 3:
  15506. gl.vertexAttrib3fv(programAttribute, value);
  15507. break;
  15508. case 4:
  15509. gl.vertexAttrib4fv(programAttribute, value);
  15510. break;
  15511. default:
  15512. gl.vertexAttrib1fv(programAttribute, value);
  15513. }
  15514. }
  15515. }
  15516. }
  15517. }
  15518. disableUnusedAttributes();
  15519. }
  15520. function dispose() {
  15521. reset();
  15522. for (var geometryId in bindingStates) {
  15523. var programMap = bindingStates[geometryId];
  15524. for (var programId in programMap) {
  15525. var stateMap = programMap[programId];
  15526. for (var wireframe in stateMap) {
  15527. deleteVertexArrayObject(stateMap[wireframe].object);
  15528. delete stateMap[wireframe];
  15529. }
  15530. delete programMap[programId];
  15531. }
  15532. delete bindingStates[geometryId];
  15533. }
  15534. }
  15535. function releaseStatesOfGeometry(geometry) {
  15536. if (bindingStates[geometry.id] === undefined) return;
  15537. var programMap = bindingStates[geometry.id];
  15538. for (var programId in programMap) {
  15539. var stateMap = programMap[programId];
  15540. for (var wireframe in stateMap) {
  15541. deleteVertexArrayObject(stateMap[wireframe].object);
  15542. delete stateMap[wireframe];
  15543. }
  15544. delete programMap[programId];
  15545. }
  15546. delete bindingStates[geometry.id];
  15547. }
  15548. function releaseStatesOfProgram(program) {
  15549. for (var geometryId in bindingStates) {
  15550. var programMap = bindingStates[geometryId];
  15551. if (programMap[program.id] === undefined) continue;
  15552. var stateMap = programMap[program.id];
  15553. for (var wireframe in stateMap) {
  15554. deleteVertexArrayObject(stateMap[wireframe].object);
  15555. delete stateMap[wireframe];
  15556. }
  15557. delete programMap[program.id];
  15558. }
  15559. }
  15560. function reset() {
  15561. resetDefaultState();
  15562. if (currentState === defaultState) return;
  15563. currentState = defaultState;
  15564. bindVertexArrayObject(currentState.object);
  15565. } // for backward-compatilibity
  15566. function resetDefaultState() {
  15567. defaultState.geometry = null;
  15568. defaultState.program = null;
  15569. defaultState.wireframe = false;
  15570. }
  15571. return {
  15572. setup: setup,
  15573. reset: reset,
  15574. resetDefaultState: resetDefaultState,
  15575. dispose: dispose,
  15576. releaseStatesOfGeometry: releaseStatesOfGeometry,
  15577. releaseStatesOfProgram: releaseStatesOfProgram,
  15578. initAttributes: initAttributes,
  15579. enableAttribute: enableAttribute,
  15580. disableUnusedAttributes: disableUnusedAttributes
  15581. };
  15582. }
  15583. function WebGLBufferRenderer(gl, extensions, info, capabilities) {
  15584. var isWebGL2 = capabilities.isWebGL2;
  15585. var mode;
  15586. function setMode(value) {
  15587. mode = value;
  15588. }
  15589. function render(start, count) {
  15590. gl.drawArrays(mode, start, count);
  15591. info.update(count, mode, 1);
  15592. }
  15593. function renderInstances(start, count, primcount) {
  15594. if (primcount === 0) return;
  15595. var extension, methodName;
  15596. if (isWebGL2) {
  15597. extension = gl;
  15598. methodName = 'drawArraysInstanced';
  15599. } else {
  15600. extension = extensions.get('ANGLE_instanced_arrays');
  15601. methodName = 'drawArraysInstancedANGLE';
  15602. if (extension === null) {
  15603. console.error('THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.');
  15604. return;
  15605. }
  15606. }
  15607. extension[methodName](mode, start, count, primcount);
  15608. info.update(count, mode, primcount);
  15609. } //
  15610. this.setMode = setMode;
  15611. this.render = render;
  15612. this.renderInstances = renderInstances;
  15613. }
  15614. function WebGLCapabilities(gl, extensions, parameters) {
  15615. var maxAnisotropy;
  15616. function getMaxAnisotropy() {
  15617. if (maxAnisotropy !== undefined) return maxAnisotropy;
  15618. var extension = extensions.get('EXT_texture_filter_anisotropic');
  15619. if (extension !== null) {
  15620. maxAnisotropy = gl.getParameter(extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT);
  15621. } else {
  15622. maxAnisotropy = 0;
  15623. }
  15624. return maxAnisotropy;
  15625. }
  15626. function getMaxPrecision(precision) {
  15627. if (precision === 'highp') {
  15628. if (gl.getShaderPrecisionFormat(35633, 36338).precision > 0 && gl.getShaderPrecisionFormat(35632, 36338).precision > 0) {
  15629. return 'highp';
  15630. }
  15631. precision = 'mediump';
  15632. }
  15633. if (precision === 'mediump') {
  15634. if (gl.getShaderPrecisionFormat(35633, 36337).precision > 0 && gl.getShaderPrecisionFormat(35632, 36337).precision > 0) {
  15635. return 'mediump';
  15636. }
  15637. }
  15638. return 'lowp';
  15639. }
  15640. /* eslint-disable no-undef */
  15641. var isWebGL2 = typeof WebGL2RenderingContext !== 'undefined' && gl instanceof WebGL2RenderingContext || typeof WebGL2ComputeRenderingContext !== 'undefined' && gl instanceof WebGL2ComputeRenderingContext;
  15642. /* eslint-enable no-undef */
  15643. var precision = parameters.precision !== undefined ? parameters.precision : 'highp';
  15644. var maxPrecision = getMaxPrecision(precision);
  15645. if (maxPrecision !== precision) {
  15646. console.warn('THREE.WebGLRenderer:', precision, 'not supported, using', maxPrecision, 'instead.');
  15647. precision = maxPrecision;
  15648. }
  15649. var logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true;
  15650. var maxTextures = gl.getParameter(34930);
  15651. var maxVertexTextures = gl.getParameter(35660);
  15652. var maxTextureSize = gl.getParameter(3379);
  15653. var maxCubemapSize = gl.getParameter(34076);
  15654. var maxAttributes = gl.getParameter(34921);
  15655. var maxVertexUniforms = gl.getParameter(36347);
  15656. var maxVaryings = gl.getParameter(36348);
  15657. var maxFragmentUniforms = gl.getParameter(36349);
  15658. var vertexTextures = maxVertexTextures > 0;
  15659. var floatFragmentTextures = isWebGL2 || !!extensions.get('OES_texture_float');
  15660. var floatVertexTextures = vertexTextures && floatFragmentTextures;
  15661. var maxSamples = isWebGL2 ? gl.getParameter(36183) : 0;
  15662. return {
  15663. isWebGL2: isWebGL2,
  15664. getMaxAnisotropy: getMaxAnisotropy,
  15665. getMaxPrecision: getMaxPrecision,
  15666. precision: precision,
  15667. logarithmicDepthBuffer: logarithmicDepthBuffer,
  15668. maxTextures: maxTextures,
  15669. maxVertexTextures: maxVertexTextures,
  15670. maxTextureSize: maxTextureSize,
  15671. maxCubemapSize: maxCubemapSize,
  15672. maxAttributes: maxAttributes,
  15673. maxVertexUniforms: maxVertexUniforms,
  15674. maxVaryings: maxVaryings,
  15675. maxFragmentUniforms: maxFragmentUniforms,
  15676. vertexTextures: vertexTextures,
  15677. floatFragmentTextures: floatFragmentTextures,
  15678. floatVertexTextures: floatVertexTextures,
  15679. maxSamples: maxSamples
  15680. };
  15681. }
  15682. function WebGLClipping(properties) {
  15683. var scope = this;
  15684. var globalState = null,
  15685. numGlobalPlanes = 0,
  15686. localClippingEnabled = false,
  15687. renderingShadows = false;
  15688. var plane = new Plane(),
  15689. viewNormalMatrix = new Matrix3(),
  15690. uniform = {
  15691. value: null,
  15692. needsUpdate: false
  15693. };
  15694. this.uniform = uniform;
  15695. this.numPlanes = 0;
  15696. this.numIntersection = 0;
  15697. this.init = function (planes, enableLocalClipping, camera) {
  15698. var enabled = planes.length !== 0 || enableLocalClipping || // enable state of previous frame - the clipping code has to
  15699. // run another frame in order to reset the state:
  15700. numGlobalPlanes !== 0 || localClippingEnabled;
  15701. localClippingEnabled = enableLocalClipping;
  15702. globalState = projectPlanes(planes, camera, 0);
  15703. numGlobalPlanes = planes.length;
  15704. return enabled;
  15705. };
  15706. this.beginShadows = function () {
  15707. renderingShadows = true;
  15708. projectPlanes(null);
  15709. };
  15710. this.endShadows = function () {
  15711. renderingShadows = false;
  15712. resetGlobalState();
  15713. };
  15714. this.setState = function (material, camera, useCache) {
  15715. var planes = material.clippingPlanes,
  15716. clipIntersection = material.clipIntersection,
  15717. clipShadows = material.clipShadows;
  15718. var materialProperties = properties.get(material);
  15719. if (!localClippingEnabled || planes === null || planes.length === 0 || renderingShadows && !clipShadows) {
  15720. // there's no local clipping
  15721. if (renderingShadows) {
  15722. // there's no global clipping
  15723. projectPlanes(null);
  15724. } else {
  15725. resetGlobalState();
  15726. }
  15727. } else {
  15728. var nGlobal = renderingShadows ? 0 : numGlobalPlanes,
  15729. lGlobal = nGlobal * 4;
  15730. var dstArray = materialProperties.clippingState || null;
  15731. uniform.value = dstArray; // ensure unique state
  15732. dstArray = projectPlanes(planes, camera, lGlobal, useCache);
  15733. for (var i = 0; i !== lGlobal; ++i) {
  15734. dstArray[i] = globalState[i];
  15735. }
  15736. materialProperties.clippingState = dstArray;
  15737. this.numIntersection = clipIntersection ? this.numPlanes : 0;
  15738. this.numPlanes += nGlobal;
  15739. }
  15740. };
  15741. function resetGlobalState() {
  15742. if (uniform.value !== globalState) {
  15743. uniform.value = globalState;
  15744. uniform.needsUpdate = numGlobalPlanes > 0;
  15745. }
  15746. scope.numPlanes = numGlobalPlanes;
  15747. scope.numIntersection = 0;
  15748. }
  15749. function projectPlanes(planes, camera, dstOffset, skipTransform) {
  15750. var nPlanes = planes !== null ? planes.length : 0;
  15751. var dstArray = null;
  15752. if (nPlanes !== 0) {
  15753. dstArray = uniform.value;
  15754. if (skipTransform !== true || dstArray === null) {
  15755. var flatSize = dstOffset + nPlanes * 4,
  15756. viewMatrix = camera.matrixWorldInverse;
  15757. viewNormalMatrix.getNormalMatrix(viewMatrix);
  15758. if (dstArray === null || dstArray.length < flatSize) {
  15759. dstArray = new Float32Array(flatSize);
  15760. }
  15761. for (var i = 0, i4 = dstOffset; i !== nPlanes; ++i, i4 += 4) {
  15762. plane.copy(planes[i]).applyMatrix4(viewMatrix, viewNormalMatrix);
  15763. plane.normal.toArray(dstArray, i4);
  15764. dstArray[i4 + 3] = plane.constant;
  15765. }
  15766. }
  15767. uniform.value = dstArray;
  15768. uniform.needsUpdate = true;
  15769. }
  15770. scope.numPlanes = nPlanes;
  15771. scope.numIntersection = 0;
  15772. return dstArray;
  15773. }
  15774. }
  15775. function WebGLCubeMaps(renderer) {
  15776. var cubemaps = new WeakMap();
  15777. function mapTextureMapping(texture, mapping) {
  15778. if (mapping === EquirectangularReflectionMapping) {
  15779. texture.mapping = CubeReflectionMapping;
  15780. } else if (mapping === EquirectangularRefractionMapping) {
  15781. texture.mapping = CubeRefractionMapping;
  15782. }
  15783. return texture;
  15784. }
  15785. function get(texture) {
  15786. if (texture && texture.isTexture) {
  15787. var mapping = texture.mapping;
  15788. if (mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping) {
  15789. if (cubemaps.has(texture)) {
  15790. var cubemap = cubemaps.get(texture).texture;
  15791. return mapTextureMapping(cubemap, texture.mapping);
  15792. } else {
  15793. var image = texture.image;
  15794. if (image && image.height > 0) {
  15795. var currentRenderList = renderer.getRenderList();
  15796. var currentRenderTarget = renderer.getRenderTarget();
  15797. var renderTarget = new WebGLCubeRenderTarget(image.height / 2);
  15798. renderTarget.fromEquirectangularTexture(renderer, texture);
  15799. cubemaps.set(texture, renderTarget);
  15800. renderer.setRenderTarget(currentRenderTarget);
  15801. renderer.setRenderList(currentRenderList);
  15802. texture.addEventListener('dispose', onTextureDispose);
  15803. return mapTextureMapping(renderTarget.texture, texture.mapping);
  15804. } else {
  15805. // image not yet ready. try the conversion next frame
  15806. return null;
  15807. }
  15808. }
  15809. }
  15810. }
  15811. return texture;
  15812. }
  15813. function onTextureDispose(event) {
  15814. var texture = event.target;
  15815. texture.removeEventListener('dispose', onTextureDispose);
  15816. var cubemap = cubemaps.get(texture);
  15817. if (cubemap !== undefined) {
  15818. cubemaps.delete(texture);
  15819. cubemap.dispose();
  15820. }
  15821. }
  15822. function dispose() {
  15823. cubemaps = new WeakMap();
  15824. }
  15825. return {
  15826. get: get,
  15827. dispose: dispose
  15828. };
  15829. }
  15830. function WebGLExtensions(gl) {
  15831. var extensions = {};
  15832. function getExtension(name) {
  15833. if (extensions[name] !== undefined) {
  15834. return extensions[name];
  15835. }
  15836. var extension;
  15837. switch (name) {
  15838. case 'WEBGL_depth_texture':
  15839. extension = gl.getExtension('WEBGL_depth_texture') || gl.getExtension('MOZ_WEBGL_depth_texture') || gl.getExtension('WEBKIT_WEBGL_depth_texture');
  15840. break;
  15841. case 'EXT_texture_filter_anisotropic':
  15842. extension = gl.getExtension('EXT_texture_filter_anisotropic') || gl.getExtension('MOZ_EXT_texture_filter_anisotropic') || gl.getExtension('WEBKIT_EXT_texture_filter_anisotropic');
  15843. break;
  15844. case 'WEBGL_compressed_texture_s3tc':
  15845. extension = gl.getExtension('WEBGL_compressed_texture_s3tc') || gl.getExtension('MOZ_WEBGL_compressed_texture_s3tc') || gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  15846. break;
  15847. case 'WEBGL_compressed_texture_pvrtc':
  15848. extension = gl.getExtension('WEBGL_compressed_texture_pvrtc') || gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  15849. break;
  15850. default:
  15851. extension = gl.getExtension(name);
  15852. }
  15853. extensions[name] = extension;
  15854. return extension;
  15855. }
  15856. return {
  15857. has: function has(name) {
  15858. return getExtension(name) !== null;
  15859. },
  15860. init: function init(capabilities) {
  15861. if (capabilities.isWebGL2) {
  15862. getExtension('EXT_color_buffer_float');
  15863. } else {
  15864. getExtension('WEBGL_depth_texture');
  15865. getExtension('OES_texture_float');
  15866. getExtension('OES_texture_half_float');
  15867. getExtension('OES_texture_half_float_linear');
  15868. getExtension('OES_standard_derivatives');
  15869. getExtension('OES_element_index_uint');
  15870. getExtension('OES_vertex_array_object');
  15871. getExtension('ANGLE_instanced_arrays');
  15872. }
  15873. getExtension('OES_texture_float_linear');
  15874. getExtension('EXT_color_buffer_half_float');
  15875. },
  15876. get: function get(name) {
  15877. var extension = getExtension(name);
  15878. if (extension === null) {
  15879. console.warn('THREE.WebGLRenderer: ' + name + ' extension not supported.');
  15880. }
  15881. return extension;
  15882. }
  15883. };
  15884. }
  15885. function WebGLGeometries(gl, attributes, info, bindingStates) {
  15886. var geometries = {};
  15887. var wireframeAttributes = new WeakMap();
  15888. function onGeometryDispose(event) {
  15889. var geometry = event.target;
  15890. if (geometry.index !== null) {
  15891. attributes.remove(geometry.index);
  15892. }
  15893. for (var name in geometry.attributes) {
  15894. attributes.remove(geometry.attributes[name]);
  15895. }
  15896. geometry.removeEventListener('dispose', onGeometryDispose);
  15897. delete geometries[geometry.id];
  15898. var attribute = wireframeAttributes.get(geometry);
  15899. if (attribute) {
  15900. attributes.remove(attribute);
  15901. wireframeAttributes.delete(geometry);
  15902. }
  15903. bindingStates.releaseStatesOfGeometry(geometry);
  15904. if (geometry.isInstancedBufferGeometry === true) {
  15905. delete geometry._maxInstanceCount;
  15906. } //
  15907. info.memory.geometries--;
  15908. }
  15909. function get(object, geometry) {
  15910. if (geometries[geometry.id] === true) return geometry;
  15911. geometry.addEventListener('dispose', onGeometryDispose);
  15912. geometries[geometry.id] = true;
  15913. info.memory.geometries++;
  15914. return geometry;
  15915. }
  15916. function update(geometry) {
  15917. var geometryAttributes = geometry.attributes; // Updating index buffer in VAO now. See WebGLBindingStates.
  15918. for (var name in geometryAttributes) {
  15919. attributes.update(geometryAttributes[name], 34962);
  15920. } // morph targets
  15921. var morphAttributes = geometry.morphAttributes;
  15922. for (var _name in morphAttributes) {
  15923. var array = morphAttributes[_name];
  15924. for (var i = 0, l = array.length; i < l; i++) {
  15925. attributes.update(array[i], 34962);
  15926. }
  15927. }
  15928. }
  15929. function updateWireframeAttribute(geometry) {
  15930. var indices = [];
  15931. var geometryIndex = geometry.index;
  15932. var geometryPosition = geometry.attributes.position;
  15933. var version = 0;
  15934. if (geometryIndex !== null) {
  15935. var array = geometryIndex.array;
  15936. version = geometryIndex.version;
  15937. for (var i = 0, l = array.length; i < l; i += 3) {
  15938. var a = array[i + 0];
  15939. var b = array[i + 1];
  15940. var c = array[i + 2];
  15941. indices.push(a, b, b, c, c, a);
  15942. }
  15943. } else {
  15944. var _array = geometryPosition.array;
  15945. version = geometryPosition.version;
  15946. for (var _i = 0, _l = _array.length / 3 - 1; _i < _l; _i += 3) {
  15947. var _a = _i + 0;
  15948. var _b = _i + 1;
  15949. var _c = _i + 2;
  15950. indices.push(_a, _b, _b, _c, _c, _a);
  15951. }
  15952. }
  15953. var attribute = new (arrayMax(indices) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute)(indices, 1);
  15954. attribute.version = version; // Updating index buffer in VAO now. See WebGLBindingStates
  15955. //
  15956. var previousAttribute = wireframeAttributes.get(geometry);
  15957. if (previousAttribute) attributes.remove(previousAttribute); //
  15958. wireframeAttributes.set(geometry, attribute);
  15959. }
  15960. function getWireframeAttribute(geometry) {
  15961. var currentAttribute = wireframeAttributes.get(geometry);
  15962. if (currentAttribute) {
  15963. var geometryIndex = geometry.index;
  15964. if (geometryIndex !== null) {
  15965. // if the attribute is obsolete, create a new one
  15966. if (currentAttribute.version < geometryIndex.version) {
  15967. updateWireframeAttribute(geometry);
  15968. }
  15969. }
  15970. } else {
  15971. updateWireframeAttribute(geometry);
  15972. }
  15973. return wireframeAttributes.get(geometry);
  15974. }
  15975. return {
  15976. get: get,
  15977. update: update,
  15978. getWireframeAttribute: getWireframeAttribute
  15979. };
  15980. }
  15981. function WebGLIndexedBufferRenderer(gl, extensions, info, capabilities) {
  15982. var isWebGL2 = capabilities.isWebGL2;
  15983. var mode;
  15984. function setMode(value) {
  15985. mode = value;
  15986. }
  15987. var type, bytesPerElement;
  15988. function setIndex(value) {
  15989. type = value.type;
  15990. bytesPerElement = value.bytesPerElement;
  15991. }
  15992. function render(start, count) {
  15993. gl.drawElements(mode, count, type, start * bytesPerElement);
  15994. info.update(count, mode, 1);
  15995. }
  15996. function renderInstances(start, count, primcount) {
  15997. if (primcount === 0) return;
  15998. var extension, methodName;
  15999. if (isWebGL2) {
  16000. extension = gl;
  16001. methodName = 'drawElementsInstanced';
  16002. } else {
  16003. extension = extensions.get('ANGLE_instanced_arrays');
  16004. methodName = 'drawElementsInstancedANGLE';
  16005. if (extension === null) {
  16006. console.error('THREE.WebGLIndexedBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.');
  16007. return;
  16008. }
  16009. }
  16010. extension[methodName](mode, count, type, start * bytesPerElement, primcount);
  16011. info.update(count, mode, primcount);
  16012. } //
  16013. this.setMode = setMode;
  16014. this.setIndex = setIndex;
  16015. this.render = render;
  16016. this.renderInstances = renderInstances;
  16017. }
  16018. function WebGLInfo(gl) {
  16019. var memory = {
  16020. geometries: 0,
  16021. textures: 0
  16022. };
  16023. var render = {
  16024. frame: 0,
  16025. calls: 0,
  16026. triangles: 0,
  16027. points: 0,
  16028. lines: 0
  16029. };
  16030. function update(count, mode, instanceCount) {
  16031. render.calls++;
  16032. switch (mode) {
  16033. case 4:
  16034. render.triangles += instanceCount * (count / 3);
  16035. break;
  16036. case 1:
  16037. render.lines += instanceCount * (count / 2);
  16038. break;
  16039. case 3:
  16040. render.lines += instanceCount * (count - 1);
  16041. break;
  16042. case 2:
  16043. render.lines += instanceCount * count;
  16044. break;
  16045. case 0:
  16046. render.points += instanceCount * count;
  16047. break;
  16048. default:
  16049. console.error('THREE.WebGLInfo: Unknown draw mode:', mode);
  16050. break;
  16051. }
  16052. }
  16053. function reset() {
  16054. render.frame++;
  16055. render.calls = 0;
  16056. render.triangles = 0;
  16057. render.points = 0;
  16058. render.lines = 0;
  16059. }
  16060. return {
  16061. memory: memory,
  16062. render: render,
  16063. programs: null,
  16064. autoReset: true,
  16065. reset: reset,
  16066. update: update
  16067. };
  16068. }
  16069. function numericalSort(a, b) {
  16070. return a[0] - b[0];
  16071. }
  16072. function absNumericalSort(a, b) {
  16073. return Math.abs(b[1]) - Math.abs(a[1]);
  16074. }
  16075. function WebGLMorphtargets(gl) {
  16076. var influencesList = {};
  16077. var morphInfluences = new Float32Array(8);
  16078. var workInfluences = [];
  16079. for (var i = 0; i < 8; i++) {
  16080. workInfluences[i] = [i, 0];
  16081. }
  16082. function update(object, geometry, material, program) {
  16083. var objectInfluences = object.morphTargetInfluences; // When object doesn't have morph target influences defined, we treat it as a 0-length array
  16084. // This is important to make sure we set up morphTargetBaseInfluence / morphTargetInfluences
  16085. var length = objectInfluences === undefined ? 0 : objectInfluences.length;
  16086. var influences = influencesList[geometry.id];
  16087. if (influences === undefined) {
  16088. // initialise list
  16089. influences = [];
  16090. for (var _i = 0; _i < length; _i++) {
  16091. influences[_i] = [_i, 0];
  16092. }
  16093. influencesList[geometry.id] = influences;
  16094. } // Collect influences
  16095. for (var _i2 = 0; _i2 < length; _i2++) {
  16096. var influence = influences[_i2];
  16097. influence[0] = _i2;
  16098. influence[1] = objectInfluences[_i2];
  16099. }
  16100. influences.sort(absNumericalSort);
  16101. for (var _i3 = 0; _i3 < 8; _i3++) {
  16102. if (_i3 < length && influences[_i3][1]) {
  16103. workInfluences[_i3][0] = influences[_i3][0];
  16104. workInfluences[_i3][1] = influences[_i3][1];
  16105. } else {
  16106. workInfluences[_i3][0] = Number.MAX_SAFE_INTEGER;
  16107. workInfluences[_i3][1] = 0;
  16108. }
  16109. }
  16110. workInfluences.sort(numericalSort);
  16111. var morphTargets = material.morphTargets && geometry.morphAttributes.position;
  16112. var morphNormals = material.morphNormals && geometry.morphAttributes.normal;
  16113. var morphInfluencesSum = 0;
  16114. for (var _i4 = 0; _i4 < 8; _i4++) {
  16115. var _influence = workInfluences[_i4];
  16116. var index = _influence[0];
  16117. var value = _influence[1];
  16118. if (index !== Number.MAX_SAFE_INTEGER && value) {
  16119. if (morphTargets && geometry.getAttribute('morphTarget' + _i4) !== morphTargets[index]) {
  16120. geometry.setAttribute('morphTarget' + _i4, morphTargets[index]);
  16121. }
  16122. if (morphNormals && geometry.getAttribute('morphNormal' + _i4) !== morphNormals[index]) {
  16123. geometry.setAttribute('morphNormal' + _i4, morphNormals[index]);
  16124. }
  16125. morphInfluences[_i4] = value;
  16126. morphInfluencesSum += value;
  16127. } else {
  16128. if (morphTargets && geometry.hasAttribute('morphTarget' + _i4) === true) {
  16129. geometry.deleteAttribute('morphTarget' + _i4);
  16130. }
  16131. if (morphNormals && geometry.hasAttribute('morphNormal' + _i4) === true) {
  16132. geometry.deleteAttribute('morphNormal' + _i4);
  16133. }
  16134. morphInfluences[_i4] = 0;
  16135. }
  16136. } // GLSL shader uses formula baseinfluence * base + sum(target * influence)
  16137. // This allows us to switch between absolute morphs and relative morphs without changing shader code
  16138. // When baseinfluence = 1 - sum(influence), the above is equivalent to sum((target - base) * influence)
  16139. var morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  16140. program.getUniforms().setValue(gl, 'morphTargetBaseInfluence', morphBaseInfluence);
  16141. program.getUniforms().setValue(gl, 'morphTargetInfluences', morphInfluences);
  16142. }
  16143. return {
  16144. update: update
  16145. };
  16146. }
  16147. function WebGLObjects(gl, geometries, attributes, info) {
  16148. var updateMap = new WeakMap();
  16149. function update(object) {
  16150. var frame = info.render.frame;
  16151. var geometry = object.geometry;
  16152. var buffergeometry = geometries.get(object, geometry); // Update once per frame
  16153. if (updateMap.get(buffergeometry) !== frame) {
  16154. geometries.update(buffergeometry);
  16155. updateMap.set(buffergeometry, frame);
  16156. }
  16157. if (object.isInstancedMesh) {
  16158. if (object.hasEventListener('dispose', onInstancedMeshDispose) === false) {
  16159. object.addEventListener('dispose', onInstancedMeshDispose);
  16160. }
  16161. attributes.update(object.instanceMatrix, 34962);
  16162. if (object.instanceColor !== null) {
  16163. attributes.update(object.instanceColor, 34962);
  16164. }
  16165. }
  16166. return buffergeometry;
  16167. }
  16168. function dispose() {
  16169. updateMap = new WeakMap();
  16170. }
  16171. function onInstancedMeshDispose(event) {
  16172. var instancedMesh = event.target;
  16173. instancedMesh.removeEventListener('dispose', onInstancedMeshDispose);
  16174. attributes.remove(instancedMesh.instanceMatrix);
  16175. if (instancedMesh.instanceColor !== null) attributes.remove(instancedMesh.instanceColor);
  16176. }
  16177. return {
  16178. update: update,
  16179. dispose: dispose
  16180. };
  16181. }
  16182. function DataTexture2DArray(data, width, height, depth) {
  16183. if (data === void 0) {
  16184. data = null;
  16185. }
  16186. if (width === void 0) {
  16187. width = 1;
  16188. }
  16189. if (height === void 0) {
  16190. height = 1;
  16191. }
  16192. if (depth === void 0) {
  16193. depth = 1;
  16194. }
  16195. Texture.call(this, null);
  16196. this.image = {
  16197. data: data,
  16198. width: width,
  16199. height: height,
  16200. depth: depth
  16201. };
  16202. this.magFilter = NearestFilter;
  16203. this.minFilter = NearestFilter;
  16204. this.wrapR = ClampToEdgeWrapping;
  16205. this.generateMipmaps = false;
  16206. this.flipY = false;
  16207. this.needsUpdate = true;
  16208. }
  16209. DataTexture2DArray.prototype = Object.create(Texture.prototype);
  16210. DataTexture2DArray.prototype.constructor = DataTexture2DArray;
  16211. DataTexture2DArray.prototype.isDataTexture2DArray = true;
  16212. function DataTexture3D(data, width, height, depth) {
  16213. if (data === void 0) {
  16214. data = null;
  16215. }
  16216. if (width === void 0) {
  16217. width = 1;
  16218. }
  16219. if (height === void 0) {
  16220. height = 1;
  16221. }
  16222. if (depth === void 0) {
  16223. depth = 1;
  16224. }
  16225. // We're going to add .setXXX() methods for setting properties later.
  16226. // Users can still set in DataTexture3D directly.
  16227. //
  16228. // const texture = new THREE.DataTexture3D( data, width, height, depth );
  16229. // texture.anisotropy = 16;
  16230. //
  16231. // See #14839
  16232. Texture.call(this, null);
  16233. this.image = {
  16234. data: data,
  16235. width: width,
  16236. height: height,
  16237. depth: depth
  16238. };
  16239. this.magFilter = NearestFilter;
  16240. this.minFilter = NearestFilter;
  16241. this.wrapR = ClampToEdgeWrapping;
  16242. this.generateMipmaps = false;
  16243. this.flipY = false;
  16244. this.needsUpdate = true;
  16245. }
  16246. DataTexture3D.prototype = Object.create(Texture.prototype);
  16247. DataTexture3D.prototype.constructor = DataTexture3D;
  16248. DataTexture3D.prototype.isDataTexture3D = true;
  16249. /**
  16250. * Uniforms of a program.
  16251. * Those form a tree structure with a special top-level container for the root,
  16252. * which you get by calling 'new WebGLUniforms( gl, program )'.
  16253. *
  16254. *
  16255. * Properties of inner nodes including the top-level container:
  16256. *
  16257. * .seq - array of nested uniforms
  16258. * .map - nested uniforms by name
  16259. *
  16260. *
  16261. * Methods of all nodes except the top-level container:
  16262. *
  16263. * .setValue( gl, value, [textures] )
  16264. *
  16265. * uploads a uniform value(s)
  16266. * the 'textures' parameter is needed for sampler uniforms
  16267. *
  16268. *
  16269. * Static methods of the top-level container (textures factorizations):
  16270. *
  16271. * .upload( gl, seq, values, textures )
  16272. *
  16273. * sets uniforms in 'seq' to 'values[id].value'
  16274. *
  16275. * .seqWithValue( seq, values ) : filteredSeq
  16276. *
  16277. * filters 'seq' entries with corresponding entry in values
  16278. *
  16279. *
  16280. * Methods of the top-level container (textures factorizations):
  16281. *
  16282. * .setValue( gl, name, value, textures )
  16283. *
  16284. * sets uniform with name 'name' to 'value'
  16285. *
  16286. * .setOptional( gl, obj, prop )
  16287. *
  16288. * like .set for an optional property of the object
  16289. *
  16290. */
  16291. var emptyTexture = new Texture();
  16292. var emptyTexture2dArray = new DataTexture2DArray();
  16293. var emptyTexture3d = new DataTexture3D();
  16294. var emptyCubeTexture = new CubeTexture(); // --- Utilities ---
  16295. // Array Caches (provide typed arrays for temporary by size)
  16296. var arrayCacheF32 = [];
  16297. var arrayCacheI32 = []; // Float32Array caches used for uploading Matrix uniforms
  16298. var mat4array = new Float32Array(16);
  16299. var mat3array = new Float32Array(9);
  16300. var mat2array = new Float32Array(4); // Flattening for arrays of vectors and matrices
  16301. function flatten(array, nBlocks, blockSize) {
  16302. var firstElem = array[0];
  16303. if (firstElem <= 0 || firstElem > 0) return array; // unoptimized: ! isNaN( firstElem )
  16304. // see http://jacksondunstan.com/articles/983
  16305. var n = nBlocks * blockSize;
  16306. var r = arrayCacheF32[n];
  16307. if (r === undefined) {
  16308. r = new Float32Array(n);
  16309. arrayCacheF32[n] = r;
  16310. }
  16311. if (nBlocks !== 0) {
  16312. firstElem.toArray(r, 0);
  16313. for (var i = 1, offset = 0; i !== nBlocks; ++i) {
  16314. offset += blockSize;
  16315. array[i].toArray(r, offset);
  16316. }
  16317. }
  16318. return r;
  16319. }
  16320. function arraysEqual(a, b) {
  16321. if (a.length !== b.length) return false;
  16322. for (var i = 0, l = a.length; i < l; i++) {
  16323. if (a[i] !== b[i]) return false;
  16324. }
  16325. return true;
  16326. }
  16327. function copyArray(a, b) {
  16328. for (var i = 0, l = b.length; i < l; i++) {
  16329. a[i] = b[i];
  16330. }
  16331. } // Texture unit allocation
  16332. function allocTexUnits(textures, n) {
  16333. var r = arrayCacheI32[n];
  16334. if (r === undefined) {
  16335. r = new Int32Array(n);
  16336. arrayCacheI32[n] = r;
  16337. }
  16338. for (var i = 0; i !== n; ++i) {
  16339. r[i] = textures.allocateTextureUnit();
  16340. }
  16341. return r;
  16342. } // --- Setters ---
  16343. // Note: Defining these methods externally, because they come in a bunch
  16344. // and this way their names minify.
  16345. // Single scalar
  16346. function setValueV1f(gl, v) {
  16347. var cache = this.cache;
  16348. if (cache[0] === v) return;
  16349. gl.uniform1f(this.addr, v);
  16350. cache[0] = v;
  16351. } // Single float vector (from flat array or THREE.VectorN)
  16352. function setValueV2f(gl, v) {
  16353. var cache = this.cache;
  16354. if (v.x !== undefined) {
  16355. if (cache[0] !== v.x || cache[1] !== v.y) {
  16356. gl.uniform2f(this.addr, v.x, v.y);
  16357. cache[0] = v.x;
  16358. cache[1] = v.y;
  16359. }
  16360. } else {
  16361. if (arraysEqual(cache, v)) return;
  16362. gl.uniform2fv(this.addr, v);
  16363. copyArray(cache, v);
  16364. }
  16365. }
  16366. function setValueV3f(gl, v) {
  16367. var cache = this.cache;
  16368. if (v.x !== undefined) {
  16369. if (cache[0] !== v.x || cache[1] !== v.y || cache[2] !== v.z) {
  16370. gl.uniform3f(this.addr, v.x, v.y, v.z);
  16371. cache[0] = v.x;
  16372. cache[1] = v.y;
  16373. cache[2] = v.z;
  16374. }
  16375. } else if (v.r !== undefined) {
  16376. if (cache[0] !== v.r || cache[1] !== v.g || cache[2] !== v.b) {
  16377. gl.uniform3f(this.addr, v.r, v.g, v.b);
  16378. cache[0] = v.r;
  16379. cache[1] = v.g;
  16380. cache[2] = v.b;
  16381. }
  16382. } else {
  16383. if (arraysEqual(cache, v)) return;
  16384. gl.uniform3fv(this.addr, v);
  16385. copyArray(cache, v);
  16386. }
  16387. }
  16388. function setValueV4f(gl, v) {
  16389. var cache = this.cache;
  16390. if (v.x !== undefined) {
  16391. if (cache[0] !== v.x || cache[1] !== v.y || cache[2] !== v.z || cache[3] !== v.w) {
  16392. gl.uniform4f(this.addr, v.x, v.y, v.z, v.w);
  16393. cache[0] = v.x;
  16394. cache[1] = v.y;
  16395. cache[2] = v.z;
  16396. cache[3] = v.w;
  16397. }
  16398. } else {
  16399. if (arraysEqual(cache, v)) return;
  16400. gl.uniform4fv(this.addr, v);
  16401. copyArray(cache, v);
  16402. }
  16403. } // Single matrix (from flat array or MatrixN)
  16404. function setValueM2(gl, v) {
  16405. var cache = this.cache;
  16406. var elements = v.elements;
  16407. if (elements === undefined) {
  16408. if (arraysEqual(cache, v)) return;
  16409. gl.uniformMatrix2fv(this.addr, false, v);
  16410. copyArray(cache, v);
  16411. } else {
  16412. if (arraysEqual(cache, elements)) return;
  16413. mat2array.set(elements);
  16414. gl.uniformMatrix2fv(this.addr, false, mat2array);
  16415. copyArray(cache, elements);
  16416. }
  16417. }
  16418. function setValueM3(gl, v) {
  16419. var cache = this.cache;
  16420. var elements = v.elements;
  16421. if (elements === undefined) {
  16422. if (arraysEqual(cache, v)) return;
  16423. gl.uniformMatrix3fv(this.addr, false, v);
  16424. copyArray(cache, v);
  16425. } else {
  16426. if (arraysEqual(cache, elements)) return;
  16427. mat3array.set(elements);
  16428. gl.uniformMatrix3fv(this.addr, false, mat3array);
  16429. copyArray(cache, elements);
  16430. }
  16431. }
  16432. function setValueM4(gl, v) {
  16433. var cache = this.cache;
  16434. var elements = v.elements;
  16435. if (elements === undefined) {
  16436. if (arraysEqual(cache, v)) return;
  16437. gl.uniformMatrix4fv(this.addr, false, v);
  16438. copyArray(cache, v);
  16439. } else {
  16440. if (arraysEqual(cache, elements)) return;
  16441. mat4array.set(elements);
  16442. gl.uniformMatrix4fv(this.addr, false, mat4array);
  16443. copyArray(cache, elements);
  16444. }
  16445. } // Single texture (2D / Cube)
  16446. function setValueT1(gl, v, textures) {
  16447. var cache = this.cache;
  16448. var unit = textures.allocateTextureUnit();
  16449. if (cache[0] !== unit) {
  16450. gl.uniform1i(this.addr, unit);
  16451. cache[0] = unit;
  16452. }
  16453. textures.safeSetTexture2D(v || emptyTexture, unit);
  16454. }
  16455. function setValueT2DArray1(gl, v, textures) {
  16456. var cache = this.cache;
  16457. var unit = textures.allocateTextureUnit();
  16458. if (cache[0] !== unit) {
  16459. gl.uniform1i(this.addr, unit);
  16460. cache[0] = unit;
  16461. }
  16462. textures.setTexture2DArray(v || emptyTexture2dArray, unit);
  16463. }
  16464. function setValueT3D1(gl, v, textures) {
  16465. var cache = this.cache;
  16466. var unit = textures.allocateTextureUnit();
  16467. if (cache[0] !== unit) {
  16468. gl.uniform1i(this.addr, unit);
  16469. cache[0] = unit;
  16470. }
  16471. textures.setTexture3D(v || emptyTexture3d, unit);
  16472. }
  16473. function setValueT6(gl, v, textures) {
  16474. var cache = this.cache;
  16475. var unit = textures.allocateTextureUnit();
  16476. if (cache[0] !== unit) {
  16477. gl.uniform1i(this.addr, unit);
  16478. cache[0] = unit;
  16479. }
  16480. textures.safeSetTextureCube(v || emptyCubeTexture, unit);
  16481. } // Integer / Boolean vectors or arrays thereof (always flat arrays)
  16482. function setValueV1i(gl, v) {
  16483. var cache = this.cache;
  16484. if (cache[0] === v) return;
  16485. gl.uniform1i(this.addr, v);
  16486. cache[0] = v;
  16487. }
  16488. function setValueV2i(gl, v) {
  16489. var cache = this.cache;
  16490. if (arraysEqual(cache, v)) return;
  16491. gl.uniform2iv(this.addr, v);
  16492. copyArray(cache, v);
  16493. }
  16494. function setValueV3i(gl, v) {
  16495. var cache = this.cache;
  16496. if (arraysEqual(cache, v)) return;
  16497. gl.uniform3iv(this.addr, v);
  16498. copyArray(cache, v);
  16499. }
  16500. function setValueV4i(gl, v) {
  16501. var cache = this.cache;
  16502. if (arraysEqual(cache, v)) return;
  16503. gl.uniform4iv(this.addr, v);
  16504. copyArray(cache, v);
  16505. } // uint
  16506. function setValueV1ui(gl, v) {
  16507. var cache = this.cache;
  16508. if (cache[0] === v) return;
  16509. gl.uniform1ui(this.addr, v);
  16510. cache[0] = v;
  16511. } // Helper to pick the right setter for the singular case
  16512. function getSingularSetter(type) {
  16513. switch (type) {
  16514. case 0x1406:
  16515. return setValueV1f;
  16516. // FLOAT
  16517. case 0x8b50:
  16518. return setValueV2f;
  16519. // _VEC2
  16520. case 0x8b51:
  16521. return setValueV3f;
  16522. // _VEC3
  16523. case 0x8b52:
  16524. return setValueV4f;
  16525. // _VEC4
  16526. case 0x8b5a:
  16527. return setValueM2;
  16528. // _MAT2
  16529. case 0x8b5b:
  16530. return setValueM3;
  16531. // _MAT3
  16532. case 0x8b5c:
  16533. return setValueM4;
  16534. // _MAT4
  16535. case 0x1404:
  16536. case 0x8b56:
  16537. return setValueV1i;
  16538. // INT, BOOL
  16539. case 0x8b53:
  16540. case 0x8b57:
  16541. return setValueV2i;
  16542. // _VEC2
  16543. case 0x8b54:
  16544. case 0x8b58:
  16545. return setValueV3i;
  16546. // _VEC3
  16547. case 0x8b55:
  16548. case 0x8b59:
  16549. return setValueV4i;
  16550. // _VEC4
  16551. case 0x1405:
  16552. return setValueV1ui;
  16553. // UINT
  16554. case 0x8b5e: // SAMPLER_2D
  16555. case 0x8d66: // SAMPLER_EXTERNAL_OES
  16556. case 0x8dca: // INT_SAMPLER_2D
  16557. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  16558. case 0x8b62:
  16559. // SAMPLER_2D_SHADOW
  16560. return setValueT1;
  16561. case 0x8b5f: // SAMPLER_3D
  16562. case 0x8dcb: // INT_SAMPLER_3D
  16563. case 0x8dd3:
  16564. // UNSIGNED_INT_SAMPLER_3D
  16565. return setValueT3D1;
  16566. case 0x8b60: // SAMPLER_CUBE
  16567. case 0x8dcc: // INT_SAMPLER_CUBE
  16568. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  16569. case 0x8dc5:
  16570. // SAMPLER_CUBE_SHADOW
  16571. return setValueT6;
  16572. case 0x8dc1: // SAMPLER_2D_ARRAY
  16573. case 0x8dcf: // INT_SAMPLER_2D_ARRAY
  16574. case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY
  16575. case 0x8dc4:
  16576. // SAMPLER_2D_ARRAY_SHADOW
  16577. return setValueT2DArray1;
  16578. }
  16579. } // Array of scalars
  16580. function setValueV1fArray(gl, v) {
  16581. gl.uniform1fv(this.addr, v);
  16582. } // Integer / Boolean vectors or arrays thereof (always flat arrays)
  16583. function setValueV1iArray(gl, v) {
  16584. gl.uniform1iv(this.addr, v);
  16585. }
  16586. function setValueV2iArray(gl, v) {
  16587. gl.uniform2iv(this.addr, v);
  16588. }
  16589. function setValueV3iArray(gl, v) {
  16590. gl.uniform3iv(this.addr, v);
  16591. }
  16592. function setValueV4iArray(gl, v) {
  16593. gl.uniform4iv(this.addr, v);
  16594. } // Array of vectors (flat or from THREE classes)
  16595. function setValueV2fArray(gl, v) {
  16596. var data = flatten(v, this.size, 2);
  16597. gl.uniform2fv(this.addr, data);
  16598. }
  16599. function setValueV3fArray(gl, v) {
  16600. var data = flatten(v, this.size, 3);
  16601. gl.uniform3fv(this.addr, data);
  16602. }
  16603. function setValueV4fArray(gl, v) {
  16604. var data = flatten(v, this.size, 4);
  16605. gl.uniform4fv(this.addr, data);
  16606. } // Array of matrices (flat or from THREE clases)
  16607. function setValueM2Array(gl, v) {
  16608. var data = flatten(v, this.size, 4);
  16609. gl.uniformMatrix2fv(this.addr, false, data);
  16610. }
  16611. function setValueM3Array(gl, v) {
  16612. var data = flatten(v, this.size, 9);
  16613. gl.uniformMatrix3fv(this.addr, false, data);
  16614. }
  16615. function setValueM4Array(gl, v) {
  16616. var data = flatten(v, this.size, 16);
  16617. gl.uniformMatrix4fv(this.addr, false, data);
  16618. } // Array of textures (2D / Cube)
  16619. function setValueT1Array(gl, v, textures) {
  16620. var n = v.length;
  16621. var units = allocTexUnits(textures, n);
  16622. gl.uniform1iv(this.addr, units);
  16623. for (var i = 0; i !== n; ++i) {
  16624. textures.safeSetTexture2D(v[i] || emptyTexture, units[i]);
  16625. }
  16626. }
  16627. function setValueT6Array(gl, v, textures) {
  16628. var n = v.length;
  16629. var units = allocTexUnits(textures, n);
  16630. gl.uniform1iv(this.addr, units);
  16631. for (var i = 0; i !== n; ++i) {
  16632. textures.safeSetTextureCube(v[i] || emptyCubeTexture, units[i]);
  16633. }
  16634. } // Helper to pick the right setter for a pure (bottom-level) array
  16635. function getPureArraySetter(type) {
  16636. switch (type) {
  16637. case 0x1406:
  16638. return setValueV1fArray;
  16639. // FLOAT
  16640. case 0x8b50:
  16641. return setValueV2fArray;
  16642. // _VEC2
  16643. case 0x8b51:
  16644. return setValueV3fArray;
  16645. // _VEC3
  16646. case 0x8b52:
  16647. return setValueV4fArray;
  16648. // _VEC4
  16649. case 0x8b5a:
  16650. return setValueM2Array;
  16651. // _MAT2
  16652. case 0x8b5b:
  16653. return setValueM3Array;
  16654. // _MAT3
  16655. case 0x8b5c:
  16656. return setValueM4Array;
  16657. // _MAT4
  16658. case 0x1404:
  16659. case 0x8b56:
  16660. return setValueV1iArray;
  16661. // INT, BOOL
  16662. case 0x8b53:
  16663. case 0x8b57:
  16664. return setValueV2iArray;
  16665. // _VEC2
  16666. case 0x8b54:
  16667. case 0x8b58:
  16668. return setValueV3iArray;
  16669. // _VEC3
  16670. case 0x8b55:
  16671. case 0x8b59:
  16672. return setValueV4iArray;
  16673. // _VEC4
  16674. case 0x8b5e: // SAMPLER_2D
  16675. case 0x8d66: // SAMPLER_EXTERNAL_OES
  16676. case 0x8dca: // INT_SAMPLER_2D
  16677. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  16678. case 0x8b62:
  16679. // SAMPLER_2D_SHADOW
  16680. return setValueT1Array;
  16681. case 0x8b60: // SAMPLER_CUBE
  16682. case 0x8dcc: // INT_SAMPLER_CUBE
  16683. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  16684. case 0x8dc5:
  16685. // SAMPLER_CUBE_SHADOW
  16686. return setValueT6Array;
  16687. }
  16688. } // --- Uniform Classes ---
  16689. function SingleUniform(id, activeInfo, addr) {
  16690. this.id = id;
  16691. this.addr = addr;
  16692. this.cache = [];
  16693. this.setValue = getSingularSetter(activeInfo.type); // this.path = activeInfo.name; // DEBUG
  16694. }
  16695. function PureArrayUniform(id, activeInfo, addr) {
  16696. this.id = id;
  16697. this.addr = addr;
  16698. this.cache = [];
  16699. this.size = activeInfo.size;
  16700. this.setValue = getPureArraySetter(activeInfo.type); // this.path = activeInfo.name; // DEBUG
  16701. }
  16702. PureArrayUniform.prototype.updateCache = function (data) {
  16703. var cache = this.cache;
  16704. if (data instanceof Float32Array && cache.length !== data.length) {
  16705. this.cache = new Float32Array(data.length);
  16706. }
  16707. copyArray(cache, data);
  16708. };
  16709. function StructuredUniform(id) {
  16710. this.id = id;
  16711. this.seq = [];
  16712. this.map = {};
  16713. }
  16714. StructuredUniform.prototype.setValue = function (gl, value, textures) {
  16715. var seq = this.seq;
  16716. for (var i = 0, n = seq.length; i !== n; ++i) {
  16717. var u = seq[i];
  16718. u.setValue(gl, value[u.id], textures);
  16719. }
  16720. }; // --- Top-level ---
  16721. // Parser - builds up the property tree from the path strings
  16722. var RePathPart = /(\w+)(\])?(\[|\.)?/g; // extracts
  16723. // - the identifier (member name or array index)
  16724. // - followed by an optional right bracket (found when array index)
  16725. // - followed by an optional left bracket or dot (type of subscript)
  16726. //
  16727. // Note: These portions can be read in a non-overlapping fashion and
  16728. // allow straightforward parsing of the hierarchy that WebGL encodes
  16729. // in the uniform names.
  16730. function addUniform(container, uniformObject) {
  16731. container.seq.push(uniformObject);
  16732. container.map[uniformObject.id] = uniformObject;
  16733. }
  16734. function parseUniform(activeInfo, addr, container) {
  16735. var path = activeInfo.name,
  16736. pathLength = path.length; // reset RegExp object, because of the early exit of a previous run
  16737. RePathPart.lastIndex = 0;
  16738. while (true) {
  16739. var match = RePathPart.exec(path),
  16740. matchEnd = RePathPart.lastIndex;
  16741. var id = match[1];
  16742. var idIsIndex = match[2] === ']',
  16743. subscript = match[3];
  16744. if (idIsIndex) id = id | 0; // convert to integer
  16745. if (subscript === undefined || subscript === '[' && matchEnd + 2 === pathLength) {
  16746. // bare name or "pure" bottom-level array "[0]" suffix
  16747. addUniform(container, subscript === undefined ? new SingleUniform(id, activeInfo, addr) : new PureArrayUniform(id, activeInfo, addr));
  16748. break;
  16749. } else {
  16750. // step into inner node / create it in case it doesn't exist
  16751. var map = container.map;
  16752. var next = map[id];
  16753. if (next === undefined) {
  16754. next = new StructuredUniform(id);
  16755. addUniform(container, next);
  16756. }
  16757. container = next;
  16758. }
  16759. }
  16760. } // Root Container
  16761. function WebGLUniforms(gl, program) {
  16762. this.seq = [];
  16763. this.map = {};
  16764. var n = gl.getProgramParameter(program, 35718);
  16765. for (var i = 0; i < n; ++i) {
  16766. var info = gl.getActiveUniform(program, i),
  16767. addr = gl.getUniformLocation(program, info.name);
  16768. parseUniform(info, addr, this);
  16769. }
  16770. }
  16771. WebGLUniforms.prototype.setValue = function (gl, name, value, textures) {
  16772. var u = this.map[name];
  16773. if (u !== undefined) u.setValue(gl, value, textures);
  16774. };
  16775. WebGLUniforms.prototype.setOptional = function (gl, object, name) {
  16776. var v = object[name];
  16777. if (v !== undefined) this.setValue(gl, name, v);
  16778. }; // Static interface
  16779. WebGLUniforms.upload = function (gl, seq, values, textures) {
  16780. for (var i = 0, n = seq.length; i !== n; ++i) {
  16781. var u = seq[i],
  16782. v = values[u.id];
  16783. if (v.needsUpdate !== false) {
  16784. // note: always updating when .needsUpdate is undefined
  16785. u.setValue(gl, v.value, textures);
  16786. }
  16787. }
  16788. };
  16789. WebGLUniforms.seqWithValue = function (seq, values) {
  16790. var r = [];
  16791. for (var i = 0, n = seq.length; i !== n; ++i) {
  16792. var u = seq[i];
  16793. if (u.id in values) r.push(u);
  16794. }
  16795. return r;
  16796. };
  16797. function WebGLShader(gl, type, string) {
  16798. var shader = gl.createShader(type);
  16799. gl.shaderSource(shader, string);
  16800. gl.compileShader(shader);
  16801. return shader;
  16802. }
  16803. var programIdCount = 0;
  16804. function addLineNumbers(string) {
  16805. var lines = string.split('\n');
  16806. for (var i = 0; i < lines.length; i++) {
  16807. lines[i] = i + 1 + ': ' + lines[i];
  16808. }
  16809. return lines.join('\n');
  16810. }
  16811. function getEncodingComponents(encoding) {
  16812. switch (encoding) {
  16813. case LinearEncoding:
  16814. return ['Linear', '( value )'];
  16815. case sRGBEncoding:
  16816. return ['sRGB', '( value )'];
  16817. case RGBEEncoding:
  16818. return ['RGBE', '( value )'];
  16819. case RGBM7Encoding:
  16820. return ['RGBM', '( value, 7.0 )'];
  16821. case RGBM16Encoding:
  16822. return ['RGBM', '( value, 16.0 )'];
  16823. case RGBDEncoding:
  16824. return ['RGBD', '( value, 256.0 )'];
  16825. case GammaEncoding:
  16826. return ['Gamma', '( value, float( GAMMA_FACTOR ) )'];
  16827. case LogLuvEncoding:
  16828. return ['LogLuv', '( value )'];
  16829. default:
  16830. console.warn('THREE.WebGLProgram: Unsupported encoding:', encoding);
  16831. return ['Linear', '( value )'];
  16832. }
  16833. }
  16834. function getShaderErrors(gl, shader, type) {
  16835. var status = gl.getShaderParameter(shader, 35713);
  16836. var log = gl.getShaderInfoLog(shader).trim();
  16837. if (status && log === '') return ''; // --enable-privileged-webgl-extension
  16838. // console.log( '**' + type + '**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) );
  16839. var source = gl.getShaderSource(shader);
  16840. return 'THREE.WebGLShader: gl.getShaderInfoLog() ' + type + '\n' + log + addLineNumbers(source);
  16841. }
  16842. function getTexelDecodingFunction(functionName, encoding) {
  16843. var components = getEncodingComponents(encoding);
  16844. return 'vec4 ' + functionName + '( vec4 value ) { return ' + components[0] + 'ToLinear' + components[1] + '; }';
  16845. }
  16846. function getTexelEncodingFunction(functionName, encoding) {
  16847. var components = getEncodingComponents(encoding);
  16848. return 'vec4 ' + functionName + '( vec4 value ) { return LinearTo' + components[0] + components[1] + '; }';
  16849. }
  16850. function getToneMappingFunction(functionName, toneMapping) {
  16851. var toneMappingName;
  16852. switch (toneMapping) {
  16853. case LinearToneMapping:
  16854. toneMappingName = 'Linear';
  16855. break;
  16856. case ReinhardToneMapping:
  16857. toneMappingName = 'Reinhard';
  16858. break;
  16859. case CineonToneMapping:
  16860. toneMappingName = 'OptimizedCineon';
  16861. break;
  16862. case ACESFilmicToneMapping:
  16863. toneMappingName = 'ACESFilmic';
  16864. break;
  16865. case CustomToneMapping:
  16866. toneMappingName = 'Custom';
  16867. break;
  16868. default:
  16869. console.warn('THREE.WebGLProgram: Unsupported toneMapping:', toneMapping);
  16870. toneMappingName = 'Linear';
  16871. }
  16872. return 'vec3 ' + functionName + '( vec3 color ) { return ' + toneMappingName + 'ToneMapping( color ); }';
  16873. }
  16874. function generateExtensions(parameters) {
  16875. var chunks = [parameters.extensionDerivatives || parameters.envMapCubeUV || parameters.bumpMap || parameters.tangentSpaceNormalMap || parameters.clearcoatNormalMap || parameters.flatShading || parameters.shaderID === 'physical' ? '#extension GL_OES_standard_derivatives : enable' : '', (parameters.extensionFragDepth || parameters.logarithmicDepthBuffer) && parameters.rendererExtensionFragDepth ? '#extension GL_EXT_frag_depth : enable' : '', parameters.extensionDrawBuffers && parameters.rendererExtensionDrawBuffers ? '#extension GL_EXT_draw_buffers : require' : '', (parameters.extensionShaderTextureLOD || parameters.envMap) && parameters.rendererExtensionShaderTextureLod ? '#extension GL_EXT_shader_texture_lod : enable' : ''];
  16876. return chunks.filter(filterEmptyLine).join('\n');
  16877. }
  16878. function generateDefines(defines) {
  16879. var chunks = [];
  16880. for (var name in defines) {
  16881. var value = defines[name];
  16882. if (value === false) continue;
  16883. chunks.push('#define ' + name + ' ' + value);
  16884. }
  16885. return chunks.join('\n');
  16886. }
  16887. function fetchAttributeLocations(gl, program) {
  16888. var attributes = {};
  16889. var n = gl.getProgramParameter(program, 35721);
  16890. for (var i = 0; i < n; i++) {
  16891. var info = gl.getActiveAttrib(program, i);
  16892. var name = info.name; // console.log( 'THREE.WebGLProgram: ACTIVE VERTEX ATTRIBUTE:', name, i );
  16893. attributes[name] = gl.getAttribLocation(program, name);
  16894. }
  16895. return attributes;
  16896. }
  16897. function filterEmptyLine(string) {
  16898. return string !== '';
  16899. }
  16900. function replaceLightNums(string, parameters) {
  16901. return string.replace(/NUM_DIR_LIGHTS/g, parameters.numDirLights).replace(/NUM_SPOT_LIGHTS/g, parameters.numSpotLights).replace(/NUM_RECT_AREA_LIGHTS/g, parameters.numRectAreaLights).replace(/NUM_POINT_LIGHTS/g, parameters.numPointLights).replace(/NUM_HEMI_LIGHTS/g, parameters.numHemiLights).replace(/NUM_DIR_LIGHT_SHADOWS/g, parameters.numDirLightShadows).replace(/NUM_SPOT_LIGHT_SHADOWS/g, parameters.numSpotLightShadows).replace(/NUM_POINT_LIGHT_SHADOWS/g, parameters.numPointLightShadows);
  16902. }
  16903. function replaceClippingPlaneNums(string, parameters) {
  16904. return string.replace(/NUM_CLIPPING_PLANES/g, parameters.numClippingPlanes).replace(/UNION_CLIPPING_PLANES/g, parameters.numClippingPlanes - parameters.numClipIntersection);
  16905. } // Resolve Includes
  16906. var includePattern = /^[ \t]*#include +<([\w\d./]+)>/gm;
  16907. function resolveIncludes(string) {
  16908. return string.replace(includePattern, includeReplacer);
  16909. }
  16910. function includeReplacer(match, include) {
  16911. var string = ShaderChunk[include];
  16912. if (string === undefined) {
  16913. throw new Error('Can not resolve #include <' + include + '>');
  16914. }
  16915. return resolveIncludes(string);
  16916. } // Unroll Loops
  16917. var deprecatedUnrollLoopPattern = /#pragma unroll_loop[\s]+?for \( int i \= (\d+)\; i < (\d+)\; i \+\+ \) \{([\s\S]+?)(?=\})\}/g;
  16918. var unrollLoopPattern = /#pragma unroll_loop_start\s+for\s*\(\s*int\s+i\s*=\s*(\d+)\s*;\s*i\s*<\s*(\d+)\s*;\s*i\s*\+\+\s*\)\s*{([\s\S]+?)}\s+#pragma unroll_loop_end/g;
  16919. function unrollLoops(string) {
  16920. return string.replace(unrollLoopPattern, loopReplacer).replace(deprecatedUnrollLoopPattern, deprecatedLoopReplacer);
  16921. }
  16922. function deprecatedLoopReplacer(match, start, end, snippet) {
  16923. console.warn('WebGLProgram: #pragma unroll_loop shader syntax is deprecated. Please use #pragma unroll_loop_start syntax instead.');
  16924. return loopReplacer(match, start, end, snippet);
  16925. }
  16926. function loopReplacer(match, start, end, snippet) {
  16927. var string = '';
  16928. for (var i = parseInt(start); i < parseInt(end); i++) {
  16929. string += snippet.replace(/\[\s*i\s*\]/g, '[ ' + i + ' ]').replace(/UNROLLED_LOOP_INDEX/g, i);
  16930. }
  16931. return string;
  16932. } //
  16933. function generatePrecision(parameters) {
  16934. var precisionstring = 'precision ' + parameters.precision + ' float;\nprecision ' + parameters.precision + ' int;';
  16935. if (parameters.precision === 'highp') {
  16936. precisionstring += '\n#define HIGH_PRECISION';
  16937. } else if (parameters.precision === 'mediump') {
  16938. precisionstring += '\n#define MEDIUM_PRECISION';
  16939. } else if (parameters.precision === 'lowp') {
  16940. precisionstring += '\n#define LOW_PRECISION';
  16941. }
  16942. return precisionstring;
  16943. }
  16944. function generateShadowMapTypeDefine(parameters) {
  16945. var shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC';
  16946. if (parameters.shadowMapType === PCFShadowMap) {
  16947. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF';
  16948. } else if (parameters.shadowMapType === PCFSoftShadowMap) {
  16949. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT';
  16950. } else if (parameters.shadowMapType === VSMShadowMap) {
  16951. shadowMapTypeDefine = 'SHADOWMAP_TYPE_VSM';
  16952. }
  16953. return shadowMapTypeDefine;
  16954. }
  16955. function generateEnvMapTypeDefine(parameters) {
  16956. var envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  16957. if (parameters.envMap) {
  16958. switch (parameters.envMapMode) {
  16959. case CubeReflectionMapping:
  16960. case CubeRefractionMapping:
  16961. envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  16962. break;
  16963. case CubeUVReflectionMapping:
  16964. case CubeUVRefractionMapping:
  16965. envMapTypeDefine = 'ENVMAP_TYPE_CUBE_UV';
  16966. break;
  16967. }
  16968. }
  16969. return envMapTypeDefine;
  16970. }
  16971. function generateEnvMapModeDefine(parameters) {
  16972. var envMapModeDefine = 'ENVMAP_MODE_REFLECTION';
  16973. if (parameters.envMap) {
  16974. switch (parameters.envMapMode) {
  16975. case CubeRefractionMapping:
  16976. case CubeUVRefractionMapping:
  16977. envMapModeDefine = 'ENVMAP_MODE_REFRACTION';
  16978. break;
  16979. }
  16980. }
  16981. return envMapModeDefine;
  16982. }
  16983. function generateEnvMapBlendingDefine(parameters) {
  16984. var envMapBlendingDefine = 'ENVMAP_BLENDING_NONE';
  16985. if (parameters.envMap) {
  16986. switch (parameters.combine) {
  16987. case MultiplyOperation:
  16988. envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  16989. break;
  16990. case MixOperation:
  16991. envMapBlendingDefine = 'ENVMAP_BLENDING_MIX';
  16992. break;
  16993. case AddOperation:
  16994. envMapBlendingDefine = 'ENVMAP_BLENDING_ADD';
  16995. break;
  16996. }
  16997. }
  16998. return envMapBlendingDefine;
  16999. }
  17000. function WebGLProgram(renderer, cacheKey, parameters, bindingStates) {
  17001. var gl = renderer.getContext();
  17002. var defines = parameters.defines;
  17003. var vertexShader = parameters.vertexShader;
  17004. var fragmentShader = parameters.fragmentShader;
  17005. var shadowMapTypeDefine = generateShadowMapTypeDefine(parameters);
  17006. var envMapTypeDefine = generateEnvMapTypeDefine(parameters);
  17007. var envMapModeDefine = generateEnvMapModeDefine(parameters);
  17008. var envMapBlendingDefine = generateEnvMapBlendingDefine(parameters);
  17009. var gammaFactorDefine = renderer.gammaFactor > 0 ? renderer.gammaFactor : 1.0;
  17010. var customExtensions = parameters.isWebGL2 ? '' : generateExtensions(parameters);
  17011. var customDefines = generateDefines(defines);
  17012. var program = gl.createProgram();
  17013. var prefixVertex, prefixFragment;
  17014. var versionString = parameters.glslVersion ? '#version ' + parameters.glslVersion + '\n' : '';
  17015. if (parameters.isRawShaderMaterial) {
  17016. prefixVertex = [customDefines].filter(filterEmptyLine).join('\n');
  17017. if (prefixVertex.length > 0) {
  17018. prefixVertex += '\n';
  17019. }
  17020. prefixFragment = [customExtensions, customDefines].filter(filterEmptyLine).join('\n');
  17021. if (prefixFragment.length > 0) {
  17022. prefixFragment += '\n';
  17023. }
  17024. } else {
  17025. prefixVertex = [generatePrecision(parameters), '#define SHADER_NAME ' + parameters.shaderName, customDefines, parameters.instancing ? '#define USE_INSTANCING' : '', parameters.instancingColor ? '#define USE_INSTANCING_COLOR' : '', parameters.supportsVertexTextures ? '#define VERTEX_TEXTURES' : '', '#define GAMMA_FACTOR ' + gammaFactorDefine, '#define MAX_BONES ' + parameters.maxBones, parameters.useFog && parameters.fog ? '#define USE_FOG' : '', parameters.useFog && parameters.fogExp2 ? '#define FOG_EXP2' : '', parameters.map ? '#define USE_MAP' : '', parameters.envMap ? '#define USE_ENVMAP' : '', parameters.envMap ? '#define ' + envMapModeDefine : '', parameters.lightMap ? '#define USE_LIGHTMAP' : '', parameters.aoMap ? '#define USE_AOMAP' : '', parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '', parameters.bumpMap ? '#define USE_BUMPMAP' : '', parameters.normalMap ? '#define USE_NORMALMAP' : '', parameters.normalMap && parameters.objectSpaceNormalMap ? '#define OBJECTSPACE_NORMALMAP' : '', parameters.normalMap && parameters.tangentSpaceNormalMap ? '#define TANGENTSPACE_NORMALMAP' : '', parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '', parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '', parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '', parameters.displacementMap && parameters.supportsVertexTextures ? '#define USE_DISPLACEMENTMAP' : '', parameters.specularMap ? '#define USE_SPECULARMAP' : '', parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '', parameters.metalnessMap ? '#define USE_METALNESSMAP' : '', parameters.alphaMap ? '#define USE_ALPHAMAP' : '', parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '', parameters.vertexTangents ? '#define USE_TANGENT' : '', parameters.vertexColors ? '#define USE_COLOR' : '', parameters.vertexUvs ? '#define USE_UV' : '', parameters.uvsVertexOnly ? '#define UVS_VERTEX_ONLY' : '', parameters.flatShading ? '#define FLAT_SHADED' : '', parameters.skinning ? '#define USE_SKINNING' : '', parameters.useVertexTexture ? '#define BONE_TEXTURE' : '', parameters.morphTargets ? '#define USE_MORPHTARGETS' : '', parameters.morphNormals && parameters.flatShading === false ? '#define USE_MORPHNORMALS' : '', parameters.doubleSided ? '#define DOUBLE_SIDED' : '', parameters.flipSided ? '#define FLIP_SIDED' : '', parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '', parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '', parameters.sizeAttenuation ? '#define USE_SIZEATTENUATION' : '', parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '', parameters.logarithmicDepthBuffer && parameters.rendererExtensionFragDepth ? '#define USE_LOGDEPTHBUF_EXT' : '', 'uniform mat4 modelMatrix;', 'uniform mat4 modelViewMatrix;', 'uniform mat4 projectionMatrix;', 'uniform mat4 viewMatrix;', 'uniform mat3 normalMatrix;', 'uniform vec3 cameraPosition;', 'uniform bool isOrthographic;', '#ifdef USE_INSTANCING', ' attribute mat4 instanceMatrix;', '#endif', '#ifdef USE_INSTANCING_COLOR', ' attribute vec3 instanceColor;', '#endif', 'attribute vec3 position;', 'attribute vec3 normal;', 'attribute vec2 uv;', '#ifdef USE_TANGENT', ' attribute vec4 tangent;', '#endif', '#ifdef USE_COLOR', ' attribute vec3 color;', '#endif', '#ifdef USE_MORPHTARGETS', ' attribute vec3 morphTarget0;', ' attribute vec3 morphTarget1;', ' attribute vec3 morphTarget2;', ' attribute vec3 morphTarget3;', ' #ifdef USE_MORPHNORMALS', ' attribute vec3 morphNormal0;', ' attribute vec3 morphNormal1;', ' attribute vec3 morphNormal2;', ' attribute vec3 morphNormal3;', ' #else', ' attribute vec3 morphTarget4;', ' attribute vec3 morphTarget5;', ' attribute vec3 morphTarget6;', ' attribute vec3 morphTarget7;', ' #endif', '#endif', '#ifdef USE_SKINNING', ' attribute vec4 skinIndex;', ' attribute vec4 skinWeight;', '#endif', '\n'].filter(filterEmptyLine).join('\n');
  17026. prefixFragment = [customExtensions, generatePrecision(parameters), '#define SHADER_NAME ' + parameters.shaderName, customDefines, parameters.alphaTest ? '#define ALPHATEST ' + parameters.alphaTest + (parameters.alphaTest % 1 ? '' : '.0') : '', // add '.0' if integer
  17027. '#define GAMMA_FACTOR ' + gammaFactorDefine, parameters.useFog && parameters.fog ? '#define USE_FOG' : '', parameters.useFog && parameters.fogExp2 ? '#define FOG_EXP2' : '', parameters.map ? '#define USE_MAP' : '', parameters.matcap ? '#define USE_MATCAP' : '', parameters.envMap ? '#define USE_ENVMAP' : '', parameters.envMap ? '#define ' + envMapTypeDefine : '', parameters.envMap ? '#define ' + envMapModeDefine : '', parameters.envMap ? '#define ' + envMapBlendingDefine : '', parameters.lightMap ? '#define USE_LIGHTMAP' : '', parameters.aoMap ? '#define USE_AOMAP' : '', parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '', parameters.bumpMap ? '#define USE_BUMPMAP' : '', parameters.normalMap ? '#define USE_NORMALMAP' : '', parameters.normalMap && parameters.objectSpaceNormalMap ? '#define OBJECTSPACE_NORMALMAP' : '', parameters.normalMap && parameters.tangentSpaceNormalMap ? '#define TANGENTSPACE_NORMALMAP' : '', parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '', parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '', parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '', parameters.specularMap ? '#define USE_SPECULARMAP' : '', parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '', parameters.metalnessMap ? '#define USE_METALNESSMAP' : '', parameters.alphaMap ? '#define USE_ALPHAMAP' : '', parameters.sheen ? '#define USE_SHEEN' : '', parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '', parameters.vertexTangents ? '#define USE_TANGENT' : '', parameters.vertexColors || parameters.instancingColor ? '#define USE_COLOR' : '', parameters.vertexUvs ? '#define USE_UV' : '', parameters.uvsVertexOnly ? '#define UVS_VERTEX_ONLY' : '', parameters.gradientMap ? '#define USE_GRADIENTMAP' : '', parameters.flatShading ? '#define FLAT_SHADED' : '', parameters.doubleSided ? '#define DOUBLE_SIDED' : '', parameters.flipSided ? '#define FLIP_SIDED' : '', parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '', parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '', parameters.premultipliedAlpha ? '#define PREMULTIPLIED_ALPHA' : '', parameters.physicallyCorrectLights ? '#define PHYSICALLY_CORRECT_LIGHTS' : '', parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '', parameters.logarithmicDepthBuffer && parameters.rendererExtensionFragDepth ? '#define USE_LOGDEPTHBUF_EXT' : '', (parameters.extensionShaderTextureLOD || parameters.envMap) && parameters.rendererExtensionShaderTextureLod ? '#define TEXTURE_LOD_EXT' : '', 'uniform mat4 viewMatrix;', 'uniform vec3 cameraPosition;', 'uniform bool isOrthographic;', parameters.toneMapping !== NoToneMapping ? '#define TONE_MAPPING' : '', parameters.toneMapping !== NoToneMapping ? ShaderChunk['tonemapping_pars_fragment'] : '', // this code is required here because it is used by the toneMapping() function defined below
  17028. parameters.toneMapping !== NoToneMapping ? getToneMappingFunction('toneMapping', parameters.toneMapping) : '', parameters.dithering ? '#define DITHERING' : '', ShaderChunk['encodings_pars_fragment'], // this code is required here because it is used by the various encoding/decoding function defined below
  17029. parameters.map ? getTexelDecodingFunction('mapTexelToLinear', parameters.mapEncoding) : '', parameters.matcap ? getTexelDecodingFunction('matcapTexelToLinear', parameters.matcapEncoding) : '', parameters.envMap ? getTexelDecodingFunction('envMapTexelToLinear', parameters.envMapEncoding) : '', parameters.emissiveMap ? getTexelDecodingFunction('emissiveMapTexelToLinear', parameters.emissiveMapEncoding) : '', parameters.lightMap ? getTexelDecodingFunction('lightMapTexelToLinear', parameters.lightMapEncoding) : '', getTexelEncodingFunction('linearToOutputTexel', parameters.outputEncoding), parameters.depthPacking ? '#define DEPTH_PACKING ' + parameters.depthPacking : '', '\n'].filter(filterEmptyLine).join('\n');
  17030. }
  17031. vertexShader = resolveIncludes(vertexShader);
  17032. vertexShader = replaceLightNums(vertexShader, parameters);
  17033. vertexShader = replaceClippingPlaneNums(vertexShader, parameters);
  17034. fragmentShader = resolveIncludes(fragmentShader);
  17035. fragmentShader = replaceLightNums(fragmentShader, parameters);
  17036. fragmentShader = replaceClippingPlaneNums(fragmentShader, parameters);
  17037. vertexShader = unrollLoops(vertexShader);
  17038. fragmentShader = unrollLoops(fragmentShader);
  17039. if (parameters.isWebGL2 && parameters.isRawShaderMaterial !== true) {
  17040. // GLSL 3.0 conversion for built-in materials and ShaderMaterial
  17041. versionString = '#version 300 es\n';
  17042. prefixVertex = ['#define attribute in', '#define varying out', '#define texture2D texture'].join('\n') + '\n' + prefixVertex;
  17043. prefixFragment = ['#define varying in', parameters.glslVersion === GLSL3 ? '' : 'out highp vec4 pc_fragColor;', parameters.glslVersion === GLSL3 ? '' : '#define gl_FragColor pc_fragColor', '#define gl_FragDepthEXT gl_FragDepth', '#define texture2D texture', '#define textureCube texture', '#define texture2DProj textureProj', '#define texture2DLodEXT textureLod', '#define texture2DProjLodEXT textureProjLod', '#define textureCubeLodEXT textureLod', '#define texture2DGradEXT textureGrad', '#define texture2DProjGradEXT textureProjGrad', '#define textureCubeGradEXT textureGrad'].join('\n') + '\n' + prefixFragment;
  17044. }
  17045. var vertexGlsl = versionString + prefixVertex + vertexShader;
  17046. var fragmentGlsl = versionString + prefixFragment + fragmentShader; // console.log( '*VERTEX*', vertexGlsl );
  17047. // console.log( '*FRAGMENT*', fragmentGlsl );
  17048. var glVertexShader = WebGLShader(gl, 35633, vertexGlsl);
  17049. var glFragmentShader = WebGLShader(gl, 35632, fragmentGlsl);
  17050. gl.attachShader(program, glVertexShader);
  17051. gl.attachShader(program, glFragmentShader); // Force a particular attribute to index 0.
  17052. if (parameters.index0AttributeName !== undefined) {
  17053. gl.bindAttribLocation(program, 0, parameters.index0AttributeName);
  17054. } else if (parameters.morphTargets === true) {
  17055. // programs with morphTargets displace position out of attribute 0
  17056. gl.bindAttribLocation(program, 0, 'position');
  17057. }
  17058. gl.linkProgram(program); // check for link errors
  17059. if (renderer.debug.checkShaderErrors) {
  17060. var programLog = gl.getProgramInfoLog(program).trim();
  17061. var vertexLog = gl.getShaderInfoLog(glVertexShader).trim();
  17062. var fragmentLog = gl.getShaderInfoLog(glFragmentShader).trim();
  17063. var runnable = true;
  17064. var haveDiagnostics = true;
  17065. if (gl.getProgramParameter(program, 35714) === false) {
  17066. runnable = false;
  17067. var vertexErrors = getShaderErrors(gl, glVertexShader, 'vertex');
  17068. var fragmentErrors = getShaderErrors(gl, glFragmentShader, 'fragment');
  17069. console.error('THREE.WebGLProgram: shader error: ', gl.getError(), '35715', gl.getProgramParameter(program, 35715), 'gl.getProgramInfoLog', programLog, vertexErrors, fragmentErrors);
  17070. } else if (programLog !== '') {
  17071. console.warn('THREE.WebGLProgram: gl.getProgramInfoLog()', programLog);
  17072. } else if (vertexLog === '' || fragmentLog === '') {
  17073. haveDiagnostics = false;
  17074. }
  17075. if (haveDiagnostics) {
  17076. this.diagnostics = {
  17077. runnable: runnable,
  17078. programLog: programLog,
  17079. vertexShader: {
  17080. log: vertexLog,
  17081. prefix: prefixVertex
  17082. },
  17083. fragmentShader: {
  17084. log: fragmentLog,
  17085. prefix: prefixFragment
  17086. }
  17087. };
  17088. }
  17089. } // Clean up
  17090. // Crashes in iOS9 and iOS10. #18402
  17091. // gl.detachShader( program, glVertexShader );
  17092. // gl.detachShader( program, glFragmentShader );
  17093. gl.deleteShader(glVertexShader);
  17094. gl.deleteShader(glFragmentShader); // set up caching for uniform locations
  17095. var cachedUniforms;
  17096. this.getUniforms = function () {
  17097. if (cachedUniforms === undefined) {
  17098. cachedUniforms = new WebGLUniforms(gl, program);
  17099. }
  17100. return cachedUniforms;
  17101. }; // set up caching for attribute locations
  17102. var cachedAttributes;
  17103. this.getAttributes = function () {
  17104. if (cachedAttributes === undefined) {
  17105. cachedAttributes = fetchAttributeLocations(gl, program);
  17106. }
  17107. return cachedAttributes;
  17108. }; // free resource
  17109. this.destroy = function () {
  17110. bindingStates.releaseStatesOfProgram(this);
  17111. gl.deleteProgram(program);
  17112. this.program = undefined;
  17113. }; //
  17114. this.name = parameters.shaderName;
  17115. this.id = programIdCount++;
  17116. this.cacheKey = cacheKey;
  17117. this.usedTimes = 1;
  17118. this.program = program;
  17119. this.vertexShader = glVertexShader;
  17120. this.fragmentShader = glFragmentShader;
  17121. return this;
  17122. }
  17123. function WebGLPrograms(renderer, cubemaps, extensions, capabilities, bindingStates, clipping) {
  17124. var programs = [];
  17125. var isWebGL2 = capabilities.isWebGL2;
  17126. var logarithmicDepthBuffer = capabilities.logarithmicDepthBuffer;
  17127. var floatVertexTextures = capabilities.floatVertexTextures;
  17128. var maxVertexUniforms = capabilities.maxVertexUniforms;
  17129. var vertexTextures = capabilities.vertexTextures;
  17130. var precision = capabilities.precision;
  17131. var shaderIDs = {
  17132. MeshDepthMaterial: 'depth',
  17133. MeshDistanceMaterial: 'distanceRGBA',
  17134. MeshNormalMaterial: 'normal',
  17135. MeshBasicMaterial: 'basic',
  17136. MeshLambertMaterial: 'lambert',
  17137. MeshPhongMaterial: 'phong',
  17138. MeshToonMaterial: 'toon',
  17139. MeshStandardMaterial: 'physical',
  17140. MeshPhysicalMaterial: 'physical',
  17141. MeshMatcapMaterial: 'matcap',
  17142. LineBasicMaterial: 'basic',
  17143. LineDashedMaterial: 'dashed',
  17144. PointsMaterial: 'points',
  17145. ShadowMaterial: 'shadow',
  17146. SpriteMaterial: 'sprite'
  17147. };
  17148. var parameterNames = ['precision', 'isWebGL2', 'supportsVertexTextures', 'outputEncoding', 'instancing', 'instancingColor', 'map', 'mapEncoding', 'matcap', 'matcapEncoding', 'envMap', 'envMapMode', 'envMapEncoding', 'envMapCubeUV', 'lightMap', 'lightMapEncoding', 'aoMap', 'emissiveMap', 'emissiveMapEncoding', 'bumpMap', 'normalMap', 'objectSpaceNormalMap', 'tangentSpaceNormalMap', 'clearcoatMap', 'clearcoatRoughnessMap', 'clearcoatNormalMap', 'displacementMap', 'specularMap', 'roughnessMap', 'metalnessMap', 'gradientMap', 'alphaMap', 'combine', 'vertexColors', 'vertexTangents', 'vertexUvs', 'uvsVertexOnly', 'fog', 'useFog', 'fogExp2', 'flatShading', 'sizeAttenuation', 'logarithmicDepthBuffer', 'skinning', 'maxBones', 'useVertexTexture', 'morphTargets', 'morphNormals', 'maxMorphTargets', 'maxMorphNormals', 'premultipliedAlpha', 'numDirLights', 'numPointLights', 'numSpotLights', 'numHemiLights', 'numRectAreaLights', 'numDirLightShadows', 'numPointLightShadows', 'numSpotLightShadows', 'shadowMapEnabled', 'shadowMapType', 'toneMapping', 'physicallyCorrectLights', 'alphaTest', 'doubleSided', 'flipSided', 'numClippingPlanes', 'numClipIntersection', 'depthPacking', 'dithering', 'sheen', 'transmissionMap'];
  17149. function getMaxBones(object) {
  17150. var skeleton = object.skeleton;
  17151. var bones = skeleton.bones;
  17152. if (floatVertexTextures) {
  17153. return 1024;
  17154. } else {
  17155. // default for when object is not specified
  17156. // ( for example when prebuilding shader to be used with multiple objects )
  17157. //
  17158. // - leave some extra space for other uniforms
  17159. // - limit here is ANGLE's 254 max uniform vectors
  17160. // (up to 54 should be safe)
  17161. var nVertexUniforms = maxVertexUniforms;
  17162. var nVertexMatrices = Math.floor((nVertexUniforms - 20) / 4);
  17163. var maxBones = Math.min(nVertexMatrices, bones.length);
  17164. if (maxBones < bones.length) {
  17165. console.warn('THREE.WebGLRenderer: Skeleton has ' + bones.length + ' bones. This GPU supports ' + maxBones + '.');
  17166. return 0;
  17167. }
  17168. return maxBones;
  17169. }
  17170. }
  17171. function getTextureEncodingFromMap(map) {
  17172. var encoding;
  17173. if (map && map.isTexture) {
  17174. encoding = map.encoding;
  17175. } else if (map && map.isWebGLRenderTarget) {
  17176. console.warn('THREE.WebGLPrograms.getTextureEncodingFromMap: don\'t use render targets as textures. Use their .texture property instead.');
  17177. encoding = map.texture.encoding;
  17178. } else {
  17179. encoding = LinearEncoding;
  17180. }
  17181. return encoding;
  17182. }
  17183. function getParameters(material, lights, shadows, scene, object) {
  17184. var fog = scene.fog;
  17185. var environment = material.isMeshStandardMaterial ? scene.environment : null;
  17186. var envMap = cubemaps.get(material.envMap || environment);
  17187. var shaderID = shaderIDs[material.type]; // heuristics to create shader parameters according to lights in the scene
  17188. // (not to blow over maxLights budget)
  17189. var maxBones = object.isSkinnedMesh ? getMaxBones(object) : 0;
  17190. if (material.precision !== null) {
  17191. precision = capabilities.getMaxPrecision(material.precision);
  17192. if (precision !== material.precision) {
  17193. console.warn('THREE.WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.');
  17194. }
  17195. }
  17196. var vertexShader, fragmentShader;
  17197. if (shaderID) {
  17198. var shader = ShaderLib[shaderID];
  17199. vertexShader = shader.vertexShader;
  17200. fragmentShader = shader.fragmentShader;
  17201. } else {
  17202. vertexShader = material.vertexShader;
  17203. fragmentShader = material.fragmentShader;
  17204. }
  17205. var currentRenderTarget = renderer.getRenderTarget();
  17206. var parameters = {
  17207. isWebGL2: isWebGL2,
  17208. shaderID: shaderID,
  17209. shaderName: material.type,
  17210. vertexShader: vertexShader,
  17211. fragmentShader: fragmentShader,
  17212. defines: material.defines,
  17213. isRawShaderMaterial: material.isRawShaderMaterial === true,
  17214. glslVersion: material.glslVersion,
  17215. precision: precision,
  17216. instancing: object.isInstancedMesh === true,
  17217. instancingColor: object.isInstancedMesh === true && object.instanceColor !== null,
  17218. supportsVertexTextures: vertexTextures,
  17219. outputEncoding: currentRenderTarget !== null ? getTextureEncodingFromMap(currentRenderTarget.texture) : renderer.outputEncoding,
  17220. map: !!material.map,
  17221. mapEncoding: getTextureEncodingFromMap(material.map),
  17222. matcap: !!material.matcap,
  17223. matcapEncoding: getTextureEncodingFromMap(material.matcap),
  17224. envMap: !!envMap,
  17225. envMapMode: envMap && envMap.mapping,
  17226. envMapEncoding: getTextureEncodingFromMap(envMap),
  17227. envMapCubeUV: !!envMap && (envMap.mapping === CubeUVReflectionMapping || envMap.mapping === CubeUVRefractionMapping),
  17228. lightMap: !!material.lightMap,
  17229. lightMapEncoding: getTextureEncodingFromMap(material.lightMap),
  17230. aoMap: !!material.aoMap,
  17231. emissiveMap: !!material.emissiveMap,
  17232. emissiveMapEncoding: getTextureEncodingFromMap(material.emissiveMap),
  17233. bumpMap: !!material.bumpMap,
  17234. normalMap: !!material.normalMap,
  17235. objectSpaceNormalMap: material.normalMapType === ObjectSpaceNormalMap,
  17236. tangentSpaceNormalMap: material.normalMapType === TangentSpaceNormalMap,
  17237. clearcoatMap: !!material.clearcoatMap,
  17238. clearcoatRoughnessMap: !!material.clearcoatRoughnessMap,
  17239. clearcoatNormalMap: !!material.clearcoatNormalMap,
  17240. displacementMap: !!material.displacementMap,
  17241. roughnessMap: !!material.roughnessMap,
  17242. metalnessMap: !!material.metalnessMap,
  17243. specularMap: !!material.specularMap,
  17244. alphaMap: !!material.alphaMap,
  17245. gradientMap: !!material.gradientMap,
  17246. sheen: !!material.sheen,
  17247. transmissionMap: !!material.transmissionMap,
  17248. combine: material.combine,
  17249. vertexTangents: material.normalMap && material.vertexTangents,
  17250. vertexColors: material.vertexColors,
  17251. vertexUvs: !!material.map || !!material.bumpMap || !!material.normalMap || !!material.specularMap || !!material.alphaMap || !!material.emissiveMap || !!material.roughnessMap || !!material.metalnessMap || !!material.clearcoatMap || !!material.clearcoatRoughnessMap || !!material.clearcoatNormalMap || !!material.displacementMap || !!material.transmissionMap,
  17252. uvsVertexOnly: !(!!material.map || !!material.bumpMap || !!material.normalMap || !!material.specularMap || !!material.alphaMap || !!material.emissiveMap || !!material.roughnessMap || !!material.metalnessMap || !!material.clearcoatNormalMap || !!material.transmissionMap) && !!material.displacementMap,
  17253. fog: !!fog,
  17254. useFog: material.fog,
  17255. fogExp2: fog && fog.isFogExp2,
  17256. flatShading: material.flatShading,
  17257. sizeAttenuation: material.sizeAttenuation,
  17258. logarithmicDepthBuffer: logarithmicDepthBuffer,
  17259. skinning: material.skinning && maxBones > 0,
  17260. maxBones: maxBones,
  17261. useVertexTexture: floatVertexTextures,
  17262. morphTargets: material.morphTargets,
  17263. morphNormals: material.morphNormals,
  17264. maxMorphTargets: renderer.maxMorphTargets,
  17265. maxMorphNormals: renderer.maxMorphNormals,
  17266. numDirLights: lights.directional.length,
  17267. numPointLights: lights.point.length,
  17268. numSpotLights: lights.spot.length,
  17269. numRectAreaLights: lights.rectArea.length,
  17270. numHemiLights: lights.hemi.length,
  17271. numDirLightShadows: lights.directionalShadowMap.length,
  17272. numPointLightShadows: lights.pointShadowMap.length,
  17273. numSpotLightShadows: lights.spotShadowMap.length,
  17274. numClippingPlanes: clipping.numPlanes,
  17275. numClipIntersection: clipping.numIntersection,
  17276. dithering: material.dithering,
  17277. shadowMapEnabled: renderer.shadowMap.enabled && shadows.length > 0,
  17278. shadowMapType: renderer.shadowMap.type,
  17279. toneMapping: material.toneMapped ? renderer.toneMapping : NoToneMapping,
  17280. physicallyCorrectLights: renderer.physicallyCorrectLights,
  17281. premultipliedAlpha: material.premultipliedAlpha,
  17282. alphaTest: material.alphaTest,
  17283. doubleSided: material.side === DoubleSide,
  17284. flipSided: material.side === BackSide,
  17285. depthPacking: material.depthPacking !== undefined ? material.depthPacking : false,
  17286. index0AttributeName: material.index0AttributeName,
  17287. extensionDerivatives: material.extensions && material.extensions.derivatives,
  17288. extensionFragDepth: material.extensions && material.extensions.fragDepth,
  17289. extensionDrawBuffers: material.extensions && material.extensions.drawBuffers,
  17290. extensionShaderTextureLOD: material.extensions && material.extensions.shaderTextureLOD,
  17291. rendererExtensionFragDepth: isWebGL2 || extensions.has('EXT_frag_depth'),
  17292. rendererExtensionDrawBuffers: isWebGL2 || extensions.has('WEBGL_draw_buffers'),
  17293. rendererExtensionShaderTextureLod: isWebGL2 || extensions.has('EXT_shader_texture_lod'),
  17294. customProgramCacheKey: material.customProgramCacheKey()
  17295. };
  17296. return parameters;
  17297. }
  17298. function getProgramCacheKey(parameters) {
  17299. var array = [];
  17300. if (parameters.shaderID) {
  17301. array.push(parameters.shaderID);
  17302. } else {
  17303. array.push(parameters.fragmentShader);
  17304. array.push(parameters.vertexShader);
  17305. }
  17306. if (parameters.defines !== undefined) {
  17307. for (var name in parameters.defines) {
  17308. array.push(name);
  17309. array.push(parameters.defines[name]);
  17310. }
  17311. }
  17312. if (parameters.isRawShaderMaterial === false) {
  17313. for (var i = 0; i < parameterNames.length; i++) {
  17314. array.push(parameters[parameterNames[i]]);
  17315. }
  17316. array.push(renderer.outputEncoding);
  17317. array.push(renderer.gammaFactor);
  17318. }
  17319. array.push(parameters.customProgramCacheKey);
  17320. return array.join();
  17321. }
  17322. function getUniforms(material) {
  17323. var shaderID = shaderIDs[material.type];
  17324. var uniforms;
  17325. if (shaderID) {
  17326. var shader = ShaderLib[shaderID];
  17327. uniforms = UniformsUtils.clone(shader.uniforms);
  17328. } else {
  17329. uniforms = material.uniforms;
  17330. }
  17331. return uniforms;
  17332. }
  17333. function acquireProgram(parameters, cacheKey) {
  17334. var program; // Check if code has been already compiled
  17335. for (var p = 0, pl = programs.length; p < pl; p++) {
  17336. var preexistingProgram = programs[p];
  17337. if (preexistingProgram.cacheKey === cacheKey) {
  17338. program = preexistingProgram;
  17339. ++program.usedTimes;
  17340. break;
  17341. }
  17342. }
  17343. if (program === undefined) {
  17344. program = new WebGLProgram(renderer, cacheKey, parameters, bindingStates);
  17345. programs.push(program);
  17346. }
  17347. return program;
  17348. }
  17349. function releaseProgram(program) {
  17350. if (--program.usedTimes === 0) {
  17351. // Remove from unordered set
  17352. var i = programs.indexOf(program);
  17353. programs[i] = programs[programs.length - 1];
  17354. programs.pop(); // Free WebGL resources
  17355. program.destroy();
  17356. }
  17357. }
  17358. return {
  17359. getParameters: getParameters,
  17360. getProgramCacheKey: getProgramCacheKey,
  17361. getUniforms: getUniforms,
  17362. acquireProgram: acquireProgram,
  17363. releaseProgram: releaseProgram,
  17364. // Exposed for resource monitoring & error feedback via renderer.info:
  17365. programs: programs
  17366. };
  17367. }
  17368. function WebGLProperties() {
  17369. var properties = new WeakMap();
  17370. function get(object) {
  17371. var map = properties.get(object);
  17372. if (map === undefined) {
  17373. map = {};
  17374. properties.set(object, map);
  17375. }
  17376. return map;
  17377. }
  17378. function remove(object) {
  17379. properties.delete(object);
  17380. }
  17381. function update(object, key, value) {
  17382. properties.get(object)[key] = value;
  17383. }
  17384. function dispose() {
  17385. properties = new WeakMap();
  17386. }
  17387. return {
  17388. get: get,
  17389. remove: remove,
  17390. update: update,
  17391. dispose: dispose
  17392. };
  17393. }
  17394. function painterSortStable(a, b) {
  17395. if (a.groupOrder !== b.groupOrder) {
  17396. return a.groupOrder - b.groupOrder;
  17397. } else if (a.renderOrder !== b.renderOrder) {
  17398. return a.renderOrder - b.renderOrder;
  17399. } else if (a.program !== b.program) {
  17400. return a.program.id - b.program.id;
  17401. } else if (a.material.id !== b.material.id) {
  17402. return a.material.id - b.material.id;
  17403. } else if (a.z !== b.z) {
  17404. return a.z - b.z;
  17405. } else {
  17406. return a.id - b.id;
  17407. }
  17408. }
  17409. function reversePainterSortStable(a, b) {
  17410. if (a.groupOrder !== b.groupOrder) {
  17411. return a.groupOrder - b.groupOrder;
  17412. } else if (a.renderOrder !== b.renderOrder) {
  17413. return a.renderOrder - b.renderOrder;
  17414. } else if (a.z !== b.z) {
  17415. return b.z - a.z;
  17416. } else {
  17417. return a.id - b.id;
  17418. }
  17419. }
  17420. function WebGLRenderList(properties) {
  17421. var renderItems = [];
  17422. var renderItemsIndex = 0;
  17423. var opaque = [];
  17424. var transparent = [];
  17425. var defaultProgram = {
  17426. id: -1
  17427. };
  17428. function init() {
  17429. renderItemsIndex = 0;
  17430. opaque.length = 0;
  17431. transparent.length = 0;
  17432. }
  17433. function getNextRenderItem(object, geometry, material, groupOrder, z, group) {
  17434. var renderItem = renderItems[renderItemsIndex];
  17435. var materialProperties = properties.get(material);
  17436. if (renderItem === undefined) {
  17437. renderItem = {
  17438. id: object.id,
  17439. object: object,
  17440. geometry: geometry,
  17441. material: material,
  17442. program: materialProperties.program || defaultProgram,
  17443. groupOrder: groupOrder,
  17444. renderOrder: object.renderOrder,
  17445. z: z,
  17446. group: group
  17447. };
  17448. renderItems[renderItemsIndex] = renderItem;
  17449. } else {
  17450. renderItem.id = object.id;
  17451. renderItem.object = object;
  17452. renderItem.geometry = geometry;
  17453. renderItem.material = material;
  17454. renderItem.program = materialProperties.program || defaultProgram;
  17455. renderItem.groupOrder = groupOrder;
  17456. renderItem.renderOrder = object.renderOrder;
  17457. renderItem.z = z;
  17458. renderItem.group = group;
  17459. }
  17460. renderItemsIndex++;
  17461. return renderItem;
  17462. }
  17463. function push(object, geometry, material, groupOrder, z, group) {
  17464. var renderItem = getNextRenderItem(object, geometry, material, groupOrder, z, group);
  17465. (material.transparent === true ? transparent : opaque).push(renderItem);
  17466. }
  17467. function unshift(object, geometry, material, groupOrder, z, group) {
  17468. var renderItem = getNextRenderItem(object, geometry, material, groupOrder, z, group);
  17469. (material.transparent === true ? transparent : opaque).unshift(renderItem);
  17470. }
  17471. function sort(customOpaqueSort, customTransparentSort) {
  17472. if (opaque.length > 1) opaque.sort(customOpaqueSort || painterSortStable);
  17473. if (transparent.length > 1) transparent.sort(customTransparentSort || reversePainterSortStable);
  17474. }
  17475. function finish() {
  17476. // Clear references from inactive renderItems in the list
  17477. for (var i = renderItemsIndex, il = renderItems.length; i < il; i++) {
  17478. var renderItem = renderItems[i];
  17479. if (renderItem.id === null) break;
  17480. renderItem.id = null;
  17481. renderItem.object = null;
  17482. renderItem.geometry = null;
  17483. renderItem.material = null;
  17484. renderItem.program = null;
  17485. renderItem.group = null;
  17486. }
  17487. }
  17488. return {
  17489. opaque: opaque,
  17490. transparent: transparent,
  17491. init: init,
  17492. push: push,
  17493. unshift: unshift,
  17494. finish: finish,
  17495. sort: sort
  17496. };
  17497. }
  17498. function WebGLRenderLists(properties) {
  17499. var lists = new WeakMap();
  17500. function get(scene, camera) {
  17501. var cameras = lists.get(scene);
  17502. var list;
  17503. if (cameras === undefined) {
  17504. list = new WebGLRenderList(properties);
  17505. lists.set(scene, new WeakMap());
  17506. lists.get(scene).set(camera, list);
  17507. } else {
  17508. list = cameras.get(camera);
  17509. if (list === undefined) {
  17510. list = new WebGLRenderList(properties);
  17511. cameras.set(camera, list);
  17512. }
  17513. }
  17514. return list;
  17515. }
  17516. function dispose() {
  17517. lists = new WeakMap();
  17518. }
  17519. return {
  17520. get: get,
  17521. dispose: dispose
  17522. };
  17523. }
  17524. function UniformsCache() {
  17525. var lights = {};
  17526. return {
  17527. get: function get(light) {
  17528. if (lights[light.id] !== undefined) {
  17529. return lights[light.id];
  17530. }
  17531. var uniforms;
  17532. switch (light.type) {
  17533. case 'DirectionalLight':
  17534. uniforms = {
  17535. direction: new Vector3(),
  17536. color: new Color()
  17537. };
  17538. break;
  17539. case 'SpotLight':
  17540. uniforms = {
  17541. position: new Vector3(),
  17542. direction: new Vector3(),
  17543. color: new Color(),
  17544. distance: 0,
  17545. coneCos: 0,
  17546. penumbraCos: 0,
  17547. decay: 0
  17548. };
  17549. break;
  17550. case 'PointLight':
  17551. uniforms = {
  17552. position: new Vector3(),
  17553. color: new Color(),
  17554. distance: 0,
  17555. decay: 0
  17556. };
  17557. break;
  17558. case 'HemisphereLight':
  17559. uniforms = {
  17560. direction: new Vector3(),
  17561. skyColor: new Color(),
  17562. groundColor: new Color()
  17563. };
  17564. break;
  17565. case 'RectAreaLight':
  17566. uniforms = {
  17567. color: new Color(),
  17568. position: new Vector3(),
  17569. halfWidth: new Vector3(),
  17570. halfHeight: new Vector3()
  17571. };
  17572. break;
  17573. }
  17574. lights[light.id] = uniforms;
  17575. return uniforms;
  17576. }
  17577. };
  17578. }
  17579. function ShadowUniformsCache() {
  17580. var lights = {};
  17581. return {
  17582. get: function get(light) {
  17583. if (lights[light.id] !== undefined) {
  17584. return lights[light.id];
  17585. }
  17586. var uniforms;
  17587. switch (light.type) {
  17588. case 'DirectionalLight':
  17589. uniforms = {
  17590. shadowBias: 0,
  17591. shadowNormalBias: 0,
  17592. shadowRadius: 1,
  17593. shadowMapSize: new Vector2()
  17594. };
  17595. break;
  17596. case 'SpotLight':
  17597. uniforms = {
  17598. shadowBias: 0,
  17599. shadowNormalBias: 0,
  17600. shadowRadius: 1,
  17601. shadowMapSize: new Vector2()
  17602. };
  17603. break;
  17604. case 'PointLight':
  17605. uniforms = {
  17606. shadowBias: 0,
  17607. shadowNormalBias: 0,
  17608. shadowRadius: 1,
  17609. shadowMapSize: new Vector2(),
  17610. shadowCameraNear: 1,
  17611. shadowCameraFar: 1000
  17612. };
  17613. break;
  17614. // TODO (abelnation): set RectAreaLight shadow uniforms
  17615. }
  17616. lights[light.id] = uniforms;
  17617. return uniforms;
  17618. }
  17619. };
  17620. }
  17621. var nextVersion = 0;
  17622. function shadowCastingLightsFirst(lightA, lightB) {
  17623. return (lightB.castShadow ? 1 : 0) - (lightA.castShadow ? 1 : 0);
  17624. }
  17625. function WebGLLights(extensions, capabilities) {
  17626. var cache = new UniformsCache();
  17627. var shadowCache = ShadowUniformsCache();
  17628. var state = {
  17629. version: 0,
  17630. hash: {
  17631. directionalLength: -1,
  17632. pointLength: -1,
  17633. spotLength: -1,
  17634. rectAreaLength: -1,
  17635. hemiLength: -1,
  17636. numDirectionalShadows: -1,
  17637. numPointShadows: -1,
  17638. numSpotShadows: -1
  17639. },
  17640. ambient: [0, 0, 0],
  17641. probe: [],
  17642. directional: [],
  17643. directionalShadow: [],
  17644. directionalShadowMap: [],
  17645. directionalShadowMatrix: [],
  17646. spot: [],
  17647. spotShadow: [],
  17648. spotShadowMap: [],
  17649. spotShadowMatrix: [],
  17650. rectArea: [],
  17651. rectAreaLTC1: null,
  17652. rectAreaLTC2: null,
  17653. point: [],
  17654. pointShadow: [],
  17655. pointShadowMap: [],
  17656. pointShadowMatrix: [],
  17657. hemi: []
  17658. };
  17659. for (var i = 0; i < 9; i++) {
  17660. state.probe.push(new Vector3());
  17661. }
  17662. var vector3 = new Vector3();
  17663. var matrix4 = new Matrix4();
  17664. var matrix42 = new Matrix4();
  17665. function setup(lights) {
  17666. var r = 0,
  17667. g = 0,
  17668. b = 0;
  17669. for (var _i = 0; _i < 9; _i++) {
  17670. state.probe[_i].set(0, 0, 0);
  17671. }
  17672. var directionalLength = 0;
  17673. var pointLength = 0;
  17674. var spotLength = 0;
  17675. var rectAreaLength = 0;
  17676. var hemiLength = 0;
  17677. var numDirectionalShadows = 0;
  17678. var numPointShadows = 0;
  17679. var numSpotShadows = 0;
  17680. lights.sort(shadowCastingLightsFirst);
  17681. for (var _i2 = 0, l = lights.length; _i2 < l; _i2++) {
  17682. var light = lights[_i2];
  17683. var color = light.color;
  17684. var intensity = light.intensity;
  17685. var distance = light.distance;
  17686. var shadowMap = light.shadow && light.shadow.map ? light.shadow.map.texture : null;
  17687. if (light.isAmbientLight) {
  17688. r += color.r * intensity;
  17689. g += color.g * intensity;
  17690. b += color.b * intensity;
  17691. } else if (light.isLightProbe) {
  17692. for (var j = 0; j < 9; j++) {
  17693. state.probe[j].addScaledVector(light.sh.coefficients[j], intensity);
  17694. }
  17695. } else if (light.isDirectionalLight) {
  17696. var uniforms = cache.get(light);
  17697. uniforms.color.copy(light.color).multiplyScalar(light.intensity);
  17698. if (light.castShadow) {
  17699. var shadow = light.shadow;
  17700. var shadowUniforms = shadowCache.get(light);
  17701. shadowUniforms.shadowBias = shadow.bias;
  17702. shadowUniforms.shadowNormalBias = shadow.normalBias;
  17703. shadowUniforms.shadowRadius = shadow.radius;
  17704. shadowUniforms.shadowMapSize = shadow.mapSize;
  17705. state.directionalShadow[directionalLength] = shadowUniforms;
  17706. state.directionalShadowMap[directionalLength] = shadowMap;
  17707. state.directionalShadowMatrix[directionalLength] = light.shadow.matrix;
  17708. numDirectionalShadows++;
  17709. }
  17710. state.directional[directionalLength] = uniforms;
  17711. directionalLength++;
  17712. } else if (light.isSpotLight) {
  17713. var _uniforms = cache.get(light);
  17714. _uniforms.position.setFromMatrixPosition(light.matrixWorld);
  17715. _uniforms.color.copy(color).multiplyScalar(intensity);
  17716. _uniforms.distance = distance;
  17717. _uniforms.coneCos = Math.cos(light.angle);
  17718. _uniforms.penumbraCos = Math.cos(light.angle * (1 - light.penumbra));
  17719. _uniforms.decay = light.decay;
  17720. if (light.castShadow) {
  17721. var _shadow = light.shadow;
  17722. var _shadowUniforms = shadowCache.get(light);
  17723. _shadowUniforms.shadowBias = _shadow.bias;
  17724. _shadowUniforms.shadowNormalBias = _shadow.normalBias;
  17725. _shadowUniforms.shadowRadius = _shadow.radius;
  17726. _shadowUniforms.shadowMapSize = _shadow.mapSize;
  17727. state.spotShadow[spotLength] = _shadowUniforms;
  17728. state.spotShadowMap[spotLength] = shadowMap;
  17729. state.spotShadowMatrix[spotLength] = light.shadow.matrix;
  17730. numSpotShadows++;
  17731. }
  17732. state.spot[spotLength] = _uniforms;
  17733. spotLength++;
  17734. } else if (light.isRectAreaLight) {
  17735. var _uniforms2 = cache.get(light); // (a) intensity is the total visible light emitted
  17736. //uniforms.color.copy( color ).multiplyScalar( intensity / ( light.width * light.height * Math.PI ) );
  17737. // (b) intensity is the brightness of the light
  17738. _uniforms2.color.copy(color).multiplyScalar(intensity);
  17739. _uniforms2.halfWidth.set(light.width * 0.5, 0.0, 0.0);
  17740. _uniforms2.halfHeight.set(0.0, light.height * 0.5, 0.0);
  17741. state.rectArea[rectAreaLength] = _uniforms2;
  17742. rectAreaLength++;
  17743. } else if (light.isPointLight) {
  17744. var _uniforms3 = cache.get(light);
  17745. _uniforms3.color.copy(light.color).multiplyScalar(light.intensity);
  17746. _uniforms3.distance = light.distance;
  17747. _uniforms3.decay = light.decay;
  17748. if (light.castShadow) {
  17749. var _shadow2 = light.shadow;
  17750. var _shadowUniforms2 = shadowCache.get(light);
  17751. _shadowUniforms2.shadowBias = _shadow2.bias;
  17752. _shadowUniforms2.shadowNormalBias = _shadow2.normalBias;
  17753. _shadowUniforms2.shadowRadius = _shadow2.radius;
  17754. _shadowUniforms2.shadowMapSize = _shadow2.mapSize;
  17755. _shadowUniforms2.shadowCameraNear = _shadow2.camera.near;
  17756. _shadowUniforms2.shadowCameraFar = _shadow2.camera.far;
  17757. state.pointShadow[pointLength] = _shadowUniforms2;
  17758. state.pointShadowMap[pointLength] = shadowMap;
  17759. state.pointShadowMatrix[pointLength] = light.shadow.matrix;
  17760. numPointShadows++;
  17761. }
  17762. state.point[pointLength] = _uniforms3;
  17763. pointLength++;
  17764. } else if (light.isHemisphereLight) {
  17765. var _uniforms4 = cache.get(light);
  17766. _uniforms4.skyColor.copy(light.color).multiplyScalar(intensity);
  17767. _uniforms4.groundColor.copy(light.groundColor).multiplyScalar(intensity);
  17768. state.hemi[hemiLength] = _uniforms4;
  17769. hemiLength++;
  17770. }
  17771. }
  17772. if (rectAreaLength > 0) {
  17773. if (capabilities.isWebGL2) {
  17774. // WebGL 2
  17775. state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1;
  17776. state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2;
  17777. } else {
  17778. // WebGL 1
  17779. if (extensions.has('OES_texture_float_linear') === true) {
  17780. state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1;
  17781. state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2;
  17782. } else if (extensions.has('OES_texture_half_float_linear') === true) {
  17783. state.rectAreaLTC1 = UniformsLib.LTC_HALF_1;
  17784. state.rectAreaLTC2 = UniformsLib.LTC_HALF_2;
  17785. } else {
  17786. console.error('THREE.WebGLRenderer: Unable to use RectAreaLight. Missing WebGL extensions.');
  17787. }
  17788. }
  17789. }
  17790. state.ambient[0] = r;
  17791. state.ambient[1] = g;
  17792. state.ambient[2] = b;
  17793. var hash = state.hash;
  17794. if (hash.directionalLength !== directionalLength || hash.pointLength !== pointLength || hash.spotLength !== spotLength || hash.rectAreaLength !== rectAreaLength || hash.hemiLength !== hemiLength || hash.numDirectionalShadows !== numDirectionalShadows || hash.numPointShadows !== numPointShadows || hash.numSpotShadows !== numSpotShadows) {
  17795. state.directional.length = directionalLength;
  17796. state.spot.length = spotLength;
  17797. state.rectArea.length = rectAreaLength;
  17798. state.point.length = pointLength;
  17799. state.hemi.length = hemiLength;
  17800. state.directionalShadow.length = numDirectionalShadows;
  17801. state.directionalShadowMap.length = numDirectionalShadows;
  17802. state.pointShadow.length = numPointShadows;
  17803. state.pointShadowMap.length = numPointShadows;
  17804. state.spotShadow.length = numSpotShadows;
  17805. state.spotShadowMap.length = numSpotShadows;
  17806. state.directionalShadowMatrix.length = numDirectionalShadows;
  17807. state.pointShadowMatrix.length = numPointShadows;
  17808. state.spotShadowMatrix.length = numSpotShadows;
  17809. hash.directionalLength = directionalLength;
  17810. hash.pointLength = pointLength;
  17811. hash.spotLength = spotLength;
  17812. hash.rectAreaLength = rectAreaLength;
  17813. hash.hemiLength = hemiLength;
  17814. hash.numDirectionalShadows = numDirectionalShadows;
  17815. hash.numPointShadows = numPointShadows;
  17816. hash.numSpotShadows = numSpotShadows;
  17817. state.version = nextVersion++;
  17818. }
  17819. }
  17820. function setupView(lights, camera) {
  17821. var directionalLength = 0;
  17822. var pointLength = 0;
  17823. var spotLength = 0;
  17824. var rectAreaLength = 0;
  17825. var hemiLength = 0;
  17826. var viewMatrix = camera.matrixWorldInverse;
  17827. for (var _i3 = 0, l = lights.length; _i3 < l; _i3++) {
  17828. var light = lights[_i3];
  17829. if (light.isDirectionalLight) {
  17830. var uniforms = state.directional[directionalLength];
  17831. uniforms.direction.setFromMatrixPosition(light.matrixWorld);
  17832. vector3.setFromMatrixPosition(light.target.matrixWorld);
  17833. uniforms.direction.sub(vector3);
  17834. uniforms.direction.transformDirection(viewMatrix);
  17835. directionalLength++;
  17836. } else if (light.isSpotLight) {
  17837. var _uniforms5 = state.spot[spotLength];
  17838. _uniforms5.position.setFromMatrixPosition(light.matrixWorld);
  17839. _uniforms5.position.applyMatrix4(viewMatrix);
  17840. _uniforms5.direction.setFromMatrixPosition(light.matrixWorld);
  17841. vector3.setFromMatrixPosition(light.target.matrixWorld);
  17842. _uniforms5.direction.sub(vector3);
  17843. _uniforms5.direction.transformDirection(viewMatrix);
  17844. spotLength++;
  17845. } else if (light.isRectAreaLight) {
  17846. var _uniforms6 = state.rectArea[rectAreaLength];
  17847. _uniforms6.position.setFromMatrixPosition(light.matrixWorld);
  17848. _uniforms6.position.applyMatrix4(viewMatrix); // extract local rotation of light to derive width/height half vectors
  17849. matrix42.identity();
  17850. matrix4.copy(light.matrixWorld);
  17851. matrix4.premultiply(viewMatrix);
  17852. matrix42.extractRotation(matrix4);
  17853. _uniforms6.halfWidth.set(light.width * 0.5, 0.0, 0.0);
  17854. _uniforms6.halfHeight.set(0.0, light.height * 0.5, 0.0);
  17855. _uniforms6.halfWidth.applyMatrix4(matrix42);
  17856. _uniforms6.halfHeight.applyMatrix4(matrix42);
  17857. rectAreaLength++;
  17858. } else if (light.isPointLight) {
  17859. var _uniforms7 = state.point[pointLength];
  17860. _uniforms7.position.setFromMatrixPosition(light.matrixWorld);
  17861. _uniforms7.position.applyMatrix4(viewMatrix);
  17862. pointLength++;
  17863. } else if (light.isHemisphereLight) {
  17864. var _uniforms8 = state.hemi[hemiLength];
  17865. _uniforms8.direction.setFromMatrixPosition(light.matrixWorld);
  17866. _uniforms8.direction.transformDirection(viewMatrix);
  17867. _uniforms8.direction.normalize();
  17868. hemiLength++;
  17869. }
  17870. }
  17871. }
  17872. return {
  17873. setup: setup,
  17874. setupView: setupView,
  17875. state: state
  17876. };
  17877. }
  17878. function WebGLRenderState(extensions, capabilities) {
  17879. var lights = new WebGLLights(extensions, capabilities);
  17880. var lightsArray = [];
  17881. var shadowsArray = [];
  17882. function init() {
  17883. lightsArray.length = 0;
  17884. shadowsArray.length = 0;
  17885. }
  17886. function pushLight(light) {
  17887. lightsArray.push(light);
  17888. }
  17889. function pushShadow(shadowLight) {
  17890. shadowsArray.push(shadowLight);
  17891. }
  17892. function setupLights() {
  17893. lights.setup(lightsArray);
  17894. }
  17895. function setupLightsView(camera) {
  17896. lights.setupView(lightsArray, camera);
  17897. }
  17898. var state = {
  17899. lightsArray: lightsArray,
  17900. shadowsArray: shadowsArray,
  17901. lights: lights
  17902. };
  17903. return {
  17904. init: init,
  17905. state: state,
  17906. setupLights: setupLights,
  17907. setupLightsView: setupLightsView,
  17908. pushLight: pushLight,
  17909. pushShadow: pushShadow
  17910. };
  17911. }
  17912. function WebGLRenderStates(extensions, capabilities) {
  17913. var renderStates = new WeakMap();
  17914. function get(scene, renderCallDepth) {
  17915. if (renderCallDepth === void 0) {
  17916. renderCallDepth = 0;
  17917. }
  17918. var renderState;
  17919. if (renderStates.has(scene) === false) {
  17920. renderState = new WebGLRenderState(extensions, capabilities);
  17921. renderStates.set(scene, []);
  17922. renderStates.get(scene).push(renderState);
  17923. } else {
  17924. if (renderCallDepth >= renderStates.get(scene).length) {
  17925. renderState = new WebGLRenderState(extensions, capabilities);
  17926. renderStates.get(scene).push(renderState);
  17927. } else {
  17928. renderState = renderStates.get(scene)[renderCallDepth];
  17929. }
  17930. }
  17931. return renderState;
  17932. }
  17933. function dispose() {
  17934. renderStates = new WeakMap();
  17935. }
  17936. return {
  17937. get: get,
  17938. dispose: dispose
  17939. };
  17940. }
  17941. /**
  17942. * parameters = {
  17943. *
  17944. * opacity: <float>,
  17945. *
  17946. * map: new THREE.Texture( <Image> ),
  17947. *
  17948. * alphaMap: new THREE.Texture( <Image> ),
  17949. *
  17950. * displacementMap: new THREE.Texture( <Image> ),
  17951. * displacementScale: <float>,
  17952. * displacementBias: <float>,
  17953. *
  17954. * wireframe: <boolean>,
  17955. * wireframeLinewidth: <float>
  17956. * }
  17957. */
  17958. function MeshDepthMaterial(parameters) {
  17959. Material.call(this);
  17960. this.type = 'MeshDepthMaterial';
  17961. this.depthPacking = BasicDepthPacking;
  17962. this.skinning = false;
  17963. this.morphTargets = false;
  17964. this.map = null;
  17965. this.alphaMap = null;
  17966. this.displacementMap = null;
  17967. this.displacementScale = 1;
  17968. this.displacementBias = 0;
  17969. this.wireframe = false;
  17970. this.wireframeLinewidth = 1;
  17971. this.fog = false;
  17972. this.setValues(parameters);
  17973. }
  17974. MeshDepthMaterial.prototype = Object.create(Material.prototype);
  17975. MeshDepthMaterial.prototype.constructor = MeshDepthMaterial;
  17976. MeshDepthMaterial.prototype.isMeshDepthMaterial = true;
  17977. MeshDepthMaterial.prototype.copy = function (source) {
  17978. Material.prototype.copy.call(this, source);
  17979. this.depthPacking = source.depthPacking;
  17980. this.skinning = source.skinning;
  17981. this.morphTargets = source.morphTargets;
  17982. this.map = source.map;
  17983. this.alphaMap = source.alphaMap;
  17984. this.displacementMap = source.displacementMap;
  17985. this.displacementScale = source.displacementScale;
  17986. this.displacementBias = source.displacementBias;
  17987. this.wireframe = source.wireframe;
  17988. this.wireframeLinewidth = source.wireframeLinewidth;
  17989. return this;
  17990. };
  17991. /**
  17992. * parameters = {
  17993. *
  17994. * referencePosition: <float>,
  17995. * nearDistance: <float>,
  17996. * farDistance: <float>,
  17997. *
  17998. * skinning: <bool>,
  17999. * morphTargets: <bool>,
  18000. *
  18001. * map: new THREE.Texture( <Image> ),
  18002. *
  18003. * alphaMap: new THREE.Texture( <Image> ),
  18004. *
  18005. * displacementMap: new THREE.Texture( <Image> ),
  18006. * displacementScale: <float>,
  18007. * displacementBias: <float>
  18008. *
  18009. * }
  18010. */
  18011. function MeshDistanceMaterial(parameters) {
  18012. Material.call(this);
  18013. this.type = 'MeshDistanceMaterial';
  18014. this.referencePosition = new Vector3();
  18015. this.nearDistance = 1;
  18016. this.farDistance = 1000;
  18017. this.skinning = false;
  18018. this.morphTargets = false;
  18019. this.map = null;
  18020. this.alphaMap = null;
  18021. this.displacementMap = null;
  18022. this.displacementScale = 1;
  18023. this.displacementBias = 0;
  18024. this.fog = false;
  18025. this.setValues(parameters);
  18026. }
  18027. MeshDistanceMaterial.prototype = Object.create(Material.prototype);
  18028. MeshDistanceMaterial.prototype.constructor = MeshDistanceMaterial;
  18029. MeshDistanceMaterial.prototype.isMeshDistanceMaterial = true;
  18030. MeshDistanceMaterial.prototype.copy = function (source) {
  18031. Material.prototype.copy.call(this, source);
  18032. this.referencePosition.copy(source.referencePosition);
  18033. this.nearDistance = source.nearDistance;
  18034. this.farDistance = source.farDistance;
  18035. this.skinning = source.skinning;
  18036. this.morphTargets = source.morphTargets;
  18037. this.map = source.map;
  18038. this.alphaMap = source.alphaMap;
  18039. this.displacementMap = source.displacementMap;
  18040. this.displacementScale = source.displacementScale;
  18041. this.displacementBias = source.displacementBias;
  18042. return this;
  18043. };
  18044. var vsm_frag = "uniform sampler2D shadow_pass;\nuniform vec2 resolution;\nuniform float radius;\n#include <packing>\nvoid main() {\n\tfloat mean = 0.0;\n\tfloat squared_mean = 0.0;\n\tfloat depth = unpackRGBAToDepth( texture2D( shadow_pass, ( gl_FragCoord.xy ) / resolution ) );\n\tfor ( float i = -1.0; i < 1.0 ; i += SAMPLE_RATE) {\n\t\t#ifdef HORIZONTAL_PASS\n\t\t\tvec2 distribution = unpackRGBATo2Half( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( i, 0.0 ) * radius ) / resolution ) );\n\t\t\tmean += distribution.x;\n\t\t\tsquared_mean += distribution.y * distribution.y + distribution.x * distribution.x;\n\t\t#else\n\t\t\tfloat depth = unpackRGBAToDepth( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( 0.0, i ) * radius ) / resolution ) );\n\t\t\tmean += depth;\n\t\t\tsquared_mean += depth * depth;\n\t\t#endif\n\t}\n\tmean = mean * HALF_SAMPLE_RATE;\n\tsquared_mean = squared_mean * HALF_SAMPLE_RATE;\n\tfloat std_dev = sqrt( squared_mean - mean * mean );\n\tgl_FragColor = pack2HalfToRGBA( vec2( mean, std_dev ) );\n}";
  18045. var vsm_vert = "void main() {\n\tgl_Position = vec4( position, 1.0 );\n}";
  18046. function WebGLShadowMap(_renderer, _objects, maxTextureSize) {
  18047. var _frustum = new Frustum();
  18048. var _shadowMapSize = new Vector2(),
  18049. _viewportSize = new Vector2(),
  18050. _viewport = new Vector4(),
  18051. _depthMaterials = [],
  18052. _distanceMaterials = [],
  18053. _materialCache = {};
  18054. var shadowSide = {
  18055. 0: BackSide,
  18056. 1: FrontSide,
  18057. 2: DoubleSide
  18058. };
  18059. var shadowMaterialVertical = new ShaderMaterial({
  18060. defines: {
  18061. SAMPLE_RATE: 2.0 / 8.0,
  18062. HALF_SAMPLE_RATE: 1.0 / 8.0
  18063. },
  18064. uniforms: {
  18065. shadow_pass: {
  18066. value: null
  18067. },
  18068. resolution: {
  18069. value: new Vector2()
  18070. },
  18071. radius: {
  18072. value: 4.0
  18073. }
  18074. },
  18075. vertexShader: vsm_vert,
  18076. fragmentShader: vsm_frag
  18077. });
  18078. var shadowMaterialHorizontal = shadowMaterialVertical.clone();
  18079. shadowMaterialHorizontal.defines.HORIZONTAL_PASS = 1;
  18080. var fullScreenTri = new BufferGeometry();
  18081. fullScreenTri.setAttribute('position', new BufferAttribute(new Float32Array([-1, -1, 0.5, 3, -1, 0.5, -1, 3, 0.5]), 3));
  18082. var fullScreenMesh = new Mesh(fullScreenTri, shadowMaterialVertical);
  18083. var scope = this;
  18084. this.enabled = false;
  18085. this.autoUpdate = true;
  18086. this.needsUpdate = false;
  18087. this.type = PCFShadowMap;
  18088. this.render = function (lights, scene, camera) {
  18089. if (scope.enabled === false) return;
  18090. if (scope.autoUpdate === false && scope.needsUpdate === false) return;
  18091. if (lights.length === 0) return;
  18092. var currentRenderTarget = _renderer.getRenderTarget();
  18093. var activeCubeFace = _renderer.getActiveCubeFace();
  18094. var activeMipmapLevel = _renderer.getActiveMipmapLevel();
  18095. var _state = _renderer.state; // Set GL state for depth map.
  18096. _state.setBlending(NoBlending);
  18097. _state.buffers.color.setClear(1, 1, 1, 1);
  18098. _state.buffers.depth.setTest(true);
  18099. _state.setScissorTest(false); // render depth map
  18100. for (var i = 0, il = lights.length; i < il; i++) {
  18101. var light = lights[i];
  18102. var shadow = light.shadow;
  18103. if (shadow === undefined) {
  18104. console.warn('THREE.WebGLShadowMap:', light, 'has no shadow.');
  18105. continue;
  18106. }
  18107. if (shadow.autoUpdate === false && shadow.needsUpdate === false) continue;
  18108. _shadowMapSize.copy(shadow.mapSize);
  18109. var shadowFrameExtents = shadow.getFrameExtents();
  18110. _shadowMapSize.multiply(shadowFrameExtents);
  18111. _viewportSize.copy(shadow.mapSize);
  18112. if (_shadowMapSize.x > maxTextureSize || _shadowMapSize.y > maxTextureSize) {
  18113. if (_shadowMapSize.x > maxTextureSize) {
  18114. _viewportSize.x = Math.floor(maxTextureSize / shadowFrameExtents.x);
  18115. _shadowMapSize.x = _viewportSize.x * shadowFrameExtents.x;
  18116. shadow.mapSize.x = _viewportSize.x;
  18117. }
  18118. if (_shadowMapSize.y > maxTextureSize) {
  18119. _viewportSize.y = Math.floor(maxTextureSize / shadowFrameExtents.y);
  18120. _shadowMapSize.y = _viewportSize.y * shadowFrameExtents.y;
  18121. shadow.mapSize.y = _viewportSize.y;
  18122. }
  18123. }
  18124. if (shadow.map === null && !shadow.isPointLightShadow && this.type === VSMShadowMap) {
  18125. var pars = {
  18126. minFilter: LinearFilter,
  18127. magFilter: LinearFilter,
  18128. format: RGBAFormat
  18129. };
  18130. shadow.map = new WebGLRenderTarget(_shadowMapSize.x, _shadowMapSize.y, pars);
  18131. shadow.map.texture.name = light.name + '.shadowMap';
  18132. shadow.mapPass = new WebGLRenderTarget(_shadowMapSize.x, _shadowMapSize.y, pars);
  18133. shadow.camera.updateProjectionMatrix();
  18134. }
  18135. if (shadow.map === null) {
  18136. var _pars = {
  18137. minFilter: NearestFilter,
  18138. magFilter: NearestFilter,
  18139. format: RGBAFormat
  18140. };
  18141. shadow.map = new WebGLRenderTarget(_shadowMapSize.x, _shadowMapSize.y, _pars);
  18142. shadow.map.texture.name = light.name + '.shadowMap';
  18143. shadow.camera.updateProjectionMatrix();
  18144. }
  18145. _renderer.setRenderTarget(shadow.map);
  18146. _renderer.clear();
  18147. var viewportCount = shadow.getViewportCount();
  18148. for (var vp = 0; vp < viewportCount; vp++) {
  18149. var viewport = shadow.getViewport(vp);
  18150. _viewport.set(_viewportSize.x * viewport.x, _viewportSize.y * viewport.y, _viewportSize.x * viewport.z, _viewportSize.y * viewport.w);
  18151. _state.viewport(_viewport);
  18152. shadow.updateMatrices(light, vp);
  18153. _frustum = shadow.getFrustum();
  18154. renderObject(scene, camera, shadow.camera, light, this.type);
  18155. } // do blur pass for VSM
  18156. if (!shadow.isPointLightShadow && this.type === VSMShadowMap) {
  18157. VSMPass(shadow, camera);
  18158. }
  18159. shadow.needsUpdate = false;
  18160. }
  18161. scope.needsUpdate = false;
  18162. _renderer.setRenderTarget(currentRenderTarget, activeCubeFace, activeMipmapLevel);
  18163. };
  18164. function VSMPass(shadow, camera) {
  18165. var geometry = _objects.update(fullScreenMesh); // vertical pass
  18166. shadowMaterialVertical.uniforms.shadow_pass.value = shadow.map.texture;
  18167. shadowMaterialVertical.uniforms.resolution.value = shadow.mapSize;
  18168. shadowMaterialVertical.uniforms.radius.value = shadow.radius;
  18169. _renderer.setRenderTarget(shadow.mapPass);
  18170. _renderer.clear();
  18171. _renderer.renderBufferDirect(camera, null, geometry, shadowMaterialVertical, fullScreenMesh, null); // horizontal pass
  18172. shadowMaterialHorizontal.uniforms.shadow_pass.value = shadow.mapPass.texture;
  18173. shadowMaterialHorizontal.uniforms.resolution.value = shadow.mapSize;
  18174. shadowMaterialHorizontal.uniforms.radius.value = shadow.radius;
  18175. _renderer.setRenderTarget(shadow.map);
  18176. _renderer.clear();
  18177. _renderer.renderBufferDirect(camera, null, geometry, shadowMaterialHorizontal, fullScreenMesh, null);
  18178. }
  18179. function getDepthMaterialVariant(useMorphing, useSkinning, useInstancing) {
  18180. var index = useMorphing << 0 | useSkinning << 1 | useInstancing << 2;
  18181. var material = _depthMaterials[index];
  18182. if (material === undefined) {
  18183. material = new MeshDepthMaterial({
  18184. depthPacking: RGBADepthPacking,
  18185. morphTargets: useMorphing,
  18186. skinning: useSkinning
  18187. });
  18188. _depthMaterials[index] = material;
  18189. }
  18190. return material;
  18191. }
  18192. function getDistanceMaterialVariant(useMorphing, useSkinning, useInstancing) {
  18193. var index = useMorphing << 0 | useSkinning << 1 | useInstancing << 2;
  18194. var material = _distanceMaterials[index];
  18195. if (material === undefined) {
  18196. material = new MeshDistanceMaterial({
  18197. morphTargets: useMorphing,
  18198. skinning: useSkinning
  18199. });
  18200. _distanceMaterials[index] = material;
  18201. }
  18202. return material;
  18203. }
  18204. function getDepthMaterial(object, geometry, material, light, shadowCameraNear, shadowCameraFar, type) {
  18205. var result = null;
  18206. var getMaterialVariant = getDepthMaterialVariant;
  18207. var customMaterial = object.customDepthMaterial;
  18208. if (light.isPointLight === true) {
  18209. getMaterialVariant = getDistanceMaterialVariant;
  18210. customMaterial = object.customDistanceMaterial;
  18211. }
  18212. if (customMaterial === undefined) {
  18213. var useMorphing = false;
  18214. if (material.morphTargets === true) {
  18215. useMorphing = geometry.morphAttributes && geometry.morphAttributes.position && geometry.morphAttributes.position.length > 0;
  18216. }
  18217. var useSkinning = false;
  18218. if (object.isSkinnedMesh === true) {
  18219. if (material.skinning === true) {
  18220. useSkinning = true;
  18221. } else {
  18222. console.warn('THREE.WebGLShadowMap: THREE.SkinnedMesh with material.skinning set to false:', object);
  18223. }
  18224. }
  18225. var useInstancing = object.isInstancedMesh === true;
  18226. result = getMaterialVariant(useMorphing, useSkinning, useInstancing);
  18227. } else {
  18228. result = customMaterial;
  18229. }
  18230. if (_renderer.localClippingEnabled && material.clipShadows === true && material.clippingPlanes.length !== 0) {
  18231. // in this case we need a unique material instance reflecting the
  18232. // appropriate state
  18233. var keyA = result.uuid,
  18234. keyB = material.uuid;
  18235. var materialsForVariant = _materialCache[keyA];
  18236. if (materialsForVariant === undefined) {
  18237. materialsForVariant = {};
  18238. _materialCache[keyA] = materialsForVariant;
  18239. }
  18240. var cachedMaterial = materialsForVariant[keyB];
  18241. if (cachedMaterial === undefined) {
  18242. cachedMaterial = result.clone();
  18243. materialsForVariant[keyB] = cachedMaterial;
  18244. }
  18245. result = cachedMaterial;
  18246. }
  18247. result.visible = material.visible;
  18248. result.wireframe = material.wireframe;
  18249. if (type === VSMShadowMap) {
  18250. result.side = material.shadowSide !== null ? material.shadowSide : material.side;
  18251. } else {
  18252. result.side = material.shadowSide !== null ? material.shadowSide : shadowSide[material.side];
  18253. }
  18254. result.clipShadows = material.clipShadows;
  18255. result.clippingPlanes = material.clippingPlanes;
  18256. result.clipIntersection = material.clipIntersection;
  18257. result.wireframeLinewidth = material.wireframeLinewidth;
  18258. result.linewidth = material.linewidth;
  18259. if (light.isPointLight === true && result.isMeshDistanceMaterial === true) {
  18260. result.referencePosition.setFromMatrixPosition(light.matrixWorld);
  18261. result.nearDistance = shadowCameraNear;
  18262. result.farDistance = shadowCameraFar;
  18263. }
  18264. return result;
  18265. }
  18266. function renderObject(object, camera, shadowCamera, light, type) {
  18267. if (object.visible === false) return;
  18268. var visible = object.layers.test(camera.layers);
  18269. if (visible && (object.isMesh || object.isLine || object.isPoints)) {
  18270. if ((object.castShadow || object.receiveShadow && type === VSMShadowMap) && (!object.frustumCulled || _frustum.intersectsObject(object))) {
  18271. object.modelViewMatrix.multiplyMatrices(shadowCamera.matrixWorldInverse, object.matrixWorld);
  18272. var geometry = _objects.update(object);
  18273. var material = object.material;
  18274. if (Array.isArray(material)) {
  18275. var groups = geometry.groups;
  18276. for (var k = 0, kl = groups.length; k < kl; k++) {
  18277. var group = groups[k];
  18278. var groupMaterial = material[group.materialIndex];
  18279. if (groupMaterial && groupMaterial.visible) {
  18280. var depthMaterial = getDepthMaterial(object, geometry, groupMaterial, light, shadowCamera.near, shadowCamera.far, type);
  18281. _renderer.renderBufferDirect(shadowCamera, null, geometry, depthMaterial, object, group);
  18282. }
  18283. }
  18284. } else if (material.visible) {
  18285. var _depthMaterial = getDepthMaterial(object, geometry, material, light, shadowCamera.near, shadowCamera.far, type);
  18286. _renderer.renderBufferDirect(shadowCamera, null, geometry, _depthMaterial, object, null);
  18287. }
  18288. }
  18289. }
  18290. var children = object.children;
  18291. for (var i = 0, l = children.length; i < l; i++) {
  18292. renderObject(children[i], camera, shadowCamera, light, type);
  18293. }
  18294. }
  18295. }
  18296. function WebGLState(gl, extensions, capabilities) {
  18297. var _equationToGL, _factorToGL;
  18298. var isWebGL2 = capabilities.isWebGL2;
  18299. function ColorBuffer() {
  18300. var locked = false;
  18301. var color = new Vector4();
  18302. var currentColorMask = null;
  18303. var currentColorClear = new Vector4(0, 0, 0, 0);
  18304. return {
  18305. setMask: function setMask(colorMask) {
  18306. if (currentColorMask !== colorMask && !locked) {
  18307. gl.colorMask(colorMask, colorMask, colorMask, colorMask);
  18308. currentColorMask = colorMask;
  18309. }
  18310. },
  18311. setLocked: function setLocked(lock) {
  18312. locked = lock;
  18313. },
  18314. setClear: function setClear(r, g, b, a, premultipliedAlpha) {
  18315. if (premultipliedAlpha === true) {
  18316. r *= a;
  18317. g *= a;
  18318. b *= a;
  18319. }
  18320. color.set(r, g, b, a);
  18321. if (currentColorClear.equals(color) === false) {
  18322. gl.clearColor(r, g, b, a);
  18323. currentColorClear.copy(color);
  18324. }
  18325. },
  18326. reset: function reset() {
  18327. locked = false;
  18328. currentColorMask = null;
  18329. currentColorClear.set(-1, 0, 0, 0); // set to invalid state
  18330. }
  18331. };
  18332. }
  18333. function DepthBuffer() {
  18334. var locked = false;
  18335. var currentDepthMask = null;
  18336. var currentDepthFunc = null;
  18337. var currentDepthClear = null;
  18338. return {
  18339. setTest: function setTest(depthTest) {
  18340. if (depthTest) {
  18341. enable(2929);
  18342. } else {
  18343. disable(2929);
  18344. }
  18345. },
  18346. setMask: function setMask(depthMask) {
  18347. if (currentDepthMask !== depthMask && !locked) {
  18348. gl.depthMask(depthMask);
  18349. currentDepthMask = depthMask;
  18350. }
  18351. },
  18352. setFunc: function setFunc(depthFunc) {
  18353. if (currentDepthFunc !== depthFunc) {
  18354. if (depthFunc) {
  18355. switch (depthFunc) {
  18356. case NeverDepth:
  18357. gl.depthFunc(512);
  18358. break;
  18359. case AlwaysDepth:
  18360. gl.depthFunc(519);
  18361. break;
  18362. case LessDepth:
  18363. gl.depthFunc(513);
  18364. break;
  18365. case LessEqualDepth:
  18366. gl.depthFunc(515);
  18367. break;
  18368. case EqualDepth:
  18369. gl.depthFunc(514);
  18370. break;
  18371. case GreaterEqualDepth:
  18372. gl.depthFunc(518);
  18373. break;
  18374. case GreaterDepth:
  18375. gl.depthFunc(516);
  18376. break;
  18377. case NotEqualDepth:
  18378. gl.depthFunc(517);
  18379. break;
  18380. default:
  18381. gl.depthFunc(515);
  18382. }
  18383. } else {
  18384. gl.depthFunc(515);
  18385. }
  18386. currentDepthFunc = depthFunc;
  18387. }
  18388. },
  18389. setLocked: function setLocked(lock) {
  18390. locked = lock;
  18391. },
  18392. setClear: function setClear(depth) {
  18393. if (currentDepthClear !== depth) {
  18394. gl.clearDepth(depth);
  18395. currentDepthClear = depth;
  18396. }
  18397. },
  18398. reset: function reset() {
  18399. locked = false;
  18400. currentDepthMask = null;
  18401. currentDepthFunc = null;
  18402. currentDepthClear = null;
  18403. }
  18404. };
  18405. }
  18406. function StencilBuffer() {
  18407. var locked = false;
  18408. var currentStencilMask = null;
  18409. var currentStencilFunc = null;
  18410. var currentStencilRef = null;
  18411. var currentStencilFuncMask = null;
  18412. var currentStencilFail = null;
  18413. var currentStencilZFail = null;
  18414. var currentStencilZPass = null;
  18415. var currentStencilClear = null;
  18416. return {
  18417. setTest: function setTest(stencilTest) {
  18418. if (!locked) {
  18419. if (stencilTest) {
  18420. enable(2960);
  18421. } else {
  18422. disable(2960);
  18423. }
  18424. }
  18425. },
  18426. setMask: function setMask(stencilMask) {
  18427. if (currentStencilMask !== stencilMask && !locked) {
  18428. gl.stencilMask(stencilMask);
  18429. currentStencilMask = stencilMask;
  18430. }
  18431. },
  18432. setFunc: function setFunc(stencilFunc, stencilRef, stencilMask) {
  18433. if (currentStencilFunc !== stencilFunc || currentStencilRef !== stencilRef || currentStencilFuncMask !== stencilMask) {
  18434. gl.stencilFunc(stencilFunc, stencilRef, stencilMask);
  18435. currentStencilFunc = stencilFunc;
  18436. currentStencilRef = stencilRef;
  18437. currentStencilFuncMask = stencilMask;
  18438. }
  18439. },
  18440. setOp: function setOp(stencilFail, stencilZFail, stencilZPass) {
  18441. if (currentStencilFail !== stencilFail || currentStencilZFail !== stencilZFail || currentStencilZPass !== stencilZPass) {
  18442. gl.stencilOp(stencilFail, stencilZFail, stencilZPass);
  18443. currentStencilFail = stencilFail;
  18444. currentStencilZFail = stencilZFail;
  18445. currentStencilZPass = stencilZPass;
  18446. }
  18447. },
  18448. setLocked: function setLocked(lock) {
  18449. locked = lock;
  18450. },
  18451. setClear: function setClear(stencil) {
  18452. if (currentStencilClear !== stencil) {
  18453. gl.clearStencil(stencil);
  18454. currentStencilClear = stencil;
  18455. }
  18456. },
  18457. reset: function reset() {
  18458. locked = false;
  18459. currentStencilMask = null;
  18460. currentStencilFunc = null;
  18461. currentStencilRef = null;
  18462. currentStencilFuncMask = null;
  18463. currentStencilFail = null;
  18464. currentStencilZFail = null;
  18465. currentStencilZPass = null;
  18466. currentStencilClear = null;
  18467. }
  18468. };
  18469. } //
  18470. var colorBuffer = new ColorBuffer();
  18471. var depthBuffer = new DepthBuffer();
  18472. var stencilBuffer = new StencilBuffer();
  18473. var enabledCapabilities = {};
  18474. var currentProgram = null;
  18475. var currentBlendingEnabled = null;
  18476. var currentBlending = null;
  18477. var currentBlendEquation = null;
  18478. var currentBlendSrc = null;
  18479. var currentBlendDst = null;
  18480. var currentBlendEquationAlpha = null;
  18481. var currentBlendSrcAlpha = null;
  18482. var currentBlendDstAlpha = null;
  18483. var currentPremultipledAlpha = false;
  18484. var currentFlipSided = null;
  18485. var currentCullFace = null;
  18486. var currentLineWidth = null;
  18487. var currentPolygonOffsetFactor = null;
  18488. var currentPolygonOffsetUnits = null;
  18489. var maxTextures = gl.getParameter(35661);
  18490. var lineWidthAvailable = false;
  18491. var version = 0;
  18492. var glVersion = gl.getParameter(7938);
  18493. if (glVersion.indexOf('WebGL') !== -1) {
  18494. version = parseFloat(/^WebGL (\d)/.exec(glVersion)[1]);
  18495. lineWidthAvailable = version >= 1.0;
  18496. } else if (glVersion.indexOf('OpenGL ES') !== -1) {
  18497. version = parseFloat(/^OpenGL ES (\d)/.exec(glVersion)[1]);
  18498. lineWidthAvailable = version >= 2.0;
  18499. }
  18500. var currentTextureSlot = null;
  18501. var currentBoundTextures = {};
  18502. var currentScissor = new Vector4();
  18503. var currentViewport = new Vector4();
  18504. function createTexture(type, target, count) {
  18505. var data = new Uint8Array(4); // 4 is required to match default unpack alignment of 4.
  18506. var texture = gl.createTexture();
  18507. gl.bindTexture(type, texture);
  18508. gl.texParameteri(type, 10241, 9728);
  18509. gl.texParameteri(type, 10240, 9728);
  18510. for (var i = 0; i < count; i++) {
  18511. gl.texImage2D(target + i, 0, 6408, 1, 1, 0, 6408, 5121, data);
  18512. }
  18513. return texture;
  18514. }
  18515. var emptyTextures = {};
  18516. emptyTextures[3553] = createTexture(3553, 3553, 1);
  18517. emptyTextures[34067] = createTexture(34067, 34069, 6); // init
  18518. colorBuffer.setClear(0, 0, 0, 1);
  18519. depthBuffer.setClear(1);
  18520. stencilBuffer.setClear(0);
  18521. enable(2929);
  18522. depthBuffer.setFunc(LessEqualDepth);
  18523. setFlipSided(false);
  18524. setCullFace(CullFaceBack);
  18525. enable(2884);
  18526. setBlending(NoBlending); //
  18527. function enable(id) {
  18528. if (enabledCapabilities[id] !== true) {
  18529. gl.enable(id);
  18530. enabledCapabilities[id] = true;
  18531. }
  18532. }
  18533. function disable(id) {
  18534. if (enabledCapabilities[id] !== false) {
  18535. gl.disable(id);
  18536. enabledCapabilities[id] = false;
  18537. }
  18538. }
  18539. function useProgram(program) {
  18540. if (currentProgram !== program) {
  18541. gl.useProgram(program);
  18542. currentProgram = program;
  18543. return true;
  18544. }
  18545. return false;
  18546. }
  18547. var equationToGL = (_equationToGL = {}, _equationToGL[AddEquation] = 32774, _equationToGL[SubtractEquation] = 32778, _equationToGL[ReverseSubtractEquation] = 32779, _equationToGL);
  18548. if (isWebGL2) {
  18549. equationToGL[MinEquation] = 32775;
  18550. equationToGL[MaxEquation] = 32776;
  18551. } else {
  18552. var extension = extensions.get('EXT_blend_minmax');
  18553. if (extension !== null) {
  18554. equationToGL[MinEquation] = extension.MIN_EXT;
  18555. equationToGL[MaxEquation] = extension.MAX_EXT;
  18556. }
  18557. }
  18558. var factorToGL = (_factorToGL = {}, _factorToGL[ZeroFactor] = 0, _factorToGL[OneFactor] = 1, _factorToGL[SrcColorFactor] = 768, _factorToGL[SrcAlphaFactor] = 770, _factorToGL[SrcAlphaSaturateFactor] = 776, _factorToGL[DstColorFactor] = 774, _factorToGL[DstAlphaFactor] = 772, _factorToGL[OneMinusSrcColorFactor] = 769, _factorToGL[OneMinusSrcAlphaFactor] = 771, _factorToGL[OneMinusDstColorFactor] = 775, _factorToGL[OneMinusDstAlphaFactor] = 773, _factorToGL);
  18559. function setBlending(blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha) {
  18560. if (blending === NoBlending) {
  18561. if (currentBlendingEnabled) {
  18562. disable(3042);
  18563. currentBlendingEnabled = false;
  18564. }
  18565. return;
  18566. }
  18567. if (!currentBlendingEnabled) {
  18568. enable(3042);
  18569. currentBlendingEnabled = true;
  18570. }
  18571. if (blending !== CustomBlending) {
  18572. if (blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha) {
  18573. if (currentBlendEquation !== AddEquation || currentBlendEquationAlpha !== AddEquation) {
  18574. gl.blendEquation(32774);
  18575. currentBlendEquation = AddEquation;
  18576. currentBlendEquationAlpha = AddEquation;
  18577. }
  18578. if (premultipliedAlpha) {
  18579. switch (blending) {
  18580. case NormalBlending:
  18581. gl.blendFuncSeparate(1, 771, 1, 771);
  18582. break;
  18583. case AdditiveBlending:
  18584. gl.blendFunc(1, 1);
  18585. break;
  18586. case SubtractiveBlending:
  18587. gl.blendFuncSeparate(0, 0, 769, 771);
  18588. break;
  18589. case MultiplyBlending:
  18590. gl.blendFuncSeparate(0, 768, 0, 770);
  18591. break;
  18592. default:
  18593. console.error('THREE.WebGLState: Invalid blending: ', blending);
  18594. break;
  18595. }
  18596. } else {
  18597. switch (blending) {
  18598. case NormalBlending:
  18599. gl.blendFuncSeparate(770, 771, 1, 771);
  18600. break;
  18601. case AdditiveBlending:
  18602. gl.blendFunc(770, 1);
  18603. break;
  18604. case SubtractiveBlending:
  18605. gl.blendFunc(0, 769);
  18606. break;
  18607. case MultiplyBlending:
  18608. gl.blendFunc(0, 768);
  18609. break;
  18610. default:
  18611. console.error('THREE.WebGLState: Invalid blending: ', blending);
  18612. break;
  18613. }
  18614. }
  18615. currentBlendSrc = null;
  18616. currentBlendDst = null;
  18617. currentBlendSrcAlpha = null;
  18618. currentBlendDstAlpha = null;
  18619. currentBlending = blending;
  18620. currentPremultipledAlpha = premultipliedAlpha;
  18621. }
  18622. return;
  18623. } // custom blending
  18624. blendEquationAlpha = blendEquationAlpha || blendEquation;
  18625. blendSrcAlpha = blendSrcAlpha || blendSrc;
  18626. blendDstAlpha = blendDstAlpha || blendDst;
  18627. if (blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha) {
  18628. gl.blendEquationSeparate(equationToGL[blendEquation], equationToGL[blendEquationAlpha]);
  18629. currentBlendEquation = blendEquation;
  18630. currentBlendEquationAlpha = blendEquationAlpha;
  18631. }
  18632. if (blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha) {
  18633. gl.blendFuncSeparate(factorToGL[blendSrc], factorToGL[blendDst], factorToGL[blendSrcAlpha], factorToGL[blendDstAlpha]);
  18634. currentBlendSrc = blendSrc;
  18635. currentBlendDst = blendDst;
  18636. currentBlendSrcAlpha = blendSrcAlpha;
  18637. currentBlendDstAlpha = blendDstAlpha;
  18638. }
  18639. currentBlending = blending;
  18640. currentPremultipledAlpha = null;
  18641. }
  18642. function setMaterial(material, frontFaceCW) {
  18643. material.side === DoubleSide ? disable(2884) : enable(2884);
  18644. var flipSided = material.side === BackSide;
  18645. if (frontFaceCW) flipSided = !flipSided;
  18646. setFlipSided(flipSided);
  18647. material.blending === NormalBlending && material.transparent === false ? setBlending(NoBlending) : setBlending(material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha);
  18648. depthBuffer.setFunc(material.depthFunc);
  18649. depthBuffer.setTest(material.depthTest);
  18650. depthBuffer.setMask(material.depthWrite);
  18651. colorBuffer.setMask(material.colorWrite);
  18652. var stencilWrite = material.stencilWrite;
  18653. stencilBuffer.setTest(stencilWrite);
  18654. if (stencilWrite) {
  18655. stencilBuffer.setMask(material.stencilWriteMask);
  18656. stencilBuffer.setFunc(material.stencilFunc, material.stencilRef, material.stencilFuncMask);
  18657. stencilBuffer.setOp(material.stencilFail, material.stencilZFail, material.stencilZPass);
  18658. }
  18659. setPolygonOffset(material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits);
  18660. } //
  18661. function setFlipSided(flipSided) {
  18662. if (currentFlipSided !== flipSided) {
  18663. if (flipSided) {
  18664. gl.frontFace(2304);
  18665. } else {
  18666. gl.frontFace(2305);
  18667. }
  18668. currentFlipSided = flipSided;
  18669. }
  18670. }
  18671. function setCullFace(cullFace) {
  18672. if (cullFace !== CullFaceNone) {
  18673. enable(2884);
  18674. if (cullFace !== currentCullFace) {
  18675. if (cullFace === CullFaceBack) {
  18676. gl.cullFace(1029);
  18677. } else if (cullFace === CullFaceFront) {
  18678. gl.cullFace(1028);
  18679. } else {
  18680. gl.cullFace(1032);
  18681. }
  18682. }
  18683. } else {
  18684. disable(2884);
  18685. }
  18686. currentCullFace = cullFace;
  18687. }
  18688. function setLineWidth(width) {
  18689. if (width !== currentLineWidth) {
  18690. if (lineWidthAvailable) gl.lineWidth(width);
  18691. currentLineWidth = width;
  18692. }
  18693. }
  18694. function setPolygonOffset(polygonOffset, factor, units) {
  18695. if (polygonOffset) {
  18696. enable(32823);
  18697. if (currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units) {
  18698. gl.polygonOffset(factor, units);
  18699. currentPolygonOffsetFactor = factor;
  18700. currentPolygonOffsetUnits = units;
  18701. }
  18702. } else {
  18703. disable(32823);
  18704. }
  18705. }
  18706. function setScissorTest(scissorTest) {
  18707. if (scissorTest) {
  18708. enable(3089);
  18709. } else {
  18710. disable(3089);
  18711. }
  18712. } // texture
  18713. function activeTexture(webglSlot) {
  18714. if (webglSlot === undefined) webglSlot = 33984 + maxTextures - 1;
  18715. if (currentTextureSlot !== webglSlot) {
  18716. gl.activeTexture(webglSlot);
  18717. currentTextureSlot = webglSlot;
  18718. }
  18719. }
  18720. function bindTexture(webglType, webglTexture) {
  18721. if (currentTextureSlot === null) {
  18722. activeTexture();
  18723. }
  18724. var boundTexture = currentBoundTextures[currentTextureSlot];
  18725. if (boundTexture === undefined) {
  18726. boundTexture = {
  18727. type: undefined,
  18728. texture: undefined
  18729. };
  18730. currentBoundTextures[currentTextureSlot] = boundTexture;
  18731. }
  18732. if (boundTexture.type !== webglType || boundTexture.texture !== webglTexture) {
  18733. gl.bindTexture(webglType, webglTexture || emptyTextures[webglType]);
  18734. boundTexture.type = webglType;
  18735. boundTexture.texture = webglTexture;
  18736. }
  18737. }
  18738. function unbindTexture() {
  18739. var boundTexture = currentBoundTextures[currentTextureSlot];
  18740. if (boundTexture !== undefined && boundTexture.type !== undefined) {
  18741. gl.bindTexture(boundTexture.type, null);
  18742. boundTexture.type = undefined;
  18743. boundTexture.texture = undefined;
  18744. }
  18745. }
  18746. function compressedTexImage2D() {
  18747. try {
  18748. gl.compressedTexImage2D.apply(gl, arguments);
  18749. } catch (error) {
  18750. console.error('THREE.WebGLState:', error);
  18751. }
  18752. }
  18753. function texImage2D() {
  18754. try {
  18755. gl.texImage2D.apply(gl, arguments);
  18756. } catch (error) {
  18757. console.error('THREE.WebGLState:', error);
  18758. }
  18759. }
  18760. function texImage3D() {
  18761. try {
  18762. gl.texImage3D.apply(gl, arguments);
  18763. } catch (error) {
  18764. console.error('THREE.WebGLState:', error);
  18765. }
  18766. } //
  18767. function scissor(scissor) {
  18768. if (currentScissor.equals(scissor) === false) {
  18769. gl.scissor(scissor.x, scissor.y, scissor.z, scissor.w);
  18770. currentScissor.copy(scissor);
  18771. }
  18772. }
  18773. function viewport(viewport) {
  18774. if (currentViewport.equals(viewport) === false) {
  18775. gl.viewport(viewport.x, viewport.y, viewport.z, viewport.w);
  18776. currentViewport.copy(viewport);
  18777. }
  18778. } //
  18779. function reset() {
  18780. enabledCapabilities = {};
  18781. currentTextureSlot = null;
  18782. currentBoundTextures = {};
  18783. currentProgram = null;
  18784. currentBlendingEnabled = null;
  18785. currentBlending = null;
  18786. currentBlendEquation = null;
  18787. currentBlendSrc = null;
  18788. currentBlendDst = null;
  18789. currentBlendEquationAlpha = null;
  18790. currentBlendSrcAlpha = null;
  18791. currentBlendDstAlpha = null;
  18792. currentPremultipledAlpha = false;
  18793. currentFlipSided = null;
  18794. currentCullFace = null;
  18795. currentLineWidth = null;
  18796. currentPolygonOffsetFactor = null;
  18797. currentPolygonOffsetUnits = null;
  18798. colorBuffer.reset();
  18799. depthBuffer.reset();
  18800. stencilBuffer.reset();
  18801. }
  18802. return {
  18803. buffers: {
  18804. color: colorBuffer,
  18805. depth: depthBuffer,
  18806. stencil: stencilBuffer
  18807. },
  18808. enable: enable,
  18809. disable: disable,
  18810. useProgram: useProgram,
  18811. setBlending: setBlending,
  18812. setMaterial: setMaterial,
  18813. setFlipSided: setFlipSided,
  18814. setCullFace: setCullFace,
  18815. setLineWidth: setLineWidth,
  18816. setPolygonOffset: setPolygonOffset,
  18817. setScissorTest: setScissorTest,
  18818. activeTexture: activeTexture,
  18819. bindTexture: bindTexture,
  18820. unbindTexture: unbindTexture,
  18821. compressedTexImage2D: compressedTexImage2D,
  18822. texImage2D: texImage2D,
  18823. texImage3D: texImage3D,
  18824. scissor: scissor,
  18825. viewport: viewport,
  18826. reset: reset
  18827. };
  18828. }
  18829. function WebGLTextures(_gl, extensions, state, properties, capabilities, utils, info) {
  18830. var _wrappingToGL, _filterToGL;
  18831. var isWebGL2 = capabilities.isWebGL2;
  18832. var maxTextures = capabilities.maxTextures;
  18833. var maxCubemapSize = capabilities.maxCubemapSize;
  18834. var maxTextureSize = capabilities.maxTextureSize;
  18835. var maxSamples = capabilities.maxSamples;
  18836. var _videoTextures = new WeakMap();
  18837. var _canvas; // cordova iOS (as of 5.0) still uses UIWebView, which provides OffscreenCanvas,
  18838. // also OffscreenCanvas.getContext("webgl"), but not OffscreenCanvas.getContext("2d")!
  18839. // Some implementations may only implement OffscreenCanvas partially (e.g. lacking 2d).
  18840. var useOffscreenCanvas = false;
  18841. try {
  18842. useOffscreenCanvas = typeof OffscreenCanvas !== 'undefined' && new OffscreenCanvas(1, 1).getContext('2d') !== null;
  18843. } catch (err) {// Ignore any errors
  18844. }
  18845. function createCanvas(width, height) {
  18846. // Use OffscreenCanvas when available. Specially needed in web workers
  18847. return useOffscreenCanvas ? new OffscreenCanvas(width, height) : document.createElementNS('http://www.w3.org/1999/xhtml', 'canvas');
  18848. }
  18849. function resizeImage(image, needsPowerOfTwo, needsNewCanvas, maxSize) {
  18850. var scale = 1; // handle case if texture exceeds max size
  18851. if (image.width > maxSize || image.height > maxSize) {
  18852. scale = maxSize / Math.max(image.width, image.height);
  18853. } // only perform resize if necessary
  18854. if (scale < 1 || needsPowerOfTwo === true) {
  18855. // only perform resize for certain image types
  18856. if (typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement || typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement || typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap) {
  18857. var floor = needsPowerOfTwo ? MathUtils.floorPowerOfTwo : Math.floor;
  18858. var width = floor(scale * image.width);
  18859. var height = floor(scale * image.height);
  18860. if (_canvas === undefined) _canvas = createCanvas(width, height); // cube textures can't reuse the same canvas
  18861. var canvas = needsNewCanvas ? createCanvas(width, height) : _canvas;
  18862. canvas.width = width;
  18863. canvas.height = height;
  18864. var context = canvas.getContext('2d');
  18865. context.drawImage(image, 0, 0, width, height);
  18866. console.warn('THREE.WebGLRenderer: Texture has been resized from (' + image.width + 'x' + image.height + ') to (' + width + 'x' + height + ').');
  18867. return canvas;
  18868. } else {
  18869. if ('data' in image) {
  18870. console.warn('THREE.WebGLRenderer: Image in DataTexture is too big (' + image.width + 'x' + image.height + ').');
  18871. }
  18872. return image;
  18873. }
  18874. }
  18875. return image;
  18876. }
  18877. function isPowerOfTwo(image) {
  18878. return MathUtils.isPowerOfTwo(image.width) && MathUtils.isPowerOfTwo(image.height);
  18879. }
  18880. function textureNeedsPowerOfTwo(texture) {
  18881. if (isWebGL2) return false;
  18882. return texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping || texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter;
  18883. }
  18884. function textureNeedsGenerateMipmaps(texture, supportsMips) {
  18885. return texture.generateMipmaps && supportsMips && texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter;
  18886. }
  18887. function generateMipmap(target, texture, width, height) {
  18888. _gl.generateMipmap(target);
  18889. var textureProperties = properties.get(texture); // Note: Math.log( x ) * Math.LOG2E used instead of Math.log2( x ) which is not supported by IE11
  18890. textureProperties.__maxMipLevel = Math.log(Math.max(width, height)) * Math.LOG2E;
  18891. }
  18892. function getInternalFormat(internalFormatName, glFormat, glType) {
  18893. if (isWebGL2 === false) return glFormat;
  18894. if (internalFormatName !== null) {
  18895. if (_gl[internalFormatName] !== undefined) return _gl[internalFormatName];
  18896. console.warn('THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'');
  18897. }
  18898. var internalFormat = glFormat;
  18899. if (glFormat === 6403) {
  18900. if (glType === 5126) internalFormat = 33326;
  18901. if (glType === 5131) internalFormat = 33325;
  18902. if (glType === 5121) internalFormat = 33321;
  18903. }
  18904. if (glFormat === 6407) {
  18905. if (glType === 5126) internalFormat = 34837;
  18906. if (glType === 5131) internalFormat = 34843;
  18907. if (glType === 5121) internalFormat = 32849;
  18908. }
  18909. if (glFormat === 6408) {
  18910. if (glType === 5126) internalFormat = 34836;
  18911. if (glType === 5131) internalFormat = 34842;
  18912. if (glType === 5121) internalFormat = 32856;
  18913. }
  18914. if (internalFormat === 33325 || internalFormat === 33326 || internalFormat === 34842 || internalFormat === 34836) {
  18915. extensions.get('EXT_color_buffer_float');
  18916. }
  18917. return internalFormat;
  18918. } // Fallback filters for non-power-of-2 textures
  18919. function filterFallback(f) {
  18920. if (f === NearestFilter || f === NearestMipmapNearestFilter || f === NearestMipmapLinearFilter) {
  18921. return 9728;
  18922. }
  18923. return 9729;
  18924. } //
  18925. function onTextureDispose(event) {
  18926. var texture = event.target;
  18927. texture.removeEventListener('dispose', onTextureDispose);
  18928. deallocateTexture(texture);
  18929. if (texture.isVideoTexture) {
  18930. _videoTextures.delete(texture);
  18931. }
  18932. info.memory.textures--;
  18933. }
  18934. function onRenderTargetDispose(event) {
  18935. var renderTarget = event.target;
  18936. renderTarget.removeEventListener('dispose', onRenderTargetDispose);
  18937. deallocateRenderTarget(renderTarget);
  18938. info.memory.textures--;
  18939. } //
  18940. function deallocateTexture(texture) {
  18941. var textureProperties = properties.get(texture);
  18942. if (textureProperties.__webglInit === undefined) return;
  18943. _gl.deleteTexture(textureProperties.__webglTexture);
  18944. properties.remove(texture);
  18945. }
  18946. function deallocateRenderTarget(renderTarget) {
  18947. var renderTargetProperties = properties.get(renderTarget);
  18948. var textureProperties = properties.get(renderTarget.texture);
  18949. if (!renderTarget) return;
  18950. if (textureProperties.__webglTexture !== undefined) {
  18951. _gl.deleteTexture(textureProperties.__webglTexture);
  18952. }
  18953. if (renderTarget.depthTexture) {
  18954. renderTarget.depthTexture.dispose();
  18955. }
  18956. if (renderTarget.isWebGLCubeRenderTarget) {
  18957. for (var i = 0; i < 6; i++) {
  18958. _gl.deleteFramebuffer(renderTargetProperties.__webglFramebuffer[i]);
  18959. if (renderTargetProperties.__webglDepthbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglDepthbuffer[i]);
  18960. }
  18961. } else {
  18962. _gl.deleteFramebuffer(renderTargetProperties.__webglFramebuffer);
  18963. if (renderTargetProperties.__webglDepthbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglDepthbuffer);
  18964. if (renderTargetProperties.__webglMultisampledFramebuffer) _gl.deleteFramebuffer(renderTargetProperties.__webglMultisampledFramebuffer);
  18965. if (renderTargetProperties.__webglColorRenderbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglColorRenderbuffer);
  18966. if (renderTargetProperties.__webglDepthRenderbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglDepthRenderbuffer);
  18967. }
  18968. properties.remove(renderTarget.texture);
  18969. properties.remove(renderTarget);
  18970. } //
  18971. var textureUnits = 0;
  18972. function resetTextureUnits() {
  18973. textureUnits = 0;
  18974. }
  18975. function allocateTextureUnit() {
  18976. var textureUnit = textureUnits;
  18977. if (textureUnit >= maxTextures) {
  18978. console.warn('THREE.WebGLTextures: Trying to use ' + textureUnit + ' texture units while this GPU supports only ' + maxTextures);
  18979. }
  18980. textureUnits += 1;
  18981. return textureUnit;
  18982. } //
  18983. function setTexture2D(texture, slot) {
  18984. var textureProperties = properties.get(texture);
  18985. if (texture.isVideoTexture) updateVideoTexture(texture);
  18986. if (texture.version > 0 && textureProperties.__version !== texture.version) {
  18987. var image = texture.image;
  18988. if (image === undefined) {
  18989. console.warn('THREE.WebGLRenderer: Texture marked for update but image is undefined');
  18990. } else if (image.complete === false) {
  18991. console.warn('THREE.WebGLRenderer: Texture marked for update but image is incomplete');
  18992. } else {
  18993. uploadTexture(textureProperties, texture, slot);
  18994. return;
  18995. }
  18996. }
  18997. state.activeTexture(33984 + slot);
  18998. state.bindTexture(3553, textureProperties.__webglTexture);
  18999. }
  19000. function setTexture2DArray(texture, slot) {
  19001. var textureProperties = properties.get(texture);
  19002. if (texture.version > 0 && textureProperties.__version !== texture.version) {
  19003. uploadTexture(textureProperties, texture, slot);
  19004. return;
  19005. }
  19006. state.activeTexture(33984 + slot);
  19007. state.bindTexture(35866, textureProperties.__webglTexture);
  19008. }
  19009. function setTexture3D(texture, slot) {
  19010. var textureProperties = properties.get(texture);
  19011. if (texture.version > 0 && textureProperties.__version !== texture.version) {
  19012. uploadTexture(textureProperties, texture, slot);
  19013. return;
  19014. }
  19015. state.activeTexture(33984 + slot);
  19016. state.bindTexture(32879, textureProperties.__webglTexture);
  19017. }
  19018. function setTextureCube(texture, slot) {
  19019. var textureProperties = properties.get(texture);
  19020. if (texture.version > 0 && textureProperties.__version !== texture.version) {
  19021. uploadCubeTexture(textureProperties, texture, slot);
  19022. return;
  19023. }
  19024. state.activeTexture(33984 + slot);
  19025. state.bindTexture(34067, textureProperties.__webglTexture);
  19026. }
  19027. var wrappingToGL = (_wrappingToGL = {}, _wrappingToGL[RepeatWrapping] = 10497, _wrappingToGL[ClampToEdgeWrapping] = 33071, _wrappingToGL[MirroredRepeatWrapping] = 33648, _wrappingToGL);
  19028. var filterToGL = (_filterToGL = {}, _filterToGL[NearestFilter] = 9728, _filterToGL[NearestMipmapNearestFilter] = 9984, _filterToGL[NearestMipmapLinearFilter] = 9986, _filterToGL[LinearFilter] = 9729, _filterToGL[LinearMipmapNearestFilter] = 9985, _filterToGL[LinearMipmapLinearFilter] = 9987, _filterToGL);
  19029. function setTextureParameters(textureType, texture, supportsMips) {
  19030. if (supportsMips) {
  19031. _gl.texParameteri(textureType, 10242, wrappingToGL[texture.wrapS]);
  19032. _gl.texParameteri(textureType, 10243, wrappingToGL[texture.wrapT]);
  19033. if (textureType === 32879 || textureType === 35866) {
  19034. _gl.texParameteri(textureType, 32882, wrappingToGL[texture.wrapR]);
  19035. }
  19036. _gl.texParameteri(textureType, 10240, filterToGL[texture.magFilter]);
  19037. _gl.texParameteri(textureType, 10241, filterToGL[texture.minFilter]);
  19038. } else {
  19039. _gl.texParameteri(textureType, 10242, 33071);
  19040. _gl.texParameteri(textureType, 10243, 33071);
  19041. if (textureType === 32879 || textureType === 35866) {
  19042. _gl.texParameteri(textureType, 32882, 33071);
  19043. }
  19044. if (texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping) {
  19045. console.warn('THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping.');
  19046. }
  19047. _gl.texParameteri(textureType, 10240, filterFallback(texture.magFilter));
  19048. _gl.texParameteri(textureType, 10241, filterFallback(texture.minFilter));
  19049. if (texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter) {
  19050. console.warn('THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.');
  19051. }
  19052. }
  19053. var extension = extensions.get('EXT_texture_filter_anisotropic');
  19054. if (extension) {
  19055. if (texture.type === FloatType && extensions.get('OES_texture_float_linear') === null) return;
  19056. if (texture.type === HalfFloatType && (isWebGL2 || extensions.get('OES_texture_half_float_linear')) === null) return;
  19057. if (texture.anisotropy > 1 || properties.get(texture).__currentAnisotropy) {
  19058. _gl.texParameterf(textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(texture.anisotropy, capabilities.getMaxAnisotropy()));
  19059. properties.get(texture).__currentAnisotropy = texture.anisotropy;
  19060. }
  19061. }
  19062. }
  19063. function initTexture(textureProperties, texture) {
  19064. if (textureProperties.__webglInit === undefined) {
  19065. textureProperties.__webglInit = true;
  19066. texture.addEventListener('dispose', onTextureDispose);
  19067. textureProperties.__webglTexture = _gl.createTexture();
  19068. info.memory.textures++;
  19069. }
  19070. }
  19071. function uploadTexture(textureProperties, texture, slot) {
  19072. var textureType = 3553;
  19073. if (texture.isDataTexture2DArray) textureType = 35866;
  19074. if (texture.isDataTexture3D) textureType = 32879;
  19075. initTexture(textureProperties, texture);
  19076. state.activeTexture(33984 + slot);
  19077. state.bindTexture(textureType, textureProperties.__webglTexture);
  19078. _gl.pixelStorei(37440, texture.flipY);
  19079. _gl.pixelStorei(37441, texture.premultiplyAlpha);
  19080. _gl.pixelStorei(3317, texture.unpackAlignment);
  19081. var needsPowerOfTwo = textureNeedsPowerOfTwo(texture) && isPowerOfTwo(texture.image) === false;
  19082. var image = resizeImage(texture.image, needsPowerOfTwo, false, maxTextureSize);
  19083. var supportsMips = isPowerOfTwo(image) || isWebGL2,
  19084. glFormat = utils.convert(texture.format);
  19085. var glType = utils.convert(texture.type),
  19086. glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType);
  19087. setTextureParameters(textureType, texture, supportsMips);
  19088. var mipmap;
  19089. var mipmaps = texture.mipmaps;
  19090. if (texture.isDepthTexture) {
  19091. // populate depth texture with dummy data
  19092. glInternalFormat = 6402;
  19093. if (isWebGL2) {
  19094. if (texture.type === FloatType) {
  19095. glInternalFormat = 36012;
  19096. } else if (texture.type === UnsignedIntType) {
  19097. glInternalFormat = 33190;
  19098. } else if (texture.type === UnsignedInt248Type) {
  19099. glInternalFormat = 35056;
  19100. } else {
  19101. glInternalFormat = 33189; // WebGL2 requires sized internalformat for glTexImage2D
  19102. }
  19103. } else {
  19104. if (texture.type === FloatType) {
  19105. console.error('WebGLRenderer: Floating point depth texture requires WebGL2.');
  19106. }
  19107. } // validation checks for WebGL 1
  19108. if (texture.format === DepthFormat && glInternalFormat === 6402) {
  19109. // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  19110. // DEPTH_COMPONENT and type is not UNSIGNED_SHORT or UNSIGNED_INT
  19111. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  19112. if (texture.type !== UnsignedShortType && texture.type !== UnsignedIntType) {
  19113. console.warn('THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture.');
  19114. texture.type = UnsignedShortType;
  19115. glType = utils.convert(texture.type);
  19116. }
  19117. }
  19118. if (texture.format === DepthStencilFormat && glInternalFormat === 6402) {
  19119. // Depth stencil textures need the DEPTH_STENCIL internal format
  19120. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  19121. glInternalFormat = 34041; // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  19122. // DEPTH_STENCIL and type is not UNSIGNED_INT_24_8_WEBGL.
  19123. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  19124. if (texture.type !== UnsignedInt248Type) {
  19125. console.warn('THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture.');
  19126. texture.type = UnsignedInt248Type;
  19127. glType = utils.convert(texture.type);
  19128. }
  19129. } //
  19130. state.texImage2D(3553, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, null);
  19131. } else if (texture.isDataTexture) {
  19132. // use manually created mipmaps if available
  19133. // if there are no manual mipmaps
  19134. // set 0 level mipmap and then use GL to generate other mipmap levels
  19135. if (mipmaps.length > 0 && supportsMips) {
  19136. for (var i = 0, il = mipmaps.length; i < il; i++) {
  19137. mipmap = mipmaps[i];
  19138. state.texImage2D(3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data);
  19139. }
  19140. texture.generateMipmaps = false;
  19141. textureProperties.__maxMipLevel = mipmaps.length - 1;
  19142. } else {
  19143. state.texImage2D(3553, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, image.data);
  19144. textureProperties.__maxMipLevel = 0;
  19145. }
  19146. } else if (texture.isCompressedTexture) {
  19147. for (var _i = 0, _il = mipmaps.length; _i < _il; _i++) {
  19148. mipmap = mipmaps[_i];
  19149. if (texture.format !== RGBAFormat && texture.format !== RGBFormat) {
  19150. if (glFormat !== null) {
  19151. state.compressedTexImage2D(3553, _i, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data);
  19152. } else {
  19153. console.warn('THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()');
  19154. }
  19155. } else {
  19156. state.texImage2D(3553, _i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data);
  19157. }
  19158. }
  19159. textureProperties.__maxMipLevel = mipmaps.length - 1;
  19160. } else if (texture.isDataTexture2DArray) {
  19161. state.texImage3D(35866, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data);
  19162. textureProperties.__maxMipLevel = 0;
  19163. } else if (texture.isDataTexture3D) {
  19164. state.texImage3D(32879, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data);
  19165. textureProperties.__maxMipLevel = 0;
  19166. } else {
  19167. // regular Texture (image, video, canvas)
  19168. // use manually created mipmaps if available
  19169. // if there are no manual mipmaps
  19170. // set 0 level mipmap and then use GL to generate other mipmap levels
  19171. if (mipmaps.length > 0 && supportsMips) {
  19172. for (var _i2 = 0, _il2 = mipmaps.length; _i2 < _il2; _i2++) {
  19173. mipmap = mipmaps[_i2];
  19174. state.texImage2D(3553, _i2, glInternalFormat, glFormat, glType, mipmap);
  19175. }
  19176. texture.generateMipmaps = false;
  19177. textureProperties.__maxMipLevel = mipmaps.length - 1;
  19178. } else {
  19179. state.texImage2D(3553, 0, glInternalFormat, glFormat, glType, image);
  19180. textureProperties.__maxMipLevel = 0;
  19181. }
  19182. }
  19183. if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
  19184. generateMipmap(textureType, texture, image.width, image.height);
  19185. }
  19186. textureProperties.__version = texture.version;
  19187. if (texture.onUpdate) texture.onUpdate(texture);
  19188. }
  19189. function uploadCubeTexture(textureProperties, texture, slot) {
  19190. if (texture.image.length !== 6) return;
  19191. initTexture(textureProperties, texture);
  19192. state.activeTexture(33984 + slot);
  19193. state.bindTexture(34067, textureProperties.__webglTexture);
  19194. _gl.pixelStorei(37440, texture.flipY);
  19195. _gl.pixelStorei(37441, texture.premultiplyAlpha);
  19196. _gl.pixelStorei(3317, texture.unpackAlignment);
  19197. var isCompressed = texture && (texture.isCompressedTexture || texture.image[0].isCompressedTexture);
  19198. var isDataTexture = texture.image[0] && texture.image[0].isDataTexture;
  19199. var cubeImage = [];
  19200. for (var i = 0; i < 6; i++) {
  19201. if (!isCompressed && !isDataTexture) {
  19202. cubeImage[i] = resizeImage(texture.image[i], false, true, maxCubemapSize);
  19203. } else {
  19204. cubeImage[i] = isDataTexture ? texture.image[i].image : texture.image[i];
  19205. }
  19206. }
  19207. var image = cubeImage[0],
  19208. supportsMips = isPowerOfTwo(image) || isWebGL2,
  19209. glFormat = utils.convert(texture.format),
  19210. glType = utils.convert(texture.type),
  19211. glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType);
  19212. setTextureParameters(34067, texture, supportsMips);
  19213. var mipmaps;
  19214. if (isCompressed) {
  19215. for (var _i3 = 0; _i3 < 6; _i3++) {
  19216. mipmaps = cubeImage[_i3].mipmaps;
  19217. for (var j = 0; j < mipmaps.length; j++) {
  19218. var mipmap = mipmaps[j];
  19219. if (texture.format !== RGBAFormat && texture.format !== RGBFormat) {
  19220. if (glFormat !== null) {
  19221. state.compressedTexImage2D(34069 + _i3, j, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data);
  19222. } else {
  19223. console.warn('THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()');
  19224. }
  19225. } else {
  19226. state.texImage2D(34069 + _i3, j, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data);
  19227. }
  19228. }
  19229. }
  19230. textureProperties.__maxMipLevel = mipmaps.length - 1;
  19231. } else {
  19232. mipmaps = texture.mipmaps;
  19233. for (var _i4 = 0; _i4 < 6; _i4++) {
  19234. if (isDataTexture) {
  19235. state.texImage2D(34069 + _i4, 0, glInternalFormat, cubeImage[_i4].width, cubeImage[_i4].height, 0, glFormat, glType, cubeImage[_i4].data);
  19236. for (var _j = 0; _j < mipmaps.length; _j++) {
  19237. var _mipmap = mipmaps[_j];
  19238. var mipmapImage = _mipmap.image[_i4].image;
  19239. state.texImage2D(34069 + _i4, _j + 1, glInternalFormat, mipmapImage.width, mipmapImage.height, 0, glFormat, glType, mipmapImage.data);
  19240. }
  19241. } else {
  19242. state.texImage2D(34069 + _i4, 0, glInternalFormat, glFormat, glType, cubeImage[_i4]);
  19243. for (var _j2 = 0; _j2 < mipmaps.length; _j2++) {
  19244. var _mipmap2 = mipmaps[_j2];
  19245. state.texImage2D(34069 + _i4, _j2 + 1, glInternalFormat, glFormat, glType, _mipmap2.image[_i4]);
  19246. }
  19247. }
  19248. }
  19249. textureProperties.__maxMipLevel = mipmaps.length;
  19250. }
  19251. if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
  19252. // We assume images for cube map have the same size.
  19253. generateMipmap(34067, texture, image.width, image.height);
  19254. }
  19255. textureProperties.__version = texture.version;
  19256. if (texture.onUpdate) texture.onUpdate(texture);
  19257. } // Render targets
  19258. // Setup storage for target texture and bind it to correct framebuffer
  19259. function setupFrameBufferTexture(framebuffer, renderTarget, attachment, textureTarget) {
  19260. var glFormat = utils.convert(renderTarget.texture.format);
  19261. var glType = utils.convert(renderTarget.texture.type);
  19262. var glInternalFormat = getInternalFormat(renderTarget.texture.internalFormat, glFormat, glType);
  19263. state.texImage2D(textureTarget, 0, glInternalFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null);
  19264. _gl.bindFramebuffer(36160, framebuffer);
  19265. _gl.framebufferTexture2D(36160, attachment, textureTarget, properties.get(renderTarget.texture).__webglTexture, 0);
  19266. _gl.bindFramebuffer(36160, null);
  19267. } // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  19268. function setupRenderBufferStorage(renderbuffer, renderTarget, isMultisample) {
  19269. _gl.bindRenderbuffer(36161, renderbuffer);
  19270. if (renderTarget.depthBuffer && !renderTarget.stencilBuffer) {
  19271. var glInternalFormat = 33189;
  19272. if (isMultisample) {
  19273. var depthTexture = renderTarget.depthTexture;
  19274. if (depthTexture && depthTexture.isDepthTexture) {
  19275. if (depthTexture.type === FloatType) {
  19276. glInternalFormat = 36012;
  19277. } else if (depthTexture.type === UnsignedIntType) {
  19278. glInternalFormat = 33190;
  19279. }
  19280. }
  19281. var samples = getRenderTargetSamples(renderTarget);
  19282. _gl.renderbufferStorageMultisample(36161, samples, glInternalFormat, renderTarget.width, renderTarget.height);
  19283. } else {
  19284. _gl.renderbufferStorage(36161, glInternalFormat, renderTarget.width, renderTarget.height);
  19285. }
  19286. _gl.framebufferRenderbuffer(36160, 36096, 36161, renderbuffer);
  19287. } else if (renderTarget.depthBuffer && renderTarget.stencilBuffer) {
  19288. if (isMultisample) {
  19289. var _samples = getRenderTargetSamples(renderTarget);
  19290. _gl.renderbufferStorageMultisample(36161, _samples, 35056, renderTarget.width, renderTarget.height);
  19291. } else {
  19292. _gl.renderbufferStorage(36161, 34041, renderTarget.width, renderTarget.height);
  19293. }
  19294. _gl.framebufferRenderbuffer(36160, 33306, 36161, renderbuffer);
  19295. } else {
  19296. var glFormat = utils.convert(renderTarget.texture.format);
  19297. var glType = utils.convert(renderTarget.texture.type);
  19298. var _glInternalFormat = getInternalFormat(renderTarget.texture.internalFormat, glFormat, glType);
  19299. if (isMultisample) {
  19300. var _samples2 = getRenderTargetSamples(renderTarget);
  19301. _gl.renderbufferStorageMultisample(36161, _samples2, _glInternalFormat, renderTarget.width, renderTarget.height);
  19302. } else {
  19303. _gl.renderbufferStorage(36161, _glInternalFormat, renderTarget.width, renderTarget.height);
  19304. }
  19305. }
  19306. _gl.bindRenderbuffer(36161, null);
  19307. } // Setup resources for a Depth Texture for a FBO (needs an extension)
  19308. function setupDepthTexture(framebuffer, renderTarget) {
  19309. var isCube = renderTarget && renderTarget.isWebGLCubeRenderTarget;
  19310. if (isCube) throw new Error('Depth Texture with cube render targets is not supported');
  19311. _gl.bindFramebuffer(36160, framebuffer);
  19312. if (!(renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture)) {
  19313. throw new Error('renderTarget.depthTexture must be an instance of THREE.DepthTexture');
  19314. } // upload an empty depth texture with framebuffer size
  19315. if (!properties.get(renderTarget.depthTexture).__webglTexture || renderTarget.depthTexture.image.width !== renderTarget.width || renderTarget.depthTexture.image.height !== renderTarget.height) {
  19316. renderTarget.depthTexture.image.width = renderTarget.width;
  19317. renderTarget.depthTexture.image.height = renderTarget.height;
  19318. renderTarget.depthTexture.needsUpdate = true;
  19319. }
  19320. setTexture2D(renderTarget.depthTexture, 0);
  19321. var webglDepthTexture = properties.get(renderTarget.depthTexture).__webglTexture;
  19322. if (renderTarget.depthTexture.format === DepthFormat) {
  19323. _gl.framebufferTexture2D(36160, 36096, 3553, webglDepthTexture, 0);
  19324. } else if (renderTarget.depthTexture.format === DepthStencilFormat) {
  19325. _gl.framebufferTexture2D(36160, 33306, 3553, webglDepthTexture, 0);
  19326. } else {
  19327. throw new Error('Unknown depthTexture format');
  19328. }
  19329. } // Setup GL resources for a non-texture depth buffer
  19330. function setupDepthRenderbuffer(renderTarget) {
  19331. var renderTargetProperties = properties.get(renderTarget);
  19332. var isCube = renderTarget.isWebGLCubeRenderTarget === true;
  19333. if (renderTarget.depthTexture) {
  19334. if (isCube) throw new Error('target.depthTexture not supported in Cube render targets');
  19335. setupDepthTexture(renderTargetProperties.__webglFramebuffer, renderTarget);
  19336. } else {
  19337. if (isCube) {
  19338. renderTargetProperties.__webglDepthbuffer = [];
  19339. for (var i = 0; i < 6; i++) {
  19340. _gl.bindFramebuffer(36160, renderTargetProperties.__webglFramebuffer[i]);
  19341. renderTargetProperties.__webglDepthbuffer[i] = _gl.createRenderbuffer();
  19342. setupRenderBufferStorage(renderTargetProperties.__webglDepthbuffer[i], renderTarget, false);
  19343. }
  19344. } else {
  19345. _gl.bindFramebuffer(36160, renderTargetProperties.__webglFramebuffer);
  19346. renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer();
  19347. setupRenderBufferStorage(renderTargetProperties.__webglDepthbuffer, renderTarget, false);
  19348. }
  19349. }
  19350. _gl.bindFramebuffer(36160, null);
  19351. } // Set up GL resources for the render target
  19352. function setupRenderTarget(renderTarget) {
  19353. var renderTargetProperties = properties.get(renderTarget);
  19354. var textureProperties = properties.get(renderTarget.texture);
  19355. renderTarget.addEventListener('dispose', onRenderTargetDispose);
  19356. textureProperties.__webglTexture = _gl.createTexture();
  19357. info.memory.textures++;
  19358. var isCube = renderTarget.isWebGLCubeRenderTarget === true;
  19359. var isMultisample = renderTarget.isWebGLMultisampleRenderTarget === true;
  19360. var supportsMips = isPowerOfTwo(renderTarget) || isWebGL2; // Handles WebGL2 RGBFormat fallback - #18858
  19361. if (isWebGL2 && renderTarget.texture.format === RGBFormat && (renderTarget.texture.type === FloatType || renderTarget.texture.type === HalfFloatType)) {
  19362. renderTarget.texture.format = RGBAFormat;
  19363. console.warn('THREE.WebGLRenderer: Rendering to textures with RGB format is not supported. Using RGBA format instead.');
  19364. } // Setup framebuffer
  19365. if (isCube) {
  19366. renderTargetProperties.__webglFramebuffer = [];
  19367. for (var i = 0; i < 6; i++) {
  19368. renderTargetProperties.__webglFramebuffer[i] = _gl.createFramebuffer();
  19369. }
  19370. } else {
  19371. renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer();
  19372. if (isMultisample) {
  19373. if (isWebGL2) {
  19374. renderTargetProperties.__webglMultisampledFramebuffer = _gl.createFramebuffer();
  19375. renderTargetProperties.__webglColorRenderbuffer = _gl.createRenderbuffer();
  19376. _gl.bindRenderbuffer(36161, renderTargetProperties.__webglColorRenderbuffer);
  19377. var glFormat = utils.convert(renderTarget.texture.format);
  19378. var glType = utils.convert(renderTarget.texture.type);
  19379. var glInternalFormat = getInternalFormat(renderTarget.texture.internalFormat, glFormat, glType);
  19380. var samples = getRenderTargetSamples(renderTarget);
  19381. _gl.renderbufferStorageMultisample(36161, samples, glInternalFormat, renderTarget.width, renderTarget.height);
  19382. _gl.bindFramebuffer(36160, renderTargetProperties.__webglMultisampledFramebuffer);
  19383. _gl.framebufferRenderbuffer(36160, 36064, 36161, renderTargetProperties.__webglColorRenderbuffer);
  19384. _gl.bindRenderbuffer(36161, null);
  19385. if (renderTarget.depthBuffer) {
  19386. renderTargetProperties.__webglDepthRenderbuffer = _gl.createRenderbuffer();
  19387. setupRenderBufferStorage(renderTargetProperties.__webglDepthRenderbuffer, renderTarget, true);
  19388. }
  19389. _gl.bindFramebuffer(36160, null);
  19390. } else {
  19391. console.warn('THREE.WebGLRenderer: WebGLMultisampleRenderTarget can only be used with WebGL2.');
  19392. }
  19393. }
  19394. } // Setup color buffer
  19395. if (isCube) {
  19396. state.bindTexture(34067, textureProperties.__webglTexture);
  19397. setTextureParameters(34067, renderTarget.texture, supportsMips);
  19398. for (var _i5 = 0; _i5 < 6; _i5++) {
  19399. setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer[_i5], renderTarget, 36064, 34069 + _i5);
  19400. }
  19401. if (textureNeedsGenerateMipmaps(renderTarget.texture, supportsMips)) {
  19402. generateMipmap(34067, renderTarget.texture, renderTarget.width, renderTarget.height);
  19403. }
  19404. state.bindTexture(34067, null);
  19405. } else {
  19406. state.bindTexture(3553, textureProperties.__webglTexture);
  19407. setTextureParameters(3553, renderTarget.texture, supportsMips);
  19408. setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer, renderTarget, 36064, 3553);
  19409. if (textureNeedsGenerateMipmaps(renderTarget.texture, supportsMips)) {
  19410. generateMipmap(3553, renderTarget.texture, renderTarget.width, renderTarget.height);
  19411. }
  19412. state.bindTexture(3553, null);
  19413. } // Setup depth and stencil buffers
  19414. if (renderTarget.depthBuffer) {
  19415. setupDepthRenderbuffer(renderTarget);
  19416. }
  19417. }
  19418. function updateRenderTargetMipmap(renderTarget) {
  19419. var texture = renderTarget.texture;
  19420. var supportsMips = isPowerOfTwo(renderTarget) || isWebGL2;
  19421. if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
  19422. var target = renderTarget.isWebGLCubeRenderTarget ? 34067 : 3553;
  19423. var webglTexture = properties.get(texture).__webglTexture;
  19424. state.bindTexture(target, webglTexture);
  19425. generateMipmap(target, texture, renderTarget.width, renderTarget.height);
  19426. state.bindTexture(target, null);
  19427. }
  19428. }
  19429. function updateMultisampleRenderTarget(renderTarget) {
  19430. if (renderTarget.isWebGLMultisampleRenderTarget) {
  19431. if (isWebGL2) {
  19432. var renderTargetProperties = properties.get(renderTarget);
  19433. _gl.bindFramebuffer(36008, renderTargetProperties.__webglMultisampledFramebuffer);
  19434. _gl.bindFramebuffer(36009, renderTargetProperties.__webglFramebuffer);
  19435. var width = renderTarget.width;
  19436. var height = renderTarget.height;
  19437. var mask = 16384;
  19438. if (renderTarget.depthBuffer) mask |= 256;
  19439. if (renderTarget.stencilBuffer) mask |= 1024;
  19440. _gl.blitFramebuffer(0, 0, width, height, 0, 0, width, height, mask, 9728);
  19441. _gl.bindFramebuffer(36160, renderTargetProperties.__webglMultisampledFramebuffer); // see #18905
  19442. } else {
  19443. console.warn('THREE.WebGLRenderer: WebGLMultisampleRenderTarget can only be used with WebGL2.');
  19444. }
  19445. }
  19446. }
  19447. function getRenderTargetSamples(renderTarget) {
  19448. return isWebGL2 && renderTarget.isWebGLMultisampleRenderTarget ? Math.min(maxSamples, renderTarget.samples) : 0;
  19449. }
  19450. function updateVideoTexture(texture) {
  19451. var frame = info.render.frame; // Check the last frame we updated the VideoTexture
  19452. if (_videoTextures.get(texture) !== frame) {
  19453. _videoTextures.set(texture, frame);
  19454. texture.update();
  19455. }
  19456. } // backwards compatibility
  19457. var warnedTexture2D = false;
  19458. var warnedTextureCube = false;
  19459. function safeSetTexture2D(texture, slot) {
  19460. if (texture && texture.isWebGLRenderTarget) {
  19461. if (warnedTexture2D === false) {
  19462. console.warn('THREE.WebGLTextures.safeSetTexture2D: don\'t use render targets as textures. Use their .texture property instead.');
  19463. warnedTexture2D = true;
  19464. }
  19465. texture = texture.texture;
  19466. }
  19467. setTexture2D(texture, slot);
  19468. }
  19469. function safeSetTextureCube(texture, slot) {
  19470. if (texture && texture.isWebGLCubeRenderTarget) {
  19471. if (warnedTextureCube === false) {
  19472. console.warn('THREE.WebGLTextures.safeSetTextureCube: don\'t use cube render targets as textures. Use their .texture property instead.');
  19473. warnedTextureCube = true;
  19474. }
  19475. texture = texture.texture;
  19476. }
  19477. setTextureCube(texture, slot);
  19478. } //
  19479. this.allocateTextureUnit = allocateTextureUnit;
  19480. this.resetTextureUnits = resetTextureUnits;
  19481. this.setTexture2D = setTexture2D;
  19482. this.setTexture2DArray = setTexture2DArray;
  19483. this.setTexture3D = setTexture3D;
  19484. this.setTextureCube = setTextureCube;
  19485. this.setupRenderTarget = setupRenderTarget;
  19486. this.updateRenderTargetMipmap = updateRenderTargetMipmap;
  19487. this.updateMultisampleRenderTarget = updateMultisampleRenderTarget;
  19488. this.safeSetTexture2D = safeSetTexture2D;
  19489. this.safeSetTextureCube = safeSetTextureCube;
  19490. }
  19491. function WebGLUtils(gl, extensions, capabilities) {
  19492. var isWebGL2 = capabilities.isWebGL2;
  19493. function convert(p) {
  19494. var extension;
  19495. if (p === UnsignedByteType) return 5121;
  19496. if (p === UnsignedShort4444Type) return 32819;
  19497. if (p === UnsignedShort5551Type) return 32820;
  19498. if (p === UnsignedShort565Type) return 33635;
  19499. if (p === ByteType) return 5120;
  19500. if (p === ShortType) return 5122;
  19501. if (p === UnsignedShortType) return 5123;
  19502. if (p === IntType) return 5124;
  19503. if (p === UnsignedIntType) return 5125;
  19504. if (p === FloatType) return 5126;
  19505. if (p === HalfFloatType) {
  19506. if (isWebGL2) return 5131;
  19507. extension = extensions.get('OES_texture_half_float');
  19508. if (extension !== null) {
  19509. return extension.HALF_FLOAT_OES;
  19510. } else {
  19511. return null;
  19512. }
  19513. }
  19514. if (p === AlphaFormat) return 6406;
  19515. if (p === RGBFormat) return 6407;
  19516. if (p === RGBAFormat) return 6408;
  19517. if (p === LuminanceFormat) return 6409;
  19518. if (p === LuminanceAlphaFormat) return 6410;
  19519. if (p === DepthFormat) return 6402;
  19520. if (p === DepthStencilFormat) return 34041;
  19521. if (p === RedFormat) return 6403; // WebGL2 formats.
  19522. if (p === RedIntegerFormat) return 36244;
  19523. if (p === RGFormat) return 33319;
  19524. if (p === RGIntegerFormat) return 33320;
  19525. if (p === RGBIntegerFormat) return 36248;
  19526. if (p === RGBAIntegerFormat) return 36249;
  19527. if (p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format) {
  19528. extension = extensions.get('WEBGL_compressed_texture_s3tc');
  19529. if (extension !== null) {
  19530. if (p === RGB_S3TC_DXT1_Format) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  19531. if (p === RGBA_S3TC_DXT1_Format) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  19532. if (p === RGBA_S3TC_DXT3_Format) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  19533. if (p === RGBA_S3TC_DXT5_Format) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  19534. } else {
  19535. return null;
  19536. }
  19537. }
  19538. if (p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format) {
  19539. extension = extensions.get('WEBGL_compressed_texture_pvrtc');
  19540. if (extension !== null) {
  19541. if (p === RGB_PVRTC_4BPPV1_Format) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  19542. if (p === RGB_PVRTC_2BPPV1_Format) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  19543. if (p === RGBA_PVRTC_4BPPV1_Format) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  19544. if (p === RGBA_PVRTC_2BPPV1_Format) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  19545. } else {
  19546. return null;
  19547. }
  19548. }
  19549. if (p === RGB_ETC1_Format) {
  19550. extension = extensions.get('WEBGL_compressed_texture_etc1');
  19551. if (extension !== null) {
  19552. return extension.COMPRESSED_RGB_ETC1_WEBGL;
  19553. } else {
  19554. return null;
  19555. }
  19556. }
  19557. if (p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format) {
  19558. extension = extensions.get('WEBGL_compressed_texture_etc');
  19559. if (extension !== null) {
  19560. if (p === RGB_ETC2_Format) return extension.COMPRESSED_RGB8_ETC2;
  19561. if (p === RGBA_ETC2_EAC_Format) return extension.COMPRESSED_RGBA8_ETC2_EAC;
  19562. }
  19563. }
  19564. if (p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format || p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format || p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format || p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format || p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format || p === SRGB8_ALPHA8_ASTC_4x4_Format || p === SRGB8_ALPHA8_ASTC_5x4_Format || p === SRGB8_ALPHA8_ASTC_5x5_Format || p === SRGB8_ALPHA8_ASTC_6x5_Format || p === SRGB8_ALPHA8_ASTC_6x6_Format || p === SRGB8_ALPHA8_ASTC_8x5_Format || p === SRGB8_ALPHA8_ASTC_8x6_Format || p === SRGB8_ALPHA8_ASTC_8x8_Format || p === SRGB8_ALPHA8_ASTC_10x5_Format || p === SRGB8_ALPHA8_ASTC_10x6_Format || p === SRGB8_ALPHA8_ASTC_10x8_Format || p === SRGB8_ALPHA8_ASTC_10x10_Format || p === SRGB8_ALPHA8_ASTC_12x10_Format || p === SRGB8_ALPHA8_ASTC_12x12_Format) {
  19565. extension = extensions.get('WEBGL_compressed_texture_astc');
  19566. if (extension !== null) {
  19567. // TODO Complete?
  19568. return p;
  19569. } else {
  19570. return null;
  19571. }
  19572. }
  19573. if (p === RGBA_BPTC_Format) {
  19574. extension = extensions.get('EXT_texture_compression_bptc');
  19575. if (extension !== null) {
  19576. // TODO Complete?
  19577. return p;
  19578. } else {
  19579. return null;
  19580. }
  19581. }
  19582. if (p === UnsignedInt248Type) {
  19583. if (isWebGL2) return 34042;
  19584. extension = extensions.get('WEBGL_depth_texture');
  19585. if (extension !== null) {
  19586. return extension.UNSIGNED_INT_24_8_WEBGL;
  19587. } else {
  19588. return null;
  19589. }
  19590. }
  19591. }
  19592. return {
  19593. convert: convert
  19594. };
  19595. }
  19596. function Group() {
  19597. Object3D.call(this);
  19598. this.type = 'Group';
  19599. }
  19600. Group.prototype = Object.assign(Object.create(Object3D.prototype), {
  19601. constructor: Group,
  19602. isGroup: true
  19603. });
  19604. function ArrayCamera(array) {
  19605. if (array === void 0) {
  19606. array = [];
  19607. }
  19608. PerspectiveCamera.call(this);
  19609. this.cameras = array;
  19610. }
  19611. ArrayCamera.prototype = Object.assign(Object.create(PerspectiveCamera.prototype), {
  19612. constructor: ArrayCamera,
  19613. isArrayCamera: true
  19614. });
  19615. /**
  19616. * @author jsantell / https://www.jsantell.com/
  19617. * @author mrdoob / http://mrdoob.com/
  19618. */
  19619. var cameraLPos = new Vector3();
  19620. var cameraRPos = new Vector3();
  19621. /**
  19622. * Assumes 2 cameras that are parallel and share an X-axis, and that
  19623. * the cameras' projection and world matrices have already been set.
  19624. * And that near and far planes are identical for both cameras.
  19625. * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765
  19626. */
  19627. function setProjectionFromUnion(camera, cameraL, cameraR) {
  19628. cameraLPos.setFromMatrixPosition(cameraL.matrixWorld);
  19629. cameraRPos.setFromMatrixPosition(cameraR.matrixWorld);
  19630. var ipd = cameraLPos.distanceTo(cameraRPos);
  19631. var projL = cameraL.projectionMatrix.elements;
  19632. var projR = cameraR.projectionMatrix.elements; // VR systems will have identical far and near planes, and
  19633. // most likely identical top and bottom frustum extents.
  19634. // Use the left camera for these values.
  19635. var near = projL[14] / (projL[10] - 1);
  19636. var far = projL[14] / (projL[10] + 1);
  19637. var topFov = (projL[9] + 1) / projL[5];
  19638. var bottomFov = (projL[9] - 1) / projL[5];
  19639. var leftFov = (projL[8] - 1) / projL[0];
  19640. var rightFov = (projR[8] + 1) / projR[0];
  19641. var left = near * leftFov;
  19642. var right = near * rightFov; // Calculate the new camera's position offset from the
  19643. // left camera. xOffset should be roughly half `ipd`.
  19644. var zOffset = ipd / (-leftFov + rightFov);
  19645. var xOffset = zOffset * -leftFov; // TODO: Better way to apply this offset?
  19646. cameraL.matrixWorld.decompose(camera.position, camera.quaternion, camera.scale);
  19647. camera.translateX(xOffset);
  19648. camera.translateZ(zOffset);
  19649. camera.matrixWorld.compose(camera.position, camera.quaternion, camera.scale);
  19650. camera.matrixWorldInverse.getInverse(camera.matrixWorld); // Find the union of the frustum values of the cameras and scale
  19651. // the values so that the near plane's position does not change in world space,
  19652. // although must now be relative to the new union camera.
  19653. var near2 = near + zOffset;
  19654. var far2 = far + zOffset;
  19655. var left2 = left - xOffset;
  19656. var right2 = right + (ipd - xOffset);
  19657. var top2 = topFov * far / far2 * near2;
  19658. var bottom2 = bottomFov * far / far2 * near2;
  19659. camera.projectionMatrix.makePerspective(left2, right2, top2, bottom2, near2, far2);
  19660. }
  19661. /**
  19662. * @author mrdoob / http://mrdoob.com/
  19663. */
  19664. function WebVRManager(renderer) {
  19665. var renderWidth, renderHeight;
  19666. var scope = this;
  19667. var device = null;
  19668. var frameData = null;
  19669. var poseTarget = null;
  19670. var controllers = [];
  19671. var standingMatrix = new Matrix4();
  19672. var standingMatrixInverse = new Matrix4();
  19673. var framebufferScaleFactor = 1.0;
  19674. var referenceSpaceType = 'local-floor';
  19675. if (typeof window !== 'undefined' && 'VRFrameData' in window) {
  19676. frameData = new window.VRFrameData();
  19677. window.addEventListener('vrdisplaypresentchange', onVRDisplayPresentChange, false);
  19678. }
  19679. var matrixWorldInverse = new Matrix4();
  19680. var tempQuaternion = new Quaternion();
  19681. var tempPosition = new Vector3();
  19682. var cameraL = new PerspectiveCamera();
  19683. cameraL.viewport = new Vector4();
  19684. cameraL.layers.enable(1);
  19685. var cameraR = new PerspectiveCamera();
  19686. cameraR.viewport = new Vector4();
  19687. cameraR.layers.enable(2);
  19688. var cameraVR = new ArrayCamera([cameraL, cameraR]);
  19689. cameraVR.layers.enable(1);
  19690. cameraVR.layers.enable(2);
  19691. var currentSize = new Vector2(),
  19692. currentPixelRatio;
  19693. function onVRDisplayPresentChange() {
  19694. var isPresenting = scope.isPresenting = device !== null && device.isPresenting === true;
  19695. if (isPresenting) {
  19696. var eyeParameters = device.getEyeParameters('left');
  19697. renderWidth = 2 * eyeParameters.renderWidth * framebufferScaleFactor;
  19698. renderHeight = eyeParameters.renderHeight * framebufferScaleFactor;
  19699. currentPixelRatio = renderer.getPixelRatio();
  19700. renderer.getSize(currentSize);
  19701. renderer.setDrawingBufferSize(renderWidth, renderHeight, 1);
  19702. cameraL.viewport.set(0, 0, renderWidth / 2, renderHeight);
  19703. cameraR.viewport.set(renderWidth / 2, 0, renderWidth / 2, renderHeight);
  19704. animation.start();
  19705. scope.dispatchEvent({
  19706. type: 'sessionstart'
  19707. });
  19708. } else {
  19709. if (scope.enabled) {
  19710. renderer.setDrawingBufferSize(currentSize.width, currentSize.height, currentPixelRatio);
  19711. }
  19712. animation.stop();
  19713. scope.dispatchEvent({
  19714. type: 'sessionend'
  19715. });
  19716. }
  19717. } //
  19718. var triggers = [];
  19719. var grips = [];
  19720. function findGamepad(id) {
  19721. var gamepads = navigator.getGamepads && navigator.getGamepads();
  19722. for (var i = 0, l = gamepads.length; i < l; i++) {
  19723. var gamepad = gamepads[i];
  19724. if (gamepad && (gamepad.id === 'Daydream Controller' || gamepad.id === 'Gear VR Controller' || gamepad.id === 'Oculus Go Controller' || gamepad.id === 'OpenVR Gamepad' || gamepad.id.startsWith('Oculus Touch') || gamepad.id.startsWith('HTC Vive Focus') || gamepad.id.startsWith('Spatial Controller'))) {
  19725. var hand = gamepad.hand;
  19726. if (id === 0 && (hand === '' || hand === 'right')) return gamepad;
  19727. if (id === 1 && hand === 'left') return gamepad;
  19728. }
  19729. }
  19730. }
  19731. function updateControllers() {
  19732. for (var i = 0; i < controllers.length; i++) {
  19733. var controller = controllers[i];
  19734. var gamepad = findGamepad(i);
  19735. if (gamepad !== undefined && gamepad.pose !== undefined) {
  19736. if (gamepad.pose === null) return; // Pose
  19737. var pose = gamepad.pose;
  19738. if (pose.hasPosition === false) controller.position.set(0.2, -0.6, -0.05);
  19739. if (pose.position !== null) controller.position.fromArray(pose.position);
  19740. if (pose.orientation !== null) controller.quaternion.fromArray(pose.orientation);
  19741. controller.matrix.compose(controller.position, controller.quaternion, controller.scale);
  19742. controller.matrix.premultiply(standingMatrix);
  19743. controller.matrix.decompose(controller.position, controller.quaternion, controller.scale);
  19744. controller.matrixWorldNeedsUpdate = true;
  19745. controller.visible = true; // Trigger
  19746. var buttonId = gamepad.id === 'Daydream Controller' ? 0 : 1;
  19747. if (triggers[i] === undefined) triggers[i] = false;
  19748. if (triggers[i] !== gamepad.buttons[buttonId].pressed) {
  19749. triggers[i] = gamepad.buttons[buttonId].pressed;
  19750. if (triggers[i] === true) {
  19751. controller.dispatchEvent({
  19752. type: 'selectstart'
  19753. });
  19754. } else {
  19755. controller.dispatchEvent({
  19756. type: 'selectend'
  19757. });
  19758. controller.dispatchEvent({
  19759. type: 'select'
  19760. });
  19761. }
  19762. } // Grip
  19763. buttonId = 2;
  19764. if (grips[i] === undefined) grips[i] = false; // Skip if the grip button doesn't exist on this controller
  19765. if (gamepad.buttons[buttonId] !== undefined) {
  19766. if (grips[i] !== gamepad.buttons[buttonId].pressed) {
  19767. grips[i] = gamepad.buttons[buttonId].pressed;
  19768. if (grips[i] === true) {
  19769. controller.dispatchEvent({
  19770. type: 'squeezestart'
  19771. });
  19772. } else {
  19773. controller.dispatchEvent({
  19774. type: 'squeezeend'
  19775. });
  19776. controller.dispatchEvent({
  19777. type: 'squeeze'
  19778. });
  19779. }
  19780. }
  19781. }
  19782. } else {
  19783. controller.visible = false;
  19784. }
  19785. }
  19786. }
  19787. function updateViewportFromBounds(viewport, bounds) {
  19788. if (bounds !== null && bounds.length === 4) {
  19789. viewport.set(bounds[0] * renderWidth, bounds[1] * renderHeight, bounds[2] * renderWidth, bounds[3] * renderHeight);
  19790. }
  19791. } //
  19792. this.enabled = false;
  19793. this.getController = function (id) {
  19794. var controller = controllers[id];
  19795. if (controller === undefined) {
  19796. controller = new Group();
  19797. controller.matrixAutoUpdate = false;
  19798. controller.visible = false;
  19799. controllers[id] = controller;
  19800. }
  19801. return controller;
  19802. };
  19803. this.getDevice = function () {
  19804. return device;
  19805. };
  19806. this.setDevice = function (value) {
  19807. if (value !== undefined) device = value;
  19808. animation.setContext(value);
  19809. };
  19810. this.setFramebufferScaleFactor = function (value) {
  19811. framebufferScaleFactor = value;
  19812. };
  19813. this.setReferenceSpaceType = function (value) {
  19814. referenceSpaceType = value;
  19815. };
  19816. this.setPoseTarget = function (object) {
  19817. if (object !== undefined) poseTarget = object;
  19818. };
  19819. this.getCamera = function (camera) {
  19820. var userHeight = referenceSpaceType === 'local-floor' ? 1.6 : 0;
  19821. device.depthNear = camera.near;
  19822. device.depthFar = camera.far;
  19823. device.getFrameData(frameData); //
  19824. if (referenceSpaceType === 'local-floor') {
  19825. var stageParameters = device.stageParameters;
  19826. if (stageParameters) {
  19827. standingMatrix.fromArray(stageParameters.sittingToStandingTransform);
  19828. } else {
  19829. standingMatrix.makeTranslation(0, userHeight, 0);
  19830. }
  19831. }
  19832. var pose = frameData.pose;
  19833. var poseObject = poseTarget !== null ? poseTarget : camera; // We want to manipulate poseObject by its position and quaternion components since users may rely on them.
  19834. poseObject.matrix.copy(standingMatrix);
  19835. poseObject.matrix.decompose(poseObject.position, poseObject.quaternion, poseObject.scale);
  19836. if (pose.orientation !== null) {
  19837. tempQuaternion.fromArray(pose.orientation);
  19838. poseObject.quaternion.multiply(tempQuaternion);
  19839. }
  19840. if (pose.position !== null) {
  19841. tempQuaternion.setFromRotationMatrix(standingMatrix);
  19842. tempPosition.fromArray(pose.position);
  19843. tempPosition.applyQuaternion(tempQuaternion);
  19844. poseObject.position.add(tempPosition);
  19845. }
  19846. poseObject.updateMatrixWorld();
  19847. var children = poseObject.children;
  19848. for (var i = 0, l = children.length; i < l; i++) {
  19849. children[i].updateMatrixWorld(true);
  19850. } //
  19851. cameraL.near = camera.near;
  19852. cameraR.near = camera.near;
  19853. cameraL.far = camera.far;
  19854. cameraR.far = camera.far;
  19855. cameraL.matrixWorldInverse.fromArray(frameData.leftViewMatrix);
  19856. cameraR.matrixWorldInverse.fromArray(frameData.rightViewMatrix); // TODO (mrdoob) Double check this code
  19857. standingMatrixInverse.getInverse(standingMatrix);
  19858. if (referenceSpaceType === 'local-floor') {
  19859. cameraL.matrixWorldInverse.multiply(standingMatrixInverse);
  19860. cameraR.matrixWorldInverse.multiply(standingMatrixInverse);
  19861. }
  19862. var parent = poseObject.parent;
  19863. if (parent !== null) {
  19864. matrixWorldInverse.getInverse(parent.matrixWorld);
  19865. cameraL.matrixWorldInverse.multiply(matrixWorldInverse);
  19866. cameraR.matrixWorldInverse.multiply(matrixWorldInverse);
  19867. } // envMap and Mirror needs camera.matrixWorld
  19868. cameraL.matrixWorld.getInverse(cameraL.matrixWorldInverse);
  19869. cameraR.matrixWorld.getInverse(cameraR.matrixWorldInverse);
  19870. cameraL.projectionMatrix.fromArray(frameData.leftProjectionMatrix);
  19871. cameraR.projectionMatrix.fromArray(frameData.rightProjectionMatrix);
  19872. setProjectionFromUnion(cameraVR, cameraL, cameraR); //
  19873. var layers = device.getLayers();
  19874. if (layers.length) {
  19875. var layer = layers[0];
  19876. updateViewportFromBounds(cameraL.viewport, layer.leftBounds);
  19877. updateViewportFromBounds(cameraR.viewport, layer.rightBounds);
  19878. }
  19879. updateControllers();
  19880. return cameraVR;
  19881. };
  19882. this.getStandingMatrix = function () {
  19883. return standingMatrix;
  19884. };
  19885. this.isPresenting = false; // Animation Loop
  19886. var animation = new WebGLAnimation();
  19887. this.setAnimationLoop = function (callback) {
  19888. animation.setAnimationLoop(callback);
  19889. if (this.isPresenting) animation.start();
  19890. };
  19891. this.submitFrame = function () {
  19892. if (this.isPresenting) device.submitFrame();
  19893. };
  19894. this.dispose = function () {
  19895. if (typeof window !== 'undefined') {
  19896. window.removeEventListener('vrdisplaypresentchange', onVRDisplayPresentChange);
  19897. }
  19898. }; // DEPRECATED
  19899. this.setFrameOfReferenceType = function () {
  19900. console.warn('THREE.WebVRManager: setFrameOfReferenceType() has been deprecated.');
  19901. };
  19902. }
  19903. Object.assign(WebVRManager.prototype, EventDispatcher.prototype);
  19904. function WebXRController() {
  19905. this._targetRay = null;
  19906. this._grip = null;
  19907. this._hand = null;
  19908. }
  19909. Object.assign(WebXRController.prototype, {
  19910. constructor: WebXRController,
  19911. getHandSpace: function getHandSpace() {
  19912. if (this._hand === null) {
  19913. this._hand = new Group();
  19914. this._hand.matrixAutoUpdate = false;
  19915. this._hand.visible = false;
  19916. this._hand.joints = {};
  19917. this._hand.inputState = {
  19918. pinching: false
  19919. };
  19920. }
  19921. return this._hand;
  19922. },
  19923. getTargetRaySpace: function getTargetRaySpace() {
  19924. if (this._targetRay === null) {
  19925. this._targetRay = new Group();
  19926. this._targetRay.matrixAutoUpdate = false;
  19927. this._targetRay.visible = false;
  19928. }
  19929. return this._targetRay;
  19930. },
  19931. getGripSpace: function getGripSpace() {
  19932. if (this._grip === null) {
  19933. this._grip = new Group();
  19934. this._grip.matrixAutoUpdate = false;
  19935. this._grip.visible = false;
  19936. }
  19937. return this._grip;
  19938. },
  19939. dispatchEvent: function dispatchEvent(event) {
  19940. if (this._targetRay !== null) {
  19941. this._targetRay.dispatchEvent(event);
  19942. }
  19943. if (this._grip !== null) {
  19944. this._grip.dispatchEvent(event);
  19945. }
  19946. if (this._hand !== null) {
  19947. this._hand.dispatchEvent(event);
  19948. }
  19949. return this;
  19950. },
  19951. disconnect: function disconnect(inputSource) {
  19952. this.dispatchEvent({
  19953. type: 'disconnected',
  19954. data: inputSource
  19955. });
  19956. if (this._targetRay !== null) {
  19957. this._targetRay.visible = false;
  19958. }
  19959. if (this._grip !== null) {
  19960. this._grip.visible = false;
  19961. }
  19962. if (this._hand !== null) {
  19963. this._hand.visible = false;
  19964. }
  19965. return this;
  19966. },
  19967. update: function update(inputSource, frame, referenceSpace) {
  19968. var inputPose = null;
  19969. var gripPose = null;
  19970. var handPose = null;
  19971. var targetRay = this._targetRay;
  19972. var grip = this._grip;
  19973. var hand = this._hand;
  19974. if (inputSource && frame.session.visibilityState !== 'visible-blurred') {
  19975. if (hand && inputSource.hand) {
  19976. handPose = true;
  19977. for (var _iterator = _createForOfIteratorHelperLoose(inputSource.hand.values()), _step; !(_step = _iterator()).done;) {
  19978. var inputjoint = _step.value;
  19979. // Update the joints groups with the XRJoint poses
  19980. var jointPose = frame.getJointPose(inputjoint, referenceSpace);
  19981. if (hand.joints[inputjoint.jointName] === undefined) {
  19982. // The transform of this joint will be updated with the joint pose on each frame
  19983. var _joint = new Group();
  19984. _joint.matrixAutoUpdate = false;
  19985. _joint.visible = false;
  19986. hand.joints[inputjoint.jointName] = _joint; // ??
  19987. hand.add(_joint);
  19988. }
  19989. var joint = hand.joints[inputjoint.jointName];
  19990. if (jointPose !== null) {
  19991. joint.matrix.fromArray(jointPose.transform.matrix);
  19992. joint.matrix.decompose(joint.position, joint.rotation, joint.scale);
  19993. joint.jointRadius = jointPose.radius;
  19994. }
  19995. joint.visible = jointPose !== null;
  19996. } // Custom events
  19997. // Check pinchz
  19998. var indexTip = hand.joints['index-finger-tip'];
  19999. var thumbTip = hand.joints['thumb-tip'];
  20000. var distance = indexTip.position.distanceTo(thumbTip.position);
  20001. var distanceToPinch = 0.02;
  20002. var threshold = 0.005;
  20003. if (hand.inputState.pinching && distance > distanceToPinch + threshold) {
  20004. hand.inputState.pinching = false;
  20005. this.dispatchEvent({
  20006. type: 'pinchend',
  20007. handedness: inputSource.handedness,
  20008. target: this
  20009. });
  20010. } else if (!hand.inputState.pinching && distance <= distanceToPinch - threshold) {
  20011. hand.inputState.pinching = true;
  20012. this.dispatchEvent({
  20013. type: 'pinchstart',
  20014. handedness: inputSource.handedness,
  20015. target: this
  20016. });
  20017. }
  20018. } else {
  20019. if (targetRay !== null) {
  20020. inputPose = frame.getPose(inputSource.targetRaySpace, referenceSpace);
  20021. if (inputPose !== null) {
  20022. targetRay.matrix.fromArray(inputPose.transform.matrix);
  20023. targetRay.matrix.decompose(targetRay.position, targetRay.rotation, targetRay.scale);
  20024. }
  20025. }
  20026. if (grip !== null && inputSource.gripSpace) {
  20027. gripPose = frame.getPose(inputSource.gripSpace, referenceSpace);
  20028. if (gripPose !== null) {
  20029. grip.matrix.fromArray(gripPose.transform.matrix);
  20030. grip.matrix.decompose(grip.position, grip.rotation, grip.scale);
  20031. }
  20032. }
  20033. }
  20034. }
  20035. if (targetRay !== null) {
  20036. targetRay.visible = inputPose !== null;
  20037. }
  20038. if (grip !== null) {
  20039. grip.visible = gripPose !== null;
  20040. }
  20041. if (hand !== null) {
  20042. hand.visible = handPose !== null;
  20043. }
  20044. return this;
  20045. }
  20046. });
  20047. function WebXRManager(renderer, gl) {
  20048. var scope = this;
  20049. var session = null;
  20050. var framebufferScaleFactor = 1.0;
  20051. var referenceSpace = null;
  20052. var referenceSpaceType = 'local-floor';
  20053. var pose = null;
  20054. var poseTarget = null;
  20055. var controllers = [];
  20056. var inputSourcesMap = new Map();
  20057. var layers = [];
  20058. var baseLayer; //
  20059. var cameraL = new PerspectiveCamera();
  20060. cameraL.layers.enable(1);
  20061. cameraL.viewport = new Vector4();
  20062. var cameraR = new PerspectiveCamera();
  20063. cameraR.layers.enable(2);
  20064. cameraR.viewport = new Vector4();
  20065. var cameras = [cameraL, cameraR];
  20066. var cameraVR = new ArrayCamera();
  20067. cameraVR.layers.enable(1);
  20068. cameraVR.layers.enable(2);
  20069. var _currentDepthNear = null;
  20070. var _currentDepthFar = null; //
  20071. this.layersEnabled = false;
  20072. this.enabled = false;
  20073. this.isPresenting = false;
  20074. this.getCameraPose = function () {
  20075. return pose;
  20076. };
  20077. this.getController = function (index) {
  20078. var controller = controllers[index];
  20079. if (controller === undefined) {
  20080. controller = new WebXRController();
  20081. controllers[index] = controller;
  20082. }
  20083. return controller.getTargetRaySpace();
  20084. };
  20085. this.getControllerGrip = function (index) {
  20086. var controller = controllers[index];
  20087. if (controller === undefined) {
  20088. controller = new WebXRController();
  20089. controllers[index] = controller;
  20090. }
  20091. return controller.getGripSpace();
  20092. };
  20093. this.getHand = function (index) {
  20094. var controller = controllers[index];
  20095. if (controller === undefined) {
  20096. controller = new WebXRController();
  20097. controllers[index] = controller;
  20098. }
  20099. return controller.getHandSpace();
  20100. }; //
  20101. function onSessionEvent(event) {
  20102. var controller = inputSourcesMap.get(event.inputSource);
  20103. if (controller) {
  20104. controller.dispatchEvent({
  20105. type: event.type,
  20106. data: event.inputSource
  20107. });
  20108. }
  20109. }
  20110. function onSessionEnd() {
  20111. inputSourcesMap.forEach(function (controller, inputSource) {
  20112. controller.disconnect(inputSource);
  20113. });
  20114. inputSourcesMap.clear();
  20115. _currentDepthNear = null;
  20116. _currentDepthFar = null; //
  20117. renderer.setFramebuffer(null);
  20118. renderer.setRenderTarget(renderer.getRenderTarget()); // Hack #15830
  20119. animation.stop();
  20120. scope.isPresenting = false;
  20121. scope.dispatchEvent({
  20122. type: 'sessionend'
  20123. });
  20124. }
  20125. this.setFramebufferScaleFactor = function (value) {
  20126. framebufferScaleFactor = value;
  20127. if (scope.isPresenting === true) {
  20128. console.warn('THREE.WebXRManager: Cannot change framebuffer scale while presenting.');
  20129. }
  20130. };
  20131. this.setReferenceSpaceType = function (value) {
  20132. referenceSpaceType = value;
  20133. if (scope.isPresenting === true) {
  20134. console.warn('THREE.WebXRManager: Cannot change reference space type while presenting.');
  20135. }
  20136. };
  20137. this.getReferenceSpace = function () {
  20138. return referenceSpace;
  20139. };
  20140. this.getSession = function () {
  20141. return session;
  20142. };
  20143. this.setSession = /*#__PURE__*/function () {
  20144. var _ref = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(value) {
  20145. var attributes, layerInit;
  20146. return regeneratorRuntime.wrap(function _callee$(_context) {
  20147. while (1) {
  20148. switch (_context.prev = _context.next) {
  20149. case 0:
  20150. session = value;
  20151. if (!(session !== null)) {
  20152. _context.next = 24;
  20153. break;
  20154. }
  20155. session.addEventListener('select', onSessionEvent);
  20156. session.addEventListener('selectstart', onSessionEvent);
  20157. session.addEventListener('selectend', onSessionEvent);
  20158. session.addEventListener('squeeze', onSessionEvent);
  20159. session.addEventListener('squeezestart', onSessionEvent);
  20160. session.addEventListener('squeezeend', onSessionEvent);
  20161. session.addEventListener('end', onSessionEnd);
  20162. session.addEventListener('inputsourceschange', onInputSourcesChange);
  20163. attributes = gl.getContextAttributes();
  20164. if (!(attributes.xrCompatible !== true)) {
  20165. _context.next = 14;
  20166. break;
  20167. }
  20168. _context.next = 14;
  20169. return gl.makeXRCompatible();
  20170. case 14:
  20171. layerInit = {
  20172. antialias: attributes.antialias,
  20173. alpha: attributes.alpha,
  20174. depth: attributes.depth,
  20175. stencil: attributes.stencil,
  20176. framebufferScaleFactor: framebufferScaleFactor
  20177. }; // eslint-disable-next-line no-undef
  20178. baseLayer = new XRWebGLLayer(session, gl, layerInit);
  20179. if (window.XRWebGLBinding && this.layersEnabled) {
  20180. this.addLayer(baseLayer);
  20181. } else {
  20182. session.updateRenderState({
  20183. baseLayer: baseLayer
  20184. });
  20185. }
  20186. _context.next = 19;
  20187. return session.requestReferenceSpace(referenceSpaceType);
  20188. case 19:
  20189. referenceSpace = _context.sent;
  20190. animation.setContext(session);
  20191. animation.start();
  20192. scope.isPresenting = true;
  20193. scope.dispatchEvent({
  20194. type: 'sessionstart'
  20195. });
  20196. case 24:
  20197. case "end":
  20198. return _context.stop();
  20199. }
  20200. }
  20201. }, _callee, this);
  20202. }));
  20203. return function (_x) {
  20204. return _ref.apply(this, arguments);
  20205. };
  20206. }();
  20207. this.addLayer = function (layer) {
  20208. if (!window.XRWebGLBinding || !this.layersEnabled || !session) {
  20209. return;
  20210. }
  20211. layers.push(layer);
  20212. session.updateRenderState({
  20213. layers: layers
  20214. });
  20215. };
  20216. this.removeLayer = function (layer) {
  20217. if (!window.XRWebGLBinding || !this.layersEnabled || !session) {
  20218. return;
  20219. }
  20220. layers.splice(layers.indexOf(layer), 1);
  20221. session.updateRenderState({
  20222. layers: layers
  20223. });
  20224. };
  20225. function onInputSourcesChange(event) {
  20226. var inputSources = session.inputSources; // Assign inputSources to available controllers
  20227. for (var i = 0; i < controllers.length; i++) {
  20228. inputSourcesMap.set(inputSources[i], controllers[i]);
  20229. } // Notify disconnected
  20230. for (var _i = 0; _i < event.removed.length; _i++) {
  20231. var inputSource = event.removed[_i];
  20232. var controller = inputSourcesMap.get(inputSource);
  20233. if (controller) {
  20234. controller.dispatchEvent({
  20235. type: 'disconnected',
  20236. data: inputSource
  20237. });
  20238. inputSourcesMap.delete(inputSource);
  20239. }
  20240. } // Notify connected
  20241. for (var _i2 = 0; _i2 < event.added.length; _i2++) {
  20242. var _inputSource = event.added[_i2];
  20243. var _controller = inputSourcesMap.get(_inputSource);
  20244. if (_controller) {
  20245. _controller.dispatchEvent({
  20246. type: 'connected',
  20247. data: _inputSource
  20248. });
  20249. }
  20250. }
  20251. } //
  20252. var cameraLPos = new Vector3();
  20253. var cameraRPos = new Vector3();
  20254. /**
  20255. * Assumes 2 cameras that are parallel and share an X-axis, and that
  20256. * the cameras' projection and world matrices have already been set.
  20257. * And that near and far planes are identical for both cameras.
  20258. * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765
  20259. */
  20260. function setProjectionFromUnion(camera, cameraL, cameraR) {
  20261. cameraLPos.setFromMatrixPosition(cameraL.matrixWorld);
  20262. cameraRPos.setFromMatrixPosition(cameraR.matrixWorld);
  20263. var ipd = cameraLPos.distanceTo(cameraRPos);
  20264. var projL = cameraL.projectionMatrix.elements;
  20265. var projR = cameraR.projectionMatrix.elements; // VR systems will have identical far and near planes, and
  20266. // most likely identical top and bottom frustum extents.
  20267. // Use the left camera for these values.
  20268. var near = projL[14] / (projL[10] - 1);
  20269. var far = projL[14] / (projL[10] + 1);
  20270. var topFov = (projL[9] + 1) / projL[5];
  20271. var bottomFov = (projL[9] - 1) / projL[5];
  20272. var leftFov = (projL[8] - 1) / projL[0];
  20273. var rightFov = (projR[8] + 1) / projR[0];
  20274. var left = near * leftFov;
  20275. var right = near * rightFov; // Calculate the new camera's position offset from the
  20276. // left camera. xOffset should be roughly half `ipd`.
  20277. var zOffset = ipd / (-leftFov + rightFov);
  20278. var xOffset = zOffset * -leftFov; // TODO: Better way to apply this offset?
  20279. cameraL.matrixWorld.decompose(camera.position, camera.quaternion, camera.scale);
  20280. camera.translateX(xOffset);
  20281. camera.translateZ(zOffset);
  20282. camera.matrixWorld.compose(camera.position, camera.quaternion, camera.scale);
  20283. camera.matrixWorldInverse.copy(camera.matrixWorld).invert(); // Find the union of the frustum values of the cameras and scale
  20284. // the values so that the near plane's position does not change in world space,
  20285. // although must now be relative to the new union camera.
  20286. var near2 = near + zOffset;
  20287. var far2 = far + zOffset;
  20288. var left2 = left - xOffset;
  20289. var right2 = right + (ipd - xOffset);
  20290. var top2 = topFov * far / far2 * near2;
  20291. var bottom2 = bottomFov * far / far2 * near2;
  20292. camera.projectionMatrix.makePerspective(left2, right2, top2, bottom2, near2, far2);
  20293. }
  20294. function updateCamera(camera, parent) {
  20295. if (parent === null) {
  20296. camera.matrixWorld.copy(camera.matrix);
  20297. } else {
  20298. camera.matrixWorld.multiplyMatrices(parent.matrixWorld, camera.matrix);
  20299. }
  20300. camera.matrixWorldInverse.copy(camera.matrixWorld).invert();
  20301. }
  20302. this.setPoseTarget = function (object) {
  20303. if (object !== undefined) poseTarget = object;
  20304. };
  20305. this.getCamera = function (camera) {
  20306. cameraVR.near = cameraR.near = cameraL.near = camera.near;
  20307. cameraVR.far = cameraR.far = cameraL.far = camera.far;
  20308. if (_currentDepthNear !== cameraVR.near || _currentDepthFar !== cameraVR.far) {
  20309. // Note that the new renderState won't apply until the next frame. See #18320
  20310. session.updateRenderState({
  20311. depthNear: cameraVR.near,
  20312. depthFar: cameraVR.far
  20313. });
  20314. _currentDepthNear = cameraVR.near;
  20315. _currentDepthFar = cameraVR.far;
  20316. }
  20317. var parent = camera.parent;
  20318. var cameras = cameraVR.cameras;
  20319. var object = poseTarget || camera;
  20320. updateCamera(cameraVR, parent);
  20321. for (var i = 0; i < cameras.length; i++) {
  20322. updateCamera(cameras[i], parent);
  20323. } // update camera and its children
  20324. object.matrixWorld.copy(cameraVR.matrixWorld);
  20325. var children = object.children;
  20326. for (var _i3 = 0, l = children.length; _i3 < l; _i3++) {
  20327. children[_i3].updateMatrixWorld(true);
  20328. } // update projection matrix for proper view frustum culling
  20329. if (cameras.length === 2) {
  20330. setProjectionFromUnion(cameraVR, cameraL, cameraR);
  20331. } else {
  20332. // assume single camera setup (AR)
  20333. cameraVR.projectionMatrix.copy(cameraL.projectionMatrix);
  20334. }
  20335. return cameraVR;
  20336. }; // Animation Loop
  20337. var onAnimationFrameCallback = null;
  20338. function onAnimationFrame(time, frame) {
  20339. pose = frame.getViewerPose(referenceSpace);
  20340. if (pose !== null) {
  20341. var views = pose.views;
  20342. renderer.setFramebuffer(baseLayer.framebuffer);
  20343. var cameraVRNeedsUpdate = false; // check if it's necessary to rebuild cameraVR's camera list
  20344. if (views.length !== cameraVR.cameras.length) {
  20345. cameraVR.cameras.length = 0;
  20346. cameraVRNeedsUpdate = true;
  20347. }
  20348. for (var i = 0; i < views.length; i++) {
  20349. var view = views[i];
  20350. var viewport = baseLayer.getViewport(view);
  20351. var camera = cameras[i];
  20352. camera.matrix.fromArray(view.transform.matrix);
  20353. camera.projectionMatrix.fromArray(view.projectionMatrix);
  20354. camera.viewport.set(viewport.x, viewport.y, viewport.width, viewport.height);
  20355. if (i === 0) {
  20356. cameraVR.matrix.copy(camera.matrix);
  20357. }
  20358. if (cameraVRNeedsUpdate === true) {
  20359. cameraVR.cameras.push(camera);
  20360. }
  20361. }
  20362. } //
  20363. var inputSources = session.inputSources;
  20364. for (var _i4 = 0; _i4 < controllers.length; _i4++) {
  20365. var controller = controllers[_i4];
  20366. var inputSource = inputSources[_i4];
  20367. controller.update(inputSource, frame, referenceSpace);
  20368. }
  20369. if (onAnimationFrameCallback) onAnimationFrameCallback(time, frame);
  20370. }
  20371. var animation = new WebGLAnimation();
  20372. animation.setAnimationLoop(onAnimationFrame);
  20373. this.setAnimationLoop = function (callback) {
  20374. onAnimationFrameCallback = callback;
  20375. };
  20376. this.dispose = function () {};
  20377. }
  20378. Object.assign(WebXRManager.prototype, EventDispatcher.prototype);
  20379. function WebGLMaterials(properties) {
  20380. function refreshFogUniforms(uniforms, fog) {
  20381. uniforms.fogColor.value.copy(fog.color);
  20382. if (fog.isFog) {
  20383. uniforms.fogNear.value = fog.near;
  20384. uniforms.fogFar.value = fog.far;
  20385. } else if (fog.isFogExp2) {
  20386. uniforms.fogDensity.value = fog.density;
  20387. }
  20388. }
  20389. function refreshMaterialUniforms(uniforms, material, pixelRatio, height) {
  20390. if (material.isMeshBasicMaterial) {
  20391. refreshUniformsCommon(uniforms, material);
  20392. } else if (material.isMeshLambertMaterial) {
  20393. refreshUniformsCommon(uniforms, material);
  20394. refreshUniformsLambert(uniforms, material);
  20395. } else if (material.isMeshToonMaterial) {
  20396. refreshUniformsCommon(uniforms, material);
  20397. refreshUniformsToon(uniforms, material);
  20398. } else if (material.isMeshPhongMaterial) {
  20399. refreshUniformsCommon(uniforms, material);
  20400. refreshUniformsPhong(uniforms, material);
  20401. } else if (material.isMeshStandardMaterial) {
  20402. refreshUniformsCommon(uniforms, material);
  20403. if (material.isMeshPhysicalMaterial) {
  20404. refreshUniformsPhysical(uniforms, material);
  20405. } else {
  20406. refreshUniformsStandard(uniforms, material);
  20407. }
  20408. } else if (material.isMeshMatcapMaterial) {
  20409. refreshUniformsCommon(uniforms, material);
  20410. refreshUniformsMatcap(uniforms, material);
  20411. } else if (material.isMeshDepthMaterial) {
  20412. refreshUniformsCommon(uniforms, material);
  20413. refreshUniformsDepth(uniforms, material);
  20414. } else if (material.isMeshDistanceMaterial) {
  20415. refreshUniformsCommon(uniforms, material);
  20416. refreshUniformsDistance(uniforms, material);
  20417. } else if (material.isMeshNormalMaterial) {
  20418. refreshUniformsCommon(uniforms, material);
  20419. refreshUniformsNormal(uniforms, material);
  20420. } else if (material.isLineBasicMaterial) {
  20421. refreshUniformsLine(uniforms, material);
  20422. if (material.isLineDashedMaterial) {
  20423. refreshUniformsDash(uniforms, material);
  20424. }
  20425. } else if (material.isPointsMaterial) {
  20426. refreshUniformsPoints(uniforms, material, pixelRatio, height);
  20427. } else if (material.isSpriteMaterial) {
  20428. refreshUniformsSprites(uniforms, material);
  20429. } else if (material.isShadowMaterial) {
  20430. uniforms.color.value.copy(material.color);
  20431. uniforms.opacity.value = material.opacity;
  20432. } else if (material.isShaderMaterial) {
  20433. material.uniformsNeedUpdate = false; // #15581
  20434. }
  20435. }
  20436. function refreshUniformsCommon(uniforms, material) {
  20437. uniforms.opacity.value = material.opacity;
  20438. if (material.color) {
  20439. uniforms.diffuse.value.copy(material.color);
  20440. }
  20441. if (material.emissive) {
  20442. uniforms.emissive.value.copy(material.emissive).multiplyScalar(material.emissiveIntensity);
  20443. }
  20444. if (material.map) {
  20445. uniforms.map.value = material.map;
  20446. }
  20447. if (material.alphaMap) {
  20448. uniforms.alphaMap.value = material.alphaMap;
  20449. }
  20450. if (material.specularMap) {
  20451. uniforms.specularMap.value = material.specularMap;
  20452. }
  20453. var envMap = properties.get(material).envMap;
  20454. if (envMap) {
  20455. uniforms.envMap.value = envMap;
  20456. uniforms.flipEnvMap.value = envMap.isCubeTexture && envMap._needsFlipEnvMap ? -1 : 1;
  20457. uniforms.reflectivity.value = material.reflectivity;
  20458. uniforms.refractionRatio.value = material.refractionRatio;
  20459. var maxMipLevel = properties.get(envMap).__maxMipLevel;
  20460. if (maxMipLevel !== undefined) {
  20461. uniforms.maxMipLevel.value = maxMipLevel;
  20462. }
  20463. }
  20464. if (material.lightMap) {
  20465. uniforms.lightMap.value = material.lightMap;
  20466. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  20467. }
  20468. if (material.aoMap) {
  20469. uniforms.aoMap.value = material.aoMap;
  20470. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  20471. } // uv repeat and offset setting priorities
  20472. // 1. color map
  20473. // 2. specular map
  20474. // 3. displacementMap map
  20475. // 4. normal map
  20476. // 5. bump map
  20477. // 6. roughnessMap map
  20478. // 7. metalnessMap map
  20479. // 8. alphaMap map
  20480. // 9. emissiveMap map
  20481. // 10. clearcoat map
  20482. // 11. clearcoat normal map
  20483. // 12. clearcoat roughnessMap map
  20484. var uvScaleMap;
  20485. if (material.map) {
  20486. uvScaleMap = material.map;
  20487. } else if (material.specularMap) {
  20488. uvScaleMap = material.specularMap;
  20489. } else if (material.displacementMap) {
  20490. uvScaleMap = material.displacementMap;
  20491. } else if (material.normalMap) {
  20492. uvScaleMap = material.normalMap;
  20493. } else if (material.bumpMap) {
  20494. uvScaleMap = material.bumpMap;
  20495. } else if (material.roughnessMap) {
  20496. uvScaleMap = material.roughnessMap;
  20497. } else if (material.metalnessMap) {
  20498. uvScaleMap = material.metalnessMap;
  20499. } else if (material.alphaMap) {
  20500. uvScaleMap = material.alphaMap;
  20501. } else if (material.emissiveMap) {
  20502. uvScaleMap = material.emissiveMap;
  20503. } else if (material.clearcoatMap) {
  20504. uvScaleMap = material.clearcoatMap;
  20505. } else if (material.clearcoatNormalMap) {
  20506. uvScaleMap = material.clearcoatNormalMap;
  20507. } else if (material.clearcoatRoughnessMap) {
  20508. uvScaleMap = material.clearcoatRoughnessMap;
  20509. }
  20510. if (uvScaleMap !== undefined) {
  20511. // backwards compatibility
  20512. if (uvScaleMap.isWebGLRenderTarget) {
  20513. uvScaleMap = uvScaleMap.texture;
  20514. }
  20515. if (uvScaleMap.matrixAutoUpdate === true) {
  20516. uvScaleMap.updateMatrix();
  20517. }
  20518. uniforms.uvTransform.value.copy(uvScaleMap.matrix);
  20519. } // uv repeat and offset setting priorities for uv2
  20520. // 1. ao map
  20521. // 2. light map
  20522. var uv2ScaleMap;
  20523. if (material.aoMap) {
  20524. uv2ScaleMap = material.aoMap;
  20525. } else if (material.lightMap) {
  20526. uv2ScaleMap = material.lightMap;
  20527. }
  20528. if (uv2ScaleMap !== undefined) {
  20529. // backwards compatibility
  20530. if (uv2ScaleMap.isWebGLRenderTarget) {
  20531. uv2ScaleMap = uv2ScaleMap.texture;
  20532. }
  20533. if (uv2ScaleMap.matrixAutoUpdate === true) {
  20534. uv2ScaleMap.updateMatrix();
  20535. }
  20536. uniforms.uv2Transform.value.copy(uv2ScaleMap.matrix);
  20537. }
  20538. }
  20539. function refreshUniformsLine(uniforms, material) {
  20540. uniforms.diffuse.value.copy(material.color);
  20541. uniforms.opacity.value = material.opacity;
  20542. }
  20543. function refreshUniformsDash(uniforms, material) {
  20544. uniforms.dashSize.value = material.dashSize;
  20545. uniforms.totalSize.value = material.dashSize + material.gapSize;
  20546. uniforms.scale.value = material.scale;
  20547. }
  20548. function refreshUniformsPoints(uniforms, material, pixelRatio, height) {
  20549. uniforms.diffuse.value.copy(material.color);
  20550. uniforms.opacity.value = material.opacity;
  20551. uniforms.size.value = material.size * pixelRatio;
  20552. uniforms.scale.value = height * 0.5;
  20553. if (material.map) {
  20554. uniforms.map.value = material.map;
  20555. }
  20556. if (material.alphaMap) {
  20557. uniforms.alphaMap.value = material.alphaMap;
  20558. } // uv repeat and offset setting priorities
  20559. // 1. color map
  20560. // 2. alpha map
  20561. var uvScaleMap;
  20562. if (material.map) {
  20563. uvScaleMap = material.map;
  20564. } else if (material.alphaMap) {
  20565. uvScaleMap = material.alphaMap;
  20566. }
  20567. if (uvScaleMap !== undefined) {
  20568. if (uvScaleMap.matrixAutoUpdate === true) {
  20569. uvScaleMap.updateMatrix();
  20570. }
  20571. uniforms.uvTransform.value.copy(uvScaleMap.matrix);
  20572. }
  20573. }
  20574. function refreshUniformsSprites(uniforms, material) {
  20575. uniforms.diffuse.value.copy(material.color);
  20576. uniforms.opacity.value = material.opacity;
  20577. uniforms.rotation.value = material.rotation;
  20578. if (material.map) {
  20579. uniforms.map.value = material.map;
  20580. }
  20581. if (material.alphaMap) {
  20582. uniforms.alphaMap.value = material.alphaMap;
  20583. } // uv repeat and offset setting priorities
  20584. // 1. color map
  20585. // 2. alpha map
  20586. var uvScaleMap;
  20587. if (material.map) {
  20588. uvScaleMap = material.map;
  20589. } else if (material.alphaMap) {
  20590. uvScaleMap = material.alphaMap;
  20591. }
  20592. if (uvScaleMap !== undefined) {
  20593. if (uvScaleMap.matrixAutoUpdate === true) {
  20594. uvScaleMap.updateMatrix();
  20595. }
  20596. uniforms.uvTransform.value.copy(uvScaleMap.matrix);
  20597. }
  20598. }
  20599. function refreshUniformsLambert(uniforms, material) {
  20600. if (material.emissiveMap) {
  20601. uniforms.emissiveMap.value = material.emissiveMap;
  20602. }
  20603. }
  20604. function refreshUniformsPhong(uniforms, material) {
  20605. uniforms.specular.value.copy(material.specular);
  20606. uniforms.shininess.value = Math.max(material.shininess, 1e-4); // to prevent pow( 0.0, 0.0 )
  20607. if (material.emissiveMap) {
  20608. uniforms.emissiveMap.value = material.emissiveMap;
  20609. }
  20610. if (material.bumpMap) {
  20611. uniforms.bumpMap.value = material.bumpMap;
  20612. uniforms.bumpScale.value = material.bumpScale;
  20613. if (material.side === BackSide) uniforms.bumpScale.value *= -1;
  20614. }
  20615. if (material.normalMap) {
  20616. uniforms.normalMap.value = material.normalMap;
  20617. uniforms.normalScale.value.copy(material.normalScale);
  20618. if (material.side === BackSide) uniforms.normalScale.value.negate();
  20619. }
  20620. if (material.displacementMap) {
  20621. uniforms.displacementMap.value = material.displacementMap;
  20622. uniforms.displacementScale.value = material.displacementScale;
  20623. uniforms.displacementBias.value = material.displacementBias;
  20624. }
  20625. }
  20626. function refreshUniformsToon(uniforms, material) {
  20627. if (material.gradientMap) {
  20628. uniforms.gradientMap.value = material.gradientMap;
  20629. }
  20630. if (material.emissiveMap) {
  20631. uniforms.emissiveMap.value = material.emissiveMap;
  20632. }
  20633. if (material.bumpMap) {
  20634. uniforms.bumpMap.value = material.bumpMap;
  20635. uniforms.bumpScale.value = material.bumpScale;
  20636. if (material.side === BackSide) uniforms.bumpScale.value *= -1;
  20637. }
  20638. if (material.normalMap) {
  20639. uniforms.normalMap.value = material.normalMap;
  20640. uniforms.normalScale.value.copy(material.normalScale);
  20641. if (material.side === BackSide) uniforms.normalScale.value.negate();
  20642. }
  20643. if (material.displacementMap) {
  20644. uniforms.displacementMap.value = material.displacementMap;
  20645. uniforms.displacementScale.value = material.displacementScale;
  20646. uniforms.displacementBias.value = material.displacementBias;
  20647. }
  20648. }
  20649. function refreshUniformsStandard(uniforms, material) {
  20650. uniforms.roughness.value = material.roughness;
  20651. uniforms.metalness.value = material.metalness;
  20652. if (material.roughnessMap) {
  20653. uniforms.roughnessMap.value = material.roughnessMap;
  20654. }
  20655. if (material.metalnessMap) {
  20656. uniforms.metalnessMap.value = material.metalnessMap;
  20657. }
  20658. if (material.emissiveMap) {
  20659. uniforms.emissiveMap.value = material.emissiveMap;
  20660. }
  20661. if (material.bumpMap) {
  20662. uniforms.bumpMap.value = material.bumpMap;
  20663. uniforms.bumpScale.value = material.bumpScale;
  20664. if (material.side === BackSide) uniforms.bumpScale.value *= -1;
  20665. }
  20666. if (material.normalMap) {
  20667. uniforms.normalMap.value = material.normalMap;
  20668. uniforms.normalScale.value.copy(material.normalScale);
  20669. if (material.side === BackSide) uniforms.normalScale.value.negate();
  20670. }
  20671. if (material.displacementMap) {
  20672. uniforms.displacementMap.value = material.displacementMap;
  20673. uniforms.displacementScale.value = material.displacementScale;
  20674. uniforms.displacementBias.value = material.displacementBias;
  20675. }
  20676. var envMap = properties.get(material).envMap;
  20677. if (envMap) {
  20678. //uniforms.envMap.value = material.envMap; // part of uniforms common
  20679. uniforms.envMapIntensity.value = material.envMapIntensity;
  20680. }
  20681. }
  20682. function refreshUniformsPhysical(uniforms, material) {
  20683. refreshUniformsStandard(uniforms, material);
  20684. uniforms.reflectivity.value = material.reflectivity; // also part of uniforms common
  20685. uniforms.clearcoat.value = material.clearcoat;
  20686. uniforms.clearcoatRoughness.value = material.clearcoatRoughness;
  20687. if (material.sheen) uniforms.sheen.value.copy(material.sheen);
  20688. if (material.clearcoatMap) {
  20689. uniforms.clearcoatMap.value = material.clearcoatMap;
  20690. }
  20691. if (material.clearcoatRoughnessMap) {
  20692. uniforms.clearcoatRoughnessMap.value = material.clearcoatRoughnessMap;
  20693. }
  20694. if (material.clearcoatNormalMap) {
  20695. uniforms.clearcoatNormalScale.value.copy(material.clearcoatNormalScale);
  20696. uniforms.clearcoatNormalMap.value = material.clearcoatNormalMap;
  20697. if (material.side === BackSide) {
  20698. uniforms.clearcoatNormalScale.value.negate();
  20699. }
  20700. }
  20701. uniforms.transmission.value = material.transmission;
  20702. if (material.transmissionMap) {
  20703. uniforms.transmissionMap.value = material.transmissionMap;
  20704. }
  20705. }
  20706. function refreshUniformsMatcap(uniforms, material) {
  20707. if (material.matcap) {
  20708. uniforms.matcap.value = material.matcap;
  20709. }
  20710. if (material.bumpMap) {
  20711. uniforms.bumpMap.value = material.bumpMap;
  20712. uniforms.bumpScale.value = material.bumpScale;
  20713. if (material.side === BackSide) uniforms.bumpScale.value *= -1;
  20714. }
  20715. if (material.normalMap) {
  20716. uniforms.normalMap.value = material.normalMap;
  20717. uniforms.normalScale.value.copy(material.normalScale);
  20718. if (material.side === BackSide) uniforms.normalScale.value.negate();
  20719. }
  20720. if (material.displacementMap) {
  20721. uniforms.displacementMap.value = material.displacementMap;
  20722. uniforms.displacementScale.value = material.displacementScale;
  20723. uniforms.displacementBias.value = material.displacementBias;
  20724. }
  20725. }
  20726. function refreshUniformsDepth(uniforms, material) {
  20727. if (material.displacementMap) {
  20728. uniforms.displacementMap.value = material.displacementMap;
  20729. uniforms.displacementScale.value = material.displacementScale;
  20730. uniforms.displacementBias.value = material.displacementBias;
  20731. }
  20732. }
  20733. function refreshUniformsDistance(uniforms, material) {
  20734. if (material.displacementMap) {
  20735. uniforms.displacementMap.value = material.displacementMap;
  20736. uniforms.displacementScale.value = material.displacementScale;
  20737. uniforms.displacementBias.value = material.displacementBias;
  20738. }
  20739. uniforms.referencePosition.value.copy(material.referencePosition);
  20740. uniforms.nearDistance.value = material.nearDistance;
  20741. uniforms.farDistance.value = material.farDistance;
  20742. }
  20743. function refreshUniformsNormal(uniforms, material) {
  20744. if (material.bumpMap) {
  20745. uniforms.bumpMap.value = material.bumpMap;
  20746. uniforms.bumpScale.value = material.bumpScale;
  20747. if (material.side === BackSide) uniforms.bumpScale.value *= -1;
  20748. }
  20749. if (material.normalMap) {
  20750. uniforms.normalMap.value = material.normalMap;
  20751. uniforms.normalScale.value.copy(material.normalScale);
  20752. if (material.side === BackSide) uniforms.normalScale.value.negate();
  20753. }
  20754. if (material.displacementMap) {
  20755. uniforms.displacementMap.value = material.displacementMap;
  20756. uniforms.displacementScale.value = material.displacementScale;
  20757. uniforms.displacementBias.value = material.displacementBias;
  20758. }
  20759. }
  20760. return {
  20761. refreshFogUniforms: refreshFogUniforms,
  20762. refreshMaterialUniforms: refreshMaterialUniforms
  20763. };
  20764. }
  20765. function createCanvasElement() {
  20766. var canvas = document.createElementNS('http://www.w3.org/1999/xhtml', 'canvas');
  20767. canvas.style.display = 'block';
  20768. return canvas;
  20769. }
  20770. function WebGLRenderer(parameters) {
  20771. parameters = parameters || {};
  20772. var _canvas = parameters.canvas !== undefined ? parameters.canvas : createCanvasElement(),
  20773. _context = parameters.context !== undefined ? parameters.context : null,
  20774. _alpha = parameters.alpha !== undefined ? parameters.alpha : false,
  20775. _depth = parameters.depth !== undefined ? parameters.depth : true,
  20776. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  20777. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  20778. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  20779. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
  20780. _powerPreference = parameters.powerPreference !== undefined ? parameters.powerPreference : 'default',
  20781. _failIfMajorPerformanceCaveat = parameters.failIfMajorPerformanceCaveat !== undefined ? parameters.failIfMajorPerformanceCaveat : false;
  20782. var currentRenderList = null;
  20783. var currentRenderState = null; // render() can be called from within a callback triggered by another render.
  20784. // We track this so that the nested render call gets its state isolated from the parent render call.
  20785. var renderStateStack = []; // public properties
  20786. this.domElement = _canvas; // Debug configuration container
  20787. this.debug = {
  20788. /**
  20789. * Enables error checking and reporting when shader programs are being compiled
  20790. * @type {boolean}
  20791. */
  20792. checkShaderErrors: true
  20793. }; // clearing
  20794. this.autoClear = true;
  20795. this.autoClearColor = true;
  20796. this.autoClearDepth = true;
  20797. this.autoClearStencil = true; // scene graph
  20798. this.sortObjects = true; // user-defined clipping
  20799. this.clippingPlanes = [];
  20800. this.localClippingEnabled = false; // physically based shading
  20801. this.gammaFactor = 2.0; // for backwards compatibility
  20802. this.outputEncoding = LinearEncoding; // physical lights
  20803. this.physicallyCorrectLights = false; // tone mapping
  20804. this.toneMapping = NoToneMapping;
  20805. this.toneMappingExposure = 1.0; // morphs
  20806. this.maxMorphTargets = 8;
  20807. this.maxMorphNormals = 4; // internal properties
  20808. var _this = this;
  20809. var _isContextLost = false; // internal state cache
  20810. var _framebuffer = null;
  20811. var _currentActiveCubeFace = 0;
  20812. var _currentActiveMipmapLevel = 0;
  20813. var _currentRenderTarget = null;
  20814. var _currentFramebuffer = null;
  20815. var _currentMaterialId = -1;
  20816. var _currentCamera = null;
  20817. var _currentViewport = new Vector4();
  20818. var _currentScissor = new Vector4();
  20819. var _currentScissorTest = null; //
  20820. var _width = _canvas.width;
  20821. var _height = _canvas.height;
  20822. var _pixelRatio = 1;
  20823. var _opaqueSort = null;
  20824. var _transparentSort = null;
  20825. var _viewport = new Vector4(0, 0, _width, _height);
  20826. var _scissor = new Vector4(0, 0, _width, _height);
  20827. var _scissorTest = false; // frustum
  20828. var _frustum = new Frustum(); // clipping
  20829. var _clippingEnabled = false;
  20830. var _localClippingEnabled = false; // camera matrices cache
  20831. var _projScreenMatrix = new Matrix4();
  20832. var _vector3 = new Vector3();
  20833. var _emptyScene = {
  20834. background: null,
  20835. fog: null,
  20836. environment: null,
  20837. overrideMaterial: null,
  20838. isScene: true
  20839. };
  20840. function getTargetPixelRatio() {
  20841. return _currentRenderTarget === null ? _pixelRatio : 1;
  20842. } // initialize
  20843. var _gl = _context;
  20844. function getContext(contextNames, contextAttributes) {
  20845. for (var i = 0; i < contextNames.length; i++) {
  20846. var contextName = contextNames[i];
  20847. var context = _canvas.getContext(contextName, contextAttributes);
  20848. if (context !== null) return context;
  20849. }
  20850. return null;
  20851. }
  20852. try {
  20853. var contextAttributes = {
  20854. alpha: _alpha,
  20855. depth: _depth,
  20856. stencil: _stencil,
  20857. antialias: _antialias,
  20858. premultipliedAlpha: _premultipliedAlpha,
  20859. preserveDrawingBuffer: _preserveDrawingBuffer,
  20860. powerPreference: _powerPreference,
  20861. failIfMajorPerformanceCaveat: _failIfMajorPerformanceCaveat
  20862. }; // event listeners must be registered before WebGL context is created, see #12753
  20863. _canvas.addEventListener('webglcontextlost', onContextLost, false);
  20864. _canvas.addEventListener('webglcontextrestored', onContextRestore, false);
  20865. if (_gl === null) {
  20866. var contextNames = ['webgl2', 'webgl', 'experimental-webgl'];
  20867. if (_this.isWebGL1Renderer === true) {
  20868. contextNames.shift();
  20869. }
  20870. _gl = getContext(contextNames, contextAttributes);
  20871. if (_gl === null) {
  20872. if (getContext(contextNames)) {
  20873. throw new Error('Error creating WebGL context with your selected attributes.');
  20874. } else {
  20875. throw new Error('Error creating WebGL context.');
  20876. }
  20877. }
  20878. } // Some experimental-webgl implementations do not have getShaderPrecisionFormat
  20879. if (_gl.getShaderPrecisionFormat === undefined) {
  20880. _gl.getShaderPrecisionFormat = function () {
  20881. return {
  20882. 'rangeMin': 1,
  20883. 'rangeMax': 1,
  20884. 'precision': 1
  20885. };
  20886. };
  20887. }
  20888. } catch (error) {
  20889. console.error('THREE.WebGLRenderer: ' + error.message);
  20890. throw error;
  20891. }
  20892. var extensions, capabilities, state, info;
  20893. var properties, textures, cubemaps, attributes, geometries, objects;
  20894. var programCache, materials, renderLists, renderStates, clipping;
  20895. var background, morphtargets, bufferRenderer, indexedBufferRenderer;
  20896. var utils, bindingStates;
  20897. function initGLContext() {
  20898. extensions = new WebGLExtensions(_gl);
  20899. capabilities = new WebGLCapabilities(_gl, extensions, parameters);
  20900. extensions.init(capabilities);
  20901. utils = new WebGLUtils(_gl, extensions, capabilities);
  20902. state = new WebGLState(_gl, extensions, capabilities);
  20903. state.scissor(_currentScissor.copy(_scissor).multiplyScalar(_pixelRatio).floor());
  20904. state.viewport(_currentViewport.copy(_viewport).multiplyScalar(_pixelRatio).floor());
  20905. info = new WebGLInfo(_gl);
  20906. properties = new WebGLProperties();
  20907. textures = new WebGLTextures(_gl, extensions, state, properties, capabilities, utils, info);
  20908. cubemaps = new WebGLCubeMaps(_this);
  20909. attributes = new WebGLAttributes(_gl, capabilities);
  20910. bindingStates = new WebGLBindingStates(_gl, extensions, attributes, capabilities);
  20911. geometries = new WebGLGeometries(_gl, attributes, info, bindingStates);
  20912. objects = new WebGLObjects(_gl, geometries, attributes, info);
  20913. morphtargets = new WebGLMorphtargets(_gl);
  20914. clipping = new WebGLClipping(properties);
  20915. programCache = new WebGLPrograms(_this, cubemaps, extensions, capabilities, bindingStates, clipping);
  20916. materials = new WebGLMaterials(properties);
  20917. renderLists = new WebGLRenderLists(properties);
  20918. renderStates = new WebGLRenderStates(extensions, capabilities);
  20919. background = new WebGLBackground(_this, cubemaps, state, objects, _premultipliedAlpha);
  20920. bufferRenderer = new WebGLBufferRenderer(_gl, extensions, info, capabilities);
  20921. indexedBufferRenderer = new WebGLIndexedBufferRenderer(_gl, extensions, info, capabilities);
  20922. info.programs = programCache.programs;
  20923. _this.capabilities = capabilities;
  20924. _this.extensions = extensions;
  20925. _this.properties = properties;
  20926. _this.renderLists = renderLists;
  20927. _this.state = state;
  20928. _this.info = info;
  20929. }
  20930. initGLContext();
  20931. var xr = typeof navigator !== 'undefined' && 'xr' in navigator ? new WebXRManager(_this, _gl) : new WebVRManager(_this);
  20932. this.xr = xr; // shadow map
  20933. var shadowMap = new WebGLShadowMap(_this, objects, capabilities.maxTextureSize);
  20934. this.shadowMap = shadowMap; // API
  20935. this.getContext = function () {
  20936. return _gl;
  20937. };
  20938. this.getContextAttributes = function () {
  20939. return _gl.getContextAttributes();
  20940. };
  20941. this.forceContextLoss = function () {
  20942. var extension = extensions.get('WEBGL_lose_context');
  20943. if (extension) extension.loseContext();
  20944. };
  20945. this.forceContextRestore = function () {
  20946. var extension = extensions.get('WEBGL_lose_context');
  20947. if (extension) extension.restoreContext();
  20948. };
  20949. this.getPixelRatio = function () {
  20950. return _pixelRatio;
  20951. };
  20952. this.setPixelRatio = function (value) {
  20953. if (value === undefined) return;
  20954. _pixelRatio = value;
  20955. this.setSize(_width, _height, false);
  20956. };
  20957. this.getSize = function (target) {
  20958. if (target === undefined) {
  20959. console.warn('WebGLRenderer: .getsize() now requires a Vector2 as an argument');
  20960. target = new Vector2();
  20961. }
  20962. return target.set(_width, _height);
  20963. };
  20964. this.setSize = function (width, height, updateStyle) {
  20965. if (xr.isPresenting) {
  20966. console.warn('THREE.WebGLRenderer: Can\'t change size while VR device is presenting.');
  20967. return;
  20968. }
  20969. _width = width;
  20970. _height = height;
  20971. _canvas.width = Math.floor(width * _pixelRatio);
  20972. _canvas.height = Math.floor(height * _pixelRatio);
  20973. if (updateStyle !== false) {
  20974. _canvas.style.width = width + 'px';
  20975. _canvas.style.height = height + 'px';
  20976. }
  20977. this.setViewport(0, 0, width, height);
  20978. };
  20979. this.getDrawingBufferSize = function (target) {
  20980. if (target === undefined) {
  20981. console.warn('WebGLRenderer: .getdrawingBufferSize() now requires a Vector2 as an argument');
  20982. target = new Vector2();
  20983. }
  20984. return target.set(_width * _pixelRatio, _height * _pixelRatio).floor();
  20985. };
  20986. this.setDrawingBufferSize = function (width, height, pixelRatio) {
  20987. _width = width;
  20988. _height = height;
  20989. _pixelRatio = pixelRatio;
  20990. _canvas.width = Math.floor(width * pixelRatio);
  20991. _canvas.height = Math.floor(height * pixelRatio);
  20992. this.setViewport(0, 0, width, height);
  20993. };
  20994. this.getCurrentViewport = function (target) {
  20995. if (target === undefined) {
  20996. console.warn('WebGLRenderer: .getCurrentViewport() now requires a Vector4 as an argument');
  20997. target = new Vector4();
  20998. }
  20999. return target.copy(_currentViewport);
  21000. };
  21001. this.getViewport = function (target) {
  21002. return target.copy(_viewport);
  21003. };
  21004. this.setViewport = function (x, y, width, height) {
  21005. if (x.isVector4) {
  21006. _viewport.set(x.x, x.y, x.z, x.w);
  21007. } else {
  21008. _viewport.set(x, y, width, height);
  21009. }
  21010. state.viewport(_currentViewport.copy(_viewport).multiplyScalar(_pixelRatio).floor());
  21011. };
  21012. this.getScissor = function (target) {
  21013. return target.copy(_scissor);
  21014. };
  21015. this.setScissor = function (x, y, width, height) {
  21016. if (x.isVector4) {
  21017. _scissor.set(x.x, x.y, x.z, x.w);
  21018. } else {
  21019. _scissor.set(x, y, width, height);
  21020. }
  21021. state.scissor(_currentScissor.copy(_scissor).multiplyScalar(_pixelRatio).floor());
  21022. };
  21023. this.getScissorTest = function () {
  21024. return _scissorTest;
  21025. };
  21026. this.setScissorTest = function (boolean) {
  21027. state.setScissorTest(_scissorTest = boolean);
  21028. };
  21029. this.setOpaqueSort = function (method) {
  21030. _opaqueSort = method;
  21031. };
  21032. this.setTransparentSort = function (method) {
  21033. _transparentSort = method;
  21034. }; // Clearing
  21035. this.getClearColor = function (target) {
  21036. if (target === undefined) {
  21037. console.warn('WebGLRenderer: .getClearColor() now requires a Color as an argument');
  21038. target = new Color();
  21039. }
  21040. return target.copy(background.getClearColor());
  21041. };
  21042. this.setClearColor = function () {
  21043. background.setClearColor.apply(background, arguments);
  21044. };
  21045. this.getClearAlpha = function () {
  21046. return background.getClearAlpha();
  21047. };
  21048. this.setClearAlpha = function () {
  21049. background.setClearAlpha.apply(background, arguments);
  21050. };
  21051. this.clear = function (color, depth, stencil) {
  21052. var bits = 0;
  21053. if (color === undefined || color) bits |= 16384;
  21054. if (depth === undefined || depth) bits |= 256;
  21055. if (stencil === undefined || stencil) bits |= 1024;
  21056. _gl.clear(bits);
  21057. };
  21058. this.clearColor = function () {
  21059. this.clear(true, false, false);
  21060. };
  21061. this.clearDepth = function () {
  21062. this.clear(false, true, false);
  21063. };
  21064. this.clearStencil = function () {
  21065. this.clear(false, false, true);
  21066. }; //
  21067. this.dispose = function () {
  21068. _canvas.removeEventListener('webglcontextlost', onContextLost, false);
  21069. _canvas.removeEventListener('webglcontextrestored', onContextRestore, false);
  21070. renderLists.dispose();
  21071. renderStates.dispose();
  21072. properties.dispose();
  21073. cubemaps.dispose();
  21074. objects.dispose();
  21075. bindingStates.dispose();
  21076. xr.dispose();
  21077. animation.stop();
  21078. }; // Events
  21079. function onContextLost(event) {
  21080. event.preventDefault();
  21081. console.log('THREE.WebGLRenderer: Context Lost.');
  21082. _isContextLost = true;
  21083. }
  21084. function onContextRestore()
  21085. /* event */
  21086. {
  21087. console.log('THREE.WebGLRenderer: Context Restored.');
  21088. _isContextLost = false;
  21089. initGLContext();
  21090. }
  21091. function onMaterialDispose(event) {
  21092. var material = event.target;
  21093. material.removeEventListener('dispose', onMaterialDispose);
  21094. deallocateMaterial(material);
  21095. } // Buffer deallocation
  21096. function deallocateMaterial(material) {
  21097. releaseMaterialProgramReference(material);
  21098. properties.remove(material);
  21099. }
  21100. function releaseMaterialProgramReference(material) {
  21101. var programInfo = properties.get(material).program;
  21102. if (programInfo !== undefined) {
  21103. programCache.releaseProgram(programInfo);
  21104. }
  21105. } // Buffer rendering
  21106. function renderObjectImmediate(object, program) {
  21107. object.render(function (object) {
  21108. _this.renderBufferImmediate(object, program);
  21109. });
  21110. }
  21111. this.renderBufferImmediate = function (object, program) {
  21112. bindingStates.initAttributes();
  21113. var buffers = properties.get(object);
  21114. if (object.hasPositions && !buffers.position) buffers.position = _gl.createBuffer();
  21115. if (object.hasNormals && !buffers.normal) buffers.normal = _gl.createBuffer();
  21116. if (object.hasUvs && !buffers.uv) buffers.uv = _gl.createBuffer();
  21117. if (object.hasColors && !buffers.color) buffers.color = _gl.createBuffer();
  21118. var programAttributes = program.getAttributes();
  21119. if (object.hasPositions) {
  21120. _gl.bindBuffer(34962, buffers.position);
  21121. _gl.bufferData(34962, object.positionArray, 35048);
  21122. bindingStates.enableAttribute(programAttributes.position);
  21123. _gl.vertexAttribPointer(programAttributes.position, 3, 5126, false, 0, 0);
  21124. }
  21125. if (object.hasNormals) {
  21126. _gl.bindBuffer(34962, buffers.normal);
  21127. _gl.bufferData(34962, object.normalArray, 35048);
  21128. bindingStates.enableAttribute(programAttributes.normal);
  21129. _gl.vertexAttribPointer(programAttributes.normal, 3, 5126, false, 0, 0);
  21130. }
  21131. if (object.hasUvs) {
  21132. _gl.bindBuffer(34962, buffers.uv);
  21133. _gl.bufferData(34962, object.uvArray, 35048);
  21134. bindingStates.enableAttribute(programAttributes.uv);
  21135. _gl.vertexAttribPointer(programAttributes.uv, 2, 5126, false, 0, 0);
  21136. }
  21137. if (object.hasColors) {
  21138. _gl.bindBuffer(34962, buffers.color);
  21139. _gl.bufferData(34962, object.colorArray, 35048);
  21140. bindingStates.enableAttribute(programAttributes.color);
  21141. _gl.vertexAttribPointer(programAttributes.color, 3, 5126, false, 0, 0);
  21142. }
  21143. bindingStates.disableUnusedAttributes();
  21144. _gl.drawArrays(4, 0, object.count);
  21145. object.count = 0;
  21146. };
  21147. this.renderBufferDirect = function (camera, scene, geometry, material, object, group) {
  21148. if (scene === null) scene = _emptyScene; // renderBufferDirect second parameter used to be fog (could be null)
  21149. var frontFaceCW = object.isMesh && object.matrixWorld.determinant() < 0;
  21150. var program = setProgram(camera, scene, material, object);
  21151. state.setMaterial(material, frontFaceCW); //
  21152. var index = geometry.index;
  21153. var position = geometry.attributes.position; //
  21154. if (index === null) {
  21155. if (position === undefined || position.count === 0) return;
  21156. } else if (index.count === 0) {
  21157. return;
  21158. } //
  21159. var rangeFactor = 1;
  21160. if (material.wireframe === true) {
  21161. index = geometries.getWireframeAttribute(geometry);
  21162. rangeFactor = 2;
  21163. }
  21164. if (material.morphTargets || material.morphNormals) {
  21165. morphtargets.update(object, geometry, material, program);
  21166. }
  21167. bindingStates.setup(object, material, program, geometry, index);
  21168. var attribute;
  21169. var renderer = bufferRenderer;
  21170. if (index !== null) {
  21171. attribute = attributes.get(index);
  21172. renderer = indexedBufferRenderer;
  21173. renderer.setIndex(attribute);
  21174. } //
  21175. var dataCount = index !== null ? index.count : position.count;
  21176. var rangeStart = geometry.drawRange.start * rangeFactor;
  21177. var rangeCount = geometry.drawRange.count * rangeFactor;
  21178. var groupStart = group !== null ? group.start * rangeFactor : 0;
  21179. var groupCount = group !== null ? group.count * rangeFactor : Infinity;
  21180. var drawStart = Math.max(rangeStart, groupStart);
  21181. var drawEnd = Math.min(dataCount, rangeStart + rangeCount, groupStart + groupCount) - 1;
  21182. var drawCount = Math.max(0, drawEnd - drawStart + 1);
  21183. if (drawCount === 0) return; //
  21184. if (object.isMesh) {
  21185. if (material.wireframe === true) {
  21186. state.setLineWidth(material.wireframeLinewidth * getTargetPixelRatio());
  21187. renderer.setMode(1);
  21188. } else {
  21189. renderer.setMode(4);
  21190. }
  21191. } else if (object.isLine) {
  21192. var lineWidth = material.linewidth;
  21193. if (lineWidth === undefined) lineWidth = 1; // Not using Line*Material
  21194. state.setLineWidth(lineWidth * getTargetPixelRatio());
  21195. if (object.isLineSegments) {
  21196. renderer.setMode(1);
  21197. } else if (object.isLineLoop) {
  21198. renderer.setMode(2);
  21199. } else {
  21200. renderer.setMode(3);
  21201. }
  21202. } else if (object.isPoints) {
  21203. renderer.setMode(0);
  21204. } else if (object.isSprite) {
  21205. renderer.setMode(4);
  21206. }
  21207. if (object.isInstancedMesh) {
  21208. renderer.renderInstances(drawStart, drawCount, object.count);
  21209. } else if (geometry.isInstancedBufferGeometry) {
  21210. var instanceCount = Math.min(geometry.instanceCount, geometry._maxInstanceCount);
  21211. renderer.renderInstances(drawStart, drawCount, instanceCount);
  21212. } else {
  21213. renderer.render(drawStart, drawCount);
  21214. }
  21215. }; // Compile
  21216. this.compile = function (scene, camera) {
  21217. currentRenderState = renderStates.get(scene);
  21218. currentRenderState.init();
  21219. scene.traverseVisible(function (object) {
  21220. if (object.isLight && object.layers.test(camera.layers)) {
  21221. currentRenderState.pushLight(object);
  21222. if (object.castShadow) {
  21223. currentRenderState.pushShadow(object);
  21224. }
  21225. }
  21226. });
  21227. currentRenderState.setupLights();
  21228. var compiled = new WeakMap();
  21229. scene.traverse(function (object) {
  21230. var material = object.material;
  21231. if (material) {
  21232. if (Array.isArray(material)) {
  21233. for (var i = 0; i < material.length; i++) {
  21234. var material2 = material[i];
  21235. if (compiled.has(material2) === false) {
  21236. initMaterial(material2, scene, object);
  21237. compiled.set(material2);
  21238. }
  21239. }
  21240. } else if (compiled.has(material) === false) {
  21241. initMaterial(material, scene, object);
  21242. compiled.set(material);
  21243. }
  21244. }
  21245. });
  21246. }; // Animation Loop
  21247. var onAnimationFrameCallback = null;
  21248. function onAnimationFrame(time) {
  21249. if (xr.isPresenting) return;
  21250. if (onAnimationFrameCallback) onAnimationFrameCallback(time);
  21251. }
  21252. var animation = new WebGLAnimation();
  21253. animation.setAnimationLoop(onAnimationFrame);
  21254. if (typeof window !== 'undefined') animation.setContext(window);
  21255. this.setAnimationLoop = function (callback) {
  21256. onAnimationFrameCallback = callback;
  21257. xr.setAnimationLoop(callback);
  21258. callback === null ? animation.stop() : animation.start();
  21259. }; // Rendering
  21260. this.render = function (scene, camera) {
  21261. var renderTarget, forceClear;
  21262. if (arguments[2] !== undefined) {
  21263. console.warn('THREE.WebGLRenderer.render(): the renderTarget argument has been removed. Use .setRenderTarget() instead.');
  21264. renderTarget = arguments[2];
  21265. }
  21266. if (arguments[3] !== undefined) {
  21267. console.warn('THREE.WebGLRenderer.render(): the forceClear argument has been removed. Use .clear() instead.');
  21268. forceClear = arguments[3];
  21269. }
  21270. if (camera !== undefined && camera.isCamera !== true) {
  21271. console.error('THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.');
  21272. return;
  21273. }
  21274. if (_isContextLost === true) return; // reset caching for this frame
  21275. bindingStates.resetDefaultState();
  21276. _currentMaterialId = -1;
  21277. _currentCamera = null; // update scene graph
  21278. if (scene.autoUpdate === true) scene.updateMatrixWorld(); // update camera matrices and frustum
  21279. if (camera.parent === null) camera.updateMatrixWorld();
  21280. if (xr.enabled === true && xr.isPresenting === true) {
  21281. camera = xr.getCamera(camera);
  21282. } //
  21283. if (scene.isScene === true) scene.onBeforeRender(_this, scene, camera, renderTarget || _currentRenderTarget);
  21284. currentRenderState = renderStates.get(scene, renderStateStack.length);
  21285. currentRenderState.init();
  21286. renderStateStack.push(currentRenderState);
  21287. _projScreenMatrix.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse);
  21288. _frustum.setFromProjectionMatrix(_projScreenMatrix);
  21289. _localClippingEnabled = this.localClippingEnabled;
  21290. _clippingEnabled = clipping.init(this.clippingPlanes, _localClippingEnabled, camera);
  21291. currentRenderList = renderLists.get(scene, camera);
  21292. currentRenderList.init();
  21293. projectObject(scene, camera, 0, _this.sortObjects);
  21294. currentRenderList.finish();
  21295. if (_this.sortObjects === true) {
  21296. currentRenderList.sort(_opaqueSort, _transparentSort);
  21297. } //
  21298. if (_clippingEnabled === true) clipping.beginShadows();
  21299. var shadowsArray = currentRenderState.state.shadowsArray;
  21300. shadowMap.render(shadowsArray, scene, camera);
  21301. currentRenderState.setupLights();
  21302. currentRenderState.setupLightsView(camera);
  21303. if (_clippingEnabled === true) clipping.endShadows(); //
  21304. if (this.info.autoReset === true) this.info.reset();
  21305. if (renderTarget !== undefined) {
  21306. this.setRenderTarget(renderTarget);
  21307. } //
  21308. background.render(currentRenderList, scene, camera, forceClear); // render scene
  21309. var opaqueObjects = currentRenderList.opaque;
  21310. var transparentObjects = currentRenderList.transparent;
  21311. if (opaqueObjects.length > 0) renderObjects(opaqueObjects, scene, camera);
  21312. if (transparentObjects.length > 0) renderObjects(transparentObjects, scene, camera); //
  21313. if (scene.isScene === true) scene.onAfterRender(_this, scene, camera); //
  21314. if (_currentRenderTarget !== null) {
  21315. // Generate mipmap if we're using any kind of mipmap filtering
  21316. textures.updateRenderTargetMipmap(_currentRenderTarget); // resolve multisample renderbuffers to a single-sample texture if necessary
  21317. textures.updateMultisampleRenderTarget(_currentRenderTarget);
  21318. } // Ensure depth buffer writing is enabled so it can be cleared on next render
  21319. state.buffers.depth.setTest(true);
  21320. state.buffers.depth.setMask(true);
  21321. state.buffers.color.setMask(true);
  21322. state.setPolygonOffset(false);
  21323. if (xr.enabled && xr.submitFrame) {
  21324. xr.submitFrame();
  21325. } // _gl.finish();
  21326. renderStateStack.pop();
  21327. if (renderStateStack.length > 0) {
  21328. currentRenderState = renderStateStack[renderStateStack.length - 1];
  21329. } else {
  21330. currentRenderState = null;
  21331. }
  21332. currentRenderList = null;
  21333. };
  21334. function projectObject(object, camera, groupOrder, sortObjects) {
  21335. if (object.visible === false) return;
  21336. var visible = object.layers.test(camera.layers);
  21337. if (visible) {
  21338. if (object.isGroup) {
  21339. groupOrder = object.renderOrder;
  21340. } else if (object.isLOD) {
  21341. if (object.autoUpdate === true) object.update(camera);
  21342. } else if (object.isLight) {
  21343. currentRenderState.pushLight(object);
  21344. if (object.castShadow) {
  21345. currentRenderState.pushShadow(object);
  21346. }
  21347. } else if (object.isSprite) {
  21348. if (!object.frustumCulled || _frustum.intersectsSprite(object)) {
  21349. if (sortObjects) {
  21350. _vector3.setFromMatrixPosition(object.matrixWorld).applyMatrix4(_projScreenMatrix);
  21351. }
  21352. var geometry = objects.update(object);
  21353. var material = object.material;
  21354. if (material.visible) {
  21355. currentRenderList.push(object, geometry, material, groupOrder, _vector3.z, null);
  21356. }
  21357. }
  21358. } else if (object.isImmediateRenderObject) {
  21359. if (sortObjects) {
  21360. _vector3.setFromMatrixPosition(object.matrixWorld).applyMatrix4(_projScreenMatrix);
  21361. }
  21362. currentRenderList.push(object, null, object.material, groupOrder, _vector3.z, null);
  21363. } else if (object.isMesh || object.isLine || object.isPoints) {
  21364. if (object.isSkinnedMesh) {
  21365. // update skeleton only once in a frame
  21366. if (object.skeleton.frame !== info.render.frame) {
  21367. object.skeleton.update();
  21368. object.skeleton.frame = info.render.frame;
  21369. }
  21370. }
  21371. if (!object.frustumCulled || _frustum.intersectsObject(object)) {
  21372. if (sortObjects) {
  21373. _vector3.setFromMatrixPosition(object.matrixWorld).applyMatrix4(_projScreenMatrix);
  21374. }
  21375. var _geometry = objects.update(object);
  21376. var _material = object.material;
  21377. if (Array.isArray(_material)) {
  21378. var groups = _geometry.groups;
  21379. for (var i = 0, l = groups.length; i < l; i++) {
  21380. var group = groups[i];
  21381. var groupMaterial = _material[group.materialIndex];
  21382. if (groupMaterial && groupMaterial.visible) {
  21383. currentRenderList.push(object, _geometry, groupMaterial, groupOrder, _vector3.z, group);
  21384. }
  21385. }
  21386. } else if (_material.visible) {
  21387. currentRenderList.push(object, _geometry, _material, groupOrder, _vector3.z, null);
  21388. }
  21389. }
  21390. }
  21391. }
  21392. var children = object.children;
  21393. for (var _i = 0, _l = children.length; _i < _l; _i++) {
  21394. projectObject(children[_i], camera, groupOrder, sortObjects);
  21395. }
  21396. }
  21397. function renderObjects(renderList, scene, camera) {
  21398. var overrideMaterial = scene.isScene === true ? scene.overrideMaterial : null;
  21399. for (var i = 0, l = renderList.length; i < l; i++) {
  21400. var renderItem = renderList[i];
  21401. var object = renderItem.object;
  21402. var geometry = renderItem.geometry;
  21403. var material = overrideMaterial === null ? renderItem.material : overrideMaterial;
  21404. var group = renderItem.group;
  21405. if (camera.isArrayCamera) {
  21406. var cameras = camera.cameras;
  21407. for (var j = 0, jl = cameras.length; j < jl; j++) {
  21408. var camera2 = cameras[j];
  21409. if (object.layers.test(camera2.layers)) {
  21410. state.viewport(_currentViewport.copy(camera2.viewport));
  21411. currentRenderState.setupLightsView(camera2);
  21412. renderObject(object, scene, camera2, geometry, material, group);
  21413. }
  21414. }
  21415. } else {
  21416. renderObject(object, scene, camera, geometry, material, group);
  21417. }
  21418. }
  21419. }
  21420. function renderObject(object, scene, camera, geometry, material, group) {
  21421. object.onBeforeRender(_this, scene, camera, geometry, material, group);
  21422. object.modelViewMatrix.multiplyMatrices(camera.matrixWorldInverse, object.matrixWorld);
  21423. object.normalMatrix.getNormalMatrix(object.modelViewMatrix);
  21424. if (object.isImmediateRenderObject) {
  21425. var program = setProgram(camera, scene, material, object);
  21426. state.setMaterial(material);
  21427. bindingStates.reset();
  21428. renderObjectImmediate(object, program);
  21429. } else {
  21430. _this.renderBufferDirect(camera, scene, geometry, material, object, group);
  21431. }
  21432. object.onAfterRender(_this, scene, camera, geometry, material, group);
  21433. }
  21434. function initMaterial(material, scene, object) {
  21435. if (scene.isScene !== true) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  21436. var materialProperties = properties.get(material);
  21437. var lights = currentRenderState.state.lights;
  21438. var shadowsArray = currentRenderState.state.shadowsArray;
  21439. var lightsStateVersion = lights.state.version;
  21440. var parameters = programCache.getParameters(material, lights.state, shadowsArray, scene, object);
  21441. var programCacheKey = programCache.getProgramCacheKey(parameters);
  21442. var program = materialProperties.program;
  21443. var programChange = true; // always update environment and fog - changing these trigger an initMaterial call, but it's possible that the program doesn't change
  21444. materialProperties.environment = material.isMeshStandardMaterial ? scene.environment : null;
  21445. materialProperties.fog = scene.fog;
  21446. materialProperties.envMap = cubemaps.get(material.envMap || materialProperties.environment);
  21447. if (program === undefined) {
  21448. // new material
  21449. material.addEventListener('dispose', onMaterialDispose);
  21450. } else if (program.cacheKey !== programCacheKey) {
  21451. // changed glsl or parameters
  21452. releaseMaterialProgramReference(material);
  21453. } else if (materialProperties.lightsStateVersion !== lightsStateVersion) {
  21454. programChange = false;
  21455. } else if (parameters.shaderID !== undefined) {
  21456. // same glsl and uniform list
  21457. return;
  21458. } else {
  21459. // only rebuild uniform list
  21460. programChange = false;
  21461. }
  21462. if (programChange) {
  21463. parameters.uniforms = programCache.getUniforms(material);
  21464. material.onBeforeCompile(parameters, _this);
  21465. program = programCache.acquireProgram(parameters, programCacheKey);
  21466. materialProperties.program = program;
  21467. materialProperties.uniforms = parameters.uniforms;
  21468. materialProperties.outputEncoding = parameters.outputEncoding;
  21469. }
  21470. var uniforms = materialProperties.uniforms;
  21471. if (!material.isShaderMaterial && !material.isRawShaderMaterial || material.clipping === true) {
  21472. materialProperties.numClippingPlanes = clipping.numPlanes;
  21473. materialProperties.numIntersection = clipping.numIntersection;
  21474. uniforms.clippingPlanes = clipping.uniform;
  21475. } // store the light setup it was created for
  21476. materialProperties.needsLights = materialNeedsLights(material);
  21477. materialProperties.lightsStateVersion = lightsStateVersion;
  21478. if (materialProperties.needsLights) {
  21479. // wire up the material to this renderer's lighting state
  21480. uniforms.ambientLightColor.value = lights.state.ambient;
  21481. uniforms.lightProbe.value = lights.state.probe;
  21482. uniforms.directionalLights.value = lights.state.directional;
  21483. uniforms.directionalLightShadows.value = lights.state.directionalShadow;
  21484. uniforms.spotLights.value = lights.state.spot;
  21485. uniforms.spotLightShadows.value = lights.state.spotShadow;
  21486. uniforms.rectAreaLights.value = lights.state.rectArea;
  21487. uniforms.ltc_1.value = lights.state.rectAreaLTC1;
  21488. uniforms.ltc_2.value = lights.state.rectAreaLTC2;
  21489. uniforms.pointLights.value = lights.state.point;
  21490. uniforms.pointLightShadows.value = lights.state.pointShadow;
  21491. uniforms.hemisphereLights.value = lights.state.hemi;
  21492. uniforms.directionalShadowMap.value = lights.state.directionalShadowMap;
  21493. uniforms.directionalShadowMatrix.value = lights.state.directionalShadowMatrix;
  21494. uniforms.spotShadowMap.value = lights.state.spotShadowMap;
  21495. uniforms.spotShadowMatrix.value = lights.state.spotShadowMatrix;
  21496. uniforms.pointShadowMap.value = lights.state.pointShadowMap;
  21497. uniforms.pointShadowMatrix.value = lights.state.pointShadowMatrix; // TODO (abelnation): add area lights shadow info to uniforms
  21498. }
  21499. var progUniforms = materialProperties.program.getUniforms();
  21500. var uniformsList = WebGLUniforms.seqWithValue(progUniforms.seq, uniforms);
  21501. materialProperties.uniformsList = uniformsList;
  21502. }
  21503. function setProgram(camera, scene, material, object) {
  21504. if (scene.isScene !== true) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  21505. textures.resetTextureUnits();
  21506. var fog = scene.fog;
  21507. var environment = material.isMeshStandardMaterial ? scene.environment : null;
  21508. var encoding = _currentRenderTarget === null ? _this.outputEncoding : _currentRenderTarget.texture.encoding;
  21509. var envMap = cubemaps.get(material.envMap || environment);
  21510. var materialProperties = properties.get(material);
  21511. var lights = currentRenderState.state.lights;
  21512. if (_clippingEnabled === true) {
  21513. if (_localClippingEnabled === true || camera !== _currentCamera) {
  21514. var useCache = camera === _currentCamera && material.id === _currentMaterialId; // we might want to call this function with some ClippingGroup
  21515. // object instead of the material, once it becomes feasible
  21516. // (#8465, #8379)
  21517. clipping.setState(material, camera, useCache);
  21518. }
  21519. }
  21520. if (material.version === materialProperties.__version) {
  21521. if (material.fog && materialProperties.fog !== fog) {
  21522. initMaterial(material, scene, object);
  21523. } else if (materialProperties.environment !== environment) {
  21524. initMaterial(material, scene, object);
  21525. } else if (materialProperties.needsLights && materialProperties.lightsStateVersion !== lights.state.version) {
  21526. initMaterial(material, scene, object);
  21527. } else if (materialProperties.numClippingPlanes !== undefined && (materialProperties.numClippingPlanes !== clipping.numPlanes || materialProperties.numIntersection !== clipping.numIntersection)) {
  21528. initMaterial(material, scene, object);
  21529. } else if (materialProperties.outputEncoding !== encoding) {
  21530. initMaterial(material, scene, object);
  21531. } else if (materialProperties.envMap !== envMap) {
  21532. initMaterial(material, scene, object);
  21533. }
  21534. } else {
  21535. initMaterial(material, scene, object);
  21536. materialProperties.__version = material.version;
  21537. }
  21538. var refreshProgram = false;
  21539. var refreshMaterial = false;
  21540. var refreshLights = false;
  21541. var program = materialProperties.program,
  21542. p_uniforms = program.getUniforms(),
  21543. m_uniforms = materialProperties.uniforms;
  21544. if (state.useProgram(program.program)) {
  21545. refreshProgram = true;
  21546. refreshMaterial = true;
  21547. refreshLights = true;
  21548. }
  21549. if (material.id !== _currentMaterialId) {
  21550. _currentMaterialId = material.id;
  21551. refreshMaterial = true;
  21552. }
  21553. if (refreshProgram || _currentCamera !== camera) {
  21554. p_uniforms.setValue(_gl, 'projectionMatrix', camera.projectionMatrix);
  21555. if (capabilities.logarithmicDepthBuffer) {
  21556. p_uniforms.setValue(_gl, 'logDepthBufFC', 2.0 / (Math.log(camera.far + 1.0) / Math.LN2));
  21557. }
  21558. if (_currentCamera !== camera) {
  21559. _currentCamera = camera; // lighting uniforms depend on the camera so enforce an update
  21560. // now, in case this material supports lights - or later, when
  21561. // the next material that does gets activated:
  21562. refreshMaterial = true; // set to true on material change
  21563. refreshLights = true; // remains set until update done
  21564. } // load material specific uniforms
  21565. // (shader material also gets them for the sake of genericity)
  21566. if (material.isShaderMaterial || material.isMeshPhongMaterial || material.isMeshToonMaterial || material.isMeshStandardMaterial || material.envMap) {
  21567. var uCamPos = p_uniforms.map.cameraPosition;
  21568. if (uCamPos !== undefined) {
  21569. uCamPos.setValue(_gl, _vector3.setFromMatrixPosition(camera.matrixWorld));
  21570. }
  21571. }
  21572. if (material.isMeshPhongMaterial || material.isMeshToonMaterial || material.isMeshLambertMaterial || material.isMeshBasicMaterial || material.isMeshStandardMaterial || material.isShaderMaterial) {
  21573. p_uniforms.setValue(_gl, 'isOrthographic', camera.isOrthographicCamera === true);
  21574. }
  21575. if (material.isMeshPhongMaterial || material.isMeshToonMaterial || material.isMeshLambertMaterial || material.isMeshBasicMaterial || material.isMeshStandardMaterial || material.isShaderMaterial || material.isShadowMaterial || material.skinning) {
  21576. p_uniforms.setValue(_gl, 'viewMatrix', camera.matrixWorldInverse);
  21577. }
  21578. } // skinning uniforms must be set even if material didn't change
  21579. // auto-setting of texture unit for bone texture must go before other textures
  21580. // otherwise textures used for skinning can take over texture units reserved for other material textures
  21581. if (material.skinning) {
  21582. p_uniforms.setOptional(_gl, object, 'bindMatrix');
  21583. p_uniforms.setOptional(_gl, object, 'bindMatrixInverse');
  21584. var skeleton = object.skeleton;
  21585. if (skeleton) {
  21586. var bones = skeleton.bones;
  21587. if (capabilities.floatVertexTextures) {
  21588. if (skeleton.boneTexture === null) {
  21589. // layout (1 matrix = 4 pixels)
  21590. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  21591. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  21592. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  21593. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  21594. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  21595. var size = Math.sqrt(bones.length * 4); // 4 pixels needed for 1 matrix
  21596. size = MathUtils.ceilPowerOfTwo(size);
  21597. size = Math.max(size, 4);
  21598. var boneMatrices = new Float32Array(size * size * 4); // 4 floats per RGBA pixel
  21599. boneMatrices.set(skeleton.boneMatrices); // copy current values
  21600. var boneTexture = new DataTexture(boneMatrices, size, size, RGBAFormat, FloatType);
  21601. skeleton.boneMatrices = boneMatrices;
  21602. skeleton.boneTexture = boneTexture;
  21603. skeleton.boneTextureSize = size;
  21604. }
  21605. p_uniforms.setValue(_gl, 'boneTexture', skeleton.boneTexture, textures);
  21606. p_uniforms.setValue(_gl, 'boneTextureSize', skeleton.boneTextureSize);
  21607. } else {
  21608. p_uniforms.setOptional(_gl, skeleton, 'boneMatrices');
  21609. }
  21610. }
  21611. }
  21612. if (refreshMaterial || materialProperties.receiveShadow !== object.receiveShadow) {
  21613. materialProperties.receiveShadow = object.receiveShadow;
  21614. p_uniforms.setValue(_gl, 'receiveShadow', object.receiveShadow);
  21615. }
  21616. if (refreshMaterial) {
  21617. p_uniforms.setValue(_gl, 'toneMappingExposure', _this.toneMappingExposure);
  21618. if (materialProperties.needsLights) {
  21619. // the current material requires lighting info
  21620. // note: all lighting uniforms are always set correctly
  21621. // they simply reference the renderer's state for their
  21622. // values
  21623. //
  21624. // use the current material's .needsUpdate flags to set
  21625. // the GL state when required
  21626. markUniformsLightsNeedsUpdate(m_uniforms, refreshLights);
  21627. } // refresh uniforms common to several materials
  21628. if (fog && material.fog) {
  21629. materials.refreshFogUniforms(m_uniforms, fog);
  21630. }
  21631. materials.refreshMaterialUniforms(m_uniforms, material, _pixelRatio, _height);
  21632. WebGLUniforms.upload(_gl, materialProperties.uniformsList, m_uniforms, textures);
  21633. }
  21634. if (material.isShaderMaterial && material.uniformsNeedUpdate === true) {
  21635. WebGLUniforms.upload(_gl, materialProperties.uniformsList, m_uniforms, textures);
  21636. material.uniformsNeedUpdate = false;
  21637. }
  21638. if (material.isSpriteMaterial) {
  21639. p_uniforms.setValue(_gl, 'center', object.center);
  21640. } // common matrices
  21641. p_uniforms.setValue(_gl, 'modelViewMatrix', object.modelViewMatrix);
  21642. p_uniforms.setValue(_gl, 'normalMatrix', object.normalMatrix);
  21643. p_uniforms.setValue(_gl, 'modelMatrix', object.matrixWorld);
  21644. return program;
  21645. } // If uniforms are marked as clean, they don't need to be loaded to the GPU.
  21646. function markUniformsLightsNeedsUpdate(uniforms, value) {
  21647. uniforms.ambientLightColor.needsUpdate = value;
  21648. uniforms.lightProbe.needsUpdate = value;
  21649. uniforms.directionalLights.needsUpdate = value;
  21650. uniforms.directionalLightShadows.needsUpdate = value;
  21651. uniforms.pointLights.needsUpdate = value;
  21652. uniforms.pointLightShadows.needsUpdate = value;
  21653. uniforms.spotLights.needsUpdate = value;
  21654. uniforms.spotLightShadows.needsUpdate = value;
  21655. uniforms.rectAreaLights.needsUpdate = value;
  21656. uniforms.hemisphereLights.needsUpdate = value;
  21657. }
  21658. function materialNeedsLights(material) {
  21659. return material.isMeshLambertMaterial || material.isMeshToonMaterial || material.isMeshPhongMaterial || material.isMeshStandardMaterial || material.isShadowMaterial || material.isShaderMaterial && material.lights === true;
  21660. } // this.setTexture2D = setTexture2D;
  21661. this.setTexture2D = function () {
  21662. var warned = false; // backwards compatibility: peel texture.texture
  21663. return function setTexture2D(texture, slot) {
  21664. if (texture && texture.isWebGLRenderTarget) {
  21665. if (!warned) {
  21666. console.warn("THREE.WebGLRenderer.setTexture2D: don't use render targets as textures. Use their .texture property instead.");
  21667. warned = true;
  21668. }
  21669. texture = texture.texture;
  21670. }
  21671. textures.setTexture2D(texture, slot);
  21672. };
  21673. }(); //
  21674. this.setFramebuffer = function (value) {
  21675. if (_framebuffer !== value && _currentRenderTarget === null) _gl.bindFramebuffer(36160, value);
  21676. _framebuffer = value;
  21677. };
  21678. this.getActiveCubeFace = function () {
  21679. return _currentActiveCubeFace;
  21680. };
  21681. this.getActiveMipmapLevel = function () {
  21682. return _currentActiveMipmapLevel;
  21683. };
  21684. this.getRenderList = function () {
  21685. return currentRenderList;
  21686. };
  21687. this.setRenderList = function (renderList) {
  21688. currentRenderList = renderList;
  21689. };
  21690. this.getRenderTarget = function () {
  21691. return _currentRenderTarget;
  21692. };
  21693. this.setRenderTarget = function (renderTarget, activeCubeFace, activeMipmapLevel) {
  21694. if (activeCubeFace === void 0) {
  21695. activeCubeFace = 0;
  21696. }
  21697. if (activeMipmapLevel === void 0) {
  21698. activeMipmapLevel = 0;
  21699. }
  21700. _currentRenderTarget = renderTarget;
  21701. _currentActiveCubeFace = activeCubeFace;
  21702. _currentActiveMipmapLevel = activeMipmapLevel;
  21703. if (renderTarget && properties.get(renderTarget).__webglFramebuffer === undefined) {
  21704. textures.setupRenderTarget(renderTarget);
  21705. }
  21706. var framebuffer = _framebuffer;
  21707. var isCube = false;
  21708. if (renderTarget) {
  21709. var __webglFramebuffer = properties.get(renderTarget).__webglFramebuffer;
  21710. if (renderTarget.isWebGLCubeRenderTarget) {
  21711. framebuffer = __webglFramebuffer[activeCubeFace];
  21712. isCube = true;
  21713. } else if (renderTarget.isWebGLMultisampleRenderTarget) {
  21714. framebuffer = properties.get(renderTarget).__webglMultisampledFramebuffer;
  21715. } else {
  21716. framebuffer = __webglFramebuffer;
  21717. }
  21718. _currentViewport.copy(renderTarget.viewport);
  21719. _currentScissor.copy(renderTarget.scissor);
  21720. _currentScissorTest = renderTarget.scissorTest;
  21721. } else {
  21722. _currentViewport.copy(_viewport).multiplyScalar(_pixelRatio).floor();
  21723. _currentScissor.copy(_scissor).multiplyScalar(_pixelRatio).floor();
  21724. _currentScissorTest = _scissorTest;
  21725. }
  21726. if (_currentFramebuffer !== framebuffer) {
  21727. _gl.bindFramebuffer(36160, framebuffer);
  21728. _currentFramebuffer = framebuffer;
  21729. }
  21730. state.viewport(_currentViewport);
  21731. state.scissor(_currentScissor);
  21732. state.setScissorTest(_currentScissorTest);
  21733. if (isCube) {
  21734. var textureProperties = properties.get(renderTarget.texture);
  21735. _gl.framebufferTexture2D(36160, 36064, 34069 + activeCubeFace, textureProperties.__webglTexture, activeMipmapLevel);
  21736. }
  21737. };
  21738. this.readRenderTargetPixels = function (renderTarget, x, y, width, height, buffer, activeCubeFaceIndex) {
  21739. if (!(renderTarget && renderTarget.isWebGLRenderTarget)) {
  21740. console.error('THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.');
  21741. return;
  21742. }
  21743. var framebuffer = properties.get(renderTarget).__webglFramebuffer;
  21744. if (renderTarget.isWebGLCubeRenderTarget && activeCubeFaceIndex !== undefined) {
  21745. framebuffer = framebuffer[activeCubeFaceIndex];
  21746. }
  21747. if (framebuffer) {
  21748. var restore = false;
  21749. if (framebuffer !== _currentFramebuffer) {
  21750. _gl.bindFramebuffer(36160, framebuffer);
  21751. restore = true;
  21752. }
  21753. try {
  21754. var texture = renderTarget.texture;
  21755. var textureFormat = texture.format;
  21756. var textureType = texture.type;
  21757. if (textureFormat !== RGBAFormat && utils.convert(textureFormat) !== _gl.getParameter(35739)) {
  21758. console.error('THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.');
  21759. return;
  21760. }
  21761. var halfFloatSupportedByExt = textureType === HalfFloatType && (extensions.has('EXT_color_buffer_half_float') || capabilities.isWebGL2 && extensions.has('EXT_color_buffer_float'));
  21762. if (textureType !== UnsignedByteType && utils.convert(textureType) !== _gl.getParameter(35738) && // IE11, Edge and Chrome Mac < 52 (#9513)
  21763. !(textureType === FloatType && (capabilities.isWebGL2 || extensions.has('OES_texture_float') || extensions.has('WEBGL_color_buffer_float'))) && // Chrome Mac >= 52 and Firefox
  21764. !halfFloatSupportedByExt) {
  21765. console.error('THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.');
  21766. return;
  21767. }
  21768. if (_gl.checkFramebufferStatus(36160) === 36053) {
  21769. // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  21770. if (x >= 0 && x <= renderTarget.width - width && y >= 0 && y <= renderTarget.height - height) {
  21771. _gl.readPixels(x, y, width, height, utils.convert(textureFormat), utils.convert(textureType), buffer);
  21772. }
  21773. } else {
  21774. console.error('THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete.');
  21775. }
  21776. } finally {
  21777. if (restore) {
  21778. _gl.bindFramebuffer(36160, _currentFramebuffer);
  21779. }
  21780. }
  21781. }
  21782. };
  21783. this.copyFramebufferToTexture = function (position, texture, level) {
  21784. if (level === void 0) {
  21785. level = 0;
  21786. }
  21787. var levelScale = Math.pow(2, -level);
  21788. var width = Math.floor(texture.image.width * levelScale);
  21789. var height = Math.floor(texture.image.height * levelScale);
  21790. var glFormat = utils.convert(texture.format);
  21791. textures.setTexture2D(texture, 0);
  21792. _gl.copyTexImage2D(3553, level, glFormat, position.x, position.y, width, height, 0);
  21793. state.unbindTexture();
  21794. };
  21795. this.copyTextureToTexture = function (position, srcTexture, dstTexture, level) {
  21796. if (level === void 0) {
  21797. level = 0;
  21798. }
  21799. var width = srcTexture.image.width;
  21800. var height = srcTexture.image.height;
  21801. var glFormat = utils.convert(dstTexture.format);
  21802. var glType = utils.convert(dstTexture.type);
  21803. textures.setTexture2D(dstTexture, 0); // As another texture upload may have changed pixelStorei
  21804. // parameters, make sure they are correct for the dstTexture
  21805. _gl.pixelStorei(37440, dstTexture.flipY);
  21806. _gl.pixelStorei(37441, dstTexture.premultiplyAlpha);
  21807. _gl.pixelStorei(3317, dstTexture.unpackAlignment);
  21808. if (srcTexture.isDataTexture) {
  21809. _gl.texSubImage2D(3553, level, position.x, position.y, width, height, glFormat, glType, srcTexture.image.data);
  21810. } else {
  21811. if (srcTexture.isCompressedTexture) {
  21812. _gl.compressedTexSubImage2D(3553, level, position.x, position.y, srcTexture.mipmaps[0].width, srcTexture.mipmaps[0].height, glFormat, srcTexture.mipmaps[0].data);
  21813. } else {
  21814. _gl.texSubImage2D(3553, level, position.x, position.y, glFormat, glType, srcTexture.image);
  21815. }
  21816. } // Generate mipmaps only when copying level 0
  21817. if (level === 0 && dstTexture.generateMipmaps) _gl.generateMipmap(3553);
  21818. state.unbindTexture();
  21819. };
  21820. this.initTexture = function (texture) {
  21821. textures.setTexture2D(texture, 0);
  21822. state.unbindTexture();
  21823. };
  21824. this.resetState = function () {
  21825. state.reset();
  21826. bindingStates.reset();
  21827. };
  21828. if (typeof __THREE_DEVTOOLS__ !== 'undefined') {
  21829. __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent('observe', {
  21830. detail: this
  21831. })); // eslint-disable-line no-undef
  21832. }
  21833. }
  21834. function WebGL1Renderer(parameters) {
  21835. WebGLRenderer.call(this, parameters);
  21836. }
  21837. WebGL1Renderer.prototype = Object.assign(Object.create(WebGLRenderer.prototype), {
  21838. constructor: WebGL1Renderer,
  21839. isWebGL1Renderer: true
  21840. });
  21841. var FogExp2 = /*#__PURE__*/function () {
  21842. function FogExp2(color, density) {
  21843. Object.defineProperty(this, 'isFogExp2', {
  21844. value: true
  21845. });
  21846. this.name = '';
  21847. this.color = new Color(color);
  21848. this.density = density !== undefined ? density : 0.00025;
  21849. }
  21850. var _proto = FogExp2.prototype;
  21851. _proto.clone = function clone() {
  21852. return new FogExp2(this.color, this.density);
  21853. };
  21854. _proto.toJSON = function toJSON()
  21855. /* meta */
  21856. {
  21857. return {
  21858. type: 'FogExp2',
  21859. color: this.color.getHex(),
  21860. density: this.density
  21861. };
  21862. };
  21863. return FogExp2;
  21864. }();
  21865. var Fog = /*#__PURE__*/function () {
  21866. function Fog(color, near, far) {
  21867. Object.defineProperty(this, 'isFog', {
  21868. value: true
  21869. });
  21870. this.name = '';
  21871. this.color = new Color(color);
  21872. this.near = near !== undefined ? near : 1;
  21873. this.far = far !== undefined ? far : 1000;
  21874. }
  21875. var _proto = Fog.prototype;
  21876. _proto.clone = function clone() {
  21877. return new Fog(this.color, this.near, this.far);
  21878. };
  21879. _proto.toJSON = function toJSON()
  21880. /* meta */
  21881. {
  21882. return {
  21883. type: 'Fog',
  21884. color: this.color.getHex(),
  21885. near: this.near,
  21886. far: this.far
  21887. };
  21888. };
  21889. return Fog;
  21890. }();
  21891. var Scene = /*#__PURE__*/function (_Object3D) {
  21892. _inheritsLoose(Scene, _Object3D);
  21893. function Scene() {
  21894. var _this;
  21895. _this = _Object3D.call(this) || this;
  21896. Object.defineProperty(_assertThisInitialized(_this), 'isScene', {
  21897. value: true
  21898. });
  21899. _this.type = 'Scene';
  21900. _this.background = null;
  21901. _this.environment = null;
  21902. _this.fog = null;
  21903. _this.overrideMaterial = null;
  21904. _this.autoUpdate = true; // checked by the renderer
  21905. if (typeof __THREE_DEVTOOLS__ !== 'undefined') {
  21906. __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent('observe', {
  21907. detail: _assertThisInitialized(_this)
  21908. })); // eslint-disable-line no-undef
  21909. }
  21910. return _this;
  21911. }
  21912. var _proto = Scene.prototype;
  21913. _proto.copy = function copy(source, recursive) {
  21914. _Object3D.prototype.copy.call(this, source, recursive);
  21915. if (source.background !== null) this.background = source.background.clone();
  21916. if (source.environment !== null) this.environment = source.environment.clone();
  21917. if (source.fog !== null) this.fog = source.fog.clone();
  21918. if (source.overrideMaterial !== null) this.overrideMaterial = source.overrideMaterial.clone();
  21919. this.autoUpdate = source.autoUpdate;
  21920. this.matrixAutoUpdate = source.matrixAutoUpdate;
  21921. return this;
  21922. };
  21923. _proto.toJSON = function toJSON(meta) {
  21924. var data = _Object3D.prototype.toJSON.call(this, meta);
  21925. if (this.background !== null) data.object.background = this.background.toJSON(meta);
  21926. if (this.environment !== null) data.object.environment = this.environment.toJSON(meta);
  21927. if (this.fog !== null) data.object.fog = this.fog.toJSON();
  21928. return data;
  21929. };
  21930. return Scene;
  21931. }(Object3D);
  21932. function InterleavedBuffer(array, stride) {
  21933. this.array = array;
  21934. this.stride = stride;
  21935. this.count = array !== undefined ? array.length / stride : 0;
  21936. this.usage = StaticDrawUsage;
  21937. this.updateRange = {
  21938. offset: 0,
  21939. count: -1
  21940. };
  21941. this.version = 0;
  21942. this.uuid = MathUtils.generateUUID();
  21943. }
  21944. Object.defineProperty(InterleavedBuffer.prototype, 'needsUpdate', {
  21945. set: function set(value) {
  21946. if (value === true) this.version++;
  21947. }
  21948. });
  21949. Object.assign(InterleavedBuffer.prototype, {
  21950. isInterleavedBuffer: true,
  21951. onUploadCallback: function onUploadCallback() {},
  21952. setUsage: function setUsage(value) {
  21953. this.usage = value;
  21954. return this;
  21955. },
  21956. copy: function copy(source) {
  21957. this.array = new source.array.constructor(source.array);
  21958. this.count = source.count;
  21959. this.stride = source.stride;
  21960. this.usage = source.usage;
  21961. return this;
  21962. },
  21963. copyAt: function copyAt(index1, attribute, index2) {
  21964. index1 *= this.stride;
  21965. index2 *= attribute.stride;
  21966. for (var i = 0, l = this.stride; i < l; i++) {
  21967. this.array[index1 + i] = attribute.array[index2 + i];
  21968. }
  21969. return this;
  21970. },
  21971. set: function set(value, offset) {
  21972. if (offset === void 0) {
  21973. offset = 0;
  21974. }
  21975. this.array.set(value, offset);
  21976. return this;
  21977. },
  21978. clone: function clone(data) {
  21979. if (data.arrayBuffers === undefined) {
  21980. data.arrayBuffers = {};
  21981. }
  21982. if (this.array.buffer._uuid === undefined) {
  21983. this.array.buffer._uuid = MathUtils.generateUUID();
  21984. }
  21985. if (data.arrayBuffers[this.array.buffer._uuid] === undefined) {
  21986. data.arrayBuffers[this.array.buffer._uuid] = this.array.slice(0).buffer;
  21987. }
  21988. var array = new this.array.constructor(data.arrayBuffers[this.array.buffer._uuid]);
  21989. var ib = new InterleavedBuffer(array, this.stride);
  21990. ib.setUsage(this.usage);
  21991. return ib;
  21992. },
  21993. onUpload: function onUpload(callback) {
  21994. this.onUploadCallback = callback;
  21995. return this;
  21996. },
  21997. toJSON: function toJSON(data) {
  21998. if (data.arrayBuffers === undefined) {
  21999. data.arrayBuffers = {};
  22000. } // generate UUID for array buffer if necessary
  22001. if (this.array.buffer._uuid === undefined) {
  22002. this.array.buffer._uuid = MathUtils.generateUUID();
  22003. }
  22004. if (data.arrayBuffers[this.array.buffer._uuid] === undefined) {
  22005. data.arrayBuffers[this.array.buffer._uuid] = Array.prototype.slice.call(new Uint32Array(this.array.buffer));
  22006. } //
  22007. return {
  22008. uuid: this.uuid,
  22009. buffer: this.array.buffer._uuid,
  22010. type: this.array.constructor.name,
  22011. stride: this.stride
  22012. };
  22013. }
  22014. });
  22015. var _vector$6 = new Vector3();
  22016. function InterleavedBufferAttribute(interleavedBuffer, itemSize, offset, normalized) {
  22017. this.name = '';
  22018. this.data = interleavedBuffer;
  22019. this.itemSize = itemSize;
  22020. this.offset = offset;
  22021. this.normalized = normalized === true;
  22022. }
  22023. Object.defineProperties(InterleavedBufferAttribute.prototype, {
  22024. count: {
  22025. get: function get() {
  22026. return this.data.count;
  22027. }
  22028. },
  22029. array: {
  22030. get: function get() {
  22031. return this.data.array;
  22032. }
  22033. },
  22034. needsUpdate: {
  22035. set: function set(value) {
  22036. this.data.needsUpdate = value;
  22037. }
  22038. }
  22039. });
  22040. Object.assign(InterleavedBufferAttribute.prototype, {
  22041. isInterleavedBufferAttribute: true,
  22042. applyMatrix4: function applyMatrix4(m) {
  22043. for (var i = 0, l = this.data.count; i < l; i++) {
  22044. _vector$6.x = this.getX(i);
  22045. _vector$6.y = this.getY(i);
  22046. _vector$6.z = this.getZ(i);
  22047. _vector$6.applyMatrix4(m);
  22048. this.setXYZ(i, _vector$6.x, _vector$6.y, _vector$6.z);
  22049. }
  22050. return this;
  22051. },
  22052. setX: function setX(index, x) {
  22053. this.data.array[index * this.data.stride + this.offset] = x;
  22054. return this;
  22055. },
  22056. setY: function setY(index, y) {
  22057. this.data.array[index * this.data.stride + this.offset + 1] = y;
  22058. return this;
  22059. },
  22060. setZ: function setZ(index, z) {
  22061. this.data.array[index * this.data.stride + this.offset + 2] = z;
  22062. return this;
  22063. },
  22064. setW: function setW(index, w) {
  22065. this.data.array[index * this.data.stride + this.offset + 3] = w;
  22066. return this;
  22067. },
  22068. getX: function getX(index) {
  22069. return this.data.array[index * this.data.stride + this.offset];
  22070. },
  22071. getY: function getY(index) {
  22072. return this.data.array[index * this.data.stride + this.offset + 1];
  22073. },
  22074. getZ: function getZ(index) {
  22075. return this.data.array[index * this.data.stride + this.offset + 2];
  22076. },
  22077. getW: function getW(index) {
  22078. return this.data.array[index * this.data.stride + this.offset + 3];
  22079. },
  22080. setXY: function setXY(index, x, y) {
  22081. index = index * this.data.stride + this.offset;
  22082. this.data.array[index + 0] = x;
  22083. this.data.array[index + 1] = y;
  22084. return this;
  22085. },
  22086. setXYZ: function setXYZ(index, x, y, z) {
  22087. index = index * this.data.stride + this.offset;
  22088. this.data.array[index + 0] = x;
  22089. this.data.array[index + 1] = y;
  22090. this.data.array[index + 2] = z;
  22091. return this;
  22092. },
  22093. setXYZW: function setXYZW(index, x, y, z, w) {
  22094. index = index * this.data.stride + this.offset;
  22095. this.data.array[index + 0] = x;
  22096. this.data.array[index + 1] = y;
  22097. this.data.array[index + 2] = z;
  22098. this.data.array[index + 3] = w;
  22099. return this;
  22100. },
  22101. clone: function clone(data) {
  22102. if (data === undefined) {
  22103. console.log('THREE.InterleavedBufferAttribute.clone(): Cloning an interlaved buffer attribute will deinterleave buffer data.');
  22104. var array = [];
  22105. for (var i = 0; i < this.count; i++) {
  22106. var index = i * this.data.stride + this.offset;
  22107. for (var j = 0; j < this.itemSize; j++) {
  22108. array.push(this.data.array[index + j]);
  22109. }
  22110. }
  22111. return new BufferAttribute(new this.array.constructor(array), this.itemSize, this.normalized);
  22112. } else {
  22113. if (data.interleavedBuffers === undefined) {
  22114. data.interleavedBuffers = {};
  22115. }
  22116. if (data.interleavedBuffers[this.data.uuid] === undefined) {
  22117. data.interleavedBuffers[this.data.uuid] = this.data.clone(data);
  22118. }
  22119. return new InterleavedBufferAttribute(data.interleavedBuffers[this.data.uuid], this.itemSize, this.offset, this.normalized);
  22120. }
  22121. },
  22122. toJSON: function toJSON(data) {
  22123. if (data === undefined) {
  22124. console.log('THREE.InterleavedBufferAttribute.toJSON(): Serializing an interlaved buffer attribute will deinterleave buffer data.');
  22125. var array = [];
  22126. for (var i = 0; i < this.count; i++) {
  22127. var index = i * this.data.stride + this.offset;
  22128. for (var j = 0; j < this.itemSize; j++) {
  22129. array.push(this.data.array[index + j]);
  22130. }
  22131. } // deinterleave data and save it as an ordinary buffer attribute for now
  22132. return {
  22133. itemSize: this.itemSize,
  22134. type: this.array.constructor.name,
  22135. array: array,
  22136. normalized: this.normalized
  22137. };
  22138. } else {
  22139. // save as true interlaved attribtue
  22140. if (data.interleavedBuffers === undefined) {
  22141. data.interleavedBuffers = {};
  22142. }
  22143. if (data.interleavedBuffers[this.data.uuid] === undefined) {
  22144. data.interleavedBuffers[this.data.uuid] = this.data.toJSON(data);
  22145. }
  22146. return {
  22147. isInterleavedBufferAttribute: true,
  22148. itemSize: this.itemSize,
  22149. data: this.data.uuid,
  22150. offset: this.offset,
  22151. normalized: this.normalized
  22152. };
  22153. }
  22154. }
  22155. });
  22156. /**
  22157. * parameters = {
  22158. * color: <hex>,
  22159. * map: new THREE.Texture( <Image> ),
  22160. * alphaMap: new THREE.Texture( <Image> ),
  22161. * rotation: <float>,
  22162. * sizeAttenuation: <bool>
  22163. * }
  22164. */
  22165. function SpriteMaterial(parameters) {
  22166. Material.call(this);
  22167. this.type = 'SpriteMaterial';
  22168. this.color = new Color(0xffffff);
  22169. this.map = null;
  22170. this.alphaMap = null;
  22171. this.rotation = 0;
  22172. this.sizeAttenuation = true;
  22173. this.transparent = true;
  22174. this.setValues(parameters);
  22175. }
  22176. SpriteMaterial.prototype = Object.create(Material.prototype);
  22177. SpriteMaterial.prototype.constructor = SpriteMaterial;
  22178. SpriteMaterial.prototype.isSpriteMaterial = true;
  22179. SpriteMaterial.prototype.copy = function (source) {
  22180. Material.prototype.copy.call(this, source);
  22181. this.color.copy(source.color);
  22182. this.map = source.map;
  22183. this.alphaMap = source.alphaMap;
  22184. this.rotation = source.rotation;
  22185. this.sizeAttenuation = source.sizeAttenuation;
  22186. return this;
  22187. };
  22188. var _geometry;
  22189. var _intersectPoint = new Vector3();
  22190. var _worldScale = new Vector3();
  22191. var _mvPosition = new Vector3();
  22192. var _alignedPosition = new Vector2();
  22193. var _rotatedPosition = new Vector2();
  22194. var _viewWorldMatrix = new Matrix4();
  22195. var _vA$1 = new Vector3();
  22196. var _vB$1 = new Vector3();
  22197. var _vC$1 = new Vector3();
  22198. var _uvA$1 = new Vector2();
  22199. var _uvB$1 = new Vector2();
  22200. var _uvC$1 = new Vector2();
  22201. function Sprite(material) {
  22202. Object3D.call(this);
  22203. this.type = 'Sprite';
  22204. if (_geometry === undefined) {
  22205. _geometry = new BufferGeometry();
  22206. var float32Array = new Float32Array([-0.5, -0.5, 0, 0, 0, 0.5, -0.5, 0, 1, 0, 0.5, 0.5, 0, 1, 1, -0.5, 0.5, 0, 0, 1]);
  22207. var interleavedBuffer = new InterleavedBuffer(float32Array, 5);
  22208. _geometry.setIndex([0, 1, 2, 0, 2, 3]);
  22209. _geometry.setAttribute('position', new InterleavedBufferAttribute(interleavedBuffer, 3, 0, false));
  22210. _geometry.setAttribute('uv', new InterleavedBufferAttribute(interleavedBuffer, 2, 3, false));
  22211. }
  22212. this.geometry = _geometry;
  22213. this.material = material !== undefined ? material : new SpriteMaterial();
  22214. this.center = new Vector2(0.5, 0.5);
  22215. }
  22216. Sprite.prototype = Object.assign(Object.create(Object3D.prototype), {
  22217. constructor: Sprite,
  22218. isSprite: true,
  22219. raycast: function raycast(raycaster, intersects) {
  22220. if (raycaster.camera === null) {
  22221. console.error('THREE.Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.');
  22222. }
  22223. _worldScale.setFromMatrixScale(this.matrixWorld);
  22224. _viewWorldMatrix.copy(raycaster.camera.matrixWorld);
  22225. this.modelViewMatrix.multiplyMatrices(raycaster.camera.matrixWorldInverse, this.matrixWorld);
  22226. _mvPosition.setFromMatrixPosition(this.modelViewMatrix);
  22227. if (raycaster.camera.isPerspectiveCamera && this.material.sizeAttenuation === false) {
  22228. _worldScale.multiplyScalar(-_mvPosition.z);
  22229. }
  22230. var rotation = this.material.rotation;
  22231. var sin, cos;
  22232. if (rotation !== 0) {
  22233. cos = Math.cos(rotation);
  22234. sin = Math.sin(rotation);
  22235. }
  22236. var center = this.center;
  22237. transformVertex(_vA$1.set(-0.5, -0.5, 0), _mvPosition, center, _worldScale, sin, cos);
  22238. transformVertex(_vB$1.set(0.5, -0.5, 0), _mvPosition, center, _worldScale, sin, cos);
  22239. transformVertex(_vC$1.set(0.5, 0.5, 0), _mvPosition, center, _worldScale, sin, cos);
  22240. _uvA$1.set(0, 0);
  22241. _uvB$1.set(1, 0);
  22242. _uvC$1.set(1, 1); // check first triangle
  22243. var intersect = raycaster.ray.intersectTriangle(_vA$1, _vB$1, _vC$1, false, _intersectPoint);
  22244. if (intersect === null) {
  22245. // check second triangle
  22246. transformVertex(_vB$1.set(-0.5, 0.5, 0), _mvPosition, center, _worldScale, sin, cos);
  22247. _uvB$1.set(0, 1);
  22248. intersect = raycaster.ray.intersectTriangle(_vA$1, _vC$1, _vB$1, false, _intersectPoint);
  22249. if (intersect === null) {
  22250. return;
  22251. }
  22252. }
  22253. var distance = raycaster.ray.origin.distanceTo(_intersectPoint);
  22254. if (distance < raycaster.near || distance > raycaster.far) return;
  22255. intersects.push({
  22256. distance: distance,
  22257. point: _intersectPoint.clone(),
  22258. uv: Triangle.getUV(_intersectPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2()),
  22259. face: null,
  22260. object: this
  22261. });
  22262. },
  22263. copy: function copy(source) {
  22264. Object3D.prototype.copy.call(this, source);
  22265. if (source.center !== undefined) this.center.copy(source.center);
  22266. this.material = source.material;
  22267. return this;
  22268. }
  22269. });
  22270. function transformVertex(vertexPosition, mvPosition, center, scale, sin, cos) {
  22271. // compute position in camera space
  22272. _alignedPosition.subVectors(vertexPosition, center).addScalar(0.5).multiply(scale); // to check if rotation is not zero
  22273. if (sin !== undefined) {
  22274. _rotatedPosition.x = cos * _alignedPosition.x - sin * _alignedPosition.y;
  22275. _rotatedPosition.y = sin * _alignedPosition.x + cos * _alignedPosition.y;
  22276. } else {
  22277. _rotatedPosition.copy(_alignedPosition);
  22278. }
  22279. vertexPosition.copy(mvPosition);
  22280. vertexPosition.x += _rotatedPosition.x;
  22281. vertexPosition.y += _rotatedPosition.y; // transform to world space
  22282. vertexPosition.applyMatrix4(_viewWorldMatrix);
  22283. }
  22284. var _v1$4 = new Vector3();
  22285. var _v2$2 = new Vector3();
  22286. function LOD() {
  22287. Object3D.call(this);
  22288. this._currentLevel = 0;
  22289. this.type = 'LOD';
  22290. Object.defineProperties(this, {
  22291. levels: {
  22292. enumerable: true,
  22293. value: []
  22294. }
  22295. });
  22296. this.autoUpdate = true;
  22297. }
  22298. LOD.prototype = Object.assign(Object.create(Object3D.prototype), {
  22299. constructor: LOD,
  22300. isLOD: true,
  22301. copy: function copy(source) {
  22302. Object3D.prototype.copy.call(this, source, false);
  22303. var levels = source.levels;
  22304. for (var i = 0, l = levels.length; i < l; i++) {
  22305. var level = levels[i];
  22306. this.addLevel(level.object.clone(), level.distance);
  22307. }
  22308. this.autoUpdate = source.autoUpdate;
  22309. return this;
  22310. },
  22311. addLevel: function addLevel(object, distance) {
  22312. if (distance === void 0) {
  22313. distance = 0;
  22314. }
  22315. distance = Math.abs(distance);
  22316. var levels = this.levels;
  22317. var l;
  22318. for (l = 0; l < levels.length; l++) {
  22319. if (distance < levels[l].distance) {
  22320. break;
  22321. }
  22322. }
  22323. levels.splice(l, 0, {
  22324. distance: distance,
  22325. object: object
  22326. });
  22327. this.add(object);
  22328. return this;
  22329. },
  22330. getCurrentLevel: function getCurrentLevel() {
  22331. return this._currentLevel;
  22332. },
  22333. getObjectForDistance: function getObjectForDistance(distance) {
  22334. var levels = this.levels;
  22335. if (levels.length > 0) {
  22336. var i, l;
  22337. for (i = 1, l = levels.length; i < l; i++) {
  22338. if (distance < levels[i].distance) {
  22339. break;
  22340. }
  22341. }
  22342. return levels[i - 1].object;
  22343. }
  22344. return null;
  22345. },
  22346. raycast: function raycast(raycaster, intersects) {
  22347. var levels = this.levels;
  22348. if (levels.length > 0) {
  22349. _v1$4.setFromMatrixPosition(this.matrixWorld);
  22350. var distance = raycaster.ray.origin.distanceTo(_v1$4);
  22351. this.getObjectForDistance(distance).raycast(raycaster, intersects);
  22352. }
  22353. },
  22354. update: function update(camera) {
  22355. var levels = this.levels;
  22356. if (levels.length > 1) {
  22357. _v1$4.setFromMatrixPosition(camera.matrixWorld);
  22358. _v2$2.setFromMatrixPosition(this.matrixWorld);
  22359. var distance = _v1$4.distanceTo(_v2$2) / camera.zoom;
  22360. levels[0].object.visible = true;
  22361. var i, l;
  22362. for (i = 1, l = levels.length; i < l; i++) {
  22363. if (distance >= levels[i].distance) {
  22364. levels[i - 1].object.visible = false;
  22365. levels[i].object.visible = true;
  22366. } else {
  22367. break;
  22368. }
  22369. }
  22370. this._currentLevel = i - 1;
  22371. for (; i < l; i++) {
  22372. levels[i].object.visible = false;
  22373. }
  22374. }
  22375. },
  22376. toJSON: function toJSON(meta) {
  22377. var data = Object3D.prototype.toJSON.call(this, meta);
  22378. if (this.autoUpdate === false) data.object.autoUpdate = false;
  22379. data.object.levels = [];
  22380. var levels = this.levels;
  22381. for (var i = 0, l = levels.length; i < l; i++) {
  22382. var level = levels[i];
  22383. data.object.levels.push({
  22384. object: level.object.uuid,
  22385. distance: level.distance
  22386. });
  22387. }
  22388. return data;
  22389. }
  22390. });
  22391. var _basePosition = new Vector3();
  22392. var _skinIndex = new Vector4();
  22393. var _skinWeight = new Vector4();
  22394. var _vector$7 = new Vector3();
  22395. var _matrix$1 = new Matrix4();
  22396. function SkinnedMesh(geometry, material) {
  22397. if (geometry && geometry.isGeometry) {
  22398. console.error('THREE.SkinnedMesh no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  22399. }
  22400. Mesh.call(this, geometry, material);
  22401. this.type = 'SkinnedMesh';
  22402. this.bindMode = 'attached';
  22403. this.bindMatrix = new Matrix4();
  22404. this.bindMatrixInverse = new Matrix4();
  22405. }
  22406. SkinnedMesh.prototype = Object.assign(Object.create(Mesh.prototype), {
  22407. constructor: SkinnedMesh,
  22408. isSkinnedMesh: true,
  22409. copy: function copy(source) {
  22410. Mesh.prototype.copy.call(this, source);
  22411. this.bindMode = source.bindMode;
  22412. this.bindMatrix.copy(source.bindMatrix);
  22413. this.bindMatrixInverse.copy(source.bindMatrixInverse);
  22414. this.skeleton = source.skeleton;
  22415. return this;
  22416. },
  22417. bind: function bind(skeleton, bindMatrix) {
  22418. this.skeleton = skeleton;
  22419. if (bindMatrix === undefined) {
  22420. this.updateMatrixWorld(true);
  22421. this.skeleton.calculateInverses();
  22422. bindMatrix = this.matrixWorld;
  22423. }
  22424. this.bindMatrix.copy(bindMatrix);
  22425. this.bindMatrixInverse.copy(bindMatrix).invert();
  22426. },
  22427. pose: function pose() {
  22428. this.skeleton.pose();
  22429. },
  22430. normalizeSkinWeights: function normalizeSkinWeights() {
  22431. var vector = new Vector4();
  22432. var skinWeight = this.geometry.attributes.skinWeight;
  22433. for (var i = 0, l = skinWeight.count; i < l; i++) {
  22434. vector.x = skinWeight.getX(i);
  22435. vector.y = skinWeight.getY(i);
  22436. vector.z = skinWeight.getZ(i);
  22437. vector.w = skinWeight.getW(i);
  22438. var scale = 1.0 / vector.manhattanLength();
  22439. if (scale !== Infinity) {
  22440. vector.multiplyScalar(scale);
  22441. } else {
  22442. vector.set(1, 0, 0, 0); // do something reasonable
  22443. }
  22444. skinWeight.setXYZW(i, vector.x, vector.y, vector.z, vector.w);
  22445. }
  22446. },
  22447. updateMatrixWorld: function updateMatrixWorld(force) {
  22448. Mesh.prototype.updateMatrixWorld.call(this, force);
  22449. if (this.bindMode === 'attached') {
  22450. this.bindMatrixInverse.copy(this.matrixWorld).invert();
  22451. } else if (this.bindMode === 'detached') {
  22452. this.bindMatrixInverse.copy(this.bindMatrix).invert();
  22453. } else {
  22454. console.warn('THREE.SkinnedMesh: Unrecognized bindMode: ' + this.bindMode);
  22455. }
  22456. },
  22457. boneTransform: function boneTransform(index, target) {
  22458. var skeleton = this.skeleton;
  22459. var geometry = this.geometry;
  22460. _skinIndex.fromBufferAttribute(geometry.attributes.skinIndex, index);
  22461. _skinWeight.fromBufferAttribute(geometry.attributes.skinWeight, index);
  22462. _basePosition.fromBufferAttribute(geometry.attributes.position, index).applyMatrix4(this.bindMatrix);
  22463. target.set(0, 0, 0);
  22464. for (var i = 0; i < 4; i++) {
  22465. var weight = _skinWeight.getComponent(i);
  22466. if (weight !== 0) {
  22467. var boneIndex = _skinIndex.getComponent(i);
  22468. _matrix$1.multiplyMatrices(skeleton.bones[boneIndex].matrixWorld, skeleton.boneInverses[boneIndex]);
  22469. target.addScaledVector(_vector$7.copy(_basePosition).applyMatrix4(_matrix$1), weight);
  22470. }
  22471. }
  22472. return target.applyMatrix4(this.bindMatrixInverse);
  22473. }
  22474. });
  22475. function Bone() {
  22476. Object3D.call(this);
  22477. this.type = 'Bone';
  22478. }
  22479. Bone.prototype = Object.assign(Object.create(Object3D.prototype), {
  22480. constructor: Bone,
  22481. isBone: true
  22482. });
  22483. var _offsetMatrix = new Matrix4();
  22484. var _identityMatrix = new Matrix4();
  22485. function Skeleton(bones, boneInverses) {
  22486. if (bones === void 0) {
  22487. bones = [];
  22488. }
  22489. if (boneInverses === void 0) {
  22490. boneInverses = [];
  22491. }
  22492. this.uuid = MathUtils.generateUUID();
  22493. this.bones = bones.slice(0);
  22494. this.boneInverses = boneInverses;
  22495. this.boneMatrices = null;
  22496. this.boneTexture = null;
  22497. this.boneTextureSize = 0;
  22498. this.frame = -1;
  22499. this.init();
  22500. }
  22501. Object.assign(Skeleton.prototype, {
  22502. init: function init() {
  22503. var bones = this.bones;
  22504. var boneInverses = this.boneInverses;
  22505. this.boneMatrices = new Float32Array(bones.length * 16); // calculate inverse bone matrices if necessary
  22506. if (boneInverses.length === 0) {
  22507. this.calculateInverses();
  22508. } else {
  22509. // handle special case
  22510. if (bones.length !== boneInverses.length) {
  22511. console.warn('THREE.Skeleton: Number of inverse bone matrices does not match amount of bones.');
  22512. this.boneInverses = [];
  22513. for (var i = 0, il = this.bones.length; i < il; i++) {
  22514. this.boneInverses.push(new Matrix4());
  22515. }
  22516. }
  22517. }
  22518. },
  22519. calculateInverses: function calculateInverses() {
  22520. this.boneInverses.length = 0;
  22521. for (var i = 0, il = this.bones.length; i < il; i++) {
  22522. var inverse = new Matrix4();
  22523. if (this.bones[i]) {
  22524. inverse.copy(this.bones[i].matrixWorld).invert();
  22525. }
  22526. this.boneInverses.push(inverse);
  22527. }
  22528. },
  22529. pose: function pose() {
  22530. // recover the bind-time world matrices
  22531. for (var i = 0, il = this.bones.length; i < il; i++) {
  22532. var bone = this.bones[i];
  22533. if (bone) {
  22534. bone.matrixWorld.copy(this.boneInverses[i]).invert();
  22535. }
  22536. } // compute the local matrices, positions, rotations and scales
  22537. for (var _i = 0, _il = this.bones.length; _i < _il; _i++) {
  22538. var _bone = this.bones[_i];
  22539. if (_bone) {
  22540. if (_bone.parent && _bone.parent.isBone) {
  22541. _bone.matrix.copy(_bone.parent.matrixWorld).invert();
  22542. _bone.matrix.multiply(_bone.matrixWorld);
  22543. } else {
  22544. _bone.matrix.copy(_bone.matrixWorld);
  22545. }
  22546. _bone.matrix.decompose(_bone.position, _bone.quaternion, _bone.scale);
  22547. }
  22548. }
  22549. },
  22550. update: function update() {
  22551. var bones = this.bones;
  22552. var boneInverses = this.boneInverses;
  22553. var boneMatrices = this.boneMatrices;
  22554. var boneTexture = this.boneTexture; // flatten bone matrices to array
  22555. for (var i = 0, il = bones.length; i < il; i++) {
  22556. // compute the offset between the current and the original transform
  22557. var matrix = bones[i] ? bones[i].matrixWorld : _identityMatrix;
  22558. _offsetMatrix.multiplyMatrices(matrix, boneInverses[i]);
  22559. _offsetMatrix.toArray(boneMatrices, i * 16);
  22560. }
  22561. if (boneTexture !== null) {
  22562. boneTexture.needsUpdate = true;
  22563. }
  22564. },
  22565. clone: function clone() {
  22566. return new Skeleton(this.bones, this.boneInverses);
  22567. },
  22568. getBoneByName: function getBoneByName(name) {
  22569. for (var i = 0, il = this.bones.length; i < il; i++) {
  22570. var bone = this.bones[i];
  22571. if (bone.name === name) {
  22572. return bone;
  22573. }
  22574. }
  22575. return undefined;
  22576. },
  22577. dispose: function dispose() {
  22578. if (this.boneTexture !== null) {
  22579. this.boneTexture.dispose();
  22580. this.boneTexture = null;
  22581. }
  22582. },
  22583. fromJSON: function fromJSON(json, bones) {
  22584. this.uuid = json.uuid;
  22585. for (var i = 0, l = json.bones.length; i < l; i++) {
  22586. var uuid = json.bones[i];
  22587. var bone = bones[uuid];
  22588. if (bone === undefined) {
  22589. console.warn('THREE.Skeleton: No bone found with UUID:', uuid);
  22590. bone = new Bone();
  22591. }
  22592. this.bones.push(bone);
  22593. this.boneInverses.push(new Matrix4().fromArray(json.boneInverses[i]));
  22594. }
  22595. this.init();
  22596. return this;
  22597. },
  22598. toJSON: function toJSON() {
  22599. var data = {
  22600. metadata: {
  22601. version: 4.5,
  22602. type: 'Skeleton',
  22603. generator: 'Skeleton.toJSON'
  22604. },
  22605. bones: [],
  22606. boneInverses: []
  22607. };
  22608. data.uuid = this.uuid;
  22609. var bones = this.bones;
  22610. var boneInverses = this.boneInverses;
  22611. for (var i = 0, l = bones.length; i < l; i++) {
  22612. var bone = bones[i];
  22613. data.bones.push(bone.uuid);
  22614. var boneInverse = boneInverses[i];
  22615. data.boneInverses.push(boneInverse.toArray());
  22616. }
  22617. return data;
  22618. }
  22619. });
  22620. var _instanceLocalMatrix = new Matrix4();
  22621. var _instanceWorldMatrix = new Matrix4();
  22622. var _instanceIntersects = [];
  22623. var _mesh = new Mesh();
  22624. function InstancedMesh(geometry, material, count) {
  22625. Mesh.call(this, geometry, material);
  22626. this.instanceMatrix = new BufferAttribute(new Float32Array(count * 16), 16);
  22627. this.instanceColor = null;
  22628. this.count = count;
  22629. this.frustumCulled = false;
  22630. }
  22631. InstancedMesh.prototype = Object.assign(Object.create(Mesh.prototype), {
  22632. constructor: InstancedMesh,
  22633. isInstancedMesh: true,
  22634. copy: function copy(source) {
  22635. Mesh.prototype.copy.call(this, source);
  22636. this.instanceMatrix.copy(source.instanceMatrix);
  22637. if (source.instanceColor !== null) this.instanceColor = source.instanceColor.clone();
  22638. this.count = source.count;
  22639. return this;
  22640. },
  22641. getColorAt: function getColorAt(index, color) {
  22642. color.fromArray(this.instanceColor.array, index * 3);
  22643. },
  22644. getMatrixAt: function getMatrixAt(index, matrix) {
  22645. matrix.fromArray(this.instanceMatrix.array, index * 16);
  22646. },
  22647. raycast: function raycast(raycaster, intersects) {
  22648. var matrixWorld = this.matrixWorld;
  22649. var raycastTimes = this.count;
  22650. _mesh.geometry = this.geometry;
  22651. _mesh.material = this.material;
  22652. if (_mesh.material === undefined) return;
  22653. for (var instanceId = 0; instanceId < raycastTimes; instanceId++) {
  22654. // calculate the world matrix for each instance
  22655. this.getMatrixAt(instanceId, _instanceLocalMatrix);
  22656. _instanceWorldMatrix.multiplyMatrices(matrixWorld, _instanceLocalMatrix); // the mesh represents this single instance
  22657. _mesh.matrixWorld = _instanceWorldMatrix;
  22658. _mesh.raycast(raycaster, _instanceIntersects); // process the result of raycast
  22659. for (var i = 0, l = _instanceIntersects.length; i < l; i++) {
  22660. var intersect = _instanceIntersects[i];
  22661. intersect.instanceId = instanceId;
  22662. intersect.object = this;
  22663. intersects.push(intersect);
  22664. }
  22665. _instanceIntersects.length = 0;
  22666. }
  22667. },
  22668. setColorAt: function setColorAt(index, color) {
  22669. if (this.instanceColor === null) {
  22670. this.instanceColor = new BufferAttribute(new Float32Array(this.count * 3), 3);
  22671. }
  22672. color.toArray(this.instanceColor.array, index * 3);
  22673. },
  22674. setMatrixAt: function setMatrixAt(index, matrix) {
  22675. matrix.toArray(this.instanceMatrix.array, index * 16);
  22676. },
  22677. updateMorphTargets: function updateMorphTargets() {},
  22678. dispose: function dispose() {
  22679. this.dispatchEvent({
  22680. type: 'dispose'
  22681. });
  22682. }
  22683. });
  22684. /**
  22685. * parameters = {
  22686. * color: <hex>,
  22687. * opacity: <float>,
  22688. *
  22689. * linewidth: <float>,
  22690. * linecap: "round",
  22691. * linejoin: "round"
  22692. * }
  22693. */
  22694. function LineBasicMaterial(parameters) {
  22695. Material.call(this);
  22696. this.type = 'LineBasicMaterial';
  22697. this.color = new Color(0xffffff);
  22698. this.linewidth = 1;
  22699. this.linecap = 'round';
  22700. this.linejoin = 'round';
  22701. this.morphTargets = false;
  22702. this.setValues(parameters);
  22703. }
  22704. LineBasicMaterial.prototype = Object.create(Material.prototype);
  22705. LineBasicMaterial.prototype.constructor = LineBasicMaterial;
  22706. LineBasicMaterial.prototype.isLineBasicMaterial = true;
  22707. LineBasicMaterial.prototype.copy = function (source) {
  22708. Material.prototype.copy.call(this, source);
  22709. this.color.copy(source.color);
  22710. this.linewidth = source.linewidth;
  22711. this.linecap = source.linecap;
  22712. this.linejoin = source.linejoin;
  22713. this.morphTargets = source.morphTargets;
  22714. return this;
  22715. };
  22716. var _start = new Vector3();
  22717. var _end = new Vector3();
  22718. var _inverseMatrix$1 = new Matrix4();
  22719. var _ray$1 = new Ray();
  22720. var _sphere$2 = new Sphere();
  22721. function Line(geometry, material) {
  22722. if (geometry === void 0) {
  22723. geometry = new BufferGeometry();
  22724. }
  22725. if (material === void 0) {
  22726. material = new LineBasicMaterial();
  22727. }
  22728. Object3D.call(this);
  22729. this.type = 'Line';
  22730. this.geometry = geometry;
  22731. this.material = material;
  22732. this.updateMorphTargets();
  22733. }
  22734. Line.prototype = Object.assign(Object.create(Object3D.prototype), {
  22735. constructor: Line,
  22736. isLine: true,
  22737. copy: function copy(source) {
  22738. Object3D.prototype.copy.call(this, source);
  22739. this.material = source.material;
  22740. this.geometry = source.geometry;
  22741. return this;
  22742. },
  22743. computeLineDistances: function computeLineDistances() {
  22744. var geometry = this.geometry;
  22745. if (geometry.isBufferGeometry) {
  22746. // we assume non-indexed geometry
  22747. if (geometry.index === null) {
  22748. var positionAttribute = geometry.attributes.position;
  22749. var lineDistances = [0];
  22750. for (var i = 1, l = positionAttribute.count; i < l; i++) {
  22751. _start.fromBufferAttribute(positionAttribute, i - 1);
  22752. _end.fromBufferAttribute(positionAttribute, i);
  22753. lineDistances[i] = lineDistances[i - 1];
  22754. lineDistances[i] += _start.distanceTo(_end);
  22755. }
  22756. geometry.setAttribute('lineDistance', new Float32BufferAttribute(lineDistances, 1));
  22757. } else {
  22758. console.warn('THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.');
  22759. }
  22760. } else if (geometry.isGeometry) {
  22761. console.error('THREE.Line.computeLineDistances() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  22762. }
  22763. return this;
  22764. },
  22765. raycast: function raycast(raycaster, intersects) {
  22766. var geometry = this.geometry;
  22767. var matrixWorld = this.matrixWorld;
  22768. var threshold = raycaster.params.Line.threshold; // Checking boundingSphere distance to ray
  22769. if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
  22770. _sphere$2.copy(geometry.boundingSphere);
  22771. _sphere$2.applyMatrix4(matrixWorld);
  22772. _sphere$2.radius += threshold;
  22773. if (raycaster.ray.intersectsSphere(_sphere$2) === false) return; //
  22774. _inverseMatrix$1.copy(matrixWorld).invert();
  22775. _ray$1.copy(raycaster.ray).applyMatrix4(_inverseMatrix$1);
  22776. var localThreshold = threshold / ((this.scale.x + this.scale.y + this.scale.z) / 3);
  22777. var localThresholdSq = localThreshold * localThreshold;
  22778. var vStart = new Vector3();
  22779. var vEnd = new Vector3();
  22780. var interSegment = new Vector3();
  22781. var interRay = new Vector3();
  22782. var step = this.isLineSegments ? 2 : 1;
  22783. if (geometry.isBufferGeometry) {
  22784. var index = geometry.index;
  22785. var attributes = geometry.attributes;
  22786. var positionAttribute = attributes.position;
  22787. if (index !== null) {
  22788. var indices = index.array;
  22789. for (var i = 0, l = indices.length - 1; i < l; i += step) {
  22790. var a = indices[i];
  22791. var b = indices[i + 1];
  22792. vStart.fromBufferAttribute(positionAttribute, a);
  22793. vEnd.fromBufferAttribute(positionAttribute, b);
  22794. var distSq = _ray$1.distanceSqToSegment(vStart, vEnd, interRay, interSegment);
  22795. if (distSq > localThresholdSq) continue;
  22796. interRay.applyMatrix4(this.matrixWorld); //Move back to world space for distance calculation
  22797. var distance = raycaster.ray.origin.distanceTo(interRay);
  22798. if (distance < raycaster.near || distance > raycaster.far) continue;
  22799. intersects.push({
  22800. distance: distance,
  22801. // What do we want? intersection point on the ray or on the segment??
  22802. // point: raycaster.ray.at( distance ),
  22803. point: interSegment.clone().applyMatrix4(this.matrixWorld),
  22804. index: i,
  22805. face: null,
  22806. faceIndex: null,
  22807. object: this
  22808. });
  22809. }
  22810. } else {
  22811. for (var _i = 0, _l = positionAttribute.count - 1; _i < _l; _i += step) {
  22812. vStart.fromBufferAttribute(positionAttribute, _i);
  22813. vEnd.fromBufferAttribute(positionAttribute, _i + 1);
  22814. var _distSq = _ray$1.distanceSqToSegment(vStart, vEnd, interRay, interSegment);
  22815. if (_distSq > localThresholdSq) continue;
  22816. interRay.applyMatrix4(this.matrixWorld); //Move back to world space for distance calculation
  22817. var _distance = raycaster.ray.origin.distanceTo(interRay);
  22818. if (_distance < raycaster.near || _distance > raycaster.far) continue;
  22819. intersects.push({
  22820. distance: _distance,
  22821. // What do we want? intersection point on the ray or on the segment??
  22822. // point: raycaster.ray.at( distance ),
  22823. point: interSegment.clone().applyMatrix4(this.matrixWorld),
  22824. index: _i,
  22825. face: null,
  22826. faceIndex: null,
  22827. object: this
  22828. });
  22829. }
  22830. }
  22831. } else if (geometry.isGeometry) {
  22832. console.error('THREE.Line.raycast() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  22833. }
  22834. },
  22835. updateMorphTargets: function updateMorphTargets() {
  22836. var geometry = this.geometry;
  22837. if (geometry.isBufferGeometry) {
  22838. var morphAttributes = geometry.morphAttributes;
  22839. var keys = Object.keys(morphAttributes);
  22840. if (keys.length > 0) {
  22841. var morphAttribute = morphAttributes[keys[0]];
  22842. if (morphAttribute !== undefined) {
  22843. this.morphTargetInfluences = [];
  22844. this.morphTargetDictionary = {};
  22845. for (var m = 0, ml = morphAttribute.length; m < ml; m++) {
  22846. var name = morphAttribute[m].name || String(m);
  22847. this.morphTargetInfluences.push(0);
  22848. this.morphTargetDictionary[name] = m;
  22849. }
  22850. }
  22851. }
  22852. } else {
  22853. var morphTargets = geometry.morphTargets;
  22854. if (morphTargets !== undefined && morphTargets.length > 0) {
  22855. console.error('THREE.Line.updateMorphTargets() does not support THREE.Geometry. Use THREE.BufferGeometry instead.');
  22856. }
  22857. }
  22858. }
  22859. });
  22860. var _start$1 = new Vector3();
  22861. var _end$1 = new Vector3();
  22862. function LineSegments(geometry, material) {
  22863. Line.call(this, geometry, material);
  22864. this.type = 'LineSegments';
  22865. }
  22866. LineSegments.prototype = Object.assign(Object.create(Line.prototype), {
  22867. constructor: LineSegments,
  22868. isLineSegments: true,
  22869. computeLineDistances: function computeLineDistances() {
  22870. var geometry = this.geometry;
  22871. if (geometry.isBufferGeometry) {
  22872. // we assume non-indexed geometry
  22873. if (geometry.index === null) {
  22874. var positionAttribute = geometry.attributes.position;
  22875. var lineDistances = [];
  22876. for (var i = 0, l = positionAttribute.count; i < l; i += 2) {
  22877. _start$1.fromBufferAttribute(positionAttribute, i);
  22878. _end$1.fromBufferAttribute(positionAttribute, i + 1);
  22879. lineDistances[i] = i === 0 ? 0 : lineDistances[i - 1];
  22880. lineDistances[i + 1] = lineDistances[i] + _start$1.distanceTo(_end$1);
  22881. }
  22882. geometry.setAttribute('lineDistance', new Float32BufferAttribute(lineDistances, 1));
  22883. } else {
  22884. console.warn('THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.');
  22885. }
  22886. } else if (geometry.isGeometry) {
  22887. console.error('THREE.LineSegments.computeLineDistances() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  22888. }
  22889. return this;
  22890. }
  22891. });
  22892. function LineLoop(geometry, material) {
  22893. Line.call(this, geometry, material);
  22894. this.type = 'LineLoop';
  22895. }
  22896. LineLoop.prototype = Object.assign(Object.create(Line.prototype), {
  22897. constructor: LineLoop,
  22898. isLineLoop: true
  22899. });
  22900. /**
  22901. * parameters = {
  22902. * color: <hex>,
  22903. * opacity: <float>,
  22904. * map: new THREE.Texture( <Image> ),
  22905. * alphaMap: new THREE.Texture( <Image> ),
  22906. *
  22907. * size: <float>,
  22908. * sizeAttenuation: <bool>
  22909. *
  22910. * morphTargets: <bool>
  22911. * }
  22912. */
  22913. function PointsMaterial(parameters) {
  22914. Material.call(this);
  22915. this.type = 'PointsMaterial';
  22916. this.color = new Color(0xffffff);
  22917. this.map = null;
  22918. this.alphaMap = null;
  22919. this.size = 1;
  22920. this.sizeAttenuation = true;
  22921. this.morphTargets = false;
  22922. this.setValues(parameters);
  22923. }
  22924. PointsMaterial.prototype = Object.create(Material.prototype);
  22925. PointsMaterial.prototype.constructor = PointsMaterial;
  22926. PointsMaterial.prototype.isPointsMaterial = true;
  22927. PointsMaterial.prototype.copy = function (source) {
  22928. Material.prototype.copy.call(this, source);
  22929. this.color.copy(source.color);
  22930. this.map = source.map;
  22931. this.alphaMap = source.alphaMap;
  22932. this.size = source.size;
  22933. this.sizeAttenuation = source.sizeAttenuation;
  22934. this.morphTargets = source.morphTargets;
  22935. return this;
  22936. };
  22937. var _inverseMatrix$2 = new Matrix4();
  22938. var _ray$2 = new Ray();
  22939. var _sphere$3 = new Sphere();
  22940. var _position$1 = new Vector3();
  22941. function Points(geometry, material) {
  22942. if (geometry === void 0) {
  22943. geometry = new BufferGeometry();
  22944. }
  22945. if (material === void 0) {
  22946. material = new PointsMaterial();
  22947. }
  22948. Object3D.call(this);
  22949. this.type = 'Points';
  22950. this.geometry = geometry;
  22951. this.material = material;
  22952. this.updateMorphTargets();
  22953. }
  22954. Points.prototype = Object.assign(Object.create(Object3D.prototype), {
  22955. constructor: Points,
  22956. isPoints: true,
  22957. copy: function copy(source) {
  22958. Object3D.prototype.copy.call(this, source);
  22959. this.material = source.material;
  22960. this.geometry = source.geometry;
  22961. return this;
  22962. },
  22963. raycast: function raycast(raycaster, intersects) {
  22964. var geometry = this.geometry;
  22965. var matrixWorld = this.matrixWorld;
  22966. var threshold = raycaster.params.Points.threshold; // Checking boundingSphere distance to ray
  22967. if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
  22968. _sphere$3.copy(geometry.boundingSphere);
  22969. _sphere$3.applyMatrix4(matrixWorld);
  22970. _sphere$3.radius += threshold;
  22971. if (raycaster.ray.intersectsSphere(_sphere$3) === false) return; //
  22972. _inverseMatrix$2.copy(matrixWorld).invert();
  22973. _ray$2.copy(raycaster.ray).applyMatrix4(_inverseMatrix$2);
  22974. var localThreshold = threshold / ((this.scale.x + this.scale.y + this.scale.z) / 3);
  22975. var localThresholdSq = localThreshold * localThreshold;
  22976. if (geometry.isBufferGeometry) {
  22977. var index = geometry.index;
  22978. var attributes = geometry.attributes;
  22979. var positionAttribute = attributes.position;
  22980. if (index !== null) {
  22981. var indices = index.array;
  22982. for (var i = 0, il = indices.length; i < il; i++) {
  22983. var a = indices[i];
  22984. _position$1.fromBufferAttribute(positionAttribute, a);
  22985. testPoint(_position$1, a, localThresholdSq, matrixWorld, raycaster, intersects, this);
  22986. }
  22987. } else {
  22988. for (var _i = 0, l = positionAttribute.count; _i < l; _i++) {
  22989. _position$1.fromBufferAttribute(positionAttribute, _i);
  22990. testPoint(_position$1, _i, localThresholdSq, matrixWorld, raycaster, intersects, this);
  22991. }
  22992. }
  22993. } else {
  22994. console.error('THREE.Points.raycast() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  22995. }
  22996. },
  22997. updateMorphTargets: function updateMorphTargets() {
  22998. var geometry = this.geometry;
  22999. if (geometry.isBufferGeometry) {
  23000. var morphAttributes = geometry.morphAttributes;
  23001. var keys = Object.keys(morphAttributes);
  23002. if (keys.length > 0) {
  23003. var morphAttribute = morphAttributes[keys[0]];
  23004. if (morphAttribute !== undefined) {
  23005. this.morphTargetInfluences = [];
  23006. this.morphTargetDictionary = {};
  23007. for (var m = 0, ml = morphAttribute.length; m < ml; m++) {
  23008. var name = morphAttribute[m].name || String(m);
  23009. this.morphTargetInfluences.push(0);
  23010. this.morphTargetDictionary[name] = m;
  23011. }
  23012. }
  23013. }
  23014. } else {
  23015. var morphTargets = geometry.morphTargets;
  23016. if (morphTargets !== undefined && morphTargets.length > 0) {
  23017. console.error('THREE.Points.updateMorphTargets() does not support THREE.Geometry. Use THREE.BufferGeometry instead.');
  23018. }
  23019. }
  23020. }
  23021. });
  23022. function testPoint(point, index, localThresholdSq, matrixWorld, raycaster, intersects, object) {
  23023. var rayPointDistanceSq = _ray$2.distanceSqToPoint(point);
  23024. if (rayPointDistanceSq < localThresholdSq) {
  23025. var intersectPoint = new Vector3();
  23026. _ray$2.closestPointToPoint(point, intersectPoint);
  23027. intersectPoint.applyMatrix4(matrixWorld);
  23028. var distance = raycaster.ray.origin.distanceTo(intersectPoint);
  23029. if (distance < raycaster.near || distance > raycaster.far) return;
  23030. intersects.push({
  23031. distance: distance,
  23032. distanceToRay: Math.sqrt(rayPointDistanceSq),
  23033. point: intersectPoint,
  23034. index: index,
  23035. face: null,
  23036. object: object
  23037. });
  23038. }
  23039. }
  23040. function VideoTexture(video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy) {
  23041. Texture.call(this, video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy);
  23042. this.format = format !== undefined ? format : RGBFormat;
  23043. this.minFilter = minFilter !== undefined ? minFilter : LinearFilter;
  23044. this.magFilter = magFilter !== undefined ? magFilter : LinearFilter;
  23045. this.generateMipmaps = false;
  23046. var scope = this;
  23047. function updateVideo() {
  23048. scope.needsUpdate = true;
  23049. video.requestVideoFrameCallback(updateVideo);
  23050. }
  23051. if ('requestVideoFrameCallback' in video) {
  23052. video.requestVideoFrameCallback(updateVideo);
  23053. }
  23054. }
  23055. VideoTexture.prototype = Object.assign(Object.create(Texture.prototype), {
  23056. constructor: VideoTexture,
  23057. clone: function clone() {
  23058. return new this.constructor(this.image).copy(this);
  23059. },
  23060. isVideoTexture: true,
  23061. update: function update() {
  23062. var video = this.image;
  23063. var hasVideoFrameCallback = ('requestVideoFrameCallback' in video);
  23064. if (hasVideoFrameCallback === false && video.readyState >= video.HAVE_CURRENT_DATA) {
  23065. this.needsUpdate = true;
  23066. }
  23067. }
  23068. });
  23069. function CompressedTexture(mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding) {
  23070. Texture.call(this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding);
  23071. this.image = {
  23072. width: width,
  23073. height: height
  23074. };
  23075. this.mipmaps = mipmaps; // no flipping for cube textures
  23076. // (also flipping doesn't work for compressed textures )
  23077. this.flipY = false; // can't generate mipmaps for compressed textures
  23078. // mips must be embedded in DDS files
  23079. this.generateMipmaps = false;
  23080. }
  23081. CompressedTexture.prototype = Object.create(Texture.prototype);
  23082. CompressedTexture.prototype.constructor = CompressedTexture;
  23083. CompressedTexture.prototype.isCompressedTexture = true;
  23084. function CanvasTexture(canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy) {
  23085. Texture.call(this, canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy);
  23086. this.needsUpdate = true;
  23087. }
  23088. CanvasTexture.prototype = Object.create(Texture.prototype);
  23089. CanvasTexture.prototype.constructor = CanvasTexture;
  23090. CanvasTexture.prototype.isCanvasTexture = true;
  23091. function DepthTexture(width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format) {
  23092. format = format !== undefined ? format : DepthFormat;
  23093. if (format !== DepthFormat && format !== DepthStencilFormat) {
  23094. throw new Error('DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat');
  23095. }
  23096. if (type === undefined && format === DepthFormat) type = UnsignedShortType;
  23097. if (type === undefined && format === DepthStencilFormat) type = UnsignedInt248Type;
  23098. Texture.call(this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy);
  23099. this.image = {
  23100. width: width,
  23101. height: height
  23102. };
  23103. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  23104. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  23105. this.flipY = false;
  23106. this.generateMipmaps = false;
  23107. }
  23108. DepthTexture.prototype = Object.create(Texture.prototype);
  23109. DepthTexture.prototype.constructor = DepthTexture;
  23110. DepthTexture.prototype.isDepthTexture = true;
  23111. var CircleGeometry = /*#__PURE__*/function (_BufferGeometry) {
  23112. _inheritsLoose(CircleGeometry, _BufferGeometry);
  23113. function CircleGeometry(radius, segments, thetaStart, thetaLength) {
  23114. var _this;
  23115. if (radius === void 0) {
  23116. radius = 1;
  23117. }
  23118. if (segments === void 0) {
  23119. segments = 8;
  23120. }
  23121. if (thetaStart === void 0) {
  23122. thetaStart = 0;
  23123. }
  23124. if (thetaLength === void 0) {
  23125. thetaLength = Math.PI * 2;
  23126. }
  23127. _this = _BufferGeometry.call(this) || this;
  23128. _this.type = 'CircleGeometry';
  23129. _this.parameters = {
  23130. radius: radius,
  23131. segments: segments,
  23132. thetaStart: thetaStart,
  23133. thetaLength: thetaLength
  23134. };
  23135. segments = Math.max(3, segments); // buffers
  23136. var indices = [];
  23137. var vertices = [];
  23138. var normals = [];
  23139. var uvs = []; // helper variables
  23140. var vertex = new Vector3();
  23141. var uv = new Vector2(); // center point
  23142. vertices.push(0, 0, 0);
  23143. normals.push(0, 0, 1);
  23144. uvs.push(0.5, 0.5);
  23145. for (var s = 0, i = 3; s <= segments; s++, i += 3) {
  23146. var segment = thetaStart + s / segments * thetaLength; // vertex
  23147. vertex.x = radius * Math.cos(segment);
  23148. vertex.y = radius * Math.sin(segment);
  23149. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  23150. normals.push(0, 0, 1); // uvs
  23151. uv.x = (vertices[i] / radius + 1) / 2;
  23152. uv.y = (vertices[i + 1] / radius + 1) / 2;
  23153. uvs.push(uv.x, uv.y);
  23154. } // indices
  23155. for (var _i = 1; _i <= segments; _i++) {
  23156. indices.push(_i, _i + 1, 0);
  23157. } // build geometry
  23158. _this.setIndex(indices);
  23159. _this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  23160. _this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  23161. _this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  23162. return _this;
  23163. }
  23164. return CircleGeometry;
  23165. }(BufferGeometry);
  23166. var CylinderGeometry = /*#__PURE__*/function (_BufferGeometry) {
  23167. _inheritsLoose(CylinderGeometry, _BufferGeometry);
  23168. function CylinderGeometry(radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength) {
  23169. var _this;
  23170. if (radiusTop === void 0) {
  23171. radiusTop = 1;
  23172. }
  23173. if (radiusBottom === void 0) {
  23174. radiusBottom = 1;
  23175. }
  23176. if (height === void 0) {
  23177. height = 1;
  23178. }
  23179. if (radialSegments === void 0) {
  23180. radialSegments = 8;
  23181. }
  23182. if (heightSegments === void 0) {
  23183. heightSegments = 1;
  23184. }
  23185. if (openEnded === void 0) {
  23186. openEnded = false;
  23187. }
  23188. if (thetaStart === void 0) {
  23189. thetaStart = 0;
  23190. }
  23191. if (thetaLength === void 0) {
  23192. thetaLength = Math.PI * 2;
  23193. }
  23194. _this = _BufferGeometry.call(this) || this;
  23195. _this.type = 'CylinderGeometry';
  23196. _this.parameters = {
  23197. radiusTop: radiusTop,
  23198. radiusBottom: radiusBottom,
  23199. height: height,
  23200. radialSegments: radialSegments,
  23201. heightSegments: heightSegments,
  23202. openEnded: openEnded,
  23203. thetaStart: thetaStart,
  23204. thetaLength: thetaLength
  23205. };
  23206. var scope = _assertThisInitialized(_this);
  23207. radialSegments = Math.floor(radialSegments);
  23208. heightSegments = Math.floor(heightSegments); // buffers
  23209. var indices = [];
  23210. var vertices = [];
  23211. var normals = [];
  23212. var uvs = []; // helper variables
  23213. var index = 0;
  23214. var indexArray = [];
  23215. var halfHeight = height / 2;
  23216. var groupStart = 0; // generate geometry
  23217. generateTorso();
  23218. if (openEnded === false) {
  23219. if (radiusTop > 0) generateCap(true);
  23220. if (radiusBottom > 0) generateCap(false);
  23221. } // build geometry
  23222. _this.setIndex(indices);
  23223. _this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  23224. _this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  23225. _this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  23226. function generateTorso() {
  23227. var normal = new Vector3();
  23228. var vertex = new Vector3();
  23229. var groupCount = 0; // this will be used to calculate the normal
  23230. var slope = (radiusBottom - radiusTop) / height; // generate vertices, normals and uvs
  23231. for (var y = 0; y <= heightSegments; y++) {
  23232. var indexRow = [];
  23233. var v = y / heightSegments; // calculate the radius of the current row
  23234. var radius = v * (radiusBottom - radiusTop) + radiusTop;
  23235. for (var x = 0; x <= radialSegments; x++) {
  23236. var u = x / radialSegments;
  23237. var theta = u * thetaLength + thetaStart;
  23238. var sinTheta = Math.sin(theta);
  23239. var cosTheta = Math.cos(theta); // vertex
  23240. vertex.x = radius * sinTheta;
  23241. vertex.y = -v * height + halfHeight;
  23242. vertex.z = radius * cosTheta;
  23243. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  23244. normal.set(sinTheta, slope, cosTheta).normalize();
  23245. normals.push(normal.x, normal.y, normal.z); // uv
  23246. uvs.push(u, 1 - v); // save index of vertex in respective row
  23247. indexRow.push(index++);
  23248. } // now save vertices of the row in our index array
  23249. indexArray.push(indexRow);
  23250. } // generate indices
  23251. for (var _x = 0; _x < radialSegments; _x++) {
  23252. for (var _y = 0; _y < heightSegments; _y++) {
  23253. // we use the index array to access the correct indices
  23254. var a = indexArray[_y][_x];
  23255. var b = indexArray[_y + 1][_x];
  23256. var c = indexArray[_y + 1][_x + 1];
  23257. var d = indexArray[_y][_x + 1]; // faces
  23258. indices.push(a, b, d);
  23259. indices.push(b, c, d); // update group counter
  23260. groupCount += 6;
  23261. }
  23262. } // add a group to the geometry. this will ensure multi material support
  23263. scope.addGroup(groupStart, groupCount, 0); // calculate new start value for groups
  23264. groupStart += groupCount;
  23265. }
  23266. function generateCap(top) {
  23267. // save the index of the first center vertex
  23268. var centerIndexStart = index;
  23269. var uv = new Vector2();
  23270. var vertex = new Vector3();
  23271. var groupCount = 0;
  23272. var radius = top === true ? radiusTop : radiusBottom;
  23273. var sign = top === true ? 1 : -1; // first we generate the center vertex data of the cap.
  23274. // because the geometry needs one set of uvs per face,
  23275. // we must generate a center vertex per face/segment
  23276. for (var x = 1; x <= radialSegments; x++) {
  23277. // vertex
  23278. vertices.push(0, halfHeight * sign, 0); // normal
  23279. normals.push(0, sign, 0); // uv
  23280. uvs.push(0.5, 0.5); // increase index
  23281. index++;
  23282. } // save the index of the last center vertex
  23283. var centerIndexEnd = index; // now we generate the surrounding vertices, normals and uvs
  23284. for (var _x2 = 0; _x2 <= radialSegments; _x2++) {
  23285. var u = _x2 / radialSegments;
  23286. var theta = u * thetaLength + thetaStart;
  23287. var cosTheta = Math.cos(theta);
  23288. var sinTheta = Math.sin(theta); // vertex
  23289. vertex.x = radius * sinTheta;
  23290. vertex.y = halfHeight * sign;
  23291. vertex.z = radius * cosTheta;
  23292. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  23293. normals.push(0, sign, 0); // uv
  23294. uv.x = cosTheta * 0.5 + 0.5;
  23295. uv.y = sinTheta * 0.5 * sign + 0.5;
  23296. uvs.push(uv.x, uv.y); // increase index
  23297. index++;
  23298. } // generate indices
  23299. for (var _x3 = 0; _x3 < radialSegments; _x3++) {
  23300. var c = centerIndexStart + _x3;
  23301. var i = centerIndexEnd + _x3;
  23302. if (top === true) {
  23303. // face top
  23304. indices.push(i, i + 1, c);
  23305. } else {
  23306. // face bottom
  23307. indices.push(i + 1, i, c);
  23308. }
  23309. groupCount += 3;
  23310. } // add a group to the geometry. this will ensure multi material support
  23311. scope.addGroup(groupStart, groupCount, top === true ? 1 : 2); // calculate new start value for groups
  23312. groupStart += groupCount;
  23313. }
  23314. return _this;
  23315. }
  23316. return CylinderGeometry;
  23317. }(BufferGeometry);
  23318. var ConeGeometry = /*#__PURE__*/function (_CylinderGeometry) {
  23319. _inheritsLoose(ConeGeometry, _CylinderGeometry);
  23320. function ConeGeometry(radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength) {
  23321. var _this;
  23322. if (radius === void 0) {
  23323. radius = 1;
  23324. }
  23325. if (height === void 0) {
  23326. height = 1;
  23327. }
  23328. if (radialSegments === void 0) {
  23329. radialSegments = 8;
  23330. }
  23331. if (heightSegments === void 0) {
  23332. heightSegments = 1;
  23333. }
  23334. if (openEnded === void 0) {
  23335. openEnded = false;
  23336. }
  23337. if (thetaStart === void 0) {
  23338. thetaStart = 0;
  23339. }
  23340. if (thetaLength === void 0) {
  23341. thetaLength = Math.PI * 2;
  23342. }
  23343. _this = _CylinderGeometry.call(this, 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength) || this;
  23344. _this.type = 'ConeGeometry';
  23345. _this.parameters = {
  23346. radius: radius,
  23347. height: height,
  23348. radialSegments: radialSegments,
  23349. heightSegments: heightSegments,
  23350. openEnded: openEnded,
  23351. thetaStart: thetaStart,
  23352. thetaLength: thetaLength
  23353. };
  23354. return _this;
  23355. }
  23356. return ConeGeometry;
  23357. }(CylinderGeometry);
  23358. var PolyhedronGeometry = /*#__PURE__*/function (_BufferGeometry) {
  23359. _inheritsLoose(PolyhedronGeometry, _BufferGeometry);
  23360. function PolyhedronGeometry(vertices, indices, radius, detail) {
  23361. var _this;
  23362. if (radius === void 0) {
  23363. radius = 1;
  23364. }
  23365. if (detail === void 0) {
  23366. detail = 0;
  23367. }
  23368. _this = _BufferGeometry.call(this) || this;
  23369. _this.type = 'PolyhedronGeometry';
  23370. _this.parameters = {
  23371. vertices: vertices,
  23372. indices: indices,
  23373. radius: radius,
  23374. detail: detail
  23375. }; // default buffer data
  23376. var vertexBuffer = [];
  23377. var uvBuffer = []; // the subdivision creates the vertex buffer data
  23378. subdivide(detail); // all vertices should lie on a conceptual sphere with a given radius
  23379. applyRadius(radius); // finally, create the uv data
  23380. generateUVs(); // build non-indexed geometry
  23381. _this.setAttribute('position', new Float32BufferAttribute(vertexBuffer, 3));
  23382. _this.setAttribute('normal', new Float32BufferAttribute(vertexBuffer.slice(), 3));
  23383. _this.setAttribute('uv', new Float32BufferAttribute(uvBuffer, 2));
  23384. if (detail === 0) {
  23385. _this.computeVertexNormals(); // flat normals
  23386. } else {
  23387. _this.normalizeNormals(); // smooth normals
  23388. } // helper functions
  23389. function subdivide(detail) {
  23390. var a = new Vector3();
  23391. var b = new Vector3();
  23392. var c = new Vector3(); // iterate over all faces and apply a subdivison with the given detail value
  23393. for (var i = 0; i < indices.length; i += 3) {
  23394. // get the vertices of the face
  23395. getVertexByIndex(indices[i + 0], a);
  23396. getVertexByIndex(indices[i + 1], b);
  23397. getVertexByIndex(indices[i + 2], c); // perform subdivision
  23398. subdivideFace(a, b, c, detail);
  23399. }
  23400. }
  23401. function subdivideFace(a, b, c, detail) {
  23402. var cols = detail + 1; // we use this multidimensional array as a data structure for creating the subdivision
  23403. var v = []; // construct all of the vertices for this subdivision
  23404. for (var i = 0; i <= cols; i++) {
  23405. v[i] = [];
  23406. var aj = a.clone().lerp(c, i / cols);
  23407. var bj = b.clone().lerp(c, i / cols);
  23408. var rows = cols - i;
  23409. for (var j = 0; j <= rows; j++) {
  23410. if (j === 0 && i === cols) {
  23411. v[i][j] = aj;
  23412. } else {
  23413. v[i][j] = aj.clone().lerp(bj, j / rows);
  23414. }
  23415. }
  23416. } // construct all of the faces
  23417. for (var _i = 0; _i < cols; _i++) {
  23418. for (var _j = 0; _j < 2 * (cols - _i) - 1; _j++) {
  23419. var k = Math.floor(_j / 2);
  23420. if (_j % 2 === 0) {
  23421. pushVertex(v[_i][k + 1]);
  23422. pushVertex(v[_i + 1][k]);
  23423. pushVertex(v[_i][k]);
  23424. } else {
  23425. pushVertex(v[_i][k + 1]);
  23426. pushVertex(v[_i + 1][k + 1]);
  23427. pushVertex(v[_i + 1][k]);
  23428. }
  23429. }
  23430. }
  23431. }
  23432. function applyRadius(radius) {
  23433. var vertex = new Vector3(); // iterate over the entire buffer and apply the radius to each vertex
  23434. for (var i = 0; i < vertexBuffer.length; i += 3) {
  23435. vertex.x = vertexBuffer[i + 0];
  23436. vertex.y = vertexBuffer[i + 1];
  23437. vertex.z = vertexBuffer[i + 2];
  23438. vertex.normalize().multiplyScalar(radius);
  23439. vertexBuffer[i + 0] = vertex.x;
  23440. vertexBuffer[i + 1] = vertex.y;
  23441. vertexBuffer[i + 2] = vertex.z;
  23442. }
  23443. }
  23444. function generateUVs() {
  23445. var vertex = new Vector3();
  23446. for (var i = 0; i < vertexBuffer.length; i += 3) {
  23447. vertex.x = vertexBuffer[i + 0];
  23448. vertex.y = vertexBuffer[i + 1];
  23449. vertex.z = vertexBuffer[i + 2];
  23450. var u = azimuth(vertex) / 2 / Math.PI + 0.5;
  23451. var v = inclination(vertex) / Math.PI + 0.5;
  23452. uvBuffer.push(u, 1 - v);
  23453. }
  23454. correctUVs();
  23455. correctSeam();
  23456. }
  23457. function correctSeam() {
  23458. // handle case when face straddles the seam, see #3269
  23459. for (var i = 0; i < uvBuffer.length; i += 6) {
  23460. // uv data of a single face
  23461. var x0 = uvBuffer[i + 0];
  23462. var x1 = uvBuffer[i + 2];
  23463. var x2 = uvBuffer[i + 4];
  23464. var max = Math.max(x0, x1, x2);
  23465. var min = Math.min(x0, x1, x2); // 0.9 is somewhat arbitrary
  23466. if (max > 0.9 && min < 0.1) {
  23467. if (x0 < 0.2) uvBuffer[i + 0] += 1;
  23468. if (x1 < 0.2) uvBuffer[i + 2] += 1;
  23469. if (x2 < 0.2) uvBuffer[i + 4] += 1;
  23470. }
  23471. }
  23472. }
  23473. function pushVertex(vertex) {
  23474. vertexBuffer.push(vertex.x, vertex.y, vertex.z);
  23475. }
  23476. function getVertexByIndex(index, vertex) {
  23477. var stride = index * 3;
  23478. vertex.x = vertices[stride + 0];
  23479. vertex.y = vertices[stride + 1];
  23480. vertex.z = vertices[stride + 2];
  23481. }
  23482. function correctUVs() {
  23483. var a = new Vector3();
  23484. var b = new Vector3();
  23485. var c = new Vector3();
  23486. var centroid = new Vector3();
  23487. var uvA = new Vector2();
  23488. var uvB = new Vector2();
  23489. var uvC = new Vector2();
  23490. for (var i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6) {
  23491. a.set(vertexBuffer[i + 0], vertexBuffer[i + 1], vertexBuffer[i + 2]);
  23492. b.set(vertexBuffer[i + 3], vertexBuffer[i + 4], vertexBuffer[i + 5]);
  23493. c.set(vertexBuffer[i + 6], vertexBuffer[i + 7], vertexBuffer[i + 8]);
  23494. uvA.set(uvBuffer[j + 0], uvBuffer[j + 1]);
  23495. uvB.set(uvBuffer[j + 2], uvBuffer[j + 3]);
  23496. uvC.set(uvBuffer[j + 4], uvBuffer[j + 5]);
  23497. centroid.copy(a).add(b).add(c).divideScalar(3);
  23498. var azi = azimuth(centroid);
  23499. correctUV(uvA, j + 0, a, azi);
  23500. correctUV(uvB, j + 2, b, azi);
  23501. correctUV(uvC, j + 4, c, azi);
  23502. }
  23503. }
  23504. function correctUV(uv, stride, vector, azimuth) {
  23505. if (azimuth < 0 && uv.x === 1) {
  23506. uvBuffer[stride] = uv.x - 1;
  23507. }
  23508. if (vector.x === 0 && vector.z === 0) {
  23509. uvBuffer[stride] = azimuth / 2 / Math.PI + 0.5;
  23510. }
  23511. } // Angle around the Y axis, counter-clockwise when looking from above.
  23512. function azimuth(vector) {
  23513. return Math.atan2(vector.z, -vector.x);
  23514. } // Angle above the XZ plane.
  23515. function inclination(vector) {
  23516. return Math.atan2(-vector.y, Math.sqrt(vector.x * vector.x + vector.z * vector.z));
  23517. }
  23518. return _this;
  23519. }
  23520. return PolyhedronGeometry;
  23521. }(BufferGeometry);
  23522. var DodecahedronGeometry = /*#__PURE__*/function (_PolyhedronGeometry) {
  23523. _inheritsLoose(DodecahedronGeometry, _PolyhedronGeometry);
  23524. function DodecahedronGeometry(radius, detail) {
  23525. var _this;
  23526. if (radius === void 0) {
  23527. radius = 1;
  23528. }
  23529. if (detail === void 0) {
  23530. detail = 0;
  23531. }
  23532. var t = (1 + Math.sqrt(5)) / 2;
  23533. var r = 1 / t;
  23534. var vertices = [// (±1, ±1, ±1)
  23535. -1, -1, -1, -1, -1, 1, -1, 1, -1, -1, 1, 1, 1, -1, -1, 1, -1, 1, 1, 1, -1, 1, 1, 1, // (0, ±1/φ, ±φ)
  23536. 0, -r, -t, 0, -r, t, 0, r, -t, 0, r, t, // (±1/φ, ±φ, 0)
  23537. -r, -t, 0, -r, t, 0, r, -t, 0, r, t, 0, // (±φ, 0, ±1/φ)
  23538. -t, 0, -r, t, 0, -r, -t, 0, r, t, 0, r];
  23539. var indices = [3, 11, 7, 3, 7, 15, 3, 15, 13, 7, 19, 17, 7, 17, 6, 7, 6, 15, 17, 4, 8, 17, 8, 10, 17, 10, 6, 8, 0, 16, 8, 16, 2, 8, 2, 10, 0, 12, 1, 0, 1, 18, 0, 18, 16, 6, 10, 2, 6, 2, 13, 6, 13, 15, 2, 16, 18, 2, 18, 3, 2, 3, 13, 18, 1, 9, 18, 9, 11, 18, 11, 3, 4, 14, 12, 4, 12, 0, 4, 0, 8, 11, 9, 5, 11, 5, 19, 11, 19, 7, 19, 5, 14, 19, 14, 4, 19, 4, 17, 1, 12, 14, 1, 14, 5, 1, 5, 9];
  23540. _this = _PolyhedronGeometry.call(this, vertices, indices, radius, detail) || this;
  23541. _this.type = 'DodecahedronGeometry';
  23542. _this.parameters = {
  23543. radius: radius,
  23544. detail: detail
  23545. };
  23546. return _this;
  23547. }
  23548. return DodecahedronGeometry;
  23549. }(PolyhedronGeometry);
  23550. var _v0$2 = new Vector3();
  23551. var _v1$5 = new Vector3();
  23552. var _normal$1 = new Vector3();
  23553. var _triangle = new Triangle();
  23554. var EdgesGeometry = /*#__PURE__*/function (_BufferGeometry) {
  23555. _inheritsLoose(EdgesGeometry, _BufferGeometry);
  23556. function EdgesGeometry(geometry, thresholdAngle) {
  23557. var _this;
  23558. _this = _BufferGeometry.call(this) || this;
  23559. _this.type = 'EdgesGeometry';
  23560. _this.parameters = {
  23561. thresholdAngle: thresholdAngle
  23562. };
  23563. thresholdAngle = thresholdAngle !== undefined ? thresholdAngle : 1;
  23564. if (geometry.isGeometry === true) {
  23565. console.error('THREE.EdgesGeometry no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  23566. return _assertThisInitialized(_this);
  23567. }
  23568. var precisionPoints = 4;
  23569. var precision = Math.pow(10, precisionPoints);
  23570. var thresholdDot = Math.cos(MathUtils.DEG2RAD * thresholdAngle);
  23571. var indexAttr = geometry.getIndex();
  23572. var positionAttr = geometry.getAttribute('position');
  23573. var indexCount = indexAttr ? indexAttr.count : positionAttr.count;
  23574. var indexArr = [0, 0, 0];
  23575. var vertKeys = ['a', 'b', 'c'];
  23576. var hashes = new Array(3);
  23577. var edgeData = {};
  23578. var vertices = [];
  23579. for (var i = 0; i < indexCount; i += 3) {
  23580. if (indexAttr) {
  23581. indexArr[0] = indexAttr.getX(i);
  23582. indexArr[1] = indexAttr.getX(i + 1);
  23583. indexArr[2] = indexAttr.getX(i + 2);
  23584. } else {
  23585. indexArr[0] = i;
  23586. indexArr[1] = i + 1;
  23587. indexArr[2] = i + 2;
  23588. }
  23589. var a = _triangle.a,
  23590. b = _triangle.b,
  23591. c = _triangle.c;
  23592. a.fromBufferAttribute(positionAttr, indexArr[0]);
  23593. b.fromBufferAttribute(positionAttr, indexArr[1]);
  23594. c.fromBufferAttribute(positionAttr, indexArr[2]);
  23595. _triangle.getNormal(_normal$1); // create hashes for the edge from the vertices
  23596. hashes[0] = Math.round(a.x * precision) + "," + Math.round(a.y * precision) + "," + Math.round(a.z * precision);
  23597. hashes[1] = Math.round(b.x * precision) + "," + Math.round(b.y * precision) + "," + Math.round(b.z * precision);
  23598. hashes[2] = Math.round(c.x * precision) + "," + Math.round(c.y * precision) + "," + Math.round(c.z * precision); // skip degenerate triangles
  23599. if (hashes[0] === hashes[1] || hashes[1] === hashes[2] || hashes[2] === hashes[0]) {
  23600. continue;
  23601. } // iterate over every edge
  23602. for (var j = 0; j < 3; j++) {
  23603. // get the first and next vertex making up the edge
  23604. var jNext = (j + 1) % 3;
  23605. var vecHash0 = hashes[j];
  23606. var vecHash1 = hashes[jNext];
  23607. var v0 = _triangle[vertKeys[j]];
  23608. var v1 = _triangle[vertKeys[jNext]];
  23609. var hash = vecHash0 + "_" + vecHash1;
  23610. var reverseHash = vecHash1 + "_" + vecHash0;
  23611. if (reverseHash in edgeData && edgeData[reverseHash]) {
  23612. // if we found a sibling edge add it into the vertex array if
  23613. // it meets the angle threshold and delete the edge from the map.
  23614. if (_normal$1.dot(edgeData[reverseHash].normal) <= thresholdDot) {
  23615. vertices.push(v0.x, v0.y, v0.z);
  23616. vertices.push(v1.x, v1.y, v1.z);
  23617. }
  23618. edgeData[reverseHash] = null;
  23619. } else if (!(hash in edgeData)) {
  23620. // if we've already got an edge here then skip adding a new one
  23621. edgeData[hash] = {
  23622. index0: indexArr[j],
  23623. index1: indexArr[jNext],
  23624. normal: _normal$1.clone()
  23625. };
  23626. }
  23627. }
  23628. } // iterate over all remaining, unmatched edges and add them to the vertex array
  23629. for (var key in edgeData) {
  23630. if (edgeData[key]) {
  23631. var _edgeData$key = edgeData[key],
  23632. index0 = _edgeData$key.index0,
  23633. index1 = _edgeData$key.index1;
  23634. _v0$2.fromBufferAttribute(positionAttr, index0);
  23635. _v1$5.fromBufferAttribute(positionAttr, index1);
  23636. vertices.push(_v0$2.x, _v0$2.y, _v0$2.z);
  23637. vertices.push(_v1$5.x, _v1$5.y, _v1$5.z);
  23638. }
  23639. }
  23640. _this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  23641. return _this;
  23642. }
  23643. return EdgesGeometry;
  23644. }(BufferGeometry);
  23645. /**
  23646. * Port from https://github.com/mapbox/earcut (v2.2.2)
  23647. */
  23648. var Earcut = {
  23649. triangulate: function triangulate(data, holeIndices, dim) {
  23650. dim = dim || 2;
  23651. var hasHoles = holeIndices && holeIndices.length;
  23652. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  23653. var outerNode = linkedList(data, 0, outerLen, dim, true);
  23654. var triangles = [];
  23655. if (!outerNode || outerNode.next === outerNode.prev) return triangles;
  23656. var minX, minY, maxX, maxY, x, y, invSize;
  23657. if (hasHoles) outerNode = eliminateHoles(data, holeIndices, outerNode, dim); // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  23658. if (data.length > 80 * dim) {
  23659. minX = maxX = data[0];
  23660. minY = maxY = data[1];
  23661. for (var i = dim; i < outerLen; i += dim) {
  23662. x = data[i];
  23663. y = data[i + 1];
  23664. if (x < minX) minX = x;
  23665. if (y < minY) minY = y;
  23666. if (x > maxX) maxX = x;
  23667. if (y > maxY) maxY = y;
  23668. } // minX, minY and invSize are later used to transform coords into integers for z-order calculation
  23669. invSize = Math.max(maxX - minX, maxY - minY);
  23670. invSize = invSize !== 0 ? 1 / invSize : 0;
  23671. }
  23672. earcutLinked(outerNode, triangles, dim, minX, minY, invSize);
  23673. return triangles;
  23674. }
  23675. }; // create a circular doubly linked list from polygon points in the specified winding order
  23676. function linkedList(data, start, end, dim, clockwise) {
  23677. var i, last;
  23678. if (clockwise === signedArea(data, start, end, dim) > 0) {
  23679. for (i = start; i < end; i += dim) {
  23680. last = insertNode(i, data[i], data[i + 1], last);
  23681. }
  23682. } else {
  23683. for (i = end - dim; i >= start; i -= dim) {
  23684. last = insertNode(i, data[i], data[i + 1], last);
  23685. }
  23686. }
  23687. if (last && equals(last, last.next)) {
  23688. removeNode(last);
  23689. last = last.next;
  23690. }
  23691. return last;
  23692. } // eliminate colinear or duplicate points
  23693. function filterPoints(start, end) {
  23694. if (!start) return start;
  23695. if (!end) end = start;
  23696. var p = start,
  23697. again;
  23698. do {
  23699. again = false;
  23700. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  23701. removeNode(p);
  23702. p = end = p.prev;
  23703. if (p === p.next) break;
  23704. again = true;
  23705. } else {
  23706. p = p.next;
  23707. }
  23708. } while (again || p !== end);
  23709. return end;
  23710. } // main ear slicing loop which triangulates a polygon (given as a linked list)
  23711. function earcutLinked(ear, triangles, dim, minX, minY, invSize, pass) {
  23712. if (!ear) return; // interlink polygon nodes in z-order
  23713. if (!pass && invSize) indexCurve(ear, minX, minY, invSize);
  23714. var stop = ear,
  23715. prev,
  23716. next; // iterate through ears, slicing them one by one
  23717. while (ear.prev !== ear.next) {
  23718. prev = ear.prev;
  23719. next = ear.next;
  23720. if (invSize ? isEarHashed(ear, minX, minY, invSize) : isEar(ear)) {
  23721. // cut off the triangle
  23722. triangles.push(prev.i / dim);
  23723. triangles.push(ear.i / dim);
  23724. triangles.push(next.i / dim);
  23725. removeNode(ear); // skipping the next vertex leads to less sliver triangles
  23726. ear = next.next;
  23727. stop = next.next;
  23728. continue;
  23729. }
  23730. ear = next; // if we looped through the whole remaining polygon and can't find any more ears
  23731. if (ear === stop) {
  23732. // try filtering points and slicing again
  23733. if (!pass) {
  23734. earcutLinked(filterPoints(ear), triangles, dim, minX, minY, invSize, 1); // if this didn't work, try curing all small self-intersections locally
  23735. } else if (pass === 1) {
  23736. ear = cureLocalIntersections(filterPoints(ear), triangles, dim);
  23737. earcutLinked(ear, triangles, dim, minX, minY, invSize, 2); // as a last resort, try splitting the remaining polygon into two
  23738. } else if (pass === 2) {
  23739. splitEarcut(ear, triangles, dim, minX, minY, invSize);
  23740. }
  23741. break;
  23742. }
  23743. }
  23744. } // check whether a polygon node forms a valid ear with adjacent nodes
  23745. function isEar(ear) {
  23746. var a = ear.prev,
  23747. b = ear,
  23748. c = ear.next;
  23749. if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
  23750. // now make sure we don't have other points inside the potential ear
  23751. var p = ear.next.next;
  23752. while (p !== ear.prev) {
  23753. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false;
  23754. p = p.next;
  23755. }
  23756. return true;
  23757. }
  23758. function isEarHashed(ear, minX, minY, invSize) {
  23759. var a = ear.prev,
  23760. b = ear,
  23761. c = ear.next;
  23762. if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
  23763. // triangle bbox; min & max are calculated like this for speed
  23764. var minTX = a.x < b.x ? a.x < c.x ? a.x : c.x : b.x < c.x ? b.x : c.x,
  23765. minTY = a.y < b.y ? a.y < c.y ? a.y : c.y : b.y < c.y ? b.y : c.y,
  23766. maxTX = a.x > b.x ? a.x > c.x ? a.x : c.x : b.x > c.x ? b.x : c.x,
  23767. maxTY = a.y > b.y ? a.y > c.y ? a.y : c.y : b.y > c.y ? b.y : c.y; // z-order range for the current triangle bbox;
  23768. var minZ = zOrder(minTX, minTY, minX, minY, invSize),
  23769. maxZ = zOrder(maxTX, maxTY, minX, minY, invSize);
  23770. var p = ear.prevZ,
  23771. n = ear.nextZ; // look for points inside the triangle in both directions
  23772. while (p && p.z >= minZ && n && n.z <= maxZ) {
  23773. if (p !== ear.prev && p !== ear.next && pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false;
  23774. p = p.prevZ;
  23775. if (n !== ear.prev && n !== ear.next && pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, n.x, n.y) && area(n.prev, n, n.next) >= 0) return false;
  23776. n = n.nextZ;
  23777. } // look for remaining points in decreasing z-order
  23778. while (p && p.z >= minZ) {
  23779. if (p !== ear.prev && p !== ear.next && pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false;
  23780. p = p.prevZ;
  23781. } // look for remaining points in increasing z-order
  23782. while (n && n.z <= maxZ) {
  23783. if (n !== ear.prev && n !== ear.next && pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, n.x, n.y) && area(n.prev, n, n.next) >= 0) return false;
  23784. n = n.nextZ;
  23785. }
  23786. return true;
  23787. } // go through all polygon nodes and cure small local self-intersections
  23788. function cureLocalIntersections(start, triangles, dim) {
  23789. var p = start;
  23790. do {
  23791. var a = p.prev,
  23792. b = p.next.next;
  23793. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  23794. triangles.push(a.i / dim);
  23795. triangles.push(p.i / dim);
  23796. triangles.push(b.i / dim); // remove two nodes involved
  23797. removeNode(p);
  23798. removeNode(p.next);
  23799. p = start = b;
  23800. }
  23801. p = p.next;
  23802. } while (p !== start);
  23803. return filterPoints(p);
  23804. } // try splitting polygon into two and triangulate them independently
  23805. function splitEarcut(start, triangles, dim, minX, minY, invSize) {
  23806. // look for a valid diagonal that divides the polygon into two
  23807. var a = start;
  23808. do {
  23809. var b = a.next.next;
  23810. while (b !== a.prev) {
  23811. if (a.i !== b.i && isValidDiagonal(a, b)) {
  23812. // split the polygon in two by the diagonal
  23813. var c = splitPolygon(a, b); // filter colinear points around the cuts
  23814. a = filterPoints(a, a.next);
  23815. c = filterPoints(c, c.next); // run earcut on each half
  23816. earcutLinked(a, triangles, dim, minX, minY, invSize);
  23817. earcutLinked(c, triangles, dim, minX, minY, invSize);
  23818. return;
  23819. }
  23820. b = b.next;
  23821. }
  23822. a = a.next;
  23823. } while (a !== start);
  23824. } // link every hole into the outer loop, producing a single-ring polygon without holes
  23825. function eliminateHoles(data, holeIndices, outerNode, dim) {
  23826. var queue = [];
  23827. var i, len, start, end, list;
  23828. for (i = 0, len = holeIndices.length; i < len; i++) {
  23829. start = holeIndices[i] * dim;
  23830. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  23831. list = linkedList(data, start, end, dim, false);
  23832. if (list === list.next) list.steiner = true;
  23833. queue.push(getLeftmost(list));
  23834. }
  23835. queue.sort(compareX); // process holes from left to right
  23836. for (i = 0; i < queue.length; i++) {
  23837. eliminateHole(queue[i], outerNode);
  23838. outerNode = filterPoints(outerNode, outerNode.next);
  23839. }
  23840. return outerNode;
  23841. }
  23842. function compareX(a, b) {
  23843. return a.x - b.x;
  23844. } // find a bridge between vertices that connects hole with an outer ring and and link it
  23845. function eliminateHole(hole, outerNode) {
  23846. outerNode = findHoleBridge(hole, outerNode);
  23847. if (outerNode) {
  23848. var b = splitPolygon(outerNode, hole); // filter collinear points around the cuts
  23849. filterPoints(outerNode, outerNode.next);
  23850. filterPoints(b, b.next);
  23851. }
  23852. } // David Eberly's algorithm for finding a bridge between hole and outer polygon
  23853. function findHoleBridge(hole, outerNode) {
  23854. var p = outerNode;
  23855. var hx = hole.x;
  23856. var hy = hole.y;
  23857. var qx = -Infinity,
  23858. m; // find a segment intersected by a ray from the hole's leftmost point to the left;
  23859. // segment's endpoint with lesser x will be potential connection point
  23860. do {
  23861. if (hy <= p.y && hy >= p.next.y && p.next.y !== p.y) {
  23862. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  23863. if (x <= hx && x > qx) {
  23864. qx = x;
  23865. if (x === hx) {
  23866. if (hy === p.y) return p;
  23867. if (hy === p.next.y) return p.next;
  23868. }
  23869. m = p.x < p.next.x ? p : p.next;
  23870. }
  23871. }
  23872. p = p.next;
  23873. } while (p !== outerNode);
  23874. if (!m) return null;
  23875. if (hx === qx) return m; // hole touches outer segment; pick leftmost endpoint
  23876. // look for points inside the triangle of hole point, segment intersection and endpoint;
  23877. // if there are no points found, we have a valid connection;
  23878. // otherwise choose the point of the minimum angle with the ray as connection point
  23879. var stop = m,
  23880. mx = m.x,
  23881. my = m.y;
  23882. var tanMin = Infinity,
  23883. tan;
  23884. p = m;
  23885. do {
  23886. if (hx >= p.x && p.x >= mx && hx !== p.x && pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  23887. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  23888. if (locallyInside(p, hole) && (tan < tanMin || tan === tanMin && (p.x > m.x || p.x === m.x && sectorContainsSector(m, p)))) {
  23889. m = p;
  23890. tanMin = tan;
  23891. }
  23892. }
  23893. p = p.next;
  23894. } while (p !== stop);
  23895. return m;
  23896. } // whether sector in vertex m contains sector in vertex p in the same coordinates
  23897. function sectorContainsSector(m, p) {
  23898. return area(m.prev, m, p.prev) < 0 && area(p.next, m, m.next) < 0;
  23899. } // interlink polygon nodes in z-order
  23900. function indexCurve(start, minX, minY, invSize) {
  23901. var p = start;
  23902. do {
  23903. if (p.z === null) p.z = zOrder(p.x, p.y, minX, minY, invSize);
  23904. p.prevZ = p.prev;
  23905. p.nextZ = p.next;
  23906. p = p.next;
  23907. } while (p !== start);
  23908. p.prevZ.nextZ = null;
  23909. p.prevZ = null;
  23910. sortLinked(p);
  23911. } // Simon Tatham's linked list merge sort algorithm
  23912. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  23913. function sortLinked(list) {
  23914. var i,
  23915. p,
  23916. q,
  23917. e,
  23918. tail,
  23919. numMerges,
  23920. pSize,
  23921. qSize,
  23922. inSize = 1;
  23923. do {
  23924. p = list;
  23925. list = null;
  23926. tail = null;
  23927. numMerges = 0;
  23928. while (p) {
  23929. numMerges++;
  23930. q = p;
  23931. pSize = 0;
  23932. for (i = 0; i < inSize; i++) {
  23933. pSize++;
  23934. q = q.nextZ;
  23935. if (!q) break;
  23936. }
  23937. qSize = inSize;
  23938. while (pSize > 0 || qSize > 0 && q) {
  23939. if (pSize !== 0 && (qSize === 0 || !q || p.z <= q.z)) {
  23940. e = p;
  23941. p = p.nextZ;
  23942. pSize--;
  23943. } else {
  23944. e = q;
  23945. q = q.nextZ;
  23946. qSize--;
  23947. }
  23948. if (tail) tail.nextZ = e;else list = e;
  23949. e.prevZ = tail;
  23950. tail = e;
  23951. }
  23952. p = q;
  23953. }
  23954. tail.nextZ = null;
  23955. inSize *= 2;
  23956. } while (numMerges > 1);
  23957. return list;
  23958. } // z-order of a point given coords and inverse of the longer side of data bbox
  23959. function zOrder(x, y, minX, minY, invSize) {
  23960. // coords are transformed into non-negative 15-bit integer range
  23961. x = 32767 * (x - minX) * invSize;
  23962. y = 32767 * (y - minY) * invSize;
  23963. x = (x | x << 8) & 0x00FF00FF;
  23964. x = (x | x << 4) & 0x0F0F0F0F;
  23965. x = (x | x << 2) & 0x33333333;
  23966. x = (x | x << 1) & 0x55555555;
  23967. y = (y | y << 8) & 0x00FF00FF;
  23968. y = (y | y << 4) & 0x0F0F0F0F;
  23969. y = (y | y << 2) & 0x33333333;
  23970. y = (y | y << 1) & 0x55555555;
  23971. return x | y << 1;
  23972. } // find the leftmost node of a polygon ring
  23973. function getLeftmost(start) {
  23974. var p = start,
  23975. leftmost = start;
  23976. do {
  23977. if (p.x < leftmost.x || p.x === leftmost.x && p.y < leftmost.y) leftmost = p;
  23978. p = p.next;
  23979. } while (p !== start);
  23980. return leftmost;
  23981. } // check if a point lies within a convex triangle
  23982. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  23983. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 && (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 && (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  23984. } // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  23985. function isValidDiagonal(a, b) {
  23986. return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) && ( // dones't intersect other edges
  23987. locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b) && ( // locally visible
  23988. area(a.prev, a, b.prev) || area(a, b.prev, b)) || // does not create opposite-facing sectors
  23989. equals(a, b) && area(a.prev, a, a.next) > 0 && area(b.prev, b, b.next) > 0); // special zero-length case
  23990. } // signed area of a triangle
  23991. function area(p, q, r) {
  23992. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  23993. } // check if two points are equal
  23994. function equals(p1, p2) {
  23995. return p1.x === p2.x && p1.y === p2.y;
  23996. } // check if two segments intersect
  23997. function intersects(p1, q1, p2, q2) {
  23998. var o1 = sign(area(p1, q1, p2));
  23999. var o2 = sign(area(p1, q1, q2));
  24000. var o3 = sign(area(p2, q2, p1));
  24001. var o4 = sign(area(p2, q2, q1));
  24002. if (o1 !== o2 && o3 !== o4) return true; // general case
  24003. if (o1 === 0 && onSegment(p1, p2, q1)) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1
  24004. if (o2 === 0 && onSegment(p1, q2, q1)) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1
  24005. if (o3 === 0 && onSegment(p2, p1, q2)) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2
  24006. if (o4 === 0 && onSegment(p2, q1, q2)) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2
  24007. return false;
  24008. } // for collinear points p, q, r, check if point q lies on segment pr
  24009. function onSegment(p, q, r) {
  24010. return q.x <= Math.max(p.x, r.x) && q.x >= Math.min(p.x, r.x) && q.y <= Math.max(p.y, r.y) && q.y >= Math.min(p.y, r.y);
  24011. }
  24012. function sign(num) {
  24013. return num > 0 ? 1 : num < 0 ? -1 : 0;
  24014. } // check if a polygon diagonal intersects any polygon segments
  24015. function intersectsPolygon(a, b) {
  24016. var p = a;
  24017. do {
  24018. if (p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i && intersects(p, p.next, a, b)) return true;
  24019. p = p.next;
  24020. } while (p !== a);
  24021. return false;
  24022. } // check if a polygon diagonal is locally inside the polygon
  24023. function locallyInside(a, b) {
  24024. return area(a.prev, a, a.next) < 0 ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0 : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  24025. } // check if the middle point of a polygon diagonal is inside the polygon
  24026. function middleInside(a, b) {
  24027. var p = a,
  24028. inside = false;
  24029. var px = (a.x + b.x) / 2,
  24030. py = (a.y + b.y) / 2;
  24031. do {
  24032. if (p.y > py !== p.next.y > py && p.next.y !== p.y && px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x) inside = !inside;
  24033. p = p.next;
  24034. } while (p !== a);
  24035. return inside;
  24036. } // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  24037. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  24038. function splitPolygon(a, b) {
  24039. var a2 = new Node(a.i, a.x, a.y),
  24040. b2 = new Node(b.i, b.x, b.y),
  24041. an = a.next,
  24042. bp = b.prev;
  24043. a.next = b;
  24044. b.prev = a;
  24045. a2.next = an;
  24046. an.prev = a2;
  24047. b2.next = a2;
  24048. a2.prev = b2;
  24049. bp.next = b2;
  24050. b2.prev = bp;
  24051. return b2;
  24052. } // create a node and optionally link it with previous one (in a circular doubly linked list)
  24053. function insertNode(i, x, y, last) {
  24054. var p = new Node(i, x, y);
  24055. if (!last) {
  24056. p.prev = p;
  24057. p.next = p;
  24058. } else {
  24059. p.next = last.next;
  24060. p.prev = last;
  24061. last.next.prev = p;
  24062. last.next = p;
  24063. }
  24064. return p;
  24065. }
  24066. function removeNode(p) {
  24067. p.next.prev = p.prev;
  24068. p.prev.next = p.next;
  24069. if (p.prevZ) p.prevZ.nextZ = p.nextZ;
  24070. if (p.nextZ) p.nextZ.prevZ = p.prevZ;
  24071. }
  24072. function Node(i, x, y) {
  24073. // vertex index in coordinates array
  24074. this.i = i; // vertex coordinates
  24075. this.x = x;
  24076. this.y = y; // previous and next vertex nodes in a polygon ring
  24077. this.prev = null;
  24078. this.next = null; // z-order curve value
  24079. this.z = null; // previous and next nodes in z-order
  24080. this.prevZ = null;
  24081. this.nextZ = null; // indicates whether this is a steiner point
  24082. this.steiner = false;
  24083. }
  24084. function signedArea(data, start, end, dim) {
  24085. var sum = 0;
  24086. for (var i = start, j = end - dim; i < end; i += dim) {
  24087. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  24088. j = i;
  24089. }
  24090. return sum;
  24091. }
  24092. var ShapeUtils = {
  24093. // calculate area of the contour polygon
  24094. area: function area(contour) {
  24095. var n = contour.length;
  24096. var a = 0.0;
  24097. for (var p = n - 1, q = 0; q < n; p = q++) {
  24098. a += contour[p].x * contour[q].y - contour[q].x * contour[p].y;
  24099. }
  24100. return a * 0.5;
  24101. },
  24102. isClockWise: function isClockWise(pts) {
  24103. return ShapeUtils.area(pts) < 0;
  24104. },
  24105. triangulateShape: function triangulateShape(contour, holes) {
  24106. var vertices = []; // flat array of vertices like [ x0,y0, x1,y1, x2,y2, ... ]
  24107. var holeIndices = []; // array of hole indices
  24108. var faces = []; // final array of vertex indices like [ [ a,b,d ], [ b,c,d ] ]
  24109. removeDupEndPts(contour);
  24110. addContour(vertices, contour); //
  24111. var holeIndex = contour.length;
  24112. holes.forEach(removeDupEndPts);
  24113. for (var i = 0; i < holes.length; i++) {
  24114. holeIndices.push(holeIndex);
  24115. holeIndex += holes[i].length;
  24116. addContour(vertices, holes[i]);
  24117. } //
  24118. var triangles = Earcut.triangulate(vertices, holeIndices); //
  24119. for (var _i = 0; _i < triangles.length; _i += 3) {
  24120. faces.push(triangles.slice(_i, _i + 3));
  24121. }
  24122. return faces;
  24123. }
  24124. };
  24125. function removeDupEndPts(points) {
  24126. var l = points.length;
  24127. if (l > 2 && points[l - 1].equals(points[0])) {
  24128. points.pop();
  24129. }
  24130. }
  24131. function addContour(vertices, contour) {
  24132. for (var i = 0; i < contour.length; i++) {
  24133. vertices.push(contour[i].x);
  24134. vertices.push(contour[i].y);
  24135. }
  24136. }
  24137. var ExtrudeGeometry = /*#__PURE__*/function (_BufferGeometry) {
  24138. _inheritsLoose(ExtrudeGeometry, _BufferGeometry);
  24139. function ExtrudeGeometry(shapes, options) {
  24140. var _this;
  24141. _this = _BufferGeometry.call(this) || this;
  24142. _this.type = 'ExtrudeGeometry';
  24143. _this.parameters = {
  24144. shapes: shapes,
  24145. options: options
  24146. };
  24147. shapes = Array.isArray(shapes) ? shapes : [shapes];
  24148. var scope = _assertThisInitialized(_this);
  24149. var verticesArray = [];
  24150. var uvArray = [];
  24151. for (var i = 0, l = shapes.length; i < l; i++) {
  24152. var shape = shapes[i];
  24153. addShape(shape);
  24154. } // build geometry
  24155. _this.setAttribute('position', new Float32BufferAttribute(verticesArray, 3));
  24156. _this.setAttribute('uv', new Float32BufferAttribute(uvArray, 2));
  24157. _this.computeVertexNormals(); // functions
  24158. function addShape(shape) {
  24159. var placeholder = []; // options
  24160. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  24161. var steps = options.steps !== undefined ? options.steps : 1;
  24162. var depth = options.depth !== undefined ? options.depth : 100;
  24163. var bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true;
  24164. var bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6;
  24165. var bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2;
  24166. var bevelOffset = options.bevelOffset !== undefined ? options.bevelOffset : 0;
  24167. var bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  24168. var extrudePath = options.extrudePath;
  24169. var uvgen = options.UVGenerator !== undefined ? options.UVGenerator : WorldUVGenerator; // deprecated options
  24170. if (options.amount !== undefined) {
  24171. console.warn('THREE.ExtrudeBufferGeometry: amount has been renamed to depth.');
  24172. depth = options.amount;
  24173. } //
  24174. var extrudePts,
  24175. extrudeByPath = false;
  24176. var splineTube, binormal, normal, position2;
  24177. if (extrudePath) {
  24178. extrudePts = extrudePath.getSpacedPoints(steps);
  24179. extrudeByPath = true;
  24180. bevelEnabled = false; // bevels not supported for path extrusion
  24181. // SETUP TNB variables
  24182. // TODO1 - have a .isClosed in spline?
  24183. splineTube = extrudePath.computeFrenetFrames(steps, false); // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  24184. binormal = new Vector3();
  24185. normal = new Vector3();
  24186. position2 = new Vector3();
  24187. } // Safeguards if bevels are not enabled
  24188. if (!bevelEnabled) {
  24189. bevelSegments = 0;
  24190. bevelThickness = 0;
  24191. bevelSize = 0;
  24192. bevelOffset = 0;
  24193. } // Variables initialization
  24194. var shapePoints = shape.extractPoints(curveSegments);
  24195. var vertices = shapePoints.shape;
  24196. var holes = shapePoints.holes;
  24197. var reverse = !ShapeUtils.isClockWise(vertices);
  24198. if (reverse) {
  24199. vertices = vertices.reverse(); // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  24200. for (var h = 0, hl = holes.length; h < hl; h++) {
  24201. var ahole = holes[h];
  24202. if (ShapeUtils.isClockWise(ahole)) {
  24203. holes[h] = ahole.reverse();
  24204. }
  24205. }
  24206. }
  24207. var faces = ShapeUtils.triangulateShape(vertices, holes);
  24208. /* Vertices */
  24209. var contour = vertices; // vertices has all points but contour has only points of circumference
  24210. for (var _h = 0, _hl = holes.length; _h < _hl; _h++) {
  24211. var _ahole = holes[_h];
  24212. vertices = vertices.concat(_ahole);
  24213. }
  24214. function scalePt2(pt, vec, size) {
  24215. if (!vec) console.error('THREE.ExtrudeGeometry: vec does not exist');
  24216. return vec.clone().multiplyScalar(size).add(pt);
  24217. }
  24218. var vlen = vertices.length,
  24219. flen = faces.length; // Find directions for point movement
  24220. function getBevelVec(inPt, inPrev, inNext) {
  24221. // computes for inPt the corresponding point inPt' on a new contour
  24222. // shifted by 1 unit (length of normalized vector) to the left
  24223. // if we walk along contour clockwise, this new contour is outside the old one
  24224. //
  24225. // inPt' is the intersection of the two lines parallel to the two
  24226. // adjacent edges of inPt at a distance of 1 unit on the left side.
  24227. var v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPt
  24228. // good reading for geometry algorithms (here: line-line intersection)
  24229. // http://geomalgorithms.com/a05-_intersect-1.html
  24230. var v_prev_x = inPt.x - inPrev.x,
  24231. v_prev_y = inPt.y - inPrev.y;
  24232. var v_next_x = inNext.x - inPt.x,
  24233. v_next_y = inNext.y - inPt.y;
  24234. var v_prev_lensq = v_prev_x * v_prev_x + v_prev_y * v_prev_y; // check for collinear edges
  24235. var collinear0 = v_prev_x * v_next_y - v_prev_y * v_next_x;
  24236. if (Math.abs(collinear0) > Number.EPSILON) {
  24237. // not collinear
  24238. // length of vectors for normalizing
  24239. var v_prev_len = Math.sqrt(v_prev_lensq);
  24240. var v_next_len = Math.sqrt(v_next_x * v_next_x + v_next_y * v_next_y); // shift adjacent points by unit vectors to the left
  24241. var ptPrevShift_x = inPrev.x - v_prev_y / v_prev_len;
  24242. var ptPrevShift_y = inPrev.y + v_prev_x / v_prev_len;
  24243. var ptNextShift_x = inNext.x - v_next_y / v_next_len;
  24244. var ptNextShift_y = inNext.y + v_next_x / v_next_len; // scaling factor for v_prev to intersection point
  24245. var sf = ((ptNextShift_x - ptPrevShift_x) * v_next_y - (ptNextShift_y - ptPrevShift_y) * v_next_x) / (v_prev_x * v_next_y - v_prev_y * v_next_x); // vector from inPt to intersection point
  24246. v_trans_x = ptPrevShift_x + v_prev_x * sf - inPt.x;
  24247. v_trans_y = ptPrevShift_y + v_prev_y * sf - inPt.y; // Don't normalize!, otherwise sharp corners become ugly
  24248. // but prevent crazy spikes
  24249. var v_trans_lensq = v_trans_x * v_trans_x + v_trans_y * v_trans_y;
  24250. if (v_trans_lensq <= 2) {
  24251. return new Vector2(v_trans_x, v_trans_y);
  24252. } else {
  24253. shrink_by = Math.sqrt(v_trans_lensq / 2);
  24254. }
  24255. } else {
  24256. // handle special case of collinear edges
  24257. var direction_eq = false; // assumes: opposite
  24258. if (v_prev_x > Number.EPSILON) {
  24259. if (v_next_x > Number.EPSILON) {
  24260. direction_eq = true;
  24261. }
  24262. } else {
  24263. if (v_prev_x < -Number.EPSILON) {
  24264. if (v_next_x < -Number.EPSILON) {
  24265. direction_eq = true;
  24266. }
  24267. } else {
  24268. if (Math.sign(v_prev_y) === Math.sign(v_next_y)) {
  24269. direction_eq = true;
  24270. }
  24271. }
  24272. }
  24273. if (direction_eq) {
  24274. // console.log("Warning: lines are a straight sequence");
  24275. v_trans_x = -v_prev_y;
  24276. v_trans_y = v_prev_x;
  24277. shrink_by = Math.sqrt(v_prev_lensq);
  24278. } else {
  24279. // console.log("Warning: lines are a straight spike");
  24280. v_trans_x = v_prev_x;
  24281. v_trans_y = v_prev_y;
  24282. shrink_by = Math.sqrt(v_prev_lensq / 2);
  24283. }
  24284. }
  24285. return new Vector2(v_trans_x / shrink_by, v_trans_y / shrink_by);
  24286. }
  24287. var contourMovements = [];
  24288. for (var _i = 0, il = contour.length, j = il - 1, k = _i + 1; _i < il; _i++, j++, k++) {
  24289. if (j === il) j = 0;
  24290. if (k === il) k = 0; // (j)---(i)---(k)
  24291. // console.log('i,j,k', i, j , k)
  24292. contourMovements[_i] = getBevelVec(contour[_i], contour[j], contour[k]);
  24293. }
  24294. var holesMovements = [];
  24295. var oneHoleMovements,
  24296. verticesMovements = contourMovements.concat();
  24297. for (var _h2 = 0, _hl2 = holes.length; _h2 < _hl2; _h2++) {
  24298. var _ahole2 = holes[_h2];
  24299. oneHoleMovements = [];
  24300. for (var _i2 = 0, _il = _ahole2.length, _j = _il - 1, _k = _i2 + 1; _i2 < _il; _i2++, _j++, _k++) {
  24301. if (_j === _il) _j = 0;
  24302. if (_k === _il) _k = 0; // (j)---(i)---(k)
  24303. oneHoleMovements[_i2] = getBevelVec(_ahole2[_i2], _ahole2[_j], _ahole2[_k]);
  24304. }
  24305. holesMovements.push(oneHoleMovements);
  24306. verticesMovements = verticesMovements.concat(oneHoleMovements);
  24307. } // Loop bevelSegments, 1 for the front, 1 for the back
  24308. for (var b = 0; b < bevelSegments; b++) {
  24309. //for ( b = bevelSegments; b > 0; b -- ) {
  24310. var t = b / bevelSegments;
  24311. var z = bevelThickness * Math.cos(t * Math.PI / 2);
  24312. var _bs = bevelSize * Math.sin(t * Math.PI / 2) + bevelOffset; // contract shape
  24313. for (var _i3 = 0, _il2 = contour.length; _i3 < _il2; _i3++) {
  24314. var vert = scalePt2(contour[_i3], contourMovements[_i3], _bs);
  24315. v(vert.x, vert.y, -z);
  24316. } // expand holes
  24317. for (var _h3 = 0, _hl3 = holes.length; _h3 < _hl3; _h3++) {
  24318. var _ahole3 = holes[_h3];
  24319. oneHoleMovements = holesMovements[_h3];
  24320. for (var _i4 = 0, _il3 = _ahole3.length; _i4 < _il3; _i4++) {
  24321. var _vert = scalePt2(_ahole3[_i4], oneHoleMovements[_i4], _bs);
  24322. v(_vert.x, _vert.y, -z);
  24323. }
  24324. }
  24325. }
  24326. var bs = bevelSize + bevelOffset; // Back facing vertices
  24327. for (var _i5 = 0; _i5 < vlen; _i5++) {
  24328. var _vert2 = bevelEnabled ? scalePt2(vertices[_i5], verticesMovements[_i5], bs) : vertices[_i5];
  24329. if (!extrudeByPath) {
  24330. v(_vert2.x, _vert2.y, 0);
  24331. } else {
  24332. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  24333. normal.copy(splineTube.normals[0]).multiplyScalar(_vert2.x);
  24334. binormal.copy(splineTube.binormals[0]).multiplyScalar(_vert2.y);
  24335. position2.copy(extrudePts[0]).add(normal).add(binormal);
  24336. v(position2.x, position2.y, position2.z);
  24337. }
  24338. } // Add stepped vertices...
  24339. // Including front facing vertices
  24340. for (var s = 1; s <= steps; s++) {
  24341. for (var _i6 = 0; _i6 < vlen; _i6++) {
  24342. var _vert3 = bevelEnabled ? scalePt2(vertices[_i6], verticesMovements[_i6], bs) : vertices[_i6];
  24343. if (!extrudeByPath) {
  24344. v(_vert3.x, _vert3.y, depth / steps * s);
  24345. } else {
  24346. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  24347. normal.copy(splineTube.normals[s]).multiplyScalar(_vert3.x);
  24348. binormal.copy(splineTube.binormals[s]).multiplyScalar(_vert3.y);
  24349. position2.copy(extrudePts[s]).add(normal).add(binormal);
  24350. v(position2.x, position2.y, position2.z);
  24351. }
  24352. }
  24353. } // Add bevel segments planes
  24354. //for ( b = 1; b <= bevelSegments; b ++ ) {
  24355. for (var _b = bevelSegments - 1; _b >= 0; _b--) {
  24356. var _t = _b / bevelSegments;
  24357. var _z = bevelThickness * Math.cos(_t * Math.PI / 2);
  24358. var _bs2 = bevelSize * Math.sin(_t * Math.PI / 2) + bevelOffset; // contract shape
  24359. for (var _i7 = 0, _il4 = contour.length; _i7 < _il4; _i7++) {
  24360. var _vert4 = scalePt2(contour[_i7], contourMovements[_i7], _bs2);
  24361. v(_vert4.x, _vert4.y, depth + _z);
  24362. } // expand holes
  24363. for (var _h4 = 0, _hl4 = holes.length; _h4 < _hl4; _h4++) {
  24364. var _ahole4 = holes[_h4];
  24365. oneHoleMovements = holesMovements[_h4];
  24366. for (var _i8 = 0, _il5 = _ahole4.length; _i8 < _il5; _i8++) {
  24367. var _vert5 = scalePt2(_ahole4[_i8], oneHoleMovements[_i8], _bs2);
  24368. if (!extrudeByPath) {
  24369. v(_vert5.x, _vert5.y, depth + _z);
  24370. } else {
  24371. v(_vert5.x, _vert5.y + extrudePts[steps - 1].y, extrudePts[steps - 1].x + _z);
  24372. }
  24373. }
  24374. }
  24375. }
  24376. /* Faces */
  24377. // Top and bottom faces
  24378. buildLidFaces(); // Sides faces
  24379. buildSideFaces(); ///// Internal functions
  24380. function buildLidFaces() {
  24381. var start = verticesArray.length / 3;
  24382. if (bevelEnabled) {
  24383. var layer = 0; // steps + 1
  24384. var offset = vlen * layer; // Bottom faces
  24385. for (var _i9 = 0; _i9 < flen; _i9++) {
  24386. var face = faces[_i9];
  24387. f3(face[2] + offset, face[1] + offset, face[0] + offset);
  24388. }
  24389. layer = steps + bevelSegments * 2;
  24390. offset = vlen * layer; // Top faces
  24391. for (var _i10 = 0; _i10 < flen; _i10++) {
  24392. var _face = faces[_i10];
  24393. f3(_face[0] + offset, _face[1] + offset, _face[2] + offset);
  24394. }
  24395. } else {
  24396. // Bottom faces
  24397. for (var _i11 = 0; _i11 < flen; _i11++) {
  24398. var _face2 = faces[_i11];
  24399. f3(_face2[2], _face2[1], _face2[0]);
  24400. } // Top faces
  24401. for (var _i12 = 0; _i12 < flen; _i12++) {
  24402. var _face3 = faces[_i12];
  24403. f3(_face3[0] + vlen * steps, _face3[1] + vlen * steps, _face3[2] + vlen * steps);
  24404. }
  24405. }
  24406. scope.addGroup(start, verticesArray.length / 3 - start, 0);
  24407. } // Create faces for the z-sides of the shape
  24408. function buildSideFaces() {
  24409. var start = verticesArray.length / 3;
  24410. var layeroffset = 0;
  24411. sidewalls(contour, layeroffset);
  24412. layeroffset += contour.length;
  24413. for (var _h5 = 0, _hl5 = holes.length; _h5 < _hl5; _h5++) {
  24414. var _ahole5 = holes[_h5];
  24415. sidewalls(_ahole5, layeroffset); //, true
  24416. layeroffset += _ahole5.length;
  24417. }
  24418. scope.addGroup(start, verticesArray.length / 3 - start, 1);
  24419. }
  24420. function sidewalls(contour, layeroffset) {
  24421. var i = contour.length;
  24422. while (--i >= 0) {
  24423. var _j2 = i;
  24424. var _k2 = i - 1;
  24425. if (_k2 < 0) _k2 = contour.length - 1; //console.log('b', i,j, i-1, k,vertices.length);
  24426. for (var _s = 0, sl = steps + bevelSegments * 2; _s < sl; _s++) {
  24427. var slen1 = vlen * _s;
  24428. var slen2 = vlen * (_s + 1);
  24429. var a = layeroffset + _j2 + slen1,
  24430. _b2 = layeroffset + _k2 + slen1,
  24431. c = layeroffset + _k2 + slen2,
  24432. d = layeroffset + _j2 + slen2;
  24433. f4(a, _b2, c, d);
  24434. }
  24435. }
  24436. }
  24437. function v(x, y, z) {
  24438. placeholder.push(x);
  24439. placeholder.push(y);
  24440. placeholder.push(z);
  24441. }
  24442. function f3(a, b, c) {
  24443. addVertex(a);
  24444. addVertex(b);
  24445. addVertex(c);
  24446. var nextIndex = verticesArray.length / 3;
  24447. var uvs = uvgen.generateTopUV(scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1);
  24448. addUV(uvs[0]);
  24449. addUV(uvs[1]);
  24450. addUV(uvs[2]);
  24451. }
  24452. function f4(a, b, c, d) {
  24453. addVertex(a);
  24454. addVertex(b);
  24455. addVertex(d);
  24456. addVertex(b);
  24457. addVertex(c);
  24458. addVertex(d);
  24459. var nextIndex = verticesArray.length / 3;
  24460. var uvs = uvgen.generateSideWallUV(scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1);
  24461. addUV(uvs[0]);
  24462. addUV(uvs[1]);
  24463. addUV(uvs[3]);
  24464. addUV(uvs[1]);
  24465. addUV(uvs[2]);
  24466. addUV(uvs[3]);
  24467. }
  24468. function addVertex(index) {
  24469. verticesArray.push(placeholder[index * 3 + 0]);
  24470. verticesArray.push(placeholder[index * 3 + 1]);
  24471. verticesArray.push(placeholder[index * 3 + 2]);
  24472. }
  24473. function addUV(vector2) {
  24474. uvArray.push(vector2.x);
  24475. uvArray.push(vector2.y);
  24476. }
  24477. }
  24478. return _this;
  24479. }
  24480. var _proto = ExtrudeGeometry.prototype;
  24481. _proto.toJSON = function toJSON() {
  24482. var data = BufferGeometry.prototype.toJSON.call(this);
  24483. var shapes = this.parameters.shapes;
  24484. var options = this.parameters.options;
  24485. return _toJSON(shapes, options, data);
  24486. };
  24487. return ExtrudeGeometry;
  24488. }(BufferGeometry);
  24489. var WorldUVGenerator = {
  24490. generateTopUV: function generateTopUV(geometry, vertices, indexA, indexB, indexC) {
  24491. var a_x = vertices[indexA * 3];
  24492. var a_y = vertices[indexA * 3 + 1];
  24493. var b_x = vertices[indexB * 3];
  24494. var b_y = vertices[indexB * 3 + 1];
  24495. var c_x = vertices[indexC * 3];
  24496. var c_y = vertices[indexC * 3 + 1];
  24497. return [new Vector2(a_x, a_y), new Vector2(b_x, b_y), new Vector2(c_x, c_y)];
  24498. },
  24499. generateSideWallUV: function generateSideWallUV(geometry, vertices, indexA, indexB, indexC, indexD) {
  24500. var a_x = vertices[indexA * 3];
  24501. var a_y = vertices[indexA * 3 + 1];
  24502. var a_z = vertices[indexA * 3 + 2];
  24503. var b_x = vertices[indexB * 3];
  24504. var b_y = vertices[indexB * 3 + 1];
  24505. var b_z = vertices[indexB * 3 + 2];
  24506. var c_x = vertices[indexC * 3];
  24507. var c_y = vertices[indexC * 3 + 1];
  24508. var c_z = vertices[indexC * 3 + 2];
  24509. var d_x = vertices[indexD * 3];
  24510. var d_y = vertices[indexD * 3 + 1];
  24511. var d_z = vertices[indexD * 3 + 2];
  24512. if (Math.abs(a_y - b_y) < 0.01) {
  24513. return [new Vector2(a_x, 1 - a_z), new Vector2(b_x, 1 - b_z), new Vector2(c_x, 1 - c_z), new Vector2(d_x, 1 - d_z)];
  24514. } else {
  24515. return [new Vector2(a_y, 1 - a_z), new Vector2(b_y, 1 - b_z), new Vector2(c_y, 1 - c_z), new Vector2(d_y, 1 - d_z)];
  24516. }
  24517. }
  24518. };
  24519. function _toJSON(shapes, options, data) {
  24520. data.shapes = [];
  24521. if (Array.isArray(shapes)) {
  24522. for (var i = 0, l = shapes.length; i < l; i++) {
  24523. var shape = shapes[i];
  24524. data.shapes.push(shape.uuid);
  24525. }
  24526. } else {
  24527. data.shapes.push(shapes.uuid);
  24528. }
  24529. if (options.extrudePath !== undefined) data.options.extrudePath = options.extrudePath.toJSON();
  24530. return data;
  24531. }
  24532. var IcosahedronGeometry = /*#__PURE__*/function (_PolyhedronGeometry) {
  24533. _inheritsLoose(IcosahedronGeometry, _PolyhedronGeometry);
  24534. function IcosahedronGeometry(radius, detail) {
  24535. var _this;
  24536. if (radius === void 0) {
  24537. radius = 1;
  24538. }
  24539. if (detail === void 0) {
  24540. detail = 0;
  24541. }
  24542. var t = (1 + Math.sqrt(5)) / 2;
  24543. var vertices = [-1, t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, 0, -1, t, 0, 1, t, 0, -1, -t, 0, 1, -t, t, 0, -1, t, 0, 1, -t, 0, -1, -t, 0, 1];
  24544. var indices = [0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11, 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8, 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9, 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1];
  24545. _this = _PolyhedronGeometry.call(this, vertices, indices, radius, detail) || this;
  24546. _this.type = 'IcosahedronGeometry';
  24547. _this.parameters = {
  24548. radius: radius,
  24549. detail: detail
  24550. };
  24551. return _this;
  24552. }
  24553. return IcosahedronGeometry;
  24554. }(PolyhedronGeometry);
  24555. var LatheGeometry = /*#__PURE__*/function (_BufferGeometry) {
  24556. _inheritsLoose(LatheGeometry, _BufferGeometry);
  24557. function LatheGeometry(points, segments, phiStart, phiLength) {
  24558. var _this;
  24559. if (segments === void 0) {
  24560. segments = 12;
  24561. }
  24562. if (phiStart === void 0) {
  24563. phiStart = 0;
  24564. }
  24565. if (phiLength === void 0) {
  24566. phiLength = Math.PI * 2;
  24567. }
  24568. _this = _BufferGeometry.call(this) || this;
  24569. _this.type = 'LatheGeometry';
  24570. _this.parameters = {
  24571. points: points,
  24572. segments: segments,
  24573. phiStart: phiStart,
  24574. phiLength: phiLength
  24575. };
  24576. segments = Math.floor(segments); // clamp phiLength so it's in range of [ 0, 2PI ]
  24577. phiLength = MathUtils.clamp(phiLength, 0, Math.PI * 2); // buffers
  24578. var indices = [];
  24579. var vertices = [];
  24580. var uvs = []; // helper variables
  24581. var inverseSegments = 1.0 / segments;
  24582. var vertex = new Vector3();
  24583. var uv = new Vector2(); // generate vertices and uvs
  24584. for (var i = 0; i <= segments; i++) {
  24585. var phi = phiStart + i * inverseSegments * phiLength;
  24586. var sin = Math.sin(phi);
  24587. var cos = Math.cos(phi);
  24588. for (var j = 0; j <= points.length - 1; j++) {
  24589. // vertex
  24590. vertex.x = points[j].x * sin;
  24591. vertex.y = points[j].y;
  24592. vertex.z = points[j].x * cos;
  24593. vertices.push(vertex.x, vertex.y, vertex.z); // uv
  24594. uv.x = i / segments;
  24595. uv.y = j / (points.length - 1);
  24596. uvs.push(uv.x, uv.y);
  24597. }
  24598. } // indices
  24599. for (var _i = 0; _i < segments; _i++) {
  24600. for (var _j = 0; _j < points.length - 1; _j++) {
  24601. var base = _j + _i * points.length;
  24602. var a = base;
  24603. var b = base + points.length;
  24604. var c = base + points.length + 1;
  24605. var d = base + 1; // faces
  24606. indices.push(a, b, d);
  24607. indices.push(b, c, d);
  24608. }
  24609. } // build geometry
  24610. _this.setIndex(indices);
  24611. _this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  24612. _this.setAttribute('uv', new Float32BufferAttribute(uvs, 2)); // generate normals
  24613. _this.computeVertexNormals(); // if the geometry is closed, we need to average the normals along the seam.
  24614. // because the corresponding vertices are identical (but still have different UVs).
  24615. if (phiLength === Math.PI * 2) {
  24616. var normals = _this.attributes.normal.array;
  24617. var n1 = new Vector3();
  24618. var n2 = new Vector3();
  24619. var n = new Vector3(); // this is the buffer offset for the last line of vertices
  24620. var _base = segments * points.length * 3;
  24621. for (var _i2 = 0, _j2 = 0; _i2 < points.length; _i2++, _j2 += 3) {
  24622. // select the normal of the vertex in the first line
  24623. n1.x = normals[_j2 + 0];
  24624. n1.y = normals[_j2 + 1];
  24625. n1.z = normals[_j2 + 2]; // select the normal of the vertex in the last line
  24626. n2.x = normals[_base + _j2 + 0];
  24627. n2.y = normals[_base + _j2 + 1];
  24628. n2.z = normals[_base + _j2 + 2]; // average normals
  24629. n.addVectors(n1, n2).normalize(); // assign the new values to both normals
  24630. normals[_j2 + 0] = normals[_base + _j2 + 0] = n.x;
  24631. normals[_j2 + 1] = normals[_base + _j2 + 1] = n.y;
  24632. normals[_j2 + 2] = normals[_base + _j2 + 2] = n.z;
  24633. }
  24634. }
  24635. return _this;
  24636. }
  24637. return LatheGeometry;
  24638. }(BufferGeometry);
  24639. var OctahedronGeometry = /*#__PURE__*/function (_PolyhedronGeometry) {
  24640. _inheritsLoose(OctahedronGeometry, _PolyhedronGeometry);
  24641. function OctahedronGeometry(radius, detail) {
  24642. var _this;
  24643. if (radius === void 0) {
  24644. radius = 1;
  24645. }
  24646. if (detail === void 0) {
  24647. detail = 0;
  24648. }
  24649. var vertices = [1, 0, 0, -1, 0, 0, 0, 1, 0, 0, -1, 0, 0, 0, 1, 0, 0, -1];
  24650. var indices = [0, 2, 4, 0, 4, 3, 0, 3, 5, 0, 5, 2, 1, 2, 5, 1, 5, 3, 1, 3, 4, 1, 4, 2];
  24651. _this = _PolyhedronGeometry.call(this, vertices, indices, radius, detail) || this;
  24652. _this.type = 'OctahedronGeometry';
  24653. _this.parameters = {
  24654. radius: radius,
  24655. detail: detail
  24656. };
  24657. return _this;
  24658. }
  24659. return OctahedronGeometry;
  24660. }(PolyhedronGeometry);
  24661. /**
  24662. * Parametric Surfaces Geometry
  24663. * based on the brilliant article by @prideout https://prideout.net/blog/old/blog/index.html@p=44.html
  24664. */
  24665. function ParametricGeometry(func, slices, stacks) {
  24666. BufferGeometry.call(this);
  24667. this.type = 'ParametricGeometry';
  24668. this.parameters = {
  24669. func: func,
  24670. slices: slices,
  24671. stacks: stacks
  24672. }; // buffers
  24673. var indices = [];
  24674. var vertices = [];
  24675. var normals = [];
  24676. var uvs = [];
  24677. var EPS = 0.00001;
  24678. var normal = new Vector3();
  24679. var p0 = new Vector3(),
  24680. p1 = new Vector3();
  24681. var pu = new Vector3(),
  24682. pv = new Vector3();
  24683. if (func.length < 3) {
  24684. console.error('THREE.ParametricGeometry: Function must now modify a Vector3 as third parameter.');
  24685. } // generate vertices, normals and uvs
  24686. var sliceCount = slices + 1;
  24687. for (var i = 0; i <= stacks; i++) {
  24688. var v = i / stacks;
  24689. for (var j = 0; j <= slices; j++) {
  24690. var u = j / slices; // vertex
  24691. func(u, v, p0);
  24692. vertices.push(p0.x, p0.y, p0.z); // normal
  24693. // approximate tangent vectors via finite differences
  24694. if (u - EPS >= 0) {
  24695. func(u - EPS, v, p1);
  24696. pu.subVectors(p0, p1);
  24697. } else {
  24698. func(u + EPS, v, p1);
  24699. pu.subVectors(p1, p0);
  24700. }
  24701. if (v - EPS >= 0) {
  24702. func(u, v - EPS, p1);
  24703. pv.subVectors(p0, p1);
  24704. } else {
  24705. func(u, v + EPS, p1);
  24706. pv.subVectors(p1, p0);
  24707. } // cross product of tangent vectors returns surface normal
  24708. normal.crossVectors(pu, pv).normalize();
  24709. normals.push(normal.x, normal.y, normal.z); // uv
  24710. uvs.push(u, v);
  24711. }
  24712. } // generate indices
  24713. for (var _i = 0; _i < stacks; _i++) {
  24714. for (var _j = 0; _j < slices; _j++) {
  24715. var a = _i * sliceCount + _j;
  24716. var b = _i * sliceCount + _j + 1;
  24717. var c = (_i + 1) * sliceCount + _j + 1;
  24718. var d = (_i + 1) * sliceCount + _j; // faces one and two
  24719. indices.push(a, b, d);
  24720. indices.push(b, c, d);
  24721. }
  24722. } // build geometry
  24723. this.setIndex(indices);
  24724. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  24725. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  24726. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  24727. }
  24728. ParametricGeometry.prototype = Object.create(BufferGeometry.prototype);
  24729. ParametricGeometry.prototype.constructor = ParametricGeometry;
  24730. var RingGeometry = /*#__PURE__*/function (_BufferGeometry) {
  24731. _inheritsLoose(RingGeometry, _BufferGeometry);
  24732. function RingGeometry(innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength) {
  24733. var _this;
  24734. if (innerRadius === void 0) {
  24735. innerRadius = 0.5;
  24736. }
  24737. if (outerRadius === void 0) {
  24738. outerRadius = 1;
  24739. }
  24740. if (thetaSegments === void 0) {
  24741. thetaSegments = 8;
  24742. }
  24743. if (phiSegments === void 0) {
  24744. phiSegments = 1;
  24745. }
  24746. if (thetaStart === void 0) {
  24747. thetaStart = 0;
  24748. }
  24749. if (thetaLength === void 0) {
  24750. thetaLength = Math.PI * 2;
  24751. }
  24752. _this = _BufferGeometry.call(this) || this;
  24753. _this.type = 'RingGeometry';
  24754. _this.parameters = {
  24755. innerRadius: innerRadius,
  24756. outerRadius: outerRadius,
  24757. thetaSegments: thetaSegments,
  24758. phiSegments: phiSegments,
  24759. thetaStart: thetaStart,
  24760. thetaLength: thetaLength
  24761. };
  24762. thetaSegments = Math.max(3, thetaSegments);
  24763. phiSegments = Math.max(1, phiSegments); // buffers
  24764. var indices = [];
  24765. var vertices = [];
  24766. var normals = [];
  24767. var uvs = []; // some helper variables
  24768. var radius = innerRadius;
  24769. var radiusStep = (outerRadius - innerRadius) / phiSegments;
  24770. var vertex = new Vector3();
  24771. var uv = new Vector2(); // generate vertices, normals and uvs
  24772. for (var j = 0; j <= phiSegments; j++) {
  24773. for (var i = 0; i <= thetaSegments; i++) {
  24774. // values are generate from the inside of the ring to the outside
  24775. var segment = thetaStart + i / thetaSegments * thetaLength; // vertex
  24776. vertex.x = radius * Math.cos(segment);
  24777. vertex.y = radius * Math.sin(segment);
  24778. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  24779. normals.push(0, 0, 1); // uv
  24780. uv.x = (vertex.x / outerRadius + 1) / 2;
  24781. uv.y = (vertex.y / outerRadius + 1) / 2;
  24782. uvs.push(uv.x, uv.y);
  24783. } // increase the radius for next row of vertices
  24784. radius += radiusStep;
  24785. } // indices
  24786. for (var _j = 0; _j < phiSegments; _j++) {
  24787. var thetaSegmentLevel = _j * (thetaSegments + 1);
  24788. for (var _i = 0; _i < thetaSegments; _i++) {
  24789. var _segment = _i + thetaSegmentLevel;
  24790. var a = _segment;
  24791. var b = _segment + thetaSegments + 1;
  24792. var c = _segment + thetaSegments + 2;
  24793. var d = _segment + 1; // faces
  24794. indices.push(a, b, d);
  24795. indices.push(b, c, d);
  24796. }
  24797. } // build geometry
  24798. _this.setIndex(indices);
  24799. _this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  24800. _this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  24801. _this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  24802. return _this;
  24803. }
  24804. return RingGeometry;
  24805. }(BufferGeometry);
  24806. var ShapeGeometry = /*#__PURE__*/function (_BufferGeometry) {
  24807. _inheritsLoose(ShapeGeometry, _BufferGeometry);
  24808. function ShapeGeometry(shapes, curveSegments) {
  24809. var _this;
  24810. if (curveSegments === void 0) {
  24811. curveSegments = 12;
  24812. }
  24813. _this = _BufferGeometry.call(this) || this;
  24814. _this.type = 'ShapeGeometry';
  24815. _this.parameters = {
  24816. shapes: shapes,
  24817. curveSegments: curveSegments
  24818. }; // buffers
  24819. var indices = [];
  24820. var vertices = [];
  24821. var normals = [];
  24822. var uvs = []; // helper variables
  24823. var groupStart = 0;
  24824. var groupCount = 0; // allow single and array values for "shapes" parameter
  24825. if (Array.isArray(shapes) === false) {
  24826. addShape(shapes);
  24827. } else {
  24828. for (var i = 0; i < shapes.length; i++) {
  24829. addShape(shapes[i]);
  24830. _this.addGroup(groupStart, groupCount, i); // enables MultiMaterial support
  24831. groupStart += groupCount;
  24832. groupCount = 0;
  24833. }
  24834. } // build geometry
  24835. _this.setIndex(indices);
  24836. _this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  24837. _this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  24838. _this.setAttribute('uv', new Float32BufferAttribute(uvs, 2)); // helper functions
  24839. function addShape(shape) {
  24840. var indexOffset = vertices.length / 3;
  24841. var points = shape.extractPoints(curveSegments);
  24842. var shapeVertices = points.shape;
  24843. var shapeHoles = points.holes; // check direction of vertices
  24844. if (ShapeUtils.isClockWise(shapeVertices) === false) {
  24845. shapeVertices = shapeVertices.reverse();
  24846. }
  24847. for (var _i = 0, l = shapeHoles.length; _i < l; _i++) {
  24848. var shapeHole = shapeHoles[_i];
  24849. if (ShapeUtils.isClockWise(shapeHole) === true) {
  24850. shapeHoles[_i] = shapeHole.reverse();
  24851. }
  24852. }
  24853. var faces = ShapeUtils.triangulateShape(shapeVertices, shapeHoles); // join vertices of inner and outer paths to a single array
  24854. for (var _i2 = 0, _l = shapeHoles.length; _i2 < _l; _i2++) {
  24855. var _shapeHole = shapeHoles[_i2];
  24856. shapeVertices = shapeVertices.concat(_shapeHole);
  24857. } // vertices, normals, uvs
  24858. for (var _i3 = 0, _l2 = shapeVertices.length; _i3 < _l2; _i3++) {
  24859. var vertex = shapeVertices[_i3];
  24860. vertices.push(vertex.x, vertex.y, 0);
  24861. normals.push(0, 0, 1);
  24862. uvs.push(vertex.x, vertex.y); // world uvs
  24863. } // incides
  24864. for (var _i4 = 0, _l3 = faces.length; _i4 < _l3; _i4++) {
  24865. var face = faces[_i4];
  24866. var a = face[0] + indexOffset;
  24867. var b = face[1] + indexOffset;
  24868. var c = face[2] + indexOffset;
  24869. indices.push(a, b, c);
  24870. groupCount += 3;
  24871. }
  24872. }
  24873. return _this;
  24874. }
  24875. var _proto = ShapeGeometry.prototype;
  24876. _proto.toJSON = function toJSON() {
  24877. var data = BufferGeometry.prototype.toJSON.call(this);
  24878. var shapes = this.parameters.shapes;
  24879. return _toJSON$1(shapes, data);
  24880. };
  24881. return ShapeGeometry;
  24882. }(BufferGeometry);
  24883. function _toJSON$1(shapes, data) {
  24884. data.shapes = [];
  24885. if (Array.isArray(shapes)) {
  24886. for (var i = 0, l = shapes.length; i < l; i++) {
  24887. var shape = shapes[i];
  24888. data.shapes.push(shape.uuid);
  24889. }
  24890. } else {
  24891. data.shapes.push(shapes.uuid);
  24892. }
  24893. return data;
  24894. }
  24895. var SphereGeometry = /*#__PURE__*/function (_BufferGeometry) {
  24896. _inheritsLoose(SphereGeometry, _BufferGeometry);
  24897. function SphereGeometry(radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength) {
  24898. var _this;
  24899. if (radius === void 0) {
  24900. radius = 1;
  24901. }
  24902. if (widthSegments === void 0) {
  24903. widthSegments = 8;
  24904. }
  24905. if (heightSegments === void 0) {
  24906. heightSegments = 6;
  24907. }
  24908. if (phiStart === void 0) {
  24909. phiStart = 0;
  24910. }
  24911. if (phiLength === void 0) {
  24912. phiLength = Math.PI * 2;
  24913. }
  24914. if (thetaStart === void 0) {
  24915. thetaStart = 0;
  24916. }
  24917. if (thetaLength === void 0) {
  24918. thetaLength = Math.PI;
  24919. }
  24920. _this = _BufferGeometry.call(this) || this;
  24921. _this.type = 'SphereGeometry';
  24922. _this.parameters = {
  24923. radius: radius,
  24924. widthSegments: widthSegments,
  24925. heightSegments: heightSegments,
  24926. phiStart: phiStart,
  24927. phiLength: phiLength,
  24928. thetaStart: thetaStart,
  24929. thetaLength: thetaLength
  24930. };
  24931. widthSegments = Math.max(3, Math.floor(widthSegments));
  24932. heightSegments = Math.max(2, Math.floor(heightSegments));
  24933. var thetaEnd = Math.min(thetaStart + thetaLength, Math.PI);
  24934. var index = 0;
  24935. var grid = [];
  24936. var vertex = new Vector3();
  24937. var normal = new Vector3(); // buffers
  24938. var indices = [];
  24939. var vertices = [];
  24940. var normals = [];
  24941. var uvs = []; // generate vertices, normals and uvs
  24942. for (var iy = 0; iy <= heightSegments; iy++) {
  24943. var verticesRow = [];
  24944. var v = iy / heightSegments; // special case for the poles
  24945. var uOffset = 0;
  24946. if (iy == 0 && thetaStart == 0) {
  24947. uOffset = 0.5 / widthSegments;
  24948. } else if (iy == heightSegments && thetaEnd == Math.PI) {
  24949. uOffset = -0.5 / widthSegments;
  24950. }
  24951. for (var ix = 0; ix <= widthSegments; ix++) {
  24952. var u = ix / widthSegments; // vertex
  24953. vertex.x = -radius * Math.cos(phiStart + u * phiLength) * Math.sin(thetaStart + v * thetaLength);
  24954. vertex.y = radius * Math.cos(thetaStart + v * thetaLength);
  24955. vertex.z = radius * Math.sin(phiStart + u * phiLength) * Math.sin(thetaStart + v * thetaLength);
  24956. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  24957. normal.copy(vertex).normalize();
  24958. normals.push(normal.x, normal.y, normal.z); // uv
  24959. uvs.push(u + uOffset, 1 - v);
  24960. verticesRow.push(index++);
  24961. }
  24962. grid.push(verticesRow);
  24963. } // indices
  24964. for (var _iy = 0; _iy < heightSegments; _iy++) {
  24965. for (var _ix = 0; _ix < widthSegments; _ix++) {
  24966. var a = grid[_iy][_ix + 1];
  24967. var b = grid[_iy][_ix];
  24968. var c = grid[_iy + 1][_ix];
  24969. var d = grid[_iy + 1][_ix + 1];
  24970. if (_iy !== 0 || thetaStart > 0) indices.push(a, b, d);
  24971. if (_iy !== heightSegments - 1 || thetaEnd < Math.PI) indices.push(b, c, d);
  24972. }
  24973. } // build geometry
  24974. _this.setIndex(indices);
  24975. _this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  24976. _this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  24977. _this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  24978. return _this;
  24979. }
  24980. return SphereGeometry;
  24981. }(BufferGeometry);
  24982. var TetrahedronGeometry = /*#__PURE__*/function (_PolyhedronGeometry) {
  24983. _inheritsLoose(TetrahedronGeometry, _PolyhedronGeometry);
  24984. function TetrahedronGeometry(radius, detail) {
  24985. var _this;
  24986. if (radius === void 0) {
  24987. radius = 1;
  24988. }
  24989. if (detail === void 0) {
  24990. detail = 0;
  24991. }
  24992. var vertices = [1, 1, 1, -1, -1, 1, -1, 1, -1, 1, -1, -1];
  24993. var indices = [2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1];
  24994. _this = _PolyhedronGeometry.call(this, vertices, indices, radius, detail) || this;
  24995. _this.type = 'TetrahedronGeometry';
  24996. _this.parameters = {
  24997. radius: radius,
  24998. detail: detail
  24999. };
  25000. return _this;
  25001. }
  25002. return TetrahedronGeometry;
  25003. }(PolyhedronGeometry);
  25004. var TextGeometry = /*#__PURE__*/function (_ExtrudeGeometry) {
  25005. _inheritsLoose(TextGeometry, _ExtrudeGeometry);
  25006. function TextGeometry(text, parameters) {
  25007. var _this;
  25008. if (parameters === void 0) {
  25009. parameters = {};
  25010. }
  25011. var font = parameters.font;
  25012. if (!(font && font.isFont)) {
  25013. console.error('THREE.TextGeometry: font parameter is not an instance of THREE.Font.');
  25014. return new BufferGeometry() || _assertThisInitialized(_this);
  25015. }
  25016. var shapes = font.generateShapes(text, parameters.size); // translate parameters to ExtrudeGeometry API
  25017. parameters.depth = parameters.height !== undefined ? parameters.height : 50; // defaults
  25018. if (parameters.bevelThickness === undefined) parameters.bevelThickness = 10;
  25019. if (parameters.bevelSize === undefined) parameters.bevelSize = 8;
  25020. if (parameters.bevelEnabled === undefined) parameters.bevelEnabled = false;
  25021. _this = _ExtrudeGeometry.call(this, shapes, parameters) || this;
  25022. _this.type = 'TextGeometry';
  25023. return _this;
  25024. }
  25025. return TextGeometry;
  25026. }(ExtrudeGeometry);
  25027. var TorusGeometry = /*#__PURE__*/function (_BufferGeometry) {
  25028. _inheritsLoose(TorusGeometry, _BufferGeometry);
  25029. function TorusGeometry(radius, tube, radialSegments, tubularSegments, arc) {
  25030. var _this;
  25031. if (radius === void 0) {
  25032. radius = 1;
  25033. }
  25034. if (tube === void 0) {
  25035. tube = 0.4;
  25036. }
  25037. if (radialSegments === void 0) {
  25038. radialSegments = 8;
  25039. }
  25040. if (tubularSegments === void 0) {
  25041. tubularSegments = 6;
  25042. }
  25043. if (arc === void 0) {
  25044. arc = Math.PI * 2;
  25045. }
  25046. _this = _BufferGeometry.call(this) || this;
  25047. _this.type = 'TorusGeometry';
  25048. _this.parameters = {
  25049. radius: radius,
  25050. tube: tube,
  25051. radialSegments: radialSegments,
  25052. tubularSegments: tubularSegments,
  25053. arc: arc
  25054. };
  25055. radialSegments = Math.floor(radialSegments);
  25056. tubularSegments = Math.floor(tubularSegments); // buffers
  25057. var indices = [];
  25058. var vertices = [];
  25059. var normals = [];
  25060. var uvs = []; // helper variables
  25061. var center = new Vector3();
  25062. var vertex = new Vector3();
  25063. var normal = new Vector3(); // generate vertices, normals and uvs
  25064. for (var j = 0; j <= radialSegments; j++) {
  25065. for (var i = 0; i <= tubularSegments; i++) {
  25066. var u = i / tubularSegments * arc;
  25067. var v = j / radialSegments * Math.PI * 2; // vertex
  25068. vertex.x = (radius + tube * Math.cos(v)) * Math.cos(u);
  25069. vertex.y = (radius + tube * Math.cos(v)) * Math.sin(u);
  25070. vertex.z = tube * Math.sin(v);
  25071. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  25072. center.x = radius * Math.cos(u);
  25073. center.y = radius * Math.sin(u);
  25074. normal.subVectors(vertex, center).normalize();
  25075. normals.push(normal.x, normal.y, normal.z); // uv
  25076. uvs.push(i / tubularSegments);
  25077. uvs.push(j / radialSegments);
  25078. }
  25079. } // generate indices
  25080. for (var _j = 1; _j <= radialSegments; _j++) {
  25081. for (var _i = 1; _i <= tubularSegments; _i++) {
  25082. // indices
  25083. var a = (tubularSegments + 1) * _j + _i - 1;
  25084. var b = (tubularSegments + 1) * (_j - 1) + _i - 1;
  25085. var c = (tubularSegments + 1) * (_j - 1) + _i;
  25086. var d = (tubularSegments + 1) * _j + _i; // faces
  25087. indices.push(a, b, d);
  25088. indices.push(b, c, d);
  25089. }
  25090. } // build geometry
  25091. _this.setIndex(indices);
  25092. _this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  25093. _this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  25094. _this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  25095. return _this;
  25096. }
  25097. return TorusGeometry;
  25098. }(BufferGeometry);
  25099. var TorusKnotGeometry = /*#__PURE__*/function (_BufferGeometry) {
  25100. _inheritsLoose(TorusKnotGeometry, _BufferGeometry);
  25101. function TorusKnotGeometry(radius, tube, tubularSegments, radialSegments, p, q) {
  25102. var _this;
  25103. if (radius === void 0) {
  25104. radius = 1;
  25105. }
  25106. if (tube === void 0) {
  25107. tube = 0.4;
  25108. }
  25109. if (tubularSegments === void 0) {
  25110. tubularSegments = 64;
  25111. }
  25112. if (radialSegments === void 0) {
  25113. radialSegments = 8;
  25114. }
  25115. if (p === void 0) {
  25116. p = 2;
  25117. }
  25118. if (q === void 0) {
  25119. q = 3;
  25120. }
  25121. _this = _BufferGeometry.call(this) || this;
  25122. _this.type = 'TorusKnotGeometry';
  25123. _this.parameters = {
  25124. radius: radius,
  25125. tube: tube,
  25126. tubularSegments: tubularSegments,
  25127. radialSegments: radialSegments,
  25128. p: p,
  25129. q: q
  25130. };
  25131. tubularSegments = Math.floor(tubularSegments);
  25132. radialSegments = Math.floor(radialSegments); // buffers
  25133. var indices = [];
  25134. var vertices = [];
  25135. var normals = [];
  25136. var uvs = []; // helper variables
  25137. var vertex = new Vector3();
  25138. var normal = new Vector3();
  25139. var P1 = new Vector3();
  25140. var P2 = new Vector3();
  25141. var B = new Vector3();
  25142. var T = new Vector3();
  25143. var N = new Vector3(); // generate vertices, normals and uvs
  25144. for (var i = 0; i <= tubularSegments; ++i) {
  25145. // the radian "u" is used to calculate the position on the torus curve of the current tubular segement
  25146. var u = i / tubularSegments * p * Math.PI * 2; // now we calculate two points. P1 is our current position on the curve, P2 is a little farther ahead.
  25147. // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions
  25148. calculatePositionOnCurve(u, p, q, radius, P1);
  25149. calculatePositionOnCurve(u + 0.01, p, q, radius, P2); // calculate orthonormal basis
  25150. T.subVectors(P2, P1);
  25151. N.addVectors(P2, P1);
  25152. B.crossVectors(T, N);
  25153. N.crossVectors(B, T); // normalize B, N. T can be ignored, we don't use it
  25154. B.normalize();
  25155. N.normalize();
  25156. for (var j = 0; j <= radialSegments; ++j) {
  25157. // now calculate the vertices. they are nothing more than an extrusion of the torus curve.
  25158. // because we extrude a shape in the xy-plane, there is no need to calculate a z-value.
  25159. var v = j / radialSegments * Math.PI * 2;
  25160. var cx = -tube * Math.cos(v);
  25161. var cy = tube * Math.sin(v); // now calculate the final vertex position.
  25162. // first we orient the extrusion with our basis vectos, then we add it to the current position on the curve
  25163. vertex.x = P1.x + (cx * N.x + cy * B.x);
  25164. vertex.y = P1.y + (cx * N.y + cy * B.y);
  25165. vertex.z = P1.z + (cx * N.z + cy * B.z);
  25166. vertices.push(vertex.x, vertex.y, vertex.z); // normal (P1 is always the center/origin of the extrusion, thus we can use it to calculate the normal)
  25167. normal.subVectors(vertex, P1).normalize();
  25168. normals.push(normal.x, normal.y, normal.z); // uv
  25169. uvs.push(i / tubularSegments);
  25170. uvs.push(j / radialSegments);
  25171. }
  25172. } // generate indices
  25173. for (var _j = 1; _j <= tubularSegments; _j++) {
  25174. for (var _i = 1; _i <= radialSegments; _i++) {
  25175. // indices
  25176. var a = (radialSegments + 1) * (_j - 1) + (_i - 1);
  25177. var b = (radialSegments + 1) * _j + (_i - 1);
  25178. var c = (radialSegments + 1) * _j + _i;
  25179. var d = (radialSegments + 1) * (_j - 1) + _i; // faces
  25180. indices.push(a, b, d);
  25181. indices.push(b, c, d);
  25182. }
  25183. } // build geometry
  25184. _this.setIndex(indices);
  25185. _this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  25186. _this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  25187. _this.setAttribute('uv', new Float32BufferAttribute(uvs, 2)); // this function calculates the current position on the torus curve
  25188. function calculatePositionOnCurve(u, p, q, radius, position) {
  25189. var cu = Math.cos(u);
  25190. var su = Math.sin(u);
  25191. var quOverP = q / p * u;
  25192. var cs = Math.cos(quOverP);
  25193. position.x = radius * (2 + cs) * 0.5 * cu;
  25194. position.y = radius * (2 + cs) * su * 0.5;
  25195. position.z = radius * Math.sin(quOverP) * 0.5;
  25196. }
  25197. return _this;
  25198. }
  25199. return TorusKnotGeometry;
  25200. }(BufferGeometry);
  25201. var TubeGeometry = /*#__PURE__*/function (_BufferGeometry) {
  25202. _inheritsLoose(TubeGeometry, _BufferGeometry);
  25203. function TubeGeometry(path, tubularSegments, radius, radialSegments, closed) {
  25204. var _this;
  25205. if (tubularSegments === void 0) {
  25206. tubularSegments = 64;
  25207. }
  25208. if (radius === void 0) {
  25209. radius = 1;
  25210. }
  25211. if (radialSegments === void 0) {
  25212. radialSegments = 8;
  25213. }
  25214. if (closed === void 0) {
  25215. closed = false;
  25216. }
  25217. _this = _BufferGeometry.call(this) || this;
  25218. _this.type = 'TubeGeometry';
  25219. _this.parameters = {
  25220. path: path,
  25221. tubularSegments: tubularSegments,
  25222. radius: radius,
  25223. radialSegments: radialSegments,
  25224. closed: closed
  25225. };
  25226. var frames = path.computeFrenetFrames(tubularSegments, closed); // expose internals
  25227. _this.tangents = frames.tangents;
  25228. _this.normals = frames.normals;
  25229. _this.binormals = frames.binormals; // helper variables
  25230. var vertex = new Vector3();
  25231. var normal = new Vector3();
  25232. var uv = new Vector2();
  25233. var P = new Vector3(); // buffer
  25234. var vertices = [];
  25235. var normals = [];
  25236. var uvs = [];
  25237. var indices = []; // create buffer data
  25238. generateBufferData(); // build geometry
  25239. _this.setIndex(indices);
  25240. _this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  25241. _this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  25242. _this.setAttribute('uv', new Float32BufferAttribute(uvs, 2)); // functions
  25243. function generateBufferData() {
  25244. for (var i = 0; i < tubularSegments; i++) {
  25245. generateSegment(i);
  25246. } // if the geometry is not closed, generate the last row of vertices and normals
  25247. // at the regular position on the given path
  25248. //
  25249. // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ)
  25250. generateSegment(closed === false ? tubularSegments : 0); // uvs are generated in a separate function.
  25251. // this makes it easy compute correct values for closed geometries
  25252. generateUVs(); // finally create faces
  25253. generateIndices();
  25254. }
  25255. function generateSegment(i) {
  25256. // we use getPointAt to sample evenly distributed points from the given path
  25257. P = path.getPointAt(i / tubularSegments, P); // retrieve corresponding normal and binormal
  25258. var N = frames.normals[i];
  25259. var B = frames.binormals[i]; // generate normals and vertices for the current segment
  25260. for (var j = 0; j <= radialSegments; j++) {
  25261. var v = j / radialSegments * Math.PI * 2;
  25262. var sin = Math.sin(v);
  25263. var cos = -Math.cos(v); // normal
  25264. normal.x = cos * N.x + sin * B.x;
  25265. normal.y = cos * N.y + sin * B.y;
  25266. normal.z = cos * N.z + sin * B.z;
  25267. normal.normalize();
  25268. normals.push(normal.x, normal.y, normal.z); // vertex
  25269. vertex.x = P.x + radius * normal.x;
  25270. vertex.y = P.y + radius * normal.y;
  25271. vertex.z = P.z + radius * normal.z;
  25272. vertices.push(vertex.x, vertex.y, vertex.z);
  25273. }
  25274. }
  25275. function generateIndices() {
  25276. for (var j = 1; j <= tubularSegments; j++) {
  25277. for (var i = 1; i <= radialSegments; i++) {
  25278. var a = (radialSegments + 1) * (j - 1) + (i - 1);
  25279. var b = (radialSegments + 1) * j + (i - 1);
  25280. var c = (radialSegments + 1) * j + i;
  25281. var d = (radialSegments + 1) * (j - 1) + i; // faces
  25282. indices.push(a, b, d);
  25283. indices.push(b, c, d);
  25284. }
  25285. }
  25286. }
  25287. function generateUVs() {
  25288. for (var i = 0; i <= tubularSegments; i++) {
  25289. for (var j = 0; j <= radialSegments; j++) {
  25290. uv.x = i / tubularSegments;
  25291. uv.y = j / radialSegments;
  25292. uvs.push(uv.x, uv.y);
  25293. }
  25294. }
  25295. }
  25296. return _this;
  25297. }
  25298. var _proto = TubeGeometry.prototype;
  25299. _proto.toJSON = function toJSON() {
  25300. var data = BufferGeometry.prototype.toJSON.call(this);
  25301. data.path = this.parameters.path.toJSON();
  25302. return data;
  25303. };
  25304. return TubeGeometry;
  25305. }(BufferGeometry);
  25306. var WireframeGeometry = /*#__PURE__*/function (_BufferGeometry) {
  25307. _inheritsLoose(WireframeGeometry, _BufferGeometry);
  25308. function WireframeGeometry(geometry) {
  25309. var _this;
  25310. _this = _BufferGeometry.call(this) || this;
  25311. _this.type = 'WireframeGeometry';
  25312. if (geometry.isGeometry === true) {
  25313. console.error('THREE.WireframeGeometry no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  25314. return _assertThisInitialized(_this);
  25315. } // buffer
  25316. var vertices = []; // helper variables
  25317. var edge = [0, 0],
  25318. edges = {};
  25319. var vertex = new Vector3();
  25320. if (geometry.index !== null) {
  25321. // indexed BufferGeometry
  25322. var position = geometry.attributes.position;
  25323. var indices = geometry.index;
  25324. var groups = geometry.groups;
  25325. if (groups.length === 0) {
  25326. groups = [{
  25327. start: 0,
  25328. count: indices.count,
  25329. materialIndex: 0
  25330. }];
  25331. } // create a data structure that contains all eges without duplicates
  25332. for (var o = 0, ol = groups.length; o < ol; ++o) {
  25333. var group = groups[o];
  25334. var start = group.start;
  25335. var count = group.count;
  25336. for (var i = start, l = start + count; i < l; i += 3) {
  25337. for (var j = 0; j < 3; j++) {
  25338. var edge1 = indices.getX(i + j);
  25339. var edge2 = indices.getX(i + (j + 1) % 3);
  25340. edge[0] = Math.min(edge1, edge2); // sorting prevents duplicates
  25341. edge[1] = Math.max(edge1, edge2);
  25342. var key = edge[0] + ',' + edge[1];
  25343. if (edges[key] === undefined) {
  25344. edges[key] = {
  25345. index1: edge[0],
  25346. index2: edge[1]
  25347. };
  25348. }
  25349. }
  25350. }
  25351. } // generate vertices
  25352. for (var _key in edges) {
  25353. var e = edges[_key];
  25354. vertex.fromBufferAttribute(position, e.index1);
  25355. vertices.push(vertex.x, vertex.y, vertex.z);
  25356. vertex.fromBufferAttribute(position, e.index2);
  25357. vertices.push(vertex.x, vertex.y, vertex.z);
  25358. }
  25359. } else {
  25360. // non-indexed BufferGeometry
  25361. var _position = geometry.attributes.position;
  25362. for (var _i = 0, _l = _position.count / 3; _i < _l; _i++) {
  25363. for (var _j = 0; _j < 3; _j++) {
  25364. // three edges per triangle, an edge is represented as (index1, index2)
  25365. // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0)
  25366. var index1 = 3 * _i + _j;
  25367. vertex.fromBufferAttribute(_position, index1);
  25368. vertices.push(vertex.x, vertex.y, vertex.z);
  25369. var index2 = 3 * _i + (_j + 1) % 3;
  25370. vertex.fromBufferAttribute(_position, index2);
  25371. vertices.push(vertex.x, vertex.y, vertex.z);
  25372. }
  25373. }
  25374. } // build geometry
  25375. _this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  25376. return _this;
  25377. }
  25378. return WireframeGeometry;
  25379. }(BufferGeometry);
  25380. var Geometries = /*#__PURE__*/Object.freeze({
  25381. __proto__: null,
  25382. BoxGeometry: BoxGeometry,
  25383. BoxBufferGeometry: BoxGeometry,
  25384. CircleGeometry: CircleGeometry,
  25385. CircleBufferGeometry: CircleGeometry,
  25386. ConeGeometry: ConeGeometry,
  25387. ConeBufferGeometry: ConeGeometry,
  25388. CylinderGeometry: CylinderGeometry,
  25389. CylinderBufferGeometry: CylinderGeometry,
  25390. DodecahedronGeometry: DodecahedronGeometry,
  25391. DodecahedronBufferGeometry: DodecahedronGeometry,
  25392. EdgesGeometry: EdgesGeometry,
  25393. ExtrudeGeometry: ExtrudeGeometry,
  25394. ExtrudeBufferGeometry: ExtrudeGeometry,
  25395. IcosahedronGeometry: IcosahedronGeometry,
  25396. IcosahedronBufferGeometry: IcosahedronGeometry,
  25397. LatheGeometry: LatheGeometry,
  25398. LatheBufferGeometry: LatheGeometry,
  25399. OctahedronGeometry: OctahedronGeometry,
  25400. OctahedronBufferGeometry: OctahedronGeometry,
  25401. ParametricGeometry: ParametricGeometry,
  25402. ParametricBufferGeometry: ParametricGeometry,
  25403. PlaneGeometry: PlaneGeometry,
  25404. PlaneBufferGeometry: PlaneGeometry,
  25405. PolyhedronGeometry: PolyhedronGeometry,
  25406. PolyhedronBufferGeometry: PolyhedronGeometry,
  25407. RingGeometry: RingGeometry,
  25408. RingBufferGeometry: RingGeometry,
  25409. ShapeGeometry: ShapeGeometry,
  25410. ShapeBufferGeometry: ShapeGeometry,
  25411. SphereGeometry: SphereGeometry,
  25412. SphereBufferGeometry: SphereGeometry,
  25413. TetrahedronGeometry: TetrahedronGeometry,
  25414. TetrahedronBufferGeometry: TetrahedronGeometry,
  25415. TextGeometry: TextGeometry,
  25416. TextBufferGeometry: TextGeometry,
  25417. TorusGeometry: TorusGeometry,
  25418. TorusBufferGeometry: TorusGeometry,
  25419. TorusKnotGeometry: TorusKnotGeometry,
  25420. TorusKnotBufferGeometry: TorusKnotGeometry,
  25421. TubeGeometry: TubeGeometry,
  25422. TubeBufferGeometry: TubeGeometry,
  25423. WireframeGeometry: WireframeGeometry
  25424. });
  25425. /**
  25426. * parameters = {
  25427. * color: <THREE.Color>
  25428. * }
  25429. */
  25430. function ShadowMaterial(parameters) {
  25431. Material.call(this);
  25432. this.type = 'ShadowMaterial';
  25433. this.color = new Color(0x000000);
  25434. this.transparent = true;
  25435. this.setValues(parameters);
  25436. }
  25437. ShadowMaterial.prototype = Object.create(Material.prototype);
  25438. ShadowMaterial.prototype.constructor = ShadowMaterial;
  25439. ShadowMaterial.prototype.isShadowMaterial = true;
  25440. ShadowMaterial.prototype.copy = function (source) {
  25441. Material.prototype.copy.call(this, source);
  25442. this.color.copy(source.color);
  25443. return this;
  25444. };
  25445. function RawShaderMaterial(parameters) {
  25446. ShaderMaterial.call(this, parameters);
  25447. this.type = 'RawShaderMaterial';
  25448. }
  25449. RawShaderMaterial.prototype = Object.create(ShaderMaterial.prototype);
  25450. RawShaderMaterial.prototype.constructor = RawShaderMaterial;
  25451. RawShaderMaterial.prototype.isRawShaderMaterial = true;
  25452. /**
  25453. * parameters = {
  25454. * color: <hex>,
  25455. * roughness: <float>,
  25456. * metalness: <float>,
  25457. * opacity: <float>,
  25458. *
  25459. * map: new THREE.Texture( <Image> ),
  25460. *
  25461. * lightMap: new THREE.Texture( <Image> ),
  25462. * lightMapIntensity: <float>
  25463. *
  25464. * aoMap: new THREE.Texture( <Image> ),
  25465. * aoMapIntensity: <float>
  25466. *
  25467. * emissive: <hex>,
  25468. * emissiveIntensity: <float>
  25469. * emissiveMap: new THREE.Texture( <Image> ),
  25470. *
  25471. * bumpMap: new THREE.Texture( <Image> ),
  25472. * bumpScale: <float>,
  25473. *
  25474. * normalMap: new THREE.Texture( <Image> ),
  25475. * normalMapType: THREE.TangentSpaceNormalMap,
  25476. * normalScale: <Vector2>,
  25477. *
  25478. * displacementMap: new THREE.Texture( <Image> ),
  25479. * displacementScale: <float>,
  25480. * displacementBias: <float>,
  25481. *
  25482. * roughnessMap: new THREE.Texture( <Image> ),
  25483. *
  25484. * metalnessMap: new THREE.Texture( <Image> ),
  25485. *
  25486. * alphaMap: new THREE.Texture( <Image> ),
  25487. *
  25488. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  25489. * envMapIntensity: <float>
  25490. *
  25491. * refractionRatio: <float>,
  25492. *
  25493. * wireframe: <boolean>,
  25494. * wireframeLinewidth: <float>,
  25495. *
  25496. * skinning: <bool>,
  25497. * morphTargets: <bool>,
  25498. * morphNormals: <bool>
  25499. * }
  25500. */
  25501. function MeshStandardMaterial(parameters) {
  25502. Material.call(this);
  25503. this.defines = {
  25504. 'STANDARD': ''
  25505. };
  25506. this.type = 'MeshStandardMaterial';
  25507. this.color = new Color(0xffffff); // diffuse
  25508. this.roughness = 1.0;
  25509. this.metalness = 0.0;
  25510. this.map = null;
  25511. this.lightMap = null;
  25512. this.lightMapIntensity = 1.0;
  25513. this.aoMap = null;
  25514. this.aoMapIntensity = 1.0;
  25515. this.emissive = new Color(0x000000);
  25516. this.emissiveIntensity = 1.0;
  25517. this.emissiveMap = null;
  25518. this.bumpMap = null;
  25519. this.bumpScale = 1;
  25520. this.normalMap = null;
  25521. this.normalMapType = TangentSpaceNormalMap;
  25522. this.normalScale = new Vector2(1, 1);
  25523. this.displacementMap = null;
  25524. this.displacementScale = 1;
  25525. this.displacementBias = 0;
  25526. this.roughnessMap = null;
  25527. this.metalnessMap = null;
  25528. this.alphaMap = null;
  25529. this.envMap = null;
  25530. this.envMapIntensity = 1.0;
  25531. this.refractionRatio = 0.98;
  25532. this.wireframe = false;
  25533. this.wireframeLinewidth = 1;
  25534. this.wireframeLinecap = 'round';
  25535. this.wireframeLinejoin = 'round';
  25536. this.skinning = false;
  25537. this.morphTargets = false;
  25538. this.morphNormals = false;
  25539. this.vertexTangents = false;
  25540. this.setValues(parameters);
  25541. }
  25542. MeshStandardMaterial.prototype = Object.create(Material.prototype);
  25543. MeshStandardMaterial.prototype.constructor = MeshStandardMaterial;
  25544. MeshStandardMaterial.prototype.isMeshStandardMaterial = true;
  25545. MeshStandardMaterial.prototype.copy = function (source) {
  25546. Material.prototype.copy.call(this, source);
  25547. this.defines = {
  25548. 'STANDARD': ''
  25549. };
  25550. this.color.copy(source.color);
  25551. this.roughness = source.roughness;
  25552. this.metalness = source.metalness;
  25553. this.map = source.map;
  25554. this.lightMap = source.lightMap;
  25555. this.lightMapIntensity = source.lightMapIntensity;
  25556. this.aoMap = source.aoMap;
  25557. this.aoMapIntensity = source.aoMapIntensity;
  25558. this.emissive.copy(source.emissive);
  25559. this.emissiveMap = source.emissiveMap;
  25560. this.emissiveIntensity = source.emissiveIntensity;
  25561. this.bumpMap = source.bumpMap;
  25562. this.bumpScale = source.bumpScale;
  25563. this.normalMap = source.normalMap;
  25564. this.normalMapType = source.normalMapType;
  25565. this.normalScale.copy(source.normalScale);
  25566. this.displacementMap = source.displacementMap;
  25567. this.displacementScale = source.displacementScale;
  25568. this.displacementBias = source.displacementBias;
  25569. this.roughnessMap = source.roughnessMap;
  25570. this.metalnessMap = source.metalnessMap;
  25571. this.alphaMap = source.alphaMap;
  25572. this.envMap = source.envMap;
  25573. this.envMapIntensity = source.envMapIntensity;
  25574. this.refractionRatio = source.refractionRatio;
  25575. this.wireframe = source.wireframe;
  25576. this.wireframeLinewidth = source.wireframeLinewidth;
  25577. this.wireframeLinecap = source.wireframeLinecap;
  25578. this.wireframeLinejoin = source.wireframeLinejoin;
  25579. this.skinning = source.skinning;
  25580. this.morphTargets = source.morphTargets;
  25581. this.morphNormals = source.morphNormals;
  25582. this.vertexTangents = source.vertexTangents;
  25583. return this;
  25584. };
  25585. /**
  25586. * parameters = {
  25587. * clearcoat: <float>,
  25588. * clearcoatMap: new THREE.Texture( <Image> ),
  25589. * clearcoatRoughness: <float>,
  25590. * clearcoatRoughnessMap: new THREE.Texture( <Image> ),
  25591. * clearcoatNormalScale: <Vector2>,
  25592. * clearcoatNormalMap: new THREE.Texture( <Image> ),
  25593. *
  25594. * reflectivity: <float>,
  25595. * ior: <float>,
  25596. *
  25597. * sheen: <Color>,
  25598. *
  25599. * transmission: <float>,
  25600. * transmissionMap: new THREE.Texture( <Image> )
  25601. * }
  25602. */
  25603. function MeshPhysicalMaterial(parameters) {
  25604. MeshStandardMaterial.call(this);
  25605. this.defines = {
  25606. 'STANDARD': '',
  25607. 'PHYSICAL': ''
  25608. };
  25609. this.type = 'MeshPhysicalMaterial';
  25610. this.clearcoat = 0.0;
  25611. this.clearcoatMap = null;
  25612. this.clearcoatRoughness = 0.0;
  25613. this.clearcoatRoughnessMap = null;
  25614. this.clearcoatNormalScale = new Vector2(1, 1);
  25615. this.clearcoatNormalMap = null;
  25616. this.reflectivity = 0.5; // maps to F0 = 0.04
  25617. Object.defineProperty(this, 'ior', {
  25618. get: function get() {
  25619. return (1 + 0.4 * this.reflectivity) / (1 - 0.4 * this.reflectivity);
  25620. },
  25621. set: function set(ior) {
  25622. this.reflectivity = MathUtils.clamp(2.5 * (ior - 1) / (ior + 1), 0, 1);
  25623. }
  25624. });
  25625. this.sheen = null; // null will disable sheen bsdf
  25626. this.transmission = 0.0;
  25627. this.transmissionMap = null;
  25628. this.setValues(parameters);
  25629. }
  25630. MeshPhysicalMaterial.prototype = Object.create(MeshStandardMaterial.prototype);
  25631. MeshPhysicalMaterial.prototype.constructor = MeshPhysicalMaterial;
  25632. MeshPhysicalMaterial.prototype.isMeshPhysicalMaterial = true;
  25633. MeshPhysicalMaterial.prototype.copy = function (source) {
  25634. MeshStandardMaterial.prototype.copy.call(this, source);
  25635. this.defines = {
  25636. 'STANDARD': '',
  25637. 'PHYSICAL': ''
  25638. };
  25639. this.clearcoat = source.clearcoat;
  25640. this.clearcoatMap = source.clearcoatMap;
  25641. this.clearcoatRoughness = source.clearcoatRoughness;
  25642. this.clearcoatRoughnessMap = source.clearcoatRoughnessMap;
  25643. this.clearcoatNormalMap = source.clearcoatNormalMap;
  25644. this.clearcoatNormalScale.copy(source.clearcoatNormalScale);
  25645. this.reflectivity = source.reflectivity;
  25646. if (source.sheen) {
  25647. this.sheen = (this.sheen || new Color()).copy(source.sheen);
  25648. } else {
  25649. this.sheen = null;
  25650. }
  25651. this.transmission = source.transmission;
  25652. this.transmissionMap = source.transmissionMap;
  25653. return this;
  25654. };
  25655. /**
  25656. * parameters = {
  25657. * color: <hex>,
  25658. * specular: <hex>,
  25659. * shininess: <float>,
  25660. * opacity: <float>,
  25661. *
  25662. * map: new THREE.Texture( <Image> ),
  25663. *
  25664. * lightMap: new THREE.Texture( <Image> ),
  25665. * lightMapIntensity: <float>
  25666. *
  25667. * aoMap: new THREE.Texture( <Image> ),
  25668. * aoMapIntensity: <float>
  25669. *
  25670. * emissive: <hex>,
  25671. * emissiveIntensity: <float>
  25672. * emissiveMap: new THREE.Texture( <Image> ),
  25673. *
  25674. * bumpMap: new THREE.Texture( <Image> ),
  25675. * bumpScale: <float>,
  25676. *
  25677. * normalMap: new THREE.Texture( <Image> ),
  25678. * normalMapType: THREE.TangentSpaceNormalMap,
  25679. * normalScale: <Vector2>,
  25680. *
  25681. * displacementMap: new THREE.Texture( <Image> ),
  25682. * displacementScale: <float>,
  25683. * displacementBias: <float>,
  25684. *
  25685. * specularMap: new THREE.Texture( <Image> ),
  25686. *
  25687. * alphaMap: new THREE.Texture( <Image> ),
  25688. *
  25689. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  25690. * combine: THREE.MultiplyOperation,
  25691. * reflectivity: <float>,
  25692. * refractionRatio: <float>,
  25693. *
  25694. * wireframe: <boolean>,
  25695. * wireframeLinewidth: <float>,
  25696. *
  25697. * skinning: <bool>,
  25698. * morphTargets: <bool>,
  25699. * morphNormals: <bool>
  25700. * }
  25701. */
  25702. function MeshPhongMaterial(parameters) {
  25703. Material.call(this);
  25704. this.type = 'MeshPhongMaterial';
  25705. this.color = new Color(0xffffff); // diffuse
  25706. this.specular = new Color(0x111111);
  25707. this.shininess = 30;
  25708. this.map = null;
  25709. this.lightMap = null;
  25710. this.lightMapIntensity = 1.0;
  25711. this.aoMap = null;
  25712. this.aoMapIntensity = 1.0;
  25713. this.emissive = new Color(0x000000);
  25714. this.emissiveIntensity = 1.0;
  25715. this.emissiveMap = null;
  25716. this.bumpMap = null;
  25717. this.bumpScale = 1;
  25718. this.normalMap = null;
  25719. this.normalMapType = TangentSpaceNormalMap;
  25720. this.normalScale = new Vector2(1, 1);
  25721. this.displacementMap = null;
  25722. this.displacementScale = 1;
  25723. this.displacementBias = 0;
  25724. this.specularMap = null;
  25725. this.alphaMap = null;
  25726. this.envMap = null;
  25727. this.combine = MultiplyOperation;
  25728. this.reflectivity = 1;
  25729. this.refractionRatio = 0.98;
  25730. this.wireframe = false;
  25731. this.wireframeLinewidth = 1;
  25732. this.wireframeLinecap = 'round';
  25733. this.wireframeLinejoin = 'round';
  25734. this.skinning = false;
  25735. this.morphTargets = false;
  25736. this.morphNormals = false;
  25737. this.setValues(parameters);
  25738. }
  25739. MeshPhongMaterial.prototype = Object.create(Material.prototype);
  25740. MeshPhongMaterial.prototype.constructor = MeshPhongMaterial;
  25741. MeshPhongMaterial.prototype.isMeshPhongMaterial = true;
  25742. MeshPhongMaterial.prototype.copy = function (source) {
  25743. Material.prototype.copy.call(this, source);
  25744. this.color.copy(source.color);
  25745. this.specular.copy(source.specular);
  25746. this.shininess = source.shininess;
  25747. this.map = source.map;
  25748. this.lightMap = source.lightMap;
  25749. this.lightMapIntensity = source.lightMapIntensity;
  25750. this.aoMap = source.aoMap;
  25751. this.aoMapIntensity = source.aoMapIntensity;
  25752. this.emissive.copy(source.emissive);
  25753. this.emissiveMap = source.emissiveMap;
  25754. this.emissiveIntensity = source.emissiveIntensity;
  25755. this.bumpMap = source.bumpMap;
  25756. this.bumpScale = source.bumpScale;
  25757. this.normalMap = source.normalMap;
  25758. this.normalMapType = source.normalMapType;
  25759. this.normalScale.copy(source.normalScale);
  25760. this.displacementMap = source.displacementMap;
  25761. this.displacementScale = source.displacementScale;
  25762. this.displacementBias = source.displacementBias;
  25763. this.specularMap = source.specularMap;
  25764. this.alphaMap = source.alphaMap;
  25765. this.envMap = source.envMap;
  25766. this.combine = source.combine;
  25767. this.reflectivity = source.reflectivity;
  25768. this.refractionRatio = source.refractionRatio;
  25769. this.wireframe = source.wireframe;
  25770. this.wireframeLinewidth = source.wireframeLinewidth;
  25771. this.wireframeLinecap = source.wireframeLinecap;
  25772. this.wireframeLinejoin = source.wireframeLinejoin;
  25773. this.skinning = source.skinning;
  25774. this.morphTargets = source.morphTargets;
  25775. this.morphNormals = source.morphNormals;
  25776. return this;
  25777. };
  25778. /**
  25779. * parameters = {
  25780. * color: <hex>,
  25781. *
  25782. * map: new THREE.Texture( <Image> ),
  25783. * gradientMap: new THREE.Texture( <Image> ),
  25784. *
  25785. * lightMap: new THREE.Texture( <Image> ),
  25786. * lightMapIntensity: <float>
  25787. *
  25788. * aoMap: new THREE.Texture( <Image> ),
  25789. * aoMapIntensity: <float>
  25790. *
  25791. * emissive: <hex>,
  25792. * emissiveIntensity: <float>
  25793. * emissiveMap: new THREE.Texture( <Image> ),
  25794. *
  25795. * bumpMap: new THREE.Texture( <Image> ),
  25796. * bumpScale: <float>,
  25797. *
  25798. * normalMap: new THREE.Texture( <Image> ),
  25799. * normalMapType: THREE.TangentSpaceNormalMap,
  25800. * normalScale: <Vector2>,
  25801. *
  25802. * displacementMap: new THREE.Texture( <Image> ),
  25803. * displacementScale: <float>,
  25804. * displacementBias: <float>,
  25805. *
  25806. * alphaMap: new THREE.Texture( <Image> ),
  25807. *
  25808. * wireframe: <boolean>,
  25809. * wireframeLinewidth: <float>,
  25810. *
  25811. * skinning: <bool>,
  25812. * morphTargets: <bool>,
  25813. * morphNormals: <bool>
  25814. * }
  25815. */
  25816. function MeshToonMaterial(parameters) {
  25817. Material.call(this);
  25818. this.defines = {
  25819. 'TOON': ''
  25820. };
  25821. this.type = 'MeshToonMaterial';
  25822. this.color = new Color(0xffffff);
  25823. this.map = null;
  25824. this.gradientMap = null;
  25825. this.lightMap = null;
  25826. this.lightMapIntensity = 1.0;
  25827. this.aoMap = null;
  25828. this.aoMapIntensity = 1.0;
  25829. this.emissive = new Color(0x000000);
  25830. this.emissiveIntensity = 1.0;
  25831. this.emissiveMap = null;
  25832. this.bumpMap = null;
  25833. this.bumpScale = 1;
  25834. this.normalMap = null;
  25835. this.normalMapType = TangentSpaceNormalMap;
  25836. this.normalScale = new Vector2(1, 1);
  25837. this.displacementMap = null;
  25838. this.displacementScale = 1;
  25839. this.displacementBias = 0;
  25840. this.alphaMap = null;
  25841. this.wireframe = false;
  25842. this.wireframeLinewidth = 1;
  25843. this.wireframeLinecap = 'round';
  25844. this.wireframeLinejoin = 'round';
  25845. this.skinning = false;
  25846. this.morphTargets = false;
  25847. this.morphNormals = false;
  25848. this.setValues(parameters);
  25849. }
  25850. MeshToonMaterial.prototype = Object.create(Material.prototype);
  25851. MeshToonMaterial.prototype.constructor = MeshToonMaterial;
  25852. MeshToonMaterial.prototype.isMeshToonMaterial = true;
  25853. MeshToonMaterial.prototype.copy = function (source) {
  25854. Material.prototype.copy.call(this, source);
  25855. this.color.copy(source.color);
  25856. this.map = source.map;
  25857. this.gradientMap = source.gradientMap;
  25858. this.lightMap = source.lightMap;
  25859. this.lightMapIntensity = source.lightMapIntensity;
  25860. this.aoMap = source.aoMap;
  25861. this.aoMapIntensity = source.aoMapIntensity;
  25862. this.emissive.copy(source.emissive);
  25863. this.emissiveMap = source.emissiveMap;
  25864. this.emissiveIntensity = source.emissiveIntensity;
  25865. this.bumpMap = source.bumpMap;
  25866. this.bumpScale = source.bumpScale;
  25867. this.normalMap = source.normalMap;
  25868. this.normalMapType = source.normalMapType;
  25869. this.normalScale.copy(source.normalScale);
  25870. this.displacementMap = source.displacementMap;
  25871. this.displacementScale = source.displacementScale;
  25872. this.displacementBias = source.displacementBias;
  25873. this.alphaMap = source.alphaMap;
  25874. this.wireframe = source.wireframe;
  25875. this.wireframeLinewidth = source.wireframeLinewidth;
  25876. this.wireframeLinecap = source.wireframeLinecap;
  25877. this.wireframeLinejoin = source.wireframeLinejoin;
  25878. this.skinning = source.skinning;
  25879. this.morphTargets = source.morphTargets;
  25880. this.morphNormals = source.morphNormals;
  25881. return this;
  25882. };
  25883. /**
  25884. * parameters = {
  25885. * opacity: <float>,
  25886. *
  25887. * bumpMap: new THREE.Texture( <Image> ),
  25888. * bumpScale: <float>,
  25889. *
  25890. * normalMap: new THREE.Texture( <Image> ),
  25891. * normalMapType: THREE.TangentSpaceNormalMap,
  25892. * normalScale: <Vector2>,
  25893. *
  25894. * displacementMap: new THREE.Texture( <Image> ),
  25895. * displacementScale: <float>,
  25896. * displacementBias: <float>,
  25897. *
  25898. * wireframe: <boolean>,
  25899. * wireframeLinewidth: <float>
  25900. *
  25901. * skinning: <bool>,
  25902. * morphTargets: <bool>,
  25903. * morphNormals: <bool>
  25904. * }
  25905. */
  25906. function MeshNormalMaterial(parameters) {
  25907. Material.call(this);
  25908. this.type = 'MeshNormalMaterial';
  25909. this.bumpMap = null;
  25910. this.bumpScale = 1;
  25911. this.normalMap = null;
  25912. this.normalMapType = TangentSpaceNormalMap;
  25913. this.normalScale = new Vector2(1, 1);
  25914. this.displacementMap = null;
  25915. this.displacementScale = 1;
  25916. this.displacementBias = 0;
  25917. this.wireframe = false;
  25918. this.wireframeLinewidth = 1;
  25919. this.fog = false;
  25920. this.skinning = false;
  25921. this.morphTargets = false;
  25922. this.morphNormals = false;
  25923. this.setValues(parameters);
  25924. }
  25925. MeshNormalMaterial.prototype = Object.create(Material.prototype);
  25926. MeshNormalMaterial.prototype.constructor = MeshNormalMaterial;
  25927. MeshNormalMaterial.prototype.isMeshNormalMaterial = true;
  25928. MeshNormalMaterial.prototype.copy = function (source) {
  25929. Material.prototype.copy.call(this, source);
  25930. this.bumpMap = source.bumpMap;
  25931. this.bumpScale = source.bumpScale;
  25932. this.normalMap = source.normalMap;
  25933. this.normalMapType = source.normalMapType;
  25934. this.normalScale.copy(source.normalScale);
  25935. this.displacementMap = source.displacementMap;
  25936. this.displacementScale = source.displacementScale;
  25937. this.displacementBias = source.displacementBias;
  25938. this.wireframe = source.wireframe;
  25939. this.wireframeLinewidth = source.wireframeLinewidth;
  25940. this.skinning = source.skinning;
  25941. this.morphTargets = source.morphTargets;
  25942. this.morphNormals = source.morphNormals;
  25943. return this;
  25944. };
  25945. /**
  25946. * parameters = {
  25947. * color: <hex>,
  25948. * opacity: <float>,
  25949. *
  25950. * map: new THREE.Texture( <Image> ),
  25951. *
  25952. * lightMap: new THREE.Texture( <Image> ),
  25953. * lightMapIntensity: <float>
  25954. *
  25955. * aoMap: new THREE.Texture( <Image> ),
  25956. * aoMapIntensity: <float>
  25957. *
  25958. * emissive: <hex>,
  25959. * emissiveIntensity: <float>
  25960. * emissiveMap: new THREE.Texture( <Image> ),
  25961. *
  25962. * specularMap: new THREE.Texture( <Image> ),
  25963. *
  25964. * alphaMap: new THREE.Texture( <Image> ),
  25965. *
  25966. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  25967. * combine: THREE.Multiply,
  25968. * reflectivity: <float>,
  25969. * refractionRatio: <float>,
  25970. *
  25971. * wireframe: <boolean>,
  25972. * wireframeLinewidth: <float>,
  25973. *
  25974. * skinning: <bool>,
  25975. * morphTargets: <bool>,
  25976. * morphNormals: <bool>
  25977. * }
  25978. */
  25979. function MeshLambertMaterial(parameters) {
  25980. Material.call(this);
  25981. this.type = 'MeshLambertMaterial';
  25982. this.color = new Color(0xffffff); // diffuse
  25983. this.map = null;
  25984. this.lightMap = null;
  25985. this.lightMapIntensity = 1.0;
  25986. this.aoMap = null;
  25987. this.aoMapIntensity = 1.0;
  25988. this.emissive = new Color(0x000000);
  25989. this.emissiveIntensity = 1.0;
  25990. this.emissiveMap = null;
  25991. this.specularMap = null;
  25992. this.alphaMap = null;
  25993. this.envMap = null;
  25994. this.combine = MultiplyOperation;
  25995. this.reflectivity = 1;
  25996. this.refractionRatio = 0.98;
  25997. this.wireframe = false;
  25998. this.wireframeLinewidth = 1;
  25999. this.wireframeLinecap = 'round';
  26000. this.wireframeLinejoin = 'round';
  26001. this.skinning = false;
  26002. this.morphTargets = false;
  26003. this.morphNormals = false;
  26004. this.setValues(parameters);
  26005. }
  26006. MeshLambertMaterial.prototype = Object.create(Material.prototype);
  26007. MeshLambertMaterial.prototype.constructor = MeshLambertMaterial;
  26008. MeshLambertMaterial.prototype.isMeshLambertMaterial = true;
  26009. MeshLambertMaterial.prototype.copy = function (source) {
  26010. Material.prototype.copy.call(this, source);
  26011. this.color.copy(source.color);
  26012. this.map = source.map;
  26013. this.lightMap = source.lightMap;
  26014. this.lightMapIntensity = source.lightMapIntensity;
  26015. this.aoMap = source.aoMap;
  26016. this.aoMapIntensity = source.aoMapIntensity;
  26017. this.emissive.copy(source.emissive);
  26018. this.emissiveMap = source.emissiveMap;
  26019. this.emissiveIntensity = source.emissiveIntensity;
  26020. this.specularMap = source.specularMap;
  26021. this.alphaMap = source.alphaMap;
  26022. this.envMap = source.envMap;
  26023. this.combine = source.combine;
  26024. this.reflectivity = source.reflectivity;
  26025. this.refractionRatio = source.refractionRatio;
  26026. this.wireframe = source.wireframe;
  26027. this.wireframeLinewidth = source.wireframeLinewidth;
  26028. this.wireframeLinecap = source.wireframeLinecap;
  26029. this.wireframeLinejoin = source.wireframeLinejoin;
  26030. this.skinning = source.skinning;
  26031. this.morphTargets = source.morphTargets;
  26032. this.morphNormals = source.morphNormals;
  26033. return this;
  26034. };
  26035. /**
  26036. * parameters = {
  26037. * color: <hex>,
  26038. * opacity: <float>,
  26039. *
  26040. * matcap: new THREE.Texture( <Image> ),
  26041. *
  26042. * map: new THREE.Texture( <Image> ),
  26043. *
  26044. * bumpMap: new THREE.Texture( <Image> ),
  26045. * bumpScale: <float>,
  26046. *
  26047. * normalMap: new THREE.Texture( <Image> ),
  26048. * normalMapType: THREE.TangentSpaceNormalMap,
  26049. * normalScale: <Vector2>,
  26050. *
  26051. * displacementMap: new THREE.Texture( <Image> ),
  26052. * displacementScale: <float>,
  26053. * displacementBias: <float>,
  26054. *
  26055. * alphaMap: new THREE.Texture( <Image> ),
  26056. *
  26057. * skinning: <bool>,
  26058. * morphTargets: <bool>,
  26059. * morphNormals: <bool>
  26060. * }
  26061. */
  26062. function MeshMatcapMaterial(parameters) {
  26063. Material.call(this);
  26064. this.defines = {
  26065. 'MATCAP': ''
  26066. };
  26067. this.type = 'MeshMatcapMaterial';
  26068. this.color = new Color(0xffffff); // diffuse
  26069. this.matcap = null;
  26070. this.map = null;
  26071. this.bumpMap = null;
  26072. this.bumpScale = 1;
  26073. this.normalMap = null;
  26074. this.normalMapType = TangentSpaceNormalMap;
  26075. this.normalScale = new Vector2(1, 1);
  26076. this.displacementMap = null;
  26077. this.displacementScale = 1;
  26078. this.displacementBias = 0;
  26079. this.alphaMap = null;
  26080. this.skinning = false;
  26081. this.morphTargets = false;
  26082. this.morphNormals = false;
  26083. this.setValues(parameters);
  26084. }
  26085. MeshMatcapMaterial.prototype = Object.create(Material.prototype);
  26086. MeshMatcapMaterial.prototype.constructor = MeshMatcapMaterial;
  26087. MeshMatcapMaterial.prototype.isMeshMatcapMaterial = true;
  26088. MeshMatcapMaterial.prototype.copy = function (source) {
  26089. Material.prototype.copy.call(this, source);
  26090. this.defines = {
  26091. 'MATCAP': ''
  26092. };
  26093. this.color.copy(source.color);
  26094. this.matcap = source.matcap;
  26095. this.map = source.map;
  26096. this.bumpMap = source.bumpMap;
  26097. this.bumpScale = source.bumpScale;
  26098. this.normalMap = source.normalMap;
  26099. this.normalMapType = source.normalMapType;
  26100. this.normalScale.copy(source.normalScale);
  26101. this.displacementMap = source.displacementMap;
  26102. this.displacementScale = source.displacementScale;
  26103. this.displacementBias = source.displacementBias;
  26104. this.alphaMap = source.alphaMap;
  26105. this.skinning = source.skinning;
  26106. this.morphTargets = source.morphTargets;
  26107. this.morphNormals = source.morphNormals;
  26108. return this;
  26109. };
  26110. /**
  26111. * parameters = {
  26112. * color: <hex>,
  26113. * opacity: <float>,
  26114. *
  26115. * linewidth: <float>,
  26116. *
  26117. * scale: <float>,
  26118. * dashSize: <float>,
  26119. * gapSize: <float>
  26120. * }
  26121. */
  26122. function LineDashedMaterial(parameters) {
  26123. LineBasicMaterial.call(this);
  26124. this.type = 'LineDashedMaterial';
  26125. this.scale = 1;
  26126. this.dashSize = 3;
  26127. this.gapSize = 1;
  26128. this.setValues(parameters);
  26129. }
  26130. LineDashedMaterial.prototype = Object.create(LineBasicMaterial.prototype);
  26131. LineDashedMaterial.prototype.constructor = LineDashedMaterial;
  26132. LineDashedMaterial.prototype.isLineDashedMaterial = true;
  26133. LineDashedMaterial.prototype.copy = function (source) {
  26134. LineBasicMaterial.prototype.copy.call(this, source);
  26135. this.scale = source.scale;
  26136. this.dashSize = source.dashSize;
  26137. this.gapSize = source.gapSize;
  26138. return this;
  26139. };
  26140. var Materials = /*#__PURE__*/Object.freeze({
  26141. __proto__: null,
  26142. ShadowMaterial: ShadowMaterial,
  26143. SpriteMaterial: SpriteMaterial,
  26144. RawShaderMaterial: RawShaderMaterial,
  26145. ShaderMaterial: ShaderMaterial,
  26146. PointsMaterial: PointsMaterial,
  26147. MeshPhysicalMaterial: MeshPhysicalMaterial,
  26148. MeshStandardMaterial: MeshStandardMaterial,
  26149. MeshPhongMaterial: MeshPhongMaterial,
  26150. MeshToonMaterial: MeshToonMaterial,
  26151. MeshNormalMaterial: MeshNormalMaterial,
  26152. MeshLambertMaterial: MeshLambertMaterial,
  26153. MeshDepthMaterial: MeshDepthMaterial,
  26154. MeshDistanceMaterial: MeshDistanceMaterial,
  26155. MeshBasicMaterial: MeshBasicMaterial,
  26156. MeshMatcapMaterial: MeshMatcapMaterial,
  26157. LineDashedMaterial: LineDashedMaterial,
  26158. LineBasicMaterial: LineBasicMaterial,
  26159. Material: Material
  26160. });
  26161. var AnimationUtils = {
  26162. // same as Array.prototype.slice, but also works on typed arrays
  26163. arraySlice: function arraySlice(array, from, to) {
  26164. if (AnimationUtils.isTypedArray(array)) {
  26165. // in ios9 array.subarray(from, undefined) will return empty array
  26166. // but array.subarray(from) or array.subarray(from, len) is correct
  26167. return new array.constructor(array.subarray(from, to !== undefined ? to : array.length));
  26168. }
  26169. return array.slice(from, to);
  26170. },
  26171. // converts an array to a specific type
  26172. convertArray: function convertArray(array, type, forceClone) {
  26173. if (!array || // let 'undefined' and 'null' pass
  26174. !forceClone && array.constructor === type) return array;
  26175. if (typeof type.BYTES_PER_ELEMENT === 'number') {
  26176. return new type(array); // create typed array
  26177. }
  26178. return Array.prototype.slice.call(array); // create Array
  26179. },
  26180. isTypedArray: function isTypedArray(object) {
  26181. return ArrayBuffer.isView(object) && !(object instanceof DataView);
  26182. },
  26183. // returns an array by which times and values can be sorted
  26184. getKeyframeOrder: function getKeyframeOrder(times) {
  26185. function compareTime(i, j) {
  26186. return times[i] - times[j];
  26187. }
  26188. var n = times.length;
  26189. var result = new Array(n);
  26190. for (var i = 0; i !== n; ++i) {
  26191. result[i] = i;
  26192. }
  26193. result.sort(compareTime);
  26194. return result;
  26195. },
  26196. // uses the array previously returned by 'getKeyframeOrder' to sort data
  26197. sortedArray: function sortedArray(values, stride, order) {
  26198. var nValues = values.length;
  26199. var result = new values.constructor(nValues);
  26200. for (var i = 0, dstOffset = 0; dstOffset !== nValues; ++i) {
  26201. var srcOffset = order[i] * stride;
  26202. for (var j = 0; j !== stride; ++j) {
  26203. result[dstOffset++] = values[srcOffset + j];
  26204. }
  26205. }
  26206. return result;
  26207. },
  26208. // function for parsing AOS keyframe formats
  26209. flattenJSON: function flattenJSON(jsonKeys, times, values, valuePropertyName) {
  26210. var i = 1,
  26211. key = jsonKeys[0];
  26212. while (key !== undefined && key[valuePropertyName] === undefined) {
  26213. key = jsonKeys[i++];
  26214. }
  26215. if (key === undefined) return; // no data
  26216. var value = key[valuePropertyName];
  26217. if (value === undefined) return; // no data
  26218. if (Array.isArray(value)) {
  26219. do {
  26220. value = key[valuePropertyName];
  26221. if (value !== undefined) {
  26222. times.push(key.time);
  26223. values.push.apply(values, value); // push all elements
  26224. }
  26225. key = jsonKeys[i++];
  26226. } while (key !== undefined);
  26227. } else if (value.toArray !== undefined) {
  26228. // ...assume THREE.Math-ish
  26229. do {
  26230. value = key[valuePropertyName];
  26231. if (value !== undefined) {
  26232. times.push(key.time);
  26233. value.toArray(values, values.length);
  26234. }
  26235. key = jsonKeys[i++];
  26236. } while (key !== undefined);
  26237. } else {
  26238. // otherwise push as-is
  26239. do {
  26240. value = key[valuePropertyName];
  26241. if (value !== undefined) {
  26242. times.push(key.time);
  26243. values.push(value);
  26244. }
  26245. key = jsonKeys[i++];
  26246. } while (key !== undefined);
  26247. }
  26248. },
  26249. subclip: function subclip(sourceClip, name, startFrame, endFrame, fps) {
  26250. if (fps === void 0) {
  26251. fps = 30;
  26252. }
  26253. var clip = sourceClip.clone();
  26254. clip.name = name;
  26255. var tracks = [];
  26256. for (var i = 0; i < clip.tracks.length; ++i) {
  26257. var track = clip.tracks[i];
  26258. var valueSize = track.getValueSize();
  26259. var times = [];
  26260. var values = [];
  26261. for (var j = 0; j < track.times.length; ++j) {
  26262. var frame = track.times[j] * fps;
  26263. if (frame < startFrame || frame >= endFrame) continue;
  26264. times.push(track.times[j]);
  26265. for (var k = 0; k < valueSize; ++k) {
  26266. values.push(track.values[j * valueSize + k]);
  26267. }
  26268. }
  26269. if (times.length === 0) continue;
  26270. track.times = AnimationUtils.convertArray(times, track.times.constructor);
  26271. track.values = AnimationUtils.convertArray(values, track.values.constructor);
  26272. tracks.push(track);
  26273. }
  26274. clip.tracks = tracks; // find minimum .times value across all tracks in the trimmed clip
  26275. var minStartTime = Infinity;
  26276. for (var _i = 0; _i < clip.tracks.length; ++_i) {
  26277. if (minStartTime > clip.tracks[_i].times[0]) {
  26278. minStartTime = clip.tracks[_i].times[0];
  26279. }
  26280. } // shift all tracks such that clip begins at t=0
  26281. for (var _i2 = 0; _i2 < clip.tracks.length; ++_i2) {
  26282. clip.tracks[_i2].shift(-1 * minStartTime);
  26283. }
  26284. clip.resetDuration();
  26285. return clip;
  26286. },
  26287. makeClipAdditive: function makeClipAdditive(targetClip, referenceFrame, referenceClip, fps) {
  26288. if (referenceFrame === void 0) {
  26289. referenceFrame = 0;
  26290. }
  26291. if (referenceClip === void 0) {
  26292. referenceClip = targetClip;
  26293. }
  26294. if (fps === void 0) {
  26295. fps = 30;
  26296. }
  26297. if (fps <= 0) fps = 30;
  26298. var numTracks = referenceClip.tracks.length;
  26299. var referenceTime = referenceFrame / fps; // Make each track's values relative to the values at the reference frame
  26300. var _loop = function _loop(i) {
  26301. var referenceTrack = referenceClip.tracks[i];
  26302. var referenceTrackType = referenceTrack.ValueTypeName; // Skip this track if it's non-numeric
  26303. if (referenceTrackType === 'bool' || referenceTrackType === 'string') return "continue"; // Find the track in the target clip whose name and type matches the reference track
  26304. var targetTrack = targetClip.tracks.find(function (track) {
  26305. return track.name === referenceTrack.name && track.ValueTypeName === referenceTrackType;
  26306. });
  26307. if (targetTrack === undefined) return "continue";
  26308. var referenceOffset = 0;
  26309. var referenceValueSize = referenceTrack.getValueSize();
  26310. if (referenceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline) {
  26311. referenceOffset = referenceValueSize / 3;
  26312. }
  26313. var targetOffset = 0;
  26314. var targetValueSize = targetTrack.getValueSize();
  26315. if (targetTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline) {
  26316. targetOffset = targetValueSize / 3;
  26317. }
  26318. var lastIndex = referenceTrack.times.length - 1;
  26319. var referenceValue = void 0; // Find the value to subtract out of the track
  26320. if (referenceTime <= referenceTrack.times[0]) {
  26321. // Reference frame is earlier than the first keyframe, so just use the first keyframe
  26322. var startIndex = referenceOffset;
  26323. var endIndex = referenceValueSize - referenceOffset;
  26324. referenceValue = AnimationUtils.arraySlice(referenceTrack.values, startIndex, endIndex);
  26325. } else if (referenceTime >= referenceTrack.times[lastIndex]) {
  26326. // Reference frame is after the last keyframe, so just use the last keyframe
  26327. var _startIndex = lastIndex * referenceValueSize + referenceOffset;
  26328. var _endIndex = _startIndex + referenceValueSize - referenceOffset;
  26329. referenceValue = AnimationUtils.arraySlice(referenceTrack.values, _startIndex, _endIndex);
  26330. } else {
  26331. // Interpolate to the reference value
  26332. var interpolant = referenceTrack.createInterpolant();
  26333. var _startIndex2 = referenceOffset;
  26334. var _endIndex2 = referenceValueSize - referenceOffset;
  26335. interpolant.evaluate(referenceTime);
  26336. referenceValue = AnimationUtils.arraySlice(interpolant.resultBuffer, _startIndex2, _endIndex2);
  26337. } // Conjugate the quaternion
  26338. if (referenceTrackType === 'quaternion') {
  26339. var referenceQuat = new Quaternion().fromArray(referenceValue).normalize().conjugate();
  26340. referenceQuat.toArray(referenceValue);
  26341. } // Subtract the reference value from all of the track values
  26342. var numTimes = targetTrack.times.length;
  26343. for (var j = 0; j < numTimes; ++j) {
  26344. var valueStart = j * targetValueSize + targetOffset;
  26345. if (referenceTrackType === 'quaternion') {
  26346. // Multiply the conjugate for quaternion track types
  26347. Quaternion.multiplyQuaternionsFlat(targetTrack.values, valueStart, referenceValue, 0, targetTrack.values, valueStart);
  26348. } else {
  26349. var valueEnd = targetValueSize - targetOffset * 2; // Subtract each value for all other numeric track types
  26350. for (var k = 0; k < valueEnd; ++k) {
  26351. targetTrack.values[valueStart + k] -= referenceValue[k];
  26352. }
  26353. }
  26354. }
  26355. };
  26356. for (var i = 0; i < numTracks; ++i) {
  26357. var _ret = _loop(i);
  26358. if (_ret === "continue") continue;
  26359. }
  26360. targetClip.blendMode = AdditiveAnimationBlendMode;
  26361. return targetClip;
  26362. }
  26363. };
  26364. /**
  26365. * Abstract base class of interpolants over parametric samples.
  26366. *
  26367. * The parameter domain is one dimensional, typically the time or a path
  26368. * along a curve defined by the data.
  26369. *
  26370. * The sample values can have any dimensionality and derived classes may
  26371. * apply special interpretations to the data.
  26372. *
  26373. * This class provides the interval seek in a Template Method, deferring
  26374. * the actual interpolation to derived classes.
  26375. *
  26376. * Time complexity is O(1) for linear access crossing at most two points
  26377. * and O(log N) for random access, where N is the number of positions.
  26378. *
  26379. * References:
  26380. *
  26381. * http://www.oodesign.com/template-method-pattern.html
  26382. *
  26383. */
  26384. function Interpolant(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  26385. this.parameterPositions = parameterPositions;
  26386. this._cachedIndex = 0;
  26387. this.resultBuffer = resultBuffer !== undefined ? resultBuffer : new sampleValues.constructor(sampleSize);
  26388. this.sampleValues = sampleValues;
  26389. this.valueSize = sampleSize;
  26390. }
  26391. Object.assign(Interpolant.prototype, {
  26392. evaluate: function evaluate(t) {
  26393. var pp = this.parameterPositions;
  26394. var i1 = this._cachedIndex,
  26395. t1 = pp[i1],
  26396. t0 = pp[i1 - 1];
  26397. validate_interval: {
  26398. seek: {
  26399. var right;
  26400. linear_scan: {
  26401. //- See http://jsperf.com/comparison-to-undefined/3
  26402. //- slower code:
  26403. //-
  26404. //- if ( t >= t1 || t1 === undefined ) {
  26405. forward_scan: if (!(t < t1)) {
  26406. for (var giveUpAt = i1 + 2;;) {
  26407. if (t1 === undefined) {
  26408. if (t < t0) break forward_scan; // after end
  26409. i1 = pp.length;
  26410. this._cachedIndex = i1;
  26411. return this.afterEnd_(i1 - 1, t, t0);
  26412. }
  26413. if (i1 === giveUpAt) break; // this loop
  26414. t0 = t1;
  26415. t1 = pp[++i1];
  26416. if (t < t1) {
  26417. // we have arrived at the sought interval
  26418. break seek;
  26419. }
  26420. } // prepare binary search on the right side of the index
  26421. right = pp.length;
  26422. break linear_scan;
  26423. } //- slower code:
  26424. //- if ( t < t0 || t0 === undefined ) {
  26425. if (!(t >= t0)) {
  26426. // looping?
  26427. var t1global = pp[1];
  26428. if (t < t1global) {
  26429. i1 = 2; // + 1, using the scan for the details
  26430. t0 = t1global;
  26431. } // linear reverse scan
  26432. for (var _giveUpAt = i1 - 2;;) {
  26433. if (t0 === undefined) {
  26434. // before start
  26435. this._cachedIndex = 0;
  26436. return this.beforeStart_(0, t, t1);
  26437. }
  26438. if (i1 === _giveUpAt) break; // this loop
  26439. t1 = t0;
  26440. t0 = pp[--i1 - 1];
  26441. if (t >= t0) {
  26442. // we have arrived at the sought interval
  26443. break seek;
  26444. }
  26445. } // prepare binary search on the left side of the index
  26446. right = i1;
  26447. i1 = 0;
  26448. break linear_scan;
  26449. } // the interval is valid
  26450. break validate_interval;
  26451. } // linear scan
  26452. // binary search
  26453. while (i1 < right) {
  26454. var mid = i1 + right >>> 1;
  26455. if (t < pp[mid]) {
  26456. right = mid;
  26457. } else {
  26458. i1 = mid + 1;
  26459. }
  26460. }
  26461. t1 = pp[i1];
  26462. t0 = pp[i1 - 1]; // check boundary cases, again
  26463. if (t0 === undefined) {
  26464. this._cachedIndex = 0;
  26465. return this.beforeStart_(0, t, t1);
  26466. }
  26467. if (t1 === undefined) {
  26468. i1 = pp.length;
  26469. this._cachedIndex = i1;
  26470. return this.afterEnd_(i1 - 1, t0, t);
  26471. }
  26472. } // seek
  26473. this._cachedIndex = i1;
  26474. this.intervalChanged_(i1, t0, t1);
  26475. } // validate_interval
  26476. return this.interpolate_(i1, t0, t, t1);
  26477. },
  26478. settings: null,
  26479. // optional, subclass-specific settings structure
  26480. // Note: The indirection allows central control of many interpolants.
  26481. // --- Protected interface
  26482. DefaultSettings_: {},
  26483. getSettings_: function getSettings_() {
  26484. return this.settings || this.DefaultSettings_;
  26485. },
  26486. copySampleValue_: function copySampleValue_(index) {
  26487. // copies a sample value to the result buffer
  26488. var result = this.resultBuffer,
  26489. values = this.sampleValues,
  26490. stride = this.valueSize,
  26491. offset = index * stride;
  26492. for (var i = 0; i !== stride; ++i) {
  26493. result[i] = values[offset + i];
  26494. }
  26495. return result;
  26496. },
  26497. // Template methods for derived classes:
  26498. interpolate_: function interpolate_()
  26499. /* i1, t0, t, t1 */
  26500. {
  26501. throw new Error('call to abstract method'); // implementations shall return this.resultBuffer
  26502. },
  26503. intervalChanged_: function intervalChanged_()
  26504. /* i1, t0, t1 */
  26505. {// empty
  26506. }
  26507. }); // DECLARE ALIAS AFTER assign prototype
  26508. Object.assign(Interpolant.prototype, {
  26509. //( 0, t, t0 ), returns this.resultBuffer
  26510. beforeStart_: Interpolant.prototype.copySampleValue_,
  26511. //( N-1, tN-1, t ), returns this.resultBuffer
  26512. afterEnd_: Interpolant.prototype.copySampleValue_
  26513. });
  26514. /**
  26515. * Fast and simple cubic spline interpolant.
  26516. *
  26517. * It was derived from a Hermitian construction setting the first derivative
  26518. * at each sample position to the linear slope between neighboring positions
  26519. * over their parameter interval.
  26520. */
  26521. function CubicInterpolant(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  26522. Interpolant.call(this, parameterPositions, sampleValues, sampleSize, resultBuffer);
  26523. this._weightPrev = -0;
  26524. this._offsetPrev = -0;
  26525. this._weightNext = -0;
  26526. this._offsetNext = -0;
  26527. }
  26528. CubicInterpolant.prototype = Object.assign(Object.create(Interpolant.prototype), {
  26529. constructor: CubicInterpolant,
  26530. DefaultSettings_: {
  26531. endingStart: ZeroCurvatureEnding,
  26532. endingEnd: ZeroCurvatureEnding
  26533. },
  26534. intervalChanged_: function intervalChanged_(i1, t0, t1) {
  26535. var pp = this.parameterPositions;
  26536. var iPrev = i1 - 2,
  26537. iNext = i1 + 1,
  26538. tPrev = pp[iPrev],
  26539. tNext = pp[iNext];
  26540. if (tPrev === undefined) {
  26541. switch (this.getSettings_().endingStart) {
  26542. case ZeroSlopeEnding:
  26543. // f'(t0) = 0
  26544. iPrev = i1;
  26545. tPrev = 2 * t0 - t1;
  26546. break;
  26547. case WrapAroundEnding:
  26548. // use the other end of the curve
  26549. iPrev = pp.length - 2;
  26550. tPrev = t0 + pp[iPrev] - pp[iPrev + 1];
  26551. break;
  26552. default:
  26553. // ZeroCurvatureEnding
  26554. // f''(t0) = 0 a.k.a. Natural Spline
  26555. iPrev = i1;
  26556. tPrev = t1;
  26557. }
  26558. }
  26559. if (tNext === undefined) {
  26560. switch (this.getSettings_().endingEnd) {
  26561. case ZeroSlopeEnding:
  26562. // f'(tN) = 0
  26563. iNext = i1;
  26564. tNext = 2 * t1 - t0;
  26565. break;
  26566. case WrapAroundEnding:
  26567. // use the other end of the curve
  26568. iNext = 1;
  26569. tNext = t1 + pp[1] - pp[0];
  26570. break;
  26571. default:
  26572. // ZeroCurvatureEnding
  26573. // f''(tN) = 0, a.k.a. Natural Spline
  26574. iNext = i1 - 1;
  26575. tNext = t0;
  26576. }
  26577. }
  26578. var halfDt = (t1 - t0) * 0.5,
  26579. stride = this.valueSize;
  26580. this._weightPrev = halfDt / (t0 - tPrev);
  26581. this._weightNext = halfDt / (tNext - t1);
  26582. this._offsetPrev = iPrev * stride;
  26583. this._offsetNext = iNext * stride;
  26584. },
  26585. interpolate_: function interpolate_(i1, t0, t, t1) {
  26586. var result = this.resultBuffer,
  26587. values = this.sampleValues,
  26588. stride = this.valueSize,
  26589. o1 = i1 * stride,
  26590. o0 = o1 - stride,
  26591. oP = this._offsetPrev,
  26592. oN = this._offsetNext,
  26593. wP = this._weightPrev,
  26594. wN = this._weightNext,
  26595. p = (t - t0) / (t1 - t0),
  26596. pp = p * p,
  26597. ppp = pp * p; // evaluate polynomials
  26598. var sP = -wP * ppp + 2 * wP * pp - wP * p;
  26599. var s0 = (1 + wP) * ppp + (-1.5 - 2 * wP) * pp + (-0.5 + wP) * p + 1;
  26600. var s1 = (-1 - wN) * ppp + (1.5 + wN) * pp + 0.5 * p;
  26601. var sN = wN * ppp - wN * pp; // combine data linearly
  26602. for (var i = 0; i !== stride; ++i) {
  26603. result[i] = sP * values[oP + i] + s0 * values[o0 + i] + s1 * values[o1 + i] + sN * values[oN + i];
  26604. }
  26605. return result;
  26606. }
  26607. });
  26608. function LinearInterpolant(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  26609. Interpolant.call(this, parameterPositions, sampleValues, sampleSize, resultBuffer);
  26610. }
  26611. LinearInterpolant.prototype = Object.assign(Object.create(Interpolant.prototype), {
  26612. constructor: LinearInterpolant,
  26613. interpolate_: function interpolate_(i1, t0, t, t1) {
  26614. var result = this.resultBuffer,
  26615. values = this.sampleValues,
  26616. stride = this.valueSize,
  26617. offset1 = i1 * stride,
  26618. offset0 = offset1 - stride,
  26619. weight1 = (t - t0) / (t1 - t0),
  26620. weight0 = 1 - weight1;
  26621. for (var i = 0; i !== stride; ++i) {
  26622. result[i] = values[offset0 + i] * weight0 + values[offset1 + i] * weight1;
  26623. }
  26624. return result;
  26625. }
  26626. });
  26627. /**
  26628. *
  26629. * Interpolant that evaluates to the sample value at the position preceeding
  26630. * the parameter.
  26631. */
  26632. function DiscreteInterpolant(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  26633. Interpolant.call(this, parameterPositions, sampleValues, sampleSize, resultBuffer);
  26634. }
  26635. DiscreteInterpolant.prototype = Object.assign(Object.create(Interpolant.prototype), {
  26636. constructor: DiscreteInterpolant,
  26637. interpolate_: function interpolate_(i1
  26638. /*, t0, t, t1 */
  26639. ) {
  26640. return this.copySampleValue_(i1 - 1);
  26641. }
  26642. });
  26643. function KeyframeTrack(name, times, values, interpolation) {
  26644. if (name === undefined) throw new Error('THREE.KeyframeTrack: track name is undefined');
  26645. if (times === undefined || times.length === 0) throw new Error('THREE.KeyframeTrack: no keyframes in track named ' + name);
  26646. this.name = name;
  26647. this.times = AnimationUtils.convertArray(times, this.TimeBufferType);
  26648. this.values = AnimationUtils.convertArray(values, this.ValueBufferType);
  26649. this.setInterpolation(interpolation || this.DefaultInterpolation);
  26650. } // Static methods
  26651. Object.assign(KeyframeTrack, {
  26652. // Serialization (in static context, because of constructor invocation
  26653. // and automatic invocation of .toJSON):
  26654. toJSON: function toJSON(track) {
  26655. var trackType = track.constructor;
  26656. var json; // derived classes can define a static toJSON method
  26657. if (trackType.toJSON !== undefined) {
  26658. json = trackType.toJSON(track);
  26659. } else {
  26660. // by default, we assume the data can be serialized as-is
  26661. json = {
  26662. 'name': track.name,
  26663. 'times': AnimationUtils.convertArray(track.times, Array),
  26664. 'values': AnimationUtils.convertArray(track.values, Array)
  26665. };
  26666. var interpolation = track.getInterpolation();
  26667. if (interpolation !== track.DefaultInterpolation) {
  26668. json.interpolation = interpolation;
  26669. }
  26670. }
  26671. json.type = track.ValueTypeName; // mandatory
  26672. return json;
  26673. }
  26674. });
  26675. Object.assign(KeyframeTrack.prototype, {
  26676. constructor: KeyframeTrack,
  26677. TimeBufferType: Float32Array,
  26678. ValueBufferType: Float32Array,
  26679. DefaultInterpolation: InterpolateLinear,
  26680. InterpolantFactoryMethodDiscrete: function InterpolantFactoryMethodDiscrete(result) {
  26681. return new DiscreteInterpolant(this.times, this.values, this.getValueSize(), result);
  26682. },
  26683. InterpolantFactoryMethodLinear: function InterpolantFactoryMethodLinear(result) {
  26684. return new LinearInterpolant(this.times, this.values, this.getValueSize(), result);
  26685. },
  26686. InterpolantFactoryMethodSmooth: function InterpolantFactoryMethodSmooth(result) {
  26687. return new CubicInterpolant(this.times, this.values, this.getValueSize(), result);
  26688. },
  26689. setInterpolation: function setInterpolation(interpolation) {
  26690. var factoryMethod;
  26691. switch (interpolation) {
  26692. case InterpolateDiscrete:
  26693. factoryMethod = this.InterpolantFactoryMethodDiscrete;
  26694. break;
  26695. case InterpolateLinear:
  26696. factoryMethod = this.InterpolantFactoryMethodLinear;
  26697. break;
  26698. case InterpolateSmooth:
  26699. factoryMethod = this.InterpolantFactoryMethodSmooth;
  26700. break;
  26701. }
  26702. if (factoryMethod === undefined) {
  26703. var message = 'unsupported interpolation for ' + this.ValueTypeName + ' keyframe track named ' + this.name;
  26704. if (this.createInterpolant === undefined) {
  26705. // fall back to default, unless the default itself is messed up
  26706. if (interpolation !== this.DefaultInterpolation) {
  26707. this.setInterpolation(this.DefaultInterpolation);
  26708. } else {
  26709. throw new Error(message); // fatal, in this case
  26710. }
  26711. }
  26712. console.warn('THREE.KeyframeTrack:', message);
  26713. return this;
  26714. }
  26715. this.createInterpolant = factoryMethod;
  26716. return this;
  26717. },
  26718. getInterpolation: function getInterpolation() {
  26719. switch (this.createInterpolant) {
  26720. case this.InterpolantFactoryMethodDiscrete:
  26721. return InterpolateDiscrete;
  26722. case this.InterpolantFactoryMethodLinear:
  26723. return InterpolateLinear;
  26724. case this.InterpolantFactoryMethodSmooth:
  26725. return InterpolateSmooth;
  26726. }
  26727. },
  26728. getValueSize: function getValueSize() {
  26729. return this.values.length / this.times.length;
  26730. },
  26731. // move all keyframes either forwards or backwards in time
  26732. shift: function shift(timeOffset) {
  26733. if (timeOffset !== 0.0) {
  26734. var times = this.times;
  26735. for (var i = 0, n = times.length; i !== n; ++i) {
  26736. times[i] += timeOffset;
  26737. }
  26738. }
  26739. return this;
  26740. },
  26741. // scale all keyframe times by a factor (useful for frame <-> seconds conversions)
  26742. scale: function scale(timeScale) {
  26743. if (timeScale !== 1.0) {
  26744. var times = this.times;
  26745. for (var i = 0, n = times.length; i !== n; ++i) {
  26746. times[i] *= timeScale;
  26747. }
  26748. }
  26749. return this;
  26750. },
  26751. // removes keyframes before and after animation without changing any values within the range [startTime, endTime].
  26752. // IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values
  26753. trim: function trim(startTime, endTime) {
  26754. var times = this.times,
  26755. nKeys = times.length;
  26756. var from = 0,
  26757. to = nKeys - 1;
  26758. while (from !== nKeys && times[from] < startTime) {
  26759. ++from;
  26760. }
  26761. while (to !== -1 && times[to] > endTime) {
  26762. --to;
  26763. }
  26764. ++to; // inclusive -> exclusive bound
  26765. if (from !== 0 || to !== nKeys) {
  26766. // empty tracks are forbidden, so keep at least one keyframe
  26767. if (from >= to) {
  26768. to = Math.max(to, 1);
  26769. from = to - 1;
  26770. }
  26771. var stride = this.getValueSize();
  26772. this.times = AnimationUtils.arraySlice(times, from, to);
  26773. this.values = AnimationUtils.arraySlice(this.values, from * stride, to * stride);
  26774. }
  26775. return this;
  26776. },
  26777. // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable
  26778. validate: function validate() {
  26779. var valid = true;
  26780. var valueSize = this.getValueSize();
  26781. if (valueSize - Math.floor(valueSize) !== 0) {
  26782. console.error('THREE.KeyframeTrack: Invalid value size in track.', this);
  26783. valid = false;
  26784. }
  26785. var times = this.times,
  26786. values = this.values,
  26787. nKeys = times.length;
  26788. if (nKeys === 0) {
  26789. console.error('THREE.KeyframeTrack: Track is empty.', this);
  26790. valid = false;
  26791. }
  26792. var prevTime = null;
  26793. for (var i = 0; i !== nKeys; i++) {
  26794. var currTime = times[i];
  26795. if (typeof currTime === 'number' && isNaN(currTime)) {
  26796. console.error('THREE.KeyframeTrack: Time is not a valid number.', this, i, currTime);
  26797. valid = false;
  26798. break;
  26799. }
  26800. if (prevTime !== null && prevTime > currTime) {
  26801. console.error('THREE.KeyframeTrack: Out of order keys.', this, i, currTime, prevTime);
  26802. valid = false;
  26803. break;
  26804. }
  26805. prevTime = currTime;
  26806. }
  26807. if (values !== undefined) {
  26808. if (AnimationUtils.isTypedArray(values)) {
  26809. for (var _i = 0, n = values.length; _i !== n; ++_i) {
  26810. var value = values[_i];
  26811. if (isNaN(value)) {
  26812. console.error('THREE.KeyframeTrack: Value is not a valid number.', this, _i, value);
  26813. valid = false;
  26814. break;
  26815. }
  26816. }
  26817. }
  26818. }
  26819. return valid;
  26820. },
  26821. // removes equivalent sequential keys as common in morph target sequences
  26822. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  26823. optimize: function optimize() {
  26824. // times or values may be shared with other tracks, so overwriting is unsafe
  26825. var times = AnimationUtils.arraySlice(this.times),
  26826. values = AnimationUtils.arraySlice(this.values),
  26827. stride = this.getValueSize(),
  26828. smoothInterpolation = this.getInterpolation() === InterpolateSmooth,
  26829. lastIndex = times.length - 1;
  26830. var writeIndex = 1;
  26831. for (var i = 1; i < lastIndex; ++i) {
  26832. var keep = false;
  26833. var time = times[i];
  26834. var timeNext = times[i + 1]; // remove adjacent keyframes scheduled at the same time
  26835. if (time !== timeNext && (i !== 1 || time !== times[0])) {
  26836. if (!smoothInterpolation) {
  26837. // remove unnecessary keyframes same as their neighbors
  26838. var offset = i * stride,
  26839. offsetP = offset - stride,
  26840. offsetN = offset + stride;
  26841. for (var j = 0; j !== stride; ++j) {
  26842. var value = values[offset + j];
  26843. if (value !== values[offsetP + j] || value !== values[offsetN + j]) {
  26844. keep = true;
  26845. break;
  26846. }
  26847. }
  26848. } else {
  26849. keep = true;
  26850. }
  26851. } // in-place compaction
  26852. if (keep) {
  26853. if (i !== writeIndex) {
  26854. times[writeIndex] = times[i];
  26855. var readOffset = i * stride,
  26856. writeOffset = writeIndex * stride;
  26857. for (var _j = 0; _j !== stride; ++_j) {
  26858. values[writeOffset + _j] = values[readOffset + _j];
  26859. }
  26860. }
  26861. ++writeIndex;
  26862. }
  26863. } // flush last keyframe (compaction looks ahead)
  26864. if (lastIndex > 0) {
  26865. times[writeIndex] = times[lastIndex];
  26866. for (var _readOffset = lastIndex * stride, _writeOffset = writeIndex * stride, _j2 = 0; _j2 !== stride; ++_j2) {
  26867. values[_writeOffset + _j2] = values[_readOffset + _j2];
  26868. }
  26869. ++writeIndex;
  26870. }
  26871. if (writeIndex !== times.length) {
  26872. this.times = AnimationUtils.arraySlice(times, 0, writeIndex);
  26873. this.values = AnimationUtils.arraySlice(values, 0, writeIndex * stride);
  26874. } else {
  26875. this.times = times;
  26876. this.values = values;
  26877. }
  26878. return this;
  26879. },
  26880. clone: function clone() {
  26881. var times = AnimationUtils.arraySlice(this.times, 0);
  26882. var values = AnimationUtils.arraySlice(this.values, 0);
  26883. var TypedKeyframeTrack = this.constructor;
  26884. var track = new TypedKeyframeTrack(this.name, times, values); // Interpolant argument to constructor is not saved, so copy the factory method directly.
  26885. track.createInterpolant = this.createInterpolant;
  26886. return track;
  26887. }
  26888. });
  26889. /**
  26890. * A Track of Boolean keyframe values.
  26891. */
  26892. function BooleanKeyframeTrack(name, times, values) {
  26893. KeyframeTrack.call(this, name, times, values);
  26894. }
  26895. BooleanKeyframeTrack.prototype = Object.assign(Object.create(KeyframeTrack.prototype), {
  26896. constructor: BooleanKeyframeTrack,
  26897. ValueTypeName: 'bool',
  26898. ValueBufferType: Array,
  26899. DefaultInterpolation: InterpolateDiscrete,
  26900. InterpolantFactoryMethodLinear: undefined,
  26901. InterpolantFactoryMethodSmooth: undefined // Note: Actually this track could have a optimized / compressed
  26902. // representation of a single value and a custom interpolant that
  26903. // computes "firstValue ^ isOdd( index )".
  26904. });
  26905. /**
  26906. * A Track of keyframe values that represent color.
  26907. */
  26908. function ColorKeyframeTrack(name, times, values, interpolation) {
  26909. KeyframeTrack.call(this, name, times, values, interpolation);
  26910. }
  26911. ColorKeyframeTrack.prototype = Object.assign(Object.create(KeyframeTrack.prototype), {
  26912. constructor: ColorKeyframeTrack,
  26913. ValueTypeName: 'color' // ValueBufferType is inherited
  26914. // DefaultInterpolation is inherited
  26915. // Note: Very basic implementation and nothing special yet.
  26916. // However, this is the place for color space parameterization.
  26917. });
  26918. /**
  26919. * A Track of numeric keyframe values.
  26920. */
  26921. function NumberKeyframeTrack(name, times, values, interpolation) {
  26922. KeyframeTrack.call(this, name, times, values, interpolation);
  26923. }
  26924. NumberKeyframeTrack.prototype = Object.assign(Object.create(KeyframeTrack.prototype), {
  26925. constructor: NumberKeyframeTrack,
  26926. ValueTypeName: 'number' // ValueBufferType is inherited
  26927. // DefaultInterpolation is inherited
  26928. });
  26929. /**
  26930. * Spherical linear unit quaternion interpolant.
  26931. */
  26932. function QuaternionLinearInterpolant(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  26933. Interpolant.call(this, parameterPositions, sampleValues, sampleSize, resultBuffer);
  26934. }
  26935. QuaternionLinearInterpolant.prototype = Object.assign(Object.create(Interpolant.prototype), {
  26936. constructor: QuaternionLinearInterpolant,
  26937. interpolate_: function interpolate_(i1, t0, t, t1) {
  26938. var result = this.resultBuffer,
  26939. values = this.sampleValues,
  26940. stride = this.valueSize,
  26941. alpha = (t - t0) / (t1 - t0);
  26942. var offset = i1 * stride;
  26943. for (var end = offset + stride; offset !== end; offset += 4) {
  26944. Quaternion.slerpFlat(result, 0, values, offset - stride, values, offset, alpha);
  26945. }
  26946. return result;
  26947. }
  26948. });
  26949. /**
  26950. * A Track of quaternion keyframe values.
  26951. */
  26952. function QuaternionKeyframeTrack(name, times, values, interpolation) {
  26953. KeyframeTrack.call(this, name, times, values, interpolation);
  26954. }
  26955. QuaternionKeyframeTrack.prototype = Object.assign(Object.create(KeyframeTrack.prototype), {
  26956. constructor: QuaternionKeyframeTrack,
  26957. ValueTypeName: 'quaternion',
  26958. // ValueBufferType is inherited
  26959. DefaultInterpolation: InterpolateLinear,
  26960. InterpolantFactoryMethodLinear: function InterpolantFactoryMethodLinear(result) {
  26961. return new QuaternionLinearInterpolant(this.times, this.values, this.getValueSize(), result);
  26962. },
  26963. InterpolantFactoryMethodSmooth: undefined // not yet implemented
  26964. });
  26965. /**
  26966. * A Track that interpolates Strings
  26967. */
  26968. function StringKeyframeTrack(name, times, values, interpolation) {
  26969. KeyframeTrack.call(this, name, times, values, interpolation);
  26970. }
  26971. StringKeyframeTrack.prototype = Object.assign(Object.create(KeyframeTrack.prototype), {
  26972. constructor: StringKeyframeTrack,
  26973. ValueTypeName: 'string',
  26974. ValueBufferType: Array,
  26975. DefaultInterpolation: InterpolateDiscrete,
  26976. InterpolantFactoryMethodLinear: undefined,
  26977. InterpolantFactoryMethodSmooth: undefined
  26978. });
  26979. /**
  26980. * A Track of vectored keyframe values.
  26981. */
  26982. function VectorKeyframeTrack(name, times, values, interpolation) {
  26983. KeyframeTrack.call(this, name, times, values, interpolation);
  26984. }
  26985. VectorKeyframeTrack.prototype = Object.assign(Object.create(KeyframeTrack.prototype), {
  26986. constructor: VectorKeyframeTrack,
  26987. ValueTypeName: 'vector' // ValueBufferType is inherited
  26988. // DefaultInterpolation is inherited
  26989. });
  26990. function AnimationClip(name, duration, tracks, blendMode) {
  26991. if (duration === void 0) {
  26992. duration = -1;
  26993. }
  26994. if (blendMode === void 0) {
  26995. blendMode = NormalAnimationBlendMode;
  26996. }
  26997. this.name = name;
  26998. this.tracks = tracks;
  26999. this.duration = duration;
  27000. this.blendMode = blendMode;
  27001. this.uuid = MathUtils.generateUUID(); // this means it should figure out its duration by scanning the tracks
  27002. if (this.duration < 0) {
  27003. this.resetDuration();
  27004. }
  27005. }
  27006. function getTrackTypeForValueTypeName(typeName) {
  27007. switch (typeName.toLowerCase()) {
  27008. case 'scalar':
  27009. case 'double':
  27010. case 'float':
  27011. case 'number':
  27012. case 'integer':
  27013. return NumberKeyframeTrack;
  27014. case 'vector':
  27015. case 'vector2':
  27016. case 'vector3':
  27017. case 'vector4':
  27018. return VectorKeyframeTrack;
  27019. case 'color':
  27020. return ColorKeyframeTrack;
  27021. case 'quaternion':
  27022. return QuaternionKeyframeTrack;
  27023. case 'bool':
  27024. case 'boolean':
  27025. return BooleanKeyframeTrack;
  27026. case 'string':
  27027. return StringKeyframeTrack;
  27028. }
  27029. throw new Error('THREE.KeyframeTrack: Unsupported typeName: ' + typeName);
  27030. }
  27031. function parseKeyframeTrack(json) {
  27032. if (json.type === undefined) {
  27033. throw new Error('THREE.KeyframeTrack: track type undefined, can not parse');
  27034. }
  27035. var trackType = getTrackTypeForValueTypeName(json.type);
  27036. if (json.times === undefined) {
  27037. var times = [],
  27038. values = [];
  27039. AnimationUtils.flattenJSON(json.keys, times, values, 'value');
  27040. json.times = times;
  27041. json.values = values;
  27042. } // derived classes can define a static parse method
  27043. if (trackType.parse !== undefined) {
  27044. return trackType.parse(json);
  27045. } else {
  27046. // by default, we assume a constructor compatible with the base
  27047. return new trackType(json.name, json.times, json.values, json.interpolation);
  27048. }
  27049. }
  27050. Object.assign(AnimationClip, {
  27051. parse: function parse(json) {
  27052. var tracks = [],
  27053. jsonTracks = json.tracks,
  27054. frameTime = 1.0 / (json.fps || 1.0);
  27055. for (var i = 0, n = jsonTracks.length; i !== n; ++i) {
  27056. tracks.push(parseKeyframeTrack(jsonTracks[i]).scale(frameTime));
  27057. }
  27058. var clip = new AnimationClip(json.name, json.duration, tracks, json.blendMode);
  27059. clip.uuid = json.uuid;
  27060. return clip;
  27061. },
  27062. toJSON: function toJSON(clip) {
  27063. var tracks = [],
  27064. clipTracks = clip.tracks;
  27065. var json = {
  27066. 'name': clip.name,
  27067. 'duration': clip.duration,
  27068. 'tracks': tracks,
  27069. 'uuid': clip.uuid,
  27070. 'blendMode': clip.blendMode
  27071. };
  27072. for (var i = 0, n = clipTracks.length; i !== n; ++i) {
  27073. tracks.push(KeyframeTrack.toJSON(clipTracks[i]));
  27074. }
  27075. return json;
  27076. },
  27077. CreateFromMorphTargetSequence: function CreateFromMorphTargetSequence(name, morphTargetSequence, fps, noLoop) {
  27078. var numMorphTargets = morphTargetSequence.length;
  27079. var tracks = [];
  27080. for (var i = 0; i < numMorphTargets; i++) {
  27081. var times = [];
  27082. var values = [];
  27083. times.push((i + numMorphTargets - 1) % numMorphTargets, i, (i + 1) % numMorphTargets);
  27084. values.push(0, 1, 0);
  27085. var order = AnimationUtils.getKeyframeOrder(times);
  27086. times = AnimationUtils.sortedArray(times, 1, order);
  27087. values = AnimationUtils.sortedArray(values, 1, order); // if there is a key at the first frame, duplicate it as the
  27088. // last frame as well for perfect loop.
  27089. if (!noLoop && times[0] === 0) {
  27090. times.push(numMorphTargets);
  27091. values.push(values[0]);
  27092. }
  27093. tracks.push(new NumberKeyframeTrack('.morphTargetInfluences[' + morphTargetSequence[i].name + ']', times, values).scale(1.0 / fps));
  27094. }
  27095. return new AnimationClip(name, -1, tracks);
  27096. },
  27097. findByName: function findByName(objectOrClipArray, name) {
  27098. var clipArray = objectOrClipArray;
  27099. if (!Array.isArray(objectOrClipArray)) {
  27100. var o = objectOrClipArray;
  27101. clipArray = o.geometry && o.geometry.animations || o.animations;
  27102. }
  27103. for (var i = 0; i < clipArray.length; i++) {
  27104. if (clipArray[i].name === name) {
  27105. return clipArray[i];
  27106. }
  27107. }
  27108. return null;
  27109. },
  27110. CreateClipsFromMorphTargetSequences: function CreateClipsFromMorphTargetSequences(morphTargets, fps, noLoop) {
  27111. var animationToMorphTargets = {}; // tested with https://regex101.com/ on trick sequences
  27112. // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  27113. var pattern = /^([\w-]*?)([\d]+)$/; // sort morph target names into animation groups based
  27114. // patterns like Walk_001, Walk_002, Run_001, Run_002
  27115. for (var i = 0, il = morphTargets.length; i < il; i++) {
  27116. var morphTarget = morphTargets[i];
  27117. var parts = morphTarget.name.match(pattern);
  27118. if (parts && parts.length > 1) {
  27119. var name = parts[1];
  27120. var animationMorphTargets = animationToMorphTargets[name];
  27121. if (!animationMorphTargets) {
  27122. animationToMorphTargets[name] = animationMorphTargets = [];
  27123. }
  27124. animationMorphTargets.push(morphTarget);
  27125. }
  27126. }
  27127. var clips = [];
  27128. for (var _name in animationToMorphTargets) {
  27129. clips.push(AnimationClip.CreateFromMorphTargetSequence(_name, animationToMorphTargets[_name], fps, noLoop));
  27130. }
  27131. return clips;
  27132. },
  27133. // parse the animation.hierarchy format
  27134. parseAnimation: function parseAnimation(animation, bones) {
  27135. if (!animation) {
  27136. console.error('THREE.AnimationClip: No animation in JSONLoader data.');
  27137. return null;
  27138. }
  27139. var addNonemptyTrack = function addNonemptyTrack(trackType, trackName, animationKeys, propertyName, destTracks) {
  27140. // only return track if there are actually keys.
  27141. if (animationKeys.length !== 0) {
  27142. var times = [];
  27143. var values = [];
  27144. AnimationUtils.flattenJSON(animationKeys, times, values, propertyName); // empty keys are filtered out, so check again
  27145. if (times.length !== 0) {
  27146. destTracks.push(new trackType(trackName, times, values));
  27147. }
  27148. }
  27149. };
  27150. var tracks = [];
  27151. var clipName = animation.name || 'default';
  27152. var fps = animation.fps || 30;
  27153. var blendMode = animation.blendMode; // automatic length determination in AnimationClip.
  27154. var duration = animation.length || -1;
  27155. var hierarchyTracks = animation.hierarchy || [];
  27156. for (var h = 0; h < hierarchyTracks.length; h++) {
  27157. var animationKeys = hierarchyTracks[h].keys; // skip empty tracks
  27158. if (!animationKeys || animationKeys.length === 0) continue; // process morph targets
  27159. if (animationKeys[0].morphTargets) {
  27160. // figure out all morph targets used in this track
  27161. var morphTargetNames = {};
  27162. var k = void 0;
  27163. for (k = 0; k < animationKeys.length; k++) {
  27164. if (animationKeys[k].morphTargets) {
  27165. for (var m = 0; m < animationKeys[k].morphTargets.length; m++) {
  27166. morphTargetNames[animationKeys[k].morphTargets[m]] = -1;
  27167. }
  27168. }
  27169. } // create a track for each morph target with all zero
  27170. // morphTargetInfluences except for the keys in which
  27171. // the morphTarget is named.
  27172. for (var morphTargetName in morphTargetNames) {
  27173. var times = [];
  27174. var values = [];
  27175. for (var _m = 0; _m !== animationKeys[k].morphTargets.length; ++_m) {
  27176. var animationKey = animationKeys[k];
  27177. times.push(animationKey.time);
  27178. values.push(animationKey.morphTarget === morphTargetName ? 1 : 0);
  27179. }
  27180. tracks.push(new NumberKeyframeTrack('.morphTargetInfluence[' + morphTargetName + ']', times, values));
  27181. }
  27182. duration = morphTargetNames.length * (fps || 1.0);
  27183. } else {
  27184. // ...assume skeletal animation
  27185. var boneName = '.bones[' + bones[h].name + ']';
  27186. addNonemptyTrack(VectorKeyframeTrack, boneName + '.position', animationKeys, 'pos', tracks);
  27187. addNonemptyTrack(QuaternionKeyframeTrack, boneName + '.quaternion', animationKeys, 'rot', tracks);
  27188. addNonemptyTrack(VectorKeyframeTrack, boneName + '.scale', animationKeys, 'scl', tracks);
  27189. }
  27190. }
  27191. if (tracks.length === 0) {
  27192. return null;
  27193. }
  27194. var clip = new AnimationClip(clipName, duration, tracks, blendMode);
  27195. return clip;
  27196. }
  27197. });
  27198. Object.assign(AnimationClip.prototype, {
  27199. resetDuration: function resetDuration() {
  27200. var tracks = this.tracks;
  27201. var duration = 0;
  27202. for (var i = 0, n = tracks.length; i !== n; ++i) {
  27203. var track = this.tracks[i];
  27204. duration = Math.max(duration, track.times[track.times.length - 1]);
  27205. }
  27206. this.duration = duration;
  27207. return this;
  27208. },
  27209. trim: function trim() {
  27210. for (var i = 0; i < this.tracks.length; i++) {
  27211. this.tracks[i].trim(0, this.duration);
  27212. }
  27213. return this;
  27214. },
  27215. validate: function validate() {
  27216. var valid = true;
  27217. for (var i = 0; i < this.tracks.length; i++) {
  27218. valid = valid && this.tracks[i].validate();
  27219. }
  27220. return valid;
  27221. },
  27222. optimize: function optimize() {
  27223. for (var i = 0; i < this.tracks.length; i++) {
  27224. this.tracks[i].optimize();
  27225. }
  27226. return this;
  27227. },
  27228. clone: function clone() {
  27229. var tracks = [];
  27230. for (var i = 0; i < this.tracks.length; i++) {
  27231. tracks.push(this.tracks[i].clone());
  27232. }
  27233. return new AnimationClip(this.name, this.duration, tracks, this.blendMode);
  27234. },
  27235. toJSON: function toJSON() {
  27236. return AnimationClip.toJSON(this);
  27237. }
  27238. });
  27239. var Cache = {
  27240. enabled: false,
  27241. files: {},
  27242. add: function add(key, file) {
  27243. if (this.enabled === false) return; // console.log( 'THREE.Cache', 'Adding key:', key );
  27244. this.files[key] = file;
  27245. },
  27246. get: function get(key) {
  27247. if (this.enabled === false) return; // console.log( 'THREE.Cache', 'Checking key:', key );
  27248. return this.files[key];
  27249. },
  27250. remove: function remove(key) {
  27251. delete this.files[key];
  27252. },
  27253. clear: function clear() {
  27254. this.files = {};
  27255. }
  27256. };
  27257. function LoadingManager(onLoad, onProgress, onError) {
  27258. var scope = this;
  27259. var isLoading = false;
  27260. var itemsLoaded = 0;
  27261. var itemsTotal = 0;
  27262. var urlModifier = undefined;
  27263. var handlers = []; // Refer to #5689 for the reason why we don't set .onStart
  27264. // in the constructor
  27265. this.onStart = undefined;
  27266. this.onLoad = onLoad;
  27267. this.onProgress = onProgress;
  27268. this.onError = onError;
  27269. this.itemStart = function (url) {
  27270. itemsTotal++;
  27271. if (isLoading === false) {
  27272. if (scope.onStart !== undefined) {
  27273. scope.onStart(url, itemsLoaded, itemsTotal);
  27274. }
  27275. }
  27276. isLoading = true;
  27277. };
  27278. this.itemEnd = function (url) {
  27279. itemsLoaded++;
  27280. if (scope.onProgress !== undefined) {
  27281. scope.onProgress(url, itemsLoaded, itemsTotal);
  27282. }
  27283. if (itemsLoaded === itemsTotal) {
  27284. isLoading = false;
  27285. if (scope.onLoad !== undefined) {
  27286. scope.onLoad();
  27287. }
  27288. }
  27289. };
  27290. this.itemError = function (url) {
  27291. if (scope.onError !== undefined) {
  27292. scope.onError(url);
  27293. }
  27294. };
  27295. this.resolveURL = function (url) {
  27296. if (urlModifier) {
  27297. return urlModifier(url);
  27298. }
  27299. return url;
  27300. };
  27301. this.setURLModifier = function (transform) {
  27302. urlModifier = transform;
  27303. return this;
  27304. };
  27305. this.addHandler = function (regex, loader) {
  27306. handlers.push(regex, loader);
  27307. return this;
  27308. };
  27309. this.removeHandler = function (regex) {
  27310. var index = handlers.indexOf(regex);
  27311. if (index !== -1) {
  27312. handlers.splice(index, 2);
  27313. }
  27314. return this;
  27315. };
  27316. this.getHandler = function (file) {
  27317. for (var i = 0, l = handlers.length; i < l; i += 2) {
  27318. var regex = handlers[i];
  27319. var loader = handlers[i + 1];
  27320. if (regex.global) regex.lastIndex = 0; // see #17920
  27321. if (regex.test(file)) {
  27322. return loader;
  27323. }
  27324. }
  27325. return null;
  27326. };
  27327. }
  27328. var DefaultLoadingManager = new LoadingManager();
  27329. function Loader(manager) {
  27330. this.manager = manager !== undefined ? manager : DefaultLoadingManager;
  27331. this.crossOrigin = 'anonymous';
  27332. this.withCredentials = false;
  27333. this.path = '';
  27334. this.resourcePath = '';
  27335. this.requestHeader = {};
  27336. }
  27337. Object.assign(Loader.prototype, {
  27338. load: function load()
  27339. /* url, onLoad, onProgress, onError */
  27340. {},
  27341. loadAsync: function loadAsync(url, onProgress) {
  27342. var scope = this;
  27343. return new Promise(function (resolve, reject) {
  27344. scope.load(url, resolve, onProgress, reject);
  27345. });
  27346. },
  27347. parse: function parse()
  27348. /* data */
  27349. {},
  27350. setCrossOrigin: function setCrossOrigin(crossOrigin) {
  27351. this.crossOrigin = crossOrigin;
  27352. return this;
  27353. },
  27354. setWithCredentials: function setWithCredentials(value) {
  27355. this.withCredentials = value;
  27356. return this;
  27357. },
  27358. setPath: function setPath(path) {
  27359. this.path = path;
  27360. return this;
  27361. },
  27362. setResourcePath: function setResourcePath(resourcePath) {
  27363. this.resourcePath = resourcePath;
  27364. return this;
  27365. },
  27366. setRequestHeader: function setRequestHeader(requestHeader) {
  27367. this.requestHeader = requestHeader;
  27368. return this;
  27369. }
  27370. });
  27371. var loading = {};
  27372. function FileLoader(manager) {
  27373. Loader.call(this, manager);
  27374. }
  27375. FileLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  27376. constructor: FileLoader,
  27377. load: function load(url, onLoad, onProgress, onError) {
  27378. if (url === undefined) url = '';
  27379. if (this.path !== undefined) url = this.path + url;
  27380. url = this.manager.resolveURL(url);
  27381. var scope = this;
  27382. var cached = Cache.get(url);
  27383. if (cached !== undefined) {
  27384. scope.manager.itemStart(url);
  27385. setTimeout(function () {
  27386. if (onLoad) onLoad(cached);
  27387. scope.manager.itemEnd(url);
  27388. }, 0);
  27389. return cached;
  27390. } // Check if request is duplicate
  27391. if (loading[url] !== undefined) {
  27392. loading[url].push({
  27393. onLoad: onLoad,
  27394. onProgress: onProgress,
  27395. onError: onError
  27396. });
  27397. return;
  27398. } // Check for data: URI
  27399. var dataUriRegex = /^data:(.*?)(;base64)?,(.*)$/;
  27400. var dataUriRegexResult = url.match(dataUriRegex);
  27401. var request; // Safari can not handle Data URIs through XMLHttpRequest so process manually
  27402. if (dataUriRegexResult) {
  27403. var mimeType = dataUriRegexResult[1];
  27404. var isBase64 = !!dataUriRegexResult[2];
  27405. var data = dataUriRegexResult[3];
  27406. data = decodeURIComponent(data);
  27407. if (isBase64) data = atob(data);
  27408. try {
  27409. var response;
  27410. var responseType = (this.responseType || '').toLowerCase();
  27411. switch (responseType) {
  27412. case 'arraybuffer':
  27413. case 'blob':
  27414. var view = new Uint8Array(data.length);
  27415. for (var i = 0; i < data.length; i++) {
  27416. view[i] = data.charCodeAt(i);
  27417. }
  27418. if (responseType === 'blob') {
  27419. response = new Blob([view.buffer], {
  27420. type: mimeType
  27421. });
  27422. } else {
  27423. response = view.buffer;
  27424. }
  27425. break;
  27426. case 'document':
  27427. var parser = new DOMParser();
  27428. response = parser.parseFromString(data, mimeType);
  27429. break;
  27430. case 'json':
  27431. response = JSON.parse(data);
  27432. break;
  27433. default:
  27434. // 'text' or other
  27435. response = data;
  27436. break;
  27437. } // Wait for next browser tick like standard XMLHttpRequest event dispatching does
  27438. setTimeout(function () {
  27439. if (onLoad) onLoad(response);
  27440. scope.manager.itemEnd(url);
  27441. }, 0);
  27442. } catch (error) {
  27443. // Wait for next browser tick like standard XMLHttpRequest event dispatching does
  27444. setTimeout(function () {
  27445. if (onError) onError(error);
  27446. scope.manager.itemError(url);
  27447. scope.manager.itemEnd(url);
  27448. }, 0);
  27449. }
  27450. } else {
  27451. // Initialise array for duplicate requests
  27452. loading[url] = [];
  27453. loading[url].push({
  27454. onLoad: onLoad,
  27455. onProgress: onProgress,
  27456. onError: onError
  27457. });
  27458. request = new XMLHttpRequest();
  27459. request.open('GET', url, true);
  27460. request.addEventListener('load', function (event) {
  27461. var response = this.response;
  27462. var callbacks = loading[url];
  27463. delete loading[url];
  27464. if (this.status === 200 || this.status === 0) {
  27465. // Some browsers return HTTP Status 0 when using non-http protocol
  27466. // e.g. 'file://' or 'data://'. Handle as success.
  27467. if (this.status === 0) console.warn('THREE.FileLoader: HTTP Status 0 received.'); // Add to cache only on HTTP success, so that we do not cache
  27468. // error response bodies as proper responses to requests.
  27469. Cache.add(url, response);
  27470. for (var _i = 0, il = callbacks.length; _i < il; _i++) {
  27471. var callback = callbacks[_i];
  27472. if (callback.onLoad) callback.onLoad(response);
  27473. }
  27474. scope.manager.itemEnd(url);
  27475. } else {
  27476. for (var _i2 = 0, _il = callbacks.length; _i2 < _il; _i2++) {
  27477. var _callback = callbacks[_i2];
  27478. if (_callback.onError) _callback.onError(event);
  27479. }
  27480. scope.manager.itemError(url);
  27481. scope.manager.itemEnd(url);
  27482. }
  27483. }, false);
  27484. request.addEventListener('progress', function (event) {
  27485. var callbacks = loading[url];
  27486. for (var _i3 = 0, il = callbacks.length; _i3 < il; _i3++) {
  27487. var callback = callbacks[_i3];
  27488. if (callback.onProgress) callback.onProgress(event);
  27489. }
  27490. }, false);
  27491. request.addEventListener('error', function (event) {
  27492. var callbacks = loading[url];
  27493. delete loading[url];
  27494. for (var _i4 = 0, il = callbacks.length; _i4 < il; _i4++) {
  27495. var callback = callbacks[_i4];
  27496. if (callback.onError) callback.onError(event);
  27497. }
  27498. scope.manager.itemError(url);
  27499. scope.manager.itemEnd(url);
  27500. }, false);
  27501. request.addEventListener('abort', function (event) {
  27502. var callbacks = loading[url];
  27503. delete loading[url];
  27504. for (var _i5 = 0, il = callbacks.length; _i5 < il; _i5++) {
  27505. var callback = callbacks[_i5];
  27506. if (callback.onError) callback.onError(event);
  27507. }
  27508. scope.manager.itemError(url);
  27509. scope.manager.itemEnd(url);
  27510. }, false);
  27511. if (this.responseType !== undefined) request.responseType = this.responseType;
  27512. if (this.withCredentials !== undefined) request.withCredentials = this.withCredentials;
  27513. if (request.overrideMimeType) request.overrideMimeType(this.mimeType !== undefined ? this.mimeType : 'text/plain');
  27514. for (var header in this.requestHeader) {
  27515. request.setRequestHeader(header, this.requestHeader[header]);
  27516. }
  27517. request.send(null);
  27518. }
  27519. scope.manager.itemStart(url);
  27520. return request;
  27521. },
  27522. setResponseType: function setResponseType(value) {
  27523. this.responseType = value;
  27524. return this;
  27525. },
  27526. setMimeType: function setMimeType(value) {
  27527. this.mimeType = value;
  27528. return this;
  27529. }
  27530. });
  27531. function AnimationLoader(manager) {
  27532. Loader.call(this, manager);
  27533. }
  27534. AnimationLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  27535. constructor: AnimationLoader,
  27536. load: function load(url, onLoad, onProgress, onError) {
  27537. var scope = this;
  27538. var loader = new FileLoader(scope.manager);
  27539. loader.setPath(scope.path);
  27540. loader.setRequestHeader(scope.requestHeader);
  27541. loader.setWithCredentials(scope.withCredentials);
  27542. loader.load(url, function (text) {
  27543. try {
  27544. onLoad(scope.parse(JSON.parse(text)));
  27545. } catch (e) {
  27546. if (onError) {
  27547. onError(e);
  27548. } else {
  27549. console.error(e);
  27550. }
  27551. scope.manager.itemError(url);
  27552. }
  27553. }, onProgress, onError);
  27554. },
  27555. parse: function parse(json) {
  27556. var animations = [];
  27557. for (var i = 0; i < json.length; i++) {
  27558. var clip = AnimationClip.parse(json[i]);
  27559. animations.push(clip);
  27560. }
  27561. return animations;
  27562. }
  27563. });
  27564. /**
  27565. * Abstract Base class to block based textures loader (dds, pvr, ...)
  27566. *
  27567. * Sub classes have to implement the parse() method which will be used in load().
  27568. */
  27569. function CompressedTextureLoader(manager) {
  27570. Loader.call(this, manager);
  27571. }
  27572. CompressedTextureLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  27573. constructor: CompressedTextureLoader,
  27574. load: function load(url, onLoad, onProgress, onError) {
  27575. var scope = this;
  27576. var images = [];
  27577. var texture = new CompressedTexture();
  27578. var loader = new FileLoader(this.manager);
  27579. loader.setPath(this.path);
  27580. loader.setResponseType('arraybuffer');
  27581. loader.setRequestHeader(this.requestHeader);
  27582. loader.setWithCredentials(scope.withCredentials);
  27583. var loaded = 0;
  27584. function loadTexture(i) {
  27585. loader.load(url[i], function (buffer) {
  27586. var texDatas = scope.parse(buffer, true);
  27587. images[i] = {
  27588. width: texDatas.width,
  27589. height: texDatas.height,
  27590. format: texDatas.format,
  27591. mipmaps: texDatas.mipmaps
  27592. };
  27593. loaded += 1;
  27594. if (loaded === 6) {
  27595. if (texDatas.mipmapCount === 1) texture.minFilter = LinearFilter;
  27596. texture.image = images;
  27597. texture.format = texDatas.format;
  27598. texture.needsUpdate = true;
  27599. if (onLoad) onLoad(texture);
  27600. }
  27601. }, onProgress, onError);
  27602. }
  27603. if (Array.isArray(url)) {
  27604. for (var i = 0, il = url.length; i < il; ++i) {
  27605. loadTexture(i);
  27606. }
  27607. } else {
  27608. // compressed cubemap texture stored in a single DDS file
  27609. loader.load(url, function (buffer) {
  27610. var texDatas = scope.parse(buffer, true);
  27611. if (texDatas.isCubemap) {
  27612. var faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  27613. for (var f = 0; f < faces; f++) {
  27614. images[f] = {
  27615. mipmaps: []
  27616. };
  27617. for (var _i = 0; _i < texDatas.mipmapCount; _i++) {
  27618. images[f].mipmaps.push(texDatas.mipmaps[f * texDatas.mipmapCount + _i]);
  27619. images[f].format = texDatas.format;
  27620. images[f].width = texDatas.width;
  27621. images[f].height = texDatas.height;
  27622. }
  27623. }
  27624. texture.image = images;
  27625. } else {
  27626. texture.image.width = texDatas.width;
  27627. texture.image.height = texDatas.height;
  27628. texture.mipmaps = texDatas.mipmaps;
  27629. }
  27630. if (texDatas.mipmapCount === 1) {
  27631. texture.minFilter = LinearFilter;
  27632. }
  27633. texture.format = texDatas.format;
  27634. texture.needsUpdate = true;
  27635. if (onLoad) onLoad(texture);
  27636. }, onProgress, onError);
  27637. }
  27638. return texture;
  27639. }
  27640. });
  27641. function ImageLoader(manager) {
  27642. Loader.call(this, manager);
  27643. }
  27644. ImageLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  27645. constructor: ImageLoader,
  27646. load: function load(url, onLoad, onProgress, onError) {
  27647. if (this.path !== undefined) url = this.path + url;
  27648. url = this.manager.resolveURL(url);
  27649. var scope = this;
  27650. var cached = Cache.get(url);
  27651. if (cached !== undefined) {
  27652. scope.manager.itemStart(url);
  27653. setTimeout(function () {
  27654. if (onLoad) onLoad(cached);
  27655. scope.manager.itemEnd(url);
  27656. }, 0);
  27657. return cached;
  27658. }
  27659. var image = document.createElementNS('http://www.w3.org/1999/xhtml', 'img');
  27660. function onImageLoad() {
  27661. image.removeEventListener('load', onImageLoad, false);
  27662. image.removeEventListener('error', onImageError, false);
  27663. Cache.add(url, this);
  27664. if (onLoad) onLoad(this);
  27665. scope.manager.itemEnd(url);
  27666. }
  27667. function onImageError(event) {
  27668. image.removeEventListener('load', onImageLoad, false);
  27669. image.removeEventListener('error', onImageError, false);
  27670. if (onError) onError(event);
  27671. scope.manager.itemError(url);
  27672. scope.manager.itemEnd(url);
  27673. }
  27674. image.addEventListener('load', onImageLoad, false);
  27675. image.addEventListener('error', onImageError, false);
  27676. if (url.substr(0, 5) !== 'data:') {
  27677. if (this.crossOrigin !== undefined) image.crossOrigin = this.crossOrigin;
  27678. }
  27679. scope.manager.itemStart(url);
  27680. image.src = url;
  27681. return image;
  27682. }
  27683. });
  27684. function CubeTextureLoader(manager) {
  27685. Loader.call(this, manager);
  27686. }
  27687. CubeTextureLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  27688. constructor: CubeTextureLoader,
  27689. load: function load(urls, onLoad, onProgress, onError) {
  27690. var texture = new CubeTexture();
  27691. var loader = new ImageLoader(this.manager);
  27692. loader.setCrossOrigin(this.crossOrigin);
  27693. loader.setPath(this.path);
  27694. var loaded = 0;
  27695. function loadTexture(i) {
  27696. loader.load(urls[i], function (image) {
  27697. texture.images[i] = image;
  27698. loaded++;
  27699. if (loaded === 6) {
  27700. texture.needsUpdate = true;
  27701. if (onLoad) onLoad(texture);
  27702. }
  27703. }, undefined, onError);
  27704. }
  27705. for (var i = 0; i < urls.length; ++i) {
  27706. loadTexture(i);
  27707. }
  27708. return texture;
  27709. }
  27710. });
  27711. /**
  27712. * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...)
  27713. *
  27714. * Sub classes have to implement the parse() method which will be used in load().
  27715. */
  27716. function DataTextureLoader(manager) {
  27717. Loader.call(this, manager);
  27718. }
  27719. DataTextureLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  27720. constructor: DataTextureLoader,
  27721. load: function load(url, onLoad, onProgress, onError) {
  27722. var scope = this;
  27723. var texture = new DataTexture();
  27724. var loader = new FileLoader(this.manager);
  27725. loader.setResponseType('arraybuffer');
  27726. loader.setRequestHeader(this.requestHeader);
  27727. loader.setPath(this.path);
  27728. loader.setWithCredentials(scope.withCredentials);
  27729. loader.load(url, function (buffer) {
  27730. var texData = scope.parse(buffer);
  27731. if (!texData) return;
  27732. if (texData.image !== undefined) {
  27733. texture.image = texData.image;
  27734. } else if (texData.data !== undefined) {
  27735. texture.image.width = texData.width;
  27736. texture.image.height = texData.height;
  27737. texture.image.data = texData.data;
  27738. }
  27739. texture.wrapS = texData.wrapS !== undefined ? texData.wrapS : ClampToEdgeWrapping;
  27740. texture.wrapT = texData.wrapT !== undefined ? texData.wrapT : ClampToEdgeWrapping;
  27741. texture.magFilter = texData.magFilter !== undefined ? texData.magFilter : LinearFilter;
  27742. texture.minFilter = texData.minFilter !== undefined ? texData.minFilter : LinearFilter;
  27743. texture.anisotropy = texData.anisotropy !== undefined ? texData.anisotropy : 1;
  27744. if (texData.encoding !== undefined) {
  27745. texture.encoding = texData.encoding;
  27746. }
  27747. if (texData.flipY !== undefined) {
  27748. texture.flipY = texData.flipY;
  27749. }
  27750. if (texData.format !== undefined) {
  27751. texture.format = texData.format;
  27752. }
  27753. if (texData.type !== undefined) {
  27754. texture.type = texData.type;
  27755. }
  27756. if (texData.mipmaps !== undefined) {
  27757. texture.mipmaps = texData.mipmaps;
  27758. texture.minFilter = LinearMipmapLinearFilter; // presumably...
  27759. }
  27760. if (texData.mipmapCount === 1) {
  27761. texture.minFilter = LinearFilter;
  27762. }
  27763. texture.needsUpdate = true;
  27764. if (onLoad) onLoad(texture, texData);
  27765. }, onProgress, onError);
  27766. return texture;
  27767. }
  27768. });
  27769. function TextureLoader(manager) {
  27770. Loader.call(this, manager);
  27771. }
  27772. TextureLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  27773. constructor: TextureLoader,
  27774. load: function load(url, onLoad, onProgress, onError) {
  27775. var texture = new Texture();
  27776. var loader = new ImageLoader(this.manager);
  27777. loader.setCrossOrigin(this.crossOrigin);
  27778. loader.setPath(this.path);
  27779. loader.load(url, function (image) {
  27780. texture.image = image; // JPEGs can't have an alpha channel, so memory can be saved by storing them as RGB.
  27781. var isJPEG = url.search(/\.jpe?g($|\?)/i) > 0 || url.search(/^data\:image\/jpeg/) === 0;
  27782. texture.format = isJPEG ? RGBFormat : RGBAFormat;
  27783. texture.needsUpdate = true;
  27784. if (onLoad !== undefined) {
  27785. onLoad(texture);
  27786. }
  27787. }, onProgress, onError);
  27788. return texture;
  27789. }
  27790. });
  27791. /**
  27792. * Extensible curve object.
  27793. *
  27794. * Some common of curve methods:
  27795. * .getPoint( t, optionalTarget ), .getTangent( t, optionalTarget )
  27796. * .getPointAt( u, optionalTarget ), .getTangentAt( u, optionalTarget )
  27797. * .getPoints(), .getSpacedPoints()
  27798. * .getLength()
  27799. * .updateArcLengths()
  27800. *
  27801. * This following curves inherit from THREE.Curve:
  27802. *
  27803. * -- 2D curves --
  27804. * THREE.ArcCurve
  27805. * THREE.CubicBezierCurve
  27806. * THREE.EllipseCurve
  27807. * THREE.LineCurve
  27808. * THREE.QuadraticBezierCurve
  27809. * THREE.SplineCurve
  27810. *
  27811. * -- 3D curves --
  27812. * THREE.CatmullRomCurve3
  27813. * THREE.CubicBezierCurve3
  27814. * THREE.LineCurve3
  27815. * THREE.QuadraticBezierCurve3
  27816. *
  27817. * A series of curves can be represented as a THREE.CurvePath.
  27818. *
  27819. **/
  27820. function Curve() {
  27821. this.type = 'Curve';
  27822. this.arcLengthDivisions = 200;
  27823. }
  27824. Object.assign(Curve.prototype, {
  27825. // Virtual base class method to overwrite and implement in subclasses
  27826. // - t [0 .. 1]
  27827. getPoint: function getPoint()
  27828. /* t, optionalTarget */
  27829. {
  27830. console.warn('THREE.Curve: .getPoint() not implemented.');
  27831. return null;
  27832. },
  27833. // Get point at relative position in curve according to arc length
  27834. // - u [0 .. 1]
  27835. getPointAt: function getPointAt(u, optionalTarget) {
  27836. var t = this.getUtoTmapping(u);
  27837. return this.getPoint(t, optionalTarget);
  27838. },
  27839. // Get sequence of points using getPoint( t )
  27840. getPoints: function getPoints(divisions) {
  27841. if (divisions === void 0) {
  27842. divisions = 5;
  27843. }
  27844. var points = [];
  27845. for (var d = 0; d <= divisions; d++) {
  27846. points.push(this.getPoint(d / divisions));
  27847. }
  27848. return points;
  27849. },
  27850. // Get sequence of points using getPointAt( u )
  27851. getSpacedPoints: function getSpacedPoints(divisions) {
  27852. if (divisions === void 0) {
  27853. divisions = 5;
  27854. }
  27855. var points = [];
  27856. for (var d = 0; d <= divisions; d++) {
  27857. points.push(this.getPointAt(d / divisions));
  27858. }
  27859. return points;
  27860. },
  27861. // Get total curve arc length
  27862. getLength: function getLength() {
  27863. var lengths = this.getLengths();
  27864. return lengths[lengths.length - 1];
  27865. },
  27866. // Get list of cumulative segment lengths
  27867. getLengths: function getLengths(divisions) {
  27868. if (divisions === undefined) divisions = this.arcLengthDivisions;
  27869. if (this.cacheArcLengths && this.cacheArcLengths.length === divisions + 1 && !this.needsUpdate) {
  27870. return this.cacheArcLengths;
  27871. }
  27872. this.needsUpdate = false;
  27873. var cache = [];
  27874. var current,
  27875. last = this.getPoint(0);
  27876. var sum = 0;
  27877. cache.push(0);
  27878. for (var p = 1; p <= divisions; p++) {
  27879. current = this.getPoint(p / divisions);
  27880. sum += current.distanceTo(last);
  27881. cache.push(sum);
  27882. last = current;
  27883. }
  27884. this.cacheArcLengths = cache;
  27885. return cache; // { sums: cache, sum: sum }; Sum is in the last element.
  27886. },
  27887. updateArcLengths: function updateArcLengths() {
  27888. this.needsUpdate = true;
  27889. this.getLengths();
  27890. },
  27891. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant
  27892. getUtoTmapping: function getUtoTmapping(u, distance) {
  27893. var arcLengths = this.getLengths();
  27894. var i = 0;
  27895. var il = arcLengths.length;
  27896. var targetArcLength; // The targeted u distance value to get
  27897. if (distance) {
  27898. targetArcLength = distance;
  27899. } else {
  27900. targetArcLength = u * arcLengths[il - 1];
  27901. } // binary search for the index with largest value smaller than target u distance
  27902. var low = 0,
  27903. high = il - 1,
  27904. comparison;
  27905. while (low <= high) {
  27906. i = Math.floor(low + (high - low) / 2); // less likely to overflow, though probably not issue here, JS doesn't really have integers, all numbers are floats
  27907. comparison = arcLengths[i] - targetArcLength;
  27908. if (comparison < 0) {
  27909. low = i + 1;
  27910. } else if (comparison > 0) {
  27911. high = i - 1;
  27912. } else {
  27913. high = i;
  27914. break; // DONE
  27915. }
  27916. }
  27917. i = high;
  27918. if (arcLengths[i] === targetArcLength) {
  27919. return i / (il - 1);
  27920. } // we could get finer grain at lengths, or use simple interpolation between two points
  27921. var lengthBefore = arcLengths[i];
  27922. var lengthAfter = arcLengths[i + 1];
  27923. var segmentLength = lengthAfter - lengthBefore; // determine where we are between the 'before' and 'after' points
  27924. var segmentFraction = (targetArcLength - lengthBefore) / segmentLength; // add that fractional amount to t
  27925. var t = (i + segmentFraction) / (il - 1);
  27926. return t;
  27927. },
  27928. // Returns a unit vector tangent at t
  27929. // In case any sub curve does not implement its tangent derivation,
  27930. // 2 points a small delta apart will be used to find its gradient
  27931. // which seems to give a reasonable approximation
  27932. getTangent: function getTangent(t, optionalTarget) {
  27933. var delta = 0.0001;
  27934. var t1 = t - delta;
  27935. var t2 = t + delta; // Capping in case of danger
  27936. if (t1 < 0) t1 = 0;
  27937. if (t2 > 1) t2 = 1;
  27938. var pt1 = this.getPoint(t1);
  27939. var pt2 = this.getPoint(t2);
  27940. var tangent = optionalTarget || (pt1.isVector2 ? new Vector2() : new Vector3());
  27941. tangent.copy(pt2).sub(pt1).normalize();
  27942. return tangent;
  27943. },
  27944. getTangentAt: function getTangentAt(u, optionalTarget) {
  27945. var t = this.getUtoTmapping(u);
  27946. return this.getTangent(t, optionalTarget);
  27947. },
  27948. computeFrenetFrames: function computeFrenetFrames(segments, closed) {
  27949. // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  27950. var normal = new Vector3();
  27951. var tangents = [];
  27952. var normals = [];
  27953. var binormals = [];
  27954. var vec = new Vector3();
  27955. var mat = new Matrix4(); // compute the tangent vectors for each segment on the curve
  27956. for (var i = 0; i <= segments; i++) {
  27957. var u = i / segments;
  27958. tangents[i] = this.getTangentAt(u, new Vector3());
  27959. tangents[i].normalize();
  27960. } // select an initial normal vector perpendicular to the first tangent vector,
  27961. // and in the direction of the minimum tangent xyz component
  27962. normals[0] = new Vector3();
  27963. binormals[0] = new Vector3();
  27964. var min = Number.MAX_VALUE;
  27965. var tx = Math.abs(tangents[0].x);
  27966. var ty = Math.abs(tangents[0].y);
  27967. var tz = Math.abs(tangents[0].z);
  27968. if (tx <= min) {
  27969. min = tx;
  27970. normal.set(1, 0, 0);
  27971. }
  27972. if (ty <= min) {
  27973. min = ty;
  27974. normal.set(0, 1, 0);
  27975. }
  27976. if (tz <= min) {
  27977. normal.set(0, 0, 1);
  27978. }
  27979. vec.crossVectors(tangents[0], normal).normalize();
  27980. normals[0].crossVectors(tangents[0], vec);
  27981. binormals[0].crossVectors(tangents[0], normals[0]); // compute the slowly-varying normal and binormal vectors for each segment on the curve
  27982. for (var _i = 1; _i <= segments; _i++) {
  27983. normals[_i] = normals[_i - 1].clone();
  27984. binormals[_i] = binormals[_i - 1].clone();
  27985. vec.crossVectors(tangents[_i - 1], tangents[_i]);
  27986. if (vec.length() > Number.EPSILON) {
  27987. vec.normalize();
  27988. var theta = Math.acos(MathUtils.clamp(tangents[_i - 1].dot(tangents[_i]), -1, 1)); // clamp for floating pt errors
  27989. normals[_i].applyMatrix4(mat.makeRotationAxis(vec, theta));
  27990. }
  27991. binormals[_i].crossVectors(tangents[_i], normals[_i]);
  27992. } // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  27993. if (closed === true) {
  27994. var _theta = Math.acos(MathUtils.clamp(normals[0].dot(normals[segments]), -1, 1));
  27995. _theta /= segments;
  27996. if (tangents[0].dot(vec.crossVectors(normals[0], normals[segments])) > 0) {
  27997. _theta = -_theta;
  27998. }
  27999. for (var _i2 = 1; _i2 <= segments; _i2++) {
  28000. // twist a little...
  28001. normals[_i2].applyMatrix4(mat.makeRotationAxis(tangents[_i2], _theta * _i2));
  28002. binormals[_i2].crossVectors(tangents[_i2], normals[_i2]);
  28003. }
  28004. }
  28005. return {
  28006. tangents: tangents,
  28007. normals: normals,
  28008. binormals: binormals
  28009. };
  28010. },
  28011. clone: function clone() {
  28012. return new this.constructor().copy(this);
  28013. },
  28014. copy: function copy(source) {
  28015. this.arcLengthDivisions = source.arcLengthDivisions;
  28016. return this;
  28017. },
  28018. toJSON: function toJSON() {
  28019. var data = {
  28020. metadata: {
  28021. version: 4.5,
  28022. type: 'Curve',
  28023. generator: 'Curve.toJSON'
  28024. }
  28025. };
  28026. data.arcLengthDivisions = this.arcLengthDivisions;
  28027. data.type = this.type;
  28028. return data;
  28029. },
  28030. fromJSON: function fromJSON(json) {
  28031. this.arcLengthDivisions = json.arcLengthDivisions;
  28032. return this;
  28033. }
  28034. });
  28035. function EllipseCurve(aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation) {
  28036. Curve.call(this);
  28037. this.type = 'EllipseCurve';
  28038. this.aX = aX || 0;
  28039. this.aY = aY || 0;
  28040. this.xRadius = xRadius || 1;
  28041. this.yRadius = yRadius || 1;
  28042. this.aStartAngle = aStartAngle || 0;
  28043. this.aEndAngle = aEndAngle || 2 * Math.PI;
  28044. this.aClockwise = aClockwise || false;
  28045. this.aRotation = aRotation || 0;
  28046. }
  28047. EllipseCurve.prototype = Object.create(Curve.prototype);
  28048. EllipseCurve.prototype.constructor = EllipseCurve;
  28049. EllipseCurve.prototype.isEllipseCurve = true;
  28050. EllipseCurve.prototype.getPoint = function (t, optionalTarget) {
  28051. var point = optionalTarget || new Vector2();
  28052. var twoPi = Math.PI * 2;
  28053. var deltaAngle = this.aEndAngle - this.aStartAngle;
  28054. var samePoints = Math.abs(deltaAngle) < Number.EPSILON; // ensures that deltaAngle is 0 .. 2 PI
  28055. while (deltaAngle < 0) {
  28056. deltaAngle += twoPi;
  28057. }
  28058. while (deltaAngle > twoPi) {
  28059. deltaAngle -= twoPi;
  28060. }
  28061. if (deltaAngle < Number.EPSILON) {
  28062. if (samePoints) {
  28063. deltaAngle = 0;
  28064. } else {
  28065. deltaAngle = twoPi;
  28066. }
  28067. }
  28068. if (this.aClockwise === true && !samePoints) {
  28069. if (deltaAngle === twoPi) {
  28070. deltaAngle = -twoPi;
  28071. } else {
  28072. deltaAngle = deltaAngle - twoPi;
  28073. }
  28074. }
  28075. var angle = this.aStartAngle + t * deltaAngle;
  28076. var x = this.aX + this.xRadius * Math.cos(angle);
  28077. var y = this.aY + this.yRadius * Math.sin(angle);
  28078. if (this.aRotation !== 0) {
  28079. var cos = Math.cos(this.aRotation);
  28080. var sin = Math.sin(this.aRotation);
  28081. var tx = x - this.aX;
  28082. var ty = y - this.aY; // Rotate the point about the center of the ellipse.
  28083. x = tx * cos - ty * sin + this.aX;
  28084. y = tx * sin + ty * cos + this.aY;
  28085. }
  28086. return point.set(x, y);
  28087. };
  28088. EllipseCurve.prototype.copy = function (source) {
  28089. Curve.prototype.copy.call(this, source);
  28090. this.aX = source.aX;
  28091. this.aY = source.aY;
  28092. this.xRadius = source.xRadius;
  28093. this.yRadius = source.yRadius;
  28094. this.aStartAngle = source.aStartAngle;
  28095. this.aEndAngle = source.aEndAngle;
  28096. this.aClockwise = source.aClockwise;
  28097. this.aRotation = source.aRotation;
  28098. return this;
  28099. };
  28100. EllipseCurve.prototype.toJSON = function () {
  28101. var data = Curve.prototype.toJSON.call(this);
  28102. data.aX = this.aX;
  28103. data.aY = this.aY;
  28104. data.xRadius = this.xRadius;
  28105. data.yRadius = this.yRadius;
  28106. data.aStartAngle = this.aStartAngle;
  28107. data.aEndAngle = this.aEndAngle;
  28108. data.aClockwise = this.aClockwise;
  28109. data.aRotation = this.aRotation;
  28110. return data;
  28111. };
  28112. EllipseCurve.prototype.fromJSON = function (json) {
  28113. Curve.prototype.fromJSON.call(this, json);
  28114. this.aX = json.aX;
  28115. this.aY = json.aY;
  28116. this.xRadius = json.xRadius;
  28117. this.yRadius = json.yRadius;
  28118. this.aStartAngle = json.aStartAngle;
  28119. this.aEndAngle = json.aEndAngle;
  28120. this.aClockwise = json.aClockwise;
  28121. this.aRotation = json.aRotation;
  28122. return this;
  28123. };
  28124. function ArcCurve(aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) {
  28125. EllipseCurve.call(this, aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise);
  28126. this.type = 'ArcCurve';
  28127. }
  28128. ArcCurve.prototype = Object.create(EllipseCurve.prototype);
  28129. ArcCurve.prototype.constructor = ArcCurve;
  28130. ArcCurve.prototype.isArcCurve = true;
  28131. /**
  28132. * Centripetal CatmullRom Curve - which is useful for avoiding
  28133. * cusps and self-intersections in non-uniform catmull rom curves.
  28134. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  28135. *
  28136. * curve.type accepts centripetal(default), chordal and catmullrom
  28137. * curve.tension is used for catmullrom which defaults to 0.5
  28138. */
  28139. /*
  28140. Based on an optimized c++ solution in
  28141. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  28142. - http://ideone.com/NoEbVM
  28143. This CubicPoly class could be used for reusing some variables and calculations,
  28144. but for three.js curve use, it could be possible inlined and flatten into a single function call
  28145. which can be placed in CurveUtils.
  28146. */
  28147. function CubicPoly() {
  28148. var c0 = 0,
  28149. c1 = 0,
  28150. c2 = 0,
  28151. c3 = 0;
  28152. /*
  28153. * Compute coefficients for a cubic polynomial
  28154. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  28155. * such that
  28156. * p(0) = x0, p(1) = x1
  28157. * and
  28158. * p'(0) = t0, p'(1) = t1.
  28159. */
  28160. function init(x0, x1, t0, t1) {
  28161. c0 = x0;
  28162. c1 = t0;
  28163. c2 = -3 * x0 + 3 * x1 - 2 * t0 - t1;
  28164. c3 = 2 * x0 - 2 * x1 + t0 + t1;
  28165. }
  28166. return {
  28167. initCatmullRom: function initCatmullRom(x0, x1, x2, x3, tension) {
  28168. init(x1, x2, tension * (x2 - x0), tension * (x3 - x1));
  28169. },
  28170. initNonuniformCatmullRom: function initNonuniformCatmullRom(x0, x1, x2, x3, dt0, dt1, dt2) {
  28171. // compute tangents when parameterized in [t1,t2]
  28172. var t1 = (x1 - x0) / dt0 - (x2 - x0) / (dt0 + dt1) + (x2 - x1) / dt1;
  28173. var t2 = (x2 - x1) / dt1 - (x3 - x1) / (dt1 + dt2) + (x3 - x2) / dt2; // rescale tangents for parametrization in [0,1]
  28174. t1 *= dt1;
  28175. t2 *= dt1;
  28176. init(x1, x2, t1, t2);
  28177. },
  28178. calc: function calc(t) {
  28179. var t2 = t * t;
  28180. var t3 = t2 * t;
  28181. return c0 + c1 * t + c2 * t2 + c3 * t3;
  28182. }
  28183. };
  28184. } //
  28185. var tmp = new Vector3();
  28186. var px = new CubicPoly(),
  28187. py = new CubicPoly(),
  28188. pz = new CubicPoly();
  28189. function CatmullRomCurve3(points, closed, curveType, tension) {
  28190. if (points === void 0) {
  28191. points = [];
  28192. }
  28193. if (closed === void 0) {
  28194. closed = false;
  28195. }
  28196. if (curveType === void 0) {
  28197. curveType = 'centripetal';
  28198. }
  28199. if (tension === void 0) {
  28200. tension = 0.5;
  28201. }
  28202. Curve.call(this);
  28203. this.type = 'CatmullRomCurve3';
  28204. this.points = points;
  28205. this.closed = closed;
  28206. this.curveType = curveType;
  28207. this.tension = tension;
  28208. }
  28209. CatmullRomCurve3.prototype = Object.create(Curve.prototype);
  28210. CatmullRomCurve3.prototype.constructor = CatmullRomCurve3;
  28211. CatmullRomCurve3.prototype.isCatmullRomCurve3 = true;
  28212. CatmullRomCurve3.prototype.getPoint = function (t, optionalTarget) {
  28213. if (optionalTarget === void 0) {
  28214. optionalTarget = new Vector3();
  28215. }
  28216. var point = optionalTarget;
  28217. var points = this.points;
  28218. var l = points.length;
  28219. var p = (l - (this.closed ? 0 : 1)) * t;
  28220. var intPoint = Math.floor(p);
  28221. var weight = p - intPoint;
  28222. if (this.closed) {
  28223. intPoint += intPoint > 0 ? 0 : (Math.floor(Math.abs(intPoint) / l) + 1) * l;
  28224. } else if (weight === 0 && intPoint === l - 1) {
  28225. intPoint = l - 2;
  28226. weight = 1;
  28227. }
  28228. var p0, p3; // 4 points (p1 & p2 defined below)
  28229. if (this.closed || intPoint > 0) {
  28230. p0 = points[(intPoint - 1) % l];
  28231. } else {
  28232. // extrapolate first point
  28233. tmp.subVectors(points[0], points[1]).add(points[0]);
  28234. p0 = tmp;
  28235. }
  28236. var p1 = points[intPoint % l];
  28237. var p2 = points[(intPoint + 1) % l];
  28238. if (this.closed || intPoint + 2 < l) {
  28239. p3 = points[(intPoint + 2) % l];
  28240. } else {
  28241. // extrapolate last point
  28242. tmp.subVectors(points[l - 1], points[l - 2]).add(points[l - 1]);
  28243. p3 = tmp;
  28244. }
  28245. if (this.curveType === 'centripetal' || this.curveType === 'chordal') {
  28246. // init Centripetal / Chordal Catmull-Rom
  28247. var pow = this.curveType === 'chordal' ? 0.5 : 0.25;
  28248. var dt0 = Math.pow(p0.distanceToSquared(p1), pow);
  28249. var dt1 = Math.pow(p1.distanceToSquared(p2), pow);
  28250. var dt2 = Math.pow(p2.distanceToSquared(p3), pow); // safety check for repeated points
  28251. if (dt1 < 1e-4) dt1 = 1.0;
  28252. if (dt0 < 1e-4) dt0 = dt1;
  28253. if (dt2 < 1e-4) dt2 = dt1;
  28254. px.initNonuniformCatmullRom(p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2);
  28255. py.initNonuniformCatmullRom(p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2);
  28256. pz.initNonuniformCatmullRom(p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2);
  28257. } else if (this.curveType === 'catmullrom') {
  28258. px.initCatmullRom(p0.x, p1.x, p2.x, p3.x, this.tension);
  28259. py.initCatmullRom(p0.y, p1.y, p2.y, p3.y, this.tension);
  28260. pz.initCatmullRom(p0.z, p1.z, p2.z, p3.z, this.tension);
  28261. }
  28262. point.set(px.calc(weight), py.calc(weight), pz.calc(weight));
  28263. return point;
  28264. };
  28265. CatmullRomCurve3.prototype.copy = function (source) {
  28266. Curve.prototype.copy.call(this, source);
  28267. this.points = [];
  28268. for (var i = 0, l = source.points.length; i < l; i++) {
  28269. var point = source.points[i];
  28270. this.points.push(point.clone());
  28271. }
  28272. this.closed = source.closed;
  28273. this.curveType = source.curveType;
  28274. this.tension = source.tension;
  28275. return this;
  28276. };
  28277. CatmullRomCurve3.prototype.toJSON = function () {
  28278. var data = Curve.prototype.toJSON.call(this);
  28279. data.points = [];
  28280. for (var i = 0, l = this.points.length; i < l; i++) {
  28281. var point = this.points[i];
  28282. data.points.push(point.toArray());
  28283. }
  28284. data.closed = this.closed;
  28285. data.curveType = this.curveType;
  28286. data.tension = this.tension;
  28287. return data;
  28288. };
  28289. CatmullRomCurve3.prototype.fromJSON = function (json) {
  28290. Curve.prototype.fromJSON.call(this, json);
  28291. this.points = [];
  28292. for (var i = 0, l = json.points.length; i < l; i++) {
  28293. var point = json.points[i];
  28294. this.points.push(new Vector3().fromArray(point));
  28295. }
  28296. this.closed = json.closed;
  28297. this.curveType = json.curveType;
  28298. this.tension = json.tension;
  28299. return this;
  28300. };
  28301. /**
  28302. * Bezier Curves formulas obtained from
  28303. * http://en.wikipedia.org/wiki/Bézier_curve
  28304. */
  28305. function CatmullRom(t, p0, p1, p2, p3) {
  28306. var v0 = (p2 - p0) * 0.5;
  28307. var v1 = (p3 - p1) * 0.5;
  28308. var t2 = t * t;
  28309. var t3 = t * t2;
  28310. return (2 * p1 - 2 * p2 + v0 + v1) * t3 + (-3 * p1 + 3 * p2 - 2 * v0 - v1) * t2 + v0 * t + p1;
  28311. } //
  28312. function QuadraticBezierP0(t, p) {
  28313. var k = 1 - t;
  28314. return k * k * p;
  28315. }
  28316. function QuadraticBezierP1(t, p) {
  28317. return 2 * (1 - t) * t * p;
  28318. }
  28319. function QuadraticBezierP2(t, p) {
  28320. return t * t * p;
  28321. }
  28322. function QuadraticBezier(t, p0, p1, p2) {
  28323. return QuadraticBezierP0(t, p0) + QuadraticBezierP1(t, p1) + QuadraticBezierP2(t, p2);
  28324. } //
  28325. function CubicBezierP0(t, p) {
  28326. var k = 1 - t;
  28327. return k * k * k * p;
  28328. }
  28329. function CubicBezierP1(t, p) {
  28330. var k = 1 - t;
  28331. return 3 * k * k * t * p;
  28332. }
  28333. function CubicBezierP2(t, p) {
  28334. return 3 * (1 - t) * t * t * p;
  28335. }
  28336. function CubicBezierP3(t, p) {
  28337. return t * t * t * p;
  28338. }
  28339. function CubicBezier(t, p0, p1, p2, p3) {
  28340. return CubicBezierP0(t, p0) + CubicBezierP1(t, p1) + CubicBezierP2(t, p2) + CubicBezierP3(t, p3);
  28341. }
  28342. function CubicBezierCurve(v0, v1, v2, v3) {
  28343. if (v0 === void 0) {
  28344. v0 = new Vector2();
  28345. }
  28346. if (v1 === void 0) {
  28347. v1 = new Vector2();
  28348. }
  28349. if (v2 === void 0) {
  28350. v2 = new Vector2();
  28351. }
  28352. if (v3 === void 0) {
  28353. v3 = new Vector2();
  28354. }
  28355. Curve.call(this);
  28356. this.type = 'CubicBezierCurve';
  28357. this.v0 = v0;
  28358. this.v1 = v1;
  28359. this.v2 = v2;
  28360. this.v3 = v3;
  28361. }
  28362. CubicBezierCurve.prototype = Object.create(Curve.prototype);
  28363. CubicBezierCurve.prototype.constructor = CubicBezierCurve;
  28364. CubicBezierCurve.prototype.isCubicBezierCurve = true;
  28365. CubicBezierCurve.prototype.getPoint = function (t, optionalTarget) {
  28366. if (optionalTarget === void 0) {
  28367. optionalTarget = new Vector2();
  28368. }
  28369. var point = optionalTarget;
  28370. var v0 = this.v0,
  28371. v1 = this.v1,
  28372. v2 = this.v2,
  28373. v3 = this.v3;
  28374. point.set(CubicBezier(t, v0.x, v1.x, v2.x, v3.x), CubicBezier(t, v0.y, v1.y, v2.y, v3.y));
  28375. return point;
  28376. };
  28377. CubicBezierCurve.prototype.copy = function (source) {
  28378. Curve.prototype.copy.call(this, source);
  28379. this.v0.copy(source.v0);
  28380. this.v1.copy(source.v1);
  28381. this.v2.copy(source.v2);
  28382. this.v3.copy(source.v3);
  28383. return this;
  28384. };
  28385. CubicBezierCurve.prototype.toJSON = function () {
  28386. var data = Curve.prototype.toJSON.call(this);
  28387. data.v0 = this.v0.toArray();
  28388. data.v1 = this.v1.toArray();
  28389. data.v2 = this.v2.toArray();
  28390. data.v3 = this.v3.toArray();
  28391. return data;
  28392. };
  28393. CubicBezierCurve.prototype.fromJSON = function (json) {
  28394. Curve.prototype.fromJSON.call(this, json);
  28395. this.v0.fromArray(json.v0);
  28396. this.v1.fromArray(json.v1);
  28397. this.v2.fromArray(json.v2);
  28398. this.v3.fromArray(json.v3);
  28399. return this;
  28400. };
  28401. function CubicBezierCurve3(v0, v1, v2, v3) {
  28402. if (v0 === void 0) {
  28403. v0 = new Vector3();
  28404. }
  28405. if (v1 === void 0) {
  28406. v1 = new Vector3();
  28407. }
  28408. if (v2 === void 0) {
  28409. v2 = new Vector3();
  28410. }
  28411. if (v3 === void 0) {
  28412. v3 = new Vector3();
  28413. }
  28414. Curve.call(this);
  28415. this.type = 'CubicBezierCurve3';
  28416. this.v0 = v0;
  28417. this.v1 = v1;
  28418. this.v2 = v2;
  28419. this.v3 = v3;
  28420. }
  28421. CubicBezierCurve3.prototype = Object.create(Curve.prototype);
  28422. CubicBezierCurve3.prototype.constructor = CubicBezierCurve3;
  28423. CubicBezierCurve3.prototype.isCubicBezierCurve3 = true;
  28424. CubicBezierCurve3.prototype.getPoint = function (t, optionalTarget) {
  28425. if (optionalTarget === void 0) {
  28426. optionalTarget = new Vector3();
  28427. }
  28428. var point = optionalTarget;
  28429. var v0 = this.v0,
  28430. v1 = this.v1,
  28431. v2 = this.v2,
  28432. v3 = this.v3;
  28433. point.set(CubicBezier(t, v0.x, v1.x, v2.x, v3.x), CubicBezier(t, v0.y, v1.y, v2.y, v3.y), CubicBezier(t, v0.z, v1.z, v2.z, v3.z));
  28434. return point;
  28435. };
  28436. CubicBezierCurve3.prototype.copy = function (source) {
  28437. Curve.prototype.copy.call(this, source);
  28438. this.v0.copy(source.v0);
  28439. this.v1.copy(source.v1);
  28440. this.v2.copy(source.v2);
  28441. this.v3.copy(source.v3);
  28442. return this;
  28443. };
  28444. CubicBezierCurve3.prototype.toJSON = function () {
  28445. var data = Curve.prototype.toJSON.call(this);
  28446. data.v0 = this.v0.toArray();
  28447. data.v1 = this.v1.toArray();
  28448. data.v2 = this.v2.toArray();
  28449. data.v3 = this.v3.toArray();
  28450. return data;
  28451. };
  28452. CubicBezierCurve3.prototype.fromJSON = function (json) {
  28453. Curve.prototype.fromJSON.call(this, json);
  28454. this.v0.fromArray(json.v0);
  28455. this.v1.fromArray(json.v1);
  28456. this.v2.fromArray(json.v2);
  28457. this.v3.fromArray(json.v3);
  28458. return this;
  28459. };
  28460. function LineCurve(v1, v2) {
  28461. if (v1 === void 0) {
  28462. v1 = new Vector2();
  28463. }
  28464. if (v2 === void 0) {
  28465. v2 = new Vector2();
  28466. }
  28467. Curve.call(this);
  28468. this.type = 'LineCurve';
  28469. this.v1 = v1;
  28470. this.v2 = v2;
  28471. }
  28472. LineCurve.prototype = Object.create(Curve.prototype);
  28473. LineCurve.prototype.constructor = LineCurve;
  28474. LineCurve.prototype.isLineCurve = true;
  28475. LineCurve.prototype.getPoint = function (t, optionalTarget) {
  28476. if (optionalTarget === void 0) {
  28477. optionalTarget = new Vector2();
  28478. }
  28479. var point = optionalTarget;
  28480. if (t === 1) {
  28481. point.copy(this.v2);
  28482. } else {
  28483. point.copy(this.v2).sub(this.v1);
  28484. point.multiplyScalar(t).add(this.v1);
  28485. }
  28486. return point;
  28487. }; // Line curve is linear, so we can overwrite default getPointAt
  28488. LineCurve.prototype.getPointAt = function (u, optionalTarget) {
  28489. return this.getPoint(u, optionalTarget);
  28490. };
  28491. LineCurve.prototype.getTangent = function (t, optionalTarget) {
  28492. var tangent = optionalTarget || new Vector2();
  28493. tangent.copy(this.v2).sub(this.v1).normalize();
  28494. return tangent;
  28495. };
  28496. LineCurve.prototype.copy = function (source) {
  28497. Curve.prototype.copy.call(this, source);
  28498. this.v1.copy(source.v1);
  28499. this.v2.copy(source.v2);
  28500. return this;
  28501. };
  28502. LineCurve.prototype.toJSON = function () {
  28503. var data = Curve.prototype.toJSON.call(this);
  28504. data.v1 = this.v1.toArray();
  28505. data.v2 = this.v2.toArray();
  28506. return data;
  28507. };
  28508. LineCurve.prototype.fromJSON = function (json) {
  28509. Curve.prototype.fromJSON.call(this, json);
  28510. this.v1.fromArray(json.v1);
  28511. this.v2.fromArray(json.v2);
  28512. return this;
  28513. };
  28514. function LineCurve3(v1, v2) {
  28515. if (v1 === void 0) {
  28516. v1 = new Vector3();
  28517. }
  28518. if (v2 === void 0) {
  28519. v2 = new Vector3();
  28520. }
  28521. Curve.call(this);
  28522. this.type = 'LineCurve3';
  28523. this.v1 = v1;
  28524. this.v2 = v2;
  28525. }
  28526. LineCurve3.prototype = Object.create(Curve.prototype);
  28527. LineCurve3.prototype.constructor = LineCurve3;
  28528. LineCurve3.prototype.isLineCurve3 = true;
  28529. LineCurve3.prototype.getPoint = function (t, optionalTarget) {
  28530. if (optionalTarget === void 0) {
  28531. optionalTarget = new Vector3();
  28532. }
  28533. var point = optionalTarget;
  28534. if (t === 1) {
  28535. point.copy(this.v2);
  28536. } else {
  28537. point.copy(this.v2).sub(this.v1);
  28538. point.multiplyScalar(t).add(this.v1);
  28539. }
  28540. return point;
  28541. }; // Line curve is linear, so we can overwrite default getPointAt
  28542. LineCurve3.prototype.getPointAt = function (u, optionalTarget) {
  28543. return this.getPoint(u, optionalTarget);
  28544. };
  28545. LineCurve3.prototype.copy = function (source) {
  28546. Curve.prototype.copy.call(this, source);
  28547. this.v1.copy(source.v1);
  28548. this.v2.copy(source.v2);
  28549. return this;
  28550. };
  28551. LineCurve3.prototype.toJSON = function () {
  28552. var data = Curve.prototype.toJSON.call(this);
  28553. data.v1 = this.v1.toArray();
  28554. data.v2 = this.v2.toArray();
  28555. return data;
  28556. };
  28557. LineCurve3.prototype.fromJSON = function (json) {
  28558. Curve.prototype.fromJSON.call(this, json);
  28559. this.v1.fromArray(json.v1);
  28560. this.v2.fromArray(json.v2);
  28561. return this;
  28562. };
  28563. function QuadraticBezierCurve(v0, v1, v2) {
  28564. if (v0 === void 0) {
  28565. v0 = new Vector2();
  28566. }
  28567. if (v1 === void 0) {
  28568. v1 = new Vector2();
  28569. }
  28570. if (v2 === void 0) {
  28571. v2 = new Vector2();
  28572. }
  28573. Curve.call(this);
  28574. this.type = 'QuadraticBezierCurve';
  28575. this.v0 = v0;
  28576. this.v1 = v1;
  28577. this.v2 = v2;
  28578. }
  28579. QuadraticBezierCurve.prototype = Object.create(Curve.prototype);
  28580. QuadraticBezierCurve.prototype.constructor = QuadraticBezierCurve;
  28581. QuadraticBezierCurve.prototype.isQuadraticBezierCurve = true;
  28582. QuadraticBezierCurve.prototype.getPoint = function (t, optionalTarget) {
  28583. if (optionalTarget === void 0) {
  28584. optionalTarget = new Vector2();
  28585. }
  28586. var point = optionalTarget;
  28587. var v0 = this.v0,
  28588. v1 = this.v1,
  28589. v2 = this.v2;
  28590. point.set(QuadraticBezier(t, v0.x, v1.x, v2.x), QuadraticBezier(t, v0.y, v1.y, v2.y));
  28591. return point;
  28592. };
  28593. QuadraticBezierCurve.prototype.copy = function (source) {
  28594. Curve.prototype.copy.call(this, source);
  28595. this.v0.copy(source.v0);
  28596. this.v1.copy(source.v1);
  28597. this.v2.copy(source.v2);
  28598. return this;
  28599. };
  28600. QuadraticBezierCurve.prototype.toJSON = function () {
  28601. var data = Curve.prototype.toJSON.call(this);
  28602. data.v0 = this.v0.toArray();
  28603. data.v1 = this.v1.toArray();
  28604. data.v2 = this.v2.toArray();
  28605. return data;
  28606. };
  28607. QuadraticBezierCurve.prototype.fromJSON = function (json) {
  28608. Curve.prototype.fromJSON.call(this, json);
  28609. this.v0.fromArray(json.v0);
  28610. this.v1.fromArray(json.v1);
  28611. this.v2.fromArray(json.v2);
  28612. return this;
  28613. };
  28614. function QuadraticBezierCurve3(v0, v1, v2) {
  28615. if (v0 === void 0) {
  28616. v0 = new Vector3();
  28617. }
  28618. if (v1 === void 0) {
  28619. v1 = new Vector3();
  28620. }
  28621. if (v2 === void 0) {
  28622. v2 = new Vector3();
  28623. }
  28624. Curve.call(this);
  28625. this.type = 'QuadraticBezierCurve3';
  28626. this.v0 = v0;
  28627. this.v1 = v1;
  28628. this.v2 = v2;
  28629. }
  28630. QuadraticBezierCurve3.prototype = Object.create(Curve.prototype);
  28631. QuadraticBezierCurve3.prototype.constructor = QuadraticBezierCurve3;
  28632. QuadraticBezierCurve3.prototype.isQuadraticBezierCurve3 = true;
  28633. QuadraticBezierCurve3.prototype.getPoint = function (t, optionalTarget) {
  28634. if (optionalTarget === void 0) {
  28635. optionalTarget = new Vector3();
  28636. }
  28637. var point = optionalTarget;
  28638. var v0 = this.v0,
  28639. v1 = this.v1,
  28640. v2 = this.v2;
  28641. point.set(QuadraticBezier(t, v0.x, v1.x, v2.x), QuadraticBezier(t, v0.y, v1.y, v2.y), QuadraticBezier(t, v0.z, v1.z, v2.z));
  28642. return point;
  28643. };
  28644. QuadraticBezierCurve3.prototype.copy = function (source) {
  28645. Curve.prototype.copy.call(this, source);
  28646. this.v0.copy(source.v0);
  28647. this.v1.copy(source.v1);
  28648. this.v2.copy(source.v2);
  28649. return this;
  28650. };
  28651. QuadraticBezierCurve3.prototype.toJSON = function () {
  28652. var data = Curve.prototype.toJSON.call(this);
  28653. data.v0 = this.v0.toArray();
  28654. data.v1 = this.v1.toArray();
  28655. data.v2 = this.v2.toArray();
  28656. return data;
  28657. };
  28658. QuadraticBezierCurve3.prototype.fromJSON = function (json) {
  28659. Curve.prototype.fromJSON.call(this, json);
  28660. this.v0.fromArray(json.v0);
  28661. this.v1.fromArray(json.v1);
  28662. this.v2.fromArray(json.v2);
  28663. return this;
  28664. };
  28665. function SplineCurve(points) {
  28666. if (points === void 0) {
  28667. points = [];
  28668. }
  28669. Curve.call(this);
  28670. this.type = 'SplineCurve';
  28671. this.points = points;
  28672. }
  28673. SplineCurve.prototype = Object.create(Curve.prototype);
  28674. SplineCurve.prototype.constructor = SplineCurve;
  28675. SplineCurve.prototype.isSplineCurve = true;
  28676. SplineCurve.prototype.getPoint = function (t, optionalTarget) {
  28677. if (optionalTarget === void 0) {
  28678. optionalTarget = new Vector2();
  28679. }
  28680. var point = optionalTarget;
  28681. var points = this.points;
  28682. var p = (points.length - 1) * t;
  28683. var intPoint = Math.floor(p);
  28684. var weight = p - intPoint;
  28685. var p0 = points[intPoint === 0 ? intPoint : intPoint - 1];
  28686. var p1 = points[intPoint];
  28687. var p2 = points[intPoint > points.length - 2 ? points.length - 1 : intPoint + 1];
  28688. var p3 = points[intPoint > points.length - 3 ? points.length - 1 : intPoint + 2];
  28689. point.set(CatmullRom(weight, p0.x, p1.x, p2.x, p3.x), CatmullRom(weight, p0.y, p1.y, p2.y, p3.y));
  28690. return point;
  28691. };
  28692. SplineCurve.prototype.copy = function (source) {
  28693. Curve.prototype.copy.call(this, source);
  28694. this.points = [];
  28695. for (var i = 0, l = source.points.length; i < l; i++) {
  28696. var point = source.points[i];
  28697. this.points.push(point.clone());
  28698. }
  28699. return this;
  28700. };
  28701. SplineCurve.prototype.toJSON = function () {
  28702. var data = Curve.prototype.toJSON.call(this);
  28703. data.points = [];
  28704. for (var i = 0, l = this.points.length; i < l; i++) {
  28705. var point = this.points[i];
  28706. data.points.push(point.toArray());
  28707. }
  28708. return data;
  28709. };
  28710. SplineCurve.prototype.fromJSON = function (json) {
  28711. Curve.prototype.fromJSON.call(this, json);
  28712. this.points = [];
  28713. for (var i = 0, l = json.points.length; i < l; i++) {
  28714. var point = json.points[i];
  28715. this.points.push(new Vector2().fromArray(point));
  28716. }
  28717. return this;
  28718. };
  28719. var Curves = /*#__PURE__*/Object.freeze({
  28720. __proto__: null,
  28721. ArcCurve: ArcCurve,
  28722. CatmullRomCurve3: CatmullRomCurve3,
  28723. CubicBezierCurve: CubicBezierCurve,
  28724. CubicBezierCurve3: CubicBezierCurve3,
  28725. EllipseCurve: EllipseCurve,
  28726. LineCurve: LineCurve,
  28727. LineCurve3: LineCurve3,
  28728. QuadraticBezierCurve: QuadraticBezierCurve,
  28729. QuadraticBezierCurve3: QuadraticBezierCurve3,
  28730. SplineCurve: SplineCurve
  28731. });
  28732. /**************************************************************
  28733. * Curved Path - a curve path is simply a array of connected
  28734. * curves, but retains the api of a curve
  28735. **************************************************************/
  28736. function CurvePath() {
  28737. Curve.call(this);
  28738. this.type = 'CurvePath';
  28739. this.curves = [];
  28740. this.autoClose = false; // Automatically closes the path
  28741. }
  28742. CurvePath.prototype = Object.assign(Object.create(Curve.prototype), {
  28743. constructor: CurvePath,
  28744. add: function add(curve) {
  28745. this.curves.push(curve);
  28746. },
  28747. closePath: function closePath() {
  28748. // Add a line curve if start and end of lines are not connected
  28749. var startPoint = this.curves[0].getPoint(0);
  28750. var endPoint = this.curves[this.curves.length - 1].getPoint(1);
  28751. if (!startPoint.equals(endPoint)) {
  28752. this.curves.push(new LineCurve(endPoint, startPoint));
  28753. }
  28754. },
  28755. // To get accurate point with reference to
  28756. // entire path distance at time t,
  28757. // following has to be done:
  28758. // 1. Length of each sub path have to be known
  28759. // 2. Locate and identify type of curve
  28760. // 3. Get t for the curve
  28761. // 4. Return curve.getPointAt(t')
  28762. getPoint: function getPoint(t) {
  28763. var d = t * this.getLength();
  28764. var curveLengths = this.getCurveLengths();
  28765. var i = 0; // To think about boundaries points.
  28766. while (i < curveLengths.length) {
  28767. if (curveLengths[i] >= d) {
  28768. var diff = curveLengths[i] - d;
  28769. var curve = this.curves[i];
  28770. var segmentLength = curve.getLength();
  28771. var u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;
  28772. return curve.getPointAt(u);
  28773. }
  28774. i++;
  28775. }
  28776. return null; // loop where sum != 0, sum > d , sum+1 <d
  28777. },
  28778. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  28779. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  28780. // getPoint() depends on getLength
  28781. getLength: function getLength() {
  28782. var lens = this.getCurveLengths();
  28783. return lens[lens.length - 1];
  28784. },
  28785. // cacheLengths must be recalculated.
  28786. updateArcLengths: function updateArcLengths() {
  28787. this.needsUpdate = true;
  28788. this.cacheLengths = null;
  28789. this.getCurveLengths();
  28790. },
  28791. // Compute lengths and cache them
  28792. // We cannot overwrite getLengths() because UtoT mapping uses it.
  28793. getCurveLengths: function getCurveLengths() {
  28794. // We use cache values if curves and cache array are same length
  28795. if (this.cacheLengths && this.cacheLengths.length === this.curves.length) {
  28796. return this.cacheLengths;
  28797. } // Get length of sub-curve
  28798. // Push sums into cached array
  28799. var lengths = [];
  28800. var sums = 0;
  28801. for (var i = 0, l = this.curves.length; i < l; i++) {
  28802. sums += this.curves[i].getLength();
  28803. lengths.push(sums);
  28804. }
  28805. this.cacheLengths = lengths;
  28806. return lengths;
  28807. },
  28808. getSpacedPoints: function getSpacedPoints(divisions) {
  28809. if (divisions === void 0) {
  28810. divisions = 40;
  28811. }
  28812. var points = [];
  28813. for (var i = 0; i <= divisions; i++) {
  28814. points.push(this.getPoint(i / divisions));
  28815. }
  28816. if (this.autoClose) {
  28817. points.push(points[0]);
  28818. }
  28819. return points;
  28820. },
  28821. getPoints: function getPoints(divisions) {
  28822. if (divisions === void 0) {
  28823. divisions = 12;
  28824. }
  28825. var points = [];
  28826. var last;
  28827. for (var i = 0, curves = this.curves; i < curves.length; i++) {
  28828. var curve = curves[i];
  28829. var resolution = curve && curve.isEllipseCurve ? divisions * 2 : curve && (curve.isLineCurve || curve.isLineCurve3) ? 1 : curve && curve.isSplineCurve ? divisions * curve.points.length : divisions;
  28830. var pts = curve.getPoints(resolution);
  28831. for (var j = 0; j < pts.length; j++) {
  28832. var point = pts[j];
  28833. if (last && last.equals(point)) continue; // ensures no consecutive points are duplicates
  28834. points.push(point);
  28835. last = point;
  28836. }
  28837. }
  28838. if (this.autoClose && points.length > 1 && !points[points.length - 1].equals(points[0])) {
  28839. points.push(points[0]);
  28840. }
  28841. return points;
  28842. },
  28843. copy: function copy(source) {
  28844. Curve.prototype.copy.call(this, source);
  28845. this.curves = [];
  28846. for (var i = 0, l = source.curves.length; i < l; i++) {
  28847. var curve = source.curves[i];
  28848. this.curves.push(curve.clone());
  28849. }
  28850. this.autoClose = source.autoClose;
  28851. return this;
  28852. },
  28853. toJSON: function toJSON() {
  28854. var data = Curve.prototype.toJSON.call(this);
  28855. data.autoClose = this.autoClose;
  28856. data.curves = [];
  28857. for (var i = 0, l = this.curves.length; i < l; i++) {
  28858. var curve = this.curves[i];
  28859. data.curves.push(curve.toJSON());
  28860. }
  28861. return data;
  28862. },
  28863. fromJSON: function fromJSON(json) {
  28864. Curve.prototype.fromJSON.call(this, json);
  28865. this.autoClose = json.autoClose;
  28866. this.curves = [];
  28867. for (var i = 0, l = json.curves.length; i < l; i++) {
  28868. var curve = json.curves[i];
  28869. this.curves.push(new Curves[curve.type]().fromJSON(curve));
  28870. }
  28871. return this;
  28872. }
  28873. });
  28874. function Path(points) {
  28875. CurvePath.call(this);
  28876. this.type = 'Path';
  28877. this.currentPoint = new Vector2();
  28878. if (points) {
  28879. this.setFromPoints(points);
  28880. }
  28881. }
  28882. Path.prototype = Object.assign(Object.create(CurvePath.prototype), {
  28883. constructor: Path,
  28884. setFromPoints: function setFromPoints(points) {
  28885. this.moveTo(points[0].x, points[0].y);
  28886. for (var i = 1, l = points.length; i < l; i++) {
  28887. this.lineTo(points[i].x, points[i].y);
  28888. }
  28889. return this;
  28890. },
  28891. moveTo: function moveTo(x, y) {
  28892. this.currentPoint.set(x, y); // TODO consider referencing vectors instead of copying?
  28893. return this;
  28894. },
  28895. lineTo: function lineTo(x, y) {
  28896. var curve = new LineCurve(this.currentPoint.clone(), new Vector2(x, y));
  28897. this.curves.push(curve);
  28898. this.currentPoint.set(x, y);
  28899. return this;
  28900. },
  28901. quadraticCurveTo: function quadraticCurveTo(aCPx, aCPy, aX, aY) {
  28902. var curve = new QuadraticBezierCurve(this.currentPoint.clone(), new Vector2(aCPx, aCPy), new Vector2(aX, aY));
  28903. this.curves.push(curve);
  28904. this.currentPoint.set(aX, aY);
  28905. return this;
  28906. },
  28907. bezierCurveTo: function bezierCurveTo(aCP1x, aCP1y, aCP2x, aCP2y, aX, aY) {
  28908. var curve = new CubicBezierCurve(this.currentPoint.clone(), new Vector2(aCP1x, aCP1y), new Vector2(aCP2x, aCP2y), new Vector2(aX, aY));
  28909. this.curves.push(curve);
  28910. this.currentPoint.set(aX, aY);
  28911. return this;
  28912. },
  28913. splineThru: function splineThru(pts
  28914. /*Array of Vector*/
  28915. ) {
  28916. var npts = [this.currentPoint.clone()].concat(pts);
  28917. var curve = new SplineCurve(npts);
  28918. this.curves.push(curve);
  28919. this.currentPoint.copy(pts[pts.length - 1]);
  28920. return this;
  28921. },
  28922. arc: function arc(aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) {
  28923. var x0 = this.currentPoint.x;
  28924. var y0 = this.currentPoint.y;
  28925. this.absarc(aX + x0, aY + y0, aRadius, aStartAngle, aEndAngle, aClockwise);
  28926. return this;
  28927. },
  28928. absarc: function absarc(aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) {
  28929. this.absellipse(aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise);
  28930. return this;
  28931. },
  28932. ellipse: function ellipse(aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation) {
  28933. var x0 = this.currentPoint.x;
  28934. var y0 = this.currentPoint.y;
  28935. this.absellipse(aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation);
  28936. return this;
  28937. },
  28938. absellipse: function absellipse(aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation) {
  28939. var curve = new EllipseCurve(aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation);
  28940. if (this.curves.length > 0) {
  28941. // if a previous curve is present, attempt to join
  28942. var firstPoint = curve.getPoint(0);
  28943. if (!firstPoint.equals(this.currentPoint)) {
  28944. this.lineTo(firstPoint.x, firstPoint.y);
  28945. }
  28946. }
  28947. this.curves.push(curve);
  28948. var lastPoint = curve.getPoint(1);
  28949. this.currentPoint.copy(lastPoint);
  28950. return this;
  28951. },
  28952. copy: function copy(source) {
  28953. CurvePath.prototype.copy.call(this, source);
  28954. this.currentPoint.copy(source.currentPoint);
  28955. return this;
  28956. },
  28957. toJSON: function toJSON() {
  28958. var data = CurvePath.prototype.toJSON.call(this);
  28959. data.currentPoint = this.currentPoint.toArray();
  28960. return data;
  28961. },
  28962. fromJSON: function fromJSON(json) {
  28963. CurvePath.prototype.fromJSON.call(this, json);
  28964. this.currentPoint.fromArray(json.currentPoint);
  28965. return this;
  28966. }
  28967. });
  28968. function Shape(points) {
  28969. Path.call(this, points);
  28970. this.uuid = MathUtils.generateUUID();
  28971. this.type = 'Shape';
  28972. this.holes = [];
  28973. }
  28974. Shape.prototype = Object.assign(Object.create(Path.prototype), {
  28975. constructor: Shape,
  28976. getPointsHoles: function getPointsHoles(divisions) {
  28977. var holesPts = [];
  28978. for (var i = 0, l = this.holes.length; i < l; i++) {
  28979. holesPts[i] = this.holes[i].getPoints(divisions);
  28980. }
  28981. return holesPts;
  28982. },
  28983. // get points of shape and holes (keypoints based on segments parameter)
  28984. extractPoints: function extractPoints(divisions) {
  28985. return {
  28986. shape: this.getPoints(divisions),
  28987. holes: this.getPointsHoles(divisions)
  28988. };
  28989. },
  28990. copy: function copy(source) {
  28991. Path.prototype.copy.call(this, source);
  28992. this.holes = [];
  28993. for (var i = 0, l = source.holes.length; i < l; i++) {
  28994. var hole = source.holes[i];
  28995. this.holes.push(hole.clone());
  28996. }
  28997. return this;
  28998. },
  28999. toJSON: function toJSON() {
  29000. var data = Path.prototype.toJSON.call(this);
  29001. data.uuid = this.uuid;
  29002. data.holes = [];
  29003. for (var i = 0, l = this.holes.length; i < l; i++) {
  29004. var hole = this.holes[i];
  29005. data.holes.push(hole.toJSON());
  29006. }
  29007. return data;
  29008. },
  29009. fromJSON: function fromJSON(json) {
  29010. Path.prototype.fromJSON.call(this, json);
  29011. this.uuid = json.uuid;
  29012. this.holes = [];
  29013. for (var i = 0, l = json.holes.length; i < l; i++) {
  29014. var hole = json.holes[i];
  29015. this.holes.push(new Path().fromJSON(hole));
  29016. }
  29017. return this;
  29018. }
  29019. });
  29020. function Light(color, intensity) {
  29021. if (intensity === void 0) {
  29022. intensity = 1;
  29023. }
  29024. Object3D.call(this);
  29025. this.type = 'Light';
  29026. this.color = new Color(color);
  29027. this.intensity = intensity;
  29028. }
  29029. Light.prototype = Object.assign(Object.create(Object3D.prototype), {
  29030. constructor: Light,
  29031. isLight: true,
  29032. copy: function copy(source) {
  29033. Object3D.prototype.copy.call(this, source);
  29034. this.color.copy(source.color);
  29035. this.intensity = source.intensity;
  29036. return this;
  29037. },
  29038. toJSON: function toJSON(meta) {
  29039. var data = Object3D.prototype.toJSON.call(this, meta);
  29040. data.object.color = this.color.getHex();
  29041. data.object.intensity = this.intensity;
  29042. if (this.groundColor !== undefined) data.object.groundColor = this.groundColor.getHex();
  29043. if (this.distance !== undefined) data.object.distance = this.distance;
  29044. if (this.angle !== undefined) data.object.angle = this.angle;
  29045. if (this.decay !== undefined) data.object.decay = this.decay;
  29046. if (this.penumbra !== undefined) data.object.penumbra = this.penumbra;
  29047. if (this.shadow !== undefined) data.object.shadow = this.shadow.toJSON();
  29048. return data;
  29049. }
  29050. });
  29051. function HemisphereLight(skyColor, groundColor, intensity) {
  29052. Light.call(this, skyColor, intensity);
  29053. this.type = 'HemisphereLight';
  29054. this.position.copy(Object3D.DefaultUp);
  29055. this.updateMatrix();
  29056. this.groundColor = new Color(groundColor);
  29057. }
  29058. HemisphereLight.prototype = Object.assign(Object.create(Light.prototype), {
  29059. constructor: HemisphereLight,
  29060. isHemisphereLight: true,
  29061. copy: function copy(source) {
  29062. Light.prototype.copy.call(this, source);
  29063. this.groundColor.copy(source.groundColor);
  29064. return this;
  29065. }
  29066. });
  29067. function LightShadow(camera) {
  29068. this.camera = camera;
  29069. this.bias = 0;
  29070. this.normalBias = 0;
  29071. this.radius = 1;
  29072. this.mapSize = new Vector2(512, 512);
  29073. this.map = null;
  29074. this.mapPass = null;
  29075. this.matrix = new Matrix4();
  29076. this.autoUpdate = true;
  29077. this.needsUpdate = false;
  29078. this._frustum = new Frustum();
  29079. this._frameExtents = new Vector2(1, 1);
  29080. this._viewportCount = 1;
  29081. this._viewports = [new Vector4(0, 0, 1, 1)];
  29082. }
  29083. Object.assign(LightShadow.prototype, {
  29084. _projScreenMatrix: new Matrix4(),
  29085. _lightPositionWorld: new Vector3(),
  29086. _lookTarget: new Vector3(),
  29087. getViewportCount: function getViewportCount() {
  29088. return this._viewportCount;
  29089. },
  29090. getFrustum: function getFrustum() {
  29091. return this._frustum;
  29092. },
  29093. updateMatrices: function updateMatrices(light) {
  29094. var shadowCamera = this.camera,
  29095. shadowMatrix = this.matrix,
  29096. projScreenMatrix = this._projScreenMatrix,
  29097. lookTarget = this._lookTarget,
  29098. lightPositionWorld = this._lightPositionWorld;
  29099. lightPositionWorld.setFromMatrixPosition(light.matrixWorld);
  29100. shadowCamera.position.copy(lightPositionWorld);
  29101. lookTarget.setFromMatrixPosition(light.target.matrixWorld);
  29102. shadowCamera.lookAt(lookTarget);
  29103. shadowCamera.updateMatrixWorld();
  29104. projScreenMatrix.multiplyMatrices(shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse);
  29105. this._frustum.setFromProjectionMatrix(projScreenMatrix);
  29106. shadowMatrix.set(0.5, 0.0, 0.0, 0.5, 0.0, 0.5, 0.0, 0.5, 0.0, 0.0, 0.5, 0.5, 0.0, 0.0, 0.0, 1.0);
  29107. shadowMatrix.multiply(shadowCamera.projectionMatrix);
  29108. shadowMatrix.multiply(shadowCamera.matrixWorldInverse);
  29109. },
  29110. getViewport: function getViewport(viewportIndex) {
  29111. return this._viewports[viewportIndex];
  29112. },
  29113. getFrameExtents: function getFrameExtents() {
  29114. return this._frameExtents;
  29115. },
  29116. copy: function copy(source) {
  29117. this.camera = source.camera.clone();
  29118. this.bias = source.bias;
  29119. this.radius = source.radius;
  29120. this.mapSize.copy(source.mapSize);
  29121. return this;
  29122. },
  29123. clone: function clone() {
  29124. return new this.constructor().copy(this);
  29125. },
  29126. toJSON: function toJSON() {
  29127. var object = {};
  29128. if (this.bias !== 0) object.bias = this.bias;
  29129. if (this.normalBias !== 0) object.normalBias = this.normalBias;
  29130. if (this.radius !== 1) object.radius = this.radius;
  29131. if (this.mapSize.x !== 512 || this.mapSize.y !== 512) object.mapSize = this.mapSize.toArray();
  29132. object.camera = this.camera.toJSON(false).object;
  29133. delete object.camera.matrix;
  29134. return object;
  29135. }
  29136. });
  29137. function SpotLightShadow() {
  29138. LightShadow.call(this, new PerspectiveCamera(50, 1, 0.5, 500));
  29139. this.focus = 1;
  29140. }
  29141. SpotLightShadow.prototype = Object.assign(Object.create(LightShadow.prototype), {
  29142. constructor: SpotLightShadow,
  29143. isSpotLightShadow: true,
  29144. updateMatrices: function updateMatrices(light) {
  29145. var camera = this.camera;
  29146. var fov = MathUtils.RAD2DEG * 2 * light.angle * this.focus;
  29147. var aspect = this.mapSize.width / this.mapSize.height;
  29148. var far = light.distance || camera.far;
  29149. if (fov !== camera.fov || aspect !== camera.aspect || far !== camera.far) {
  29150. camera.fov = fov;
  29151. camera.aspect = aspect;
  29152. camera.far = far;
  29153. camera.updateProjectionMatrix();
  29154. }
  29155. LightShadow.prototype.updateMatrices.call(this, light);
  29156. }
  29157. });
  29158. function SpotLight(color, intensity, distance, angle, penumbra, decay) {
  29159. Light.call(this, color, intensity);
  29160. this.type = 'SpotLight';
  29161. this.position.copy(Object3D.DefaultUp);
  29162. this.updateMatrix();
  29163. this.target = new Object3D();
  29164. Object.defineProperty(this, 'power', {
  29165. get: function get() {
  29166. // intensity = power per solid angle.
  29167. // ref: equation (17) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  29168. return this.intensity * Math.PI;
  29169. },
  29170. set: function set(power) {
  29171. // intensity = power per solid angle.
  29172. // ref: equation (17) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  29173. this.intensity = power / Math.PI;
  29174. }
  29175. });
  29176. this.distance = distance !== undefined ? distance : 0;
  29177. this.angle = angle !== undefined ? angle : Math.PI / 3;
  29178. this.penumbra = penumbra !== undefined ? penumbra : 0;
  29179. this.decay = decay !== undefined ? decay : 1; // for physically correct lights, should be 2.
  29180. this.shadow = new SpotLightShadow();
  29181. }
  29182. SpotLight.prototype = Object.assign(Object.create(Light.prototype), {
  29183. constructor: SpotLight,
  29184. isSpotLight: true,
  29185. copy: function copy(source) {
  29186. Light.prototype.copy.call(this, source);
  29187. this.distance = source.distance;
  29188. this.angle = source.angle;
  29189. this.penumbra = source.penumbra;
  29190. this.decay = source.decay;
  29191. this.target = source.target.clone();
  29192. this.shadow = source.shadow.clone();
  29193. return this;
  29194. }
  29195. });
  29196. function PointLightShadow() {
  29197. LightShadow.call(this, new PerspectiveCamera(90, 1, 0.5, 500));
  29198. this._frameExtents = new Vector2(4, 2);
  29199. this._viewportCount = 6;
  29200. this._viewports = [// These viewports map a cube-map onto a 2D texture with the
  29201. // following orientation:
  29202. //
  29203. // xzXZ
  29204. // y Y
  29205. //
  29206. // X - Positive x direction
  29207. // x - Negative x direction
  29208. // Y - Positive y direction
  29209. // y - Negative y direction
  29210. // Z - Positive z direction
  29211. // z - Negative z direction
  29212. // positive X
  29213. new Vector4(2, 1, 1, 1), // negative X
  29214. new Vector4(0, 1, 1, 1), // positive Z
  29215. new Vector4(3, 1, 1, 1), // negative Z
  29216. new Vector4(1, 1, 1, 1), // positive Y
  29217. new Vector4(3, 0, 1, 1), // negative Y
  29218. new Vector4(1, 0, 1, 1)];
  29219. this._cubeDirections = [new Vector3(1, 0, 0), new Vector3(-1, 0, 0), new Vector3(0, 0, 1), new Vector3(0, 0, -1), new Vector3(0, 1, 0), new Vector3(0, -1, 0)];
  29220. this._cubeUps = [new Vector3(0, 1, 0), new Vector3(0, 1, 0), new Vector3(0, 1, 0), new Vector3(0, 1, 0), new Vector3(0, 0, 1), new Vector3(0, 0, -1)];
  29221. }
  29222. PointLightShadow.prototype = Object.assign(Object.create(LightShadow.prototype), {
  29223. constructor: PointLightShadow,
  29224. isPointLightShadow: true,
  29225. updateMatrices: function updateMatrices(light, viewportIndex) {
  29226. if (viewportIndex === void 0) {
  29227. viewportIndex = 0;
  29228. }
  29229. var camera = this.camera,
  29230. shadowMatrix = this.matrix,
  29231. lightPositionWorld = this._lightPositionWorld,
  29232. lookTarget = this._lookTarget,
  29233. projScreenMatrix = this._projScreenMatrix;
  29234. lightPositionWorld.setFromMatrixPosition(light.matrixWorld);
  29235. camera.position.copy(lightPositionWorld);
  29236. lookTarget.copy(camera.position);
  29237. lookTarget.add(this._cubeDirections[viewportIndex]);
  29238. camera.up.copy(this._cubeUps[viewportIndex]);
  29239. camera.lookAt(lookTarget);
  29240. camera.updateMatrixWorld();
  29241. shadowMatrix.makeTranslation(-lightPositionWorld.x, -lightPositionWorld.y, -lightPositionWorld.z);
  29242. projScreenMatrix.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse);
  29243. this._frustum.setFromProjectionMatrix(projScreenMatrix);
  29244. }
  29245. });
  29246. function PointLight(color, intensity, distance, decay) {
  29247. Light.call(this, color, intensity);
  29248. this.type = 'PointLight';
  29249. Object.defineProperty(this, 'power', {
  29250. get: function get() {
  29251. // intensity = power per solid angle.
  29252. // ref: equation (15) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  29253. return this.intensity * 4 * Math.PI;
  29254. },
  29255. set: function set(power) {
  29256. // intensity = power per solid angle.
  29257. // ref: equation (15) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  29258. this.intensity = power / (4 * Math.PI);
  29259. }
  29260. });
  29261. this.distance = distance !== undefined ? distance : 0;
  29262. this.decay = decay !== undefined ? decay : 1; // for physically correct lights, should be 2.
  29263. this.shadow = new PointLightShadow();
  29264. }
  29265. PointLight.prototype = Object.assign(Object.create(Light.prototype), {
  29266. constructor: PointLight,
  29267. isPointLight: true,
  29268. copy: function copy(source) {
  29269. Light.prototype.copy.call(this, source);
  29270. this.distance = source.distance;
  29271. this.decay = source.decay;
  29272. this.shadow = source.shadow.clone();
  29273. return this;
  29274. }
  29275. });
  29276. function OrthographicCamera(left, right, top, bottom, near, far) {
  29277. if (left === void 0) {
  29278. left = -1;
  29279. }
  29280. if (right === void 0) {
  29281. right = 1;
  29282. }
  29283. if (top === void 0) {
  29284. top = 1;
  29285. }
  29286. if (bottom === void 0) {
  29287. bottom = -1;
  29288. }
  29289. if (near === void 0) {
  29290. near = 0.1;
  29291. }
  29292. if (far === void 0) {
  29293. far = 2000;
  29294. }
  29295. Camera.call(this);
  29296. this.type = 'OrthographicCamera';
  29297. this.zoom = 1;
  29298. this.view = null;
  29299. this.left = left;
  29300. this.right = right;
  29301. this.top = top;
  29302. this.bottom = bottom;
  29303. this.near = near;
  29304. this.far = far;
  29305. this.updateProjectionMatrix();
  29306. }
  29307. OrthographicCamera.prototype = Object.assign(Object.create(Camera.prototype), {
  29308. constructor: OrthographicCamera,
  29309. isOrthographicCamera: true,
  29310. copy: function copy(source, recursive) {
  29311. Camera.prototype.copy.call(this, source, recursive);
  29312. this.left = source.left;
  29313. this.right = source.right;
  29314. this.top = source.top;
  29315. this.bottom = source.bottom;
  29316. this.near = source.near;
  29317. this.far = source.far;
  29318. this.zoom = source.zoom;
  29319. this.view = source.view === null ? null : Object.assign({}, source.view);
  29320. return this;
  29321. },
  29322. setViewOffset: function setViewOffset(fullWidth, fullHeight, x, y, width, height) {
  29323. if (this.view === null) {
  29324. this.view = {
  29325. enabled: true,
  29326. fullWidth: 1,
  29327. fullHeight: 1,
  29328. offsetX: 0,
  29329. offsetY: 0,
  29330. width: 1,
  29331. height: 1
  29332. };
  29333. }
  29334. this.view.enabled = true;
  29335. this.view.fullWidth = fullWidth;
  29336. this.view.fullHeight = fullHeight;
  29337. this.view.offsetX = x;
  29338. this.view.offsetY = y;
  29339. this.view.width = width;
  29340. this.view.height = height;
  29341. this.updateProjectionMatrix();
  29342. },
  29343. clearViewOffset: function clearViewOffset() {
  29344. if (this.view !== null) {
  29345. this.view.enabled = false;
  29346. }
  29347. this.updateProjectionMatrix();
  29348. },
  29349. updateProjectionMatrix: function updateProjectionMatrix() {
  29350. var dx = (this.right - this.left) / (2 * this.zoom);
  29351. var dy = (this.top - this.bottom) / (2 * this.zoom);
  29352. var cx = (this.right + this.left) / 2;
  29353. var cy = (this.top + this.bottom) / 2;
  29354. var left = cx - dx;
  29355. var right = cx + dx;
  29356. var top = cy + dy;
  29357. var bottom = cy - dy;
  29358. if (this.view !== null && this.view.enabled) {
  29359. var scaleW = (this.right - this.left) / this.view.fullWidth / this.zoom;
  29360. var scaleH = (this.top - this.bottom) / this.view.fullHeight / this.zoom;
  29361. left += scaleW * this.view.offsetX;
  29362. right = left + scaleW * this.view.width;
  29363. top -= scaleH * this.view.offsetY;
  29364. bottom = top - scaleH * this.view.height;
  29365. }
  29366. this.projectionMatrix.makeOrthographic(left, right, top, bottom, this.near, this.far);
  29367. this.projectionMatrixInverse.copy(this.projectionMatrix).invert();
  29368. },
  29369. toJSON: function toJSON(meta) {
  29370. var data = Object3D.prototype.toJSON.call(this, meta);
  29371. data.object.zoom = this.zoom;
  29372. data.object.left = this.left;
  29373. data.object.right = this.right;
  29374. data.object.top = this.top;
  29375. data.object.bottom = this.bottom;
  29376. data.object.near = this.near;
  29377. data.object.far = this.far;
  29378. if (this.view !== null) data.object.view = Object.assign({}, this.view);
  29379. return data;
  29380. }
  29381. });
  29382. function DirectionalLightShadow() {
  29383. LightShadow.call(this, new OrthographicCamera(-5, 5, 5, -5, 0.5, 500));
  29384. }
  29385. DirectionalLightShadow.prototype = Object.assign(Object.create(LightShadow.prototype), {
  29386. constructor: DirectionalLightShadow,
  29387. isDirectionalLightShadow: true,
  29388. updateMatrices: function updateMatrices(light) {
  29389. LightShadow.prototype.updateMatrices.call(this, light);
  29390. }
  29391. });
  29392. function DirectionalLight(color, intensity) {
  29393. Light.call(this, color, intensity);
  29394. this.type = 'DirectionalLight';
  29395. this.position.copy(Object3D.DefaultUp);
  29396. this.updateMatrix();
  29397. this.target = new Object3D();
  29398. this.shadow = new DirectionalLightShadow();
  29399. }
  29400. DirectionalLight.prototype = Object.assign(Object.create(Light.prototype), {
  29401. constructor: DirectionalLight,
  29402. isDirectionalLight: true,
  29403. copy: function copy(source) {
  29404. Light.prototype.copy.call(this, source);
  29405. this.target = source.target.clone();
  29406. this.shadow = source.shadow.clone();
  29407. return this;
  29408. }
  29409. });
  29410. function AmbientLight(color, intensity) {
  29411. Light.call(this, color, intensity);
  29412. this.type = 'AmbientLight';
  29413. }
  29414. AmbientLight.prototype = Object.assign(Object.create(Light.prototype), {
  29415. constructor: AmbientLight,
  29416. isAmbientLight: true
  29417. });
  29418. function RectAreaLight(color, intensity, width, height) {
  29419. Light.call(this, color, intensity);
  29420. this.type = 'RectAreaLight';
  29421. this.width = width !== undefined ? width : 10;
  29422. this.height = height !== undefined ? height : 10;
  29423. }
  29424. RectAreaLight.prototype = Object.assign(Object.create(Light.prototype), {
  29425. constructor: RectAreaLight,
  29426. isRectAreaLight: true,
  29427. copy: function copy(source) {
  29428. Light.prototype.copy.call(this, source);
  29429. this.width = source.width;
  29430. this.height = source.height;
  29431. return this;
  29432. },
  29433. toJSON: function toJSON(meta) {
  29434. var data = Light.prototype.toJSON.call(this, meta);
  29435. data.object.width = this.width;
  29436. data.object.height = this.height;
  29437. return data;
  29438. }
  29439. });
  29440. /**
  29441. * Primary reference:
  29442. * https://graphics.stanford.edu/papers/envmap/envmap.pdf
  29443. *
  29444. * Secondary reference:
  29445. * https://www.ppsloan.org/publications/StupidSH36.pdf
  29446. */
  29447. // 3-band SH defined by 9 coefficients
  29448. var SphericalHarmonics3 = /*#__PURE__*/function () {
  29449. function SphericalHarmonics3() {
  29450. Object.defineProperty(this, 'isSphericalHarmonics3', {
  29451. value: true
  29452. });
  29453. this.coefficients = [];
  29454. for (var i = 0; i < 9; i++) {
  29455. this.coefficients.push(new Vector3());
  29456. }
  29457. }
  29458. var _proto = SphericalHarmonics3.prototype;
  29459. _proto.set = function set(coefficients) {
  29460. for (var i = 0; i < 9; i++) {
  29461. this.coefficients[i].copy(coefficients[i]);
  29462. }
  29463. return this;
  29464. };
  29465. _proto.zero = function zero() {
  29466. for (var i = 0; i < 9; i++) {
  29467. this.coefficients[i].set(0, 0, 0);
  29468. }
  29469. return this;
  29470. } // get the radiance in the direction of the normal
  29471. // target is a Vector3
  29472. ;
  29473. _proto.getAt = function getAt(normal, target) {
  29474. // normal is assumed to be unit length
  29475. var x = normal.x,
  29476. y = normal.y,
  29477. z = normal.z;
  29478. var coeff = this.coefficients; // band 0
  29479. target.copy(coeff[0]).multiplyScalar(0.282095); // band 1
  29480. target.addScaledVector(coeff[1], 0.488603 * y);
  29481. target.addScaledVector(coeff[2], 0.488603 * z);
  29482. target.addScaledVector(coeff[3], 0.488603 * x); // band 2
  29483. target.addScaledVector(coeff[4], 1.092548 * (x * y));
  29484. target.addScaledVector(coeff[5], 1.092548 * (y * z));
  29485. target.addScaledVector(coeff[6], 0.315392 * (3.0 * z * z - 1.0));
  29486. target.addScaledVector(coeff[7], 1.092548 * (x * z));
  29487. target.addScaledVector(coeff[8], 0.546274 * (x * x - y * y));
  29488. return target;
  29489. } // get the irradiance (radiance convolved with cosine lobe) in the direction of the normal
  29490. // target is a Vector3
  29491. // https://graphics.stanford.edu/papers/envmap/envmap.pdf
  29492. ;
  29493. _proto.getIrradianceAt = function getIrradianceAt(normal, target) {
  29494. // normal is assumed to be unit length
  29495. var x = normal.x,
  29496. y = normal.y,
  29497. z = normal.z;
  29498. var coeff = this.coefficients; // band 0
  29499. target.copy(coeff[0]).multiplyScalar(0.886227); // π * 0.282095
  29500. // band 1
  29501. target.addScaledVector(coeff[1], 2.0 * 0.511664 * y); // ( 2 * π / 3 ) * 0.488603
  29502. target.addScaledVector(coeff[2], 2.0 * 0.511664 * z);
  29503. target.addScaledVector(coeff[3], 2.0 * 0.511664 * x); // band 2
  29504. target.addScaledVector(coeff[4], 2.0 * 0.429043 * x * y); // ( π / 4 ) * 1.092548
  29505. target.addScaledVector(coeff[5], 2.0 * 0.429043 * y * z);
  29506. target.addScaledVector(coeff[6], 0.743125 * z * z - 0.247708); // ( π / 4 ) * 0.315392 * 3
  29507. target.addScaledVector(coeff[7], 2.0 * 0.429043 * x * z);
  29508. target.addScaledVector(coeff[8], 0.429043 * (x * x - y * y)); // ( π / 4 ) * 0.546274
  29509. return target;
  29510. };
  29511. _proto.add = function add(sh) {
  29512. for (var i = 0; i < 9; i++) {
  29513. this.coefficients[i].add(sh.coefficients[i]);
  29514. }
  29515. return this;
  29516. };
  29517. _proto.addScaledSH = function addScaledSH(sh, s) {
  29518. for (var i = 0; i < 9; i++) {
  29519. this.coefficients[i].addScaledVector(sh.coefficients[i], s);
  29520. }
  29521. return this;
  29522. };
  29523. _proto.scale = function scale(s) {
  29524. for (var i = 0; i < 9; i++) {
  29525. this.coefficients[i].multiplyScalar(s);
  29526. }
  29527. return this;
  29528. };
  29529. _proto.lerp = function lerp(sh, alpha) {
  29530. for (var i = 0; i < 9; i++) {
  29531. this.coefficients[i].lerp(sh.coefficients[i], alpha);
  29532. }
  29533. return this;
  29534. };
  29535. _proto.equals = function equals(sh) {
  29536. for (var i = 0; i < 9; i++) {
  29537. if (!this.coefficients[i].equals(sh.coefficients[i])) {
  29538. return false;
  29539. }
  29540. }
  29541. return true;
  29542. };
  29543. _proto.copy = function copy(sh) {
  29544. return this.set(sh.coefficients);
  29545. };
  29546. _proto.clone = function clone() {
  29547. return new this.constructor().copy(this);
  29548. };
  29549. _proto.fromArray = function fromArray(array, offset) {
  29550. if (offset === void 0) {
  29551. offset = 0;
  29552. }
  29553. var coefficients = this.coefficients;
  29554. for (var i = 0; i < 9; i++) {
  29555. coefficients[i].fromArray(array, offset + i * 3);
  29556. }
  29557. return this;
  29558. };
  29559. _proto.toArray = function toArray(array, offset) {
  29560. if (array === void 0) {
  29561. array = [];
  29562. }
  29563. if (offset === void 0) {
  29564. offset = 0;
  29565. }
  29566. var coefficients = this.coefficients;
  29567. for (var i = 0; i < 9; i++) {
  29568. coefficients[i].toArray(array, offset + i * 3);
  29569. }
  29570. return array;
  29571. } // evaluate the basis functions
  29572. // shBasis is an Array[ 9 ]
  29573. ;
  29574. SphericalHarmonics3.getBasisAt = function getBasisAt(normal, shBasis) {
  29575. // normal is assumed to be unit length
  29576. var x = normal.x,
  29577. y = normal.y,
  29578. z = normal.z; // band 0
  29579. shBasis[0] = 0.282095; // band 1
  29580. shBasis[1] = 0.488603 * y;
  29581. shBasis[2] = 0.488603 * z;
  29582. shBasis[3] = 0.488603 * x; // band 2
  29583. shBasis[4] = 1.092548 * x * y;
  29584. shBasis[5] = 1.092548 * y * z;
  29585. shBasis[6] = 0.315392 * (3 * z * z - 1);
  29586. shBasis[7] = 1.092548 * x * z;
  29587. shBasis[8] = 0.546274 * (x * x - y * y);
  29588. };
  29589. return SphericalHarmonics3;
  29590. }();
  29591. function LightProbe(sh, intensity) {
  29592. Light.call(this, undefined, intensity);
  29593. this.type = 'LightProbe';
  29594. this.sh = sh !== undefined ? sh : new SphericalHarmonics3();
  29595. }
  29596. LightProbe.prototype = Object.assign(Object.create(Light.prototype), {
  29597. constructor: LightProbe,
  29598. isLightProbe: true,
  29599. copy: function copy(source) {
  29600. Light.prototype.copy.call(this, source);
  29601. this.sh.copy(source.sh);
  29602. return this;
  29603. },
  29604. fromJSON: function fromJSON(json) {
  29605. this.intensity = json.intensity; // TODO: Move this bit to Light.fromJSON();
  29606. this.sh.fromArray(json.sh);
  29607. return this;
  29608. },
  29609. toJSON: function toJSON(meta) {
  29610. var data = Light.prototype.toJSON.call(this, meta);
  29611. data.object.sh = this.sh.toArray();
  29612. return data;
  29613. }
  29614. });
  29615. function MaterialLoader(manager) {
  29616. Loader.call(this, manager);
  29617. this.textures = {};
  29618. }
  29619. MaterialLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  29620. constructor: MaterialLoader,
  29621. load: function load(url, onLoad, onProgress, onError) {
  29622. var scope = this;
  29623. var loader = new FileLoader(scope.manager);
  29624. loader.setPath(scope.path);
  29625. loader.setRequestHeader(scope.requestHeader);
  29626. loader.setWithCredentials(scope.withCredentials);
  29627. loader.load(url, function (text) {
  29628. try {
  29629. onLoad(scope.parse(JSON.parse(text)));
  29630. } catch (e) {
  29631. if (onError) {
  29632. onError(e);
  29633. } else {
  29634. console.error(e);
  29635. }
  29636. scope.manager.itemError(url);
  29637. }
  29638. }, onProgress, onError);
  29639. },
  29640. parse: function parse(json) {
  29641. var textures = this.textures;
  29642. function getTexture(name) {
  29643. if (textures[name] === undefined) {
  29644. console.warn('THREE.MaterialLoader: Undefined texture', name);
  29645. }
  29646. return textures[name];
  29647. }
  29648. var material = new Materials[json.type]();
  29649. if (json.uuid !== undefined) material.uuid = json.uuid;
  29650. if (json.name !== undefined) material.name = json.name;
  29651. if (json.color !== undefined && material.color !== undefined) material.color.setHex(json.color);
  29652. if (json.roughness !== undefined) material.roughness = json.roughness;
  29653. if (json.metalness !== undefined) material.metalness = json.metalness;
  29654. if (json.sheen !== undefined) material.sheen = new Color().setHex(json.sheen);
  29655. if (json.emissive !== undefined && material.emissive !== undefined) material.emissive.setHex(json.emissive);
  29656. if (json.specular !== undefined && material.specular !== undefined) material.specular.setHex(json.specular);
  29657. if (json.shininess !== undefined) material.shininess = json.shininess;
  29658. if (json.clearcoat !== undefined) material.clearcoat = json.clearcoat;
  29659. if (json.clearcoatRoughness !== undefined) material.clearcoatRoughness = json.clearcoatRoughness;
  29660. if (json.fog !== undefined) material.fog = json.fog;
  29661. if (json.flatShading !== undefined) material.flatShading = json.flatShading;
  29662. if (json.blending !== undefined) material.blending = json.blending;
  29663. if (json.combine !== undefined) material.combine = json.combine;
  29664. if (json.side !== undefined) material.side = json.side;
  29665. if (json.opacity !== undefined) material.opacity = json.opacity;
  29666. if (json.transparent !== undefined) material.transparent = json.transparent;
  29667. if (json.alphaTest !== undefined) material.alphaTest = json.alphaTest;
  29668. if (json.depthTest !== undefined) material.depthTest = json.depthTest;
  29669. if (json.depthWrite !== undefined) material.depthWrite = json.depthWrite;
  29670. if (json.colorWrite !== undefined) material.colorWrite = json.colorWrite;
  29671. if (json.stencilWrite !== undefined) material.stencilWrite = json.stencilWrite;
  29672. if (json.stencilWriteMask !== undefined) material.stencilWriteMask = json.stencilWriteMask;
  29673. if (json.stencilFunc !== undefined) material.stencilFunc = json.stencilFunc;
  29674. if (json.stencilRef !== undefined) material.stencilRef = json.stencilRef;
  29675. if (json.stencilFuncMask !== undefined) material.stencilFuncMask = json.stencilFuncMask;
  29676. if (json.stencilFail !== undefined) material.stencilFail = json.stencilFail;
  29677. if (json.stencilZFail !== undefined) material.stencilZFail = json.stencilZFail;
  29678. if (json.stencilZPass !== undefined) material.stencilZPass = json.stencilZPass;
  29679. if (json.wireframe !== undefined) material.wireframe = json.wireframe;
  29680. if (json.wireframeLinewidth !== undefined) material.wireframeLinewidth = json.wireframeLinewidth;
  29681. if (json.wireframeLinecap !== undefined) material.wireframeLinecap = json.wireframeLinecap;
  29682. if (json.wireframeLinejoin !== undefined) material.wireframeLinejoin = json.wireframeLinejoin;
  29683. if (json.rotation !== undefined) material.rotation = json.rotation;
  29684. if (json.linewidth !== 1) material.linewidth = json.linewidth;
  29685. if (json.dashSize !== undefined) material.dashSize = json.dashSize;
  29686. if (json.gapSize !== undefined) material.gapSize = json.gapSize;
  29687. if (json.scale !== undefined) material.scale = json.scale;
  29688. if (json.polygonOffset !== undefined) material.polygonOffset = json.polygonOffset;
  29689. if (json.polygonOffsetFactor !== undefined) material.polygonOffsetFactor = json.polygonOffsetFactor;
  29690. if (json.polygonOffsetUnits !== undefined) material.polygonOffsetUnits = json.polygonOffsetUnits;
  29691. if (json.skinning !== undefined) material.skinning = json.skinning;
  29692. if (json.morphTargets !== undefined) material.morphTargets = json.morphTargets;
  29693. if (json.morphNormals !== undefined) material.morphNormals = json.morphNormals;
  29694. if (json.dithering !== undefined) material.dithering = json.dithering;
  29695. if (json.vertexTangents !== undefined) material.vertexTangents = json.vertexTangents;
  29696. if (json.visible !== undefined) material.visible = json.visible;
  29697. if (json.toneMapped !== undefined) material.toneMapped = json.toneMapped;
  29698. if (json.userData !== undefined) material.userData = json.userData;
  29699. if (json.vertexColors !== undefined) {
  29700. if (typeof json.vertexColors === 'number') {
  29701. material.vertexColors = json.vertexColors > 0 ? true : false;
  29702. } else {
  29703. material.vertexColors = json.vertexColors;
  29704. }
  29705. } // Shader Material
  29706. if (json.uniforms !== undefined) {
  29707. for (var name in json.uniforms) {
  29708. var uniform = json.uniforms[name];
  29709. material.uniforms[name] = {};
  29710. switch (uniform.type) {
  29711. case 't':
  29712. material.uniforms[name].value = getTexture(uniform.value);
  29713. break;
  29714. case 'c':
  29715. material.uniforms[name].value = new Color().setHex(uniform.value);
  29716. break;
  29717. case 'v2':
  29718. material.uniforms[name].value = new Vector2().fromArray(uniform.value);
  29719. break;
  29720. case 'v3':
  29721. material.uniforms[name].value = new Vector3().fromArray(uniform.value);
  29722. break;
  29723. case 'v4':
  29724. material.uniforms[name].value = new Vector4().fromArray(uniform.value);
  29725. break;
  29726. case 'm3':
  29727. material.uniforms[name].value = new Matrix3().fromArray(uniform.value);
  29728. break;
  29729. case 'm4':
  29730. material.uniforms[name].value = new Matrix4().fromArray(uniform.value);
  29731. break;
  29732. default:
  29733. material.uniforms[name].value = uniform.value;
  29734. }
  29735. }
  29736. }
  29737. if (json.defines !== undefined) material.defines = json.defines;
  29738. if (json.vertexShader !== undefined) material.vertexShader = json.vertexShader;
  29739. if (json.fragmentShader !== undefined) material.fragmentShader = json.fragmentShader;
  29740. if (json.extensions !== undefined) {
  29741. for (var key in json.extensions) {
  29742. material.extensions[key] = json.extensions[key];
  29743. }
  29744. } // Deprecated
  29745. if (json.shading !== undefined) material.flatShading = json.shading === 1; // THREE.FlatShading
  29746. // for PointsMaterial
  29747. if (json.size !== undefined) material.size = json.size;
  29748. if (json.sizeAttenuation !== undefined) material.sizeAttenuation = json.sizeAttenuation; // maps
  29749. if (json.map !== undefined) material.map = getTexture(json.map);
  29750. if (json.matcap !== undefined) material.matcap = getTexture(json.matcap);
  29751. if (json.alphaMap !== undefined) material.alphaMap = getTexture(json.alphaMap);
  29752. if (json.bumpMap !== undefined) material.bumpMap = getTexture(json.bumpMap);
  29753. if (json.bumpScale !== undefined) material.bumpScale = json.bumpScale;
  29754. if (json.normalMap !== undefined) material.normalMap = getTexture(json.normalMap);
  29755. if (json.normalMapType !== undefined) material.normalMapType = json.normalMapType;
  29756. if (json.normalScale !== undefined) {
  29757. var normalScale = json.normalScale;
  29758. if (Array.isArray(normalScale) === false) {
  29759. // Blender exporter used to export a scalar. See #7459
  29760. normalScale = [normalScale, normalScale];
  29761. }
  29762. material.normalScale = new Vector2().fromArray(normalScale);
  29763. }
  29764. if (json.displacementMap !== undefined) material.displacementMap = getTexture(json.displacementMap);
  29765. if (json.displacementScale !== undefined) material.displacementScale = json.displacementScale;
  29766. if (json.displacementBias !== undefined) material.displacementBias = json.displacementBias;
  29767. if (json.roughnessMap !== undefined) material.roughnessMap = getTexture(json.roughnessMap);
  29768. if (json.metalnessMap !== undefined) material.metalnessMap = getTexture(json.metalnessMap);
  29769. if (json.emissiveMap !== undefined) material.emissiveMap = getTexture(json.emissiveMap);
  29770. if (json.emissiveIntensity !== undefined) material.emissiveIntensity = json.emissiveIntensity;
  29771. if (json.specularMap !== undefined) material.specularMap = getTexture(json.specularMap);
  29772. if (json.envMap !== undefined) material.envMap = getTexture(json.envMap);
  29773. if (json.envMapIntensity !== undefined) material.envMapIntensity = json.envMapIntensity;
  29774. if (json.reflectivity !== undefined) material.reflectivity = json.reflectivity;
  29775. if (json.refractionRatio !== undefined) material.refractionRatio = json.refractionRatio;
  29776. if (json.lightMap !== undefined) material.lightMap = getTexture(json.lightMap);
  29777. if (json.lightMapIntensity !== undefined) material.lightMapIntensity = json.lightMapIntensity;
  29778. if (json.aoMap !== undefined) material.aoMap = getTexture(json.aoMap);
  29779. if (json.aoMapIntensity !== undefined) material.aoMapIntensity = json.aoMapIntensity;
  29780. if (json.gradientMap !== undefined) material.gradientMap = getTexture(json.gradientMap);
  29781. if (json.clearcoatMap !== undefined) material.clearcoatMap = getTexture(json.clearcoatMap);
  29782. if (json.clearcoatRoughnessMap !== undefined) material.clearcoatRoughnessMap = getTexture(json.clearcoatRoughnessMap);
  29783. if (json.clearcoatNormalMap !== undefined) material.clearcoatNormalMap = getTexture(json.clearcoatNormalMap);
  29784. if (json.clearcoatNormalScale !== undefined) material.clearcoatNormalScale = new Vector2().fromArray(json.clearcoatNormalScale);
  29785. if (json.transmission !== undefined) material.transmission = json.transmission;
  29786. if (json.transmissionMap !== undefined) material.transmissionMap = getTexture(json.transmissionMap);
  29787. return material;
  29788. },
  29789. setTextures: function setTextures(value) {
  29790. this.textures = value;
  29791. return this;
  29792. }
  29793. });
  29794. var LoaderUtils = {
  29795. decodeText: function decodeText(array) {
  29796. if (typeof TextDecoder !== 'undefined') {
  29797. return new TextDecoder().decode(array);
  29798. } // Avoid the String.fromCharCode.apply(null, array) shortcut, which
  29799. // throws a "maximum call stack size exceeded" error for large arrays.
  29800. var s = '';
  29801. for (var i = 0, il = array.length; i < il; i++) {
  29802. // Implicitly assumes little-endian.
  29803. s += String.fromCharCode(array[i]);
  29804. }
  29805. try {
  29806. // merges multi-byte utf-8 characters.
  29807. return decodeURIComponent(escape(s));
  29808. } catch (e) {
  29809. // see #16358
  29810. return s;
  29811. }
  29812. },
  29813. extractUrlBase: function extractUrlBase(url) {
  29814. var index = url.lastIndexOf('/');
  29815. if (index === -1) return './';
  29816. return url.substr(0, index + 1);
  29817. }
  29818. };
  29819. function InstancedBufferGeometry() {
  29820. BufferGeometry.call(this);
  29821. this.type = 'InstancedBufferGeometry';
  29822. this.instanceCount = Infinity;
  29823. }
  29824. InstancedBufferGeometry.prototype = Object.assign(Object.create(BufferGeometry.prototype), {
  29825. constructor: InstancedBufferGeometry,
  29826. isInstancedBufferGeometry: true,
  29827. copy: function copy(source) {
  29828. BufferGeometry.prototype.copy.call(this, source);
  29829. this.instanceCount = source.instanceCount;
  29830. return this;
  29831. },
  29832. clone: function clone() {
  29833. return new this.constructor().copy(this);
  29834. },
  29835. toJSON: function toJSON() {
  29836. var data = BufferGeometry.prototype.toJSON.call(this);
  29837. data.instanceCount = this.instanceCount;
  29838. data.isInstancedBufferGeometry = true;
  29839. return data;
  29840. }
  29841. });
  29842. function InstancedBufferAttribute(array, itemSize, normalized, meshPerAttribute) {
  29843. if (typeof normalized === 'number') {
  29844. meshPerAttribute = normalized;
  29845. normalized = false;
  29846. console.error('THREE.InstancedBufferAttribute: The constructor now expects normalized as the third argument.');
  29847. }
  29848. BufferAttribute.call(this, array, itemSize, normalized);
  29849. this.meshPerAttribute = meshPerAttribute || 1;
  29850. }
  29851. InstancedBufferAttribute.prototype = Object.assign(Object.create(BufferAttribute.prototype), {
  29852. constructor: InstancedBufferAttribute,
  29853. isInstancedBufferAttribute: true,
  29854. copy: function copy(source) {
  29855. BufferAttribute.prototype.copy.call(this, source);
  29856. this.meshPerAttribute = source.meshPerAttribute;
  29857. return this;
  29858. },
  29859. toJSON: function toJSON() {
  29860. var data = BufferAttribute.prototype.toJSON.call(this);
  29861. data.meshPerAttribute = this.meshPerAttribute;
  29862. data.isInstancedBufferAttribute = true;
  29863. return data;
  29864. }
  29865. });
  29866. function BufferGeometryLoader(manager) {
  29867. Loader.call(this, manager);
  29868. }
  29869. BufferGeometryLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  29870. constructor: BufferGeometryLoader,
  29871. load: function load(url, onLoad, onProgress, onError) {
  29872. var scope = this;
  29873. var loader = new FileLoader(scope.manager);
  29874. loader.setPath(scope.path);
  29875. loader.setRequestHeader(scope.requestHeader);
  29876. loader.setWithCredentials(scope.withCredentials);
  29877. loader.load(url, function (text) {
  29878. try {
  29879. onLoad(scope.parse(JSON.parse(text)));
  29880. } catch (e) {
  29881. if (onError) {
  29882. onError(e);
  29883. } else {
  29884. console.error(e);
  29885. }
  29886. scope.manager.itemError(url);
  29887. }
  29888. }, onProgress, onError);
  29889. },
  29890. parse: function parse(json) {
  29891. var interleavedBufferMap = {};
  29892. var arrayBufferMap = {};
  29893. function getInterleavedBuffer(json, uuid) {
  29894. if (interleavedBufferMap[uuid] !== undefined) return interleavedBufferMap[uuid];
  29895. var interleavedBuffers = json.interleavedBuffers;
  29896. var interleavedBuffer = interleavedBuffers[uuid];
  29897. var buffer = getArrayBuffer(json, interleavedBuffer.buffer);
  29898. var array = getTypedArray(interleavedBuffer.type, buffer);
  29899. var ib = new InterleavedBuffer(array, interleavedBuffer.stride);
  29900. ib.uuid = interleavedBuffer.uuid;
  29901. interleavedBufferMap[uuid] = ib;
  29902. return ib;
  29903. }
  29904. function getArrayBuffer(json, uuid) {
  29905. if (arrayBufferMap[uuid] !== undefined) return arrayBufferMap[uuid];
  29906. var arrayBuffers = json.arrayBuffers;
  29907. var arrayBuffer = arrayBuffers[uuid];
  29908. var ab = new Uint32Array(arrayBuffer).buffer;
  29909. arrayBufferMap[uuid] = ab;
  29910. return ab;
  29911. }
  29912. var geometry = json.isInstancedBufferGeometry ? new InstancedBufferGeometry() : new BufferGeometry();
  29913. var index = json.data.index;
  29914. if (index !== undefined) {
  29915. var typedArray = getTypedArray(index.type, index.array);
  29916. geometry.setIndex(new BufferAttribute(typedArray, 1));
  29917. }
  29918. var attributes = json.data.attributes;
  29919. for (var key in attributes) {
  29920. var attribute = attributes[key];
  29921. var bufferAttribute = void 0;
  29922. if (attribute.isInterleavedBufferAttribute) {
  29923. var interleavedBuffer = getInterleavedBuffer(json.data, attribute.data);
  29924. bufferAttribute = new InterleavedBufferAttribute(interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized);
  29925. } else {
  29926. var _typedArray = getTypedArray(attribute.type, attribute.array);
  29927. var bufferAttributeConstr = attribute.isInstancedBufferAttribute ? InstancedBufferAttribute : BufferAttribute;
  29928. bufferAttribute = new bufferAttributeConstr(_typedArray, attribute.itemSize, attribute.normalized);
  29929. }
  29930. if (attribute.name !== undefined) bufferAttribute.name = attribute.name;
  29931. geometry.setAttribute(key, bufferAttribute);
  29932. }
  29933. var morphAttributes = json.data.morphAttributes;
  29934. if (morphAttributes) {
  29935. for (var _key in morphAttributes) {
  29936. var attributeArray = morphAttributes[_key];
  29937. var array = [];
  29938. for (var i = 0, il = attributeArray.length; i < il; i++) {
  29939. var _attribute = attributeArray[i];
  29940. var _bufferAttribute = void 0;
  29941. if (_attribute.isInterleavedBufferAttribute) {
  29942. var _interleavedBuffer = getInterleavedBuffer(json.data, _attribute.data);
  29943. _bufferAttribute = new InterleavedBufferAttribute(_interleavedBuffer, _attribute.itemSize, _attribute.offset, _attribute.normalized);
  29944. } else {
  29945. var _typedArray2 = getTypedArray(_attribute.type, _attribute.array);
  29946. _bufferAttribute = new BufferAttribute(_typedArray2, _attribute.itemSize, _attribute.normalized);
  29947. }
  29948. if (_attribute.name !== undefined) _bufferAttribute.name = _attribute.name;
  29949. array.push(_bufferAttribute);
  29950. }
  29951. geometry.morphAttributes[_key] = array;
  29952. }
  29953. }
  29954. var morphTargetsRelative = json.data.morphTargetsRelative;
  29955. if (morphTargetsRelative) {
  29956. geometry.morphTargetsRelative = true;
  29957. }
  29958. var groups = json.data.groups || json.data.drawcalls || json.data.offsets;
  29959. if (groups !== undefined) {
  29960. for (var _i = 0, n = groups.length; _i !== n; ++_i) {
  29961. var group = groups[_i];
  29962. geometry.addGroup(group.start, group.count, group.materialIndex);
  29963. }
  29964. }
  29965. var boundingSphere = json.data.boundingSphere;
  29966. if (boundingSphere !== undefined) {
  29967. var center = new Vector3();
  29968. if (boundingSphere.center !== undefined) {
  29969. center.fromArray(boundingSphere.center);
  29970. }
  29971. geometry.boundingSphere = new Sphere(center, boundingSphere.radius);
  29972. }
  29973. if (json.name) geometry.name = json.name;
  29974. if (json.userData) geometry.userData = json.userData;
  29975. return geometry;
  29976. }
  29977. });
  29978. var ObjectLoader = /*#__PURE__*/function (_Loader) {
  29979. _inheritsLoose(ObjectLoader, _Loader);
  29980. function ObjectLoader(manager) {
  29981. return _Loader.call(this, manager) || this;
  29982. }
  29983. var _proto = ObjectLoader.prototype;
  29984. _proto.load = function load(url, onLoad, onProgress, onError) {
  29985. var scope = this;
  29986. var path = this.path === '' ? LoaderUtils.extractUrlBase(url) : this.path;
  29987. this.resourcePath = this.resourcePath || path;
  29988. var loader = new FileLoader(this.manager);
  29989. loader.setPath(this.path);
  29990. loader.setRequestHeader(this.requestHeader);
  29991. loader.setWithCredentials(this.withCredentials);
  29992. loader.load(url, function (text) {
  29993. var json = null;
  29994. try {
  29995. json = JSON.parse(text);
  29996. } catch (error) {
  29997. if (onError !== undefined) onError(error);
  29998. console.error('THREE:ObjectLoader: Can\'t parse ' + url + '.', error.message);
  29999. return;
  30000. }
  30001. var metadata = json.metadata;
  30002. if (metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry') {
  30003. console.error('THREE.ObjectLoader: Can\'t load ' + url);
  30004. return;
  30005. }
  30006. scope.parse(json, onLoad);
  30007. }, onProgress, onError);
  30008. };
  30009. _proto.parse = function parse(json, onLoad) {
  30010. var animations = this.parseAnimations(json.animations);
  30011. var shapes = this.parseShapes(json.shapes);
  30012. var geometries = this.parseGeometries(json.geometries, shapes);
  30013. var images = this.parseImages(json.images, function () {
  30014. if (onLoad !== undefined) onLoad(object);
  30015. });
  30016. var textures = this.parseTextures(json.textures, images);
  30017. var materials = this.parseMaterials(json.materials, textures);
  30018. var object = this.parseObject(json.object, geometries, materials, animations);
  30019. var skeletons = this.parseSkeletons(json.skeletons, object);
  30020. this.bindSkeletons(object, skeletons); //
  30021. if (onLoad !== undefined) {
  30022. var hasImages = false;
  30023. for (var uuid in images) {
  30024. if (images[uuid] instanceof HTMLImageElement) {
  30025. hasImages = true;
  30026. break;
  30027. }
  30028. }
  30029. if (hasImages === false) onLoad(object);
  30030. }
  30031. return object;
  30032. };
  30033. _proto.parseShapes = function parseShapes(json) {
  30034. var shapes = {};
  30035. if (json !== undefined) {
  30036. for (var i = 0, l = json.length; i < l; i++) {
  30037. var shape = new Shape().fromJSON(json[i]);
  30038. shapes[shape.uuid] = shape;
  30039. }
  30040. }
  30041. return shapes;
  30042. };
  30043. _proto.parseSkeletons = function parseSkeletons(json, object) {
  30044. var skeletons = {};
  30045. var bones = {}; // generate bone lookup table
  30046. object.traverse(function (child) {
  30047. if (child.isBone) bones[child.uuid] = child;
  30048. }); // create skeletons
  30049. if (json !== undefined) {
  30050. for (var i = 0, l = json.length; i < l; i++) {
  30051. var skeleton = new Skeleton().fromJSON(json[i], bones);
  30052. skeletons[skeleton.uuid] = skeleton;
  30053. }
  30054. }
  30055. return skeletons;
  30056. };
  30057. _proto.parseGeometries = function parseGeometries(json, shapes) {
  30058. var geometries = {};
  30059. var geometryShapes;
  30060. if (json !== undefined) {
  30061. var bufferGeometryLoader = new BufferGeometryLoader();
  30062. for (var i = 0, l = json.length; i < l; i++) {
  30063. var geometry = void 0;
  30064. var data = json[i];
  30065. switch (data.type) {
  30066. case 'PlaneGeometry':
  30067. case 'PlaneBufferGeometry':
  30068. geometry = new Geometries[data.type](data.width, data.height, data.widthSegments, data.heightSegments);
  30069. break;
  30070. case 'BoxGeometry':
  30071. case 'BoxBufferGeometry':
  30072. geometry = new Geometries[data.type](data.width, data.height, data.depth, data.widthSegments, data.heightSegments, data.depthSegments);
  30073. break;
  30074. case 'CircleGeometry':
  30075. case 'CircleBufferGeometry':
  30076. geometry = new Geometries[data.type](data.radius, data.segments, data.thetaStart, data.thetaLength);
  30077. break;
  30078. case 'CylinderGeometry':
  30079. case 'CylinderBufferGeometry':
  30080. geometry = new Geometries[data.type](data.radiusTop, data.radiusBottom, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength);
  30081. break;
  30082. case 'ConeGeometry':
  30083. case 'ConeBufferGeometry':
  30084. geometry = new Geometries[data.type](data.radius, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength);
  30085. break;
  30086. case 'SphereGeometry':
  30087. case 'SphereBufferGeometry':
  30088. geometry = new Geometries[data.type](data.radius, data.widthSegments, data.heightSegments, data.phiStart, data.phiLength, data.thetaStart, data.thetaLength);
  30089. break;
  30090. case 'DodecahedronGeometry':
  30091. case 'DodecahedronBufferGeometry':
  30092. case 'IcosahedronGeometry':
  30093. case 'IcosahedronBufferGeometry':
  30094. case 'OctahedronGeometry':
  30095. case 'OctahedronBufferGeometry':
  30096. case 'TetrahedronGeometry':
  30097. case 'TetrahedronBufferGeometry':
  30098. geometry = new Geometries[data.type](data.radius, data.detail);
  30099. break;
  30100. case 'RingGeometry':
  30101. case 'RingBufferGeometry':
  30102. geometry = new Geometries[data.type](data.innerRadius, data.outerRadius, data.thetaSegments, data.phiSegments, data.thetaStart, data.thetaLength);
  30103. break;
  30104. case 'TorusGeometry':
  30105. case 'TorusBufferGeometry':
  30106. geometry = new Geometries[data.type](data.radius, data.tube, data.radialSegments, data.tubularSegments, data.arc);
  30107. break;
  30108. case 'TorusKnotGeometry':
  30109. case 'TorusKnotBufferGeometry':
  30110. geometry = new Geometries[data.type](data.radius, data.tube, data.tubularSegments, data.radialSegments, data.p, data.q);
  30111. break;
  30112. case 'TubeGeometry':
  30113. case 'TubeBufferGeometry':
  30114. // This only works for built-in curves (e.g. CatmullRomCurve3).
  30115. // User defined curves or instances of CurvePath will not be deserialized.
  30116. geometry = new Geometries[data.type](new Curves[data.path.type]().fromJSON(data.path), data.tubularSegments, data.radius, data.radialSegments, data.closed);
  30117. break;
  30118. case 'LatheGeometry':
  30119. case 'LatheBufferGeometry':
  30120. geometry = new Geometries[data.type](data.points, data.segments, data.phiStart, data.phiLength);
  30121. break;
  30122. case 'PolyhedronGeometry':
  30123. case 'PolyhedronBufferGeometry':
  30124. geometry = new Geometries[data.type](data.vertices, data.indices, data.radius, data.details);
  30125. break;
  30126. case 'ShapeGeometry':
  30127. case 'ShapeBufferGeometry':
  30128. geometryShapes = [];
  30129. for (var j = 0, jl = data.shapes.length; j < jl; j++) {
  30130. var shape = shapes[data.shapes[j]];
  30131. geometryShapes.push(shape);
  30132. }
  30133. geometry = new Geometries[data.type](geometryShapes, data.curveSegments);
  30134. break;
  30135. case 'ExtrudeGeometry':
  30136. case 'ExtrudeBufferGeometry':
  30137. geometryShapes = [];
  30138. for (var _j = 0, _jl = data.shapes.length; _j < _jl; _j++) {
  30139. var _shape = shapes[data.shapes[_j]];
  30140. geometryShapes.push(_shape);
  30141. }
  30142. var extrudePath = data.options.extrudePath;
  30143. if (extrudePath !== undefined) {
  30144. data.options.extrudePath = new Curves[extrudePath.type]().fromJSON(extrudePath);
  30145. }
  30146. geometry = new Geometries[data.type](geometryShapes, data.options);
  30147. break;
  30148. case 'BufferGeometry':
  30149. case 'InstancedBufferGeometry':
  30150. geometry = bufferGeometryLoader.parse(data);
  30151. break;
  30152. case 'Geometry':
  30153. if ('THREE' in window && 'LegacyJSONLoader' in THREE) {
  30154. var geometryLoader = new THREE.LegacyJSONLoader();
  30155. geometry = geometryLoader.parse(data, this.resourcePath).geometry;
  30156. } else {
  30157. console.error('THREE.ObjectLoader: You have to import LegacyJSONLoader in order load geometry data of type "Geometry".');
  30158. }
  30159. break;
  30160. default:
  30161. console.warn('THREE.ObjectLoader: Unsupported geometry type "' + data.type + '"');
  30162. continue;
  30163. }
  30164. geometry.uuid = data.uuid;
  30165. if (data.name !== undefined) geometry.name = data.name;
  30166. if (geometry.isBufferGeometry === true && data.userData !== undefined) geometry.userData = data.userData;
  30167. geometries[data.uuid] = geometry;
  30168. }
  30169. }
  30170. return geometries;
  30171. };
  30172. _proto.parseMaterials = function parseMaterials(json, textures) {
  30173. var cache = {}; // MultiMaterial
  30174. var materials = {};
  30175. if (json !== undefined) {
  30176. var loader = new MaterialLoader();
  30177. loader.setTextures(textures);
  30178. for (var i = 0, l = json.length; i < l; i++) {
  30179. var data = json[i];
  30180. if (data.type === 'MultiMaterial') {
  30181. // Deprecated
  30182. var array = [];
  30183. for (var j = 0; j < data.materials.length; j++) {
  30184. var material = data.materials[j];
  30185. if (cache[material.uuid] === undefined) {
  30186. cache[material.uuid] = loader.parse(material);
  30187. }
  30188. array.push(cache[material.uuid]);
  30189. }
  30190. materials[data.uuid] = array;
  30191. } else {
  30192. if (cache[data.uuid] === undefined) {
  30193. cache[data.uuid] = loader.parse(data);
  30194. }
  30195. materials[data.uuid] = cache[data.uuid];
  30196. }
  30197. }
  30198. }
  30199. return materials;
  30200. };
  30201. _proto.parseAnimations = function parseAnimations(json) {
  30202. var animations = {};
  30203. if (json !== undefined) {
  30204. for (var i = 0; i < json.length; i++) {
  30205. var data = json[i];
  30206. var clip = AnimationClip.parse(data);
  30207. animations[clip.uuid] = clip;
  30208. }
  30209. }
  30210. return animations;
  30211. };
  30212. _proto.parseImages = function parseImages(json, onLoad) {
  30213. var scope = this;
  30214. var images = {};
  30215. var loader;
  30216. function loadImage(url) {
  30217. scope.manager.itemStart(url);
  30218. return loader.load(url, function () {
  30219. scope.manager.itemEnd(url);
  30220. }, undefined, function () {
  30221. scope.manager.itemError(url);
  30222. scope.manager.itemEnd(url);
  30223. });
  30224. }
  30225. function deserializeImage(image) {
  30226. if (typeof image === 'string') {
  30227. var url = image;
  30228. var path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test(url) ? url : scope.resourcePath + url;
  30229. return loadImage(path);
  30230. } else {
  30231. if (image.data) {
  30232. return {
  30233. data: getTypedArray(image.type, image.data),
  30234. width: image.width,
  30235. height: image.height
  30236. };
  30237. } else {
  30238. return null;
  30239. }
  30240. }
  30241. }
  30242. if (json !== undefined && json.length > 0) {
  30243. var manager = new LoadingManager(onLoad);
  30244. loader = new ImageLoader(manager);
  30245. loader.setCrossOrigin(this.crossOrigin);
  30246. for (var i = 0, il = json.length; i < il; i++) {
  30247. var image = json[i];
  30248. var url = image.url;
  30249. if (Array.isArray(url)) {
  30250. // load array of images e.g CubeTexture
  30251. images[image.uuid] = [];
  30252. for (var j = 0, jl = url.length; j < jl; j++) {
  30253. var currentUrl = url[j];
  30254. var deserializedImage = deserializeImage(currentUrl);
  30255. if (deserializedImage !== null) {
  30256. if (deserializedImage instanceof HTMLImageElement) {
  30257. images[image.uuid].push(deserializedImage);
  30258. } else {
  30259. // special case: handle array of data textures for cube textures
  30260. images[image.uuid].push(new DataTexture(deserializedImage.data, deserializedImage.width, deserializedImage.height));
  30261. }
  30262. }
  30263. }
  30264. } else {
  30265. // load single image
  30266. var _deserializedImage = deserializeImage(image.url);
  30267. if (_deserializedImage !== null) {
  30268. images[image.uuid] = _deserializedImage;
  30269. }
  30270. }
  30271. }
  30272. }
  30273. return images;
  30274. };
  30275. _proto.parseTextures = function parseTextures(json, images) {
  30276. function parseConstant(value, type) {
  30277. if (typeof value === 'number') return value;
  30278. console.warn('THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value);
  30279. return type[value];
  30280. }
  30281. var textures = {};
  30282. if (json !== undefined) {
  30283. for (var i = 0, l = json.length; i < l; i++) {
  30284. var data = json[i];
  30285. if (data.image === undefined) {
  30286. console.warn('THREE.ObjectLoader: No "image" specified for', data.uuid);
  30287. }
  30288. if (images[data.image] === undefined) {
  30289. console.warn('THREE.ObjectLoader: Undefined image', data.image);
  30290. }
  30291. var texture = void 0;
  30292. var image = images[data.image];
  30293. if (Array.isArray(image)) {
  30294. texture = new CubeTexture(image);
  30295. if (image.length === 6) texture.needsUpdate = true;
  30296. } else {
  30297. if (image && image.data) {
  30298. texture = new DataTexture(image.data, image.width, image.height);
  30299. } else {
  30300. texture = new Texture(image);
  30301. }
  30302. if (image) texture.needsUpdate = true; // textures can have undefined image data
  30303. }
  30304. texture.uuid = data.uuid;
  30305. if (data.name !== undefined) texture.name = data.name;
  30306. if (data.mapping !== undefined) texture.mapping = parseConstant(data.mapping, TEXTURE_MAPPING);
  30307. if (data.offset !== undefined) texture.offset.fromArray(data.offset);
  30308. if (data.repeat !== undefined) texture.repeat.fromArray(data.repeat);
  30309. if (data.center !== undefined) texture.center.fromArray(data.center);
  30310. if (data.rotation !== undefined) texture.rotation = data.rotation;
  30311. if (data.wrap !== undefined) {
  30312. texture.wrapS = parseConstant(data.wrap[0], TEXTURE_WRAPPING);
  30313. texture.wrapT = parseConstant(data.wrap[1], TEXTURE_WRAPPING);
  30314. }
  30315. if (data.format !== undefined) texture.format = data.format;
  30316. if (data.type !== undefined) texture.type = data.type;
  30317. if (data.encoding !== undefined) texture.encoding = data.encoding;
  30318. if (data.minFilter !== undefined) texture.minFilter = parseConstant(data.minFilter, TEXTURE_FILTER);
  30319. if (data.magFilter !== undefined) texture.magFilter = parseConstant(data.magFilter, TEXTURE_FILTER);
  30320. if (data.anisotropy !== undefined) texture.anisotropy = data.anisotropy;
  30321. if (data.flipY !== undefined) texture.flipY = data.flipY;
  30322. if (data.premultiplyAlpha !== undefined) texture.premultiplyAlpha = data.premultiplyAlpha;
  30323. if (data.unpackAlignment !== undefined) texture.unpackAlignment = data.unpackAlignment;
  30324. textures[data.uuid] = texture;
  30325. }
  30326. }
  30327. return textures;
  30328. };
  30329. _proto.parseObject = function parseObject(data, geometries, materials, animations) {
  30330. var object;
  30331. function getGeometry(name) {
  30332. if (geometries[name] === undefined) {
  30333. console.warn('THREE.ObjectLoader: Undefined geometry', name);
  30334. }
  30335. return geometries[name];
  30336. }
  30337. function getMaterial(name) {
  30338. if (name === undefined) return undefined;
  30339. if (Array.isArray(name)) {
  30340. var array = [];
  30341. for (var i = 0, l = name.length; i < l; i++) {
  30342. var uuid = name[i];
  30343. if (materials[uuid] === undefined) {
  30344. console.warn('THREE.ObjectLoader: Undefined material', uuid);
  30345. }
  30346. array.push(materials[uuid]);
  30347. }
  30348. return array;
  30349. }
  30350. if (materials[name] === undefined) {
  30351. console.warn('THREE.ObjectLoader: Undefined material', name);
  30352. }
  30353. return materials[name];
  30354. }
  30355. var geometry, material;
  30356. switch (data.type) {
  30357. case 'Scene':
  30358. object = new Scene();
  30359. if (data.background !== undefined) {
  30360. if (Number.isInteger(data.background)) {
  30361. object.background = new Color(data.background);
  30362. }
  30363. }
  30364. if (data.fog !== undefined) {
  30365. if (data.fog.type === 'Fog') {
  30366. object.fog = new Fog(data.fog.color, data.fog.near, data.fog.far);
  30367. } else if (data.fog.type === 'FogExp2') {
  30368. object.fog = new FogExp2(data.fog.color, data.fog.density);
  30369. }
  30370. }
  30371. break;
  30372. case 'PerspectiveCamera':
  30373. object = new PerspectiveCamera(data.fov, data.aspect, data.near, data.far);
  30374. if (data.focus !== undefined) object.focus = data.focus;
  30375. if (data.zoom !== undefined) object.zoom = data.zoom;
  30376. if (data.filmGauge !== undefined) object.filmGauge = data.filmGauge;
  30377. if (data.filmOffset !== undefined) object.filmOffset = data.filmOffset;
  30378. if (data.view !== undefined) object.view = Object.assign({}, data.view);
  30379. break;
  30380. case 'OrthographicCamera':
  30381. object = new OrthographicCamera(data.left, data.right, data.top, data.bottom, data.near, data.far);
  30382. if (data.zoom !== undefined) object.zoom = data.zoom;
  30383. if (data.view !== undefined) object.view = Object.assign({}, data.view);
  30384. break;
  30385. case 'AmbientLight':
  30386. object = new AmbientLight(data.color, data.intensity);
  30387. break;
  30388. case 'DirectionalLight':
  30389. object = new DirectionalLight(data.color, data.intensity);
  30390. break;
  30391. case 'PointLight':
  30392. object = new PointLight(data.color, data.intensity, data.distance, data.decay);
  30393. break;
  30394. case 'RectAreaLight':
  30395. object = new RectAreaLight(data.color, data.intensity, data.width, data.height);
  30396. break;
  30397. case 'SpotLight':
  30398. object = new SpotLight(data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay);
  30399. break;
  30400. case 'HemisphereLight':
  30401. object = new HemisphereLight(data.color, data.groundColor, data.intensity);
  30402. break;
  30403. case 'LightProbe':
  30404. object = new LightProbe().fromJSON(data);
  30405. break;
  30406. case 'SkinnedMesh':
  30407. geometry = getGeometry(data.geometry);
  30408. material = getMaterial(data.material);
  30409. object = new SkinnedMesh(geometry, material);
  30410. if (data.bindMode !== undefined) object.bindMode = data.bindMode;
  30411. if (data.bindMatrix !== undefined) object.bindMatrix.fromArray(data.bindMatrix);
  30412. if (data.skeleton !== undefined) object.skeleton = data.skeleton;
  30413. break;
  30414. case 'Mesh':
  30415. geometry = getGeometry(data.geometry);
  30416. material = getMaterial(data.material);
  30417. object = new Mesh(geometry, material);
  30418. break;
  30419. case 'InstancedMesh':
  30420. geometry = getGeometry(data.geometry);
  30421. material = getMaterial(data.material);
  30422. var count = data.count;
  30423. var instanceMatrix = data.instanceMatrix;
  30424. object = new InstancedMesh(geometry, material, count);
  30425. object.instanceMatrix = new BufferAttribute(new Float32Array(instanceMatrix.array), 16);
  30426. break;
  30427. case 'LOD':
  30428. object = new LOD();
  30429. break;
  30430. case 'Line':
  30431. object = new Line(getGeometry(data.geometry), getMaterial(data.material));
  30432. break;
  30433. case 'LineLoop':
  30434. object = new LineLoop(getGeometry(data.geometry), getMaterial(data.material));
  30435. break;
  30436. case 'LineSegments':
  30437. object = new LineSegments(getGeometry(data.geometry), getMaterial(data.material));
  30438. break;
  30439. case 'PointCloud':
  30440. case 'Points':
  30441. object = new Points(getGeometry(data.geometry), getMaterial(data.material));
  30442. break;
  30443. case 'Sprite':
  30444. object = new Sprite(getMaterial(data.material));
  30445. break;
  30446. case 'Group':
  30447. object = new Group();
  30448. break;
  30449. case 'Bone':
  30450. object = new Bone();
  30451. break;
  30452. default:
  30453. object = new Object3D();
  30454. }
  30455. object.uuid = data.uuid;
  30456. if (data.name !== undefined) object.name = data.name;
  30457. if (data.matrix !== undefined) {
  30458. object.matrix.fromArray(data.matrix);
  30459. if (data.matrixAutoUpdate !== undefined) object.matrixAutoUpdate = data.matrixAutoUpdate;
  30460. if (object.matrixAutoUpdate) object.matrix.decompose(object.position, object.quaternion, object.scale);
  30461. } else {
  30462. if (data.position !== undefined) object.position.fromArray(data.position);
  30463. if (data.rotation !== undefined) object.rotation.fromArray(data.rotation);
  30464. if (data.quaternion !== undefined) object.quaternion.fromArray(data.quaternion);
  30465. if (data.scale !== undefined) object.scale.fromArray(data.scale);
  30466. }
  30467. if (data.castShadow !== undefined) object.castShadow = data.castShadow;
  30468. if (data.receiveShadow !== undefined) object.receiveShadow = data.receiveShadow;
  30469. if (data.shadow) {
  30470. if (data.shadow.bias !== undefined) object.shadow.bias = data.shadow.bias;
  30471. if (data.shadow.normalBias !== undefined) object.shadow.normalBias = data.shadow.normalBias;
  30472. if (data.shadow.radius !== undefined) object.shadow.radius = data.shadow.radius;
  30473. if (data.shadow.mapSize !== undefined) object.shadow.mapSize.fromArray(data.shadow.mapSize);
  30474. if (data.shadow.camera !== undefined) object.shadow.camera = this.parseObject(data.shadow.camera);
  30475. }
  30476. if (data.visible !== undefined) object.visible = data.visible;
  30477. if (data.frustumCulled !== undefined) object.frustumCulled = data.frustumCulled;
  30478. if (data.renderOrder !== undefined) object.renderOrder = data.renderOrder;
  30479. if (data.userData !== undefined) object.userData = data.userData;
  30480. if (data.layers !== undefined) object.layers.mask = data.layers;
  30481. if (data.children !== undefined) {
  30482. var children = data.children;
  30483. for (var i = 0; i < children.length; i++) {
  30484. object.add(this.parseObject(children[i], geometries, materials, animations));
  30485. }
  30486. }
  30487. if (data.animations !== undefined) {
  30488. var objectAnimations = data.animations;
  30489. for (var _i = 0; _i < objectAnimations.length; _i++) {
  30490. var uuid = objectAnimations[_i];
  30491. object.animations.push(animations[uuid]);
  30492. }
  30493. }
  30494. if (data.type === 'LOD') {
  30495. if (data.autoUpdate !== undefined) object.autoUpdate = data.autoUpdate;
  30496. var levels = data.levels;
  30497. for (var l = 0; l < levels.length; l++) {
  30498. var level = levels[l];
  30499. var child = object.getObjectByProperty('uuid', level.object);
  30500. if (child !== undefined) {
  30501. object.addLevel(child, level.distance);
  30502. }
  30503. }
  30504. }
  30505. return object;
  30506. };
  30507. _proto.bindSkeletons = function bindSkeletons(object, skeletons) {
  30508. if (Object.keys(skeletons).length === 0) return;
  30509. object.traverse(function (child) {
  30510. if (child.isSkinnedMesh === true && child.skeleton !== undefined) {
  30511. var skeleton = skeletons[child.skeleton];
  30512. if (skeleton === undefined) {
  30513. console.warn('THREE.ObjectLoader: No skeleton found with UUID:', child.skeleton);
  30514. } else {
  30515. child.bind(skeleton, child.bindMatrix);
  30516. }
  30517. }
  30518. });
  30519. }
  30520. /* DEPRECATED */
  30521. ;
  30522. _proto.setTexturePath = function setTexturePath(value) {
  30523. console.warn('THREE.ObjectLoader: .setTexturePath() has been renamed to .setResourcePath().');
  30524. return this.setResourcePath(value);
  30525. };
  30526. return ObjectLoader;
  30527. }(Loader);
  30528. var TEXTURE_MAPPING = {
  30529. UVMapping: UVMapping,
  30530. CubeReflectionMapping: CubeReflectionMapping,
  30531. CubeRefractionMapping: CubeRefractionMapping,
  30532. EquirectangularReflectionMapping: EquirectangularReflectionMapping,
  30533. EquirectangularRefractionMapping: EquirectangularRefractionMapping,
  30534. CubeUVReflectionMapping: CubeUVReflectionMapping,
  30535. CubeUVRefractionMapping: CubeUVRefractionMapping
  30536. };
  30537. var TEXTURE_WRAPPING = {
  30538. RepeatWrapping: RepeatWrapping,
  30539. ClampToEdgeWrapping: ClampToEdgeWrapping,
  30540. MirroredRepeatWrapping: MirroredRepeatWrapping
  30541. };
  30542. var TEXTURE_FILTER = {
  30543. NearestFilter: NearestFilter,
  30544. NearestMipmapNearestFilter: NearestMipmapNearestFilter,
  30545. NearestMipmapLinearFilter: NearestMipmapLinearFilter,
  30546. LinearFilter: LinearFilter,
  30547. LinearMipmapNearestFilter: LinearMipmapNearestFilter,
  30548. LinearMipmapLinearFilter: LinearMipmapLinearFilter
  30549. };
  30550. function ImageBitmapLoader(manager) {
  30551. if (typeof createImageBitmap === 'undefined') {
  30552. console.warn('THREE.ImageBitmapLoader: createImageBitmap() not supported.');
  30553. }
  30554. if (typeof fetch === 'undefined') {
  30555. console.warn('THREE.ImageBitmapLoader: fetch() not supported.');
  30556. }
  30557. Loader.call(this, manager);
  30558. this.options = {
  30559. premultiplyAlpha: 'none'
  30560. };
  30561. }
  30562. ImageBitmapLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  30563. constructor: ImageBitmapLoader,
  30564. isImageBitmapLoader: true,
  30565. setOptions: function setOptions(options) {
  30566. this.options = options;
  30567. return this;
  30568. },
  30569. load: function load(url, onLoad, onProgress, onError) {
  30570. if (url === undefined) url = '';
  30571. if (this.path !== undefined) url = this.path + url;
  30572. url = this.manager.resolveURL(url);
  30573. var scope = this;
  30574. var cached = Cache.get(url);
  30575. if (cached !== undefined) {
  30576. scope.manager.itemStart(url);
  30577. setTimeout(function () {
  30578. if (onLoad) onLoad(cached);
  30579. scope.manager.itemEnd(url);
  30580. }, 0);
  30581. return cached;
  30582. }
  30583. var fetchOptions = {};
  30584. fetchOptions.credentials = this.crossOrigin === 'anonymous' ? 'same-origin' : 'include';
  30585. fetch(url, fetchOptions).then(function (res) {
  30586. return res.blob();
  30587. }).then(function (blob) {
  30588. return createImageBitmap(blob, scope.options);
  30589. }).then(function (imageBitmap) {
  30590. Cache.add(url, imageBitmap);
  30591. if (onLoad) onLoad(imageBitmap);
  30592. scope.manager.itemEnd(url);
  30593. }).catch(function (e) {
  30594. if (onError) onError(e);
  30595. scope.manager.itemError(url);
  30596. scope.manager.itemEnd(url);
  30597. });
  30598. scope.manager.itemStart(url);
  30599. }
  30600. });
  30601. function ShapePath() {
  30602. this.type = 'ShapePath';
  30603. this.color = new Color();
  30604. this.subPaths = [];
  30605. this.currentPath = null;
  30606. }
  30607. Object.assign(ShapePath.prototype, {
  30608. moveTo: function moveTo(x, y) {
  30609. this.currentPath = new Path();
  30610. this.subPaths.push(this.currentPath);
  30611. this.currentPath.moveTo(x, y);
  30612. return this;
  30613. },
  30614. lineTo: function lineTo(x, y) {
  30615. this.currentPath.lineTo(x, y);
  30616. return this;
  30617. },
  30618. quadraticCurveTo: function quadraticCurveTo(aCPx, aCPy, aX, aY) {
  30619. this.currentPath.quadraticCurveTo(aCPx, aCPy, aX, aY);
  30620. return this;
  30621. },
  30622. bezierCurveTo: function bezierCurveTo(aCP1x, aCP1y, aCP2x, aCP2y, aX, aY) {
  30623. this.currentPath.bezierCurveTo(aCP1x, aCP1y, aCP2x, aCP2y, aX, aY);
  30624. return this;
  30625. },
  30626. splineThru: function splineThru(pts) {
  30627. this.currentPath.splineThru(pts);
  30628. return this;
  30629. },
  30630. toShapes: function toShapes(isCCW, noHoles) {
  30631. function toShapesNoHoles(inSubpaths) {
  30632. var shapes = [];
  30633. for (var i = 0, l = inSubpaths.length; i < l; i++) {
  30634. var _tmpPath = inSubpaths[i];
  30635. var _tmpShape = new Shape();
  30636. _tmpShape.curves = _tmpPath.curves;
  30637. shapes.push(_tmpShape);
  30638. }
  30639. return shapes;
  30640. }
  30641. function isPointInsidePolygon(inPt, inPolygon) {
  30642. var polyLen = inPolygon.length; // inPt on polygon contour => immediate success or
  30643. // toggling of inside/outside at every single! intersection point of an edge
  30644. // with the horizontal line through inPt, left of inPt
  30645. // not counting lowerY endpoints of edges and whole edges on that line
  30646. var inside = false;
  30647. for (var p = polyLen - 1, q = 0; q < polyLen; p = q++) {
  30648. var edgeLowPt = inPolygon[p];
  30649. var edgeHighPt = inPolygon[q];
  30650. var edgeDx = edgeHighPt.x - edgeLowPt.x;
  30651. var edgeDy = edgeHighPt.y - edgeLowPt.y;
  30652. if (Math.abs(edgeDy) > Number.EPSILON) {
  30653. // not parallel
  30654. if (edgeDy < 0) {
  30655. edgeLowPt = inPolygon[q];
  30656. edgeDx = -edgeDx;
  30657. edgeHighPt = inPolygon[p];
  30658. edgeDy = -edgeDy;
  30659. }
  30660. if (inPt.y < edgeLowPt.y || inPt.y > edgeHighPt.y) continue;
  30661. if (inPt.y === edgeLowPt.y) {
  30662. if (inPt.x === edgeLowPt.x) return true; // inPt is on contour ?
  30663. // continue; // no intersection or edgeLowPt => doesn't count !!!
  30664. } else {
  30665. var perpEdge = edgeDy * (inPt.x - edgeLowPt.x) - edgeDx * (inPt.y - edgeLowPt.y);
  30666. if (perpEdge === 0) return true; // inPt is on contour ?
  30667. if (perpEdge < 0) continue;
  30668. inside = !inside; // true intersection left of inPt
  30669. }
  30670. } else {
  30671. // parallel or collinear
  30672. if (inPt.y !== edgeLowPt.y) continue; // parallel
  30673. // edge lies on the same horizontal line as inPt
  30674. if (edgeHighPt.x <= inPt.x && inPt.x <= edgeLowPt.x || edgeLowPt.x <= inPt.x && inPt.x <= edgeHighPt.x) return true; // inPt: Point on contour !
  30675. // continue;
  30676. }
  30677. }
  30678. return inside;
  30679. }
  30680. var isClockWise = ShapeUtils.isClockWise;
  30681. var subPaths = this.subPaths;
  30682. if (subPaths.length === 0) return [];
  30683. if (noHoles === true) return toShapesNoHoles(subPaths);
  30684. var solid, tmpPath, tmpShape;
  30685. var shapes = [];
  30686. if (subPaths.length === 1) {
  30687. tmpPath = subPaths[0];
  30688. tmpShape = new Shape();
  30689. tmpShape.curves = tmpPath.curves;
  30690. shapes.push(tmpShape);
  30691. return shapes;
  30692. }
  30693. var holesFirst = !isClockWise(subPaths[0].getPoints());
  30694. holesFirst = isCCW ? !holesFirst : holesFirst; // console.log("Holes first", holesFirst);
  30695. var betterShapeHoles = [];
  30696. var newShapes = [];
  30697. var newShapeHoles = [];
  30698. var mainIdx = 0;
  30699. var tmpPoints;
  30700. newShapes[mainIdx] = undefined;
  30701. newShapeHoles[mainIdx] = [];
  30702. for (var i = 0, l = subPaths.length; i < l; i++) {
  30703. tmpPath = subPaths[i];
  30704. tmpPoints = tmpPath.getPoints();
  30705. solid = isClockWise(tmpPoints);
  30706. solid = isCCW ? !solid : solid;
  30707. if (solid) {
  30708. if (!holesFirst && newShapes[mainIdx]) mainIdx++;
  30709. newShapes[mainIdx] = {
  30710. s: new Shape(),
  30711. p: tmpPoints
  30712. };
  30713. newShapes[mainIdx].s.curves = tmpPath.curves;
  30714. if (holesFirst) mainIdx++;
  30715. newShapeHoles[mainIdx] = []; //console.log('cw', i);
  30716. } else {
  30717. newShapeHoles[mainIdx].push({
  30718. h: tmpPath,
  30719. p: tmpPoints[0]
  30720. }); //console.log('ccw', i);
  30721. }
  30722. } // only Holes? -> probably all Shapes with wrong orientation
  30723. if (!newShapes[0]) return toShapesNoHoles(subPaths);
  30724. if (newShapes.length > 1) {
  30725. var ambiguous = false;
  30726. var toChange = [];
  30727. for (var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx++) {
  30728. betterShapeHoles[sIdx] = [];
  30729. }
  30730. for (var _sIdx = 0, _sLen = newShapes.length; _sIdx < _sLen; _sIdx++) {
  30731. var sho = newShapeHoles[_sIdx];
  30732. for (var hIdx = 0; hIdx < sho.length; hIdx++) {
  30733. var ho = sho[hIdx];
  30734. var hole_unassigned = true;
  30735. for (var s2Idx = 0; s2Idx < newShapes.length; s2Idx++) {
  30736. if (isPointInsidePolygon(ho.p, newShapes[s2Idx].p)) {
  30737. if (_sIdx !== s2Idx) toChange.push({
  30738. froms: _sIdx,
  30739. tos: s2Idx,
  30740. hole: hIdx
  30741. });
  30742. if (hole_unassigned) {
  30743. hole_unassigned = false;
  30744. betterShapeHoles[s2Idx].push(ho);
  30745. } else {
  30746. ambiguous = true;
  30747. }
  30748. }
  30749. }
  30750. if (hole_unassigned) {
  30751. betterShapeHoles[_sIdx].push(ho);
  30752. }
  30753. }
  30754. } // console.log("ambiguous: ", ambiguous);
  30755. if (toChange.length > 0) {
  30756. // console.log("to change: ", toChange);
  30757. if (!ambiguous) newShapeHoles = betterShapeHoles;
  30758. }
  30759. }
  30760. var tmpHoles;
  30761. for (var _i = 0, il = newShapes.length; _i < il; _i++) {
  30762. tmpShape = newShapes[_i].s;
  30763. shapes.push(tmpShape);
  30764. tmpHoles = newShapeHoles[_i];
  30765. for (var j = 0, jl = tmpHoles.length; j < jl; j++) {
  30766. tmpShape.holes.push(tmpHoles[j].h);
  30767. }
  30768. } //console.log("shape", shapes);
  30769. return shapes;
  30770. }
  30771. });
  30772. var Font = /*#__PURE__*/function () {
  30773. function Font(data) {
  30774. Object.defineProperty(this, 'isFont', {
  30775. value: true
  30776. });
  30777. this.type = 'Font';
  30778. this.data = data;
  30779. }
  30780. var _proto = Font.prototype;
  30781. _proto.generateShapes = function generateShapes(text, size) {
  30782. if (size === void 0) {
  30783. size = 100;
  30784. }
  30785. var shapes = [];
  30786. var paths = createPaths(text, size, this.data);
  30787. for (var p = 0, pl = paths.length; p < pl; p++) {
  30788. Array.prototype.push.apply(shapes, paths[p].toShapes());
  30789. }
  30790. return shapes;
  30791. };
  30792. return Font;
  30793. }();
  30794. function createPaths(text, size, data) {
  30795. var chars = Array.from ? Array.from(text) : String(text).split(''); // workaround for IE11, see #13988
  30796. var scale = size / data.resolution;
  30797. var line_height = (data.boundingBox.yMax - data.boundingBox.yMin + data.underlineThickness) * scale;
  30798. var paths = [];
  30799. var offsetX = 0,
  30800. offsetY = 0;
  30801. for (var i = 0; i < chars.length; i++) {
  30802. var char = chars[i];
  30803. if (char === '\n') {
  30804. offsetX = 0;
  30805. offsetY -= line_height;
  30806. } else {
  30807. var ret = createPath(char, scale, offsetX, offsetY, data);
  30808. offsetX += ret.offsetX;
  30809. paths.push(ret.path);
  30810. }
  30811. }
  30812. return paths;
  30813. }
  30814. function createPath(char, scale, offsetX, offsetY, data) {
  30815. var glyph = data.glyphs[char] || data.glyphs['?'];
  30816. if (!glyph) {
  30817. console.error('THREE.Font: character "' + char + '" does not exists in font family ' + data.familyName + '.');
  30818. return;
  30819. }
  30820. var path = new ShapePath();
  30821. var x, y, cpx, cpy, cpx1, cpy1, cpx2, cpy2;
  30822. if (glyph.o) {
  30823. var outline = glyph._cachedOutline || (glyph._cachedOutline = glyph.o.split(' '));
  30824. for (var i = 0, l = outline.length; i < l;) {
  30825. var action = outline[i++];
  30826. switch (action) {
  30827. case 'm':
  30828. // moveTo
  30829. x = outline[i++] * scale + offsetX;
  30830. y = outline[i++] * scale + offsetY;
  30831. path.moveTo(x, y);
  30832. break;
  30833. case 'l':
  30834. // lineTo
  30835. x = outline[i++] * scale + offsetX;
  30836. y = outline[i++] * scale + offsetY;
  30837. path.lineTo(x, y);
  30838. break;
  30839. case 'q':
  30840. // quadraticCurveTo
  30841. cpx = outline[i++] * scale + offsetX;
  30842. cpy = outline[i++] * scale + offsetY;
  30843. cpx1 = outline[i++] * scale + offsetX;
  30844. cpy1 = outline[i++] * scale + offsetY;
  30845. path.quadraticCurveTo(cpx1, cpy1, cpx, cpy);
  30846. break;
  30847. case 'b':
  30848. // bezierCurveTo
  30849. cpx = outline[i++] * scale + offsetX;
  30850. cpy = outline[i++] * scale + offsetY;
  30851. cpx1 = outline[i++] * scale + offsetX;
  30852. cpy1 = outline[i++] * scale + offsetY;
  30853. cpx2 = outline[i++] * scale + offsetX;
  30854. cpy2 = outline[i++] * scale + offsetY;
  30855. path.bezierCurveTo(cpx1, cpy1, cpx2, cpy2, cpx, cpy);
  30856. break;
  30857. }
  30858. }
  30859. }
  30860. return {
  30861. offsetX: glyph.ha * scale,
  30862. path: path
  30863. };
  30864. }
  30865. function FontLoader(manager) {
  30866. Loader.call(this, manager);
  30867. }
  30868. FontLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  30869. constructor: FontLoader,
  30870. load: function load(url, onLoad, onProgress, onError) {
  30871. var scope = this;
  30872. var loader = new FileLoader(this.manager);
  30873. loader.setPath(this.path);
  30874. loader.setRequestHeader(this.requestHeader);
  30875. loader.setWithCredentials(scope.withCredentials);
  30876. loader.load(url, function (text) {
  30877. var json;
  30878. try {
  30879. json = JSON.parse(text);
  30880. } catch (e) {
  30881. console.warn('THREE.FontLoader: typeface.js support is being deprecated. Use typeface.json instead.');
  30882. json = JSON.parse(text.substring(65, text.length - 2));
  30883. }
  30884. var font = scope.parse(json);
  30885. if (onLoad) onLoad(font);
  30886. }, onProgress, onError);
  30887. },
  30888. parse: function parse(json) {
  30889. return new Font(json);
  30890. }
  30891. });
  30892. var _context;
  30893. var AudioContext = {
  30894. getContext: function getContext() {
  30895. if (_context === undefined) {
  30896. _context = new (window.AudioContext || window.webkitAudioContext)();
  30897. }
  30898. return _context;
  30899. },
  30900. setContext: function setContext(value) {
  30901. _context = value;
  30902. }
  30903. };
  30904. function AudioLoader(manager) {
  30905. Loader.call(this, manager);
  30906. }
  30907. AudioLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  30908. constructor: AudioLoader,
  30909. load: function load(url, onLoad, onProgress, onError) {
  30910. var scope = this;
  30911. var loader = new FileLoader(scope.manager);
  30912. loader.setResponseType('arraybuffer');
  30913. loader.setPath(scope.path);
  30914. loader.setRequestHeader(scope.requestHeader);
  30915. loader.setWithCredentials(scope.withCredentials);
  30916. loader.load(url, function (buffer) {
  30917. try {
  30918. // Create a copy of the buffer. The `decodeAudioData` method
  30919. // detaches the buffer when complete, preventing reuse.
  30920. var bufferCopy = buffer.slice(0);
  30921. var context = AudioContext.getContext();
  30922. context.decodeAudioData(bufferCopy, function (audioBuffer) {
  30923. onLoad(audioBuffer);
  30924. });
  30925. } catch (e) {
  30926. if (onError) {
  30927. onError(e);
  30928. } else {
  30929. console.error(e);
  30930. }
  30931. scope.manager.itemError(url);
  30932. }
  30933. }, onProgress, onError);
  30934. }
  30935. });
  30936. function HemisphereLightProbe(skyColor, groundColor, intensity) {
  30937. LightProbe.call(this, undefined, intensity);
  30938. var color1 = new Color().set(skyColor);
  30939. var color2 = new Color().set(groundColor);
  30940. var sky = new Vector3(color1.r, color1.g, color1.b);
  30941. var ground = new Vector3(color2.r, color2.g, color2.b); // without extra factor of PI in the shader, should = 1 / Math.sqrt( Math.PI );
  30942. var c0 = Math.sqrt(Math.PI);
  30943. var c1 = c0 * Math.sqrt(0.75);
  30944. this.sh.coefficients[0].copy(sky).add(ground).multiplyScalar(c0);
  30945. this.sh.coefficients[1].copy(sky).sub(ground).multiplyScalar(c1);
  30946. }
  30947. HemisphereLightProbe.prototype = Object.assign(Object.create(LightProbe.prototype), {
  30948. constructor: HemisphereLightProbe,
  30949. isHemisphereLightProbe: true,
  30950. copy: function copy(source) {
  30951. // modifying colors not currently supported
  30952. LightProbe.prototype.copy.call(this, source);
  30953. return this;
  30954. },
  30955. toJSON: function toJSON(meta) {
  30956. var data = LightProbe.prototype.toJSON.call(this, meta); // data.sh = this.sh.toArray(); // todo
  30957. return data;
  30958. }
  30959. });
  30960. function AmbientLightProbe(color, intensity) {
  30961. LightProbe.call(this, undefined, intensity);
  30962. var color1 = new Color().set(color); // without extra factor of PI in the shader, would be 2 / Math.sqrt( Math.PI );
  30963. this.sh.coefficients[0].set(color1.r, color1.g, color1.b).multiplyScalar(2 * Math.sqrt(Math.PI));
  30964. }
  30965. AmbientLightProbe.prototype = Object.assign(Object.create(LightProbe.prototype), {
  30966. constructor: AmbientLightProbe,
  30967. isAmbientLightProbe: true,
  30968. copy: function copy(source) {
  30969. // modifying color not currently supported
  30970. LightProbe.prototype.copy.call(this, source);
  30971. return this;
  30972. },
  30973. toJSON: function toJSON(meta) {
  30974. var data = LightProbe.prototype.toJSON.call(this, meta); // data.sh = this.sh.toArray(); // todo
  30975. return data;
  30976. }
  30977. });
  30978. var _eyeRight = new Matrix4();
  30979. var _eyeLeft = new Matrix4();
  30980. function StereoCamera() {
  30981. this.type = 'StereoCamera';
  30982. this.aspect = 1;
  30983. this.eyeSep = 0.064;
  30984. this.cameraL = new PerspectiveCamera();
  30985. this.cameraL.layers.enable(1);
  30986. this.cameraL.matrixAutoUpdate = false;
  30987. this.cameraR = new PerspectiveCamera();
  30988. this.cameraR.layers.enable(2);
  30989. this.cameraR.matrixAutoUpdate = false;
  30990. this._cache = {
  30991. focus: null,
  30992. fov: null,
  30993. aspect: null,
  30994. near: null,
  30995. far: null,
  30996. zoom: null,
  30997. eyeSep: null
  30998. };
  30999. }
  31000. Object.assign(StereoCamera.prototype, {
  31001. update: function update(camera) {
  31002. var cache = this._cache;
  31003. var needsUpdate = cache.focus !== camera.focus || cache.fov !== camera.fov || cache.aspect !== camera.aspect * this.aspect || cache.near !== camera.near || cache.far !== camera.far || cache.zoom !== camera.zoom || cache.eyeSep !== this.eyeSep;
  31004. if (needsUpdate) {
  31005. cache.focus = camera.focus;
  31006. cache.fov = camera.fov;
  31007. cache.aspect = camera.aspect * this.aspect;
  31008. cache.near = camera.near;
  31009. cache.far = camera.far;
  31010. cache.zoom = camera.zoom;
  31011. cache.eyeSep = this.eyeSep; // Off-axis stereoscopic effect based on
  31012. // http://paulbourke.net/stereographics/stereorender/
  31013. var projectionMatrix = camera.projectionMatrix.clone();
  31014. var eyeSepHalf = cache.eyeSep / 2;
  31015. var eyeSepOnProjection = eyeSepHalf * cache.near / cache.focus;
  31016. var ymax = cache.near * Math.tan(MathUtils.DEG2RAD * cache.fov * 0.5) / cache.zoom;
  31017. var xmin, xmax; // translate xOffset
  31018. _eyeLeft.elements[12] = -eyeSepHalf;
  31019. _eyeRight.elements[12] = eyeSepHalf; // for left eye
  31020. xmin = -ymax * cache.aspect + eyeSepOnProjection;
  31021. xmax = ymax * cache.aspect + eyeSepOnProjection;
  31022. projectionMatrix.elements[0] = 2 * cache.near / (xmax - xmin);
  31023. projectionMatrix.elements[8] = (xmax + xmin) / (xmax - xmin);
  31024. this.cameraL.projectionMatrix.copy(projectionMatrix); // for right eye
  31025. xmin = -ymax * cache.aspect - eyeSepOnProjection;
  31026. xmax = ymax * cache.aspect - eyeSepOnProjection;
  31027. projectionMatrix.elements[0] = 2 * cache.near / (xmax - xmin);
  31028. projectionMatrix.elements[8] = (xmax + xmin) / (xmax - xmin);
  31029. this.cameraR.projectionMatrix.copy(projectionMatrix);
  31030. }
  31031. this.cameraL.matrixWorld.copy(camera.matrixWorld).multiply(_eyeLeft);
  31032. this.cameraR.matrixWorld.copy(camera.matrixWorld).multiply(_eyeRight);
  31033. }
  31034. });
  31035. var Clock = /*#__PURE__*/function () {
  31036. function Clock(autoStart) {
  31037. this.autoStart = autoStart !== undefined ? autoStart : true;
  31038. this.startTime = 0;
  31039. this.oldTime = 0;
  31040. this.elapsedTime = 0;
  31041. this.running = false;
  31042. }
  31043. var _proto = Clock.prototype;
  31044. _proto.start = function start() {
  31045. this.startTime = now();
  31046. this.oldTime = this.startTime;
  31047. this.elapsedTime = 0;
  31048. this.running = true;
  31049. };
  31050. _proto.stop = function stop() {
  31051. this.getElapsedTime();
  31052. this.running = false;
  31053. this.autoStart = false;
  31054. };
  31055. _proto.getElapsedTime = function getElapsedTime() {
  31056. this.getDelta();
  31057. return this.elapsedTime;
  31058. };
  31059. _proto.getDelta = function getDelta() {
  31060. var diff = 0;
  31061. if (this.autoStart && !this.running) {
  31062. this.start();
  31063. return 0;
  31064. }
  31065. if (this.running) {
  31066. var newTime = now();
  31067. diff = (newTime - this.oldTime) / 1000;
  31068. this.oldTime = newTime;
  31069. this.elapsedTime += diff;
  31070. }
  31071. return diff;
  31072. };
  31073. return Clock;
  31074. }();
  31075. function now() {
  31076. return (typeof performance === 'undefined' ? Date : performance).now(); // see #10732
  31077. }
  31078. var _position$2 = /*@__PURE__*/new Vector3();
  31079. var _quaternion$3 = /*@__PURE__*/new Quaternion();
  31080. var _scale$1 = /*@__PURE__*/new Vector3();
  31081. var _orientation = /*@__PURE__*/new Vector3();
  31082. var AudioListener = /*#__PURE__*/function (_Object3D) {
  31083. _inheritsLoose(AudioListener, _Object3D);
  31084. function AudioListener() {
  31085. var _this;
  31086. _this = _Object3D.call(this) || this;
  31087. _this.type = 'AudioListener';
  31088. _this.context = AudioContext.getContext();
  31089. _this.gain = _this.context.createGain();
  31090. _this.gain.connect(_this.context.destination);
  31091. _this.filter = null;
  31092. _this.timeDelta = 0; // private
  31093. _this._clock = new Clock();
  31094. return _this;
  31095. }
  31096. var _proto = AudioListener.prototype;
  31097. _proto.getInput = function getInput() {
  31098. return this.gain;
  31099. };
  31100. _proto.removeFilter = function removeFilter() {
  31101. if (this.filter !== null) {
  31102. this.gain.disconnect(this.filter);
  31103. this.filter.disconnect(this.context.destination);
  31104. this.gain.connect(this.context.destination);
  31105. this.filter = null;
  31106. }
  31107. return this;
  31108. };
  31109. _proto.getFilter = function getFilter() {
  31110. return this.filter;
  31111. };
  31112. _proto.setFilter = function setFilter(value) {
  31113. if (this.filter !== null) {
  31114. this.gain.disconnect(this.filter);
  31115. this.filter.disconnect(this.context.destination);
  31116. } else {
  31117. this.gain.disconnect(this.context.destination);
  31118. }
  31119. this.filter = value;
  31120. this.gain.connect(this.filter);
  31121. this.filter.connect(this.context.destination);
  31122. return this;
  31123. };
  31124. _proto.getMasterVolume = function getMasterVolume() {
  31125. return this.gain.gain.value;
  31126. };
  31127. _proto.setMasterVolume = function setMasterVolume(value) {
  31128. this.gain.gain.setTargetAtTime(value, this.context.currentTime, 0.01);
  31129. return this;
  31130. };
  31131. _proto.updateMatrixWorld = function updateMatrixWorld(force) {
  31132. _Object3D.prototype.updateMatrixWorld.call(this, force);
  31133. var listener = this.context.listener;
  31134. var up = this.up;
  31135. this.timeDelta = this._clock.getDelta();
  31136. this.matrixWorld.decompose(_position$2, _quaternion$3, _scale$1);
  31137. _orientation.set(0, 0, -1).applyQuaternion(_quaternion$3);
  31138. if (listener.positionX) {
  31139. // code path for Chrome (see #14393)
  31140. var endTime = this.context.currentTime + this.timeDelta;
  31141. listener.positionX.linearRampToValueAtTime(_position$2.x, endTime);
  31142. listener.positionY.linearRampToValueAtTime(_position$2.y, endTime);
  31143. listener.positionZ.linearRampToValueAtTime(_position$2.z, endTime);
  31144. listener.forwardX.linearRampToValueAtTime(_orientation.x, endTime);
  31145. listener.forwardY.linearRampToValueAtTime(_orientation.y, endTime);
  31146. listener.forwardZ.linearRampToValueAtTime(_orientation.z, endTime);
  31147. listener.upX.linearRampToValueAtTime(up.x, endTime);
  31148. listener.upY.linearRampToValueAtTime(up.y, endTime);
  31149. listener.upZ.linearRampToValueAtTime(up.z, endTime);
  31150. } else {
  31151. listener.setPosition(_position$2.x, _position$2.y, _position$2.z);
  31152. listener.setOrientation(_orientation.x, _orientation.y, _orientation.z, up.x, up.y, up.z);
  31153. }
  31154. };
  31155. return AudioListener;
  31156. }(Object3D);
  31157. var Audio = /*#__PURE__*/function (_Object3D) {
  31158. _inheritsLoose(Audio, _Object3D);
  31159. function Audio(listener) {
  31160. var _this;
  31161. _this = _Object3D.call(this) || this;
  31162. _this.type = 'Audio';
  31163. _this.listener = listener;
  31164. _this.context = listener.context;
  31165. _this.gain = _this.context.createGain();
  31166. _this.gain.connect(listener.getInput());
  31167. _this.autoplay = false;
  31168. _this.buffer = null;
  31169. _this.detune = 0;
  31170. _this.loop = false;
  31171. _this.loopStart = 0;
  31172. _this.loopEnd = 0;
  31173. _this.offset = 0;
  31174. _this.duration = undefined;
  31175. _this.playbackRate = 1;
  31176. _this.isPlaying = false;
  31177. _this.hasPlaybackControl = true;
  31178. _this.source = null;
  31179. _this.sourceType = 'empty';
  31180. _this._startedAt = 0;
  31181. _this._progress = 0;
  31182. _this._connected = false;
  31183. _this.filters = [];
  31184. return _this;
  31185. }
  31186. var _proto = Audio.prototype;
  31187. _proto.getOutput = function getOutput() {
  31188. return this.gain;
  31189. };
  31190. _proto.setNodeSource = function setNodeSource(audioNode) {
  31191. this.hasPlaybackControl = false;
  31192. this.sourceType = 'audioNode';
  31193. this.source = audioNode;
  31194. this.connect();
  31195. return this;
  31196. };
  31197. _proto.setMediaElementSource = function setMediaElementSource(mediaElement) {
  31198. this.hasPlaybackControl = false;
  31199. this.sourceType = 'mediaNode';
  31200. this.source = this.context.createMediaElementSource(mediaElement);
  31201. this.connect();
  31202. return this;
  31203. };
  31204. _proto.setMediaStreamSource = function setMediaStreamSource(mediaStream) {
  31205. this.hasPlaybackControl = false;
  31206. this.sourceType = 'mediaStreamNode';
  31207. this.source = this.context.createMediaStreamSource(mediaStream);
  31208. this.connect();
  31209. return this;
  31210. };
  31211. _proto.setBuffer = function setBuffer(audioBuffer) {
  31212. this.buffer = audioBuffer;
  31213. this.sourceType = 'buffer';
  31214. if (this.autoplay) this.play();
  31215. return this;
  31216. };
  31217. _proto.play = function play(delay) {
  31218. if (delay === void 0) {
  31219. delay = 0;
  31220. }
  31221. if (this.isPlaying === true) {
  31222. console.warn('THREE.Audio: Audio is already playing.');
  31223. return;
  31224. }
  31225. if (this.hasPlaybackControl === false) {
  31226. console.warn('THREE.Audio: this Audio has no playback control.');
  31227. return;
  31228. }
  31229. this._startedAt = this.context.currentTime + delay;
  31230. var source = this.context.createBufferSource();
  31231. source.buffer = this.buffer;
  31232. source.loop = this.loop;
  31233. source.loopStart = this.loopStart;
  31234. source.loopEnd = this.loopEnd;
  31235. source.onended = this.onEnded.bind(this);
  31236. source.start(this._startedAt, this._progress + this.offset, this.duration);
  31237. this.isPlaying = true;
  31238. this.source = source;
  31239. this.setDetune(this.detune);
  31240. this.setPlaybackRate(this.playbackRate);
  31241. return this.connect();
  31242. };
  31243. _proto.pause = function pause() {
  31244. if (this.hasPlaybackControl === false) {
  31245. console.warn('THREE.Audio: this Audio has no playback control.');
  31246. return;
  31247. }
  31248. if (this.isPlaying === true) {
  31249. // update current progress
  31250. this._progress += Math.max(this.context.currentTime - this._startedAt, 0) * this.playbackRate;
  31251. if (this.loop === true) {
  31252. // ensure _progress does not exceed duration with looped audios
  31253. this._progress = this._progress % (this.duration || this.buffer.duration);
  31254. }
  31255. this.source.stop();
  31256. this.source.onended = null;
  31257. this.isPlaying = false;
  31258. }
  31259. return this;
  31260. };
  31261. _proto.stop = function stop() {
  31262. if (this.hasPlaybackControl === false) {
  31263. console.warn('THREE.Audio: this Audio has no playback control.');
  31264. return;
  31265. }
  31266. this._progress = 0;
  31267. this.source.stop();
  31268. this.source.onended = null;
  31269. this.isPlaying = false;
  31270. return this;
  31271. };
  31272. _proto.connect = function connect() {
  31273. if (this.filters.length > 0) {
  31274. this.source.connect(this.filters[0]);
  31275. for (var i = 1, l = this.filters.length; i < l; i++) {
  31276. this.filters[i - 1].connect(this.filters[i]);
  31277. }
  31278. this.filters[this.filters.length - 1].connect(this.getOutput());
  31279. } else {
  31280. this.source.connect(this.getOutput());
  31281. }
  31282. this._connected = true;
  31283. return this;
  31284. };
  31285. _proto.disconnect = function disconnect() {
  31286. if (this.filters.length > 0) {
  31287. this.source.disconnect(this.filters[0]);
  31288. for (var i = 1, l = this.filters.length; i < l; i++) {
  31289. this.filters[i - 1].disconnect(this.filters[i]);
  31290. }
  31291. this.filters[this.filters.length - 1].disconnect(this.getOutput());
  31292. } else {
  31293. this.source.disconnect(this.getOutput());
  31294. }
  31295. this._connected = false;
  31296. return this;
  31297. };
  31298. _proto.getFilters = function getFilters() {
  31299. return this.filters;
  31300. };
  31301. _proto.setFilters = function setFilters(value) {
  31302. if (!value) value = [];
  31303. if (this._connected === true) {
  31304. this.disconnect();
  31305. this.filters = value.slice();
  31306. this.connect();
  31307. } else {
  31308. this.filters = value.slice();
  31309. }
  31310. return this;
  31311. };
  31312. _proto.setDetune = function setDetune(value) {
  31313. this.detune = value;
  31314. if (this.source.detune === undefined) return; // only set detune when available
  31315. if (this.isPlaying === true) {
  31316. this.source.detune.setTargetAtTime(this.detune, this.context.currentTime, 0.01);
  31317. }
  31318. return this;
  31319. };
  31320. _proto.getDetune = function getDetune() {
  31321. return this.detune;
  31322. };
  31323. _proto.getFilter = function getFilter() {
  31324. return this.getFilters()[0];
  31325. };
  31326. _proto.setFilter = function setFilter(filter) {
  31327. return this.setFilters(filter ? [filter] : []);
  31328. };
  31329. _proto.setPlaybackRate = function setPlaybackRate(value) {
  31330. if (this.hasPlaybackControl === false) {
  31331. console.warn('THREE.Audio: this Audio has no playback control.');
  31332. return;
  31333. }
  31334. this.playbackRate = value;
  31335. if (this.isPlaying === true) {
  31336. this.source.playbackRate.setTargetAtTime(this.playbackRate, this.context.currentTime, 0.01);
  31337. }
  31338. return this;
  31339. };
  31340. _proto.getPlaybackRate = function getPlaybackRate() {
  31341. return this.playbackRate;
  31342. };
  31343. _proto.onEnded = function onEnded() {
  31344. this.isPlaying = false;
  31345. };
  31346. _proto.getLoop = function getLoop() {
  31347. if (this.hasPlaybackControl === false) {
  31348. console.warn('THREE.Audio: this Audio has no playback control.');
  31349. return false;
  31350. }
  31351. return this.loop;
  31352. };
  31353. _proto.setLoop = function setLoop(value) {
  31354. if (this.hasPlaybackControl === false) {
  31355. console.warn('THREE.Audio: this Audio has no playback control.');
  31356. return;
  31357. }
  31358. this.loop = value;
  31359. if (this.isPlaying === true) {
  31360. this.source.loop = this.loop;
  31361. }
  31362. return this;
  31363. };
  31364. _proto.setLoopStart = function setLoopStart(value) {
  31365. this.loopStart = value;
  31366. return this;
  31367. };
  31368. _proto.setLoopEnd = function setLoopEnd(value) {
  31369. this.loopEnd = value;
  31370. return this;
  31371. };
  31372. _proto.getVolume = function getVolume() {
  31373. return this.gain.gain.value;
  31374. };
  31375. _proto.setVolume = function setVolume(value) {
  31376. this.gain.gain.setTargetAtTime(value, this.context.currentTime, 0.01);
  31377. return this;
  31378. };
  31379. return Audio;
  31380. }(Object3D);
  31381. var _position$3 = /*@__PURE__*/new Vector3();
  31382. var _quaternion$4 = /*@__PURE__*/new Quaternion();
  31383. var _scale$2 = /*@__PURE__*/new Vector3();
  31384. var _orientation$1 = /*@__PURE__*/new Vector3();
  31385. var PositionalAudio = /*#__PURE__*/function (_Audio) {
  31386. _inheritsLoose(PositionalAudio, _Audio);
  31387. function PositionalAudio(listener) {
  31388. var _this;
  31389. _this = _Audio.call(this, listener) || this;
  31390. _this.panner = _this.context.createPanner();
  31391. _this.panner.panningModel = 'HRTF';
  31392. _this.panner.connect(_this.gain);
  31393. return _this;
  31394. }
  31395. var _proto = PositionalAudio.prototype;
  31396. _proto.getOutput = function getOutput() {
  31397. return this.panner;
  31398. };
  31399. _proto.getRefDistance = function getRefDistance() {
  31400. return this.panner.refDistance;
  31401. };
  31402. _proto.setRefDistance = function setRefDistance(value) {
  31403. this.panner.refDistance = value;
  31404. return this;
  31405. };
  31406. _proto.getRolloffFactor = function getRolloffFactor() {
  31407. return this.panner.rolloffFactor;
  31408. };
  31409. _proto.setRolloffFactor = function setRolloffFactor(value) {
  31410. this.panner.rolloffFactor = value;
  31411. return this;
  31412. };
  31413. _proto.getDistanceModel = function getDistanceModel() {
  31414. return this.panner.distanceModel;
  31415. };
  31416. _proto.setDistanceModel = function setDistanceModel(value) {
  31417. this.panner.distanceModel = value;
  31418. return this;
  31419. };
  31420. _proto.getMaxDistance = function getMaxDistance() {
  31421. return this.panner.maxDistance;
  31422. };
  31423. _proto.setMaxDistance = function setMaxDistance(value) {
  31424. this.panner.maxDistance = value;
  31425. return this;
  31426. };
  31427. _proto.setDirectionalCone = function setDirectionalCone(coneInnerAngle, coneOuterAngle, coneOuterGain) {
  31428. this.panner.coneInnerAngle = coneInnerAngle;
  31429. this.panner.coneOuterAngle = coneOuterAngle;
  31430. this.panner.coneOuterGain = coneOuterGain;
  31431. return this;
  31432. };
  31433. _proto.updateMatrixWorld = function updateMatrixWorld(force) {
  31434. _Audio.prototype.updateMatrixWorld.call(this, force);
  31435. if (this.hasPlaybackControl === true && this.isPlaying === false) return;
  31436. this.matrixWorld.decompose(_position$3, _quaternion$4, _scale$2);
  31437. _orientation$1.set(0, 0, 1).applyQuaternion(_quaternion$4);
  31438. var panner = this.panner;
  31439. if (panner.positionX) {
  31440. // code path for Chrome and Firefox (see #14393)
  31441. var endTime = this.context.currentTime + this.listener.timeDelta;
  31442. panner.positionX.linearRampToValueAtTime(_position$3.x, endTime);
  31443. panner.positionY.linearRampToValueAtTime(_position$3.y, endTime);
  31444. panner.positionZ.linearRampToValueAtTime(_position$3.z, endTime);
  31445. panner.orientationX.linearRampToValueAtTime(_orientation$1.x, endTime);
  31446. panner.orientationY.linearRampToValueAtTime(_orientation$1.y, endTime);
  31447. panner.orientationZ.linearRampToValueAtTime(_orientation$1.z, endTime);
  31448. } else {
  31449. panner.setPosition(_position$3.x, _position$3.y, _position$3.z);
  31450. panner.setOrientation(_orientation$1.x, _orientation$1.y, _orientation$1.z);
  31451. }
  31452. };
  31453. return PositionalAudio;
  31454. }(Audio);
  31455. var AudioAnalyser = /*#__PURE__*/function () {
  31456. function AudioAnalyser(audio, fftSize) {
  31457. if (fftSize === void 0) {
  31458. fftSize = 2048;
  31459. }
  31460. this.analyser = audio.context.createAnalyser();
  31461. this.analyser.fftSize = fftSize;
  31462. this.data = new Uint8Array(this.analyser.frequencyBinCount);
  31463. audio.getOutput().connect(this.analyser);
  31464. }
  31465. var _proto = AudioAnalyser.prototype;
  31466. _proto.getFrequencyData = function getFrequencyData() {
  31467. this.analyser.getByteFrequencyData(this.data);
  31468. return this.data;
  31469. };
  31470. _proto.getAverageFrequency = function getAverageFrequency() {
  31471. var value = 0;
  31472. var data = this.getFrequencyData();
  31473. for (var i = 0; i < data.length; i++) {
  31474. value += data[i];
  31475. }
  31476. return value / data.length;
  31477. };
  31478. return AudioAnalyser;
  31479. }();
  31480. function PropertyMixer(binding, typeName, valueSize) {
  31481. this.binding = binding;
  31482. this.valueSize = valueSize;
  31483. var mixFunction, mixFunctionAdditive, setIdentity; // buffer layout: [ incoming | accu0 | accu1 | orig | addAccu | (optional work) ]
  31484. //
  31485. // interpolators can use .buffer as their .result
  31486. // the data then goes to 'incoming'
  31487. //
  31488. // 'accu0' and 'accu1' are used frame-interleaved for
  31489. // the cumulative result and are compared to detect
  31490. // changes
  31491. //
  31492. // 'orig' stores the original state of the property
  31493. //
  31494. // 'add' is used for additive cumulative results
  31495. //
  31496. // 'work' is optional and is only present for quaternion types. It is used
  31497. // to store intermediate quaternion multiplication results
  31498. switch (typeName) {
  31499. case 'quaternion':
  31500. mixFunction = this._slerp;
  31501. mixFunctionAdditive = this._slerpAdditive;
  31502. setIdentity = this._setAdditiveIdentityQuaternion;
  31503. this.buffer = new Float64Array(valueSize * 6);
  31504. this._workIndex = 5;
  31505. break;
  31506. case 'string':
  31507. case 'bool':
  31508. mixFunction = this._select; // Use the regular mix function and for additive on these types,
  31509. // additive is not relevant for non-numeric types
  31510. mixFunctionAdditive = this._select;
  31511. setIdentity = this._setAdditiveIdentityOther;
  31512. this.buffer = new Array(valueSize * 5);
  31513. break;
  31514. default:
  31515. mixFunction = this._lerp;
  31516. mixFunctionAdditive = this._lerpAdditive;
  31517. setIdentity = this._setAdditiveIdentityNumeric;
  31518. this.buffer = new Float64Array(valueSize * 5);
  31519. }
  31520. this._mixBufferRegion = mixFunction;
  31521. this._mixBufferRegionAdditive = mixFunctionAdditive;
  31522. this._setIdentity = setIdentity;
  31523. this._origIndex = 3;
  31524. this._addIndex = 4;
  31525. this.cumulativeWeight = 0;
  31526. this.cumulativeWeightAdditive = 0;
  31527. this.useCount = 0;
  31528. this.referenceCount = 0;
  31529. }
  31530. Object.assign(PropertyMixer.prototype, {
  31531. // accumulate data in the 'incoming' region into 'accu<i>'
  31532. accumulate: function accumulate(accuIndex, weight) {
  31533. // note: happily accumulating nothing when weight = 0, the caller knows
  31534. // the weight and shouldn't have made the call in the first place
  31535. var buffer = this.buffer,
  31536. stride = this.valueSize,
  31537. offset = accuIndex * stride + stride;
  31538. var currentWeight = this.cumulativeWeight;
  31539. if (currentWeight === 0) {
  31540. // accuN := incoming * weight
  31541. for (var i = 0; i !== stride; ++i) {
  31542. buffer[offset + i] = buffer[i];
  31543. }
  31544. currentWeight = weight;
  31545. } else {
  31546. // accuN := accuN + incoming * weight
  31547. currentWeight += weight;
  31548. var mix = weight / currentWeight;
  31549. this._mixBufferRegion(buffer, offset, 0, mix, stride);
  31550. }
  31551. this.cumulativeWeight = currentWeight;
  31552. },
  31553. // accumulate data in the 'incoming' region into 'add'
  31554. accumulateAdditive: function accumulateAdditive(weight) {
  31555. var buffer = this.buffer,
  31556. stride = this.valueSize,
  31557. offset = stride * this._addIndex;
  31558. if (this.cumulativeWeightAdditive === 0) {
  31559. // add = identity
  31560. this._setIdentity();
  31561. } // add := add + incoming * weight
  31562. this._mixBufferRegionAdditive(buffer, offset, 0, weight, stride);
  31563. this.cumulativeWeightAdditive += weight;
  31564. },
  31565. // apply the state of 'accu<i>' to the binding when accus differ
  31566. apply: function apply(accuIndex) {
  31567. var stride = this.valueSize,
  31568. buffer = this.buffer,
  31569. offset = accuIndex * stride + stride,
  31570. weight = this.cumulativeWeight,
  31571. weightAdditive = this.cumulativeWeightAdditive,
  31572. binding = this.binding;
  31573. this.cumulativeWeight = 0;
  31574. this.cumulativeWeightAdditive = 0;
  31575. if (weight < 1) {
  31576. // accuN := accuN + original * ( 1 - cumulativeWeight )
  31577. var originalValueOffset = stride * this._origIndex;
  31578. this._mixBufferRegion(buffer, offset, originalValueOffset, 1 - weight, stride);
  31579. }
  31580. if (weightAdditive > 0) {
  31581. // accuN := accuN + additive accuN
  31582. this._mixBufferRegionAdditive(buffer, offset, this._addIndex * stride, 1, stride);
  31583. }
  31584. for (var i = stride, e = stride + stride; i !== e; ++i) {
  31585. if (buffer[i] !== buffer[i + stride]) {
  31586. // value has changed -> update scene graph
  31587. binding.setValue(buffer, offset);
  31588. break;
  31589. }
  31590. }
  31591. },
  31592. // remember the state of the bound property and copy it to both accus
  31593. saveOriginalState: function saveOriginalState() {
  31594. var binding = this.binding;
  31595. var buffer = this.buffer,
  31596. stride = this.valueSize,
  31597. originalValueOffset = stride * this._origIndex;
  31598. binding.getValue(buffer, originalValueOffset); // accu[0..1] := orig -- initially detect changes against the original
  31599. for (var i = stride, e = originalValueOffset; i !== e; ++i) {
  31600. buffer[i] = buffer[originalValueOffset + i % stride];
  31601. } // Add to identity for additive
  31602. this._setIdentity();
  31603. this.cumulativeWeight = 0;
  31604. this.cumulativeWeightAdditive = 0;
  31605. },
  31606. // apply the state previously taken via 'saveOriginalState' to the binding
  31607. restoreOriginalState: function restoreOriginalState() {
  31608. var originalValueOffset = this.valueSize * 3;
  31609. this.binding.setValue(this.buffer, originalValueOffset);
  31610. },
  31611. _setAdditiveIdentityNumeric: function _setAdditiveIdentityNumeric() {
  31612. var startIndex = this._addIndex * this.valueSize;
  31613. var endIndex = startIndex + this.valueSize;
  31614. for (var i = startIndex; i < endIndex; i++) {
  31615. this.buffer[i] = 0;
  31616. }
  31617. },
  31618. _setAdditiveIdentityQuaternion: function _setAdditiveIdentityQuaternion() {
  31619. this._setAdditiveIdentityNumeric();
  31620. this.buffer[this._addIndex * this.valueSize + 3] = 1;
  31621. },
  31622. _setAdditiveIdentityOther: function _setAdditiveIdentityOther() {
  31623. var startIndex = this._origIndex * this.valueSize;
  31624. var targetIndex = this._addIndex * this.valueSize;
  31625. for (var i = 0; i < this.valueSize; i++) {
  31626. this.buffer[targetIndex + i] = this.buffer[startIndex + i];
  31627. }
  31628. },
  31629. // mix functions
  31630. _select: function _select(buffer, dstOffset, srcOffset, t, stride) {
  31631. if (t >= 0.5) {
  31632. for (var i = 0; i !== stride; ++i) {
  31633. buffer[dstOffset + i] = buffer[srcOffset + i];
  31634. }
  31635. }
  31636. },
  31637. _slerp: function _slerp(buffer, dstOffset, srcOffset, t) {
  31638. Quaternion.slerpFlat(buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t);
  31639. },
  31640. _slerpAdditive: function _slerpAdditive(buffer, dstOffset, srcOffset, t, stride) {
  31641. var workOffset = this._workIndex * stride; // Store result in intermediate buffer offset
  31642. Quaternion.multiplyQuaternionsFlat(buffer, workOffset, buffer, dstOffset, buffer, srcOffset); // Slerp to the intermediate result
  31643. Quaternion.slerpFlat(buffer, dstOffset, buffer, dstOffset, buffer, workOffset, t);
  31644. },
  31645. _lerp: function _lerp(buffer, dstOffset, srcOffset, t, stride) {
  31646. var s = 1 - t;
  31647. for (var i = 0; i !== stride; ++i) {
  31648. var j = dstOffset + i;
  31649. buffer[j] = buffer[j] * s + buffer[srcOffset + i] * t;
  31650. }
  31651. },
  31652. _lerpAdditive: function _lerpAdditive(buffer, dstOffset, srcOffset, t, stride) {
  31653. for (var i = 0; i !== stride; ++i) {
  31654. var j = dstOffset + i;
  31655. buffer[j] = buffer[j] + buffer[srcOffset + i] * t;
  31656. }
  31657. }
  31658. });
  31659. // Characters [].:/ are reserved for track binding syntax.
  31660. var _RESERVED_CHARS_RE = '\\[\\]\\.:\\/';
  31661. var _reservedRe = new RegExp('[' + _RESERVED_CHARS_RE + ']', 'g'); // Attempts to allow node names from any language. ES5's `\w` regexp matches
  31662. // only latin characters, and the unicode \p{L} is not yet supported. So
  31663. // instead, we exclude reserved characters and match everything else.
  31664. var _wordChar = '[^' + _RESERVED_CHARS_RE + ']';
  31665. var _wordCharOrDot = '[^' + _RESERVED_CHARS_RE.replace('\\.', '') + ']'; // Parent directories, delimited by '/' or ':'. Currently unused, but must
  31666. // be matched to parse the rest of the track name.
  31667. var _directoryRe = /((?:WC+[\/:])*)/.source.replace('WC', _wordChar); // Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'.
  31668. var _nodeRe = /(WCOD+)?/.source.replace('WCOD', _wordCharOrDot); // Object on target node, and accessor. May not contain reserved
  31669. // characters. Accessor may contain any character except closing bracket.
  31670. var _objectRe = /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace('WC', _wordChar); // Property and accessor. May not contain reserved characters. Accessor may
  31671. // contain any non-bracket characters.
  31672. var _propertyRe = /\.(WC+)(?:\[(.+)\])?/.source.replace('WC', _wordChar);
  31673. var _trackRe = new RegExp('' + '^' + _directoryRe + _nodeRe + _objectRe + _propertyRe + '$');
  31674. var _supportedObjectNames = ['material', 'materials', 'bones'];
  31675. function Composite(targetGroup, path, optionalParsedPath) {
  31676. var parsedPath = optionalParsedPath || PropertyBinding.parseTrackName(path);
  31677. this._targetGroup = targetGroup;
  31678. this._bindings = targetGroup.subscribe_(path, parsedPath);
  31679. }
  31680. Object.assign(Composite.prototype, {
  31681. getValue: function getValue(array, offset) {
  31682. this.bind(); // bind all binding
  31683. var firstValidIndex = this._targetGroup.nCachedObjects_,
  31684. binding = this._bindings[firstValidIndex]; // and only call .getValue on the first
  31685. if (binding !== undefined) binding.getValue(array, offset);
  31686. },
  31687. setValue: function setValue(array, offset) {
  31688. var bindings = this._bindings;
  31689. for (var i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++i) {
  31690. bindings[i].setValue(array, offset);
  31691. }
  31692. },
  31693. bind: function bind() {
  31694. var bindings = this._bindings;
  31695. for (var i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++i) {
  31696. bindings[i].bind();
  31697. }
  31698. },
  31699. unbind: function unbind() {
  31700. var bindings = this._bindings;
  31701. for (var i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++i) {
  31702. bindings[i].unbind();
  31703. }
  31704. }
  31705. });
  31706. function PropertyBinding(rootNode, path, parsedPath) {
  31707. this.path = path;
  31708. this.parsedPath = parsedPath || PropertyBinding.parseTrackName(path);
  31709. this.node = PropertyBinding.findNode(rootNode, this.parsedPath.nodeName) || rootNode;
  31710. this.rootNode = rootNode;
  31711. }
  31712. Object.assign(PropertyBinding, {
  31713. Composite: Composite,
  31714. create: function create(root, path, parsedPath) {
  31715. if (!(root && root.isAnimationObjectGroup)) {
  31716. return new PropertyBinding(root, path, parsedPath);
  31717. } else {
  31718. return new PropertyBinding.Composite(root, path, parsedPath);
  31719. }
  31720. },
  31721. /**
  31722. * Replaces spaces with underscores and removes unsupported characters from
  31723. * node names, to ensure compatibility with parseTrackName().
  31724. *
  31725. * @param {string} name Node name to be sanitized.
  31726. * @return {string}
  31727. */
  31728. sanitizeNodeName: function sanitizeNodeName(name) {
  31729. return name.replace(/\s/g, '_').replace(_reservedRe, '');
  31730. },
  31731. parseTrackName: function parseTrackName(trackName) {
  31732. var matches = _trackRe.exec(trackName);
  31733. if (!matches) {
  31734. throw new Error('PropertyBinding: Cannot parse trackName: ' + trackName);
  31735. }
  31736. var results = {
  31737. // directoryName: matches[ 1 ], // (tschw) currently unused
  31738. nodeName: matches[2],
  31739. objectName: matches[3],
  31740. objectIndex: matches[4],
  31741. propertyName: matches[5],
  31742. // required
  31743. propertyIndex: matches[6]
  31744. };
  31745. var lastDot = results.nodeName && results.nodeName.lastIndexOf('.');
  31746. if (lastDot !== undefined && lastDot !== -1) {
  31747. var objectName = results.nodeName.substring(lastDot + 1); // Object names must be checked against an allowlist. Otherwise, there
  31748. // is no way to parse 'foo.bar.baz': 'baz' must be a property, but
  31749. // 'bar' could be the objectName, or part of a nodeName (which can
  31750. // include '.' characters).
  31751. if (_supportedObjectNames.indexOf(objectName) !== -1) {
  31752. results.nodeName = results.nodeName.substring(0, lastDot);
  31753. results.objectName = objectName;
  31754. }
  31755. }
  31756. if (results.propertyName === null || results.propertyName.length === 0) {
  31757. throw new Error('PropertyBinding: can not parse propertyName from trackName: ' + trackName);
  31758. }
  31759. return results;
  31760. },
  31761. findNode: function findNode(root, nodeName) {
  31762. if (!nodeName || nodeName === '' || nodeName === '.' || nodeName === -1 || nodeName === root.name || nodeName === root.uuid) {
  31763. return root;
  31764. } // search into skeleton bones.
  31765. if (root.skeleton) {
  31766. var bone = root.skeleton.getBoneByName(nodeName);
  31767. if (bone !== undefined) {
  31768. return bone;
  31769. }
  31770. } // search into node subtree.
  31771. if (root.children) {
  31772. var searchNodeSubtree = function searchNodeSubtree(children) {
  31773. for (var i = 0; i < children.length; i++) {
  31774. var childNode = children[i];
  31775. if (childNode.name === nodeName || childNode.uuid === nodeName) {
  31776. return childNode;
  31777. }
  31778. var result = searchNodeSubtree(childNode.children);
  31779. if (result) return result;
  31780. }
  31781. return null;
  31782. };
  31783. var subTreeNode = searchNodeSubtree(root.children);
  31784. if (subTreeNode) {
  31785. return subTreeNode;
  31786. }
  31787. }
  31788. return null;
  31789. }
  31790. });
  31791. Object.assign(PropertyBinding.prototype, {
  31792. // prototype, continued
  31793. // these are used to "bind" a nonexistent property
  31794. _getValue_unavailable: function _getValue_unavailable() {},
  31795. _setValue_unavailable: function _setValue_unavailable() {},
  31796. BindingType: {
  31797. Direct: 0,
  31798. EntireArray: 1,
  31799. ArrayElement: 2,
  31800. HasFromToArray: 3
  31801. },
  31802. Versioning: {
  31803. None: 0,
  31804. NeedsUpdate: 1,
  31805. MatrixWorldNeedsUpdate: 2
  31806. },
  31807. GetterByBindingType: [function getValue_direct(buffer, offset) {
  31808. buffer[offset] = this.node[this.propertyName];
  31809. }, function getValue_array(buffer, offset) {
  31810. var source = this.resolvedProperty;
  31811. for (var i = 0, n = source.length; i !== n; ++i) {
  31812. buffer[offset++] = source[i];
  31813. }
  31814. }, function getValue_arrayElement(buffer, offset) {
  31815. buffer[offset] = this.resolvedProperty[this.propertyIndex];
  31816. }, function getValue_toArray(buffer, offset) {
  31817. this.resolvedProperty.toArray(buffer, offset);
  31818. }],
  31819. SetterByBindingTypeAndVersioning: [[// Direct
  31820. function setValue_direct(buffer, offset) {
  31821. this.targetObject[this.propertyName] = buffer[offset];
  31822. }, function setValue_direct_setNeedsUpdate(buffer, offset) {
  31823. this.targetObject[this.propertyName] = buffer[offset];
  31824. this.targetObject.needsUpdate = true;
  31825. }, function setValue_direct_setMatrixWorldNeedsUpdate(buffer, offset) {
  31826. this.targetObject[this.propertyName] = buffer[offset];
  31827. this.targetObject.matrixWorldNeedsUpdate = true;
  31828. }], [// EntireArray
  31829. function setValue_array(buffer, offset) {
  31830. var dest = this.resolvedProperty;
  31831. for (var i = 0, n = dest.length; i !== n; ++i) {
  31832. dest[i] = buffer[offset++];
  31833. }
  31834. }, function setValue_array_setNeedsUpdate(buffer, offset) {
  31835. var dest = this.resolvedProperty;
  31836. for (var i = 0, n = dest.length; i !== n; ++i) {
  31837. dest[i] = buffer[offset++];
  31838. }
  31839. this.targetObject.needsUpdate = true;
  31840. }, function setValue_array_setMatrixWorldNeedsUpdate(buffer, offset) {
  31841. var dest = this.resolvedProperty;
  31842. for (var i = 0, n = dest.length; i !== n; ++i) {
  31843. dest[i] = buffer[offset++];
  31844. }
  31845. this.targetObject.matrixWorldNeedsUpdate = true;
  31846. }], [// ArrayElement
  31847. function setValue_arrayElement(buffer, offset) {
  31848. this.resolvedProperty[this.propertyIndex] = buffer[offset];
  31849. }, function setValue_arrayElement_setNeedsUpdate(buffer, offset) {
  31850. this.resolvedProperty[this.propertyIndex] = buffer[offset];
  31851. this.targetObject.needsUpdate = true;
  31852. }, function setValue_arrayElement_setMatrixWorldNeedsUpdate(buffer, offset) {
  31853. this.resolvedProperty[this.propertyIndex] = buffer[offset];
  31854. this.targetObject.matrixWorldNeedsUpdate = true;
  31855. }], [// HasToFromArray
  31856. function setValue_fromArray(buffer, offset) {
  31857. this.resolvedProperty.fromArray(buffer, offset);
  31858. }, function setValue_fromArray_setNeedsUpdate(buffer, offset) {
  31859. this.resolvedProperty.fromArray(buffer, offset);
  31860. this.targetObject.needsUpdate = true;
  31861. }, function setValue_fromArray_setMatrixWorldNeedsUpdate(buffer, offset) {
  31862. this.resolvedProperty.fromArray(buffer, offset);
  31863. this.targetObject.matrixWorldNeedsUpdate = true;
  31864. }]],
  31865. getValue: function getValue_unbound(targetArray, offset) {
  31866. this.bind();
  31867. this.getValue(targetArray, offset); // Note: This class uses a State pattern on a per-method basis:
  31868. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  31869. // prototype version of these methods with one that represents
  31870. // the bound state. When the property is not found, the methods
  31871. // become no-ops.
  31872. },
  31873. setValue: function getValue_unbound(sourceArray, offset) {
  31874. this.bind();
  31875. this.setValue(sourceArray, offset);
  31876. },
  31877. // create getter / setter pair for a property in the scene graph
  31878. bind: function bind() {
  31879. var targetObject = this.node;
  31880. var parsedPath = this.parsedPath;
  31881. var objectName = parsedPath.objectName;
  31882. var propertyName = parsedPath.propertyName;
  31883. var propertyIndex = parsedPath.propertyIndex;
  31884. if (!targetObject) {
  31885. targetObject = PropertyBinding.findNode(this.rootNode, parsedPath.nodeName) || this.rootNode;
  31886. this.node = targetObject;
  31887. } // set fail state so we can just 'return' on error
  31888. this.getValue = this._getValue_unavailable;
  31889. this.setValue = this._setValue_unavailable; // ensure there is a value node
  31890. if (!targetObject) {
  31891. console.error('THREE.PropertyBinding: Trying to update node for track: ' + this.path + ' but it wasn\'t found.');
  31892. return;
  31893. }
  31894. if (objectName) {
  31895. var objectIndex = parsedPath.objectIndex; // special cases were we need to reach deeper into the hierarchy to get the face materials....
  31896. switch (objectName) {
  31897. case 'materials':
  31898. if (!targetObject.material) {
  31899. console.error('THREE.PropertyBinding: Can not bind to material as node does not have a material.', this);
  31900. return;
  31901. }
  31902. if (!targetObject.material.materials) {
  31903. console.error('THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.', this);
  31904. return;
  31905. }
  31906. targetObject = targetObject.material.materials;
  31907. break;
  31908. case 'bones':
  31909. if (!targetObject.skeleton) {
  31910. console.error('THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.', this);
  31911. return;
  31912. } // potential future optimization: skip this if propertyIndex is already an integer
  31913. // and convert the integer string to a true integer.
  31914. targetObject = targetObject.skeleton.bones; // support resolving morphTarget names into indices.
  31915. for (var i = 0; i < targetObject.length; i++) {
  31916. if (targetObject[i].name === objectIndex) {
  31917. objectIndex = i;
  31918. break;
  31919. }
  31920. }
  31921. break;
  31922. default:
  31923. if (targetObject[objectName] === undefined) {
  31924. console.error('THREE.PropertyBinding: Can not bind to objectName of node undefined.', this);
  31925. return;
  31926. }
  31927. targetObject = targetObject[objectName];
  31928. }
  31929. if (objectIndex !== undefined) {
  31930. if (targetObject[objectIndex] === undefined) {
  31931. console.error('THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject);
  31932. return;
  31933. }
  31934. targetObject = targetObject[objectIndex];
  31935. }
  31936. } // resolve property
  31937. var nodeProperty = targetObject[propertyName];
  31938. if (nodeProperty === undefined) {
  31939. var nodeName = parsedPath.nodeName;
  31940. console.error('THREE.PropertyBinding: Trying to update property for track: ' + nodeName + '.' + propertyName + ' but it wasn\'t found.', targetObject);
  31941. return;
  31942. } // determine versioning scheme
  31943. var versioning = this.Versioning.None;
  31944. this.targetObject = targetObject;
  31945. if (targetObject.needsUpdate !== undefined) {
  31946. // material
  31947. versioning = this.Versioning.NeedsUpdate;
  31948. } else if (targetObject.matrixWorldNeedsUpdate !== undefined) {
  31949. // node transform
  31950. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  31951. } // determine how the property gets bound
  31952. var bindingType = this.BindingType.Direct;
  31953. if (propertyIndex !== undefined) {
  31954. // access a sub element of the property array (only primitives are supported right now)
  31955. if (propertyName === 'morphTargetInfluences') {
  31956. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  31957. // support resolving morphTarget names into indices.
  31958. if (!targetObject.geometry) {
  31959. console.error('THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this);
  31960. return;
  31961. }
  31962. if (targetObject.geometry.isBufferGeometry) {
  31963. if (!targetObject.geometry.morphAttributes) {
  31964. console.error('THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this);
  31965. return;
  31966. }
  31967. if (targetObject.morphTargetDictionary[propertyIndex] !== undefined) {
  31968. propertyIndex = targetObject.morphTargetDictionary[propertyIndex];
  31969. }
  31970. } else {
  31971. console.error('THREE.PropertyBinding: Can not bind to morphTargetInfluences on THREE.Geometry. Use THREE.BufferGeometry instead.', this);
  31972. return;
  31973. }
  31974. }
  31975. bindingType = this.BindingType.ArrayElement;
  31976. this.resolvedProperty = nodeProperty;
  31977. this.propertyIndex = propertyIndex;
  31978. } else if (nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined) {
  31979. // must use copy for Object3D.Euler/Quaternion
  31980. bindingType = this.BindingType.HasFromToArray;
  31981. this.resolvedProperty = nodeProperty;
  31982. } else if (Array.isArray(nodeProperty)) {
  31983. bindingType = this.BindingType.EntireArray;
  31984. this.resolvedProperty = nodeProperty;
  31985. } else {
  31986. this.propertyName = propertyName;
  31987. } // select getter / setter
  31988. this.getValue = this.GetterByBindingType[bindingType];
  31989. this.setValue = this.SetterByBindingTypeAndVersioning[bindingType][versioning];
  31990. },
  31991. unbind: function unbind() {
  31992. this.node = null; // back to the prototype version of getValue / setValue
  31993. // note: avoiding to mutate the shape of 'this' via 'delete'
  31994. this.getValue = this._getValue_unbound;
  31995. this.setValue = this._setValue_unbound;
  31996. }
  31997. }); // DECLARE ALIAS AFTER assign prototype
  31998. Object.assign(PropertyBinding.prototype, {
  31999. // initial state of these methods that calls 'bind'
  32000. _getValue_unbound: PropertyBinding.prototype.getValue,
  32001. _setValue_unbound: PropertyBinding.prototype.setValue
  32002. });
  32003. /**
  32004. *
  32005. * A group of objects that receives a shared animation state.
  32006. *
  32007. * Usage:
  32008. *
  32009. * - Add objects you would otherwise pass as 'root' to the
  32010. * constructor or the .clipAction method of AnimationMixer.
  32011. *
  32012. * - Instead pass this object as 'root'.
  32013. *
  32014. * - You can also add and remove objects later when the mixer
  32015. * is running.
  32016. *
  32017. * Note:
  32018. *
  32019. * Objects of this class appear as one object to the mixer,
  32020. * so cache control of the individual objects must be done
  32021. * on the group.
  32022. *
  32023. * Limitation:
  32024. *
  32025. * - The animated properties must be compatible among the
  32026. * all objects in the group.
  32027. *
  32028. * - A single property can either be controlled through a
  32029. * target group or directly, but not both.
  32030. */
  32031. function AnimationObjectGroup() {
  32032. this.uuid = MathUtils.generateUUID(); // cached objects followed by the active ones
  32033. this._objects = Array.prototype.slice.call(arguments);
  32034. this.nCachedObjects_ = 0; // threshold
  32035. // note: read by PropertyBinding.Composite
  32036. var indices = {};
  32037. this._indicesByUUID = indices; // for bookkeeping
  32038. for (var i = 0, n = arguments.length; i !== n; ++i) {
  32039. indices[arguments[i].uuid] = i;
  32040. }
  32041. this._paths = []; // inside: string
  32042. this._parsedPaths = []; // inside: { we don't care, here }
  32043. this._bindings = []; // inside: Array< PropertyBinding >
  32044. this._bindingsIndicesByPath = {}; // inside: indices in these arrays
  32045. var scope = this;
  32046. this.stats = {
  32047. objects: {
  32048. get total() {
  32049. return scope._objects.length;
  32050. },
  32051. get inUse() {
  32052. return this.total - scope.nCachedObjects_;
  32053. }
  32054. },
  32055. get bindingsPerObject() {
  32056. return scope._bindings.length;
  32057. }
  32058. };
  32059. }
  32060. Object.assign(AnimationObjectGroup.prototype, {
  32061. isAnimationObjectGroup: true,
  32062. add: function add() {
  32063. var objects = this._objects,
  32064. indicesByUUID = this._indicesByUUID,
  32065. paths = this._paths,
  32066. parsedPaths = this._parsedPaths,
  32067. bindings = this._bindings,
  32068. nBindings = bindings.length;
  32069. var knownObject = undefined,
  32070. nObjects = objects.length,
  32071. nCachedObjects = this.nCachedObjects_;
  32072. for (var i = 0, n = arguments.length; i !== n; ++i) {
  32073. var object = arguments[i],
  32074. uuid = object.uuid;
  32075. var index = indicesByUUID[uuid];
  32076. if (index === undefined) {
  32077. // unknown object -> add it to the ACTIVE region
  32078. index = nObjects++;
  32079. indicesByUUID[uuid] = index;
  32080. objects.push(object); // accounting is done, now do the same for all bindings
  32081. for (var j = 0, m = nBindings; j !== m; ++j) {
  32082. bindings[j].push(new PropertyBinding(object, paths[j], parsedPaths[j]));
  32083. }
  32084. } else if (index < nCachedObjects) {
  32085. knownObject = objects[index]; // move existing object to the ACTIVE region
  32086. var firstActiveIndex = --nCachedObjects,
  32087. lastCachedObject = objects[firstActiveIndex];
  32088. indicesByUUID[lastCachedObject.uuid] = index;
  32089. objects[index] = lastCachedObject;
  32090. indicesByUUID[uuid] = firstActiveIndex;
  32091. objects[firstActiveIndex] = object; // accounting is done, now do the same for all bindings
  32092. for (var _j = 0, _m = nBindings; _j !== _m; ++_j) {
  32093. var bindingsForPath = bindings[_j],
  32094. lastCached = bindingsForPath[firstActiveIndex];
  32095. var binding = bindingsForPath[index];
  32096. bindingsForPath[index] = lastCached;
  32097. if (binding === undefined) {
  32098. // since we do not bother to create new bindings
  32099. // for objects that are cached, the binding may
  32100. // or may not exist
  32101. binding = new PropertyBinding(object, paths[_j], parsedPaths[_j]);
  32102. }
  32103. bindingsForPath[firstActiveIndex] = binding;
  32104. }
  32105. } else if (objects[index] !== knownObject) {
  32106. console.error('THREE.AnimationObjectGroup: Different objects with the same UUID ' + 'detected. Clean the caches or recreate your infrastructure when reloading scenes.');
  32107. } // else the object is already where we want it to be
  32108. } // for arguments
  32109. this.nCachedObjects_ = nCachedObjects;
  32110. },
  32111. remove: function remove() {
  32112. var objects = this._objects,
  32113. indicesByUUID = this._indicesByUUID,
  32114. bindings = this._bindings,
  32115. nBindings = bindings.length;
  32116. var nCachedObjects = this.nCachedObjects_;
  32117. for (var i = 0, n = arguments.length; i !== n; ++i) {
  32118. var object = arguments[i],
  32119. uuid = object.uuid,
  32120. index = indicesByUUID[uuid];
  32121. if (index !== undefined && index >= nCachedObjects) {
  32122. // move existing object into the CACHED region
  32123. var lastCachedIndex = nCachedObjects++,
  32124. firstActiveObject = objects[lastCachedIndex];
  32125. indicesByUUID[firstActiveObject.uuid] = index;
  32126. objects[index] = firstActiveObject;
  32127. indicesByUUID[uuid] = lastCachedIndex;
  32128. objects[lastCachedIndex] = object; // accounting is done, now do the same for all bindings
  32129. for (var j = 0, m = nBindings; j !== m; ++j) {
  32130. var bindingsForPath = bindings[j],
  32131. firstActive = bindingsForPath[lastCachedIndex],
  32132. binding = bindingsForPath[index];
  32133. bindingsForPath[index] = firstActive;
  32134. bindingsForPath[lastCachedIndex] = binding;
  32135. }
  32136. }
  32137. } // for arguments
  32138. this.nCachedObjects_ = nCachedObjects;
  32139. },
  32140. // remove & forget
  32141. uncache: function uncache() {
  32142. var objects = this._objects,
  32143. indicesByUUID = this._indicesByUUID,
  32144. bindings = this._bindings,
  32145. nBindings = bindings.length;
  32146. var nCachedObjects = this.nCachedObjects_,
  32147. nObjects = objects.length;
  32148. for (var i = 0, n = arguments.length; i !== n; ++i) {
  32149. var object = arguments[i],
  32150. uuid = object.uuid,
  32151. index = indicesByUUID[uuid];
  32152. if (index !== undefined) {
  32153. delete indicesByUUID[uuid];
  32154. if (index < nCachedObjects) {
  32155. // object is cached, shrink the CACHED region
  32156. var firstActiveIndex = --nCachedObjects,
  32157. lastCachedObject = objects[firstActiveIndex],
  32158. lastIndex = --nObjects,
  32159. lastObject = objects[lastIndex]; // last cached object takes this object's place
  32160. indicesByUUID[lastCachedObject.uuid] = index;
  32161. objects[index] = lastCachedObject; // last object goes to the activated slot and pop
  32162. indicesByUUID[lastObject.uuid] = firstActiveIndex;
  32163. objects[firstActiveIndex] = lastObject;
  32164. objects.pop(); // accounting is done, now do the same for all bindings
  32165. for (var j = 0, m = nBindings; j !== m; ++j) {
  32166. var bindingsForPath = bindings[j],
  32167. lastCached = bindingsForPath[firstActiveIndex],
  32168. last = bindingsForPath[lastIndex];
  32169. bindingsForPath[index] = lastCached;
  32170. bindingsForPath[firstActiveIndex] = last;
  32171. bindingsForPath.pop();
  32172. }
  32173. } else {
  32174. // object is active, just swap with the last and pop
  32175. var _lastIndex = --nObjects,
  32176. _lastObject = objects[_lastIndex];
  32177. if (_lastIndex > 0) {
  32178. indicesByUUID[_lastObject.uuid] = index;
  32179. }
  32180. objects[index] = _lastObject;
  32181. objects.pop(); // accounting is done, now do the same for all bindings
  32182. for (var _j2 = 0, _m2 = nBindings; _j2 !== _m2; ++_j2) {
  32183. var _bindingsForPath = bindings[_j2];
  32184. _bindingsForPath[index] = _bindingsForPath[_lastIndex];
  32185. _bindingsForPath.pop();
  32186. }
  32187. } // cached or active
  32188. } // if object is known
  32189. } // for arguments
  32190. this.nCachedObjects_ = nCachedObjects;
  32191. },
  32192. // Internal interface used by befriended PropertyBinding.Composite:
  32193. subscribe_: function subscribe_(path, parsedPath) {
  32194. // returns an array of bindings for the given path that is changed
  32195. // according to the contained objects in the group
  32196. var indicesByPath = this._bindingsIndicesByPath;
  32197. var index = indicesByPath[path];
  32198. var bindings = this._bindings;
  32199. if (index !== undefined) return bindings[index];
  32200. var paths = this._paths,
  32201. parsedPaths = this._parsedPaths,
  32202. objects = this._objects,
  32203. nObjects = objects.length,
  32204. nCachedObjects = this.nCachedObjects_,
  32205. bindingsForPath = new Array(nObjects);
  32206. index = bindings.length;
  32207. indicesByPath[path] = index;
  32208. paths.push(path);
  32209. parsedPaths.push(parsedPath);
  32210. bindings.push(bindingsForPath);
  32211. for (var i = nCachedObjects, n = objects.length; i !== n; ++i) {
  32212. var object = objects[i];
  32213. bindingsForPath[i] = new PropertyBinding(object, path, parsedPath);
  32214. }
  32215. return bindingsForPath;
  32216. },
  32217. unsubscribe_: function unsubscribe_(path) {
  32218. // tells the group to forget about a property path and no longer
  32219. // update the array previously obtained with 'subscribe_'
  32220. var indicesByPath = this._bindingsIndicesByPath,
  32221. index = indicesByPath[path];
  32222. if (index !== undefined) {
  32223. var paths = this._paths,
  32224. parsedPaths = this._parsedPaths,
  32225. bindings = this._bindings,
  32226. lastBindingsIndex = bindings.length - 1,
  32227. lastBindings = bindings[lastBindingsIndex],
  32228. lastBindingsPath = path[lastBindingsIndex];
  32229. indicesByPath[lastBindingsPath] = index;
  32230. bindings[index] = lastBindings;
  32231. bindings.pop();
  32232. parsedPaths[index] = parsedPaths[lastBindingsIndex];
  32233. parsedPaths.pop();
  32234. paths[index] = paths[lastBindingsIndex];
  32235. paths.pop();
  32236. }
  32237. }
  32238. });
  32239. var AnimationAction = /*#__PURE__*/function () {
  32240. function AnimationAction(mixer, clip, localRoot, blendMode) {
  32241. if (localRoot === void 0) {
  32242. localRoot = null;
  32243. }
  32244. if (blendMode === void 0) {
  32245. blendMode = clip.blendMode;
  32246. }
  32247. this._mixer = mixer;
  32248. this._clip = clip;
  32249. this._localRoot = localRoot;
  32250. this.blendMode = blendMode;
  32251. var tracks = clip.tracks,
  32252. nTracks = tracks.length,
  32253. interpolants = new Array(nTracks);
  32254. var interpolantSettings = {
  32255. endingStart: ZeroCurvatureEnding,
  32256. endingEnd: ZeroCurvatureEnding
  32257. };
  32258. for (var i = 0; i !== nTracks; ++i) {
  32259. var interpolant = tracks[i].createInterpolant(null);
  32260. interpolants[i] = interpolant;
  32261. interpolant.settings = interpolantSettings;
  32262. }
  32263. this._interpolantSettings = interpolantSettings;
  32264. this._interpolants = interpolants; // bound by the mixer
  32265. // inside: PropertyMixer (managed by the mixer)
  32266. this._propertyBindings = new Array(nTracks);
  32267. this._cacheIndex = null; // for the memory manager
  32268. this._byClipCacheIndex = null; // for the memory manager
  32269. this._timeScaleInterpolant = null;
  32270. this._weightInterpolant = null;
  32271. this.loop = LoopRepeat;
  32272. this._loopCount = -1; // global mixer time when the action is to be started
  32273. // it's set back to 'null' upon start of the action
  32274. this._startTime = null; // scaled local time of the action
  32275. // gets clamped or wrapped to 0..clip.duration according to loop
  32276. this.time = 0;
  32277. this.timeScale = 1;
  32278. this._effectiveTimeScale = 1;
  32279. this.weight = 1;
  32280. this._effectiveWeight = 1;
  32281. this.repetitions = Infinity; // no. of repetitions when looping
  32282. this.paused = false; // true -> zero effective time scale
  32283. this.enabled = true; // false -> zero effective weight
  32284. this.clampWhenFinished = false; // keep feeding the last frame?
  32285. this.zeroSlopeAtStart = true; // for smooth interpolation w/o separate
  32286. this.zeroSlopeAtEnd = true; // clips for start, loop and end
  32287. } // State & Scheduling
  32288. var _proto = AnimationAction.prototype;
  32289. _proto.play = function play() {
  32290. this._mixer._activateAction(this);
  32291. return this;
  32292. };
  32293. _proto.stop = function stop() {
  32294. this._mixer._deactivateAction(this);
  32295. return this.reset();
  32296. };
  32297. _proto.reset = function reset() {
  32298. this.paused = false;
  32299. this.enabled = true;
  32300. this.time = 0; // restart clip
  32301. this._loopCount = -1; // forget previous loops
  32302. this._startTime = null; // forget scheduling
  32303. return this.stopFading().stopWarping();
  32304. };
  32305. _proto.isRunning = function isRunning() {
  32306. return this.enabled && !this.paused && this.timeScale !== 0 && this._startTime === null && this._mixer._isActiveAction(this);
  32307. } // return true when play has been called
  32308. ;
  32309. _proto.isScheduled = function isScheduled() {
  32310. return this._mixer._isActiveAction(this);
  32311. };
  32312. _proto.startAt = function startAt(time) {
  32313. this._startTime = time;
  32314. return this;
  32315. };
  32316. _proto.setLoop = function setLoop(mode, repetitions) {
  32317. this.loop = mode;
  32318. this.repetitions = repetitions;
  32319. return this;
  32320. } // Weight
  32321. // set the weight stopping any scheduled fading
  32322. // although .enabled = false yields an effective weight of zero, this
  32323. // method does *not* change .enabled, because it would be confusing
  32324. ;
  32325. _proto.setEffectiveWeight = function setEffectiveWeight(weight) {
  32326. this.weight = weight; // note: same logic as when updated at runtime
  32327. this._effectiveWeight = this.enabled ? weight : 0;
  32328. return this.stopFading();
  32329. } // return the weight considering fading and .enabled
  32330. ;
  32331. _proto.getEffectiveWeight = function getEffectiveWeight() {
  32332. return this._effectiveWeight;
  32333. };
  32334. _proto.fadeIn = function fadeIn(duration) {
  32335. return this._scheduleFading(duration, 0, 1);
  32336. };
  32337. _proto.fadeOut = function fadeOut(duration) {
  32338. return this._scheduleFading(duration, 1, 0);
  32339. };
  32340. _proto.crossFadeFrom = function crossFadeFrom(fadeOutAction, duration, warp) {
  32341. fadeOutAction.fadeOut(duration);
  32342. this.fadeIn(duration);
  32343. if (warp) {
  32344. var fadeInDuration = this._clip.duration,
  32345. fadeOutDuration = fadeOutAction._clip.duration,
  32346. startEndRatio = fadeOutDuration / fadeInDuration,
  32347. endStartRatio = fadeInDuration / fadeOutDuration;
  32348. fadeOutAction.warp(1.0, startEndRatio, duration);
  32349. this.warp(endStartRatio, 1.0, duration);
  32350. }
  32351. return this;
  32352. };
  32353. _proto.crossFadeTo = function crossFadeTo(fadeInAction, duration, warp) {
  32354. return fadeInAction.crossFadeFrom(this, duration, warp);
  32355. };
  32356. _proto.stopFading = function stopFading() {
  32357. var weightInterpolant = this._weightInterpolant;
  32358. if (weightInterpolant !== null) {
  32359. this._weightInterpolant = null;
  32360. this._mixer._takeBackControlInterpolant(weightInterpolant);
  32361. }
  32362. return this;
  32363. } // Time Scale Control
  32364. // set the time scale stopping any scheduled warping
  32365. // although .paused = true yields an effective time scale of zero, this
  32366. // method does *not* change .paused, because it would be confusing
  32367. ;
  32368. _proto.setEffectiveTimeScale = function setEffectiveTimeScale(timeScale) {
  32369. this.timeScale = timeScale;
  32370. this._effectiveTimeScale = this.paused ? 0 : timeScale;
  32371. return this.stopWarping();
  32372. } // return the time scale considering warping and .paused
  32373. ;
  32374. _proto.getEffectiveTimeScale = function getEffectiveTimeScale() {
  32375. return this._effectiveTimeScale;
  32376. };
  32377. _proto.setDuration = function setDuration(duration) {
  32378. this.timeScale = this._clip.duration / duration;
  32379. return this.stopWarping();
  32380. };
  32381. _proto.syncWith = function syncWith(action) {
  32382. this.time = action.time;
  32383. this.timeScale = action.timeScale;
  32384. return this.stopWarping();
  32385. };
  32386. _proto.halt = function halt(duration) {
  32387. return this.warp(this._effectiveTimeScale, 0, duration);
  32388. };
  32389. _proto.warp = function warp(startTimeScale, endTimeScale, duration) {
  32390. var mixer = this._mixer,
  32391. now = mixer.time,
  32392. timeScale = this.timeScale;
  32393. var interpolant = this._timeScaleInterpolant;
  32394. if (interpolant === null) {
  32395. interpolant = mixer._lendControlInterpolant();
  32396. this._timeScaleInterpolant = interpolant;
  32397. }
  32398. var times = interpolant.parameterPositions,
  32399. values = interpolant.sampleValues;
  32400. times[0] = now;
  32401. times[1] = now + duration;
  32402. values[0] = startTimeScale / timeScale;
  32403. values[1] = endTimeScale / timeScale;
  32404. return this;
  32405. };
  32406. _proto.stopWarping = function stopWarping() {
  32407. var timeScaleInterpolant = this._timeScaleInterpolant;
  32408. if (timeScaleInterpolant !== null) {
  32409. this._timeScaleInterpolant = null;
  32410. this._mixer._takeBackControlInterpolant(timeScaleInterpolant);
  32411. }
  32412. return this;
  32413. } // Object Accessors
  32414. ;
  32415. _proto.getMixer = function getMixer() {
  32416. return this._mixer;
  32417. };
  32418. _proto.getClip = function getClip() {
  32419. return this._clip;
  32420. };
  32421. _proto.getRoot = function getRoot() {
  32422. return this._localRoot || this._mixer._root;
  32423. } // Interna
  32424. ;
  32425. _proto._update = function _update(time, deltaTime, timeDirection, accuIndex) {
  32426. // called by the mixer
  32427. if (!this.enabled) {
  32428. // call ._updateWeight() to update ._effectiveWeight
  32429. this._updateWeight(time);
  32430. return;
  32431. }
  32432. var startTime = this._startTime;
  32433. if (startTime !== null) {
  32434. // check for scheduled start of action
  32435. var timeRunning = (time - startTime) * timeDirection;
  32436. if (timeRunning < 0 || timeDirection === 0) {
  32437. return; // yet to come / don't decide when delta = 0
  32438. } // start
  32439. this._startTime = null; // unschedule
  32440. deltaTime = timeDirection * timeRunning;
  32441. } // apply time scale and advance time
  32442. deltaTime *= this._updateTimeScale(time);
  32443. var clipTime = this._updateTime(deltaTime); // note: _updateTime may disable the action resulting in
  32444. // an effective weight of 0
  32445. var weight = this._updateWeight(time);
  32446. if (weight > 0) {
  32447. var _interpolants = this._interpolants;
  32448. var propertyMixers = this._propertyBindings;
  32449. switch (this.blendMode) {
  32450. case AdditiveAnimationBlendMode:
  32451. for (var j = 0, m = _interpolants.length; j !== m; ++j) {
  32452. _interpolants[j].evaluate(clipTime);
  32453. propertyMixers[j].accumulateAdditive(weight);
  32454. }
  32455. break;
  32456. case NormalAnimationBlendMode:
  32457. default:
  32458. for (var _j = 0, _m = _interpolants.length; _j !== _m; ++_j) {
  32459. _interpolants[_j].evaluate(clipTime);
  32460. propertyMixers[_j].accumulate(accuIndex, weight);
  32461. }
  32462. }
  32463. }
  32464. };
  32465. _proto._updateWeight = function _updateWeight(time) {
  32466. var weight = 0;
  32467. if (this.enabled) {
  32468. weight = this.weight;
  32469. var interpolant = this._weightInterpolant;
  32470. if (interpolant !== null) {
  32471. var interpolantValue = interpolant.evaluate(time)[0];
  32472. weight *= interpolantValue;
  32473. if (time > interpolant.parameterPositions[1]) {
  32474. this.stopFading();
  32475. if (interpolantValue === 0) {
  32476. // faded out, disable
  32477. this.enabled = false;
  32478. }
  32479. }
  32480. }
  32481. }
  32482. this._effectiveWeight = weight;
  32483. return weight;
  32484. };
  32485. _proto._updateTimeScale = function _updateTimeScale(time) {
  32486. var timeScale = 0;
  32487. if (!this.paused) {
  32488. timeScale = this.timeScale;
  32489. var interpolant = this._timeScaleInterpolant;
  32490. if (interpolant !== null) {
  32491. var interpolantValue = interpolant.evaluate(time)[0];
  32492. timeScale *= interpolantValue;
  32493. if (time > interpolant.parameterPositions[1]) {
  32494. this.stopWarping();
  32495. if (timeScale === 0) {
  32496. // motion has halted, pause
  32497. this.paused = true;
  32498. } else {
  32499. // warp done - apply final time scale
  32500. this.timeScale = timeScale;
  32501. }
  32502. }
  32503. }
  32504. }
  32505. this._effectiveTimeScale = timeScale;
  32506. return timeScale;
  32507. };
  32508. _proto._updateTime = function _updateTime(deltaTime) {
  32509. var duration = this._clip.duration;
  32510. var loop = this.loop;
  32511. var time = this.time + deltaTime;
  32512. var loopCount = this._loopCount;
  32513. var pingPong = loop === LoopPingPong;
  32514. if (deltaTime === 0) {
  32515. if (loopCount === -1) return time;
  32516. return pingPong && (loopCount & 1) === 1 ? duration - time : time;
  32517. }
  32518. if (loop === LoopOnce) {
  32519. if (loopCount === -1) {
  32520. // just started
  32521. this._loopCount = 0;
  32522. this._setEndings(true, true, false);
  32523. }
  32524. handle_stop: {
  32525. if (time >= duration) {
  32526. time = duration;
  32527. } else if (time < 0) {
  32528. time = 0;
  32529. } else {
  32530. this.time = time;
  32531. break handle_stop;
  32532. }
  32533. if (this.clampWhenFinished) this.paused = true;else this.enabled = false;
  32534. this.time = time;
  32535. this._mixer.dispatchEvent({
  32536. type: 'finished',
  32537. action: this,
  32538. direction: deltaTime < 0 ? -1 : 1
  32539. });
  32540. }
  32541. } else {
  32542. // repetitive Repeat or PingPong
  32543. if (loopCount === -1) {
  32544. // just started
  32545. if (deltaTime >= 0) {
  32546. loopCount = 0;
  32547. this._setEndings(true, this.repetitions === 0, pingPong);
  32548. } else {
  32549. // when looping in reverse direction, the initial
  32550. // transition through zero counts as a repetition,
  32551. // so leave loopCount at -1
  32552. this._setEndings(this.repetitions === 0, true, pingPong);
  32553. }
  32554. }
  32555. if (time >= duration || time < 0) {
  32556. // wrap around
  32557. var loopDelta = Math.floor(time / duration); // signed
  32558. time -= duration * loopDelta;
  32559. loopCount += Math.abs(loopDelta);
  32560. var pending = this.repetitions - loopCount;
  32561. if (pending <= 0) {
  32562. // have to stop (switch state, clamp time, fire event)
  32563. if (this.clampWhenFinished) this.paused = true;else this.enabled = false;
  32564. time = deltaTime > 0 ? duration : 0;
  32565. this.time = time;
  32566. this._mixer.dispatchEvent({
  32567. type: 'finished',
  32568. action: this,
  32569. direction: deltaTime > 0 ? 1 : -1
  32570. });
  32571. } else {
  32572. // keep running
  32573. if (pending === 1) {
  32574. // entering the last round
  32575. var atStart = deltaTime < 0;
  32576. this._setEndings(atStart, !atStart, pingPong);
  32577. } else {
  32578. this._setEndings(false, false, pingPong);
  32579. }
  32580. this._loopCount = loopCount;
  32581. this.time = time;
  32582. this._mixer.dispatchEvent({
  32583. type: 'loop',
  32584. action: this,
  32585. loopDelta: loopDelta
  32586. });
  32587. }
  32588. } else {
  32589. this.time = time;
  32590. }
  32591. if (pingPong && (loopCount & 1) === 1) {
  32592. // invert time for the "pong round"
  32593. return duration - time;
  32594. }
  32595. }
  32596. return time;
  32597. };
  32598. _proto._setEndings = function _setEndings(atStart, atEnd, pingPong) {
  32599. var settings = this._interpolantSettings;
  32600. if (pingPong) {
  32601. settings.endingStart = ZeroSlopeEnding;
  32602. settings.endingEnd = ZeroSlopeEnding;
  32603. } else {
  32604. // assuming for LoopOnce atStart == atEnd == true
  32605. if (atStart) {
  32606. settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding;
  32607. } else {
  32608. settings.endingStart = WrapAroundEnding;
  32609. }
  32610. if (atEnd) {
  32611. settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding;
  32612. } else {
  32613. settings.endingEnd = WrapAroundEnding;
  32614. }
  32615. }
  32616. };
  32617. _proto._scheduleFading = function _scheduleFading(duration, weightNow, weightThen) {
  32618. var mixer = this._mixer,
  32619. now = mixer.time;
  32620. var interpolant = this._weightInterpolant;
  32621. if (interpolant === null) {
  32622. interpolant = mixer._lendControlInterpolant();
  32623. this._weightInterpolant = interpolant;
  32624. }
  32625. var times = interpolant.parameterPositions,
  32626. values = interpolant.sampleValues;
  32627. times[0] = now;
  32628. values[0] = weightNow;
  32629. times[1] = now + duration;
  32630. values[1] = weightThen;
  32631. return this;
  32632. };
  32633. return AnimationAction;
  32634. }();
  32635. function AnimationMixer(root) {
  32636. this._root = root;
  32637. this._initMemoryManager();
  32638. this._accuIndex = 0;
  32639. this.time = 0;
  32640. this.timeScale = 1.0;
  32641. }
  32642. AnimationMixer.prototype = Object.assign(Object.create(EventDispatcher.prototype), {
  32643. constructor: AnimationMixer,
  32644. _bindAction: function _bindAction(action, prototypeAction) {
  32645. var root = action._localRoot || this._root,
  32646. tracks = action._clip.tracks,
  32647. nTracks = tracks.length,
  32648. bindings = action._propertyBindings,
  32649. interpolants = action._interpolants,
  32650. rootUuid = root.uuid,
  32651. bindingsByRoot = this._bindingsByRootAndName;
  32652. var bindingsByName = bindingsByRoot[rootUuid];
  32653. if (bindingsByName === undefined) {
  32654. bindingsByName = {};
  32655. bindingsByRoot[rootUuid] = bindingsByName;
  32656. }
  32657. for (var i = 0; i !== nTracks; ++i) {
  32658. var track = tracks[i],
  32659. trackName = track.name;
  32660. var binding = bindingsByName[trackName];
  32661. if (binding !== undefined) {
  32662. bindings[i] = binding;
  32663. } else {
  32664. binding = bindings[i];
  32665. if (binding !== undefined) {
  32666. // existing binding, make sure the cache knows
  32667. if (binding._cacheIndex === null) {
  32668. ++binding.referenceCount;
  32669. this._addInactiveBinding(binding, rootUuid, trackName);
  32670. }
  32671. continue;
  32672. }
  32673. var path = prototypeAction && prototypeAction._propertyBindings[i].binding.parsedPath;
  32674. binding = new PropertyMixer(PropertyBinding.create(root, trackName, path), track.ValueTypeName, track.getValueSize());
  32675. ++binding.referenceCount;
  32676. this._addInactiveBinding(binding, rootUuid, trackName);
  32677. bindings[i] = binding;
  32678. }
  32679. interpolants[i].resultBuffer = binding.buffer;
  32680. }
  32681. },
  32682. _activateAction: function _activateAction(action) {
  32683. if (!this._isActiveAction(action)) {
  32684. if (action._cacheIndex === null) {
  32685. // this action has been forgotten by the cache, but the user
  32686. // appears to be still using it -> rebind
  32687. var rootUuid = (action._localRoot || this._root).uuid,
  32688. clipUuid = action._clip.uuid,
  32689. actionsForClip = this._actionsByClip[clipUuid];
  32690. this._bindAction(action, actionsForClip && actionsForClip.knownActions[0]);
  32691. this._addInactiveAction(action, clipUuid, rootUuid);
  32692. }
  32693. var bindings = action._propertyBindings; // increment reference counts / sort out state
  32694. for (var i = 0, n = bindings.length; i !== n; ++i) {
  32695. var binding = bindings[i];
  32696. if (binding.useCount++ === 0) {
  32697. this._lendBinding(binding);
  32698. binding.saveOriginalState();
  32699. }
  32700. }
  32701. this._lendAction(action);
  32702. }
  32703. },
  32704. _deactivateAction: function _deactivateAction(action) {
  32705. if (this._isActiveAction(action)) {
  32706. var bindings = action._propertyBindings; // decrement reference counts / sort out state
  32707. for (var i = 0, n = bindings.length; i !== n; ++i) {
  32708. var binding = bindings[i];
  32709. if (--binding.useCount === 0) {
  32710. binding.restoreOriginalState();
  32711. this._takeBackBinding(binding);
  32712. }
  32713. }
  32714. this._takeBackAction(action);
  32715. }
  32716. },
  32717. // Memory manager
  32718. _initMemoryManager: function _initMemoryManager() {
  32719. this._actions = []; // 'nActiveActions' followed by inactive ones
  32720. this._nActiveActions = 0;
  32721. this._actionsByClip = {}; // inside:
  32722. // {
  32723. // knownActions: Array< AnimationAction > - used as prototypes
  32724. // actionByRoot: AnimationAction - lookup
  32725. // }
  32726. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  32727. this._nActiveBindings = 0;
  32728. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  32729. this._controlInterpolants = []; // same game as above
  32730. this._nActiveControlInterpolants = 0;
  32731. var scope = this;
  32732. this.stats = {
  32733. actions: {
  32734. get total() {
  32735. return scope._actions.length;
  32736. },
  32737. get inUse() {
  32738. return scope._nActiveActions;
  32739. }
  32740. },
  32741. bindings: {
  32742. get total() {
  32743. return scope._bindings.length;
  32744. },
  32745. get inUse() {
  32746. return scope._nActiveBindings;
  32747. }
  32748. },
  32749. controlInterpolants: {
  32750. get total() {
  32751. return scope._controlInterpolants.length;
  32752. },
  32753. get inUse() {
  32754. return scope._nActiveControlInterpolants;
  32755. }
  32756. }
  32757. };
  32758. },
  32759. // Memory management for AnimationAction objects
  32760. _isActiveAction: function _isActiveAction(action) {
  32761. var index = action._cacheIndex;
  32762. return index !== null && index < this._nActiveActions;
  32763. },
  32764. _addInactiveAction: function _addInactiveAction(action, clipUuid, rootUuid) {
  32765. var actions = this._actions,
  32766. actionsByClip = this._actionsByClip;
  32767. var actionsForClip = actionsByClip[clipUuid];
  32768. if (actionsForClip === undefined) {
  32769. actionsForClip = {
  32770. knownActions: [action],
  32771. actionByRoot: {}
  32772. };
  32773. action._byClipCacheIndex = 0;
  32774. actionsByClip[clipUuid] = actionsForClip;
  32775. } else {
  32776. var knownActions = actionsForClip.knownActions;
  32777. action._byClipCacheIndex = knownActions.length;
  32778. knownActions.push(action);
  32779. }
  32780. action._cacheIndex = actions.length;
  32781. actions.push(action);
  32782. actionsForClip.actionByRoot[rootUuid] = action;
  32783. },
  32784. _removeInactiveAction: function _removeInactiveAction(action) {
  32785. var actions = this._actions,
  32786. lastInactiveAction = actions[actions.length - 1],
  32787. cacheIndex = action._cacheIndex;
  32788. lastInactiveAction._cacheIndex = cacheIndex;
  32789. actions[cacheIndex] = lastInactiveAction;
  32790. actions.pop();
  32791. action._cacheIndex = null;
  32792. var clipUuid = action._clip.uuid,
  32793. actionsByClip = this._actionsByClip,
  32794. actionsForClip = actionsByClip[clipUuid],
  32795. knownActionsForClip = actionsForClip.knownActions,
  32796. lastKnownAction = knownActionsForClip[knownActionsForClip.length - 1],
  32797. byClipCacheIndex = action._byClipCacheIndex;
  32798. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  32799. knownActionsForClip[byClipCacheIndex] = lastKnownAction;
  32800. knownActionsForClip.pop();
  32801. action._byClipCacheIndex = null;
  32802. var actionByRoot = actionsForClip.actionByRoot,
  32803. rootUuid = (action._localRoot || this._root).uuid;
  32804. delete actionByRoot[rootUuid];
  32805. if (knownActionsForClip.length === 0) {
  32806. delete actionsByClip[clipUuid];
  32807. }
  32808. this._removeInactiveBindingsForAction(action);
  32809. },
  32810. _removeInactiveBindingsForAction: function _removeInactiveBindingsForAction(action) {
  32811. var bindings = action._propertyBindings;
  32812. for (var i = 0, n = bindings.length; i !== n; ++i) {
  32813. var binding = bindings[i];
  32814. if (--binding.referenceCount === 0) {
  32815. this._removeInactiveBinding(binding);
  32816. }
  32817. }
  32818. },
  32819. _lendAction: function _lendAction(action) {
  32820. // [ active actions | inactive actions ]
  32821. // [ active actions >| inactive actions ]
  32822. // s a
  32823. // <-swap->
  32824. // a s
  32825. var actions = this._actions,
  32826. prevIndex = action._cacheIndex,
  32827. lastActiveIndex = this._nActiveActions++,
  32828. firstInactiveAction = actions[lastActiveIndex];
  32829. action._cacheIndex = lastActiveIndex;
  32830. actions[lastActiveIndex] = action;
  32831. firstInactiveAction._cacheIndex = prevIndex;
  32832. actions[prevIndex] = firstInactiveAction;
  32833. },
  32834. _takeBackAction: function _takeBackAction(action) {
  32835. // [ active actions | inactive actions ]
  32836. // [ active actions |< inactive actions ]
  32837. // a s
  32838. // <-swap->
  32839. // s a
  32840. var actions = this._actions,
  32841. prevIndex = action._cacheIndex,
  32842. firstInactiveIndex = --this._nActiveActions,
  32843. lastActiveAction = actions[firstInactiveIndex];
  32844. action._cacheIndex = firstInactiveIndex;
  32845. actions[firstInactiveIndex] = action;
  32846. lastActiveAction._cacheIndex = prevIndex;
  32847. actions[prevIndex] = lastActiveAction;
  32848. },
  32849. // Memory management for PropertyMixer objects
  32850. _addInactiveBinding: function _addInactiveBinding(binding, rootUuid, trackName) {
  32851. var bindingsByRoot = this._bindingsByRootAndName,
  32852. bindings = this._bindings;
  32853. var bindingByName = bindingsByRoot[rootUuid];
  32854. if (bindingByName === undefined) {
  32855. bindingByName = {};
  32856. bindingsByRoot[rootUuid] = bindingByName;
  32857. }
  32858. bindingByName[trackName] = binding;
  32859. binding._cacheIndex = bindings.length;
  32860. bindings.push(binding);
  32861. },
  32862. _removeInactiveBinding: function _removeInactiveBinding(binding) {
  32863. var bindings = this._bindings,
  32864. propBinding = binding.binding,
  32865. rootUuid = propBinding.rootNode.uuid,
  32866. trackName = propBinding.path,
  32867. bindingsByRoot = this._bindingsByRootAndName,
  32868. bindingByName = bindingsByRoot[rootUuid],
  32869. lastInactiveBinding = bindings[bindings.length - 1],
  32870. cacheIndex = binding._cacheIndex;
  32871. lastInactiveBinding._cacheIndex = cacheIndex;
  32872. bindings[cacheIndex] = lastInactiveBinding;
  32873. bindings.pop();
  32874. delete bindingByName[trackName];
  32875. if (Object.keys(bindingByName).length === 0) {
  32876. delete bindingsByRoot[rootUuid];
  32877. }
  32878. },
  32879. _lendBinding: function _lendBinding(binding) {
  32880. var bindings = this._bindings,
  32881. prevIndex = binding._cacheIndex,
  32882. lastActiveIndex = this._nActiveBindings++,
  32883. firstInactiveBinding = bindings[lastActiveIndex];
  32884. binding._cacheIndex = lastActiveIndex;
  32885. bindings[lastActiveIndex] = binding;
  32886. firstInactiveBinding._cacheIndex = prevIndex;
  32887. bindings[prevIndex] = firstInactiveBinding;
  32888. },
  32889. _takeBackBinding: function _takeBackBinding(binding) {
  32890. var bindings = this._bindings,
  32891. prevIndex = binding._cacheIndex,
  32892. firstInactiveIndex = --this._nActiveBindings,
  32893. lastActiveBinding = bindings[firstInactiveIndex];
  32894. binding._cacheIndex = firstInactiveIndex;
  32895. bindings[firstInactiveIndex] = binding;
  32896. lastActiveBinding._cacheIndex = prevIndex;
  32897. bindings[prevIndex] = lastActiveBinding;
  32898. },
  32899. // Memory management of Interpolants for weight and time scale
  32900. _lendControlInterpolant: function _lendControlInterpolant() {
  32901. var interpolants = this._controlInterpolants,
  32902. lastActiveIndex = this._nActiveControlInterpolants++;
  32903. var interpolant = interpolants[lastActiveIndex];
  32904. if (interpolant === undefined) {
  32905. interpolant = new LinearInterpolant(new Float32Array(2), new Float32Array(2), 1, this._controlInterpolantsResultBuffer);
  32906. interpolant.__cacheIndex = lastActiveIndex;
  32907. interpolants[lastActiveIndex] = interpolant;
  32908. }
  32909. return interpolant;
  32910. },
  32911. _takeBackControlInterpolant: function _takeBackControlInterpolant(interpolant) {
  32912. var interpolants = this._controlInterpolants,
  32913. prevIndex = interpolant.__cacheIndex,
  32914. firstInactiveIndex = --this._nActiveControlInterpolants,
  32915. lastActiveInterpolant = interpolants[firstInactiveIndex];
  32916. interpolant.__cacheIndex = firstInactiveIndex;
  32917. interpolants[firstInactiveIndex] = interpolant;
  32918. lastActiveInterpolant.__cacheIndex = prevIndex;
  32919. interpolants[prevIndex] = lastActiveInterpolant;
  32920. },
  32921. _controlInterpolantsResultBuffer: new Float32Array(1),
  32922. // return an action for a clip optionally using a custom root target
  32923. // object (this method allocates a lot of dynamic memory in case a
  32924. // previously unknown clip/root combination is specified)
  32925. clipAction: function clipAction(clip, optionalRoot, blendMode) {
  32926. var root = optionalRoot || this._root,
  32927. rootUuid = root.uuid;
  32928. var clipObject = typeof clip === 'string' ? AnimationClip.findByName(root, clip) : clip;
  32929. var clipUuid = clipObject !== null ? clipObject.uuid : clip;
  32930. var actionsForClip = this._actionsByClip[clipUuid];
  32931. var prototypeAction = null;
  32932. if (blendMode === undefined) {
  32933. if (clipObject !== null) {
  32934. blendMode = clipObject.blendMode;
  32935. } else {
  32936. blendMode = NormalAnimationBlendMode;
  32937. }
  32938. }
  32939. if (actionsForClip !== undefined) {
  32940. var existingAction = actionsForClip.actionByRoot[rootUuid];
  32941. if (existingAction !== undefined && existingAction.blendMode === blendMode) {
  32942. return existingAction;
  32943. } // we know the clip, so we don't have to parse all
  32944. // the bindings again but can just copy
  32945. prototypeAction = actionsForClip.knownActions[0]; // also, take the clip from the prototype action
  32946. if (clipObject === null) clipObject = prototypeAction._clip;
  32947. } // clip must be known when specified via string
  32948. if (clipObject === null) return null; // allocate all resources required to run it
  32949. var newAction = new AnimationAction(this, clipObject, optionalRoot, blendMode);
  32950. this._bindAction(newAction, prototypeAction); // and make the action known to the memory manager
  32951. this._addInactiveAction(newAction, clipUuid, rootUuid);
  32952. return newAction;
  32953. },
  32954. // get an existing action
  32955. existingAction: function existingAction(clip, optionalRoot) {
  32956. var root = optionalRoot || this._root,
  32957. rootUuid = root.uuid,
  32958. clipObject = typeof clip === 'string' ? AnimationClip.findByName(root, clip) : clip,
  32959. clipUuid = clipObject ? clipObject.uuid : clip,
  32960. actionsForClip = this._actionsByClip[clipUuid];
  32961. if (actionsForClip !== undefined) {
  32962. return actionsForClip.actionByRoot[rootUuid] || null;
  32963. }
  32964. return null;
  32965. },
  32966. // deactivates all previously scheduled actions
  32967. stopAllAction: function stopAllAction() {
  32968. var actions = this._actions,
  32969. nActions = this._nActiveActions;
  32970. for (var i = nActions - 1; i >= 0; --i) {
  32971. actions[i].stop();
  32972. }
  32973. return this;
  32974. },
  32975. // advance the time and update apply the animation
  32976. update: function update(deltaTime) {
  32977. deltaTime *= this.timeScale;
  32978. var actions = this._actions,
  32979. nActions = this._nActiveActions,
  32980. time = this.time += deltaTime,
  32981. timeDirection = Math.sign(deltaTime),
  32982. accuIndex = this._accuIndex ^= 1; // run active actions
  32983. for (var i = 0; i !== nActions; ++i) {
  32984. var action = actions[i];
  32985. action._update(time, deltaTime, timeDirection, accuIndex);
  32986. } // update scene graph
  32987. var bindings = this._bindings,
  32988. nBindings = this._nActiveBindings;
  32989. for (var _i = 0; _i !== nBindings; ++_i) {
  32990. bindings[_i].apply(accuIndex);
  32991. }
  32992. return this;
  32993. },
  32994. // Allows you to seek to a specific time in an animation.
  32995. setTime: function setTime(timeInSeconds) {
  32996. this.time = 0; // Zero out time attribute for AnimationMixer object;
  32997. for (var i = 0; i < this._actions.length; i++) {
  32998. this._actions[i].time = 0; // Zero out time attribute for all associated AnimationAction objects.
  32999. }
  33000. return this.update(timeInSeconds); // Update used to set exact time. Returns "this" AnimationMixer object.
  33001. },
  33002. // return this mixer's root target object
  33003. getRoot: function getRoot() {
  33004. return this._root;
  33005. },
  33006. // free all resources specific to a particular clip
  33007. uncacheClip: function uncacheClip(clip) {
  33008. var actions = this._actions,
  33009. clipUuid = clip.uuid,
  33010. actionsByClip = this._actionsByClip,
  33011. actionsForClip = actionsByClip[clipUuid];
  33012. if (actionsForClip !== undefined) {
  33013. // note: just calling _removeInactiveAction would mess up the
  33014. // iteration state and also require updating the state we can
  33015. // just throw away
  33016. var actionsToRemove = actionsForClip.knownActions;
  33017. for (var i = 0, n = actionsToRemove.length; i !== n; ++i) {
  33018. var action = actionsToRemove[i];
  33019. this._deactivateAction(action);
  33020. var cacheIndex = action._cacheIndex,
  33021. lastInactiveAction = actions[actions.length - 1];
  33022. action._cacheIndex = null;
  33023. action._byClipCacheIndex = null;
  33024. lastInactiveAction._cacheIndex = cacheIndex;
  33025. actions[cacheIndex] = lastInactiveAction;
  33026. actions.pop();
  33027. this._removeInactiveBindingsForAction(action);
  33028. }
  33029. delete actionsByClip[clipUuid];
  33030. }
  33031. },
  33032. // free all resources specific to a particular root target object
  33033. uncacheRoot: function uncacheRoot(root) {
  33034. var rootUuid = root.uuid,
  33035. actionsByClip = this._actionsByClip;
  33036. for (var clipUuid in actionsByClip) {
  33037. var actionByRoot = actionsByClip[clipUuid].actionByRoot,
  33038. action = actionByRoot[rootUuid];
  33039. if (action !== undefined) {
  33040. this._deactivateAction(action);
  33041. this._removeInactiveAction(action);
  33042. }
  33043. }
  33044. var bindingsByRoot = this._bindingsByRootAndName,
  33045. bindingByName = bindingsByRoot[rootUuid];
  33046. if (bindingByName !== undefined) {
  33047. for (var trackName in bindingByName) {
  33048. var binding = bindingByName[trackName];
  33049. binding.restoreOriginalState();
  33050. this._removeInactiveBinding(binding);
  33051. }
  33052. }
  33053. },
  33054. // remove a targeted clip from the cache
  33055. uncacheAction: function uncacheAction(clip, optionalRoot) {
  33056. var action = this.existingAction(clip, optionalRoot);
  33057. if (action !== null) {
  33058. this._deactivateAction(action);
  33059. this._removeInactiveAction(action);
  33060. }
  33061. }
  33062. });
  33063. var Uniform = /*#__PURE__*/function () {
  33064. function Uniform(value) {
  33065. if (typeof value === 'string') {
  33066. console.warn('THREE.Uniform: Type parameter is no longer needed.');
  33067. value = arguments[1];
  33068. }
  33069. this.value = value;
  33070. }
  33071. var _proto = Uniform.prototype;
  33072. _proto.clone = function clone() {
  33073. return new Uniform(this.value.clone === undefined ? this.value : this.value.clone());
  33074. };
  33075. return Uniform;
  33076. }();
  33077. function InstancedInterleavedBuffer(array, stride, meshPerAttribute) {
  33078. InterleavedBuffer.call(this, array, stride);
  33079. this.meshPerAttribute = meshPerAttribute || 1;
  33080. }
  33081. InstancedInterleavedBuffer.prototype = Object.assign(Object.create(InterleavedBuffer.prototype), {
  33082. constructor: InstancedInterleavedBuffer,
  33083. isInstancedInterleavedBuffer: true,
  33084. copy: function copy(source) {
  33085. InterleavedBuffer.prototype.copy.call(this, source);
  33086. this.meshPerAttribute = source.meshPerAttribute;
  33087. return this;
  33088. },
  33089. clone: function clone(data) {
  33090. var ib = InterleavedBuffer.prototype.clone.call(this, data);
  33091. ib.meshPerAttribute = this.meshPerAttribute;
  33092. return ib;
  33093. },
  33094. toJSON: function toJSON(data) {
  33095. var json = InterleavedBuffer.prototype.toJSON.call(this, data);
  33096. json.isInstancedInterleavedBuffer = true;
  33097. json.meshPerAttribute = this.meshPerAttribute;
  33098. return json;
  33099. }
  33100. });
  33101. function GLBufferAttribute(buffer, type, itemSize, elementSize, count) {
  33102. this.buffer = buffer;
  33103. this.type = type;
  33104. this.itemSize = itemSize;
  33105. this.elementSize = elementSize;
  33106. this.count = count;
  33107. this.version = 0;
  33108. }
  33109. Object.defineProperty(GLBufferAttribute.prototype, 'needsUpdate', {
  33110. set: function set(value) {
  33111. if (value === true) this.version++;
  33112. }
  33113. });
  33114. Object.assign(GLBufferAttribute.prototype, {
  33115. isGLBufferAttribute: true,
  33116. setBuffer: function setBuffer(buffer) {
  33117. this.buffer = buffer;
  33118. return this;
  33119. },
  33120. setType: function setType(type, elementSize) {
  33121. this.type = type;
  33122. this.elementSize = elementSize;
  33123. return this;
  33124. },
  33125. setItemSize: function setItemSize(itemSize) {
  33126. this.itemSize = itemSize;
  33127. return this;
  33128. },
  33129. setCount: function setCount(count) {
  33130. this.count = count;
  33131. return this;
  33132. }
  33133. });
  33134. function Raycaster(origin, direction, near, far) {
  33135. this.ray = new Ray(origin, direction); // direction is assumed to be normalized (for accurate distance calculations)
  33136. this.near = near || 0;
  33137. this.far = far || Infinity;
  33138. this.camera = null;
  33139. this.layers = new Layers();
  33140. this.params = {
  33141. Mesh: {},
  33142. Line: {
  33143. threshold: 1
  33144. },
  33145. LOD: {},
  33146. Points: {
  33147. threshold: 1
  33148. },
  33149. Sprite: {}
  33150. };
  33151. Object.defineProperties(this.params, {
  33152. PointCloud: {
  33153. get: function get() {
  33154. console.warn('THREE.Raycaster: params.PointCloud has been renamed to params.Points.');
  33155. return this.Points;
  33156. }
  33157. }
  33158. });
  33159. }
  33160. function ascSort(a, b) {
  33161. return a.distance - b.distance;
  33162. }
  33163. function _intersectObject(object, raycaster, intersects, recursive) {
  33164. if (object.layers.test(raycaster.layers)) {
  33165. object.raycast(raycaster, intersects);
  33166. }
  33167. if (recursive === true) {
  33168. var children = object.children;
  33169. for (var i = 0, l = children.length; i < l; i++) {
  33170. _intersectObject(children[i], raycaster, intersects, true);
  33171. }
  33172. }
  33173. }
  33174. Object.assign(Raycaster.prototype, {
  33175. set: function set(origin, direction) {
  33176. // direction is assumed to be normalized (for accurate distance calculations)
  33177. this.ray.set(origin, direction);
  33178. },
  33179. setFromCamera: function setFromCamera(coords, camera) {
  33180. if (camera && camera.isPerspectiveCamera) {
  33181. this.ray.origin.setFromMatrixPosition(camera.matrixWorld);
  33182. this.ray.direction.set(coords.x, coords.y, 0.5).unproject(camera).sub(this.ray.origin).normalize();
  33183. this.camera = camera;
  33184. } else if (camera && camera.isOrthographicCamera) {
  33185. this.ray.origin.set(coords.x, coords.y, (camera.near + camera.far) / (camera.near - camera.far)).unproject(camera); // set origin in plane of camera
  33186. this.ray.direction.set(0, 0, -1).transformDirection(camera.matrixWorld);
  33187. this.camera = camera;
  33188. } else {
  33189. console.error('THREE.Raycaster: Unsupported camera type: ' + camera.type);
  33190. }
  33191. },
  33192. intersectObject: function intersectObject(object, recursive, optionalTarget) {
  33193. var intersects = optionalTarget || [];
  33194. _intersectObject(object, this, intersects, recursive);
  33195. intersects.sort(ascSort);
  33196. return intersects;
  33197. },
  33198. intersectObjects: function intersectObjects(objects, recursive, optionalTarget) {
  33199. var intersects = optionalTarget || [];
  33200. if (Array.isArray(objects) === false) {
  33201. console.warn('THREE.Raycaster.intersectObjects: objects is not an Array.');
  33202. return intersects;
  33203. }
  33204. for (var i = 0, l = objects.length; i < l; i++) {
  33205. _intersectObject(objects[i], this, intersects, recursive);
  33206. }
  33207. intersects.sort(ascSort);
  33208. return intersects;
  33209. }
  33210. });
  33211. /**
  33212. * Ref: https://en.wikipedia.org/wiki/Spherical_coordinate_system
  33213. *
  33214. * The polar angle (phi) is measured from the positive y-axis. The positive y-axis is up.
  33215. * The azimuthal angle (theta) is measured from the positive z-axis.
  33216. */
  33217. var Spherical = /*#__PURE__*/function () {
  33218. function Spherical(radius, phi, theta) {
  33219. if (radius === void 0) {
  33220. radius = 1;
  33221. }
  33222. if (phi === void 0) {
  33223. phi = 0;
  33224. }
  33225. if (theta === void 0) {
  33226. theta = 0;
  33227. }
  33228. this.radius = radius;
  33229. this.phi = phi; // polar angle
  33230. this.theta = theta; // azimuthal angle
  33231. return this;
  33232. }
  33233. var _proto = Spherical.prototype;
  33234. _proto.set = function set(radius, phi, theta) {
  33235. this.radius = radius;
  33236. this.phi = phi;
  33237. this.theta = theta;
  33238. return this;
  33239. };
  33240. _proto.clone = function clone() {
  33241. return new this.constructor().copy(this);
  33242. };
  33243. _proto.copy = function copy(other) {
  33244. this.radius = other.radius;
  33245. this.phi = other.phi;
  33246. this.theta = other.theta;
  33247. return this;
  33248. } // restrict phi to be betwee EPS and PI-EPS
  33249. ;
  33250. _proto.makeSafe = function makeSafe() {
  33251. var EPS = 0.000001;
  33252. this.phi = Math.max(EPS, Math.min(Math.PI - EPS, this.phi));
  33253. return this;
  33254. };
  33255. _proto.setFromVector3 = function setFromVector3(v) {
  33256. return this.setFromCartesianCoords(v.x, v.y, v.z);
  33257. };
  33258. _proto.setFromCartesianCoords = function setFromCartesianCoords(x, y, z) {
  33259. this.radius = Math.sqrt(x * x + y * y + z * z);
  33260. if (this.radius === 0) {
  33261. this.theta = 0;
  33262. this.phi = 0;
  33263. } else {
  33264. this.theta = Math.atan2(x, z);
  33265. this.phi = Math.acos(MathUtils.clamp(y / this.radius, -1, 1));
  33266. }
  33267. return this;
  33268. };
  33269. return Spherical;
  33270. }();
  33271. /**
  33272. * Ref: https://en.wikipedia.org/wiki/Cylindrical_coordinate_system
  33273. */
  33274. var Cylindrical = /*#__PURE__*/function () {
  33275. function Cylindrical(radius, theta, y) {
  33276. this.radius = radius !== undefined ? radius : 1.0; // distance from the origin to a point in the x-z plane
  33277. this.theta = theta !== undefined ? theta : 0; // counterclockwise angle in the x-z plane measured in radians from the positive z-axis
  33278. this.y = y !== undefined ? y : 0; // height above the x-z plane
  33279. return this;
  33280. }
  33281. var _proto = Cylindrical.prototype;
  33282. _proto.set = function set(radius, theta, y) {
  33283. this.radius = radius;
  33284. this.theta = theta;
  33285. this.y = y;
  33286. return this;
  33287. };
  33288. _proto.clone = function clone() {
  33289. return new this.constructor().copy(this);
  33290. };
  33291. _proto.copy = function copy(other) {
  33292. this.radius = other.radius;
  33293. this.theta = other.theta;
  33294. this.y = other.y;
  33295. return this;
  33296. };
  33297. _proto.setFromVector3 = function setFromVector3(v) {
  33298. return this.setFromCartesianCoords(v.x, v.y, v.z);
  33299. };
  33300. _proto.setFromCartesianCoords = function setFromCartesianCoords(x, y, z) {
  33301. this.radius = Math.sqrt(x * x + z * z);
  33302. this.theta = Math.atan2(x, z);
  33303. this.y = y;
  33304. return this;
  33305. };
  33306. return Cylindrical;
  33307. }();
  33308. var _vector$8 = /*@__PURE__*/new Vector2();
  33309. var Box2 = /*#__PURE__*/function () {
  33310. function Box2(min, max) {
  33311. Object.defineProperty(this, 'isBox2', {
  33312. value: true
  33313. });
  33314. this.min = min !== undefined ? min : new Vector2(+Infinity, +Infinity);
  33315. this.max = max !== undefined ? max : new Vector2(-Infinity, -Infinity);
  33316. }
  33317. var _proto = Box2.prototype;
  33318. _proto.set = function set(min, max) {
  33319. this.min.copy(min);
  33320. this.max.copy(max);
  33321. return this;
  33322. };
  33323. _proto.setFromPoints = function setFromPoints(points) {
  33324. this.makeEmpty();
  33325. for (var i = 0, il = points.length; i < il; i++) {
  33326. this.expandByPoint(points[i]);
  33327. }
  33328. return this;
  33329. };
  33330. _proto.setFromCenterAndSize = function setFromCenterAndSize(center, size) {
  33331. var halfSize = _vector$8.copy(size).multiplyScalar(0.5);
  33332. this.min.copy(center).sub(halfSize);
  33333. this.max.copy(center).add(halfSize);
  33334. return this;
  33335. };
  33336. _proto.clone = function clone() {
  33337. return new this.constructor().copy(this);
  33338. };
  33339. _proto.copy = function copy(box) {
  33340. this.min.copy(box.min);
  33341. this.max.copy(box.max);
  33342. return this;
  33343. };
  33344. _proto.makeEmpty = function makeEmpty() {
  33345. this.min.x = this.min.y = +Infinity;
  33346. this.max.x = this.max.y = -Infinity;
  33347. return this;
  33348. };
  33349. _proto.isEmpty = function isEmpty() {
  33350. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  33351. return this.max.x < this.min.x || this.max.y < this.min.y;
  33352. };
  33353. _proto.getCenter = function getCenter(target) {
  33354. if (target === undefined) {
  33355. console.warn('THREE.Box2: .getCenter() target is now required');
  33356. target = new Vector2();
  33357. }
  33358. return this.isEmpty() ? target.set(0, 0) : target.addVectors(this.min, this.max).multiplyScalar(0.5);
  33359. };
  33360. _proto.getSize = function getSize(target) {
  33361. if (target === undefined) {
  33362. console.warn('THREE.Box2: .getSize() target is now required');
  33363. target = new Vector2();
  33364. }
  33365. return this.isEmpty() ? target.set(0, 0) : target.subVectors(this.max, this.min);
  33366. };
  33367. _proto.expandByPoint = function expandByPoint(point) {
  33368. this.min.min(point);
  33369. this.max.max(point);
  33370. return this;
  33371. };
  33372. _proto.expandByVector = function expandByVector(vector) {
  33373. this.min.sub(vector);
  33374. this.max.add(vector);
  33375. return this;
  33376. };
  33377. _proto.expandByScalar = function expandByScalar(scalar) {
  33378. this.min.addScalar(-scalar);
  33379. this.max.addScalar(scalar);
  33380. return this;
  33381. };
  33382. _proto.containsPoint = function containsPoint(point) {
  33383. return point.x < this.min.x || point.x > this.max.x || point.y < this.min.y || point.y > this.max.y ? false : true;
  33384. };
  33385. _proto.containsBox = function containsBox(box) {
  33386. return this.min.x <= box.min.x && box.max.x <= this.max.x && this.min.y <= box.min.y && box.max.y <= this.max.y;
  33387. };
  33388. _proto.getParameter = function getParameter(point, target) {
  33389. // This can potentially have a divide by zero if the box
  33390. // has a size dimension of 0.
  33391. if (target === undefined) {
  33392. console.warn('THREE.Box2: .getParameter() target is now required');
  33393. target = new Vector2();
  33394. }
  33395. return target.set((point.x - this.min.x) / (this.max.x - this.min.x), (point.y - this.min.y) / (this.max.y - this.min.y));
  33396. };
  33397. _proto.intersectsBox = function intersectsBox(box) {
  33398. // using 4 splitting planes to rule out intersections
  33399. return box.max.x < this.min.x || box.min.x > this.max.x || box.max.y < this.min.y || box.min.y > this.max.y ? false : true;
  33400. };
  33401. _proto.clampPoint = function clampPoint(point, target) {
  33402. if (target === undefined) {
  33403. console.warn('THREE.Box2: .clampPoint() target is now required');
  33404. target = new Vector2();
  33405. }
  33406. return target.copy(point).clamp(this.min, this.max);
  33407. };
  33408. _proto.distanceToPoint = function distanceToPoint(point) {
  33409. var clampedPoint = _vector$8.copy(point).clamp(this.min, this.max);
  33410. return clampedPoint.sub(point).length();
  33411. };
  33412. _proto.intersect = function intersect(box) {
  33413. this.min.max(box.min);
  33414. this.max.min(box.max);
  33415. return this;
  33416. };
  33417. _proto.union = function union(box) {
  33418. this.min.min(box.min);
  33419. this.max.max(box.max);
  33420. return this;
  33421. };
  33422. _proto.translate = function translate(offset) {
  33423. this.min.add(offset);
  33424. this.max.add(offset);
  33425. return this;
  33426. };
  33427. _proto.equals = function equals(box) {
  33428. return box.min.equals(this.min) && box.max.equals(this.max);
  33429. };
  33430. return Box2;
  33431. }();
  33432. var _startP = /*@__PURE__*/new Vector3();
  33433. var _startEnd = /*@__PURE__*/new Vector3();
  33434. var Line3 = /*#__PURE__*/function () {
  33435. function Line3(start, end) {
  33436. this.start = start !== undefined ? start : new Vector3();
  33437. this.end = end !== undefined ? end : new Vector3();
  33438. }
  33439. var _proto = Line3.prototype;
  33440. _proto.set = function set(start, end) {
  33441. this.start.copy(start);
  33442. this.end.copy(end);
  33443. return this;
  33444. };
  33445. _proto.clone = function clone() {
  33446. return new this.constructor().copy(this);
  33447. };
  33448. _proto.copy = function copy(line) {
  33449. this.start.copy(line.start);
  33450. this.end.copy(line.end);
  33451. return this;
  33452. };
  33453. _proto.getCenter = function getCenter(target) {
  33454. if (target === undefined) {
  33455. console.warn('THREE.Line3: .getCenter() target is now required');
  33456. target = new Vector3();
  33457. }
  33458. return target.addVectors(this.start, this.end).multiplyScalar(0.5);
  33459. };
  33460. _proto.delta = function delta(target) {
  33461. if (target === undefined) {
  33462. console.warn('THREE.Line3: .delta() target is now required');
  33463. target = new Vector3();
  33464. }
  33465. return target.subVectors(this.end, this.start);
  33466. };
  33467. _proto.distanceSq = function distanceSq() {
  33468. return this.start.distanceToSquared(this.end);
  33469. };
  33470. _proto.distance = function distance() {
  33471. return this.start.distanceTo(this.end);
  33472. };
  33473. _proto.at = function at(t, target) {
  33474. if (target === undefined) {
  33475. console.warn('THREE.Line3: .at() target is now required');
  33476. target = new Vector3();
  33477. }
  33478. return this.delta(target).multiplyScalar(t).add(this.start);
  33479. };
  33480. _proto.closestPointToPointParameter = function closestPointToPointParameter(point, clampToLine) {
  33481. _startP.subVectors(point, this.start);
  33482. _startEnd.subVectors(this.end, this.start);
  33483. var startEnd2 = _startEnd.dot(_startEnd);
  33484. var startEnd_startP = _startEnd.dot(_startP);
  33485. var t = startEnd_startP / startEnd2;
  33486. if (clampToLine) {
  33487. t = MathUtils.clamp(t, 0, 1);
  33488. }
  33489. return t;
  33490. };
  33491. _proto.closestPointToPoint = function closestPointToPoint(point, clampToLine, target) {
  33492. var t = this.closestPointToPointParameter(point, clampToLine);
  33493. if (target === undefined) {
  33494. console.warn('THREE.Line3: .closestPointToPoint() target is now required');
  33495. target = new Vector3();
  33496. }
  33497. return this.delta(target).multiplyScalar(t).add(this.start);
  33498. };
  33499. _proto.applyMatrix4 = function applyMatrix4(matrix) {
  33500. this.start.applyMatrix4(matrix);
  33501. this.end.applyMatrix4(matrix);
  33502. return this;
  33503. };
  33504. _proto.equals = function equals(line) {
  33505. return line.start.equals(this.start) && line.end.equals(this.end);
  33506. };
  33507. return Line3;
  33508. }();
  33509. function ImmediateRenderObject(material) {
  33510. Object3D.call(this);
  33511. this.material = material;
  33512. this.render = function ()
  33513. /* renderCallback */
  33514. {};
  33515. this.hasPositions = false;
  33516. this.hasNormals = false;
  33517. this.hasColors = false;
  33518. this.hasUvs = false;
  33519. this.positionArray = null;
  33520. this.normalArray = null;
  33521. this.colorArray = null;
  33522. this.uvArray = null;
  33523. this.count = 0;
  33524. }
  33525. ImmediateRenderObject.prototype = Object.create(Object3D.prototype);
  33526. ImmediateRenderObject.prototype.constructor = ImmediateRenderObject;
  33527. ImmediateRenderObject.prototype.isImmediateRenderObject = true;
  33528. var _vector$9 = /*@__PURE__*/new Vector3();
  33529. var SpotLightHelper = /*#__PURE__*/function (_Object3D) {
  33530. _inheritsLoose(SpotLightHelper, _Object3D);
  33531. function SpotLightHelper(light, color) {
  33532. var _this;
  33533. _this = _Object3D.call(this) || this;
  33534. _this.light = light;
  33535. _this.light.updateMatrixWorld();
  33536. _this.matrix = light.matrixWorld;
  33537. _this.matrixAutoUpdate = false;
  33538. _this.color = color;
  33539. var geometry = new BufferGeometry();
  33540. var positions = [0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, -1, 0, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, -1, 1];
  33541. for (var i = 0, j = 1, l = 32; i < l; i++, j++) {
  33542. var p1 = i / l * Math.PI * 2;
  33543. var p2 = j / l * Math.PI * 2;
  33544. positions.push(Math.cos(p1), Math.sin(p1), 1, Math.cos(p2), Math.sin(p2), 1);
  33545. }
  33546. geometry.setAttribute('position', new Float32BufferAttribute(positions, 3));
  33547. var material = new LineBasicMaterial({
  33548. fog: false,
  33549. toneMapped: false
  33550. });
  33551. _this.cone = new LineSegments(geometry, material);
  33552. _this.add(_this.cone);
  33553. _this.update();
  33554. return _this;
  33555. }
  33556. var _proto = SpotLightHelper.prototype;
  33557. _proto.dispose = function dispose() {
  33558. this.cone.geometry.dispose();
  33559. this.cone.material.dispose();
  33560. };
  33561. _proto.update = function update() {
  33562. this.light.updateMatrixWorld();
  33563. var coneLength = this.light.distance ? this.light.distance : 1000;
  33564. var coneWidth = coneLength * Math.tan(this.light.angle);
  33565. this.cone.scale.set(coneWidth, coneWidth, coneLength);
  33566. _vector$9.setFromMatrixPosition(this.light.target.matrixWorld);
  33567. this.cone.lookAt(_vector$9);
  33568. if (this.color !== undefined) {
  33569. this.cone.material.color.set(this.color);
  33570. } else {
  33571. this.cone.material.color.copy(this.light.color);
  33572. }
  33573. };
  33574. return SpotLightHelper;
  33575. }(Object3D);
  33576. var _vector$a = /*@__PURE__*/new Vector3();
  33577. var _boneMatrix = /*@__PURE__*/new Matrix4();
  33578. var _matrixWorldInv = /*@__PURE__*/new Matrix4();
  33579. var SkeletonHelper = /*#__PURE__*/function (_LineSegments) {
  33580. _inheritsLoose(SkeletonHelper, _LineSegments);
  33581. function SkeletonHelper(object) {
  33582. var _this;
  33583. var bones = getBoneList(object);
  33584. var geometry = new BufferGeometry();
  33585. var vertices = [];
  33586. var colors = [];
  33587. var color1 = new Color(0, 0, 1);
  33588. var color2 = new Color(0, 1, 0);
  33589. for (var i = 0; i < bones.length; i++) {
  33590. var bone = bones[i];
  33591. if (bone.parent && bone.parent.isBone) {
  33592. vertices.push(0, 0, 0);
  33593. vertices.push(0, 0, 0);
  33594. colors.push(color1.r, color1.g, color1.b);
  33595. colors.push(color2.r, color2.g, color2.b);
  33596. }
  33597. }
  33598. geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  33599. geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
  33600. var material = new LineBasicMaterial({
  33601. vertexColors: true,
  33602. depthTest: false,
  33603. depthWrite: false,
  33604. toneMapped: false,
  33605. transparent: true
  33606. });
  33607. _this = _LineSegments.call(this, geometry, material) || this;
  33608. _this.type = 'SkeletonHelper';
  33609. _this.isSkeletonHelper = true;
  33610. _this.root = object;
  33611. _this.bones = bones;
  33612. _this.matrix = object.matrixWorld;
  33613. _this.matrixAutoUpdate = false;
  33614. return _this;
  33615. }
  33616. var _proto = SkeletonHelper.prototype;
  33617. _proto.updateMatrixWorld = function updateMatrixWorld(force) {
  33618. var bones = this.bones;
  33619. var geometry = this.geometry;
  33620. var position = geometry.getAttribute('position');
  33621. _matrixWorldInv.copy(this.root.matrixWorld).invert();
  33622. for (var i = 0, j = 0; i < bones.length; i++) {
  33623. var bone = bones[i];
  33624. if (bone.parent && bone.parent.isBone) {
  33625. _boneMatrix.multiplyMatrices(_matrixWorldInv, bone.matrixWorld);
  33626. _vector$a.setFromMatrixPosition(_boneMatrix);
  33627. position.setXYZ(j, _vector$a.x, _vector$a.y, _vector$a.z);
  33628. _boneMatrix.multiplyMatrices(_matrixWorldInv, bone.parent.matrixWorld);
  33629. _vector$a.setFromMatrixPosition(_boneMatrix);
  33630. position.setXYZ(j + 1, _vector$a.x, _vector$a.y, _vector$a.z);
  33631. j += 2;
  33632. }
  33633. }
  33634. geometry.getAttribute('position').needsUpdate = true;
  33635. _LineSegments.prototype.updateMatrixWorld.call(this, force);
  33636. };
  33637. return SkeletonHelper;
  33638. }(LineSegments);
  33639. function getBoneList(object) {
  33640. var boneList = [];
  33641. if (object && object.isBone) {
  33642. boneList.push(object);
  33643. }
  33644. for (var i = 0; i < object.children.length; i++) {
  33645. boneList.push.apply(boneList, getBoneList(object.children[i]));
  33646. }
  33647. return boneList;
  33648. }
  33649. var PointLightHelper = /*#__PURE__*/function (_Mesh) {
  33650. _inheritsLoose(PointLightHelper, _Mesh);
  33651. function PointLightHelper(light, sphereSize, color) {
  33652. var _this;
  33653. var geometry = new SphereGeometry(sphereSize, 4, 2);
  33654. var material = new MeshBasicMaterial({
  33655. wireframe: true,
  33656. fog: false,
  33657. toneMapped: false
  33658. });
  33659. _this = _Mesh.call(this, geometry, material) || this;
  33660. _this.light = light;
  33661. _this.light.updateMatrixWorld();
  33662. _this.color = color;
  33663. _this.type = 'PointLightHelper';
  33664. _this.matrix = _this.light.matrixWorld;
  33665. _this.matrixAutoUpdate = false;
  33666. _this.update();
  33667. /*
  33668. // TODO: delete this comment?
  33669. const distanceGeometry = new THREE.IcosahedronBufferGeometry( 1, 2 );
  33670. const distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  33671. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  33672. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  33673. const d = light.distance;
  33674. if ( d === 0.0 ) {
  33675. this.lightDistance.visible = false;
  33676. } else {
  33677. this.lightDistance.scale.set( d, d, d );
  33678. }
  33679. this.add( this.lightDistance );
  33680. */
  33681. return _this;
  33682. }
  33683. var _proto = PointLightHelper.prototype;
  33684. _proto.dispose = function dispose() {
  33685. this.geometry.dispose();
  33686. this.material.dispose();
  33687. };
  33688. _proto.update = function update() {
  33689. if (this.color !== undefined) {
  33690. this.material.color.set(this.color);
  33691. } else {
  33692. this.material.color.copy(this.light.color);
  33693. }
  33694. /*
  33695. const d = this.light.distance;
  33696. if ( d === 0.0 ) {
  33697. this.lightDistance.visible = false;
  33698. } else {
  33699. this.lightDistance.visible = true;
  33700. this.lightDistance.scale.set( d, d, d );
  33701. }
  33702. */
  33703. };
  33704. return PointLightHelper;
  33705. }(Mesh);
  33706. var _vector$b = /*@__PURE__*/new Vector3();
  33707. var _color1 = /*@__PURE__*/new Color();
  33708. var _color2 = /*@__PURE__*/new Color();
  33709. var HemisphereLightHelper = /*#__PURE__*/function (_Object3D) {
  33710. _inheritsLoose(HemisphereLightHelper, _Object3D);
  33711. function HemisphereLightHelper(light, size, color) {
  33712. var _this;
  33713. _this = _Object3D.call(this) || this;
  33714. _this.light = light;
  33715. _this.light.updateMatrixWorld();
  33716. _this.matrix = light.matrixWorld;
  33717. _this.matrixAutoUpdate = false;
  33718. _this.color = color;
  33719. var geometry = new OctahedronGeometry(size);
  33720. geometry.rotateY(Math.PI * 0.5);
  33721. _this.material = new MeshBasicMaterial({
  33722. wireframe: true,
  33723. fog: false,
  33724. toneMapped: false
  33725. });
  33726. if (_this.color === undefined) _this.material.vertexColors = true;
  33727. var position = geometry.getAttribute('position');
  33728. var colors = new Float32Array(position.count * 3);
  33729. geometry.setAttribute('color', new BufferAttribute(colors, 3));
  33730. _this.add(new Mesh(geometry, _this.material));
  33731. _this.update();
  33732. return _this;
  33733. }
  33734. var _proto = HemisphereLightHelper.prototype;
  33735. _proto.dispose = function dispose() {
  33736. this.children[0].geometry.dispose();
  33737. this.children[0].material.dispose();
  33738. };
  33739. _proto.update = function update() {
  33740. var mesh = this.children[0];
  33741. if (this.color !== undefined) {
  33742. this.material.color.set(this.color);
  33743. } else {
  33744. var colors = mesh.geometry.getAttribute('color');
  33745. _color1.copy(this.light.color);
  33746. _color2.copy(this.light.groundColor);
  33747. for (var i = 0, l = colors.count; i < l; i++) {
  33748. var color = i < l / 2 ? _color1 : _color2;
  33749. colors.setXYZ(i, color.r, color.g, color.b);
  33750. }
  33751. colors.needsUpdate = true;
  33752. }
  33753. mesh.lookAt(_vector$b.setFromMatrixPosition(this.light.matrixWorld).negate());
  33754. };
  33755. return HemisphereLightHelper;
  33756. }(Object3D);
  33757. var GridHelper = /*#__PURE__*/function (_LineSegments) {
  33758. _inheritsLoose(GridHelper, _LineSegments);
  33759. function GridHelper(size, divisions, color1, color2) {
  33760. var _this;
  33761. if (size === void 0) {
  33762. size = 10;
  33763. }
  33764. if (divisions === void 0) {
  33765. divisions = 10;
  33766. }
  33767. if (color1 === void 0) {
  33768. color1 = 0x444444;
  33769. }
  33770. if (color2 === void 0) {
  33771. color2 = 0x888888;
  33772. }
  33773. color1 = new Color(color1);
  33774. color2 = new Color(color2);
  33775. var center = divisions / 2;
  33776. var step = size / divisions;
  33777. var halfSize = size / 2;
  33778. var vertices = [],
  33779. colors = [];
  33780. for (var i = 0, j = 0, k = -halfSize; i <= divisions; i++, k += step) {
  33781. vertices.push(-halfSize, 0, k, halfSize, 0, k);
  33782. vertices.push(k, 0, -halfSize, k, 0, halfSize);
  33783. var color = i === center ? color1 : color2;
  33784. color.toArray(colors, j);
  33785. j += 3;
  33786. color.toArray(colors, j);
  33787. j += 3;
  33788. color.toArray(colors, j);
  33789. j += 3;
  33790. color.toArray(colors, j);
  33791. j += 3;
  33792. }
  33793. var geometry = new BufferGeometry();
  33794. geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  33795. geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
  33796. var material = new LineBasicMaterial({
  33797. vertexColors: true,
  33798. toneMapped: false
  33799. });
  33800. _this = _LineSegments.call(this, geometry, material) || this;
  33801. _this.type = 'GridHelper';
  33802. return _this;
  33803. }
  33804. return GridHelper;
  33805. }(LineSegments);
  33806. var PolarGridHelper = /*#__PURE__*/function (_LineSegments) {
  33807. _inheritsLoose(PolarGridHelper, _LineSegments);
  33808. function PolarGridHelper(radius, radials, circles, divisions, color1, color2) {
  33809. var _this;
  33810. if (radius === void 0) {
  33811. radius = 10;
  33812. }
  33813. if (radials === void 0) {
  33814. radials = 16;
  33815. }
  33816. if (circles === void 0) {
  33817. circles = 8;
  33818. }
  33819. if (divisions === void 0) {
  33820. divisions = 64;
  33821. }
  33822. if (color1 === void 0) {
  33823. color1 = 0x444444;
  33824. }
  33825. if (color2 === void 0) {
  33826. color2 = 0x888888;
  33827. }
  33828. color1 = new Color(color1);
  33829. color2 = new Color(color2);
  33830. var vertices = [];
  33831. var colors = []; // create the radials
  33832. for (var i = 0; i <= radials; i++) {
  33833. var v = i / radials * (Math.PI * 2);
  33834. var x = Math.sin(v) * radius;
  33835. var z = Math.cos(v) * radius;
  33836. vertices.push(0, 0, 0);
  33837. vertices.push(x, 0, z);
  33838. var color = i & 1 ? color1 : color2;
  33839. colors.push(color.r, color.g, color.b);
  33840. colors.push(color.r, color.g, color.b);
  33841. } // create the circles
  33842. for (var _i = 0; _i <= circles; _i++) {
  33843. var _color = _i & 1 ? color1 : color2;
  33844. var r = radius - radius / circles * _i;
  33845. for (var j = 0; j < divisions; j++) {
  33846. // first vertex
  33847. var _v = j / divisions * (Math.PI * 2);
  33848. var _x = Math.sin(_v) * r;
  33849. var _z = Math.cos(_v) * r;
  33850. vertices.push(_x, 0, _z);
  33851. colors.push(_color.r, _color.g, _color.b); // second vertex
  33852. _v = (j + 1) / divisions * (Math.PI * 2);
  33853. _x = Math.sin(_v) * r;
  33854. _z = Math.cos(_v) * r;
  33855. vertices.push(_x, 0, _z);
  33856. colors.push(_color.r, _color.g, _color.b);
  33857. }
  33858. }
  33859. var geometry = new BufferGeometry();
  33860. geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  33861. geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
  33862. var material = new LineBasicMaterial({
  33863. vertexColors: true,
  33864. toneMapped: false
  33865. });
  33866. _this = _LineSegments.call(this, geometry, material) || this;
  33867. _this.type = 'PolarGridHelper';
  33868. return _this;
  33869. }
  33870. return PolarGridHelper;
  33871. }(LineSegments);
  33872. var _v1$6 = /*@__PURE__*/new Vector3();
  33873. var _v2$3 = /*@__PURE__*/new Vector3();
  33874. var _v3$1 = /*@__PURE__*/new Vector3();
  33875. var DirectionalLightHelper = /*#__PURE__*/function (_Object3D) {
  33876. _inheritsLoose(DirectionalLightHelper, _Object3D);
  33877. function DirectionalLightHelper(light, size, color) {
  33878. var _this;
  33879. _this = _Object3D.call(this) || this;
  33880. _this.light = light;
  33881. _this.light.updateMatrixWorld();
  33882. _this.matrix = light.matrixWorld;
  33883. _this.matrixAutoUpdate = false;
  33884. _this.color = color;
  33885. if (size === undefined) size = 1;
  33886. var geometry = new BufferGeometry();
  33887. geometry.setAttribute('position', new Float32BufferAttribute([-size, size, 0, size, size, 0, size, -size, 0, -size, -size, 0, -size, size, 0], 3));
  33888. var material = new LineBasicMaterial({
  33889. fog: false,
  33890. toneMapped: false
  33891. });
  33892. _this.lightPlane = new Line(geometry, material);
  33893. _this.add(_this.lightPlane);
  33894. geometry = new BufferGeometry();
  33895. geometry.setAttribute('position', new Float32BufferAttribute([0, 0, 0, 0, 0, 1], 3));
  33896. _this.targetLine = new Line(geometry, material);
  33897. _this.add(_this.targetLine);
  33898. _this.update();
  33899. return _this;
  33900. }
  33901. var _proto = DirectionalLightHelper.prototype;
  33902. _proto.dispose = function dispose() {
  33903. this.lightPlane.geometry.dispose();
  33904. this.lightPlane.material.dispose();
  33905. this.targetLine.geometry.dispose();
  33906. this.targetLine.material.dispose();
  33907. };
  33908. _proto.update = function update() {
  33909. _v1$6.setFromMatrixPosition(this.light.matrixWorld);
  33910. _v2$3.setFromMatrixPosition(this.light.target.matrixWorld);
  33911. _v3$1.subVectors(_v2$3, _v1$6);
  33912. this.lightPlane.lookAt(_v2$3);
  33913. if (this.color !== undefined) {
  33914. this.lightPlane.material.color.set(this.color);
  33915. this.targetLine.material.color.set(this.color);
  33916. } else {
  33917. this.lightPlane.material.color.copy(this.light.color);
  33918. this.targetLine.material.color.copy(this.light.color);
  33919. }
  33920. this.targetLine.lookAt(_v2$3);
  33921. this.targetLine.scale.z = _v3$1.length();
  33922. };
  33923. return DirectionalLightHelper;
  33924. }(Object3D);
  33925. var _vector$c = /*@__PURE__*/new Vector3();
  33926. var _camera = /*@__PURE__*/new Camera();
  33927. /**
  33928. * - shows frustum, line of sight and up of the camera
  33929. * - suitable for fast updates
  33930. * - based on frustum visualization in lightgl.js shadowmap example
  33931. * http://evanw.github.com/lightgl.js/tests/shadowmap.html
  33932. */
  33933. var CameraHelper = /*#__PURE__*/function (_LineSegments) {
  33934. _inheritsLoose(CameraHelper, _LineSegments);
  33935. function CameraHelper(camera) {
  33936. var _this;
  33937. var geometry = new BufferGeometry();
  33938. var material = new LineBasicMaterial({
  33939. color: 0xffffff,
  33940. vertexColors: true,
  33941. toneMapped: false
  33942. });
  33943. var vertices = [];
  33944. var colors = [];
  33945. var pointMap = {}; // colors
  33946. var colorFrustum = new Color(0xffaa00);
  33947. var colorCone = new Color(0xff0000);
  33948. var colorUp = new Color(0x00aaff);
  33949. var colorTarget = new Color(0xffffff);
  33950. var colorCross = new Color(0x333333); // near
  33951. addLine('n1', 'n2', colorFrustum);
  33952. addLine('n2', 'n4', colorFrustum);
  33953. addLine('n4', 'n3', colorFrustum);
  33954. addLine('n3', 'n1', colorFrustum); // far
  33955. addLine('f1', 'f2', colorFrustum);
  33956. addLine('f2', 'f4', colorFrustum);
  33957. addLine('f4', 'f3', colorFrustum);
  33958. addLine('f3', 'f1', colorFrustum); // sides
  33959. addLine('n1', 'f1', colorFrustum);
  33960. addLine('n2', 'f2', colorFrustum);
  33961. addLine('n3', 'f3', colorFrustum);
  33962. addLine('n4', 'f4', colorFrustum); // cone
  33963. addLine('p', 'n1', colorCone);
  33964. addLine('p', 'n2', colorCone);
  33965. addLine('p', 'n3', colorCone);
  33966. addLine('p', 'n4', colorCone); // up
  33967. addLine('u1', 'u2', colorUp);
  33968. addLine('u2', 'u3', colorUp);
  33969. addLine('u3', 'u1', colorUp); // target
  33970. addLine('c', 't', colorTarget);
  33971. addLine('p', 'c', colorCross); // cross
  33972. addLine('cn1', 'cn2', colorCross);
  33973. addLine('cn3', 'cn4', colorCross);
  33974. addLine('cf1', 'cf2', colorCross);
  33975. addLine('cf3', 'cf4', colorCross);
  33976. function addLine(a, b, color) {
  33977. addPoint(a, color);
  33978. addPoint(b, color);
  33979. }
  33980. function addPoint(id, color) {
  33981. vertices.push(0, 0, 0);
  33982. colors.push(color.r, color.g, color.b);
  33983. if (pointMap[id] === undefined) {
  33984. pointMap[id] = [];
  33985. }
  33986. pointMap[id].push(vertices.length / 3 - 1);
  33987. }
  33988. geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  33989. geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
  33990. _this = _LineSegments.call(this, geometry, material) || this;
  33991. _this.type = 'CameraHelper';
  33992. _this.camera = camera;
  33993. if (_this.camera.updateProjectionMatrix) _this.camera.updateProjectionMatrix();
  33994. _this.matrix = camera.matrixWorld;
  33995. _this.matrixAutoUpdate = false;
  33996. _this.pointMap = pointMap;
  33997. _this.update();
  33998. return _this;
  33999. }
  34000. var _proto = CameraHelper.prototype;
  34001. _proto.update = function update() {
  34002. var geometry = this.geometry;
  34003. var pointMap = this.pointMap;
  34004. var w = 1,
  34005. h = 1; // we need just camera projection matrix inverse
  34006. // world matrix must be identity
  34007. _camera.projectionMatrixInverse.copy(this.camera.projectionMatrixInverse); // center / target
  34008. setPoint('c', pointMap, geometry, _camera, 0, 0, -1);
  34009. setPoint('t', pointMap, geometry, _camera, 0, 0, 1); // near
  34010. setPoint('n1', pointMap, geometry, _camera, -w, -h, -1);
  34011. setPoint('n2', pointMap, geometry, _camera, w, -h, -1);
  34012. setPoint('n3', pointMap, geometry, _camera, -w, h, -1);
  34013. setPoint('n4', pointMap, geometry, _camera, w, h, -1); // far
  34014. setPoint('f1', pointMap, geometry, _camera, -w, -h, 1);
  34015. setPoint('f2', pointMap, geometry, _camera, w, -h, 1);
  34016. setPoint('f3', pointMap, geometry, _camera, -w, h, 1);
  34017. setPoint('f4', pointMap, geometry, _camera, w, h, 1); // up
  34018. setPoint('u1', pointMap, geometry, _camera, w * 0.7, h * 1.1, -1);
  34019. setPoint('u2', pointMap, geometry, _camera, -w * 0.7, h * 1.1, -1);
  34020. setPoint('u3', pointMap, geometry, _camera, 0, h * 2, -1); // cross
  34021. setPoint('cf1', pointMap, geometry, _camera, -w, 0, 1);
  34022. setPoint('cf2', pointMap, geometry, _camera, w, 0, 1);
  34023. setPoint('cf3', pointMap, geometry, _camera, 0, -h, 1);
  34024. setPoint('cf4', pointMap, geometry, _camera, 0, h, 1);
  34025. setPoint('cn1', pointMap, geometry, _camera, -w, 0, -1);
  34026. setPoint('cn2', pointMap, geometry, _camera, w, 0, -1);
  34027. setPoint('cn3', pointMap, geometry, _camera, 0, -h, -1);
  34028. setPoint('cn4', pointMap, geometry, _camera, 0, h, -1);
  34029. geometry.getAttribute('position').needsUpdate = true;
  34030. };
  34031. return CameraHelper;
  34032. }(LineSegments);
  34033. function setPoint(point, pointMap, geometry, camera, x, y, z) {
  34034. _vector$c.set(x, y, z).unproject(camera);
  34035. var points = pointMap[point];
  34036. if (points !== undefined) {
  34037. var position = geometry.getAttribute('position');
  34038. for (var i = 0, l = points.length; i < l; i++) {
  34039. position.setXYZ(points[i], _vector$c.x, _vector$c.y, _vector$c.z);
  34040. }
  34041. }
  34042. }
  34043. var _box$3 = /*@__PURE__*/new Box3();
  34044. var BoxHelper = /*#__PURE__*/function (_LineSegments) {
  34045. _inheritsLoose(BoxHelper, _LineSegments);
  34046. function BoxHelper(object, color) {
  34047. var _this;
  34048. if (color === void 0) {
  34049. color = 0xffff00;
  34050. }
  34051. var indices = new Uint16Array([0, 1, 1, 2, 2, 3, 3, 0, 4, 5, 5, 6, 6, 7, 7, 4, 0, 4, 1, 5, 2, 6, 3, 7]);
  34052. var positions = new Float32Array(8 * 3);
  34053. var geometry = new BufferGeometry();
  34054. geometry.setIndex(new BufferAttribute(indices, 1));
  34055. geometry.setAttribute('position', new BufferAttribute(positions, 3));
  34056. _this = _LineSegments.call(this, geometry, new LineBasicMaterial({
  34057. color: color,
  34058. toneMapped: false
  34059. })) || this;
  34060. _this.object = object;
  34061. _this.type = 'BoxHelper';
  34062. _this.matrixAutoUpdate = false;
  34063. _this.update();
  34064. return _this;
  34065. }
  34066. var _proto = BoxHelper.prototype;
  34067. _proto.update = function update(object) {
  34068. if (object !== undefined) {
  34069. console.warn('THREE.BoxHelper: .update() has no longer arguments.');
  34070. }
  34071. if (this.object !== undefined) {
  34072. _box$3.setFromObject(this.object);
  34073. }
  34074. if (_box$3.isEmpty()) return;
  34075. var min = _box$3.min;
  34076. var max = _box$3.max;
  34077. /*
  34078. 5____4
  34079. 1/___0/|
  34080. | 6__|_7
  34081. 2/___3/
  34082. 0: max.x, max.y, max.z
  34083. 1: min.x, max.y, max.z
  34084. 2: min.x, min.y, max.z
  34085. 3: max.x, min.y, max.z
  34086. 4: max.x, max.y, min.z
  34087. 5: min.x, max.y, min.z
  34088. 6: min.x, min.y, min.z
  34089. 7: max.x, min.y, min.z
  34090. */
  34091. var position = this.geometry.attributes.position;
  34092. var array = position.array;
  34093. array[0] = max.x;
  34094. array[1] = max.y;
  34095. array[2] = max.z;
  34096. array[3] = min.x;
  34097. array[4] = max.y;
  34098. array[5] = max.z;
  34099. array[6] = min.x;
  34100. array[7] = min.y;
  34101. array[8] = max.z;
  34102. array[9] = max.x;
  34103. array[10] = min.y;
  34104. array[11] = max.z;
  34105. array[12] = max.x;
  34106. array[13] = max.y;
  34107. array[14] = min.z;
  34108. array[15] = min.x;
  34109. array[16] = max.y;
  34110. array[17] = min.z;
  34111. array[18] = min.x;
  34112. array[19] = min.y;
  34113. array[20] = min.z;
  34114. array[21] = max.x;
  34115. array[22] = min.y;
  34116. array[23] = min.z;
  34117. position.needsUpdate = true;
  34118. this.geometry.computeBoundingSphere();
  34119. };
  34120. _proto.setFromObject = function setFromObject(object) {
  34121. this.object = object;
  34122. this.update();
  34123. return this;
  34124. };
  34125. _proto.copy = function copy(source) {
  34126. LineSegments.prototype.copy.call(this, source);
  34127. this.object = source.object;
  34128. return this;
  34129. };
  34130. return BoxHelper;
  34131. }(LineSegments);
  34132. var Box3Helper = /*#__PURE__*/function (_LineSegments) {
  34133. _inheritsLoose(Box3Helper, _LineSegments);
  34134. function Box3Helper(box, color) {
  34135. var _this;
  34136. if (color === void 0) {
  34137. color = 0xffff00;
  34138. }
  34139. var indices = new Uint16Array([0, 1, 1, 2, 2, 3, 3, 0, 4, 5, 5, 6, 6, 7, 7, 4, 0, 4, 1, 5, 2, 6, 3, 7]);
  34140. var positions = [1, 1, 1, -1, 1, 1, -1, -1, 1, 1, -1, 1, 1, 1, -1, -1, 1, -1, -1, -1, -1, 1, -1, -1];
  34141. var geometry = new BufferGeometry();
  34142. geometry.setIndex(new BufferAttribute(indices, 1));
  34143. geometry.setAttribute('position', new Float32BufferAttribute(positions, 3));
  34144. _this = _LineSegments.call(this, geometry, new LineBasicMaterial({
  34145. color: color,
  34146. toneMapped: false
  34147. })) || this;
  34148. _this.box = box;
  34149. _this.type = 'Box3Helper';
  34150. _this.geometry.computeBoundingSphere();
  34151. return _this;
  34152. }
  34153. var _proto = Box3Helper.prototype;
  34154. _proto.updateMatrixWorld = function updateMatrixWorld(force) {
  34155. var box = this.box;
  34156. if (box.isEmpty()) return;
  34157. box.getCenter(this.position);
  34158. box.getSize(this.scale);
  34159. this.scale.multiplyScalar(0.5);
  34160. _LineSegments.prototype.updateMatrixWorld.call(this, force);
  34161. };
  34162. return Box3Helper;
  34163. }(LineSegments);
  34164. var PlaneHelper = /*#__PURE__*/function (_Line) {
  34165. _inheritsLoose(PlaneHelper, _Line);
  34166. function PlaneHelper(plane, size, hex) {
  34167. var _this;
  34168. if (size === void 0) {
  34169. size = 1;
  34170. }
  34171. if (hex === void 0) {
  34172. hex = 0xffff00;
  34173. }
  34174. var color = hex;
  34175. var positions = [1, -1, 1, -1, 1, 1, -1, -1, 1, 1, 1, 1, -1, 1, 1, -1, -1, 1, 1, -1, 1, 1, 1, 1, 0, 0, 1, 0, 0, 0];
  34176. var geometry = new BufferGeometry();
  34177. geometry.setAttribute('position', new Float32BufferAttribute(positions, 3));
  34178. geometry.computeBoundingSphere();
  34179. _this = _Line.call(this, geometry, new LineBasicMaterial({
  34180. color: color,
  34181. toneMapped: false
  34182. })) || this;
  34183. _this.type = 'PlaneHelper';
  34184. _this.plane = plane;
  34185. _this.size = size;
  34186. var positions2 = [1, 1, 1, -1, 1, 1, -1, -1, 1, 1, 1, 1, -1, -1, 1, 1, -1, 1];
  34187. var geometry2 = new BufferGeometry();
  34188. geometry2.setAttribute('position', new Float32BufferAttribute(positions2, 3));
  34189. geometry2.computeBoundingSphere();
  34190. _this.add(new Mesh(geometry2, new MeshBasicMaterial({
  34191. color: color,
  34192. opacity: 0.2,
  34193. transparent: true,
  34194. depthWrite: false,
  34195. toneMapped: false
  34196. })));
  34197. return _this;
  34198. }
  34199. var _proto = PlaneHelper.prototype;
  34200. _proto.updateMatrixWorld = function updateMatrixWorld(force) {
  34201. var scale = -this.plane.constant;
  34202. if (Math.abs(scale) < 1e-8) scale = 1e-8; // sign does not matter
  34203. this.scale.set(0.5 * this.size, 0.5 * this.size, scale);
  34204. this.children[0].material.side = scale < 0 ? BackSide : FrontSide; // renderer flips side when determinant < 0; flipping not wanted here
  34205. this.lookAt(this.plane.normal);
  34206. _Line.prototype.updateMatrixWorld.call(this, force);
  34207. };
  34208. return PlaneHelper;
  34209. }(Line);
  34210. var _axis = /*@__PURE__*/new Vector3();
  34211. var _lineGeometry, _coneGeometry;
  34212. var ArrowHelper = /*#__PURE__*/function (_Object3D) {
  34213. _inheritsLoose(ArrowHelper, _Object3D);
  34214. function ArrowHelper(dir, origin, length, color, headLength, headWidth) {
  34215. var _this;
  34216. _this = _Object3D.call(this) || this; // dir is assumed to be normalized
  34217. _this.type = 'ArrowHelper';
  34218. if (dir === undefined) dir = new Vector3(0, 0, 1);
  34219. if (origin === undefined) origin = new Vector3(0, 0, 0);
  34220. if (length === undefined) length = 1;
  34221. if (color === undefined) color = 0xffff00;
  34222. if (headLength === undefined) headLength = 0.2 * length;
  34223. if (headWidth === undefined) headWidth = 0.2 * headLength;
  34224. if (_lineGeometry === undefined) {
  34225. _lineGeometry = new BufferGeometry();
  34226. _lineGeometry.setAttribute('position', new Float32BufferAttribute([0, 0, 0, 0, 1, 0], 3));
  34227. _coneGeometry = new CylinderGeometry(0, 0.5, 1, 5, 1);
  34228. _coneGeometry.translate(0, -0.5, 0);
  34229. }
  34230. _this.position.copy(origin);
  34231. _this.line = new Line(_lineGeometry, new LineBasicMaterial({
  34232. color: color,
  34233. toneMapped: false
  34234. }));
  34235. _this.line.matrixAutoUpdate = false;
  34236. _this.add(_this.line);
  34237. _this.cone = new Mesh(_coneGeometry, new MeshBasicMaterial({
  34238. color: color,
  34239. toneMapped: false
  34240. }));
  34241. _this.cone.matrixAutoUpdate = false;
  34242. _this.add(_this.cone);
  34243. _this.setDirection(dir);
  34244. _this.setLength(length, headLength, headWidth);
  34245. return _this;
  34246. }
  34247. var _proto = ArrowHelper.prototype;
  34248. _proto.setDirection = function setDirection(dir) {
  34249. // dir is assumed to be normalized
  34250. if (dir.y > 0.99999) {
  34251. this.quaternion.set(0, 0, 0, 1);
  34252. } else if (dir.y < -0.99999) {
  34253. this.quaternion.set(1, 0, 0, 0);
  34254. } else {
  34255. _axis.set(dir.z, 0, -dir.x).normalize();
  34256. var radians = Math.acos(dir.y);
  34257. this.quaternion.setFromAxisAngle(_axis, radians);
  34258. }
  34259. };
  34260. _proto.setLength = function setLength(length, headLength, headWidth) {
  34261. if (headLength === undefined) headLength = 0.2 * length;
  34262. if (headWidth === undefined) headWidth = 0.2 * headLength;
  34263. this.line.scale.set(1, Math.max(0.0001, length - headLength), 1); // see #17458
  34264. this.line.updateMatrix();
  34265. this.cone.scale.set(headWidth, headLength, headWidth);
  34266. this.cone.position.y = length;
  34267. this.cone.updateMatrix();
  34268. };
  34269. _proto.setColor = function setColor(color) {
  34270. this.line.material.color.set(color);
  34271. this.cone.material.color.set(color);
  34272. };
  34273. _proto.copy = function copy(source) {
  34274. _Object3D.prototype.copy.call(this, source, false);
  34275. this.line.copy(source.line);
  34276. this.cone.copy(source.cone);
  34277. return this;
  34278. };
  34279. return ArrowHelper;
  34280. }(Object3D);
  34281. var AxesHelper = /*#__PURE__*/function (_LineSegments) {
  34282. _inheritsLoose(AxesHelper, _LineSegments);
  34283. function AxesHelper(size) {
  34284. var _this;
  34285. if (size === void 0) {
  34286. size = 1;
  34287. }
  34288. var vertices = [0, 0, 0, size, 0, 0, 0, 0, 0, 0, size, 0, 0, 0, 0, 0, 0, size];
  34289. var colors = [1, 0, 0, 1, 0.6, 0, 0, 1, 0, 0.6, 1, 0, 0, 0, 1, 0, 0.6, 1];
  34290. var geometry = new BufferGeometry();
  34291. geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  34292. geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
  34293. var material = new LineBasicMaterial({
  34294. vertexColors: true,
  34295. toneMapped: false
  34296. });
  34297. _this = _LineSegments.call(this, geometry, material) || this;
  34298. _this.type = 'AxesHelper';
  34299. return _this;
  34300. }
  34301. return AxesHelper;
  34302. }(LineSegments);
  34303. var _floatView = new Float32Array(1);
  34304. var _int32View = new Int32Array(_floatView.buffer);
  34305. var DataUtils = {
  34306. // Converts float32 to float16 (stored as uint16 value).
  34307. toHalfFloat: function toHalfFloat(val) {
  34308. // Source: http://gamedev.stackexchange.com/questions/17326/conversion-of-a-number-from-single-precision-floating-point-representation-to-a/17410#17410
  34309. /* This method is faster than the OpenEXR implementation (very often
  34310. * used, eg. in Ogre), with the additional benefit of rounding, inspired
  34311. * by James Tursa?s half-precision code. */
  34312. _floatView[0] = val;
  34313. var x = _int32View[0];
  34314. var bits = x >> 16 & 0x8000;
  34315. /* Get the sign */
  34316. var m = x >> 12 & 0x07ff;
  34317. /* Keep one extra bit for rounding */
  34318. var e = x >> 23 & 0xff;
  34319. /* Using int is faster here */
  34320. /* If zero, or denormal, or exponent underflows too much for a denormal
  34321. * half, return signed zero. */
  34322. if (e < 103) return bits;
  34323. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  34324. if (e > 142) {
  34325. bits |= 0x7c00;
  34326. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  34327. * not Inf, so make sure we set one mantissa bit too. */
  34328. bits |= (e == 255 ? 0 : 1) && x & 0x007fffff;
  34329. return bits;
  34330. }
  34331. /* If exponent underflows but not too much, return a denormal */
  34332. if (e < 113) {
  34333. m |= 0x0800;
  34334. /* Extra rounding may overflow and set mantissa to 0 and exponent
  34335. * to 1, which is OK. */
  34336. bits |= (m >> 114 - e) + (m >> 113 - e & 1);
  34337. return bits;
  34338. }
  34339. bits |= e - 112 << 10 | m >> 1;
  34340. /* Extra rounding. An overflow will set mantissa to 0 and increment
  34341. * the exponent, which is OK. */
  34342. bits += m & 1;
  34343. return bits;
  34344. }
  34345. };
  34346. var _ENCODINGS;
  34347. var LOD_MIN = 4;
  34348. var LOD_MAX = 8;
  34349. var SIZE_MAX = Math.pow(2, LOD_MAX); // The standard deviations (radians) associated with the extra mips. These are
  34350. // chosen to approximate a Trowbridge-Reitz distribution function times the
  34351. // geometric shadowing function. These sigma values squared must match the
  34352. // variance #defines in cube_uv_reflection_fragment.glsl.js.
  34353. var EXTRA_LOD_SIGMA = [0.125, 0.215, 0.35, 0.446, 0.526, 0.582];
  34354. var TOTAL_LODS = LOD_MAX - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length; // The maximum length of the blur for loop. Smaller sigmas will use fewer
  34355. // samples and exit early, but not recompile the shader.
  34356. var MAX_SAMPLES = 20;
  34357. var ENCODINGS = (_ENCODINGS = {}, _ENCODINGS[LinearEncoding] = 0, _ENCODINGS[sRGBEncoding] = 1, _ENCODINGS[RGBEEncoding] = 2, _ENCODINGS[RGBM7Encoding] = 3, _ENCODINGS[RGBM16Encoding] = 4, _ENCODINGS[RGBDEncoding] = 5, _ENCODINGS[GammaEncoding] = 6, _ENCODINGS);
  34358. var backgroundMaterial = new MeshBasicMaterial({
  34359. side: BackSide,
  34360. depthWrite: false,
  34361. depthTest: false
  34362. });
  34363. var backgroundBox = new Mesh(new BoxGeometry(), backgroundMaterial);
  34364. var _flatCamera = /*@__PURE__*/new OrthographicCamera();
  34365. var _createPlanes2 = /*@__PURE__*/_createPlanes(),
  34366. _lodPlanes = _createPlanes2._lodPlanes,
  34367. _sizeLods = _createPlanes2._sizeLods,
  34368. _sigmas = _createPlanes2._sigmas;
  34369. var _clearColor = /*@__PURE__*/new Color();
  34370. var _oldTarget = null; // Golden Ratio
  34371. var PHI = (1 + Math.sqrt(5)) / 2;
  34372. var INV_PHI = 1 / PHI; // Vertices of a dodecahedron (except the opposites, which represent the
  34373. // same axis), used as axis directions evenly spread on a sphere.
  34374. var _axisDirections = [/*@__PURE__*/new Vector3(1, 1, 1), /*@__PURE__*/new Vector3(-1, 1, 1), /*@__PURE__*/new Vector3(1, 1, -1), /*@__PURE__*/new Vector3(-1, 1, -1), /*@__PURE__*/new Vector3(0, PHI, INV_PHI), /*@__PURE__*/new Vector3(0, PHI, -INV_PHI), /*@__PURE__*/new Vector3(INV_PHI, 0, PHI), /*@__PURE__*/new Vector3(-INV_PHI, 0, PHI), /*@__PURE__*/new Vector3(PHI, INV_PHI, 0), /*@__PURE__*/new Vector3(-PHI, INV_PHI, 0)];
  34375. /**
  34376. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  34377. * (PMREM) from a cubeMap environment texture. This allows different levels of
  34378. * blur to be quickly accessed based on material roughness. It is packed into a
  34379. * special CubeUV format that allows us to perform custom interpolation so that
  34380. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  34381. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  34382. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  34383. * higher roughness levels. In this way we maintain resolution to smoothly
  34384. * interpolate diffuse lighting while limiting sampling computation.
  34385. */
  34386. function convertLinearToRGBE(color) {
  34387. var maxComponent = Math.max(color.r, color.g, color.b);
  34388. var fExp = Math.min(Math.max(Math.ceil(Math.log2(maxComponent)), -128.0), 127.0);
  34389. color.multiplyScalar(Math.pow(2.0, -fExp));
  34390. var alpha = (fExp + 128.0) / 255.0;
  34391. return alpha;
  34392. }
  34393. var PMREMGenerator = /*#__PURE__*/function () {
  34394. function PMREMGenerator(renderer) {
  34395. this._renderer = renderer;
  34396. this._pingPongRenderTarget = null;
  34397. this._blurMaterial = _getBlurShader(MAX_SAMPLES);
  34398. this._equirectShader = null;
  34399. this._cubemapShader = null;
  34400. this._compileMaterial(this._blurMaterial);
  34401. }
  34402. /**
  34403. * Generates a PMREM from a supplied Scene, which can be faster than using an
  34404. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  34405. * in radians to be applied to the scene before PMREM generation. Optional near
  34406. * and far planes ensure the scene is rendered in its entirety (the cubeCamera
  34407. * is placed at the origin).
  34408. */
  34409. var _proto = PMREMGenerator.prototype;
  34410. _proto.fromScene = function fromScene(scene, sigma, near, far) {
  34411. if (sigma === void 0) {
  34412. sigma = 0;
  34413. }
  34414. if (near === void 0) {
  34415. near = 0.1;
  34416. }
  34417. if (far === void 0) {
  34418. far = 100;
  34419. }
  34420. _oldTarget = this._renderer.getRenderTarget();
  34421. var cubeUVRenderTarget = this._allocateTargets();
  34422. this._sceneToCubeUV(scene, near, far, cubeUVRenderTarget);
  34423. if (sigma > 0) {
  34424. this._blur(cubeUVRenderTarget, 0, 0, sigma);
  34425. }
  34426. this._applyPMREM(cubeUVRenderTarget);
  34427. this._cleanup(cubeUVRenderTarget);
  34428. return cubeUVRenderTarget;
  34429. }
  34430. /**
  34431. * Generates a PMREM from an equirectangular texture, which can be either LDR
  34432. * (RGBFormat) or HDR (RGBEFormat). The ideal input image size is 1k (1024 x 512),
  34433. * as this matches best with the 256 x 256 cubemap output.
  34434. */
  34435. ;
  34436. _proto.fromEquirectangular = function fromEquirectangular(equirectangular) {
  34437. return this._fromTexture(equirectangular);
  34438. }
  34439. /**
  34440. * Generates a PMREM from an cubemap texture, which can be either LDR
  34441. * (RGBFormat) or HDR (RGBEFormat). The ideal input cube size is 256 x 256,
  34442. * as this matches best with the 256 x 256 cubemap output.
  34443. */
  34444. ;
  34445. _proto.fromCubemap = function fromCubemap(cubemap) {
  34446. return this._fromTexture(cubemap);
  34447. }
  34448. /**
  34449. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  34450. * your texture's network fetch for increased concurrency.
  34451. */
  34452. ;
  34453. _proto.compileCubemapShader = function compileCubemapShader() {
  34454. if (this._cubemapShader === null) {
  34455. this._cubemapShader = _getCubemapShader();
  34456. this._compileMaterial(this._cubemapShader);
  34457. }
  34458. }
  34459. /**
  34460. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  34461. * your texture's network fetch for increased concurrency.
  34462. */
  34463. ;
  34464. _proto.compileEquirectangularShader = function compileEquirectangularShader() {
  34465. if (this._equirectShader === null) {
  34466. this._equirectShader = _getEquirectShader();
  34467. this._compileMaterial(this._equirectShader);
  34468. }
  34469. }
  34470. /**
  34471. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  34472. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  34473. * one of them will cause any others to also become unusable.
  34474. */
  34475. ;
  34476. _proto.dispose = function dispose() {
  34477. this._blurMaterial.dispose();
  34478. if (this._cubemapShader !== null) this._cubemapShader.dispose();
  34479. if (this._equirectShader !== null) this._equirectShader.dispose();
  34480. for (var i = 0; i < _lodPlanes.length; i++) {
  34481. _lodPlanes[i].dispose();
  34482. }
  34483. } // private interface
  34484. ;
  34485. _proto._cleanup = function _cleanup(outputTarget) {
  34486. this._pingPongRenderTarget.dispose();
  34487. this._renderer.setRenderTarget(_oldTarget);
  34488. outputTarget.scissorTest = false;
  34489. _setViewport(outputTarget, 0, 0, outputTarget.width, outputTarget.height);
  34490. };
  34491. _proto._fromTexture = function _fromTexture(texture) {
  34492. _oldTarget = this._renderer.getRenderTarget();
  34493. var cubeUVRenderTarget = this._allocateTargets(texture);
  34494. this._textureToCubeUV(texture, cubeUVRenderTarget);
  34495. this._applyPMREM(cubeUVRenderTarget);
  34496. this._cleanup(cubeUVRenderTarget);
  34497. return cubeUVRenderTarget;
  34498. };
  34499. _proto._allocateTargets = function _allocateTargets(texture) {
  34500. // warning: null texture is valid
  34501. var params = {
  34502. magFilter: NearestFilter,
  34503. minFilter: NearestFilter,
  34504. generateMipmaps: false,
  34505. type: UnsignedByteType,
  34506. format: RGBEFormat,
  34507. encoding: _isLDR(texture) ? texture.encoding : RGBEEncoding,
  34508. depthBuffer: false
  34509. };
  34510. var cubeUVRenderTarget = _createRenderTarget(params);
  34511. cubeUVRenderTarget.depthBuffer = texture ? false : true;
  34512. this._pingPongRenderTarget = _createRenderTarget(params);
  34513. return cubeUVRenderTarget;
  34514. };
  34515. _proto._compileMaterial = function _compileMaterial(material) {
  34516. var tmpMesh = new Mesh(_lodPlanes[0], material);
  34517. this._renderer.compile(tmpMesh, _flatCamera);
  34518. };
  34519. _proto._sceneToCubeUV = function _sceneToCubeUV(scene, near, far, cubeUVRenderTarget) {
  34520. var fov = 90;
  34521. var aspect = 1;
  34522. var cubeCamera = new PerspectiveCamera(fov, aspect, near, far);
  34523. var upSign = [1, -1, 1, 1, 1, 1];
  34524. var forwardSign = [1, 1, 1, -1, -1, -1];
  34525. var renderer = this._renderer;
  34526. var originalAutoClear = renderer.autoClear;
  34527. var outputEncoding = renderer.outputEncoding;
  34528. var toneMapping = renderer.toneMapping;
  34529. renderer.getClearColor(_clearColor);
  34530. renderer.toneMapping = NoToneMapping;
  34531. renderer.outputEncoding = LinearEncoding;
  34532. renderer.autoClear = false;
  34533. var useSolidColor = false;
  34534. var background = scene.background;
  34535. if (background) {
  34536. if (background.isColor) {
  34537. backgroundMaterial.color.copy(background).convertSRGBToLinear();
  34538. scene.background = null;
  34539. var alpha = convertLinearToRGBE(backgroundMaterial.color);
  34540. backgroundMaterial.opacity = alpha;
  34541. useSolidColor = true;
  34542. }
  34543. } else {
  34544. backgroundMaterial.color.copy(_clearColor).convertSRGBToLinear();
  34545. var _alpha = convertLinearToRGBE(backgroundMaterial.color);
  34546. backgroundMaterial.opacity = _alpha;
  34547. useSolidColor = true;
  34548. }
  34549. for (var i = 0; i < 6; i++) {
  34550. var col = i % 3;
  34551. if (col == 0) {
  34552. cubeCamera.up.set(0, upSign[i], 0);
  34553. cubeCamera.lookAt(forwardSign[i], 0, 0);
  34554. } else if (col == 1) {
  34555. cubeCamera.up.set(0, 0, upSign[i]);
  34556. cubeCamera.lookAt(0, forwardSign[i], 0);
  34557. } else {
  34558. cubeCamera.up.set(0, upSign[i], 0);
  34559. cubeCamera.lookAt(0, 0, forwardSign[i]);
  34560. }
  34561. _setViewport(cubeUVRenderTarget, col * SIZE_MAX, i > 2 ? SIZE_MAX : 0, SIZE_MAX, SIZE_MAX);
  34562. renderer.setRenderTarget(cubeUVRenderTarget);
  34563. if (useSolidColor) {
  34564. renderer.render(backgroundBox, cubeCamera);
  34565. }
  34566. renderer.render(scene, cubeCamera);
  34567. }
  34568. renderer.toneMapping = toneMapping;
  34569. renderer.outputEncoding = outputEncoding;
  34570. renderer.autoClear = originalAutoClear;
  34571. };
  34572. _proto._textureToCubeUV = function _textureToCubeUV(texture, cubeUVRenderTarget) {
  34573. var renderer = this._renderer;
  34574. if (texture.isCubeTexture) {
  34575. if (this._cubemapShader == null) {
  34576. this._cubemapShader = _getCubemapShader();
  34577. }
  34578. } else {
  34579. if (this._equirectShader == null) {
  34580. this._equirectShader = _getEquirectShader();
  34581. }
  34582. }
  34583. var material = texture.isCubeTexture ? this._cubemapShader : this._equirectShader;
  34584. var mesh = new Mesh(_lodPlanes[0], material);
  34585. var uniforms = material.uniforms;
  34586. uniforms['envMap'].value = texture;
  34587. if (!texture.isCubeTexture) {
  34588. uniforms['texelSize'].value.set(1.0 / texture.image.width, 1.0 / texture.image.height);
  34589. }
  34590. uniforms['inputEncoding'].value = ENCODINGS[texture.encoding];
  34591. uniforms['outputEncoding'].value = ENCODINGS[cubeUVRenderTarget.texture.encoding];
  34592. _setViewport(cubeUVRenderTarget, 0, 0, 3 * SIZE_MAX, 2 * SIZE_MAX);
  34593. renderer.setRenderTarget(cubeUVRenderTarget);
  34594. renderer.render(mesh, _flatCamera);
  34595. };
  34596. _proto._applyPMREM = function _applyPMREM(cubeUVRenderTarget) {
  34597. var renderer = this._renderer;
  34598. var autoClear = renderer.autoClear;
  34599. renderer.autoClear = false;
  34600. for (var i = 1; i < TOTAL_LODS; i++) {
  34601. var sigma = Math.sqrt(_sigmas[i] * _sigmas[i] - _sigmas[i - 1] * _sigmas[i - 1]);
  34602. var poleAxis = _axisDirections[(i - 1) % _axisDirections.length];
  34603. this._blur(cubeUVRenderTarget, i - 1, i, sigma, poleAxis);
  34604. }
  34605. renderer.autoClear = autoClear;
  34606. }
  34607. /**
  34608. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  34609. * vertically and horizontally, but this breaks down on a cube. Here we apply
  34610. * the blur latitudinally (around the poles), and then longitudinally (towards
  34611. * the poles) to approximate the orthogonally-separable blur. It is least
  34612. * accurate at the poles, but still does a decent job.
  34613. */
  34614. ;
  34615. _proto._blur = function _blur(cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis) {
  34616. var pingPongRenderTarget = this._pingPongRenderTarget;
  34617. this._halfBlur(cubeUVRenderTarget, pingPongRenderTarget, lodIn, lodOut, sigma, 'latitudinal', poleAxis);
  34618. this._halfBlur(pingPongRenderTarget, cubeUVRenderTarget, lodOut, lodOut, sigma, 'longitudinal', poleAxis);
  34619. };
  34620. _proto._halfBlur = function _halfBlur(targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis) {
  34621. var renderer = this._renderer;
  34622. var blurMaterial = this._blurMaterial;
  34623. if (direction !== 'latitudinal' && direction !== 'longitudinal') {
  34624. console.error('blur direction must be either latitudinal or longitudinal!');
  34625. } // Number of standard deviations at which to cut off the discrete approximation.
  34626. var STANDARD_DEVIATIONS = 3;
  34627. var blurMesh = new Mesh(_lodPlanes[lodOut], blurMaterial);
  34628. var blurUniforms = blurMaterial.uniforms;
  34629. var pixels = _sizeLods[lodIn] - 1;
  34630. var radiansPerPixel = isFinite(sigmaRadians) ? Math.PI / (2 * pixels) : 2 * Math.PI / (2 * MAX_SAMPLES - 1);
  34631. var sigmaPixels = sigmaRadians / radiansPerPixel;
  34632. var samples = isFinite(sigmaRadians) ? 1 + Math.floor(STANDARD_DEVIATIONS * sigmaPixels) : MAX_SAMPLES;
  34633. if (samples > MAX_SAMPLES) {
  34634. console.warn("sigmaRadians, " + sigmaRadians + ", is too large and will clip, as it requested " + samples + " samples when the maximum is set to " + MAX_SAMPLES);
  34635. }
  34636. var weights = [];
  34637. var sum = 0;
  34638. for (var i = 0; i < MAX_SAMPLES; ++i) {
  34639. var _x = i / sigmaPixels;
  34640. var weight = Math.exp(-_x * _x / 2);
  34641. weights.push(weight);
  34642. if (i == 0) {
  34643. sum += weight;
  34644. } else if (i < samples) {
  34645. sum += 2 * weight;
  34646. }
  34647. }
  34648. for (var _i = 0; _i < weights.length; _i++) {
  34649. weights[_i] = weights[_i] / sum;
  34650. }
  34651. blurUniforms['envMap'].value = targetIn.texture;
  34652. blurUniforms['samples'].value = samples;
  34653. blurUniforms['weights'].value = weights;
  34654. blurUniforms['latitudinal'].value = direction === 'latitudinal';
  34655. if (poleAxis) {
  34656. blurUniforms['poleAxis'].value = poleAxis;
  34657. }
  34658. blurUniforms['dTheta'].value = radiansPerPixel;
  34659. blurUniforms['mipInt'].value = LOD_MAX - lodIn;
  34660. blurUniforms['inputEncoding'].value = ENCODINGS[targetIn.texture.encoding];
  34661. blurUniforms['outputEncoding'].value = ENCODINGS[targetIn.texture.encoding];
  34662. var outputSize = _sizeLods[lodOut];
  34663. var x = 3 * Math.max(0, SIZE_MAX - 2 * outputSize);
  34664. var y = (lodOut === 0 ? 0 : 2 * SIZE_MAX) + 2 * outputSize * (lodOut > LOD_MAX - LOD_MIN ? lodOut - LOD_MAX + LOD_MIN : 0);
  34665. _setViewport(targetOut, x, y, 3 * outputSize, 2 * outputSize);
  34666. renderer.setRenderTarget(targetOut);
  34667. renderer.render(blurMesh, _flatCamera);
  34668. };
  34669. return PMREMGenerator;
  34670. }();
  34671. function _isLDR(texture) {
  34672. if (texture === undefined || texture.type !== UnsignedByteType) return false;
  34673. return texture.encoding === LinearEncoding || texture.encoding === sRGBEncoding || texture.encoding === GammaEncoding;
  34674. }
  34675. function _createPlanes() {
  34676. var _lodPlanes = [];
  34677. var _sizeLods = [];
  34678. var _sigmas = [];
  34679. var lod = LOD_MAX;
  34680. for (var i = 0; i < TOTAL_LODS; i++) {
  34681. var sizeLod = Math.pow(2, lod);
  34682. _sizeLods.push(sizeLod);
  34683. var sigma = 1.0 / sizeLod;
  34684. if (i > LOD_MAX - LOD_MIN) {
  34685. sigma = EXTRA_LOD_SIGMA[i - LOD_MAX + LOD_MIN - 1];
  34686. } else if (i == 0) {
  34687. sigma = 0;
  34688. }
  34689. _sigmas.push(sigma);
  34690. var texelSize = 1.0 / (sizeLod - 1);
  34691. var min = -texelSize / 2;
  34692. var max = 1 + texelSize / 2;
  34693. var uv1 = [min, min, max, min, max, max, min, min, max, max, min, max];
  34694. var cubeFaces = 6;
  34695. var vertices = 6;
  34696. var positionSize = 3;
  34697. var uvSize = 2;
  34698. var faceIndexSize = 1;
  34699. var position = new Float32Array(positionSize * vertices * cubeFaces);
  34700. var uv = new Float32Array(uvSize * vertices * cubeFaces);
  34701. var faceIndex = new Float32Array(faceIndexSize * vertices * cubeFaces);
  34702. for (var face = 0; face < cubeFaces; face++) {
  34703. var x = face % 3 * 2 / 3 - 1;
  34704. var y = face > 2 ? 0 : -1;
  34705. var coordinates = [x, y, 0, x + 2 / 3, y, 0, x + 2 / 3, y + 1, 0, x, y, 0, x + 2 / 3, y + 1, 0, x, y + 1, 0];
  34706. position.set(coordinates, positionSize * vertices * face);
  34707. uv.set(uv1, uvSize * vertices * face);
  34708. var fill = [face, face, face, face, face, face];
  34709. faceIndex.set(fill, faceIndexSize * vertices * face);
  34710. }
  34711. var planes = new BufferGeometry();
  34712. planes.setAttribute('position', new BufferAttribute(position, positionSize));
  34713. planes.setAttribute('uv', new BufferAttribute(uv, uvSize));
  34714. planes.setAttribute('faceIndex', new BufferAttribute(faceIndex, faceIndexSize));
  34715. _lodPlanes.push(planes);
  34716. if (lod > LOD_MIN) {
  34717. lod--;
  34718. }
  34719. }
  34720. return {
  34721. _lodPlanes: _lodPlanes,
  34722. _sizeLods: _sizeLods,
  34723. _sigmas: _sigmas
  34724. };
  34725. }
  34726. function _createRenderTarget(params) {
  34727. var cubeUVRenderTarget = new WebGLRenderTarget(3 * SIZE_MAX, 3 * SIZE_MAX, params);
  34728. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  34729. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  34730. cubeUVRenderTarget.scissorTest = true;
  34731. return cubeUVRenderTarget;
  34732. }
  34733. function _setViewport(target, x, y, width, height) {
  34734. target.viewport.set(x, y, width, height);
  34735. target.scissor.set(x, y, width, height);
  34736. }
  34737. function _getBlurShader(maxSamples) {
  34738. var weights = new Float32Array(maxSamples);
  34739. var poleAxis = new Vector3(0, 1, 0);
  34740. var shaderMaterial = new RawShaderMaterial({
  34741. name: 'SphericalGaussianBlur',
  34742. defines: {
  34743. 'n': maxSamples
  34744. },
  34745. uniforms: {
  34746. 'envMap': {
  34747. value: null
  34748. },
  34749. 'samples': {
  34750. value: 1
  34751. },
  34752. 'weights': {
  34753. value: weights
  34754. },
  34755. 'latitudinal': {
  34756. value: false
  34757. },
  34758. 'dTheta': {
  34759. value: 0
  34760. },
  34761. 'mipInt': {
  34762. value: 0
  34763. },
  34764. 'poleAxis': {
  34765. value: poleAxis
  34766. },
  34767. 'inputEncoding': {
  34768. value: ENCODINGS[LinearEncoding]
  34769. },
  34770. 'outputEncoding': {
  34771. value: ENCODINGS[LinearEncoding]
  34772. }
  34773. },
  34774. vertexShader: _getCommonVertexShader(),
  34775. fragmentShader:
  34776. /* glsl */
  34777. "\n\n\t\t\tprecision mediump float;\n\t\t\tprecision mediump int;\n\n\t\t\tvarying vec3 vOutputDirection;\n\n\t\t\tuniform sampler2D envMap;\n\t\t\tuniform int samples;\n\t\t\tuniform float weights[ n ];\n\t\t\tuniform bool latitudinal;\n\t\t\tuniform float dTheta;\n\t\t\tuniform float mipInt;\n\t\t\tuniform vec3 poleAxis;\n\n\t\t\t" + _getEncodings() + "\n\n\t\t\t#define ENVMAP_TYPE_CUBE_UV\n\t\t\t#include <cube_uv_reflection_fragment>\n\n\t\t\tvec3 getSample( float theta, vec3 axis ) {\n\n\t\t\t\tfloat cosTheta = cos( theta );\n\t\t\t\t// Rodrigues' axis-angle rotation\n\t\t\t\tvec3 sampleDirection = vOutputDirection * cosTheta\n\t\t\t\t\t+ cross( axis, vOutputDirection ) * sin( theta )\n\t\t\t\t\t+ axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta );\n\n\t\t\t\treturn bilinearCubeUV( envMap, sampleDirection, mipInt );\n\n\t\t\t}\n\n\t\t\tvoid main() {\n\n\t\t\t\tvec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection );\n\n\t\t\t\tif ( all( equal( axis, vec3( 0.0 ) ) ) ) {\n\n\t\t\t\t\taxis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x );\n\n\t\t\t\t}\n\n\t\t\t\taxis = normalize( axis );\n\n\t\t\t\tgl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );\n\t\t\t\tgl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis );\n\n\t\t\t\tfor ( int i = 1; i < n; i++ ) {\n\n\t\t\t\t\tif ( i >= samples ) {\n\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\t}\n\n\t\t\t\t\tfloat theta = dTheta * float( i );\n\t\t\t\t\tgl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis );\n\t\t\t\t\tgl_FragColor.rgb += weights[ i ] * getSample( theta, axis );\n\n\t\t\t\t}\n\n\t\t\t\tgl_FragColor = linearToOutputTexel( gl_FragColor );\n\n\t\t\t}\n\t\t",
  34778. blending: NoBlending,
  34779. depthTest: false,
  34780. depthWrite: false
  34781. });
  34782. return shaderMaterial;
  34783. }
  34784. function _getEquirectShader() {
  34785. var texelSize = new Vector2(1, 1);
  34786. var shaderMaterial = new RawShaderMaterial({
  34787. name: 'EquirectangularToCubeUV',
  34788. uniforms: {
  34789. 'envMap': {
  34790. value: null
  34791. },
  34792. 'texelSize': {
  34793. value: texelSize
  34794. },
  34795. 'inputEncoding': {
  34796. value: ENCODINGS[LinearEncoding]
  34797. },
  34798. 'outputEncoding': {
  34799. value: ENCODINGS[LinearEncoding]
  34800. }
  34801. },
  34802. vertexShader: _getCommonVertexShader(),
  34803. fragmentShader:
  34804. /* glsl */
  34805. "\n\n\t\t\tprecision mediump float;\n\t\t\tprecision mediump int;\n\n\t\t\tvarying vec3 vOutputDirection;\n\n\t\t\tuniform sampler2D envMap;\n\t\t\tuniform vec2 texelSize;\n\n\t\t\t" + _getEncodings() + "\n\n\t\t\t#include <common>\n\n\t\t\tvoid main() {\n\n\t\t\t\tgl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );\n\n\t\t\t\tvec3 outputDirection = normalize( vOutputDirection );\n\t\t\t\tvec2 uv = equirectUv( outputDirection );\n\n\t\t\t\tvec2 f = fract( uv / texelSize - 0.5 );\n\t\t\t\tuv -= f * texelSize;\n\t\t\t\tvec3 tl = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;\n\t\t\t\tuv.x += texelSize.x;\n\t\t\t\tvec3 tr = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;\n\t\t\t\tuv.y += texelSize.y;\n\t\t\t\tvec3 br = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;\n\t\t\t\tuv.x -= texelSize.x;\n\t\t\t\tvec3 bl = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;\n\n\t\t\t\tvec3 tm = mix( tl, tr, f.x );\n\t\t\t\tvec3 bm = mix( bl, br, f.x );\n\t\t\t\tgl_FragColor.rgb = mix( tm, bm, f.y );\n\n\t\t\t\tgl_FragColor = linearToOutputTexel( gl_FragColor );\n\n\t\t\t}\n\t\t",
  34806. blending: NoBlending,
  34807. depthTest: false,
  34808. depthWrite: false
  34809. });
  34810. return shaderMaterial;
  34811. }
  34812. function _getCubemapShader() {
  34813. var shaderMaterial = new RawShaderMaterial({
  34814. name: 'CubemapToCubeUV',
  34815. uniforms: {
  34816. 'envMap': {
  34817. value: null
  34818. },
  34819. 'inputEncoding': {
  34820. value: ENCODINGS[LinearEncoding]
  34821. },
  34822. 'outputEncoding': {
  34823. value: ENCODINGS[LinearEncoding]
  34824. }
  34825. },
  34826. vertexShader: _getCommonVertexShader(),
  34827. fragmentShader:
  34828. /* glsl */
  34829. "\n\n\t\t\tprecision mediump float;\n\t\t\tprecision mediump int;\n\n\t\t\tvarying vec3 vOutputDirection;\n\n\t\t\tuniform samplerCube envMap;\n\n\t\t\t" + _getEncodings() + "\n\n\t\t\tvoid main() {\n\n\t\t\t\tgl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );\n\t\t\t\tgl_FragColor.rgb = envMapTexelToLinear( textureCube( envMap, vec3( - vOutputDirection.x, vOutputDirection.yz ) ) ).rgb;\n\t\t\t\tgl_FragColor = linearToOutputTexel( gl_FragColor );\n\n\t\t\t}\n\t\t",
  34830. blending: NoBlending,
  34831. depthTest: false,
  34832. depthWrite: false
  34833. });
  34834. return shaderMaterial;
  34835. }
  34836. function _getCommonVertexShader() {
  34837. return (
  34838. /* glsl */
  34839. "\n\n\t\tprecision mediump float;\n\t\tprecision mediump int;\n\n\t\tattribute vec3 position;\n\t\tattribute vec2 uv;\n\t\tattribute float faceIndex;\n\n\t\tvarying vec3 vOutputDirection;\n\n\t\t// RH coordinate system; PMREM face-indexing convention\n\t\tvec3 getDirection( vec2 uv, float face ) {\n\n\t\t\tuv = 2.0 * uv - 1.0;\n\n\t\t\tvec3 direction = vec3( uv, 1.0 );\n\n\t\t\tif ( face == 0.0 ) {\n\n\t\t\t\tdirection = direction.zyx; // ( 1, v, u ) pos x\n\n\t\t\t} else if ( face == 1.0 ) {\n\n\t\t\t\tdirection = direction.xzy;\n\t\t\t\tdirection.xz *= -1.0; // ( -u, 1, -v ) pos y\n\n\t\t\t} else if ( face == 2.0 ) {\n\n\t\t\t\tdirection.x *= -1.0; // ( -u, v, 1 ) pos z\n\n\t\t\t} else if ( face == 3.0 ) {\n\n\t\t\t\tdirection = direction.zyx;\n\t\t\t\tdirection.xz *= -1.0; // ( -1, v, -u ) neg x\n\n\t\t\t} else if ( face == 4.0 ) {\n\n\t\t\t\tdirection = direction.xzy;\n\t\t\t\tdirection.xy *= -1.0; // ( -u, -1, v ) neg y\n\n\t\t\t} else if ( face == 5.0 ) {\n\n\t\t\t\tdirection.z *= -1.0; // ( u, v, -1 ) neg z\n\n\t\t\t}\n\n\t\t\treturn direction;\n\n\t\t}\n\n\t\tvoid main() {\n\n\t\t\tvOutputDirection = getDirection( uv, faceIndex );\n\t\t\tgl_Position = vec4( position, 1.0 );\n\n\t\t}\n\t"
  34840. );
  34841. }
  34842. function _getEncodings() {
  34843. return (
  34844. /* glsl */
  34845. "\n\n\t\tuniform int inputEncoding;\n\t\tuniform int outputEncoding;\n\n\t\t#include <encodings_pars_fragment>\n\n\t\tvec4 inputTexelToLinear( vec4 value ) {\n\n\t\t\tif ( inputEncoding == 0 ) {\n\n\t\t\t\treturn value;\n\n\t\t\t} else if ( inputEncoding == 1 ) {\n\n\t\t\t\treturn sRGBToLinear( value );\n\n\t\t\t} else if ( inputEncoding == 2 ) {\n\n\t\t\t\treturn RGBEToLinear( value );\n\n\t\t\t} else if ( inputEncoding == 3 ) {\n\n\t\t\t\treturn RGBMToLinear( value, 7.0 );\n\n\t\t\t} else if ( inputEncoding == 4 ) {\n\n\t\t\t\treturn RGBMToLinear( value, 16.0 );\n\n\t\t\t} else if ( inputEncoding == 5 ) {\n\n\t\t\t\treturn RGBDToLinear( value, 256.0 );\n\n\t\t\t} else {\n\n\t\t\t\treturn GammaToLinear( value, 2.2 );\n\n\t\t\t}\n\n\t\t}\n\n\t\tvec4 linearToOutputTexel( vec4 value ) {\n\n\t\t\tif ( outputEncoding == 0 ) {\n\n\t\t\t\treturn value;\n\n\t\t\t} else if ( outputEncoding == 1 ) {\n\n\t\t\t\treturn LinearTosRGB( value );\n\n\t\t\t} else if ( outputEncoding == 2 ) {\n\n\t\t\t\treturn LinearToRGBE( value );\n\n\t\t\t} else if ( outputEncoding == 3 ) {\n\n\t\t\t\treturn LinearToRGBM( value, 7.0 );\n\n\t\t\t} else if ( outputEncoding == 4 ) {\n\n\t\t\t\treturn LinearToRGBM( value, 16.0 );\n\n\t\t\t} else if ( outputEncoding == 5 ) {\n\n\t\t\t\treturn LinearToRGBD( value, 256.0 );\n\n\t\t\t} else {\n\n\t\t\t\treturn LinearToGamma( value, 2.2 );\n\n\t\t\t}\n\n\t\t}\n\n\t\tvec4 envMapTexelToLinear( vec4 color ) {\n\n\t\t\treturn inputTexelToLinear( color );\n\n\t\t}\n\t"
  34846. );
  34847. }
  34848. function Face4(a, b, c, d, normal, color, materialIndex) {
  34849. console.warn('THREE.Face4 has been removed. A THREE.Face3 will be created instead.');
  34850. return new Face3(a, b, c, normal, color, materialIndex);
  34851. }
  34852. var LineStrip = 0;
  34853. var LinePieces = 1;
  34854. var NoColors = 0;
  34855. var FaceColors = 1;
  34856. var VertexColors = 2;
  34857. function MeshFaceMaterial(materials) {
  34858. console.warn('THREE.MeshFaceMaterial has been removed. Use an Array instead.');
  34859. return materials;
  34860. }
  34861. function MultiMaterial(materials) {
  34862. if (materials === void 0) {
  34863. materials = [];
  34864. }
  34865. console.warn('THREE.MultiMaterial has been removed. Use an Array instead.');
  34866. materials.isMultiMaterial = true;
  34867. materials.materials = materials;
  34868. materials.clone = function () {
  34869. return materials.slice();
  34870. };
  34871. return materials;
  34872. }
  34873. function PointCloud(geometry, material) {
  34874. console.warn('THREE.PointCloud has been renamed to THREE.Points.');
  34875. return new Points(geometry, material);
  34876. }
  34877. function Particle(material) {
  34878. console.warn('THREE.Particle has been renamed to THREE.Sprite.');
  34879. return new Sprite(material);
  34880. }
  34881. function ParticleSystem(geometry, material) {
  34882. console.warn('THREE.ParticleSystem has been renamed to THREE.Points.');
  34883. return new Points(geometry, material);
  34884. }
  34885. function PointCloudMaterial(parameters) {
  34886. console.warn('THREE.PointCloudMaterial has been renamed to THREE.PointsMaterial.');
  34887. return new PointsMaterial(parameters);
  34888. }
  34889. function ParticleBasicMaterial(parameters) {
  34890. console.warn('THREE.ParticleBasicMaterial has been renamed to THREE.PointsMaterial.');
  34891. return new PointsMaterial(parameters);
  34892. }
  34893. function ParticleSystemMaterial(parameters) {
  34894. console.warn('THREE.ParticleSystemMaterial has been renamed to THREE.PointsMaterial.');
  34895. return new PointsMaterial(parameters);
  34896. }
  34897. function Vertex(x, y, z) {
  34898. console.warn('THREE.Vertex has been removed. Use THREE.Vector3 instead.');
  34899. return new Vector3(x, y, z);
  34900. } //
  34901. function DynamicBufferAttribute(array, itemSize) {
  34902. console.warn('THREE.DynamicBufferAttribute has been removed. Use new THREE.BufferAttribute().setUsage( THREE.DynamicDrawUsage ) instead.');
  34903. return new BufferAttribute(array, itemSize).setUsage(DynamicDrawUsage);
  34904. }
  34905. function Int8Attribute(array, itemSize) {
  34906. console.warn('THREE.Int8Attribute has been removed. Use new THREE.Int8BufferAttribute() instead.');
  34907. return new Int8BufferAttribute(array, itemSize);
  34908. }
  34909. function Uint8Attribute(array, itemSize) {
  34910. console.warn('THREE.Uint8Attribute has been removed. Use new THREE.Uint8BufferAttribute() instead.');
  34911. return new Uint8BufferAttribute(array, itemSize);
  34912. }
  34913. function Uint8ClampedAttribute(array, itemSize) {
  34914. console.warn('THREE.Uint8ClampedAttribute has been removed. Use new THREE.Uint8ClampedBufferAttribute() instead.');
  34915. return new Uint8ClampedBufferAttribute(array, itemSize);
  34916. }
  34917. function Int16Attribute(array, itemSize) {
  34918. console.warn('THREE.Int16Attribute has been removed. Use new THREE.Int16BufferAttribute() instead.');
  34919. return new Int16BufferAttribute(array, itemSize);
  34920. }
  34921. function Uint16Attribute(array, itemSize) {
  34922. console.warn('THREE.Uint16Attribute has been removed. Use new THREE.Uint16BufferAttribute() instead.');
  34923. return new Uint16BufferAttribute(array, itemSize);
  34924. }
  34925. function Int32Attribute(array, itemSize) {
  34926. console.warn('THREE.Int32Attribute has been removed. Use new THREE.Int32BufferAttribute() instead.');
  34927. return new Int32BufferAttribute(array, itemSize);
  34928. }
  34929. function Uint32Attribute(array, itemSize) {
  34930. console.warn('THREE.Uint32Attribute has been removed. Use new THREE.Uint32BufferAttribute() instead.');
  34931. return new Uint32BufferAttribute(array, itemSize);
  34932. }
  34933. function Float32Attribute(array, itemSize) {
  34934. console.warn('THREE.Float32Attribute has been removed. Use new THREE.Float32BufferAttribute() instead.');
  34935. return new Float32BufferAttribute(array, itemSize);
  34936. }
  34937. function Float64Attribute(array, itemSize) {
  34938. console.warn('THREE.Float64Attribute has been removed. Use new THREE.Float64BufferAttribute() instead.');
  34939. return new Float64BufferAttribute(array, itemSize);
  34940. } //
  34941. Curve.create = function (construct, getPoint) {
  34942. console.log('THREE.Curve.create() has been deprecated');
  34943. construct.prototype = Object.create(Curve.prototype);
  34944. construct.prototype.constructor = construct;
  34945. construct.prototype.getPoint = getPoint;
  34946. return construct;
  34947. }; //
  34948. Object.assign(Path.prototype, {
  34949. fromPoints: function fromPoints(points) {
  34950. console.warn('THREE.Path: .fromPoints() has been renamed to .setFromPoints().');
  34951. return this.setFromPoints(points);
  34952. }
  34953. }); //
  34954. function ClosedSplineCurve3(points) {
  34955. console.warn('THREE.ClosedSplineCurve3 has been deprecated. Use THREE.CatmullRomCurve3 instead.');
  34956. CatmullRomCurve3.call(this, points);
  34957. this.type = 'catmullrom';
  34958. this.closed = true;
  34959. }
  34960. ClosedSplineCurve3.prototype = Object.create(CatmullRomCurve3.prototype); //
  34961. function SplineCurve3(points) {
  34962. console.warn('THREE.SplineCurve3 has been deprecated. Use THREE.CatmullRomCurve3 instead.');
  34963. CatmullRomCurve3.call(this, points);
  34964. this.type = 'catmullrom';
  34965. }
  34966. SplineCurve3.prototype = Object.create(CatmullRomCurve3.prototype); //
  34967. function Spline(points) {
  34968. console.warn('THREE.Spline has been removed. Use THREE.CatmullRomCurve3 instead.');
  34969. CatmullRomCurve3.call(this, points);
  34970. this.type = 'catmullrom';
  34971. }
  34972. Spline.prototype = Object.create(CatmullRomCurve3.prototype);
  34973. Object.assign(Spline.prototype, {
  34974. initFromArray: function initFromArray()
  34975. /* a */
  34976. {
  34977. console.error('THREE.Spline: .initFromArray() has been removed.');
  34978. },
  34979. getControlPointsArray: function getControlPointsArray()
  34980. /* optionalTarget */
  34981. {
  34982. console.error('THREE.Spline: .getControlPointsArray() has been removed.');
  34983. },
  34984. reparametrizeByArcLength: function reparametrizeByArcLength()
  34985. /* samplingCoef */
  34986. {
  34987. console.error('THREE.Spline: .reparametrizeByArcLength() has been removed.');
  34988. }
  34989. }); //
  34990. function AxisHelper(size) {
  34991. console.warn('THREE.AxisHelper has been renamed to THREE.AxesHelper.');
  34992. return new AxesHelper(size);
  34993. }
  34994. function BoundingBoxHelper(object, color) {
  34995. console.warn('THREE.BoundingBoxHelper has been deprecated. Creating a THREE.BoxHelper instead.');
  34996. return new BoxHelper(object, color);
  34997. }
  34998. function EdgesHelper(object, hex) {
  34999. console.warn('THREE.EdgesHelper has been removed. Use THREE.EdgesGeometry instead.');
  35000. return new LineSegments(new EdgesGeometry(object.geometry), new LineBasicMaterial({
  35001. color: hex !== undefined ? hex : 0xffffff
  35002. }));
  35003. }
  35004. GridHelper.prototype.setColors = function () {
  35005. console.error('THREE.GridHelper: setColors() has been deprecated, pass them in the constructor instead.');
  35006. };
  35007. SkeletonHelper.prototype.update = function () {
  35008. console.error('THREE.SkeletonHelper: update() no longer needs to be called.');
  35009. };
  35010. function WireframeHelper(object, hex) {
  35011. console.warn('THREE.WireframeHelper has been removed. Use THREE.WireframeGeometry instead.');
  35012. return new LineSegments(new WireframeGeometry(object.geometry), new LineBasicMaterial({
  35013. color: hex !== undefined ? hex : 0xffffff
  35014. }));
  35015. } //
  35016. Object.assign(Loader.prototype, {
  35017. extractUrlBase: function extractUrlBase(url) {
  35018. console.warn('THREE.Loader: .extractUrlBase() has been deprecated. Use THREE.LoaderUtils.extractUrlBase() instead.');
  35019. return LoaderUtils.extractUrlBase(url);
  35020. }
  35021. });
  35022. Loader.Handlers = {
  35023. add: function add()
  35024. /* regex, loader */
  35025. {
  35026. console.error('THREE.Loader: Handlers.add() has been removed. Use LoadingManager.addHandler() instead.');
  35027. },
  35028. get: function get()
  35029. /* file */
  35030. {
  35031. console.error('THREE.Loader: Handlers.get() has been removed. Use LoadingManager.getHandler() instead.');
  35032. }
  35033. };
  35034. function XHRLoader(manager) {
  35035. console.warn('THREE.XHRLoader has been renamed to THREE.FileLoader.');
  35036. return new FileLoader(manager);
  35037. }
  35038. function BinaryTextureLoader(manager) {
  35039. console.warn('THREE.BinaryTextureLoader has been renamed to THREE.DataTextureLoader.');
  35040. return new DataTextureLoader(manager);
  35041. } //
  35042. Object.assign(Box2.prototype, {
  35043. center: function center(optionalTarget) {
  35044. console.warn('THREE.Box2: .center() has been renamed to .getCenter().');
  35045. return this.getCenter(optionalTarget);
  35046. },
  35047. empty: function empty() {
  35048. console.warn('THREE.Box2: .empty() has been renamed to .isEmpty().');
  35049. return this.isEmpty();
  35050. },
  35051. isIntersectionBox: function isIntersectionBox(box) {
  35052. console.warn('THREE.Box2: .isIntersectionBox() has been renamed to .intersectsBox().');
  35053. return this.intersectsBox(box);
  35054. },
  35055. size: function size(optionalTarget) {
  35056. console.warn('THREE.Box2: .size() has been renamed to .getSize().');
  35057. return this.getSize(optionalTarget);
  35058. }
  35059. });
  35060. Object.assign(Box3.prototype, {
  35061. center: function center(optionalTarget) {
  35062. console.warn('THREE.Box3: .center() has been renamed to .getCenter().');
  35063. return this.getCenter(optionalTarget);
  35064. },
  35065. empty: function empty() {
  35066. console.warn('THREE.Box3: .empty() has been renamed to .isEmpty().');
  35067. return this.isEmpty();
  35068. },
  35069. isIntersectionBox: function isIntersectionBox(box) {
  35070. console.warn('THREE.Box3: .isIntersectionBox() has been renamed to .intersectsBox().');
  35071. return this.intersectsBox(box);
  35072. },
  35073. isIntersectionSphere: function isIntersectionSphere(sphere) {
  35074. console.warn('THREE.Box3: .isIntersectionSphere() has been renamed to .intersectsSphere().');
  35075. return this.intersectsSphere(sphere);
  35076. },
  35077. size: function size(optionalTarget) {
  35078. console.warn('THREE.Box3: .size() has been renamed to .getSize().');
  35079. return this.getSize(optionalTarget);
  35080. }
  35081. });
  35082. Object.assign(Sphere.prototype, {
  35083. empty: function empty() {
  35084. console.warn('THREE.Sphere: .empty() has been renamed to .isEmpty().');
  35085. return this.isEmpty();
  35086. }
  35087. });
  35088. Frustum.prototype.setFromMatrix = function (m) {
  35089. console.warn('THREE.Frustum: .setFromMatrix() has been renamed to .setFromProjectionMatrix().');
  35090. return this.setFromProjectionMatrix(m);
  35091. };
  35092. Line3.prototype.center = function (optionalTarget) {
  35093. console.warn('THREE.Line3: .center() has been renamed to .getCenter().');
  35094. return this.getCenter(optionalTarget);
  35095. };
  35096. Object.assign(MathUtils, {
  35097. random16: function random16() {
  35098. console.warn('THREE.Math: .random16() has been deprecated. Use Math.random() instead.');
  35099. return Math.random();
  35100. },
  35101. nearestPowerOfTwo: function nearestPowerOfTwo(value) {
  35102. console.warn('THREE.Math: .nearestPowerOfTwo() has been renamed to .floorPowerOfTwo().');
  35103. return MathUtils.floorPowerOfTwo(value);
  35104. },
  35105. nextPowerOfTwo: function nextPowerOfTwo(value) {
  35106. console.warn('THREE.Math: .nextPowerOfTwo() has been renamed to .ceilPowerOfTwo().');
  35107. return MathUtils.ceilPowerOfTwo(value);
  35108. }
  35109. });
  35110. Object.assign(Matrix3.prototype, {
  35111. flattenToArrayOffset: function flattenToArrayOffset(array, offset) {
  35112. console.warn('THREE.Matrix3: .flattenToArrayOffset() has been deprecated. Use .toArray() instead.');
  35113. return this.toArray(array, offset);
  35114. },
  35115. multiplyVector3: function multiplyVector3(vector) {
  35116. console.warn('THREE.Matrix3: .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.');
  35117. return vector.applyMatrix3(this);
  35118. },
  35119. multiplyVector3Array: function multiplyVector3Array()
  35120. /* a */
  35121. {
  35122. console.error('THREE.Matrix3: .multiplyVector3Array() has been removed.');
  35123. },
  35124. applyToBufferAttribute: function applyToBufferAttribute(attribute) {
  35125. console.warn('THREE.Matrix3: .applyToBufferAttribute() has been removed. Use attribute.applyMatrix3( matrix ) instead.');
  35126. return attribute.applyMatrix3(this);
  35127. },
  35128. applyToVector3Array: function applyToVector3Array()
  35129. /* array, offset, length */
  35130. {
  35131. console.error('THREE.Matrix3: .applyToVector3Array() has been removed.');
  35132. },
  35133. getInverse: function getInverse(matrix) {
  35134. console.warn('THREE.Matrix3: .getInverse() has been removed. Use matrixInv.copy( matrix ).invert(); instead.');
  35135. return this.copy(matrix).invert();
  35136. }
  35137. });
  35138. Object.assign(Matrix4.prototype, {
  35139. extractPosition: function extractPosition(m) {
  35140. console.warn('THREE.Matrix4: .extractPosition() has been renamed to .copyPosition().');
  35141. return this.copyPosition(m);
  35142. },
  35143. flattenToArrayOffset: function flattenToArrayOffset(array, offset) {
  35144. console.warn('THREE.Matrix4: .flattenToArrayOffset() has been deprecated. Use .toArray() instead.');
  35145. return this.toArray(array, offset);
  35146. },
  35147. getPosition: function getPosition() {
  35148. console.warn('THREE.Matrix4: .getPosition() has been removed. Use Vector3.setFromMatrixPosition( matrix ) instead.');
  35149. return new Vector3().setFromMatrixColumn(this, 3);
  35150. },
  35151. setRotationFromQuaternion: function setRotationFromQuaternion(q) {
  35152. console.warn('THREE.Matrix4: .setRotationFromQuaternion() has been renamed to .makeRotationFromQuaternion().');
  35153. return this.makeRotationFromQuaternion(q);
  35154. },
  35155. multiplyToArray: function multiplyToArray() {
  35156. console.warn('THREE.Matrix4: .multiplyToArray() has been removed.');
  35157. },
  35158. multiplyVector3: function multiplyVector3(vector) {
  35159. console.warn('THREE.Matrix4: .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) instead.');
  35160. return vector.applyMatrix4(this);
  35161. },
  35162. multiplyVector4: function multiplyVector4(vector) {
  35163. console.warn('THREE.Matrix4: .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead.');
  35164. return vector.applyMatrix4(this);
  35165. },
  35166. multiplyVector3Array: function multiplyVector3Array()
  35167. /* a */
  35168. {
  35169. console.error('THREE.Matrix4: .multiplyVector3Array() has been removed.');
  35170. },
  35171. rotateAxis: function rotateAxis(v) {
  35172. console.warn('THREE.Matrix4: .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead.');
  35173. v.transformDirection(this);
  35174. },
  35175. crossVector: function crossVector(vector) {
  35176. console.warn('THREE.Matrix4: .crossVector() has been removed. Use vector.applyMatrix4( matrix ) instead.');
  35177. return vector.applyMatrix4(this);
  35178. },
  35179. translate: function translate() {
  35180. console.error('THREE.Matrix4: .translate() has been removed.');
  35181. },
  35182. rotateX: function rotateX() {
  35183. console.error('THREE.Matrix4: .rotateX() has been removed.');
  35184. },
  35185. rotateY: function rotateY() {
  35186. console.error('THREE.Matrix4: .rotateY() has been removed.');
  35187. },
  35188. rotateZ: function rotateZ() {
  35189. console.error('THREE.Matrix4: .rotateZ() has been removed.');
  35190. },
  35191. rotateByAxis: function rotateByAxis() {
  35192. console.error('THREE.Matrix4: .rotateByAxis() has been removed.');
  35193. },
  35194. applyToBufferAttribute: function applyToBufferAttribute(attribute) {
  35195. console.warn('THREE.Matrix4: .applyToBufferAttribute() has been removed. Use attribute.applyMatrix4( matrix ) instead.');
  35196. return attribute.applyMatrix4(this);
  35197. },
  35198. applyToVector3Array: function applyToVector3Array()
  35199. /* array, offset, length */
  35200. {
  35201. console.error('THREE.Matrix4: .applyToVector3Array() has been removed.');
  35202. },
  35203. makeFrustum: function makeFrustum(left, right, bottom, top, near, far) {
  35204. console.warn('THREE.Matrix4: .makeFrustum() has been removed. Use .makePerspective( left, right, top, bottom, near, far ) instead.');
  35205. return this.makePerspective(left, right, top, bottom, near, far);
  35206. },
  35207. getInverse: function getInverse(matrix) {
  35208. console.warn('THREE.Matrix4: .getInverse() has been removed. Use matrixInv.copy( matrix ).invert(); instead.');
  35209. return this.copy(matrix).invert();
  35210. }
  35211. });
  35212. Plane.prototype.isIntersectionLine = function (line) {
  35213. console.warn('THREE.Plane: .isIntersectionLine() has been renamed to .intersectsLine().');
  35214. return this.intersectsLine(line);
  35215. };
  35216. Object.assign(Quaternion.prototype, {
  35217. multiplyVector3: function multiplyVector3(vector) {
  35218. console.warn('THREE.Quaternion: .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.');
  35219. return vector.applyQuaternion(this);
  35220. },
  35221. inverse: function inverse() {
  35222. console.warn('THREE.Quaternion: .inverse() has been renamed to invert().');
  35223. return this.invert();
  35224. }
  35225. });
  35226. Object.assign(Ray.prototype, {
  35227. isIntersectionBox: function isIntersectionBox(box) {
  35228. console.warn('THREE.Ray: .isIntersectionBox() has been renamed to .intersectsBox().');
  35229. return this.intersectsBox(box);
  35230. },
  35231. isIntersectionPlane: function isIntersectionPlane(plane) {
  35232. console.warn('THREE.Ray: .isIntersectionPlane() has been renamed to .intersectsPlane().');
  35233. return this.intersectsPlane(plane);
  35234. },
  35235. isIntersectionSphere: function isIntersectionSphere(sphere) {
  35236. console.warn('THREE.Ray: .isIntersectionSphere() has been renamed to .intersectsSphere().');
  35237. return this.intersectsSphere(sphere);
  35238. }
  35239. });
  35240. Object.assign(Triangle.prototype, {
  35241. area: function area() {
  35242. console.warn('THREE.Triangle: .area() has been renamed to .getArea().');
  35243. return this.getArea();
  35244. },
  35245. barycoordFromPoint: function barycoordFromPoint(point, target) {
  35246. console.warn('THREE.Triangle: .barycoordFromPoint() has been renamed to .getBarycoord().');
  35247. return this.getBarycoord(point, target);
  35248. },
  35249. midpoint: function midpoint(target) {
  35250. console.warn('THREE.Triangle: .midpoint() has been renamed to .getMidpoint().');
  35251. return this.getMidpoint(target);
  35252. },
  35253. normal: function normal(target) {
  35254. console.warn('THREE.Triangle: .normal() has been renamed to .getNormal().');
  35255. return this.getNormal(target);
  35256. },
  35257. plane: function plane(target) {
  35258. console.warn('THREE.Triangle: .plane() has been renamed to .getPlane().');
  35259. return this.getPlane(target);
  35260. }
  35261. });
  35262. Object.assign(Triangle, {
  35263. barycoordFromPoint: function barycoordFromPoint(point, a, b, c, target) {
  35264. console.warn('THREE.Triangle: .barycoordFromPoint() has been renamed to .getBarycoord().');
  35265. return Triangle.getBarycoord(point, a, b, c, target);
  35266. },
  35267. normal: function normal(a, b, c, target) {
  35268. console.warn('THREE.Triangle: .normal() has been renamed to .getNormal().');
  35269. return Triangle.getNormal(a, b, c, target);
  35270. }
  35271. });
  35272. Object.assign(Shape.prototype, {
  35273. extractAllPoints: function extractAllPoints(divisions) {
  35274. console.warn('THREE.Shape: .extractAllPoints() has been removed. Use .extractPoints() instead.');
  35275. return this.extractPoints(divisions);
  35276. },
  35277. extrude: function extrude(options) {
  35278. console.warn('THREE.Shape: .extrude() has been removed. Use ExtrudeGeometry() instead.');
  35279. return new ExtrudeGeometry(this, options);
  35280. },
  35281. makeGeometry: function makeGeometry(options) {
  35282. console.warn('THREE.Shape: .makeGeometry() has been removed. Use ShapeGeometry() instead.');
  35283. return new ShapeGeometry(this, options);
  35284. }
  35285. });
  35286. Object.assign(Vector2.prototype, {
  35287. fromAttribute: function fromAttribute(attribute, index, offset) {
  35288. console.warn('THREE.Vector2: .fromAttribute() has been renamed to .fromBufferAttribute().');
  35289. return this.fromBufferAttribute(attribute, index, offset);
  35290. },
  35291. distanceToManhattan: function distanceToManhattan(v) {
  35292. console.warn('THREE.Vector2: .distanceToManhattan() has been renamed to .manhattanDistanceTo().');
  35293. return this.manhattanDistanceTo(v);
  35294. },
  35295. lengthManhattan: function lengthManhattan() {
  35296. console.warn('THREE.Vector2: .lengthManhattan() has been renamed to .manhattanLength().');
  35297. return this.manhattanLength();
  35298. }
  35299. });
  35300. Object.assign(Vector3.prototype, {
  35301. setEulerFromRotationMatrix: function setEulerFromRotationMatrix() {
  35302. console.error('THREE.Vector3: .setEulerFromRotationMatrix() has been removed. Use Euler.setFromRotationMatrix() instead.');
  35303. },
  35304. setEulerFromQuaternion: function setEulerFromQuaternion() {
  35305. console.error('THREE.Vector3: .setEulerFromQuaternion() has been removed. Use Euler.setFromQuaternion() instead.');
  35306. },
  35307. getPositionFromMatrix: function getPositionFromMatrix(m) {
  35308. console.warn('THREE.Vector3: .getPositionFromMatrix() has been renamed to .setFromMatrixPosition().');
  35309. return this.setFromMatrixPosition(m);
  35310. },
  35311. getScaleFromMatrix: function getScaleFromMatrix(m) {
  35312. console.warn('THREE.Vector3: .getScaleFromMatrix() has been renamed to .setFromMatrixScale().');
  35313. return this.setFromMatrixScale(m);
  35314. },
  35315. getColumnFromMatrix: function getColumnFromMatrix(index, matrix) {
  35316. console.warn('THREE.Vector3: .getColumnFromMatrix() has been renamed to .setFromMatrixColumn().');
  35317. return this.setFromMatrixColumn(matrix, index);
  35318. },
  35319. applyProjection: function applyProjection(m) {
  35320. console.warn('THREE.Vector3: .applyProjection() has been removed. Use .applyMatrix4( m ) instead.');
  35321. return this.applyMatrix4(m);
  35322. },
  35323. fromAttribute: function fromAttribute(attribute, index, offset) {
  35324. console.warn('THREE.Vector3: .fromAttribute() has been renamed to .fromBufferAttribute().');
  35325. return this.fromBufferAttribute(attribute, index, offset);
  35326. },
  35327. distanceToManhattan: function distanceToManhattan(v) {
  35328. console.warn('THREE.Vector3: .distanceToManhattan() has been renamed to .manhattanDistanceTo().');
  35329. return this.manhattanDistanceTo(v);
  35330. },
  35331. lengthManhattan: function lengthManhattan() {
  35332. console.warn('THREE.Vector3: .lengthManhattan() has been renamed to .manhattanLength().');
  35333. return this.manhattanLength();
  35334. }
  35335. });
  35336. Object.assign(Vector4.prototype, {
  35337. fromAttribute: function fromAttribute(attribute, index, offset) {
  35338. console.warn('THREE.Vector4: .fromAttribute() has been renamed to .fromBufferAttribute().');
  35339. return this.fromBufferAttribute(attribute, index, offset);
  35340. },
  35341. lengthManhattan: function lengthManhattan() {
  35342. console.warn('THREE.Vector4: .lengthManhattan() has been renamed to .manhattanLength().');
  35343. return this.manhattanLength();
  35344. }
  35345. }); //
  35346. Object.assign(Object3D.prototype, {
  35347. getChildByName: function getChildByName(name) {
  35348. console.warn('THREE.Object3D: .getChildByName() has been renamed to .getObjectByName().');
  35349. return this.getObjectByName(name);
  35350. },
  35351. renderDepth: function renderDepth() {
  35352. console.warn('THREE.Object3D: .renderDepth has been removed. Use .renderOrder, instead.');
  35353. },
  35354. translate: function translate(distance, axis) {
  35355. console.warn('THREE.Object3D: .translate() has been removed. Use .translateOnAxis( axis, distance ) instead.');
  35356. return this.translateOnAxis(axis, distance);
  35357. },
  35358. getWorldRotation: function getWorldRotation() {
  35359. console.error('THREE.Object3D: .getWorldRotation() has been removed. Use THREE.Object3D.getWorldQuaternion( target ) instead.');
  35360. },
  35361. applyMatrix: function applyMatrix(matrix) {
  35362. console.warn('THREE.Object3D: .applyMatrix() has been renamed to .applyMatrix4().');
  35363. return this.applyMatrix4(matrix);
  35364. }
  35365. });
  35366. Object.defineProperties(Object3D.prototype, {
  35367. eulerOrder: {
  35368. get: function get() {
  35369. console.warn('THREE.Object3D: .eulerOrder is now .rotation.order.');
  35370. return this.rotation.order;
  35371. },
  35372. set: function set(value) {
  35373. console.warn('THREE.Object3D: .eulerOrder is now .rotation.order.');
  35374. this.rotation.order = value;
  35375. }
  35376. },
  35377. useQuaternion: {
  35378. get: function get() {
  35379. console.warn('THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.');
  35380. },
  35381. set: function set() {
  35382. console.warn('THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.');
  35383. }
  35384. }
  35385. });
  35386. Object.assign(Mesh.prototype, {
  35387. setDrawMode: function setDrawMode() {
  35388. console.error('THREE.Mesh: .setDrawMode() has been removed. The renderer now always assumes THREE.TrianglesDrawMode. Transform your geometry via BufferGeometryUtils.toTrianglesDrawMode() if necessary.');
  35389. }
  35390. });
  35391. Object.defineProperties(Mesh.prototype, {
  35392. drawMode: {
  35393. get: function get() {
  35394. console.error('THREE.Mesh: .drawMode has been removed. The renderer now always assumes THREE.TrianglesDrawMode.');
  35395. return TrianglesDrawMode;
  35396. },
  35397. set: function set() {
  35398. console.error('THREE.Mesh: .drawMode has been removed. The renderer now always assumes THREE.TrianglesDrawMode. Transform your geometry via BufferGeometryUtils.toTrianglesDrawMode() if necessary.');
  35399. }
  35400. }
  35401. });
  35402. Object.defineProperties(LOD.prototype, {
  35403. objects: {
  35404. get: function get() {
  35405. console.warn('THREE.LOD: .objects has been renamed to .levels.');
  35406. return this.levels;
  35407. }
  35408. }
  35409. });
  35410. Object.defineProperty(Skeleton.prototype, 'useVertexTexture', {
  35411. get: function get() {
  35412. console.warn('THREE.Skeleton: useVertexTexture has been removed.');
  35413. },
  35414. set: function set() {
  35415. console.warn('THREE.Skeleton: useVertexTexture has been removed.');
  35416. }
  35417. });
  35418. SkinnedMesh.prototype.initBones = function () {
  35419. console.error('THREE.SkinnedMesh: initBones() has been removed.');
  35420. };
  35421. Object.defineProperty(Curve.prototype, '__arcLengthDivisions', {
  35422. get: function get() {
  35423. console.warn('THREE.Curve: .__arcLengthDivisions is now .arcLengthDivisions.');
  35424. return this.arcLengthDivisions;
  35425. },
  35426. set: function set(value) {
  35427. console.warn('THREE.Curve: .__arcLengthDivisions is now .arcLengthDivisions.');
  35428. this.arcLengthDivisions = value;
  35429. }
  35430. }); //
  35431. PerspectiveCamera.prototype.setLens = function (focalLength, filmGauge) {
  35432. console.warn('THREE.PerspectiveCamera.setLens is deprecated. ' + 'Use .setFocalLength and .filmGauge for a photographic setup.');
  35433. if (filmGauge !== undefined) this.filmGauge = filmGauge;
  35434. this.setFocalLength(focalLength);
  35435. }; //
  35436. Object.defineProperties(Light.prototype, {
  35437. onlyShadow: {
  35438. set: function set() {
  35439. console.warn('THREE.Light: .onlyShadow has been removed.');
  35440. }
  35441. },
  35442. shadowCameraFov: {
  35443. set: function set(value) {
  35444. console.warn('THREE.Light: .shadowCameraFov is now .shadow.camera.fov.');
  35445. this.shadow.camera.fov = value;
  35446. }
  35447. },
  35448. shadowCameraLeft: {
  35449. set: function set(value) {
  35450. console.warn('THREE.Light: .shadowCameraLeft is now .shadow.camera.left.');
  35451. this.shadow.camera.left = value;
  35452. }
  35453. },
  35454. shadowCameraRight: {
  35455. set: function set(value) {
  35456. console.warn('THREE.Light: .shadowCameraRight is now .shadow.camera.right.');
  35457. this.shadow.camera.right = value;
  35458. }
  35459. },
  35460. shadowCameraTop: {
  35461. set: function set(value) {
  35462. console.warn('THREE.Light: .shadowCameraTop is now .shadow.camera.top.');
  35463. this.shadow.camera.top = value;
  35464. }
  35465. },
  35466. shadowCameraBottom: {
  35467. set: function set(value) {
  35468. console.warn('THREE.Light: .shadowCameraBottom is now .shadow.camera.bottom.');
  35469. this.shadow.camera.bottom = value;
  35470. }
  35471. },
  35472. shadowCameraNear: {
  35473. set: function set(value) {
  35474. console.warn('THREE.Light: .shadowCameraNear is now .shadow.camera.near.');
  35475. this.shadow.camera.near = value;
  35476. }
  35477. },
  35478. shadowCameraFar: {
  35479. set: function set(value) {
  35480. console.warn('THREE.Light: .shadowCameraFar is now .shadow.camera.far.');
  35481. this.shadow.camera.far = value;
  35482. }
  35483. },
  35484. shadowCameraVisible: {
  35485. set: function set() {
  35486. console.warn('THREE.Light: .shadowCameraVisible has been removed. Use new THREE.CameraHelper( light.shadow.camera ) instead.');
  35487. }
  35488. },
  35489. shadowBias: {
  35490. set: function set(value) {
  35491. console.warn('THREE.Light: .shadowBias is now .shadow.bias.');
  35492. this.shadow.bias = value;
  35493. }
  35494. },
  35495. shadowDarkness: {
  35496. set: function set() {
  35497. console.warn('THREE.Light: .shadowDarkness has been removed.');
  35498. }
  35499. },
  35500. shadowMapWidth: {
  35501. set: function set(value) {
  35502. console.warn('THREE.Light: .shadowMapWidth is now .shadow.mapSize.width.');
  35503. this.shadow.mapSize.width = value;
  35504. }
  35505. },
  35506. shadowMapHeight: {
  35507. set: function set(value) {
  35508. console.warn('THREE.Light: .shadowMapHeight is now .shadow.mapSize.height.');
  35509. this.shadow.mapSize.height = value;
  35510. }
  35511. }
  35512. }); //
  35513. Object.defineProperties(BufferAttribute.prototype, {
  35514. length: {
  35515. get: function get() {
  35516. console.warn('THREE.BufferAttribute: .length has been deprecated. Use .count instead.');
  35517. return this.array.length;
  35518. }
  35519. },
  35520. dynamic: {
  35521. get: function get() {
  35522. console.warn('THREE.BufferAttribute: .dynamic has been deprecated. Use .usage instead.');
  35523. return this.usage === DynamicDrawUsage;
  35524. },
  35525. set: function set()
  35526. /* value */
  35527. {
  35528. console.warn('THREE.BufferAttribute: .dynamic has been deprecated. Use .usage instead.');
  35529. this.setUsage(DynamicDrawUsage);
  35530. }
  35531. }
  35532. });
  35533. Object.assign(BufferAttribute.prototype, {
  35534. setDynamic: function setDynamic(value) {
  35535. console.warn('THREE.BufferAttribute: .setDynamic() has been deprecated. Use .setUsage() instead.');
  35536. this.setUsage(value === true ? DynamicDrawUsage : StaticDrawUsage);
  35537. return this;
  35538. },
  35539. copyIndicesArray: function copyIndicesArray()
  35540. /* indices */
  35541. {
  35542. console.error('THREE.BufferAttribute: .copyIndicesArray() has been removed.');
  35543. },
  35544. setArray: function setArray()
  35545. /* array */
  35546. {
  35547. console.error('THREE.BufferAttribute: .setArray has been removed. Use BufferGeometry .setAttribute to replace/resize attribute buffers');
  35548. }
  35549. });
  35550. Object.assign(BufferGeometry.prototype, {
  35551. addIndex: function addIndex(index) {
  35552. console.warn('THREE.BufferGeometry: .addIndex() has been renamed to .setIndex().');
  35553. this.setIndex(index);
  35554. },
  35555. addAttribute: function addAttribute(name, attribute) {
  35556. console.warn('THREE.BufferGeometry: .addAttribute() has been renamed to .setAttribute().');
  35557. if (!(attribute && attribute.isBufferAttribute) && !(attribute && attribute.isInterleavedBufferAttribute)) {
  35558. console.warn('THREE.BufferGeometry: .addAttribute() now expects ( name, attribute ).');
  35559. return this.setAttribute(name, new BufferAttribute(arguments[1], arguments[2]));
  35560. }
  35561. if (name === 'index') {
  35562. console.warn('THREE.BufferGeometry.addAttribute: Use .setIndex() for index attribute.');
  35563. this.setIndex(attribute);
  35564. return this;
  35565. }
  35566. return this.setAttribute(name, attribute);
  35567. },
  35568. addDrawCall: function addDrawCall(start, count, indexOffset) {
  35569. if (indexOffset !== undefined) {
  35570. console.warn('THREE.BufferGeometry: .addDrawCall() no longer supports indexOffset.');
  35571. }
  35572. console.warn('THREE.BufferGeometry: .addDrawCall() is now .addGroup().');
  35573. this.addGroup(start, count);
  35574. },
  35575. clearDrawCalls: function clearDrawCalls() {
  35576. console.warn('THREE.BufferGeometry: .clearDrawCalls() is now .clearGroups().');
  35577. this.clearGroups();
  35578. },
  35579. computeOffsets: function computeOffsets() {
  35580. console.warn('THREE.BufferGeometry: .computeOffsets() has been removed.');
  35581. },
  35582. removeAttribute: function removeAttribute(name) {
  35583. console.warn('THREE.BufferGeometry: .removeAttribute() has been renamed to .deleteAttribute().');
  35584. return this.deleteAttribute(name);
  35585. },
  35586. applyMatrix: function applyMatrix(matrix) {
  35587. console.warn('THREE.BufferGeometry: .applyMatrix() has been renamed to .applyMatrix4().');
  35588. return this.applyMatrix4(matrix);
  35589. }
  35590. });
  35591. Object.defineProperties(BufferGeometry.prototype, {
  35592. drawcalls: {
  35593. get: function get() {
  35594. console.error('THREE.BufferGeometry: .drawcalls has been renamed to .groups.');
  35595. return this.groups;
  35596. }
  35597. },
  35598. offsets: {
  35599. get: function get() {
  35600. console.warn('THREE.BufferGeometry: .offsets has been renamed to .groups.');
  35601. return this.groups;
  35602. }
  35603. }
  35604. });
  35605. Object.defineProperties(InstancedBufferGeometry.prototype, {
  35606. maxInstancedCount: {
  35607. get: function get() {
  35608. console.warn('THREE.InstancedBufferGeometry: .maxInstancedCount has been renamed to .instanceCount.');
  35609. return this.instanceCount;
  35610. },
  35611. set: function set(value) {
  35612. console.warn('THREE.InstancedBufferGeometry: .maxInstancedCount has been renamed to .instanceCount.');
  35613. this.instanceCount = value;
  35614. }
  35615. }
  35616. });
  35617. Object.defineProperties(Raycaster.prototype, {
  35618. linePrecision: {
  35619. get: function get() {
  35620. console.warn('THREE.Raycaster: .linePrecision has been deprecated. Use .params.Line.threshold instead.');
  35621. return this.params.Line.threshold;
  35622. },
  35623. set: function set(value) {
  35624. console.warn('THREE.Raycaster: .linePrecision has been deprecated. Use .params.Line.threshold instead.');
  35625. this.params.Line.threshold = value;
  35626. }
  35627. }
  35628. });
  35629. Object.defineProperties(InterleavedBuffer.prototype, {
  35630. dynamic: {
  35631. get: function get() {
  35632. console.warn('THREE.InterleavedBuffer: .length has been deprecated. Use .usage instead.');
  35633. return this.usage === DynamicDrawUsage;
  35634. },
  35635. set: function set(value) {
  35636. console.warn('THREE.InterleavedBuffer: .length has been deprecated. Use .usage instead.');
  35637. this.setUsage(value);
  35638. }
  35639. }
  35640. });
  35641. Object.assign(InterleavedBuffer.prototype, {
  35642. setDynamic: function setDynamic(value) {
  35643. console.warn('THREE.InterleavedBuffer: .setDynamic() has been deprecated. Use .setUsage() instead.');
  35644. this.setUsage(value === true ? DynamicDrawUsage : StaticDrawUsage);
  35645. return this;
  35646. },
  35647. setArray: function setArray()
  35648. /* array */
  35649. {
  35650. console.error('THREE.InterleavedBuffer: .setArray has been removed. Use BufferGeometry .setAttribute to replace/resize attribute buffers');
  35651. }
  35652. }); //
  35653. Object.assign(ExtrudeGeometry.prototype, {
  35654. getArrays: function getArrays() {
  35655. console.error('THREE.ExtrudeGeometry: .getArrays() has been removed.');
  35656. },
  35657. addShapeList: function addShapeList() {
  35658. console.error('THREE.ExtrudeGeometry: .addShapeList() has been removed.');
  35659. },
  35660. addShape: function addShape() {
  35661. console.error('THREE.ExtrudeGeometry: .addShape() has been removed.');
  35662. }
  35663. }); //
  35664. Object.assign(Scene.prototype, {
  35665. dispose: function dispose() {
  35666. console.error('THREE.Scene: .dispose() has been removed.');
  35667. }
  35668. }); //
  35669. Object.defineProperties(Uniform.prototype, {
  35670. dynamic: {
  35671. set: function set() {
  35672. console.warn('THREE.Uniform: .dynamic has been removed. Use object.onBeforeRender() instead.');
  35673. }
  35674. },
  35675. onUpdate: {
  35676. value: function value() {
  35677. console.warn('THREE.Uniform: .onUpdate() has been removed. Use object.onBeforeRender() instead.');
  35678. return this;
  35679. }
  35680. }
  35681. }); //
  35682. Object.defineProperties(Material.prototype, {
  35683. wrapAround: {
  35684. get: function get() {
  35685. console.warn('THREE.Material: .wrapAround has been removed.');
  35686. },
  35687. set: function set() {
  35688. console.warn('THREE.Material: .wrapAround has been removed.');
  35689. }
  35690. },
  35691. overdraw: {
  35692. get: function get() {
  35693. console.warn('THREE.Material: .overdraw has been removed.');
  35694. },
  35695. set: function set() {
  35696. console.warn('THREE.Material: .overdraw has been removed.');
  35697. }
  35698. },
  35699. wrapRGB: {
  35700. get: function get() {
  35701. console.warn('THREE.Material: .wrapRGB has been removed.');
  35702. return new Color();
  35703. }
  35704. },
  35705. shading: {
  35706. get: function get() {
  35707. console.error('THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.');
  35708. },
  35709. set: function set(value) {
  35710. console.warn('THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.');
  35711. this.flatShading = value === FlatShading;
  35712. }
  35713. },
  35714. stencilMask: {
  35715. get: function get() {
  35716. console.warn('THREE.' + this.type + ': .stencilMask has been removed. Use .stencilFuncMask instead.');
  35717. return this.stencilFuncMask;
  35718. },
  35719. set: function set(value) {
  35720. console.warn('THREE.' + this.type + ': .stencilMask has been removed. Use .stencilFuncMask instead.');
  35721. this.stencilFuncMask = value;
  35722. }
  35723. }
  35724. });
  35725. Object.defineProperties(MeshPhongMaterial.prototype, {
  35726. metal: {
  35727. get: function get() {
  35728. console.warn('THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead.');
  35729. return false;
  35730. },
  35731. set: function set() {
  35732. console.warn('THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead');
  35733. }
  35734. }
  35735. });
  35736. Object.defineProperties(MeshPhysicalMaterial.prototype, {
  35737. transparency: {
  35738. get: function get() {
  35739. console.warn('THREE.MeshPhysicalMaterial: .transparency has been renamed to .transmission.');
  35740. return this.transmission;
  35741. },
  35742. set: function set(value) {
  35743. console.warn('THREE.MeshPhysicalMaterial: .transparency has been renamed to .transmission.');
  35744. this.transmission = value;
  35745. }
  35746. }
  35747. });
  35748. Object.defineProperties(ShaderMaterial.prototype, {
  35749. derivatives: {
  35750. get: function get() {
  35751. console.warn('THREE.ShaderMaterial: .derivatives has been moved to .extensions.derivatives.');
  35752. return this.extensions.derivatives;
  35753. },
  35754. set: function set(value) {
  35755. console.warn('THREE. ShaderMaterial: .derivatives has been moved to .extensions.derivatives.');
  35756. this.extensions.derivatives = value;
  35757. }
  35758. }
  35759. }); //
  35760. Object.assign(WebGLRenderer.prototype, {
  35761. clearTarget: function clearTarget(renderTarget, color, depth, stencil) {
  35762. console.warn('THREE.WebGLRenderer: .clearTarget() has been deprecated. Use .setRenderTarget() and .clear() instead.');
  35763. this.setRenderTarget(renderTarget);
  35764. this.clear(color, depth, stencil);
  35765. },
  35766. animate: function animate(callback) {
  35767. console.warn('THREE.WebGLRenderer: .animate() is now .setAnimationLoop().');
  35768. this.setAnimationLoop(callback);
  35769. },
  35770. getCurrentRenderTarget: function getCurrentRenderTarget() {
  35771. console.warn('THREE.WebGLRenderer: .getCurrentRenderTarget() is now .getRenderTarget().');
  35772. return this.getRenderTarget();
  35773. },
  35774. getMaxAnisotropy: function getMaxAnisotropy() {
  35775. console.warn('THREE.WebGLRenderer: .getMaxAnisotropy() is now .capabilities.getMaxAnisotropy().');
  35776. return this.capabilities.getMaxAnisotropy();
  35777. },
  35778. getPrecision: function getPrecision() {
  35779. console.warn('THREE.WebGLRenderer: .getPrecision() is now .capabilities.precision.');
  35780. return this.capabilities.precision;
  35781. },
  35782. resetGLState: function resetGLState() {
  35783. console.warn('THREE.WebGLRenderer: .resetGLState() is now .state.reset().');
  35784. return this.state.reset();
  35785. },
  35786. supportsFloatTextures: function supportsFloatTextures() {
  35787. console.warn('THREE.WebGLRenderer: .supportsFloatTextures() is now .extensions.get( \'OES_texture_float\' ).');
  35788. return this.extensions.get('OES_texture_float');
  35789. },
  35790. supportsHalfFloatTextures: function supportsHalfFloatTextures() {
  35791. console.warn('THREE.WebGLRenderer: .supportsHalfFloatTextures() is now .extensions.get( \'OES_texture_half_float\' ).');
  35792. return this.extensions.get('OES_texture_half_float');
  35793. },
  35794. supportsStandardDerivatives: function supportsStandardDerivatives() {
  35795. console.warn('THREE.WebGLRenderer: .supportsStandardDerivatives() is now .extensions.get( \'OES_standard_derivatives\' ).');
  35796. return this.extensions.get('OES_standard_derivatives');
  35797. },
  35798. supportsCompressedTextureS3TC: function supportsCompressedTextureS3TC() {
  35799. console.warn('THREE.WebGLRenderer: .supportsCompressedTextureS3TC() is now .extensions.get( \'WEBGL_compressed_texture_s3tc\' ).');
  35800. return this.extensions.get('WEBGL_compressed_texture_s3tc');
  35801. },
  35802. supportsCompressedTexturePVRTC: function supportsCompressedTexturePVRTC() {
  35803. console.warn('THREE.WebGLRenderer: .supportsCompressedTexturePVRTC() is now .extensions.get( \'WEBGL_compressed_texture_pvrtc\' ).');
  35804. return this.extensions.get('WEBGL_compressed_texture_pvrtc');
  35805. },
  35806. supportsBlendMinMax: function supportsBlendMinMax() {
  35807. console.warn('THREE.WebGLRenderer: .supportsBlendMinMax() is now .extensions.get( \'EXT_blend_minmax\' ).');
  35808. return this.extensions.get('EXT_blend_minmax');
  35809. },
  35810. supportsVertexTextures: function supportsVertexTextures() {
  35811. console.warn('THREE.WebGLRenderer: .supportsVertexTextures() is now .capabilities.vertexTextures.');
  35812. return this.capabilities.vertexTextures;
  35813. },
  35814. supportsInstancedArrays: function supportsInstancedArrays() {
  35815. console.warn('THREE.WebGLRenderer: .supportsInstancedArrays() is now .extensions.get( \'ANGLE_instanced_arrays\' ).');
  35816. return this.extensions.get('ANGLE_instanced_arrays');
  35817. },
  35818. enableScissorTest: function enableScissorTest(boolean) {
  35819. console.warn('THREE.WebGLRenderer: .enableScissorTest() is now .setScissorTest().');
  35820. this.setScissorTest(boolean);
  35821. },
  35822. initMaterial: function initMaterial() {
  35823. console.warn('THREE.WebGLRenderer: .initMaterial() has been removed.');
  35824. },
  35825. addPrePlugin: function addPrePlugin() {
  35826. console.warn('THREE.WebGLRenderer: .addPrePlugin() has been removed.');
  35827. },
  35828. addPostPlugin: function addPostPlugin() {
  35829. console.warn('THREE.WebGLRenderer: .addPostPlugin() has been removed.');
  35830. },
  35831. updateShadowMap: function updateShadowMap() {
  35832. console.warn('THREE.WebGLRenderer: .updateShadowMap() has been removed.');
  35833. },
  35834. setFaceCulling: function setFaceCulling() {
  35835. console.warn('THREE.WebGLRenderer: .setFaceCulling() has been removed.');
  35836. },
  35837. allocTextureUnit: function allocTextureUnit() {
  35838. console.warn('THREE.WebGLRenderer: .allocTextureUnit() has been removed.');
  35839. },
  35840. setTexture: function setTexture() {
  35841. console.warn('THREE.WebGLRenderer: .setTexture() has been removed.');
  35842. },
  35843. setTextureCube: function setTextureCube() {
  35844. console.warn('THREE.WebGLRenderer: .setTextureCube() has been removed.');
  35845. },
  35846. getActiveMipMapLevel: function getActiveMipMapLevel() {
  35847. console.warn('THREE.WebGLRenderer: .getActiveMipMapLevel() is now .getActiveMipmapLevel().');
  35848. return this.getActiveMipmapLevel();
  35849. }
  35850. });
  35851. Object.defineProperties(WebGLRenderer.prototype, {
  35852. shadowMapEnabled: {
  35853. get: function get() {
  35854. return this.shadowMap.enabled;
  35855. },
  35856. set: function set(value) {
  35857. console.warn('THREE.WebGLRenderer: .shadowMapEnabled is now .shadowMap.enabled.');
  35858. this.shadowMap.enabled = value;
  35859. }
  35860. },
  35861. shadowMapType: {
  35862. get: function get() {
  35863. return this.shadowMap.type;
  35864. },
  35865. set: function set(value) {
  35866. console.warn('THREE.WebGLRenderer: .shadowMapType is now .shadowMap.type.');
  35867. this.shadowMap.type = value;
  35868. }
  35869. },
  35870. shadowMapCullFace: {
  35871. get: function get() {
  35872. console.warn('THREE.WebGLRenderer: .shadowMapCullFace has been removed. Set Material.shadowSide instead.');
  35873. return undefined;
  35874. },
  35875. set: function set()
  35876. /* value */
  35877. {
  35878. console.warn('THREE.WebGLRenderer: .shadowMapCullFace has been removed. Set Material.shadowSide instead.');
  35879. }
  35880. },
  35881. context: {
  35882. get: function get() {
  35883. console.warn('THREE.WebGLRenderer: .context has been removed. Use .getContext() instead.');
  35884. return this.getContext();
  35885. }
  35886. },
  35887. vr: {
  35888. get: function get() {
  35889. console.warn('THREE.WebGLRenderer: .vr has been renamed to .xr');
  35890. return this.xr;
  35891. }
  35892. },
  35893. gammaInput: {
  35894. get: function get() {
  35895. console.warn('THREE.WebGLRenderer: .gammaInput has been removed. Set the encoding for textures via Texture.encoding instead.');
  35896. return false;
  35897. },
  35898. set: function set() {
  35899. console.warn('THREE.WebGLRenderer: .gammaInput has been removed. Set the encoding for textures via Texture.encoding instead.');
  35900. }
  35901. },
  35902. gammaOutput: {
  35903. get: function get() {
  35904. console.warn('THREE.WebGLRenderer: .gammaOutput has been removed. Set WebGLRenderer.outputEncoding instead.');
  35905. return false;
  35906. },
  35907. set: function set(value) {
  35908. console.warn('THREE.WebGLRenderer: .gammaOutput has been removed. Set WebGLRenderer.outputEncoding instead.');
  35909. this.outputEncoding = value === true ? sRGBEncoding : LinearEncoding;
  35910. }
  35911. },
  35912. toneMappingWhitePoint: {
  35913. get: function get() {
  35914. console.warn('THREE.WebGLRenderer: .toneMappingWhitePoint has been removed.');
  35915. return 1.0;
  35916. },
  35917. set: function set() {
  35918. console.warn('THREE.WebGLRenderer: .toneMappingWhitePoint has been removed.');
  35919. }
  35920. }
  35921. });
  35922. Object.defineProperties(WebGLShadowMap.prototype, {
  35923. cullFace: {
  35924. get: function get() {
  35925. console.warn('THREE.WebGLRenderer: .shadowMap.cullFace has been removed. Set Material.shadowSide instead.');
  35926. return undefined;
  35927. },
  35928. set: function set()
  35929. /* cullFace */
  35930. {
  35931. console.warn('THREE.WebGLRenderer: .shadowMap.cullFace has been removed. Set Material.shadowSide instead.');
  35932. }
  35933. },
  35934. renderReverseSided: {
  35935. get: function get() {
  35936. console.warn('THREE.WebGLRenderer: .shadowMap.renderReverseSided has been removed. Set Material.shadowSide instead.');
  35937. return undefined;
  35938. },
  35939. set: function set() {
  35940. console.warn('THREE.WebGLRenderer: .shadowMap.renderReverseSided has been removed. Set Material.shadowSide instead.');
  35941. }
  35942. },
  35943. renderSingleSided: {
  35944. get: function get() {
  35945. console.warn('THREE.WebGLRenderer: .shadowMap.renderSingleSided has been removed. Set Material.shadowSide instead.');
  35946. return undefined;
  35947. },
  35948. set: function set() {
  35949. console.warn('THREE.WebGLRenderer: .shadowMap.renderSingleSided has been removed. Set Material.shadowSide instead.');
  35950. }
  35951. }
  35952. });
  35953. function WebGLRenderTargetCube(width, height, options) {
  35954. console.warn('THREE.WebGLRenderTargetCube( width, height, options ) is now WebGLCubeRenderTarget( size, options ).');
  35955. return new WebGLCubeRenderTarget(width, options);
  35956. } //
  35957. Object.defineProperties(WebGLRenderTarget.prototype, {
  35958. wrapS: {
  35959. get: function get() {
  35960. console.warn('THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.');
  35961. return this.texture.wrapS;
  35962. },
  35963. set: function set(value) {
  35964. console.warn('THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.');
  35965. this.texture.wrapS = value;
  35966. }
  35967. },
  35968. wrapT: {
  35969. get: function get() {
  35970. console.warn('THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.');
  35971. return this.texture.wrapT;
  35972. },
  35973. set: function set(value) {
  35974. console.warn('THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.');
  35975. this.texture.wrapT = value;
  35976. }
  35977. },
  35978. magFilter: {
  35979. get: function get() {
  35980. console.warn('THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.');
  35981. return this.texture.magFilter;
  35982. },
  35983. set: function set(value) {
  35984. console.warn('THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.');
  35985. this.texture.magFilter = value;
  35986. }
  35987. },
  35988. minFilter: {
  35989. get: function get() {
  35990. console.warn('THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.');
  35991. return this.texture.minFilter;
  35992. },
  35993. set: function set(value) {
  35994. console.warn('THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.');
  35995. this.texture.minFilter = value;
  35996. }
  35997. },
  35998. anisotropy: {
  35999. get: function get() {
  36000. console.warn('THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.');
  36001. return this.texture.anisotropy;
  36002. },
  36003. set: function set(value) {
  36004. console.warn('THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.');
  36005. this.texture.anisotropy = value;
  36006. }
  36007. },
  36008. offset: {
  36009. get: function get() {
  36010. console.warn('THREE.WebGLRenderTarget: .offset is now .texture.offset.');
  36011. return this.texture.offset;
  36012. },
  36013. set: function set(value) {
  36014. console.warn('THREE.WebGLRenderTarget: .offset is now .texture.offset.');
  36015. this.texture.offset = value;
  36016. }
  36017. },
  36018. repeat: {
  36019. get: function get() {
  36020. console.warn('THREE.WebGLRenderTarget: .repeat is now .texture.repeat.');
  36021. return this.texture.repeat;
  36022. },
  36023. set: function set(value) {
  36024. console.warn('THREE.WebGLRenderTarget: .repeat is now .texture.repeat.');
  36025. this.texture.repeat = value;
  36026. }
  36027. },
  36028. format: {
  36029. get: function get() {
  36030. console.warn('THREE.WebGLRenderTarget: .format is now .texture.format.');
  36031. return this.texture.format;
  36032. },
  36033. set: function set(value) {
  36034. console.warn('THREE.WebGLRenderTarget: .format is now .texture.format.');
  36035. this.texture.format = value;
  36036. }
  36037. },
  36038. type: {
  36039. get: function get() {
  36040. console.warn('THREE.WebGLRenderTarget: .type is now .texture.type.');
  36041. return this.texture.type;
  36042. },
  36043. set: function set(value) {
  36044. console.warn('THREE.WebGLRenderTarget: .type is now .texture.type.');
  36045. this.texture.type = value;
  36046. }
  36047. },
  36048. generateMipmaps: {
  36049. get: function get() {
  36050. console.warn('THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.');
  36051. return this.texture.generateMipmaps;
  36052. },
  36053. set: function set(value) {
  36054. console.warn('THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.');
  36055. this.texture.generateMipmaps = value;
  36056. }
  36057. }
  36058. }); //
  36059. Object.defineProperties(Audio.prototype, {
  36060. load: {
  36061. value: function value(file) {
  36062. console.warn('THREE.Audio: .load has been deprecated. Use THREE.AudioLoader instead.');
  36063. var scope = this;
  36064. var audioLoader = new AudioLoader();
  36065. audioLoader.load(file, function (buffer) {
  36066. scope.setBuffer(buffer);
  36067. });
  36068. return this;
  36069. }
  36070. },
  36071. startTime: {
  36072. set: function set() {
  36073. console.warn('THREE.Audio: .startTime is now .play( delay ).');
  36074. }
  36075. }
  36076. });
  36077. AudioAnalyser.prototype.getData = function () {
  36078. console.warn('THREE.AudioAnalyser: .getData() is now .getFrequencyData().');
  36079. return this.getFrequencyData();
  36080. }; //
  36081. CubeCamera.prototype.updateCubeMap = function (renderer, scene) {
  36082. console.warn('THREE.CubeCamera: .updateCubeMap() is now .update().');
  36083. return this.update(renderer, scene);
  36084. };
  36085. CubeCamera.prototype.clear = function (renderer, color, depth, stencil) {
  36086. console.warn('THREE.CubeCamera: .clear() is now .renderTarget.clear().');
  36087. return this.renderTarget.clear(renderer, color, depth, stencil);
  36088. }; //
  36089. var GeometryUtils = {
  36090. merge: function merge(geometry1, geometry2, materialIndexOffset) {
  36091. console.warn('THREE.GeometryUtils: .merge() has been moved to Geometry. Use geometry.merge( geometry2, matrix, materialIndexOffset ) instead.');
  36092. var matrix;
  36093. if (geometry2.isMesh) {
  36094. geometry2.matrixAutoUpdate && geometry2.updateMatrix();
  36095. matrix = geometry2.matrix;
  36096. geometry2 = geometry2.geometry;
  36097. }
  36098. geometry1.merge(geometry2, matrix, materialIndexOffset);
  36099. },
  36100. center: function center(geometry) {
  36101. console.warn('THREE.GeometryUtils: .center() has been moved to Geometry. Use geometry.center() instead.');
  36102. return geometry.center();
  36103. }
  36104. };
  36105. ImageUtils.crossOrigin = undefined;
  36106. ImageUtils.loadTexture = function (url, mapping, onLoad, onError) {
  36107. console.warn('THREE.ImageUtils.loadTexture has been deprecated. Use THREE.TextureLoader() instead.');
  36108. var loader = new TextureLoader();
  36109. loader.setCrossOrigin(this.crossOrigin);
  36110. var texture = loader.load(url, onLoad, undefined, onError);
  36111. if (mapping) texture.mapping = mapping;
  36112. return texture;
  36113. };
  36114. ImageUtils.loadTextureCube = function (urls, mapping, onLoad, onError) {
  36115. console.warn('THREE.ImageUtils.loadTextureCube has been deprecated. Use THREE.CubeTextureLoader() instead.');
  36116. var loader = new CubeTextureLoader();
  36117. loader.setCrossOrigin(this.crossOrigin);
  36118. var texture = loader.load(urls, onLoad, undefined, onError);
  36119. if (mapping) texture.mapping = mapping;
  36120. return texture;
  36121. };
  36122. ImageUtils.loadCompressedTexture = function () {
  36123. console.error('THREE.ImageUtils.loadCompressedTexture has been removed. Use THREE.DDSLoader instead.');
  36124. };
  36125. ImageUtils.loadCompressedTextureCube = function () {
  36126. console.error('THREE.ImageUtils.loadCompressedTextureCube has been removed. Use THREE.DDSLoader instead.');
  36127. }; //
  36128. function CanvasRenderer() {
  36129. console.error('THREE.CanvasRenderer has been removed');
  36130. } //
  36131. function JSONLoader() {
  36132. console.error('THREE.JSONLoader has been removed.');
  36133. } //
  36134. var SceneUtils = {
  36135. createMultiMaterialObject: function createMultiMaterialObject()
  36136. /* geometry, materials */
  36137. {
  36138. console.error('THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js');
  36139. },
  36140. detach: function detach()
  36141. /* child, parent, scene */
  36142. {
  36143. console.error('THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js');
  36144. },
  36145. attach: function attach()
  36146. /* child, scene, parent */
  36147. {
  36148. console.error('THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js');
  36149. }
  36150. }; //
  36151. function LensFlare() {
  36152. console.error('THREE.LensFlare has been moved to /examples/jsm/objects/Lensflare.js');
  36153. }
  36154. if (typeof __THREE_DEVTOOLS__ !== 'undefined') {
  36155. /* eslint-disable no-undef */
  36156. __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent('register', {
  36157. detail: {
  36158. revision: REVISION
  36159. }
  36160. }));
  36161. /* eslint-enable no-undef */
  36162. }
  36163. if (typeof window !== 'undefined') {
  36164. if (window.__THREE__) {
  36165. console.warn('WARNING: Multiple instances of Three.js being imported.');
  36166. } else {
  36167. window.__THREE__ = REVISION;
  36168. }
  36169. }
  36170. exports.ACESFilmicToneMapping = ACESFilmicToneMapping;
  36171. exports.AddEquation = AddEquation;
  36172. exports.AddOperation = AddOperation;
  36173. exports.AdditiveAnimationBlendMode = AdditiveAnimationBlendMode;
  36174. exports.AdditiveBlending = AdditiveBlending;
  36175. exports.AlphaFormat = AlphaFormat;
  36176. exports.AlwaysDepth = AlwaysDepth;
  36177. exports.AlwaysStencilFunc = AlwaysStencilFunc;
  36178. exports.AmbientLight = AmbientLight;
  36179. exports.AmbientLightProbe = AmbientLightProbe;
  36180. exports.AnimationClip = AnimationClip;
  36181. exports.AnimationLoader = AnimationLoader;
  36182. exports.AnimationMixer = AnimationMixer;
  36183. exports.AnimationObjectGroup = AnimationObjectGroup;
  36184. exports.AnimationUtils = AnimationUtils;
  36185. exports.ArcCurve = ArcCurve;
  36186. exports.ArrayCamera = ArrayCamera;
  36187. exports.ArrowHelper = ArrowHelper;
  36188. exports.Audio = Audio;
  36189. exports.AudioAnalyser = AudioAnalyser;
  36190. exports.AudioContext = AudioContext;
  36191. exports.AudioListener = AudioListener;
  36192. exports.AudioLoader = AudioLoader;
  36193. exports.AxesHelper = AxesHelper;
  36194. exports.AxisHelper = AxisHelper;
  36195. exports.BackSide = BackSide;
  36196. exports.BasicDepthPacking = BasicDepthPacking;
  36197. exports.BasicShadowMap = BasicShadowMap;
  36198. exports.BinaryTextureLoader = BinaryTextureLoader;
  36199. exports.Bone = Bone;
  36200. exports.BooleanKeyframeTrack = BooleanKeyframeTrack;
  36201. exports.BoundingBoxHelper = BoundingBoxHelper;
  36202. exports.Box2 = Box2;
  36203. exports.Box3 = Box3;
  36204. exports.Box3Helper = Box3Helper;
  36205. exports.BoxBufferGeometry = BoxGeometry;
  36206. exports.BoxGeometry = BoxGeometry;
  36207. exports.BoxHelper = BoxHelper;
  36208. exports.BufferAttribute = BufferAttribute;
  36209. exports.BufferGeometry = BufferGeometry;
  36210. exports.BufferGeometryLoader = BufferGeometryLoader;
  36211. exports.ByteType = ByteType;
  36212. exports.Cache = Cache;
  36213. exports.Camera = Camera;
  36214. exports.CameraHelper = CameraHelper;
  36215. exports.CanvasRenderer = CanvasRenderer;
  36216. exports.CanvasTexture = CanvasTexture;
  36217. exports.CatmullRomCurve3 = CatmullRomCurve3;
  36218. exports.CineonToneMapping = CineonToneMapping;
  36219. exports.CircleBufferGeometry = CircleGeometry;
  36220. exports.CircleGeometry = CircleGeometry;
  36221. exports.ClampToEdgeWrapping = ClampToEdgeWrapping;
  36222. exports.Clock = Clock;
  36223. exports.ClosedSplineCurve3 = ClosedSplineCurve3;
  36224. exports.Color = Color;
  36225. exports.ColorKeyframeTrack = ColorKeyframeTrack;
  36226. exports.CompressedTexture = CompressedTexture;
  36227. exports.CompressedTextureLoader = CompressedTextureLoader;
  36228. exports.ConeBufferGeometry = ConeGeometry;
  36229. exports.ConeGeometry = ConeGeometry;
  36230. exports.CubeCamera = CubeCamera;
  36231. exports.CubeReflectionMapping = CubeReflectionMapping;
  36232. exports.CubeRefractionMapping = CubeRefractionMapping;
  36233. exports.CubeTexture = CubeTexture;
  36234. exports.CubeTextureLoader = CubeTextureLoader;
  36235. exports.CubeUVReflectionMapping = CubeUVReflectionMapping;
  36236. exports.CubeUVRefractionMapping = CubeUVRefractionMapping;
  36237. exports.CubicBezierCurve = CubicBezierCurve;
  36238. exports.CubicBezierCurve3 = CubicBezierCurve3;
  36239. exports.CubicInterpolant = CubicInterpolant;
  36240. exports.CullFaceBack = CullFaceBack;
  36241. exports.CullFaceFront = CullFaceFront;
  36242. exports.CullFaceFrontBack = CullFaceFrontBack;
  36243. exports.CullFaceNone = CullFaceNone;
  36244. exports.Curve = Curve;
  36245. exports.CurvePath = CurvePath;
  36246. exports.CustomBlending = CustomBlending;
  36247. exports.CustomToneMapping = CustomToneMapping;
  36248. exports.CylinderBufferGeometry = CylinderGeometry;
  36249. exports.CylinderGeometry = CylinderGeometry;
  36250. exports.Cylindrical = Cylindrical;
  36251. exports.DataTexture = DataTexture;
  36252. exports.DataTexture2DArray = DataTexture2DArray;
  36253. exports.DataTexture3D = DataTexture3D;
  36254. exports.DataTextureLoader = DataTextureLoader;
  36255. exports.DataUtils = DataUtils;
  36256. exports.DecrementStencilOp = DecrementStencilOp;
  36257. exports.DecrementWrapStencilOp = DecrementWrapStencilOp;
  36258. exports.DefaultLoadingManager = DefaultLoadingManager;
  36259. exports.DepthFormat = DepthFormat;
  36260. exports.DepthStencilFormat = DepthStencilFormat;
  36261. exports.DepthTexture = DepthTexture;
  36262. exports.DirectionalLight = DirectionalLight;
  36263. exports.DirectionalLightHelper = DirectionalLightHelper;
  36264. exports.DiscreteInterpolant = DiscreteInterpolant;
  36265. exports.DodecahedronBufferGeometry = DodecahedronGeometry;
  36266. exports.DodecahedronGeometry = DodecahedronGeometry;
  36267. exports.DoubleSide = DoubleSide;
  36268. exports.DstAlphaFactor = DstAlphaFactor;
  36269. exports.DstColorFactor = DstColorFactor;
  36270. exports.DynamicBufferAttribute = DynamicBufferAttribute;
  36271. exports.DynamicCopyUsage = DynamicCopyUsage;
  36272. exports.DynamicDrawUsage = DynamicDrawUsage;
  36273. exports.DynamicReadUsage = DynamicReadUsage;
  36274. exports.EdgesGeometry = EdgesGeometry;
  36275. exports.EdgesHelper = EdgesHelper;
  36276. exports.EllipseCurve = EllipseCurve;
  36277. exports.EqualDepth = EqualDepth;
  36278. exports.EqualStencilFunc = EqualStencilFunc;
  36279. exports.EquirectangularReflectionMapping = EquirectangularReflectionMapping;
  36280. exports.EquirectangularRefractionMapping = EquirectangularRefractionMapping;
  36281. exports.Euler = Euler;
  36282. exports.EventDispatcher = EventDispatcher;
  36283. exports.ExtrudeBufferGeometry = ExtrudeGeometry;
  36284. exports.ExtrudeGeometry = ExtrudeGeometry;
  36285. exports.Face3 = Face3;
  36286. exports.Face4 = Face4;
  36287. exports.FaceColors = FaceColors;
  36288. exports.FileLoader = FileLoader;
  36289. exports.FlatShading = FlatShading;
  36290. exports.Float16BufferAttribute = Float16BufferAttribute;
  36291. exports.Float32Attribute = Float32Attribute;
  36292. exports.Float32BufferAttribute = Float32BufferAttribute;
  36293. exports.Float64Attribute = Float64Attribute;
  36294. exports.Float64BufferAttribute = Float64BufferAttribute;
  36295. exports.FloatType = FloatType;
  36296. exports.Fog = Fog;
  36297. exports.FogExp2 = FogExp2;
  36298. exports.Font = Font;
  36299. exports.FontLoader = FontLoader;
  36300. exports.FrontSide = FrontSide;
  36301. exports.Frustum = Frustum;
  36302. exports.GLBufferAttribute = GLBufferAttribute;
  36303. exports.GLSL1 = GLSL1;
  36304. exports.GLSL3 = GLSL3;
  36305. exports.GammaEncoding = GammaEncoding;
  36306. exports.GeometryUtils = GeometryUtils;
  36307. exports.GreaterDepth = GreaterDepth;
  36308. exports.GreaterEqualDepth = GreaterEqualDepth;
  36309. exports.GreaterEqualStencilFunc = GreaterEqualStencilFunc;
  36310. exports.GreaterStencilFunc = GreaterStencilFunc;
  36311. exports.GridHelper = GridHelper;
  36312. exports.Group = Group;
  36313. exports.HalfFloatType = HalfFloatType;
  36314. exports.HemisphereLight = HemisphereLight;
  36315. exports.HemisphereLightHelper = HemisphereLightHelper;
  36316. exports.HemisphereLightProbe = HemisphereLightProbe;
  36317. exports.IcosahedronBufferGeometry = IcosahedronGeometry;
  36318. exports.IcosahedronGeometry = IcosahedronGeometry;
  36319. exports.ImageBitmapLoader = ImageBitmapLoader;
  36320. exports.ImageLoader = ImageLoader;
  36321. exports.ImageUtils = ImageUtils;
  36322. exports.ImmediateRenderObject = ImmediateRenderObject;
  36323. exports.IncrementStencilOp = IncrementStencilOp;
  36324. exports.IncrementWrapStencilOp = IncrementWrapStencilOp;
  36325. exports.InstancedBufferAttribute = InstancedBufferAttribute;
  36326. exports.InstancedBufferGeometry = InstancedBufferGeometry;
  36327. exports.InstancedInterleavedBuffer = InstancedInterleavedBuffer;
  36328. exports.InstancedMesh = InstancedMesh;
  36329. exports.Int16Attribute = Int16Attribute;
  36330. exports.Int16BufferAttribute = Int16BufferAttribute;
  36331. exports.Int32Attribute = Int32Attribute;
  36332. exports.Int32BufferAttribute = Int32BufferAttribute;
  36333. exports.Int8Attribute = Int8Attribute;
  36334. exports.Int8BufferAttribute = Int8BufferAttribute;
  36335. exports.IntType = IntType;
  36336. exports.InterleavedBuffer = InterleavedBuffer;
  36337. exports.InterleavedBufferAttribute = InterleavedBufferAttribute;
  36338. exports.Interpolant = Interpolant;
  36339. exports.InterpolateDiscrete = InterpolateDiscrete;
  36340. exports.InterpolateLinear = InterpolateLinear;
  36341. exports.InterpolateSmooth = InterpolateSmooth;
  36342. exports.InvertStencilOp = InvertStencilOp;
  36343. exports.JSONLoader = JSONLoader;
  36344. exports.KeepStencilOp = KeepStencilOp;
  36345. exports.KeyframeTrack = KeyframeTrack;
  36346. exports.LOD = LOD;
  36347. exports.LatheBufferGeometry = LatheGeometry;
  36348. exports.LatheGeometry = LatheGeometry;
  36349. exports.Layers = Layers;
  36350. exports.LensFlare = LensFlare;
  36351. exports.LessDepth = LessDepth;
  36352. exports.LessEqualDepth = LessEqualDepth;
  36353. exports.LessEqualStencilFunc = LessEqualStencilFunc;
  36354. exports.LessStencilFunc = LessStencilFunc;
  36355. exports.Light = Light;
  36356. exports.LightProbe = LightProbe;
  36357. exports.Line = Line;
  36358. exports.Line3 = Line3;
  36359. exports.LineBasicMaterial = LineBasicMaterial;
  36360. exports.LineCurve = LineCurve;
  36361. exports.LineCurve3 = LineCurve3;
  36362. exports.LineDashedMaterial = LineDashedMaterial;
  36363. exports.LineLoop = LineLoop;
  36364. exports.LinePieces = LinePieces;
  36365. exports.LineSegments = LineSegments;
  36366. exports.LineStrip = LineStrip;
  36367. exports.LinearEncoding = LinearEncoding;
  36368. exports.LinearFilter = LinearFilter;
  36369. exports.LinearInterpolant = LinearInterpolant;
  36370. exports.LinearMipMapLinearFilter = LinearMipMapLinearFilter;
  36371. exports.LinearMipMapNearestFilter = LinearMipMapNearestFilter;
  36372. exports.LinearMipmapLinearFilter = LinearMipmapLinearFilter;
  36373. exports.LinearMipmapNearestFilter = LinearMipmapNearestFilter;
  36374. exports.LinearToneMapping = LinearToneMapping;
  36375. exports.Loader = Loader;
  36376. exports.LoaderUtils = LoaderUtils;
  36377. exports.LoadingManager = LoadingManager;
  36378. exports.LogLuvEncoding = LogLuvEncoding;
  36379. exports.LoopOnce = LoopOnce;
  36380. exports.LoopPingPong = LoopPingPong;
  36381. exports.LoopRepeat = LoopRepeat;
  36382. exports.LuminanceAlphaFormat = LuminanceAlphaFormat;
  36383. exports.LuminanceFormat = LuminanceFormat;
  36384. exports.MOUSE = MOUSE;
  36385. exports.Material = Material;
  36386. exports.MaterialLoader = MaterialLoader;
  36387. exports.Math = MathUtils;
  36388. exports.MathUtils = MathUtils;
  36389. exports.Matrix3 = Matrix3;
  36390. exports.Matrix4 = Matrix4;
  36391. exports.MaxEquation = MaxEquation;
  36392. exports.Mesh = Mesh;
  36393. exports.MeshBasicMaterial = MeshBasicMaterial;
  36394. exports.MeshDepthMaterial = MeshDepthMaterial;
  36395. exports.MeshDistanceMaterial = MeshDistanceMaterial;
  36396. exports.MeshFaceMaterial = MeshFaceMaterial;
  36397. exports.MeshLambertMaterial = MeshLambertMaterial;
  36398. exports.MeshMatcapMaterial = MeshMatcapMaterial;
  36399. exports.MeshNormalMaterial = MeshNormalMaterial;
  36400. exports.MeshPhongMaterial = MeshPhongMaterial;
  36401. exports.MeshPhysicalMaterial = MeshPhysicalMaterial;
  36402. exports.MeshStandardMaterial = MeshStandardMaterial;
  36403. exports.MeshToonMaterial = MeshToonMaterial;
  36404. exports.MinEquation = MinEquation;
  36405. exports.MirroredRepeatWrapping = MirroredRepeatWrapping;
  36406. exports.MixOperation = MixOperation;
  36407. exports.MultiMaterial = MultiMaterial;
  36408. exports.MultiplyBlending = MultiplyBlending;
  36409. exports.MultiplyOperation = MultiplyOperation;
  36410. exports.NearestFilter = NearestFilter;
  36411. exports.NearestMipMapLinearFilter = NearestMipMapLinearFilter;
  36412. exports.NearestMipMapNearestFilter = NearestMipMapNearestFilter;
  36413. exports.NearestMipmapLinearFilter = NearestMipmapLinearFilter;
  36414. exports.NearestMipmapNearestFilter = NearestMipmapNearestFilter;
  36415. exports.NeverDepth = NeverDepth;
  36416. exports.NeverStencilFunc = NeverStencilFunc;
  36417. exports.NoBlending = NoBlending;
  36418. exports.NoColors = NoColors;
  36419. exports.NoToneMapping = NoToneMapping;
  36420. exports.NormalAnimationBlendMode = NormalAnimationBlendMode;
  36421. exports.NormalBlending = NormalBlending;
  36422. exports.NotEqualDepth = NotEqualDepth;
  36423. exports.NotEqualStencilFunc = NotEqualStencilFunc;
  36424. exports.NumberKeyframeTrack = NumberKeyframeTrack;
  36425. exports.Object3D = Object3D;
  36426. exports.ObjectLoader = ObjectLoader;
  36427. exports.ObjectSpaceNormalMap = ObjectSpaceNormalMap;
  36428. exports.OctahedronBufferGeometry = OctahedronGeometry;
  36429. exports.OctahedronGeometry = OctahedronGeometry;
  36430. exports.OneFactor = OneFactor;
  36431. exports.OneMinusDstAlphaFactor = OneMinusDstAlphaFactor;
  36432. exports.OneMinusDstColorFactor = OneMinusDstColorFactor;
  36433. exports.OneMinusSrcAlphaFactor = OneMinusSrcAlphaFactor;
  36434. exports.OneMinusSrcColorFactor = OneMinusSrcColorFactor;
  36435. exports.OrthographicCamera = OrthographicCamera;
  36436. exports.PCFShadowMap = PCFShadowMap;
  36437. exports.PCFSoftShadowMap = PCFSoftShadowMap;
  36438. exports.PMREMGenerator = PMREMGenerator;
  36439. exports.ParametricBufferGeometry = ParametricGeometry;
  36440. exports.ParametricGeometry = ParametricGeometry;
  36441. exports.Particle = Particle;
  36442. exports.ParticleBasicMaterial = ParticleBasicMaterial;
  36443. exports.ParticleSystem = ParticleSystem;
  36444. exports.ParticleSystemMaterial = ParticleSystemMaterial;
  36445. exports.Path = Path;
  36446. exports.PerspectiveCamera = PerspectiveCamera;
  36447. exports.Plane = Plane;
  36448. exports.PlaneBufferGeometry = PlaneGeometry;
  36449. exports.PlaneGeometry = PlaneGeometry;
  36450. exports.PlaneHelper = PlaneHelper;
  36451. exports.PointCloud = PointCloud;
  36452. exports.PointCloudMaterial = PointCloudMaterial;
  36453. exports.PointLight = PointLight;
  36454. exports.PointLightHelper = PointLightHelper;
  36455. exports.Points = Points;
  36456. exports.PointsMaterial = PointsMaterial;
  36457. exports.PolarGridHelper = PolarGridHelper;
  36458. exports.PolyhedronBufferGeometry = PolyhedronGeometry;
  36459. exports.PolyhedronGeometry = PolyhedronGeometry;
  36460. exports.PositionalAudio = PositionalAudio;
  36461. exports.PropertyBinding = PropertyBinding;
  36462. exports.PropertyMixer = PropertyMixer;
  36463. exports.QuadraticBezierCurve = QuadraticBezierCurve;
  36464. exports.QuadraticBezierCurve3 = QuadraticBezierCurve3;
  36465. exports.Quaternion = Quaternion;
  36466. exports.QuaternionKeyframeTrack = QuaternionKeyframeTrack;
  36467. exports.QuaternionLinearInterpolant = QuaternionLinearInterpolant;
  36468. exports.REVISION = REVISION;
  36469. exports.RGBADepthPacking = RGBADepthPacking;
  36470. exports.RGBAFormat = RGBAFormat;
  36471. exports.RGBAIntegerFormat = RGBAIntegerFormat;
  36472. exports.RGBA_ASTC_10x10_Format = RGBA_ASTC_10x10_Format;
  36473. exports.RGBA_ASTC_10x5_Format = RGBA_ASTC_10x5_Format;
  36474. exports.RGBA_ASTC_10x6_Format = RGBA_ASTC_10x6_Format;
  36475. exports.RGBA_ASTC_10x8_Format = RGBA_ASTC_10x8_Format;
  36476. exports.RGBA_ASTC_12x10_Format = RGBA_ASTC_12x10_Format;
  36477. exports.RGBA_ASTC_12x12_Format = RGBA_ASTC_12x12_Format;
  36478. exports.RGBA_ASTC_4x4_Format = RGBA_ASTC_4x4_Format;
  36479. exports.RGBA_ASTC_5x4_Format = RGBA_ASTC_5x4_Format;
  36480. exports.RGBA_ASTC_5x5_Format = RGBA_ASTC_5x5_Format;
  36481. exports.RGBA_ASTC_6x5_Format = RGBA_ASTC_6x5_Format;
  36482. exports.RGBA_ASTC_6x6_Format = RGBA_ASTC_6x6_Format;
  36483. exports.RGBA_ASTC_8x5_Format = RGBA_ASTC_8x5_Format;
  36484. exports.RGBA_ASTC_8x6_Format = RGBA_ASTC_8x6_Format;
  36485. exports.RGBA_ASTC_8x8_Format = RGBA_ASTC_8x8_Format;
  36486. exports.RGBA_BPTC_Format = RGBA_BPTC_Format;
  36487. exports.RGBA_ETC2_EAC_Format = RGBA_ETC2_EAC_Format;
  36488. exports.RGBA_PVRTC_2BPPV1_Format = RGBA_PVRTC_2BPPV1_Format;
  36489. exports.RGBA_PVRTC_4BPPV1_Format = RGBA_PVRTC_4BPPV1_Format;
  36490. exports.RGBA_S3TC_DXT1_Format = RGBA_S3TC_DXT1_Format;
  36491. exports.RGBA_S3TC_DXT3_Format = RGBA_S3TC_DXT3_Format;
  36492. exports.RGBA_S3TC_DXT5_Format = RGBA_S3TC_DXT5_Format;
  36493. exports.RGBDEncoding = RGBDEncoding;
  36494. exports.RGBEEncoding = RGBEEncoding;
  36495. exports.RGBEFormat = RGBEFormat;
  36496. exports.RGBFormat = RGBFormat;
  36497. exports.RGBIntegerFormat = RGBIntegerFormat;
  36498. exports.RGBM16Encoding = RGBM16Encoding;
  36499. exports.RGBM7Encoding = RGBM7Encoding;
  36500. exports.RGB_ETC1_Format = RGB_ETC1_Format;
  36501. exports.RGB_ETC2_Format = RGB_ETC2_Format;
  36502. exports.RGB_PVRTC_2BPPV1_Format = RGB_PVRTC_2BPPV1_Format;
  36503. exports.RGB_PVRTC_4BPPV1_Format = RGB_PVRTC_4BPPV1_Format;
  36504. exports.RGB_S3TC_DXT1_Format = RGB_S3TC_DXT1_Format;
  36505. exports.RGFormat = RGFormat;
  36506. exports.RGIntegerFormat = RGIntegerFormat;
  36507. exports.RawShaderMaterial = RawShaderMaterial;
  36508. exports.Ray = Ray;
  36509. exports.Raycaster = Raycaster;
  36510. exports.RectAreaLight = RectAreaLight;
  36511. exports.RedFormat = RedFormat;
  36512. exports.RedIntegerFormat = RedIntegerFormat;
  36513. exports.ReinhardToneMapping = ReinhardToneMapping;
  36514. exports.RepeatWrapping = RepeatWrapping;
  36515. exports.ReplaceStencilOp = ReplaceStencilOp;
  36516. exports.ReverseSubtractEquation = ReverseSubtractEquation;
  36517. exports.RingBufferGeometry = RingGeometry;
  36518. exports.RingGeometry = RingGeometry;
  36519. exports.SRGB8_ALPHA8_ASTC_10x10_Format = SRGB8_ALPHA8_ASTC_10x10_Format;
  36520. exports.SRGB8_ALPHA8_ASTC_10x5_Format = SRGB8_ALPHA8_ASTC_10x5_Format;
  36521. exports.SRGB8_ALPHA8_ASTC_10x6_Format = SRGB8_ALPHA8_ASTC_10x6_Format;
  36522. exports.SRGB8_ALPHA8_ASTC_10x8_Format = SRGB8_ALPHA8_ASTC_10x8_Format;
  36523. exports.SRGB8_ALPHA8_ASTC_12x10_Format = SRGB8_ALPHA8_ASTC_12x10_Format;
  36524. exports.SRGB8_ALPHA8_ASTC_12x12_Format = SRGB8_ALPHA8_ASTC_12x12_Format;
  36525. exports.SRGB8_ALPHA8_ASTC_4x4_Format = SRGB8_ALPHA8_ASTC_4x4_Format;
  36526. exports.SRGB8_ALPHA8_ASTC_5x4_Format = SRGB8_ALPHA8_ASTC_5x4_Format;
  36527. exports.SRGB8_ALPHA8_ASTC_5x5_Format = SRGB8_ALPHA8_ASTC_5x5_Format;
  36528. exports.SRGB8_ALPHA8_ASTC_6x5_Format = SRGB8_ALPHA8_ASTC_6x5_Format;
  36529. exports.SRGB8_ALPHA8_ASTC_6x6_Format = SRGB8_ALPHA8_ASTC_6x6_Format;
  36530. exports.SRGB8_ALPHA8_ASTC_8x5_Format = SRGB8_ALPHA8_ASTC_8x5_Format;
  36531. exports.SRGB8_ALPHA8_ASTC_8x6_Format = SRGB8_ALPHA8_ASTC_8x6_Format;
  36532. exports.SRGB8_ALPHA8_ASTC_8x8_Format = SRGB8_ALPHA8_ASTC_8x8_Format;
  36533. exports.Scene = Scene;
  36534. exports.SceneUtils = SceneUtils;
  36535. exports.ShaderChunk = ShaderChunk;
  36536. exports.ShaderLib = ShaderLib;
  36537. exports.ShaderMaterial = ShaderMaterial;
  36538. exports.ShadowMaterial = ShadowMaterial;
  36539. exports.Shape = Shape;
  36540. exports.ShapeBufferGeometry = ShapeGeometry;
  36541. exports.ShapeGeometry = ShapeGeometry;
  36542. exports.ShapePath = ShapePath;
  36543. exports.ShapeUtils = ShapeUtils;
  36544. exports.ShortType = ShortType;
  36545. exports.Skeleton = Skeleton;
  36546. exports.SkeletonHelper = SkeletonHelper;
  36547. exports.SkinnedMesh = SkinnedMesh;
  36548. exports.SmoothShading = SmoothShading;
  36549. exports.Sphere = Sphere;
  36550. exports.SphereBufferGeometry = SphereGeometry;
  36551. exports.SphereGeometry = SphereGeometry;
  36552. exports.Spherical = Spherical;
  36553. exports.SphericalHarmonics3 = SphericalHarmonics3;
  36554. exports.Spline = Spline;
  36555. exports.SplineCurve = SplineCurve;
  36556. exports.SplineCurve3 = SplineCurve3;
  36557. exports.SpotLight = SpotLight;
  36558. exports.SpotLightHelper = SpotLightHelper;
  36559. exports.Sprite = Sprite;
  36560. exports.SpriteMaterial = SpriteMaterial;
  36561. exports.SrcAlphaFactor = SrcAlphaFactor;
  36562. exports.SrcAlphaSaturateFactor = SrcAlphaSaturateFactor;
  36563. exports.SrcColorFactor = SrcColorFactor;
  36564. exports.StaticCopyUsage = StaticCopyUsage;
  36565. exports.StaticDrawUsage = StaticDrawUsage;
  36566. exports.StaticReadUsage = StaticReadUsage;
  36567. exports.StereoCamera = StereoCamera;
  36568. exports.StreamCopyUsage = StreamCopyUsage;
  36569. exports.StreamDrawUsage = StreamDrawUsage;
  36570. exports.StreamReadUsage = StreamReadUsage;
  36571. exports.StringKeyframeTrack = StringKeyframeTrack;
  36572. exports.SubtractEquation = SubtractEquation;
  36573. exports.SubtractiveBlending = SubtractiveBlending;
  36574. exports.TOUCH = TOUCH;
  36575. exports.TangentSpaceNormalMap = TangentSpaceNormalMap;
  36576. exports.TetrahedronBufferGeometry = TetrahedronGeometry;
  36577. exports.TetrahedronGeometry = TetrahedronGeometry;
  36578. exports.TextBufferGeometry = TextGeometry;
  36579. exports.TextGeometry = TextGeometry;
  36580. exports.Texture = Texture;
  36581. exports.TextureLoader = TextureLoader;
  36582. exports.TorusBufferGeometry = TorusGeometry;
  36583. exports.TorusGeometry = TorusGeometry;
  36584. exports.TorusKnotBufferGeometry = TorusKnotGeometry;
  36585. exports.TorusKnotGeometry = TorusKnotGeometry;
  36586. exports.Triangle = Triangle;
  36587. exports.TriangleFanDrawMode = TriangleFanDrawMode;
  36588. exports.TriangleStripDrawMode = TriangleStripDrawMode;
  36589. exports.TrianglesDrawMode = TrianglesDrawMode;
  36590. exports.TubeBufferGeometry = TubeGeometry;
  36591. exports.TubeGeometry = TubeGeometry;
  36592. exports.UVMapping = UVMapping;
  36593. exports.Uint16Attribute = Uint16Attribute;
  36594. exports.Uint16BufferAttribute = Uint16BufferAttribute;
  36595. exports.Uint32Attribute = Uint32Attribute;
  36596. exports.Uint32BufferAttribute = Uint32BufferAttribute;
  36597. exports.Uint8Attribute = Uint8Attribute;
  36598. exports.Uint8BufferAttribute = Uint8BufferAttribute;
  36599. exports.Uint8ClampedAttribute = Uint8ClampedAttribute;
  36600. exports.Uint8ClampedBufferAttribute = Uint8ClampedBufferAttribute;
  36601. exports.Uniform = Uniform;
  36602. exports.UniformsLib = UniformsLib;
  36603. exports.UniformsUtils = UniformsUtils;
  36604. exports.UnsignedByteType = UnsignedByteType;
  36605. exports.UnsignedInt248Type = UnsignedInt248Type;
  36606. exports.UnsignedIntType = UnsignedIntType;
  36607. exports.UnsignedShort4444Type = UnsignedShort4444Type;
  36608. exports.UnsignedShort5551Type = UnsignedShort5551Type;
  36609. exports.UnsignedShort565Type = UnsignedShort565Type;
  36610. exports.UnsignedShortType = UnsignedShortType;
  36611. exports.VSMShadowMap = VSMShadowMap;
  36612. exports.Vector2 = Vector2;
  36613. exports.Vector3 = Vector3;
  36614. exports.Vector4 = Vector4;
  36615. exports.VectorKeyframeTrack = VectorKeyframeTrack;
  36616. exports.Vertex = Vertex;
  36617. exports.VertexColors = VertexColors;
  36618. exports.VideoTexture = VideoTexture;
  36619. exports.WebGL1Renderer = WebGL1Renderer;
  36620. exports.WebGLCubeRenderTarget = WebGLCubeRenderTarget;
  36621. exports.WebGLMultisampleRenderTarget = WebGLMultisampleRenderTarget;
  36622. exports.WebGLRenderTarget = WebGLRenderTarget;
  36623. exports.WebGLRenderTargetCube = WebGLRenderTargetCube;
  36624. exports.WebGLRenderer = WebGLRenderer;
  36625. exports.WebGLUtils = WebGLUtils;
  36626. exports.WireframeGeometry = WireframeGeometry;
  36627. exports.WireframeHelper = WireframeHelper;
  36628. exports.WrapAroundEnding = WrapAroundEnding;
  36629. exports.XHRLoader = XHRLoader;
  36630. exports.ZeroCurvatureEnding = ZeroCurvatureEnding;
  36631. exports.ZeroFactor = ZeroFactor;
  36632. exports.ZeroSlopeEnding = ZeroSlopeEnding;
  36633. exports.ZeroStencilOp = ZeroStencilOp;
  36634. exports.sRGBEncoding = sRGBEncoding;
  36635. Object.defineProperty(exports, '__esModule', { value: true });
  36636. })));
  36637. },{}],58:[function(_dereq_,module,exports){
  36638. THREE.DRACOLoader = function ( manager ) {
  36639. THREE.Loader.call( this, manager );
  36640. this.decoderPath = '';
  36641. this.decoderConfig = {};
  36642. this.decoderBinary = null;
  36643. this.decoderPending = null;
  36644. this.workerLimit = 4;
  36645. this.workerPool = [];
  36646. this.workerNextTaskID = 1;
  36647. this.workerSourceURL = '';
  36648. this.defaultAttributeIDs = {
  36649. position: 'POSITION',
  36650. normal: 'NORMAL',
  36651. color: 'COLOR',
  36652. uv: 'TEX_COORD'
  36653. };
  36654. this.defaultAttributeTypes = {
  36655. position: 'Float32Array',
  36656. normal: 'Float32Array',
  36657. color: 'Float32Array',
  36658. uv: 'Float32Array'
  36659. };
  36660. };
  36661. THREE.DRACOLoader.prototype = Object.assign( Object.create( THREE.Loader.prototype ), {
  36662. constructor: THREE.DRACOLoader,
  36663. setDecoderPath: function ( path ) {
  36664. this.decoderPath = path;
  36665. return this;
  36666. },
  36667. setDecoderConfig: function ( config ) {
  36668. this.decoderConfig = config;
  36669. return this;
  36670. },
  36671. setWorkerLimit: function ( workerLimit ) {
  36672. this.workerLimit = workerLimit;
  36673. return this;
  36674. },
  36675. /** @deprecated */
  36676. setVerbosity: function () {
  36677. console.warn( 'THREE.DRACOLoader: The .setVerbosity() method has been removed.' );
  36678. },
  36679. /** @deprecated */
  36680. setDrawMode: function () {
  36681. console.warn( 'THREE.DRACOLoader: The .setDrawMode() method has been removed.' );
  36682. },
  36683. /** @deprecated */
  36684. setSkipDequantization: function () {
  36685. console.warn( 'THREE.DRACOLoader: The .setSkipDequantization() method has been removed.' );
  36686. },
  36687. load: function ( url, onLoad, onProgress, onError ) {
  36688. var loader = new THREE.FileLoader( this.manager );
  36689. loader.setPath( this.path );
  36690. loader.setResponseType( 'arraybuffer' );
  36691. loader.setRequestHeader( this.requestHeader );
  36692. loader.setWithCredentials( this.withCredentials );
  36693. loader.load( url, ( buffer ) => {
  36694. var taskConfig = {
  36695. attributeIDs: this.defaultAttributeIDs,
  36696. attributeTypes: this.defaultAttributeTypes,
  36697. useUniqueIDs: false
  36698. };
  36699. this.decodeGeometry( buffer, taskConfig )
  36700. .then( onLoad )
  36701. .catch( onError );
  36702. }, onProgress, onError );
  36703. },
  36704. /** @deprecated Kept for backward-compatibility with previous DRACOLoader versions. */
  36705. decodeDracoFile: function ( buffer, callback, attributeIDs, attributeTypes ) {
  36706. var taskConfig = {
  36707. attributeIDs: attributeIDs || this.defaultAttributeIDs,
  36708. attributeTypes: attributeTypes || this.defaultAttributeTypes,
  36709. useUniqueIDs: !! attributeIDs
  36710. };
  36711. this.decodeGeometry( buffer, taskConfig ).then( callback );
  36712. },
  36713. decodeGeometry: function ( buffer, taskConfig ) {
  36714. // TODO: For backward-compatibility, support 'attributeTypes' objects containing
  36715. // references (rather than names) to typed array constructors. These must be
  36716. // serialized before sending them to the worker.
  36717. for ( var attribute in taskConfig.attributeTypes ) {
  36718. var type = taskConfig.attributeTypes[ attribute ];
  36719. if ( type.BYTES_PER_ELEMENT !== undefined ) {
  36720. taskConfig.attributeTypes[ attribute ] = type.name;
  36721. }
  36722. }
  36723. //
  36724. var taskKey = JSON.stringify( taskConfig );
  36725. // Check for an existing task using this buffer. A transferred buffer cannot be transferred
  36726. // again from this thread.
  36727. if ( THREE.DRACOLoader.taskCache.has( buffer ) ) {
  36728. var cachedTask = THREE.DRACOLoader.taskCache.get( buffer );
  36729. if ( cachedTask.key === taskKey ) {
  36730. return cachedTask.promise;
  36731. } else if ( buffer.byteLength === 0 ) {
  36732. // Technically, it would be possible to wait for the previous task to complete,
  36733. // transfer the buffer back, and decode again with the second configuration. That
  36734. // is complex, and I don't know of any reason to decode a Draco buffer twice in
  36735. // different ways, so this is left unimplemented.
  36736. throw new Error(
  36737. 'THREE.DRACOLoader: Unable to re-decode a buffer with different ' +
  36738. 'settings. Buffer has already been transferred.'
  36739. );
  36740. }
  36741. }
  36742. //
  36743. var worker;
  36744. var taskID = this.workerNextTaskID ++;
  36745. var taskCost = buffer.byteLength;
  36746. // Obtain a worker and assign a task, and construct a geometry instance
  36747. // when the task completes.
  36748. var geometryPending = this._getWorker( taskID, taskCost )
  36749. .then( ( _worker ) => {
  36750. worker = _worker;
  36751. return new Promise( ( resolve, reject ) => {
  36752. worker._callbacks[ taskID ] = { resolve, reject };
  36753. worker.postMessage( { type: 'decode', id: taskID, taskConfig, buffer }, [ buffer ] );
  36754. // this.debug();
  36755. } );
  36756. } )
  36757. .then( ( message ) => this._createGeometry( message.geometry ) );
  36758. // Remove task from the task list.
  36759. // Note: replaced '.finally()' with '.catch().then()' block - iOS 11 support (#19416)
  36760. geometryPending
  36761. .catch( () => true )
  36762. .then( () => {
  36763. if ( worker && taskID ) {
  36764. this._releaseTask( worker, taskID );
  36765. // this.debug();
  36766. }
  36767. } );
  36768. // Cache the task result.
  36769. THREE.DRACOLoader.taskCache.set( buffer, {
  36770. key: taskKey,
  36771. promise: geometryPending
  36772. } );
  36773. return geometryPending;
  36774. },
  36775. _createGeometry: function ( geometryData ) {
  36776. var geometry = new THREE.BufferGeometry();
  36777. if ( geometryData.index ) {
  36778. geometry.setIndex( new THREE.BufferAttribute( geometryData.index.array, 1 ) );
  36779. }
  36780. for ( var i = 0; i < geometryData.attributes.length; i ++ ) {
  36781. var attribute = geometryData.attributes[ i ];
  36782. var name = attribute.name;
  36783. var array = attribute.array;
  36784. var itemSize = attribute.itemSize;
  36785. geometry.setAttribute( name, new THREE.BufferAttribute( array, itemSize ) );
  36786. }
  36787. return geometry;
  36788. },
  36789. _loadLibrary: function ( url, responseType ) {
  36790. var loader = new THREE.FileLoader( this.manager );
  36791. loader.setPath( this.decoderPath );
  36792. loader.setResponseType( responseType );
  36793. loader.setWithCredentials( this.withCredentials );
  36794. return new Promise( ( resolve, reject ) => {
  36795. loader.load( url, resolve, undefined, reject );
  36796. } );
  36797. },
  36798. preload: function () {
  36799. this._initDecoder();
  36800. return this;
  36801. },
  36802. _initDecoder: function () {
  36803. if ( this.decoderPending ) return this.decoderPending;
  36804. var useJS = typeof WebAssembly !== 'object' || this.decoderConfig.type === 'js';
  36805. var librariesPending = [];
  36806. if ( useJS ) {
  36807. librariesPending.push( this._loadLibrary( 'draco_decoder.js', 'text' ) );
  36808. } else {
  36809. librariesPending.push( this._loadLibrary( 'draco_wasm_wrapper.js', 'text' ) );
  36810. librariesPending.push( this._loadLibrary( 'draco_decoder.wasm', 'arraybuffer' ) );
  36811. }
  36812. this.decoderPending = Promise.all( librariesPending )
  36813. .then( ( libraries ) => {
  36814. var jsContent = libraries[ 0 ];
  36815. if ( ! useJS ) {
  36816. this.decoderConfig.wasmBinary = libraries[ 1 ];
  36817. }
  36818. var fn = THREE.DRACOLoader.DRACOWorker.toString();
  36819. var body = [
  36820. '/* draco decoder */',
  36821. jsContent,
  36822. '',
  36823. '/* worker */',
  36824. fn.substring( fn.indexOf( '{' ) + 1, fn.lastIndexOf( '}' ) )
  36825. ].join( '\n' );
  36826. this.workerSourceURL = URL.createObjectURL( new Blob( [ body ] ) );
  36827. } );
  36828. return this.decoderPending;
  36829. },
  36830. _getWorker: function ( taskID, taskCost ) {
  36831. return this._initDecoder().then( () => {
  36832. if ( this.workerPool.length < this.workerLimit ) {
  36833. var worker = new Worker( this.workerSourceURL );
  36834. worker._callbacks = {};
  36835. worker._taskCosts = {};
  36836. worker._taskLoad = 0;
  36837. worker.postMessage( { type: 'init', decoderConfig: this.decoderConfig } );
  36838. worker.onmessage = function ( e ) {
  36839. var message = e.data;
  36840. switch ( message.type ) {
  36841. case 'decode':
  36842. worker._callbacks[ message.id ].resolve( message );
  36843. break;
  36844. case 'error':
  36845. worker._callbacks[ message.id ].reject( message );
  36846. break;
  36847. default:
  36848. console.error( 'THREE.DRACOLoader: Unexpected message, "' + message.type + '"' );
  36849. }
  36850. };
  36851. this.workerPool.push( worker );
  36852. } else {
  36853. this.workerPool.sort( function ( a, b ) {
  36854. return a._taskLoad > b._taskLoad ? - 1 : 1;
  36855. } );
  36856. }
  36857. var worker = this.workerPool[ this.workerPool.length - 1 ];
  36858. worker._taskCosts[ taskID ] = taskCost;
  36859. worker._taskLoad += taskCost;
  36860. return worker;
  36861. } );
  36862. },
  36863. _releaseTask: function ( worker, taskID ) {
  36864. worker._taskLoad -= worker._taskCosts[ taskID ];
  36865. delete worker._callbacks[ taskID ];
  36866. delete worker._taskCosts[ taskID ];
  36867. },
  36868. debug: function () {
  36869. console.log( 'Task load: ', this.workerPool.map( ( worker ) => worker._taskLoad ) );
  36870. },
  36871. dispose: function () {
  36872. for ( var i = 0; i < this.workerPool.length; ++ i ) {
  36873. this.workerPool[ i ].terminate();
  36874. }
  36875. this.workerPool.length = 0;
  36876. return this;
  36877. }
  36878. } );
  36879. /* WEB WORKER */
  36880. THREE.DRACOLoader.DRACOWorker = function () {
  36881. var decoderConfig;
  36882. var decoderPending;
  36883. onmessage = function ( e ) {
  36884. var message = e.data;
  36885. switch ( message.type ) {
  36886. case 'init':
  36887. decoderConfig = message.decoderConfig;
  36888. decoderPending = new Promise( function ( resolve/*, reject*/ ) {
  36889. decoderConfig.onModuleLoaded = function ( draco ) {
  36890. // Module is Promise-like. Wrap before resolving to avoid loop.
  36891. resolve( { draco: draco } );
  36892. };
  36893. DracoDecoderModule( decoderConfig ); // eslint-disable-line no-undef
  36894. } );
  36895. break;
  36896. case 'decode':
  36897. var buffer = message.buffer;
  36898. var taskConfig = message.taskConfig;
  36899. decoderPending.then( ( module ) => {
  36900. var draco = module.draco;
  36901. var decoder = new draco.Decoder();
  36902. var decoderBuffer = new draco.DecoderBuffer();
  36903. decoderBuffer.Init( new Int8Array( buffer ), buffer.byteLength );
  36904. try {
  36905. var geometry = decodeGeometry( draco, decoder, decoderBuffer, taskConfig );
  36906. var buffers = geometry.attributes.map( ( attr ) => attr.array.buffer );
  36907. if ( geometry.index ) buffers.push( geometry.index.array.buffer );
  36908. self.postMessage( { type: 'decode', id: message.id, geometry }, buffers );
  36909. } catch ( error ) {
  36910. console.error( error );
  36911. self.postMessage( { type: 'error', id: message.id, error: error.message } );
  36912. } finally {
  36913. draco.destroy( decoderBuffer );
  36914. draco.destroy( decoder );
  36915. }
  36916. } );
  36917. break;
  36918. }
  36919. };
  36920. function decodeGeometry( draco, decoder, decoderBuffer, taskConfig ) {
  36921. var attributeIDs = taskConfig.attributeIDs;
  36922. var attributeTypes = taskConfig.attributeTypes;
  36923. var dracoGeometry;
  36924. var decodingStatus;
  36925. var geometryType = decoder.GetEncodedGeometryType( decoderBuffer );
  36926. if ( geometryType === draco.TRIANGULAR_MESH ) {
  36927. dracoGeometry = new draco.Mesh();
  36928. decodingStatus = decoder.DecodeBufferToMesh( decoderBuffer, dracoGeometry );
  36929. } else if ( geometryType === draco.POINT_CLOUD ) {
  36930. dracoGeometry = new draco.PointCloud();
  36931. decodingStatus = decoder.DecodeBufferToPointCloud( decoderBuffer, dracoGeometry );
  36932. } else {
  36933. throw new Error( 'THREE.DRACOLoader: Unexpected geometry type.' );
  36934. }
  36935. if ( ! decodingStatus.ok() || dracoGeometry.ptr === 0 ) {
  36936. throw new Error( 'THREE.DRACOLoader: Decoding failed: ' + decodingStatus.error_msg() );
  36937. }
  36938. var geometry = { index: null, attributes: [] };
  36939. // Gather all vertex attributes.
  36940. for ( var attributeName in attributeIDs ) {
  36941. var attributeType = self[ attributeTypes[ attributeName ] ];
  36942. var attribute;
  36943. var attributeID;
  36944. // A Draco file may be created with default vertex attributes, whose attribute IDs
  36945. // are mapped 1:1 from their semantic name (POSITION, NORMAL, ...). Alternatively,
  36946. // a Draco file may contain a custom set of attributes, identified by known unique
  36947. // IDs. glTF files always do the latter, and `.drc` files typically do the former.
  36948. if ( taskConfig.useUniqueIDs ) {
  36949. attributeID = attributeIDs[ attributeName ];
  36950. attribute = decoder.GetAttributeByUniqueId( dracoGeometry, attributeID );
  36951. } else {
  36952. attributeID = decoder.GetAttributeId( dracoGeometry, draco[ attributeIDs[ attributeName ] ] );
  36953. if ( attributeID === - 1 ) continue;
  36954. attribute = decoder.GetAttribute( dracoGeometry, attributeID );
  36955. }
  36956. geometry.attributes.push( decodeAttribute( draco, decoder, dracoGeometry, attributeName, attributeType, attribute ) );
  36957. }
  36958. // Add index.
  36959. if ( geometryType === draco.TRIANGULAR_MESH ) {
  36960. geometry.index = decodeIndex( draco, decoder, dracoGeometry );
  36961. }
  36962. draco.destroy( dracoGeometry );
  36963. return geometry;
  36964. }
  36965. function decodeIndex( draco, decoder, dracoGeometry ) {
  36966. var numFaces = dracoGeometry.num_faces();
  36967. var numIndices = numFaces * 3;
  36968. var byteLength = numIndices * 4;
  36969. var ptr = draco._malloc( byteLength );
  36970. decoder.GetTrianglesUInt32Array( dracoGeometry, byteLength, ptr );
  36971. var index = new Uint32Array( draco.HEAPF32.buffer, ptr, numIndices ).slice();
  36972. draco._free( ptr );
  36973. return { array: index, itemSize: 1 };
  36974. }
  36975. function decodeAttribute( draco, decoder, dracoGeometry, attributeName, attributeType, attribute ) {
  36976. var numComponents = attribute.num_components();
  36977. var numPoints = dracoGeometry.num_points();
  36978. var numValues = numPoints * numComponents;
  36979. var byteLength = numValues * attributeType.BYTES_PER_ELEMENT;
  36980. var dataType = getDracoDataType( draco, attributeType );
  36981. var ptr = draco._malloc( byteLength );
  36982. decoder.GetAttributeDataArrayForAllPoints( dracoGeometry, attribute, dataType, byteLength, ptr );
  36983. var array = new attributeType( draco.HEAPF32.buffer, ptr, numValues ).slice();
  36984. draco._free( ptr );
  36985. return {
  36986. name: attributeName,
  36987. array: array,
  36988. itemSize: numComponents
  36989. };
  36990. }
  36991. function getDracoDataType( draco, attributeType ) {
  36992. switch ( attributeType ) {
  36993. case Float32Array: return draco.DT_FLOAT32;
  36994. case Int8Array: return draco.DT_INT8;
  36995. case Int16Array: return draco.DT_INT16;
  36996. case Int32Array: return draco.DT_INT32;
  36997. case Uint8Array: return draco.DT_UINT8;
  36998. case Uint16Array: return draco.DT_UINT16;
  36999. case Uint32Array: return draco.DT_UINT32;
  37000. }
  37001. }
  37002. };
  37003. THREE.DRACOLoader.taskCache = new WeakMap();
  37004. /** Deprecated static methods */
  37005. /** @deprecated */
  37006. THREE.DRACOLoader.setDecoderPath = function () {
  37007. console.warn( 'THREE.DRACOLoader: The .setDecoderPath() method has been removed. Use instance methods.' );
  37008. };
  37009. /** @deprecated */
  37010. THREE.DRACOLoader.setDecoderConfig = function () {
  37011. console.warn( 'THREE.DRACOLoader: The .setDecoderConfig() method has been removed. Use instance methods.' );
  37012. };
  37013. /** @deprecated */
  37014. THREE.DRACOLoader.releaseDecoderModule = function () {
  37015. console.warn( 'THREE.DRACOLoader: The .releaseDecoderModule() method has been removed. Use instance methods.' );
  37016. };
  37017. /** @deprecated */
  37018. THREE.DRACOLoader.getDecoderModule = function () {
  37019. console.warn( 'THREE.DRACOLoader: The .getDecoderModule() method has been removed. Use instance methods.' );
  37020. };
  37021. },{}],59:[function(_dereq_,module,exports){
  37022. THREE.GLTFLoader = ( function () {
  37023. function GLTFLoader( manager ) {
  37024. THREE.Loader.call( this, manager );
  37025. this.dracoLoader = null;
  37026. this.ddsLoader = null;
  37027. this.ktx2Loader = null;
  37028. this.meshoptDecoder = null;
  37029. this.pluginCallbacks = [];
  37030. this.register( function ( parser ) {
  37031. return new GLTFMaterialsClearcoatExtension( parser );
  37032. } );
  37033. this.register( function ( parser ) {
  37034. return new GLTFTextureBasisUExtension( parser );
  37035. } );
  37036. this.register( function ( parser ) {
  37037. return new GLTFTextureWebPExtension( parser );
  37038. } );
  37039. this.register( function ( parser ) {
  37040. return new GLTFMaterialsTransmissionExtension( parser );
  37041. } );
  37042. this.register( function ( parser ) {
  37043. return new GLTFLightsExtension( parser );
  37044. } );
  37045. this.register( function ( parser ) {
  37046. return new GLTFMeshoptCompression( parser );
  37047. } );
  37048. }
  37049. GLTFLoader.prototype = Object.assign( Object.create( THREE.Loader.prototype ), {
  37050. constructor: GLTFLoader,
  37051. load: function ( url, onLoad, onProgress, onError ) {
  37052. var scope = this;
  37053. var resourcePath;
  37054. if ( this.resourcePath !== '' ) {
  37055. resourcePath = this.resourcePath;
  37056. } else if ( this.path !== '' ) {
  37057. resourcePath = this.path;
  37058. } else {
  37059. resourcePath = THREE.LoaderUtils.extractUrlBase( url );
  37060. }
  37061. // Tells the LoadingManager to track an extra item, which resolves after
  37062. // the model is fully loaded. This means the count of items loaded will
  37063. // be incorrect, but ensures manager.onLoad() does not fire early.
  37064. this.manager.itemStart( url );
  37065. var _onError = function ( e ) {
  37066. if ( onError ) {
  37067. onError( e );
  37068. } else {
  37069. console.error( e );
  37070. }
  37071. scope.manager.itemError( url );
  37072. scope.manager.itemEnd( url );
  37073. };
  37074. var loader = new THREE.FileLoader( this.manager );
  37075. loader.setPath( this.path );
  37076. loader.setResponseType( 'arraybuffer' );
  37077. loader.setRequestHeader( this.requestHeader );
  37078. loader.setWithCredentials( this.withCredentials );
  37079. loader.load( url, function ( data ) {
  37080. try {
  37081. scope.parse( data, resourcePath, function ( gltf ) {
  37082. onLoad( gltf );
  37083. scope.manager.itemEnd( url );
  37084. }, _onError );
  37085. } catch ( e ) {
  37086. _onError( e );
  37087. }
  37088. }, onProgress, _onError );
  37089. },
  37090. setDRACOLoader: function ( dracoLoader ) {
  37091. this.dracoLoader = dracoLoader;
  37092. return this;
  37093. },
  37094. setDDSLoader: function ( ddsLoader ) {
  37095. this.ddsLoader = ddsLoader;
  37096. return this;
  37097. },
  37098. setKTX2Loader: function ( ktx2Loader ) {
  37099. this.ktx2Loader = ktx2Loader;
  37100. return this;
  37101. },
  37102. setMeshoptDecoder: function ( meshoptDecoder ) {
  37103. this.meshoptDecoder = meshoptDecoder;
  37104. return this;
  37105. },
  37106. register: function ( callback ) {
  37107. if ( this.pluginCallbacks.indexOf( callback ) === - 1 ) {
  37108. this.pluginCallbacks.push( callback );
  37109. }
  37110. return this;
  37111. },
  37112. unregister: function ( callback ) {
  37113. if ( this.pluginCallbacks.indexOf( callback ) !== - 1 ) {
  37114. this.pluginCallbacks.splice( this.pluginCallbacks.indexOf( callback ), 1 );
  37115. }
  37116. return this;
  37117. },
  37118. parse: function ( data, path, onLoad, onError ) {
  37119. var content;
  37120. var extensions = {};
  37121. var plugins = {};
  37122. if ( typeof data === 'string' ) {
  37123. content = data;
  37124. } else {
  37125. var magic = THREE.LoaderUtils.decodeText( new Uint8Array( data, 0, 4 ) );
  37126. if ( magic === BINARY_EXTENSION_HEADER_MAGIC ) {
  37127. try {
  37128. extensions[ EXTENSIONS.KHR_BINARY_GLTF ] = new GLTFBinaryExtension( data );
  37129. } catch ( error ) {
  37130. if ( onError ) onError( error );
  37131. return;
  37132. }
  37133. content = extensions[ EXTENSIONS.KHR_BINARY_GLTF ].content;
  37134. } else {
  37135. content = THREE.LoaderUtils.decodeText( new Uint8Array( data ) );
  37136. }
  37137. }
  37138. var json = JSON.parse( content );
  37139. if ( json.asset === undefined || json.asset.version[ 0 ] < 2 ) {
  37140. if ( onError ) onError( new Error( 'THREE.GLTFLoader: Unsupported asset. glTF versions >=2.0 are supported.' ) );
  37141. return;
  37142. }
  37143. var parser = new GLTFParser( json, {
  37144. path: path || this.resourcePath || '',
  37145. crossOrigin: this.crossOrigin,
  37146. manager: this.manager,
  37147. ktx2Loader: this.ktx2Loader,
  37148. meshoptDecoder: this.meshoptDecoder
  37149. } );
  37150. parser.fileLoader.setRequestHeader( this.requestHeader );
  37151. for ( var i = 0; i < this.pluginCallbacks.length; i ++ ) {
  37152. var plugin = this.pluginCallbacks[ i ]( parser );
  37153. plugins[ plugin.name ] = plugin;
  37154. // Workaround to avoid determining as unknown extension
  37155. // in addUnknownExtensionsToUserData().
  37156. // Remove this workaround if we move all the existing
  37157. // extension handlers to plugin system
  37158. extensions[ plugin.name ] = true;
  37159. }
  37160. if ( json.extensionsUsed ) {
  37161. for ( var i = 0; i < json.extensionsUsed.length; ++ i ) {
  37162. var extensionName = json.extensionsUsed[ i ];
  37163. var extensionsRequired = json.extensionsRequired || [];
  37164. switch ( extensionName ) {
  37165. case EXTENSIONS.KHR_MATERIALS_UNLIT:
  37166. extensions[ extensionName ] = new GLTFMaterialsUnlitExtension();
  37167. break;
  37168. case EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS:
  37169. extensions[ extensionName ] = new GLTFMaterialsPbrSpecularGlossinessExtension();
  37170. break;
  37171. case EXTENSIONS.KHR_DRACO_MESH_COMPRESSION:
  37172. extensions[ extensionName ] = new GLTFDracoMeshCompressionExtension( json, this.dracoLoader );
  37173. break;
  37174. case EXTENSIONS.MSFT_TEXTURE_DDS:
  37175. extensions[ extensionName ] = new GLTFTextureDDSExtension( this.ddsLoader );
  37176. break;
  37177. case EXTENSIONS.KHR_TEXTURE_TRANSFORM:
  37178. extensions[ extensionName ] = new GLTFTextureTransformExtension();
  37179. break;
  37180. case EXTENSIONS.KHR_MESH_QUANTIZATION:
  37181. extensions[ extensionName ] = new GLTFMeshQuantizationExtension();
  37182. break;
  37183. default:
  37184. if ( extensionsRequired.indexOf( extensionName ) >= 0 && plugins[ extensionName ] === undefined ) {
  37185. console.warn( 'THREE.GLTFLoader: Unknown extension "' + extensionName + '".' );
  37186. }
  37187. }
  37188. }
  37189. }
  37190. parser.setExtensions( extensions );
  37191. parser.setPlugins( plugins );
  37192. parser.parse( onLoad, onError );
  37193. }
  37194. } );
  37195. /* GLTFREGISTRY */
  37196. function GLTFRegistry() {
  37197. var objects = {};
  37198. return {
  37199. get: function ( key ) {
  37200. return objects[ key ];
  37201. },
  37202. add: function ( key, object ) {
  37203. objects[ key ] = object;
  37204. },
  37205. remove: function ( key ) {
  37206. delete objects[ key ];
  37207. },
  37208. removeAll: function () {
  37209. objects = {};
  37210. }
  37211. };
  37212. }
  37213. /*********************************/
  37214. /********** EXTENSIONS ***********/
  37215. /*********************************/
  37216. var EXTENSIONS = {
  37217. KHR_BINARY_GLTF: 'KHR_binary_glTF',
  37218. KHR_DRACO_MESH_COMPRESSION: 'KHR_draco_mesh_compression',
  37219. KHR_LIGHTS_PUNCTUAL: 'KHR_lights_punctual',
  37220. KHR_MATERIALS_CLEARCOAT: 'KHR_materials_clearcoat',
  37221. KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS: 'KHR_materials_pbrSpecularGlossiness',
  37222. KHR_MATERIALS_TRANSMISSION: 'KHR_materials_transmission',
  37223. KHR_MATERIALS_UNLIT: 'KHR_materials_unlit',
  37224. KHR_TEXTURE_BASISU: 'KHR_texture_basisu',
  37225. KHR_TEXTURE_TRANSFORM: 'KHR_texture_transform',
  37226. KHR_MESH_QUANTIZATION: 'KHR_mesh_quantization',
  37227. EXT_TEXTURE_WEBP: 'EXT_texture_webp',
  37228. EXT_MESHOPT_COMPRESSION: 'EXT_meshopt_compression',
  37229. MSFT_TEXTURE_DDS: 'MSFT_texture_dds'
  37230. };
  37231. /**
  37232. * DDS Texture Extension
  37233. *
  37234. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/MSFT_texture_dds
  37235. *
  37236. */
  37237. function GLTFTextureDDSExtension( ddsLoader ) {
  37238. if ( ! ddsLoader ) {
  37239. throw new Error( 'THREE.GLTFLoader: Attempting to load .dds texture without importing THREE.DDSLoader' );
  37240. }
  37241. this.name = EXTENSIONS.MSFT_TEXTURE_DDS;
  37242. this.ddsLoader = ddsLoader;
  37243. }
  37244. /**
  37245. * Punctual Lights Extension
  37246. *
  37247. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_lights_punctual
  37248. */
  37249. function GLTFLightsExtension( parser ) {
  37250. this.parser = parser;
  37251. this.name = EXTENSIONS.KHR_LIGHTS_PUNCTUAL;
  37252. // Object3D instance caches
  37253. this.cache = { refs: {}, uses: {} };
  37254. }
  37255. GLTFLightsExtension.prototype._markDefs = function () {
  37256. var parser = this.parser;
  37257. var nodeDefs = this.parser.json.nodes || [];
  37258. for ( var nodeIndex = 0, nodeLength = nodeDefs.length; nodeIndex < nodeLength; nodeIndex ++ ) {
  37259. var nodeDef = nodeDefs[ nodeIndex ];
  37260. if ( nodeDef.extensions
  37261. && nodeDef.extensions[ this.name ]
  37262. && nodeDef.extensions[ this.name ].light !== undefined ) {
  37263. parser._addNodeRef( this.cache, nodeDef.extensions[ this.name ].light );
  37264. }
  37265. }
  37266. };
  37267. GLTFLightsExtension.prototype._loadLight = function ( lightIndex ) {
  37268. var parser = this.parser;
  37269. var cacheKey = 'light:' + lightIndex;
  37270. var dependency = parser.cache.get( cacheKey );
  37271. if ( dependency ) return dependency;
  37272. var json = parser.json;
  37273. var extensions = ( json.extensions && json.extensions[ this.name ] ) || {};
  37274. var lightDefs = extensions.lights || [];
  37275. var lightDef = lightDefs[ lightIndex ];
  37276. var lightNode;
  37277. var color = new THREE.Color( 0xffffff );
  37278. if ( lightDef.color !== undefined ) color.fromArray( lightDef.color );
  37279. var range = lightDef.range !== undefined ? lightDef.range : 0;
  37280. switch ( lightDef.type ) {
  37281. case 'directional':
  37282. lightNode = new THREE.DirectionalLight( color );
  37283. lightNode.target.position.set( 0, 0, - 1 );
  37284. lightNode.add( lightNode.target );
  37285. break;
  37286. case 'point':
  37287. lightNode = new THREE.PointLight( color );
  37288. lightNode.distance = range;
  37289. break;
  37290. case 'spot':
  37291. lightNode = new THREE.SpotLight( color );
  37292. lightNode.distance = range;
  37293. // Handle spotlight properties.
  37294. lightDef.spot = lightDef.spot || {};
  37295. lightDef.spot.innerConeAngle = lightDef.spot.innerConeAngle !== undefined ? lightDef.spot.innerConeAngle : 0;
  37296. lightDef.spot.outerConeAngle = lightDef.spot.outerConeAngle !== undefined ? lightDef.spot.outerConeAngle : Math.PI / 4.0;
  37297. lightNode.angle = lightDef.spot.outerConeAngle;
  37298. lightNode.penumbra = 1.0 - lightDef.spot.innerConeAngle / lightDef.spot.outerConeAngle;
  37299. lightNode.target.position.set( 0, 0, - 1 );
  37300. lightNode.add( lightNode.target );
  37301. break;
  37302. default:
  37303. throw new Error( 'THREE.GLTFLoader: Unexpected light type: ' + lightDef.type );
  37304. }
  37305. // Some lights (e.g. spot) default to a position other than the origin. Reset the position
  37306. // here, because node-level parsing will only override position if explicitly specified.
  37307. lightNode.position.set( 0, 0, 0 );
  37308. lightNode.decay = 2;
  37309. if ( lightDef.intensity !== undefined ) lightNode.intensity = lightDef.intensity;
  37310. lightNode.name = parser.createUniqueName( lightDef.name || ( 'light_' + lightIndex ) );
  37311. dependency = Promise.resolve( lightNode );
  37312. parser.cache.add( cacheKey, dependency );
  37313. return dependency;
  37314. };
  37315. GLTFLightsExtension.prototype.createNodeAttachment = function ( nodeIndex ) {
  37316. var self = this;
  37317. var parser = this.parser;
  37318. var json = parser.json;
  37319. var nodeDef = json.nodes[ nodeIndex ];
  37320. var lightDef = ( nodeDef.extensions && nodeDef.extensions[ this.name ] ) || {};
  37321. var lightIndex = lightDef.light;
  37322. if ( lightIndex === undefined ) return null;
  37323. return this._loadLight( lightIndex ).then( function ( light ) {
  37324. return parser._getNodeRef( self.cache, lightIndex, light );
  37325. } );
  37326. };
  37327. /**
  37328. * Unlit Materials Extension
  37329. *
  37330. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_unlit
  37331. */
  37332. function GLTFMaterialsUnlitExtension() {
  37333. this.name = EXTENSIONS.KHR_MATERIALS_UNLIT;
  37334. }
  37335. GLTFMaterialsUnlitExtension.prototype.getMaterialType = function () {
  37336. return THREE.MeshBasicMaterial;
  37337. };
  37338. GLTFMaterialsUnlitExtension.prototype.extendParams = function ( materialParams, materialDef, parser ) {
  37339. var pending = [];
  37340. materialParams.color = new THREE.Color( 1.0, 1.0, 1.0 );
  37341. materialParams.opacity = 1.0;
  37342. var metallicRoughness = materialDef.pbrMetallicRoughness;
  37343. if ( metallicRoughness ) {
  37344. if ( Array.isArray( metallicRoughness.baseColorFactor ) ) {
  37345. var array = metallicRoughness.baseColorFactor;
  37346. materialParams.color.fromArray( array );
  37347. materialParams.opacity = array[ 3 ];
  37348. }
  37349. if ( metallicRoughness.baseColorTexture !== undefined ) {
  37350. pending.push( parser.assignTexture( materialParams, 'map', metallicRoughness.baseColorTexture ) );
  37351. }
  37352. }
  37353. return Promise.all( pending );
  37354. };
  37355. /**
  37356. * Clearcoat Materials Extension
  37357. *
  37358. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_clearcoat
  37359. */
  37360. function GLTFMaterialsClearcoatExtension( parser ) {
  37361. this.parser = parser;
  37362. this.name = EXTENSIONS.KHR_MATERIALS_CLEARCOAT;
  37363. }
  37364. GLTFMaterialsClearcoatExtension.prototype.getMaterialType = function ( materialIndex ) {
  37365. var parser = this.parser;
  37366. var materialDef = parser.json.materials[ materialIndex ];
  37367. if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) return null;
  37368. return THREE.MeshPhysicalMaterial;
  37369. };
  37370. GLTFMaterialsClearcoatExtension.prototype.extendMaterialParams = function ( materialIndex, materialParams ) {
  37371. var parser = this.parser;
  37372. var materialDef = parser.json.materials[ materialIndex ];
  37373. if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) {
  37374. return Promise.resolve();
  37375. }
  37376. var pending = [];
  37377. var extension = materialDef.extensions[ this.name ];
  37378. if ( extension.clearcoatFactor !== undefined ) {
  37379. materialParams.clearcoat = extension.clearcoatFactor;
  37380. }
  37381. if ( extension.clearcoatTexture !== undefined ) {
  37382. pending.push( parser.assignTexture( materialParams, 'clearcoatMap', extension.clearcoatTexture ) );
  37383. }
  37384. if ( extension.clearcoatRoughnessFactor !== undefined ) {
  37385. materialParams.clearcoatRoughness = extension.clearcoatRoughnessFactor;
  37386. }
  37387. if ( extension.clearcoatRoughnessTexture !== undefined ) {
  37388. pending.push( parser.assignTexture( materialParams, 'clearcoatRoughnessMap', extension.clearcoatRoughnessTexture ) );
  37389. }
  37390. if ( extension.clearcoatNormalTexture !== undefined ) {
  37391. pending.push( parser.assignTexture( materialParams, 'clearcoatNormalMap', extension.clearcoatNormalTexture ) );
  37392. if ( extension.clearcoatNormalTexture.scale !== undefined ) {
  37393. var scale = extension.clearcoatNormalTexture.scale;
  37394. // https://github.com/mrdoob/three.js/issues/11438#issuecomment-507003995
  37395. materialParams.clearcoatNormalScale = new THREE.Vector2( scale, -scale );
  37396. }
  37397. }
  37398. return Promise.all( pending );
  37399. };
  37400. /**
  37401. * Transmission Materials Extension
  37402. *
  37403. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_transmission
  37404. * Draft: https://github.com/KhronosGroup/glTF/pull/1698
  37405. */
  37406. function GLTFMaterialsTransmissionExtension( parser ) {
  37407. this.parser = parser;
  37408. this.name = EXTENSIONS.KHR_MATERIALS_TRANSMISSION;
  37409. }
  37410. GLTFMaterialsTransmissionExtension.prototype.getMaterialType = function ( materialIndex ) {
  37411. var parser = this.parser;
  37412. var materialDef = parser.json.materials[ materialIndex ];
  37413. if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) return null;
  37414. return THREE.MeshPhysicalMaterial;
  37415. };
  37416. GLTFMaterialsTransmissionExtension.prototype.extendMaterialParams = function ( materialIndex, materialParams ) {
  37417. var parser = this.parser;
  37418. var materialDef = parser.json.materials[ materialIndex ];
  37419. if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) {
  37420. return Promise.resolve();
  37421. }
  37422. var pending = [];
  37423. var extension = materialDef.extensions[ this.name ];
  37424. if ( extension.transmissionFactor !== undefined ) {
  37425. materialParams.transmission = extension.transmissionFactor;
  37426. }
  37427. if ( extension.transmissionTexture !== undefined ) {
  37428. pending.push( parser.assignTexture( materialParams, 'transmissionMap', extension.transmissionTexture ) );
  37429. }
  37430. return Promise.all( pending );
  37431. };
  37432. /**
  37433. * BasisU Texture Extension
  37434. *
  37435. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_texture_basisu
  37436. */
  37437. function GLTFTextureBasisUExtension( parser ) {
  37438. this.parser = parser;
  37439. this.name = EXTENSIONS.KHR_TEXTURE_BASISU;
  37440. }
  37441. GLTFTextureBasisUExtension.prototype.loadTexture = function ( textureIndex ) {
  37442. var parser = this.parser;
  37443. var json = parser.json;
  37444. var textureDef = json.textures[ textureIndex ];
  37445. if ( ! textureDef.extensions || ! textureDef.extensions[ this.name ] ) {
  37446. return null;
  37447. }
  37448. var extension = textureDef.extensions[ this.name ];
  37449. var source = json.images[ extension.source ];
  37450. var loader = parser.options.ktx2Loader;
  37451. if ( ! loader ) {
  37452. if ( json.extensionsRequired && json.extensionsRequired.indexOf( this.name ) >= 0 ) {
  37453. throw new Error( 'THREE.GLTFLoader: setKTX2Loader must be called before loading KTX2 textures' );
  37454. } else {
  37455. // Assumes that the extension is optional and that a fallback texture is present
  37456. return null;
  37457. }
  37458. }
  37459. return parser.loadTextureImage( textureIndex, source, loader );
  37460. };
  37461. /**
  37462. * WebP Texture Extension
  37463. *
  37464. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/EXT_texture_webp
  37465. */
  37466. function GLTFTextureWebPExtension( parser ) {
  37467. this.parser = parser;
  37468. this.name = EXTENSIONS.EXT_TEXTURE_WEBP;
  37469. this.isSupported = null;
  37470. }
  37471. GLTFTextureWebPExtension.prototype.loadTexture = function ( textureIndex ) {
  37472. var name = this.name;
  37473. var parser = this.parser;
  37474. var json = parser.json;
  37475. var textureDef = json.textures[ textureIndex ];
  37476. if ( ! textureDef.extensions || ! textureDef.extensions[ name ] ) {
  37477. return null;
  37478. }
  37479. var extension = textureDef.extensions[ name ];
  37480. var source = json.images[ extension.source ];
  37481. var loader = source.uri ? parser.options.manager.getHandler( source.uri ) : parser.textureLoader;
  37482. return this.detectSupport().then( function ( isSupported ) {
  37483. if ( isSupported ) return parser.loadTextureImage( textureIndex, source, loader );
  37484. if ( json.extensionsRequired && json.extensionsRequired.indexOf( name ) >= 0 ) {
  37485. throw new Error( 'THREE.GLTFLoader: WebP required by asset but unsupported.' );
  37486. }
  37487. // Fall back to PNG or JPEG.
  37488. return parser.loadTexture( textureIndex );
  37489. } );
  37490. };
  37491. GLTFTextureWebPExtension.prototype.detectSupport = function () {
  37492. if ( ! this.isSupported ) {
  37493. this.isSupported = new Promise( function ( resolve ) {
  37494. var image = new Image();
  37495. // Lossy test image. Support for lossy images doesn't guarantee support for all
  37496. // WebP images, unfortunately.
  37497. image.src = 'data:image/webp;base64,UklGRiIAAABXRUJQVlA4IBYAAAAwAQCdASoBAAEADsD+JaQAA3AAAAAA';
  37498. image.onload = image.onerror = function () {
  37499. resolve( image.height === 1 );
  37500. };
  37501. } );
  37502. }
  37503. return this.isSupported;
  37504. };
  37505. /**
  37506. * meshopt BufferView Compression Extension
  37507. *
  37508. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/EXT_meshopt_compression
  37509. */
  37510. function GLTFMeshoptCompression( parser ) {
  37511. this.name = EXTENSIONS.EXT_MESHOPT_COMPRESSION;
  37512. this.parser = parser;
  37513. }
  37514. GLTFMeshoptCompression.prototype.loadBufferView = function ( index ) {
  37515. var json = this.parser.json;
  37516. var bufferView = json.bufferViews[ index ];
  37517. if ( bufferView.extensions && bufferView.extensions[ this.name ] ) {
  37518. var extensionDef = bufferView.extensions[ this.name ];
  37519. var buffer = this.parser.getDependency( 'buffer', extensionDef.buffer );
  37520. var decoder = this.parser.options.meshoptDecoder;
  37521. if ( ! decoder || ! decoder.supported ) {
  37522. if ( json.extensionsRequired && json.extensionsRequired.indexOf( this.name ) >= 0 ) {
  37523. throw new Error( 'THREE.GLTFLoader: setMeshoptDecoder must be called before loading compressed files' );
  37524. } else {
  37525. // Assumes that the extension is optional and that fallback buffer data is present
  37526. return null;
  37527. }
  37528. }
  37529. return Promise.all( [ buffer, decoder.ready ] ).then( function ( res ) {
  37530. var byteOffset = extensionDef.byteOffset || 0;
  37531. var byteLength = extensionDef.byteLength || 0;
  37532. var count = extensionDef.count;
  37533. var stride = extensionDef.byteStride;
  37534. var result = new ArrayBuffer( count * stride );
  37535. var source = new Uint8Array( res[ 0 ], byteOffset, byteLength );
  37536. decoder.decodeGltfBuffer( new Uint8Array( result ), count, stride, source, extensionDef.mode, extensionDef.filter );
  37537. return result;
  37538. } );
  37539. } else {
  37540. return null;
  37541. }
  37542. };
  37543. /* BINARY EXTENSION */
  37544. var BINARY_EXTENSION_HEADER_MAGIC = 'glTF';
  37545. var BINARY_EXTENSION_HEADER_LENGTH = 12;
  37546. var BINARY_EXTENSION_CHUNK_TYPES = { JSON: 0x4E4F534A, BIN: 0x004E4942 };
  37547. function GLTFBinaryExtension( data ) {
  37548. this.name = EXTENSIONS.KHR_BINARY_GLTF;
  37549. this.content = null;
  37550. this.body = null;
  37551. var headerView = new DataView( data, 0, BINARY_EXTENSION_HEADER_LENGTH );
  37552. this.header = {
  37553. magic: THREE.LoaderUtils.decodeText( new Uint8Array( data.slice( 0, 4 ) ) ),
  37554. version: headerView.getUint32( 4, true ),
  37555. length: headerView.getUint32( 8, true )
  37556. };
  37557. if ( this.header.magic !== BINARY_EXTENSION_HEADER_MAGIC ) {
  37558. throw new Error( 'THREE.GLTFLoader: Unsupported glTF-Binary header.' );
  37559. } else if ( this.header.version < 2.0 ) {
  37560. throw new Error( 'THREE.GLTFLoader: Legacy binary file detected.' );
  37561. }
  37562. var chunkContentsLength = this.header.length - BINARY_EXTENSION_HEADER_LENGTH;
  37563. var chunkView = new DataView( data, BINARY_EXTENSION_HEADER_LENGTH );
  37564. var chunkIndex = 0;
  37565. while ( chunkIndex < chunkContentsLength ) {
  37566. var chunkLength = chunkView.getUint32( chunkIndex, true );
  37567. chunkIndex += 4;
  37568. var chunkType = chunkView.getUint32( chunkIndex, true );
  37569. chunkIndex += 4;
  37570. if ( chunkType === BINARY_EXTENSION_CHUNK_TYPES.JSON ) {
  37571. var contentArray = new Uint8Array( data, BINARY_EXTENSION_HEADER_LENGTH + chunkIndex, chunkLength );
  37572. this.content = THREE.LoaderUtils.decodeText( contentArray );
  37573. } else if ( chunkType === BINARY_EXTENSION_CHUNK_TYPES.BIN ) {
  37574. var byteOffset = BINARY_EXTENSION_HEADER_LENGTH + chunkIndex;
  37575. this.body = data.slice( byteOffset, byteOffset + chunkLength );
  37576. }
  37577. // Clients must ignore chunks with unknown types.
  37578. chunkIndex += chunkLength;
  37579. }
  37580. if ( this.content === null ) {
  37581. throw new Error( 'THREE.GLTFLoader: JSON content not found.' );
  37582. }
  37583. }
  37584. /**
  37585. * DRACO Mesh Compression Extension
  37586. *
  37587. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_draco_mesh_compression
  37588. */
  37589. function GLTFDracoMeshCompressionExtension( json, dracoLoader ) {
  37590. if ( ! dracoLoader ) {
  37591. throw new Error( 'THREE.GLTFLoader: No DRACOLoader instance provided.' );
  37592. }
  37593. this.name = EXTENSIONS.KHR_DRACO_MESH_COMPRESSION;
  37594. this.json = json;
  37595. this.dracoLoader = dracoLoader;
  37596. this.dracoLoader.preload();
  37597. }
  37598. GLTFDracoMeshCompressionExtension.prototype.decodePrimitive = function ( primitive, parser ) {
  37599. var json = this.json;
  37600. var dracoLoader = this.dracoLoader;
  37601. var bufferViewIndex = primitive.extensions[ this.name ].bufferView;
  37602. var gltfAttributeMap = primitive.extensions[ this.name ].attributes;
  37603. var threeAttributeMap = {};
  37604. var attributeNormalizedMap = {};
  37605. var attributeTypeMap = {};
  37606. for ( var attributeName in gltfAttributeMap ) {
  37607. var threeAttributeName = ATTRIBUTES[ attributeName ] || attributeName.toLowerCase();
  37608. threeAttributeMap[ threeAttributeName ] = gltfAttributeMap[ attributeName ];
  37609. }
  37610. for ( attributeName in primitive.attributes ) {
  37611. var threeAttributeName = ATTRIBUTES[ attributeName ] || attributeName.toLowerCase();
  37612. if ( gltfAttributeMap[ attributeName ] !== undefined ) {
  37613. var accessorDef = json.accessors[ primitive.attributes[ attributeName ] ];
  37614. var componentType = WEBGL_COMPONENT_TYPES[ accessorDef.componentType ];
  37615. attributeTypeMap[ threeAttributeName ] = componentType;
  37616. attributeNormalizedMap[ threeAttributeName ] = accessorDef.normalized === true;
  37617. }
  37618. }
  37619. return parser.getDependency( 'bufferView', bufferViewIndex ).then( function ( bufferView ) {
  37620. return new Promise( function ( resolve ) {
  37621. dracoLoader.decodeDracoFile( bufferView, function ( geometry ) {
  37622. for ( var attributeName in geometry.attributes ) {
  37623. var attribute = geometry.attributes[ attributeName ];
  37624. var normalized = attributeNormalizedMap[ attributeName ];
  37625. if ( normalized !== undefined ) attribute.normalized = normalized;
  37626. }
  37627. resolve( geometry );
  37628. }, threeAttributeMap, attributeTypeMap );
  37629. } );
  37630. } );
  37631. };
  37632. /**
  37633. * Texture Transform Extension
  37634. *
  37635. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_texture_transform
  37636. */
  37637. function GLTFTextureTransformExtension() {
  37638. this.name = EXTENSIONS.KHR_TEXTURE_TRANSFORM;
  37639. }
  37640. GLTFTextureTransformExtension.prototype.extendTexture = function ( texture, transform ) {
  37641. texture = texture.clone();
  37642. if ( transform.offset !== undefined ) {
  37643. texture.offset.fromArray( transform.offset );
  37644. }
  37645. if ( transform.rotation !== undefined ) {
  37646. texture.rotation = transform.rotation;
  37647. }
  37648. if ( transform.scale !== undefined ) {
  37649. texture.repeat.fromArray( transform.scale );
  37650. }
  37651. if ( transform.texCoord !== undefined ) {
  37652. console.warn( 'THREE.GLTFLoader: Custom UV sets in "' + this.name + '" extension not yet supported.' );
  37653. }
  37654. texture.needsUpdate = true;
  37655. return texture;
  37656. };
  37657. /**
  37658. * Specular-Glossiness Extension
  37659. *
  37660. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness
  37661. */
  37662. /**
  37663. * A sub class of THREE.StandardMaterial with some of the functionality
  37664. * changed via the `onBeforeCompile` callback
  37665. * @pailhead
  37666. */
  37667. function GLTFMeshStandardSGMaterial( params ) {
  37668. THREE.MeshStandardMaterial.call( this );
  37669. this.isGLTFSpecularGlossinessMaterial = true;
  37670. //various chunks that need replacing
  37671. var specularMapParsFragmentChunk = [
  37672. '#ifdef USE_SPECULARMAP',
  37673. ' uniform sampler2D specularMap;',
  37674. '#endif'
  37675. ].join( '\n' );
  37676. var glossinessMapParsFragmentChunk = [
  37677. '#ifdef USE_GLOSSINESSMAP',
  37678. ' uniform sampler2D glossinessMap;',
  37679. '#endif'
  37680. ].join( '\n' );
  37681. var specularMapFragmentChunk = [
  37682. 'vec3 specularFactor = specular;',
  37683. '#ifdef USE_SPECULARMAP',
  37684. ' vec4 texelSpecular = texture2D( specularMap, vUv );',
  37685. ' texelSpecular = sRGBToLinear( texelSpecular );',
  37686. ' // reads channel RGB, compatible with a glTF Specular-Glossiness (RGBA) texture',
  37687. ' specularFactor *= texelSpecular.rgb;',
  37688. '#endif'
  37689. ].join( '\n' );
  37690. var glossinessMapFragmentChunk = [
  37691. 'float glossinessFactor = glossiness;',
  37692. '#ifdef USE_GLOSSINESSMAP',
  37693. ' vec4 texelGlossiness = texture2D( glossinessMap, vUv );',
  37694. ' // reads channel A, compatible with a glTF Specular-Glossiness (RGBA) texture',
  37695. ' glossinessFactor *= texelGlossiness.a;',
  37696. '#endif'
  37697. ].join( '\n' );
  37698. var lightPhysicalFragmentChunk = [
  37699. 'PhysicalMaterial material;',
  37700. 'material.diffuseColor = diffuseColor.rgb * ( 1. - max( specularFactor.r, max( specularFactor.g, specularFactor.b ) ) );',
  37701. 'vec3 dxy = max( abs( dFdx( geometryNormal ) ), abs( dFdy( geometryNormal ) ) );',
  37702. 'float geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z );',
  37703. 'material.specularRoughness = max( 1.0 - glossinessFactor, 0.0525 ); // 0.0525 corresponds to the base mip of a 256 cubemap.',
  37704. 'material.specularRoughness += geometryRoughness;',
  37705. 'material.specularRoughness = min( material.specularRoughness, 1.0 );',
  37706. 'material.specularColor = specularFactor;',
  37707. ].join( '\n' );
  37708. var uniforms = {
  37709. specular: { value: new THREE.Color().setHex( 0xffffff ) },
  37710. glossiness: { value: 1 },
  37711. specularMap: { value: null },
  37712. glossinessMap: { value: null }
  37713. };
  37714. this._extraUniforms = uniforms;
  37715. this.onBeforeCompile = function ( shader ) {
  37716. for ( var uniformName in uniforms ) {
  37717. shader.uniforms[ uniformName ] = uniforms[ uniformName ];
  37718. }
  37719. shader.fragmentShader = shader.fragmentShader
  37720. .replace( 'uniform float roughness;', 'uniform vec3 specular;' )
  37721. .replace( 'uniform float metalness;', 'uniform float glossiness;' )
  37722. .replace( '#include <roughnessmap_pars_fragment>', specularMapParsFragmentChunk )
  37723. .replace( '#include <metalnessmap_pars_fragment>', glossinessMapParsFragmentChunk )
  37724. .replace( '#include <roughnessmap_fragment>', specularMapFragmentChunk )
  37725. .replace( '#include <metalnessmap_fragment>', glossinessMapFragmentChunk )
  37726. .replace( '#include <lights_physical_fragment>', lightPhysicalFragmentChunk );
  37727. };
  37728. Object.defineProperties( this, {
  37729. specular: {
  37730. get: function () {
  37731. return uniforms.specular.value;
  37732. },
  37733. set: function ( v ) {
  37734. uniforms.specular.value = v;
  37735. }
  37736. },
  37737. specularMap: {
  37738. get: function () {
  37739. return uniforms.specularMap.value;
  37740. },
  37741. set: function ( v ) {
  37742. uniforms.specularMap.value = v;
  37743. if ( v ) {
  37744. this.defines.USE_SPECULARMAP = ''; // USE_UV is set by the renderer for specular maps
  37745. } else {
  37746. delete this.defines.USE_SPECULARMAP;
  37747. }
  37748. }
  37749. },
  37750. glossiness: {
  37751. get: function () {
  37752. return uniforms.glossiness.value;
  37753. },
  37754. set: function ( v ) {
  37755. uniforms.glossiness.value = v;
  37756. }
  37757. },
  37758. glossinessMap: {
  37759. get: function () {
  37760. return uniforms.glossinessMap.value;
  37761. },
  37762. set: function ( v ) {
  37763. uniforms.glossinessMap.value = v;
  37764. if ( v ) {
  37765. this.defines.USE_GLOSSINESSMAP = '';
  37766. this.defines.USE_UV = '';
  37767. } else {
  37768. delete this.defines.USE_GLOSSINESSMAP;
  37769. delete this.defines.USE_UV;
  37770. }
  37771. }
  37772. }
  37773. } );
  37774. delete this.metalness;
  37775. delete this.roughness;
  37776. delete this.metalnessMap;
  37777. delete this.roughnessMap;
  37778. this.setValues( params );
  37779. }
  37780. GLTFMeshStandardSGMaterial.prototype = Object.create( THREE.MeshStandardMaterial.prototype );
  37781. GLTFMeshStandardSGMaterial.prototype.constructor = GLTFMeshStandardSGMaterial;
  37782. GLTFMeshStandardSGMaterial.prototype.copy = function ( source ) {
  37783. THREE.MeshStandardMaterial.prototype.copy.call( this, source );
  37784. this.specularMap = source.specularMap;
  37785. this.specular.copy( source.specular );
  37786. this.glossinessMap = source.glossinessMap;
  37787. this.glossiness = source.glossiness;
  37788. delete this.metalness;
  37789. delete this.roughness;
  37790. delete this.metalnessMap;
  37791. delete this.roughnessMap;
  37792. return this;
  37793. };
  37794. function GLTFMaterialsPbrSpecularGlossinessExtension() {
  37795. return {
  37796. name: EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS,
  37797. specularGlossinessParams: [
  37798. 'color',
  37799. 'map',
  37800. 'lightMap',
  37801. 'lightMapIntensity',
  37802. 'aoMap',
  37803. 'aoMapIntensity',
  37804. 'emissive',
  37805. 'emissiveIntensity',
  37806. 'emissiveMap',
  37807. 'bumpMap',
  37808. 'bumpScale',
  37809. 'normalMap',
  37810. 'normalMapType',
  37811. 'displacementMap',
  37812. 'displacementScale',
  37813. 'displacementBias',
  37814. 'specularMap',
  37815. 'specular',
  37816. 'glossinessMap',
  37817. 'glossiness',
  37818. 'alphaMap',
  37819. 'envMap',
  37820. 'envMapIntensity',
  37821. 'refractionRatio',
  37822. ],
  37823. getMaterialType: function () {
  37824. return GLTFMeshStandardSGMaterial;
  37825. },
  37826. extendParams: function ( materialParams, materialDef, parser ) {
  37827. var pbrSpecularGlossiness = materialDef.extensions[ this.name ];
  37828. materialParams.color = new THREE.Color( 1.0, 1.0, 1.0 );
  37829. materialParams.opacity = 1.0;
  37830. var pending = [];
  37831. if ( Array.isArray( pbrSpecularGlossiness.diffuseFactor ) ) {
  37832. var array = pbrSpecularGlossiness.diffuseFactor;
  37833. materialParams.color.fromArray( array );
  37834. materialParams.opacity = array[ 3 ];
  37835. }
  37836. if ( pbrSpecularGlossiness.diffuseTexture !== undefined ) {
  37837. pending.push( parser.assignTexture( materialParams, 'map', pbrSpecularGlossiness.diffuseTexture ) );
  37838. }
  37839. materialParams.emissive = new THREE.Color( 0.0, 0.0, 0.0 );
  37840. materialParams.glossiness = pbrSpecularGlossiness.glossinessFactor !== undefined ? pbrSpecularGlossiness.glossinessFactor : 1.0;
  37841. materialParams.specular = new THREE.Color( 1.0, 1.0, 1.0 );
  37842. if ( Array.isArray( pbrSpecularGlossiness.specularFactor ) ) {
  37843. materialParams.specular.fromArray( pbrSpecularGlossiness.specularFactor );
  37844. }
  37845. if ( pbrSpecularGlossiness.specularGlossinessTexture !== undefined ) {
  37846. var specGlossMapDef = pbrSpecularGlossiness.specularGlossinessTexture;
  37847. pending.push( parser.assignTexture( materialParams, 'glossinessMap', specGlossMapDef ) );
  37848. pending.push( parser.assignTexture( materialParams, 'specularMap', specGlossMapDef ) );
  37849. }
  37850. return Promise.all( pending );
  37851. },
  37852. createMaterial: function ( materialParams ) {
  37853. var material = new GLTFMeshStandardSGMaterial( materialParams );
  37854. material.fog = true;
  37855. material.color = materialParams.color;
  37856. material.map = materialParams.map === undefined ? null : materialParams.map;
  37857. material.lightMap = null;
  37858. material.lightMapIntensity = 1.0;
  37859. material.aoMap = materialParams.aoMap === undefined ? null : materialParams.aoMap;
  37860. material.aoMapIntensity = 1.0;
  37861. material.emissive = materialParams.emissive;
  37862. material.emissiveIntensity = 1.0;
  37863. material.emissiveMap = materialParams.emissiveMap === undefined ? null : materialParams.emissiveMap;
  37864. material.bumpMap = materialParams.bumpMap === undefined ? null : materialParams.bumpMap;
  37865. material.bumpScale = 1;
  37866. material.normalMap = materialParams.normalMap === undefined ? null : materialParams.normalMap;
  37867. material.normalMapType = THREE.TangentSpaceNormalMap;
  37868. if ( materialParams.normalScale ) material.normalScale = materialParams.normalScale;
  37869. material.displacementMap = null;
  37870. material.displacementScale = 1;
  37871. material.displacementBias = 0;
  37872. material.specularMap = materialParams.specularMap === undefined ? null : materialParams.specularMap;
  37873. material.specular = materialParams.specular;
  37874. material.glossinessMap = materialParams.glossinessMap === undefined ? null : materialParams.glossinessMap;
  37875. material.glossiness = materialParams.glossiness;
  37876. material.alphaMap = null;
  37877. material.envMap = materialParams.envMap === undefined ? null : materialParams.envMap;
  37878. material.envMapIntensity = 1.0;
  37879. material.refractionRatio = 0.98;
  37880. return material;
  37881. },
  37882. };
  37883. }
  37884. /**
  37885. * Mesh Quantization Extension
  37886. *
  37887. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_mesh_quantization
  37888. */
  37889. function GLTFMeshQuantizationExtension() {
  37890. this.name = EXTENSIONS.KHR_MESH_QUANTIZATION;
  37891. }
  37892. /*********************************/
  37893. /********** INTERPOLATION ********/
  37894. /*********************************/
  37895. // Spline Interpolation
  37896. // Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#appendix-c-spline-interpolation
  37897. function GLTFCubicSplineInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  37898. THREE.Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  37899. }
  37900. GLTFCubicSplineInterpolant.prototype = Object.create( THREE.Interpolant.prototype );
  37901. GLTFCubicSplineInterpolant.prototype.constructor = GLTFCubicSplineInterpolant;
  37902. GLTFCubicSplineInterpolant.prototype.copySampleValue_ = function ( index ) {
  37903. // Copies a sample value to the result buffer. See description of glTF
  37904. // CUBICSPLINE values layout in interpolate_() function below.
  37905. var result = this.resultBuffer,
  37906. values = this.sampleValues,
  37907. valueSize = this.valueSize,
  37908. offset = index * valueSize * 3 + valueSize;
  37909. for ( var i = 0; i !== valueSize; i ++ ) {
  37910. result[ i ] = values[ offset + i ];
  37911. }
  37912. return result;
  37913. };
  37914. GLTFCubicSplineInterpolant.prototype.beforeStart_ = GLTFCubicSplineInterpolant.prototype.copySampleValue_;
  37915. GLTFCubicSplineInterpolant.prototype.afterEnd_ = GLTFCubicSplineInterpolant.prototype.copySampleValue_;
  37916. GLTFCubicSplineInterpolant.prototype.interpolate_ = function ( i1, t0, t, t1 ) {
  37917. var result = this.resultBuffer;
  37918. var values = this.sampleValues;
  37919. var stride = this.valueSize;
  37920. var stride2 = stride * 2;
  37921. var stride3 = stride * 3;
  37922. var td = t1 - t0;
  37923. var p = ( t - t0 ) / td;
  37924. var pp = p * p;
  37925. var ppp = pp * p;
  37926. var offset1 = i1 * stride3;
  37927. var offset0 = offset1 - stride3;
  37928. var s2 = - 2 * ppp + 3 * pp;
  37929. var s3 = ppp - pp;
  37930. var s0 = 1 - s2;
  37931. var s1 = s3 - pp + p;
  37932. // Layout of keyframe output values for CUBICSPLINE animations:
  37933. // [ inTangent_1, splineVertex_1, outTangent_1, inTangent_2, splineVertex_2, ... ]
  37934. for ( var i = 0; i !== stride; i ++ ) {
  37935. var p0 = values[ offset0 + i + stride ]; // splineVertex_k
  37936. var m0 = values[ offset0 + i + stride2 ] * td; // outTangent_k * (t_k+1 - t_k)
  37937. var p1 = values[ offset1 + i + stride ]; // splineVertex_k+1
  37938. var m1 = values[ offset1 + i ] * td; // inTangent_k+1 * (t_k+1 - t_k)
  37939. result[ i ] = s0 * p0 + s1 * m0 + s2 * p1 + s3 * m1;
  37940. }
  37941. return result;
  37942. };
  37943. /*********************************/
  37944. /********** INTERNALS ************/
  37945. /*********************************/
  37946. /* CONSTANTS */
  37947. var WEBGL_CONSTANTS = {
  37948. FLOAT: 5126,
  37949. //FLOAT_MAT2: 35674,
  37950. FLOAT_MAT3: 35675,
  37951. FLOAT_MAT4: 35676,
  37952. FLOAT_VEC2: 35664,
  37953. FLOAT_VEC3: 35665,
  37954. FLOAT_VEC4: 35666,
  37955. LINEAR: 9729,
  37956. REPEAT: 10497,
  37957. SAMPLER_2D: 35678,
  37958. POINTS: 0,
  37959. LINES: 1,
  37960. LINE_LOOP: 2,
  37961. LINE_STRIP: 3,
  37962. TRIANGLES: 4,
  37963. TRIANGLE_STRIP: 5,
  37964. TRIANGLE_FAN: 6,
  37965. UNSIGNED_BYTE: 5121,
  37966. UNSIGNED_SHORT: 5123
  37967. };
  37968. var WEBGL_COMPONENT_TYPES = {
  37969. 5120: Int8Array,
  37970. 5121: Uint8Array,
  37971. 5122: Int16Array,
  37972. 5123: Uint16Array,
  37973. 5125: Uint32Array,
  37974. 5126: Float32Array
  37975. };
  37976. var WEBGL_FILTERS = {
  37977. 9728: THREE.NearestFilter,
  37978. 9729: THREE.LinearFilter,
  37979. 9984: THREE.NearestMipmapNearestFilter,
  37980. 9985: THREE.LinearMipmapNearestFilter,
  37981. 9986: THREE.NearestMipmapLinearFilter,
  37982. 9987: THREE.LinearMipmapLinearFilter
  37983. };
  37984. var WEBGL_WRAPPINGS = {
  37985. 33071: THREE.ClampToEdgeWrapping,
  37986. 33648: THREE.MirroredRepeatWrapping,
  37987. 10497: THREE.RepeatWrapping
  37988. };
  37989. var WEBGL_TYPE_SIZES = {
  37990. 'SCALAR': 1,
  37991. 'VEC2': 2,
  37992. 'VEC3': 3,
  37993. 'VEC4': 4,
  37994. 'MAT2': 4,
  37995. 'MAT3': 9,
  37996. 'MAT4': 16
  37997. };
  37998. var ATTRIBUTES = {
  37999. POSITION: 'position',
  38000. NORMAL: 'normal',
  38001. TANGENT: 'tangent',
  38002. TEXCOORD_0: 'uv',
  38003. TEXCOORD_1: 'uv2',
  38004. COLOR_0: 'color',
  38005. WEIGHTS_0: 'skinWeight',
  38006. JOINTS_0: 'skinIndex',
  38007. };
  38008. var PATH_PROPERTIES = {
  38009. scale: 'scale',
  38010. translation: 'position',
  38011. rotation: 'quaternion',
  38012. weights: 'morphTargetInfluences'
  38013. };
  38014. var INTERPOLATION = {
  38015. CUBICSPLINE: undefined, // We use a custom interpolant (GLTFCubicSplineInterpolation) for CUBICSPLINE tracks. Each
  38016. // keyframe track will be initialized with a default interpolation type, then modified.
  38017. LINEAR: THREE.InterpolateLinear,
  38018. STEP: THREE.InterpolateDiscrete
  38019. };
  38020. var ALPHA_MODES = {
  38021. OPAQUE: 'OPAQUE',
  38022. MASK: 'MASK',
  38023. BLEND: 'BLEND'
  38024. };
  38025. /* UTILITY FUNCTIONS */
  38026. function resolveURL( url, path ) {
  38027. // Invalid URL
  38028. if ( typeof url !== 'string' || url === '' ) return '';
  38029. // Host Relative URL
  38030. if ( /^https?:\/\//i.test( path ) && /^\//.test( url ) ) {
  38031. path = path.replace( /(^https?:\/\/[^\/]+).*/i, '$1' );
  38032. }
  38033. // Absolute URL http://,https://,//
  38034. if ( /^(https?:)?\/\//i.test( url ) ) return url;
  38035. // Data URI
  38036. if ( /^data:.*,.*$/i.test( url ) ) return url;
  38037. // Blob URL
  38038. if ( /^blob:.*$/i.test( url ) ) return url;
  38039. // Relative URL
  38040. return path + url;
  38041. }
  38042. /**
  38043. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#default-material
  38044. */
  38045. function createDefaultMaterial( cache ) {
  38046. if ( cache[ 'DefaultMaterial' ] === undefined ) {
  38047. cache[ 'DefaultMaterial' ] = new THREE.MeshStandardMaterial( {
  38048. color: 0xFFFFFF,
  38049. emissive: 0x000000,
  38050. metalness: 1,
  38051. roughness: 1,
  38052. transparent: false,
  38053. depthTest: true,
  38054. side: THREE.FrontSide
  38055. } );
  38056. }
  38057. return cache[ 'DefaultMaterial' ];
  38058. }
  38059. function addUnknownExtensionsToUserData( knownExtensions, object, objectDef ) {
  38060. // Add unknown glTF extensions to an object's userData.
  38061. for ( var name in objectDef.extensions ) {
  38062. if ( knownExtensions[ name ] === undefined ) {
  38063. object.userData.gltfExtensions = object.userData.gltfExtensions || {};
  38064. object.userData.gltfExtensions[ name ] = objectDef.extensions[ name ];
  38065. }
  38066. }
  38067. }
  38068. /**
  38069. * @param {THREE.Object3D|THREE.Material|THREE.BufferGeometry} object
  38070. * @param {GLTF.definition} gltfDef
  38071. */
  38072. function assignExtrasToUserData( object, gltfDef ) {
  38073. if ( gltfDef.extras !== undefined ) {
  38074. if ( typeof gltfDef.extras === 'object' ) {
  38075. Object.assign( object.userData, gltfDef.extras );
  38076. } else {
  38077. console.warn( 'THREE.GLTFLoader: Ignoring primitive type .extras, ' + gltfDef.extras );
  38078. }
  38079. }
  38080. }
  38081. /**
  38082. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#morph-targets
  38083. *
  38084. * @param {THREE.BufferGeometry} geometry
  38085. * @param {Array<GLTF.Target>} targets
  38086. * @param {GLTFParser} parser
  38087. * @return {Promise<THREE.BufferGeometry>}
  38088. */
  38089. function addMorphTargets( geometry, targets, parser ) {
  38090. var hasMorphPosition = false;
  38091. var hasMorphNormal = false;
  38092. for ( var i = 0, il = targets.length; i < il; i ++ ) {
  38093. var target = targets[ i ];
  38094. if ( target.POSITION !== undefined ) hasMorphPosition = true;
  38095. if ( target.NORMAL !== undefined ) hasMorphNormal = true;
  38096. if ( hasMorphPosition && hasMorphNormal ) break;
  38097. }
  38098. if ( ! hasMorphPosition && ! hasMorphNormal ) return Promise.resolve( geometry );
  38099. var pendingPositionAccessors = [];
  38100. var pendingNormalAccessors = [];
  38101. for ( var i = 0, il = targets.length; i < il; i ++ ) {
  38102. var target = targets[ i ];
  38103. if ( hasMorphPosition ) {
  38104. var pendingAccessor = target.POSITION !== undefined
  38105. ? parser.getDependency( 'accessor', target.POSITION )
  38106. : geometry.attributes.position;
  38107. pendingPositionAccessors.push( pendingAccessor );
  38108. }
  38109. if ( hasMorphNormal ) {
  38110. var pendingAccessor = target.NORMAL !== undefined
  38111. ? parser.getDependency( 'accessor', target.NORMAL )
  38112. : geometry.attributes.normal;
  38113. pendingNormalAccessors.push( pendingAccessor );
  38114. }
  38115. }
  38116. return Promise.all( [
  38117. Promise.all( pendingPositionAccessors ),
  38118. Promise.all( pendingNormalAccessors )
  38119. ] ).then( function ( accessors ) {
  38120. var morphPositions = accessors[ 0 ];
  38121. var morphNormals = accessors[ 1 ];
  38122. if ( hasMorphPosition ) geometry.morphAttributes.position = morphPositions;
  38123. if ( hasMorphNormal ) geometry.morphAttributes.normal = morphNormals;
  38124. geometry.morphTargetsRelative = true;
  38125. return geometry;
  38126. } );
  38127. }
  38128. /**
  38129. * @param {THREE.Mesh} mesh
  38130. * @param {GLTF.Mesh} meshDef
  38131. */
  38132. function updateMorphTargets( mesh, meshDef ) {
  38133. mesh.updateMorphTargets();
  38134. if ( meshDef.weights !== undefined ) {
  38135. for ( var i = 0, il = meshDef.weights.length; i < il; i ++ ) {
  38136. mesh.morphTargetInfluences[ i ] = meshDef.weights[ i ];
  38137. }
  38138. }
  38139. // .extras has user-defined data, so check that .extras.targetNames is an array.
  38140. if ( meshDef.extras && Array.isArray( meshDef.extras.targetNames ) ) {
  38141. var targetNames = meshDef.extras.targetNames;
  38142. if ( mesh.morphTargetInfluences.length === targetNames.length ) {
  38143. mesh.morphTargetDictionary = {};
  38144. for ( var i = 0, il = targetNames.length; i < il; i ++ ) {
  38145. mesh.morphTargetDictionary[ targetNames[ i ] ] = i;
  38146. }
  38147. } else {
  38148. console.warn( 'THREE.GLTFLoader: Invalid extras.targetNames length. Ignoring names.' );
  38149. }
  38150. }
  38151. }
  38152. function createPrimitiveKey( primitiveDef ) {
  38153. var dracoExtension = primitiveDef.extensions && primitiveDef.extensions[ EXTENSIONS.KHR_DRACO_MESH_COMPRESSION ];
  38154. var geometryKey;
  38155. if ( dracoExtension ) {
  38156. geometryKey = 'draco:' + dracoExtension.bufferView
  38157. + ':' + dracoExtension.indices
  38158. + ':' + createAttributesKey( dracoExtension.attributes );
  38159. } else {
  38160. geometryKey = primitiveDef.indices + ':' + createAttributesKey( primitiveDef.attributes ) + ':' + primitiveDef.mode;
  38161. }
  38162. return geometryKey;
  38163. }
  38164. function createAttributesKey( attributes ) {
  38165. var attributesKey = '';
  38166. var keys = Object.keys( attributes ).sort();
  38167. for ( var i = 0, il = keys.length; i < il; i ++ ) {
  38168. attributesKey += keys[ i ] + ':' + attributes[ keys[ i ] ] + ';';
  38169. }
  38170. return attributesKey;
  38171. }
  38172. /* GLTF PARSER */
  38173. function GLTFParser( json, options ) {
  38174. this.json = json || {};
  38175. this.extensions = {};
  38176. this.plugins = {};
  38177. this.options = options || {};
  38178. // loader object cache
  38179. this.cache = new GLTFRegistry();
  38180. // associations between Three.js objects and glTF elements
  38181. this.associations = new Map();
  38182. // BufferGeometry caching
  38183. this.primitiveCache = {};
  38184. // Object3D instance caches
  38185. this.meshCache = { refs: {}, uses: {} };
  38186. this.cameraCache = { refs: {}, uses: {} };
  38187. this.lightCache = { refs: {}, uses: {} };
  38188. // Track node names, to ensure no duplicates
  38189. this.nodeNamesUsed = {};
  38190. // Use an ImageBitmapLoader if imageBitmaps are supported. Moves much of the
  38191. // expensive work of uploading a texture to the GPU off the main thread.
  38192. if ( typeof createImageBitmap !== 'undefined' && /Firefox/.test( navigator.userAgent ) === false ) {
  38193. this.textureLoader = new THREE.ImageBitmapLoader( this.options.manager );
  38194. } else {
  38195. this.textureLoader = new THREE.TextureLoader( this.options.manager );
  38196. }
  38197. this.textureLoader.setCrossOrigin( this.options.crossOrigin );
  38198. this.fileLoader = new THREE.FileLoader( this.options.manager );
  38199. this.fileLoader.setResponseType( 'arraybuffer' );
  38200. if ( this.options.crossOrigin === 'use-credentials' ) {
  38201. this.fileLoader.setWithCredentials( true );
  38202. }
  38203. }
  38204. GLTFParser.prototype.setExtensions = function ( extensions ) {
  38205. this.extensions = extensions;
  38206. };
  38207. GLTFParser.prototype.setPlugins = function ( plugins ) {
  38208. this.plugins = plugins;
  38209. };
  38210. GLTFParser.prototype.parse = function ( onLoad, onError ) {
  38211. var parser = this;
  38212. var json = this.json;
  38213. var extensions = this.extensions;
  38214. // Clear the loader cache
  38215. this.cache.removeAll();
  38216. // Mark the special nodes/meshes in json for efficient parse
  38217. this._invokeAll( function ( ext ) {
  38218. return ext._markDefs && ext._markDefs();
  38219. } );
  38220. Promise.all( [
  38221. this.getDependencies( 'scene' ),
  38222. this.getDependencies( 'animation' ),
  38223. this.getDependencies( 'camera' ),
  38224. ] ).then( function ( dependencies ) {
  38225. var result = {
  38226. scene: dependencies[ 0 ][ json.scene || 0 ],
  38227. scenes: dependencies[ 0 ],
  38228. animations: dependencies[ 1 ],
  38229. cameras: dependencies[ 2 ],
  38230. asset: json.asset,
  38231. parser: parser,
  38232. userData: {}
  38233. };
  38234. addUnknownExtensionsToUserData( extensions, result, json );
  38235. assignExtrasToUserData( result, json );
  38236. onLoad( result );
  38237. } ).catch( onError );
  38238. };
  38239. /**
  38240. * Marks the special nodes/meshes in json for efficient parse.
  38241. */
  38242. GLTFParser.prototype._markDefs = function () {
  38243. var nodeDefs = this.json.nodes || [];
  38244. var skinDefs = this.json.skins || [];
  38245. var meshDefs = this.json.meshes || [];
  38246. // Nothing in the node definition indicates whether it is a Bone or an
  38247. // Object3D. Use the skins' joint references to mark bones.
  38248. for ( var skinIndex = 0, skinLength = skinDefs.length; skinIndex < skinLength; skinIndex ++ ) {
  38249. var joints = skinDefs[ skinIndex ].joints;
  38250. for ( var i = 0, il = joints.length; i < il; i ++ ) {
  38251. nodeDefs[ joints[ i ] ].isBone = true;
  38252. }
  38253. }
  38254. // Iterate over all nodes, marking references to shared resources,
  38255. // as well as skeleton joints.
  38256. for ( var nodeIndex = 0, nodeLength = nodeDefs.length; nodeIndex < nodeLength; nodeIndex ++ ) {
  38257. var nodeDef = nodeDefs[ nodeIndex ];
  38258. if ( nodeDef.mesh !== undefined ) {
  38259. this._addNodeRef( this.meshCache, nodeDef.mesh );
  38260. // Nothing in the mesh definition indicates whether it is
  38261. // a SkinnedMesh or Mesh. Use the node's mesh reference
  38262. // to mark SkinnedMesh if node has skin.
  38263. if ( nodeDef.skin !== undefined ) {
  38264. meshDefs[ nodeDef.mesh ].isSkinnedMesh = true;
  38265. }
  38266. }
  38267. if ( nodeDef.camera !== undefined ) {
  38268. this._addNodeRef( this.cameraCache, nodeDef.camera );
  38269. }
  38270. }
  38271. };
  38272. /**
  38273. * Counts references to shared node / Object3D resources. These resources
  38274. * can be reused, or "instantiated", at multiple nodes in the scene
  38275. * hierarchy. Mesh, Camera, and Light instances are instantiated and must
  38276. * be marked. Non-scenegraph resources (like Materials, Geometries, and
  38277. * Textures) can be reused directly and are not marked here.
  38278. *
  38279. * Example: CesiumMilkTruck sample model reuses "Wheel" meshes.
  38280. */
  38281. GLTFParser.prototype._addNodeRef = function ( cache, index ) {
  38282. if ( index === undefined ) return;
  38283. if ( cache.refs[ index ] === undefined ) {
  38284. cache.refs[ index ] = cache.uses[ index ] = 0;
  38285. }
  38286. cache.refs[ index ] ++;
  38287. };
  38288. /** Returns a reference to a shared resource, cloning it if necessary. */
  38289. GLTFParser.prototype._getNodeRef = function ( cache, index, object ) {
  38290. if ( cache.refs[ index ] <= 1 ) return object;
  38291. var ref = object.clone();
  38292. ref.name += '_instance_' + ( cache.uses[ index ] ++ );
  38293. return ref;
  38294. };
  38295. GLTFParser.prototype._invokeOne = function ( func ) {
  38296. var extensions = Object.values( this.plugins );
  38297. extensions.push( this );
  38298. for ( var i = 0; i < extensions.length; i ++ ) {
  38299. var result = func( extensions[ i ] );
  38300. if ( result ) return result;
  38301. }
  38302. };
  38303. GLTFParser.prototype._invokeAll = function ( func ) {
  38304. var extensions = Object.values( this.plugins );
  38305. extensions.unshift( this );
  38306. var pending = [];
  38307. for ( var i = 0; i < extensions.length; i ++ ) {
  38308. var result = func( extensions[ i ] );
  38309. if ( result ) pending.push( result );
  38310. }
  38311. return pending;
  38312. };
  38313. /**
  38314. * Requests the specified dependency asynchronously, with caching.
  38315. * @param {string} type
  38316. * @param {number} index
  38317. * @return {Promise<THREE.Object3D|THREE.Material|THREE.Texture|THREE.AnimationClip|ArrayBuffer|Object>}
  38318. */
  38319. GLTFParser.prototype.getDependency = function ( type, index ) {
  38320. var cacheKey = type + ':' + index;
  38321. var dependency = this.cache.get( cacheKey );
  38322. if ( ! dependency ) {
  38323. switch ( type ) {
  38324. case 'scene':
  38325. dependency = this.loadScene( index );
  38326. break;
  38327. case 'node':
  38328. dependency = this.loadNode( index );
  38329. break;
  38330. case 'mesh':
  38331. dependency = this._invokeOne( function ( ext ) {
  38332. return ext.loadMesh && ext.loadMesh( index );
  38333. } );
  38334. break;
  38335. case 'accessor':
  38336. dependency = this.loadAccessor( index );
  38337. break;
  38338. case 'bufferView':
  38339. dependency = this._invokeOne( function ( ext ) {
  38340. return ext.loadBufferView && ext.loadBufferView( index );
  38341. } );
  38342. break;
  38343. case 'buffer':
  38344. dependency = this.loadBuffer( index );
  38345. break;
  38346. case 'material':
  38347. dependency = this._invokeOne( function ( ext ) {
  38348. return ext.loadMaterial && ext.loadMaterial( index );
  38349. } );
  38350. break;
  38351. case 'texture':
  38352. dependency = this._invokeOne( function ( ext ) {
  38353. return ext.loadTexture && ext.loadTexture( index );
  38354. } );
  38355. break;
  38356. case 'skin':
  38357. dependency = this.loadSkin( index );
  38358. break;
  38359. case 'animation':
  38360. dependency = this.loadAnimation( index );
  38361. break;
  38362. case 'camera':
  38363. dependency = this.loadCamera( index );
  38364. break;
  38365. default:
  38366. throw new Error( 'Unknown type: ' + type );
  38367. }
  38368. this.cache.add( cacheKey, dependency );
  38369. }
  38370. return dependency;
  38371. };
  38372. /**
  38373. * Requests all dependencies of the specified type asynchronously, with caching.
  38374. * @param {string} type
  38375. * @return {Promise<Array<Object>>}
  38376. */
  38377. GLTFParser.prototype.getDependencies = function ( type ) {
  38378. var dependencies = this.cache.get( type );
  38379. if ( ! dependencies ) {
  38380. var parser = this;
  38381. var defs = this.json[ type + ( type === 'mesh' ? 'es' : 's' ) ] || [];
  38382. dependencies = Promise.all( defs.map( function ( def, index ) {
  38383. return parser.getDependency( type, index );
  38384. } ) );
  38385. this.cache.add( type, dependencies );
  38386. }
  38387. return dependencies;
  38388. };
  38389. /**
  38390. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#buffers-and-buffer-views
  38391. * @param {number} bufferIndex
  38392. * @return {Promise<ArrayBuffer>}
  38393. */
  38394. GLTFParser.prototype.loadBuffer = function ( bufferIndex ) {
  38395. var bufferDef = this.json.buffers[ bufferIndex ];
  38396. var loader = this.fileLoader;
  38397. if ( bufferDef.type && bufferDef.type !== 'arraybuffer' ) {
  38398. throw new Error( 'THREE.GLTFLoader: ' + bufferDef.type + ' buffer type is not supported.' );
  38399. }
  38400. // If present, GLB container is required to be the first buffer.
  38401. if ( bufferDef.uri === undefined && bufferIndex === 0 ) {
  38402. return Promise.resolve( this.extensions[ EXTENSIONS.KHR_BINARY_GLTF ].body );
  38403. }
  38404. var options = this.options;
  38405. return new Promise( function ( resolve, reject ) {
  38406. loader.load( resolveURL( bufferDef.uri, options.path ), resolve, undefined, function () {
  38407. reject( new Error( 'THREE.GLTFLoader: Failed to load buffer "' + bufferDef.uri + '".' ) );
  38408. } );
  38409. } );
  38410. };
  38411. /**
  38412. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#buffers-and-buffer-views
  38413. * @param {number} bufferViewIndex
  38414. * @return {Promise<ArrayBuffer>}
  38415. */
  38416. GLTFParser.prototype.loadBufferView = function ( bufferViewIndex ) {
  38417. var bufferViewDef = this.json.bufferViews[ bufferViewIndex ];
  38418. return this.getDependency( 'buffer', bufferViewDef.buffer ).then( function ( buffer ) {
  38419. var byteLength = bufferViewDef.byteLength || 0;
  38420. var byteOffset = bufferViewDef.byteOffset || 0;
  38421. return buffer.slice( byteOffset, byteOffset + byteLength );
  38422. } );
  38423. };
  38424. /**
  38425. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#accessors
  38426. * @param {number} accessorIndex
  38427. * @return {Promise<THREE.BufferAttribute|THREE.InterleavedBufferAttribute>}
  38428. */
  38429. GLTFParser.prototype.loadAccessor = function ( accessorIndex ) {
  38430. var parser = this;
  38431. var json = this.json;
  38432. var accessorDef = this.json.accessors[ accessorIndex ];
  38433. if ( accessorDef.bufferView === undefined && accessorDef.sparse === undefined ) {
  38434. // Ignore empty accessors, which may be used to declare runtime
  38435. // information about attributes coming from another source (e.g. Draco
  38436. // compression extension).
  38437. return Promise.resolve( null );
  38438. }
  38439. var pendingBufferViews = [];
  38440. if ( accessorDef.bufferView !== undefined ) {
  38441. pendingBufferViews.push( this.getDependency( 'bufferView', accessorDef.bufferView ) );
  38442. } else {
  38443. pendingBufferViews.push( null );
  38444. }
  38445. if ( accessorDef.sparse !== undefined ) {
  38446. pendingBufferViews.push( this.getDependency( 'bufferView', accessorDef.sparse.indices.bufferView ) );
  38447. pendingBufferViews.push( this.getDependency( 'bufferView', accessorDef.sparse.values.bufferView ) );
  38448. }
  38449. return Promise.all( pendingBufferViews ).then( function ( bufferViews ) {
  38450. var bufferView = bufferViews[ 0 ];
  38451. var itemSize = WEBGL_TYPE_SIZES[ accessorDef.type ];
  38452. var TypedArray = WEBGL_COMPONENT_TYPES[ accessorDef.componentType ];
  38453. // For VEC3: itemSize is 3, elementBytes is 4, itemBytes is 12.
  38454. var elementBytes = TypedArray.BYTES_PER_ELEMENT;
  38455. var itemBytes = elementBytes * itemSize;
  38456. var byteOffset = accessorDef.byteOffset || 0;
  38457. var byteStride = accessorDef.bufferView !== undefined ? json.bufferViews[ accessorDef.bufferView ].byteStride : undefined;
  38458. var normalized = accessorDef.normalized === true;
  38459. var array, bufferAttribute;
  38460. // The buffer is not interleaved if the stride is the item size in bytes.
  38461. if ( byteStride && byteStride !== itemBytes ) {
  38462. // Each "slice" of the buffer, as defined by 'count' elements of 'byteStride' bytes, gets its own InterleavedBuffer
  38463. // This makes sure that IBA.count reflects accessor.count properly
  38464. var ibSlice = Math.floor( byteOffset / byteStride );
  38465. var ibCacheKey = 'InterleavedBuffer:' + accessorDef.bufferView + ':' + accessorDef.componentType + ':' + ibSlice + ':' + accessorDef.count;
  38466. var ib = parser.cache.get( ibCacheKey );
  38467. if ( ! ib ) {
  38468. array = new TypedArray( bufferView, ibSlice * byteStride, accessorDef.count * byteStride / elementBytes );
  38469. // Integer parameters to IB/IBA are in array elements, not bytes.
  38470. ib = new THREE.InterleavedBuffer( array, byteStride / elementBytes );
  38471. parser.cache.add( ibCacheKey, ib );
  38472. }
  38473. bufferAttribute = new THREE.InterleavedBufferAttribute( ib, itemSize, ( byteOffset % byteStride ) / elementBytes, normalized );
  38474. } else {
  38475. if ( bufferView === null ) {
  38476. array = new TypedArray( accessorDef.count * itemSize );
  38477. } else {
  38478. array = new TypedArray( bufferView, byteOffset, accessorDef.count * itemSize );
  38479. }
  38480. bufferAttribute = new THREE.BufferAttribute( array, itemSize, normalized );
  38481. }
  38482. // https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#sparse-accessors
  38483. if ( accessorDef.sparse !== undefined ) {
  38484. var itemSizeIndices = WEBGL_TYPE_SIZES.SCALAR;
  38485. var TypedArrayIndices = WEBGL_COMPONENT_TYPES[ accessorDef.sparse.indices.componentType ];
  38486. var byteOffsetIndices = accessorDef.sparse.indices.byteOffset || 0;
  38487. var byteOffsetValues = accessorDef.sparse.values.byteOffset || 0;
  38488. var sparseIndices = new TypedArrayIndices( bufferViews[ 1 ], byteOffsetIndices, accessorDef.sparse.count * itemSizeIndices );
  38489. var sparseValues = new TypedArray( bufferViews[ 2 ], byteOffsetValues, accessorDef.sparse.count * itemSize );
  38490. if ( bufferView !== null ) {
  38491. // Avoid modifying the original ArrayBuffer, if the bufferView wasn't initialized with zeroes.
  38492. bufferAttribute = new THREE.BufferAttribute( bufferAttribute.array.slice(), bufferAttribute.itemSize, bufferAttribute.normalized );
  38493. }
  38494. for ( var i = 0, il = sparseIndices.length; i < il; i ++ ) {
  38495. var index = sparseIndices[ i ];
  38496. bufferAttribute.setX( index, sparseValues[ i * itemSize ] );
  38497. if ( itemSize >= 2 ) bufferAttribute.setY( index, sparseValues[ i * itemSize + 1 ] );
  38498. if ( itemSize >= 3 ) bufferAttribute.setZ( index, sparseValues[ i * itemSize + 2 ] );
  38499. if ( itemSize >= 4 ) bufferAttribute.setW( index, sparseValues[ i * itemSize + 3 ] );
  38500. if ( itemSize >= 5 ) throw new Error( 'THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute.' );
  38501. }
  38502. }
  38503. return bufferAttribute;
  38504. } );
  38505. };
  38506. /**
  38507. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#textures
  38508. * @param {number} textureIndex
  38509. * @return {Promise<THREE.Texture>}
  38510. */
  38511. GLTFParser.prototype.loadTexture = function ( textureIndex ) {
  38512. var parser = this;
  38513. var json = this.json;
  38514. var options = this.options;
  38515. var textureDef = json.textures[ textureIndex ];
  38516. var textureExtensions = textureDef.extensions || {};
  38517. var source;
  38518. if ( textureExtensions[ EXTENSIONS.MSFT_TEXTURE_DDS ] ) {
  38519. source = json.images[ textureExtensions[ EXTENSIONS.MSFT_TEXTURE_DDS ].source ];
  38520. } else {
  38521. source = json.images[ textureDef.source ];
  38522. }
  38523. var loader;
  38524. if ( source.uri ) {
  38525. loader = options.manager.getHandler( source.uri );
  38526. }
  38527. if ( ! loader ) {
  38528. loader = textureExtensions[ EXTENSIONS.MSFT_TEXTURE_DDS ]
  38529. ? parser.extensions[ EXTENSIONS.MSFT_TEXTURE_DDS ].ddsLoader
  38530. : this.textureLoader;
  38531. }
  38532. return this.loadTextureImage( textureIndex, source, loader );
  38533. };
  38534. GLTFParser.prototype.loadTextureImage = function ( textureIndex, source, loader ) {
  38535. var parser = this;
  38536. var json = this.json;
  38537. var options = this.options;
  38538. var textureDef = json.textures[ textureIndex ];
  38539. var URL = self.URL || self.webkitURL;
  38540. var sourceURI = source.uri;
  38541. var isObjectURL = false;
  38542. var hasAlpha = true;
  38543. if ( source.mimeType === 'image/jpeg' ) hasAlpha = false;
  38544. if ( source.bufferView !== undefined ) {
  38545. // Load binary image data from bufferView, if provided.
  38546. sourceURI = parser.getDependency( 'bufferView', source.bufferView ).then( function ( bufferView ) {
  38547. if ( source.mimeType === 'image/png' ) {
  38548. // Inspect the PNG 'IHDR' chunk to determine whether the image could have an
  38549. // alpha channel. This check is conservative — the image could have an alpha
  38550. // channel with all values == 1, and the indexed type (colorType == 3) only
  38551. // sometimes contains alpha.
  38552. //
  38553. // https://en.wikipedia.org/wiki/Portable_Network_Graphics#File_header
  38554. var colorType = new DataView( bufferView, 25, 1 ).getUint8( 0, false );
  38555. hasAlpha = colorType === 6 || colorType === 4 || colorType === 3;
  38556. }
  38557. isObjectURL = true;
  38558. var blob = new Blob( [ bufferView ], { type: source.mimeType } );
  38559. sourceURI = URL.createObjectURL( blob );
  38560. return sourceURI;
  38561. } );
  38562. }
  38563. return Promise.resolve( sourceURI ).then( function ( sourceURI ) {
  38564. return new Promise( function ( resolve, reject ) {
  38565. var onLoad = resolve;
  38566. if ( loader.isImageBitmapLoader === true ) {
  38567. onLoad = function ( imageBitmap ) {
  38568. resolve( new THREE.CanvasTexture( imageBitmap ) );
  38569. };
  38570. }
  38571. loader.load( resolveURL( sourceURI, options.path ), onLoad, undefined, reject );
  38572. } );
  38573. } ).then( function ( texture ) {
  38574. // Clean up resources and configure Texture.
  38575. if ( isObjectURL === true ) {
  38576. URL.revokeObjectURL( sourceURI );
  38577. }
  38578. texture.flipY = false;
  38579. if ( textureDef.name ) texture.name = textureDef.name;
  38580. // When there is definitely no alpha channel in the texture, set RGBFormat to save space.
  38581. if ( ! hasAlpha ) texture.format = THREE.RGBFormat;
  38582. var samplers = json.samplers || {};
  38583. var sampler = samplers[ textureDef.sampler ] || {};
  38584. texture.magFilter = WEBGL_FILTERS[ sampler.magFilter ] || THREE.LinearFilter;
  38585. texture.minFilter = WEBGL_FILTERS[ sampler.minFilter ] || THREE.LinearMipmapLinearFilter;
  38586. texture.wrapS = WEBGL_WRAPPINGS[ sampler.wrapS ] || THREE.RepeatWrapping;
  38587. texture.wrapT = WEBGL_WRAPPINGS[ sampler.wrapT ] || THREE.RepeatWrapping;
  38588. parser.associations.set( texture, {
  38589. type: 'textures',
  38590. index: textureIndex
  38591. } );
  38592. return texture;
  38593. } );
  38594. };
  38595. /**
  38596. * Asynchronously assigns a texture to the given material parameters.
  38597. * @param {Object} materialParams
  38598. * @param {string} mapName
  38599. * @param {Object} mapDef
  38600. * @return {Promise}
  38601. */
  38602. GLTFParser.prototype.assignTexture = function ( materialParams, mapName, mapDef ) {
  38603. var parser = this;
  38604. return this.getDependency( 'texture', mapDef.index ).then( function ( texture ) {
  38605. // Materials sample aoMap from UV set 1 and other maps from UV set 0 - this can't be configured
  38606. // However, we will copy UV set 0 to UV set 1 on demand for aoMap
  38607. if ( mapDef.texCoord !== undefined && mapDef.texCoord != 0 && ! ( mapName === 'aoMap' && mapDef.texCoord == 1 ) ) {
  38608. console.warn( 'THREE.GLTFLoader: Custom UV set ' + mapDef.texCoord + ' for texture ' + mapName + ' not yet supported.' );
  38609. }
  38610. if ( parser.extensions[ EXTENSIONS.KHR_TEXTURE_TRANSFORM ] ) {
  38611. var transform = mapDef.extensions !== undefined ? mapDef.extensions[ EXTENSIONS.KHR_TEXTURE_TRANSFORM ] : undefined;
  38612. if ( transform ) {
  38613. var gltfReference = parser.associations.get( texture );
  38614. texture = parser.extensions[ EXTENSIONS.KHR_TEXTURE_TRANSFORM ].extendTexture( texture, transform );
  38615. parser.associations.set( texture, gltfReference );
  38616. }
  38617. }
  38618. materialParams[ mapName ] = texture;
  38619. } );
  38620. };
  38621. /**
  38622. * Assigns final material to a Mesh, Line, or Points instance. The instance
  38623. * already has a material (generated from the glTF material options alone)
  38624. * but reuse of the same glTF material may require multiple threejs materials
  38625. * to accomodate different primitive types, defines, etc. New materials will
  38626. * be created if necessary, and reused from a cache.
  38627. * @param {THREE.Object3D} mesh Mesh, Line, or Points instance.
  38628. */
  38629. GLTFParser.prototype.assignFinalMaterial = function ( mesh ) {
  38630. var geometry = mesh.geometry;
  38631. var material = mesh.material;
  38632. var useVertexTangents = geometry.attributes.tangent !== undefined;
  38633. var useVertexColors = geometry.attributes.color !== undefined;
  38634. var useFlatShading = geometry.attributes.normal === undefined;
  38635. var useSkinning = mesh.isSkinnedMesh === true;
  38636. var useMorphTargets = Object.keys( geometry.morphAttributes ).length > 0;
  38637. var useMorphNormals = useMorphTargets && geometry.morphAttributes.normal !== undefined;
  38638. if ( mesh.isPoints ) {
  38639. var cacheKey = 'PointsMaterial:' + material.uuid;
  38640. var pointsMaterial = this.cache.get( cacheKey );
  38641. if ( ! pointsMaterial ) {
  38642. pointsMaterial = new THREE.PointsMaterial();
  38643. THREE.Material.prototype.copy.call( pointsMaterial, material );
  38644. pointsMaterial.color.copy( material.color );
  38645. pointsMaterial.map = material.map;
  38646. pointsMaterial.sizeAttenuation = false; // glTF spec says points should be 1px
  38647. this.cache.add( cacheKey, pointsMaterial );
  38648. }
  38649. material = pointsMaterial;
  38650. } else if ( mesh.isLine ) {
  38651. var cacheKey = 'LineBasicMaterial:' + material.uuid;
  38652. var lineMaterial = this.cache.get( cacheKey );
  38653. if ( ! lineMaterial ) {
  38654. lineMaterial = new THREE.LineBasicMaterial();
  38655. THREE.Material.prototype.copy.call( lineMaterial, material );
  38656. lineMaterial.color.copy( material.color );
  38657. this.cache.add( cacheKey, lineMaterial );
  38658. }
  38659. material = lineMaterial;
  38660. }
  38661. // Clone the material if it will be modified
  38662. if ( useVertexTangents || useVertexColors || useFlatShading || useSkinning || useMorphTargets ) {
  38663. var cacheKey = 'ClonedMaterial:' + material.uuid + ':';
  38664. if ( material.isGLTFSpecularGlossinessMaterial ) cacheKey += 'specular-glossiness:';
  38665. if ( useSkinning ) cacheKey += 'skinning:';
  38666. if ( useVertexTangents ) cacheKey += 'vertex-tangents:';
  38667. if ( useVertexColors ) cacheKey += 'vertex-colors:';
  38668. if ( useFlatShading ) cacheKey += 'flat-shading:';
  38669. if ( useMorphTargets ) cacheKey += 'morph-targets:';
  38670. if ( useMorphNormals ) cacheKey += 'morph-normals:';
  38671. var cachedMaterial = this.cache.get( cacheKey );
  38672. if ( ! cachedMaterial ) {
  38673. cachedMaterial = material.clone();
  38674. if ( useSkinning ) cachedMaterial.skinning = true;
  38675. if ( useVertexColors ) cachedMaterial.vertexColors = true;
  38676. if ( useFlatShading ) cachedMaterial.flatShading = true;
  38677. if ( useMorphTargets ) cachedMaterial.morphTargets = true;
  38678. if ( useMorphNormals ) cachedMaterial.morphNormals = true;
  38679. if ( useVertexTangents ) {
  38680. cachedMaterial.vertexTangents = true;
  38681. // https://github.com/mrdoob/three.js/issues/11438#issuecomment-507003995
  38682. if ( material.normalScale ) material.normalScale.y *= -1;
  38683. if ( material.clearcoatNormalScale ) material.clearcoatNormalScale.y *= -1;
  38684. }
  38685. this.cache.add( cacheKey, cachedMaterial );
  38686. this.associations.set( cachedMaterial, this.associations.get( material ) );
  38687. }
  38688. material = cachedMaterial;
  38689. }
  38690. // workarounds for mesh and geometry
  38691. if ( material.aoMap && geometry.attributes.uv2 === undefined && geometry.attributes.uv !== undefined ) {
  38692. geometry.setAttribute( 'uv2', geometry.attributes.uv );
  38693. }
  38694. mesh.material = material;
  38695. };
  38696. GLTFParser.prototype.getMaterialType = function ( /* materialIndex */ ) {
  38697. return THREE.MeshStandardMaterial;
  38698. };
  38699. /**
  38700. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#materials
  38701. * @param {number} materialIndex
  38702. * @return {Promise<THREE.Material>}
  38703. */
  38704. GLTFParser.prototype.loadMaterial = function ( materialIndex ) {
  38705. var parser = this;
  38706. var json = this.json;
  38707. var extensions = this.extensions;
  38708. var materialDef = json.materials[ materialIndex ];
  38709. var materialType;
  38710. var materialParams = {};
  38711. var materialExtensions = materialDef.extensions || {};
  38712. var pending = [];
  38713. if ( materialExtensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ] ) {
  38714. var sgExtension = extensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ];
  38715. materialType = sgExtension.getMaterialType();
  38716. pending.push( sgExtension.extendParams( materialParams, materialDef, parser ) );
  38717. } else if ( materialExtensions[ EXTENSIONS.KHR_MATERIALS_UNLIT ] ) {
  38718. var kmuExtension = extensions[ EXTENSIONS.KHR_MATERIALS_UNLIT ];
  38719. materialType = kmuExtension.getMaterialType();
  38720. pending.push( kmuExtension.extendParams( materialParams, materialDef, parser ) );
  38721. } else {
  38722. // Specification:
  38723. // https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#metallic-roughness-material
  38724. var metallicRoughness = materialDef.pbrMetallicRoughness || {};
  38725. materialParams.color = new THREE.Color( 1.0, 1.0, 1.0 );
  38726. materialParams.opacity = 1.0;
  38727. if ( Array.isArray( metallicRoughness.baseColorFactor ) ) {
  38728. var array = metallicRoughness.baseColorFactor;
  38729. materialParams.color.fromArray( array );
  38730. materialParams.opacity = array[ 3 ];
  38731. }
  38732. if ( metallicRoughness.baseColorTexture !== undefined ) {
  38733. pending.push( parser.assignTexture( materialParams, 'map', metallicRoughness.baseColorTexture ) );
  38734. }
  38735. materialParams.metalness = metallicRoughness.metallicFactor !== undefined ? metallicRoughness.metallicFactor : 1.0;
  38736. materialParams.roughness = metallicRoughness.roughnessFactor !== undefined ? metallicRoughness.roughnessFactor : 1.0;
  38737. if ( metallicRoughness.metallicRoughnessTexture !== undefined ) {
  38738. pending.push( parser.assignTexture( materialParams, 'metalnessMap', metallicRoughness.metallicRoughnessTexture ) );
  38739. pending.push( parser.assignTexture( materialParams, 'roughnessMap', metallicRoughness.metallicRoughnessTexture ) );
  38740. }
  38741. materialType = this._invokeOne( function ( ext ) {
  38742. return ext.getMaterialType && ext.getMaterialType( materialIndex );
  38743. } );
  38744. pending.push( Promise.all( this._invokeAll( function ( ext ) {
  38745. return ext.extendMaterialParams && ext.extendMaterialParams( materialIndex, materialParams );
  38746. } ) ) );
  38747. }
  38748. if ( materialDef.doubleSided === true ) {
  38749. materialParams.side = THREE.DoubleSide;
  38750. }
  38751. var alphaMode = materialDef.alphaMode || ALPHA_MODES.OPAQUE;
  38752. if ( alphaMode === ALPHA_MODES.BLEND ) {
  38753. materialParams.transparent = true;
  38754. // See: https://github.com/mrdoob/three.js/issues/17706
  38755. materialParams.depthWrite = false;
  38756. } else {
  38757. materialParams.transparent = false;
  38758. if ( alphaMode === ALPHA_MODES.MASK ) {
  38759. materialParams.alphaTest = materialDef.alphaCutoff !== undefined ? materialDef.alphaCutoff : 0.5;
  38760. }
  38761. }
  38762. if ( materialDef.normalTexture !== undefined && materialType !== THREE.MeshBasicMaterial ) {
  38763. pending.push( parser.assignTexture( materialParams, 'normalMap', materialDef.normalTexture ) );
  38764. // https://github.com/mrdoob/three.js/issues/11438#issuecomment-507003995
  38765. materialParams.normalScale = new THREE.Vector2( 1, -1 );
  38766. if ( materialDef.normalTexture.scale !== undefined ) {
  38767. materialParams.normalScale.set( materialDef.normalTexture.scale, -materialDef.normalTexture.scale );
  38768. }
  38769. }
  38770. if ( materialDef.occlusionTexture !== undefined && materialType !== THREE.MeshBasicMaterial ) {
  38771. pending.push( parser.assignTexture( materialParams, 'aoMap', materialDef.occlusionTexture ) );
  38772. if ( materialDef.occlusionTexture.strength !== undefined ) {
  38773. materialParams.aoMapIntensity = materialDef.occlusionTexture.strength;
  38774. }
  38775. }
  38776. if ( materialDef.emissiveFactor !== undefined && materialType !== THREE.MeshBasicMaterial ) {
  38777. materialParams.emissive = new THREE.Color().fromArray( materialDef.emissiveFactor );
  38778. }
  38779. if ( materialDef.emissiveTexture !== undefined && materialType !== THREE.MeshBasicMaterial ) {
  38780. pending.push( parser.assignTexture( materialParams, 'emissiveMap', materialDef.emissiveTexture ) );
  38781. }
  38782. return Promise.all( pending ).then( function () {
  38783. var material;
  38784. if ( materialType === GLTFMeshStandardSGMaterial ) {
  38785. material = extensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ].createMaterial( materialParams );
  38786. } else {
  38787. material = new materialType( materialParams );
  38788. }
  38789. if ( materialDef.name ) material.name = materialDef.name;
  38790. // baseColorTexture, emissiveTexture, and specularGlossinessTexture use sRGB encoding.
  38791. if ( material.map ) material.map.encoding = THREE.sRGBEncoding;
  38792. if ( material.emissiveMap ) material.emissiveMap.encoding = THREE.sRGBEncoding;
  38793. assignExtrasToUserData( material, materialDef );
  38794. parser.associations.set( material, { type: 'materials', index: materialIndex } );
  38795. if ( materialDef.extensions ) addUnknownExtensionsToUserData( extensions, material, materialDef );
  38796. return material;
  38797. } );
  38798. };
  38799. /** When Object3D instances are targeted by animation, they need unique names. */
  38800. GLTFParser.prototype.createUniqueName = function ( originalName ) {
  38801. var sanitizedName = THREE.PropertyBinding.sanitizeNodeName( originalName || '' );
  38802. var name = sanitizedName;
  38803. for ( var i = 1; this.nodeNamesUsed[ name ]; ++ i ) {
  38804. name = sanitizedName + '_' + i;
  38805. }
  38806. this.nodeNamesUsed[ name ] = true;
  38807. return name;
  38808. };
  38809. /**
  38810. * @param {THREE.BufferGeometry} geometry
  38811. * @param {GLTF.Primitive} primitiveDef
  38812. * @param {GLTFParser} parser
  38813. */
  38814. function computeBounds( geometry, primitiveDef, parser ) {
  38815. var attributes = primitiveDef.attributes;
  38816. var box = new THREE.Box3();
  38817. if ( attributes.POSITION !== undefined ) {
  38818. var accessor = parser.json.accessors[ attributes.POSITION ];
  38819. var min = accessor.min;
  38820. var max = accessor.max;
  38821. // glTF requires 'min' and 'max', but VRM (which extends glTF) currently ignores that requirement.
  38822. if ( min !== undefined && max !== undefined ) {
  38823. box.set(
  38824. new THREE.Vector3( min[ 0 ], min[ 1 ], min[ 2 ] ),
  38825. new THREE.Vector3( max[ 0 ], max[ 1 ], max[ 2 ] ) );
  38826. } else {
  38827. console.warn( 'THREE.GLTFLoader: Missing min/max properties for accessor POSITION.' );
  38828. return;
  38829. }
  38830. } else {
  38831. return;
  38832. }
  38833. var targets = primitiveDef.targets;
  38834. if ( targets !== undefined ) {
  38835. var maxDisplacement = new THREE.Vector3();
  38836. var vector = new THREE.Vector3();
  38837. for ( var i = 0, il = targets.length; i < il; i ++ ) {
  38838. var target = targets[ i ];
  38839. if ( target.POSITION !== undefined ) {
  38840. var accessor = parser.json.accessors[ target.POSITION ];
  38841. var min = accessor.min;
  38842. var max = accessor.max;
  38843. // glTF requires 'min' and 'max', but VRM (which extends glTF) currently ignores that requirement.
  38844. if ( min !== undefined && max !== undefined ) {
  38845. // we need to get max of absolute components because target weight is [-1,1]
  38846. vector.setX( Math.max( Math.abs( min[ 0 ] ), Math.abs( max[ 0 ] ) ) );
  38847. vector.setY( Math.max( Math.abs( min[ 1 ] ), Math.abs( max[ 1 ] ) ) );
  38848. vector.setZ( Math.max( Math.abs( min[ 2 ] ), Math.abs( max[ 2 ] ) ) );
  38849. // Note: this assumes that the sum of all weights is at most 1. This isn't quite correct - it's more conservative
  38850. // to assume that each target can have a max weight of 1. However, for some use cases - notably, when morph targets
  38851. // are used to implement key-frame animations and as such only two are active at a time - this results in very large
  38852. // boxes. So for now we make a box that's sometimes a touch too small but is hopefully mostly of reasonable size.
  38853. maxDisplacement.max( vector );
  38854. } else {
  38855. console.warn( 'THREE.GLTFLoader: Missing min/max properties for accessor POSITION.' );
  38856. }
  38857. }
  38858. }
  38859. // As per comment above this box isn't conservative, but has a reasonable size for a very large number of morph targets.
  38860. box.expandByVector( maxDisplacement );
  38861. }
  38862. geometry.boundingBox = box;
  38863. var sphere = new THREE.Sphere();
  38864. box.getCenter( sphere.center );
  38865. sphere.radius = box.min.distanceTo( box.max ) / 2;
  38866. geometry.boundingSphere = sphere;
  38867. }
  38868. /**
  38869. * @param {THREE.BufferGeometry} geometry
  38870. * @param {GLTF.Primitive} primitiveDef
  38871. * @param {GLTFParser} parser
  38872. * @return {Promise<THREE.BufferGeometry>}
  38873. */
  38874. function addPrimitiveAttributes( geometry, primitiveDef, parser ) {
  38875. var attributes = primitiveDef.attributes;
  38876. var pending = [];
  38877. function assignAttributeAccessor( accessorIndex, attributeName ) {
  38878. return parser.getDependency( 'accessor', accessorIndex )
  38879. .then( function ( accessor ) {
  38880. geometry.setAttribute( attributeName, accessor );
  38881. } );
  38882. }
  38883. for ( var gltfAttributeName in attributes ) {
  38884. var threeAttributeName = ATTRIBUTES[ gltfAttributeName ] || gltfAttributeName.toLowerCase();
  38885. // Skip attributes already provided by e.g. Draco extension.
  38886. if ( threeAttributeName in geometry.attributes ) continue;
  38887. pending.push( assignAttributeAccessor( attributes[ gltfAttributeName ], threeAttributeName ) );
  38888. }
  38889. if ( primitiveDef.indices !== undefined && ! geometry.index ) {
  38890. var accessor = parser.getDependency( 'accessor', primitiveDef.indices ).then( function ( accessor ) {
  38891. geometry.setIndex( accessor );
  38892. } );
  38893. pending.push( accessor );
  38894. }
  38895. assignExtrasToUserData( geometry, primitiveDef );
  38896. computeBounds( geometry, primitiveDef, parser );
  38897. return Promise.all( pending ).then( function () {
  38898. return primitiveDef.targets !== undefined
  38899. ? addMorphTargets( geometry, primitiveDef.targets, parser )
  38900. : geometry;
  38901. } );
  38902. }
  38903. /**
  38904. * @param {THREE.BufferGeometry} geometry
  38905. * @param {Number} drawMode
  38906. * @return {THREE.BufferGeometry}
  38907. */
  38908. function toTrianglesDrawMode( geometry, drawMode ) {
  38909. var index = geometry.getIndex();
  38910. // generate index if not present
  38911. if ( index === null ) {
  38912. var indices = [];
  38913. var position = geometry.getAttribute( 'position' );
  38914. if ( position !== undefined ) {
  38915. for ( var i = 0; i < position.count; i ++ ) {
  38916. indices.push( i );
  38917. }
  38918. geometry.setIndex( indices );
  38919. index = geometry.getIndex();
  38920. } else {
  38921. console.error( 'THREE.GLTFLoader.toTrianglesDrawMode(): Undefined position attribute. Processing not possible.' );
  38922. return geometry;
  38923. }
  38924. }
  38925. //
  38926. var numberOfTriangles = index.count - 2;
  38927. var newIndices = [];
  38928. if ( drawMode === THREE.TriangleFanDrawMode ) {
  38929. // gl.TRIANGLE_FAN
  38930. for ( var i = 1; i <= numberOfTriangles; i ++ ) {
  38931. newIndices.push( index.getX( 0 ) );
  38932. newIndices.push( index.getX( i ) );
  38933. newIndices.push( index.getX( i + 1 ) );
  38934. }
  38935. } else {
  38936. // gl.TRIANGLE_STRIP
  38937. for ( var i = 0; i < numberOfTriangles; i ++ ) {
  38938. if ( i % 2 === 0 ) {
  38939. newIndices.push( index.getX( i ) );
  38940. newIndices.push( index.getX( i + 1 ) );
  38941. newIndices.push( index.getX( i + 2 ) );
  38942. } else {
  38943. newIndices.push( index.getX( i + 2 ) );
  38944. newIndices.push( index.getX( i + 1 ) );
  38945. newIndices.push( index.getX( i ) );
  38946. }
  38947. }
  38948. }
  38949. if ( ( newIndices.length / 3 ) !== numberOfTriangles ) {
  38950. console.error( 'THREE.GLTFLoader.toTrianglesDrawMode(): Unable to generate correct amount of triangles.' );
  38951. }
  38952. // build final geometry
  38953. var newGeometry = geometry.clone();
  38954. newGeometry.setIndex( newIndices );
  38955. return newGeometry;
  38956. }
  38957. /**
  38958. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#geometry
  38959. *
  38960. * Creates BufferGeometries from primitives.
  38961. *
  38962. * @param {Array<GLTF.Primitive>} primitives
  38963. * @return {Promise<Array<THREE.BufferGeometry>>}
  38964. */
  38965. GLTFParser.prototype.loadGeometries = function ( primitives ) {
  38966. var parser = this;
  38967. var extensions = this.extensions;
  38968. var cache = this.primitiveCache;
  38969. function createDracoPrimitive( primitive ) {
  38970. return extensions[ EXTENSIONS.KHR_DRACO_MESH_COMPRESSION ]
  38971. .decodePrimitive( primitive, parser )
  38972. .then( function ( geometry ) {
  38973. return addPrimitiveAttributes( geometry, primitive, parser );
  38974. } );
  38975. }
  38976. var pending = [];
  38977. for ( var i = 0, il = primitives.length; i < il; i ++ ) {
  38978. var primitive = primitives[ i ];
  38979. var cacheKey = createPrimitiveKey( primitive );
  38980. // See if we've already created this geometry
  38981. var cached = cache[ cacheKey ];
  38982. if ( cached ) {
  38983. // Use the cached geometry if it exists
  38984. pending.push( cached.promise );
  38985. } else {
  38986. var geometryPromise;
  38987. if ( primitive.extensions && primitive.extensions[ EXTENSIONS.KHR_DRACO_MESH_COMPRESSION ] ) {
  38988. // Use DRACO geometry if available
  38989. geometryPromise = createDracoPrimitive( primitive );
  38990. } else {
  38991. // Otherwise create a new geometry
  38992. geometryPromise = addPrimitiveAttributes( new THREE.BufferGeometry(), primitive, parser );
  38993. }
  38994. // Cache this geometry
  38995. cache[ cacheKey ] = { primitive: primitive, promise: geometryPromise };
  38996. pending.push( geometryPromise );
  38997. }
  38998. }
  38999. return Promise.all( pending );
  39000. };
  39001. /**
  39002. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#meshes
  39003. * @param {number} meshIndex
  39004. * @return {Promise<THREE.Group|THREE.Mesh|THREE.SkinnedMesh>}
  39005. */
  39006. GLTFParser.prototype.loadMesh = function ( meshIndex ) {
  39007. var parser = this;
  39008. var json = this.json;
  39009. var extensions = this.extensions;
  39010. var meshDef = json.meshes[ meshIndex ];
  39011. var primitives = meshDef.primitives;
  39012. var pending = [];
  39013. for ( var i = 0, il = primitives.length; i < il; i ++ ) {
  39014. var material = primitives[ i ].material === undefined
  39015. ? createDefaultMaterial( this.cache )
  39016. : this.getDependency( 'material', primitives[ i ].material );
  39017. pending.push( material );
  39018. }
  39019. pending.push( parser.loadGeometries( primitives ) );
  39020. return Promise.all( pending ).then( function ( results ) {
  39021. var materials = results.slice( 0, results.length - 1 );
  39022. var geometries = results[ results.length - 1 ];
  39023. var meshes = [];
  39024. for ( var i = 0, il = geometries.length; i < il; i ++ ) {
  39025. var geometry = geometries[ i ];
  39026. var primitive = primitives[ i ];
  39027. // 1. create Mesh
  39028. var mesh;
  39029. var material = materials[ i ];
  39030. if ( primitive.mode === WEBGL_CONSTANTS.TRIANGLES ||
  39031. primitive.mode === WEBGL_CONSTANTS.TRIANGLE_STRIP ||
  39032. primitive.mode === WEBGL_CONSTANTS.TRIANGLE_FAN ||
  39033. primitive.mode === undefined ) {
  39034. // .isSkinnedMesh isn't in glTF spec. See ._markDefs()
  39035. mesh = meshDef.isSkinnedMesh === true
  39036. ? new THREE.SkinnedMesh( geometry, material )
  39037. : new THREE.Mesh( geometry, material );
  39038. // Fix double sided rendered models on certain mobile devices, see https://github.com/mrdoob/three.js/issues/20997#issuecomment-756082184
  39039. if ( material.isMeshStandardMaterial === true &&
  39040. material.side === THREE.DoubleSide &&
  39041. geometry.getIndex() !== null &&
  39042. geometry.hasAttribute( 'position' ) === true &&
  39043. geometry.hasAttribute( 'normal' ) === true &&
  39044. geometry.hasAttribute( 'uv' ) === true &&
  39045. geometry.hasAttribute( 'tangent' ) === false ) {
  39046. geometry.computeTangents();
  39047. material.vertexTangents = true;
  39048. }
  39049. if ( mesh.isSkinnedMesh === true && ! mesh.geometry.attributes.skinWeight.normalized ) {
  39050. // we normalize floating point skin weight array to fix malformed assets (see #15319)
  39051. // it's important to skip this for non-float32 data since normalizeSkinWeights assumes non-normalized inputs
  39052. mesh.normalizeSkinWeights();
  39053. }
  39054. if ( primitive.mode === WEBGL_CONSTANTS.TRIANGLE_STRIP ) {
  39055. mesh.geometry = toTrianglesDrawMode( mesh.geometry, THREE.TriangleStripDrawMode );
  39056. } else if ( primitive.mode === WEBGL_CONSTANTS.TRIANGLE_FAN ) {
  39057. mesh.geometry = toTrianglesDrawMode( mesh.geometry, THREE.TriangleFanDrawMode );
  39058. }
  39059. } else if ( primitive.mode === WEBGL_CONSTANTS.LINES ) {
  39060. mesh = new THREE.LineSegments( geometry, material );
  39061. } else if ( primitive.mode === WEBGL_CONSTANTS.LINE_STRIP ) {
  39062. mesh = new THREE.Line( geometry, material );
  39063. } else if ( primitive.mode === WEBGL_CONSTANTS.LINE_LOOP ) {
  39064. mesh = new THREE.LineLoop( geometry, material );
  39065. } else if ( primitive.mode === WEBGL_CONSTANTS.POINTS ) {
  39066. mesh = new THREE.Points( geometry, material );
  39067. } else {
  39068. throw new Error( 'THREE.GLTFLoader: Primitive mode unsupported: ' + primitive.mode );
  39069. }
  39070. if ( Object.keys( mesh.geometry.morphAttributes ).length > 0 ) {
  39071. updateMorphTargets( mesh, meshDef );
  39072. }
  39073. mesh.name = parser.createUniqueName( meshDef.name || ( 'mesh_' + meshIndex ) );
  39074. assignExtrasToUserData( mesh, meshDef );
  39075. if ( primitive.extensions ) addUnknownExtensionsToUserData( extensions, mesh, primitive );
  39076. parser.assignFinalMaterial( mesh );
  39077. meshes.push( mesh );
  39078. }
  39079. if ( meshes.length === 1 ) {
  39080. return meshes[ 0 ];
  39081. }
  39082. var group = new THREE.Group();
  39083. for ( var i = 0, il = meshes.length; i < il; i ++ ) {
  39084. group.add( meshes[ i ] );
  39085. }
  39086. return group;
  39087. } );
  39088. };
  39089. /**
  39090. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#cameras
  39091. * @param {number} cameraIndex
  39092. * @return {Promise<THREE.Camera>}
  39093. */
  39094. GLTFParser.prototype.loadCamera = function ( cameraIndex ) {
  39095. var camera;
  39096. var cameraDef = this.json.cameras[ cameraIndex ];
  39097. var params = cameraDef[ cameraDef.type ];
  39098. if ( ! params ) {
  39099. console.warn( 'THREE.GLTFLoader: Missing camera parameters.' );
  39100. return;
  39101. }
  39102. if ( cameraDef.type === 'perspective' ) {
  39103. camera = new THREE.PerspectiveCamera( THREE.MathUtils.radToDeg( params.yfov ), params.aspectRatio || 1, params.znear || 1, params.zfar || 2e6 );
  39104. } else if ( cameraDef.type === 'orthographic' ) {
  39105. camera = new THREE.OrthographicCamera( - params.xmag, params.xmag, params.ymag, - params.ymag, params.znear, params.zfar );
  39106. }
  39107. if ( cameraDef.name ) camera.name = this.createUniqueName( cameraDef.name );
  39108. assignExtrasToUserData( camera, cameraDef );
  39109. return Promise.resolve( camera );
  39110. };
  39111. /**
  39112. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins
  39113. * @param {number} skinIndex
  39114. * @return {Promise<Object>}
  39115. */
  39116. GLTFParser.prototype.loadSkin = function ( skinIndex ) {
  39117. var skinDef = this.json.skins[ skinIndex ];
  39118. var skinEntry = { joints: skinDef.joints };
  39119. if ( skinDef.inverseBindMatrices === undefined ) {
  39120. return Promise.resolve( skinEntry );
  39121. }
  39122. return this.getDependency( 'accessor', skinDef.inverseBindMatrices ).then( function ( accessor ) {
  39123. skinEntry.inverseBindMatrices = accessor;
  39124. return skinEntry;
  39125. } );
  39126. };
  39127. /**
  39128. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#animations
  39129. * @param {number} animationIndex
  39130. * @return {Promise<THREE.AnimationClip>}
  39131. */
  39132. GLTFParser.prototype.loadAnimation = function ( animationIndex ) {
  39133. var json = this.json;
  39134. var animationDef = json.animations[ animationIndex ];
  39135. var pendingNodes = [];
  39136. var pendingInputAccessors = [];
  39137. var pendingOutputAccessors = [];
  39138. var pendingSamplers = [];
  39139. var pendingTargets = [];
  39140. for ( var i = 0, il = animationDef.channels.length; i < il; i ++ ) {
  39141. var channel = animationDef.channels[ i ];
  39142. var sampler = animationDef.samplers[ channel.sampler ];
  39143. var target = channel.target;
  39144. var name = target.node !== undefined ? target.node : target.id; // NOTE: target.id is deprecated.
  39145. var input = animationDef.parameters !== undefined ? animationDef.parameters[ sampler.input ] : sampler.input;
  39146. var output = animationDef.parameters !== undefined ? animationDef.parameters[ sampler.output ] : sampler.output;
  39147. pendingNodes.push( this.getDependency( 'node', name ) );
  39148. pendingInputAccessors.push( this.getDependency( 'accessor', input ) );
  39149. pendingOutputAccessors.push( this.getDependency( 'accessor', output ) );
  39150. pendingSamplers.push( sampler );
  39151. pendingTargets.push( target );
  39152. }
  39153. return Promise.all( [
  39154. Promise.all( pendingNodes ),
  39155. Promise.all( pendingInputAccessors ),
  39156. Promise.all( pendingOutputAccessors ),
  39157. Promise.all( pendingSamplers ),
  39158. Promise.all( pendingTargets )
  39159. ] ).then( function ( dependencies ) {
  39160. var nodes = dependencies[ 0 ];
  39161. var inputAccessors = dependencies[ 1 ];
  39162. var outputAccessors = dependencies[ 2 ];
  39163. var samplers = dependencies[ 3 ];
  39164. var targets = dependencies[ 4 ];
  39165. var tracks = [];
  39166. for ( var i = 0, il = nodes.length; i < il; i ++ ) {
  39167. var node = nodes[ i ];
  39168. var inputAccessor = inputAccessors[ i ];
  39169. var outputAccessor = outputAccessors[ i ];
  39170. var sampler = samplers[ i ];
  39171. var target = targets[ i ];
  39172. if ( node === undefined ) continue;
  39173. node.updateMatrix();
  39174. node.matrixAutoUpdate = true;
  39175. var TypedKeyframeTrack;
  39176. switch ( PATH_PROPERTIES[ target.path ] ) {
  39177. case PATH_PROPERTIES.weights:
  39178. TypedKeyframeTrack = THREE.NumberKeyframeTrack;
  39179. break;
  39180. case PATH_PROPERTIES.rotation:
  39181. TypedKeyframeTrack = THREE.QuaternionKeyframeTrack;
  39182. break;
  39183. case PATH_PROPERTIES.position:
  39184. case PATH_PROPERTIES.scale:
  39185. default:
  39186. TypedKeyframeTrack = THREE.VectorKeyframeTrack;
  39187. break;
  39188. }
  39189. var targetName = node.name ? node.name : node.uuid;
  39190. var interpolation = sampler.interpolation !== undefined ? INTERPOLATION[ sampler.interpolation ] : THREE.InterpolateLinear;
  39191. var targetNames = [];
  39192. if ( PATH_PROPERTIES[ target.path ] === PATH_PROPERTIES.weights ) {
  39193. // Node may be a THREE.Group (glTF mesh with several primitives) or a THREE.Mesh.
  39194. node.traverse( function ( object ) {
  39195. if ( object.isMesh === true && object.morphTargetInfluences ) {
  39196. targetNames.push( object.name ? object.name : object.uuid );
  39197. }
  39198. } );
  39199. } else {
  39200. targetNames.push( targetName );
  39201. }
  39202. var outputArray = outputAccessor.array;
  39203. if ( outputAccessor.normalized ) {
  39204. var scale;
  39205. if ( outputArray.constructor === Int8Array ) {
  39206. scale = 1 / 127;
  39207. } else if ( outputArray.constructor === Uint8Array ) {
  39208. scale = 1 / 255;
  39209. } else if ( outputArray.constructor == Int16Array ) {
  39210. scale = 1 / 32767;
  39211. } else if ( outputArray.constructor === Uint16Array ) {
  39212. scale = 1 / 65535;
  39213. } else {
  39214. throw new Error( 'THREE.GLTFLoader: Unsupported output accessor component type.' );
  39215. }
  39216. var scaled = new Float32Array( outputArray.length );
  39217. for ( var j = 0, jl = outputArray.length; j < jl; j ++ ) {
  39218. scaled[ j ] = outputArray[ j ] * scale;
  39219. }
  39220. outputArray = scaled;
  39221. }
  39222. for ( var j = 0, jl = targetNames.length; j < jl; j ++ ) {
  39223. var track = new TypedKeyframeTrack(
  39224. targetNames[ j ] + '.' + PATH_PROPERTIES[ target.path ],
  39225. inputAccessor.array,
  39226. outputArray,
  39227. interpolation
  39228. );
  39229. // Override interpolation with custom factory method.
  39230. if ( sampler.interpolation === 'CUBICSPLINE' ) {
  39231. track.createInterpolant = function InterpolantFactoryMethodGLTFCubicSpline( result ) {
  39232. // A CUBICSPLINE keyframe in glTF has three output values for each input value,
  39233. // representing inTangent, splineVertex, and outTangent. As a result, track.getValueSize()
  39234. // must be divided by three to get the interpolant's sampleSize argument.
  39235. return new GLTFCubicSplineInterpolant( this.times, this.values, this.getValueSize() / 3, result );
  39236. };
  39237. // Mark as CUBICSPLINE. `track.getInterpolation()` doesn't support custom interpolants.
  39238. track.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline = true;
  39239. }
  39240. tracks.push( track );
  39241. }
  39242. }
  39243. var name = animationDef.name ? animationDef.name : 'animation_' + animationIndex;
  39244. return new THREE.AnimationClip( name, undefined, tracks );
  39245. } );
  39246. };
  39247. /**
  39248. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#nodes-and-hierarchy
  39249. * @param {number} nodeIndex
  39250. * @return {Promise<THREE.Object3D>}
  39251. */
  39252. GLTFParser.prototype.loadNode = function ( nodeIndex ) {
  39253. var json = this.json;
  39254. var extensions = this.extensions;
  39255. var parser = this;
  39256. var nodeDef = json.nodes[ nodeIndex ];
  39257. // reserve node's name before its dependencies, so the root has the intended name.
  39258. var nodeName = nodeDef.name ? parser.createUniqueName( nodeDef.name ) : '';
  39259. return ( function () {
  39260. var pending = [];
  39261. if ( nodeDef.mesh !== undefined ) {
  39262. pending.push( parser.getDependency( 'mesh', nodeDef.mesh ).then( function ( mesh ) {
  39263. var node = parser._getNodeRef( parser.meshCache, nodeDef.mesh, mesh );
  39264. // if weights are provided on the node, override weights on the mesh.
  39265. if ( nodeDef.weights !== undefined ) {
  39266. node.traverse( function ( o ) {
  39267. if ( ! o.isMesh ) return;
  39268. for ( var i = 0, il = nodeDef.weights.length; i < il; i ++ ) {
  39269. o.morphTargetInfluences[ i ] = nodeDef.weights[ i ];
  39270. }
  39271. } );
  39272. }
  39273. return node;
  39274. } ) );
  39275. }
  39276. if ( nodeDef.camera !== undefined ) {
  39277. pending.push( parser.getDependency( 'camera', nodeDef.camera ).then( function ( camera ) {
  39278. return parser._getNodeRef( parser.cameraCache, nodeDef.camera, camera );
  39279. } ) );
  39280. }
  39281. parser._invokeAll( function ( ext ) {
  39282. return ext.createNodeAttachment && ext.createNodeAttachment( nodeIndex );
  39283. } ).forEach( function ( promise ) {
  39284. pending.push( promise );
  39285. } );
  39286. return Promise.all( pending );
  39287. }() ).then( function ( objects ) {
  39288. var node;
  39289. // .isBone isn't in glTF spec. See ._markDefs
  39290. if ( nodeDef.isBone === true ) {
  39291. node = new THREE.Bone();
  39292. } else if ( objects.length > 1 ) {
  39293. node = new THREE.Group();
  39294. } else if ( objects.length === 1 ) {
  39295. node = objects[ 0 ];
  39296. } else {
  39297. node = new THREE.Object3D();
  39298. }
  39299. if ( node !== objects[ 0 ] ) {
  39300. for ( var i = 0, il = objects.length; i < il; i ++ ) {
  39301. node.add( objects[ i ] );
  39302. }
  39303. }
  39304. if ( nodeDef.name ) {
  39305. node.userData.name = nodeDef.name;
  39306. node.name = nodeName;
  39307. }
  39308. assignExtrasToUserData( node, nodeDef );
  39309. if ( nodeDef.extensions ) addUnknownExtensionsToUserData( extensions, node, nodeDef );
  39310. if ( nodeDef.matrix !== undefined ) {
  39311. var matrix = new THREE.Matrix4();
  39312. matrix.fromArray( nodeDef.matrix );
  39313. node.applyMatrix4( matrix );
  39314. } else {
  39315. if ( nodeDef.translation !== undefined ) {
  39316. node.position.fromArray( nodeDef.translation );
  39317. }
  39318. if ( nodeDef.rotation !== undefined ) {
  39319. node.quaternion.fromArray( nodeDef.rotation );
  39320. }
  39321. if ( nodeDef.scale !== undefined ) {
  39322. node.scale.fromArray( nodeDef.scale );
  39323. }
  39324. }
  39325. parser.associations.set( node, { type: 'nodes', index: nodeIndex } );
  39326. return node;
  39327. } );
  39328. };
  39329. /**
  39330. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#scenes
  39331. * @param {number} sceneIndex
  39332. * @return {Promise<THREE.Group>}
  39333. */
  39334. GLTFParser.prototype.loadScene = function () {
  39335. // scene node hierachy builder
  39336. function buildNodeHierachy( nodeId, parentObject, json, parser ) {
  39337. var nodeDef = json.nodes[ nodeId ];
  39338. return parser.getDependency( 'node', nodeId ).then( function ( node ) {
  39339. if ( nodeDef.skin === undefined ) return node;
  39340. // build skeleton here as well
  39341. var skinEntry;
  39342. return parser.getDependency( 'skin', nodeDef.skin ).then( function ( skin ) {
  39343. skinEntry = skin;
  39344. var pendingJoints = [];
  39345. for ( var i = 0, il = skinEntry.joints.length; i < il; i ++ ) {
  39346. pendingJoints.push( parser.getDependency( 'node', skinEntry.joints[ i ] ) );
  39347. }
  39348. return Promise.all( pendingJoints );
  39349. } ).then( function ( jointNodes ) {
  39350. node.traverse( function ( mesh ) {
  39351. if ( ! mesh.isMesh ) return;
  39352. var bones = [];
  39353. var boneInverses = [];
  39354. for ( var j = 0, jl = jointNodes.length; j < jl; j ++ ) {
  39355. var jointNode = jointNodes[ j ];
  39356. if ( jointNode ) {
  39357. bones.push( jointNode );
  39358. var mat = new THREE.Matrix4();
  39359. if ( skinEntry.inverseBindMatrices !== undefined ) {
  39360. mat.fromArray( skinEntry.inverseBindMatrices.array, j * 16 );
  39361. }
  39362. boneInverses.push( mat );
  39363. } else {
  39364. console.warn( 'THREE.GLTFLoader: Joint "%s" could not be found.', skinEntry.joints[ j ] );
  39365. }
  39366. }
  39367. mesh.bind( new THREE.Skeleton( bones, boneInverses ), mesh.matrixWorld );
  39368. } );
  39369. return node;
  39370. } );
  39371. } ).then( function ( node ) {
  39372. // build node hierachy
  39373. parentObject.add( node );
  39374. var pending = [];
  39375. if ( nodeDef.children ) {
  39376. var children = nodeDef.children;
  39377. for ( var i = 0, il = children.length; i < il; i ++ ) {
  39378. var child = children[ i ];
  39379. pending.push( buildNodeHierachy( child, node, json, parser ) );
  39380. }
  39381. }
  39382. return Promise.all( pending );
  39383. } );
  39384. }
  39385. return function loadScene( sceneIndex ) {
  39386. var json = this.json;
  39387. var extensions = this.extensions;
  39388. var sceneDef = this.json.scenes[ sceneIndex ];
  39389. var parser = this;
  39390. // Loader returns Group, not Scene.
  39391. // See: https://github.com/mrdoob/three.js/issues/18342#issuecomment-578981172
  39392. var scene = new THREE.Group();
  39393. if ( sceneDef.name ) scene.name = parser.createUniqueName( sceneDef.name );
  39394. assignExtrasToUserData( scene, sceneDef );
  39395. if ( sceneDef.extensions ) addUnknownExtensionsToUserData( extensions, scene, sceneDef );
  39396. var nodeIds = sceneDef.nodes || [];
  39397. var pending = [];
  39398. for ( var i = 0, il = nodeIds.length; i < il; i ++ ) {
  39399. pending.push( buildNodeHierachy( nodeIds[ i ], scene, json, parser ) );
  39400. }
  39401. return Promise.all( pending ).then( function () {
  39402. return scene;
  39403. } );
  39404. };
  39405. }();
  39406. return GLTFLoader;
  39407. } )();
  39408. },{}],60:[function(_dereq_,module,exports){
  39409. /**
  39410. * Loads a Wavefront .mtl file specifying materials
  39411. */
  39412. THREE.MTLLoader = function ( manager ) {
  39413. THREE.Loader.call( this, manager );
  39414. };
  39415. THREE.MTLLoader.prototype = Object.assign( Object.create( THREE.Loader.prototype ), {
  39416. constructor: THREE.MTLLoader,
  39417. /**
  39418. * Loads and parses a MTL asset from a URL.
  39419. *
  39420. * @param {String} url - URL to the MTL file.
  39421. * @param {Function} [onLoad] - Callback invoked with the loaded object.
  39422. * @param {Function} [onProgress] - Callback for download progress.
  39423. * @param {Function} [onError] - Callback for download errors.
  39424. *
  39425. * @see setPath setResourcePath
  39426. *
  39427. * @note In order for relative texture references to resolve correctly
  39428. * you must call setResourcePath() explicitly prior to load.
  39429. */
  39430. load: function ( url, onLoad, onProgress, onError ) {
  39431. var scope = this;
  39432. var path = ( this.path === '' ) ? THREE.LoaderUtils.extractUrlBase( url ) : this.path;
  39433. var loader = new THREE.FileLoader( this.manager );
  39434. loader.setPath( this.path );
  39435. loader.setRequestHeader( this.requestHeader );
  39436. loader.setWithCredentials( this.withCredentials );
  39437. loader.load( url, function ( text ) {
  39438. try {
  39439. onLoad( scope.parse( text, path ) );
  39440. } catch ( e ) {
  39441. if ( onError ) {
  39442. onError( e );
  39443. } else {
  39444. console.error( e );
  39445. }
  39446. scope.manager.itemError( url );
  39447. }
  39448. }, onProgress, onError );
  39449. },
  39450. setMaterialOptions: function ( value ) {
  39451. this.materialOptions = value;
  39452. return this;
  39453. },
  39454. /**
  39455. * Parses a MTL file.
  39456. *
  39457. * @param {String} text - Content of MTL file
  39458. * @return {THREE.MTLLoader.MaterialCreator}
  39459. *
  39460. * @see setPath setResourcePath
  39461. *
  39462. * @note In order for relative texture references to resolve correctly
  39463. * you must call setResourcePath() explicitly prior to parse.
  39464. */
  39465. parse: function ( text, path ) {
  39466. var lines = text.split( '\n' );
  39467. var info = {};
  39468. var delimiter_pattern = /\s+/;
  39469. var materialsInfo = {};
  39470. for ( var i = 0; i < lines.length; i ++ ) {
  39471. var line = lines[ i ];
  39472. line = line.trim();
  39473. if ( line.length === 0 || line.charAt( 0 ) === '#' ) {
  39474. // Blank line or comment ignore
  39475. continue;
  39476. }
  39477. var pos = line.indexOf( ' ' );
  39478. var key = ( pos >= 0 ) ? line.substring( 0, pos ) : line;
  39479. key = key.toLowerCase();
  39480. var value = ( pos >= 0 ) ? line.substring( pos + 1 ) : '';
  39481. value = value.trim();
  39482. if ( key === 'newmtl' ) {
  39483. // New material
  39484. info = { name: value };
  39485. materialsInfo[ value ] = info;
  39486. } else {
  39487. if ( key === 'ka' || key === 'kd' || key === 'ks' || key === 'ke' ) {
  39488. var ss = value.split( delimiter_pattern, 3 );
  39489. info[ key ] = [ parseFloat( ss[ 0 ] ), parseFloat( ss[ 1 ] ), parseFloat( ss[ 2 ] ) ];
  39490. } else {
  39491. info[ key ] = value;
  39492. }
  39493. }
  39494. }
  39495. var materialCreator = new THREE.MTLLoader.MaterialCreator( this.resourcePath || path, this.materialOptions );
  39496. materialCreator.setCrossOrigin( this.crossOrigin );
  39497. materialCreator.setManager( this.manager );
  39498. materialCreator.setMaterials( materialsInfo );
  39499. return materialCreator;
  39500. }
  39501. } );
  39502. /**
  39503. * Create a new THREE.MTLLoader.MaterialCreator
  39504. * @param baseUrl - Url relative to which textures are loaded
  39505. * @param options - Set of options on how to construct the materials
  39506. * side: Which side to apply the material
  39507. * THREE.FrontSide (default), THREE.BackSide, THREE.DoubleSide
  39508. * wrap: What type of wrapping to apply for textures
  39509. * THREE.RepeatWrapping (default), THREE.ClampToEdgeWrapping, THREE.MirroredRepeatWrapping
  39510. * normalizeRGB: RGBs need to be normalized to 0-1 from 0-255
  39511. * Default: false, assumed to be already normalized
  39512. * ignoreZeroRGBs: Ignore values of RGBs (Ka,Kd,Ks) that are all 0's
  39513. * Default: false
  39514. * @constructor
  39515. */
  39516. THREE.MTLLoader.MaterialCreator = function ( baseUrl, options ) {
  39517. this.baseUrl = baseUrl || '';
  39518. this.options = options;
  39519. this.materialsInfo = {};
  39520. this.materials = {};
  39521. this.materialsArray = [];
  39522. this.nameLookup = {};
  39523. this.side = ( this.options && this.options.side ) ? this.options.side : THREE.FrontSide;
  39524. this.wrap = ( this.options && this.options.wrap ) ? this.options.wrap : THREE.RepeatWrapping;
  39525. };
  39526. THREE.MTLLoader.MaterialCreator.prototype = {
  39527. constructor: THREE.MTLLoader.MaterialCreator,
  39528. crossOrigin: 'anonymous',
  39529. setCrossOrigin: function ( value ) {
  39530. this.crossOrigin = value;
  39531. return this;
  39532. },
  39533. setManager: function ( value ) {
  39534. this.manager = value;
  39535. },
  39536. setMaterials: function ( materialsInfo ) {
  39537. this.materialsInfo = this.convert( materialsInfo );
  39538. this.materials = {};
  39539. this.materialsArray = [];
  39540. this.nameLookup = {};
  39541. },
  39542. convert: function ( materialsInfo ) {
  39543. if ( ! this.options ) return materialsInfo;
  39544. var converted = {};
  39545. for ( var mn in materialsInfo ) {
  39546. // Convert materials info into normalized form based on options
  39547. var mat = materialsInfo[ mn ];
  39548. var covmat = {};
  39549. converted[ mn ] = covmat;
  39550. for ( var prop in mat ) {
  39551. var save = true;
  39552. var value = mat[ prop ];
  39553. var lprop = prop.toLowerCase();
  39554. switch ( lprop ) {
  39555. case 'kd':
  39556. case 'ka':
  39557. case 'ks':
  39558. // Diffuse color (color under white light) using RGB values
  39559. if ( this.options && this.options.normalizeRGB ) {
  39560. value = [ value[ 0 ] / 255, value[ 1 ] / 255, value[ 2 ] / 255 ];
  39561. }
  39562. if ( this.options && this.options.ignoreZeroRGBs ) {
  39563. if ( value[ 0 ] === 0 && value[ 1 ] === 0 && value[ 2 ] === 0 ) {
  39564. // ignore
  39565. save = false;
  39566. }
  39567. }
  39568. break;
  39569. default:
  39570. break;
  39571. }
  39572. if ( save ) {
  39573. covmat[ lprop ] = value;
  39574. }
  39575. }
  39576. }
  39577. return converted;
  39578. },
  39579. preload: function () {
  39580. for ( var mn in this.materialsInfo ) {
  39581. this.create( mn );
  39582. }
  39583. },
  39584. getIndex: function ( materialName ) {
  39585. return this.nameLookup[ materialName ];
  39586. },
  39587. getAsArray: function () {
  39588. var index = 0;
  39589. for ( var mn in this.materialsInfo ) {
  39590. this.materialsArray[ index ] = this.create( mn );
  39591. this.nameLookup[ mn ] = index;
  39592. index ++;
  39593. }
  39594. return this.materialsArray;
  39595. },
  39596. create: function ( materialName ) {
  39597. if ( this.materials[ materialName ] === undefined ) {
  39598. this.createMaterial_( materialName );
  39599. }
  39600. return this.materials[ materialName ];
  39601. },
  39602. createMaterial_: function ( materialName ) {
  39603. // Create material
  39604. var scope = this;
  39605. var mat = this.materialsInfo[ materialName ];
  39606. var params = {
  39607. name: materialName,
  39608. side: this.side
  39609. };
  39610. function resolveURL( baseUrl, url ) {
  39611. if ( typeof url !== 'string' || url === '' )
  39612. return '';
  39613. // Absolute URL
  39614. if ( /^https?:\/\//i.test( url ) ) return url;
  39615. return baseUrl + url;
  39616. }
  39617. function setMapForType( mapType, value ) {
  39618. if ( params[ mapType ] ) return; // Keep the first encountered texture
  39619. var texParams = scope.getTextureParams( value, params );
  39620. var map = scope.loadTexture( resolveURL( scope.baseUrl, texParams.url ) );
  39621. map.repeat.copy( texParams.scale );
  39622. map.offset.copy( texParams.offset );
  39623. map.wrapS = scope.wrap;
  39624. map.wrapT = scope.wrap;
  39625. params[ mapType ] = map;
  39626. }
  39627. for ( var prop in mat ) {
  39628. var value = mat[ prop ];
  39629. var n;
  39630. if ( value === '' ) continue;
  39631. switch ( prop.toLowerCase() ) {
  39632. // Ns is material specular exponent
  39633. case 'kd':
  39634. // Diffuse color (color under white light) using RGB values
  39635. params.color = new THREE.Color().fromArray( value );
  39636. break;
  39637. case 'ks':
  39638. // Specular color (color when light is reflected from shiny surface) using RGB values
  39639. params.specular = new THREE.Color().fromArray( value );
  39640. break;
  39641. case 'ke':
  39642. // Emissive using RGB values
  39643. params.emissive = new THREE.Color().fromArray( value );
  39644. break;
  39645. case 'map_kd':
  39646. // Diffuse texture map
  39647. setMapForType( 'map', value );
  39648. break;
  39649. case 'map_ks':
  39650. // Specular map
  39651. setMapForType( 'specularMap', value );
  39652. break;
  39653. case 'map_ke':
  39654. // Emissive map
  39655. setMapForType( 'emissiveMap', value );
  39656. break;
  39657. case 'norm':
  39658. setMapForType( 'normalMap', value );
  39659. break;
  39660. case 'map_bump':
  39661. case 'bump':
  39662. // Bump texture map
  39663. setMapForType( 'bumpMap', value );
  39664. break;
  39665. case 'map_d':
  39666. // Alpha map
  39667. setMapForType( 'alphaMap', value );
  39668. params.transparent = true;
  39669. break;
  39670. case 'ns':
  39671. // The specular exponent (defines the focus of the specular highlight)
  39672. // A high exponent results in a tight, concentrated highlight. Ns values normally range from 0 to 1000.
  39673. params.shininess = parseFloat( value );
  39674. break;
  39675. case 'd':
  39676. n = parseFloat( value );
  39677. if ( n < 1 ) {
  39678. params.opacity = n;
  39679. params.transparent = true;
  39680. }
  39681. break;
  39682. case 'tr':
  39683. n = parseFloat( value );
  39684. if ( this.options && this.options.invertTrProperty ) n = 1 - n;
  39685. if ( n > 0 ) {
  39686. params.opacity = 1 - n;
  39687. params.transparent = true;
  39688. }
  39689. break;
  39690. default:
  39691. break;
  39692. }
  39693. }
  39694. this.materials[ materialName ] = new THREE.MeshPhongMaterial( params );
  39695. return this.materials[ materialName ];
  39696. },
  39697. getTextureParams: function ( value, matParams ) {
  39698. var texParams = {
  39699. scale: new THREE.Vector2( 1, 1 ),
  39700. offset: new THREE.Vector2( 0, 0 )
  39701. };
  39702. var items = value.split( /\s+/ );
  39703. var pos;
  39704. pos = items.indexOf( '-bm' );
  39705. if ( pos >= 0 ) {
  39706. matParams.bumpScale = parseFloat( items[ pos + 1 ] );
  39707. items.splice( pos, 2 );
  39708. }
  39709. pos = items.indexOf( '-s' );
  39710. if ( pos >= 0 ) {
  39711. texParams.scale.set( parseFloat( items[ pos + 1 ] ), parseFloat( items[ pos + 2 ] ) );
  39712. items.splice( pos, 4 ); // we expect 3 parameters here!
  39713. }
  39714. pos = items.indexOf( '-o' );
  39715. if ( pos >= 0 ) {
  39716. texParams.offset.set( parseFloat( items[ pos + 1 ] ), parseFloat( items[ pos + 2 ] ) );
  39717. items.splice( pos, 4 ); // we expect 3 parameters here!
  39718. }
  39719. texParams.url = items.join( ' ' ).trim();
  39720. return texParams;
  39721. },
  39722. loadTexture: function ( url, mapping, onLoad, onProgress, onError ) {
  39723. var texture;
  39724. var manager = ( this.manager !== undefined ) ? this.manager : THREE.DefaultLoadingManager;
  39725. var loader = manager.getHandler( url );
  39726. if ( loader === null ) {
  39727. loader = new THREE.TextureLoader( manager );
  39728. }
  39729. if ( loader.setCrossOrigin ) loader.setCrossOrigin( this.crossOrigin );
  39730. texture = loader.load( url, onLoad, onProgress, onError );
  39731. if ( mapping !== undefined ) texture.mapping = mapping;
  39732. return texture;
  39733. }
  39734. };
  39735. },{}],61:[function(_dereq_,module,exports){
  39736. THREE.OBJLoader = ( function () {
  39737. // o object_name | g group_name
  39738. var object_pattern = /^[og]\s*(.+)?/;
  39739. // mtllib file_reference
  39740. var material_library_pattern = /^mtllib /;
  39741. // usemtl material_name
  39742. var material_use_pattern = /^usemtl /;
  39743. // usemap map_name
  39744. var map_use_pattern = /^usemap /;
  39745. var vA = new THREE.Vector3();
  39746. var vB = new THREE.Vector3();
  39747. var vC = new THREE.Vector3();
  39748. var ab = new THREE.Vector3();
  39749. var cb = new THREE.Vector3();
  39750. function ParserState() {
  39751. var state = {
  39752. objects: [],
  39753. object: {},
  39754. vertices: [],
  39755. normals: [],
  39756. colors: [],
  39757. uvs: [],
  39758. materials: {},
  39759. materialLibraries: [],
  39760. startObject: function ( name, fromDeclaration ) {
  39761. // If the current object (initial from reset) is not from a g/o declaration in the parsed
  39762. // file. We need to use it for the first parsed g/o to keep things in sync.
  39763. if ( this.object && this.object.fromDeclaration === false ) {
  39764. this.object.name = name;
  39765. this.object.fromDeclaration = ( fromDeclaration !== false );
  39766. return;
  39767. }
  39768. var previousMaterial = ( this.object && typeof this.object.currentMaterial === 'function' ? this.object.currentMaterial() : undefined );
  39769. if ( this.object && typeof this.object._finalize === 'function' ) {
  39770. this.object._finalize( true );
  39771. }
  39772. this.object = {
  39773. name: name || '',
  39774. fromDeclaration: ( fromDeclaration !== false ),
  39775. geometry: {
  39776. vertices: [],
  39777. normals: [],
  39778. colors: [],
  39779. uvs: [],
  39780. hasUVIndices: false
  39781. },
  39782. materials: [],
  39783. smooth: true,
  39784. startMaterial: function ( name, libraries ) {
  39785. var previous = this._finalize( false );
  39786. // New usemtl declaration overwrites an inherited material, except if faces were declared
  39787. // after the material, then it must be preserved for proper MultiMaterial continuation.
  39788. if ( previous && ( previous.inherited || previous.groupCount <= 0 ) ) {
  39789. this.materials.splice( previous.index, 1 );
  39790. }
  39791. var material = {
  39792. index: this.materials.length,
  39793. name: name || '',
  39794. mtllib: ( Array.isArray( libraries ) && libraries.length > 0 ? libraries[ libraries.length - 1 ] : '' ),
  39795. smooth: ( previous !== undefined ? previous.smooth : this.smooth ),
  39796. groupStart: ( previous !== undefined ? previous.groupEnd : 0 ),
  39797. groupEnd: - 1,
  39798. groupCount: - 1,
  39799. inherited: false,
  39800. clone: function ( index ) {
  39801. var cloned = {
  39802. index: ( typeof index === 'number' ? index : this.index ),
  39803. name: this.name,
  39804. mtllib: this.mtllib,
  39805. smooth: this.smooth,
  39806. groupStart: 0,
  39807. groupEnd: - 1,
  39808. groupCount: - 1,
  39809. inherited: false
  39810. };
  39811. cloned.clone = this.clone.bind( cloned );
  39812. return cloned;
  39813. }
  39814. };
  39815. this.materials.push( material );
  39816. return material;
  39817. },
  39818. currentMaterial: function () {
  39819. if ( this.materials.length > 0 ) {
  39820. return this.materials[ this.materials.length - 1 ];
  39821. }
  39822. return undefined;
  39823. },
  39824. _finalize: function ( end ) {
  39825. var lastMultiMaterial = this.currentMaterial();
  39826. if ( lastMultiMaterial && lastMultiMaterial.groupEnd === - 1 ) {
  39827. lastMultiMaterial.groupEnd = this.geometry.vertices.length / 3;
  39828. lastMultiMaterial.groupCount = lastMultiMaterial.groupEnd - lastMultiMaterial.groupStart;
  39829. lastMultiMaterial.inherited = false;
  39830. }
  39831. // Ignore objects tail materials if no face declarations followed them before a new o/g started.
  39832. if ( end && this.materials.length > 1 ) {
  39833. for ( var mi = this.materials.length - 1; mi >= 0; mi -- ) {
  39834. if ( this.materials[ mi ].groupCount <= 0 ) {
  39835. this.materials.splice( mi, 1 );
  39836. }
  39837. }
  39838. }
  39839. // Guarantee at least one empty material, this makes the creation later more straight forward.
  39840. if ( end && this.materials.length === 0 ) {
  39841. this.materials.push( {
  39842. name: '',
  39843. smooth: this.smooth
  39844. } );
  39845. }
  39846. return lastMultiMaterial;
  39847. }
  39848. };
  39849. // Inherit previous objects material.
  39850. // Spec tells us that a declared material must be set to all objects until a new material is declared.
  39851. // If a usemtl declaration is encountered while this new object is being parsed, it will
  39852. // overwrite the inherited material. Exception being that there was already face declarations
  39853. // to the inherited material, then it will be preserved for proper MultiMaterial continuation.
  39854. if ( previousMaterial && previousMaterial.name && typeof previousMaterial.clone === 'function' ) {
  39855. var declared = previousMaterial.clone( 0 );
  39856. declared.inherited = true;
  39857. this.object.materials.push( declared );
  39858. }
  39859. this.objects.push( this.object );
  39860. },
  39861. finalize: function () {
  39862. if ( this.object && typeof this.object._finalize === 'function' ) {
  39863. this.object._finalize( true );
  39864. }
  39865. },
  39866. parseVertexIndex: function ( value, len ) {
  39867. var index = parseInt( value, 10 );
  39868. return ( index >= 0 ? index - 1 : index + len / 3 ) * 3;
  39869. },
  39870. parseNormalIndex: function ( value, len ) {
  39871. var index = parseInt( value, 10 );
  39872. return ( index >= 0 ? index - 1 : index + len / 3 ) * 3;
  39873. },
  39874. parseUVIndex: function ( value, len ) {
  39875. var index = parseInt( value, 10 );
  39876. return ( index >= 0 ? index - 1 : index + len / 2 ) * 2;
  39877. },
  39878. addVertex: function ( a, b, c ) {
  39879. var src = this.vertices;
  39880. var dst = this.object.geometry.vertices;
  39881. dst.push( src[ a + 0 ], src[ a + 1 ], src[ a + 2 ] );
  39882. dst.push( src[ b + 0 ], src[ b + 1 ], src[ b + 2 ] );
  39883. dst.push( src[ c + 0 ], src[ c + 1 ], src[ c + 2 ] );
  39884. },
  39885. addVertexPoint: function ( a ) {
  39886. var src = this.vertices;
  39887. var dst = this.object.geometry.vertices;
  39888. dst.push( src[ a + 0 ], src[ a + 1 ], src[ a + 2 ] );
  39889. },
  39890. addVertexLine: function ( a ) {
  39891. var src = this.vertices;
  39892. var dst = this.object.geometry.vertices;
  39893. dst.push( src[ a + 0 ], src[ a + 1 ], src[ a + 2 ] );
  39894. },
  39895. addNormal: function ( a, b, c ) {
  39896. var src = this.normals;
  39897. var dst = this.object.geometry.normals;
  39898. dst.push( src[ a + 0 ], src[ a + 1 ], src[ a + 2 ] );
  39899. dst.push( src[ b + 0 ], src[ b + 1 ], src[ b + 2 ] );
  39900. dst.push( src[ c + 0 ], src[ c + 1 ], src[ c + 2 ] );
  39901. },
  39902. addFaceNormal: function ( a, b, c ) {
  39903. var src = this.vertices;
  39904. var dst = this.object.geometry.normals;
  39905. vA.fromArray( src, a );
  39906. vB.fromArray( src, b );
  39907. vC.fromArray( src, c );
  39908. cb.subVectors( vC, vB );
  39909. ab.subVectors( vA, vB );
  39910. cb.cross( ab );
  39911. cb.normalize();
  39912. dst.push( cb.x, cb.y, cb.z );
  39913. dst.push( cb.x, cb.y, cb.z );
  39914. dst.push( cb.x, cb.y, cb.z );
  39915. },
  39916. addColor: function ( a, b, c ) {
  39917. var src = this.colors;
  39918. var dst = this.object.geometry.colors;
  39919. if ( src[ a ] !== undefined ) dst.push( src[ a + 0 ], src[ a + 1 ], src[ a + 2 ] );
  39920. if ( src[ b ] !== undefined ) dst.push( src[ b + 0 ], src[ b + 1 ], src[ b + 2 ] );
  39921. if ( src[ c ] !== undefined ) dst.push( src[ c + 0 ], src[ c + 1 ], src[ c + 2 ] );
  39922. },
  39923. addUV: function ( a, b, c ) {
  39924. var src = this.uvs;
  39925. var dst = this.object.geometry.uvs;
  39926. dst.push( src[ a + 0 ], src[ a + 1 ] );
  39927. dst.push( src[ b + 0 ], src[ b + 1 ] );
  39928. dst.push( src[ c + 0 ], src[ c + 1 ] );
  39929. },
  39930. addDefaultUV: function () {
  39931. var dst = this.object.geometry.uvs;
  39932. dst.push( 0, 0 );
  39933. dst.push( 0, 0 );
  39934. dst.push( 0, 0 );
  39935. },
  39936. addUVLine: function ( a ) {
  39937. var src = this.uvs;
  39938. var dst = this.object.geometry.uvs;
  39939. dst.push( src[ a + 0 ], src[ a + 1 ] );
  39940. },
  39941. addFace: function ( a, b, c, ua, ub, uc, na, nb, nc ) {
  39942. var vLen = this.vertices.length;
  39943. var ia = this.parseVertexIndex( a, vLen );
  39944. var ib = this.parseVertexIndex( b, vLen );
  39945. var ic = this.parseVertexIndex( c, vLen );
  39946. this.addVertex( ia, ib, ic );
  39947. this.addColor( ia, ib, ic );
  39948. // normals
  39949. if ( na !== undefined && na !== '' ) {
  39950. var nLen = this.normals.length;
  39951. ia = this.parseNormalIndex( na, nLen );
  39952. ib = this.parseNormalIndex( nb, nLen );
  39953. ic = this.parseNormalIndex( nc, nLen );
  39954. this.addNormal( ia, ib, ic );
  39955. } else {
  39956. this.addFaceNormal( ia, ib, ic );
  39957. }
  39958. // uvs
  39959. if ( ua !== undefined && ua !== '' ) {
  39960. var uvLen = this.uvs.length;
  39961. ia = this.parseUVIndex( ua, uvLen );
  39962. ib = this.parseUVIndex( ub, uvLen );
  39963. ic = this.parseUVIndex( uc, uvLen );
  39964. this.addUV( ia, ib, ic );
  39965. this.object.geometry.hasUVIndices = true;
  39966. } else {
  39967. // add placeholder values (for inconsistent face definitions)
  39968. this.addDefaultUV();
  39969. }
  39970. },
  39971. addPointGeometry: function ( vertices ) {
  39972. this.object.geometry.type = 'Points';
  39973. var vLen = this.vertices.length;
  39974. for ( var vi = 0, l = vertices.length; vi < l; vi ++ ) {
  39975. var index = this.parseVertexIndex( vertices[ vi ], vLen );
  39976. this.addVertexPoint( index );
  39977. this.addColor( index );
  39978. }
  39979. },
  39980. addLineGeometry: function ( vertices, uvs ) {
  39981. this.object.geometry.type = 'Line';
  39982. var vLen = this.vertices.length;
  39983. var uvLen = this.uvs.length;
  39984. for ( var vi = 0, l = vertices.length; vi < l; vi ++ ) {
  39985. this.addVertexLine( this.parseVertexIndex( vertices[ vi ], vLen ) );
  39986. }
  39987. for ( var uvi = 0, l = uvs.length; uvi < l; uvi ++ ) {
  39988. this.addUVLine( this.parseUVIndex( uvs[ uvi ], uvLen ) );
  39989. }
  39990. }
  39991. };
  39992. state.startObject( '', false );
  39993. return state;
  39994. }
  39995. //
  39996. function OBJLoader( manager ) {
  39997. THREE.Loader.call( this, manager );
  39998. this.materials = null;
  39999. }
  40000. OBJLoader.prototype = Object.assign( Object.create( THREE.Loader.prototype ), {
  40001. constructor: OBJLoader,
  40002. load: function ( url, onLoad, onProgress, onError ) {
  40003. var scope = this;
  40004. var loader = new THREE.FileLoader( this.manager );
  40005. loader.setPath( this.path );
  40006. loader.setRequestHeader( this.requestHeader );
  40007. loader.setWithCredentials( this.withCredentials );
  40008. loader.load( url, function ( text ) {
  40009. try {
  40010. onLoad( scope.parse( text ) );
  40011. } catch ( e ) {
  40012. if ( onError ) {
  40013. onError( e );
  40014. } else {
  40015. console.error( e );
  40016. }
  40017. scope.manager.itemError( url );
  40018. }
  40019. }, onProgress, onError );
  40020. },
  40021. setMaterials: function ( materials ) {
  40022. this.materials = materials;
  40023. return this;
  40024. },
  40025. parse: function ( text ) {
  40026. var state = new ParserState();
  40027. if ( text.indexOf( '\r\n' ) !== - 1 ) {
  40028. // This is faster than String.split with regex that splits on both
  40029. text = text.replace( /\r\n/g, '\n' );
  40030. }
  40031. if ( text.indexOf( '\\\n' ) !== - 1 ) {
  40032. // join lines separated by a line continuation character (\)
  40033. text = text.replace( /\\\n/g, '' );
  40034. }
  40035. var lines = text.split( '\n' );
  40036. var line = '', lineFirstChar = '';
  40037. var lineLength = 0;
  40038. var result = [];
  40039. // Faster to just trim left side of the line. Use if available.
  40040. var trimLeft = ( typeof ''.trimLeft === 'function' );
  40041. for ( var i = 0, l = lines.length; i < l; i ++ ) {
  40042. line = lines[ i ];
  40043. line = trimLeft ? line.trimLeft() : line.trim();
  40044. lineLength = line.length;
  40045. if ( lineLength === 0 ) continue;
  40046. lineFirstChar = line.charAt( 0 );
  40047. // @todo invoke passed in handler if any
  40048. if ( lineFirstChar === '#' ) continue;
  40049. if ( lineFirstChar === 'v' ) {
  40050. var data = line.split( /\s+/ );
  40051. switch ( data[ 0 ] ) {
  40052. case 'v':
  40053. state.vertices.push(
  40054. parseFloat( data[ 1 ] ),
  40055. parseFloat( data[ 2 ] ),
  40056. parseFloat( data[ 3 ] )
  40057. );
  40058. if ( data.length >= 7 ) {
  40059. state.colors.push(
  40060. parseFloat( data[ 4 ] ),
  40061. parseFloat( data[ 5 ] ),
  40062. parseFloat( data[ 6 ] )
  40063. );
  40064. } else {
  40065. // if no colors are defined, add placeholders so color and vertex indices match
  40066. state.colors.push( undefined, undefined, undefined );
  40067. }
  40068. break;
  40069. case 'vn':
  40070. state.normals.push(
  40071. parseFloat( data[ 1 ] ),
  40072. parseFloat( data[ 2 ] ),
  40073. parseFloat( data[ 3 ] )
  40074. );
  40075. break;
  40076. case 'vt':
  40077. state.uvs.push(
  40078. parseFloat( data[ 1 ] ),
  40079. parseFloat( data[ 2 ] )
  40080. );
  40081. break;
  40082. }
  40083. } else if ( lineFirstChar === 'f' ) {
  40084. var lineData = line.substr( 1 ).trim();
  40085. var vertexData = lineData.split( /\s+/ );
  40086. var faceVertices = [];
  40087. // Parse the face vertex data into an easy to work with format
  40088. for ( var j = 0, jl = vertexData.length; j < jl; j ++ ) {
  40089. var vertex = vertexData[ j ];
  40090. if ( vertex.length > 0 ) {
  40091. var vertexParts = vertex.split( '/' );
  40092. faceVertices.push( vertexParts );
  40093. }
  40094. }
  40095. // Draw an edge between the first vertex and all subsequent vertices to form an n-gon
  40096. var v1 = faceVertices[ 0 ];
  40097. for ( var j = 1, jl = faceVertices.length - 1; j < jl; j ++ ) {
  40098. var v2 = faceVertices[ j ];
  40099. var v3 = faceVertices[ j + 1 ];
  40100. state.addFace(
  40101. v1[ 0 ], v2[ 0 ], v3[ 0 ],
  40102. v1[ 1 ], v2[ 1 ], v3[ 1 ],
  40103. v1[ 2 ], v2[ 2 ], v3[ 2 ]
  40104. );
  40105. }
  40106. } else if ( lineFirstChar === 'l' ) {
  40107. var lineParts = line.substring( 1 ).trim().split( ' ' );
  40108. var lineVertices = [], lineUVs = [];
  40109. if ( line.indexOf( '/' ) === - 1 ) {
  40110. lineVertices = lineParts;
  40111. } else {
  40112. for ( var li = 0, llen = lineParts.length; li < llen; li ++ ) {
  40113. var parts = lineParts[ li ].split( '/' );
  40114. if ( parts[ 0 ] !== '' ) lineVertices.push( parts[ 0 ] );
  40115. if ( parts[ 1 ] !== '' ) lineUVs.push( parts[ 1 ] );
  40116. }
  40117. }
  40118. state.addLineGeometry( lineVertices, lineUVs );
  40119. } else if ( lineFirstChar === 'p' ) {
  40120. var lineData = line.substr( 1 ).trim();
  40121. var pointData = lineData.split( ' ' );
  40122. state.addPointGeometry( pointData );
  40123. } else if ( ( result = object_pattern.exec( line ) ) !== null ) {
  40124. // o object_name
  40125. // or
  40126. // g group_name
  40127. // WORKAROUND: https://bugs.chromium.org/p/v8/issues/detail?id=2869
  40128. // var name = result[ 0 ].substr( 1 ).trim();
  40129. var name = ( ' ' + result[ 0 ].substr( 1 ).trim() ).substr( 1 );
  40130. state.startObject( name );
  40131. } else if ( material_use_pattern.test( line ) ) {
  40132. // material
  40133. state.object.startMaterial( line.substring( 7 ).trim(), state.materialLibraries );
  40134. } else if ( material_library_pattern.test( line ) ) {
  40135. // mtl file
  40136. state.materialLibraries.push( line.substring( 7 ).trim() );
  40137. } else if ( map_use_pattern.test( line ) ) {
  40138. // the line is parsed but ignored since the loader assumes textures are defined MTL files
  40139. // (according to https://www.okino.com/conv/imp_wave.htm, 'usemap' is the old-style Wavefront texture reference method)
  40140. console.warn( 'THREE.OBJLoader: Rendering identifier "usemap" not supported. Textures must be defined in MTL files.' );
  40141. } else if ( lineFirstChar === 's' ) {
  40142. result = line.split( ' ' );
  40143. // smooth shading
  40144. // @todo Handle files that have varying smooth values for a set of faces inside one geometry,
  40145. // but does not define a usemtl for each face set.
  40146. // This should be detected and a dummy material created (later MultiMaterial and geometry groups).
  40147. // This requires some care to not create extra material on each smooth value for "normal" obj files.
  40148. // where explicit usemtl defines geometry groups.
  40149. // Example asset: examples/models/obj/cerberus/Cerberus.obj
  40150. /*
  40151. * http://paulbourke.net/dataformats/obj/
  40152. * or
  40153. * http://www.cs.utah.edu/~boulos/cs3505/obj_spec.pdf
  40154. *
  40155. * From chapter "Grouping" Syntax explanation "s group_number":
  40156. * "group_number is the smoothing group number. To turn off smoothing groups, use a value of 0 or off.
  40157. * Polygonal elements use group numbers to put elements in different smoothing groups. For free-form
  40158. * surfaces, smoothing groups are either turned on or off; there is no difference between values greater
  40159. * than 0."
  40160. */
  40161. if ( result.length > 1 ) {
  40162. var value = result[ 1 ].trim().toLowerCase();
  40163. state.object.smooth = ( value !== '0' && value !== 'off' );
  40164. } else {
  40165. // ZBrush can produce "s" lines #11707
  40166. state.object.smooth = true;
  40167. }
  40168. var material = state.object.currentMaterial();
  40169. if ( material ) material.smooth = state.object.smooth;
  40170. } else {
  40171. // Handle null terminated files without exception
  40172. if ( line === '\0' ) continue;
  40173. console.warn( 'THREE.OBJLoader: Unexpected line: "' + line + '"' );
  40174. }
  40175. }
  40176. state.finalize();
  40177. var container = new THREE.Group();
  40178. container.materialLibraries = [].concat( state.materialLibraries );
  40179. var hasPrimitives = ! ( state.objects.length === 1 && state.objects[ 0 ].geometry.vertices.length === 0 );
  40180. if ( hasPrimitives === true ) {
  40181. for ( var i = 0, l = state.objects.length; i < l; i ++ ) {
  40182. var object = state.objects[ i ];
  40183. var geometry = object.geometry;
  40184. var materials = object.materials;
  40185. var isLine = ( geometry.type === 'Line' );
  40186. var isPoints = ( geometry.type === 'Points' );
  40187. var hasVertexColors = false;
  40188. // Skip o/g line declarations that did not follow with any faces
  40189. if ( geometry.vertices.length === 0 ) continue;
  40190. var buffergeometry = new THREE.BufferGeometry();
  40191. buffergeometry.setAttribute( 'position', new THREE.Float32BufferAttribute( geometry.vertices, 3 ) );
  40192. if ( geometry.normals.length > 0 ) {
  40193. buffergeometry.setAttribute( 'normal', new THREE.Float32BufferAttribute( geometry.normals, 3 ) );
  40194. }
  40195. if ( geometry.colors.length > 0 ) {
  40196. hasVertexColors = true;
  40197. buffergeometry.setAttribute( 'color', new THREE.Float32BufferAttribute( geometry.colors, 3 ) );
  40198. }
  40199. if ( geometry.hasUVIndices === true ) {
  40200. buffergeometry.setAttribute( 'uv', new THREE.Float32BufferAttribute( geometry.uvs, 2 ) );
  40201. }
  40202. // Create materials
  40203. var createdMaterials = [];
  40204. for ( var mi = 0, miLen = materials.length; mi < miLen; mi ++ ) {
  40205. var sourceMaterial = materials[ mi ];
  40206. var materialHash = sourceMaterial.name + '_' + sourceMaterial.smooth + '_' + hasVertexColors;
  40207. var material = state.materials[ materialHash ];
  40208. if ( this.materials !== null ) {
  40209. material = this.materials.create( sourceMaterial.name );
  40210. // mtl etc. loaders probably can't create line materials correctly, copy properties to a line material.
  40211. if ( isLine && material && ! ( material instanceof THREE.LineBasicMaterial ) ) {
  40212. var materialLine = new THREE.LineBasicMaterial();
  40213. THREE.Material.prototype.copy.call( materialLine, material );
  40214. materialLine.color.copy( material.color );
  40215. material = materialLine;
  40216. } else if ( isPoints && material && ! ( material instanceof THREE.PointsMaterial ) ) {
  40217. var materialPoints = new THREE.PointsMaterial( { size: 10, sizeAttenuation: false } );
  40218. THREE.Material.prototype.copy.call( materialPoints, material );
  40219. materialPoints.color.copy( material.color );
  40220. materialPoints.map = material.map;
  40221. material = materialPoints;
  40222. }
  40223. }
  40224. if ( material === undefined ) {
  40225. if ( isLine ) {
  40226. material = new THREE.LineBasicMaterial();
  40227. } else if ( isPoints ) {
  40228. material = new THREE.PointsMaterial( { size: 1, sizeAttenuation: false } );
  40229. } else {
  40230. material = new THREE.MeshPhongMaterial();
  40231. }
  40232. material.name = sourceMaterial.name;
  40233. material.flatShading = sourceMaterial.smooth ? false : true;
  40234. material.vertexColors = hasVertexColors;
  40235. state.materials[ materialHash ] = material;
  40236. }
  40237. createdMaterials.push( material );
  40238. }
  40239. // Create mesh
  40240. var mesh;
  40241. if ( createdMaterials.length > 1 ) {
  40242. for ( var mi = 0, miLen = materials.length; mi < miLen; mi ++ ) {
  40243. var sourceMaterial = materials[ mi ];
  40244. buffergeometry.addGroup( sourceMaterial.groupStart, sourceMaterial.groupCount, mi );
  40245. }
  40246. if ( isLine ) {
  40247. mesh = new THREE.LineSegments( buffergeometry, createdMaterials );
  40248. } else if ( isPoints ) {
  40249. mesh = new THREE.Points( buffergeometry, createdMaterials );
  40250. } else {
  40251. mesh = new THREE.Mesh( buffergeometry, createdMaterials );
  40252. }
  40253. } else {
  40254. if ( isLine ) {
  40255. mesh = new THREE.LineSegments( buffergeometry, createdMaterials[ 0 ] );
  40256. } else if ( isPoints ) {
  40257. mesh = new THREE.Points( buffergeometry, createdMaterials[ 0 ] );
  40258. } else {
  40259. mesh = new THREE.Mesh( buffergeometry, createdMaterials[ 0 ] );
  40260. }
  40261. }
  40262. mesh.name = object.name;
  40263. container.add( mesh );
  40264. }
  40265. } else {
  40266. // if there is only the default parser state object with no geometry data, interpret data as point cloud
  40267. if ( state.vertices.length > 0 ) {
  40268. var material = new THREE.PointsMaterial( { size: 1, sizeAttenuation: false } );
  40269. var buffergeometry = new THREE.BufferGeometry();
  40270. buffergeometry.setAttribute( 'position', new THREE.Float32BufferAttribute( state.vertices, 3 ) );
  40271. if ( state.colors.length > 0 && state.colors[ 0 ] !== undefined ) {
  40272. buffergeometry.setAttribute( 'color', new THREE.Float32BufferAttribute( state.colors, 3 ) );
  40273. material.vertexColors = true;
  40274. }
  40275. var points = new THREE.Points( buffergeometry, material );
  40276. container.add( points );
  40277. }
  40278. }
  40279. return container;
  40280. }
  40281. } );
  40282. return OBJLoader;
  40283. } )();
  40284. },{}],62:[function(_dereq_,module,exports){
  40285. THREE.BufferGeometryUtils = {
  40286. computeTangents: function ( geometry ) {
  40287. geometry.computeTangents();
  40288. console.warn( 'THREE.BufferGeometryUtils: .computeTangents() has been removed. Use BufferGeometry.computeTangents() instead.' );
  40289. },
  40290. /**
  40291. * @param {Array<THREE.BufferGeometry>} geometries
  40292. * @param {Boolean} useGroups
  40293. * @return {THREE.BufferGeometry}
  40294. */
  40295. mergeBufferGeometries: function ( geometries, useGroups ) {
  40296. var isIndexed = geometries[ 0 ].index !== null;
  40297. var attributesUsed = new Set( Object.keys( geometries[ 0 ].attributes ) );
  40298. var morphAttributesUsed = new Set( Object.keys( geometries[ 0 ].morphAttributes ) );
  40299. var attributes = {};
  40300. var morphAttributes = {};
  40301. var morphTargetsRelative = geometries[ 0 ].morphTargetsRelative;
  40302. var mergedGeometry = new THREE.BufferGeometry();
  40303. var offset = 0;
  40304. for ( var i = 0; i < geometries.length; ++ i ) {
  40305. var geometry = geometries[ i ];
  40306. var attributesCount = 0;
  40307. // ensure that all geometries are indexed, or none
  40308. if ( isIndexed !== ( geometry.index !== null ) ) {
  40309. console.error( 'THREE.BufferGeometryUtils: .mergeBufferGeometries() failed with geometry at index ' + i + '. All geometries must have compatible attributes; make sure index attribute exists among all geometries, or in none of them.' );
  40310. return null;
  40311. }
  40312. // gather attributes, exit early if they're different
  40313. for ( var name in geometry.attributes ) {
  40314. if ( ! attributesUsed.has( name ) ) {
  40315. console.error( 'THREE.BufferGeometryUtils: .mergeBufferGeometries() failed with geometry at index ' + i + '. All geometries must have compatible attributes; make sure "' + name + '" attribute exists among all geometries, or in none of them.' );
  40316. return null;
  40317. }
  40318. if ( attributes[ name ] === undefined ) attributes[ name ] = [];
  40319. attributes[ name ].push( geometry.attributes[ name ] );
  40320. attributesCount ++;
  40321. }
  40322. // ensure geometries have the same number of attributes
  40323. if ( attributesCount !== attributesUsed.size ) {
  40324. console.error( 'THREE.BufferGeometryUtils: .mergeBufferGeometries() failed with geometry at index ' + i + '. Make sure all geometries have the same number of attributes.' );
  40325. return null;
  40326. }
  40327. // gather morph attributes, exit early if they're different
  40328. if ( morphTargetsRelative !== geometry.morphTargetsRelative ) {
  40329. console.error( 'THREE.BufferGeometryUtils: .mergeBufferGeometries() failed with geometry at index ' + i + '. .morphTargetsRelative must be consistent throughout all geometries.' );
  40330. return null;
  40331. }
  40332. for ( var name in geometry.morphAttributes ) {
  40333. if ( ! morphAttributesUsed.has( name ) ) {
  40334. console.error( 'THREE.BufferGeometryUtils: .mergeBufferGeometries() failed with geometry at index ' + i + '. .morphAttributes must be consistent throughout all geometries.' );
  40335. return null;
  40336. }
  40337. if ( morphAttributes[ name ] === undefined ) morphAttributes[ name ] = [];
  40338. morphAttributes[ name ].push( geometry.morphAttributes[ name ] );
  40339. }
  40340. // gather .userData
  40341. mergedGeometry.userData.mergedUserData = mergedGeometry.userData.mergedUserData || [];
  40342. mergedGeometry.userData.mergedUserData.push( geometry.userData );
  40343. if ( useGroups ) {
  40344. var count;
  40345. if ( isIndexed ) {
  40346. count = geometry.index.count;
  40347. } else if ( geometry.attributes.position !== undefined ) {
  40348. count = geometry.attributes.position.count;
  40349. } else {
  40350. console.error( 'THREE.BufferGeometryUtils: .mergeBufferGeometries() failed with geometry at index ' + i + '. The geometry must have either an index or a position attribute' );
  40351. return null;
  40352. }
  40353. mergedGeometry.addGroup( offset, count, i );
  40354. offset += count;
  40355. }
  40356. }
  40357. // merge indices
  40358. if ( isIndexed ) {
  40359. var indexOffset = 0;
  40360. var mergedIndex = [];
  40361. for ( var i = 0; i < geometries.length; ++ i ) {
  40362. var index = geometries[ i ].index;
  40363. for ( var j = 0; j < index.count; ++ j ) {
  40364. mergedIndex.push( index.getX( j ) + indexOffset );
  40365. }
  40366. indexOffset += geometries[ i ].attributes.position.count;
  40367. }
  40368. mergedGeometry.setIndex( mergedIndex );
  40369. }
  40370. // merge attributes
  40371. for ( var name in attributes ) {
  40372. var mergedAttribute = this.mergeBufferAttributes( attributes[ name ] );
  40373. if ( ! mergedAttribute ) {
  40374. console.error( 'THREE.BufferGeometryUtils: .mergeBufferGeometries() failed while trying to merge the ' + name + ' attribute.' );
  40375. return null;
  40376. }
  40377. mergedGeometry.setAttribute( name, mergedAttribute );
  40378. }
  40379. // merge morph attributes
  40380. for ( var name in morphAttributes ) {
  40381. var numMorphTargets = morphAttributes[ name ][ 0 ].length;
  40382. if ( numMorphTargets === 0 ) break;
  40383. mergedGeometry.morphAttributes = mergedGeometry.morphAttributes || {};
  40384. mergedGeometry.morphAttributes[ name ] = [];
  40385. for ( var i = 0; i < numMorphTargets; ++ i ) {
  40386. var morphAttributesToMerge = [];
  40387. for ( var j = 0; j < morphAttributes[ name ].length; ++ j ) {
  40388. morphAttributesToMerge.push( morphAttributes[ name ][ j ][ i ] );
  40389. }
  40390. var mergedMorphAttribute = this.mergeBufferAttributes( morphAttributesToMerge );
  40391. if ( ! mergedMorphAttribute ) {
  40392. console.error( 'THREE.BufferGeometryUtils: .mergeBufferGeometries() failed while trying to merge the ' + name + ' morphAttribute.' );
  40393. return null;
  40394. }
  40395. mergedGeometry.morphAttributes[ name ].push( mergedMorphAttribute );
  40396. }
  40397. }
  40398. return mergedGeometry;
  40399. },
  40400. /**
  40401. * @param {Array<THREE.BufferAttribute>} attributes
  40402. * @return {THREE.BufferAttribute}
  40403. */
  40404. mergeBufferAttributes: function ( attributes ) {
  40405. var TypedArray;
  40406. var itemSize;
  40407. var normalized;
  40408. var arrayLength = 0;
  40409. for ( var i = 0; i < attributes.length; ++ i ) {
  40410. var attribute = attributes[ i ];
  40411. if ( attribute.isInterleavedBufferAttribute ) {
  40412. console.error( 'THREE.BufferGeometryUtils: .mergeBufferAttributes() failed. InterleavedBufferAttributes are not supported.' );
  40413. return null;
  40414. }
  40415. if ( TypedArray === undefined ) TypedArray = attribute.array.constructor;
  40416. if ( TypedArray !== attribute.array.constructor ) {
  40417. console.error( 'THREE.BufferGeometryUtils: .mergeBufferAttributes() failed. BufferAttribute.array must be of consistent array types across matching attributes.' );
  40418. return null;
  40419. }
  40420. if ( itemSize === undefined ) itemSize = attribute.itemSize;
  40421. if ( itemSize !== attribute.itemSize ) {
  40422. console.error( 'THREE.BufferGeometryUtils: .mergeBufferAttributes() failed. BufferAttribute.itemSize must be consistent across matching attributes.' );
  40423. return null;
  40424. }
  40425. if ( normalized === undefined ) normalized = attribute.normalized;
  40426. if ( normalized !== attribute.normalized ) {
  40427. console.error( 'THREE.BufferGeometryUtils: .mergeBufferAttributes() failed. BufferAttribute.normalized must be consistent across matching attributes.' );
  40428. return null;
  40429. }
  40430. arrayLength += attribute.array.length;
  40431. }
  40432. var array = new TypedArray( arrayLength );
  40433. var offset = 0;
  40434. for ( var i = 0; i < attributes.length; ++ i ) {
  40435. array.set( attributes[ i ].array, offset );
  40436. offset += attributes[ i ].array.length;
  40437. }
  40438. return new THREE.BufferAttribute( array, itemSize, normalized );
  40439. },
  40440. /**
  40441. * @param {Array<THREE.BufferAttribute>} attributes
  40442. * @return {Array<THREE.InterleavedBufferAttribute>}
  40443. */
  40444. interleaveAttributes: function ( attributes ) {
  40445. // Interleaves the provided attributes into an InterleavedBuffer and returns
  40446. // a set of InterleavedBufferAttributes for each attribute
  40447. var TypedArray;
  40448. var arrayLength = 0;
  40449. var stride = 0;
  40450. // calculate the the length and type of the interleavedBuffer
  40451. for ( var i = 0, l = attributes.length; i < l; ++ i ) {
  40452. var attribute = attributes[ i ];
  40453. if ( TypedArray === undefined ) TypedArray = attribute.array.constructor;
  40454. if ( TypedArray !== attribute.array.constructor ) {
  40455. console.error( 'AttributeBuffers of different types cannot be interleaved' );
  40456. return null;
  40457. }
  40458. arrayLength += attribute.array.length;
  40459. stride += attribute.itemSize;
  40460. }
  40461. // Create the set of buffer attributes
  40462. var interleavedBuffer = new THREE.InterleavedBuffer( new TypedArray( arrayLength ), stride );
  40463. var offset = 0;
  40464. var res = [];
  40465. var getters = [ 'getX', 'getY', 'getZ', 'getW' ];
  40466. var setters = [ 'setX', 'setY', 'setZ', 'setW' ];
  40467. for ( var j = 0, l = attributes.length; j < l; j ++ ) {
  40468. var attribute = attributes[ j ];
  40469. var itemSize = attribute.itemSize;
  40470. var count = attribute.count;
  40471. var iba = new THREE.InterleavedBufferAttribute( interleavedBuffer, itemSize, offset, attribute.normalized );
  40472. res.push( iba );
  40473. offset += itemSize;
  40474. // Move the data for each attribute into the new interleavedBuffer
  40475. // at the appropriate offset
  40476. for ( var c = 0; c < count; c ++ ) {
  40477. for ( var k = 0; k < itemSize; k ++ ) {
  40478. iba[ setters[ k ] ]( c, attribute[ getters[ k ] ]( c ) );
  40479. }
  40480. }
  40481. }
  40482. return res;
  40483. },
  40484. /**
  40485. * @param {Array<THREE.BufferGeometry>} geometry
  40486. * @return {number}
  40487. */
  40488. estimateBytesUsed: function ( geometry ) {
  40489. // Return the estimated memory used by this geometry in bytes
  40490. // Calculate using itemSize, count, and BYTES_PER_ELEMENT to account
  40491. // for InterleavedBufferAttributes.
  40492. var mem = 0;
  40493. for ( var name in geometry.attributes ) {
  40494. var attr = geometry.getAttribute( name );
  40495. mem += attr.count * attr.itemSize * attr.array.BYTES_PER_ELEMENT;
  40496. }
  40497. var indices = geometry.getIndex();
  40498. mem += indices ? indices.count * indices.itemSize * indices.array.BYTES_PER_ELEMENT : 0;
  40499. return mem;
  40500. },
  40501. /**
  40502. * @param {THREE.BufferGeometry} geometry
  40503. * @param {number} tolerance
  40504. * @return {THREE.BufferGeometry>}
  40505. */
  40506. mergeVertices: function ( geometry, tolerance = 1e-4 ) {
  40507. tolerance = Math.max( tolerance, Number.EPSILON );
  40508. // Generate an index buffer if the geometry doesn't have one, or optimize it
  40509. // if it's already available.
  40510. var hashToIndex = {};
  40511. var indices = geometry.getIndex();
  40512. var positions = geometry.getAttribute( 'position' );
  40513. var vertexCount = indices ? indices.count : positions.count;
  40514. // next value for triangle indices
  40515. var nextIndex = 0;
  40516. // attributes and new attribute arrays
  40517. var attributeNames = Object.keys( geometry.attributes );
  40518. var attrArrays = {};
  40519. var morphAttrsArrays = {};
  40520. var newIndices = [];
  40521. var getters = [ 'getX', 'getY', 'getZ', 'getW' ];
  40522. // initialize the arrays
  40523. for ( var i = 0, l = attributeNames.length; i < l; i ++ ) {
  40524. var name = attributeNames[ i ];
  40525. attrArrays[ name ] = [];
  40526. var morphAttr = geometry.morphAttributes[ name ];
  40527. if ( morphAttr ) {
  40528. morphAttrsArrays[ name ] = new Array( morphAttr.length ).fill().map( () => [] );
  40529. }
  40530. }
  40531. // convert the error tolerance to an amount of decimal places to truncate to
  40532. var decimalShift = Math.log10( 1 / tolerance );
  40533. var shiftMultiplier = Math.pow( 10, decimalShift );
  40534. for ( var i = 0; i < vertexCount; i ++ ) {
  40535. var index = indices ? indices.getX( i ) : i;
  40536. // Generate a hash for the vertex attributes at the current index 'i'
  40537. var hash = '';
  40538. for ( var j = 0, l = attributeNames.length; j < l; j ++ ) {
  40539. var name = attributeNames[ j ];
  40540. var attribute = geometry.getAttribute( name );
  40541. var itemSize = attribute.itemSize;
  40542. for ( var k = 0; k < itemSize; k ++ ) {
  40543. // double tilde truncates the decimal value
  40544. hash += `${ ~ ~ ( attribute[ getters[ k ] ]( index ) * shiftMultiplier ) },`;
  40545. }
  40546. }
  40547. // Add another reference to the vertex if it's already
  40548. // used by another index
  40549. if ( hash in hashToIndex ) {
  40550. newIndices.push( hashToIndex[ hash ] );
  40551. } else {
  40552. // copy data to the new index in the attribute arrays
  40553. for ( var j = 0, l = attributeNames.length; j < l; j ++ ) {
  40554. var name = attributeNames[ j ];
  40555. var attribute = geometry.getAttribute( name );
  40556. var morphAttr = geometry.morphAttributes[ name ];
  40557. var itemSize = attribute.itemSize;
  40558. var newarray = attrArrays[ name ];
  40559. var newMorphArrays = morphAttrsArrays[ name ];
  40560. for ( var k = 0; k < itemSize; k ++ ) {
  40561. var getterFunc = getters[ k ];
  40562. newarray.push( attribute[ getterFunc ]( index ) );
  40563. if ( morphAttr ) {
  40564. for ( var m = 0, ml = morphAttr.length; m < ml; m ++ ) {
  40565. newMorphArrays[ m ].push( morphAttr[ m ][ getterFunc ]( index ) );
  40566. }
  40567. }
  40568. }
  40569. }
  40570. hashToIndex[ hash ] = nextIndex;
  40571. newIndices.push( nextIndex );
  40572. nextIndex ++;
  40573. }
  40574. }
  40575. // Generate typed arrays from new attribute arrays and update
  40576. // the attributeBuffers
  40577. const result = geometry.clone();
  40578. for ( var i = 0, l = attributeNames.length; i < l; i ++ ) {
  40579. var name = attributeNames[ i ];
  40580. var oldAttribute = geometry.getAttribute( name );
  40581. var buffer = new oldAttribute.array.constructor( attrArrays[ name ] );
  40582. var attribute = new THREE.BufferAttribute( buffer, oldAttribute.itemSize, oldAttribute.normalized );
  40583. result.setAttribute( name, attribute );
  40584. // Update the attribute arrays
  40585. if ( name in morphAttrsArrays ) {
  40586. for ( var j = 0; j < morphAttrsArrays[ name ].length; j ++ ) {
  40587. var oldMorphAttribute = geometry.morphAttributes[ name ][ j ];
  40588. var buffer = new oldMorphAttribute.array.constructor( morphAttrsArrays[ name ][ j ] );
  40589. var morphAttribute = new THREE.BufferAttribute( buffer, oldMorphAttribute.itemSize, oldMorphAttribute.normalized );
  40590. result.morphAttributes[ name ][ j ] = morphAttribute;
  40591. }
  40592. }
  40593. }
  40594. // indices
  40595. result.setIndex( newIndices );
  40596. return result;
  40597. },
  40598. /**
  40599. * @param {THREE.BufferGeometry} geometry
  40600. * @param {number} drawMode
  40601. * @return {THREE.BufferGeometry>}
  40602. */
  40603. toTrianglesDrawMode: function ( geometry, drawMode ) {
  40604. if ( drawMode === THREE.TrianglesDrawMode ) {
  40605. console.warn( 'THREE.BufferGeometryUtils.toTrianglesDrawMode(): Geometry already defined as triangles.' );
  40606. return geometry;
  40607. }
  40608. if ( drawMode === THREE.TriangleFanDrawMode || drawMode === THREE.TriangleStripDrawMode ) {
  40609. var index = geometry.getIndex();
  40610. // generate index if not present
  40611. if ( index === null ) {
  40612. var indices = [];
  40613. var position = geometry.getAttribute( 'position' );
  40614. if ( position !== undefined ) {
  40615. for ( var i = 0; i < position.count; i ++ ) {
  40616. indices.push( i );
  40617. }
  40618. geometry.setIndex( indices );
  40619. index = geometry.getIndex();
  40620. } else {
  40621. console.error( 'THREE.BufferGeometryUtils.toTrianglesDrawMode(): Undefined position attribute. Processing not possible.' );
  40622. return geometry;
  40623. }
  40624. }
  40625. //
  40626. var numberOfTriangles = index.count - 2;
  40627. var newIndices = [];
  40628. if ( drawMode === THREE.TriangleFanDrawMode ) {
  40629. // gl.TRIANGLE_FAN
  40630. for ( var i = 1; i <= numberOfTriangles; i ++ ) {
  40631. newIndices.push( index.getX( 0 ) );
  40632. newIndices.push( index.getX( i ) );
  40633. newIndices.push( index.getX( i + 1 ) );
  40634. }
  40635. } else {
  40636. // gl.TRIANGLE_STRIP
  40637. for ( var i = 0; i < numberOfTriangles; i ++ ) {
  40638. if ( i % 2 === 0 ) {
  40639. newIndices.push( index.getX( i ) );
  40640. newIndices.push( index.getX( i + 1 ) );
  40641. newIndices.push( index.getX( i + 2 ) );
  40642. } else {
  40643. newIndices.push( index.getX( i + 2 ) );
  40644. newIndices.push( index.getX( i + 1 ) );
  40645. newIndices.push( index.getX( i ) );
  40646. }
  40647. }
  40648. }
  40649. if ( ( newIndices.length / 3 ) !== numberOfTriangles ) {
  40650. console.error( 'THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unable to generate correct amount of triangles.' );
  40651. }
  40652. // build final geometry
  40653. var newGeometry = geometry.clone();
  40654. newGeometry.setIndex( newIndices );
  40655. newGeometry.clearGroups();
  40656. return newGeometry;
  40657. } else {
  40658. console.error( 'THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unknown draw mode:', drawMode );
  40659. return geometry;
  40660. }
  40661. },
  40662. /**
  40663. * Calculates the morphed attributes of a morphed/skinned BufferGeometry.
  40664. * Helpful for Raytracing or Decals.
  40665. * @param {Mesh | Line | Points} object An instance of Mesh, Line or Points.
  40666. * @return {Object} An Object with original position/normal attributes and morphed ones.
  40667. */
  40668. computeMorphedAttributes: function ( object ) {
  40669. if ( object.geometry.isBufferGeometry !== true ) {
  40670. console.error( 'THREE.BufferGeometryUtils: Geometry is not of type THREE.BufferGeometry.' );
  40671. return null;
  40672. }
  40673. var _vA = new THREE.Vector3();
  40674. var _vB = new THREE.Vector3();
  40675. var _vC = new THREE.Vector3();
  40676. var _tempA = new THREE.Vector3();
  40677. var _tempB = new THREE.Vector3();
  40678. var _tempC = new THREE.Vector3();
  40679. var _morphA = new THREE.Vector3();
  40680. var _morphB = new THREE.Vector3();
  40681. var _morphC = new THREE.Vector3();
  40682. function _calculateMorphedAttributeData(
  40683. object,
  40684. material,
  40685. attribute,
  40686. morphAttribute,
  40687. morphTargetsRelative,
  40688. a,
  40689. b,
  40690. c,
  40691. modifiedAttributeArray
  40692. ) {
  40693. _vA.fromBufferAttribute( attribute, a );
  40694. _vB.fromBufferAttribute( attribute, b );
  40695. _vC.fromBufferAttribute( attribute, c );
  40696. var morphInfluences = object.morphTargetInfluences;
  40697. if ( material.morphTargets && morphAttribute && morphInfluences ) {
  40698. _morphA.set( 0, 0, 0 );
  40699. _morphB.set( 0, 0, 0 );
  40700. _morphC.set( 0, 0, 0 );
  40701. for ( var i = 0, il = morphAttribute.length; i < il; i ++ ) {
  40702. var influence = morphInfluences[ i ];
  40703. var morphAttribute = morphAttribute[ i ];
  40704. if ( influence === 0 ) continue;
  40705. _tempA.fromBufferAttribute( morphAttribute, a );
  40706. _tempB.fromBufferAttribute( morphAttribute, b );
  40707. _tempC.fromBufferAttribute( morphAttribute, c );
  40708. if ( morphTargetsRelative ) {
  40709. _morphA.addScaledVector( _tempA, influence );
  40710. _morphB.addScaledVector( _tempB, influence );
  40711. _morphC.addScaledVector( _tempC, influence );
  40712. } else {
  40713. _morphA.addScaledVector( _tempA.sub( _vA ), influence );
  40714. _morphB.addScaledVector( _tempB.sub( _vB ), influence );
  40715. _morphC.addScaledVector( _tempC.sub( _vC ), influence );
  40716. }
  40717. }
  40718. _vA.add( _morphA );
  40719. _vB.add( _morphB );
  40720. _vC.add( _morphC );
  40721. }
  40722. if ( object.isSkinnedMesh ) {
  40723. object.boneTransform( a, _vA );
  40724. object.boneTransform( b, _vB );
  40725. object.boneTransform( c, _vC );
  40726. }
  40727. modifiedAttributeArray[ a * 3 + 0 ] = _vA.x;
  40728. modifiedAttributeArray[ a * 3 + 1 ] = _vA.y;
  40729. modifiedAttributeArray[ a * 3 + 2 ] = _vA.z;
  40730. modifiedAttributeArray[ b * 3 + 0 ] = _vB.x;
  40731. modifiedAttributeArray[ b * 3 + 1 ] = _vB.y;
  40732. modifiedAttributeArray[ b * 3 + 2 ] = _vB.z;
  40733. modifiedAttributeArray[ c * 3 + 0 ] = _vC.x;
  40734. modifiedAttributeArray[ c * 3 + 1 ] = _vC.y;
  40735. modifiedAttributeArray[ c * 3 + 2 ] = _vC.z;
  40736. }
  40737. var geometry = object.geometry;
  40738. var material = object.material;
  40739. var a, b, c;
  40740. var index = geometry.index;
  40741. var positionAttribute = geometry.attributes.position;
  40742. var morphPosition = geometry.morphAttributes.position;
  40743. var morphTargetsRelative = geometry.morphTargetsRelative;
  40744. var normalAttribute = geometry.attributes.normal;
  40745. var morphNormal = geometry.morphAttributes.position;
  40746. var groups = geometry.groups;
  40747. var drawRange = geometry.drawRange;
  40748. var i, j, il, jl;
  40749. var group, groupMaterial;
  40750. var start, end;
  40751. var modifiedPosition = new Float32Array( positionAttribute.count * positionAttribute.itemSize );
  40752. var modifiedNormal = new Float32Array( normalAttribute.count * normalAttribute.itemSize );
  40753. if ( index !== null ) {
  40754. // indexed buffer geometry
  40755. if ( Array.isArray( material ) ) {
  40756. for ( i = 0, il = groups.length; i < il; i ++ ) {
  40757. group = groups[ i ];
  40758. groupMaterial = material[ group.materialIndex ];
  40759. start = Math.max( group.start, drawRange.start );
  40760. end = Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) );
  40761. for ( j = start, jl = end; j < jl; j += 3 ) {
  40762. a = index.getX( j );
  40763. b = index.getX( j + 1 );
  40764. c = index.getX( j + 2 );
  40765. _calculateMorphedAttributeData(
  40766. object,
  40767. groupMaterial,
  40768. positionAttribute,
  40769. morphPosition,
  40770. morphTargetsRelative,
  40771. a, b, c,
  40772. modifiedPosition
  40773. );
  40774. _calculateMorphedAttributeData(
  40775. object,
  40776. groupMaterial,
  40777. normalAttribute,
  40778. morphNormal,
  40779. morphTargetsRelative,
  40780. a, b, c,
  40781. modifiedNormal
  40782. );
  40783. }
  40784. }
  40785. } else {
  40786. start = Math.max( 0, drawRange.start );
  40787. end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  40788. for ( i = start, il = end; i < il; i += 3 ) {
  40789. a = index.getX( i );
  40790. b = index.getX( i + 1 );
  40791. c = index.getX( i + 2 );
  40792. _calculateMorphedAttributeData(
  40793. object,
  40794. material,
  40795. positionAttribute,
  40796. morphPosition,
  40797. morphTargetsRelative,
  40798. a, b, c,
  40799. modifiedPosition
  40800. );
  40801. _calculateMorphedAttributeData(
  40802. object,
  40803. material,
  40804. normalAttribute,
  40805. morphNormal,
  40806. morphTargetsRelative,
  40807. a, b, c,
  40808. modifiedNormal
  40809. );
  40810. }
  40811. }
  40812. } else if ( positionAttribute !== undefined ) {
  40813. // non-indexed buffer geometry
  40814. if ( Array.isArray( material ) ) {
  40815. for ( i = 0, il = groups.length; i < il; i ++ ) {
  40816. group = groups[ i ];
  40817. groupMaterial = material[ group.materialIndex ];
  40818. start = Math.max( group.start, drawRange.start );
  40819. end = Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) );
  40820. for ( j = start, jl = end; j < jl; j += 3 ) {
  40821. a = j;
  40822. b = j + 1;
  40823. c = j + 2;
  40824. _calculateMorphedAttributeData(
  40825. object,
  40826. groupMaterial,
  40827. positionAttribute,
  40828. morphPosition,
  40829. morphTargetsRelative,
  40830. a, b, c,
  40831. modifiedPosition
  40832. );
  40833. _calculateMorphedAttributeData(
  40834. object,
  40835. groupMaterial,
  40836. normalAttribute,
  40837. morphNormal,
  40838. morphTargetsRelative,
  40839. a, b, c,
  40840. modifiedNormal
  40841. );
  40842. }
  40843. }
  40844. } else {
  40845. start = Math.max( 0, drawRange.start );
  40846. end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  40847. for ( i = start, il = end; i < il; i += 3 ) {
  40848. a = i;
  40849. b = i + 1;
  40850. c = i + 2;
  40851. _calculateMorphedAttributeData(
  40852. object,
  40853. material,
  40854. positionAttribute,
  40855. morphPosition,
  40856. morphTargetsRelative,
  40857. a, b, c,
  40858. modifiedPosition
  40859. );
  40860. _calculateMorphedAttributeData(
  40861. object,
  40862. material,
  40863. normalAttribute,
  40864. morphNormal,
  40865. morphTargetsRelative,
  40866. a, b, c,
  40867. modifiedNormal
  40868. );
  40869. }
  40870. }
  40871. }
  40872. var morphedPositionAttribute = new THREE.Float32BufferAttribute( modifiedPosition, 3 );
  40873. var morphedNormalAttribute = new THREE.Float32BufferAttribute( modifiedNormal, 3 );
  40874. return {
  40875. positionAttribute: positionAttribute,
  40876. normalAttribute: normalAttribute,
  40877. morphedPositionAttribute: morphedPositionAttribute,
  40878. morphedNormalAttribute: morphedNormalAttribute
  40879. };
  40880. }
  40881. };
  40882. },{}],63:[function(_dereq_,module,exports){
  40883. var createLayout = _dereq_('layout-bmfont-text')
  40884. var inherits = _dereq_('inherits')
  40885. var createIndices = _dereq_('quad-indices')
  40886. var buffer = _dereq_('three-buffer-vertex-data')
  40887. var assign = _dereq_('object-assign')
  40888. var vertices = _dereq_('./lib/vertices')
  40889. var utils = _dereq_('./lib/utils')
  40890. var Base = THREE.BufferGeometry
  40891. module.exports = function createTextGeometry (opt) {
  40892. return new TextGeometry(opt)
  40893. }
  40894. function TextGeometry (opt) {
  40895. Base.call(this)
  40896. if (typeof opt === 'string') {
  40897. opt = { text: opt }
  40898. }
  40899. // use these as default values for any subsequent
  40900. // calls to update()
  40901. this._opt = assign({}, opt)
  40902. // also do an initial setup...
  40903. if (opt) this.update(opt)
  40904. }
  40905. inherits(TextGeometry, Base)
  40906. TextGeometry.prototype.update = function (opt) {
  40907. if (typeof opt === 'string') {
  40908. opt = { text: opt }
  40909. }
  40910. // use constructor defaults
  40911. opt = assign({}, this._opt, opt)
  40912. if (!opt.font) {
  40913. throw new TypeError('must specify a { font } in options')
  40914. }
  40915. this.layout = createLayout(opt)
  40916. // get vec2 texcoords
  40917. var flipY = opt.flipY !== false
  40918. // the desired BMFont data
  40919. var font = opt.font
  40920. // determine texture size from font file
  40921. var texWidth = font.common.scaleW
  40922. var texHeight = font.common.scaleH
  40923. // get visible glyphs
  40924. var glyphs = this.layout.glyphs.filter(function (glyph) {
  40925. var bitmap = glyph.data
  40926. return bitmap.width * bitmap.height > 0
  40927. })
  40928. // provide visible glyphs for convenience
  40929. this.visibleGlyphs = glyphs
  40930. // get common vertex data
  40931. var positions = vertices.positions(glyphs)
  40932. var uvs = vertices.uvs(glyphs, texWidth, texHeight, flipY)
  40933. var indices = createIndices({
  40934. clockwise: true,
  40935. type: 'uint16',
  40936. count: glyphs.length
  40937. })
  40938. // update vertex data
  40939. buffer.index(this, indices, 1, 'uint16')
  40940. buffer.attr(this, 'position', positions, 2)
  40941. buffer.attr(this, 'uv', uvs, 2)
  40942. // update multipage data
  40943. if (!opt.multipage && 'page' in this.attributes) {
  40944. // disable multipage rendering
  40945. this.removeAttribute('page')
  40946. } else if (opt.multipage) {
  40947. var pages = vertices.pages(glyphs)
  40948. // enable multipage rendering
  40949. buffer.attr(this, 'page', pages, 1)
  40950. }
  40951. }
  40952. TextGeometry.prototype.computeBoundingSphere = function () {
  40953. if (this.boundingSphere === null) {
  40954. this.boundingSphere = new THREE.Sphere()
  40955. }
  40956. var positions = this.attributes.position.array
  40957. var itemSize = this.attributes.position.itemSize
  40958. if (!positions || !itemSize || positions.length < 2) {
  40959. this.boundingSphere.radius = 0
  40960. this.boundingSphere.center.set(0, 0, 0)
  40961. return
  40962. }
  40963. utils.computeSphere(positions, this.boundingSphere)
  40964. if (isNaN(this.boundingSphere.radius)) {
  40965. console.error('THREE.BufferGeometry.computeBoundingSphere(): ' +
  40966. 'Computed radius is NaN. The ' +
  40967. '"position" attribute is likely to have NaN values.')
  40968. }
  40969. }
  40970. TextGeometry.prototype.computeBoundingBox = function () {
  40971. if (this.boundingBox === null) {
  40972. this.boundingBox = new THREE.Box3()
  40973. }
  40974. var bbox = this.boundingBox
  40975. var positions = this.attributes.position.array
  40976. var itemSize = this.attributes.position.itemSize
  40977. if (!positions || !itemSize || positions.length < 2) {
  40978. bbox.makeEmpty()
  40979. return
  40980. }
  40981. utils.computeBox(positions, bbox)
  40982. }
  40983. },{"./lib/utils":64,"./lib/vertices":65,"inherits":30,"layout-bmfont-text":36,"object-assign":39,"quad-indices":51,"three-buffer-vertex-data":66}],64:[function(_dereq_,module,exports){
  40984. var itemSize = 2
  40985. var box = { min: [0, 0], max: [0, 0] }
  40986. function bounds (positions) {
  40987. var count = positions.length / itemSize
  40988. box.min[0] = positions[0]
  40989. box.min[1] = positions[1]
  40990. box.max[0] = positions[0]
  40991. box.max[1] = positions[1]
  40992. for (var i = 0; i < count; i++) {
  40993. var x = positions[i * itemSize + 0]
  40994. var y = positions[i * itemSize + 1]
  40995. box.min[0] = Math.min(x, box.min[0])
  40996. box.min[1] = Math.min(y, box.min[1])
  40997. box.max[0] = Math.max(x, box.max[0])
  40998. box.max[1] = Math.max(y, box.max[1])
  40999. }
  41000. }
  41001. module.exports.computeBox = function (positions, output) {
  41002. bounds(positions)
  41003. output.min.set(box.min[0], box.min[1], 0)
  41004. output.max.set(box.max[0], box.max[1], 0)
  41005. }
  41006. module.exports.computeSphere = function (positions, output) {
  41007. bounds(positions)
  41008. var minX = box.min[0]
  41009. var minY = box.min[1]
  41010. var maxX = box.max[0]
  41011. var maxY = box.max[1]
  41012. var width = maxX - minX
  41013. var height = maxY - minY
  41014. var length = Math.sqrt(width * width + height * height)
  41015. output.center.set(minX + width / 2, minY + height / 2, 0)
  41016. output.radius = length / 2
  41017. }
  41018. },{}],65:[function(_dereq_,module,exports){
  41019. module.exports.pages = function pages (glyphs) {
  41020. var pages = new Float32Array(glyphs.length * 4 * 1)
  41021. var i = 0
  41022. glyphs.forEach(function (glyph) {
  41023. var id = glyph.data.page || 0
  41024. pages[i++] = id
  41025. pages[i++] = id
  41026. pages[i++] = id
  41027. pages[i++] = id
  41028. })
  41029. return pages
  41030. }
  41031. module.exports.uvs = function uvs (glyphs, texWidth, texHeight, flipY) {
  41032. var uvs = new Float32Array(glyphs.length * 4 * 2)
  41033. var i = 0
  41034. glyphs.forEach(function (glyph) {
  41035. var bitmap = glyph.data
  41036. var bw = (bitmap.x + bitmap.width)
  41037. var bh = (bitmap.y + bitmap.height)
  41038. // top left position
  41039. var u0 = bitmap.x / texWidth
  41040. var v1 = bitmap.y / texHeight
  41041. var u1 = bw / texWidth
  41042. var v0 = bh / texHeight
  41043. if (flipY) {
  41044. v1 = (texHeight - bitmap.y) / texHeight
  41045. v0 = (texHeight - bh) / texHeight
  41046. }
  41047. // BL
  41048. uvs[i++] = u0
  41049. uvs[i++] = v1
  41050. // TL
  41051. uvs[i++] = u0
  41052. uvs[i++] = v0
  41053. // TR
  41054. uvs[i++] = u1
  41055. uvs[i++] = v0
  41056. // BR
  41057. uvs[i++] = u1
  41058. uvs[i++] = v1
  41059. })
  41060. return uvs
  41061. }
  41062. module.exports.positions = function positions (glyphs) {
  41063. var positions = new Float32Array(glyphs.length * 4 * 2)
  41064. var i = 0
  41065. glyphs.forEach(function (glyph) {
  41066. var bitmap = glyph.data
  41067. // bottom left position
  41068. var x = glyph.position[0] + bitmap.xoffset
  41069. var y = glyph.position[1] + bitmap.yoffset
  41070. // quad size
  41071. var w = bitmap.width
  41072. var h = bitmap.height
  41073. // BL
  41074. positions[i++] = x
  41075. positions[i++] = y
  41076. // TL
  41077. positions[i++] = x
  41078. positions[i++] = y + h
  41079. // TR
  41080. positions[i++] = x + w
  41081. positions[i++] = y + h
  41082. // BR
  41083. positions[i++] = x + w
  41084. positions[i++] = y
  41085. })
  41086. return positions
  41087. }
  41088. },{}],66:[function(_dereq_,module,exports){
  41089. var flatten = _dereq_('flatten-vertex-data')
  41090. var warned = false;
  41091. module.exports.attr = setAttribute
  41092. module.exports.index = setIndex
  41093. function setIndex (geometry, data, itemSize, dtype) {
  41094. if (typeof itemSize !== 'number') itemSize = 1
  41095. if (typeof dtype !== 'string') dtype = 'uint16'
  41096. var isR69 = !geometry.index && typeof geometry.setIndex !== 'function'
  41097. var attrib = isR69 ? geometry.getAttribute('index') : geometry.index
  41098. var newAttrib = updateAttribute(attrib, data, itemSize, dtype)
  41099. if (newAttrib) {
  41100. if (isR69) geometry.addAttribute('index', newAttrib)
  41101. else geometry.index = newAttrib
  41102. }
  41103. }
  41104. function setAttribute (geometry, key, data, itemSize, dtype) {
  41105. if (typeof itemSize !== 'number') itemSize = 3
  41106. if (typeof dtype !== 'string') dtype = 'float32'
  41107. if (Array.isArray(data) &&
  41108. Array.isArray(data[0]) &&
  41109. data[0].length !== itemSize) {
  41110. throw new Error('Nested vertex array has unexpected size; expected ' +
  41111. itemSize + ' but found ' + data[0].length)
  41112. }
  41113. var attrib = geometry.getAttribute(key)
  41114. var newAttrib = updateAttribute(attrib, data, itemSize, dtype)
  41115. geometry.setAttribute(key, newAttrib)
  41116. }
  41117. function updateAttribute (attrib, data, itemSize, dtype) {
  41118. data = data || []
  41119. // create a new array with desired type
  41120. data = flatten(data, dtype)
  41121. attrib = new THREE.BufferAttribute(data, itemSize);
  41122. attrib.itemSize = itemSize;
  41123. attrib.needsUpdate = true;
  41124. return attrib
  41125. }
  41126. // Test whether the attribute needs to be re-created,
  41127. // returns false if we can re-use it as-is.
  41128. function rebuildAttribute (attrib, data, itemSize) {
  41129. if (attrib.itemSize !== itemSize) return true
  41130. if (!attrib.array) return true
  41131. var attribLength = attrib.array.length
  41132. if (Array.isArray(data) && Array.isArray(data[0])) {
  41133. // [ [ x, y, z ] ]
  41134. return attribLength !== data.length * itemSize
  41135. } else {
  41136. // [ x, y, z ]
  41137. return attribLength !== data.length
  41138. }
  41139. return false
  41140. }
  41141. },{"flatten-vertex-data":23}],67:[function(_dereq_,module,exports){
  41142. (function (setImmediate,clearImmediate){
  41143. var nextTick = _dereq_('process/browser.js').nextTick;
  41144. var apply = Function.prototype.apply;
  41145. var slice = Array.prototype.slice;
  41146. var immediateIds = {};
  41147. var nextImmediateId = 0;
  41148. // DOM APIs, for completeness
  41149. exports.setTimeout = function() {
  41150. return new Timeout(apply.call(setTimeout, window, arguments), clearTimeout);
  41151. };
  41152. exports.setInterval = function() {
  41153. return new Timeout(apply.call(setInterval, window, arguments), clearInterval);
  41154. };
  41155. exports.clearTimeout =
  41156. exports.clearInterval = function(timeout) { timeout.close(); };
  41157. function Timeout(id, clearFn) {
  41158. this._id = id;
  41159. this._clearFn = clearFn;
  41160. }
  41161. Timeout.prototype.unref = Timeout.prototype.ref = function() {};
  41162. Timeout.prototype.close = function() {
  41163. this._clearFn.call(window, this._id);
  41164. };
  41165. // Does not start the time, just sets up the members needed.
  41166. exports.enroll = function(item, msecs) {
  41167. clearTimeout(item._idleTimeoutId);
  41168. item._idleTimeout = msecs;
  41169. };
  41170. exports.unenroll = function(item) {
  41171. clearTimeout(item._idleTimeoutId);
  41172. item._idleTimeout = -1;
  41173. };
  41174. exports._unrefActive = exports.active = function(item) {
  41175. clearTimeout(item._idleTimeoutId);
  41176. var msecs = item._idleTimeout;
  41177. if (msecs >= 0) {
  41178. item._idleTimeoutId = setTimeout(function onTimeout() {
  41179. if (item._onTimeout)
  41180. item._onTimeout();
  41181. }, msecs);
  41182. }
  41183. };
  41184. // That's not how node.js implements it but the exposed api is the same.
  41185. exports.setImmediate = typeof setImmediate === "function" ? setImmediate : function(fn) {
  41186. var id = nextImmediateId++;
  41187. var args = arguments.length < 2 ? false : slice.call(arguments, 1);
  41188. immediateIds[id] = true;
  41189. nextTick(function onNextTick() {
  41190. if (immediateIds[id]) {
  41191. // fn.call() is faster so we optimize for the common use-case
  41192. // @see http://jsperf.com/call-apply-segu
  41193. if (args) {
  41194. fn.apply(null, args);
  41195. } else {
  41196. fn.call(null);
  41197. }
  41198. // Prevent ids from leaking
  41199. exports.clearImmediate(id);
  41200. }
  41201. });
  41202. return id;
  41203. };
  41204. exports.clearImmediate = typeof clearImmediate === "function" ? clearImmediate : function(id) {
  41205. delete immediateIds[id];
  41206. };
  41207. }).call(this,_dereq_("timers").setImmediate,_dereq_("timers").clearImmediate)
  41208. },{"process/browser.js":49,"timers":67}],68:[function(_dereq_,module,exports){
  41209. (function (global){
  41210. /**
  41211. * @license
  41212. * webvr-polyfill
  41213. * Copyright (c) 2015-2017 Google
  41214. * Licensed under the Apache License, Version 2.0 (the "License");
  41215. * you may not use this file except in compliance with the License.
  41216. * You may obtain a copy of the License at
  41217. *
  41218. * http://www.apache.org/licenses/LICENSE-2.0
  41219. *
  41220. * Unless required by applicable law or agreed to in writing, software
  41221. * distributed under the License is distributed on an "AS IS" BASIS,
  41222. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  41223. * See the License for the specific language governing permissions and
  41224. * limitations under the License.
  41225. */
  41226. /**
  41227. * @license
  41228. * cardboard-vr-display
  41229. * Copyright (c) 2015-2017 Google
  41230. * Licensed under the Apache License, Version 2.0 (the "License");
  41231. * you may not use this file except in compliance with the License.
  41232. * You may obtain a copy of the License at
  41233. *
  41234. * http://www.apache.org/licenses/LICENSE-2.0
  41235. *
  41236. * Unless required by applicable law or agreed to in writing, software
  41237. * distributed under the License is distributed on an "AS IS" BASIS,
  41238. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  41239. * See the License for the specific language governing permissions and
  41240. * limitations under the License.
  41241. */
  41242. /**
  41243. * @license
  41244. * webvr-polyfill-dpdb
  41245. * Copyright (c) 2017 Google
  41246. * Licensed under the Apache License, Version 2.0 (the "License");
  41247. * you may not use this file except in compliance with the License.
  41248. * You may obtain a copy of the License at
  41249. *
  41250. * http://www.apache.org/licenses/LICENSE-2.0
  41251. *
  41252. * Unless required by applicable law or agreed to in writing, software
  41253. * distributed under the License is distributed on an "AS IS" BASIS,
  41254. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  41255. * See the License for the specific language governing permissions and
  41256. * limitations under the License.
  41257. */
  41258. /**
  41259. * @license
  41260. * wglu-preserve-state
  41261. * Copyright (c) 2016, Brandon Jones.
  41262. *
  41263. * Permission is hereby granted, free of charge, to any person obtaining a copy
  41264. * of this software and associated documentation files (the "Software"), to deal
  41265. * in the Software without restriction, including without limitation the rights
  41266. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  41267. * copies of the Software, and to permit persons to whom the Software is
  41268. * furnished to do so, subject to the following conditions:
  41269. *
  41270. * The above copyright notice and this permission notice shall be included in
  41271. * all copies or substantial portions of the Software.
  41272. *
  41273. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  41274. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  41275. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  41276. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  41277. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  41278. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  41279. * THE SOFTWARE.
  41280. */
  41281. /**
  41282. * @license
  41283. * nosleep.js
  41284. * Copyright (c) 2017, Rich Tibbett
  41285. *
  41286. * Permission is hereby granted, free of charge, to any person obtaining a copy
  41287. * of this software and associated documentation files (the "Software"), to deal
  41288. * in the Software without restriction, including without limitation the rights
  41289. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  41290. * copies of the Software, and to permit persons to whom the Software is
  41291. * furnished to do so, subject to the following conditions:
  41292. *
  41293. * The above copyright notice and this permission notice shall be included in
  41294. * all copies or substantial portions of the Software.
  41295. *
  41296. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  41297. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  41298. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  41299. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  41300. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  41301. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  41302. * THE SOFTWARE.
  41303. */
  41304. (function (global, factory) {
  41305. typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
  41306. typeof define === 'function' && define.amd ? define(factory) :
  41307. (global.WebVRPolyfill = factory());
  41308. }(this, (function () { 'use strict';
  41309. var commonjsGlobal = typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
  41310. function unwrapExports (x) {
  41311. return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
  41312. }
  41313. function createCommonjsModule(fn, module) {
  41314. return module = { exports: {} }, fn(module, module.exports), module.exports;
  41315. }
  41316. var isMobile = function isMobile() {
  41317. return (/Android/i.test(navigator.userAgent) || /iPhone|iPad|iPod/i.test(navigator.userAgent)
  41318. );
  41319. };
  41320. var copyArray = function copyArray(source, dest) {
  41321. for (var i = 0, n = source.length; i < n; i++) {
  41322. dest[i] = source[i];
  41323. }
  41324. };
  41325. var extend = function extend(dest, src) {
  41326. for (var key in src) {
  41327. if (src.hasOwnProperty(key)) {
  41328. dest[key] = src[key];
  41329. }
  41330. }
  41331. return dest;
  41332. };
  41333. var cardboardVrDisplay = createCommonjsModule(function (module, exports) {
  41334. /**
  41335. * @license
  41336. * cardboard-vr-display
  41337. * Copyright (c) 2015-2017 Google
  41338. * Licensed under the Apache License, Version 2.0 (the "License");
  41339. * you may not use this file except in compliance with the License.
  41340. * You may obtain a copy of the License at
  41341. *
  41342. * http://www.apache.org/licenses/LICENSE-2.0
  41343. *
  41344. * Unless required by applicable law or agreed to in writing, software
  41345. * distributed under the License is distributed on an "AS IS" BASIS,
  41346. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  41347. * See the License for the specific language governing permissions and
  41348. * limitations under the License.
  41349. */
  41350. /**
  41351. * @license
  41352. * gl-preserve-state
  41353. * Copyright (c) 2016, Brandon Jones.
  41354. *
  41355. * Permission is hereby granted, free of charge, to any person obtaining a copy
  41356. * of this software and associated documentation files (the "Software"), to deal
  41357. * in the Software without restriction, including without limitation the rights
  41358. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  41359. * copies of the Software, and to permit persons to whom the Software is
  41360. * furnished to do so, subject to the following conditions:
  41361. *
  41362. * The above copyright notice and this permission notice shall be included in
  41363. * all copies or substantial portions of the Software.
  41364. *
  41365. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  41366. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  41367. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  41368. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  41369. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  41370. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  41371. * THE SOFTWARE.
  41372. */
  41373. /**
  41374. * @license
  41375. * webvr-polyfill-dpdb
  41376. * Copyright (c) 2015-2017 Google
  41377. * Licensed under the Apache License, Version 2.0 (the "License");
  41378. * you may not use this file except in compliance with the License.
  41379. * You may obtain a copy of the License at
  41380. *
  41381. * http://www.apache.org/licenses/LICENSE-2.0
  41382. *
  41383. * Unless required by applicable law or agreed to in writing, software
  41384. * distributed under the License is distributed on an "AS IS" BASIS,
  41385. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  41386. * See the License for the specific language governing permissions and
  41387. * limitations under the License.
  41388. */
  41389. /**
  41390. * @license
  41391. * nosleep.js
  41392. * Copyright (c) 2017, Rich Tibbett
  41393. *
  41394. * Permission is hereby granted, free of charge, to any person obtaining a copy
  41395. * of this software and associated documentation files (the "Software"), to deal
  41396. * in the Software without restriction, including without limitation the rights
  41397. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  41398. * copies of the Software, and to permit persons to whom the Software is
  41399. * furnished to do so, subject to the following conditions:
  41400. *
  41401. * The above copyright notice and this permission notice shall be included in
  41402. * all copies or substantial portions of the Software.
  41403. *
  41404. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  41405. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  41406. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  41407. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  41408. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  41409. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  41410. * THE SOFTWARE.
  41411. */
  41412. (function (global, factory) {
  41413. module.exports = factory();
  41414. }(commonjsGlobal, (function () { var classCallCheck = function (instance, Constructor) {
  41415. if (!(instance instanceof Constructor)) {
  41416. throw new TypeError("Cannot call a class as a function");
  41417. }
  41418. };
  41419. var createClass = function () {
  41420. function defineProperties(target, props) {
  41421. for (var i = 0; i < props.length; i++) {
  41422. var descriptor = props[i];
  41423. descriptor.enumerable = descriptor.enumerable || false;
  41424. descriptor.configurable = true;
  41425. if ("value" in descriptor) descriptor.writable = true;
  41426. Object.defineProperty(target, descriptor.key, descriptor);
  41427. }
  41428. }
  41429. return function (Constructor, protoProps, staticProps) {
  41430. if (protoProps) defineProperties(Constructor.prototype, protoProps);
  41431. if (staticProps) defineProperties(Constructor, staticProps);
  41432. return Constructor;
  41433. };
  41434. }();
  41435. var slicedToArray = function () {
  41436. function sliceIterator(arr, i) {
  41437. var _arr = [];
  41438. var _n = true;
  41439. var _d = false;
  41440. var _e = undefined;
  41441. try {
  41442. for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {
  41443. _arr.push(_s.value);
  41444. if (i && _arr.length === i) break;
  41445. }
  41446. } catch (err) {
  41447. _d = true;
  41448. _e = err;
  41449. } finally {
  41450. try {
  41451. if (!_n && _i["return"]) _i["return"]();
  41452. } finally {
  41453. if (_d) throw _e;
  41454. }
  41455. }
  41456. return _arr;
  41457. }
  41458. return function (arr, i) {
  41459. if (Array.isArray(arr)) {
  41460. return arr;
  41461. } else if (Symbol.iterator in Object(arr)) {
  41462. return sliceIterator(arr, i);
  41463. } else {
  41464. throw new TypeError("Invalid attempt to destructure non-iterable instance");
  41465. }
  41466. };
  41467. }();
  41468. var MIN_TIMESTEP = 0.001;
  41469. var MAX_TIMESTEP = 1;
  41470. var dataUri = function dataUri(mimeType, svg) {
  41471. return 'data:' + mimeType + ',' + encodeURIComponent(svg);
  41472. };
  41473. var lerp = function lerp(a, b, t) {
  41474. return a + (b - a) * t;
  41475. };
  41476. var isIOS = function () {
  41477. var isIOS = /iPad|iPhone|iPod/.test(navigator.platform);
  41478. return function () {
  41479. return isIOS;
  41480. };
  41481. }();
  41482. var isWebViewAndroid = function () {
  41483. var isWebViewAndroid = navigator.userAgent.indexOf('Version') !== -1 && navigator.userAgent.indexOf('Android') !== -1 && navigator.userAgent.indexOf('Chrome') !== -1;
  41484. return function () {
  41485. return isWebViewAndroid;
  41486. };
  41487. }();
  41488. var isSafari = function () {
  41489. var isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  41490. return function () {
  41491. return isSafari;
  41492. };
  41493. }();
  41494. var isFirefoxAndroid = function () {
  41495. var isFirefoxAndroid = navigator.userAgent.indexOf('Firefox') !== -1 && navigator.userAgent.indexOf('Android') !== -1;
  41496. return function () {
  41497. return isFirefoxAndroid;
  41498. };
  41499. }();
  41500. var getChromeVersion = function () {
  41501. var match = navigator.userAgent.match(/.*Chrome\/([0-9]+)/);
  41502. var value = match ? parseInt(match[1], 10) : null;
  41503. return function () {
  41504. return value;
  41505. };
  41506. }();
  41507. var isSafariWithoutDeviceMotion = function () {
  41508. var value = false;
  41509. value = isIOS() && isSafari() && navigator.userAgent.indexOf('13_4') !== -1;
  41510. return function () {
  41511. return value;
  41512. };
  41513. }();
  41514. var isChromeWithoutDeviceMotion = function () {
  41515. var value = false;
  41516. if (getChromeVersion() === 65) {
  41517. var match = navigator.userAgent.match(/.*Chrome\/([0-9\.]*)/);
  41518. if (match) {
  41519. var _match$1$split = match[1].split('.'),
  41520. _match$1$split2 = slicedToArray(_match$1$split, 4),
  41521. major = _match$1$split2[0],
  41522. minor = _match$1$split2[1],
  41523. branch = _match$1$split2[2],
  41524. build = _match$1$split2[3];
  41525. value = parseInt(branch, 10) === 3325 && parseInt(build, 10) < 148;
  41526. }
  41527. }
  41528. return function () {
  41529. return value;
  41530. };
  41531. }();
  41532. var isR7 = function () {
  41533. var isR7 = navigator.userAgent.indexOf('R7 Build') !== -1;
  41534. return function () {
  41535. return isR7;
  41536. };
  41537. }();
  41538. var isLandscapeMode = function isLandscapeMode() {
  41539. var rtn = window.orientation == 90 || window.orientation == -90;
  41540. return isR7() ? !rtn : rtn;
  41541. };
  41542. var isTimestampDeltaValid = function isTimestampDeltaValid(timestampDeltaS) {
  41543. if (isNaN(timestampDeltaS)) {
  41544. return false;
  41545. }
  41546. if (timestampDeltaS <= MIN_TIMESTEP) {
  41547. return false;
  41548. }
  41549. if (timestampDeltaS > MAX_TIMESTEP) {
  41550. return false;
  41551. }
  41552. return true;
  41553. };
  41554. var getScreenWidth = function getScreenWidth() {
  41555. return Math.max(window.screen.width, window.screen.height) * window.devicePixelRatio;
  41556. };
  41557. var getScreenHeight = function getScreenHeight() {
  41558. return Math.min(window.screen.width, window.screen.height) * window.devicePixelRatio;
  41559. };
  41560. var requestFullscreen = function requestFullscreen(element) {
  41561. if (isWebViewAndroid()) {
  41562. return false;
  41563. }
  41564. if (element.requestFullscreen) {
  41565. element.requestFullscreen();
  41566. } else if (element.webkitRequestFullscreen) {
  41567. element.webkitRequestFullscreen();
  41568. } else if (element.mozRequestFullScreen) {
  41569. element.mozRequestFullScreen();
  41570. } else if (element.msRequestFullscreen) {
  41571. element.msRequestFullscreen();
  41572. } else {
  41573. return false;
  41574. }
  41575. return true;
  41576. };
  41577. var exitFullscreen = function exitFullscreen() {
  41578. if (document.exitFullscreen) {
  41579. document.exitFullscreen();
  41580. } else if (document.webkitExitFullscreen) {
  41581. document.webkitExitFullscreen();
  41582. } else if (document.mozCancelFullScreen) {
  41583. document.mozCancelFullScreen();
  41584. } else if (document.msExitFullscreen) {
  41585. document.msExitFullscreen();
  41586. } else {
  41587. return false;
  41588. }
  41589. return true;
  41590. };
  41591. var getFullscreenElement = function getFullscreenElement() {
  41592. return document.fullscreenElement || document.webkitFullscreenElement || document.mozFullScreenElement || document.msFullscreenElement;
  41593. };
  41594. var linkProgram = function linkProgram(gl, vertexSource, fragmentSource, attribLocationMap) {
  41595. var vertexShader = gl.createShader(gl.VERTEX_SHADER);
  41596. gl.shaderSource(vertexShader, vertexSource);
  41597. gl.compileShader(vertexShader);
  41598. var fragmentShader = gl.createShader(gl.FRAGMENT_SHADER);
  41599. gl.shaderSource(fragmentShader, fragmentSource);
  41600. gl.compileShader(fragmentShader);
  41601. var program = gl.createProgram();
  41602. gl.attachShader(program, vertexShader);
  41603. gl.attachShader(program, fragmentShader);
  41604. for (var attribName in attribLocationMap) {
  41605. gl.bindAttribLocation(program, attribLocationMap[attribName], attribName);
  41606. }gl.linkProgram(program);
  41607. gl.deleteShader(vertexShader);
  41608. gl.deleteShader(fragmentShader);
  41609. return program;
  41610. };
  41611. var getProgramUniforms = function getProgramUniforms(gl, program) {
  41612. var uniforms = {};
  41613. var uniformCount = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS);
  41614. var uniformName = '';
  41615. for (var i = 0; i < uniformCount; i++) {
  41616. var uniformInfo = gl.getActiveUniform(program, i);
  41617. uniformName = uniformInfo.name.replace('[0]', '');
  41618. uniforms[uniformName] = gl.getUniformLocation(program, uniformName);
  41619. }
  41620. return uniforms;
  41621. };
  41622. var orthoMatrix = function orthoMatrix(out, left, right, bottom, top, near, far) {
  41623. var lr = 1 / (left - right),
  41624. bt = 1 / (bottom - top),
  41625. nf = 1 / (near - far);
  41626. out[0] = -2 * lr;
  41627. out[1] = 0;
  41628. out[2] = 0;
  41629. out[3] = 0;
  41630. out[4] = 0;
  41631. out[5] = -2 * bt;
  41632. out[6] = 0;
  41633. out[7] = 0;
  41634. out[8] = 0;
  41635. out[9] = 0;
  41636. out[10] = 2 * nf;
  41637. out[11] = 0;
  41638. out[12] = (left + right) * lr;
  41639. out[13] = (top + bottom) * bt;
  41640. out[14] = (far + near) * nf;
  41641. out[15] = 1;
  41642. return out;
  41643. };
  41644. var isMobile = function isMobile() {
  41645. var check = false;
  41646. (function (a) {
  41647. if (/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(a) || /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(a.substr(0, 4))) check = true;
  41648. })(navigator.userAgent || navigator.vendor || window.opera);
  41649. return check;
  41650. };
  41651. var extend = function extend(dest, src) {
  41652. for (var key in src) {
  41653. if (src.hasOwnProperty(key)) {
  41654. dest[key] = src[key];
  41655. }
  41656. }
  41657. return dest;
  41658. };
  41659. var safariCssSizeWorkaround = function safariCssSizeWorkaround(canvas) {
  41660. if (isIOS()) {
  41661. var width = canvas.style.width;
  41662. var height = canvas.style.height;
  41663. canvas.style.width = parseInt(width) + 1 + 'px';
  41664. canvas.style.height = parseInt(height) + 'px';
  41665. setTimeout(function () {
  41666. canvas.style.width = width;
  41667. canvas.style.height = height;
  41668. }, 100);
  41669. }
  41670. window.canvas = canvas;
  41671. };
  41672. var frameDataFromPose = function () {
  41673. var piOver180 = Math.PI / 180.0;
  41674. var rad45 = Math.PI * 0.25;
  41675. function mat4_perspectiveFromFieldOfView(out, fov, near, far) {
  41676. var upTan = Math.tan(fov ? fov.upDegrees * piOver180 : rad45),
  41677. downTan = Math.tan(fov ? fov.downDegrees * piOver180 : rad45),
  41678. leftTan = Math.tan(fov ? fov.leftDegrees * piOver180 : rad45),
  41679. rightTan = Math.tan(fov ? fov.rightDegrees * piOver180 : rad45),
  41680. xScale = 2.0 / (leftTan + rightTan),
  41681. yScale = 2.0 / (upTan + downTan);
  41682. out[0] = xScale;
  41683. out[1] = 0.0;
  41684. out[2] = 0.0;
  41685. out[3] = 0.0;
  41686. out[4] = 0.0;
  41687. out[5] = yScale;
  41688. out[6] = 0.0;
  41689. out[7] = 0.0;
  41690. out[8] = -((leftTan - rightTan) * xScale * 0.5);
  41691. out[9] = (upTan - downTan) * yScale * 0.5;
  41692. out[10] = far / (near - far);
  41693. out[11] = -1.0;
  41694. out[12] = 0.0;
  41695. out[13] = 0.0;
  41696. out[14] = far * near / (near - far);
  41697. out[15] = 0.0;
  41698. return out;
  41699. }
  41700. function mat4_fromRotationTranslation(out, q, v) {
  41701. var x = q[0],
  41702. y = q[1],
  41703. z = q[2],
  41704. w = q[3],
  41705. x2 = x + x,
  41706. y2 = y + y,
  41707. z2 = z + z,
  41708. xx = x * x2,
  41709. xy = x * y2,
  41710. xz = x * z2,
  41711. yy = y * y2,
  41712. yz = y * z2,
  41713. zz = z * z2,
  41714. wx = w * x2,
  41715. wy = w * y2,
  41716. wz = w * z2;
  41717. out[0] = 1 - (yy + zz);
  41718. out[1] = xy + wz;
  41719. out[2] = xz - wy;
  41720. out[3] = 0;
  41721. out[4] = xy - wz;
  41722. out[5] = 1 - (xx + zz);
  41723. out[6] = yz + wx;
  41724. out[7] = 0;
  41725. out[8] = xz + wy;
  41726. out[9] = yz - wx;
  41727. out[10] = 1 - (xx + yy);
  41728. out[11] = 0;
  41729. out[12] = v[0];
  41730. out[13] = v[1];
  41731. out[14] = v[2];
  41732. out[15] = 1;
  41733. return out;
  41734. }
  41735. function mat4_translate(out, a, v) {
  41736. var x = v[0],
  41737. y = v[1],
  41738. z = v[2],
  41739. a00,
  41740. a01,
  41741. a02,
  41742. a03,
  41743. a10,
  41744. a11,
  41745. a12,
  41746. a13,
  41747. a20,
  41748. a21,
  41749. a22,
  41750. a23;
  41751. if (a === out) {
  41752. out[12] = a[0] * x + a[4] * y + a[8] * z + a[12];
  41753. out[13] = a[1] * x + a[5] * y + a[9] * z + a[13];
  41754. out[14] = a[2] * x + a[6] * y + a[10] * z + a[14];
  41755. out[15] = a[3] * x + a[7] * y + a[11] * z + a[15];
  41756. } else {
  41757. a00 = a[0];a01 = a[1];a02 = a[2];a03 = a[3];
  41758. a10 = a[4];a11 = a[5];a12 = a[6];a13 = a[7];
  41759. a20 = a[8];a21 = a[9];a22 = a[10];a23 = a[11];
  41760. out[0] = a00;out[1] = a01;out[2] = a02;out[3] = a03;
  41761. out[4] = a10;out[5] = a11;out[6] = a12;out[7] = a13;
  41762. out[8] = a20;out[9] = a21;out[10] = a22;out[11] = a23;
  41763. out[12] = a00 * x + a10 * y + a20 * z + a[12];
  41764. out[13] = a01 * x + a11 * y + a21 * z + a[13];
  41765. out[14] = a02 * x + a12 * y + a22 * z + a[14];
  41766. out[15] = a03 * x + a13 * y + a23 * z + a[15];
  41767. }
  41768. return out;
  41769. }
  41770. function mat4_invert(out, a) {
  41771. var a00 = a[0],
  41772. a01 = a[1],
  41773. a02 = a[2],
  41774. a03 = a[3],
  41775. a10 = a[4],
  41776. a11 = a[5],
  41777. a12 = a[6],
  41778. a13 = a[7],
  41779. a20 = a[8],
  41780. a21 = a[9],
  41781. a22 = a[10],
  41782. a23 = a[11],
  41783. a30 = a[12],
  41784. a31 = a[13],
  41785. a32 = a[14],
  41786. a33 = a[15],
  41787. b00 = a00 * a11 - a01 * a10,
  41788. b01 = a00 * a12 - a02 * a10,
  41789. b02 = a00 * a13 - a03 * a10,
  41790. b03 = a01 * a12 - a02 * a11,
  41791. b04 = a01 * a13 - a03 * a11,
  41792. b05 = a02 * a13 - a03 * a12,
  41793. b06 = a20 * a31 - a21 * a30,
  41794. b07 = a20 * a32 - a22 * a30,
  41795. b08 = a20 * a33 - a23 * a30,
  41796. b09 = a21 * a32 - a22 * a31,
  41797. b10 = a21 * a33 - a23 * a31,
  41798. b11 = a22 * a33 - a23 * a32,
  41799. det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;
  41800. if (!det) {
  41801. return null;
  41802. }
  41803. det = 1.0 / det;
  41804. out[0] = (a11 * b11 - a12 * b10 + a13 * b09) * det;
  41805. out[1] = (a02 * b10 - a01 * b11 - a03 * b09) * det;
  41806. out[2] = (a31 * b05 - a32 * b04 + a33 * b03) * det;
  41807. out[3] = (a22 * b04 - a21 * b05 - a23 * b03) * det;
  41808. out[4] = (a12 * b08 - a10 * b11 - a13 * b07) * det;
  41809. out[5] = (a00 * b11 - a02 * b08 + a03 * b07) * det;
  41810. out[6] = (a32 * b02 - a30 * b05 - a33 * b01) * det;
  41811. out[7] = (a20 * b05 - a22 * b02 + a23 * b01) * det;
  41812. out[8] = (a10 * b10 - a11 * b08 + a13 * b06) * det;
  41813. out[9] = (a01 * b08 - a00 * b10 - a03 * b06) * det;
  41814. out[10] = (a30 * b04 - a31 * b02 + a33 * b00) * det;
  41815. out[11] = (a21 * b02 - a20 * b04 - a23 * b00) * det;
  41816. out[12] = (a11 * b07 - a10 * b09 - a12 * b06) * det;
  41817. out[13] = (a00 * b09 - a01 * b07 + a02 * b06) * det;
  41818. out[14] = (a31 * b01 - a30 * b03 - a32 * b00) * det;
  41819. out[15] = (a20 * b03 - a21 * b01 + a22 * b00) * det;
  41820. return out;
  41821. }
  41822. var defaultOrientation = new Float32Array([0, 0, 0, 1]);
  41823. var defaultPosition = new Float32Array([0, 0, 0]);
  41824. function updateEyeMatrices(projection, view, pose, fov, offset, vrDisplay) {
  41825. mat4_perspectiveFromFieldOfView(projection, fov || null, vrDisplay.depthNear, vrDisplay.depthFar);
  41826. var orientation = pose.orientation || defaultOrientation;
  41827. var position = pose.position || defaultPosition;
  41828. mat4_fromRotationTranslation(view, orientation, position);
  41829. if (offset) mat4_translate(view, view, offset);
  41830. mat4_invert(view, view);
  41831. }
  41832. return function (frameData, pose, vrDisplay) {
  41833. if (!frameData || !pose) return false;
  41834. frameData.pose = pose;
  41835. frameData.timestamp = pose.timestamp;
  41836. updateEyeMatrices(frameData.leftProjectionMatrix, frameData.leftViewMatrix, pose, vrDisplay._getFieldOfView("left"), vrDisplay._getEyeOffset("left"), vrDisplay);
  41837. updateEyeMatrices(frameData.rightProjectionMatrix, frameData.rightViewMatrix, pose, vrDisplay._getFieldOfView("right"), vrDisplay._getEyeOffset("right"), vrDisplay);
  41838. return true;
  41839. };
  41840. }();
  41841. var isInsideCrossOriginIFrame = function isInsideCrossOriginIFrame() {
  41842. var isFramed = window.self !== window.top;
  41843. var refOrigin = getOriginFromUrl(document.referrer);
  41844. var thisOrigin = getOriginFromUrl(window.location.href);
  41845. return isFramed && refOrigin !== thisOrigin;
  41846. };
  41847. var getOriginFromUrl = function getOriginFromUrl(url) {
  41848. var domainIdx;
  41849. var protoSepIdx = url.indexOf("://");
  41850. if (protoSepIdx !== -1) {
  41851. domainIdx = protoSepIdx + 3;
  41852. } else {
  41853. domainIdx = 0;
  41854. }
  41855. var domainEndIdx = url.indexOf('/', domainIdx);
  41856. if (domainEndIdx === -1) {
  41857. domainEndIdx = url.length;
  41858. }
  41859. return url.substring(0, domainEndIdx);
  41860. };
  41861. var getQuaternionAngle = function getQuaternionAngle(quat) {
  41862. if (quat.w > 1) {
  41863. console.warn('getQuaternionAngle: w > 1');
  41864. return 0;
  41865. }
  41866. var angle = 2 * Math.acos(quat.w);
  41867. return angle;
  41868. };
  41869. var warnOnce = function () {
  41870. var observedWarnings = {};
  41871. return function (key, message) {
  41872. if (observedWarnings[key] === undefined) {
  41873. console.warn('webvr-polyfill: ' + message);
  41874. observedWarnings[key] = true;
  41875. }
  41876. };
  41877. }();
  41878. var deprecateWarning = function deprecateWarning(deprecated, suggested) {
  41879. var alternative = suggested ? 'Please use ' + suggested + ' instead.' : '';
  41880. warnOnce(deprecated, deprecated + ' has been deprecated. ' + 'This may not work on native WebVR displays. ' + alternative);
  41881. };
  41882. function WGLUPreserveGLState(gl, bindings, callback) {
  41883. if (!bindings) {
  41884. callback(gl);
  41885. return;
  41886. }
  41887. var boundValues = [];
  41888. var activeTexture = null;
  41889. for (var i = 0; i < bindings.length; ++i) {
  41890. var binding = bindings[i];
  41891. switch (binding) {
  41892. case gl.TEXTURE_BINDING_2D:
  41893. case gl.TEXTURE_BINDING_CUBE_MAP:
  41894. var textureUnit = bindings[++i];
  41895. if (textureUnit < gl.TEXTURE0 || textureUnit > gl.TEXTURE31) {
  41896. console.error("TEXTURE_BINDING_2D or TEXTURE_BINDING_CUBE_MAP must be followed by a valid texture unit");
  41897. boundValues.push(null, null);
  41898. break;
  41899. }
  41900. if (!activeTexture) {
  41901. activeTexture = gl.getParameter(gl.ACTIVE_TEXTURE);
  41902. }
  41903. gl.activeTexture(textureUnit);
  41904. boundValues.push(gl.getParameter(binding), null);
  41905. break;
  41906. case gl.ACTIVE_TEXTURE:
  41907. activeTexture = gl.getParameter(gl.ACTIVE_TEXTURE);
  41908. boundValues.push(null);
  41909. break;
  41910. default:
  41911. boundValues.push(gl.getParameter(binding));
  41912. break;
  41913. }
  41914. }
  41915. callback(gl);
  41916. for (var i = 0; i < bindings.length; ++i) {
  41917. var binding = bindings[i];
  41918. var boundValue = boundValues[i];
  41919. switch (binding) {
  41920. case gl.ACTIVE_TEXTURE:
  41921. break;
  41922. case gl.ARRAY_BUFFER_BINDING:
  41923. gl.bindBuffer(gl.ARRAY_BUFFER, boundValue);
  41924. break;
  41925. case gl.COLOR_CLEAR_VALUE:
  41926. gl.clearColor(boundValue[0], boundValue[1], boundValue[2], boundValue[3]);
  41927. break;
  41928. case gl.COLOR_WRITEMASK:
  41929. gl.colorMask(boundValue[0], boundValue[1], boundValue[2], boundValue[3]);
  41930. break;
  41931. case gl.CURRENT_PROGRAM:
  41932. gl.useProgram(boundValue);
  41933. break;
  41934. case gl.ELEMENT_ARRAY_BUFFER_BINDING:
  41935. gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, boundValue);
  41936. break;
  41937. case gl.FRAMEBUFFER_BINDING:
  41938. gl.bindFramebuffer(gl.FRAMEBUFFER, boundValue);
  41939. break;
  41940. case gl.RENDERBUFFER_BINDING:
  41941. gl.bindRenderbuffer(gl.RENDERBUFFER, boundValue);
  41942. break;
  41943. case gl.TEXTURE_BINDING_2D:
  41944. var textureUnit = bindings[++i];
  41945. if (textureUnit < gl.TEXTURE0 || textureUnit > gl.TEXTURE31)
  41946. break;
  41947. gl.activeTexture(textureUnit);
  41948. gl.bindTexture(gl.TEXTURE_2D, boundValue);
  41949. break;
  41950. case gl.TEXTURE_BINDING_CUBE_MAP:
  41951. var textureUnit = bindings[++i];
  41952. if (textureUnit < gl.TEXTURE0 || textureUnit > gl.TEXTURE31)
  41953. break;
  41954. gl.activeTexture(textureUnit);
  41955. gl.bindTexture(gl.TEXTURE_CUBE_MAP, boundValue);
  41956. break;
  41957. case gl.VIEWPORT:
  41958. gl.viewport(boundValue[0], boundValue[1], boundValue[2], boundValue[3]);
  41959. break;
  41960. case gl.BLEND:
  41961. case gl.CULL_FACE:
  41962. case gl.DEPTH_TEST:
  41963. case gl.SCISSOR_TEST:
  41964. case gl.STENCIL_TEST:
  41965. if (boundValue) {
  41966. gl.enable(binding);
  41967. } else {
  41968. gl.disable(binding);
  41969. }
  41970. break;
  41971. default:
  41972. console.log("No GL restore behavior for 0x" + binding.toString(16));
  41973. break;
  41974. }
  41975. if (activeTexture) {
  41976. gl.activeTexture(activeTexture);
  41977. }
  41978. }
  41979. }
  41980. var glPreserveState = WGLUPreserveGLState;
  41981. var distortionVS = ['attribute vec2 position;', 'attribute vec3 texCoord;', 'varying vec2 vTexCoord;', 'uniform vec4 viewportOffsetScale[2];', 'void main() {', ' vec4 viewport = viewportOffsetScale[int(texCoord.z)];', ' vTexCoord = (texCoord.xy * viewport.zw) + viewport.xy;', ' gl_Position = vec4( position, 1.0, 1.0 );', '}'].join('\n');
  41982. var distortionFS = ['precision mediump float;', 'uniform sampler2D diffuse;', 'varying vec2 vTexCoord;', 'void main() {', ' gl_FragColor = texture2D(diffuse, vTexCoord);', '}'].join('\n');
  41983. function CardboardDistorter(gl, cardboardUI, bufferScale, dirtySubmitFrameBindings) {
  41984. this.gl = gl;
  41985. this.cardboardUI = cardboardUI;
  41986. this.bufferScale = bufferScale;
  41987. this.dirtySubmitFrameBindings = dirtySubmitFrameBindings;
  41988. this.ctxAttribs = gl.getContextAttributes();
  41989. this.instanceExt = gl.getExtension('ANGLE_instanced_arrays');
  41990. this.meshWidth = 20;
  41991. this.meshHeight = 20;
  41992. this.bufferWidth = gl.drawingBufferWidth;
  41993. this.bufferHeight = gl.drawingBufferHeight;
  41994. this.realBindFramebuffer = gl.bindFramebuffer;
  41995. this.realEnable = gl.enable;
  41996. this.realDisable = gl.disable;
  41997. this.realColorMask = gl.colorMask;
  41998. this.realClearColor = gl.clearColor;
  41999. this.realViewport = gl.viewport;
  42000. if (!isIOS()) {
  42001. this.realCanvasWidth = Object.getOwnPropertyDescriptor(gl.canvas.__proto__, 'width');
  42002. this.realCanvasHeight = Object.getOwnPropertyDescriptor(gl.canvas.__proto__, 'height');
  42003. }
  42004. this.isPatched = false;
  42005. this.lastBoundFramebuffer = null;
  42006. this.cullFace = false;
  42007. this.depthTest = false;
  42008. this.blend = false;
  42009. this.scissorTest = false;
  42010. this.stencilTest = false;
  42011. this.viewport = [0, 0, 0, 0];
  42012. this.colorMask = [true, true, true, true];
  42013. this.clearColor = [0, 0, 0, 0];
  42014. this.attribs = {
  42015. position: 0,
  42016. texCoord: 1
  42017. };
  42018. this.program = linkProgram(gl, distortionVS, distortionFS, this.attribs);
  42019. this.uniforms = getProgramUniforms(gl, this.program);
  42020. this.viewportOffsetScale = new Float32Array(8);
  42021. this.setTextureBounds();
  42022. this.vertexBuffer = gl.createBuffer();
  42023. this.indexBuffer = gl.createBuffer();
  42024. this.indexCount = 0;
  42025. this.renderTarget = gl.createTexture();
  42026. this.framebuffer = gl.createFramebuffer();
  42027. this.depthStencilBuffer = null;
  42028. this.depthBuffer = null;
  42029. this.stencilBuffer = null;
  42030. if (this.ctxAttribs.depth && this.ctxAttribs.stencil) {
  42031. this.depthStencilBuffer = gl.createRenderbuffer();
  42032. } else if (this.ctxAttribs.depth) {
  42033. this.depthBuffer = gl.createRenderbuffer();
  42034. } else if (this.ctxAttribs.stencil) {
  42035. this.stencilBuffer = gl.createRenderbuffer();
  42036. }
  42037. this.patch();
  42038. this.onResize();
  42039. }
  42040. CardboardDistorter.prototype.destroy = function () {
  42041. var gl = this.gl;
  42042. this.unpatch();
  42043. gl.deleteProgram(this.program);
  42044. gl.deleteBuffer(this.vertexBuffer);
  42045. gl.deleteBuffer(this.indexBuffer);
  42046. gl.deleteTexture(this.renderTarget);
  42047. gl.deleteFramebuffer(this.framebuffer);
  42048. if (this.depthStencilBuffer) {
  42049. gl.deleteRenderbuffer(this.depthStencilBuffer);
  42050. }
  42051. if (this.depthBuffer) {
  42052. gl.deleteRenderbuffer(this.depthBuffer);
  42053. }
  42054. if (this.stencilBuffer) {
  42055. gl.deleteRenderbuffer(this.stencilBuffer);
  42056. }
  42057. if (this.cardboardUI) {
  42058. this.cardboardUI.destroy();
  42059. }
  42060. };
  42061. CardboardDistorter.prototype.onResize = function () {
  42062. var gl = this.gl;
  42063. var self = this;
  42064. var glState = [gl.RENDERBUFFER_BINDING, gl.TEXTURE_BINDING_2D, gl.TEXTURE0];
  42065. glPreserveState(gl, glState, function (gl) {
  42066. self.realBindFramebuffer.call(gl, gl.FRAMEBUFFER, null);
  42067. if (self.scissorTest) {
  42068. self.realDisable.call(gl, gl.SCISSOR_TEST);
  42069. }
  42070. self.realColorMask.call(gl, true, true, true, true);
  42071. self.realViewport.call(gl, 0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
  42072. self.realClearColor.call(gl, 0, 0, 0, 1);
  42073. gl.clear(gl.COLOR_BUFFER_BIT);
  42074. self.realBindFramebuffer.call(gl, gl.FRAMEBUFFER, self.framebuffer);
  42075. gl.bindTexture(gl.TEXTURE_2D, self.renderTarget);
  42076. gl.texImage2D(gl.TEXTURE_2D, 0, self.ctxAttribs.alpha ? gl.RGBA : gl.RGB, self.bufferWidth, self.bufferHeight, 0, self.ctxAttribs.alpha ? gl.RGBA : gl.RGB, gl.UNSIGNED_BYTE, null);
  42077. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  42078. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  42079. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  42080. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  42081. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, self.renderTarget, 0);
  42082. if (self.ctxAttribs.depth && self.ctxAttribs.stencil) {
  42083. gl.bindRenderbuffer(gl.RENDERBUFFER, self.depthStencilBuffer);
  42084. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, self.bufferWidth, self.bufferHeight);
  42085. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, self.depthStencilBuffer);
  42086. } else if (self.ctxAttribs.depth) {
  42087. gl.bindRenderbuffer(gl.RENDERBUFFER, self.depthBuffer);
  42088. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, self.bufferWidth, self.bufferHeight);
  42089. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, self.depthBuffer);
  42090. } else if (self.ctxAttribs.stencil) {
  42091. gl.bindRenderbuffer(gl.RENDERBUFFER, self.stencilBuffer);
  42092. gl.renderbufferStorage(gl.RENDERBUFFER, gl.STENCIL_INDEX8, self.bufferWidth, self.bufferHeight);
  42093. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.STENCIL_ATTACHMENT, gl.RENDERBUFFER, self.stencilBuffer);
  42094. }
  42095. if (!gl.checkFramebufferStatus(gl.FRAMEBUFFER) === gl.FRAMEBUFFER_COMPLETE) {
  42096. console.error('Framebuffer incomplete!');
  42097. }
  42098. self.realBindFramebuffer.call(gl, gl.FRAMEBUFFER, self.lastBoundFramebuffer);
  42099. if (self.scissorTest) {
  42100. self.realEnable.call(gl, gl.SCISSOR_TEST);
  42101. }
  42102. self.realColorMask.apply(gl, self.colorMask);
  42103. self.realViewport.apply(gl, self.viewport);
  42104. self.realClearColor.apply(gl, self.clearColor);
  42105. });
  42106. if (this.cardboardUI) {
  42107. this.cardboardUI.onResize();
  42108. }
  42109. };
  42110. CardboardDistorter.prototype.patch = function () {
  42111. if (this.isPatched) {
  42112. return;
  42113. }
  42114. var self = this;
  42115. var canvas = this.gl.canvas;
  42116. var gl = this.gl;
  42117. if (!isIOS()) {
  42118. canvas.width = getScreenWidth() * this.bufferScale;
  42119. canvas.height = getScreenHeight() * this.bufferScale;
  42120. Object.defineProperty(canvas, 'width', {
  42121. configurable: true,
  42122. enumerable: true,
  42123. get: function get() {
  42124. return self.bufferWidth;
  42125. },
  42126. set: function set(value) {
  42127. self.bufferWidth = value;
  42128. self.realCanvasWidth.set.call(canvas, value);
  42129. self.onResize();
  42130. }
  42131. });
  42132. Object.defineProperty(canvas, 'height', {
  42133. configurable: true,
  42134. enumerable: true,
  42135. get: function get() {
  42136. return self.bufferHeight;
  42137. },
  42138. set: function set(value) {
  42139. self.bufferHeight = value;
  42140. self.realCanvasHeight.set.call(canvas, value);
  42141. self.onResize();
  42142. }
  42143. });
  42144. }
  42145. this.lastBoundFramebuffer = gl.getParameter(gl.FRAMEBUFFER_BINDING);
  42146. if (this.lastBoundFramebuffer == null) {
  42147. this.lastBoundFramebuffer = this.framebuffer;
  42148. this.gl.bindFramebuffer(gl.FRAMEBUFFER, this.framebuffer);
  42149. }
  42150. this.gl.bindFramebuffer = function (target, framebuffer) {
  42151. self.lastBoundFramebuffer = framebuffer ? framebuffer : self.framebuffer;
  42152. self.realBindFramebuffer.call(gl, target, self.lastBoundFramebuffer);
  42153. };
  42154. this.cullFace = gl.getParameter(gl.CULL_FACE);
  42155. this.depthTest = gl.getParameter(gl.DEPTH_TEST);
  42156. this.blend = gl.getParameter(gl.BLEND);
  42157. this.scissorTest = gl.getParameter(gl.SCISSOR_TEST);
  42158. this.stencilTest = gl.getParameter(gl.STENCIL_TEST);
  42159. gl.enable = function (pname) {
  42160. switch (pname) {
  42161. case gl.CULL_FACE:
  42162. self.cullFace = true;break;
  42163. case gl.DEPTH_TEST:
  42164. self.depthTest = true;break;
  42165. case gl.BLEND:
  42166. self.blend = true;break;
  42167. case gl.SCISSOR_TEST:
  42168. self.scissorTest = true;break;
  42169. case gl.STENCIL_TEST:
  42170. self.stencilTest = true;break;
  42171. }
  42172. self.realEnable.call(gl, pname);
  42173. };
  42174. gl.disable = function (pname) {
  42175. switch (pname) {
  42176. case gl.CULL_FACE:
  42177. self.cullFace = false;break;
  42178. case gl.DEPTH_TEST:
  42179. self.depthTest = false;break;
  42180. case gl.BLEND:
  42181. self.blend = false;break;
  42182. case gl.SCISSOR_TEST:
  42183. self.scissorTest = false;break;
  42184. case gl.STENCIL_TEST:
  42185. self.stencilTest = false;break;
  42186. }
  42187. self.realDisable.call(gl, pname);
  42188. };
  42189. this.colorMask = gl.getParameter(gl.COLOR_WRITEMASK);
  42190. gl.colorMask = function (r, g, b, a) {
  42191. self.colorMask[0] = r;
  42192. self.colorMask[1] = g;
  42193. self.colorMask[2] = b;
  42194. self.colorMask[3] = a;
  42195. self.realColorMask.call(gl, r, g, b, a);
  42196. };
  42197. this.clearColor = gl.getParameter(gl.COLOR_CLEAR_VALUE);
  42198. gl.clearColor = function (r, g, b, a) {
  42199. self.clearColor[0] = r;
  42200. self.clearColor[1] = g;
  42201. self.clearColor[2] = b;
  42202. self.clearColor[3] = a;
  42203. self.realClearColor.call(gl, r, g, b, a);
  42204. };
  42205. this.viewport = gl.getParameter(gl.VIEWPORT);
  42206. gl.viewport = function (x, y, w, h) {
  42207. self.viewport[0] = x;
  42208. self.viewport[1] = y;
  42209. self.viewport[2] = w;
  42210. self.viewport[3] = h;
  42211. self.realViewport.call(gl, x, y, w, h);
  42212. };
  42213. this.isPatched = true;
  42214. safariCssSizeWorkaround(canvas);
  42215. };
  42216. CardboardDistorter.prototype.unpatch = function () {
  42217. if (!this.isPatched) {
  42218. return;
  42219. }
  42220. var gl = this.gl;
  42221. var canvas = this.gl.canvas;
  42222. if (!isIOS()) {
  42223. Object.defineProperty(canvas, 'width', this.realCanvasWidth);
  42224. Object.defineProperty(canvas, 'height', this.realCanvasHeight);
  42225. }
  42226. canvas.width = this.bufferWidth;
  42227. canvas.height = this.bufferHeight;
  42228. gl.bindFramebuffer = this.realBindFramebuffer;
  42229. gl.enable = this.realEnable;
  42230. gl.disable = this.realDisable;
  42231. gl.colorMask = this.realColorMask;
  42232. gl.clearColor = this.realClearColor;
  42233. gl.viewport = this.realViewport;
  42234. if (this.lastBoundFramebuffer == this.framebuffer) {
  42235. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  42236. }
  42237. this.isPatched = false;
  42238. setTimeout(function () {
  42239. safariCssSizeWorkaround(canvas);
  42240. }, 1);
  42241. };
  42242. CardboardDistorter.prototype.setTextureBounds = function (leftBounds, rightBounds) {
  42243. if (!leftBounds) {
  42244. leftBounds = [0, 0, 0.5, 1];
  42245. }
  42246. if (!rightBounds) {
  42247. rightBounds = [0.5, 0, 0.5, 1];
  42248. }
  42249. this.viewportOffsetScale[0] = leftBounds[0];
  42250. this.viewportOffsetScale[1] = leftBounds[1];
  42251. this.viewportOffsetScale[2] = leftBounds[2];
  42252. this.viewportOffsetScale[3] = leftBounds[3];
  42253. this.viewportOffsetScale[4] = rightBounds[0];
  42254. this.viewportOffsetScale[5] = rightBounds[1];
  42255. this.viewportOffsetScale[6] = rightBounds[2];
  42256. this.viewportOffsetScale[7] = rightBounds[3];
  42257. };
  42258. CardboardDistorter.prototype.submitFrame = function () {
  42259. var gl = this.gl;
  42260. var self = this;
  42261. var glState = [];
  42262. if (!this.dirtySubmitFrameBindings) {
  42263. glState.push(gl.CURRENT_PROGRAM, gl.ARRAY_BUFFER_BINDING, gl.ELEMENT_ARRAY_BUFFER_BINDING, gl.TEXTURE_BINDING_2D, gl.TEXTURE0);
  42264. }
  42265. glPreserveState(gl, glState, function (gl) {
  42266. self.realBindFramebuffer.call(gl, gl.FRAMEBUFFER, null);
  42267. var positionDivisor = 0;
  42268. var texCoordDivisor = 0;
  42269. if (self.instanceExt) {
  42270. positionDivisor = gl.getVertexAttrib(self.attribs.position, self.instanceExt.VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE);
  42271. texCoordDivisor = gl.getVertexAttrib(self.attribs.texCoord, self.instanceExt.VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE);
  42272. }
  42273. if (self.cullFace) {
  42274. self.realDisable.call(gl, gl.CULL_FACE);
  42275. }
  42276. if (self.depthTest) {
  42277. self.realDisable.call(gl, gl.DEPTH_TEST);
  42278. }
  42279. if (self.blend) {
  42280. self.realDisable.call(gl, gl.BLEND);
  42281. }
  42282. if (self.scissorTest) {
  42283. self.realDisable.call(gl, gl.SCISSOR_TEST);
  42284. }
  42285. if (self.stencilTest) {
  42286. self.realDisable.call(gl, gl.STENCIL_TEST);
  42287. }
  42288. self.realColorMask.call(gl, true, true, true, true);
  42289. self.realViewport.call(gl, 0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
  42290. if (self.ctxAttribs.alpha || isIOS()) {
  42291. self.realClearColor.call(gl, 0, 0, 0, 1);
  42292. gl.clear(gl.COLOR_BUFFER_BIT);
  42293. }
  42294. gl.useProgram(self.program);
  42295. gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, self.indexBuffer);
  42296. gl.bindBuffer(gl.ARRAY_BUFFER, self.vertexBuffer);
  42297. gl.enableVertexAttribArray(self.attribs.position);
  42298. gl.enableVertexAttribArray(self.attribs.texCoord);
  42299. gl.vertexAttribPointer(self.attribs.position, 2, gl.FLOAT, false, 20, 0);
  42300. gl.vertexAttribPointer(self.attribs.texCoord, 3, gl.FLOAT, false, 20, 8);
  42301. if (self.instanceExt) {
  42302. if (positionDivisor != 0) {
  42303. self.instanceExt.vertexAttribDivisorANGLE(self.attribs.position, 0);
  42304. }
  42305. if (texCoordDivisor != 0) {
  42306. self.instanceExt.vertexAttribDivisorANGLE(self.attribs.texCoord, 0);
  42307. }
  42308. }
  42309. gl.activeTexture(gl.TEXTURE0);
  42310. gl.uniform1i(self.uniforms.diffuse, 0);
  42311. gl.bindTexture(gl.TEXTURE_2D, self.renderTarget);
  42312. gl.uniform4fv(self.uniforms.viewportOffsetScale, self.viewportOffsetScale);
  42313. gl.drawElements(gl.TRIANGLES, self.indexCount, gl.UNSIGNED_SHORT, 0);
  42314. if (self.cardboardUI) {
  42315. self.cardboardUI.renderNoState();
  42316. }
  42317. self.realBindFramebuffer.call(self.gl, gl.FRAMEBUFFER, self.framebuffer);
  42318. if (!self.ctxAttribs.preserveDrawingBuffer) {
  42319. self.realClearColor.call(gl, 0, 0, 0, 0);
  42320. gl.clear(gl.COLOR_BUFFER_BIT);
  42321. }
  42322. if (!self.dirtySubmitFrameBindings) {
  42323. self.realBindFramebuffer.call(gl, gl.FRAMEBUFFER, self.lastBoundFramebuffer);
  42324. }
  42325. if (self.cullFace) {
  42326. self.realEnable.call(gl, gl.CULL_FACE);
  42327. }
  42328. if (self.depthTest) {
  42329. self.realEnable.call(gl, gl.DEPTH_TEST);
  42330. }
  42331. if (self.blend) {
  42332. self.realEnable.call(gl, gl.BLEND);
  42333. }
  42334. if (self.scissorTest) {
  42335. self.realEnable.call(gl, gl.SCISSOR_TEST);
  42336. }
  42337. if (self.stencilTest) {
  42338. self.realEnable.call(gl, gl.STENCIL_TEST);
  42339. }
  42340. self.realColorMask.apply(gl, self.colorMask);
  42341. self.realViewport.apply(gl, self.viewport);
  42342. if (self.ctxAttribs.alpha || !self.ctxAttribs.preserveDrawingBuffer) {
  42343. self.realClearColor.apply(gl, self.clearColor);
  42344. }
  42345. if (self.instanceExt) {
  42346. if (positionDivisor != 0) {
  42347. self.instanceExt.vertexAttribDivisorANGLE(self.attribs.position, positionDivisor);
  42348. }
  42349. if (texCoordDivisor != 0) {
  42350. self.instanceExt.vertexAttribDivisorANGLE(self.attribs.texCoord, texCoordDivisor);
  42351. }
  42352. }
  42353. });
  42354. if (isIOS()) {
  42355. var canvas = gl.canvas;
  42356. if (canvas.width != self.bufferWidth || canvas.height != self.bufferHeight) {
  42357. self.bufferWidth = canvas.width;
  42358. self.bufferHeight = canvas.height;
  42359. self.onResize();
  42360. }
  42361. }
  42362. };
  42363. CardboardDistorter.prototype.updateDeviceInfo = function (deviceInfo) {
  42364. var gl = this.gl;
  42365. var self = this;
  42366. var glState = [gl.ARRAY_BUFFER_BINDING, gl.ELEMENT_ARRAY_BUFFER_BINDING];
  42367. glPreserveState(gl, glState, function (gl) {
  42368. var vertices = self.computeMeshVertices_(self.meshWidth, self.meshHeight, deviceInfo);
  42369. gl.bindBuffer(gl.ARRAY_BUFFER, self.vertexBuffer);
  42370. gl.bufferData(gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW);
  42371. if (!self.indexCount) {
  42372. var indices = self.computeMeshIndices_(self.meshWidth, self.meshHeight);
  42373. gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, self.indexBuffer);
  42374. gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, indices, gl.STATIC_DRAW);
  42375. self.indexCount = indices.length;
  42376. }
  42377. });
  42378. };
  42379. CardboardDistorter.prototype.computeMeshVertices_ = function (width, height, deviceInfo) {
  42380. var vertices = new Float32Array(2 * width * height * 5);
  42381. var lensFrustum = deviceInfo.getLeftEyeVisibleTanAngles();
  42382. var noLensFrustum = deviceInfo.getLeftEyeNoLensTanAngles();
  42383. var viewport = deviceInfo.getLeftEyeVisibleScreenRect(noLensFrustum);
  42384. var vidx = 0;
  42385. for (var e = 0; e < 2; e++) {
  42386. for (var j = 0; j < height; j++) {
  42387. for (var i = 0; i < width; i++, vidx++) {
  42388. var u = i / (width - 1);
  42389. var v = j / (height - 1);
  42390. var s = u;
  42391. var t = v;
  42392. var x = lerp(lensFrustum[0], lensFrustum[2], u);
  42393. var y = lerp(lensFrustum[3], lensFrustum[1], v);
  42394. var d = Math.sqrt(x * x + y * y);
  42395. var r = deviceInfo.distortion.distortInverse(d);
  42396. var p = x * r / d;
  42397. var q = y * r / d;
  42398. u = (p - noLensFrustum[0]) / (noLensFrustum[2] - noLensFrustum[0]);
  42399. v = (q - noLensFrustum[3]) / (noLensFrustum[1] - noLensFrustum[3]);
  42400. u = (viewport.x + u * viewport.width - 0.5) * 2.0;
  42401. v = (viewport.y + v * viewport.height - 0.5) * 2.0;
  42402. vertices[vidx * 5 + 0] = u;
  42403. vertices[vidx * 5 + 1] = v;
  42404. vertices[vidx * 5 + 2] = s;
  42405. vertices[vidx * 5 + 3] = t;
  42406. vertices[vidx * 5 + 4] = e;
  42407. }
  42408. }
  42409. var w = lensFrustum[2] - lensFrustum[0];
  42410. lensFrustum[0] = -(w + lensFrustum[0]);
  42411. lensFrustum[2] = w - lensFrustum[2];
  42412. w = noLensFrustum[2] - noLensFrustum[0];
  42413. noLensFrustum[0] = -(w + noLensFrustum[0]);
  42414. noLensFrustum[2] = w - noLensFrustum[2];
  42415. viewport.x = 1 - (viewport.x + viewport.width);
  42416. }
  42417. return vertices;
  42418. };
  42419. CardboardDistorter.prototype.computeMeshIndices_ = function (width, height) {
  42420. var indices = new Uint16Array(2 * (width - 1) * (height - 1) * 6);
  42421. var halfwidth = width / 2;
  42422. var halfheight = height / 2;
  42423. var vidx = 0;
  42424. var iidx = 0;
  42425. for (var e = 0; e < 2; e++) {
  42426. for (var j = 0; j < height; j++) {
  42427. for (var i = 0; i < width; i++, vidx++) {
  42428. if (i == 0 || j == 0) continue;
  42429. if (i <= halfwidth == j <= halfheight) {
  42430. indices[iidx++] = vidx;
  42431. indices[iidx++] = vidx - width - 1;
  42432. indices[iidx++] = vidx - width;
  42433. indices[iidx++] = vidx - width - 1;
  42434. indices[iidx++] = vidx;
  42435. indices[iidx++] = vidx - 1;
  42436. } else {
  42437. indices[iidx++] = vidx - 1;
  42438. indices[iidx++] = vidx - width;
  42439. indices[iidx++] = vidx;
  42440. indices[iidx++] = vidx - width;
  42441. indices[iidx++] = vidx - 1;
  42442. indices[iidx++] = vidx - width - 1;
  42443. }
  42444. }
  42445. }
  42446. }
  42447. return indices;
  42448. };
  42449. CardboardDistorter.prototype.getOwnPropertyDescriptor_ = function (proto, attrName) {
  42450. var descriptor = Object.getOwnPropertyDescriptor(proto, attrName);
  42451. if (descriptor.get === undefined || descriptor.set === undefined) {
  42452. descriptor.configurable = true;
  42453. descriptor.enumerable = true;
  42454. descriptor.get = function () {
  42455. return this.getAttribute(attrName);
  42456. };
  42457. descriptor.set = function (val) {
  42458. this.setAttribute(attrName, val);
  42459. };
  42460. }
  42461. return descriptor;
  42462. };
  42463. var uiVS = ['attribute vec2 position;', 'uniform mat4 projectionMat;', 'void main() {', ' gl_Position = projectionMat * vec4( position, -1.0, 1.0 );', '}'].join('\n');
  42464. var uiFS = ['precision mediump float;', 'uniform vec4 color;', 'void main() {', ' gl_FragColor = color;', '}'].join('\n');
  42465. var DEG2RAD = Math.PI / 180.0;
  42466. var kAnglePerGearSection = 60;
  42467. var kOuterRimEndAngle = 12;
  42468. var kInnerRimBeginAngle = 20;
  42469. var kOuterRadius = 1;
  42470. var kMiddleRadius = 0.75;
  42471. var kInnerRadius = 0.3125;
  42472. var kCenterLineThicknessDp = 4;
  42473. var kButtonWidthDp = 28;
  42474. var kTouchSlopFactor = 1.5;
  42475. function CardboardUI(gl) {
  42476. this.gl = gl;
  42477. this.attribs = {
  42478. position: 0
  42479. };
  42480. this.program = linkProgram(gl, uiVS, uiFS, this.attribs);
  42481. this.uniforms = getProgramUniforms(gl, this.program);
  42482. this.vertexBuffer = gl.createBuffer();
  42483. this.gearOffset = 0;
  42484. this.gearVertexCount = 0;
  42485. this.arrowOffset = 0;
  42486. this.arrowVertexCount = 0;
  42487. this.projMat = new Float32Array(16);
  42488. this.listener = null;
  42489. this.onResize();
  42490. }
  42491. CardboardUI.prototype.destroy = function () {
  42492. var gl = this.gl;
  42493. if (this.listener) {
  42494. gl.canvas.removeEventListener('click', this.listener, false);
  42495. }
  42496. gl.deleteProgram(this.program);
  42497. gl.deleteBuffer(this.vertexBuffer);
  42498. };
  42499. CardboardUI.prototype.listen = function (optionsCallback, backCallback) {
  42500. var canvas = this.gl.canvas;
  42501. this.listener = function (event) {
  42502. var midline = canvas.clientWidth / 2;
  42503. var buttonSize = kButtonWidthDp * kTouchSlopFactor;
  42504. if (event.clientX > midline - buttonSize && event.clientX < midline + buttonSize && event.clientY > canvas.clientHeight - buttonSize) {
  42505. optionsCallback(event);
  42506. }
  42507. else if (event.clientX < buttonSize && event.clientY < buttonSize) {
  42508. backCallback(event);
  42509. }
  42510. };
  42511. canvas.addEventListener('click', this.listener, false);
  42512. };
  42513. CardboardUI.prototype.onResize = function () {
  42514. var gl = this.gl;
  42515. var self = this;
  42516. var glState = [gl.ARRAY_BUFFER_BINDING];
  42517. glPreserveState(gl, glState, function (gl) {
  42518. var vertices = [];
  42519. var midline = gl.drawingBufferWidth / 2;
  42520. var physicalPixels = Math.max(screen.width, screen.height) * window.devicePixelRatio;
  42521. var scalingRatio = gl.drawingBufferWidth / physicalPixels;
  42522. var dps = scalingRatio * window.devicePixelRatio;
  42523. var lineWidth = kCenterLineThicknessDp * dps / 2;
  42524. var buttonSize = kButtonWidthDp * kTouchSlopFactor * dps;
  42525. var buttonScale = kButtonWidthDp * dps / 2;
  42526. var buttonBorder = (kButtonWidthDp * kTouchSlopFactor - kButtonWidthDp) * dps;
  42527. vertices.push(midline - lineWidth, buttonSize);
  42528. vertices.push(midline - lineWidth, gl.drawingBufferHeight);
  42529. vertices.push(midline + lineWidth, buttonSize);
  42530. vertices.push(midline + lineWidth, gl.drawingBufferHeight);
  42531. self.gearOffset = vertices.length / 2;
  42532. function addGearSegment(theta, r) {
  42533. var angle = (90 - theta) * DEG2RAD;
  42534. var x = Math.cos(angle);
  42535. var y = Math.sin(angle);
  42536. vertices.push(kInnerRadius * x * buttonScale + midline, kInnerRadius * y * buttonScale + buttonScale);
  42537. vertices.push(r * x * buttonScale + midline, r * y * buttonScale + buttonScale);
  42538. }
  42539. for (var i = 0; i <= 6; i++) {
  42540. var segmentTheta = i * kAnglePerGearSection;
  42541. addGearSegment(segmentTheta, kOuterRadius);
  42542. addGearSegment(segmentTheta + kOuterRimEndAngle, kOuterRadius);
  42543. addGearSegment(segmentTheta + kInnerRimBeginAngle, kMiddleRadius);
  42544. addGearSegment(segmentTheta + (kAnglePerGearSection - kInnerRimBeginAngle), kMiddleRadius);
  42545. addGearSegment(segmentTheta + (kAnglePerGearSection - kOuterRimEndAngle), kOuterRadius);
  42546. }
  42547. self.gearVertexCount = vertices.length / 2 - self.gearOffset;
  42548. self.arrowOffset = vertices.length / 2;
  42549. function addArrowVertex(x, y) {
  42550. vertices.push(buttonBorder + x, gl.drawingBufferHeight - buttonBorder - y);
  42551. }
  42552. var angledLineWidth = lineWidth / Math.sin(45 * DEG2RAD);
  42553. addArrowVertex(0, buttonScale);
  42554. addArrowVertex(buttonScale, 0);
  42555. addArrowVertex(buttonScale + angledLineWidth, angledLineWidth);
  42556. addArrowVertex(angledLineWidth, buttonScale + angledLineWidth);
  42557. addArrowVertex(angledLineWidth, buttonScale - angledLineWidth);
  42558. addArrowVertex(0, buttonScale);
  42559. addArrowVertex(buttonScale, buttonScale * 2);
  42560. addArrowVertex(buttonScale + angledLineWidth, buttonScale * 2 - angledLineWidth);
  42561. addArrowVertex(angledLineWidth, buttonScale - angledLineWidth);
  42562. addArrowVertex(0, buttonScale);
  42563. addArrowVertex(angledLineWidth, buttonScale - lineWidth);
  42564. addArrowVertex(kButtonWidthDp * dps, buttonScale - lineWidth);
  42565. addArrowVertex(angledLineWidth, buttonScale + lineWidth);
  42566. addArrowVertex(kButtonWidthDp * dps, buttonScale + lineWidth);
  42567. self.arrowVertexCount = vertices.length / 2 - self.arrowOffset;
  42568. gl.bindBuffer(gl.ARRAY_BUFFER, self.vertexBuffer);
  42569. gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW);
  42570. });
  42571. };
  42572. CardboardUI.prototype.render = function () {
  42573. var gl = this.gl;
  42574. var self = this;
  42575. var glState = [gl.CULL_FACE, gl.DEPTH_TEST, gl.BLEND, gl.SCISSOR_TEST, gl.STENCIL_TEST, gl.COLOR_WRITEMASK, gl.VIEWPORT, gl.CURRENT_PROGRAM, gl.ARRAY_BUFFER_BINDING];
  42576. glPreserveState(gl, glState, function (gl) {
  42577. gl.disable(gl.CULL_FACE);
  42578. gl.disable(gl.DEPTH_TEST);
  42579. gl.disable(gl.BLEND);
  42580. gl.disable(gl.SCISSOR_TEST);
  42581. gl.disable(gl.STENCIL_TEST);
  42582. gl.colorMask(true, true, true, true);
  42583. gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
  42584. self.renderNoState();
  42585. });
  42586. };
  42587. CardboardUI.prototype.renderNoState = function () {
  42588. var gl = this.gl;
  42589. gl.useProgram(this.program);
  42590. gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer);
  42591. gl.enableVertexAttribArray(this.attribs.position);
  42592. gl.vertexAttribPointer(this.attribs.position, 2, gl.FLOAT, false, 8, 0);
  42593. gl.uniform4f(this.uniforms.color, 1.0, 1.0, 1.0, 1.0);
  42594. orthoMatrix(this.projMat, 0, gl.drawingBufferWidth, 0, gl.drawingBufferHeight, 0.1, 1024.0);
  42595. gl.uniformMatrix4fv(this.uniforms.projectionMat, false, this.projMat);
  42596. gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
  42597. gl.drawArrays(gl.TRIANGLE_STRIP, this.gearOffset, this.gearVertexCount);
  42598. gl.drawArrays(gl.TRIANGLE_STRIP, this.arrowOffset, this.arrowVertexCount);
  42599. };
  42600. function Distortion(coefficients) {
  42601. this.coefficients = coefficients;
  42602. }
  42603. Distortion.prototype.distortInverse = function (radius) {
  42604. var r0 = 0;
  42605. var r1 = 1;
  42606. var dr0 = radius - this.distort(r0);
  42607. while (Math.abs(r1 - r0) > 0.0001 ) {
  42608. var dr1 = radius - this.distort(r1);
  42609. var r2 = r1 - dr1 * ((r1 - r0) / (dr1 - dr0));
  42610. r0 = r1;
  42611. r1 = r2;
  42612. dr0 = dr1;
  42613. }
  42614. return r1;
  42615. };
  42616. Distortion.prototype.distort = function (radius) {
  42617. var r2 = radius * radius;
  42618. var ret = 0;
  42619. for (var i = 0; i < this.coefficients.length; i++) {
  42620. ret = r2 * (ret + this.coefficients[i]);
  42621. }
  42622. return (ret + 1) * radius;
  42623. };
  42624. var degToRad = Math.PI / 180;
  42625. var radToDeg = 180 / Math.PI;
  42626. var Vector3 = function Vector3(x, y, z) {
  42627. this.x = x || 0;
  42628. this.y = y || 0;
  42629. this.z = z || 0;
  42630. };
  42631. Vector3.prototype = {
  42632. constructor: Vector3,
  42633. set: function set(x, y, z) {
  42634. this.x = x;
  42635. this.y = y;
  42636. this.z = z;
  42637. return this;
  42638. },
  42639. copy: function copy(v) {
  42640. this.x = v.x;
  42641. this.y = v.y;
  42642. this.z = v.z;
  42643. return this;
  42644. },
  42645. length: function length() {
  42646. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  42647. },
  42648. normalize: function normalize() {
  42649. var scalar = this.length();
  42650. if (scalar !== 0) {
  42651. var invScalar = 1 / scalar;
  42652. this.multiplyScalar(invScalar);
  42653. } else {
  42654. this.x = 0;
  42655. this.y = 0;
  42656. this.z = 0;
  42657. }
  42658. return this;
  42659. },
  42660. multiplyScalar: function multiplyScalar(scalar) {
  42661. this.x *= scalar;
  42662. this.y *= scalar;
  42663. this.z *= scalar;
  42664. },
  42665. applyQuaternion: function applyQuaternion(q) {
  42666. var x = this.x;
  42667. var y = this.y;
  42668. var z = this.z;
  42669. var qx = q.x;
  42670. var qy = q.y;
  42671. var qz = q.z;
  42672. var qw = q.w;
  42673. var ix = qw * x + qy * z - qz * y;
  42674. var iy = qw * y + qz * x - qx * z;
  42675. var iz = qw * z + qx * y - qy * x;
  42676. var iw = -qx * x - qy * y - qz * z;
  42677. this.x = ix * qw + iw * -qx + iy * -qz - iz * -qy;
  42678. this.y = iy * qw + iw * -qy + iz * -qx - ix * -qz;
  42679. this.z = iz * qw + iw * -qz + ix * -qy - iy * -qx;
  42680. return this;
  42681. },
  42682. dot: function dot(v) {
  42683. return this.x * v.x + this.y * v.y + this.z * v.z;
  42684. },
  42685. crossVectors: function crossVectors(a, b) {
  42686. var ax = a.x,
  42687. ay = a.y,
  42688. az = a.z;
  42689. var bx = b.x,
  42690. by = b.y,
  42691. bz = b.z;
  42692. this.x = ay * bz - az * by;
  42693. this.y = az * bx - ax * bz;
  42694. this.z = ax * by - ay * bx;
  42695. return this;
  42696. }
  42697. };
  42698. var Quaternion = function Quaternion(x, y, z, w) {
  42699. this.x = x || 0;
  42700. this.y = y || 0;
  42701. this.z = z || 0;
  42702. this.w = w !== undefined ? w : 1;
  42703. };
  42704. Quaternion.prototype = {
  42705. constructor: Quaternion,
  42706. set: function set(x, y, z, w) {
  42707. this.x = x;
  42708. this.y = y;
  42709. this.z = z;
  42710. this.w = w;
  42711. return this;
  42712. },
  42713. copy: function copy(quaternion) {
  42714. this.x = quaternion.x;
  42715. this.y = quaternion.y;
  42716. this.z = quaternion.z;
  42717. this.w = quaternion.w;
  42718. return this;
  42719. },
  42720. setFromEulerXYZ: function setFromEulerXYZ(x, y, z) {
  42721. var c1 = Math.cos(x / 2);
  42722. var c2 = Math.cos(y / 2);
  42723. var c3 = Math.cos(z / 2);
  42724. var s1 = Math.sin(x / 2);
  42725. var s2 = Math.sin(y / 2);
  42726. var s3 = Math.sin(z / 2);
  42727. this.x = s1 * c2 * c3 + c1 * s2 * s3;
  42728. this.y = c1 * s2 * c3 - s1 * c2 * s3;
  42729. this.z = c1 * c2 * s3 + s1 * s2 * c3;
  42730. this.w = c1 * c2 * c3 - s1 * s2 * s3;
  42731. return this;
  42732. },
  42733. setFromEulerYXZ: function setFromEulerYXZ(x, y, z) {
  42734. var c1 = Math.cos(x / 2);
  42735. var c2 = Math.cos(y / 2);
  42736. var c3 = Math.cos(z / 2);
  42737. var s1 = Math.sin(x / 2);
  42738. var s2 = Math.sin(y / 2);
  42739. var s3 = Math.sin(z / 2);
  42740. this.x = s1 * c2 * c3 + c1 * s2 * s3;
  42741. this.y = c1 * s2 * c3 - s1 * c2 * s3;
  42742. this.z = c1 * c2 * s3 - s1 * s2 * c3;
  42743. this.w = c1 * c2 * c3 + s1 * s2 * s3;
  42744. return this;
  42745. },
  42746. setFromAxisAngle: function setFromAxisAngle(axis, angle) {
  42747. var halfAngle = angle / 2,
  42748. s = Math.sin(halfAngle);
  42749. this.x = axis.x * s;
  42750. this.y = axis.y * s;
  42751. this.z = axis.z * s;
  42752. this.w = Math.cos(halfAngle);
  42753. return this;
  42754. },
  42755. multiply: function multiply(q) {
  42756. return this.multiplyQuaternions(this, q);
  42757. },
  42758. multiplyQuaternions: function multiplyQuaternions(a, b) {
  42759. var qax = a.x,
  42760. qay = a.y,
  42761. qaz = a.z,
  42762. qaw = a.w;
  42763. var qbx = b.x,
  42764. qby = b.y,
  42765. qbz = b.z,
  42766. qbw = b.w;
  42767. this.x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  42768. this.y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  42769. this.z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  42770. this.w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  42771. return this;
  42772. },
  42773. inverse: function inverse() {
  42774. this.x *= -1;
  42775. this.y *= -1;
  42776. this.z *= -1;
  42777. this.normalize();
  42778. return this;
  42779. },
  42780. normalize: function normalize() {
  42781. var l = Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  42782. if (l === 0) {
  42783. this.x = 0;
  42784. this.y = 0;
  42785. this.z = 0;
  42786. this.w = 1;
  42787. } else {
  42788. l = 1 / l;
  42789. this.x = this.x * l;
  42790. this.y = this.y * l;
  42791. this.z = this.z * l;
  42792. this.w = this.w * l;
  42793. }
  42794. return this;
  42795. },
  42796. slerp: function slerp(qb, t) {
  42797. if (t === 0) return this;
  42798. if (t === 1) return this.copy(qb);
  42799. var x = this.x,
  42800. y = this.y,
  42801. z = this.z,
  42802. w = this.w;
  42803. var cosHalfTheta = w * qb.w + x * qb.x + y * qb.y + z * qb.z;
  42804. if (cosHalfTheta < 0) {
  42805. this.w = -qb.w;
  42806. this.x = -qb.x;
  42807. this.y = -qb.y;
  42808. this.z = -qb.z;
  42809. cosHalfTheta = -cosHalfTheta;
  42810. } else {
  42811. this.copy(qb);
  42812. }
  42813. if (cosHalfTheta >= 1.0) {
  42814. this.w = w;
  42815. this.x = x;
  42816. this.y = y;
  42817. this.z = z;
  42818. return this;
  42819. }
  42820. var halfTheta = Math.acos(cosHalfTheta);
  42821. var sinHalfTheta = Math.sqrt(1.0 - cosHalfTheta * cosHalfTheta);
  42822. if (Math.abs(sinHalfTheta) < 0.001) {
  42823. this.w = 0.5 * (w + this.w);
  42824. this.x = 0.5 * (x + this.x);
  42825. this.y = 0.5 * (y + this.y);
  42826. this.z = 0.5 * (z + this.z);
  42827. return this;
  42828. }
  42829. var ratioA = Math.sin((1 - t) * halfTheta) / sinHalfTheta,
  42830. ratioB = Math.sin(t * halfTheta) / sinHalfTheta;
  42831. this.w = w * ratioA + this.w * ratioB;
  42832. this.x = x * ratioA + this.x * ratioB;
  42833. this.y = y * ratioA + this.y * ratioB;
  42834. this.z = z * ratioA + this.z * ratioB;
  42835. return this;
  42836. },
  42837. setFromUnitVectors: function () {
  42838. var v1, r;
  42839. var EPS = 0.000001;
  42840. return function (vFrom, vTo) {
  42841. if (v1 === undefined) v1 = new Vector3();
  42842. r = vFrom.dot(vTo) + 1;
  42843. if (r < EPS) {
  42844. r = 0;
  42845. if (Math.abs(vFrom.x) > Math.abs(vFrom.z)) {
  42846. v1.set(-vFrom.y, vFrom.x, 0);
  42847. } else {
  42848. v1.set(0, -vFrom.z, vFrom.y);
  42849. }
  42850. } else {
  42851. v1.crossVectors(vFrom, vTo);
  42852. }
  42853. this.x = v1.x;
  42854. this.y = v1.y;
  42855. this.z = v1.z;
  42856. this.w = r;
  42857. this.normalize();
  42858. return this;
  42859. };
  42860. }()
  42861. };
  42862. function Device(params) {
  42863. this.width = params.width || getScreenWidth();
  42864. this.height = params.height || getScreenHeight();
  42865. this.widthMeters = params.widthMeters;
  42866. this.heightMeters = params.heightMeters;
  42867. this.bevelMeters = params.bevelMeters;
  42868. }
  42869. var DEFAULT_ANDROID = new Device({
  42870. widthMeters: 0.110,
  42871. heightMeters: 0.062,
  42872. bevelMeters: 0.004
  42873. });
  42874. var DEFAULT_IOS = new Device({
  42875. widthMeters: 0.1038,
  42876. heightMeters: 0.0584,
  42877. bevelMeters: 0.004
  42878. });
  42879. var Viewers = {
  42880. CardboardV1: new CardboardViewer({
  42881. id: 'CardboardV1',
  42882. label: 'Cardboard I/O 2014',
  42883. fov: 40,
  42884. interLensDistance: 0.060,
  42885. baselineLensDistance: 0.035,
  42886. screenLensDistance: 0.042,
  42887. distortionCoefficients: [0.441, 0.156],
  42888. inverseCoefficients: [-0.4410035, 0.42756155, -0.4804439, 0.5460139, -0.58821183, 0.5733938, -0.48303202, 0.33299083, -0.17573841, 0.0651772, -0.01488963, 0.001559834]
  42889. }),
  42890. CardboardV2: new CardboardViewer({
  42891. id: 'CardboardV2',
  42892. label: 'Cardboard I/O 2015',
  42893. fov: 60,
  42894. interLensDistance: 0.064,
  42895. baselineLensDistance: 0.035,
  42896. screenLensDistance: 0.039,
  42897. distortionCoefficients: [0.34, 0.55],
  42898. inverseCoefficients: [-0.33836704, -0.18162185, 0.862655, -1.2462051, 1.0560602, -0.58208317, 0.21609078, -0.05444823, 0.009177956, -9.904169E-4, 6.183535E-5, -1.6981803E-6]
  42899. })
  42900. };
  42901. function DeviceInfo(deviceParams, additionalViewers) {
  42902. this.viewer = Viewers.CardboardV2;
  42903. this.updateDeviceParams(deviceParams);
  42904. this.distortion = new Distortion(this.viewer.distortionCoefficients);
  42905. for (var i = 0; i < additionalViewers.length; i++) {
  42906. var viewer = additionalViewers[i];
  42907. Viewers[viewer.id] = new CardboardViewer(viewer);
  42908. }
  42909. }
  42910. DeviceInfo.prototype.updateDeviceParams = function (deviceParams) {
  42911. this.device = this.determineDevice_(deviceParams) || this.device;
  42912. };
  42913. DeviceInfo.prototype.getDevice = function () {
  42914. return this.device;
  42915. };
  42916. DeviceInfo.prototype.setViewer = function (viewer) {
  42917. this.viewer = viewer;
  42918. this.distortion = new Distortion(this.viewer.distortionCoefficients);
  42919. };
  42920. DeviceInfo.prototype.determineDevice_ = function (deviceParams) {
  42921. if (!deviceParams) {
  42922. if (isIOS()) {
  42923. console.warn('Using fallback iOS device measurements.');
  42924. return DEFAULT_IOS;
  42925. } else {
  42926. console.warn('Using fallback Android device measurements.');
  42927. return DEFAULT_ANDROID;
  42928. }
  42929. }
  42930. var METERS_PER_INCH = 0.0254;
  42931. var metersPerPixelX = METERS_PER_INCH / deviceParams.xdpi;
  42932. var metersPerPixelY = METERS_PER_INCH / deviceParams.ydpi;
  42933. var width = getScreenWidth();
  42934. var height = getScreenHeight();
  42935. return new Device({
  42936. widthMeters: metersPerPixelX * width,
  42937. heightMeters: metersPerPixelY * height,
  42938. bevelMeters: deviceParams.bevelMm * 0.001
  42939. });
  42940. };
  42941. DeviceInfo.prototype.getDistortedFieldOfViewLeftEye = function () {
  42942. var viewer = this.viewer;
  42943. var device = this.device;
  42944. var distortion = this.distortion;
  42945. var eyeToScreenDistance = viewer.screenLensDistance;
  42946. var outerDist = (device.widthMeters - viewer.interLensDistance) / 2;
  42947. var innerDist = viewer.interLensDistance / 2;
  42948. var bottomDist = viewer.baselineLensDistance - device.bevelMeters;
  42949. var topDist = device.heightMeters - bottomDist;
  42950. var outerAngle = radToDeg * Math.atan(distortion.distort(outerDist / eyeToScreenDistance));
  42951. var innerAngle = radToDeg * Math.atan(distortion.distort(innerDist / eyeToScreenDistance));
  42952. var bottomAngle = radToDeg * Math.atan(distortion.distort(bottomDist / eyeToScreenDistance));
  42953. var topAngle = radToDeg * Math.atan(distortion.distort(topDist / eyeToScreenDistance));
  42954. return {
  42955. leftDegrees: Math.min(outerAngle, viewer.fov),
  42956. rightDegrees: Math.min(innerAngle, viewer.fov),
  42957. downDegrees: Math.min(bottomAngle, viewer.fov),
  42958. upDegrees: Math.min(topAngle, viewer.fov)
  42959. };
  42960. };
  42961. DeviceInfo.prototype.getLeftEyeVisibleTanAngles = function () {
  42962. var viewer = this.viewer;
  42963. var device = this.device;
  42964. var distortion = this.distortion;
  42965. var fovLeft = Math.tan(-degToRad * viewer.fov);
  42966. var fovTop = Math.tan(degToRad * viewer.fov);
  42967. var fovRight = Math.tan(degToRad * viewer.fov);
  42968. var fovBottom = Math.tan(-degToRad * viewer.fov);
  42969. var halfWidth = device.widthMeters / 4;
  42970. var halfHeight = device.heightMeters / 2;
  42971. var verticalLensOffset = viewer.baselineLensDistance - device.bevelMeters - halfHeight;
  42972. var centerX = viewer.interLensDistance / 2 - halfWidth;
  42973. var centerY = -verticalLensOffset;
  42974. var centerZ = viewer.screenLensDistance;
  42975. var screenLeft = distortion.distort((centerX - halfWidth) / centerZ);
  42976. var screenTop = distortion.distort((centerY + halfHeight) / centerZ);
  42977. var screenRight = distortion.distort((centerX + halfWidth) / centerZ);
  42978. var screenBottom = distortion.distort((centerY - halfHeight) / centerZ);
  42979. var result = new Float32Array(4);
  42980. result[0] = Math.max(fovLeft, screenLeft);
  42981. result[1] = Math.min(fovTop, screenTop);
  42982. result[2] = Math.min(fovRight, screenRight);
  42983. result[3] = Math.max(fovBottom, screenBottom);
  42984. return result;
  42985. };
  42986. DeviceInfo.prototype.getLeftEyeNoLensTanAngles = function () {
  42987. var viewer = this.viewer;
  42988. var device = this.device;
  42989. var distortion = this.distortion;
  42990. var result = new Float32Array(4);
  42991. var fovLeft = distortion.distortInverse(Math.tan(-degToRad * viewer.fov));
  42992. var fovTop = distortion.distortInverse(Math.tan(degToRad * viewer.fov));
  42993. var fovRight = distortion.distortInverse(Math.tan(degToRad * viewer.fov));
  42994. var fovBottom = distortion.distortInverse(Math.tan(-degToRad * viewer.fov));
  42995. var halfWidth = device.widthMeters / 4;
  42996. var halfHeight = device.heightMeters / 2;
  42997. var verticalLensOffset = viewer.baselineLensDistance - device.bevelMeters - halfHeight;
  42998. var centerX = viewer.interLensDistance / 2 - halfWidth;
  42999. var centerY = -verticalLensOffset;
  43000. var centerZ = viewer.screenLensDistance;
  43001. var screenLeft = (centerX - halfWidth) / centerZ;
  43002. var screenTop = (centerY + halfHeight) / centerZ;
  43003. var screenRight = (centerX + halfWidth) / centerZ;
  43004. var screenBottom = (centerY - halfHeight) / centerZ;
  43005. result[0] = Math.max(fovLeft, screenLeft);
  43006. result[1] = Math.min(fovTop, screenTop);
  43007. result[2] = Math.min(fovRight, screenRight);
  43008. result[3] = Math.max(fovBottom, screenBottom);
  43009. return result;
  43010. };
  43011. DeviceInfo.prototype.getLeftEyeVisibleScreenRect = function (undistortedFrustum) {
  43012. var viewer = this.viewer;
  43013. var device = this.device;
  43014. var dist = viewer.screenLensDistance;
  43015. var eyeX = (device.widthMeters - viewer.interLensDistance) / 2;
  43016. var eyeY = viewer.baselineLensDistance - device.bevelMeters;
  43017. var left = (undistortedFrustum[0] * dist + eyeX) / device.widthMeters;
  43018. var top = (undistortedFrustum[1] * dist + eyeY) / device.heightMeters;
  43019. var right = (undistortedFrustum[2] * dist + eyeX) / device.widthMeters;
  43020. var bottom = (undistortedFrustum[3] * dist + eyeY) / device.heightMeters;
  43021. return {
  43022. x: left,
  43023. y: bottom,
  43024. width: right - left,
  43025. height: top - bottom
  43026. };
  43027. };
  43028. DeviceInfo.prototype.getFieldOfViewLeftEye = function (opt_isUndistorted) {
  43029. return opt_isUndistorted ? this.getUndistortedFieldOfViewLeftEye() : this.getDistortedFieldOfViewLeftEye();
  43030. };
  43031. DeviceInfo.prototype.getFieldOfViewRightEye = function (opt_isUndistorted) {
  43032. var fov = this.getFieldOfViewLeftEye(opt_isUndistorted);
  43033. return {
  43034. leftDegrees: fov.rightDegrees,
  43035. rightDegrees: fov.leftDegrees,
  43036. upDegrees: fov.upDegrees,
  43037. downDegrees: fov.downDegrees
  43038. };
  43039. };
  43040. DeviceInfo.prototype.getUndistortedFieldOfViewLeftEye = function () {
  43041. var p = this.getUndistortedParams_();
  43042. return {
  43043. leftDegrees: radToDeg * Math.atan(p.outerDist),
  43044. rightDegrees: radToDeg * Math.atan(p.innerDist),
  43045. downDegrees: radToDeg * Math.atan(p.bottomDist),
  43046. upDegrees: radToDeg * Math.atan(p.topDist)
  43047. };
  43048. };
  43049. DeviceInfo.prototype.getUndistortedViewportLeftEye = function () {
  43050. var p = this.getUndistortedParams_();
  43051. var viewer = this.viewer;
  43052. var device = this.device;
  43053. var eyeToScreenDistance = viewer.screenLensDistance;
  43054. var screenWidth = device.widthMeters / eyeToScreenDistance;
  43055. var screenHeight = device.heightMeters / eyeToScreenDistance;
  43056. var xPxPerTanAngle = device.width / screenWidth;
  43057. var yPxPerTanAngle = device.height / screenHeight;
  43058. var x = Math.round((p.eyePosX - p.outerDist) * xPxPerTanAngle);
  43059. var y = Math.round((p.eyePosY - p.bottomDist) * yPxPerTanAngle);
  43060. return {
  43061. x: x,
  43062. y: y,
  43063. width: Math.round((p.eyePosX + p.innerDist) * xPxPerTanAngle) - x,
  43064. height: Math.round((p.eyePosY + p.topDist) * yPxPerTanAngle) - y
  43065. };
  43066. };
  43067. DeviceInfo.prototype.getUndistortedParams_ = function () {
  43068. var viewer = this.viewer;
  43069. var device = this.device;
  43070. var distortion = this.distortion;
  43071. var eyeToScreenDistance = viewer.screenLensDistance;
  43072. var halfLensDistance = viewer.interLensDistance / 2 / eyeToScreenDistance;
  43073. var screenWidth = device.widthMeters / eyeToScreenDistance;
  43074. var screenHeight = device.heightMeters / eyeToScreenDistance;
  43075. var eyePosX = screenWidth / 2 - halfLensDistance;
  43076. var eyePosY = (viewer.baselineLensDistance - device.bevelMeters) / eyeToScreenDistance;
  43077. var maxFov = viewer.fov;
  43078. var viewerMax = distortion.distortInverse(Math.tan(degToRad * maxFov));
  43079. var outerDist = Math.min(eyePosX, viewerMax);
  43080. var innerDist = Math.min(halfLensDistance, viewerMax);
  43081. var bottomDist = Math.min(eyePosY, viewerMax);
  43082. var topDist = Math.min(screenHeight - eyePosY, viewerMax);
  43083. return {
  43084. outerDist: outerDist,
  43085. innerDist: innerDist,
  43086. topDist: topDist,
  43087. bottomDist: bottomDist,
  43088. eyePosX: eyePosX,
  43089. eyePosY: eyePosY
  43090. };
  43091. };
  43092. function CardboardViewer(params) {
  43093. this.id = params.id;
  43094. this.label = params.label;
  43095. this.fov = params.fov;
  43096. this.interLensDistance = params.interLensDistance;
  43097. this.baselineLensDistance = params.baselineLensDistance;
  43098. this.screenLensDistance = params.screenLensDistance;
  43099. this.distortionCoefficients = params.distortionCoefficients;
  43100. this.inverseCoefficients = params.inverseCoefficients;
  43101. }
  43102. DeviceInfo.Viewers = Viewers;
  43103. var format = 1;
  43104. var last_updated = "2019-11-09T17:36:14Z";
  43105. var devices = [{"type":"android","rules":[{"mdmh":"asus/*/Nexus 7/*"},{"ua":"Nexus 7"}],"dpi":[320.8,323],"bw":3,"ac":500},{"type":"android","rules":[{"mdmh":"asus/*/ASUS_X00PD/*"},{"ua":"ASUS_X00PD"}],"dpi":245,"bw":3,"ac":500},{"type":"android","rules":[{"mdmh":"asus/*/ASUS_X008D/*"},{"ua":"ASUS_X008D"}],"dpi":282,"bw":3,"ac":500},{"type":"android","rules":[{"mdmh":"asus/*/ASUS_Z00AD/*"},{"ua":"ASUS_Z00AD"}],"dpi":[403,404.6],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"Google/*/Pixel 2 XL/*"},{"ua":"Pixel 2 XL"}],"dpi":537.9,"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"Google/*/Pixel 3 XL/*"},{"ua":"Pixel 3 XL"}],"dpi":[558.5,553.8],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"Google/*/Pixel XL/*"},{"ua":"Pixel XL"}],"dpi":[537.9,533],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"Google/*/Pixel 3/*"},{"ua":"Pixel 3"}],"dpi":442.4,"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"Google/*/Pixel 2/*"},{"ua":"Pixel 2"}],"dpi":441,"bw":3,"ac":500},{"type":"android","rules":[{"mdmh":"Google/*/Pixel/*"},{"ua":"Pixel"}],"dpi":[432.6,436.7],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"HTC/*/HTC6435LVW/*"},{"ua":"HTC6435LVW"}],"dpi":[449.7,443.3],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"HTC/*/HTC One XL/*"},{"ua":"HTC One XL"}],"dpi":[315.3,314.6],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"htc/*/Nexus 9/*"},{"ua":"Nexus 9"}],"dpi":289,"bw":3,"ac":500},{"type":"android","rules":[{"mdmh":"HTC/*/HTC One M9/*"},{"ua":"HTC One M9"}],"dpi":[442.5,443.3],"bw":3,"ac":500},{"type":"android","rules":[{"mdmh":"HTC/*/HTC One_M8/*"},{"ua":"HTC One_M8"}],"dpi":[449.7,447.4],"bw":3,"ac":500},{"type":"android","rules":[{"mdmh":"HTC/*/HTC One/*"},{"ua":"HTC One"}],"dpi":472.8,"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"Huawei/*/Nexus 6P/*"},{"ua":"Nexus 6P"}],"dpi":[515.1,518],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"Huawei/*/BLN-L24/*"},{"ua":"HONORBLN-L24"}],"dpi":480,"bw":4,"ac":500},{"type":"android","rules":[{"mdmh":"Huawei/*/BKL-L09/*"},{"ua":"BKL-L09"}],"dpi":403,"bw":3.47,"ac":500},{"type":"android","rules":[{"mdmh":"LENOVO/*/Lenovo PB2-690Y/*"},{"ua":"Lenovo PB2-690Y"}],"dpi":[457.2,454.713],"bw":3,"ac":500},{"type":"android","rules":[{"mdmh":"LGE/*/Nexus 5X/*"},{"ua":"Nexus 5X"}],"dpi":[422,419.9],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"LGE/*/LGMS345/*"},{"ua":"LGMS345"}],"dpi":[221.7,219.1],"bw":3,"ac":500},{"type":"android","rules":[{"mdmh":"LGE/*/LG-D800/*"},{"ua":"LG-D800"}],"dpi":[422,424.1],"bw":3,"ac":500},{"type":"android","rules":[{"mdmh":"LGE/*/LG-D850/*"},{"ua":"LG-D850"}],"dpi":[537.9,541.9],"bw":3,"ac":500},{"type":"android","rules":[{"mdmh":"LGE/*/VS985 4G/*"},{"ua":"VS985 4G"}],"dpi":[537.9,535.6],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"LGE/*/Nexus 5/*"},{"ua":"Nexus 5 B"}],"dpi":[442.4,444.8],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"LGE/*/Nexus 4/*"},{"ua":"Nexus 4"}],"dpi":[319.8,318.4],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"LGE/*/LG-P769/*"},{"ua":"LG-P769"}],"dpi":[240.6,247.5],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"LGE/*/LGMS323/*"},{"ua":"LGMS323"}],"dpi":[206.6,204.6],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"LGE/*/LGLS996/*"},{"ua":"LGLS996"}],"dpi":[403.4,401.5],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"Micromax/*/4560MMX/*"},{"ua":"4560MMX"}],"dpi":[240,219.4],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"Micromax/*/A250/*"},{"ua":"Micromax A250"}],"dpi":[480,446.4],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"Micromax/*/Micromax AQ4501/*"},{"ua":"Micromax AQ4501"}],"dpi":240,"bw":3,"ac":500},{"type":"android","rules":[{"mdmh":"motorola/*/G5/*"},{"ua":"Moto G (5) Plus"}],"dpi":[403.4,403],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"motorola/*/DROID RAZR/*"},{"ua":"DROID RAZR"}],"dpi":[368.1,256.7],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"motorola/*/XT830C/*"},{"ua":"XT830C"}],"dpi":[254,255.9],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"motorola/*/XT1021/*"},{"ua":"XT1021"}],"dpi":[254,256.7],"bw":3,"ac":500},{"type":"android","rules":[{"mdmh":"motorola/*/XT1023/*"},{"ua":"XT1023"}],"dpi":[254,256.7],"bw":3,"ac":500},{"type":"android","rules":[{"mdmh":"motorola/*/XT1028/*"},{"ua":"XT1028"}],"dpi":[326.6,327.6],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"motorola/*/XT1034/*"},{"ua":"XT1034"}],"dpi":[326.6,328.4],"bw":3,"ac":500},{"type":"android","rules":[{"mdmh":"motorola/*/XT1053/*"},{"ua":"XT1053"}],"dpi":[315.3,316.1],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"motorola/*/XT1562/*"},{"ua":"XT1562"}],"dpi":[403.4,402.7],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"motorola/*/Nexus 6/*"},{"ua":"Nexus 6 B"}],"dpi":[494.3,489.7],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"motorola/*/XT1063/*"},{"ua":"XT1063"}],"dpi":[295,296.6],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"motorola/*/XT1064/*"},{"ua":"XT1064"}],"dpi":[295,295.6],"bw":3,"ac":500},{"type":"android","rules":[{"mdmh":"motorola/*/XT1092/*"},{"ua":"XT1092"}],"dpi":[422,424.1],"bw":3,"ac":500},{"type":"android","rules":[{"mdmh":"motorola/*/XT1095/*"},{"ua":"XT1095"}],"dpi":[422,423.4],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"motorola/*/G4/*"},{"ua":"Moto G (4)"}],"dpi":401,"bw":4,"ac":1000},{"type":"android","rules":[{"mdmh":"OnePlus/*/A0001/*"},{"ua":"A0001"}],"dpi":[403.4,401],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"OnePlus/*/ONE E1001/*"},{"ua":"ONE E1001"}],"dpi":[442.4,441.4],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"OnePlus/*/ONE E1003/*"},{"ua":"ONE E1003"}],"dpi":[442.4,441.4],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"OnePlus/*/ONE E1005/*"},{"ua":"ONE E1005"}],"dpi":[442.4,441.4],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"OnePlus/*/ONE A2001/*"},{"ua":"ONE A2001"}],"dpi":[391.9,405.4],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"OnePlus/*/ONE A2003/*"},{"ua":"ONE A2003"}],"dpi":[391.9,405.4],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"OnePlus/*/ONE A2005/*"},{"ua":"ONE A2005"}],"dpi":[391.9,405.4],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"OnePlus/*/ONEPLUS A3000/*"},{"ua":"ONEPLUS A3000"}],"dpi":401,"bw":3,"ac":500},{"type":"android","rules":[{"mdmh":"OnePlus/*/ONEPLUS A3003/*"},{"ua":"ONEPLUS A3003"}],"dpi":401,"bw":3,"ac":500},{"type":"android","rules":[{"mdmh":"OnePlus/*/ONEPLUS A3010/*"},{"ua":"ONEPLUS A3010"}],"dpi":401,"bw":3,"ac":500},{"type":"android","rules":[{"mdmh":"OnePlus/*/ONEPLUS A5000/*"},{"ua":"ONEPLUS A5000 "}],"dpi":[403.411,399.737],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"OnePlus/*/ONE A5010/*"},{"ua":"ONEPLUS A5010"}],"dpi":[403,400],"bw":2,"ac":1000},{"type":"android","rules":[{"mdmh":"OnePlus/*/ONEPLUS A6000/*"},{"ua":"ONEPLUS A6000"}],"dpi":401,"bw":3,"ac":500},{"type":"android","rules":[{"mdmh":"OnePlus/*/ONEPLUS A6003/*"},{"ua":"ONEPLUS A6003"}],"dpi":401,"bw":3,"ac":500},{"type":"android","rules":[{"mdmh":"OnePlus/*/ONEPLUS A6010/*"},{"ua":"ONEPLUS A6010"}],"dpi":401,"bw":2,"ac":500},{"type":"android","rules":[{"mdmh":"OnePlus/*/ONEPLUS A6013/*"},{"ua":"ONEPLUS A6013"}],"dpi":401,"bw":2,"ac":500},{"type":"android","rules":[{"mdmh":"OPPO/*/X909/*"},{"ua":"X909"}],"dpi":[442.4,444.1],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"samsung/*/GT-I9082/*"},{"ua":"GT-I9082"}],"dpi":[184.7,185.4],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"samsung/*/SM-G360P/*"},{"ua":"SM-G360P"}],"dpi":[196.7,205.4],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"samsung/*/Nexus S/*"},{"ua":"Nexus S"}],"dpi":[234.5,229.8],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"samsung/*/GT-I9300/*"},{"ua":"GT-I9300"}],"dpi":[304.8,303.9],"bw":5,"ac":500},{"type":"android","rules":[{"mdmh":"samsung/*/SM-T230NU/*"},{"ua":"SM-T230NU"}],"dpi":216,"bw":3,"ac":500},{"type":"android","rules":[{"mdmh":"samsung/*/SGH-T399/*"},{"ua":"SGH-T399"}],"dpi":[217.7,231.4],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"samsung/*/SGH-M919/*"},{"ua":"SGH-M919"}],"dpi":[440.8,437.7],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"samsung/*/SM-N9005/*"},{"ua":"SM-N9005"}],"dpi":[386.4,387],"bw":3,"ac":500},{"type":"android","rules":[{"mdmh":"samsung/*/SAMSUNG-SM-N900A/*"},{"ua":"SAMSUNG-SM-N900A"}],"dpi":[386.4,387.7],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"samsung/*/GT-I9500/*"},{"ua":"GT-I9500"}],"dpi":[442.5,443.3],"bw":3,"ac":500},{"type":"android","rules":[{"mdmh":"samsung/*/GT-I9505/*"},{"ua":"GT-I9505"}],"dpi":439.4,"bw":4,"ac":1000},{"type":"android","rules":[{"mdmh":"samsung/*/SM-G900F/*"},{"ua":"SM-G900F"}],"dpi":[415.6,431.6],"bw":5,"ac":1000},{"type":"android","rules":[{"mdmh":"samsung/*/SM-G900M/*"},{"ua":"SM-G900M"}],"dpi":[415.6,431.6],"bw":5,"ac":1000},{"type":"android","rules":[{"mdmh":"samsung/*/SM-G800F/*"},{"ua":"SM-G800F"}],"dpi":326.8,"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"samsung/*/SM-G906S/*"},{"ua":"SM-G906S"}],"dpi":[562.7,572.4],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"samsung/*/GT-I9300/*"},{"ua":"GT-I9300"}],"dpi":[306.7,304.8],"bw":5,"ac":1000},{"type":"android","rules":[{"mdmh":"samsung/*/SM-T535/*"},{"ua":"SM-T535"}],"dpi":[142.6,136.4],"bw":3,"ac":500},{"type":"android","rules":[{"mdmh":"samsung/*/SM-N920C/*"},{"ua":"SM-N920C"}],"dpi":[515.1,518.4],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"samsung/*/SM-N920P/*"},{"ua":"SM-N920P"}],"dpi":[386.3655,390.144],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"samsung/*/SM-N920W8/*"},{"ua":"SM-N920W8"}],"dpi":[515.1,518.4],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"samsung/*/GT-I9300I/*"},{"ua":"GT-I9300I"}],"dpi":[304.8,305.8],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"samsung/*/GT-I9195/*"},{"ua":"GT-I9195"}],"dpi":[249.4,256.7],"bw":3,"ac":500},{"type":"android","rules":[{"mdmh":"samsung/*/SPH-L520/*"},{"ua":"SPH-L520"}],"dpi":[249.4,255.9],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"samsung/*/SAMSUNG-SGH-I717/*"},{"ua":"SAMSUNG-SGH-I717"}],"dpi":285.8,"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"samsung/*/SPH-D710/*"},{"ua":"SPH-D710"}],"dpi":[217.7,204.2],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"samsung/*/GT-N7100/*"},{"ua":"GT-N7100"}],"dpi":265.1,"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"samsung/*/SCH-I605/*"},{"ua":"SCH-I605"}],"dpi":265.1,"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"samsung/*/Galaxy Nexus/*"},{"ua":"Galaxy Nexus"}],"dpi":[315.3,314.2],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"samsung/*/SM-N910H/*"},{"ua":"SM-N910H"}],"dpi":[515.1,518],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"samsung/*/SM-N910C/*"},{"ua":"SM-N910C"}],"dpi":[515.2,520.2],"bw":3,"ac":500},{"type":"android","rules":[{"mdmh":"samsung/*/SM-G130M/*"},{"ua":"SM-G130M"}],"dpi":[165.9,164.8],"bw":3,"ac":500},{"type":"android","rules":[{"mdmh":"samsung/*/SM-G928I/*"},{"ua":"SM-G928I"}],"dpi":[515.1,518.4],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"samsung/*/SM-G920F/*"},{"ua":"SM-G920F"}],"dpi":580.6,"bw":3,"ac":500},{"type":"android","rules":[{"mdmh":"samsung/*/SM-G920P/*"},{"ua":"SM-G920P"}],"dpi":[522.5,577],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"samsung/*/SM-G925F/*"},{"ua":"SM-G925F"}],"dpi":580.6,"bw":3,"ac":500},{"type":"android","rules":[{"mdmh":"samsung/*/SM-G925V/*"},{"ua":"SM-G925V"}],"dpi":[522.5,576.6],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"samsung/*/SM-G930F/*"},{"ua":"SM-G930F"}],"dpi":576.6,"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"samsung/*/SM-G935F/*"},{"ua":"SM-G935F"}],"dpi":533,"bw":3,"ac":500},{"type":"android","rules":[{"mdmh":"samsung/*/SM-G950F/*"},{"ua":"SM-G950F"}],"dpi":[562.707,565.293],"bw":3,"ac":500},{"type":"android","rules":[{"mdmh":"samsung/*/SM-G955U/*"},{"ua":"SM-G955U"}],"dpi":[522.514,525.762],"bw":3,"ac":500},{"type":"android","rules":[{"mdmh":"samsung/*/SM-G955F/*"},{"ua":"SM-G955F"}],"dpi":[522.514,525.762],"bw":3,"ac":500},{"type":"android","rules":[{"mdmh":"samsung/*/SM-G960F/*"},{"ua":"SM-G960F"}],"dpi":[569.575,571.5],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"samsung/*/SM-G9600/*"},{"ua":"SM-G9600"}],"dpi":[569.575,571.5],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"samsung/*/SM-G960T/*"},{"ua":"SM-G960T"}],"dpi":[569.575,571.5],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"samsung/*/SM-G960N/*"},{"ua":"SM-G960N"}],"dpi":[569.575,571.5],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"samsung/*/SM-G960U/*"},{"ua":"SM-G960U"}],"dpi":[569.575,571.5],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"samsung/*/SM-G9608/*"},{"ua":"SM-G9608"}],"dpi":[569.575,571.5],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"samsung/*/SM-G960FD/*"},{"ua":"SM-G960FD"}],"dpi":[569.575,571.5],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"samsung/*/SM-G960W/*"},{"ua":"SM-G960W"}],"dpi":[569.575,571.5],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"samsung/*/SM-G965F/*"},{"ua":"SM-G965F"}],"dpi":529,"bw":2,"ac":1000},{"type":"android","rules":[{"mdmh":"Sony/*/C6903/*"},{"ua":"C6903"}],"dpi":[442.5,443.3],"bw":3,"ac":500},{"type":"android","rules":[{"mdmh":"Sony/*/D6653/*"},{"ua":"D6653"}],"dpi":[428.6,427.6],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"Sony/*/E6653/*"},{"ua":"E6653"}],"dpi":[428.6,425.7],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"Sony/*/E6853/*"},{"ua":"E6853"}],"dpi":[403.4,401.9],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"Sony/*/SGP321/*"},{"ua":"SGP321"}],"dpi":[224.7,224.1],"bw":3,"ac":500},{"type":"android","rules":[{"mdmh":"TCT/*/ALCATEL ONE TOUCH Fierce/*"},{"ua":"ALCATEL ONE TOUCH Fierce"}],"dpi":[240,247.5],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"THL/*/thl 5000/*"},{"ua":"thl 5000"}],"dpi":[480,443.3],"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"Fly/*/IQ4412/*"},{"ua":"IQ4412"}],"dpi":307.9,"bw":3,"ac":1000},{"type":"android","rules":[{"mdmh":"ZTE/*/ZTE Blade L2/*"},{"ua":"ZTE Blade L2"}],"dpi":240,"bw":3,"ac":500},{"type":"android","rules":[{"mdmh":"BENEVE/*/VR518/*"},{"ua":"VR518"}],"dpi":480,"bw":3,"ac":500},{"type":"ios","rules":[{"res":[640,960]}],"dpi":[325.1,328.4],"bw":4,"ac":1000},{"type":"ios","rules":[{"res":[640,1136]}],"dpi":[317.1,320.2],"bw":3,"ac":1000},{"type":"ios","rules":[{"res":[750,1334]}],"dpi":326.4,"bw":4,"ac":1000},{"type":"ios","rules":[{"res":[1242,2208]}],"dpi":[453.6,458.4],"bw":4,"ac":1000},{"type":"ios","rules":[{"res":[1125,2001]}],"dpi":[410.9,415.4],"bw":4,"ac":1000},{"type":"ios","rules":[{"res":[1125,2436]}],"dpi":458,"bw":4,"ac":1000},{"type":"android","rules":[{"mdmh":"Huawei/*/EML-L29/*"},{"ua":"EML-L29"}],"dpi":428,"bw":3.45,"ac":500},{"type":"android","rules":[{"mdmh":"Nokia/*/Nokia 7.1/*"},{"ua":"Nokia 7.1"}],"dpi":[432,431.9],"bw":3,"ac":500},{"type":"ios","rules":[{"res":[1242,2688]}],"dpi":458,"bw":4,"ac":1000},{"type":"android","rules":[{"mdmh":"samsung/*/SM-G570M/*"},{"ua":"SM-G570M"}],"dpi":320,"bw":3.684,"ac":1000},{"type":"android","rules":[{"mdmh":"samsung/*/SM-G970F/*"},{"ua":"SM-G970F"}],"dpi":438,"bw":2.281,"ac":500},{"type":"android","rules":[{"mdmh":"samsung/*/SM-G973F/*"},{"ua":"SM-G973F"}],"dpi":550,"bw":2.002,"ac":500},{"type":"android","rules":[{"mdmh":"samsung/*/SM-G975F/*"},{"ua":"SM-G975F"}],"dpi":522,"bw":2.054,"ac":500},{"type":"android","rules":[{"mdmh":"samsung/*/SM-G977F/*"},{"ua":"SM-G977F"}],"dpi":505,"bw":2.334,"ac":500},{"type":"ios","rules":[{"res":[828,1792]}],"dpi":326,"bw":5,"ac":500}];
  43106. var DPDB_CACHE = {
  43107. format: format,
  43108. last_updated: last_updated,
  43109. devices: devices
  43110. };
  43111. function Dpdb(url, onDeviceParamsUpdated) {
  43112. this.dpdb = DPDB_CACHE;
  43113. this.recalculateDeviceParams_();
  43114. if (url) {
  43115. this.onDeviceParamsUpdated = onDeviceParamsUpdated;
  43116. var xhr = new XMLHttpRequest();
  43117. var obj = this;
  43118. xhr.open('GET', url, true);
  43119. xhr.addEventListener('load', function () {
  43120. obj.loading = false;
  43121. if (xhr.status >= 200 && xhr.status <= 299) {
  43122. obj.dpdb = JSON.parse(xhr.response);
  43123. obj.recalculateDeviceParams_();
  43124. } else {
  43125. console.error('Error loading online DPDB!');
  43126. }
  43127. });
  43128. xhr.send();
  43129. }
  43130. }
  43131. Dpdb.prototype.getDeviceParams = function () {
  43132. return this.deviceParams;
  43133. };
  43134. Dpdb.prototype.recalculateDeviceParams_ = function () {
  43135. var newDeviceParams = this.calcDeviceParams_();
  43136. if (newDeviceParams) {
  43137. this.deviceParams = newDeviceParams;
  43138. if (this.onDeviceParamsUpdated) {
  43139. this.onDeviceParamsUpdated(this.deviceParams);
  43140. }
  43141. } else {
  43142. console.error('Failed to recalculate device parameters.');
  43143. }
  43144. };
  43145. Dpdb.prototype.calcDeviceParams_ = function () {
  43146. var db = this.dpdb;
  43147. if (!db) {
  43148. console.error('DPDB not available.');
  43149. return null;
  43150. }
  43151. if (db.format != 1) {
  43152. console.error('DPDB has unexpected format version.');
  43153. return null;
  43154. }
  43155. if (!db.devices || !db.devices.length) {
  43156. console.error('DPDB does not have a devices section.');
  43157. return null;
  43158. }
  43159. var userAgent = navigator.userAgent || navigator.vendor || window.opera;
  43160. var width = getScreenWidth();
  43161. var height = getScreenHeight();
  43162. if (!db.devices) {
  43163. console.error('DPDB has no devices section.');
  43164. return null;
  43165. }
  43166. for (var i = 0; i < db.devices.length; i++) {
  43167. var device = db.devices[i];
  43168. if (!device.rules) {
  43169. console.warn('Device[' + i + '] has no rules section.');
  43170. continue;
  43171. }
  43172. if (device.type != 'ios' && device.type != 'android') {
  43173. console.warn('Device[' + i + '] has invalid type.');
  43174. continue;
  43175. }
  43176. if (isIOS() != (device.type == 'ios')) continue;
  43177. var matched = false;
  43178. for (var j = 0; j < device.rules.length; j++) {
  43179. var rule = device.rules[j];
  43180. if (this.ruleMatches_(rule, userAgent, width, height)) {
  43181. matched = true;
  43182. break;
  43183. }
  43184. }
  43185. if (!matched) continue;
  43186. var xdpi = device.dpi[0] || device.dpi;
  43187. var ydpi = device.dpi[1] || device.dpi;
  43188. return new DeviceParams({ xdpi: xdpi, ydpi: ydpi, bevelMm: device.bw });
  43189. }
  43190. console.warn('No DPDB device match.');
  43191. return null;
  43192. };
  43193. Dpdb.prototype.ruleMatches_ = function (rule, ua, screenWidth, screenHeight) {
  43194. if (!rule.ua && !rule.res) return false;
  43195. if (rule.ua && rule.ua.substring(0, 2) === 'SM') rule.ua = rule.ua.substring(0, 7);
  43196. if (rule.ua && ua.indexOf(rule.ua) < 0) return false;
  43197. if (rule.res) {
  43198. if (!rule.res[0] || !rule.res[1]) return false;
  43199. var resX = rule.res[0];
  43200. var resY = rule.res[1];
  43201. if (Math.min(screenWidth, screenHeight) != Math.min(resX, resY) || Math.max(screenWidth, screenHeight) != Math.max(resX, resY)) {
  43202. return false;
  43203. }
  43204. }
  43205. return true;
  43206. };
  43207. function DeviceParams(params) {
  43208. this.xdpi = params.xdpi;
  43209. this.ydpi = params.ydpi;
  43210. this.bevelMm = params.bevelMm;
  43211. }
  43212. function SensorSample(sample, timestampS) {
  43213. this.set(sample, timestampS);
  43214. }
  43215. SensorSample.prototype.set = function (sample, timestampS) {
  43216. this.sample = sample;
  43217. this.timestampS = timestampS;
  43218. };
  43219. SensorSample.prototype.copy = function (sensorSample) {
  43220. this.set(sensorSample.sample, sensorSample.timestampS);
  43221. };
  43222. function ComplementaryFilter(kFilter, isDebug) {
  43223. this.kFilter = kFilter;
  43224. this.isDebug = isDebug;
  43225. this.currentAccelMeasurement = new SensorSample();
  43226. this.currentGyroMeasurement = new SensorSample();
  43227. this.previousGyroMeasurement = new SensorSample();
  43228. if (isIOS()) {
  43229. this.filterQ = new Quaternion(-1, 0, 0, 1);
  43230. } else {
  43231. this.filterQ = new Quaternion(1, 0, 0, 1);
  43232. }
  43233. this.previousFilterQ = new Quaternion();
  43234. this.previousFilterQ.copy(this.filterQ);
  43235. this.accelQ = new Quaternion();
  43236. this.isOrientationInitialized = false;
  43237. this.estimatedGravity = new Vector3();
  43238. this.measuredGravity = new Vector3();
  43239. this.gyroIntegralQ = new Quaternion();
  43240. }
  43241. ComplementaryFilter.prototype.addAccelMeasurement = function (vector, timestampS) {
  43242. this.currentAccelMeasurement.set(vector, timestampS);
  43243. };
  43244. ComplementaryFilter.prototype.addGyroMeasurement = function (vector, timestampS) {
  43245. this.currentGyroMeasurement.set(vector, timestampS);
  43246. var deltaT = timestampS - this.previousGyroMeasurement.timestampS;
  43247. if (isTimestampDeltaValid(deltaT)) {
  43248. this.run_();
  43249. }
  43250. this.previousGyroMeasurement.copy(this.currentGyroMeasurement);
  43251. };
  43252. ComplementaryFilter.prototype.run_ = function () {
  43253. if (!this.isOrientationInitialized) {
  43254. this.accelQ = this.accelToQuaternion_(this.currentAccelMeasurement.sample);
  43255. this.previousFilterQ.copy(this.accelQ);
  43256. this.isOrientationInitialized = true;
  43257. return;
  43258. }
  43259. var deltaT = this.currentGyroMeasurement.timestampS - this.previousGyroMeasurement.timestampS;
  43260. var gyroDeltaQ = this.gyroToQuaternionDelta_(this.currentGyroMeasurement.sample, deltaT);
  43261. this.gyroIntegralQ.multiply(gyroDeltaQ);
  43262. this.filterQ.copy(this.previousFilterQ);
  43263. this.filterQ.multiply(gyroDeltaQ);
  43264. var invFilterQ = new Quaternion();
  43265. invFilterQ.copy(this.filterQ);
  43266. invFilterQ.inverse();
  43267. this.estimatedGravity.set(0, 0, -1);
  43268. this.estimatedGravity.applyQuaternion(invFilterQ);
  43269. this.estimatedGravity.normalize();
  43270. this.measuredGravity.copy(this.currentAccelMeasurement.sample);
  43271. this.measuredGravity.normalize();
  43272. var deltaQ = new Quaternion();
  43273. deltaQ.setFromUnitVectors(this.estimatedGravity, this.measuredGravity);
  43274. deltaQ.inverse();
  43275. if (this.isDebug) {
  43276. console.log('Delta: %d deg, G_est: (%s, %s, %s), G_meas: (%s, %s, %s)', radToDeg * getQuaternionAngle(deltaQ), this.estimatedGravity.x.toFixed(1), this.estimatedGravity.y.toFixed(1), this.estimatedGravity.z.toFixed(1), this.measuredGravity.x.toFixed(1), this.measuredGravity.y.toFixed(1), this.measuredGravity.z.toFixed(1));
  43277. }
  43278. var targetQ = new Quaternion();
  43279. targetQ.copy(this.filterQ);
  43280. targetQ.multiply(deltaQ);
  43281. this.filterQ.slerp(targetQ, 1 - this.kFilter);
  43282. this.previousFilterQ.copy(this.filterQ);
  43283. };
  43284. ComplementaryFilter.prototype.getOrientation = function () {
  43285. return this.filterQ;
  43286. };
  43287. ComplementaryFilter.prototype.accelToQuaternion_ = function (accel) {
  43288. var normAccel = new Vector3();
  43289. normAccel.copy(accel);
  43290. normAccel.normalize();
  43291. var quat = new Quaternion();
  43292. quat.setFromUnitVectors(new Vector3(0, 0, -1), normAccel);
  43293. quat.inverse();
  43294. return quat;
  43295. };
  43296. ComplementaryFilter.prototype.gyroToQuaternionDelta_ = function (gyro, dt) {
  43297. var quat = new Quaternion();
  43298. var axis = new Vector3();
  43299. axis.copy(gyro);
  43300. axis.normalize();
  43301. quat.setFromAxisAngle(axis, gyro.length() * dt);
  43302. return quat;
  43303. };
  43304. function PosePredictor(predictionTimeS, isDebug) {
  43305. this.predictionTimeS = predictionTimeS;
  43306. this.isDebug = isDebug;
  43307. this.previousQ = new Quaternion();
  43308. this.previousTimestampS = null;
  43309. this.deltaQ = new Quaternion();
  43310. this.outQ = new Quaternion();
  43311. }
  43312. PosePredictor.prototype.getPrediction = function (currentQ, gyro, timestampS) {
  43313. if (!this.previousTimestampS) {
  43314. this.previousQ.copy(currentQ);
  43315. this.previousTimestampS = timestampS;
  43316. return currentQ;
  43317. }
  43318. var axis = new Vector3();
  43319. axis.copy(gyro);
  43320. axis.normalize();
  43321. var angularSpeed = gyro.length();
  43322. if (angularSpeed < degToRad * 20) {
  43323. if (this.isDebug) {
  43324. console.log('Moving slowly, at %s deg/s: no prediction', (radToDeg * angularSpeed).toFixed(1));
  43325. }
  43326. this.outQ.copy(currentQ);
  43327. this.previousQ.copy(currentQ);
  43328. return this.outQ;
  43329. }
  43330. var predictAngle = angularSpeed * this.predictionTimeS;
  43331. this.deltaQ.setFromAxisAngle(axis, predictAngle);
  43332. this.outQ.copy(this.previousQ);
  43333. this.outQ.multiply(this.deltaQ);
  43334. this.previousQ.copy(currentQ);
  43335. this.previousTimestampS = timestampS;
  43336. return this.outQ;
  43337. };
  43338. function FusionPoseSensor(kFilter, predictionTime, yawOnly, isDebug) {
  43339. this.yawOnly = yawOnly;
  43340. this.accelerometer = new Vector3();
  43341. this.gyroscope = new Vector3();
  43342. this.filter = new ComplementaryFilter(kFilter, isDebug);
  43343. this.posePredictor = new PosePredictor(predictionTime, isDebug);
  43344. this.isFirefoxAndroid = isFirefoxAndroid();
  43345. this.isIOS = isIOS();
  43346. var chromeVersion = getChromeVersion();
  43347. this.isDeviceMotionInRadians = !this.isIOS && chromeVersion && chromeVersion < 66;
  43348. this.isWithoutDeviceMotion = isChromeWithoutDeviceMotion() || isSafariWithoutDeviceMotion();
  43349. this.filterToWorldQ = new Quaternion();
  43350. if (isIOS()) {
  43351. this.filterToWorldQ.setFromAxisAngle(new Vector3(1, 0, 0), Math.PI / 2);
  43352. } else {
  43353. this.filterToWorldQ.setFromAxisAngle(new Vector3(1, 0, 0), -Math.PI / 2);
  43354. }
  43355. this.inverseWorldToScreenQ = new Quaternion();
  43356. this.worldToScreenQ = new Quaternion();
  43357. this.originalPoseAdjustQ = new Quaternion();
  43358. this.originalPoseAdjustQ.setFromAxisAngle(new Vector3(0, 0, 1), -window.orientation * Math.PI / 180);
  43359. this.setScreenTransform_();
  43360. if (isLandscapeMode()) {
  43361. this.filterToWorldQ.multiply(this.inverseWorldToScreenQ);
  43362. }
  43363. this.resetQ = new Quaternion();
  43364. this.orientationOut_ = new Float32Array(4);
  43365. this.start();
  43366. }
  43367. FusionPoseSensor.prototype.getPosition = function () {
  43368. return null;
  43369. };
  43370. FusionPoseSensor.prototype.getOrientation = function () {
  43371. var orientation = void 0;
  43372. if (this.isWithoutDeviceMotion && this._deviceOrientationQ) {
  43373. this.deviceOrientationFixQ = this.deviceOrientationFixQ || function () {
  43374. var z = new Quaternion().setFromAxisAngle(new Vector3(0, 0, -1), 0);
  43375. var y = new Quaternion();
  43376. if (window.orientation === -90) {
  43377. y.setFromAxisAngle(new Vector3(0, 1, 0), Math.PI / -2);
  43378. } else {
  43379. y.setFromAxisAngle(new Vector3(0, 1, 0), Math.PI / 2);
  43380. }
  43381. return z.multiply(y);
  43382. }();
  43383. this.deviceOrientationFilterToWorldQ = this.deviceOrientationFilterToWorldQ || function () {
  43384. var q = new Quaternion();
  43385. q.setFromAxisAngle(new Vector3(1, 0, 0), -Math.PI / 2);
  43386. return q;
  43387. }();
  43388. orientation = this._deviceOrientationQ;
  43389. var out = new Quaternion();
  43390. out.copy(orientation);
  43391. out.multiply(this.deviceOrientationFilterToWorldQ);
  43392. out.multiply(this.resetQ);
  43393. out.multiply(this.worldToScreenQ);
  43394. out.multiplyQuaternions(this.deviceOrientationFixQ, out);
  43395. if (this.yawOnly) {
  43396. out.x = 0;
  43397. out.z = 0;
  43398. out.normalize();
  43399. }
  43400. this.orientationOut_[0] = out.x;
  43401. this.orientationOut_[1] = out.y;
  43402. this.orientationOut_[2] = out.z;
  43403. this.orientationOut_[3] = out.w;
  43404. return this.orientationOut_;
  43405. } else {
  43406. var filterOrientation = this.filter.getOrientation();
  43407. orientation = this.posePredictor.getPrediction(filterOrientation, this.gyroscope, this.previousTimestampS);
  43408. }
  43409. var out = new Quaternion();
  43410. out.copy(this.filterToWorldQ);
  43411. out.multiply(this.resetQ);
  43412. out.multiply(orientation);
  43413. out.multiply(this.worldToScreenQ);
  43414. if (this.yawOnly) {
  43415. out.x = 0;
  43416. out.z = 0;
  43417. out.normalize();
  43418. }
  43419. this.orientationOut_[0] = out.x;
  43420. this.orientationOut_[1] = out.y;
  43421. this.orientationOut_[2] = out.z;
  43422. this.orientationOut_[3] = out.w;
  43423. return this.orientationOut_;
  43424. };
  43425. FusionPoseSensor.prototype.resetPose = function () {
  43426. this.resetQ.copy(this.filter.getOrientation());
  43427. this.resetQ.x = 0;
  43428. this.resetQ.y = 0;
  43429. this.resetQ.z *= -1;
  43430. this.resetQ.normalize();
  43431. if (isLandscapeMode()) {
  43432. this.resetQ.multiply(this.inverseWorldToScreenQ);
  43433. }
  43434. this.resetQ.multiply(this.originalPoseAdjustQ);
  43435. };
  43436. FusionPoseSensor.prototype.onDeviceOrientation_ = function (e) {
  43437. this._deviceOrientationQ = this._deviceOrientationQ || new Quaternion();
  43438. var alpha = e.alpha,
  43439. beta = e.beta,
  43440. gamma = e.gamma;
  43441. alpha = (alpha || 0) * Math.PI / 180;
  43442. beta = (beta || 0) * Math.PI / 180;
  43443. gamma = (gamma || 0) * Math.PI / 180;
  43444. this._deviceOrientationQ.setFromEulerYXZ(beta, alpha, -gamma);
  43445. };
  43446. FusionPoseSensor.prototype.onDeviceMotion_ = function (deviceMotion) {
  43447. this.updateDeviceMotion_(deviceMotion);
  43448. };
  43449. FusionPoseSensor.prototype.updateDeviceMotion_ = function (deviceMotion) {
  43450. var accGravity = deviceMotion.accelerationIncludingGravity;
  43451. var rotRate = deviceMotion.rotationRate;
  43452. var timestampS = deviceMotion.timeStamp / 1000;
  43453. var deltaS = timestampS - this.previousTimestampS;
  43454. if (deltaS < 0) {
  43455. warnOnce('fusion-pose-sensor:invalid:non-monotonic', 'Invalid timestamps detected: non-monotonic timestamp from devicemotion');
  43456. this.previousTimestampS = timestampS;
  43457. return;
  43458. } else if (deltaS <= MIN_TIMESTEP || deltaS > MAX_TIMESTEP) {
  43459. warnOnce('fusion-pose-sensor:invalid:outside-threshold', 'Invalid timestamps detected: Timestamp from devicemotion outside expected range.');
  43460. this.previousTimestampS = timestampS;
  43461. return;
  43462. }
  43463. this.accelerometer.set(-accGravity.x, -accGravity.y, -accGravity.z);
  43464. if (rotRate) {
  43465. if (isR7()) {
  43466. this.gyroscope.set(-rotRate.beta, rotRate.alpha, rotRate.gamma);
  43467. } else {
  43468. this.gyroscope.set(rotRate.alpha, rotRate.beta, rotRate.gamma);
  43469. }
  43470. if (!this.isDeviceMotionInRadians) {
  43471. this.gyroscope.multiplyScalar(Math.PI / 180);
  43472. }
  43473. this.filter.addGyroMeasurement(this.gyroscope, timestampS);
  43474. }
  43475. this.filter.addAccelMeasurement(this.accelerometer, timestampS);
  43476. this.previousTimestampS = timestampS;
  43477. };
  43478. FusionPoseSensor.prototype.onOrientationChange_ = function (screenOrientation) {
  43479. this.setScreenTransform_();
  43480. };
  43481. FusionPoseSensor.prototype.onMessage_ = function (event) {
  43482. var message = event.data;
  43483. if (!message || !message.type) {
  43484. return;
  43485. }
  43486. var type = message.type.toLowerCase();
  43487. if (type !== 'devicemotion') {
  43488. return;
  43489. }
  43490. this.updateDeviceMotion_(message.deviceMotionEvent);
  43491. };
  43492. FusionPoseSensor.prototype.setScreenTransform_ = function () {
  43493. this.worldToScreenQ.set(0, 0, 0, 1);
  43494. switch (window.orientation) {
  43495. case 0:
  43496. break;
  43497. case 90:
  43498. this.worldToScreenQ.setFromAxisAngle(new Vector3(0, 0, 1), -Math.PI / 2);
  43499. break;
  43500. case -90:
  43501. this.worldToScreenQ.setFromAxisAngle(new Vector3(0, 0, 1), Math.PI / 2);
  43502. break;
  43503. case 180:
  43504. break;
  43505. }
  43506. this.inverseWorldToScreenQ.copy(this.worldToScreenQ);
  43507. this.inverseWorldToScreenQ.inverse();
  43508. };
  43509. FusionPoseSensor.prototype.start = function () {
  43510. this.onDeviceMotionCallback_ = this.onDeviceMotion_.bind(this);
  43511. this.onOrientationChangeCallback_ = this.onOrientationChange_.bind(this);
  43512. this.onMessageCallback_ = this.onMessage_.bind(this);
  43513. this.onDeviceOrientationCallback_ = this.onDeviceOrientation_.bind(this);
  43514. if (isIOS() && isInsideCrossOriginIFrame()) {
  43515. window.addEventListener('message', this.onMessageCallback_);
  43516. }
  43517. window.addEventListener('orientationchange', this.onOrientationChangeCallback_);
  43518. if (this.isWithoutDeviceMotion) {
  43519. window.addEventListener('deviceorientation', this.onDeviceOrientationCallback_);
  43520. } else {
  43521. window.addEventListener('devicemotion', this.onDeviceMotionCallback_);
  43522. }
  43523. };
  43524. FusionPoseSensor.prototype.stop = function () {
  43525. window.removeEventListener('devicemotion', this.onDeviceMotionCallback_);
  43526. window.removeEventListener('deviceorientation', this.onDeviceOrientationCallback_);
  43527. window.removeEventListener('orientationchange', this.onOrientationChangeCallback_);
  43528. window.removeEventListener('message', this.onMessageCallback_);
  43529. };
  43530. var SENSOR_FREQUENCY = 60;
  43531. var X_AXIS = new Vector3(1, 0, 0);
  43532. var Z_AXIS = new Vector3(0, 0, 1);
  43533. var SENSOR_TO_VR = new Quaternion();
  43534. SENSOR_TO_VR.setFromAxisAngle(X_AXIS, -Math.PI / 2);
  43535. SENSOR_TO_VR.multiply(new Quaternion().setFromAxisAngle(Z_AXIS, Math.PI / 2));
  43536. var PoseSensor = function () {
  43537. function PoseSensor(config) {
  43538. classCallCheck(this, PoseSensor);
  43539. this.config = config;
  43540. this.sensor = null;
  43541. this.fusionSensor = null;
  43542. this._out = new Float32Array(4);
  43543. this.api = null;
  43544. this.errors = [];
  43545. this._sensorQ = new Quaternion();
  43546. this._outQ = new Quaternion();
  43547. this._onSensorRead = this._onSensorRead.bind(this);
  43548. this._onSensorError = this._onSensorError.bind(this);
  43549. this.init();
  43550. }
  43551. createClass(PoseSensor, [{
  43552. key: 'init',
  43553. value: function init() {
  43554. var sensor = null;
  43555. try {
  43556. sensor = new RelativeOrientationSensor({
  43557. frequency: SENSOR_FREQUENCY,
  43558. referenceFrame: 'screen'
  43559. });
  43560. sensor.addEventListener('error', this._onSensorError);
  43561. } catch (error) {
  43562. this.errors.push(error);
  43563. if (error.name === 'SecurityError') {
  43564. console.error('Cannot construct sensors due to the Feature Policy');
  43565. console.warn('Attempting to fall back using "devicemotion"; however this will ' + 'fail in the future without correct permissions.');
  43566. this.useDeviceMotion();
  43567. } else if (error.name === 'ReferenceError') {
  43568. this.useDeviceMotion();
  43569. } else {
  43570. console.error(error);
  43571. }
  43572. }
  43573. if (sensor) {
  43574. this.api = 'sensor';
  43575. this.sensor = sensor;
  43576. this.sensor.addEventListener('reading', this._onSensorRead);
  43577. this.sensor.start();
  43578. }
  43579. }
  43580. }, {
  43581. key: 'useDeviceMotion',
  43582. value: function useDeviceMotion() {
  43583. this.api = 'devicemotion';
  43584. this.fusionSensor = new FusionPoseSensor(this.config.K_FILTER, this.config.PREDICTION_TIME_S, this.config.YAW_ONLY, this.config.DEBUG);
  43585. if (this.sensor) {
  43586. this.sensor.removeEventListener('reading', this._onSensorRead);
  43587. this.sensor.removeEventListener('error', this._onSensorError);
  43588. this.sensor = null;
  43589. }
  43590. }
  43591. }, {
  43592. key: 'getOrientation',
  43593. value: function getOrientation() {
  43594. if (this.fusionSensor) {
  43595. return this.fusionSensor.getOrientation();
  43596. }
  43597. if (!this.sensor || !this.sensor.quaternion) {
  43598. this._out[0] = this._out[1] = this._out[2] = 0;
  43599. this._out[3] = 1;
  43600. return this._out;
  43601. }
  43602. var q = this.sensor.quaternion;
  43603. this._sensorQ.set(q[0], q[1], q[2], q[3]);
  43604. var out = this._outQ;
  43605. out.copy(SENSOR_TO_VR);
  43606. out.multiply(this._sensorQ);
  43607. if (this.config.YAW_ONLY) {
  43608. out.x = out.z = 0;
  43609. out.normalize();
  43610. }
  43611. this._out[0] = out.x;
  43612. this._out[1] = out.y;
  43613. this._out[2] = out.z;
  43614. this._out[3] = out.w;
  43615. return this._out;
  43616. }
  43617. }, {
  43618. key: '_onSensorError',
  43619. value: function _onSensorError(event) {
  43620. this.errors.push(event.error);
  43621. if (event.error.name === 'NotAllowedError') {
  43622. console.error('Permission to access sensor was denied');
  43623. } else if (event.error.name === 'NotReadableError') {
  43624. console.error('Sensor could not be read');
  43625. } else {
  43626. console.error(event.error);
  43627. }
  43628. this.useDeviceMotion();
  43629. }
  43630. }, {
  43631. key: '_onSensorRead',
  43632. value: function _onSensorRead() {}
  43633. }]);
  43634. return PoseSensor;
  43635. }();
  43636. var rotateInstructionsAsset = "<svg width='198' height='240' viewBox='0 0 198 240' xmlns='http://www.w3.org/2000/svg'><g fill='none' fill-rule='evenodd'><path d='M149.625 109.527l6.737 3.891v.886c0 .177.013.36.038.549.01.081.02.162.027.242.14 1.415.974 2.998 2.105 3.999l5.72 5.062.081-.09s4.382-2.53 5.235-3.024l25.97 14.993v54.001c0 .771-.386 1.217-.948 1.217-.233 0-.495-.076-.772-.236l-23.967-13.838-.014.024-27.322 15.775-.85-1.323c-4.731-1.529-9.748-2.74-14.951-3.61a.27.27 0 0 0-.007.024l-5.067 16.961-7.891 4.556-.037-.063v27.59c0 .772-.386 1.217-.948 1.217-.232 0-.495-.076-.772-.236l-42.473-24.522c-.95-.549-1.72-1.877-1.72-2.967v-1.035l-.021.047a5.111 5.111 0 0 0-1.816-.399 5.682 5.682 0 0 0-.546.001 13.724 13.724 0 0 1-1.918-.041c-1.655-.153-3.2-.6-4.404-1.296l-46.576-26.89.005.012-10.278-18.75c-1.001-1.827-.241-4.216 1.698-5.336l56.011-32.345a4.194 4.194 0 0 1 2.099-.572c1.326 0 2.572.659 3.227 1.853l.005-.003.227.413-.006.004a9.63 9.63 0 0 0 1.477 2.018l.277.27c1.914 1.85 4.468 2.801 7.113 2.801 1.949 0 3.948-.517 5.775-1.572.013 0 7.319-4.219 7.319-4.219a4.194 4.194 0 0 1 2.099-.572c1.326 0 2.572.658 3.226 1.853l3.25 5.928.022-.018 6.785 3.917-.105-.182 46.881-26.965m0-1.635c-.282 0-.563.073-.815.218l-46.169 26.556-5.41-3.124-3.005-5.481c-.913-1.667-2.699-2.702-4.66-2.703-1.011 0-2.02.274-2.917.792a3825 3825 0 0 1-7.275 4.195l-.044.024a9.937 9.937 0 0 1-4.957 1.353c-2.292 0-4.414-.832-5.976-2.342l-.252-.245a7.992 7.992 0 0 1-1.139-1.534 1.379 1.379 0 0 0-.06-.122l-.227-.414a1.718 1.718 0 0 0-.095-.154c-.938-1.574-2.673-2.545-4.571-2.545-1.011 0-2.02.274-2.917.792L3.125 155.502c-2.699 1.559-3.738 4.94-2.314 7.538l10.278 18.75c.177.323.448.563.761.704l46.426 26.804c1.403.81 3.157 1.332 5.072 1.508a15.661 15.661 0 0 0 2.146.046 4.766 4.766 0 0 1 .396 0c.096.004.19.011.283.022.109 1.593 1.159 3.323 2.529 4.114l42.472 24.522c.524.302 1.058.455 1.59.455 1.497 0 2.583-1.2 2.583-2.852v-26.562l7.111-4.105a1.64 1.64 0 0 0 .749-.948l4.658-15.593c4.414.797 8.692 1.848 12.742 3.128l.533.829a1.634 1.634 0 0 0 2.193.531l26.532-15.317L193 192.433c.523.302 1.058.455 1.59.455 1.497 0 2.583-1.199 2.583-2.852v-54.001c0-.584-.312-1.124-.818-1.416l-25.97-14.993a1.633 1.633 0 0 0-1.636.001c-.606.351-2.993 1.73-4.325 2.498l-4.809-4.255c-.819-.725-1.461-1.933-1.561-2.936a7.776 7.776 0 0 0-.033-.294 2.487 2.487 0 0 1-.023-.336v-.886c0-.584-.312-1.123-.817-1.416l-6.739-3.891a1.633 1.633 0 0 0-.817-.219' fill='#455A64'/><path d='M96.027 132.636l46.576 26.891c1.204.695 1.979 1.587 2.242 2.541l-.01.007-81.374 46.982h-.001c-1.654-.152-3.199-.6-4.403-1.295l-46.576-26.891 83.546-48.235' fill='#FAFAFA'/><path d='M63.461 209.174c-.008 0-.015 0-.022-.002-1.693-.156-3.228-.609-4.441-1.309l-46.576-26.89a.118.118 0 0 1 0-.203l83.546-48.235a.117.117 0 0 1 .117 0l46.576 26.891c1.227.708 2.021 1.612 2.296 2.611a.116.116 0 0 1-.042.124l-.021.016-81.375 46.981a.11.11 0 0 1-.058.016zm-50.747-28.303l46.401 26.79c1.178.68 2.671 1.121 4.32 1.276l81.272-46.922c-.279-.907-1.025-1.73-2.163-2.387l-46.517-26.857-83.313 48.1z' fill='#607D8B'/><path d='M148.327 165.471a5.85 5.85 0 0 1-.546.001c-1.894-.083-3.302-1.038-3.145-2.132a2.693 2.693 0 0 0-.072-1.105l-81.103 46.822c.628.058 1.272.073 1.918.042.182-.009.364-.009.546-.001 1.894.083 3.302 1.038 3.145 2.132l79.257-45.759' fill='#FFF'/><path d='M69.07 211.347a.118.118 0 0 1-.115-.134c.045-.317-.057-.637-.297-.925-.505-.61-1.555-1.022-2.738-1.074a5.966 5.966 0 0 0-.535.001 14.03 14.03 0 0 1-1.935-.041.117.117 0 0 1-.103-.092.116.116 0 0 1 .055-.126l81.104-46.822a.117.117 0 0 1 .171.07c.104.381.129.768.074 1.153-.045.316.057.637.296.925.506.61 1.555 1.021 2.739 1.073.178.008.357.008.535-.001a.117.117 0 0 1 .064.218l-79.256 45.759a.114.114 0 0 1-.059.016zm-3.405-2.372c.089 0 .177.002.265.006 1.266.056 2.353.488 2.908 1.158.227.274.35.575.36.882l78.685-45.429c-.036 0-.072-.001-.107-.003-1.267-.056-2.354-.489-2.909-1.158-.282-.34-.402-.724-.347-1.107a2.604 2.604 0 0 0-.032-.91L63.846 208.97a13.91 13.91 0 0 0 1.528.012c.097-.005.194-.007.291-.007z' fill='#607D8B'/><path d='M2.208 162.134c-1.001-1.827-.241-4.217 1.698-5.337l56.011-32.344c1.939-1.12 4.324-.546 5.326 1.281l.232.41a9.344 9.344 0 0 0 1.47 2.021l.278.27c3.325 3.214 8.583 3.716 12.888 1.23l7.319-4.22c1.94-1.119 4.324-.546 5.325 1.282l3.25 5.928-83.519 48.229-10.278-18.75z' fill='#FAFAFA'/><path d='M12.486 181.001a.112.112 0 0 1-.031-.005.114.114 0 0 1-.071-.056L2.106 162.19c-1.031-1.88-.249-4.345 1.742-5.494l56.01-32.344a4.328 4.328 0 0 1 2.158-.588c1.415 0 2.65.702 3.311 1.882.01.008.018.017.024.028l.227.414a.122.122 0 0 1 .013.038 9.508 9.508 0 0 0 1.439 1.959l.275.266c1.846 1.786 4.344 2.769 7.031 2.769 1.977 0 3.954-.538 5.717-1.557a.148.148 0 0 1 .035-.013l7.284-4.206a4.321 4.321 0 0 1 2.157-.588c1.427 0 2.672.716 3.329 1.914l3.249 5.929a.116.116 0 0 1-.044.157l-83.518 48.229a.116.116 0 0 1-.059.016zm49.53-57.004c-.704 0-1.41.193-2.041.557l-56.01 32.345c-1.882 1.086-2.624 3.409-1.655 5.179l10.221 18.645 83.317-48.112-3.195-5.829c-.615-1.122-1.783-1.792-3.124-1.792a4.08 4.08 0 0 0-2.04.557l-7.317 4.225a.148.148 0 0 1-.035.013 11.7 11.7 0 0 1-5.801 1.569c-2.748 0-5.303-1.007-7.194-2.835l-.278-.27a9.716 9.716 0 0 1-1.497-2.046.096.096 0 0 1-.013-.037l-.191-.347a.11.11 0 0 1-.023-.029c-.615-1.123-1.783-1.793-3.124-1.793z' fill='#607D8B'/><path d='M42.434 155.808c-2.51-.001-4.697-1.258-5.852-3.365-1.811-3.304-.438-7.634 3.059-9.654l12.291-7.098a7.599 7.599 0 0 1 3.789-1.033c2.51 0 4.697 1.258 5.852 3.365 1.811 3.304.439 7.634-3.059 9.654l-12.291 7.098a7.606 7.606 0 0 1-3.789 1.033zm13.287-20.683a7.128 7.128 0 0 0-3.555.971l-12.291 7.098c-3.279 1.893-4.573 5.942-2.883 9.024 1.071 1.955 3.106 3.122 5.442 3.122a7.13 7.13 0 0 0 3.556-.97l12.291-7.098c3.279-1.893 4.572-5.942 2.883-9.024-1.072-1.955-3.106-3.123-5.443-3.123z' fill='#607D8B'/><path d='M149.588 109.407l6.737 3.89v.887c0 .176.013.36.037.549.011.081.02.161.028.242.14 1.415.973 2.998 2.105 3.999l7.396 6.545c.177.156.358.295.541.415 1.579 1.04 2.95.466 3.062-1.282.049-.784.057-1.595.023-2.429l-.003-.16v-1.151l25.987 15.003v54c0 1.09-.77 1.53-1.72.982l-42.473-24.523c-.95-.548-1.72-1.877-1.72-2.966v-34.033' fill='#FAFAFA'/><path d='M194.553 191.25c-.257 0-.54-.085-.831-.253l-42.472-24.521c-.981-.567-1.779-1.943-1.779-3.068v-34.033h.234v34.033c0 1.051.745 2.336 1.661 2.866l42.473 24.521c.424.245.816.288 1.103.122.285-.164.442-.52.442-1.002v-53.933l-25.753-14.868.003 1.106c.034.832.026 1.654-.024 2.439-.054.844-.396 1.464-.963 1.746-.619.309-1.45.173-2.28-.373a5.023 5.023 0 0 1-.553-.426l-7.397-6.544c-1.158-1.026-1.999-2.625-2.143-4.076a9.624 9.624 0 0 0-.027-.238 4.241 4.241 0 0 1-.038-.564v-.82l-6.68-3.856.117-.202 6.738 3.89.058.034v.954c0 .171.012.351.036.533.011.083.021.165.029.246.138 1.395.948 2.935 2.065 3.923l7.397 6.545c.173.153.35.289.527.406.758.499 1.504.63 2.047.359.49-.243.786-.795.834-1.551.05-.778.057-1.591.024-2.417l-.004-.163v-1.355l.175.1 25.987 15.004.059.033v54.068c0 .569-.198.996-.559 1.204a1.002 1.002 0 0 1-.506.131' fill='#607D8B'/><path d='M145.685 163.161l24.115 13.922-25.978 14.998-1.462-.307c-6.534-2.17-13.628-3.728-21.019-4.616-4.365-.524-8.663 1.096-9.598 3.62a2.746 2.746 0 0 0-.011 1.928c1.538 4.267 4.236 8.363 7.995 12.135l.532.845-25.977 14.997-24.115-13.922 75.518-43.6' fill='#FFF'/><path d='M94.282 220.818l-.059-.033-24.29-14.024.175-.101 75.577-43.634.058.033 24.29 14.024-26.191 15.122-.045-.01-1.461-.307c-6.549-2.174-13.613-3.725-21.009-4.614a13.744 13.744 0 0 0-1.638-.097c-3.758 0-7.054 1.531-7.837 3.642a2.62 2.62 0 0 0-.01 1.848c1.535 4.258 4.216 8.326 7.968 12.091l.016.021.526.835.006.01.064.102-.105.061-25.977 14.998-.058.033zm-23.881-14.057l23.881 13.788 24.802-14.32c.546-.315.846-.489 1.017-.575l-.466-.74c-3.771-3.787-6.467-7.881-8.013-12.168a2.851 2.851 0 0 1 .011-2.008c.815-2.199 4.203-3.795 8.056-3.795.557 0 1.117.033 1.666.099 7.412.891 14.491 2.445 21.041 4.621.836.175 1.215.254 1.39.304l25.78-14.884-23.881-13.788-75.284 43.466z' fill='#607D8B'/><path d='M167.23 125.979v50.871l-27.321 15.773-6.461-14.167c-.91-1.996-3.428-1.738-5.624.574a10.238 10.238 0 0 0-2.33 4.018l-6.46 21.628-27.322 15.774v-50.871l75.518-43.6' fill='#FFF'/><path d='M91.712 220.567a.127.127 0 0 1-.059-.016.118.118 0 0 1-.058-.101v-50.871c0-.042.023-.08.058-.101l75.519-43.6a.117.117 0 0 1 .175.101v50.871c0 .041-.023.08-.059.1l-27.321 15.775a.118.118 0 0 1-.094.01.12.12 0 0 1-.071-.063l-6.46-14.168c-.375-.822-1.062-1.275-1.934-1.275-1.089 0-2.364.686-3.5 1.881a10.206 10.206 0 0 0-2.302 3.972l-6.46 21.627a.118.118 0 0 1-.054.068L91.77 220.551a.12.12 0 0 1-.058.016zm.117-50.92v50.601l27.106-15.65 6.447-21.583a10.286 10.286 0 0 1 2.357-4.065c1.18-1.242 2.517-1.954 3.669-1.954.969 0 1.731.501 2.146 1.411l6.407 14.051 27.152-15.676v-50.601l-75.284 43.466z' fill='#607D8B'/><path d='M168.543 126.213v50.87l-27.322 15.774-6.46-14.168c-.91-1.995-3.428-1.738-5.624.574a10.248 10.248 0 0 0-2.33 4.019l-6.461 21.627-27.321 15.774v-50.87l75.518-43.6' fill='#FFF'/><path d='M93.025 220.8a.123.123 0 0 1-.059-.015.12.12 0 0 1-.058-.101v-50.871c0-.042.023-.08.058-.101l75.518-43.6a.112.112 0 0 1 .117 0c.036.02.059.059.059.1v50.871a.116.116 0 0 1-.059.101l-27.321 15.774a.111.111 0 0 1-.094.01.115.115 0 0 1-.071-.062l-6.46-14.168c-.375-.823-1.062-1.275-1.935-1.275-1.088 0-2.363.685-3.499 1.881a10.19 10.19 0 0 0-2.302 3.971l-6.461 21.628a.108.108 0 0 1-.053.067l-27.322 15.775a.12.12 0 0 1-.058.015zm.117-50.919v50.6l27.106-15.649 6.447-21.584a10.293 10.293 0 0 1 2.357-4.065c1.179-1.241 2.516-1.954 3.668-1.954.969 0 1.732.502 2.147 1.412l6.407 14.051 27.152-15.676v-50.601l-75.284 43.466z' fill='#607D8B'/><path d='M169.8 177.083l-27.322 15.774-6.46-14.168c-.91-1.995-3.428-1.738-5.625.574a10.246 10.246 0 0 0-2.329 4.019l-6.461 21.627-27.321 15.774v-50.87l75.518-43.6v50.87z' fill='#FAFAFA'/><path d='M94.282 220.917a.234.234 0 0 1-.234-.233v-50.871c0-.083.045-.161.117-.202l75.518-43.601a.234.234 0 1 1 .35.202v50.871a.233.233 0 0 1-.116.202l-27.322 15.775a.232.232 0 0 1-.329-.106l-6.461-14.168c-.36-.789-.992-1.206-1.828-1.206-1.056 0-2.301.672-3.415 1.844a10.099 10.099 0 0 0-2.275 3.924l-6.46 21.628a.235.235 0 0 1-.107.136l-27.322 15.774a.23.23 0 0 1-.116.031zm.233-50.969v50.331l26.891-15.525 6.434-21.539a10.41 10.41 0 0 1 2.384-4.112c1.201-1.265 2.569-1.991 3.753-1.991 1.018 0 1.818.526 2.253 1.48l6.354 13.934 26.982-15.578v-50.331l-75.051 43.331z' fill='#607D8B'/><path d='M109.894 199.943c-1.774 0-3.241-.725-4.244-2.12a.224.224 0 0 1 .023-.294.233.233 0 0 1 .301-.023c.78.547 1.705.827 2.75.827 1.323 0 2.754-.439 4.256-1.306 5.311-3.067 9.631-10.518 9.631-16.611 0-1.927-.442-3.56-1.278-4.724a.232.232 0 0 1 .323-.327c1.671 1.172 2.591 3.381 2.591 6.219 0 6.242-4.426 13.863-9.865 17.003-1.574.908-3.084 1.356-4.488 1.356zm-2.969-1.542c.813.651 1.82.877 2.968.877h.001c1.321 0 2.753-.327 4.254-1.194 5.311-3.067 9.632-10.463 9.632-16.556 0-1.979-.463-3.599-1.326-4.761.411 1.035.625 2.275.625 3.635 0 6.243-4.426 13.883-9.865 17.023-1.574.909-3.084 1.317-4.49 1.317-.641 0-1.243-.149-1.799-.341z' fill='#607D8B'/><path d='M113.097 197.23c5.384-3.108 9.748-10.636 9.748-16.814 0-2.051-.483-3.692-1.323-4.86-1.784-1.252-4.374-1.194-7.257.47-5.384 3.108-9.748 10.636-9.748 16.814 0 2.051.483 3.692 1.323 4.86 1.784 1.252 4.374 1.194 7.257-.47' fill='#FAFAFA'/><path d='M108.724 198.614c-1.142 0-2.158-.213-3.019-.817-.021-.014-.04.014-.055-.007-.894-1.244-1.367-2.948-1.367-4.973 0-6.242 4.426-13.864 9.865-17.005 1.574-.908 3.084-1.363 4.49-1.363 1.142 0 2.158.309 3.018.913a.23.23 0 0 1 .056.056c.894 1.244 1.367 2.972 1.367 4.997 0 6.243-4.426 13.783-9.865 16.923-1.574.909-3.084 1.276-4.49 1.276zm-2.718-1.109c.774.532 1.688.776 2.718.776 1.323 0 2.754-.413 4.256-1.28 5.311-3.066 9.631-10.505 9.631-16.598 0-1.909-.434-3.523-1.255-4.685-.774-.533-1.688-.799-2.718-.799-1.323 0-2.755.441-4.256 1.308-5.311 3.066-9.631 10.506-9.631 16.599 0 1.909.434 3.517 1.255 4.679z' fill='#607D8B'/><path d='M149.318 114.262l-9.984 8.878 15.893 11.031 5.589-6.112-11.498-13.797' fill='#FAFAFA'/><path d='M169.676 120.84l-9.748 5.627c-3.642 2.103-9.528 2.113-13.147.024-3.62-2.089-3.601-5.488.041-7.591l9.495-5.608-6.729-3.885-81.836 47.071 45.923 26.514 3.081-1.779c.631-.365.869-.898.618-1.39-2.357-4.632-2.593-9.546-.683-14.262 5.638-13.92 24.509-24.815 48.618-28.07 8.169-1.103 16.68-.967 24.704.394.852.145 1.776.008 2.407-.357l3.081-1.778-25.825-14.91' fill='#FAFAFA'/><path d='M113.675 183.459a.47.47 0 0 1-.233-.062l-45.924-26.515a.468.468 0 0 1 .001-.809l81.836-47.071a.467.467 0 0 1 .466 0l6.729 3.885a.467.467 0 0 1-.467.809l-6.496-3.75-80.9 46.533 44.988 25.973 2.848-1.644c.192-.111.62-.409.435-.773-2.416-4.748-2.658-9.814-.7-14.65 2.806-6.927 8.885-13.242 17.582-18.263 8.657-4.998 19.518-8.489 31.407-10.094 8.198-1.107 16.79-.97 24.844.397.739.125 1.561.007 2.095-.301l2.381-1.374-25.125-14.506a.467.467 0 0 1 .467-.809l25.825 14.91a.467.467 0 0 1 0 .809l-3.081 1.779c-.721.417-1.763.575-2.718.413-7.963-1.351-16.457-1.486-24.563-.392-11.77 1.589-22.512 5.039-31.065 9.977-8.514 4.916-14.456 11.073-17.183 17.805-1.854 4.578-1.623 9.376.666 13.875.37.725.055 1.513-.8 2.006l-3.081 1.78a.476.476 0 0 1-.234.062' fill='#455A64'/><path d='M153.316 128.279c-2.413 0-4.821-.528-6.652-1.586-1.818-1.049-2.82-2.461-2.82-3.975 0-1.527 1.016-2.955 2.861-4.02l9.493-5.607a.233.233 0 1 1 .238.402l-9.496 5.609c-1.696.979-2.628 2.263-2.628 3.616 0 1.34.918 2.608 2.585 3.571 3.549 2.049 9.343 2.038 12.914-.024l9.748-5.628a.234.234 0 0 1 .234.405l-9.748 5.628c-1.858 1.072-4.296 1.609-6.729 1.609' fill='#607D8B'/><path d='M113.675 182.992l-45.913-26.508M113.675 183.342a.346.346 0 0 1-.175-.047l-45.913-26.508a.35.35 0 1 1 .35-.607l45.913 26.508a.35.35 0 0 1-.175.654' fill='#455A64'/><path d='M67.762 156.484v54.001c0 1.09.77 2.418 1.72 2.967l42.473 24.521c.95.549 1.72.11 1.72-.98v-54.001' fill='#FAFAFA'/><path d='M112.727 238.561c-.297 0-.62-.095-.947-.285l-42.473-24.521c-1.063-.613-1.895-2.05-1.895-3.27v-54.001a.35.35 0 1 1 .701 0v54.001c0 .96.707 2.18 1.544 2.663l42.473 24.522c.344.198.661.243.87.122.206-.119.325-.411.325-.799v-54.001a.35.35 0 1 1 .7 0v54.001c0 .655-.239 1.154-.675 1.406a1.235 1.235 0 0 1-.623.162' fill='#455A64'/><path d='M112.86 147.512h-.001c-2.318 0-4.499-.522-6.142-1.471-1.705-.984-2.643-2.315-2.643-3.749 0-1.445.952-2.791 2.68-3.788l12.041-6.953c1.668-.962 3.874-1.493 6.212-1.493 2.318 0 4.499.523 6.143 1.472 1.704.984 2.643 2.315 2.643 3.748 0 1.446-.952 2.791-2.68 3.789l-12.042 6.952c-1.668.963-3.874 1.493-6.211 1.493zm12.147-16.753c-2.217 0-4.298.497-5.861 1.399l-12.042 6.952c-1.502.868-2.33 1.998-2.33 3.182 0 1.173.815 2.289 2.293 3.142 1.538.889 3.596 1.378 5.792 1.378h.001c2.216 0 4.298-.497 5.861-1.399l12.041-6.953c1.502-.867 2.33-1.997 2.33-3.182 0-1.172-.814-2.288-2.292-3.142-1.539-.888-3.596-1.377-5.793-1.377z' fill='#607D8B'/><path d='M165.63 123.219l-5.734 3.311c-3.167 1.828-8.286 1.837-11.433.02-3.147-1.817-3.131-4.772.036-6.601l5.734-3.31 11.397 6.58' fill='#FAFAFA'/><path d='M154.233 117.448l9.995 5.771-4.682 2.704c-1.434.827-3.352 1.283-5.399 1.283-2.029 0-3.923-.449-5.333-1.263-1.29-.744-2-1.694-2-2.674 0-.991.723-1.955 2.036-2.713l5.383-3.108m0-.809l-5.734 3.31c-3.167 1.829-3.183 4.784-.036 6.601 1.568.905 3.623 1.357 5.684 1.357 2.077 0 4.159-.46 5.749-1.377l5.734-3.311-11.397-6.58M145.445 179.667c-1.773 0-3.241-.85-4.243-2.245-.067-.092-.057-.275.023-.356.08-.081.207-.12.3-.055.781.548 1.706.812 2.751.811 1.322 0 2.754-.446 4.256-1.313 5.31-3.066 9.631-10.522 9.631-16.615 0-1.927-.442-3.562-1.279-4.726a.235.235 0 0 1 .024-.301.232.232 0 0 1 .3-.027c1.67 1.172 2.59 3.38 2.59 6.219 0 6.242-4.425 13.987-9.865 17.127-1.573.908-3.083 1.481-4.488 1.481zM142.476 178c.814.651 1.82 1.002 2.969 1.002 1.322 0 2.753-.452 4.255-1.32 5.31-3.065 9.631-10.523 9.631-16.617 0-1.98-.463-3.63-1.325-4.793.411 1.035.624 2.26.624 3.62 0 6.242-4.425 13.875-9.865 17.015-1.573.909-3.084 1.376-4.489 1.376a5.49 5.49 0 0 1-1.8-.283z' fill='#607D8B'/><path d='M148.648 176.704c5.384-3.108 9.748-10.636 9.748-16.813 0-2.052-.483-3.693-1.322-4.861-1.785-1.252-4.375-1.194-7.258.471-5.383 3.108-9.748 10.636-9.748 16.813 0 2.051.484 3.692 1.323 4.86 1.785 1.253 4.374 1.195 7.257-.47' fill='#FAFAFA'/><path d='M144.276 178.276c-1.143 0-2.158-.307-3.019-.911a.217.217 0 0 1-.055-.054c-.895-1.244-1.367-2.972-1.367-4.997 0-6.241 4.425-13.875 9.865-17.016 1.573-.908 3.084-1.369 4.489-1.369 1.143 0 2.158.307 3.019.91a.24.24 0 0 1 .055.055c.894 1.244 1.367 2.971 1.367 4.997 0 6.241-4.425 13.875-9.865 17.016-1.573.908-3.084 1.369-4.489 1.369zm-2.718-1.172c.773.533 1.687.901 2.718.901 1.322 0 2.754-.538 4.256-1.405 5.31-3.066 9.631-10.567 9.631-16.661 0-1.908-.434-3.554-1.256-4.716-.774-.532-1.688-.814-2.718-.814-1.322 0-2.754.433-4.256 1.3-5.31 3.066-9.631 10.564-9.631 16.657 0 1.91.434 3.576 1.256 4.738z' fill='#607D8B'/><path d='M150.72 172.361l-.363-.295a24.105 24.105 0 0 0 2.148-3.128 24.05 24.05 0 0 0 1.977-4.375l.443.149a24.54 24.54 0 0 1-2.015 4.46 24.61 24.61 0 0 1-2.19 3.189M115.917 191.514l-.363-.294a24.174 24.174 0 0 0 2.148-3.128 24.038 24.038 0 0 0 1.976-4.375l.443.148a24.48 24.48 0 0 1-2.015 4.461 24.662 24.662 0 0 1-2.189 3.188M114 237.476V182.584 237.476' fill='#607D8B'/><g><path d='M81.822 37.474c.017-.135-.075-.28-.267-.392-.327-.188-.826-.21-1.109-.045l-6.012 3.471c-.131.076-.194.178-.191.285.002.132.002.461.002.578v.043l-.007.128-6.591 3.779c-.001 0-2.077 1.046-2.787 5.192 0 0-.912 6.961-.898 19.745.015 12.57.606 17.07 1.167 21.351.22 1.684 3.001 2.125 3.001 2.125.331.04.698-.027 1.08-.248l75.273-43.551c1.808-1.069 2.667-3.719 3.056-6.284 1.213-7.99 1.675-32.978-.275-39.878-.196-.693-.51-1.083-.868-1.282l-2.086-.79c-.727.028-1.416.467-1.534.535L82.032 37.072l-.21.402' fill='#FFF'/><path d='M144.311 1.701l2.085.79c.358.199.672.589.868 1.282 1.949 6.9 1.487 31.887.275 39.878-.39 2.565-1.249 5.215-3.056 6.284L69.21 93.486a1.78 1.78 0 0 1-.896.258l-.183-.011c0 .001-2.782-.44-3.003-2.124-.56-4.282-1.151-8.781-1.165-21.351-.015-12.784.897-19.745.897-19.745.71-4.146 2.787-5.192 2.787-5.192l6.591-3.779.007-.128v-.043c0-.117 0-.446-.002-.578-.003-.107.059-.21.191-.285l6.012-3.472a.98.98 0 0 1 .481-.11c.218 0 .449.053.627.156.193.112.285.258.268.392l.211-.402 60.744-34.836c.117-.068.806-.507 1.534-.535m0-.997l-.039.001c-.618.023-1.283.244-1.974.656l-.021.012-60.519 34.706a2.358 2.358 0 0 0-.831-.15c-.365 0-.704.084-.98.244l-6.012 3.471c-.442.255-.699.69-.689 1.166l.001.15-6.08 3.487c-.373.199-2.542 1.531-3.29 5.898l-.006.039c-.009.07-.92 7.173-.906 19.875.014 12.62.603 17.116 1.172 21.465l.002.015c.308 2.355 3.475 2.923 3.836 2.98l.034.004c.101.013.204.019.305.019a2.77 2.77 0 0 0 1.396-.392l75.273-43.552c1.811-1.071 2.999-3.423 3.542-6.997 1.186-7.814 1.734-33.096-.301-40.299-.253-.893-.704-1.527-1.343-1.882l-.132-.062-2.085-.789a.973.973 0 0 0-.353-.065' fill='#455A64'/><path d='M128.267 11.565l1.495.434-56.339 32.326' fill='#FFF'/><path d='M74.202 90.545a.5.5 0 0 1-.25-.931l18.437-10.645a.499.499 0 1 1 .499.864L74.451 90.478l-.249.067M75.764 42.654l-.108-.062.046-.171 5.135-2.964.17.045-.045.171-5.135 2.964-.063.017M70.52 90.375V46.421l.063-.036L137.84 7.554v43.954l-.062.036L70.52 90.375zm.25-43.811v43.38l66.821-38.579V7.985L70.77 46.564z' fill='#607D8B'/><path d='M86.986 83.182c-.23.149-.612.384-.849.523l-11.505 6.701c-.237.139-.206.252.068.252h.565c.275 0 .693-.113.93-.252L87.7 83.705c.237-.139.428-.253.425-.256a11.29 11.29 0 0 1-.006-.503c0-.274-.188-.377-.418-.227l-.715.463' fill='#607D8B'/><path d='M75.266 90.782H74.7c-.2 0-.316-.056-.346-.166-.03-.11.043-.217.215-.317l11.505-6.702c.236-.138.615-.371.844-.519l.715-.464a.488.488 0 0 1 .266-.089c.172 0 .345.13.345.421 0 .214.001.363.003.437l.006.004-.004.069c-.003.075-.003.075-.486.356l-11.505 6.702a2.282 2.282 0 0 1-.992.268zm-.6-.25l.034.001h.566c.252 0 .649-.108.866-.234l11.505-6.702c.168-.098.294-.173.361-.214-.004-.084-.004-.218-.004-.437l-.095-.171-.131.049-.714.463c-.232.15-.616.386-.854.525l-11.505 6.702-.029.018z' fill='#607D8B'/><path d='M75.266 89.871H74.7c-.2 0-.316-.056-.346-.166-.03-.11.043-.217.215-.317l11.505-6.702c.258-.151.694-.268.993-.268h.565c.2 0 .316.056.346.166.03.11-.043.217-.215.317l-11.505 6.702a2.282 2.282 0 0 1-.992.268zm-.6-.25l.034.001h.566c.252 0 .649-.107.866-.234l11.505-6.702.03-.018-.035-.001h-.565c-.252 0-.649.108-.867.234l-11.505 6.702-.029.018zM74.37 90.801v-1.247 1.247' fill='#607D8B'/><path d='M68.13 93.901c-.751-.093-1.314-.737-1.439-1.376-.831-4.238-1.151-8.782-1.165-21.352-.015-12.784.897-19.745.897-19.745.711-4.146 2.787-5.192 2.787-5.192l74.859-43.219c.223-.129 2.487-1.584 3.195.923 1.95 6.9 1.488 31.887.275 39.878-.389 2.565-1.248 5.215-3.056 6.283L69.21 93.653c-.382.221-.749.288-1.08.248 0 0-2.781-.441-3.001-2.125-.561-4.281-1.152-8.781-1.167-21.351-.014-12.784.898-19.745.898-19.745.71-4.146 2.787-5.191 2.787-5.191l6.598-3.81.871-.119 6.599-3.83.046-.461L68.13 93.901' fill='#FAFAFA'/><path d='M68.317 94.161l-.215-.013h-.001l-.244-.047c-.719-.156-2.772-.736-2.976-2.292-.568-4.34-1.154-8.813-1.168-21.384-.014-12.654.891-19.707.9-19.777.725-4.231 2.832-5.338 2.922-5.382l6.628-3.827.87-.119 6.446-3.742.034-.334a.248.248 0 0 1 .273-.223.248.248 0 0 1 .223.272l-.059.589-6.752 3.919-.87.118-6.556 3.785c-.031.016-1.99 1.068-2.666 5.018-.007.06-.908 7.086-.894 19.702.014 12.539.597 16.996 1.161 21.305.091.691.689 1.154 1.309 1.452a1.95 1.95 0 0 1-.236-.609c-.781-3.984-1.155-8.202-1.17-21.399-.014-12.653.891-19.707.9-19.777.725-4.231 2.832-5.337 2.922-5.382-.004.001 74.444-42.98 74.846-43.212l.028-.017c.904-.538 1.72-.688 2.36-.433.555.221.949.733 1.172 1.52 2.014 7.128 1.46 32.219.281 39.983-.507 3.341-1.575 5.515-3.175 6.462L69.335 93.869a2.023 2.023 0 0 1-1.018.292zm-.147-.507c.293.036.604-.037.915-.217l75.273-43.551c1.823-1.078 2.602-3.915 2.934-6.106 1.174-7.731 1.731-32.695-.268-39.772-.178-.631-.473-1.032-.876-1.192-.484-.193-1.166-.052-1.921.397l-.034.021-74.858 43.218c-.031.017-1.989 1.069-2.666 5.019-.007.059-.908 7.085-.894 19.702.015 13.155.386 17.351 1.161 21.303.09.461.476.983 1.037 1.139.114.025.185.037.196.039h.001z' fill='#455A64'/><path d='M69.317 68.982c.489-.281.885-.056.885.505 0 .56-.396 1.243-.885 1.525-.488.282-.884.057-.884-.504 0-.56.396-1.243.884-1.526' fill='#FFF'/><path d='M68.92 71.133c-.289 0-.487-.228-.487-.625 0-.56.396-1.243.884-1.526a.812.812 0 0 1 .397-.121c.289 0 .488.229.488.626 0 .56-.396 1.243-.885 1.525a.812.812 0 0 1-.397.121m.794-2.459a.976.976 0 0 0-.49.147c-.548.317-.978 1.058-.978 1.687 0 .486.271.812.674.812a.985.985 0 0 0 .491-.146c.548-.317.978-1.057.978-1.687 0-.486-.272-.813-.675-.813' fill='#8097A2'/><path d='M68.92 70.947c-.271 0-.299-.307-.299-.439 0-.491.361-1.116.79-1.363a.632.632 0 0 1 .303-.096c.272 0 .301.306.301.438 0 .491-.363 1.116-.791 1.364a.629.629 0 0 1-.304.096m.794-2.086a.812.812 0 0 0-.397.121c-.488.283-.884.966-.884 1.526 0 .397.198.625.487.625a.812.812 0 0 0 .397-.121c.489-.282.885-.965.885-1.525 0-.397-.199-.626-.488-.626' fill='#8097A2'/><path d='M69.444 85.35c.264-.152.477-.031.477.272 0 .303-.213.67-.477.822-.263.153-.477.031-.477-.271 0-.302.214-.671.477-.823' fill='#FFF'/><path d='M69.23 86.51c-.156 0-.263-.123-.263-.337 0-.302.214-.671.477-.823a.431.431 0 0 1 .214-.066c.156 0 .263.124.263.338 0 .303-.213.67-.477.822a.431.431 0 0 1-.214.066m.428-1.412c-.1 0-.203.029-.307.09-.32.185-.57.618-.57.985 0 .309.185.524.449.524a.63.63 0 0 0 .308-.09c.32-.185.57-.618.57-.985 0-.309-.185-.524-.45-.524' fill='#8097A2'/><path d='M69.23 86.322l-.076-.149c0-.235.179-.544.384-.661l.12-.041.076.151c0 .234-.179.542-.383.66l-.121.04m.428-1.038a.431.431 0 0 0-.214.066c-.263.152-.477.521-.477.823 0 .214.107.337.263.337a.431.431 0 0 0 .214-.066c.264-.152.477-.519.477-.822 0-.214-.107-.338-.263-.338' fill='#8097A2'/><path d='M139.278 7.769v43.667L72.208 90.16V46.493l67.07-38.724' fill='#455A64'/><path d='M72.083 90.375V46.421l.063-.036 67.257-38.831v43.954l-.062.036-67.258 38.831zm.25-43.811v43.38l66.821-38.579V7.985L72.333 46.564z' fill='#607D8B'/></g><path d='M125.737 88.647l-7.639 3.334V84l-11.459 4.713v8.269L99 100.315l13.369 3.646 13.368-15.314' fill='#455A64'/></g></svg>";
  43637. function RotateInstructions() {
  43638. this.loadIcon_();
  43639. var overlay = document.createElement('div');
  43640. var s = overlay.style;
  43641. s.position = 'fixed';
  43642. s.top = 0;
  43643. s.right = 0;
  43644. s.bottom = 0;
  43645. s.left = 0;
  43646. s.backgroundColor = 'gray';
  43647. s.fontFamily = 'sans-serif';
  43648. s.zIndex = 1000000;
  43649. var img = document.createElement('img');
  43650. img.src = this.icon;
  43651. var s = img.style;
  43652. s.marginLeft = '25%';
  43653. s.marginTop = '25%';
  43654. s.width = '50%';
  43655. overlay.appendChild(img);
  43656. var text = document.createElement('div');
  43657. var s = text.style;
  43658. s.textAlign = 'center';
  43659. s.fontSize = '16px';
  43660. s.lineHeight = '24px';
  43661. s.margin = '24px 25%';
  43662. s.width = '50%';
  43663. text.innerHTML = 'Place your phone into your Cardboard viewer.';
  43664. overlay.appendChild(text);
  43665. var snackbar = document.createElement('div');
  43666. var s = snackbar.style;
  43667. s.backgroundColor = '#CFD8DC';
  43668. s.position = 'fixed';
  43669. s.bottom = 0;
  43670. s.width = '100%';
  43671. s.height = '48px';
  43672. s.padding = '14px 24px';
  43673. s.boxSizing = 'border-box';
  43674. s.color = '#656A6B';
  43675. overlay.appendChild(snackbar);
  43676. var snackbarText = document.createElement('div');
  43677. snackbarText.style.float = 'left';
  43678. snackbarText.innerHTML = 'No Cardboard viewer?';
  43679. var snackbarButton = document.createElement('a');
  43680. snackbarButton.href = 'https://www.google.com/get/cardboard/get-cardboard/';
  43681. snackbarButton.innerHTML = 'get one';
  43682. snackbarButton.target = '_blank';
  43683. var s = snackbarButton.style;
  43684. s.float = 'right';
  43685. s.fontWeight = 600;
  43686. s.textTransform = 'uppercase';
  43687. s.borderLeft = '1px solid gray';
  43688. s.paddingLeft = '24px';
  43689. s.textDecoration = 'none';
  43690. s.color = '#656A6B';
  43691. snackbar.appendChild(snackbarText);
  43692. snackbar.appendChild(snackbarButton);
  43693. this.overlay = overlay;
  43694. this.text = text;
  43695. this.hide();
  43696. }
  43697. RotateInstructions.prototype.show = function (parent) {
  43698. if (!parent && !this.overlay.parentElement) {
  43699. document.body.appendChild(this.overlay);
  43700. } else if (parent) {
  43701. if (this.overlay.parentElement && this.overlay.parentElement != parent) this.overlay.parentElement.removeChild(this.overlay);
  43702. parent.appendChild(this.overlay);
  43703. }
  43704. this.overlay.style.display = 'block';
  43705. var img = this.overlay.querySelector('img');
  43706. var s = img.style;
  43707. if (isLandscapeMode()) {
  43708. s.width = '20%';
  43709. s.marginLeft = '40%';
  43710. s.marginTop = '3%';
  43711. } else {
  43712. s.width = '50%';
  43713. s.marginLeft = '25%';
  43714. s.marginTop = '25%';
  43715. }
  43716. };
  43717. RotateInstructions.prototype.hide = function () {
  43718. this.overlay.style.display = 'none';
  43719. };
  43720. RotateInstructions.prototype.showTemporarily = function (ms, parent) {
  43721. this.show(parent);
  43722. this.timer = setTimeout(this.hide.bind(this), ms);
  43723. };
  43724. RotateInstructions.prototype.disableShowTemporarily = function () {
  43725. clearTimeout(this.timer);
  43726. };
  43727. RotateInstructions.prototype.update = function () {
  43728. this.disableShowTemporarily();
  43729. if (!isLandscapeMode() && isMobile()) {
  43730. this.show();
  43731. } else {
  43732. this.hide();
  43733. }
  43734. };
  43735. RotateInstructions.prototype.loadIcon_ = function () {
  43736. this.icon = dataUri('image/svg+xml', rotateInstructionsAsset);
  43737. };
  43738. var DEFAULT_VIEWER = 'CardboardV1';
  43739. var VIEWER_KEY = 'WEBVR_CARDBOARD_VIEWER';
  43740. var CLASS_NAME = 'webvr-polyfill-viewer-selector';
  43741. function ViewerSelector(defaultViewer) {
  43742. try {
  43743. this.selectedKey = localStorage.getItem(VIEWER_KEY);
  43744. } catch (error) {
  43745. console.error('Failed to load viewer profile: %s', error);
  43746. }
  43747. if (!this.selectedKey) {
  43748. this.selectedKey = defaultViewer || DEFAULT_VIEWER;
  43749. }
  43750. this.dialog = this.createDialog_(DeviceInfo.Viewers);
  43751. this.root = null;
  43752. this.onChangeCallbacks_ = [];
  43753. }
  43754. ViewerSelector.prototype.show = function (root) {
  43755. this.root = root;
  43756. root.appendChild(this.dialog);
  43757. var selected = this.dialog.querySelector('#' + this.selectedKey);
  43758. selected.checked = true;
  43759. this.dialog.style.display = 'block';
  43760. };
  43761. ViewerSelector.prototype.hide = function () {
  43762. if (this.root && this.root.contains(this.dialog)) {
  43763. this.root.removeChild(this.dialog);
  43764. }
  43765. this.dialog.style.display = 'none';
  43766. };
  43767. ViewerSelector.prototype.getCurrentViewer = function () {
  43768. return DeviceInfo.Viewers[this.selectedKey];
  43769. };
  43770. ViewerSelector.prototype.getSelectedKey_ = function () {
  43771. var input = this.dialog.querySelector('input[name=field]:checked');
  43772. if (input) {
  43773. return input.id;
  43774. }
  43775. return null;
  43776. };
  43777. ViewerSelector.prototype.onChange = function (cb) {
  43778. this.onChangeCallbacks_.push(cb);
  43779. };
  43780. ViewerSelector.prototype.fireOnChange_ = function (viewer) {
  43781. for (var i = 0; i < this.onChangeCallbacks_.length; i++) {
  43782. this.onChangeCallbacks_[i](viewer);
  43783. }
  43784. };
  43785. ViewerSelector.prototype.onSave_ = function () {
  43786. this.selectedKey = this.getSelectedKey_();
  43787. if (!this.selectedKey || !DeviceInfo.Viewers[this.selectedKey]) {
  43788. console.error('ViewerSelector.onSave_: this should never happen!');
  43789. return;
  43790. }
  43791. this.fireOnChange_(DeviceInfo.Viewers[this.selectedKey]);
  43792. try {
  43793. localStorage.setItem(VIEWER_KEY, this.selectedKey);
  43794. } catch (error) {
  43795. console.error('Failed to save viewer profile: %s', error);
  43796. }
  43797. this.hide();
  43798. };
  43799. ViewerSelector.prototype.createDialog_ = function (options) {
  43800. var container = document.createElement('div');
  43801. container.classList.add(CLASS_NAME);
  43802. container.style.display = 'none';
  43803. var overlay = document.createElement('div');
  43804. var s = overlay.style;
  43805. s.position = 'fixed';
  43806. s.left = 0;
  43807. s.top = 0;
  43808. s.width = '100%';
  43809. s.height = '100%';
  43810. s.background = 'rgba(0, 0, 0, 0.3)';
  43811. overlay.addEventListener('click', this.hide.bind(this));
  43812. var width = 280;
  43813. var dialog = document.createElement('div');
  43814. var s = dialog.style;
  43815. s.boxSizing = 'border-box';
  43816. s.position = 'fixed';
  43817. s.top = '24px';
  43818. s.left = '50%';
  43819. s.marginLeft = -width / 2 + 'px';
  43820. s.width = width + 'px';
  43821. s.padding = '24px';
  43822. s.overflow = 'hidden';
  43823. s.background = '#fafafa';
  43824. s.fontFamily = "'Roboto', sans-serif";
  43825. s.boxShadow = '0px 5px 20px #666';
  43826. dialog.appendChild(this.createH1_('Select your viewer'));
  43827. for (var id in options) {
  43828. dialog.appendChild(this.createChoice_(id, options[id].label));
  43829. }
  43830. dialog.appendChild(this.createButton_('Save', this.onSave_.bind(this)));
  43831. container.appendChild(overlay);
  43832. container.appendChild(dialog);
  43833. return container;
  43834. };
  43835. ViewerSelector.prototype.createH1_ = function (name) {
  43836. var h1 = document.createElement('h1');
  43837. var s = h1.style;
  43838. s.color = 'black';
  43839. s.fontSize = '20px';
  43840. s.fontWeight = 'bold';
  43841. s.marginTop = 0;
  43842. s.marginBottom = '24px';
  43843. h1.innerHTML = name;
  43844. return h1;
  43845. };
  43846. ViewerSelector.prototype.createChoice_ = function (id, name) {
  43847. var div = document.createElement('div');
  43848. div.style.marginTop = '8px';
  43849. div.style.color = 'black';
  43850. var input = document.createElement('input');
  43851. input.style.fontSize = '30px';
  43852. input.setAttribute('id', id);
  43853. input.setAttribute('type', 'radio');
  43854. input.setAttribute('value', id);
  43855. input.setAttribute('name', 'field');
  43856. var label = document.createElement('label');
  43857. label.style.marginLeft = '4px';
  43858. label.setAttribute('for', id);
  43859. label.innerHTML = name;
  43860. div.appendChild(input);
  43861. div.appendChild(label);
  43862. return div;
  43863. };
  43864. ViewerSelector.prototype.createButton_ = function (label, onclick) {
  43865. var button = document.createElement('button');
  43866. button.innerHTML = label;
  43867. var s = button.style;
  43868. s.float = 'right';
  43869. s.textTransform = 'uppercase';
  43870. s.color = '#1094f7';
  43871. s.fontSize = '14px';
  43872. s.letterSpacing = 0;
  43873. s.border = 0;
  43874. s.background = 'none';
  43875. s.marginTop = '16px';
  43876. button.addEventListener('click', onclick);
  43877. return button;
  43878. };
  43879. var commonjsGlobal$$1 = typeof window !== 'undefined' ? window : typeof commonjsGlobal !== 'undefined' ? commonjsGlobal : typeof self !== 'undefined' ? self : {};
  43880. function unwrapExports$$1 (x) {
  43881. return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
  43882. }
  43883. function createCommonjsModule$$1(fn, module) {
  43884. return module = { exports: {} }, fn(module, module.exports), module.exports;
  43885. }
  43886. var NoSleep = createCommonjsModule$$1(function (module, exports) {
  43887. (function webpackUniversalModuleDefinition(root, factory) {
  43888. module.exports = factory();
  43889. })(commonjsGlobal$$1, function() {
  43890. return (function(modules) {
  43891. var installedModules = {};
  43892. function __webpack_require__(moduleId) {
  43893. if(installedModules[moduleId]) {
  43894. return installedModules[moduleId].exports;
  43895. }
  43896. var module = installedModules[moduleId] = {
  43897. i: moduleId,
  43898. l: false,
  43899. exports: {}
  43900. };
  43901. modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
  43902. module.l = true;
  43903. return module.exports;
  43904. }
  43905. __webpack_require__.m = modules;
  43906. __webpack_require__.c = installedModules;
  43907. __webpack_require__.d = function(exports, name, getter) {
  43908. if(!__webpack_require__.o(exports, name)) {
  43909. Object.defineProperty(exports, name, {
  43910. configurable: false,
  43911. enumerable: true,
  43912. get: getter
  43913. });
  43914. }
  43915. };
  43916. __webpack_require__.n = function(module) {
  43917. var getter = module && module.__esModule ?
  43918. function getDefault() { return module['default']; } :
  43919. function getModuleExports() { return module; };
  43920. __webpack_require__.d(getter, 'a', getter);
  43921. return getter;
  43922. };
  43923. __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
  43924. __webpack_require__.p = "";
  43925. return __webpack_require__(__webpack_require__.s = 0);
  43926. })
  43927. ([
  43928. (function(module, exports, __webpack_require__) {
  43929. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  43930. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  43931. var mediaFile = __webpack_require__(1);
  43932. var oldIOS = typeof navigator !== 'undefined' && parseFloat(('' + (/CPU.*OS ([0-9_]{3,4})[0-9_]{0,1}|(CPU like).*AppleWebKit.*Mobile/i.exec(navigator.userAgent) || [0, ''])[1]).replace('undefined', '3_2').replace('_', '.').replace('_', '')) < 10 && !window.MSStream;
  43933. var NoSleep = function () {
  43934. function NoSleep() {
  43935. _classCallCheck(this, NoSleep);
  43936. if (oldIOS) {
  43937. this.noSleepTimer = null;
  43938. } else {
  43939. this.noSleepVideo = document.createElement('video');
  43940. this.noSleepVideo.setAttribute('playsinline', '');
  43941. this.noSleepVideo.setAttribute('src', mediaFile);
  43942. this.noSleepVideo.addEventListener('timeupdate', function (e) {
  43943. if (this.noSleepVideo.currentTime > 0.5) {
  43944. this.noSleepVideo.currentTime = Math.random();
  43945. }
  43946. }.bind(this));
  43947. }
  43948. }
  43949. _createClass(NoSleep, [{
  43950. key: 'enable',
  43951. value: function enable() {
  43952. if (oldIOS) {
  43953. this.disable();
  43954. this.noSleepTimer = window.setInterval(function () {
  43955. window.location.href = '/';
  43956. window.setTimeout(window.stop, 0);
  43957. }, 15000);
  43958. } else {
  43959. this.noSleepVideo.play();
  43960. }
  43961. }
  43962. }, {
  43963. key: 'disable',
  43964. value: function disable() {
  43965. if (oldIOS) {
  43966. if (this.noSleepTimer) {
  43967. window.clearInterval(this.noSleepTimer);
  43968. this.noSleepTimer = null;
  43969. }
  43970. } else {
  43971. this.noSleepVideo.pause();
  43972. }
  43973. }
  43974. }]);
  43975. return NoSleep;
  43976. }();
  43977. module.exports = NoSleep;
  43978. }),
  43979. (function(module, exports, __webpack_require__) {
  43980. module.exports = 'data:video/mp4;base64,AAAAIGZ0eXBtcDQyAAACAGlzb21pc28yYXZjMW1wNDEAAAAIZnJlZQAACKBtZGF0AAAC8wYF///v3EXpvebZSLeWLNgg2SPu73gyNjQgLSBjb3JlIDE0MiByMjQ3OSBkZDc5YTYxIC0gSC4yNjQvTVBFRy00IEFWQyBjb2RlYyAtIENvcHlsZWZ0IDIwMDMtMjAxNCAtIGh0dHA6Ly93d3cudmlkZW9sYW4ub3JnL3gyNjQuaHRtbCAtIG9wdGlvbnM6IGNhYmFjPTEgcmVmPTEgZGVibG9jaz0xOjA6MCBhbmFseXNlPTB4MToweDExMSBtZT1oZXggc3VibWU9MiBwc3k9MSBwc3lfcmQ9MS4wMDowLjAwIG1peGVkX3JlZj0wIG1lX3JhbmdlPTE2IGNocm9tYV9tZT0xIHRyZWxsaXM9MCA4eDhkY3Q9MCBjcW09MCBkZWFkem9uZT0yMSwxMSBmYXN0X3Bza2lwPTEgY2hyb21hX3FwX29mZnNldD0wIHRocmVhZHM9NiBsb29rYWhlYWRfdGhyZWFkcz0xIHNsaWNlZF90aHJlYWRzPTAgbnI9MCBkZWNpbWF0ZT0xIGludGVybGFjZWQ9MCBibHVyYXlfY29tcGF0PTAgY29uc3RyYWluZWRfaW50cmE9MCBiZnJhbWVzPTMgYl9weXJhbWlkPTIgYl9hZGFwdD0xIGJfYmlhcz0wIGRpcmVjdD0xIHdlaWdodGI9MSBvcGVuX2dvcD0wIHdlaWdodHA9MSBrZXlpbnQ9MzAwIGtleWludF9taW49MzAgc2NlbmVjdXQ9NDAgaW50cmFfcmVmcmVzaD0wIHJjX2xvb2thaGVhZD0xMCByYz1jcmYgbWJ0cmVlPTEgY3JmPTIwLjAgcWNvbXA9MC42MCBxcG1pbj0wIHFwbWF4PTY5IHFwc3RlcD00IHZidl9tYXhyYXRlPTIwMDAwIHZidl9idWZzaXplPTI1MDAwIGNyZl9tYXg9MC4wIG5hbF9ocmQ9bm9uZSBmaWxsZXI9MCBpcF9yYXRpbz0xLjQwIGFxPTE6MS4wMACAAAAAOWWIhAA3//p+C7v8tDDSTjf97w55i3SbRPO4ZY+hkjD5hbkAkL3zpJ6h/LR1CAABzgB1kqqzUorlhQAAAAxBmiQYhn/+qZYADLgAAAAJQZ5CQhX/AAj5IQADQGgcIQADQGgcAAAACQGeYUQn/wALKCEAA0BoHAAAAAkBnmNEJ/8ACykhAANAaBwhAANAaBwAAAANQZpoNExDP/6plgAMuSEAA0BoHAAAAAtBnoZFESwr/wAI+SEAA0BoHCEAA0BoHAAAAAkBnqVEJ/8ACykhAANAaBwAAAAJAZ6nRCf/AAsoIQADQGgcIQADQGgcAAAADUGarDRMQz/+qZYADLghAANAaBwAAAALQZ7KRRUsK/8ACPkhAANAaBwAAAAJAZ7pRCf/AAsoIQADQGgcIQADQGgcAAAACQGe60Qn/wALKCEAA0BoHAAAAA1BmvA0TEM//qmWAAy5IQADQGgcIQADQGgcAAAAC0GfDkUVLCv/AAj5IQADQGgcAAAACQGfLUQn/wALKSEAA0BoHCEAA0BoHAAAAAkBny9EJ/8ACyghAANAaBwAAAANQZs0NExDP/6plgAMuCEAA0BoHAAAAAtBn1JFFSwr/wAI+SEAA0BoHCEAA0BoHAAAAAkBn3FEJ/8ACyghAANAaBwAAAAJAZ9zRCf/AAsoIQADQGgcIQADQGgcAAAADUGbeDRMQz/+qZYADLkhAANAaBwAAAALQZ+WRRUsK/8ACPghAANAaBwhAANAaBwAAAAJAZ+1RCf/AAspIQADQGgcAAAACQGft0Qn/wALKSEAA0BoHCEAA0BoHAAAAA1Bm7w0TEM//qmWAAy4IQADQGgcAAAAC0Gf2kUVLCv/AAj5IQADQGgcAAAACQGf+UQn/wALKCEAA0BoHCEAA0BoHAAAAAkBn/tEJ/8ACykhAANAaBwAAAANQZvgNExDP/6plgAMuSEAA0BoHCEAA0BoHAAAAAtBnh5FFSwr/wAI+CEAA0BoHAAAAAkBnj1EJ/8ACyghAANAaBwhAANAaBwAAAAJAZ4/RCf/AAspIQADQGgcAAAADUGaJDRMQz/+qZYADLghAANAaBwAAAALQZ5CRRUsK/8ACPkhAANAaBwhAANAaBwAAAAJAZ5hRCf/AAsoIQADQGgcAAAACQGeY0Qn/wALKSEAA0BoHCEAA0BoHAAAAA1Bmmg0TEM//qmWAAy5IQADQGgcAAAAC0GehkUVLCv/AAj5IQADQGgcIQADQGgcAAAACQGepUQn/wALKSEAA0BoHAAAAAkBnqdEJ/8ACyghAANAaBwAAAANQZqsNExDP/6plgAMuCEAA0BoHCEAA0BoHAAAAAtBnspFFSwr/wAI+SEAA0BoHAAAAAkBnulEJ/8ACyghAANAaBwhAANAaBwAAAAJAZ7rRCf/AAsoIQADQGgcAAAADUGa8DRMQz/+qZYADLkhAANAaBwhAANAaBwAAAALQZ8ORRUsK/8ACPkhAANAaBwAAAAJAZ8tRCf/AAspIQADQGgcIQADQGgcAAAACQGfL0Qn/wALKCEAA0BoHAAAAA1BmzQ0TEM//qmWAAy4IQADQGgcAAAAC0GfUkUVLCv/AAj5IQADQGgcIQADQGgcAAAACQGfcUQn/wALKCEAA0BoHAAAAAkBn3NEJ/8ACyghAANAaBwhAANAaBwAAAANQZt4NExC//6plgAMuSEAA0BoHAAAAAtBn5ZFFSwr/wAI+CEAA0BoHCEAA0BoHAAAAAkBn7VEJ/8ACykhAANAaBwAAAAJAZ+3RCf/AAspIQADQGgcAAAADUGbuzRMQn/+nhAAYsAhAANAaBwhAANAaBwAAAAJQZ/aQhP/AAspIQADQGgcAAAACQGf+UQn/wALKCEAA0BoHCEAA0BoHCEAA0BoHCEAA0BoHCEAA0BoHCEAA0BoHAAACiFtb292AAAAbG12aGQAAAAA1YCCX9WAgl8AAAPoAAAH/AABAAABAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADAAAAGGlvZHMAAAAAEICAgAcAT////v7/AAAF+XRyYWsAAABcdGtoZAAAAAPVgIJf1YCCXwAAAAEAAAAAAAAH0AAAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAEAAAAAAygAAAMoAAAAAACRlZHRzAAAAHGVsc3QAAAAAAAAAAQAAB9AAABdwAAEAAAAABXFtZGlhAAAAIG1kaGQAAAAA1YCCX9WAgl8AAV+QAAK/IFXEAAAAAAAtaGRscgAAAAAAAAAAdmlkZQAAAAAAAAAAAAAAAFZpZGVvSGFuZGxlcgAAAAUcbWluZgAAABR2bWhkAAAAAQAAAAAAAAAAAAAAJGRpbmYAAAAcZHJlZgAAAAAAAAABAAAADHVybCAAAAABAAAE3HN0YmwAAACYc3RzZAAAAAAAAAABAAAAiGF2YzEAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAygDKAEgAAABIAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAY//8AAAAyYXZjQwFNQCj/4QAbZ01AKOyho3ySTUBAQFAAAAMAEAAr8gDxgxlgAQAEaO+G8gAAABhzdHRzAAAAAAAAAAEAAAA8AAALuAAAABRzdHNzAAAAAAAAAAEAAAABAAAB8GN0dHMAAAAAAAAAPAAAAAEAABdwAAAAAQAAOpgAAAABAAAXcAAAAAEAAAAAAAAAAQAAC7gAAAABAAA6mAAAAAEAABdwAAAAAQAAAAAAAAABAAALuAAAAAEAADqYAAAAAQAAF3AAAAABAAAAAAAAAAEAAAu4AAAAAQAAOpgAAAABAAAXcAAAAAEAAAAAAAAAAQAAC7gAAAABAAA6mAAAAAEAABdwAAAAAQAAAAAAAAABAAALuAAAAAEAADqYAAAAAQAAF3AAAAABAAAAAAAAAAEAAAu4AAAAAQAAOpgAAAABAAAXcAAAAAEAAAAAAAAAAQAAC7gAAAABAAA6mAAAAAEAABdwAAAAAQAAAAAAAAABAAALuAAAAAEAADqYAAAAAQAAF3AAAAABAAAAAAAAAAEAAAu4AAAAAQAAOpgAAAABAAAXcAAAAAEAAAAAAAAAAQAAC7gAAAABAAA6mAAAAAEAABdwAAAAAQAAAAAAAAABAAALuAAAAAEAADqYAAAAAQAAF3AAAAABAAAAAAAAAAEAAAu4AAAAAQAAOpgAAAABAAAXcAAAAAEAAAAAAAAAAQAAC7gAAAABAAA6mAAAAAEAABdwAAAAAQAAAAAAAAABAAALuAAAAAEAAC7gAAAAAQAAF3AAAAABAAAAAAAAABxzdHNjAAAAAAAAAAEAAAABAAAAAQAAAAEAAAEEc3RzegAAAAAAAAAAAAAAPAAAAzQAAAAQAAAADQAAAA0AAAANAAAAEQAAAA8AAAANAAAADQAAABEAAAAPAAAADQAAAA0AAAARAAAADwAAAA0AAAANAAAAEQAAAA8AAAANAAAADQAAABEAAAAPAAAADQAAAA0AAAARAAAADwAAAA0AAAANAAAAEQAAAA8AAAANAAAADQAAABEAAAAPAAAADQAAAA0AAAARAAAADwAAAA0AAAANAAAAEQAAAA8AAAANAAAADQAAABEAAAAPAAAADQAAAA0AAAARAAAADwAAAA0AAAANAAAAEQAAAA8AAAANAAAADQAAABEAAAANAAAADQAAAQBzdGNvAAAAAAAAADwAAAAwAAADZAAAA3QAAAONAAADoAAAA7kAAAPQAAAD6wAAA/4AAAQXAAAELgAABEMAAARcAAAEbwAABIwAAAShAAAEugAABM0AAATkAAAE/wAABRIAAAUrAAAFQgAABV0AAAVwAAAFiQAABaAAAAW1AAAFzgAABeEAAAX+AAAGEwAABiwAAAY/AAAGVgAABnEAAAaEAAAGnQAABrQAAAbPAAAG4gAABvUAAAcSAAAHJwAAB0AAAAdTAAAHcAAAB4UAAAeeAAAHsQAAB8gAAAfjAAAH9gAACA8AAAgmAAAIQQAACFQAAAhnAAAIhAAACJcAAAMsdHJhawAAAFx0a2hkAAAAA9WAgl/VgIJfAAAAAgAAAAAAAAf8AAAAAAAAAAAAAAABAQAAAAABAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAACsm1kaWEAAAAgbWRoZAAAAADVgIJf1YCCXwAArEQAAWAAVcQAAAAAACdoZGxyAAAAAAAAAABzb3VuAAAAAAAAAAAAAAAAU3RlcmVvAAAAAmNtaW5mAAAAEHNtaGQAAAAAAAAAAAAAACRkaW5mAAAAHGRyZWYAAAAAAAAAAQAAAAx1cmwgAAAAAQAAAidzdGJsAAAAZ3N0c2QAAAAAAAAAAQAAAFdtcDRhAAAAAAAAAAEAAAAAAAAAAAACABAAAAAArEQAAAAAADNlc2RzAAAAAAOAgIAiAAIABICAgBRAFQAAAAADDUAAAAAABYCAgAISEAaAgIABAgAAABhzdHRzAAAAAAAAAAEAAABYAAAEAAAAABxzdHNjAAAAAAAAAAEAAAABAAAAAQAAAAEAAAAUc3RzegAAAAAAAAAGAAAAWAAAAXBzdGNvAAAAAAAAAFgAAAOBAAADhwAAA5oAAAOtAAADswAAA8oAAAPfAAAD5QAAA/gAAAQLAAAEEQAABCgAAAQ9AAAEUAAABFYAAARpAAAEgAAABIYAAASbAAAErgAABLQAAATHAAAE3gAABPMAAAT5AAAFDAAABR8AAAUlAAAFPAAABVEAAAVXAAAFagAABX0AAAWDAAAFmgAABa8AAAXCAAAFyAAABdsAAAXyAAAF+AAABg0AAAYgAAAGJgAABjkAAAZQAAAGZQAABmsAAAZ+AAAGkQAABpcAAAauAAAGwwAABskAAAbcAAAG7wAABwYAAAcMAAAHIQAABzQAAAc6AAAHTQAAB2QAAAdqAAAHfwAAB5IAAAeYAAAHqwAAB8IAAAfXAAAH3QAAB/AAAAgDAAAICQAACCAAAAg1AAAIOwAACE4AAAhhAAAIeAAACH4AAAiRAAAIpAAACKoAAAiwAAAItgAACLwAAAjCAAAAFnVkdGEAAAAObmFtZVN0ZXJlbwAAAHB1ZHRhAAAAaG1ldGEAAAAAAAAAIWhkbHIAAAAAAAAAAG1kaXJhcHBsAAAAAAAAAAAAAAAAO2lsc3QAAAAzqXRvbwAAACtkYXRhAAAAAQAAAABIYW5kQnJha2UgMC4xMC4yIDIwMTUwNjExMDA=';
  43981. })
  43982. ]);
  43983. });
  43984. });
  43985. var NoSleep$1 = unwrapExports$$1(NoSleep);
  43986. var nextDisplayId = 1000;
  43987. var defaultLeftBounds = [0, 0, 0.5, 1];
  43988. var defaultRightBounds = [0.5, 0, 0.5, 1];
  43989. var raf = window.requestAnimationFrame;
  43990. var caf = window.cancelAnimationFrame;
  43991. function VRFrameData() {
  43992. this.leftProjectionMatrix = new Float32Array(16);
  43993. this.leftViewMatrix = new Float32Array(16);
  43994. this.rightProjectionMatrix = new Float32Array(16);
  43995. this.rightViewMatrix = new Float32Array(16);
  43996. this.pose = null;
  43997. }
  43998. function VRDisplayCapabilities(config) {
  43999. Object.defineProperties(this, {
  44000. hasPosition: {
  44001. writable: false, enumerable: true, value: config.hasPosition
  44002. },
  44003. hasExternalDisplay: {
  44004. writable: false, enumerable: true, value: config.hasExternalDisplay
  44005. },
  44006. canPresent: {
  44007. writable: false, enumerable: true, value: config.canPresent
  44008. },
  44009. maxLayers: {
  44010. writable: false, enumerable: true, value: config.maxLayers
  44011. },
  44012. hasOrientation: {
  44013. enumerable: true, get: function get() {
  44014. deprecateWarning('VRDisplayCapabilities.prototype.hasOrientation', 'VRDisplay.prototype.getFrameData');
  44015. return config.hasOrientation;
  44016. }
  44017. }
  44018. });
  44019. }
  44020. function VRDisplay(config) {
  44021. config = config || {};
  44022. var USE_WAKELOCK = 'wakelock' in config ? config.wakelock : true;
  44023. this.isPolyfilled = true;
  44024. this.displayId = nextDisplayId++;
  44025. this.displayName = '';
  44026. this.depthNear = 0.01;
  44027. this.depthFar = 10000.0;
  44028. this.isPresenting = false;
  44029. Object.defineProperty(this, 'isConnected', {
  44030. get: function get() {
  44031. deprecateWarning('VRDisplay.prototype.isConnected', 'VRDisplayCapabilities.prototype.hasExternalDisplay');
  44032. return false;
  44033. }
  44034. });
  44035. this.capabilities = new VRDisplayCapabilities({
  44036. hasPosition: false,
  44037. hasOrientation: false,
  44038. hasExternalDisplay: false,
  44039. canPresent: false,
  44040. maxLayers: 1
  44041. });
  44042. this.stageParameters = null;
  44043. this.waitingForPresent_ = false;
  44044. this.layer_ = null;
  44045. this.originalParent_ = null;
  44046. this.fullscreenElement_ = null;
  44047. this.fullscreenWrapper_ = null;
  44048. this.fullscreenElementCachedStyle_ = null;
  44049. this.fullscreenEventTarget_ = null;
  44050. this.fullscreenChangeHandler_ = null;
  44051. this.fullscreenErrorHandler_ = null;
  44052. if (USE_WAKELOCK && isMobile()) {
  44053. this.wakelock_ = new NoSleep$1();
  44054. }
  44055. }
  44056. VRDisplay.prototype.getFrameData = function (frameData) {
  44057. return frameDataFromPose(frameData, this._getPose(), this);
  44058. };
  44059. VRDisplay.prototype.getPose = function () {
  44060. deprecateWarning('VRDisplay.prototype.getPose', 'VRDisplay.prototype.getFrameData');
  44061. return this._getPose();
  44062. };
  44063. VRDisplay.prototype.resetPose = function () {
  44064. deprecateWarning('VRDisplay.prototype.resetPose');
  44065. return this._resetPose();
  44066. };
  44067. VRDisplay.prototype.getImmediatePose = function () {
  44068. deprecateWarning('VRDisplay.prototype.getImmediatePose', 'VRDisplay.prototype.getFrameData');
  44069. return this._getPose();
  44070. };
  44071. VRDisplay.prototype.requestAnimationFrame = function (callback) {
  44072. return raf(callback);
  44073. };
  44074. VRDisplay.prototype.cancelAnimationFrame = function (id) {
  44075. return caf(id);
  44076. };
  44077. VRDisplay.prototype.wrapForFullscreen = function (element) {
  44078. if (isIOS()) {
  44079. return element;
  44080. }
  44081. if (!this.fullscreenWrapper_) {
  44082. this.fullscreenWrapper_ = document.createElement('div');
  44083. var cssProperties = ['height: ' + Math.min(screen.height, screen.width) + 'px !important', 'top: 0 !important', 'left: 0 !important', 'right: 0 !important', 'border: 0', 'margin: 0', 'padding: 0', 'z-index: 999999 !important', 'position: fixed'];
  44084. this.fullscreenWrapper_.setAttribute('style', cssProperties.join('; ') + ';');
  44085. this.fullscreenWrapper_.classList.add('webvr-polyfill-fullscreen-wrapper');
  44086. }
  44087. if (this.fullscreenElement_ == element) {
  44088. return this.fullscreenWrapper_;
  44089. }
  44090. if (this.fullscreenElement_) {
  44091. if (this.originalParent_) {
  44092. this.originalParent_.appendChild(this.fullscreenElement_);
  44093. } else {
  44094. this.fullscreenElement_.parentElement.removeChild(this.fullscreenElement_);
  44095. }
  44096. }
  44097. this.fullscreenElement_ = element;
  44098. this.originalParent_ = element.parentElement;
  44099. if (!this.originalParent_) {
  44100. document.body.appendChild(element);
  44101. }
  44102. if (!this.fullscreenWrapper_.parentElement) {
  44103. var parent = this.fullscreenElement_.parentElement;
  44104. parent.insertBefore(this.fullscreenWrapper_, this.fullscreenElement_);
  44105. parent.removeChild(this.fullscreenElement_);
  44106. }
  44107. this.fullscreenWrapper_.insertBefore(this.fullscreenElement_, this.fullscreenWrapper_.firstChild);
  44108. this.fullscreenElementCachedStyle_ = this.fullscreenElement_.getAttribute('style');
  44109. var self = this;
  44110. function applyFullscreenElementStyle() {
  44111. if (!self.fullscreenElement_) {
  44112. return;
  44113. }
  44114. var cssProperties = ['position: absolute', 'top: 0', 'left: 0', 'width: ' + Math.max(screen.width, screen.height) + 'px', 'height: ' + Math.min(screen.height, screen.width) + 'px', 'border: 0', 'margin: 0', 'padding: 0'];
  44115. self.fullscreenElement_.setAttribute('style', cssProperties.join('; ') + ';');
  44116. }
  44117. applyFullscreenElementStyle();
  44118. return this.fullscreenWrapper_;
  44119. };
  44120. VRDisplay.prototype.removeFullscreenWrapper = function () {
  44121. if (!this.fullscreenElement_) {
  44122. return;
  44123. }
  44124. var element = this.fullscreenElement_;
  44125. if (this.fullscreenElementCachedStyle_) {
  44126. element.setAttribute('style', this.fullscreenElementCachedStyle_);
  44127. } else {
  44128. element.removeAttribute('style');
  44129. }
  44130. this.fullscreenElement_ = null;
  44131. this.fullscreenElementCachedStyle_ = null;
  44132. var parent = this.fullscreenWrapper_.parentElement;
  44133. this.fullscreenWrapper_.removeChild(element);
  44134. if (this.originalParent_ === parent) {
  44135. parent.insertBefore(element, this.fullscreenWrapper_);
  44136. }
  44137. else if (this.originalParent_) {
  44138. this.originalParent_.appendChild(element);
  44139. }
  44140. parent.removeChild(this.fullscreenWrapper_);
  44141. return element;
  44142. };
  44143. VRDisplay.prototype.requestPresent = function (layers) {
  44144. var wasPresenting = this.isPresenting;
  44145. var self = this;
  44146. if (!(layers instanceof Array)) {
  44147. deprecateWarning('VRDisplay.prototype.requestPresent with non-array argument', 'an array of VRLayers as the first argument');
  44148. layers = [layers];
  44149. }
  44150. return new Promise(function (resolve, reject) {
  44151. if (!self.capabilities.canPresent) {
  44152. reject(new Error('VRDisplay is not capable of presenting.'));
  44153. return;
  44154. }
  44155. if (layers.length == 0 || layers.length > self.capabilities.maxLayers) {
  44156. reject(new Error('Invalid number of layers.'));
  44157. return;
  44158. }
  44159. var incomingLayer = layers[0];
  44160. if (!incomingLayer.source) {
  44161. resolve();
  44162. return;
  44163. }
  44164. var leftBounds = incomingLayer.leftBounds || defaultLeftBounds;
  44165. var rightBounds = incomingLayer.rightBounds || defaultRightBounds;
  44166. if (wasPresenting) {
  44167. var layer = self.layer_;
  44168. if (layer.source !== incomingLayer.source) {
  44169. layer.source = incomingLayer.source;
  44170. }
  44171. for (var i = 0; i < 4; i++) {
  44172. layer.leftBounds[i] = leftBounds[i];
  44173. layer.rightBounds[i] = rightBounds[i];
  44174. }
  44175. self.wrapForFullscreen(self.layer_.source);
  44176. self.updatePresent_();
  44177. resolve();
  44178. return;
  44179. }
  44180. self.layer_ = {
  44181. predistorted: incomingLayer.predistorted,
  44182. source: incomingLayer.source,
  44183. leftBounds: leftBounds.slice(0),
  44184. rightBounds: rightBounds.slice(0)
  44185. };
  44186. self.waitingForPresent_ = false;
  44187. if (self.layer_ && self.layer_.source) {
  44188. var fullscreenElement = self.wrapForFullscreen(self.layer_.source);
  44189. var onFullscreenChange = function onFullscreenChange() {
  44190. var actualFullscreenElement = getFullscreenElement();
  44191. self.isPresenting = fullscreenElement === actualFullscreenElement;
  44192. if (self.isPresenting) {
  44193. if (screen.orientation && screen.orientation.lock) {
  44194. screen.orientation.lock('landscape-primary').catch(function (error) {
  44195. console.error('screen.orientation.lock() failed due to', error.message);
  44196. });
  44197. }
  44198. self.waitingForPresent_ = false;
  44199. self.beginPresent_();
  44200. resolve();
  44201. } else {
  44202. if (screen.orientation && screen.orientation.unlock) {
  44203. screen.orientation.unlock();
  44204. }
  44205. self.removeFullscreenWrapper();
  44206. self.disableWakeLock();
  44207. self.endPresent_();
  44208. self.removeFullscreenListeners_();
  44209. }
  44210. self.fireVRDisplayPresentChange_();
  44211. };
  44212. var onFullscreenError = function onFullscreenError() {
  44213. if (!self.waitingForPresent_) {
  44214. return;
  44215. }
  44216. self.removeFullscreenWrapper();
  44217. self.removeFullscreenListeners_();
  44218. self.disableWakeLock();
  44219. self.waitingForPresent_ = false;
  44220. self.isPresenting = false;
  44221. reject(new Error('Unable to present.'));
  44222. };
  44223. self.addFullscreenListeners_(fullscreenElement, onFullscreenChange, onFullscreenError);
  44224. if (requestFullscreen(fullscreenElement)) {
  44225. self.enableWakeLock();
  44226. self.waitingForPresent_ = true;
  44227. } else if (isIOS() || isWebViewAndroid()) {
  44228. self.enableWakeLock();
  44229. self.isPresenting = true;
  44230. self.beginPresent_();
  44231. self.fireVRDisplayPresentChange_();
  44232. resolve();
  44233. }
  44234. }
  44235. if (!self.waitingForPresent_ && !isIOS()) {
  44236. exitFullscreen();
  44237. reject(new Error('Unable to present.'));
  44238. }
  44239. });
  44240. };
  44241. VRDisplay.prototype.exitPresent = function () {
  44242. var wasPresenting = this.isPresenting;
  44243. var self = this;
  44244. this.isPresenting = false;
  44245. this.layer_ = null;
  44246. this.disableWakeLock();
  44247. return new Promise(function (resolve, reject) {
  44248. if (wasPresenting) {
  44249. if (!exitFullscreen() && isIOS()) {
  44250. self.endPresent_();
  44251. self.fireVRDisplayPresentChange_();
  44252. }
  44253. if (isWebViewAndroid()) {
  44254. self.removeFullscreenWrapper();
  44255. self.removeFullscreenListeners_();
  44256. self.endPresent_();
  44257. self.fireVRDisplayPresentChange_();
  44258. }
  44259. resolve();
  44260. } else {
  44261. reject(new Error('Was not presenting to VRDisplay.'));
  44262. }
  44263. });
  44264. };
  44265. VRDisplay.prototype.getLayers = function () {
  44266. if (this.layer_) {
  44267. return [this.layer_];
  44268. }
  44269. return [];
  44270. };
  44271. VRDisplay.prototype.fireVRDisplayPresentChange_ = function () {
  44272. var event = new CustomEvent('vrdisplaypresentchange', { detail: { display: this } });
  44273. window.dispatchEvent(event);
  44274. };
  44275. VRDisplay.prototype.fireVRDisplayConnect_ = function () {
  44276. var event = new CustomEvent('vrdisplayconnect', { detail: { display: this } });
  44277. window.dispatchEvent(event);
  44278. };
  44279. VRDisplay.prototype.addFullscreenListeners_ = function (element, changeHandler, errorHandler) {
  44280. this.removeFullscreenListeners_();
  44281. this.fullscreenEventTarget_ = element;
  44282. this.fullscreenChangeHandler_ = changeHandler;
  44283. this.fullscreenErrorHandler_ = errorHandler;
  44284. if (changeHandler) {
  44285. if (document.fullscreenEnabled) {
  44286. element.addEventListener('fullscreenchange', changeHandler, false);
  44287. } else if (document.webkitFullscreenEnabled) {
  44288. element.addEventListener('webkitfullscreenchange', changeHandler, false);
  44289. } else if (document.mozFullScreenEnabled) {
  44290. document.addEventListener('mozfullscreenchange', changeHandler, false);
  44291. } else if (document.msFullscreenEnabled) {
  44292. element.addEventListener('msfullscreenchange', changeHandler, false);
  44293. }
  44294. }
  44295. if (errorHandler) {
  44296. if (document.fullscreenEnabled) {
  44297. element.addEventListener('fullscreenerror', errorHandler, false);
  44298. } else if (document.webkitFullscreenEnabled) {
  44299. element.addEventListener('webkitfullscreenerror', errorHandler, false);
  44300. } else if (document.mozFullScreenEnabled) {
  44301. document.addEventListener('mozfullscreenerror', errorHandler, false);
  44302. } else if (document.msFullscreenEnabled) {
  44303. element.addEventListener('msfullscreenerror', errorHandler, false);
  44304. }
  44305. }
  44306. };
  44307. VRDisplay.prototype.removeFullscreenListeners_ = function () {
  44308. if (!this.fullscreenEventTarget_) return;
  44309. var element = this.fullscreenEventTarget_;
  44310. if (this.fullscreenChangeHandler_) {
  44311. var changeHandler = this.fullscreenChangeHandler_;
  44312. element.removeEventListener('fullscreenchange', changeHandler, false);
  44313. element.removeEventListener('webkitfullscreenchange', changeHandler, false);
  44314. document.removeEventListener('mozfullscreenchange', changeHandler, false);
  44315. element.removeEventListener('msfullscreenchange', changeHandler, false);
  44316. }
  44317. if (this.fullscreenErrorHandler_) {
  44318. var errorHandler = this.fullscreenErrorHandler_;
  44319. element.removeEventListener('fullscreenerror', errorHandler, false);
  44320. element.removeEventListener('webkitfullscreenerror', errorHandler, false);
  44321. document.removeEventListener('mozfullscreenerror', errorHandler, false);
  44322. element.removeEventListener('msfullscreenerror', errorHandler, false);
  44323. }
  44324. this.fullscreenEventTarget_ = null;
  44325. this.fullscreenChangeHandler_ = null;
  44326. this.fullscreenErrorHandler_ = null;
  44327. };
  44328. VRDisplay.prototype.enableWakeLock = function () {
  44329. if (this.wakelock_) {
  44330. this.wakelock_.enable();
  44331. }
  44332. };
  44333. VRDisplay.prototype.disableWakeLock = function () {
  44334. if (this.wakelock_) {
  44335. this.wakelock_.disable();
  44336. }
  44337. };
  44338. VRDisplay.prototype.beginPresent_ = function () {
  44339. };
  44340. VRDisplay.prototype.endPresent_ = function () {
  44341. };
  44342. VRDisplay.prototype.submitFrame = function (pose) {
  44343. };
  44344. VRDisplay.prototype.getEyeParameters = function (whichEye) {
  44345. return null;
  44346. };
  44347. var config = {
  44348. ADDITIONAL_VIEWERS: [],
  44349. DEFAULT_VIEWER: '',
  44350. MOBILE_WAKE_LOCK: true,
  44351. DEBUG: false,
  44352. DPDB_URL: 'https://dpdb.webvr.rocks/dpdb.json',
  44353. K_FILTER: 0.98,
  44354. PREDICTION_TIME_S: 0.040,
  44355. CARDBOARD_UI_DISABLED: false,
  44356. ROTATE_INSTRUCTIONS_DISABLED: false,
  44357. YAW_ONLY: false,
  44358. BUFFER_SCALE: 0.5,
  44359. DIRTY_SUBMIT_FRAME_BINDINGS: false
  44360. };
  44361. var Eye = {
  44362. LEFT: 'left',
  44363. RIGHT: 'right'
  44364. };
  44365. function CardboardVRDisplay(config$$1) {
  44366. var defaults = extend({}, config);
  44367. config$$1 = extend(defaults, config$$1 || {});
  44368. VRDisplay.call(this, {
  44369. wakelock: config$$1.MOBILE_WAKE_LOCK
  44370. });
  44371. this.config = config$$1;
  44372. this.displayName = 'Cardboard VRDisplay';
  44373. this.capabilities = new VRDisplayCapabilities({
  44374. hasPosition: false,
  44375. hasOrientation: true,
  44376. hasExternalDisplay: false,
  44377. canPresent: true,
  44378. maxLayers: 1
  44379. });
  44380. this.stageParameters = null;
  44381. this.bufferScale_ = this.config.BUFFER_SCALE;
  44382. this.poseSensor_ = new PoseSensor(this.config);
  44383. this.distorter_ = null;
  44384. this.cardboardUI_ = null;
  44385. this.dpdb_ = new Dpdb(this.config.DPDB_URL, this.onDeviceParamsUpdated_.bind(this));
  44386. this.deviceInfo_ = new DeviceInfo(this.dpdb_.getDeviceParams(), config$$1.ADDITIONAL_VIEWERS);
  44387. this.viewerSelector_ = new ViewerSelector(config$$1.DEFAULT_VIEWER);
  44388. this.viewerSelector_.onChange(this.onViewerChanged_.bind(this));
  44389. this.deviceInfo_.setViewer(this.viewerSelector_.getCurrentViewer());
  44390. if (!this.config.ROTATE_INSTRUCTIONS_DISABLED) {
  44391. this.rotateInstructions_ = new RotateInstructions();
  44392. }
  44393. if (isIOS()) {
  44394. window.addEventListener('resize', this.onResize_.bind(this));
  44395. }
  44396. }
  44397. CardboardVRDisplay.prototype = Object.create(VRDisplay.prototype);
  44398. CardboardVRDisplay.prototype._getPose = function () {
  44399. return {
  44400. position: null,
  44401. orientation: this.poseSensor_.getOrientation(),
  44402. linearVelocity: null,
  44403. linearAcceleration: null,
  44404. angularVelocity: null,
  44405. angularAcceleration: null
  44406. };
  44407. };
  44408. CardboardVRDisplay.prototype._resetPose = function () {
  44409. if (this.poseSensor_.resetPose) {
  44410. this.poseSensor_.resetPose();
  44411. }
  44412. };
  44413. CardboardVRDisplay.prototype._getFieldOfView = function (whichEye) {
  44414. var fieldOfView;
  44415. if (whichEye == Eye.LEFT) {
  44416. fieldOfView = this.deviceInfo_.getFieldOfViewLeftEye();
  44417. } else if (whichEye == Eye.RIGHT) {
  44418. fieldOfView = this.deviceInfo_.getFieldOfViewRightEye();
  44419. } else {
  44420. console.error('Invalid eye provided: %s', whichEye);
  44421. return null;
  44422. }
  44423. return fieldOfView;
  44424. };
  44425. CardboardVRDisplay.prototype._getEyeOffset = function (whichEye) {
  44426. var offset;
  44427. if (whichEye == Eye.LEFT) {
  44428. offset = [-this.deviceInfo_.viewer.interLensDistance * 0.5, 0.0, 0.0];
  44429. } else if (whichEye == Eye.RIGHT) {
  44430. offset = [this.deviceInfo_.viewer.interLensDistance * 0.5, 0.0, 0.0];
  44431. } else {
  44432. console.error('Invalid eye provided: %s', whichEye);
  44433. return null;
  44434. }
  44435. return offset;
  44436. };
  44437. CardboardVRDisplay.prototype.getEyeParameters = function (whichEye) {
  44438. var offset = this._getEyeOffset(whichEye);
  44439. var fieldOfView = this._getFieldOfView(whichEye);
  44440. var eyeParams = {
  44441. offset: offset,
  44442. renderWidth: this.deviceInfo_.device.width * 0.5 * this.bufferScale_,
  44443. renderHeight: this.deviceInfo_.device.height * this.bufferScale_
  44444. };
  44445. Object.defineProperty(eyeParams, 'fieldOfView', {
  44446. enumerable: true,
  44447. get: function get() {
  44448. deprecateWarning('VRFieldOfView', 'VRFrameData\'s projection matrices');
  44449. return fieldOfView;
  44450. }
  44451. });
  44452. return eyeParams;
  44453. };
  44454. CardboardVRDisplay.prototype.onDeviceParamsUpdated_ = function (newParams) {
  44455. if (this.config.DEBUG) {
  44456. console.log('DPDB reported that device params were updated.');
  44457. }
  44458. this.deviceInfo_.updateDeviceParams(newParams);
  44459. if (this.distorter_) {
  44460. this.distorter_.updateDeviceInfo(this.deviceInfo_);
  44461. }
  44462. };
  44463. CardboardVRDisplay.prototype.updateBounds_ = function () {
  44464. if (this.layer_ && this.distorter_ && (this.layer_.leftBounds || this.layer_.rightBounds)) {
  44465. this.distorter_.setTextureBounds(this.layer_.leftBounds, this.layer_.rightBounds);
  44466. }
  44467. };
  44468. CardboardVRDisplay.prototype.beginPresent_ = function () {
  44469. var gl = this.layer_.source.getContext('webgl');
  44470. if (!gl) gl = this.layer_.source.getContext('experimental-webgl');
  44471. if (!gl) gl = this.layer_.source.getContext('webgl2');
  44472. if (!gl) return;
  44473. if (this.layer_.predistorted) {
  44474. if (!this.config.CARDBOARD_UI_DISABLED) {
  44475. gl.canvas.width = getScreenWidth() * this.bufferScale_;
  44476. gl.canvas.height = getScreenHeight() * this.bufferScale_;
  44477. this.cardboardUI_ = new CardboardUI(gl);
  44478. }
  44479. } else {
  44480. if (!this.config.CARDBOARD_UI_DISABLED) {
  44481. this.cardboardUI_ = new CardboardUI(gl);
  44482. }
  44483. this.distorter_ = new CardboardDistorter(gl, this.cardboardUI_, this.config.BUFFER_SCALE, this.config.DIRTY_SUBMIT_FRAME_BINDINGS);
  44484. this.distorter_.updateDeviceInfo(this.deviceInfo_);
  44485. }
  44486. if (this.cardboardUI_) {
  44487. this.cardboardUI_.listen(function (e) {
  44488. this.viewerSelector_.show(this.layer_.source.parentElement);
  44489. e.stopPropagation();
  44490. e.preventDefault();
  44491. }.bind(this), function (e) {
  44492. this.exitPresent();
  44493. e.stopPropagation();
  44494. e.preventDefault();
  44495. }.bind(this));
  44496. }
  44497. if (this.rotateInstructions_) {
  44498. if (isLandscapeMode() && isMobile()) {
  44499. this.rotateInstructions_.showTemporarily(3000, this.layer_.source.parentElement);
  44500. } else {
  44501. this.rotateInstructions_.update();
  44502. }
  44503. }
  44504. this.orientationHandler = this.onOrientationChange_.bind(this);
  44505. window.addEventListener('orientationchange', this.orientationHandler);
  44506. this.vrdisplaypresentchangeHandler = this.updateBounds_.bind(this);
  44507. window.addEventListener('vrdisplaypresentchange', this.vrdisplaypresentchangeHandler);
  44508. this.fireVRDisplayDeviceParamsChange_();
  44509. };
  44510. CardboardVRDisplay.prototype.endPresent_ = function () {
  44511. if (this.distorter_) {
  44512. this.distorter_.destroy();
  44513. this.distorter_ = null;
  44514. }
  44515. if (this.cardboardUI_) {
  44516. this.cardboardUI_.destroy();
  44517. this.cardboardUI_ = null;
  44518. }
  44519. if (this.rotateInstructions_) {
  44520. this.rotateInstructions_.hide();
  44521. }
  44522. this.viewerSelector_.hide();
  44523. window.removeEventListener('orientationchange', this.orientationHandler);
  44524. window.removeEventListener('vrdisplaypresentchange', this.vrdisplaypresentchangeHandler);
  44525. };
  44526. CardboardVRDisplay.prototype.updatePresent_ = function () {
  44527. this.endPresent_();
  44528. this.beginPresent_();
  44529. };
  44530. CardboardVRDisplay.prototype.submitFrame = function (pose) {
  44531. if (this.distorter_) {
  44532. this.updateBounds_();
  44533. this.distorter_.submitFrame();
  44534. } else if (this.cardboardUI_ && this.layer_) {
  44535. var gl = this.layer_.source.getContext('webgl');
  44536. if (!gl) gl = this.layer_.source.getContext('experimental-webgl');
  44537. if (!gl) gl = this.layer_.source.getContext('webgl2');
  44538. var canvas = gl.canvas;
  44539. if (canvas.width != this.lastWidth || canvas.height != this.lastHeight) {
  44540. this.cardboardUI_.onResize();
  44541. }
  44542. this.lastWidth = canvas.width;
  44543. this.lastHeight = canvas.height;
  44544. this.cardboardUI_.render();
  44545. }
  44546. };
  44547. CardboardVRDisplay.prototype.onOrientationChange_ = function (e) {
  44548. this.viewerSelector_.hide();
  44549. if (this.rotateInstructions_) {
  44550. this.rotateInstructions_.update();
  44551. }
  44552. this.onResize_();
  44553. };
  44554. CardboardVRDisplay.prototype.onResize_ = function (e) {
  44555. if (this.layer_) {
  44556. var gl = this.layer_.source.getContext('webgl');
  44557. if (!gl) gl = this.layer_.source.getContext('experimental-webgl');
  44558. if (!gl) gl = this.layer_.source.getContext('webgl2');
  44559. var cssProperties = ['position: absolute', 'top: 0', 'left: 0',
  44560. 'width: 100vw', 'height: 100vh', 'border: 0', 'margin: 0',
  44561. 'padding: 0px', 'box-sizing: content-box'];
  44562. gl.canvas.setAttribute('style', cssProperties.join('; ') + ';');
  44563. safariCssSizeWorkaround(gl.canvas);
  44564. }
  44565. };
  44566. CardboardVRDisplay.prototype.onViewerChanged_ = function (viewer) {
  44567. this.deviceInfo_.setViewer(viewer);
  44568. if (this.distorter_) {
  44569. this.distorter_.updateDeviceInfo(this.deviceInfo_);
  44570. }
  44571. this.fireVRDisplayDeviceParamsChange_();
  44572. };
  44573. CardboardVRDisplay.prototype.fireVRDisplayDeviceParamsChange_ = function () {
  44574. var event = new CustomEvent('vrdisplaydeviceparamschange', {
  44575. detail: {
  44576. vrdisplay: this,
  44577. deviceInfo: this.deviceInfo_
  44578. }
  44579. });
  44580. window.dispatchEvent(event);
  44581. };
  44582. CardboardVRDisplay.VRFrameData = VRFrameData;
  44583. CardboardVRDisplay.VRDisplay = VRDisplay;
  44584. return CardboardVRDisplay;
  44585. })));
  44586. });
  44587. var CardboardVRDisplay = unwrapExports(cardboardVrDisplay);
  44588. var version = "0.10.12";
  44589. var DefaultConfig = {
  44590. ADDITIONAL_VIEWERS: [],
  44591. DEFAULT_VIEWER: '',
  44592. PROVIDE_MOBILE_VRDISPLAY: true,
  44593. MOBILE_WAKE_LOCK: true,
  44594. DEBUG: false,
  44595. DPDB_URL: 'https://dpdb.webvr.rocks/dpdb.json',
  44596. K_FILTER: 0.98,
  44597. PREDICTION_TIME_S: 0.040,
  44598. CARDBOARD_UI_DISABLED: false,
  44599. ROTATE_INSTRUCTIONS_DISABLED: false,
  44600. YAW_ONLY: false,
  44601. BUFFER_SCALE: 0.5,
  44602. DIRTY_SUBMIT_FRAME_BINDINGS: false
  44603. };
  44604. function WebVRPolyfill(config) {
  44605. this.config = extend(extend({}, DefaultConfig), config);
  44606. this.polyfillDisplays = [];
  44607. this.enabled = false;
  44608. this.hasNative = 'getVRDisplays' in navigator;
  44609. this.native = {};
  44610. this.native.getVRDisplays = navigator.getVRDisplays;
  44611. this.native.VRFrameData = window.VRFrameData;
  44612. this.native.VRDisplay = window.VRDisplay;
  44613. if (!this.hasNative || this.config.PROVIDE_MOBILE_VRDISPLAY && isMobile()) {
  44614. this.enable();
  44615. this.getVRDisplays().then(function (displays) {
  44616. if (displays && displays[0] && displays[0].fireVRDisplayConnect_) {
  44617. displays[0].fireVRDisplayConnect_();
  44618. }
  44619. });
  44620. }
  44621. }
  44622. WebVRPolyfill.prototype.getPolyfillDisplays = function () {
  44623. if (this._polyfillDisplaysPopulated) {
  44624. return this.polyfillDisplays;
  44625. }
  44626. if (isMobile()) {
  44627. var vrDisplay = new CardboardVRDisplay({
  44628. ADDITIONAL_VIEWERS: this.config.ADDITIONAL_VIEWERS,
  44629. DEFAULT_VIEWER: this.config.DEFAULT_VIEWER,
  44630. MOBILE_WAKE_LOCK: this.config.MOBILE_WAKE_LOCK,
  44631. DEBUG: this.config.DEBUG,
  44632. DPDB_URL: this.config.DPDB_URL,
  44633. CARDBOARD_UI_DISABLED: this.config.CARDBOARD_UI_DISABLED,
  44634. K_FILTER: this.config.K_FILTER,
  44635. PREDICTION_TIME_S: this.config.PREDICTION_TIME_S,
  44636. ROTATE_INSTRUCTIONS_DISABLED: this.config.ROTATE_INSTRUCTIONS_DISABLED,
  44637. YAW_ONLY: this.config.YAW_ONLY,
  44638. BUFFER_SCALE: this.config.BUFFER_SCALE,
  44639. DIRTY_SUBMIT_FRAME_BINDINGS: this.config.DIRTY_SUBMIT_FRAME_BINDINGS
  44640. });
  44641. this.polyfillDisplays.push(vrDisplay);
  44642. }
  44643. this._polyfillDisplaysPopulated = true;
  44644. return this.polyfillDisplays;
  44645. };
  44646. WebVRPolyfill.prototype.enable = function () {
  44647. this.enabled = true;
  44648. if (this.hasNative && this.native.VRFrameData) {
  44649. var NativeVRFrameData = this.native.VRFrameData;
  44650. var nativeFrameData = new this.native.VRFrameData();
  44651. var nativeGetFrameData = this.native.VRDisplay.prototype.getFrameData;
  44652. window.VRDisplay.prototype.getFrameData = function (frameData) {
  44653. if (frameData instanceof NativeVRFrameData) {
  44654. nativeGetFrameData.call(this, frameData);
  44655. return;
  44656. }
  44657. nativeGetFrameData.call(this, nativeFrameData);
  44658. frameData.pose = nativeFrameData.pose;
  44659. copyArray(nativeFrameData.leftProjectionMatrix, frameData.leftProjectionMatrix);
  44660. copyArray(nativeFrameData.rightProjectionMatrix, frameData.rightProjectionMatrix);
  44661. copyArray(nativeFrameData.leftViewMatrix, frameData.leftViewMatrix);
  44662. copyArray(nativeFrameData.rightViewMatrix, frameData.rightViewMatrix);
  44663. };
  44664. }
  44665. navigator.getVRDisplays = this.getVRDisplays.bind(this);
  44666. window.VRDisplay = CardboardVRDisplay.VRDisplay;
  44667. window.VRFrameData = CardboardVRDisplay.VRFrameData;
  44668. };
  44669. WebVRPolyfill.prototype.getVRDisplays = function () {
  44670. var _this = this;
  44671. var config = this.config;
  44672. if (!this.hasNative) {
  44673. return Promise.resolve(this.getPolyfillDisplays());
  44674. }
  44675. return this.native.getVRDisplays.call(navigator).then(function (nativeDisplays) {
  44676. return nativeDisplays.length > 0 ? nativeDisplays : _this.getPolyfillDisplays();
  44677. });
  44678. };
  44679. WebVRPolyfill.version = version;
  44680. WebVRPolyfill.VRFrameData = CardboardVRDisplay.VRFrameData;
  44681. WebVRPolyfill.VRDisplay = CardboardVRDisplay.VRDisplay;
  44682. var webvrPolyfill = Object.freeze({
  44683. default: WebVRPolyfill
  44684. });
  44685. var require$$0 = ( webvrPolyfill && WebVRPolyfill ) || webvrPolyfill;
  44686. if (typeof commonjsGlobal !== 'undefined' && commonjsGlobal.window) {
  44687. if (!commonjsGlobal.document) {
  44688. commonjsGlobal.document = commonjsGlobal.window.document;
  44689. }
  44690. if (!commonjsGlobal.navigator) {
  44691. commonjsGlobal.navigator = commonjsGlobal.window.navigator;
  44692. }
  44693. }
  44694. var src = require$$0;
  44695. return src;
  44696. })));
  44697. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  44698. },{}],69:[function(_dereq_,module,exports){
  44699. var newline = /\n/
  44700. var newlineChar = '\n'
  44701. var whitespace = /\s/
  44702. module.exports = function(text, opt) {
  44703. var lines = module.exports.lines(text, opt)
  44704. return lines.map(function(line) {
  44705. return text.substring(line.start, line.end)
  44706. }).join('\n')
  44707. }
  44708. module.exports.lines = function wordwrap(text, opt) {
  44709. opt = opt||{}
  44710. //zero width results in nothing visible
  44711. if (opt.width === 0 && opt.mode !== 'nowrap')
  44712. return []
  44713. text = text||''
  44714. var width = typeof opt.width === 'number' ? opt.width : Number.MAX_VALUE
  44715. var start = Math.max(0, opt.start||0)
  44716. var end = typeof opt.end === 'number' ? opt.end : text.length
  44717. var mode = opt.mode
  44718. var measure = opt.measure || monospace
  44719. if (mode === 'pre')
  44720. return pre(measure, text, start, end, width)
  44721. else
  44722. return greedy(measure, text, start, end, width, mode)
  44723. }
  44724. function idxOf(text, chr, start, end) {
  44725. var idx = text.indexOf(chr, start)
  44726. if (idx === -1 || idx > end)
  44727. return end
  44728. return idx
  44729. }
  44730. function isWhitespace(chr) {
  44731. return whitespace.test(chr)
  44732. }
  44733. function pre(measure, text, start, end, width) {
  44734. var lines = []
  44735. var lineStart = start
  44736. for (var i=start; i<end && i<text.length; i++) {
  44737. var chr = text.charAt(i)
  44738. var isNewline = newline.test(chr)
  44739. //If we've reached a newline, then step down a line
  44740. //Or if we've reached the EOF
  44741. if (isNewline || i===end-1) {
  44742. var lineEnd = isNewline ? i : i+1
  44743. var measured = measure(text, lineStart, lineEnd, width)
  44744. lines.push(measured)
  44745. lineStart = i+1
  44746. }
  44747. }
  44748. return lines
  44749. }
  44750. function greedy(measure, text, start, end, width, mode) {
  44751. //A greedy word wrapper based on LibGDX algorithm
  44752. //https://github.com/libgdx/libgdx/blob/master/gdx/src/com/badlogic/gdx/graphics/g2d/BitmapFontCache.java
  44753. var lines = []
  44754. var testWidth = width
  44755. //if 'nowrap' is specified, we only wrap on newline chars
  44756. if (mode === 'nowrap')
  44757. testWidth = Number.MAX_VALUE
  44758. while (start < end && start < text.length) {
  44759. //get next newline position
  44760. var newLine = idxOf(text, newlineChar, start, end)
  44761. //eat whitespace at start of line
  44762. while (start < newLine) {
  44763. if (!isWhitespace( text.charAt(start) ))
  44764. break
  44765. start++
  44766. }
  44767. //determine visible # of glyphs for the available width
  44768. var measured = measure(text, start, newLine, testWidth)
  44769. var lineEnd = start + (measured.end-measured.start)
  44770. var nextStart = lineEnd + newlineChar.length
  44771. //if we had to cut the line before the next newline...
  44772. if (lineEnd < newLine) {
  44773. //find char to break on
  44774. while (lineEnd > start) {
  44775. if (isWhitespace(text.charAt(lineEnd)))
  44776. break
  44777. lineEnd--
  44778. }
  44779. if (lineEnd === start) {
  44780. if (nextStart > start + newlineChar.length) nextStart--
  44781. lineEnd = nextStart // If no characters to break, show all.
  44782. } else {
  44783. nextStart = lineEnd
  44784. //eat whitespace at end of line
  44785. while (lineEnd > start) {
  44786. if (!isWhitespace(text.charAt(lineEnd - newlineChar.length)))
  44787. break
  44788. lineEnd--
  44789. }
  44790. }
  44791. }
  44792. if (lineEnd >= start) {
  44793. var result = measure(text, start, lineEnd, testWidth)
  44794. lines.push(result)
  44795. }
  44796. start = nextStart
  44797. }
  44798. return lines
  44799. }
  44800. //determines the visible number of glyphs within a given width
  44801. function monospace(text, start, end, width) {
  44802. var glyphs = Math.min(width, end-start)
  44803. return {
  44804. start: start,
  44805. end: start+glyphs
  44806. }
  44807. }
  44808. },{}],70:[function(_dereq_,module,exports){
  44809. "use strict";
  44810. var window = _dereq_("global/window")
  44811. var isFunction = _dereq_("is-function")
  44812. var parseHeaders = _dereq_("parse-headers")
  44813. var xtend = _dereq_("xtend")
  44814. module.exports = createXHR
  44815. // Allow use of default import syntax in TypeScript
  44816. module.exports.default = createXHR;
  44817. createXHR.XMLHttpRequest = window.XMLHttpRequest || noop
  44818. createXHR.XDomainRequest = "withCredentials" in (new createXHR.XMLHttpRequest()) ? createXHR.XMLHttpRequest : window.XDomainRequest
  44819. forEachArray(["get", "put", "post", "patch", "head", "delete"], function(method) {
  44820. createXHR[method === "delete" ? "del" : method] = function(uri, options, callback) {
  44821. options = initParams(uri, options, callback)
  44822. options.method = method.toUpperCase()
  44823. return _createXHR(options)
  44824. }
  44825. })
  44826. function forEachArray(array, iterator) {
  44827. for (var i = 0; i < array.length; i++) {
  44828. iterator(array[i])
  44829. }
  44830. }
  44831. function isEmpty(obj){
  44832. for(var i in obj){
  44833. if(obj.hasOwnProperty(i)) return false
  44834. }
  44835. return true
  44836. }
  44837. function initParams(uri, options, callback) {
  44838. var params = uri
  44839. if (isFunction(options)) {
  44840. callback = options
  44841. if (typeof uri === "string") {
  44842. params = {uri:uri}
  44843. }
  44844. } else {
  44845. params = xtend(options, {uri: uri})
  44846. }
  44847. params.callback = callback
  44848. return params
  44849. }
  44850. function createXHR(uri, options, callback) {
  44851. options = initParams(uri, options, callback)
  44852. return _createXHR(options)
  44853. }
  44854. function _createXHR(options) {
  44855. if(typeof options.callback === "undefined"){
  44856. throw new Error("callback argument missing")
  44857. }
  44858. var called = false
  44859. var callback = function cbOnce(err, response, body){
  44860. if(!called){
  44861. called = true
  44862. options.callback(err, response, body)
  44863. }
  44864. }
  44865. function readystatechange() {
  44866. if (xhr.readyState === 4) {
  44867. setTimeout(loadFunc, 0)
  44868. }
  44869. }
  44870. function getBody() {
  44871. // Chrome with requestType=blob throws errors arround when even testing access to responseText
  44872. var body = undefined
  44873. if (xhr.response) {
  44874. body = xhr.response
  44875. } else {
  44876. body = xhr.responseText || getXml(xhr)
  44877. }
  44878. if (isJson) {
  44879. try {
  44880. body = JSON.parse(body)
  44881. } catch (e) {}
  44882. }
  44883. return body
  44884. }
  44885. function errorFunc(evt) {
  44886. clearTimeout(timeoutTimer)
  44887. if(!(evt instanceof Error)){
  44888. evt = new Error("" + (evt || "Unknown XMLHttpRequest Error") )
  44889. }
  44890. evt.statusCode = 0
  44891. return callback(evt, failureResponse)
  44892. }
  44893. // will load the data & process the response in a special response object
  44894. function loadFunc() {
  44895. if (aborted) return
  44896. var status
  44897. clearTimeout(timeoutTimer)
  44898. if(options.useXDR && xhr.status===undefined) {
  44899. //IE8 CORS GET successful response doesn't have a status field, but body is fine
  44900. status = 200
  44901. } else {
  44902. status = (xhr.status === 1223 ? 204 : xhr.status)
  44903. }
  44904. var response = failureResponse
  44905. var err = null
  44906. if (status !== 0){
  44907. response = {
  44908. body: getBody(),
  44909. statusCode: status,
  44910. method: method,
  44911. headers: {},
  44912. url: uri,
  44913. rawRequest: xhr
  44914. }
  44915. if(xhr.getAllResponseHeaders){ //remember xhr can in fact be XDR for CORS in IE
  44916. response.headers = parseHeaders(xhr.getAllResponseHeaders())
  44917. }
  44918. } else {
  44919. err = new Error("Internal XMLHttpRequest Error")
  44920. }
  44921. return callback(err, response, response.body)
  44922. }
  44923. var xhr = options.xhr || null
  44924. if (!xhr) {
  44925. if (options.cors || options.useXDR) {
  44926. xhr = new createXHR.XDomainRequest()
  44927. }else{
  44928. xhr = new createXHR.XMLHttpRequest()
  44929. }
  44930. }
  44931. var key
  44932. var aborted
  44933. var uri = xhr.url = options.uri || options.url
  44934. var method = xhr.method = options.method || "GET"
  44935. var body = options.body || options.data
  44936. var headers = xhr.headers = options.headers || {}
  44937. var sync = !!options.sync
  44938. var isJson = false
  44939. var timeoutTimer
  44940. var failureResponse = {
  44941. body: undefined,
  44942. headers: {},
  44943. statusCode: 0,
  44944. method: method,
  44945. url: uri,
  44946. rawRequest: xhr
  44947. }
  44948. if ("json" in options && options.json !== false) {
  44949. isJson = true
  44950. headers["accept"] || headers["Accept"] || (headers["Accept"] = "application/json") //Don't override existing accept header declared by user
  44951. if (method !== "GET" && method !== "HEAD") {
  44952. headers["content-type"] || headers["Content-Type"] || (headers["Content-Type"] = "application/json") //Don't override existing accept header declared by user
  44953. body = JSON.stringify(options.json === true ? body : options.json)
  44954. }
  44955. }
  44956. xhr.onreadystatechange = readystatechange
  44957. xhr.onload = loadFunc
  44958. xhr.onerror = errorFunc
  44959. // IE9 must have onprogress be set to a unique function.
  44960. xhr.onprogress = function () {
  44961. // IE must die
  44962. }
  44963. xhr.onabort = function(){
  44964. aborted = true;
  44965. }
  44966. xhr.ontimeout = errorFunc
  44967. xhr.open(method, uri, !sync, options.username, options.password)
  44968. //has to be after open
  44969. if(!sync) {
  44970. xhr.withCredentials = !!options.withCredentials
  44971. }
  44972. // Cannot set timeout with sync request
  44973. // not setting timeout on the xhr object, because of old webkits etc. not handling that correctly
  44974. // both npm's request and jquery 1.x use this kind of timeout, so this is being consistent
  44975. if (!sync && options.timeout > 0 ) {
  44976. timeoutTimer = setTimeout(function(){
  44977. if (aborted) return
  44978. aborted = true//IE9 may still call readystatechange
  44979. xhr.abort("timeout")
  44980. var e = new Error("XMLHttpRequest timeout")
  44981. e.code = "ETIMEDOUT"
  44982. errorFunc(e)
  44983. }, options.timeout )
  44984. }
  44985. if (xhr.setRequestHeader) {
  44986. for(key in headers){
  44987. if(headers.hasOwnProperty(key)){
  44988. xhr.setRequestHeader(key, headers[key])
  44989. }
  44990. }
  44991. } else if (options.headers && !isEmpty(options.headers)) {
  44992. throw new Error("Headers cannot be set on an XDomainRequest object")
  44993. }
  44994. if ("responseType" in options) {
  44995. xhr.responseType = options.responseType
  44996. }
  44997. if ("beforeSend" in options &&
  44998. typeof options.beforeSend === "function"
  44999. ) {
  45000. options.beforeSend(xhr)
  45001. }
  45002. // Microsoft Edge browser sends "undefined" when send is called with undefined value.
  45003. // XMLHttpRequest spec says to pass null as body to indicate no body
  45004. // See https://github.com/naugtur/xhr/issues/100.
  45005. xhr.send(body || null)
  45006. return xhr
  45007. }
  45008. function getXml(xhr) {
  45009. // xhr.responseXML will throw Exception "InvalidStateError" or "DOMException"
  45010. // See https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/responseXML.
  45011. try {
  45012. if (xhr.responseType === "document") {
  45013. return xhr.responseXML
  45014. }
  45015. var firefoxBugTakenEffect = xhr.responseXML && xhr.responseXML.documentElement.nodeName === "parsererror"
  45016. if (xhr.responseType === "" && !firefoxBugTakenEffect) {
  45017. return xhr.responseXML
  45018. }
  45019. } catch (e) {}
  45020. return null
  45021. }
  45022. function noop() {}
  45023. },{"global/window":27,"is-function":33,"parse-headers":47,"xtend":72}],71:[function(_dereq_,module,exports){
  45024. module.exports = (function xmlparser() {
  45025. //common browsers
  45026. if (typeof self.DOMParser !== 'undefined') {
  45027. return function(str) {
  45028. var parser = new self.DOMParser()
  45029. return parser.parseFromString(str, 'application/xml')
  45030. }
  45031. }
  45032. //IE8 fallback
  45033. if (typeof self.ActiveXObject !== 'undefined'
  45034. && new self.ActiveXObject('Microsoft.XMLDOM')) {
  45035. return function(str) {
  45036. var xmlDoc = new self.ActiveXObject("Microsoft.XMLDOM")
  45037. xmlDoc.async = "false"
  45038. xmlDoc.loadXML(str)
  45039. return xmlDoc
  45040. }
  45041. }
  45042. //last resort fallback
  45043. return function(str) {
  45044. var div = document.createElement('div')
  45045. div.innerHTML = str
  45046. return div
  45047. }
  45048. })()
  45049. },{}],72:[function(_dereq_,module,exports){
  45050. module.exports = extend
  45051. var hasOwnProperty = Object.prototype.hasOwnProperty;
  45052. function extend() {
  45053. var target = {}
  45054. for (var i = 0; i < arguments.length; i++) {
  45055. var source = arguments[i]
  45056. for (var key in source) {
  45057. if (hasOwnProperty.call(source, key)) {
  45058. target[key] = source[key]
  45059. }
  45060. }
  45061. }
  45062. return target
  45063. }
  45064. },{}],73:[function(_dereq_,module,exports){
  45065. module.exports={
  45066. "name": "aframe",
  45067. "version": "1.2.0",
  45068. "description": "A web framework for building virtual reality experiences.",
  45069. "homepage": "https://aframe.io/",
  45070. "main": "dist/aframe-master.js",
  45071. "scripts": {
  45072. "browserify": "browserify src/index.js -s 'AFRAME' -p browserify-derequire",
  45073. "build": "shx mkdir -p build/ && npm run browserify -- --debug -t [ envify --INSPECTOR_VERSION dev ] -o build/aframe.js",
  45074. "codecov": "codecov",
  45075. "dev": "npm run build && cross-env INSPECTOR_VERSION=dev node ./scripts/budo -t envify",
  45076. "dist": "node scripts/updateVersionLog.js && npm run dist:min && npm run dist:max",
  45077. "dist:max": "npm run browserify -s -- --debug | exorcist dist/aframe-master.js.map > dist/aframe-master.js",
  45078. "dist:min": "npm run browserify -s -- --debug -p [ minifyify --map aframe-master.min.js.map --output dist/aframe-master.min.js.map ] -o dist/aframe-master.min.js",
  45079. "docs": "markserv --dir docs --port 9001",
  45080. "preghpages": "node ./scripts/preghpages.js",
  45081. "ghpages": "ghpages -p gh-pages/",
  45082. "lint": "semistandard -v | snazzy",
  45083. "lint:fix": "semistandard --fix",
  45084. "precommit": "npm run lint",
  45085. "prepush": "node scripts/testOnlyCheck.js",
  45086. "prerelease": "node scripts/release.js 1.1.0 1.2.0",
  45087. "start": "npm run dev",
  45088. "start:https": "cross-env SSL=true npm run dev",
  45089. "test": "karma start ./tests/karma.conf.js",
  45090. "test:docs": "node scripts/docsLint.js",
  45091. "test:firefox": "npm test -- --browsers Firefox",
  45092. "test:chrome": "npm test -- --browsers Chrome",
  45093. "test:nobrowser": "NO_BROWSER=true npm test",
  45094. "test:node": "mocha --ui tdd tests/node"
  45095. },
  45096. "repository": "aframevr/aframe",
  45097. "license": "MIT",
  45098. "files": [
  45099. "dist/*",
  45100. "docs/**/*",
  45101. "src/**/*",
  45102. "vendor/**/*"
  45103. ],
  45104. "dependencies": {
  45105. "custom-event-polyfill": "^1.0.6",
  45106. "debug": "ngokevin/debug#noTimestamp",
  45107. "deep-assign": "^2.0.0",
  45108. "document-register-element": "dmarcos/document-register-element#8ccc532b7f3744be954574caf3072a5fd260ca90",
  45109. "load-bmfont": "^1.2.3",
  45110. "object-assign": "^4.0.1",
  45111. "present": "0.0.6",
  45112. "promise-polyfill": "^3.1.0",
  45113. "super-animejs": "^3.1.0",
  45114. "super-three": "^0.125.1",
  45115. "three-bmfont-text": "dmarcos/three-bmfont-text#1babdf8507c731a18f8af3b807292e2b9740955e",
  45116. "webvr-polyfill": "^0.10.12"
  45117. },
  45118. "devDependencies": {
  45119. "browserify": "^13.1.0",
  45120. "browserify-css": "^0.8.4",
  45121. "browserify-derequire": "^0.9.4",
  45122. "browserify-istanbul": "^2.0.0",
  45123. "budo": "^9.2.0",
  45124. "chai": "^3.5.0",
  45125. "chai-shallow-deep-equal": "^1.4.0",
  45126. "chalk": "^1.1.3",
  45127. "codecov": "^1.0.1",
  45128. "cross-env": "^5.0.1",
  45129. "envify": "^3.4.1",
  45130. "exorcist": "^0.4.0",
  45131. "ghpages": "0.0.8",
  45132. "git-rev": "^0.2.1",
  45133. "glob": "^7.1.1",
  45134. "husky": "^0.11.7",
  45135. "istanbul": "^0.4.5",
  45136. "jsdom": "^9.11.0",
  45137. "karma": "1.4.1",
  45138. "karma-browserify": "^5.1.0",
  45139. "karma-chai-shallow-deep-equal": "0.0.4",
  45140. "karma-chrome-launcher": "^2.0.0",
  45141. "karma-coverage": "^1.1.1",
  45142. "karma-env-preprocessor": "^0.1.1",
  45143. "karma-firefox-launcher": "^1.2.0",
  45144. "karma-mocha": "^1.1.1",
  45145. "karma-mocha-reporter": "^2.1.0",
  45146. "karma-sinon-chai": "1.2.4",
  45147. "lolex": "^1.5.1",
  45148. "markserv": "github:sukima/markserv#feature/fix-broken-websoketio-link",
  45149. "minifyify": "^7.3.3",
  45150. "mocha": "^3.0.2",
  45151. "mozilla-download": "^1.1.1",
  45152. "replace-in-file": "^2.5.3",
  45153. "semistandard": "^9.0.0",
  45154. "shelljs": "^0.7.7",
  45155. "shx": "^0.2.2",
  45156. "sinon": "^1.17.5",
  45157. "sinon-chai": "2.8.0",
  45158. "snazzy": "^5.0.0",
  45159. "too-wordy": "ngokevin/too-wordy",
  45160. "uglifyjs": "^2.4.10",
  45161. "write-good": "^0.9.1"
  45162. },
  45163. "link": true,
  45164. "browserify": {
  45165. "transform": [
  45166. "browserify-css",
  45167. "envify"
  45168. ]
  45169. },
  45170. "semistandard": {
  45171. "ignore": [
  45172. "build/**",
  45173. "dist/**",
  45174. "examples/**/shaders/*.js",
  45175. "**/vendor/**"
  45176. ]
  45177. },
  45178. "keywords": [
  45179. "3d",
  45180. "aframe",
  45181. "cardboard",
  45182. "components",
  45183. "oculus",
  45184. "three",
  45185. "three.js",
  45186. "rift",
  45187. "vive",
  45188. "vr",
  45189. "web-components",
  45190. "webvr"
  45191. ],
  45192. "browserify-css": {
  45193. "minify": true
  45194. },
  45195. "engines": {
  45196. "node": ">= 4.6.0",
  45197. "npm": "^2.15.9"
  45198. }
  45199. }
  45200. },{}],74:[function(_dereq_,module,exports){
  45201. var anime = _dereq_('super-animejs');
  45202. var components = _dereq_('../core/component').components;
  45203. var registerComponent = _dereq_('../core/component').registerComponent;
  45204. var THREE = _dereq_('../lib/three');
  45205. var utils = _dereq_('../utils');
  45206. var colorHelperFrom = new THREE.Color();
  45207. var colorHelperTo = new THREE.Color();
  45208. var getComponentProperty = utils.entity.getComponentProperty;
  45209. var setComponentProperty = utils.entity.setComponentProperty;
  45210. var splitCache = {};
  45211. var TYPE_COLOR = 'color';
  45212. var PROP_POSITION = 'position';
  45213. var PROP_ROTATION = 'rotation';
  45214. var PROP_SCALE = 'scale';
  45215. var STRING_COMPONENTS = 'components';
  45216. var STRING_OBJECT3D = 'object3D';
  45217. /**
  45218. * Animation component for A-Frame using anime.js.
  45219. *
  45220. * The component manually controls the tick by setting `autoplay: false` on anime.js and
  45221. * manually * calling `animation.tick()` in the tick handler. To pause or resume, we toggle a
  45222. * boolean * flag * `isAnimationPlaying`.
  45223. *
  45224. * anime.js animation config for tweenining Javascript objects and values works as:
  45225. *
  45226. * config = {
  45227. * targets: {foo: 0.0, bar: '#000'},
  45228. * foo: 1.0,
  45229. * bar: '#FFF'
  45230. * }
  45231. *
  45232. * The above will tween each property in `targets`. The `to` values are set in the root of
  45233. * the config.
  45234. *
  45235. * @member {object} animation - anime.js instance.
  45236. * @member {boolean} animationIsPlaying - Control if animation is playing.
  45237. */
  45238. module.exports.Component = registerComponent('animation', {
  45239. schema: {
  45240. autoplay: {default: true},
  45241. delay: {default: 0},
  45242. dir: {default: ''},
  45243. dur: {default: 1000},
  45244. easing: {default: 'easeInQuad'},
  45245. elasticity: {default: 400},
  45246. enabled: {default: true},
  45247. from: {default: ''},
  45248. loop: {
  45249. default: 0,
  45250. parse: function (value) {
  45251. // Boolean or integer.
  45252. if (value === true || value === 'true') { return true; }
  45253. if (value === false || value === 'false') { return false; }
  45254. return parseInt(value, 10);
  45255. }
  45256. },
  45257. property: {default: ''},
  45258. startEvents: {type: 'array'},
  45259. pauseEvents: {type: 'array'},
  45260. resumeEvents: {type: 'array'},
  45261. round: {default: false},
  45262. to: {default: ''},
  45263. type: {default: ''},
  45264. isRawProperty: {default: false}
  45265. },
  45266. multiple: true,
  45267. init: function () {
  45268. var self = this;
  45269. this.eventDetail = {name: this.attrName};
  45270. this.time = 0;
  45271. this.animation = null;
  45272. this.animationIsPlaying = false;
  45273. this.onStartEvent = this.onStartEvent.bind(this);
  45274. this.beginAnimation = this.beginAnimation.bind(this);
  45275. this.pauseAnimation = this.pauseAnimation.bind(this);
  45276. this.resumeAnimation = this.resumeAnimation.bind(this);
  45277. this.fromColor = {};
  45278. this.toColor = {};
  45279. this.targets = {};
  45280. this.targetsArray = [];
  45281. this.updateConfigForDefault = this.updateConfigForDefault.bind(this);
  45282. this.updateConfigForRawColor = this.updateConfigForRawColor.bind(this);
  45283. this.config = {
  45284. complete: function () {
  45285. self.animationIsPlaying = false;
  45286. self.el.emit('animationcomplete', self.eventDetail, false);
  45287. if (self.id) {
  45288. self.el.emit('animationcomplete__' + self.id, self.eventDetail, false);
  45289. }
  45290. }
  45291. };
  45292. },
  45293. update: function (oldData) {
  45294. var config = this.config;
  45295. var data = this.data;
  45296. this.animationIsPlaying = false;
  45297. if (!this.data.enabled) { return; }
  45298. if (!data.property) { return; }
  45299. // Base config.
  45300. config.autoplay = false;
  45301. config.direction = data.dir;
  45302. config.duration = data.dur;
  45303. config.easing = data.easing;
  45304. config.elasticity = data.elasticity;
  45305. config.loop = data.loop;
  45306. config.round = data.round;
  45307. // Start new animation.
  45308. this.createAndStartAnimation();
  45309. },
  45310. tick: function (t, dt) {
  45311. if (!this.animationIsPlaying) { return; }
  45312. this.time += dt;
  45313. this.animation.tick(this.time);
  45314. },
  45315. remove: function () {
  45316. this.pauseAnimation();
  45317. this.removeEventListeners();
  45318. },
  45319. pause: function () {
  45320. this.paused = true;
  45321. this.pausedWasPlaying = this.animationIsPlaying;
  45322. this.pauseAnimation();
  45323. this.removeEventListeners();
  45324. },
  45325. /**
  45326. * `play` handler only for resuming scene.
  45327. */
  45328. play: function () {
  45329. if (!this.paused) { return; }
  45330. this.paused = false;
  45331. this.addEventListeners();
  45332. if (this.pausedWasPlaying) {
  45333. this.resumeAnimation();
  45334. this.pausedWasPlaying = false;
  45335. }
  45336. },
  45337. /**
  45338. * Start animation from scratch.
  45339. */
  45340. createAndStartAnimation: function () {
  45341. var data = this.data;
  45342. this.updateConfig();
  45343. this.animationIsPlaying = false;
  45344. this.animation = anime(this.config);
  45345. this.animation.began = true;
  45346. this.removeEventListeners();
  45347. this.addEventListeners();
  45348. // Wait for start events for animation.
  45349. if (!data.autoplay || data.startEvents && data.startEvents.length) { return; }
  45350. // Delay animation.
  45351. if (data.delay) {
  45352. setTimeout(this.beginAnimation, data.delay);
  45353. return;
  45354. }
  45355. // Play animation.
  45356. this.beginAnimation();
  45357. },
  45358. /**
  45359. * This is before animation start (including from startEvents).
  45360. * Set to initial state (config.from, time = 0, seekTime = 0).
  45361. */
  45362. beginAnimation: function () {
  45363. this.updateConfig();
  45364. this.animation.began = true;
  45365. this.time = 0;
  45366. this.animationIsPlaying = true;
  45367. this.stopRelatedAnimations();
  45368. this.el.emit('animationbegin', this.eventDetail, false);
  45369. },
  45370. pauseAnimation: function () {
  45371. this.animationIsPlaying = false;
  45372. },
  45373. resumeAnimation: function () {
  45374. this.animationIsPlaying = true;
  45375. },
  45376. /**
  45377. * startEvents callback.
  45378. */
  45379. onStartEvent: function () {
  45380. if (!this.data.enabled) { return; }
  45381. this.updateConfig();
  45382. if (this.animation) {
  45383. this.animation.pause();
  45384. }
  45385. this.animation = anime(this.config);
  45386. // Include the delay before each start event.
  45387. if (this.data.delay) {
  45388. setTimeout(this.beginAnimation, this.data.delay);
  45389. return;
  45390. }
  45391. this.beginAnimation();
  45392. },
  45393. /**
  45394. * rawProperty: true and type: color;
  45395. */
  45396. updateConfigForRawColor: function () {
  45397. var config = this.config;
  45398. var data = this.data;
  45399. var el = this.el;
  45400. var from;
  45401. var key;
  45402. var to;
  45403. if (this.waitComponentInitRawProperty(this.updateConfigForRawColor)) {
  45404. return;
  45405. }
  45406. from = data.from === '' ? getRawProperty(el, data.property) : data.from;
  45407. to = data.to;
  45408. // Use r/g/b vector for color type.
  45409. this.setColorConfig(from, to);
  45410. from = this.fromColor;
  45411. to = this.toColor;
  45412. this.targetsArray.length = 0;
  45413. this.targetsArray.push(from);
  45414. config.targets = this.targetsArray;
  45415. for (key in to) { config[key] = to[key]; }
  45416. config.update = (function () {
  45417. var lastValue = {};
  45418. return function (anim) {
  45419. var value;
  45420. value = anim.animatables[0].target;
  45421. // For animation timeline.
  45422. if (value.r === lastValue.r &&
  45423. value.g === lastValue.g &&
  45424. value.b === lastValue.b) { return; }
  45425. setRawProperty(el, data.property, value, data.type);
  45426. };
  45427. })();
  45428. },
  45429. /**
  45430. * Stuff property into generic `property` key.
  45431. */
  45432. updateConfigForDefault: function () {
  45433. var config = this.config;
  45434. var data = this.data;
  45435. var el = this.el;
  45436. var from;
  45437. var isBoolean;
  45438. var isNumber;
  45439. var to;
  45440. if (this.waitComponentInitRawProperty(this.updateConfigForDefault)) {
  45441. return;
  45442. }
  45443. if (data.from === '') {
  45444. // Infer from.
  45445. from = isRawProperty(data)
  45446. ? getRawProperty(el, data.property)
  45447. : getComponentProperty(el, data.property);
  45448. } else {
  45449. // Explicit from.
  45450. from = data.from;
  45451. }
  45452. to = data.to;
  45453. isNumber = !isNaN(from || to);
  45454. if (isNumber) {
  45455. from = parseFloat(from);
  45456. to = parseFloat(to);
  45457. } else {
  45458. from = from ? from.toString() : from;
  45459. to = to ? to.toString() : to;
  45460. }
  45461. // Convert booleans to integer to allow boolean flipping.
  45462. isBoolean = data.to === 'true' || data.to === 'false' ||
  45463. data.to === true || data.to === false;
  45464. if (isBoolean) {
  45465. from = data.from === 'true' || data.from === true ? 1 : 0;
  45466. to = data.to === 'true' || data.to === true ? 1 : 0;
  45467. }
  45468. this.targets.aframeProperty = from;
  45469. config.targets = this.targets;
  45470. config.aframeProperty = to;
  45471. config.update = (function () {
  45472. var lastValue;
  45473. return function (anim) {
  45474. var value;
  45475. value = anim.animatables[0].target.aframeProperty;
  45476. // Need to do a last value check for animation timeline since all the tweening
  45477. // begins simultaenously even if the value has not changed. Also better for perf
  45478. // anyways.
  45479. if (value === lastValue) { return; }
  45480. lastValue = value;
  45481. if (isBoolean) { value = value >= 1; }
  45482. if (isRawProperty(data)) {
  45483. setRawProperty(el, data.property, value, data.type);
  45484. } else {
  45485. setComponentProperty(el, data.property, value);
  45486. }
  45487. };
  45488. })();
  45489. },
  45490. /**
  45491. * Extend x/y/z/w onto the config.
  45492. * Update vector by modifying object3D.
  45493. */
  45494. updateConfigForVector: function () {
  45495. var config = this.config;
  45496. var data = this.data;
  45497. var el = this.el;
  45498. var key;
  45499. var from;
  45500. var to;
  45501. // Parse coordinates.
  45502. from = data.from !== ''
  45503. ? utils.coordinates.parse(data.from) // If data.from defined, use that.
  45504. : getComponentProperty(el, data.property); // If data.from not defined, get on the fly.
  45505. to = utils.coordinates.parse(data.to);
  45506. if (data.property === PROP_ROTATION) {
  45507. toRadians(from);
  45508. toRadians(to);
  45509. }
  45510. // Set to and from.
  45511. this.targetsArray.length = 0;
  45512. this.targetsArray.push(from);
  45513. config.targets = this.targetsArray;
  45514. for (key in to) { config[key] = to[key]; }
  45515. // If animating object3D transformation, run more optimized updater.
  45516. if (data.property === PROP_POSITION || data.property === PROP_ROTATION ||
  45517. data.property === PROP_SCALE) {
  45518. config.update = (function () {
  45519. var lastValue = {};
  45520. return function (anim) {
  45521. var value = anim.animatables[0].target;
  45522. if (data.property === PROP_SCALE) {
  45523. value.x = Math.max(0.0001, value.x);
  45524. value.y = Math.max(0.0001, value.y);
  45525. value.z = Math.max(0.0001, value.z);
  45526. }
  45527. // For animation timeline.
  45528. if (value.x === lastValue.x &&
  45529. value.y === lastValue.y &&
  45530. value.z === lastValue.z) { return; }
  45531. lastValue.x = value.x;
  45532. lastValue.y = value.y;
  45533. lastValue.z = value.z;
  45534. el.object3D[data.property].set(value.x, value.y, value.z);
  45535. };
  45536. })();
  45537. return;
  45538. }
  45539. // Animating some vector.
  45540. config.update = (function () {
  45541. var lastValue = {};
  45542. return function (anim) {
  45543. var value = anim.animatables[0].target;
  45544. // Animate rotation through radians.
  45545. // For animation timeline.
  45546. if (value.x === lastValue.x &&
  45547. value.y === lastValue.y &&
  45548. value.z === lastValue.z) { return; }
  45549. lastValue.x = value.x;
  45550. lastValue.y = value.y;
  45551. lastValue.z = value.z;
  45552. setComponentProperty(el, data.property, value);
  45553. };
  45554. })();
  45555. },
  45556. /**
  45557. * Update the config before each run.
  45558. */
  45559. updateConfig: function () {
  45560. var propType;
  45561. // Route config type.
  45562. propType = getPropertyType(this.el, this.data.property);
  45563. if (isRawProperty(this.data) && this.data.type === TYPE_COLOR) {
  45564. this.updateConfigForRawColor();
  45565. } else if (propType === 'vec2' || propType === 'vec3' || propType === 'vec4') {
  45566. this.updateConfigForVector();
  45567. } else {
  45568. this.updateConfigForDefault();
  45569. }
  45570. },
  45571. /**
  45572. * Wait for component to initialize.
  45573. */
  45574. waitComponentInitRawProperty: function (cb) {
  45575. var componentName;
  45576. var data = this.data;
  45577. var el = this.el;
  45578. var self = this;
  45579. if (data.from !== '') { return false; }
  45580. if (!data.property.startsWith(STRING_COMPONENTS)) { return false; }
  45581. componentName = splitDot(data.property)[1];
  45582. if (el.components[componentName]) { return false; }
  45583. el.addEventListener('componentinitialized', function wait (evt) {
  45584. if (evt.detail.name !== componentName) { return; }
  45585. cb();
  45586. // Since the config was created async, create the animation now since we missed it
  45587. // earlier.
  45588. self.animation = anime(self.config);
  45589. el.removeEventListener('componentinitialized', wait);
  45590. });
  45591. return true;
  45592. },
  45593. /**
  45594. * Make sure two animations on the same property don't fight each other.
  45595. * e.g., animation__mouseenter="property: material.opacity"
  45596. * animation__mouseleave="property: material.opacity"
  45597. */
  45598. stopRelatedAnimations: function () {
  45599. var component;
  45600. var componentName;
  45601. for (componentName in this.el.components) {
  45602. component = this.el.components[componentName];
  45603. if (componentName === this.attrName) { continue; }
  45604. if (component.name !== 'animation') { continue; }
  45605. if (!component.animationIsPlaying) { continue; }
  45606. if (component.data.property !== this.data.property) { continue; }
  45607. component.animationIsPlaying = false;
  45608. }
  45609. },
  45610. addEventListeners: function () {
  45611. var data = this.data;
  45612. var el = this.el;
  45613. addEventListeners(el, data.startEvents, this.onStartEvent);
  45614. addEventListeners(el, data.pauseEvents, this.pauseAnimation);
  45615. addEventListeners(el, data.resumeEvents, this.resumeAnimation);
  45616. },
  45617. removeEventListeners: function () {
  45618. var data = this.data;
  45619. var el = this.el;
  45620. removeEventListeners(el, data.startEvents, this.onStartEvent);
  45621. removeEventListeners(el, data.pauseEvents, this.pauseAnimation);
  45622. removeEventListeners(el, data.resumeEvents, this.resumeAnimation);
  45623. },
  45624. setColorConfig: function (from, to) {
  45625. colorHelperFrom.set(from);
  45626. colorHelperTo.set(to);
  45627. from = this.fromColor;
  45628. to = this.toColor;
  45629. from.r = colorHelperFrom.r;
  45630. from.g = colorHelperFrom.g;
  45631. from.b = colorHelperFrom.b;
  45632. to.r = colorHelperTo.r;
  45633. to.g = colorHelperTo.g;
  45634. to.b = colorHelperTo.b;
  45635. }
  45636. });
  45637. /**
  45638. * Given property name, check schema to see what type we are animating.
  45639. * We just care whether the property is a vector.
  45640. */
  45641. function getPropertyType (el, property) {
  45642. var component;
  45643. var componentName;
  45644. var split;
  45645. var propertyName;
  45646. split = property.split('.');
  45647. componentName = split[0];
  45648. propertyName = split[1];
  45649. component = el.components[componentName] || components[componentName];
  45650. // Primitives.
  45651. if (!component) { return null; }
  45652. // Dynamic schema. We only care about vectors anyways.
  45653. if (propertyName && !component.schema[propertyName]) { return null; }
  45654. // Multi-prop.
  45655. if (propertyName) { return component.schema[propertyName].type; }
  45656. // Single-prop.
  45657. return component.schema.type;
  45658. }
  45659. /**
  45660. * Convert object to radians.
  45661. */
  45662. function toRadians (obj) {
  45663. obj.x = THREE.Math.degToRad(obj.x);
  45664. obj.y = THREE.Math.degToRad(obj.y);
  45665. obj.z = THREE.Math.degToRad(obj.z);
  45666. }
  45667. function addEventListeners (el, eventNames, handler) {
  45668. var i;
  45669. for (i = 0; i < eventNames.length; i++) {
  45670. el.addEventListener(eventNames[i], handler);
  45671. }
  45672. }
  45673. function removeEventListeners (el, eventNames, handler) {
  45674. var i;
  45675. for (i = 0; i < eventNames.length; i++) {
  45676. el.removeEventListener(eventNames[i], handler);
  45677. }
  45678. }
  45679. function getRawProperty (el, path) {
  45680. var i;
  45681. var split;
  45682. var value;
  45683. split = splitDot(path);
  45684. value = el;
  45685. for (i = 0; i < split.length; i++) {
  45686. value = value[split[i]];
  45687. }
  45688. if (value === undefined) {
  45689. console.log(el);
  45690. throw new Error('[animation] property (' + path + ') could not be found');
  45691. }
  45692. return value;
  45693. }
  45694. function setRawProperty (el, path, value, type) {
  45695. var i;
  45696. var split;
  45697. var propertyName;
  45698. var targetValue;
  45699. if (path.startsWith('object3D.rotation')) {
  45700. value = THREE.Math.degToRad(value);
  45701. }
  45702. // Walk.
  45703. split = splitDot(path);
  45704. targetValue = el;
  45705. for (i = 0; i < split.length - 1; i++) { targetValue = targetValue[split[i]]; }
  45706. propertyName = split[split.length - 1];
  45707. // Raw color.
  45708. if (type === TYPE_COLOR) {
  45709. if ('r' in targetValue[propertyName]) {
  45710. targetValue[propertyName].r = value.r;
  45711. targetValue[propertyName].g = value.g;
  45712. targetValue[propertyName].b = value.b;
  45713. } else {
  45714. targetValue[propertyName].x = value.r;
  45715. targetValue[propertyName].y = value.g;
  45716. targetValue[propertyName].z = value.b;
  45717. }
  45718. return;
  45719. }
  45720. targetValue[propertyName] = value;
  45721. }
  45722. function splitDot (path) {
  45723. if (path in splitCache) { return splitCache[path]; }
  45724. splitCache[path] = path.split('.');
  45725. return splitCache[path];
  45726. }
  45727. function isRawProperty (data) {
  45728. return data.isRawProperty || data.property.startsWith(STRING_COMPONENTS) ||
  45729. data.property.startsWith(STRING_OBJECT3D);
  45730. }
  45731. },{"../core/component":131,"../lib/three":179,"../utils":205,"super-animejs":56}],75:[function(_dereq_,module,exports){
  45732. var registerComponent = _dereq_('../core/component').registerComponent;
  45733. var THREE = _dereq_('../lib/three');
  45734. /**
  45735. * Camera component.
  45736. * Pairs along with camera system to handle tracking the active camera.
  45737. */
  45738. module.exports.Component = registerComponent('camera', {
  45739. schema: {
  45740. active: {default: true},
  45741. far: {default: 10000},
  45742. fov: {default: 80, min: 0},
  45743. near: {default: 0.005, min: 0},
  45744. spectator: {default: false},
  45745. zoom: {default: 1, min: 0}
  45746. },
  45747. /**
  45748. * Initialize three.js camera and add it to the entity.
  45749. * Add reference from scene to this entity as the camera.
  45750. */
  45751. init: function () {
  45752. var camera;
  45753. var el = this.el;
  45754. // Create camera.
  45755. camera = this.camera = new THREE.PerspectiveCamera();
  45756. el.setObject3D('camera', camera);
  45757. },
  45758. /**
  45759. * Update three.js camera.
  45760. */
  45761. update: function (oldData) {
  45762. var data = this.data;
  45763. var camera = this.camera;
  45764. // Update properties.
  45765. camera.aspect = data.aspect || (window.innerWidth / window.innerHeight);
  45766. camera.far = data.far;
  45767. camera.fov = data.fov;
  45768. camera.near = data.near;
  45769. camera.zoom = data.zoom;
  45770. camera.updateProjectionMatrix();
  45771. this.updateActiveCamera(oldData);
  45772. this.updateSpectatorCamera(oldData);
  45773. },
  45774. updateActiveCamera: function (oldData) {
  45775. var data = this.data;
  45776. var el = this.el;
  45777. var system = this.system;
  45778. // Active property did not change.
  45779. if (oldData && oldData.active === data.active || data.spectator) { return; }
  45780. // If `active` property changes, or first update, handle active camera with system.
  45781. if (data.active && system.activeCameraEl !== el) {
  45782. // Camera enabled. Set camera to this camera.
  45783. system.setActiveCamera(el);
  45784. } else if (!data.active && system.activeCameraEl === el) {
  45785. // Camera disabled. Set camera to another camera.
  45786. system.disableActiveCamera();
  45787. }
  45788. },
  45789. updateSpectatorCamera: function (oldData) {
  45790. var data = this.data;
  45791. var el = this.el;
  45792. var system = this.system;
  45793. // spectator property did not change.
  45794. if (oldData && oldData.spectator === data.spectator) { return; }
  45795. // If `spectator` property changes, or first update, handle spectator camera with system.
  45796. if (data.spectator && system.spectatorCameraEl !== el) {
  45797. // Camera enabled. Set camera to this camera.
  45798. system.setSpectatorCamera(el);
  45799. } else if (!data.spectator && system.spectatorCameraEl === el) {
  45800. // Camera disabled. Set camera to another camera.
  45801. system.disableSpectatorCamera();
  45802. }
  45803. },
  45804. /**
  45805. * Remove camera on remove (callback).
  45806. */
  45807. remove: function () {
  45808. this.el.removeObject3D('camera');
  45809. }
  45810. });
  45811. },{"../core/component":131,"../lib/three":179}],76:[function(_dereq_,module,exports){
  45812. /* global THREE */
  45813. var registerComponent = _dereq_('../core/component').registerComponent;
  45814. var utils = _dereq_('../utils/');
  45815. var bind = utils.bind;
  45816. var EVENTS = {
  45817. CLICK: 'click',
  45818. FUSING: 'fusing',
  45819. MOUSEENTER: 'mouseenter',
  45820. MOUSEDOWN: 'mousedown',
  45821. MOUSELEAVE: 'mouseleave',
  45822. MOUSEUP: 'mouseup'
  45823. };
  45824. var STATES = {
  45825. FUSING: 'cursor-fusing',
  45826. HOVERING: 'cursor-hovering',
  45827. HOVERED: 'cursor-hovered'
  45828. };
  45829. var CANVAS_EVENTS = {
  45830. DOWN: ['mousedown', 'touchstart'],
  45831. UP: ['mouseup', 'touchend']
  45832. };
  45833. var WEBXR_EVENTS = {
  45834. DOWN: ['selectstart'],
  45835. UP: ['selectend']
  45836. };
  45837. var CANVAS_HOVER_CLASS = 'a-mouse-cursor-hover';
  45838. /**
  45839. * Cursor component. Applies the raycaster component specifically for starting the raycaster
  45840. * from the camera and pointing from camera's facing direction, and then only returning the
  45841. * closest intersection. Cursor can be fine-tuned by setting raycaster properties.
  45842. *
  45843. * @member {object} fuseTimeout - Timeout to trigger fuse-click.
  45844. * @member {Element} cursorDownEl - Entity that was last mousedowned during current click.
  45845. * @member {object} intersection - Attributes of the current intersection event, including
  45846. * 3D- and 2D-space coordinates. See: http://threejs.org/docs/api/core/Raycaster.html
  45847. * @member {Element} intersectedEl - Currently-intersected entity. Used to keep track to
  45848. * emit events when unintersecting.
  45849. */
  45850. module.exports.Component = registerComponent('cursor', {
  45851. dependencies: ['raycaster'],
  45852. schema: {
  45853. downEvents: {default: []},
  45854. fuse: {default: utils.device.isMobile()},
  45855. fuseTimeout: {default: 1500, min: 0},
  45856. mouseCursorStylesEnabled: {default: true},
  45857. upEvents: {default: []},
  45858. rayOrigin: {default: 'entity', oneOf: ['mouse', 'entity']}
  45859. },
  45860. init: function () {
  45861. var self = this;
  45862. this.fuseTimeout = undefined;
  45863. this.cursorDownEl = null;
  45864. this.intersectedEl = null;
  45865. this.canvasBounds = document.body.getBoundingClientRect();
  45866. this.isCursorDown = false;
  45867. // Debounce.
  45868. this.updateCanvasBounds = utils.debounce(function updateCanvasBounds () {
  45869. self.canvasBounds = self.el.sceneEl.canvas.getBoundingClientRect();
  45870. }, 500);
  45871. this.eventDetail = {};
  45872. this.intersectedEventDetail = {cursorEl: this.el};
  45873. // Bind methods.
  45874. this.onCursorDown = bind(this.onCursorDown, this);
  45875. this.onCursorUp = bind(this.onCursorUp, this);
  45876. this.onIntersection = bind(this.onIntersection, this);
  45877. this.onIntersectionCleared = bind(this.onIntersectionCleared, this);
  45878. this.onMouseMove = bind(this.onMouseMove, this);
  45879. this.onEnterVR = bind(this.onEnterVR, this);
  45880. },
  45881. update: function (oldData) {
  45882. if (this.data.rayOrigin === oldData.rayOrigin) { return; }
  45883. this.updateMouseEventListeners();
  45884. },
  45885. play: function () {
  45886. this.addEventListeners();
  45887. },
  45888. pause: function () {
  45889. this.removeEventListeners();
  45890. },
  45891. remove: function () {
  45892. var el = this.el;
  45893. el.removeState(STATES.HOVERING);
  45894. el.removeState(STATES.FUSING);
  45895. clearTimeout(this.fuseTimeout);
  45896. if (this.intersectedEl) { this.intersectedEl.removeState(STATES.HOVERED); }
  45897. this.removeEventListeners();
  45898. },
  45899. addEventListeners: function () {
  45900. var canvas;
  45901. var data = this.data;
  45902. var el = this.el;
  45903. var self = this;
  45904. function addCanvasListeners () {
  45905. canvas = el.sceneEl.canvas;
  45906. if (data.downEvents.length || data.upEvents.length) { return; }
  45907. CANVAS_EVENTS.DOWN.forEach(function (downEvent) {
  45908. canvas.addEventListener(downEvent, self.onCursorDown);
  45909. });
  45910. CANVAS_EVENTS.UP.forEach(function (upEvent) {
  45911. canvas.addEventListener(upEvent, self.onCursorUp);
  45912. });
  45913. }
  45914. canvas = el.sceneEl.canvas;
  45915. if (canvas) {
  45916. addCanvasListeners();
  45917. } else {
  45918. el.sceneEl.addEventListener('render-target-loaded', addCanvasListeners);
  45919. }
  45920. data.downEvents.forEach(function (downEvent) {
  45921. el.addEventListener(downEvent, self.onCursorDown);
  45922. });
  45923. data.upEvents.forEach(function (upEvent) {
  45924. el.addEventListener(upEvent, self.onCursorUp);
  45925. });
  45926. el.addEventListener('raycaster-intersection', this.onIntersection);
  45927. el.addEventListener('raycaster-intersection-cleared', this.onIntersectionCleared);
  45928. el.sceneEl.addEventListener('rendererresize', this.updateCanvasBounds);
  45929. el.sceneEl.addEventListener('enter-vr', this.onEnterVR);
  45930. window.addEventListener('resize', this.updateCanvasBounds);
  45931. window.addEventListener('scroll', this.updateCanvasBounds);
  45932. this.updateMouseEventListeners();
  45933. },
  45934. removeEventListeners: function () {
  45935. var canvas;
  45936. var data = this.data;
  45937. var el = this.el;
  45938. var self = this;
  45939. canvas = el.sceneEl.canvas;
  45940. if (canvas && !data.downEvents.length && !data.upEvents.length) {
  45941. CANVAS_EVENTS.DOWN.forEach(function (downEvent) {
  45942. canvas.removeEventListener(downEvent, self.onCursorDown);
  45943. });
  45944. CANVAS_EVENTS.UP.forEach(function (upEvent) {
  45945. canvas.removeEventListener(upEvent, self.onCursorUp);
  45946. });
  45947. }
  45948. data.downEvents.forEach(function (downEvent) {
  45949. el.removeEventListener(downEvent, self.onCursorDown);
  45950. });
  45951. data.upEvents.forEach(function (upEvent) {
  45952. el.removeEventListener(upEvent, self.onCursorUp);
  45953. });
  45954. el.removeEventListener('raycaster-intersection', this.onIntersection);
  45955. el.removeEventListener('raycaster-intersection-cleared', this.onIntersectionCleared);
  45956. canvas.removeEventListener('mousemove', this.onMouseMove);
  45957. canvas.removeEventListener('touchstart', this.onMouseMove);
  45958. canvas.removeEventListener('touchmove', this.onMouseMove);
  45959. el.sceneEl.removeEventListener('rendererresize', this.updateCanvasBounds);
  45960. el.sceneEl.removeEventListener('enter-vr', this.onEnterVR);
  45961. window.removeEventListener('resize', this.updateCanvasBounds);
  45962. window.removeEventListener('scroll', this.updateCanvasBounds);
  45963. },
  45964. updateMouseEventListeners: function () {
  45965. var canvas;
  45966. var el = this.el;
  45967. canvas = el.sceneEl.canvas;
  45968. canvas.removeEventListener('mousemove', this.onMouseMove);
  45969. canvas.removeEventListener('touchmove', this.onMouseMove);
  45970. el.setAttribute('raycaster', 'useWorldCoordinates', false);
  45971. if (this.data.rayOrigin !== 'mouse') { return; }
  45972. canvas.addEventListener('mousemove', this.onMouseMove, false);
  45973. canvas.addEventListener('touchmove', this.onMouseMove, false);
  45974. el.setAttribute('raycaster', 'useWorldCoordinates', true);
  45975. this.updateCanvasBounds();
  45976. },
  45977. onMouseMove: (function () {
  45978. var direction = new THREE.Vector3();
  45979. var mouse = new THREE.Vector2();
  45980. var origin = new THREE.Vector3();
  45981. var rayCasterConfig = {origin: origin, direction: direction};
  45982. return function (evt) {
  45983. var bounds = this.canvasBounds;
  45984. var camera = this.el.sceneEl.camera;
  45985. var left;
  45986. var point;
  45987. var top;
  45988. camera.parent.updateMatrixWorld();
  45989. // Calculate mouse position based on the canvas element
  45990. if (evt.type === 'touchmove' || evt.type === 'touchstart') {
  45991. // Track the first touch for simplicity.
  45992. point = evt.touches.item(0);
  45993. } else {
  45994. point = evt;
  45995. }
  45996. left = point.clientX - bounds.left;
  45997. top = point.clientY - bounds.top;
  45998. mouse.x = (left / bounds.width) * 2 - 1;
  45999. mouse.y = -(top / bounds.height) * 2 + 1;
  46000. origin.setFromMatrixPosition(camera.matrixWorld);
  46001. direction.set(mouse.x, mouse.y, 0.5).unproject(camera).sub(origin).normalize();
  46002. this.el.setAttribute('raycaster', rayCasterConfig);
  46003. if (evt.type === 'touchmove') { evt.preventDefault(); }
  46004. };
  46005. })(),
  46006. /**
  46007. * Trigger mousedown and keep track of the mousedowned entity.
  46008. */
  46009. onCursorDown: function (evt) {
  46010. this.isCursorDown = true;
  46011. // Raycast again for touch.
  46012. if (this.data.rayOrigin === 'mouse' && evt.type === 'touchstart') {
  46013. this.onMouseMove(evt);
  46014. this.el.components.raycaster.checkIntersections();
  46015. evt.preventDefault();
  46016. }
  46017. this.twoWayEmit(EVENTS.MOUSEDOWN);
  46018. this.cursorDownEl = this.intersectedEl;
  46019. },
  46020. /**
  46021. * Trigger mouseup if:
  46022. * - Not fusing (mobile has no mouse).
  46023. * - Currently intersecting an entity.
  46024. * - Currently-intersected entity is the same as the one when mousedown was triggered,
  46025. * in case user mousedowned one entity, dragged to another, and mouseupped.
  46026. */
  46027. onCursorUp: function (evt) {
  46028. if (!this.isCursorDown) { return; }
  46029. this.isCursorDown = false;
  46030. var data = this.data;
  46031. this.twoWayEmit(EVENTS.MOUSEUP);
  46032. // If intersected entity has changed since the cursorDown, still emit mouseUp on the
  46033. // previously cursorUp entity.
  46034. if (this.cursorDownEl && this.cursorDownEl !== this.intersectedEl) {
  46035. this.intersectedEventDetail.intersection = null;
  46036. this.cursorDownEl.emit(EVENTS.MOUSEUP, this.intersectedEventDetail);
  46037. }
  46038. if ((!data.fuse || data.rayOrigin === 'mouse') &&
  46039. this.intersectedEl && this.cursorDownEl === this.intersectedEl) {
  46040. this.twoWayEmit(EVENTS.CLICK);
  46041. }
  46042. this.cursorDownEl = null;
  46043. if (evt.type === 'touchend') { evt.preventDefault(); }
  46044. },
  46045. /**
  46046. * Handle intersection.
  46047. */
  46048. onIntersection: function (evt) {
  46049. var currentIntersection;
  46050. var cursorEl = this.el;
  46051. var index;
  46052. var intersectedEl;
  46053. var intersection;
  46054. // Select closest object, excluding the cursor.
  46055. index = evt.detail.els[0] === cursorEl ? 1 : 0;
  46056. intersection = evt.detail.intersections[index];
  46057. intersectedEl = evt.detail.els[index];
  46058. // If cursor is the only intersected object, ignore the event.
  46059. if (!intersectedEl) { return; }
  46060. // Already intersecting this entity.
  46061. if (this.intersectedEl === intersectedEl) { return; }
  46062. // Ignore events further away than active intersection.
  46063. if (this.intersectedEl) {
  46064. currentIntersection = this.el.components.raycaster.getIntersection(this.intersectedEl);
  46065. if (currentIntersection && currentIntersection.distance <= intersection.distance) { return; }
  46066. }
  46067. // Unset current intersection.
  46068. this.clearCurrentIntersection(true);
  46069. this.setIntersection(intersectedEl, intersection);
  46070. },
  46071. /**
  46072. * Handle intersection cleared.
  46073. */
  46074. onIntersectionCleared: function (evt) {
  46075. var clearedEls = evt.detail.clearedEls;
  46076. // Check if the current intersection has ended
  46077. if (clearedEls.indexOf(this.intersectedEl) === -1) { return; }
  46078. this.clearCurrentIntersection();
  46079. },
  46080. onEnterVR: function () {
  46081. this.clearCurrentIntersection(true);
  46082. var xrSession = this.el.sceneEl.xrSession;
  46083. var self = this;
  46084. if (!xrSession) { return; }
  46085. if (this.data.rayOrigin === 'mouse') { return; }
  46086. WEBXR_EVENTS.DOWN.forEach(function (downEvent) {
  46087. xrSession.addEventListener(downEvent, self.onCursorDown);
  46088. });
  46089. WEBXR_EVENTS.UP.forEach(function (upEvent) {
  46090. xrSession.addEventListener(upEvent, self.onCursorUp);
  46091. });
  46092. },
  46093. setIntersection: function (intersectedEl, intersection) {
  46094. var cursorEl = this.el;
  46095. var data = this.data;
  46096. var self = this;
  46097. // Already intersecting.
  46098. if (this.intersectedEl === intersectedEl) { return; }
  46099. // Set new intersection.
  46100. this.intersectedEl = intersectedEl;
  46101. // Hovering.
  46102. cursorEl.addState(STATES.HOVERING);
  46103. intersectedEl.addState(STATES.HOVERED);
  46104. this.twoWayEmit(EVENTS.MOUSEENTER);
  46105. if (this.data.mouseCursorStylesEnabled && this.data.rayOrigin === 'mouse') {
  46106. this.el.sceneEl.canvas.classList.add(CANVAS_HOVER_CLASS);
  46107. }
  46108. // Begin fuse if necessary.
  46109. if (data.fuseTimeout === 0 || !data.fuse) { return; }
  46110. cursorEl.addState(STATES.FUSING);
  46111. this.twoWayEmit(EVENTS.FUSING);
  46112. this.fuseTimeout = setTimeout(function fuse () {
  46113. cursorEl.removeState(STATES.FUSING);
  46114. self.twoWayEmit(EVENTS.CLICK);
  46115. }, data.fuseTimeout);
  46116. },
  46117. clearCurrentIntersection: function (ignoreRemaining) {
  46118. var index;
  46119. var intersection;
  46120. var intersections;
  46121. var cursorEl = this.el;
  46122. // Nothing to be cleared.
  46123. if (!this.intersectedEl) { return; }
  46124. // No longer hovering (or fusing).
  46125. this.intersectedEl.removeState(STATES.HOVERED);
  46126. cursorEl.removeState(STATES.HOVERING);
  46127. cursorEl.removeState(STATES.FUSING);
  46128. this.twoWayEmit(EVENTS.MOUSELEAVE);
  46129. if (this.data.mouseCursorStylesEnabled && this.data.rayOrigin === 'mouse') {
  46130. this.el.sceneEl.canvas.classList.remove(CANVAS_HOVER_CLASS);
  46131. }
  46132. // Unset intersected entity (after emitting the event).
  46133. this.intersectedEl = null;
  46134. // Clear fuseTimeout.
  46135. clearTimeout(this.fuseTimeout);
  46136. // Set intersection to another raycasted element if any.
  46137. if (ignoreRemaining === true) { return; }
  46138. intersections = this.el.components.raycaster.intersections;
  46139. if (intersections.length === 0) { return; }
  46140. // Exclude the cursor.
  46141. index = intersections[0].object.el === cursorEl ? 1 : 0;
  46142. intersection = intersections[index];
  46143. if (!intersection) { return; }
  46144. this.setIntersection(intersection.object.el, intersection);
  46145. },
  46146. /**
  46147. * Helper to emit on both the cursor and the intersected entity (if exists).
  46148. */
  46149. twoWayEmit: function (evtName) {
  46150. var el = this.el;
  46151. var intersectedEl = this.intersectedEl;
  46152. var intersection;
  46153. intersection = this.el.components.raycaster.getIntersection(intersectedEl);
  46154. this.eventDetail.intersectedEl = intersectedEl;
  46155. this.eventDetail.intersection = intersection;
  46156. el.emit(evtName, this.eventDetail);
  46157. if (!intersectedEl) { return; }
  46158. this.intersectedEventDetail.intersection = intersection;
  46159. intersectedEl.emit(evtName, this.intersectedEventDetail);
  46160. }
  46161. });
  46162. },{"../core/component":131,"../utils/":205}],77:[function(_dereq_,module,exports){
  46163. var registerComponent = _dereq_('../core/component').registerComponent;
  46164. var bind = _dereq_('../utils/bind');
  46165. var trackedControlsUtils = _dereq_('../utils/tracked-controls');
  46166. var checkControllerPresentAndSetup = trackedControlsUtils.checkControllerPresentAndSetup;
  46167. var emitIfAxesChanged = trackedControlsUtils.emitIfAxesChanged;
  46168. var onButtonEvent = trackedControlsUtils.onButtonEvent;
  46169. var DAYDREAM_CONTROLLER_MODEL_BASE_URL = 'https://cdn.aframe.io/controllers/google/';
  46170. var DAYDREAM_CONTROLLER_MODEL_OBJ_URL = DAYDREAM_CONTROLLER_MODEL_BASE_URL + 'vr_controller_daydream.obj';
  46171. var DAYDREAM_CONTROLLER_MODEL_OBJ_MTL = DAYDREAM_CONTROLLER_MODEL_BASE_URL + 'vr_controller_daydream.mtl';
  46172. var isWebXRAvailable = _dereq_('../utils/').device.isWebXRAvailable;
  46173. var GAMEPAD_ID_WEBXR = 'google-daydream';
  46174. var GAMEPAD_ID_WEBVR = 'Daydream Controller';
  46175. var GAMEPAD_ID_PREFIX = isWebXRAvailable ? GAMEPAD_ID_WEBXR : GAMEPAD_ID_WEBVR;
  46176. /**
  46177. * Button indices:
  46178. * 0 - trackpad
  46179. * 1 - menu (never dispatched on this layer)
  46180. * 2 - system (never dispatched on this layer)
  46181. *
  46182. * Axis:
  46183. * 0 - trackpad x
  46184. * 1 - trackpad y
  46185. */
  46186. var INPUT_MAPPING_WEBVR = {
  46187. axes: {trackpad: [0, 1]},
  46188. buttons: ['trackpad', 'menu', 'system']
  46189. };
  46190. /**
  46191. * Button indices:
  46192. * 0 - none
  46193. * 1 - none
  46194. * 2 - touchpad
  46195. *
  46196. * Axis:
  46197. * 0 - touchpad x
  46198. * 1 - touchpad y
  46199. * Reference: https://github.com/immersive-web/webxr-input-profiles/blob/master/packages/registry/profiles/google/google-daydream.json
  46200. */
  46201. var INPUT_MAPPING_WEBXR = {
  46202. axes: {touchpad: [0, 1]},
  46203. buttons: ['none', 'none', 'touchpad', 'menu', 'system']
  46204. };
  46205. var INPUT_MAPPING = isWebXRAvailable ? INPUT_MAPPING_WEBXR : INPUT_MAPPING_WEBVR;
  46206. /**
  46207. * Daydream controls.
  46208. * Interface with Daydream controller and map Gamepad events to
  46209. * controller buttons: trackpad, menu, system
  46210. * Load a controller model and highlight the pressed buttons.
  46211. */
  46212. module.exports.Component = registerComponent('daydream-controls', {
  46213. schema: {
  46214. hand: {default: ''}, // This informs the degenerate arm model.
  46215. buttonColor: {type: 'color', default: '#000000'},
  46216. buttonTouchedColor: {type: 'color', default: '#777777'},
  46217. buttonHighlightColor: {type: 'color', default: '#FFFFFF'},
  46218. model: {default: true},
  46219. orientationOffset: {type: 'vec3'},
  46220. armModel: {default: true}
  46221. },
  46222. mapping: INPUT_MAPPING,
  46223. bindMethods: function () {
  46224. this.onModelLoaded = bind(this.onModelLoaded, this);
  46225. this.onControllersUpdate = bind(this.onControllersUpdate, this);
  46226. this.checkIfControllerPresent = bind(this.checkIfControllerPresent, this);
  46227. this.removeControllersUpdateListener = bind(this.removeControllersUpdateListener, this);
  46228. this.onAxisMoved = bind(this.onAxisMoved, this);
  46229. },
  46230. init: function () {
  46231. var self = this;
  46232. this.onButtonChanged = bind(this.onButtonChanged, this);
  46233. this.onButtonDown = function (evt) { onButtonEvent(evt.detail.id, 'down', self); };
  46234. this.onButtonUp = function (evt) { onButtonEvent(evt.detail.id, 'up', self); };
  46235. this.onButtonTouchStart = function (evt) { onButtonEvent(evt.detail.id, 'touchstart', self); };
  46236. this.onButtonTouchEnd = function (evt) { onButtonEvent(evt.detail.id, 'touchend', self); };
  46237. this.controllerPresent = false;
  46238. this.lastControllerCheck = 0;
  46239. this.bindMethods();
  46240. },
  46241. addEventListeners: function () {
  46242. var el = this.el;
  46243. el.addEventListener('buttonchanged', this.onButtonChanged);
  46244. el.addEventListener('buttondown', this.onButtonDown);
  46245. el.addEventListener('buttonup', this.onButtonUp);
  46246. el.addEventListener('touchstart', this.onButtonTouchStart);
  46247. el.addEventListener('touchend', this.onButtonTouchEnd);
  46248. el.addEventListener('model-loaded', this.onModelLoaded);
  46249. el.addEventListener('axismove', this.onAxisMoved);
  46250. this.controllerEventsActive = true;
  46251. },
  46252. removeEventListeners: function () {
  46253. var el = this.el;
  46254. el.removeEventListener('buttonchanged', this.onButtonChanged);
  46255. el.removeEventListener('buttondown', this.onButtonDown);
  46256. el.removeEventListener('buttonup', this.onButtonUp);
  46257. el.removeEventListener('touchstart', this.onButtonTouchStart);
  46258. el.removeEventListener('touchend', this.onButtonTouchEnd);
  46259. el.removeEventListener('model-loaded', this.onModelLoaded);
  46260. el.removeEventListener('axismove', this.onAxisMoved);
  46261. this.controllerEventsActive = false;
  46262. },
  46263. checkIfControllerPresent: function () {
  46264. checkControllerPresentAndSetup(this, GAMEPAD_ID_PREFIX,
  46265. this.data.hand ? {hand: this.data.hand} : {});
  46266. },
  46267. play: function () {
  46268. this.checkIfControllerPresent();
  46269. this.addControllersUpdateListener();
  46270. },
  46271. pause: function () {
  46272. this.removeEventListeners();
  46273. this.removeControllersUpdateListener();
  46274. },
  46275. injectTrackedControls: function () {
  46276. var el = this.el;
  46277. var data = this.data;
  46278. el.setAttribute('tracked-controls', {
  46279. armModel: data.armModel,
  46280. hand: data.hand,
  46281. idPrefix: GAMEPAD_ID_PREFIX,
  46282. id: GAMEPAD_ID_PREFIX,
  46283. orientationOffset: data.orientationOffset
  46284. });
  46285. if (!this.data.model) { return; }
  46286. this.el.setAttribute('obj-model', {
  46287. obj: DAYDREAM_CONTROLLER_MODEL_OBJ_URL,
  46288. mtl: DAYDREAM_CONTROLLER_MODEL_OBJ_MTL
  46289. });
  46290. },
  46291. addControllersUpdateListener: function () {
  46292. this.el.sceneEl.addEventListener('controllersupdated', this.onControllersUpdate, false);
  46293. },
  46294. removeControllersUpdateListener: function () {
  46295. this.el.sceneEl.removeEventListener('controllersupdated', this.onControllersUpdate, false);
  46296. },
  46297. onControllersUpdate: function () {
  46298. this.checkIfControllerPresent();
  46299. },
  46300. onModelLoaded: function (evt) {
  46301. var controllerObject3D = evt.detail.model;
  46302. var buttonMeshes;
  46303. if (!this.data.model) { return; }
  46304. buttonMeshes = this.buttonMeshes = {};
  46305. buttonMeshes.menu = controllerObject3D.getObjectByName('AppButton_AppButton_Cylinder.004');
  46306. buttonMeshes.system = controllerObject3D.getObjectByName('HomeButton_HomeButton_Cylinder.005');
  46307. buttonMeshes.trackpad = controllerObject3D.getObjectByName('TouchPad_TouchPad_Cylinder.003');
  46308. buttonMeshes.touchpad = controllerObject3D.getObjectByName('TouchPad_TouchPad_Cylinder.003');
  46309. // Offset pivot point.
  46310. controllerObject3D.position.set(0, 0, -0.04);
  46311. },
  46312. onAxisMoved: function (evt) {
  46313. emitIfAxesChanged(this, this.mapping.axes, evt);
  46314. },
  46315. onButtonChanged: function (evt) {
  46316. var button = this.mapping.buttons[evt.detail.id];
  46317. if (!button) return;
  46318. // Pass along changed event with button state, using button mapping for convenience.
  46319. this.el.emit(button + 'changed', evt.detail.state);
  46320. },
  46321. updateModel: function (buttonName, evtName) {
  46322. if (!this.data.model) { return; }
  46323. this.updateButtonModel(buttonName, evtName);
  46324. },
  46325. updateButtonModel: function (buttonName, state) {
  46326. var buttonMeshes = this.buttonMeshes;
  46327. if (!buttonMeshes || !buttonMeshes[buttonName]) { return; }
  46328. var color;
  46329. switch (state) {
  46330. case 'down':
  46331. color = this.data.buttonHighlightColor;
  46332. break;
  46333. case 'touchstart':
  46334. color = this.data.buttonTouchedColor;
  46335. break;
  46336. default:
  46337. color = this.data.buttonColor;
  46338. }
  46339. buttonMeshes[buttonName].material.color.set(color);
  46340. }
  46341. });
  46342. },{"../core/component":131,"../utils/":205,"../utils/bind":199,"../utils/tracked-controls":214}],78:[function(_dereq_,module,exports){
  46343. var registerComponent = _dereq_('../core/component').registerComponent;
  46344. var bind = _dereq_('../utils/bind');
  46345. var trackedControlsUtils = _dereq_('../utils/tracked-controls');
  46346. var checkControllerPresentAndSetup = trackedControlsUtils.checkControllerPresentAndSetup;
  46347. var emitIfAxesChanged = trackedControlsUtils.emitIfAxesChanged;
  46348. var onButtonEvent = trackedControlsUtils.onButtonEvent;
  46349. var isWebXRAvailable = _dereq_('../utils/').device.isWebXRAvailable;
  46350. var GEARVR_CONTROLLER_MODEL_BASE_URL = 'https://cdn.aframe.io/controllers/samsung/';
  46351. var GEARVR_CONTROLLER_MODEL_OBJ_URL = GEARVR_CONTROLLER_MODEL_BASE_URL + 'gear_vr_controller.obj';
  46352. var GEARVR_CONTROLLER_MODEL_OBJ_MTL = GEARVR_CONTROLLER_MODEL_BASE_URL + 'gear_vr_controller.mtl';
  46353. var GAMEPAD_ID_WEBXR = 'samsung-gearvr';
  46354. var GAMEPAD_ID_WEBVR = 'Gear VR';
  46355. // Prefix for Gen1 and Gen2 Oculus Touch Controllers.
  46356. var GAMEPAD_ID_PREFIX = isWebXRAvailable ? GAMEPAD_ID_WEBXR : GAMEPAD_ID_WEBVR;
  46357. /**
  46358. * Button indices:
  46359. * 0 - trackpad
  46360. * 1 - trigger
  46361. *
  46362. * Axis:
  46363. * 0 - trackpad x
  46364. * 1 - trackpad y
  46365. */
  46366. var INPUT_MAPPING_WEBVR = {
  46367. axes: {trackpad: [0, 1]},
  46368. buttons: ['trackpad', 'trigger']
  46369. };
  46370. /**
  46371. * Button indices:
  46372. * 0 - trigger
  46373. * 1 - none
  46374. * 2 - touchpad
  46375. * 3 - menu
  46376. *
  46377. * Axis:
  46378. * 0 - touchpad x
  46379. * 1 - touchpad y
  46380. * Reference: https://github.com/immersive-web/webxr-input-profiles/blob/master/packages/registry/profiles/samsung/samsung-gearvr.json
  46381. */
  46382. var INPUT_MAPPING_WEBXR = {
  46383. axes: {touchpad: [0, 1]},
  46384. buttons: ['trigger', 'none', 'touchpad', 'none', 'menu']
  46385. };
  46386. var INPUT_MAPPING = isWebXRAvailable ? INPUT_MAPPING_WEBXR : INPUT_MAPPING_WEBVR;
  46387. /**
  46388. * Gear VR controls.
  46389. * Interface with Gear VR controller and map Gamepad events to
  46390. * controller buttons: trackpad, trigger
  46391. * Load a controller model and highlight the pressed buttons.
  46392. */
  46393. module.exports.Component = registerComponent('gearvr-controls', {
  46394. schema: {
  46395. hand: {default: ''}, // This informs the degenerate arm model.
  46396. buttonColor: {type: 'color', default: '#000000'},
  46397. buttonTouchedColor: {type: 'color', default: '#777777'},
  46398. buttonHighlightColor: {type: 'color', default: '#FFFFFF'},
  46399. model: {default: true},
  46400. orientationOffset: {type: 'vec3'},
  46401. armModel: {default: true}
  46402. },
  46403. mapping: INPUT_MAPPING,
  46404. bindMethods: function () {
  46405. this.onModelLoaded = bind(this.onModelLoaded, this);
  46406. this.onControllersUpdate = bind(this.onControllersUpdate, this);
  46407. this.checkIfControllerPresent = bind(this.checkIfControllerPresent, this);
  46408. this.removeControllersUpdateListener = bind(this.removeControllersUpdateListener, this);
  46409. this.onAxisMoved = bind(this.onAxisMoved, this);
  46410. },
  46411. init: function () {
  46412. var self = this;
  46413. this.onButtonChanged = bind(this.onButtonChanged, this);
  46414. this.onButtonDown = function (evt) { onButtonEvent(evt.detail.id, 'down', self); };
  46415. this.onButtonUp = function (evt) { onButtonEvent(evt.detail.id, 'up', self); };
  46416. this.onButtonTouchStart = function (evt) { onButtonEvent(evt.detail.id, 'touchstart', self); };
  46417. this.onButtonTouchEnd = function (evt) { onButtonEvent(evt.detail.id, 'touchend', self); };
  46418. this.controllerPresent = false;
  46419. this.lastControllerCheck = 0;
  46420. this.bindMethods();
  46421. },
  46422. addEventListeners: function () {
  46423. var el = this.el;
  46424. el.addEventListener('buttonchanged', this.onButtonChanged);
  46425. el.addEventListener('buttondown', this.onButtonDown);
  46426. el.addEventListener('buttonup', this.onButtonUp);
  46427. el.addEventListener('touchstart', this.onButtonTouchStart);
  46428. el.addEventListener('touchend', this.onButtonTouchEnd);
  46429. el.addEventListener('model-loaded', this.onModelLoaded);
  46430. el.addEventListener('axismove', this.onAxisMoved);
  46431. this.controllerEventsActive = true;
  46432. },
  46433. removeEventListeners: function () {
  46434. var el = this.el;
  46435. el.removeEventListener('buttonchanged', this.onButtonChanged);
  46436. el.removeEventListener('buttondown', this.onButtonDown);
  46437. el.removeEventListener('buttonup', this.onButtonUp);
  46438. el.removeEventListener('touchstart', this.onButtonTouchStart);
  46439. el.removeEventListener('touchend', this.onButtonTouchEnd);
  46440. el.removeEventListener('model-loaded', this.onModelLoaded);
  46441. el.removeEventListener('axismove', this.onAxisMoved);
  46442. this.controllerEventsActive = false;
  46443. },
  46444. checkIfControllerPresent: function () {
  46445. checkControllerPresentAndSetup(this, GAMEPAD_ID_PREFIX,
  46446. this.data.hand ? {hand: this.data.hand} : {});
  46447. },
  46448. play: function () {
  46449. this.checkIfControllerPresent();
  46450. this.addControllersUpdateListener();
  46451. },
  46452. pause: function () {
  46453. this.removeEventListeners();
  46454. this.removeControllersUpdateListener();
  46455. },
  46456. injectTrackedControls: function () {
  46457. var el = this.el;
  46458. var data = this.data;
  46459. el.setAttribute('tracked-controls', {
  46460. armModel: data.armModel,
  46461. hand: data.hand,
  46462. idPrefix: GAMEPAD_ID_PREFIX,
  46463. id: GAMEPAD_ID_PREFIX,
  46464. orientationOffset: data.orientationOffset
  46465. });
  46466. if (!this.data.model) { return; }
  46467. this.el.setAttribute('obj-model', {
  46468. obj: GEARVR_CONTROLLER_MODEL_OBJ_URL,
  46469. mtl: GEARVR_CONTROLLER_MODEL_OBJ_MTL
  46470. });
  46471. },
  46472. addControllersUpdateListener: function () {
  46473. this.el.sceneEl.addEventListener('controllersupdated', this.onControllersUpdate, false);
  46474. },
  46475. removeControllersUpdateListener: function () {
  46476. this.el.sceneEl.removeEventListener('controllersupdated', this.onControllersUpdate, false);
  46477. },
  46478. onControllersUpdate: function () {
  46479. this.checkIfControllerPresent();
  46480. },
  46481. // No need for onButtonChanged, since Gear VR controller has no analog buttons.
  46482. onModelLoaded: function (evt) {
  46483. var controllerObject3D = evt.detail.model;
  46484. var buttonMeshes;
  46485. if (!this.data.model) { return; }
  46486. buttonMeshes = this.buttonMeshes = {};
  46487. buttonMeshes.trigger = controllerObject3D.children[2];
  46488. buttonMeshes.trackpad = controllerObject3D.children[1];
  46489. buttonMeshes.touchpad = controllerObject3D.children[1];
  46490. },
  46491. onButtonChanged: function (evt) {
  46492. var button = this.mapping.buttons[evt.detail.id];
  46493. if (!button) return;
  46494. // Pass along changed event with button state, using button mapping for convenience.
  46495. this.el.emit(button + 'changed', evt.detail.state);
  46496. },
  46497. onAxisMoved: function (evt) {
  46498. emitIfAxesChanged(this, this.mapping.axes, evt);
  46499. },
  46500. updateModel: function (buttonName, evtName) {
  46501. if (!this.data.model) { return; }
  46502. this.updateButtonModel(buttonName, evtName);
  46503. },
  46504. updateButtonModel: function (buttonName, state) {
  46505. var buttonMeshes = this.buttonMeshes;
  46506. if (!buttonMeshes || !buttonMeshes[buttonName]) { return; }
  46507. var color;
  46508. switch (state) {
  46509. case 'down':
  46510. color = this.data.buttonHighlightColor;
  46511. break;
  46512. case 'touchstart':
  46513. color = this.data.buttonTouchedColor;
  46514. break;
  46515. default:
  46516. color = this.data.buttonColor;
  46517. }
  46518. buttonMeshes[buttonName].material.color.set(color);
  46519. }
  46520. });
  46521. },{"../core/component":131,"../utils/":205,"../utils/bind":199,"../utils/tracked-controls":214}],79:[function(_dereq_,module,exports){
  46522. var registerComponent = _dereq_('../core/component').registerComponent;
  46523. var bind = _dereq_('../utils/bind');
  46524. var trackedControlsUtils = _dereq_('../utils/tracked-controls');
  46525. var checkControllerPresentAndSetup = trackedControlsUtils.checkControllerPresentAndSetup;
  46526. var emitIfAxesChanged = trackedControlsUtils.emitIfAxesChanged;
  46527. var onButtonEvent = trackedControlsUtils.onButtonEvent;
  46528. var GAMEPAD_ID_PREFIX = 'generic';
  46529. /**
  46530. * Button indices:
  46531. * 0 - trigger
  46532. * 1 - squeeze
  46533. * 2 - touchpad
  46534. * 3 - thumbstick
  46535. *
  46536. * Axis:
  46537. * 0 - touchpad
  46538. * 1 - thumbstick
  46539. *
  46540. */
  46541. var INPUT_MAPPING = {
  46542. axes: {
  46543. touchpad: [0, 1],
  46544. thumbstick: [2, 3]
  46545. },
  46546. buttons: ['trigger', 'squeeze', 'touchpad', 'thumbstick']
  46547. };
  46548. /**
  46549. * Oculus Go controls.
  46550. * Interface with Oculus Go controller and map Gamepad events to
  46551. * controller buttons: trackpad, trigger
  46552. * Load a controller model and highlight the pressed buttons.
  46553. */
  46554. module.exports.Component = registerComponent('generic-tracked-controller-controls', {
  46555. schema: {
  46556. hand: {default: ''}, // This informs the degenerate arm model.
  46557. defaultModel: {default: true},
  46558. defaultModelColor: {default: 'gray'},
  46559. orientationOffset: {type: 'vec3'},
  46560. disabled: {default: false}
  46561. },
  46562. /**
  46563. * Button IDs:
  46564. * 0 - trackpad
  46565. * 1 - trigger
  46566. */
  46567. mapping: INPUT_MAPPING,
  46568. bindMethods: function () {
  46569. this.onControllersUpdate = bind(this.onControllersUpdate, this);
  46570. this.checkIfControllerPresent = bind(this.checkIfControllerPresent, this);
  46571. this.removeControllersUpdateListener = bind(this.removeControllersUpdateListener, this);
  46572. this.onAxisMoved = bind(this.onAxisMoved, this);
  46573. },
  46574. init: function () {
  46575. var self = this;
  46576. this.onButtonChanged = bind(this.onButtonChanged, this);
  46577. this.onButtonDown = function (evt) { onButtonEvent(evt.detail.id, 'down', self); };
  46578. this.onButtonUp = function (evt) { onButtonEvent(evt.detail.id, 'up', self); };
  46579. this.onButtonTouchStart = function (evt) { onButtonEvent(evt.detail.id, 'touchstart', self); };
  46580. this.onButtonTouchEnd = function (evt) { onButtonEvent(evt.detail.id, 'touchend', self); };
  46581. this.controllerPresent = false;
  46582. this.wasControllerConnected = false;
  46583. this.lastControllerCheck = 0;
  46584. this.rendererSystem = this.el.sceneEl.systems.renderer;
  46585. this.bindMethods();
  46586. // generic-tracked-controller-controls has the lowest precedence.
  46587. // We must diable this component if there are more specialized controls components.
  46588. this.el.addEventListener('controllerconnected', function (evt) {
  46589. if (evt.detail.name === self.name) { return; }
  46590. self.wasControllerConnected = true;
  46591. self.removeEventListeners();
  46592. self.removeControllersUpdateListener();
  46593. });
  46594. },
  46595. addEventListeners: function () {
  46596. var el = this.el;
  46597. el.addEventListener('buttonchanged', this.onButtonChanged);
  46598. el.addEventListener('buttondown', this.onButtonDown);
  46599. el.addEventListener('buttonup', this.onButtonUp);
  46600. el.addEventListener('touchstart', this.onButtonTouchStart);
  46601. el.addEventListener('touchend', this.onButtonTouchEnd);
  46602. el.addEventListener('axismove', this.onAxisMoved);
  46603. this.controllerEventsActive = true;
  46604. },
  46605. removeEventListeners: function () {
  46606. var el = this.el;
  46607. el.removeEventListener('buttonchanged', this.onButtonChanged);
  46608. el.removeEventListener('buttondown', this.onButtonDown);
  46609. el.removeEventListener('buttonup', this.onButtonUp);
  46610. el.removeEventListener('touchstart', this.onButtonTouchStart);
  46611. el.removeEventListener('touchend', this.onButtonTouchEnd);
  46612. el.removeEventListener('axismove', this.onAxisMoved);
  46613. this.controllerEventsActive = false;
  46614. },
  46615. checkIfControllerPresent: function () {
  46616. var data = this.data;
  46617. var hand = data.hand ? data.hand : undefined;
  46618. checkControllerPresentAndSetup(
  46619. this, GAMEPAD_ID_PREFIX,
  46620. {hand: hand, iterateControllerProfiles: true});
  46621. },
  46622. play: function () {
  46623. if (this.wasControllerConnected) { return; }
  46624. this.checkIfControllerPresent();
  46625. this.addControllersUpdateListener();
  46626. },
  46627. pause: function () {
  46628. this.removeEventListeners();
  46629. this.removeControllersUpdateListener();
  46630. },
  46631. injectTrackedControls: function () {
  46632. var el = this.el;
  46633. var data = this.data;
  46634. // Do nothing if tracked-controls already set.
  46635. // Generic controls have the lowest precedence.
  46636. if (this.el.components['tracked-controls']) {
  46637. this.removeEventListeners();
  46638. return;
  46639. }
  46640. el.setAttribute('tracked-controls', {
  46641. hand: data.hand,
  46642. idPrefix: GAMEPAD_ID_PREFIX,
  46643. orientationOffset: data.orientationOffset,
  46644. iterateControllerProfiles: true
  46645. });
  46646. if (!this.data.defaultModel) { return; }
  46647. this.initDefaultModel();
  46648. },
  46649. addControllersUpdateListener: function () {
  46650. this.el.sceneEl.addEventListener('controllersupdated', this.onControllersUpdate, false);
  46651. },
  46652. removeControllersUpdateListener: function () {
  46653. this.el.sceneEl.removeEventListener('controllersupdated', this.onControllersUpdate, false);
  46654. },
  46655. onControllersUpdate: function () {
  46656. this.checkIfControllerPresent();
  46657. },
  46658. onButtonChanged: function (evt) {
  46659. var button = this.mapping.buttons[evt.detail.id];
  46660. if (!button) return;
  46661. // Pass along changed event with button state, using button mapping for convenience.
  46662. this.el.emit(button + 'changed', evt.detail.state);
  46663. },
  46664. onAxisMoved: function (evt) {
  46665. emitIfAxesChanged(this, this.mapping.axes, evt);
  46666. },
  46667. initDefaultModel: function () {
  46668. var modelEl = this.modelEl = document.createElement('a-entity');
  46669. modelEl.setAttribute('geometry', {
  46670. primitive: 'sphere',
  46671. radius: 0.03
  46672. });
  46673. modelEl.setAttribute('material', {color: this.data.color});
  46674. this.el.appendChild(modelEl);
  46675. }
  46676. });
  46677. },{"../core/component":131,"../utils/bind":199,"../utils/tracked-controls":214}],80:[function(_dereq_,module,exports){
  46678. var geometries = _dereq_('../core/geometry').geometries;
  46679. var geometryNames = _dereq_('../core/geometry').geometryNames;
  46680. var registerComponent = _dereq_('../core/component').registerComponent;
  46681. var THREE = _dereq_('../lib/three');
  46682. var dummyGeometry = new THREE.BufferGeometry();
  46683. /**
  46684. * Geometry component. Combined with material component to make a mesh in 3D object.
  46685. * Extended with registered geometries.
  46686. */
  46687. module.exports.Component = registerComponent('geometry', {
  46688. schema: {
  46689. buffer: {default: true},
  46690. primitive: {default: 'box', oneOf: geometryNames, schemaChange: true},
  46691. skipCache: {default: false}
  46692. },
  46693. init: function () {
  46694. this.geometry = null;
  46695. },
  46696. /**
  46697. * Talk to geometry system to get or create geometry.
  46698. */
  46699. update: function (previousData) {
  46700. var data = this.data;
  46701. var el = this.el;
  46702. var mesh;
  46703. var system = this.system;
  46704. // Dispose old geometry if we created one.
  46705. if (this.geometry) {
  46706. system.unuseGeometry(previousData);
  46707. this.geometry = null;
  46708. }
  46709. // Create new geometry.
  46710. this.geometry = system.getOrCreateGeometry(data);
  46711. // Set on mesh. If mesh does not exist, create it.
  46712. mesh = el.getObject3D('mesh');
  46713. if (mesh) {
  46714. mesh.geometry = this.geometry;
  46715. } else {
  46716. mesh = new THREE.Mesh();
  46717. mesh.geometry = this.geometry;
  46718. // Default material if not defined on the entity.
  46719. if (!this.el.getAttribute('material')) {
  46720. mesh.material = new THREE.MeshStandardMaterial({
  46721. color: Math.random() * 0xFFFFFF,
  46722. metalness: 0,
  46723. roughness: 0.5
  46724. });
  46725. }
  46726. el.setObject3D('mesh', mesh);
  46727. }
  46728. },
  46729. /**
  46730. * Tell geometry system that entity is no longer using the geometry.
  46731. * Unset the geometry on the mesh
  46732. */
  46733. remove: function () {
  46734. this.system.unuseGeometry(this.data);
  46735. this.el.getObject3D('mesh').geometry = dummyGeometry;
  46736. this.geometry = null;
  46737. },
  46738. /**
  46739. * Update geometry component schema based on geometry type.
  46740. */
  46741. updateSchema: function (data) {
  46742. var currentGeometryType = this.oldData && this.oldData.primitive;
  46743. var newGeometryType = data.primitive;
  46744. var schema = geometries[newGeometryType] && geometries[newGeometryType].schema;
  46745. // Geometry has no schema.
  46746. if (!schema) { throw new Error('Unknown geometry schema `' + newGeometryType + '`'); }
  46747. // Nothing has changed.
  46748. if (currentGeometryType && currentGeometryType === newGeometryType) { return; }
  46749. this.extendSchema(schema);
  46750. }
  46751. });
  46752. },{"../core/component":131,"../core/geometry":132,"../lib/three":179}],81:[function(_dereq_,module,exports){
  46753. var registerComponent = _dereq_('../core/component').registerComponent;
  46754. var THREE = _dereq_('../lib/three');
  46755. var utils = _dereq_('../utils/');
  46756. var warn = utils.debug('components:gltf-model:warn');
  46757. /**
  46758. * glTF model loader.
  46759. */
  46760. module.exports.Component = registerComponent('gltf-model', {
  46761. schema: {type: 'model'},
  46762. init: function () {
  46763. var dracoLoader = this.system.getDRACOLoader();
  46764. this.model = null;
  46765. this.loader = new THREE.GLTFLoader();
  46766. if (dracoLoader) {
  46767. this.loader.setDRACOLoader(dracoLoader);
  46768. }
  46769. },
  46770. update: function () {
  46771. var self = this;
  46772. var el = this.el;
  46773. var src = this.data;
  46774. if (!src) { return; }
  46775. this.remove();
  46776. this.loader.load(src, function gltfLoaded (gltfModel) {
  46777. self.model = gltfModel.scene || gltfModel.scenes[0];
  46778. self.model.animations = gltfModel.animations;
  46779. el.setObject3D('mesh', self.model);
  46780. el.emit('model-loaded', {format: 'gltf', model: self.model});
  46781. }, undefined /* onProgress */, function gltfFailed (error) {
  46782. var message = (error && error.message) ? error.message : 'Failed to load glTF model';
  46783. warn(message);
  46784. el.emit('model-error', {format: 'gltf', src: src});
  46785. });
  46786. },
  46787. remove: function () {
  46788. if (!this.model) { return; }
  46789. this.el.removeObject3D('mesh');
  46790. }
  46791. });
  46792. },{"../core/component":131,"../lib/three":179,"../utils/":205}],82:[function(_dereq_,module,exports){
  46793. /* global THREE */
  46794. var registerComponent = _dereq_('../core/component').registerComponent;
  46795. // Found at https://github.com/aframevr/assets.
  46796. var MODEL_URLS = {
  46797. toonLeft: 'https://cdn.aframe.io/controllers/hands/leftHand.glb',
  46798. toonRight: 'https://cdn.aframe.io/controllers/hands/rightHand.glb',
  46799. lowPolyLeft: 'https://cdn.aframe.io/controllers/hands/leftHandLow.glb',
  46800. lowPolyRight: 'https://cdn.aframe.io/controllers/hands/rightHandLow.glb',
  46801. highPolyLeft: 'https://cdn.aframe.io/controllers/hands/leftHandHigh.glb',
  46802. highPolyRight: 'https://cdn.aframe.io/controllers/hands/rightHandHigh.glb'
  46803. };
  46804. // Poses.
  46805. var ANIMATIONS = {
  46806. open: 'Open',
  46807. // point: grip active, trackpad surface active, trigger inactive.
  46808. point: 'Point',
  46809. // pointThumb: grip active, trigger inactive, trackpad surface inactive.
  46810. pointThumb: 'Point + Thumb',
  46811. // fist: grip active, trigger active, trackpad surface active.
  46812. fist: 'Fist',
  46813. // hold: trigger active, grip inactive.
  46814. hold: 'Hold',
  46815. // thumbUp: grip active, trigger active, trackpad surface inactive.
  46816. thumbUp: 'Thumb Up'
  46817. };
  46818. // Map animation to public events for the API.
  46819. var EVENTS = {};
  46820. EVENTS[ANIMATIONS.fist] = 'grip';
  46821. EVENTS[ANIMATIONS.thumbUp] = 'pistol';
  46822. EVENTS[ANIMATIONS.point] = 'pointing';
  46823. /**
  46824. * Hand controls component that abstracts 6DoF controls:
  46825. * oculus-touch-controls, vive-controls, windows-motion-controls.
  46826. *
  46827. * Originally meant to be a sample implementation of applications-specific controls that
  46828. * abstracts multiple types of controllers.
  46829. *
  46830. * Auto-detect appropriate controller.
  46831. * Handle common events coming from the detected vendor-specific controls.
  46832. * Translate button events to semantic hand-related event names:
  46833. * (gripclose, gripopen, thumbup, thumbdown, pointup, pointdown)
  46834. * Load hand model with gestures that are applied based on the button pressed.
  46835. *
  46836. * @property {string} Hand mapping (`left`, `right`).
  46837. */
  46838. module.exports.Component = registerComponent('hand-controls', {
  46839. schema: {
  46840. color: {default: 'white', type: 'color'},
  46841. hand: { default: 'left' },
  46842. handModelStyle: {default: 'lowPoly', oneOf: ['lowPoly', 'highPoly', 'toon']}
  46843. },
  46844. init: function () {
  46845. var self = this;
  46846. var el = this.el;
  46847. // Current pose.
  46848. this.gesture = ANIMATIONS.open;
  46849. // Active buttons populated by events provided by the attached controls.
  46850. this.pressedButtons = {};
  46851. this.touchedButtons = {};
  46852. this.loader = new THREE.GLTFLoader();
  46853. this.loader.setCrossOrigin('anonymous');
  46854. this.onGripDown = function () { self.handleButton('grip', 'down'); };
  46855. this.onGripUp = function () { self.handleButton('grip', 'up'); };
  46856. this.onTrackpadDown = function () { self.handleButton('trackpad', 'down'); };
  46857. this.onTrackpadUp = function () { self.handleButton('trackpad', 'up'); };
  46858. this.onTrackpadTouchStart = function () { self.handleButton('trackpad', 'touchstart'); };
  46859. this.onTrackpadTouchEnd = function () { self.handleButton('trackpad', 'touchend'); };
  46860. this.onTriggerDown = function () { self.handleButton('trigger', 'down'); };
  46861. this.onTriggerUp = function () { self.handleButton('trigger', 'up'); };
  46862. this.onTriggerTouchStart = function () { self.handleButton('trigger', 'touchstart'); };
  46863. this.onTriggerTouchEnd = function () { self.handleButton('trigger', 'touchend'); };
  46864. this.onGripTouchStart = function () { self.handleButton('grip', 'touchstart'); };
  46865. this.onGripTouchEnd = function () { self.handleButton('grip', 'touchend'); };
  46866. this.onThumbstickDown = function () { self.handleButton('thumbstick', 'down'); };
  46867. this.onThumbstickUp = function () { self.handleButton('thumbstick', 'up'); };
  46868. this.onAorXTouchStart = function () { self.handleButton('AorX', 'touchstart'); };
  46869. this.onAorXTouchEnd = function () { self.handleButton('AorX', 'touchend'); };
  46870. this.onBorYTouchStart = function () { self.handleButton('BorY', 'touchstart'); };
  46871. this.onBorYTouchEnd = function () { self.handleButton('BorY', 'touchend'); };
  46872. this.onSurfaceTouchStart = function () { self.handleButton('surface', 'touchstart'); };
  46873. this.onSurfaceTouchEnd = function () { self.handleButton('surface', 'touchend'); };
  46874. this.onControllerConnected = this.onControllerConnected.bind(this);
  46875. this.onControllerDisconnected = this.onControllerDisconnected.bind(this);
  46876. el.addEventListener('controllerconnected', this.onControllerConnected);
  46877. el.addEventListener('controllerdisconnected', this.onControllerDisconnected);
  46878. // Hidden by default.
  46879. el.object3D.visible = false;
  46880. },
  46881. play: function () {
  46882. this.addEventListeners();
  46883. },
  46884. pause: function () {
  46885. this.removeEventListeners();
  46886. },
  46887. tick: function (time, delta) {
  46888. var mesh = this.el.getObject3D('mesh');
  46889. if (!mesh || !mesh.mixer) { return; }
  46890. mesh.mixer.update(delta / 1000);
  46891. },
  46892. onControllerConnected: function () {
  46893. this.el.object3D.visible = true;
  46894. },
  46895. onControllerDisconnected: function () {
  46896. this.el.object3D.visible = false;
  46897. },
  46898. addEventListeners: function () {
  46899. var el = this.el;
  46900. el.addEventListener('gripdown', this.onGripDown);
  46901. el.addEventListener('gripup', this.onGripUp);
  46902. el.addEventListener('trackpaddown', this.onTrackpadDown);
  46903. el.addEventListener('trackpadup', this.onTrackpadUp);
  46904. el.addEventListener('trackpadtouchstart', this.onTrackpadTouchStart);
  46905. el.addEventListener('trackpadtouchend', this.onTrackpadTouchEnd);
  46906. el.addEventListener('triggerdown', this.onTriggerDown);
  46907. el.addEventListener('triggerup', this.onTriggerUp);
  46908. el.addEventListener('triggertouchstart', this.onTriggerTouchStart);
  46909. el.addEventListener('triggertouchend', this.onTriggerTouchEnd);
  46910. el.addEventListener('griptouchstart', this.onGripTouchStart);
  46911. el.addEventListener('griptouchend', this.onGripTouchEnd);
  46912. el.addEventListener('thumbstickdown', this.onThumbstickDown);
  46913. el.addEventListener('thumbstickup', this.onThumbstickUp);
  46914. el.addEventListener('abuttontouchstart', this.onAorXTouchStart);
  46915. el.addEventListener('abuttontouchend', this.onAorXTouchEnd);
  46916. el.addEventListener('bbuttontouchstart', this.onBorYTouchStart);
  46917. el.addEventListener('bbuttontouchend', this.onBorYTouchEnd);
  46918. el.addEventListener('xbuttontouchstart', this.onAorXTouchStart);
  46919. el.addEventListener('xbuttontouchend', this.onAorXTouchEnd);
  46920. el.addEventListener('ybuttontouchstart', this.onBorYTouchStart);
  46921. el.addEventListener('ybuttontouchend', this.onBorYTouchEnd);
  46922. el.addEventListener('surfacetouchstart', this.onSurfaceTouchStart);
  46923. el.addEventListener('surfacetouchend', this.onSurfaceTouchEnd);
  46924. },
  46925. removeEventListeners: function () {
  46926. var el = this.el;
  46927. el.removeEventListener('gripdown', this.onGripDown);
  46928. el.removeEventListener('gripup', this.onGripUp);
  46929. el.removeEventListener('trackpaddown', this.onTrackpadDown);
  46930. el.removeEventListener('trackpadup', this.onTrackpadUp);
  46931. el.removeEventListener('trackpadtouchstart', this.onTrackpadTouchStart);
  46932. el.removeEventListener('trackpadtouchend', this.onTrackpadTouchEnd);
  46933. el.removeEventListener('triggerdown', this.onTriggerDown);
  46934. el.removeEventListener('triggerup', this.onTriggerUp);
  46935. el.removeEventListener('triggertouchstart', this.onTriggerTouchStart);
  46936. el.removeEventListener('triggertouchend', this.onTriggerTouchEnd);
  46937. el.removeEventListener('griptouchstart', this.onGripTouchStart);
  46938. el.removeEventListener('griptouchend', this.onGripTouchEnd);
  46939. el.removeEventListener('thumbstickdown', this.onThumbstickDown);
  46940. el.removeEventListener('thumbstickup', this.onThumbstickUp);
  46941. el.removeEventListener('abuttontouchstart', this.onAorXTouchStart);
  46942. el.removeEventListener('abuttontouchend', this.onAorXTouchEnd);
  46943. el.removeEventListener('bbuttontouchstart', this.onBorYTouchStart);
  46944. el.removeEventListener('bbuttontouchend', this.onBorYTouchEnd);
  46945. el.removeEventListener('xbuttontouchstart', this.onAorXTouchStart);
  46946. el.removeEventListener('xbuttontouchend', this.onAorXTouchEnd);
  46947. el.removeEventListener('ybuttontouchstart', this.onBorYTouchStart);
  46948. el.removeEventListener('ybuttontouchend', this.onBorYTouchEnd);
  46949. el.removeEventListener('surfacetouchstart', this.onSurfaceTouchStart);
  46950. el.removeEventListener('surfacetouchend', this.onSurfaceTouchEnd);
  46951. },
  46952. /**
  46953. * Update handler. More like the `init` handler since the only property is the hand, and
  46954. * that won't be changing much.
  46955. */
  46956. update: function (previousHand) {
  46957. var controlConfiguration;
  46958. var el = this.el;
  46959. var hand = this.data.hand;
  46960. var handModelStyle = this.data.handModelStyle;
  46961. var handColor = this.data.color;
  46962. var self = this;
  46963. // Get common configuration to abstract different vendor controls.
  46964. controlConfiguration = {
  46965. hand: hand,
  46966. model: false
  46967. };
  46968. // Set model.
  46969. if (hand !== previousHand) {
  46970. var handmodelUrl = MODEL_URLS[handModelStyle + hand.charAt(0).toUpperCase() + hand.slice(1)];
  46971. this.loader.load(handmodelUrl, function (gltf) {
  46972. var mesh = gltf.scene.children[0];
  46973. var handModelOrientation = hand === 'left' ? Math.PI / 2 : -Math.PI / 2;
  46974. mesh.mixer = new THREE.AnimationMixer(mesh);
  46975. self.clips = gltf.animations;
  46976. el.setObject3D('mesh', mesh);
  46977. var handMaterial = mesh.children[1].material;
  46978. handMaterial.color = new THREE.Color(handColor);
  46979. mesh.position.set(0, 0, 0);
  46980. mesh.rotation.set(0, 0, handModelOrientation);
  46981. el.setAttribute('magicleap-controls', controlConfiguration);
  46982. el.setAttribute('vive-controls', controlConfiguration);
  46983. el.setAttribute('oculus-touch-controls', controlConfiguration);
  46984. el.setAttribute('windows-motion-controls', controlConfiguration);
  46985. });
  46986. }
  46987. },
  46988. remove: function () {
  46989. this.el.removeObject3D('mesh');
  46990. },
  46991. /**
  46992. * Play model animation, based on which button was pressed and which kind of event.
  46993. *
  46994. * 1. Process buttons.
  46995. * 2. Determine gesture (this.determineGesture()).
  46996. * 3. Animation gesture (this.animationGesture()).
  46997. * 4. Emit gesture events (this.emitGestureEvents()).
  46998. *
  46999. * @param {string} button - Name of the button.
  47000. * @param {string} evt - Type of event for the button (i.e., down/up/touchstart/touchend).
  47001. */
  47002. handleButton: function (button, evt) {
  47003. var lastGesture;
  47004. var isPressed = evt === 'down';
  47005. var isTouched = evt === 'touchstart';
  47006. // Update objects.
  47007. if (evt.indexOf('touch') === 0) {
  47008. // Update touch object.
  47009. if (isTouched === this.touchedButtons[button]) { return; }
  47010. this.touchedButtons[button] = isTouched;
  47011. } else {
  47012. // Update button object.
  47013. if (isPressed === this.pressedButtons[button]) { return; }
  47014. this.pressedButtons[button] = isPressed;
  47015. }
  47016. // Determine the gesture.
  47017. lastGesture = this.gesture;
  47018. this.gesture = this.determineGesture();
  47019. // Same gesture.
  47020. if (this.gesture === lastGesture) { return; }
  47021. // Animate gesture.
  47022. this.animateGesture(this.gesture, lastGesture);
  47023. // Emit events.
  47024. this.emitGestureEvents(this.gesture, lastGesture);
  47025. },
  47026. /**
  47027. * Determine which pose hand should be in considering active and touched buttons.
  47028. */
  47029. determineGesture: function () {
  47030. var gesture;
  47031. var isGripActive = this.pressedButtons.grip;
  47032. var isSurfaceActive = this.pressedButtons.surface || this.touchedButtons.surface;
  47033. var isTrackpadActive = this.pressedButtons.trackpad || this.touchedButtons.trackpad;
  47034. var isTriggerActive = this.pressedButtons.trigger || this.touchedButtons.trigger;
  47035. var isABXYActive = this.touchedButtons.AorX || this.touchedButtons.BorY;
  47036. var isVive = isViveController(this.el.components['tracked-controls']);
  47037. // Works well with Oculus Touch and Windows Motion Controls, but Vive needs tweaks.
  47038. if (isVive) {
  47039. if (isGripActive || isTriggerActive) {
  47040. gesture = ANIMATIONS.fist;
  47041. } else if (isTrackpadActive) {
  47042. gesture = ANIMATIONS.point;
  47043. }
  47044. } else {
  47045. if (isGripActive) {
  47046. if (isSurfaceActive || isABXYActive || isTrackpadActive) {
  47047. gesture = isTriggerActive ? ANIMATIONS.fist : ANIMATIONS.point;
  47048. } else {
  47049. gesture = isTriggerActive ? ANIMATIONS.thumbUp : ANIMATIONS.pointThumb;
  47050. }
  47051. } else if (isTriggerActive) {
  47052. gesture = ANIMATIONS.hold;
  47053. }
  47054. }
  47055. return gesture;
  47056. },
  47057. /**
  47058. * Play corresponding clip to a gesture
  47059. */
  47060. getClip: function (gesture) {
  47061. var clip;
  47062. var i;
  47063. for (i = 0; i < this.clips.length; i++) {
  47064. clip = this.clips[i];
  47065. if (clip.name !== gesture) { continue; }
  47066. return clip;
  47067. }
  47068. },
  47069. /**
  47070. * Play gesture animation.
  47071. *
  47072. * @param {string} gesture - Which pose to animate to. If absent, then animate to open.
  47073. * @param {string} lastGesture - Previous gesture, to reverse back to open if needed.
  47074. */
  47075. animateGesture: function (gesture, lastGesture) {
  47076. if (gesture) {
  47077. this.playAnimation(gesture || ANIMATIONS.open, lastGesture, false);
  47078. return;
  47079. }
  47080. // If no gesture, then reverse the current gesture back to open pose.
  47081. this.playAnimation(lastGesture, lastGesture, true);
  47082. },
  47083. /**
  47084. * Emit `hand-controls`-specific events.
  47085. */
  47086. emitGestureEvents: function (gesture, lastGesture) {
  47087. var el = this.el;
  47088. var eventName;
  47089. if (lastGesture === gesture) { return; }
  47090. // Emit event for lastGesture not inactive.
  47091. eventName = getGestureEventName(lastGesture, false);
  47092. if (eventName) { el.emit(eventName); }
  47093. // Emit event for current gesture now active.
  47094. eventName = getGestureEventName(gesture, true);
  47095. if (eventName) { el.emit(eventName); }
  47096. },
  47097. /**
  47098. * Play hand animation based on button state.
  47099. *
  47100. * @param {string} gesture - Name of the animation as specified by the model.
  47101. * @param {string} lastGesture - Previous pose.
  47102. * @param {boolean} reverse - Whether animation should play in reverse.
  47103. */
  47104. playAnimation: function (gesture, lastGesture, reverse) {
  47105. var clip;
  47106. var fromAction;
  47107. var mesh = this.el.getObject3D('mesh');
  47108. var toAction;
  47109. if (!mesh) { return; }
  47110. // Stop all current animations.
  47111. mesh.mixer.stopAllAction();
  47112. // Grab clip action.
  47113. clip = this.getClip(gesture);
  47114. toAction = mesh.mixer.clipAction(clip);
  47115. toAction.clampWhenFinished = true;
  47116. toAction.loop = THREE.LoopRepeat;
  47117. toAction.repetitions = 0;
  47118. toAction.timeScale = reverse ? -1 : 1;
  47119. toAction.time = reverse ? clip.duration : 0;
  47120. toAction.weight = 1;
  47121. // No gesture to gesture or gesture to no gesture.
  47122. if (!lastGesture || gesture === lastGesture) {
  47123. // Stop all current animations.
  47124. mesh.mixer.stopAllAction();
  47125. // Play animation.
  47126. toAction.play();
  47127. return;
  47128. }
  47129. // Animate or crossfade from gesture to gesture.
  47130. clip = this.getClip(lastGesture);
  47131. fromAction = mesh.mixer.clipAction(clip);
  47132. fromAction.weight = 0.15;
  47133. fromAction.play();
  47134. toAction.play();
  47135. fromAction.crossFadeTo(toAction, 0.15, true);
  47136. }
  47137. });
  47138. /**
  47139. * Suffix gestures based on toggle state (e.g., open/close, up/down, start/end).
  47140. *
  47141. * @param {string} gesture
  47142. * @param {boolean} active
  47143. */
  47144. function getGestureEventName (gesture, active) {
  47145. var eventName;
  47146. if (!gesture) { return; }
  47147. eventName = EVENTS[gesture];
  47148. if (eventName === 'grip') {
  47149. return eventName + (active ? 'close' : 'open');
  47150. }
  47151. if (eventName === 'point') {
  47152. return eventName + (active ? 'up' : 'down');
  47153. }
  47154. if (eventName === 'pointing' || eventName === 'pistol') {
  47155. return eventName + (active ? 'start' : 'end');
  47156. }
  47157. }
  47158. function isViveController (trackedControls) {
  47159. var controller = trackedControls && trackedControls.controller;
  47160. var isVive = controller && (controller.id && controller.id.indexOf('OpenVR ') === 0 ||
  47161. (controller.profiles &&
  47162. controller.profiles[0] &&
  47163. controller.profiles[0] === 'htc-vive-controller-mv'));
  47164. return isVive;
  47165. }
  47166. },{"../core/component":131}],83:[function(_dereq_,module,exports){
  47167. /* global THREE, XRRigidTransform */
  47168. var registerComponent = _dereq_('../core/component').registerComponent;
  47169. var bind = _dereq_('../utils/bind');
  47170. var trackedControlsUtils = _dereq_('../utils/tracked-controls');
  47171. var checkControllerPresentAndSetup = trackedControlsUtils.checkControllerPresentAndSetup;
  47172. var LEFT_HAND_MODEL_URL = 'https://cdn.aframe.io/controllers/oculus-hands/unity/left.glb';
  47173. var RIGHT_HAND_MODEL_URL = 'https://cdn.aframe.io/controllers/oculus-hands/unity/right.glb';
  47174. var BONE_PREFIX = {
  47175. left: 'b_l_',
  47176. right: 'b_r_'
  47177. };
  47178. var JOINTS = [
  47179. 'wrist',
  47180. 'thumb-metacarpal',
  47181. 'thumb-phalanx-proximal',
  47182. 'thumb-phalanx-distal',
  47183. 'thumb-tip',
  47184. 'index-finger-metacarpal',
  47185. 'index-finger-phalanx-proximal',
  47186. 'index-finger-phalanx-intermediate',
  47187. 'index-finger-phalanx-distal',
  47188. 'index-finger-tip',
  47189. 'middle-finger-metacarpal',
  47190. 'middle-finger-phalanx-proximal',
  47191. 'middle-finger-phalanx-intermediate',
  47192. 'middle-finger-phalanx-distal',
  47193. 'middle-finger-tip',
  47194. 'ring-finger-metacarpal',
  47195. 'ring-finger-phalanx-proximal',
  47196. 'ring-finger-phalanx-intermediate',
  47197. 'ring-finger-phalanx-distal',
  47198. 'ring-finger-tip',
  47199. 'pinky-finger-metacarpal',
  47200. 'pinky-finger-phalanx-proximal',
  47201. 'pinky-finger-phalanx-intermediate',
  47202. 'pinky-finger-phalanx-distal',
  47203. 'pinky-finger-tip'
  47204. ];
  47205. var BONE_MAPPING = {
  47206. 'wrist': 'wrist',
  47207. 'thumb-metacarpal': 'thumb1',
  47208. 'thumb-phalanx-proximal': 'thumb2',
  47209. 'thumb-phalanx-distal': 'thumb3',
  47210. 'thumb-tip': 'thumb_null',
  47211. 'index-finger-phalanx-proximal': 'index1',
  47212. 'index-finger-phalanx-intermediate': 'index2',
  47213. 'index-finger-phalanx-distal': 'index3',
  47214. 'index-finger-tip': 'index_null',
  47215. 'middle-finger-phalanx-proximal': 'middle1',
  47216. 'middle-finger-phalanx-intermediate': 'middle2',
  47217. 'middle-finger-phalanx-distal': 'middle3',
  47218. 'middle-finger-tip': 'middle_null',
  47219. 'ring-finger-phalanx-proximal': 'ring1',
  47220. 'ring-finger-phalanx-intermediate': 'ring2',
  47221. 'ring-finger-phalanx-distal': 'ring3',
  47222. 'ring-finger-tip': 'ring_null',
  47223. 'pinky-finger-metacarpal': 'pinky0',
  47224. 'pinky-finger-phalanx-proximal': 'pinky1',
  47225. 'pinky-finger-phalanx-intermediate': 'pinky2',
  47226. 'pinky-finger-phalanx-distal': 'pinky3',
  47227. 'pinky-finger-tip': 'pinky_null'
  47228. };
  47229. var PINCH_START_DISTANCE = 0.015;
  47230. var PINCH_END_DISTANCE = 0.03;
  47231. var PINCH_POSITION_INTERPOLATION = 0.5;
  47232. /**
  47233. * Controls for hand tracking
  47234. */
  47235. module.exports.Component = registerComponent('hand-tracking-controls', {
  47236. schema: {
  47237. hand: {default: 'right', oneOf: ['left', 'right']},
  47238. modelStyle: {default: 'mesh', oneOf: ['dots', 'mesh']},
  47239. modelColor: {default: 'white'}
  47240. },
  47241. bindMethods: function () {
  47242. this.onControllersUpdate = bind(this.onControllersUpdate, this);
  47243. this.checkIfControllerPresent = bind(this.checkIfControllerPresent, this);
  47244. this.removeControllersUpdateListener = bind(this.removeControllersUpdateListener, this);
  47245. },
  47246. addEventListeners: function () {
  47247. this.el.addEventListener('model-loaded', this.onModelLoaded);
  47248. for (var i = 0; i < this.jointEls.length; ++i) {
  47249. this.jointEls[i].object3D.visible = true;
  47250. }
  47251. },
  47252. removeEventListeners: function () {
  47253. this.el.removeEventListener('model-loaded', this.onModelLoaded);
  47254. for (var i = 0; i < this.jointEls.length; ++i) {
  47255. this.jointEls[i].object3D.visible = false;
  47256. }
  47257. },
  47258. init: function () {
  47259. var sceneEl = this.el.sceneEl;
  47260. var webXROptionalAttributes = sceneEl.getAttribute('webxr').optionalFeatures;
  47261. webXROptionalAttributes.push('hand-tracking');
  47262. sceneEl.setAttribute('webxr', {optionalFeatures: webXROptionalAttributes});
  47263. this.onModelLoaded = this.onModelLoaded.bind(this);
  47264. this.jointEls = [];
  47265. this.controllerPresent = false;
  47266. this.isPinched = false;
  47267. this.pinchEventDetail = {position: new THREE.Vector3()};
  47268. this.indexTipPosition = new THREE.Vector3();
  47269. this.bindMethods();
  47270. this.updateReferenceSpace = this.updateReferenceSpace.bind(this);
  47271. this.el.sceneEl.addEventListener('enter-vr', this.updateReferenceSpace);
  47272. this.el.sceneEl.addEventListener('exit-vr', this.updateReferenceSpace);
  47273. },
  47274. updateReferenceSpace: function () {
  47275. var self = this;
  47276. var xrSession = this.el.sceneEl.xrSession;
  47277. this.referenceSpace = undefined;
  47278. if (!xrSession) { return; }
  47279. var referenceSpaceType = self.el.sceneEl.systems.webxr.sessionReferenceSpaceType;
  47280. xrSession.requestReferenceSpace(referenceSpaceType).then(function (referenceSpace) {
  47281. self.referenceSpace = referenceSpace.getOffsetReferenceSpace(new XRRigidTransform({x: 0, y: 1.5, z: 0}));
  47282. }).catch(function (error) {
  47283. self.el.sceneEl.systems.webxr.warnIfFeatureNotRequested(referenceSpaceType, 'tracked-controls-webxr uses reference space ' + referenceSpaceType);
  47284. throw error;
  47285. });
  47286. },
  47287. checkIfControllerPresent: function () {
  47288. var data = this.data;
  47289. var hand = data.hand ? data.hand : undefined;
  47290. checkControllerPresentAndSetup(
  47291. this, '',
  47292. {hand: hand, iterateControllerProfiles: true, handTracking: true});
  47293. },
  47294. play: function () {
  47295. this.checkIfControllerPresent();
  47296. this.addControllersUpdateListener();
  47297. },
  47298. tick: function () {
  47299. var sceneEl = this.el.sceneEl;
  47300. var controller = this.el.components['tracked-controls'] && this.el.components['tracked-controls'].controller;
  47301. var frame = sceneEl.frame;
  47302. var trackedControlsWebXR = this.el.components['tracked-controls-webxr'];
  47303. if (!controller || !frame || !trackedControlsWebXR) { return; }
  47304. if (controller.hand) {
  47305. this.el.object3D.position.set(0, 0, 0);
  47306. this.el.object3D.rotation.set(0, 0, 0);
  47307. if (frame.getJointPose) { this.updateHandModel(); }
  47308. this.detectGesture();
  47309. }
  47310. },
  47311. updateHandModel: function () {
  47312. if (this.data.modelStyle === 'dots') {
  47313. this.updateHandDotsModel();
  47314. }
  47315. if (this.data.modelStyle === 'mesh') {
  47316. this.updateHandMeshModel();
  47317. }
  47318. },
  47319. getBone: function (name) {
  47320. var bones = this.bones;
  47321. for (var i = 0; i < bones.length; i++) {
  47322. if (bones[i].name === name) { return bones[i]; }
  47323. }
  47324. return null;
  47325. },
  47326. updateHandMeshModel: function () {
  47327. var frame = this.el.sceneEl.frame;
  47328. var controller = this.el.components['tracked-controls'] && this.el.components['tracked-controls'].controller;
  47329. var referenceSpace = this.referenceSpace;
  47330. if (!controller || !this.mesh || !referenceSpace) { return; }
  47331. this.mesh.visible = false;
  47332. for (var inputjoint of controller.hand.values()) {
  47333. var bone;
  47334. var jointPose;
  47335. var jointTransform;
  47336. jointPose = frame.getJointPose(inputjoint, referenceSpace);
  47337. if (!BONE_MAPPING[inputjoint.jointName]) { continue; }
  47338. bone = this.getBone(BONE_PREFIX[this.data.hand] + BONE_MAPPING[inputjoint.jointName]);
  47339. if (bone != null && jointPose) {
  47340. jointTransform = jointPose.transform;
  47341. this.mesh.visible = true;
  47342. bone.position.copy(jointTransform.position).multiplyScalar(100);
  47343. bone.quaternion.set(jointTransform.orientation.x, jointTransform.orientation.y, jointTransform.orientation.z, jointTransform.orientation.w);
  47344. }
  47345. }
  47346. },
  47347. updateHandDotsModel: function () {
  47348. var frame = this.el.sceneEl.frame;
  47349. var controller = this.el.components['tracked-controls'] && this.el.components['tracked-controls'].controller;
  47350. var trackedControlsWebXR = this.el.components['tracked-controls-webxr'];
  47351. var referenceSpace = trackedControlsWebXR.system.referenceSpace;
  47352. var jointEl;
  47353. var object3D;
  47354. var jointPose;
  47355. var i = 0;
  47356. for (var inputjoint of controller.hand.values()) {
  47357. jointEl = this.jointEls[i++];
  47358. object3D = jointEl.object3D;
  47359. jointPose = frame.getJointPose(inputjoint, referenceSpace);
  47360. jointEl.object3D.visible = !!jointPose;
  47361. if (!jointPose) { continue; }
  47362. object3D.matrix.elements = jointPose.transform.matrix;
  47363. object3D.matrix.decompose(object3D.position, object3D.rotation, object3D.scale);
  47364. jointEl.setAttribute('scale', {x: jointPose.radius, y: jointPose.radius, z: jointPose.radius});
  47365. }
  47366. },
  47367. detectGesture: function () {
  47368. this.detectPinch();
  47369. },
  47370. detectPinch: (function () {
  47371. var thumbTipPosition = new THREE.Vector3();
  47372. return function () {
  47373. var frame = this.el.sceneEl.frame;
  47374. var indexTipPosition = this.indexTipPosition;
  47375. var controller = this.el.components['tracked-controls'] && this.el.components['tracked-controls'].controller;
  47376. var trackedControlsWebXR = this.el.components['tracked-controls-webxr'];
  47377. var referenceSpace = this.referenceSpace || trackedControlsWebXR.system.referenceSpace;
  47378. var indexTip = controller.hand.get('index-finger-tip');
  47379. var thumbTip = controller.hand.get('thumb-tip');
  47380. if (!indexTip ||
  47381. !thumbTip) { return; }
  47382. var indexTipPose = frame.getJointPose(indexTip, referenceSpace);
  47383. var thumbTipPose = frame.getJointPose(thumbTip, referenceSpace);
  47384. if (!indexTipPose || !thumbTipPose) { return; }
  47385. thumbTipPosition.copy(thumbTipPose.transform.position);
  47386. indexTipPosition.copy(indexTipPose.transform.position);
  47387. var distance = indexTipPosition.distanceTo(thumbTipPosition);
  47388. if (distance < PINCH_START_DISTANCE && this.isPinched === false) {
  47389. this.isPinched = true;
  47390. this.pinchEventDetail.position.copy(indexTipPosition).lerp(thumbTipPosition, PINCH_POSITION_INTERPOLATION);
  47391. this.pinchEventDetail.position.y += 1.5;
  47392. this.el.emit('pinchstarted', this.pinchEventDetail);
  47393. }
  47394. if (distance > PINCH_END_DISTANCE && this.isPinched === true) {
  47395. this.isPinched = false;
  47396. this.pinchEventDetail.position.copy(indexTipPosition).lerp(thumbTipPosition, PINCH_POSITION_INTERPOLATION);
  47397. this.pinchEventDetail.position.y += 1.5;
  47398. this.el.emit('pinchended', this.pinchEventDetail);
  47399. }
  47400. if (this.isPinched) {
  47401. this.pinchEventDetail.position.copy(indexTipPosition).lerp(thumbTipPosition, PINCH_POSITION_INTERPOLATION);
  47402. this.pinchEventDetail.position.y += 1.5;
  47403. this.el.emit('pinchmoved', this.pinchEventDetail);
  47404. }
  47405. indexTipPosition.y += 1.5;
  47406. };
  47407. })(),
  47408. pause: function () {
  47409. this.removeEventListeners();
  47410. this.removeControllersUpdateListener();
  47411. },
  47412. injectTrackedControls: function () {
  47413. var el = this.el;
  47414. var data = this.data;
  47415. el.setAttribute('tracked-controls', {
  47416. hand: data.hand,
  47417. iterateControllerProfiles: true,
  47418. handTrackingEnabled: true
  47419. });
  47420. this.initDefaultModel();
  47421. },
  47422. addControllersUpdateListener: function () {
  47423. this.el.sceneEl.addEventListener('controllersupdated', this.onControllersUpdate, false);
  47424. },
  47425. removeControllersUpdateListener: function () {
  47426. this.el.sceneEl.removeEventListener('controllersupdated', this.onControllersUpdate, false);
  47427. },
  47428. onControllersUpdate: function () {
  47429. var controller;
  47430. this.checkIfControllerPresent();
  47431. controller = this.el.components['tracked-controls'] && this.el.components['tracked-controls'].controller;
  47432. if (!this.el.getObject3D('mesh')) { return; }
  47433. if (!controller || !controller.hand || !controller.hand[0]) {
  47434. this.el.getObject3D('mesh').visible = false;
  47435. }
  47436. },
  47437. initDefaultModel: function () {
  47438. if (this.el.getObject3D('mesh')) { return; }
  47439. if (this.data.modelStyle === 'dots') {
  47440. this.initDotsModel();
  47441. }
  47442. if (this.data.modelStyle === 'mesh') {
  47443. this.initMeshHandModel();
  47444. }
  47445. },
  47446. initDotsModel: function () {
  47447. // Add models just once.
  47448. if (this.jointEls.length !== 0) { return; }
  47449. for (var i = 0; i < JOINTS.length; ++i) {
  47450. var jointEl = this.jointEl = document.createElement('a-entity');
  47451. jointEl.setAttribute('geometry', {
  47452. primitive: 'sphere',
  47453. radius: 1.0
  47454. });
  47455. jointEl.setAttribute('material', {color: this.data.modelColor});
  47456. jointEl.object3D.visible = false;
  47457. this.el.appendChild(jointEl);
  47458. this.jointEls.push(jointEl);
  47459. }
  47460. },
  47461. initMeshHandModel: function () {
  47462. var modelURL = this.data.hand === 'left' ? LEFT_HAND_MODEL_URL : RIGHT_HAND_MODEL_URL;
  47463. this.el.setAttribute('gltf-model', modelURL);
  47464. },
  47465. onModelLoaded: function () {
  47466. var mesh = this.mesh = this.el.getObject3D('mesh').children[0];
  47467. var skinnedMesh = this.skinnedMesh = mesh.children[24];
  47468. if (!this.skinnedMesh) { return; }
  47469. this.bones = skinnedMesh.skeleton.bones;
  47470. this.el.removeObject3D('mesh');
  47471. mesh.position.set(0, 1.5, 0);
  47472. mesh.rotation.set(0, 0, 0);
  47473. skinnedMesh.frustumCulled = false;
  47474. skinnedMesh.material = new THREE.MeshStandardMaterial({skinning: true, color: this.data.modelColor});
  47475. this.el.setObject3D('mesh', mesh);
  47476. }
  47477. });
  47478. },{"../core/component":131,"../utils/bind":199,"../utils/tracked-controls":214}],84:[function(_dereq_,module,exports){
  47479. _dereq_('./animation');
  47480. _dereq_('./camera');
  47481. _dereq_('./cursor');
  47482. _dereq_('./daydream-controls');
  47483. _dereq_('./gearvr-controls');
  47484. _dereq_('./geometry');
  47485. _dereq_('./generic-tracked-controller-controls');
  47486. _dereq_('./gltf-model');
  47487. _dereq_('./hand-tracking-controls');
  47488. _dereq_('./hand-controls');
  47489. _dereq_('./layer');
  47490. _dereq_('./laser-controls');
  47491. _dereq_('./light');
  47492. _dereq_('./line');
  47493. _dereq_('./link');
  47494. _dereq_('./look-controls');
  47495. _dereq_('./magicleap-controls');
  47496. _dereq_('./material');
  47497. _dereq_('./obj-model');
  47498. _dereq_('./oculus-go-controls');
  47499. _dereq_('./oculus-touch-controls');
  47500. _dereq_('./position');
  47501. _dereq_('./raycaster');
  47502. _dereq_('./rotation');
  47503. _dereq_('./scale');
  47504. _dereq_('./shadow');
  47505. _dereq_('./sound');
  47506. _dereq_('./text');
  47507. _dereq_('./tracked-controls');
  47508. _dereq_('./tracked-controls-webvr');
  47509. _dereq_('./tracked-controls-webxr');
  47510. _dereq_('./visible');
  47511. _dereq_('./valve-index-controls');
  47512. _dereq_('./vive-controls');
  47513. _dereq_('./vive-focus-controls');
  47514. _dereq_('./wasd-controls');
  47515. _dereq_('./windows-motion-controls');
  47516. _dereq_('./scene/background');
  47517. _dereq_('./scene/debug');
  47518. _dereq_('./scene/device-orientation-permission-ui');
  47519. _dereq_('./scene/embedded');
  47520. _dereq_('./scene/inspector');
  47521. _dereq_('./scene/fog');
  47522. _dereq_('./scene/keyboard-shortcuts');
  47523. _dereq_('./scene/pool');
  47524. _dereq_('./scene/screenshot');
  47525. _dereq_('./scene/stats');
  47526. _dereq_('./scene/vr-mode-ui');
  47527. },{"./animation":74,"./camera":75,"./cursor":76,"./daydream-controls":77,"./gearvr-controls":78,"./generic-tracked-controller-controls":79,"./geometry":80,"./gltf-model":81,"./hand-controls":82,"./hand-tracking-controls":83,"./laser-controls":85,"./layer":86,"./light":87,"./line":88,"./link":89,"./look-controls":90,"./magicleap-controls":91,"./material":92,"./obj-model":93,"./oculus-go-controls":94,"./oculus-touch-controls":95,"./position":96,"./raycaster":97,"./rotation":98,"./scale":99,"./scene/background":100,"./scene/debug":101,"./scene/device-orientation-permission-ui":102,"./scene/embedded":103,"./scene/fog":104,"./scene/inspector":105,"./scene/keyboard-shortcuts":106,"./scene/pool":107,"./scene/screenshot":108,"./scene/stats":109,"./scene/vr-mode-ui":110,"./shadow":111,"./sound":112,"./text":113,"./tracked-controls":116,"./tracked-controls-webvr":114,"./tracked-controls-webxr":115,"./valve-index-controls":117,"./visible":118,"./vive-controls":119,"./vive-focus-controls":120,"./wasd-controls":121,"./windows-motion-controls":122}],85:[function(_dereq_,module,exports){
  47528. var registerComponent = _dereq_('../core/component').registerComponent;
  47529. var utils = _dereq_('../utils/');
  47530. registerComponent('laser-controls', {
  47531. schema: {
  47532. hand: {default: 'right'},
  47533. model: {default: true},
  47534. defaultModelColor: {type: 'color', default: 'grey'}
  47535. },
  47536. init: function () {
  47537. var config = this.config;
  47538. var data = this.data;
  47539. var el = this.el;
  47540. var self = this;
  47541. var controlsConfiguration = {hand: data.hand, model: data.model};
  47542. // Set all controller models.
  47543. el.setAttribute('daydream-controls', controlsConfiguration);
  47544. el.setAttribute('gearvr-controls', controlsConfiguration);
  47545. el.setAttribute('magicleap-controls', controlsConfiguration);
  47546. el.setAttribute('oculus-go-controls', controlsConfiguration);
  47547. el.setAttribute('oculus-touch-controls', controlsConfiguration);
  47548. el.setAttribute('valve-index-controls', controlsConfiguration);
  47549. el.setAttribute('vive-controls', controlsConfiguration);
  47550. el.setAttribute('vive-focus-controls', controlsConfiguration);
  47551. el.setAttribute('windows-motion-controls', controlsConfiguration);
  47552. el.setAttribute('generic-tracked-controller-controls', controlsConfiguration);
  47553. // Wait for controller to connect, or have a valid pointing pose, before creating ray
  47554. el.addEventListener('controllerconnected', createRay);
  47555. el.addEventListener('controllerdisconnected', hideRay);
  47556. el.addEventListener('controllermodelready', function (evt) {
  47557. createRay(evt);
  47558. self.modelReady = true;
  47559. });
  47560. function createRay (evt) {
  47561. var controllerConfig = config[evt.detail.name];
  47562. if (!controllerConfig) { return; }
  47563. // Show the line unless a particular config opts to hide it, until a controllermodelready
  47564. // event comes through.
  47565. var raycasterConfig = utils.extend({
  47566. showLine: true
  47567. }, controllerConfig.raycaster || {});
  47568. // The controllermodelready event contains a rayOrigin that takes into account
  47569. // offsets specific to the loaded model.
  47570. if (evt.detail.rayOrigin) {
  47571. raycasterConfig.origin = evt.detail.rayOrigin.origin;
  47572. raycasterConfig.direction = evt.detail.rayOrigin.direction;
  47573. raycasterConfig.showLine = true;
  47574. }
  47575. // Only apply a default raycaster if it does not yet exist. This prevents it overwriting
  47576. // config applied from a controllermodelready event.
  47577. if (evt.detail.rayOrigin || !self.modelReady) {
  47578. el.setAttribute('raycaster', raycasterConfig);
  47579. } else {
  47580. el.setAttribute('raycaster', 'showLine', true);
  47581. }
  47582. el.setAttribute('cursor', utils.extend({
  47583. fuse: false
  47584. }, controllerConfig.cursor));
  47585. }
  47586. function hideRay () {
  47587. el.setAttribute('raycaster', 'showLine', false);
  47588. }
  47589. },
  47590. config: {
  47591. 'daydream-controls': {
  47592. cursor: {downEvents: ['trackpaddown', 'triggerdown'], upEvents: ['trackpadup', 'triggerup']}
  47593. },
  47594. 'gearvr-controls': {
  47595. cursor: {downEvents: ['triggerdown'], upEvents: ['triggerup']},
  47596. raycaster: {origin: {x: 0, y: 0.0010, z: 0}}
  47597. },
  47598. 'generic-tracked-controller-controls': {
  47599. cursor: {downEvents: ['triggerdown'], upEvents: ['triggerup']}
  47600. },
  47601. 'magicleap-controls': {
  47602. cursor: {downEvents: ['trackpaddown', 'triggerdown'], upEvents: ['trackpadup', 'triggerup']}
  47603. },
  47604. 'oculus-go-controls': {
  47605. cursor: {downEvents: ['triggerdown'], upEvents: ['triggerup']},
  47606. raycaster: {origin: {x: 0, y: 0.0005, z: 0}}
  47607. },
  47608. 'oculus-touch-controls': {
  47609. cursor: {downEvents: ['triggerdown'], upEvents: ['triggerup']},
  47610. raycaster: {origin: {x: 0, y: 0, z: 0}}
  47611. },
  47612. 'valve-index-controls': {
  47613. cursor: {downEvents: ['triggerdown'], upEvents: ['triggerup']}
  47614. },
  47615. 'vive-controls': {
  47616. cursor: {downEvents: ['triggerdown'], upEvents: ['triggerup']}
  47617. },
  47618. 'vive-focus-controls': {
  47619. cursor: {downEvents: ['trackpaddown', 'triggerdown'], upEvents: ['trackpadup', 'triggerup']}
  47620. },
  47621. 'windows-motion-controls': {
  47622. cursor: {downEvents: ['triggerdown'], upEvents: ['triggerup']},
  47623. raycaster: {showLine: false}
  47624. }
  47625. }
  47626. });
  47627. },{"../core/component":131,"../utils/":205}],86:[function(_dereq_,module,exports){
  47628. /* global THREE, XRRigidTransform, XRWebGLBinding */
  47629. var registerComponent = _dereq_('../core/component').registerComponent;
  47630. var utils = _dereq_('../utils/');
  47631. var warn = utils.debug('components:layer:warn');
  47632. module.exports.Component = registerComponent('layer', {
  47633. schema: {
  47634. type: {default: 'quad', oneOf: ['quad', 'monocubemap', 'stereocubemap']},
  47635. src: {type: 'map'},
  47636. rotateCubemap: {default: false},
  47637. width: {default: 0},
  47638. height: {default: 0}
  47639. },
  47640. init: function () {
  47641. var gl = this.el.sceneEl.renderer.getContext();
  47642. this.quaternion = new THREE.Quaternion();
  47643. this.position = new THREE.Vector3();
  47644. this.bindMethods();
  47645. this.needsRedraw = false;
  47646. this.frameBuffer = gl.createFramebuffer();
  47647. var requiredFeatures = this.el.sceneEl.getAttribute('webxr').requiredFeatures;
  47648. requiredFeatures.push('layers');
  47649. this.el.sceneEl.getAttribute('webxr', 'requiredFeatures', requiredFeatures);
  47650. this.el.sceneEl.addEventListener('enter-vr', this.onEnterVR);
  47651. this.el.sceneEl.addEventListener('exit-vr', this.onExitVR);
  47652. },
  47653. bindMethods: function () {
  47654. this.onRequestedReferenceSpace = this.onRequestedReferenceSpace.bind(this);
  47655. this.onEnterVR = this.onEnterVR.bind(this);
  47656. this.onExitVR = this.onExitVR.bind(this);
  47657. },
  47658. update: function (oldData) {
  47659. if (this.data.src !== oldData.src) { this.updateSrc(); }
  47660. },
  47661. updateSrc: function () {
  47662. var type = this.data.type;
  47663. this.texture = undefined;
  47664. if (type === 'quad') {
  47665. this.loadQuadImage();
  47666. return;
  47667. }
  47668. if (type === 'monocubemap' || type === 'stereocubemap') {
  47669. this.loadCubeMapImages();
  47670. return;
  47671. }
  47672. },
  47673. loadCubeMapImages: function () {
  47674. var type = this.data.type;
  47675. var glayer;
  47676. var xrGLFactory = this.xrGLFactory;
  47677. var frame = this.el.sceneEl.frame;
  47678. var src = this.data.src;
  47679. this.visibilityChanged = false;
  47680. if (!this.layer) { return; }
  47681. if (!src.complete) {
  47682. this.pendingCubeMapUpdate = true;
  47683. } else {
  47684. this.pendingCubeMapUpdate = false;
  47685. }
  47686. if (!this.loadingScreen) {
  47687. this.loadingScreen = true;
  47688. } else {
  47689. this.loadingScreen = false;
  47690. }
  47691. if (type === 'monocubemap') {
  47692. glayer = xrGLFactory.getSubImage(this.layer, frame);
  47693. this.loadCubeMapImage(glayer.colorTexture, src, 0);
  47694. } else {
  47695. glayer = xrGLFactory.getSubImage(this.layer, frame, 'left');
  47696. this.loadCubeMapImage(glayer.colorTexture, src, 0);
  47697. glayer = xrGLFactory.getSubImage(this.layer, frame, 'right');
  47698. this.loadCubeMapImage(glayer.colorTexture, src, 6);
  47699. }
  47700. },
  47701. loadQuadImage: function () {
  47702. var src = this.data.src;
  47703. var self = this;
  47704. this.el.sceneEl.systems.material.loadTexture(src, {src: src}, function textureLoaded (texture) {
  47705. self.el.sceneEl.renderer.initTexture(texture);
  47706. self.texture = texture;
  47707. if (src.tagName === 'VIDEO') { setTimeout(function () { self.textureIsVideo = true; }, 1000); }
  47708. if (self.layer) {
  47709. self.layer.height = self.data.height / 2 || self.texture.image.height / 1000;
  47710. self.layer.width = self.data.width / 2 || self.texture.image.width / 1000;
  47711. self.needsRedraw = true;
  47712. }
  47713. self.updateQuadPanel();
  47714. });
  47715. },
  47716. preGenerateCubeMapTextures: function (src, callback) {
  47717. if (this.data.type === 'monocubemap') {
  47718. this.generateCubeMapTextures(src, 0, callback);
  47719. } else {
  47720. this.generateCubeMapTextures(src, 0, callback);
  47721. this.generateCubeMapTextures(src, 6, callback);
  47722. }
  47723. },
  47724. generateCubeMapTextures: function (src, faceOffset, callback) {
  47725. var data = this.data;
  47726. var cubeFaceSize = this.cubeFaceSize;
  47727. var textureSourceCubeFaceSize = Math.min(src.width, src.height);
  47728. var cubefaceTextures = [];
  47729. var imgTmp0;
  47730. var imgTmp2;
  47731. for (var i = 0; i < 6; i++) {
  47732. var tempCanvas = document.createElement('CANVAS');
  47733. tempCanvas.width = tempCanvas.height = cubeFaceSize;
  47734. var tempCanvasContext = tempCanvas.getContext('2d');
  47735. if (data.rotateCubemap) {
  47736. if (i === 2 || i === 3) {
  47737. tempCanvasContext.save();
  47738. tempCanvasContext.translate(cubeFaceSize, cubeFaceSize);
  47739. tempCanvasContext.rotate(Math.PI);
  47740. }
  47741. }
  47742. // Note that this call to drawImage will not only copy the bytes to the
  47743. // canvas but also could resized the image if our cube face size is
  47744. // smaller than the source image due to GL max texture size.
  47745. tempCanvasContext.drawImage(
  47746. src,
  47747. (i + faceOffset) * textureSourceCubeFaceSize, // top left x coord in source
  47748. 0, // top left y coord in source
  47749. textureSourceCubeFaceSize, // x pixel count from source
  47750. textureSourceCubeFaceSize, // y pixel count from source
  47751. 0, // dest x offset in the canvas
  47752. 0, // dest y offset in the canvas
  47753. cubeFaceSize, // x pixel count in dest
  47754. cubeFaceSize // y pixel count in dest
  47755. );
  47756. tempCanvasContext.restore();
  47757. if (callback) { callback(); }
  47758. cubefaceTextures.push(tempCanvas);
  47759. }
  47760. if (data.rotateCubemap) {
  47761. imgTmp0 = cubefaceTextures[0];
  47762. imgTmp2 = cubefaceTextures[1];
  47763. cubefaceTextures[0] = imgTmp2;
  47764. cubefaceTextures[1] = imgTmp0;
  47765. imgTmp0 = cubefaceTextures[4];
  47766. imgTmp2 = cubefaceTextures[5];
  47767. cubefaceTextures[4] = imgTmp2;
  47768. cubefaceTextures[5] = imgTmp0;
  47769. }
  47770. if (callback) { callback(); }
  47771. return cubefaceTextures;
  47772. },
  47773. loadCubeMapImage: function (layerColorTexture, src, faceOffset) {
  47774. var gl = this.el.sceneEl.renderer.getContext();
  47775. var cubefaceTextures;
  47776. // dont flip the pixels as we load them into the texture buffer.
  47777. // TEXTURE_CUBE_MAP expects the Y to be flipped for the faces and it already
  47778. // is flipped in our texture image.
  47779. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false);
  47780. gl.bindTexture(gl.TEXTURE_CUBE_MAP, layerColorTexture);
  47781. if (!src.complete || this.loadingScreen) {
  47782. cubefaceTextures = this.loadingScreenImages;
  47783. } else {
  47784. cubefaceTextures = this.generateCubeMapTextures(src, faceOffset);
  47785. }
  47786. var errorCode = 0;
  47787. cubefaceTextures.forEach(function (canvas, i) {
  47788. gl.texSubImage2D(
  47789. gl.TEXTURE_CUBE_MAP_POSITIVE_X + i,
  47790. 0,
  47791. 0, 0,
  47792. gl.RGBA,
  47793. gl.UNSIGNED_BYTE,
  47794. canvas
  47795. );
  47796. errorCode = gl.getError();
  47797. });
  47798. if (errorCode !== 0) {
  47799. console.log('renderingError, WebGL Error Code: ' + errorCode);
  47800. }
  47801. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  47802. },
  47803. tick: function () {
  47804. if (!this.el.sceneEl.xrSession) { return; }
  47805. if (!this.layer && this.el.sceneEl.is('vr-mode')) { this.initLayer(); }
  47806. this.updateTransform();
  47807. if (this.data.src.complete && (this.pendingCubeMapUpdate || this.loadingScreen || this.visibilityChanged)) { this.loadCubeMapImages(); }
  47808. if (!this.needsRedraw && !this.layer.needsRedraw && !this.textureIsVideo) { return; }
  47809. if (this.data.type === 'quad') { this.draw(); }
  47810. this.needsRedraw = false;
  47811. },
  47812. initLayer: function () {
  47813. var self = this;
  47814. var type = this.data.type;
  47815. this.el.sceneEl.xrSession.onvisibilitychange = function (evt) {
  47816. self.visibilityChanged = evt.session.visibilityState !== 'hidden';
  47817. };
  47818. if (type === 'quad') {
  47819. this.initQuadLayer();
  47820. return;
  47821. }
  47822. if (type === 'monocubemap' || type === 'stereocubemap') {
  47823. this.initCubeMapLayer();
  47824. return;
  47825. }
  47826. },
  47827. initQuadLayer: function () {
  47828. var sceneEl = this.el.sceneEl;
  47829. var gl = sceneEl.renderer.getContext();
  47830. var xrGLFactory = this.xrGLFactory = new XRWebGLBinding(sceneEl.xrSession, gl);
  47831. if (!this.texture) { return; }
  47832. this.layer = xrGLFactory.createQuadLayer({
  47833. space: this.referenceSpace,
  47834. viewPixelHeight: 2048,
  47835. viewPixelWidth: 2048,
  47836. height: this.data.height / 2 || this.texture.image.height / 1000,
  47837. width: this.data.width / 2 || this.texture.image.width / 1000
  47838. });
  47839. sceneEl.renderer.xr.addLayer(this.layer);
  47840. },
  47841. initCubeMapLayer: function () {
  47842. var src = this.data.src;
  47843. var sceneEl = this.el.sceneEl;
  47844. var gl = sceneEl.renderer.getContext();
  47845. var glSizeLimit = gl.getParameter(gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  47846. var cubeFaceSize = this.cubeFaceSize = Math.min(glSizeLimit, Math.min(src.width, src.height));
  47847. var xrGLFactory = this.xrGLFactory = new XRWebGLBinding(sceneEl.xrSession, gl);
  47848. this.layer = xrGLFactory.createCubeLayer({
  47849. space: this.referenceSpace,
  47850. viewPixelWidth: cubeFaceSize,
  47851. viewPixelHeight: cubeFaceSize,
  47852. layout: this.data.type === 'monocubemap' ? 'mono' : 'stereo',
  47853. isStatic: false
  47854. });
  47855. this.initLoadingScreenImages();
  47856. this.loadCubeMapImages();
  47857. sceneEl.renderer.xr.addLayer(this.layer);
  47858. },
  47859. initLoadingScreenImages: function () {
  47860. var cubeFaceSize = this.cubeFaceSize;
  47861. var loadingScreenImages = this.loadingScreenImages = [];
  47862. for (var i = 0; i < 6; i++) {
  47863. var tempCanvas = document.createElement('CANVAS');
  47864. tempCanvas.width = tempCanvas.height = cubeFaceSize;
  47865. var tempCanvasContext = tempCanvas.getContext('2d');
  47866. tempCanvas.width = tempCanvas.height = cubeFaceSize;
  47867. tempCanvasContext.fillStyle = 'black';
  47868. tempCanvasContext.fillRect(0, 0, cubeFaceSize, cubeFaceSize);
  47869. if (i !== 2 && i !== 3) {
  47870. tempCanvasContext.translate(cubeFaceSize, 0);
  47871. tempCanvasContext.scale(-1, 1);
  47872. tempCanvasContext.fillStyle = 'white';
  47873. tempCanvasContext.font = '30px Arial';
  47874. tempCanvasContext.fillText('Loading', cubeFaceSize / 2, cubeFaceSize / 2);
  47875. }
  47876. loadingScreenImages.push(tempCanvas);
  47877. }
  47878. },
  47879. destroyLayer: function () {
  47880. if (!this.layer) { return; }
  47881. this.el.sceneEl.renderer.xr.removeLayer(this.layer);
  47882. this.layer.destroy();
  47883. this.layer = undefined;
  47884. },
  47885. toggleCompositorLayer: function () {
  47886. this.enableCompositorLayer(!this.layerEnabled);
  47887. },
  47888. enableCompositorLayer: function (enable) {
  47889. this.layerEnabled = enable;
  47890. this.quadPanelEl.object3D.visible = !this.layerEnabled;
  47891. },
  47892. updateQuadPanel: function () {
  47893. var quadPanelEl = this.quadPanelEl;
  47894. if (!this.quadPanelEl) {
  47895. quadPanelEl = this.quadPanelEl = document.createElement('a-entity');
  47896. this.el.appendChild(quadPanelEl);
  47897. }
  47898. quadPanelEl.setAttribute('material', {
  47899. shader: 'flat',
  47900. src: this.data.src,
  47901. transparent: true
  47902. });
  47903. quadPanelEl.setAttribute('geometry', {
  47904. primitive: 'plane',
  47905. height: this.data.height || this.texture.image.height / 1000,
  47906. width: this.data.width || this.texture.image.height / 1000
  47907. });
  47908. },
  47909. draw: function () {
  47910. var sceneEl = this.el.sceneEl;
  47911. var gl = this.el.sceneEl.renderer.getContext();
  47912. var glayer = this.xrGLFactory.getSubImage(this.layer, sceneEl.frame);
  47913. var texture = sceneEl.renderer.properties.get(this.texture).__webglTexture;
  47914. var previousFrameBuffer = gl.getParameter(gl.FRAMEBUFFER_BINDING);
  47915. gl.viewport(glayer.viewport.x, glayer.viewport.y, glayer.viewport.width, glayer.viewport.height);
  47916. gl.bindFramebuffer(gl.FRAMEBUFFER, this.frameBuffer);
  47917. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, glayer.colorTexture, 0);
  47918. blitTexture(gl, texture, glayer, this.data.src);
  47919. gl.bindFramebuffer(gl.FRAMEBUFFER, previousFrameBuffer);
  47920. },
  47921. updateTransform: function () {
  47922. var el = this.el;
  47923. var position = this.position;
  47924. var quaternion = this.quaternion;
  47925. el.object3D.updateMatrixWorld();
  47926. position.setFromMatrixPosition(el.object3D.matrixWorld);
  47927. quaternion.setFromRotationMatrix(el.object3D.matrixWorld);
  47928. if (!this.layerEnabled) { position.set(0, 0, 100000000); }
  47929. this.layer.transform = new XRRigidTransform(position, quaternion);
  47930. },
  47931. onEnterVR: function () {
  47932. var sceneEl = this.el.sceneEl;
  47933. var xrSession = sceneEl.xrSession;
  47934. if (!sceneEl.hasWebXR || !XRWebGLBinding || !xrSession) {
  47935. warn('The layer component requires WebXR and the layers API enabled');
  47936. return;
  47937. }
  47938. xrSession.requestReferenceSpace('local').then(this.onRequestedReferenceSpace);
  47939. this.needsRedraw = true;
  47940. this.layerEnabled = true;
  47941. if (this.quadPanelEl) {
  47942. this.quadPanelEl.object3D.visible = false;
  47943. }
  47944. if (this.data.src.play) { this.data.src.play(); }
  47945. },
  47946. onExitVR: function () {
  47947. if (this.quadPanelEl) {
  47948. this.quadPanelEl.object3D.visible = true;
  47949. }
  47950. this.destroyLayer();
  47951. },
  47952. onRequestedReferenceSpace: function (referenceSpace) {
  47953. this.referenceSpace = referenceSpace;
  47954. }
  47955. });
  47956. function blitTexture (gl, texture, subImage, textureEl) {
  47957. var xrReadFramebuffer = gl.createFramebuffer();
  47958. let x1offset = subImage.viewport.x;
  47959. let y1offset = subImage.viewport.y;
  47960. let x2offset = subImage.viewport.x + subImage.viewport.width;
  47961. let y2offset = subImage.viewport.y + subImage.viewport.height;
  47962. // Update video texture.
  47963. if (textureEl.tagName === 'VIDEO') {
  47964. gl.bindTexture(gl.TEXTURE_2D, texture);
  47965. gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, textureEl.width, textureEl.height, gl.RGB, gl.UNSIGNED_BYTE, textureEl);
  47966. }
  47967. // Bind texture to read framebuffer.
  47968. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, xrReadFramebuffer);
  47969. gl.framebufferTexture2D(gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  47970. // Blit into layer buffer.
  47971. gl.readBuffer(gl.COLOR_ATTACHMENT0);
  47972. gl.blitFramebuffer(0, 0, textureEl.width, textureEl.height, x1offset, y1offset, x2offset, y2offset, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  47973. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, null);
  47974. gl.deleteFramebuffer(xrReadFramebuffer);
  47975. }
  47976. },{"../core/component":131,"../utils/":205}],87:[function(_dereq_,module,exports){
  47977. var bind = _dereq_('../utils/bind');
  47978. var diff = _dereq_('../utils').diff;
  47979. var debug = _dereq_('../utils/debug');
  47980. var registerComponent = _dereq_('../core/component').registerComponent;
  47981. var THREE = _dereq_('../lib/three');
  47982. var degToRad = THREE.Math.degToRad;
  47983. var warn = debug('components:light:warn');
  47984. /**
  47985. * Light component.
  47986. */
  47987. module.exports.Component = registerComponent('light', {
  47988. schema: {
  47989. angle: {default: 60, if: {type: ['spot']}},
  47990. color: {type: 'color'},
  47991. groundColor: {type: 'color', if: {type: ['hemisphere']}},
  47992. decay: {default: 1, if: {type: ['point', 'spot']}},
  47993. distance: {default: 0.0, min: 0, if: {type: ['point', 'spot']}},
  47994. intensity: {default: 1.0, min: 0, if: {type: ['ambient', 'directional', 'hemisphere', 'point', 'spot']}},
  47995. penumbra: {default: 0, min: 0, max: 1, if: {type: ['spot']}},
  47996. type: {
  47997. default: 'directional',
  47998. oneOf: ['ambient', 'directional', 'hemisphere', 'point', 'spot'],
  47999. schemaChange: true
  48000. },
  48001. target: {type: 'selector', if: {type: ['spot', 'directional']}},
  48002. // Shadows.
  48003. castShadow: {default: false, if: {type: ['point', 'spot', 'directional']}},
  48004. shadowBias: {default: 0, if: {castShadow: true}},
  48005. shadowCameraFar: {default: 500, if: {castShadow: true}},
  48006. shadowCameraFov: {default: 90, if: {castShadow: true}},
  48007. shadowCameraNear: {default: 0.5, if: {castShadow: true}},
  48008. shadowCameraTop: {default: 5, if: {castShadow: true}},
  48009. shadowCameraRight: {default: 5, if: {castShadow: true}},
  48010. shadowCameraBottom: {default: -5, if: {castShadow: true}},
  48011. shadowCameraLeft: {default: -5, if: {castShadow: true}},
  48012. shadowCameraVisible: {default: false, if: {castShadow: true}},
  48013. shadowMapHeight: {default: 512, if: {castShadow: true}},
  48014. shadowMapWidth: {default: 512, if: {castShadow: true}},
  48015. shadowRadius: {default: 1, if: {castShadow: true}}
  48016. },
  48017. /**
  48018. * Notifies scene a light has been added to remove default lighting.
  48019. */
  48020. init: function () {
  48021. var el = this.el;
  48022. this.light = null;
  48023. this.defaultTarget = null;
  48024. this.rendererSystem = this.el.sceneEl.systems.renderer;
  48025. this.system.registerLight(el);
  48026. },
  48027. /**
  48028. * (Re)create or update light.
  48029. */
  48030. update: function (oldData) {
  48031. var data = this.data;
  48032. var diffData = diff(data, oldData);
  48033. var light = this.light;
  48034. var rendererSystem = this.rendererSystem;
  48035. var self = this;
  48036. // Existing light.
  48037. if (light && !('type' in diffData)) {
  48038. var shadowsLoaded = false;
  48039. // Light type has not changed. Update light.
  48040. Object.keys(diffData).forEach(function (key) {
  48041. var value = data[key];
  48042. switch (key) {
  48043. case 'color': {
  48044. light.color.set(value);
  48045. rendererSystem.applyColorCorrection(light.color);
  48046. break;
  48047. }
  48048. case 'groundColor': {
  48049. light.groundColor.set(value);
  48050. rendererSystem.applyColorCorrection(light.groundColor);
  48051. break;
  48052. }
  48053. case 'angle': {
  48054. light.angle = degToRad(value);
  48055. break;
  48056. }
  48057. case 'target': {
  48058. // Reset target if selector is null.
  48059. if (value === null) {
  48060. if (data.type === 'spot' || data.type === 'directional') {
  48061. light.target = self.defaultTarget;
  48062. }
  48063. } else {
  48064. // Target specified, set target to entity's `object3D` when it is loaded.
  48065. if (value.hasLoaded) {
  48066. self.onSetTarget(value, light);
  48067. } else {
  48068. value.addEventListener('loaded', bind(self.onSetTarget, self, value, light));
  48069. }
  48070. }
  48071. break;
  48072. }
  48073. case 'castShadow':
  48074. case 'shadowBias':
  48075. case 'shadowCameraFar':
  48076. case 'shadowCameraFov':
  48077. case 'shadowCameraNear':
  48078. case 'shadowCameraTop':
  48079. case 'shadowCameraRight':
  48080. case 'shadowCameraBottom':
  48081. case 'shadowCameraLeft':
  48082. case 'shadowCameraVisible':
  48083. case 'shadowMapHeight':
  48084. case 'shadowMapWidth':
  48085. case 'shadowRadius':
  48086. if (!shadowsLoaded) {
  48087. self.updateShadow();
  48088. shadowsLoaded = true;
  48089. }
  48090. break;
  48091. default: {
  48092. light[key] = value;
  48093. }
  48094. }
  48095. });
  48096. return;
  48097. }
  48098. // No light yet or light type has changed. Create and add light.
  48099. this.setLight(this.data);
  48100. this.updateShadow();
  48101. },
  48102. setLight: function (data) {
  48103. var el = this.el;
  48104. var newLight = this.getLight(data);
  48105. if (newLight) {
  48106. if (this.light) {
  48107. el.removeObject3D('light');
  48108. }
  48109. this.light = newLight;
  48110. this.light.el = el;
  48111. el.setObject3D('light', this.light);
  48112. // HACK solution for issue #1624
  48113. if (data.type === 'spot' || data.type === 'directional' || data.type === 'hemisphere') {
  48114. el.getObject3D('light').translateY(-1);
  48115. }
  48116. // set and position default lighttarget as a child to enable spotlight orientation
  48117. if (data.type === 'spot') {
  48118. el.setObject3D('light-target', this.defaultTarget);
  48119. el.getObject3D('light-target').position.set(0, 0, -1);
  48120. }
  48121. }
  48122. },
  48123. /**
  48124. * Updates shadow-related properties on the current light.
  48125. */
  48126. updateShadow: function () {
  48127. var el = this.el;
  48128. var data = this.data;
  48129. var light = this.light;
  48130. light.castShadow = data.castShadow;
  48131. // Shadow camera helper.
  48132. var cameraHelper = el.getObject3D('cameraHelper');
  48133. if (data.shadowCameraVisible && !cameraHelper) {
  48134. el.setObject3D('cameraHelper', new THREE.CameraHelper(light.shadow.camera));
  48135. } else if (!data.shadowCameraVisible && cameraHelper) {
  48136. el.removeObject3D('cameraHelper');
  48137. }
  48138. if (!data.castShadow) { return light; }
  48139. // Shadow appearance.
  48140. light.shadow.bias = data.shadowBias;
  48141. light.shadow.radius = data.shadowRadius;
  48142. light.shadow.mapSize.height = data.shadowMapHeight;
  48143. light.shadow.mapSize.width = data.shadowMapWidth;
  48144. // Shadow camera.
  48145. light.shadow.camera.near = data.shadowCameraNear;
  48146. light.shadow.camera.far = data.shadowCameraFar;
  48147. if (light.shadow.camera instanceof THREE.OrthographicCamera) {
  48148. light.shadow.camera.top = data.shadowCameraTop;
  48149. light.shadow.camera.right = data.shadowCameraRight;
  48150. light.shadow.camera.bottom = data.shadowCameraBottom;
  48151. light.shadow.camera.left = data.shadowCameraLeft;
  48152. } else {
  48153. light.shadow.camera.fov = data.shadowCameraFov;
  48154. }
  48155. light.shadow.camera.updateProjectionMatrix();
  48156. if (cameraHelper) { cameraHelper.update(); }
  48157. },
  48158. /**
  48159. * Creates a new three.js light object given data object defining the light.
  48160. *
  48161. * @param {object} data
  48162. */
  48163. getLight: function (data) {
  48164. var angle = data.angle;
  48165. var color = new THREE.Color(data.color);
  48166. this.rendererSystem.applyColorCorrection(color);
  48167. color = color.getHex();
  48168. var decay = data.decay;
  48169. var distance = data.distance;
  48170. var groundColor = new THREE.Color(data.groundColor);
  48171. this.rendererSystem.applyColorCorrection(groundColor);
  48172. groundColor = groundColor.getHex();
  48173. var intensity = data.intensity;
  48174. var type = data.type;
  48175. var target = data.target;
  48176. var light = null;
  48177. switch (type.toLowerCase()) {
  48178. case 'ambient': {
  48179. return new THREE.AmbientLight(color, intensity);
  48180. }
  48181. case 'directional': {
  48182. light = new THREE.DirectionalLight(color, intensity);
  48183. this.defaultTarget = light.target;
  48184. if (target) {
  48185. if (target.hasLoaded) {
  48186. this.onSetTarget(target, light);
  48187. } else {
  48188. target.addEventListener('loaded', bind(this.onSetTarget, this, target, light));
  48189. }
  48190. }
  48191. return light;
  48192. }
  48193. case 'hemisphere': {
  48194. return new THREE.HemisphereLight(color, groundColor, intensity);
  48195. }
  48196. case 'point': {
  48197. return new THREE.PointLight(color, intensity, distance, decay);
  48198. }
  48199. case 'spot': {
  48200. light = new THREE.SpotLight(color, intensity, distance, degToRad(angle), data.penumbra, decay);
  48201. this.defaultTarget = light.target;
  48202. if (target) {
  48203. if (target.hasLoaded) {
  48204. this.onSetTarget(target, light);
  48205. } else {
  48206. target.addEventListener('loaded', bind(this.onSetTarget, this, target, light));
  48207. }
  48208. }
  48209. return light;
  48210. }
  48211. default: {
  48212. warn('%s is not a valid light type. ' +
  48213. 'Choose from ambient, directional, hemisphere, point, spot.', type);
  48214. }
  48215. }
  48216. },
  48217. onSetTarget: function (targetEl, light) {
  48218. light.target = targetEl.object3D;
  48219. },
  48220. /**
  48221. * Remove light on remove (callback).
  48222. */
  48223. remove: function () {
  48224. var el = this.el;
  48225. el.removeObject3D('light');
  48226. if (el.getObject3D('cameraHelper')) {
  48227. el.removeObject3D('cameraHelper');
  48228. }
  48229. }
  48230. });
  48231. },{"../core/component":131,"../lib/three":179,"../utils":205,"../utils/bind":199,"../utils/debug":201}],88:[function(_dereq_,module,exports){
  48232. /* global THREE */
  48233. var registerComponent = _dereq_('../core/component').registerComponent;
  48234. module.exports.Component = registerComponent('line', {
  48235. schema: {
  48236. start: {type: 'vec3', default: {x: 0, y: 0, z: 0}},
  48237. end: {type: 'vec3', default: {x: 0, y: 0, z: 0}},
  48238. color: {type: 'color', default: '#74BEC1'},
  48239. opacity: {type: 'number', default: 1},
  48240. visible: {default: true}
  48241. },
  48242. multiple: true,
  48243. init: function () {
  48244. var data = this.data;
  48245. var geometry;
  48246. var material;
  48247. this.rendererSystem = this.el.sceneEl.systems.renderer;
  48248. material = this.material = new THREE.LineBasicMaterial({
  48249. color: data.color,
  48250. opacity: data.opacity,
  48251. transparent: data.opacity < 1,
  48252. visible: data.visible
  48253. });
  48254. geometry = this.geometry = new THREE.BufferGeometry();
  48255. geometry.setAttribute('position', new THREE.BufferAttribute(new Float32Array(2 * 3), 3));
  48256. this.rendererSystem.applyColorCorrection(material.color);
  48257. this.line = new THREE.Line(geometry, material);
  48258. this.el.setObject3D(this.attrName, this.line);
  48259. },
  48260. update: function (oldData) {
  48261. var data = this.data;
  48262. var geometry = this.geometry;
  48263. var geoNeedsUpdate = false;
  48264. var material = this.material;
  48265. var positionArray = geometry.attributes.position.array;
  48266. // Update geometry.
  48267. if (!isEqualVec3(data.start, oldData.start)) {
  48268. positionArray[0] = data.start.x;
  48269. positionArray[1] = data.start.y;
  48270. positionArray[2] = data.start.z;
  48271. geoNeedsUpdate = true;
  48272. }
  48273. if (!isEqualVec3(data.end, oldData.end)) {
  48274. positionArray[3] = data.end.x;
  48275. positionArray[4] = data.end.y;
  48276. positionArray[5] = data.end.z;
  48277. geoNeedsUpdate = true;
  48278. }
  48279. if (geoNeedsUpdate) {
  48280. geometry.attributes.position.needsUpdate = true;
  48281. geometry.computeBoundingSphere();
  48282. }
  48283. material.color.setStyle(data.color);
  48284. this.rendererSystem.applyColorCorrection(material.color);
  48285. material.opacity = data.opacity;
  48286. material.transparent = data.opacity < 1;
  48287. material.visible = data.visible;
  48288. },
  48289. remove: function () {
  48290. this.el.removeObject3D('line', this.line);
  48291. }
  48292. });
  48293. function isEqualVec3 (a, b) {
  48294. if (!a || !b) { return false; }
  48295. return (a.x === b.x && a.y === b.y && a.z === b.z);
  48296. }
  48297. },{"../core/component":131}],89:[function(_dereq_,module,exports){
  48298. var registerComponent = _dereq_('../core/component').registerComponent;
  48299. var registerShader = _dereq_('../core/shader').registerShader;
  48300. var THREE = _dereq_('../lib/three');
  48301. /**
  48302. * Link component. Connect experiences and traverse between them in VR
  48303. *
  48304. * @member {object} hiddenEls - Store the hidden elements during peek mode.
  48305. */
  48306. module.exports.Component = registerComponent('link', {
  48307. schema: {
  48308. backgroundColor: {default: 'red', type: 'color'},
  48309. borderColor: {default: 'white', type: 'color'},
  48310. highlighted: {default: false},
  48311. highlightedColor: {default: '#24CAFF', type: 'color'},
  48312. href: {default: ''},
  48313. image: {type: 'asset'},
  48314. on: {default: 'click'},
  48315. peekMode: {default: false},
  48316. title: {default: ''},
  48317. titleColor: {default: 'white', type: 'color'},
  48318. visualAspectEnabled: {default: false}
  48319. },
  48320. init: function () {
  48321. this.navigate = this.navigate.bind(this);
  48322. this.previousQuaternion = undefined;
  48323. this.quaternionClone = new THREE.Quaternion();
  48324. // Store hidden elements during peek mode so we can show them again later.
  48325. this.hiddenEls = [];
  48326. },
  48327. update: function (oldData) {
  48328. var data = this.data;
  48329. var el = this.el;
  48330. var backgroundColor;
  48331. var strokeColor;
  48332. if (!data.visualAspectEnabled) { return; }
  48333. this.initVisualAspect();
  48334. backgroundColor = data.highlighted ? data.highlightedColor : data.backgroundColor;
  48335. strokeColor = data.highlighted ? data.highlightedColor : data.borderColor;
  48336. el.setAttribute('material', 'backgroundColor', backgroundColor);
  48337. el.setAttribute('material', 'strokeColor', strokeColor);
  48338. if (data.on !== oldData.on) { this.updateEventListener(); }
  48339. if (oldData.peekMode !== undefined &&
  48340. data.peekMode !== oldData.peekMode) { this.updatePeekMode(); }
  48341. if (!data.image || oldData.image === data.image) { return; }
  48342. el.setAttribute('material', 'pano',
  48343. typeof data.image === 'string' ? data.image : data.image.src);
  48344. },
  48345. /*
  48346. * Toggle all elements and full 360 preview of the linked page.
  48347. */
  48348. updatePeekMode: function () {
  48349. var el = this.el;
  48350. var sphereEl = this.sphereEl;
  48351. if (this.data.peekMode) {
  48352. this.hideAll();
  48353. el.getObject3D('mesh').visible = false;
  48354. sphereEl.setAttribute('visible', true);
  48355. } else {
  48356. this.showAll();
  48357. el.getObject3D('mesh').visible = true;
  48358. sphereEl.setAttribute('visible', false);
  48359. }
  48360. },
  48361. play: function () {
  48362. this.updateEventListener();
  48363. },
  48364. pause: function () {
  48365. this.removeEventListener();
  48366. },
  48367. updateEventListener: function () {
  48368. var el = this.el;
  48369. if (!el.isPlaying) { return; }
  48370. this.removeEventListener();
  48371. el.addEventListener(this.data.on, this.navigate);
  48372. },
  48373. removeEventListener: function () {
  48374. var on = this.data.on;
  48375. if (!on) { return; }
  48376. this.el.removeEventListener(on, this.navigate);
  48377. },
  48378. initVisualAspect: function () {
  48379. var el = this.el;
  48380. var semiSphereEl;
  48381. var sphereEl;
  48382. var textEl;
  48383. if (!this.data.visualAspectEnabled || this.visualAspectInitialized) { return; }
  48384. textEl = this.textEl = this.textEl || document.createElement('a-entity');
  48385. sphereEl = this.sphereEl = this.sphereEl || document.createElement('a-entity');
  48386. semiSphereEl = this.semiSphereEl = this.semiSphereEl || document.createElement('a-entity');
  48387. // Set portal.
  48388. el.setAttribute('geometry', {primitive: 'circle', radius: 1.0, segments: 64});
  48389. el.setAttribute('material', {shader: 'portal', pano: this.data.image, side: 'double'});
  48390. // Set text that displays the link title and URL.
  48391. textEl.setAttribute('text', {
  48392. color: this.data.titleColor,
  48393. align: 'center',
  48394. font: 'kelsonsans',
  48395. value: this.data.title || this.data.href,
  48396. width: 4
  48397. });
  48398. textEl.setAttribute('position', '0 1.5 0');
  48399. el.appendChild(textEl);
  48400. // Set sphere rendered when camera is close to portal to allow user to peek inside.
  48401. semiSphereEl.setAttribute('geometry', {
  48402. primitive: 'sphere',
  48403. radius: 1.0,
  48404. phiStart: 0,
  48405. segmentsWidth: 64,
  48406. segmentsHeight: 64,
  48407. phiLength: 180,
  48408. thetaStart: 0,
  48409. thetaLength: 360
  48410. });
  48411. semiSphereEl.setAttribute('material', {
  48412. shader: 'portal',
  48413. borderEnabled: 0.0,
  48414. pano: this.data.image,
  48415. side: 'back'
  48416. });
  48417. semiSphereEl.setAttribute('rotation', '0 180 0');
  48418. semiSphereEl.setAttribute('position', '0 0 0');
  48419. semiSphereEl.setAttribute('visible', false);
  48420. el.appendChild(semiSphereEl);
  48421. // Set sphere rendered when camera is close to portal to allow user to peek inside.
  48422. sphereEl.setAttribute('geometry', {
  48423. primitive: 'sphere',
  48424. radius: 10,
  48425. segmentsWidth: 64,
  48426. segmentsHeight: 64
  48427. });
  48428. sphereEl.setAttribute('material', {
  48429. shader: 'portal',
  48430. borderEnabled: 0.0,
  48431. pano: this.data.image,
  48432. side: 'back'
  48433. });
  48434. sphereEl.setAttribute('visible', false);
  48435. el.appendChild(sphereEl);
  48436. this.visualAspectInitialized = true;
  48437. },
  48438. navigate: function () {
  48439. window.location = this.data.href;
  48440. },
  48441. /**
  48442. * 1. Swap plane that represents portal with sphere with a hole when the camera is close
  48443. * so user can peek inside portal. Sphere is rendered on oposite side of portal
  48444. * from where user enters.
  48445. * 2. Place the url/title above or inside portal depending on distance to camera.
  48446. * 3. Face portal to camera when far away from user.
  48447. */
  48448. tick: (function () {
  48449. var cameraWorldPosition = new THREE.Vector3();
  48450. var elWorldPosition = new THREE.Vector3();
  48451. var quaternion = new THREE.Quaternion();
  48452. var scale = new THREE.Vector3();
  48453. return function () {
  48454. var el = this.el;
  48455. var object3D = el.object3D;
  48456. var camera = el.sceneEl.camera;
  48457. var cameraPortalOrientation;
  48458. var distance;
  48459. var textEl = this.textEl;
  48460. if (!this.data.visualAspectEnabled) { return; }
  48461. // Update matrices
  48462. object3D.updateMatrixWorld();
  48463. camera.parent.updateMatrixWorld();
  48464. camera.updateMatrixWorld();
  48465. object3D.matrix.decompose(elWorldPosition, quaternion, scale);
  48466. elWorldPosition.setFromMatrixPosition(object3D.matrixWorld);
  48467. cameraWorldPosition.setFromMatrixPosition(camera.matrixWorld);
  48468. distance = elWorldPosition.distanceTo(cameraWorldPosition);
  48469. if (distance > 20) {
  48470. // Store original orientation to be restored when the portal stops facing the camera.
  48471. if (!this.previousQuaternion) {
  48472. this.quaternionClone.copy(quaternion);
  48473. this.previousQuaternion = this.quaternionClone;
  48474. }
  48475. // If the portal is far away from the user, face portal to camera.
  48476. object3D.lookAt(cameraWorldPosition);
  48477. } else {
  48478. // When portal is close to the user/camera.
  48479. cameraPortalOrientation = this.calculateCameraPortalOrientation();
  48480. // If user gets very close to portal, replace with holed sphere they can peek in.
  48481. if (distance < 0.5) {
  48482. // Configure text size and sphere orientation depending side user approaches portal.
  48483. if (this.semiSphereEl.getAttribute('visible') === true) { return; }
  48484. textEl.setAttribute('text', 'width', 1.5);
  48485. if (cameraPortalOrientation <= 0.0) {
  48486. textEl.setAttribute('position', '0 0 0.75');
  48487. textEl.setAttribute('rotation', '0 180 0');
  48488. this.semiSphereEl.setAttribute('rotation', '0 0 0');
  48489. } else {
  48490. textEl.setAttribute('position', '0 0 -0.75');
  48491. textEl.setAttribute('rotation', '0 0 0');
  48492. this.semiSphereEl.setAttribute('rotation', '0 180 0');
  48493. }
  48494. el.getObject3D('mesh').visible = false;
  48495. this.semiSphereEl.setAttribute('visible', true);
  48496. this.peekCameraPortalOrientation = cameraPortalOrientation;
  48497. } else {
  48498. // Calculate wich side the camera is approaching the camera (back / front).
  48499. // Adjust text orientation based on camera position.
  48500. if (cameraPortalOrientation <= 0.0) {
  48501. textEl.setAttribute('rotation', '0 180 0');
  48502. } else {
  48503. textEl.setAttribute('rotation', '0 0 0');
  48504. }
  48505. textEl.setAttribute('text', 'width', 5);
  48506. textEl.setAttribute('position', '0 1.5 0');
  48507. el.getObject3D('mesh').visible = true;
  48508. this.semiSphereEl.setAttribute('visible', false);
  48509. this.peekCameraPortalOrientation = undefined;
  48510. }
  48511. if (this.previousQuaternion) {
  48512. object3D.quaternion.copy(this.previousQuaternion);
  48513. this.previousQuaternion = undefined;
  48514. }
  48515. }
  48516. };
  48517. })(),
  48518. hideAll: function () {
  48519. var el = this.el;
  48520. var hiddenEls = this.hiddenEls;
  48521. var self = this;
  48522. if (hiddenEls.length > 0) { return; }
  48523. el.sceneEl.object3D.traverse(function (object) {
  48524. if (object && object.el && object.el.hasAttribute('link-controls')) { return; }
  48525. if (!object.el || object === el.sceneEl.object3D || object.el === el ||
  48526. object.el === self.sphereEl || object.el === el.sceneEl.cameraEl ||
  48527. object.el.getAttribute('visible') === false || object.el === self.textEl ||
  48528. object.el === self.semiSphereEl) {
  48529. return;
  48530. }
  48531. object.el.setAttribute('visible', false);
  48532. hiddenEls.push(object.el);
  48533. });
  48534. },
  48535. showAll: function () {
  48536. this.hiddenEls.forEach(function (el) { el.setAttribute('visible', true); });
  48537. this.hiddenEls = [];
  48538. },
  48539. /**
  48540. * Calculate whether the camera faces the front or back face of the portal.
  48541. * @returns {number} > 0 if camera faces front of portal, < 0 if it faces back of portal.
  48542. */
  48543. calculateCameraPortalOrientation: (function () {
  48544. var mat4 = new THREE.Matrix4();
  48545. var cameraPosition = new THREE.Vector3();
  48546. var portalNormal = new THREE.Vector3(0, 0, 1);
  48547. var portalPosition = new THREE.Vector3(0, 0, 0);
  48548. return function () {
  48549. var el = this.el;
  48550. var camera = el.sceneEl.camera;
  48551. // Reset tmp variables.
  48552. cameraPosition.set(0, 0, 0);
  48553. portalNormal.set(0, 0, 1);
  48554. portalPosition.set(0, 0, 0);
  48555. // Apply portal orientation to the normal.
  48556. el.object3D.matrixWorld.extractRotation(mat4);
  48557. portalNormal.applyMatrix4(mat4);
  48558. // Calculate portal world position.
  48559. el.object3D.updateMatrixWorld();
  48560. el.object3D.localToWorld(portalPosition);
  48561. // Calculate camera world position.
  48562. camera.parent.parent.updateMatrixWorld();
  48563. camera.parent.updateMatrixWorld();
  48564. camera.updateMatrixWorld();
  48565. camera.localToWorld(cameraPosition);
  48566. // Calculate vector from portal to camera.
  48567. // (portal) -------> (camera)
  48568. cameraPosition.sub(portalPosition).normalize();
  48569. portalNormal.normalize();
  48570. // Side where camera approaches portal is given by sign of dot product of portal normal
  48571. // and portal to camera vectors.
  48572. return Math.sign(portalNormal.dot(cameraPosition));
  48573. };
  48574. })(),
  48575. remove: function () {
  48576. this.removeEventListener();
  48577. }
  48578. });
  48579. /* eslint-disable */
  48580. registerShader('portal', {
  48581. schema: {
  48582. borderEnabled: {default: 1.0, type: 'int', is: 'uniform'},
  48583. backgroundColor: {default: 'red', type: 'color', is: 'uniform'},
  48584. pano: {type: 'map', is: 'uniform'},
  48585. strokeColor: {default: 'white', type: 'color', is: 'uniform'}
  48586. },
  48587. vertexShader: [
  48588. 'vec3 portalPosition;',
  48589. 'varying vec3 vWorldPosition;',
  48590. 'varying float vDistanceToCenter;',
  48591. 'varying float vDistance;',
  48592. 'void main() {',
  48593. 'vDistanceToCenter = clamp(length(position - vec3(0.0, 0.0, 0.0)), 0.0, 1.0);',
  48594. 'portalPosition = (modelMatrix * vec4(0.0, 0.0, 0.0, 1.0)).xyz;',
  48595. 'vDistance = length(portalPosition - cameraPosition);',
  48596. 'vWorldPosition = (modelMatrix * vec4(position, 1.0)).xyz;',
  48597. 'gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);',
  48598. '}'
  48599. ].join('\n'),
  48600. fragmentShader: [
  48601. '#define RECIPROCAL_PI2 0.15915494',
  48602. 'uniform sampler2D pano;',
  48603. 'uniform vec3 strokeColor;',
  48604. 'uniform vec3 backgroundColor;',
  48605. 'uniform float borderEnabled;',
  48606. 'varying float vDistanceToCenter;',
  48607. 'varying float vDistance;',
  48608. 'varying vec3 vWorldPosition;',
  48609. 'void main() {',
  48610. 'vec3 direction = normalize(vWorldPosition - cameraPosition);',
  48611. 'vec2 sampleUV;',
  48612. 'float borderThickness = clamp(exp(-vDistance / 50.0), 0.6, 0.95);',
  48613. 'sampleUV.y = clamp(direction.y * 0.5 + 0.5, 0.0, 1.0);',
  48614. 'sampleUV.x = atan(direction.z, -direction.x) * -RECIPROCAL_PI2 + 0.5;',
  48615. 'if (vDistanceToCenter > borderThickness && borderEnabled == 1.0) {',
  48616. 'gl_FragColor = vec4(strokeColor, 1.0);',
  48617. '} else {',
  48618. 'gl_FragColor = mix(texture2D(pano, sampleUV), vec4(backgroundColor, 1.0), clamp(pow((vDistance / 15.0), 2.0), 0.0, 1.0));',
  48619. '}',
  48620. '}'
  48621. ].join('\n')
  48622. });
  48623. /* eslint-enable */
  48624. },{"../core/component":131,"../core/shader":141,"../lib/three":179}],90:[function(_dereq_,module,exports){
  48625. /* global DeviceOrientationEvent */
  48626. var registerComponent = _dereq_('../core/component').registerComponent;
  48627. var THREE = _dereq_('../lib/three');
  48628. var utils = _dereq_('../utils/');
  48629. var bind = utils.bind;
  48630. // To avoid recalculation at every mouse movement tick
  48631. var PI_2 = Math.PI / 2;
  48632. /**
  48633. * look-controls. Update entity pose, factoring mouse, touch, and WebVR API data.
  48634. */
  48635. module.exports.Component = registerComponent('look-controls', {
  48636. dependencies: ['position', 'rotation'],
  48637. schema: {
  48638. enabled: {default: true},
  48639. magicWindowTrackingEnabled: {default: true},
  48640. pointerLockEnabled: {default: false},
  48641. reverseMouseDrag: {default: false},
  48642. reverseTouchDrag: {default: false},
  48643. touchEnabled: {default: true},
  48644. mouseEnabled: {default: true}
  48645. },
  48646. init: function () {
  48647. this.deltaYaw = 0;
  48648. this.previousHMDPosition = new THREE.Vector3();
  48649. this.hmdQuaternion = new THREE.Quaternion();
  48650. this.magicWindowAbsoluteEuler = new THREE.Euler();
  48651. this.magicWindowDeltaEuler = new THREE.Euler();
  48652. this.position = new THREE.Vector3();
  48653. this.magicWindowObject = new THREE.Object3D();
  48654. this.rotation = {};
  48655. this.deltaRotation = {};
  48656. this.savedPose = null;
  48657. this.pointerLocked = false;
  48658. this.setupMouseControls();
  48659. this.bindMethods();
  48660. this.previousMouseEvent = {};
  48661. this.setupMagicWindowControls();
  48662. // To save / restore camera pose
  48663. this.savedPose = {
  48664. position: new THREE.Vector3(),
  48665. rotation: new THREE.Euler()
  48666. };
  48667. // Call enter VR handler if the scene has entered VR before the event listeners attached.
  48668. if (this.el.sceneEl.is('vr-mode')) { this.onEnterVR(); }
  48669. },
  48670. setupMagicWindowControls: function () {
  48671. var magicWindowControls;
  48672. var data = this.data;
  48673. // Only on mobile devices and only enabled if DeviceOrientation permission has been granted.
  48674. if (utils.device.isMobile()) {
  48675. magicWindowControls = this.magicWindowControls = new THREE.DeviceOrientationControls(this.magicWindowObject);
  48676. if (typeof DeviceOrientationEvent !== 'undefined' && DeviceOrientationEvent.requestPermission) {
  48677. magicWindowControls.enabled = false;
  48678. if (this.el.sceneEl.components['device-orientation-permission-ui'].permissionGranted) {
  48679. magicWindowControls.enabled = data.magicWindowTrackingEnabled;
  48680. } else {
  48681. this.el.sceneEl.addEventListener('deviceorientationpermissiongranted', function () {
  48682. magicWindowControls.enabled = data.magicWindowTrackingEnabled;
  48683. });
  48684. }
  48685. }
  48686. }
  48687. },
  48688. update: function (oldData) {
  48689. var data = this.data;
  48690. // Disable grab cursor classes if no longer enabled.
  48691. if (data.enabled !== oldData.enabled) {
  48692. this.updateGrabCursor(data.enabled);
  48693. }
  48694. // Reset magic window eulers if tracking is disabled.
  48695. if (oldData && !data.magicWindowTrackingEnabled && oldData.magicWindowTrackingEnabled) {
  48696. this.magicWindowAbsoluteEuler.set(0, 0, 0);
  48697. this.magicWindowDeltaEuler.set(0, 0, 0);
  48698. }
  48699. // Pass on magic window tracking setting to magicWindowControls.
  48700. if (this.magicWindowControls) {
  48701. this.magicWindowControls.enabled = data.magicWindowTrackingEnabled;
  48702. }
  48703. if (oldData && !data.pointerLockEnabled !== oldData.pointerLockEnabled) {
  48704. this.removeEventListeners();
  48705. this.addEventListeners();
  48706. if (this.pointerLocked) { this.exitPointerLock(); }
  48707. }
  48708. },
  48709. tick: function (t) {
  48710. var data = this.data;
  48711. if (!data.enabled) { return; }
  48712. this.updateOrientation();
  48713. },
  48714. play: function () {
  48715. this.addEventListeners();
  48716. },
  48717. pause: function () {
  48718. this.removeEventListeners();
  48719. if (this.pointerLocked) { this.exitPointerLock(); }
  48720. },
  48721. remove: function () {
  48722. this.removeEventListeners();
  48723. if (this.pointerLocked) { this.exitPointerLock(); }
  48724. },
  48725. bindMethods: function () {
  48726. this.onMouseDown = bind(this.onMouseDown, this);
  48727. this.onMouseMove = bind(this.onMouseMove, this);
  48728. this.onMouseUp = bind(this.onMouseUp, this);
  48729. this.onTouchStart = bind(this.onTouchStart, this);
  48730. this.onTouchMove = bind(this.onTouchMove, this);
  48731. this.onTouchEnd = bind(this.onTouchEnd, this);
  48732. this.onEnterVR = bind(this.onEnterVR, this);
  48733. this.onExitVR = bind(this.onExitVR, this);
  48734. this.onPointerLockChange = bind(this.onPointerLockChange, this);
  48735. this.onPointerLockError = bind(this.onPointerLockError, this);
  48736. },
  48737. /**
  48738. * Set up states and Object3Ds needed to store rotation data.
  48739. */
  48740. setupMouseControls: function () {
  48741. this.mouseDown = false;
  48742. this.pitchObject = new THREE.Object3D();
  48743. this.yawObject = new THREE.Object3D();
  48744. this.yawObject.position.y = 10;
  48745. this.yawObject.add(this.pitchObject);
  48746. },
  48747. /**
  48748. * Add mouse and touch event listeners to canvas.
  48749. */
  48750. addEventListeners: function () {
  48751. var sceneEl = this.el.sceneEl;
  48752. var canvasEl = sceneEl.canvas;
  48753. // Wait for canvas to load.
  48754. if (!canvasEl) {
  48755. sceneEl.addEventListener('render-target-loaded', bind(this.addEventListeners, this));
  48756. return;
  48757. }
  48758. // Mouse events.
  48759. canvasEl.addEventListener('mousedown', this.onMouseDown, false);
  48760. window.addEventListener('mousemove', this.onMouseMove, false);
  48761. window.addEventListener('mouseup', this.onMouseUp, false);
  48762. // Touch events.
  48763. canvasEl.addEventListener('touchstart', this.onTouchStart);
  48764. window.addEventListener('touchmove', this.onTouchMove);
  48765. window.addEventListener('touchend', this.onTouchEnd);
  48766. // sceneEl events.
  48767. sceneEl.addEventListener('enter-vr', this.onEnterVR);
  48768. sceneEl.addEventListener('exit-vr', this.onExitVR);
  48769. // Pointer Lock events.
  48770. if (this.data.pointerLockEnabled) {
  48771. document.addEventListener('pointerlockchange', this.onPointerLockChange, false);
  48772. document.addEventListener('mozpointerlockchange', this.onPointerLockChange, false);
  48773. document.addEventListener('pointerlockerror', this.onPointerLockError, false);
  48774. }
  48775. },
  48776. /**
  48777. * Remove mouse and touch event listeners from canvas.
  48778. */
  48779. removeEventListeners: function () {
  48780. var sceneEl = this.el.sceneEl;
  48781. var canvasEl = sceneEl && sceneEl.canvas;
  48782. if (!canvasEl) { return; }
  48783. // Mouse events.
  48784. canvasEl.removeEventListener('mousedown', this.onMouseDown);
  48785. window.removeEventListener('mousemove', this.onMouseMove);
  48786. window.removeEventListener('mouseup', this.onMouseUp);
  48787. // Touch events.
  48788. canvasEl.removeEventListener('touchstart', this.onTouchStart);
  48789. window.removeEventListener('touchmove', this.onTouchMove);
  48790. window.removeEventListener('touchend', this.onTouchEnd);
  48791. // sceneEl events.
  48792. sceneEl.removeEventListener('enter-vr', this.onEnterVR);
  48793. sceneEl.removeEventListener('exit-vr', this.onExitVR);
  48794. // Pointer Lock events.
  48795. document.removeEventListener('pointerlockchange', this.onPointerLockChange, false);
  48796. document.removeEventListener('mozpointerlockchange', this.onPointerLockChange, false);
  48797. document.removeEventListener('pointerlockerror', this.onPointerLockError, false);
  48798. },
  48799. /**
  48800. * Update orientation for mobile, mouse drag, and headset.
  48801. * Mouse-drag only enabled if HMD is not active.
  48802. */
  48803. updateOrientation: (function () {
  48804. var poseMatrix = new THREE.Matrix4();
  48805. return function () {
  48806. var object3D = this.el.object3D;
  48807. var pitchObject = this.pitchObject;
  48808. var yawObject = this.yawObject;
  48809. var pose;
  48810. var sceneEl = this.el.sceneEl;
  48811. // In VR mode, THREE is in charge of updating the camera pose.
  48812. if (sceneEl.is('vr-mode') && sceneEl.checkHeadsetConnected()) {
  48813. // With WebXR THREE applies headset pose to the object3D matrixWorld internally.
  48814. // Reflect values back on position, rotation, scale for getAttribute to return the expected values.
  48815. if (sceneEl.hasWebXR) {
  48816. pose = sceneEl.renderer.xr.getCameraPose();
  48817. if (pose) {
  48818. poseMatrix.elements = pose.transform.matrix;
  48819. poseMatrix.decompose(object3D.position, object3D.rotation, object3D.scale);
  48820. }
  48821. }
  48822. return;
  48823. }
  48824. this.updateMagicWindowOrientation();
  48825. // On mobile, do camera rotation with touch events and sensors.
  48826. object3D.rotation.x = this.magicWindowDeltaEuler.x + pitchObject.rotation.x;
  48827. object3D.rotation.y = this.magicWindowDeltaEuler.y + yawObject.rotation.y;
  48828. object3D.rotation.z = this.magicWindowDeltaEuler.z;
  48829. };
  48830. })(),
  48831. updateMagicWindowOrientation: function () {
  48832. var magicWindowAbsoluteEuler = this.magicWindowAbsoluteEuler;
  48833. var magicWindowDeltaEuler = this.magicWindowDeltaEuler;
  48834. // Calculate magic window HMD quaternion.
  48835. if (this.magicWindowControls && this.magicWindowControls.enabled) {
  48836. this.magicWindowControls.update();
  48837. magicWindowAbsoluteEuler.setFromQuaternion(this.magicWindowObject.quaternion, 'YXZ');
  48838. if (!this.previousMagicWindowYaw && magicWindowAbsoluteEuler.y !== 0) {
  48839. this.previousMagicWindowYaw = magicWindowAbsoluteEuler.y;
  48840. }
  48841. if (this.previousMagicWindowYaw) {
  48842. magicWindowDeltaEuler.x = magicWindowAbsoluteEuler.x;
  48843. magicWindowDeltaEuler.y += magicWindowAbsoluteEuler.y - this.previousMagicWindowYaw;
  48844. magicWindowDeltaEuler.z = magicWindowAbsoluteEuler.z;
  48845. this.previousMagicWindowYaw = magicWindowAbsoluteEuler.y;
  48846. }
  48847. }
  48848. },
  48849. /**
  48850. * Translate mouse drag into rotation.
  48851. *
  48852. * Dragging up and down rotates the camera around the X-axis (yaw).
  48853. * Dragging left and right rotates the camera around the Y-axis (pitch).
  48854. */
  48855. onMouseMove: function (evt) {
  48856. var direction;
  48857. var movementX;
  48858. var movementY;
  48859. var pitchObject = this.pitchObject;
  48860. var previousMouseEvent = this.previousMouseEvent;
  48861. var yawObject = this.yawObject;
  48862. // Not dragging or not enabled.
  48863. if (!this.data.enabled || (!this.mouseDown && !this.pointerLocked)) { return; }
  48864. // Calculate delta.
  48865. if (this.pointerLocked) {
  48866. movementX = evt.movementX || evt.mozMovementX || 0;
  48867. movementY = evt.movementY || evt.mozMovementY || 0;
  48868. } else {
  48869. movementX = evt.screenX - previousMouseEvent.screenX;
  48870. movementY = evt.screenY - previousMouseEvent.screenY;
  48871. }
  48872. this.previousMouseEvent.screenX = evt.screenX;
  48873. this.previousMouseEvent.screenY = evt.screenY;
  48874. // Calculate rotation.
  48875. direction = this.data.reverseMouseDrag ? 1 : -1;
  48876. yawObject.rotation.y += movementX * 0.002 * direction;
  48877. pitchObject.rotation.x += movementY * 0.002 * direction;
  48878. pitchObject.rotation.x = Math.max(-PI_2, Math.min(PI_2, pitchObject.rotation.x));
  48879. },
  48880. /**
  48881. * Register mouse down to detect mouse drag.
  48882. */
  48883. onMouseDown: function (evt) {
  48884. var sceneEl = this.el.sceneEl;
  48885. if (!this.data.enabled || !this.data.mouseEnabled || (sceneEl.is('vr-mode') && sceneEl.checkHeadsetConnected())) { return; }
  48886. // Handle only primary button.
  48887. if (evt.button !== 0) { return; }
  48888. var canvasEl = sceneEl && sceneEl.canvas;
  48889. this.mouseDown = true;
  48890. this.previousMouseEvent.screenX = evt.screenX;
  48891. this.previousMouseEvent.screenY = evt.screenY;
  48892. this.showGrabbingCursor();
  48893. if (this.data.pointerLockEnabled && !this.pointerLocked) {
  48894. if (canvasEl.requestPointerLock) {
  48895. canvasEl.requestPointerLock();
  48896. } else if (canvasEl.mozRequestPointerLock) {
  48897. canvasEl.mozRequestPointerLock();
  48898. }
  48899. }
  48900. },
  48901. /**
  48902. * Shows grabbing cursor on scene
  48903. */
  48904. showGrabbingCursor: function () {
  48905. this.el.sceneEl.canvas.style.cursor = 'grabbing';
  48906. },
  48907. /**
  48908. * Hides grabbing cursor on scene
  48909. */
  48910. hideGrabbingCursor: function () {
  48911. this.el.sceneEl.canvas.style.cursor = '';
  48912. },
  48913. /**
  48914. * Register mouse up to detect release of mouse drag.
  48915. */
  48916. onMouseUp: function () {
  48917. this.mouseDown = false;
  48918. this.hideGrabbingCursor();
  48919. },
  48920. /**
  48921. * Register touch down to detect touch drag.
  48922. */
  48923. onTouchStart: function (evt) {
  48924. if (evt.touches.length !== 1 ||
  48925. !this.data.touchEnabled ||
  48926. this.el.sceneEl.is('vr-mode')) { return; }
  48927. this.touchStart = {
  48928. x: evt.touches[0].pageX,
  48929. y: evt.touches[0].pageY
  48930. };
  48931. this.touchStarted = true;
  48932. },
  48933. /**
  48934. * Translate touch move to Y-axis rotation.
  48935. */
  48936. onTouchMove: function (evt) {
  48937. var direction;
  48938. var canvas = this.el.sceneEl.canvas;
  48939. var deltaY;
  48940. var yawObject = this.yawObject;
  48941. if (!this.touchStarted || !this.data.touchEnabled) { return; }
  48942. deltaY = 2 * Math.PI * (evt.touches[0].pageX - this.touchStart.x) / canvas.clientWidth;
  48943. direction = this.data.reverseTouchDrag ? 1 : -1;
  48944. // Limit touch orientaion to to yaw (y axis).
  48945. yawObject.rotation.y -= deltaY * 0.5 * direction;
  48946. this.touchStart = {
  48947. x: evt.touches[0].pageX,
  48948. y: evt.touches[0].pageY
  48949. };
  48950. },
  48951. /**
  48952. * Register touch end to detect release of touch drag.
  48953. */
  48954. onTouchEnd: function () {
  48955. this.touchStarted = false;
  48956. },
  48957. /**
  48958. * Save pose.
  48959. */
  48960. onEnterVR: function () {
  48961. var sceneEl = this.el.sceneEl;
  48962. if (!sceneEl.checkHeadsetConnected()) { return; }
  48963. this.saveCameraPose();
  48964. this.el.object3D.position.set(0, 0, 0);
  48965. this.el.object3D.rotation.set(0, 0, 0);
  48966. if (sceneEl.hasWebXR) {
  48967. this.el.object3D.matrixAutoUpdate = false;
  48968. this.el.object3D.updateMatrix();
  48969. }
  48970. },
  48971. /**
  48972. * Restore the pose.
  48973. */
  48974. onExitVR: function () {
  48975. if (!this.el.sceneEl.checkHeadsetConnected()) { return; }
  48976. this.restoreCameraPose();
  48977. this.previousHMDPosition.set(0, 0, 0);
  48978. this.el.object3D.matrixAutoUpdate = true;
  48979. },
  48980. /**
  48981. * Update Pointer Lock state.
  48982. */
  48983. onPointerLockChange: function () {
  48984. this.pointerLocked = !!(document.pointerLockElement || document.mozPointerLockElement);
  48985. },
  48986. /**
  48987. * Recover from Pointer Lock error.
  48988. */
  48989. onPointerLockError: function () {
  48990. this.pointerLocked = false;
  48991. },
  48992. // Exits pointer-locked mode.
  48993. exitPointerLock: function () {
  48994. document.exitPointerLock();
  48995. this.pointerLocked = false;
  48996. },
  48997. /**
  48998. * Toggle the feature of showing/hiding the grab cursor.
  48999. */
  49000. updateGrabCursor: function (enabled) {
  49001. var sceneEl = this.el.sceneEl;
  49002. function enableGrabCursor () { sceneEl.canvas.classList.add('a-grab-cursor'); }
  49003. function disableGrabCursor () { sceneEl.canvas.classList.remove('a-grab-cursor'); }
  49004. if (!sceneEl.canvas) {
  49005. if (enabled) {
  49006. sceneEl.addEventListener('render-target-loaded', enableGrabCursor);
  49007. } else {
  49008. sceneEl.addEventListener('render-target-loaded', disableGrabCursor);
  49009. }
  49010. return;
  49011. }
  49012. if (enabled) {
  49013. enableGrabCursor();
  49014. return;
  49015. }
  49016. disableGrabCursor();
  49017. },
  49018. /**
  49019. * Save camera pose before entering VR to restore later if exiting.
  49020. */
  49021. saveCameraPose: function () {
  49022. var el = this.el;
  49023. this.savedPose.position.copy(el.object3D.position);
  49024. this.savedPose.rotation.copy(el.object3D.rotation);
  49025. this.hasSavedPose = true;
  49026. },
  49027. /**
  49028. * Reset camera pose to before entering VR.
  49029. */
  49030. restoreCameraPose: function () {
  49031. var el = this.el;
  49032. var savedPose = this.savedPose;
  49033. if (!this.hasSavedPose) { return; }
  49034. // Reset camera orientation.
  49035. el.object3D.position.copy(savedPose.position);
  49036. el.object3D.rotation.copy(savedPose.rotation);
  49037. this.hasSavedPose = false;
  49038. }
  49039. });
  49040. },{"../core/component":131,"../lib/three":179,"../utils/":205}],91:[function(_dereq_,module,exports){
  49041. var bind = _dereq_('../utils/bind');
  49042. var registerComponent = _dereq_('../core/component').registerComponent;
  49043. var trackedControlsUtils = _dereq_('../utils/tracked-controls');
  49044. var checkControllerPresentAndSetup = trackedControlsUtils.checkControllerPresentAndSetup;
  49045. var emitIfAxesChanged = trackedControlsUtils.emitIfAxesChanged;
  49046. var onButtonEvent = trackedControlsUtils.onButtonEvent;
  49047. // See Profiles Registry:
  49048. // https://github.com/immersive-web/webxr-input-profiles/tree/master/packages/registry
  49049. // TODO: Add a more robust system for deriving gamepad name.
  49050. var GAMEPAD_ID_PREFIX = 'magicleap';
  49051. var GAMEPAD_ID_SUFFIX = '-one';
  49052. var GAMEPAD_ID_COMPOSITE = GAMEPAD_ID_PREFIX + GAMEPAD_ID_SUFFIX;
  49053. var MAGICLEAP_CONTROLLER_MODEL_GLB_URL = 'https://cdn.aframe.io/controllers/magicleap/magicleap-one-controller.glb';
  49054. /**
  49055. * Button IDs:
  49056. * 0 - trigger
  49057. * 1 - grip
  49058. * 2 - touchpad
  49059. * 3 - menu (never dispatched on this layer)
  49060. *
  49061. * Axis:
  49062. * 0 - touchpad x axis
  49063. * 1 - touchpad y axis
  49064. */
  49065. var INPUT_MAPPING_WEBXR = {
  49066. axes: {touchpad: [0, 1]},
  49067. buttons: ['trigger', 'grip', 'touchpad', 'menu']
  49068. };
  49069. /**
  49070. * Magic Leap Controls
  49071. * Interface with Magic Leap control and map Gamepad events to controller
  49072. * buttons: trigger, grip, touchpad, and menu.
  49073. * Load a controller model.
  49074. */
  49075. module.exports.Component = registerComponent('magicleap-controls', {
  49076. schema: {
  49077. hand: {default: 'none'},
  49078. model: {default: true},
  49079. orientationOffset: {type: 'vec3'}
  49080. },
  49081. mapping: INPUT_MAPPING_WEBXR,
  49082. init: function () {
  49083. var self = this;
  49084. this.controllerPresent = false;
  49085. this.lastControllerCheck = 0;
  49086. this.onButtonChanged = bind(this.onButtonChanged, this);
  49087. this.onButtonDown = function (evt) { onButtonEvent(evt.detail.id, 'down', self); };
  49088. this.onButtonUp = function (evt) { onButtonEvent(evt.detail.id, 'up', self); };
  49089. this.onButtonTouchEnd = function (evt) { onButtonEvent(evt.detail.id, 'touchend', self); };
  49090. this.onButtonTouchStart = function (evt) { onButtonEvent(evt.detail.id, 'touchstart', self); };
  49091. this.previousButtonValues = {};
  49092. this.rendererSystem = this.el.sceneEl.systems.renderer;
  49093. this.bindMethods();
  49094. },
  49095. update: function () {
  49096. var data = this.data;
  49097. this.controllerIndex = data.hand === 'right' ? 0 : data.hand === 'left' ? 1 : 2;
  49098. },
  49099. play: function () {
  49100. this.checkIfControllerPresent();
  49101. this.addControllersUpdateListener();
  49102. },
  49103. pause: function () {
  49104. this.removeEventListeners();
  49105. this.removeControllersUpdateListener();
  49106. },
  49107. bindMethods: function () {
  49108. this.onModelLoaded = bind(this.onModelLoaded, this);
  49109. this.onControllersUpdate = bind(this.onControllersUpdate, this);
  49110. this.checkIfControllerPresent = bind(this.checkIfControllerPresent, this);
  49111. this.removeControllersUpdateListener = bind(this.removeControllersUpdateListener, this);
  49112. this.onAxisMoved = bind(this.onAxisMoved, this);
  49113. },
  49114. addEventListeners: function () {
  49115. var el = this.el;
  49116. el.addEventListener('buttonchanged', this.onButtonChanged);
  49117. el.addEventListener('buttondown', this.onButtonDown);
  49118. el.addEventListener('buttonup', this.onButtonUp);
  49119. el.addEventListener('touchstart', this.onButtonTouchStart);
  49120. el.addEventListener('touchend', this.onButtonTouchEnd);
  49121. el.addEventListener('axismove', this.onAxisMoved);
  49122. el.addEventListener('model-loaded', this.onModelLoaded);
  49123. this.controllerEventsActive = true;
  49124. },
  49125. removeEventListeners: function () {
  49126. var el = this.el;
  49127. el.removeEventListener('buttonchanged', this.onButtonChanged);
  49128. el.removeEventListener('buttondown', this.onButtonDown);
  49129. el.removeEventListener('buttonup', this.onButtonUp);
  49130. el.removeEventListener('touchstart', this.onButtonTouchStart);
  49131. el.removeEventListener('touchend', this.onButtonTouchEnd);
  49132. el.removeEventListener('axismove', this.onAxisMoved);
  49133. el.removeEventListener('model-loaded', this.onModelLoaded);
  49134. this.controllerEventsActive = false;
  49135. },
  49136. checkIfControllerPresent: function () {
  49137. var data = this.data;
  49138. checkControllerPresentAndSetup(this, GAMEPAD_ID_COMPOSITE,
  49139. {index: this.controllerIndex, hand: data.hand});
  49140. },
  49141. injectTrackedControls: function () {
  49142. var el = this.el;
  49143. var data = this.data;
  49144. el.setAttribute('tracked-controls', {
  49145. // TODO: verify expected behavior between reserved prefixes.
  49146. idPrefix: GAMEPAD_ID_COMPOSITE,
  49147. hand: data.hand,
  49148. controller: this.controllerIndex,
  49149. orientationOffset: data.orientationOffset
  49150. });
  49151. // Load model.
  49152. if (!this.data.model) { return; }
  49153. this.el.setAttribute('gltf-model', MAGICLEAP_CONTROLLER_MODEL_GLB_URL);
  49154. },
  49155. addControllersUpdateListener: function () {
  49156. this.el.sceneEl.addEventListener('controllersupdated', this.onControllersUpdate, false);
  49157. },
  49158. removeControllersUpdateListener: function () {
  49159. this.el.sceneEl.removeEventListener('controllersupdated', this.onControllersUpdate, false);
  49160. },
  49161. onControllersUpdate: function () {
  49162. // Note that due to gamepadconnected event propagation issues, we don't rely on events.
  49163. this.checkIfControllerPresent();
  49164. },
  49165. /**
  49166. * Rotate the trigger button based on how hard the trigger is pressed.
  49167. */
  49168. onButtonChanged: function (evt) {
  49169. var button = this.mapping.buttons[evt.detail.id];
  49170. var analogValue;
  49171. if (!button) { return; }
  49172. if (button === 'trigger') {
  49173. analogValue = evt.detail.state.value;
  49174. console.log('analog value of trigger press: ' + analogValue);
  49175. }
  49176. // Pass along changed event with button state, using button mapping for convenience.
  49177. this.el.emit(button + 'changed', evt.detail.state);
  49178. },
  49179. onModelLoaded: function (evt) {
  49180. var controllerObject3D = evt.detail.model;
  49181. // our glb scale is too large.
  49182. controllerObject3D.scale.set(0.01, 0.01, 0.01);
  49183. },
  49184. onAxisMoved: function (evt) {
  49185. emitIfAxesChanged(this, this.mapping.axes, evt);
  49186. },
  49187. updateModel: function (buttonName, evtName) {},
  49188. setButtonColor: function (buttonName, color) {}
  49189. });
  49190. },{"../core/component":131,"../utils/bind":199,"../utils/tracked-controls":214}],92:[function(_dereq_,module,exports){
  49191. /* global Promise */
  49192. var utils = _dereq_('../utils/');
  49193. var component = _dereq_('../core/component');
  49194. var THREE = _dereq_('../lib/three');
  49195. var shader = _dereq_('../core/shader');
  49196. var error = utils.debug('components:material:error');
  49197. var registerComponent = component.registerComponent;
  49198. var shaders = shader.shaders;
  49199. var shaderNames = shader.shaderNames;
  49200. /**
  49201. * Material component.
  49202. *
  49203. * @member {object} shader - Determines how material is shaded. Defaults to `standard`,
  49204. * three.js's implementation of PBR. Another standard shading model is `flat` which
  49205. * uses MeshBasicMaterial.
  49206. */
  49207. module.exports.Component = registerComponent('material', {
  49208. schema: {
  49209. alphaTest: {default: 0.0, min: 0.0, max: 1.0},
  49210. depthTest: {default: true},
  49211. depthWrite: {default: true},
  49212. flatShading: {default: false},
  49213. npot: {default: false},
  49214. offset: {type: 'vec2', default: {x: 0, y: 0}},
  49215. opacity: {default: 1.0, min: 0.0, max: 1.0},
  49216. repeat: {type: 'vec2', default: {x: 1, y: 1}},
  49217. shader: {default: 'standard', oneOf: shaderNames, schemaChange: true},
  49218. side: {default: 'front', oneOf: ['front', 'back', 'double']},
  49219. transparent: {default: false},
  49220. vertexColors: {type: 'string', default: 'none', oneOf: ['face', 'vertex']},
  49221. visible: {default: true},
  49222. blending: {default: 'normal', oneOf: ['none', 'normal', 'additive', 'subtractive', 'multiply']},
  49223. dithering: {default: true}
  49224. },
  49225. init: function () {
  49226. this.material = null;
  49227. },
  49228. /**
  49229. * Update or create material.
  49230. *
  49231. * @param {object|null} oldData
  49232. */
  49233. update: function (oldData) {
  49234. var data = this.data;
  49235. if (!this.shader || data.shader !== oldData.shader) {
  49236. this.updateShader(data.shader);
  49237. }
  49238. this.shader.update(this.data);
  49239. this.updateMaterial(oldData);
  49240. },
  49241. updateSchema: function (data) {
  49242. var currentShader;
  49243. var newShader;
  49244. var schema;
  49245. var shader;
  49246. newShader = data && data.shader;
  49247. currentShader = this.oldData && this.oldData.shader;
  49248. shader = newShader || currentShader;
  49249. schema = shaders[shader] && shaders[shader].schema;
  49250. if (!schema) { error('Unknown shader schema ' + shader); }
  49251. if (currentShader && newShader === currentShader) { return; }
  49252. this.extendSchema(schema);
  49253. this.updateBehavior();
  49254. },
  49255. updateBehavior: function () {
  49256. var key;
  49257. var sceneEl = this.el.sceneEl;
  49258. var schema = this.schema;
  49259. var self = this;
  49260. var tickProperties;
  49261. function tickTime (time, delta) {
  49262. var key;
  49263. for (key in tickProperties) {
  49264. tickProperties[key] = time;
  49265. }
  49266. self.shader.update(tickProperties);
  49267. }
  49268. this.tick = undefined;
  49269. tickProperties = {};
  49270. for (key in schema) {
  49271. if (schema[key].type === 'time') {
  49272. this.tick = tickTime;
  49273. tickProperties[key] = true;
  49274. }
  49275. }
  49276. if (!sceneEl) { return; }
  49277. if (this.tick) {
  49278. sceneEl.addBehavior(this);
  49279. } else {
  49280. sceneEl.removeBehavior(this);
  49281. }
  49282. },
  49283. updateShader: function (shaderName) {
  49284. var data = this.data;
  49285. var Shader = shaders[shaderName] && shaders[shaderName].Shader;
  49286. var shaderInstance;
  49287. if (!Shader) { throw new Error('Unknown shader ' + shaderName); }
  49288. // Get material from A-Frame shader.
  49289. shaderInstance = this.shader = new Shader();
  49290. shaderInstance.el = this.el;
  49291. shaderInstance.init(data);
  49292. this.setMaterial(shaderInstance.material);
  49293. this.updateSchema(data);
  49294. },
  49295. /**
  49296. * Set and update base material properties.
  49297. * Set `needsUpdate` when needed.
  49298. */
  49299. updateMaterial: function (oldData) {
  49300. var data = this.data;
  49301. var material = this.material;
  49302. var oldDataHasKeys;
  49303. // Base material properties.
  49304. material.alphaTest = data.alphaTest;
  49305. material.depthTest = data.depthTest !== false;
  49306. material.depthWrite = data.depthWrite !== false;
  49307. material.opacity = data.opacity;
  49308. material.flatShading = data.flatShading;
  49309. material.side = parseSide(data.side);
  49310. material.transparent = data.transparent !== false || data.opacity < 1.0;
  49311. material.vertexColors = parseVertexColors(data.vertexColors);
  49312. material.visible = data.visible;
  49313. material.blending = parseBlending(data.blending);
  49314. material.dithering = data.dithering;
  49315. // Check if material needs update.
  49316. for (oldDataHasKeys in oldData) { break; }
  49317. if (oldDataHasKeys &&
  49318. (oldData.alphaTest !== data.alphaTest ||
  49319. oldData.side !== data.side ||
  49320. oldData.vertexColors !== data.vertexColors)) {
  49321. material.needsUpdate = true;
  49322. }
  49323. },
  49324. /**
  49325. * Remove material on remove (callback).
  49326. * Dispose of it from memory and unsubscribe from scene updates.
  49327. */
  49328. remove: function () {
  49329. var defaultMaterial = new THREE.MeshBasicMaterial();
  49330. var material = this.material;
  49331. var object3D = this.el.getObject3D('mesh');
  49332. if (object3D) { object3D.material = defaultMaterial; }
  49333. disposeMaterial(material, this.system);
  49334. },
  49335. /**
  49336. * (Re)create new material. Has side-effects of setting `this.material` and updating
  49337. * material registration in scene.
  49338. *
  49339. * @param {object} data - Material component data.
  49340. * @param {object} type - Material type to create.
  49341. * @returns {object} Material.
  49342. */
  49343. setMaterial: function (material) {
  49344. var el = this.el;
  49345. var mesh;
  49346. var system = this.system;
  49347. if (this.material) { disposeMaterial(this.material, system); }
  49348. this.material = material;
  49349. system.registerMaterial(material);
  49350. // Set on mesh. If mesh does not exist, wait for it.
  49351. mesh = el.getObject3D('mesh');
  49352. if (mesh) {
  49353. mesh.material = material;
  49354. } else {
  49355. el.addEventListener('object3dset', function waitForMesh (evt) {
  49356. if (evt.detail.type !== 'mesh' || evt.target !== el) { return; }
  49357. el.getObject3D('mesh').material = material;
  49358. el.removeEventListener('object3dset', waitForMesh);
  49359. });
  49360. }
  49361. }
  49362. });
  49363. /**
  49364. * Return a three.js constant determining which material face sides to render
  49365. * based on the side parameter (passed as a component property).
  49366. *
  49367. * @param {string} [side=front] - `front`, `back`, or `double`.
  49368. * @returns {number} THREE.FrontSide, THREE.BackSide, or THREE.DoubleSide.
  49369. */
  49370. function parseSide (side) {
  49371. switch (side) {
  49372. case 'back': {
  49373. return THREE.BackSide;
  49374. }
  49375. case 'double': {
  49376. return THREE.DoubleSide;
  49377. }
  49378. default: {
  49379. // Including case `front`.
  49380. return THREE.FrontSide;
  49381. }
  49382. }
  49383. }
  49384. /**
  49385. * Return a three.js constant determining vertex coloring.
  49386. */
  49387. function parseVertexColors (coloring) {
  49388. switch (coloring) {
  49389. case 'face': {
  49390. return THREE.FaceColors;
  49391. }
  49392. case 'vertex': {
  49393. return THREE.VertexColors;
  49394. }
  49395. default: {
  49396. return THREE.NoColors;
  49397. }
  49398. }
  49399. }
  49400. /**
  49401. * Return a three.js constant determining blending
  49402. *
  49403. * @param {string} [blending=normal]
  49404. * - `none`, additive`, `subtractive`,`multiply` or `normal`.
  49405. * @returns {number}
  49406. */
  49407. function parseBlending (blending) {
  49408. switch (blending) {
  49409. case 'none': {
  49410. return THREE.NoBlending;
  49411. }
  49412. case 'additive': {
  49413. return THREE.AdditiveBlending;
  49414. }
  49415. case 'subtractive': {
  49416. return THREE.SubtractiveBlending;
  49417. }
  49418. case 'multiply': {
  49419. return THREE.MultiplyBlending;
  49420. }
  49421. default: {
  49422. return THREE.NormalBlending;
  49423. }
  49424. }
  49425. }
  49426. /**
  49427. * Dispose of material from memory and unsubscribe material from scene updates like fog.
  49428. */
  49429. function disposeMaterial (material, system) {
  49430. material.dispose();
  49431. system.unregisterMaterial(material);
  49432. }
  49433. },{"../core/component":131,"../core/shader":141,"../lib/three":179,"../utils/":205}],93:[function(_dereq_,module,exports){
  49434. var debug = _dereq_('../utils/debug');
  49435. var registerComponent = _dereq_('../core/component').registerComponent;
  49436. var THREE = _dereq_('../lib/three');
  49437. var warn = debug('components:obj-model:warn');
  49438. module.exports.Component = registerComponent('obj-model', {
  49439. schema: {
  49440. mtl: {type: 'model'},
  49441. obj: {type: 'model'}
  49442. },
  49443. init: function () {
  49444. var self = this;
  49445. this.model = null;
  49446. this.objLoader = new THREE.OBJLoader();
  49447. this.mtlLoader = new THREE.MTLLoader(this.objLoader.manager);
  49448. // Allow cross-origin images to be loaded.
  49449. this.mtlLoader.crossOrigin = '';
  49450. this.el.addEventListener('componentinitialized', function (evt) {
  49451. if (!self.model) { return; }
  49452. if (evt.detail.name !== 'material') { return; }
  49453. self.applyMaterial();
  49454. });
  49455. },
  49456. update: function () {
  49457. var data = this.data;
  49458. if (!data.obj) { return; }
  49459. this.resetMesh();
  49460. this.loadObj(data.obj, data.mtl);
  49461. },
  49462. remove: function () {
  49463. if (!this.model) { return; }
  49464. this.resetMesh();
  49465. },
  49466. resetMesh: function () {
  49467. this.el.removeObject3D('mesh');
  49468. },
  49469. loadObj: function (objUrl, mtlUrl) {
  49470. var self = this;
  49471. var el = this.el;
  49472. var mtlLoader = this.mtlLoader;
  49473. var objLoader = this.objLoader;
  49474. var rendererSystem = this.el.sceneEl.systems.renderer;
  49475. var BASE_PATH = mtlUrl.substr(0, mtlUrl.lastIndexOf('/') + 1);
  49476. if (mtlUrl) {
  49477. // .OBJ with an .MTL.
  49478. if (el.hasAttribute('material')) {
  49479. warn('Material component properties are ignored when a .MTL is provided');
  49480. }
  49481. mtlLoader.setResourcePath(BASE_PATH);
  49482. mtlLoader.load(mtlUrl, function (materials) {
  49483. materials.preload();
  49484. objLoader.setMaterials(materials);
  49485. objLoader.load(objUrl, function (objModel) {
  49486. self.model = objModel;
  49487. self.model.traverse(function (object) {
  49488. if (object.isMesh) {
  49489. var material = object.material;
  49490. if (material.color) rendererSystem.applyColorCorrection(material.color);
  49491. if (material.map) rendererSystem.applyColorCorrection(material.map);
  49492. if (material.emissive) rendererSystem.applyColorCorrection(material.emissive);
  49493. if (material.emissiveMap) rendererSystem.applyColorCorrection(material.emissiveMap);
  49494. }
  49495. });
  49496. el.setObject3D('mesh', objModel);
  49497. el.emit('model-loaded', {format: 'obj', model: objModel});
  49498. });
  49499. });
  49500. return;
  49501. }
  49502. // .OBJ only.
  49503. objLoader.load(objUrl, function loadObjOnly (objModel) {
  49504. self.model = objModel;
  49505. self.applyMaterial();
  49506. el.setObject3D('mesh', objModel);
  49507. el.emit('model-loaded', {format: 'obj', model: objModel});
  49508. });
  49509. },
  49510. /**
  49511. * Apply material from material component recursively.
  49512. */
  49513. applyMaterial: function () {
  49514. var material = this.el.components.material;
  49515. if (!material) { return; }
  49516. this.model.traverse(function (child) {
  49517. if (child instanceof THREE.Mesh) {
  49518. child.material = material.material;
  49519. }
  49520. });
  49521. }
  49522. });
  49523. },{"../core/component":131,"../lib/three":179,"../utils/debug":201}],94:[function(_dereq_,module,exports){
  49524. var registerComponent = _dereq_('../core/component').registerComponent;
  49525. var bind = _dereq_('../utils/bind');
  49526. var trackedControlsUtils = _dereq_('../utils/tracked-controls');
  49527. var checkControllerPresentAndSetup = trackedControlsUtils.checkControllerPresentAndSetup;
  49528. var emitIfAxesChanged = trackedControlsUtils.emitIfAxesChanged;
  49529. var onButtonEvent = trackedControlsUtils.onButtonEvent;
  49530. var isWebXRAvailable = _dereq_('../utils/').device.isWebXRAvailable;
  49531. var GAMEPAD_ID_WEBXR = 'oculus-go';
  49532. var GAMEPAD_ID_WEBVR = 'Oculus Go';
  49533. var OCULUS_GO_CONTROLLER_MODEL_URL = 'https://cdn.aframe.io/controllers/oculus/go/oculus-go-controller.gltf';
  49534. // Prefix for Gen1 and Gen2 Oculus Touch Controllers.
  49535. var GAMEPAD_ID_PREFIX = isWebXRAvailable ? GAMEPAD_ID_WEBXR : GAMEPAD_ID_WEBVR;
  49536. /**
  49537. * Button indices:
  49538. * 0 - trackpad
  49539. * 1 - trigger
  49540. *
  49541. * Axis:
  49542. * 0 - trackpad x
  49543. * 1 - trackpad y
  49544. */
  49545. var INPUT_MAPPING_WEBVR = {
  49546. axes: {trackpad: [0, 1]},
  49547. buttons: ['trackpad', 'trigger']
  49548. };
  49549. /**
  49550. * Button indices:
  49551. * 0 - trigger
  49552. * 1 - none
  49553. * 2 - touchpad
  49554. *
  49555. * Axis:
  49556. * 0 - touchpad x
  49557. * 1 - touchpad y
  49558. * Reference: https://github.com/immersive-web/webxr-input-profiles/blob/master/packages/registry/profiles/oculus/oculus-go.json
  49559. */
  49560. var INPUT_MAPPING_WEBXR = {
  49561. axes: {touchpad: [0, 1]},
  49562. buttons: ['trigger', 'none', 'touchpad']
  49563. };
  49564. var INPUT_MAPPING = isWebXRAvailable ? INPUT_MAPPING_WEBXR : INPUT_MAPPING_WEBVR;
  49565. /**
  49566. * Oculus Go controls.
  49567. * Interface with Oculus Go controller and map Gamepad events to
  49568. * controller buttons: trackpad, trigger
  49569. * Load a controller model and highlight the pressed buttons.
  49570. */
  49571. module.exports.Component = registerComponent('oculus-go-controls', {
  49572. schema: {
  49573. hand: {default: ''}, // This informs the degenerate arm model.
  49574. buttonColor: {type: 'color', default: '#FFFFFF'},
  49575. buttonTouchedColor: {type: 'color', default: '#BBBBBB'},
  49576. buttonHighlightColor: {type: 'color', default: '#7A7A7A'},
  49577. model: {default: true},
  49578. orientationOffset: {type: 'vec3'},
  49579. armModel: {default: true}
  49580. },
  49581. mapping: INPUT_MAPPING,
  49582. bindMethods: function () {
  49583. this.onModelLoaded = bind(this.onModelLoaded, this);
  49584. this.onControllersUpdate = bind(this.onControllersUpdate, this);
  49585. this.checkIfControllerPresent = bind(this.checkIfControllerPresent, this);
  49586. this.removeControllersUpdateListener = bind(this.removeControllersUpdateListener, this);
  49587. this.onAxisMoved = bind(this.onAxisMoved, this);
  49588. },
  49589. init: function () {
  49590. var self = this;
  49591. this.onButtonChanged = bind(this.onButtonChanged, this);
  49592. this.onButtonDown = function (evt) { onButtonEvent(evt.detail.id, 'down', self); };
  49593. this.onButtonUp = function (evt) { onButtonEvent(evt.detail.id, 'up', self); };
  49594. this.onButtonTouchStart = function (evt) { onButtonEvent(evt.detail.id, 'touchstart', self); };
  49595. this.onButtonTouchEnd = function (evt) { onButtonEvent(evt.detail.id, 'touchend', self); };
  49596. this.controllerPresent = false;
  49597. this.lastControllerCheck = 0;
  49598. this.rendererSystem = this.el.sceneEl.systems.renderer;
  49599. this.bindMethods();
  49600. },
  49601. addEventListeners: function () {
  49602. var el = this.el;
  49603. el.addEventListener('buttonchanged', this.onButtonChanged);
  49604. el.addEventListener('buttondown', this.onButtonDown);
  49605. el.addEventListener('buttonup', this.onButtonUp);
  49606. el.addEventListener('touchstart', this.onButtonTouchStart);
  49607. el.addEventListener('touchend', this.onButtonTouchEnd);
  49608. el.addEventListener('model-loaded', this.onModelLoaded);
  49609. el.addEventListener('axismove', this.onAxisMoved);
  49610. this.controllerEventsActive = true;
  49611. },
  49612. removeEventListeners: function () {
  49613. var el = this.el;
  49614. el.removeEventListener('buttonchanged', this.onButtonChanged);
  49615. el.removeEventListener('buttondown', this.onButtonDown);
  49616. el.removeEventListener('buttonup', this.onButtonUp);
  49617. el.removeEventListener('touchstart', this.onButtonTouchStart);
  49618. el.removeEventListener('touchend', this.onButtonTouchEnd);
  49619. el.removeEventListener('model-loaded', this.onModelLoaded);
  49620. el.removeEventListener('axismove', this.onAxisMoved);
  49621. this.controllerEventsActive = false;
  49622. },
  49623. checkIfControllerPresent: function () {
  49624. checkControllerPresentAndSetup(this, GAMEPAD_ID_PREFIX,
  49625. this.data.hand ? {hand: this.data.hand} : {});
  49626. },
  49627. play: function () {
  49628. this.checkIfControllerPresent();
  49629. this.addControllersUpdateListener();
  49630. },
  49631. pause: function () {
  49632. this.removeEventListeners();
  49633. this.removeControllersUpdateListener();
  49634. },
  49635. injectTrackedControls: function () {
  49636. var el = this.el;
  49637. var data = this.data;
  49638. el.setAttribute('tracked-controls', {
  49639. armModel: data.armModel,
  49640. hand: data.hand,
  49641. idPrefix: GAMEPAD_ID_PREFIX,
  49642. orientationOffset: data.orientationOffset
  49643. });
  49644. if (!this.data.model) { return; }
  49645. this.el.setAttribute('gltf-model', OCULUS_GO_CONTROLLER_MODEL_URL);
  49646. },
  49647. addControllersUpdateListener: function () {
  49648. this.el.sceneEl.addEventListener('controllersupdated', this.onControllersUpdate, false);
  49649. },
  49650. removeControllersUpdateListener: function () {
  49651. this.el.sceneEl.removeEventListener('controllersupdated', this.onControllersUpdate, false);
  49652. },
  49653. onControllersUpdate: function () {
  49654. this.checkIfControllerPresent();
  49655. },
  49656. // No need for onButtonChanged, since Oculus Go controller has no analog buttons.
  49657. onModelLoaded: function (evt) {
  49658. var controllerObject3D = evt.detail.model;
  49659. var buttonMeshes;
  49660. if (!this.data.model) { return; }
  49661. buttonMeshes = this.buttonMeshes = {};
  49662. buttonMeshes.trigger = controllerObject3D.getObjectByName('oculus_go_button_trigger');
  49663. buttonMeshes.trackpad = controllerObject3D.getObjectByName('oculus_go_touchpad');
  49664. buttonMeshes.touchpad = controllerObject3D.getObjectByName('oculus_go_touchpad');
  49665. },
  49666. onButtonChanged: function (evt) {
  49667. var button = this.mapping.buttons[evt.detail.id];
  49668. if (!button) return;
  49669. // Pass along changed event with button state, using button mapping for convenience.
  49670. this.el.emit(button + 'changed', evt.detail.state);
  49671. },
  49672. onAxisMoved: function (evt) {
  49673. emitIfAxesChanged(this, this.mapping.axes, evt);
  49674. },
  49675. updateModel: function (buttonName, evtName) {
  49676. if (!this.data.model) { return; }
  49677. this.updateButtonModel(buttonName, evtName);
  49678. },
  49679. updateButtonModel: function (buttonName, state) {
  49680. var buttonMeshes = this.buttonMeshes;
  49681. if (!buttonMeshes || !buttonMeshes[buttonName]) { return; }
  49682. var color;
  49683. var button;
  49684. switch (state) {
  49685. case 'down':
  49686. color = this.data.buttonHighlightColor;
  49687. break;
  49688. case 'touchstart':
  49689. color = this.data.buttonTouchedColor;
  49690. break;
  49691. default:
  49692. color = this.data.buttonColor;
  49693. }
  49694. button = buttonMeshes[buttonName];
  49695. button.material.color.set(color);
  49696. this.rendererSystem.applyColorCorrection(button.material.color);
  49697. }
  49698. });
  49699. },{"../core/component":131,"../utils/":205,"../utils/bind":199,"../utils/tracked-controls":214}],95:[function(_dereq_,module,exports){
  49700. var bind = _dereq_('../utils/bind');
  49701. var registerComponent = _dereq_('../core/component').registerComponent;
  49702. var THREE = _dereq_('../lib/three');
  49703. var trackedControlsUtils = _dereq_('../utils/tracked-controls');
  49704. var checkControllerPresentAndSetup = trackedControlsUtils.checkControllerPresentAndSetup;
  49705. var emitIfAxesChanged = trackedControlsUtils.emitIfAxesChanged;
  49706. var onButtonEvent = trackedControlsUtils.onButtonEvent;
  49707. var isWebXRAvailable = _dereq_('../utils/').device.isWebXRAvailable;
  49708. var GAMEPAD_ID_WEBXR = 'oculus-touch';
  49709. var GAMEPAD_ID_WEBVR = 'Oculus Touch';
  49710. // Prefix for Gen1 and Gen2 Oculus Touch Controllers.
  49711. var GAMEPAD_ID_PREFIX = isWebXRAvailable ? GAMEPAD_ID_WEBXR : GAMEPAD_ID_WEBVR;
  49712. // First generation model URL.
  49713. var TOUCH_CONTROLLER_MODEL_BASE_URL = 'https://cdn.aframe.io/controllers/oculus/oculus-touch-controller-';
  49714. var OCULUS_TOUCH_WEBVR = {
  49715. left: {
  49716. modelUrl: TOUCH_CONTROLLER_MODEL_BASE_URL + 'left.gltf',
  49717. rayOrigin: {origin: {x: 0.008, y: -0.01, z: 0}, direction: {x: 0, y: -0.8, z: -1}},
  49718. modelPivotOffset: new THREE.Vector3(-0.005, 0.003, -0.055),
  49719. modelPivotRotation: new THREE.Euler(0, 0, 0)
  49720. },
  49721. right: {
  49722. modelUrl: TOUCH_CONTROLLER_MODEL_BASE_URL + 'right.gltf',
  49723. rayOrigin: {origin: {x: -0.008, y: -0.01, z: 0}, direction: {x: 0, y: -0.8, z: -1}},
  49724. modelPivotOffset: new THREE.Vector3(0.005, 0.003, -0.055),
  49725. modelPivotRotation: new THREE.Euler(0, 0, 0)
  49726. }
  49727. };
  49728. var OCULUS_TOUCH_WEBXR = {
  49729. left: {
  49730. modelUrl: TOUCH_CONTROLLER_MODEL_BASE_URL + 'left.gltf',
  49731. rayOrigin: {origin: {x: 0.002, y: -0.005, z: -0.03}, direction: {x: 0, y: -0.8, z: -1}},
  49732. modelPivotOffset: new THREE.Vector3(-0.005, 0.036, -0.037),
  49733. modelPivotRotation: new THREE.Euler(Math.PI / 4.5, 0, 0)
  49734. },
  49735. right: {
  49736. modelUrl: TOUCH_CONTROLLER_MODEL_BASE_URL + 'right.gltf',
  49737. rayOrigin: {origin: {x: -0.002, y: -0.005, z: -0.03}, direction: {x: 0, y: -0.8, z: -1}},
  49738. modelPivotOffset: new THREE.Vector3(0.005, 0.036, -0.037),
  49739. modelPivotRotation: new THREE.Euler(Math.PI / 4.5, 0, 0)
  49740. }
  49741. };
  49742. var OCULUS_TOUCH_CONFIG = isWebXRAvailable ? OCULUS_TOUCH_WEBXR : OCULUS_TOUCH_WEBVR;
  49743. var CONTROLLER_DEFAULT = 'oculus-touch';
  49744. var CONTROLLER_PROPERTIES = {
  49745. 'oculus-touch': OCULUS_TOUCH_CONFIG,
  49746. 'oculus-touch-v2': {
  49747. left: {
  49748. modelUrl: TOUCH_CONTROLLER_MODEL_BASE_URL + 'gen2-left.gltf',
  49749. rayOrigin: {origin: {x: -0.01, y: 0, z: -0.02}, direction: {x: 0, y: -0.5, z: -1}},
  49750. modelPivotOffset: new THREE.Vector3(0, 0, 0),
  49751. modelPivotRotation: new THREE.Euler(0, 0, 0)
  49752. },
  49753. right: {
  49754. modelUrl: TOUCH_CONTROLLER_MODEL_BASE_URL + 'gen2-right.gltf',
  49755. rayOrigin: {origin: {x: 0.01, y: 0, z: -0.02}, direction: {x: 0, y: -0.5, z: -1}},
  49756. modelPivotOffset: new THREE.Vector3(0, 0, 0),
  49757. modelPivotRotation: new THREE.Euler(0, 0, 0)
  49758. }
  49759. },
  49760. 'oculus-touch-v3': {
  49761. left: {
  49762. modelUrl: TOUCH_CONTROLLER_MODEL_BASE_URL + 'v3-left.glb',
  49763. rayOrigin: {origin: {x: 0.015, y: 0.005, z: 0}, direction: {x: 0, y: 0, z: -1}},
  49764. modelPivotOffset: new THREE.Vector3(0.01, -0.01, 0.05),
  49765. modelPivotRotation: new THREE.Euler(Math.PI / 4, 0, 0)
  49766. },
  49767. right: {
  49768. modelUrl: TOUCH_CONTROLLER_MODEL_BASE_URL + 'v3-right.glb',
  49769. rayOrigin: {origin: {x: -0.015, y: 0.005, z: 0}, direction: {x: 0, y: 0, z: -1}},
  49770. modelPivotOffset: new THREE.Vector3(-0.01, -0.01, 0.05),
  49771. modelPivotRotation: new THREE.Euler(Math.PI / 4, 0, 0)
  49772. }
  49773. }
  49774. };
  49775. /**
  49776. * Button indices:
  49777. * 0 - thumbstick (which has separate axismove / thumbstickmoved events)
  49778. * 1 - trigger (with analog value, which goes up to 1)
  49779. * 2 - grip (with analog value, which goes up to 1)
  49780. * 3 - X (left) or A (right)
  49781. * 4 - Y (left) or B (right)
  49782. * 5 - surface (touch only)
  49783. */
  49784. var INPUT_MAPPING_WEBVR = {
  49785. left: {
  49786. axes: {thumbstick: [0, 1]},
  49787. buttons: ['thumbstick', 'trigger', 'grip', 'xbutton', 'ybutton', 'surface']
  49788. },
  49789. right: {
  49790. axes: {thumbstick: [0, 1]},
  49791. buttons: ['thumbstick', 'trigger', 'grip', 'abutton', 'bbutton', 'surface']
  49792. }
  49793. };
  49794. /**
  49795. * Button indices:
  49796. * 0 - trigger
  49797. * 1 - grip
  49798. * 2 - none
  49799. * 3 - thumbstick
  49800. * 4 - X or A button
  49801. * 5 - Y or B button
  49802. * 6 - surface
  49803. *
  49804. * Axis:
  49805. * 0 - none
  49806. * 1 - none
  49807. * 2 - thumbstick
  49808. * 3 - thumbstick
  49809. * Reference: https://github.com/immersive-web/webxr-input-profiles/blob/master/packages/registry/profiles/oculus/oculus-touch.json
  49810. */
  49811. var INPUT_MAPPING_WEBXR = {
  49812. left: {
  49813. axes: {thumbstick: [2, 3]},
  49814. buttons: ['trigger', 'grip', 'none', 'thumbstick', 'xbutton', 'ybutton', 'surface']
  49815. },
  49816. right: {
  49817. axes: {thumbstick: [2, 3]},
  49818. buttons: ['trigger', 'grip', 'none', 'thumbstick', 'abutton', 'bbutton', 'surface']
  49819. }
  49820. };
  49821. var INPUT_MAPPING = isWebXRAvailable ? INPUT_MAPPING_WEBXR : INPUT_MAPPING_WEBVR;
  49822. /**
  49823. * Oculus Touch controls.
  49824. * Interface with Oculus Touch controllers and map Gamepad events to
  49825. * controller buttons: thumbstick, trigger, grip, xbutton, ybutton, surface
  49826. * Load a controller model and highlight the pressed buttons.
  49827. */
  49828. module.exports.Component = registerComponent('oculus-touch-controls', {
  49829. schema: {
  49830. hand: {default: 'left'},
  49831. buttonColor: {type: 'color', default: '#999'}, // Off-white.
  49832. buttonTouchColor: {type: 'color', default: '#8AB'},
  49833. buttonHighlightColor: {type: 'color', default: '#2DF'}, // Light blue.
  49834. model: {default: true},
  49835. controllerType: {default: 'auto', oneOf: ['auto', 'oculus-touch', 'oculus-touch-v2', 'oculus-touch-v3']},
  49836. orientationOffset: {type: 'vec3', default: {x: 43, y: 0, z: 0}}
  49837. },
  49838. mapping: INPUT_MAPPING,
  49839. bindMethods: function () {
  49840. this.onModelLoaded = bind(this.onModelLoaded, this);
  49841. this.onControllersUpdate = bind(this.onControllersUpdate, this);
  49842. this.checkIfControllerPresent = bind(this.checkIfControllerPresent, this);
  49843. this.onAxisMoved = bind(this.onAxisMoved, this);
  49844. },
  49845. init: function () {
  49846. var self = this;
  49847. this.onButtonChanged = bind(this.onButtonChanged, this);
  49848. this.onButtonDown = function (evt) { onButtonEvent(evt.detail.id, 'down', self, self.data.hand); };
  49849. this.onButtonUp = function (evt) { onButtonEvent(evt.detail.id, 'up', self, self.data.hand); };
  49850. this.onButtonTouchStart = function (evt) { onButtonEvent(evt.detail.id, 'touchstart', self, self.data.hand); };
  49851. this.onButtonTouchEnd = function (evt) { onButtonEvent(evt.detail.id, 'touchend', self, self.data.hand); };
  49852. this.controllerPresent = false;
  49853. this.lastControllerCheck = 0;
  49854. this.previousButtonValues = {};
  49855. this.rendererSystem = this.el.sceneEl.systems.renderer;
  49856. this.bindMethods();
  49857. },
  49858. addEventListeners: function () {
  49859. var el = this.el;
  49860. el.addEventListener('buttonchanged', this.onButtonChanged);
  49861. el.addEventListener('buttondown', this.onButtonDown);
  49862. el.addEventListener('buttonup', this.onButtonUp);
  49863. el.addEventListener('touchstart', this.onButtonTouchStart);
  49864. el.addEventListener('touchend', this.onButtonTouchEnd);
  49865. el.addEventListener('axismove', this.onAxisMoved);
  49866. el.addEventListener('model-loaded', this.onModelLoaded);
  49867. this.controllerEventsActive = true;
  49868. },
  49869. removeEventListeners: function () {
  49870. var el = this.el;
  49871. el.removeEventListener('buttonchanged', this.onButtonChanged);
  49872. el.removeEventListener('buttondown', this.onButtonDown);
  49873. el.removeEventListener('buttonup', this.onButtonUp);
  49874. el.removeEventListener('touchstart', this.onButtonTouchStart);
  49875. el.removeEventListener('touchend', this.onButtonTouchEnd);
  49876. el.removeEventListener('axismove', this.onAxisMoved);
  49877. el.removeEventListener('model-loaded', this.onModelLoaded);
  49878. this.controllerEventsActive = false;
  49879. },
  49880. checkIfControllerPresent: function () {
  49881. checkControllerPresentAndSetup(this, GAMEPAD_ID_PREFIX, {
  49882. hand: this.data.hand
  49883. });
  49884. },
  49885. play: function () {
  49886. this.checkIfControllerPresent();
  49887. this.addControllersUpdateListener();
  49888. },
  49889. pause: function () {
  49890. this.removeEventListeners();
  49891. this.removeControllersUpdateListener();
  49892. },
  49893. loadModel: function (controller) {
  49894. var data = this.data;
  49895. var controllerId;
  49896. if (!data.model) { return; }
  49897. // Set the controller display model based on the data passed in.
  49898. this.displayModel = CONTROLLER_PROPERTIES[data.controllerType] || CONTROLLER_PROPERTIES[CONTROLLER_DEFAULT];
  49899. // If the developer is asking for auto-detection, see if the displayName can be retrieved to identify the specific unit.
  49900. // This only works for WebVR currently.
  49901. if (data.controllerType === 'auto') {
  49902. var trackedControlsSystem = this.el.sceneEl.systems['tracked-controls-webvr'];
  49903. // WebVR
  49904. if (trackedControlsSystem && trackedControlsSystem.vrDisplay) {
  49905. var displayName = trackedControlsSystem.vrDisplay.displayName;
  49906. // The Oculus Quest uses the updated generation 2 inside-out tracked controllers so update the displayModel.
  49907. if (/^Oculus Quest$/.test(displayName)) {
  49908. this.displayModel = CONTROLLER_PROPERTIES['oculus-touch-v2'];
  49909. }
  49910. } else { // WebXR
  49911. controllerId = CONTROLLER_DEFAULT;
  49912. controllerId = controller.profiles.indexOf('oculus-touch-v2') !== -1 ? 'oculus-touch-v2' : controllerId;
  49913. controllerId = controller.profiles.indexOf('oculus-touch-v3') !== -1 ? 'oculus-touch-v3' : controllerId;
  49914. this.displayModel = CONTROLLER_PROPERTIES[controllerId];
  49915. }
  49916. }
  49917. var modelUrl = this.displayModel[data.hand].modelUrl;
  49918. this.el.setAttribute('gltf-model', modelUrl);
  49919. },
  49920. injectTrackedControls: function (controller) {
  49921. var data = this.data;
  49922. var webXRId = GAMEPAD_ID_WEBXR;
  49923. var webVRId = data.hand === 'right' ? 'Oculus Touch (Right)' : 'Oculus Touch (Left)';
  49924. var id = isWebXRAvailable ? webXRId : webVRId;
  49925. this.el.setAttribute('tracked-controls', {
  49926. id: id,
  49927. hand: data.hand,
  49928. orientationOffset: data.orientationOffset,
  49929. handTrackingEnabled: false
  49930. });
  49931. this.loadModel(controller);
  49932. },
  49933. addControllersUpdateListener: function () {
  49934. this.el.sceneEl.addEventListener('controllersupdated', this.onControllersUpdate, false);
  49935. },
  49936. removeControllersUpdateListener: function () {
  49937. this.el.sceneEl.removeEventListener('controllersupdated', this.onControllersUpdate, false);
  49938. },
  49939. onControllersUpdate: function () {
  49940. // Note that due to gamepadconnected event propagation issues, we don't rely on events.
  49941. this.checkIfControllerPresent();
  49942. },
  49943. onButtonChanged: function (evt) {
  49944. var button = this.mapping[this.data.hand].buttons[evt.detail.id];
  49945. var buttonMeshes = this.buttonMeshes;
  49946. var analogValue;
  49947. if (!button) { return; }
  49948. if (button === 'trigger' || button === 'grip') { analogValue = evt.detail.state.value; }
  49949. // Update trigger and/or grip meshes, if any.
  49950. if (buttonMeshes) {
  49951. if (button === 'trigger' && buttonMeshes.trigger) {
  49952. buttonMeshes.trigger.rotation.x = this.originalXRotationTrigger - analogValue * (Math.PI / 26);
  49953. }
  49954. if (button === 'grip' && buttonMeshes.grip) {
  49955. buttonMeshes.grip.position.x = this.originalXPositionGrip + (this.data.hand === 'left' ? -1 : 1) * analogValue * 0.004;
  49956. }
  49957. }
  49958. // Pass along changed event with button state, using the buttom mapping for convenience.
  49959. this.el.emit(button + 'changed', evt.detail.state);
  49960. },
  49961. onModelLoaded: function (evt) {
  49962. var controllerObject3D = this.controllerObject3D = evt.detail.model;
  49963. var buttonMeshes;
  49964. if (!this.data.model) { return; }
  49965. buttonMeshes = this.buttonMeshes = {};
  49966. buttonMeshes.grip = controllerObject3D.getObjectByName('buttonHand');
  49967. this.originalXPositionGrip = buttonMeshes.grip && buttonMeshes.grip.position.x;
  49968. buttonMeshes.thumbstick = controllerObject3D.getObjectByName('stick');
  49969. buttonMeshes.trigger = controllerObject3D.getObjectByName('buttonTrigger');
  49970. this.originalXRotationTrigger = buttonMeshes.trigger && buttonMeshes.trigger.rotation.x;
  49971. buttonMeshes.xbutton = controllerObject3D.getObjectByName('buttonX');
  49972. buttonMeshes.abutton = controllerObject3D.getObjectByName('buttonA');
  49973. buttonMeshes.ybutton = controllerObject3D.getObjectByName('buttonY');
  49974. buttonMeshes.bbutton = controllerObject3D.getObjectByName('buttonB');
  49975. // Offset pivot point
  49976. controllerObject3D.position.copy(this.displayModel[this.data.hand].modelPivotOffset);
  49977. controllerObject3D.rotation.copy(this.displayModel[this.data.hand].modelPivotRotation);
  49978. this.el.emit('controllermodelready', {
  49979. name: 'oculus-touch-controls',
  49980. model: this.data.model,
  49981. rayOrigin: this.displayModel[this.data.hand].rayOrigin
  49982. });
  49983. },
  49984. onAxisMoved: function (evt) {
  49985. emitIfAxesChanged(this, this.mapping[this.data.hand].axes, evt);
  49986. },
  49987. updateModel: function (buttonName, evtName) {
  49988. if (!this.data.model) { return; }
  49989. this.updateButtonModel(buttonName, evtName);
  49990. },
  49991. updateButtonModel: function (buttonName, state) {
  49992. var button;
  49993. var color = (state === 'up' || state === 'touchend') ? this.data.buttonColor : state === 'touchstart' ? this.data.buttonTouchColor : this.data.buttonHighlightColor;
  49994. var buttonMeshes = this.buttonMeshes;
  49995. if (!this.data.model) { return; }
  49996. if (buttonMeshes && buttonMeshes[buttonName]) {
  49997. button = buttonMeshes[buttonName];
  49998. button.material.color.set(color);
  49999. this.rendererSystem.applyColorCorrection(button.material.color);
  50000. }
  50001. }
  50002. });
  50003. },{"../core/component":131,"../lib/three":179,"../utils/":205,"../utils/bind":199,"../utils/tracked-controls":214}],96:[function(_dereq_,module,exports){
  50004. var registerComponent = _dereq_('../core/component').registerComponent;
  50005. module.exports.Component = registerComponent('position', {
  50006. schema: {type: 'vec3'},
  50007. update: function () {
  50008. var object3D = this.el.object3D;
  50009. var data = this.data;
  50010. object3D.position.set(data.x, data.y, data.z);
  50011. },
  50012. remove: function () {
  50013. // Pretty much for mixins.
  50014. this.el.object3D.position.set(0, 0, 0);
  50015. }
  50016. });
  50017. },{"../core/component":131}],97:[function(_dereq_,module,exports){
  50018. /* global MutationObserver */
  50019. var registerComponent = _dereq_('../core/component').registerComponent;
  50020. var THREE = _dereq_('../lib/three');
  50021. var utils = _dereq_('../utils/');
  50022. var warn = utils.debug('components:raycaster:warn');
  50023. // Defines selectors that should be 'safe' for the MutationObserver used to
  50024. // refresh the whitelist. Matches classnames, IDs, and presence of attributes.
  50025. // Selectors for the value of an attribute, like [position=0 2 0], cannot be
  50026. // reliably detected and are therefore disallowed.
  50027. var OBSERVER_SELECTOR_RE = /^[\w\s-.,[\]#]*$/;
  50028. // Configuration for the MutationObserver used to refresh the whitelist.
  50029. // Listens for addition/removal of elements and attributes within the scene.
  50030. var OBSERVER_CONFIG = {
  50031. childList: true,
  50032. attributes: true,
  50033. subtree: true
  50034. };
  50035. var EVENTS = {
  50036. INTERSECT: 'raycaster-intersected',
  50037. INTERSECTION: 'raycaster-intersection',
  50038. INTERSECT_CLEAR: 'raycaster-intersected-cleared',
  50039. INTERSECTION_CLEAR: 'raycaster-intersection-cleared'
  50040. };
  50041. /**
  50042. * Raycaster component.
  50043. *
  50044. * Pass options to three.js Raycaster including which objects to test.
  50045. * Poll for intersections.
  50046. * Emit event on origin entity and on target entity on intersect.
  50047. *
  50048. * @member {array} intersectedEls - List of currently intersected entities.
  50049. * @member {array} objects - Cached list of meshes to intersect.
  50050. * @member {number} prevCheckTime - Previous time intersection was checked. To help interval.
  50051. * @member {object} raycaster - three.js Raycaster.
  50052. */
  50053. module.exports.Component = registerComponent('raycaster', {
  50054. schema: {
  50055. autoRefresh: {default: true},
  50056. direction: {type: 'vec3', default: {x: 0, y: 0, z: -1}},
  50057. enabled: {default: true},
  50058. far: {default: 1000},
  50059. interval: {default: 0},
  50060. near: {default: 0},
  50061. objects: {default: ''},
  50062. origin: {type: 'vec3'},
  50063. showLine: {default: false},
  50064. lineColor: {default: 'white'},
  50065. lineOpacity: {default: 1},
  50066. useWorldCoordinates: {default: false}
  50067. },
  50068. multiple: true,
  50069. init: function () {
  50070. this.clearedIntersectedEls = [];
  50071. this.unitLineEndVec3 = new THREE.Vector3();
  50072. this.intersectedEls = [];
  50073. this.intersections = [];
  50074. this.newIntersectedEls = [];
  50075. this.newIntersections = [];
  50076. this.objects = [];
  50077. this.prevCheckTime = undefined;
  50078. this.prevIntersectedEls = [];
  50079. this.rawIntersections = [];
  50080. this.raycaster = new THREE.Raycaster();
  50081. this.updateOriginDirection();
  50082. this.setDirty = this.setDirty.bind(this);
  50083. this.updateLine = this.updateLine.bind(this);
  50084. this.observer = new MutationObserver(this.setDirty);
  50085. this.dirty = true;
  50086. this.lineEndVec3 = new THREE.Vector3();
  50087. this.otherLineEndVec3 = new THREE.Vector3();
  50088. this.lineData = {end: this.lineEndVec3};
  50089. this.getIntersection = this.getIntersection.bind(this);
  50090. this.intersectedDetail = {el: this.el, getIntersection: this.getIntersection};
  50091. this.intersectedClearedDetail = {el: this.el};
  50092. this.intersectionClearedDetail = {clearedEls: this.clearedIntersectedEls};
  50093. this.intersectionDetail = {};
  50094. },
  50095. /**
  50096. * Create or update raycaster object.
  50097. */
  50098. update: function (oldData) {
  50099. var data = this.data;
  50100. var el = this.el;
  50101. var raycaster = this.raycaster;
  50102. // Set raycaster properties.
  50103. raycaster.far = data.far;
  50104. raycaster.near = data.near;
  50105. // Draw line.
  50106. if (data.showLine &&
  50107. (data.far !== oldData.far || data.origin !== oldData.origin ||
  50108. data.direction !== oldData.direction || !oldData.showLine)) {
  50109. // Calculate unit vector for line direction. Can be multiplied via scalar to performantly
  50110. // adjust line length.
  50111. this.unitLineEndVec3.copy(data.origin).add(data.direction).normalize();
  50112. this.drawLine();
  50113. }
  50114. if (!data.showLine && oldData.showLine) {
  50115. el.removeAttribute('line');
  50116. }
  50117. if (data.objects !== oldData.objects && !OBSERVER_SELECTOR_RE.test(data.objects)) {
  50118. warn('[raycaster] Selector "' + data.objects +
  50119. '" may not update automatically with DOM changes.');
  50120. }
  50121. if (!data.objects) {
  50122. warn('[raycaster] For performance, please define raycaster.objects when using ' +
  50123. 'raycaster or cursor components to whitelist which entities to intersect with. ' +
  50124. 'e.g., raycaster="objects: [data-raycastable]".');
  50125. }
  50126. if (data.autoRefresh !== oldData.autoRefresh && el.isPlaying) {
  50127. data.autoRefresh
  50128. ? this.addEventListeners()
  50129. : this.removeEventListeners();
  50130. }
  50131. if (oldData.enabled && !data.enabled) { this.clearAllIntersections(); }
  50132. this.setDirty();
  50133. },
  50134. play: function () {
  50135. this.addEventListeners();
  50136. },
  50137. pause: function () {
  50138. this.removeEventListeners();
  50139. },
  50140. remove: function () {
  50141. if (this.data.showLine) {
  50142. this.el.removeAttribute('line');
  50143. }
  50144. this.clearAllIntersections();
  50145. },
  50146. addEventListeners: function () {
  50147. if (!this.data.autoRefresh) { return; }
  50148. this.observer.observe(this.el.sceneEl, OBSERVER_CONFIG);
  50149. this.el.sceneEl.addEventListener('object3dset', this.setDirty);
  50150. this.el.sceneEl.addEventListener('object3dremove', this.setDirty);
  50151. },
  50152. removeEventListeners: function () {
  50153. this.observer.disconnect();
  50154. this.el.sceneEl.removeEventListener('object3dset', this.setDirty);
  50155. this.el.sceneEl.removeEventListener('object3dremove', this.setDirty);
  50156. },
  50157. /**
  50158. * Mark the object list as dirty, to be refreshed before next raycast.
  50159. */
  50160. setDirty: function () {
  50161. this.dirty = true;
  50162. },
  50163. /**
  50164. * Update list of objects to test for intersection.
  50165. */
  50166. refreshObjects: function () {
  50167. var data = this.data;
  50168. var els;
  50169. // If objects not defined, intersect with everything.
  50170. els = data.objects
  50171. ? this.el.sceneEl.querySelectorAll(data.objects)
  50172. : this.el.sceneEl.querySelectorAll('*');
  50173. this.objects = this.flattenObject3DMaps(els);
  50174. this.dirty = false;
  50175. },
  50176. /**
  50177. * Check for intersections and cleared intersections on an interval.
  50178. */
  50179. tock: function (time) {
  50180. var data = this.data;
  50181. var prevCheckTime = this.prevCheckTime;
  50182. if (!data.enabled) { return; }
  50183. // Only check for intersection if interval time has passed.
  50184. if (prevCheckTime && (time - prevCheckTime < data.interval)) { return; }
  50185. // Update check time.
  50186. this.prevCheckTime = time;
  50187. this.checkIntersections();
  50188. },
  50189. /**
  50190. * Raycast for intersections and emit events for current and cleared intersections.
  50191. */
  50192. checkIntersections: function () {
  50193. var clearedIntersectedEls = this.clearedIntersectedEls;
  50194. var el = this.el;
  50195. var data = this.data;
  50196. var i;
  50197. var intersectedEls = this.intersectedEls;
  50198. var intersection;
  50199. var intersections = this.intersections;
  50200. var newIntersectedEls = this.newIntersectedEls;
  50201. var newIntersections = this.newIntersections;
  50202. var prevIntersectedEls = this.prevIntersectedEls;
  50203. var rawIntersections = this.rawIntersections;
  50204. // Refresh the object whitelist if needed.
  50205. if (this.dirty) { this.refreshObjects(); }
  50206. // Store old previously intersected entities.
  50207. copyArray(this.prevIntersectedEls, this.intersectedEls);
  50208. // Raycast.
  50209. this.updateOriginDirection();
  50210. rawIntersections.length = 0;
  50211. this.raycaster.intersectObjects(this.objects, true, rawIntersections);
  50212. // Only keep intersections against objects that have a reference to an entity.
  50213. intersections.length = 0;
  50214. intersectedEls.length = 0;
  50215. for (i = 0; i < rawIntersections.length; i++) {
  50216. intersection = rawIntersections[i];
  50217. // Don't intersect with own line.
  50218. if (data.showLine && intersection.object === el.getObject3D('line')) {
  50219. continue;
  50220. }
  50221. if (intersection.object.el) {
  50222. intersections.push(intersection);
  50223. intersectedEls.push(intersection.object.el);
  50224. }
  50225. }
  50226. // Get newly intersected entities.
  50227. newIntersections.length = 0;
  50228. newIntersectedEls.length = 0;
  50229. for (i = 0; i < intersections.length; i++) {
  50230. if (prevIntersectedEls.indexOf(intersections[i].object.el) === -1) {
  50231. newIntersections.push(intersections[i]);
  50232. newIntersectedEls.push(intersections[i].object.el);
  50233. }
  50234. }
  50235. // Emit intersection cleared on both entities per formerly intersected entity.
  50236. clearedIntersectedEls.length = 0;
  50237. for (i = 0; i < prevIntersectedEls.length; i++) {
  50238. if (intersectedEls.indexOf(prevIntersectedEls[i]) !== -1) { continue; }
  50239. prevIntersectedEls[i].emit(EVENTS.INTERSECT_CLEAR,
  50240. this.intersectedClearedDetail);
  50241. clearedIntersectedEls.push(prevIntersectedEls[i]);
  50242. }
  50243. if (clearedIntersectedEls.length) {
  50244. el.emit(EVENTS.INTERSECTION_CLEAR, this.intersectionClearedDetail);
  50245. }
  50246. // Emit intersected on intersected entity per intersected entity.
  50247. for (i = 0; i < newIntersectedEls.length; i++) {
  50248. newIntersectedEls[i].emit(EVENTS.INTERSECT, this.intersectedDetail);
  50249. }
  50250. // Emit all intersections at once on raycasting entity.
  50251. if (newIntersections.length) {
  50252. this.intersectionDetail.els = newIntersectedEls;
  50253. this.intersectionDetail.intersections = newIntersections;
  50254. el.emit(EVENTS.INTERSECTION, this.intersectionDetail);
  50255. }
  50256. // Update line length.
  50257. if (data.showLine) { setTimeout(this.updateLine); }
  50258. },
  50259. updateLine: function () {
  50260. var el = this.el;
  50261. var intersections = this.intersections;
  50262. var lineLength;
  50263. if (intersections.length) {
  50264. if (intersections[0].object.el === el && intersections[1]) {
  50265. lineLength = intersections[1].distance;
  50266. } else {
  50267. lineLength = intersections[0].distance;
  50268. }
  50269. }
  50270. this.drawLine(lineLength);
  50271. },
  50272. /**
  50273. * Return the most recent intersection details for a given entity, if any.
  50274. * @param {AEntity} el
  50275. * @return {Object}
  50276. */
  50277. getIntersection: function (el) {
  50278. var i;
  50279. var intersection;
  50280. for (i = 0; i < this.intersections.length; i++) {
  50281. intersection = this.intersections[i];
  50282. if (intersection.object.el === el) { return intersection; }
  50283. }
  50284. return null;
  50285. },
  50286. /**
  50287. * Update origin and direction of raycaster using entity transforms and supplied origin or
  50288. * direction offsets.
  50289. */
  50290. updateOriginDirection: (function () {
  50291. var direction = new THREE.Vector3();
  50292. var originVec3 = new THREE.Vector3();
  50293. // Closure to make quaternion/vector3 objects private.
  50294. return function updateOriginDirection () {
  50295. var el = this.el;
  50296. var data = this.data;
  50297. if (data.useWorldCoordinates) {
  50298. this.raycaster.set(data.origin, data.direction);
  50299. return;
  50300. }
  50301. el.object3D.updateMatrixWorld();
  50302. originVec3.setFromMatrixPosition(el.object3D.matrixWorld);
  50303. // If non-zero origin, translate the origin into world space.
  50304. if (data.origin.x !== 0 || data.origin.y !== 0 || data.origin.z !== 0) {
  50305. originVec3 = el.object3D.localToWorld(originVec3.copy(data.origin));
  50306. }
  50307. // three.js raycaster direction is relative to 0, 0, 0 NOT the origin / offset we
  50308. // provide. Apply the offset to the direction, then rotation from the object,
  50309. // and normalize.
  50310. direction.copy(data.direction).transformDirection(el.object3D.matrixWorld).normalize();
  50311. // Apply offset and direction, in world coordinates.
  50312. this.raycaster.set(originVec3, direction);
  50313. };
  50314. })(),
  50315. /**
  50316. * Create or update line to give raycaster visual representation.
  50317. * Customize the line through through line component.
  50318. * We draw the line in the raycaster component to customize the line to the
  50319. * raycaster's origin, direction, and far.
  50320. *
  50321. * Unlike the raycaster, we create the line as a child of the object. The line will
  50322. * be affected by the transforms of the objects, so we don't have to calculate transforms
  50323. * like we do with the raycaster.
  50324. *
  50325. * @param {number} length - Length of line. Pass in to shorten the line to the intersection
  50326. * point. If not provided, length will default to the max length, `raycaster.far`.
  50327. */
  50328. drawLine: function (length) {
  50329. var data = this.data;
  50330. var el = this.el;
  50331. var endVec3;
  50332. // Switch each time vector so line update triggered and to avoid unnecessary vector clone.
  50333. endVec3 = this.lineData.end === this.lineEndVec3
  50334. ? this.otherLineEndVec3
  50335. : this.lineEndVec3;
  50336. // Treat Infinity as 1000m for the line.
  50337. if (length === undefined) {
  50338. length = data.far === Infinity ? 1000 : data.far;
  50339. }
  50340. // Update the length of the line if given. `unitLineEndVec3` is the direction
  50341. // given by data.direction, then we apply a scalar to give it a length.
  50342. this.lineData.start = data.origin;
  50343. this.lineData.end = endVec3.copy(this.unitLineEndVec3).multiplyScalar(length);
  50344. this.lineData.color = data.lineColor;
  50345. this.lineData.opacity = data.lineOpacity;
  50346. el.setAttribute('line', this.lineData);
  50347. },
  50348. /**
  50349. * Return A-Frame attachments of each element's object3D group (e.g., mesh).
  50350. * Children are flattened by one level, removing the THREE.Group wrapper,
  50351. * so that non-recursive raycasting remains useful.
  50352. *
  50353. * Only push children defined as component attachements (e.g., setObject3D),
  50354. * NOT actual children in the scene graph hierarchy.
  50355. *
  50356. * @param {Array<Element>} els
  50357. * @return {Array<THREE.Object3D>}
  50358. */
  50359. flattenObject3DMaps: function (els) {
  50360. var key;
  50361. var i;
  50362. var objects = this.objects;
  50363. // Push meshes and other attachments onto list of objects to intersect.
  50364. objects.length = 0;
  50365. for (i = 0; i < els.length; i++) {
  50366. if (els[i].isEntity && els[i].object3D) {
  50367. for (key in els[i].object3DMap) {
  50368. objects.push(els[i].getObject3D(key));
  50369. }
  50370. }
  50371. }
  50372. return objects;
  50373. },
  50374. clearAllIntersections: function () {
  50375. var i;
  50376. for (i = 0; i < this.intersectedEls.length; i++) {
  50377. this.intersectedEls[i].emit(EVENTS.INTERSECT_CLEAR,
  50378. this.intersectedClearedDetail);
  50379. }
  50380. copyArray(this.clearedIntersectedEls, this.intersectedEls);
  50381. this.intersectedEls.length = 0;
  50382. this.intersections.length = 0;
  50383. this.el.emit(EVENTS.INTERSECTION_CLEAR, this.intersectionClearedDetail);
  50384. }
  50385. });
  50386. /**
  50387. * Copy contents of one array to another without allocating new array.
  50388. */
  50389. function copyArray (a, b) {
  50390. var i;
  50391. a.length = b.length;
  50392. for (i = 0; i < b.length; i++) {
  50393. a[i] = b[i];
  50394. }
  50395. }
  50396. },{"../core/component":131,"../lib/three":179,"../utils/":205}],98:[function(_dereq_,module,exports){
  50397. var degToRad = _dereq_('../lib/three').Math.degToRad;
  50398. var registerComponent = _dereq_('../core/component').registerComponent;
  50399. module.exports.Component = registerComponent('rotation', {
  50400. schema: {type: 'vec3'},
  50401. /**
  50402. * Updates object3D rotation.
  50403. */
  50404. update: function () {
  50405. var data = this.data;
  50406. var object3D = this.el.object3D;
  50407. object3D.rotation.set(degToRad(data.x), degToRad(data.y), degToRad(data.z));
  50408. object3D.rotation.order = 'YXZ';
  50409. },
  50410. remove: function () {
  50411. // Pretty much for mixins.
  50412. this.el.object3D.rotation.set(0, 0, 0);
  50413. }
  50414. });
  50415. },{"../core/component":131,"../lib/three":179}],99:[function(_dereq_,module,exports){
  50416. var registerComponent = _dereq_('../core/component').registerComponent;
  50417. // Avoids triggering a zero-determinant which makes object3D matrix non-invertible.
  50418. var zeroScale = 0.00001;
  50419. module.exports.Component = registerComponent('scale', {
  50420. schema: {
  50421. type: 'vec3',
  50422. default: {x: 1, y: 1, z: 1}
  50423. },
  50424. update: function () {
  50425. var data = this.data;
  50426. var object3D = this.el.object3D;
  50427. var x = data.x === 0 ? zeroScale : data.x;
  50428. var y = data.y === 0 ? zeroScale : data.y;
  50429. var z = data.z === 0 ? zeroScale : data.z;
  50430. object3D.scale.set(x, y, z);
  50431. },
  50432. remove: function () {
  50433. // Pretty much for mixins.
  50434. this.el.object3D.scale.set(1, 1, 1);
  50435. }
  50436. });
  50437. },{"../core/component":131}],100:[function(_dereq_,module,exports){
  50438. /* global THREE */
  50439. var register = _dereq_('../../core/component').registerComponent;
  50440. var COMPONENTS = _dereq_('../../core/component').components;
  50441. module.exports.Component = register('background', {
  50442. schema: {
  50443. color: {type: 'color', default: 'black'},
  50444. transparent: {default: false},
  50445. generateEnvironment: {default: true}
  50446. },
  50447. init: function () {
  50448. this.cubeRenderTarget = new THREE.WebGLCubeRenderTarget(128, { format: THREE.RGBFormat, generateMipmaps: true, minFilter: THREE.LinearMipmapLinearFilter });
  50449. this.cubeCamera = new THREE.CubeCamera(1, 100000, this.cubeRenderTarget);
  50450. this.needsEnvironmentUpdate = true;
  50451. },
  50452. update: function () {
  50453. var scene = this.el.sceneEl.object3D;
  50454. var data = this.data;
  50455. var object3D = this.el.object3D;
  50456. if (data.transparent) {
  50457. object3D.background = null;
  50458. } else {
  50459. object3D.background = new THREE.Color(data.color);
  50460. }
  50461. if (scene.environment && scene.environment !== this.cubeRenderTarget.texture) {
  50462. console.warn('Background will not overide predefined environment maps');
  50463. return;
  50464. }
  50465. if (data.generateEnvironment) {
  50466. scene.environment = this.cubeRenderTarget.texture;
  50467. } else {
  50468. scene.environment = null;
  50469. }
  50470. },
  50471. tick: function () {
  50472. if (!this.needsEnvironmentUpdate) return;
  50473. var scene = this.el.object3D;
  50474. var renderer = this.el.renderer;
  50475. var camera = this.el.camera;
  50476. this.el.object3D.add(this.cubeCamera);
  50477. this.cubeCamera.position.copy(camera.position);
  50478. this.cubeCamera.update(renderer, scene);
  50479. this.needsEnvironmentUpdate = false;
  50480. },
  50481. remove: function () {
  50482. var data = this.data;
  50483. var object3D = this.el.object3D;
  50484. if (data.transparent) {
  50485. object3D.background = null;
  50486. return;
  50487. }
  50488. if (object3D.environment === this.cubeRenderTarget.texture) {
  50489. object3D.environment = null;
  50490. }
  50491. object3D.background = COMPONENTS[this.name].schema.color.default;
  50492. }
  50493. });
  50494. },{"../../core/component":131}],101:[function(_dereq_,module,exports){
  50495. var register = _dereq_('../../core/component').registerComponent;
  50496. module.exports.Component = register('debug', {
  50497. schema: {default: true}
  50498. });
  50499. },{"../../core/component":131}],102:[function(_dereq_,module,exports){
  50500. /* global DeviceOrientationEvent, location */
  50501. var registerComponent = _dereq_('../../core/component').registerComponent;
  50502. var utils = _dereq_('../../utils/');
  50503. var bind = utils.bind;
  50504. var constants = _dereq_('../../constants/');
  50505. var MODAL_CLASS = 'a-modal';
  50506. var DIALOG_CLASS = 'a-dialog';
  50507. var DIALOG_TEXT_CLASS = 'a-dialog-text';
  50508. var DIALOG_TEXT_CONTAINER_CLASS = 'a-dialog-text-container';
  50509. var DIALOG_BUTTONS_CONTAINER_CLASS = 'a-dialog-buttons-container';
  50510. var DIALOG_BUTTON_CLASS = 'a-dialog-button';
  50511. var DIALOG_ALLOW_BUTTON_CLASS = 'a-dialog-allow-button';
  50512. var DIALOG_DENY_BUTTON_CLASS = 'a-dialog-deny-button';
  50513. var DIALOG_OK_BUTTON_CLASS = 'a-dialog-ok-button';
  50514. /**
  50515. * UI for enabling device motion permission
  50516. */
  50517. module.exports.Component = registerComponent('device-orientation-permission-ui', {
  50518. schema: {
  50519. enabled: {default: true},
  50520. deviceMotionMessage: {
  50521. default: 'This immersive website requires access to your device motion sensors.'
  50522. },
  50523. mobileDesktopMessage: {
  50524. default: 'Set your browser to request the mobile version of the site and reload the page to enjoy immersive mode.'
  50525. },
  50526. httpsMessage: {
  50527. default: 'Access this site over HTTPS to enter VR mode and grant access to the device sensors.'
  50528. },
  50529. denyButtonText: {default: 'Deny'},
  50530. allowButtonText: {default: 'Allow'},
  50531. cancelButtonText: {default: 'Cancel'}
  50532. },
  50533. init: function () {
  50534. var self = this;
  50535. if (!this.data.enabled) { return; }
  50536. if (location.hostname !== 'localhost' &&
  50537. location.hostname !== '127.0.0.1' &&
  50538. location.protocol === 'http:') {
  50539. this.showHTTPAlert();
  50540. }
  50541. // Show alert on iPad if Safari is on desktop mode.
  50542. if (utils.device.isMobileDeviceRequestingDesktopSite()) {
  50543. this.showMobileDesktopModeAlert();
  50544. return;
  50545. }
  50546. // Browser doesn't support or doesn't require permission to DeviceOrientationEvent API.
  50547. if (typeof DeviceOrientationEvent === 'undefined' || !DeviceOrientationEvent.requestPermission) {
  50548. this.permissionGranted = true;
  50549. return;
  50550. }
  50551. this.onDeviceMotionDialogAllowClicked = bind(this.onDeviceMotionDialogAllowClicked, this);
  50552. this.onDeviceMotionDialogDenyClicked = bind(this.onDeviceMotionDialogDenyClicked, this);
  50553. // Show dialog only if permission has not yet been granted.
  50554. DeviceOrientationEvent.requestPermission().catch(function () {
  50555. self.devicePermissionDialogEl = createPermissionDialog(
  50556. self.data.denyButtonText,
  50557. self.data.allowButtonText,
  50558. self.data.deviceMotionMessage,
  50559. self.onDeviceMotionDialogAllowClicked,
  50560. self.onDeviceMotionDialogDenyClicked);
  50561. self.el.appendChild(self.devicePermissionDialogEl);
  50562. }).then(function () {
  50563. self.el.emit('deviceorientationpermissiongranted');
  50564. self.permissionGranted = true;
  50565. });
  50566. },
  50567. remove: function () {
  50568. // This removes the modal screen
  50569. if (this.devicePermissionDialogEl) { this.el.removeChild(this.devicePermissionDialogEl); }
  50570. },
  50571. onDeviceMotionDialogDenyClicked: function () {
  50572. this.remove();
  50573. },
  50574. showMobileDesktopModeAlert: function () {
  50575. var self = this;
  50576. var safariIpadAlertEl = createAlertDialog(
  50577. self.data.cancelButtonText,
  50578. self.data.mobileDesktopMessage,
  50579. function () { self.el.removeChild(safariIpadAlertEl); });
  50580. this.el.appendChild(safariIpadAlertEl);
  50581. },
  50582. showHTTPAlert: function () {
  50583. var self = this;
  50584. var httpAlertEl = createAlertDialog(
  50585. self.data.cancelButtonText,
  50586. self.data.httpsMessage,
  50587. function () { self.el.removeChild(httpAlertEl); });
  50588. this.el.appendChild(httpAlertEl);
  50589. },
  50590. /**
  50591. * Enable device motion permission when clicked.
  50592. */
  50593. onDeviceMotionDialogAllowClicked: function () {
  50594. var self = this;
  50595. this.el.emit('deviceorientationpermissionrequested');
  50596. DeviceOrientationEvent.requestPermission().then(function (response) {
  50597. if (response === 'granted') {
  50598. self.el.emit('deviceorientationpermissiongranted');
  50599. self.permissionGranted = true;
  50600. } else {
  50601. self.el.emit('deviceorientationpermissionrejected');
  50602. }
  50603. self.remove();
  50604. }).catch(console.error);
  50605. }
  50606. });
  50607. /**
  50608. * Create a modal dialog that request users permission to access the Device Motion API.
  50609. *
  50610. * @param {function} onAllowClicked - click event handler
  50611. * @param {function} onDenyClicked - click event handler
  50612. *
  50613. * @returns {Element} Wrapper <div>.
  50614. */
  50615. function createPermissionDialog (
  50616. denyText, allowText, dialogText, onAllowClicked, onDenyClicked) {
  50617. var buttonsContainer;
  50618. var denyButton;
  50619. var acceptButton;
  50620. buttonsContainer = document.createElement('div');
  50621. buttonsContainer.classList.add(DIALOG_BUTTONS_CONTAINER_CLASS);
  50622. // Buttons
  50623. denyButton = document.createElement('button');
  50624. denyButton.classList.add(DIALOG_BUTTON_CLASS, DIALOG_DENY_BUTTON_CLASS);
  50625. denyButton.setAttribute(constants.AFRAME_INJECTED, '');
  50626. denyButton.innerHTML = denyText;
  50627. buttonsContainer.appendChild(denyButton);
  50628. acceptButton = document.createElement('button');
  50629. acceptButton.classList.add(DIALOG_BUTTON_CLASS, DIALOG_ALLOW_BUTTON_CLASS);
  50630. acceptButton.setAttribute(constants.AFRAME_INJECTED, '');
  50631. acceptButton.innerHTML = allowText;
  50632. buttonsContainer.appendChild(acceptButton);
  50633. // Ask for sensor events to be used
  50634. acceptButton.addEventListener('click', function (evt) {
  50635. evt.stopPropagation();
  50636. onAllowClicked();
  50637. });
  50638. denyButton.addEventListener('click', function (evt) {
  50639. evt.stopPropagation();
  50640. onDenyClicked();
  50641. });
  50642. return createDialog(dialogText, buttonsContainer);
  50643. }
  50644. function createAlertDialog (closeText, dialogText, onOkClicked) {
  50645. var buttonsContainer;
  50646. var okButton;
  50647. buttonsContainer = document.createElement('div');
  50648. buttonsContainer.classList.add(DIALOG_BUTTONS_CONTAINER_CLASS);
  50649. // Buttons
  50650. okButton = document.createElement('button');
  50651. okButton.classList.add(DIALOG_BUTTON_CLASS, DIALOG_OK_BUTTON_CLASS);
  50652. okButton.setAttribute(constants.AFRAME_INJECTED, '');
  50653. okButton.innerHTML = closeText;
  50654. buttonsContainer.appendChild(okButton);
  50655. // Ask for sensor events to be used
  50656. okButton.addEventListener('click', function (evt) {
  50657. evt.stopPropagation();
  50658. onOkClicked();
  50659. });
  50660. return createDialog(dialogText, buttonsContainer);
  50661. }
  50662. function createDialog (text, buttonsContainerEl) {
  50663. var modalContainer;
  50664. var dialog;
  50665. var dialogTextContainer;
  50666. var dialogText;
  50667. modalContainer = document.createElement('div');
  50668. modalContainer.classList.add(MODAL_CLASS);
  50669. modalContainer.setAttribute(constants.AFRAME_INJECTED, '');
  50670. dialog = document.createElement('div');
  50671. dialog.className = DIALOG_CLASS;
  50672. dialog.setAttribute(constants.AFRAME_INJECTED, '');
  50673. modalContainer.appendChild(dialog);
  50674. dialogTextContainer = document.createElement('div');
  50675. dialogTextContainer.classList.add(DIALOG_TEXT_CONTAINER_CLASS);
  50676. dialog.appendChild(dialogTextContainer);
  50677. dialogText = document.createElement('div');
  50678. dialogText.classList.add(DIALOG_TEXT_CLASS);
  50679. dialogText.innerHTML = text;
  50680. dialogTextContainer.appendChild(dialogText);
  50681. dialog.appendChild(buttonsContainerEl);
  50682. return modalContainer;
  50683. }
  50684. },{"../../constants/":123,"../../core/component":131,"../../utils/":205}],103:[function(_dereq_,module,exports){
  50685. var registerComponent = _dereq_('../../core/component').registerComponent;
  50686. /**
  50687. * Component to embed an a-frame scene within the layout of a 2D page.
  50688. */
  50689. module.exports.Component = registerComponent('embedded', {
  50690. dependencies: ['vr-mode-ui'],
  50691. schema: {default: true},
  50692. update: function () {
  50693. var sceneEl = this.el;
  50694. var enterVREl = sceneEl.querySelector('.a-enter-vr');
  50695. if (this.data === true) {
  50696. if (enterVREl) { enterVREl.classList.add('embedded'); }
  50697. sceneEl.removeFullScreenStyles();
  50698. } else {
  50699. if (enterVREl) { enterVREl.classList.remove('embedded'); }
  50700. sceneEl.addFullScreenStyles();
  50701. }
  50702. }
  50703. });
  50704. },{"../../core/component":131}],104:[function(_dereq_,module,exports){
  50705. var register = _dereq_('../../core/component').registerComponent;
  50706. var THREE = _dereq_('../../lib/three');
  50707. var debug = _dereq_('../../utils/debug');
  50708. var warn = debug('components:fog:warn');
  50709. /**
  50710. * Fog component.
  50711. * Applies only to the scene entity.
  50712. */
  50713. module.exports.Component = register('fog', {
  50714. schema: {
  50715. color: {type: 'color', default: '#000'},
  50716. density: {default: 0.00025},
  50717. far: {default: 1000, min: 0},
  50718. near: {default: 1, min: 0},
  50719. type: {default: 'linear', oneOf: ['linear', 'exponential']}
  50720. },
  50721. update: function () {
  50722. var data = this.data;
  50723. var el = this.el;
  50724. var fog = this.el.object3D.fog;
  50725. if (!el.isScene) {
  50726. warn('Fog component can only be applied to <a-scene>');
  50727. return;
  50728. }
  50729. // (Re)create fog if fog doesn't exist or fog type changed.
  50730. if (!fog || data.type !== fog.name) {
  50731. el.object3D.fog = getFog(data);
  50732. el.systems.material.updateMaterials();
  50733. return;
  50734. }
  50735. // Fog data changed. Update fog.
  50736. Object.keys(this.schema).forEach(function (key) {
  50737. var value = data[key];
  50738. if (key === 'color') { value = new THREE.Color(value); }
  50739. fog[key] = value;
  50740. });
  50741. },
  50742. /**
  50743. * Remove fog on remove (callback).
  50744. */
  50745. remove: function () {
  50746. var fog = this.el.object3D.fog;
  50747. if (!fog) { return; }
  50748. fog.far = 0;
  50749. fog.near = 0.1;
  50750. }
  50751. });
  50752. /**
  50753. * Creates a fog object. Sets fog.name to be able to detect fog type changes.
  50754. *
  50755. * @param {object} data - Fog data.
  50756. * @returns {object} fog
  50757. */
  50758. function getFog (data) {
  50759. var fog;
  50760. if (data.type === 'exponential') {
  50761. fog = new THREE.FogExp2(data.color, data.density);
  50762. } else {
  50763. fog = new THREE.Fog(data.color, data.near, data.far);
  50764. }
  50765. fog.name = data.type;
  50766. return fog;
  50767. }
  50768. },{"../../core/component":131,"../../lib/three":179,"../../utils/debug":201}],105:[function(_dereq_,module,exports){
  50769. (function (process){
  50770. /* global AFRAME */
  50771. var AFRAME_INJECTED = _dereq_('../../constants').AFRAME_INJECTED;
  50772. var pkg = _dereq_('../../../package');
  50773. var registerComponent = _dereq_('../../core/component').registerComponent;
  50774. var utils = _dereq_('../../utils/');
  50775. /**
  50776. * 0.4.2 to 0.4.x
  50777. * Will need to update this when A-Frame goes to 1.x.x.
  50778. */
  50779. function getFuzzyPatchVersion (version) {
  50780. var split = version.split('.');
  50781. split[2] = 'x';
  50782. return split.join('.');
  50783. }
  50784. var INSPECTOR_DEV_URL = 'https://aframe.io/aframe-inspector/dist/aframe-inspector.js';
  50785. var INSPECTOR_RELEASE_URL = 'https://unpkg.com/aframe-inspector@' + getFuzzyPatchVersion(pkg.version) + '/dist/aframe-inspector.min.js';
  50786. var INSPECTOR_URL = process.env.INSPECTOR_VERSION === 'dev' ? INSPECTOR_DEV_URL : INSPECTOR_RELEASE_URL;
  50787. var LOADING_MESSAGE = 'Loading Inspector';
  50788. var LOADING_ERROR_MESSAGE = 'Error loading Inspector';
  50789. module.exports.Component = registerComponent('inspector', {
  50790. schema: {
  50791. url: {default: INSPECTOR_URL}
  50792. },
  50793. init: function () {
  50794. this.firstPlay = true;
  50795. this.onKeydown = this.onKeydown.bind(this);
  50796. this.onMessage = this.onMessage.bind(this);
  50797. this.initOverlay();
  50798. window.addEventListener('keydown', this.onKeydown);
  50799. window.addEventListener('message', this.onMessage);
  50800. },
  50801. play: function () {
  50802. var urlParam;
  50803. if (!this.firstPlay) { return; }
  50804. urlParam = utils.getUrlParameter('inspector');
  50805. if (urlParam !== 'false' && !!urlParam) {
  50806. this.openInspector();
  50807. this.firstPlay = false;
  50808. }
  50809. },
  50810. initOverlay: function () {
  50811. var dotsHTML = '<span class="dots"><span>.</span><span>.</span><span>.</span></span>';
  50812. this.loadingMessageEl = document.createElement('div');
  50813. this.loadingMessageEl.classList.add('a-inspector-loader');
  50814. this.loadingMessageEl.innerHTML = LOADING_MESSAGE + dotsHTML;
  50815. },
  50816. remove: function () {
  50817. this.removeEventListeners();
  50818. },
  50819. /**
  50820. * <ctrl> + <alt> + i keyboard shortcut.
  50821. */
  50822. onKeydown: function (evt) {
  50823. var shortcutPressed = evt.keyCode === 73 && (evt.ctrlKey && evt.altKey || evt.getModifierState('AltGraph'));
  50824. if (!shortcutPressed) { return; }
  50825. this.openInspector();
  50826. },
  50827. showLoader: function () {
  50828. document.body.appendChild(this.loadingMessageEl);
  50829. },
  50830. hideLoader: function () {
  50831. document.body.removeChild(this.loadingMessageEl);
  50832. },
  50833. /**
  50834. * postMessage. aframe.io uses this to create a button on examples to open Inspector.
  50835. */
  50836. onMessage: function (evt) {
  50837. if (evt.data === 'INJECT_AFRAME_INSPECTOR') { this.openInspector(); }
  50838. },
  50839. openInspector: function (focusEl) {
  50840. var self = this;
  50841. var script;
  50842. // Already injected. Open.
  50843. if (AFRAME.INSPECTOR || AFRAME.inspectorInjected) {
  50844. AFRAME.INSPECTOR.open(focusEl);
  50845. return;
  50846. }
  50847. this.showLoader();
  50848. // Inject.
  50849. script = document.createElement('script');
  50850. script.src = this.data.url;
  50851. script.setAttribute('data-name', 'aframe-inspector');
  50852. script.setAttribute(AFRAME_INJECTED, '');
  50853. script.onload = function () {
  50854. AFRAME.INSPECTOR.open(focusEl);
  50855. self.hideLoader();
  50856. self.removeEventListeners();
  50857. };
  50858. script.onerror = function () {
  50859. self.loadingMessageEl.innerHTML = LOADING_ERROR_MESSAGE;
  50860. };
  50861. document.head.appendChild(script);
  50862. AFRAME.inspectorInjected = true;
  50863. },
  50864. removeEventListeners: function () {
  50865. window.removeEventListener('keydown', this.onKeydown);
  50866. window.removeEventListener('message', this.onMessage);
  50867. }
  50868. });
  50869. }).call(this,_dereq_('_process'))
  50870. },{"../../../package":73,"../../constants":123,"../../core/component":131,"../../utils/":205,"_process":49}],106:[function(_dereq_,module,exports){
  50871. var registerComponent = _dereq_('../../core/component').registerComponent;
  50872. var shouldCaptureKeyEvent = _dereq_('../../utils/').shouldCaptureKeyEvent;
  50873. module.exports.Component = registerComponent('keyboard-shortcuts', {
  50874. schema: {
  50875. enterVR: {default: true},
  50876. exitVR: {default: true}
  50877. },
  50878. init: function () {
  50879. this.onKeyup = this.onKeyup.bind(this);
  50880. },
  50881. update: function (oldData) {
  50882. var data = this.data;
  50883. this.enterVREnabled = data.enterVR;
  50884. },
  50885. play: function () {
  50886. window.addEventListener('keyup', this.onKeyup, false);
  50887. },
  50888. pause: function () {
  50889. window.removeEventListener('keyup', this.onKeyup);
  50890. },
  50891. onKeyup: function (evt) {
  50892. var scene = this.el;
  50893. if (!shouldCaptureKeyEvent(evt)) { return; }
  50894. if (this.enterVREnabled && evt.keyCode === 70) { // f.
  50895. scene.enterVR();
  50896. }
  50897. if (this.enterVREnabled && evt.keyCode === 27) { // escape.
  50898. scene.exitVR();
  50899. }
  50900. }
  50901. });
  50902. },{"../../core/component":131,"../../utils/":205}],107:[function(_dereq_,module,exports){
  50903. var debug = _dereq_('../../utils/debug');
  50904. var registerComponent = _dereq_('../../core/component').registerComponent;
  50905. var warn = debug('components:pool:warn');
  50906. /**
  50907. * Pool component to reuse entities.
  50908. * Avoids creating and destroying the same kind of entities.
  50909. * Helps reduce GC pauses. For example in a game to reuse enemies entities.
  50910. *
  50911. * @member {array} availableEls - Available entities in the pool.
  50912. * @member {array} usedEls - Entities of the pool in use.
  50913. */
  50914. module.exports.Component = registerComponent('pool', {
  50915. schema: {
  50916. container: {default: ''},
  50917. mixin: {default: ''},
  50918. size: {default: 0},
  50919. dynamic: {default: false}
  50920. },
  50921. multiple: true,
  50922. initPool: function () {
  50923. var i;
  50924. this.availableEls = [];
  50925. this.usedEls = [];
  50926. if (!this.data.mixin) {
  50927. warn('No mixin provided for pool component.');
  50928. }
  50929. if (this.data.container) {
  50930. this.container = document.querySelector(this.data.container);
  50931. if (!this.container) {
  50932. warn('Container ' + this.data.container + ' not found.');
  50933. }
  50934. }
  50935. this.container = this.container || this.el;
  50936. for (i = 0; i < this.data.size; ++i) {
  50937. this.createEntity();
  50938. }
  50939. },
  50940. update: function (oldData) {
  50941. var data = this.data;
  50942. if (oldData.mixin !== data.mixin || oldData.size !== data.size) {
  50943. this.initPool();
  50944. }
  50945. },
  50946. /**
  50947. * Add a new entity to the list of available entities.
  50948. */
  50949. createEntity: function () {
  50950. var el;
  50951. el = document.createElement('a-entity');
  50952. el.play = this.wrapPlay(el.play);
  50953. el.setAttribute('mixin', this.data.mixin);
  50954. el.object3D.visible = false;
  50955. el.pause();
  50956. this.container.appendChild(el);
  50957. this.availableEls.push(el);
  50958. },
  50959. /**
  50960. * Play wrapper for pooled entities. When pausing and playing a scene, don't want to play
  50961. * entities that are not in use.
  50962. */
  50963. wrapPlay: function (playMethod) {
  50964. var usedEls = this.usedEls;
  50965. return function () {
  50966. if (usedEls.indexOf(this) === -1) { return; }
  50967. playMethod.call(this);
  50968. };
  50969. },
  50970. /**
  50971. * Used to request one of the available entities of the pool.
  50972. */
  50973. requestEntity: function () {
  50974. var el;
  50975. if (this.availableEls.length === 0) {
  50976. if (this.data.dynamic === false) {
  50977. warn('Requested entity from empty pool: ' + this.attrName);
  50978. return;
  50979. } else {
  50980. warn('Requested entity from empty pool. This pool is dynamic and will resize ' +
  50981. 'automatically. You might want to increase its initial size: ' + this.attrName);
  50982. }
  50983. this.createEntity();
  50984. }
  50985. el = this.availableEls.shift();
  50986. this.usedEls.push(el);
  50987. el.object3D.visible = true;
  50988. return el;
  50989. },
  50990. /**
  50991. * Used to return a used entity to the pool.
  50992. */
  50993. returnEntity: function (el) {
  50994. var index = this.usedEls.indexOf(el);
  50995. if (index === -1) {
  50996. warn('The returned entity was not previously pooled from ' + this.attrName);
  50997. return;
  50998. }
  50999. this.usedEls.splice(index, 1);
  51000. this.availableEls.push(el);
  51001. el.object3D.visible = false;
  51002. el.pause();
  51003. return el;
  51004. }
  51005. });
  51006. },{"../../core/component":131,"../../utils/debug":201}],108:[function(_dereq_,module,exports){
  51007. /* global ImageData, URL */
  51008. var registerComponent = _dereq_('../../core/component').registerComponent;
  51009. var THREE = _dereq_('../../lib/three');
  51010. var VERTEX_SHADER = [
  51011. 'attribute vec3 position;',
  51012. 'attribute vec2 uv;',
  51013. 'uniform mat4 projectionMatrix;',
  51014. 'uniform mat4 modelViewMatrix;',
  51015. 'varying vec2 vUv;',
  51016. 'void main() {',
  51017. ' vUv = vec2( 1.- uv.x, uv.y );',
  51018. ' gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );',
  51019. '}'
  51020. ].join('\n');
  51021. var FRAGMENT_SHADER = [
  51022. 'precision mediump float;',
  51023. 'uniform samplerCube map;',
  51024. 'varying vec2 vUv;',
  51025. '#define M_PI 3.141592653589793238462643383279',
  51026. 'void main() {',
  51027. ' vec2 uv = vUv;',
  51028. ' float longitude = uv.x * 2. * M_PI - M_PI + M_PI / 2.;',
  51029. ' float latitude = uv.y * M_PI;',
  51030. ' vec3 dir = vec3(',
  51031. ' - sin( longitude ) * sin( latitude ),',
  51032. ' cos( latitude ),',
  51033. ' - cos( longitude ) * sin( latitude )',
  51034. ' );',
  51035. ' normalize( dir );',
  51036. ' gl_FragColor = vec4( textureCube( map, dir ).rgb, 1.0 );',
  51037. '}'
  51038. ].join('\n');
  51039. /**
  51040. * Component to take screenshots of the scene using a keboard shortcut (alt+s).
  51041. * It can be configured to either take 360&deg; captures (`equirectangular`)
  51042. * or regular screenshots (`projection`)
  51043. *
  51044. * This is based on https://github.com/spite/THREE.CubemapToEquirectangular
  51045. * To capture an equirectangular projection of the scene a THREE.CubeCamera is used
  51046. * The cube map produced by the CubeCamera is projected on a quad and then rendered to
  51047. * WebGLRenderTarget with an ortographic camera.
  51048. */
  51049. module.exports.Component = registerComponent('screenshot', {
  51050. schema: {
  51051. width: {default: 4096},
  51052. height: {default: 2048},
  51053. camera: {type: 'selector'}
  51054. },
  51055. init: function () {
  51056. var el = this.el;
  51057. var self = this;
  51058. if (el.renderer) {
  51059. setup();
  51060. } else {
  51061. el.addEventListener('render-target-loaded', setup);
  51062. }
  51063. function setup () {
  51064. var gl = el.renderer.getContext();
  51065. if (!gl) { return; }
  51066. self.cubeMapSize = gl.getParameter(gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  51067. self.material = new THREE.RawShaderMaterial({
  51068. uniforms: {map: {type: 't', value: null}},
  51069. vertexShader: VERTEX_SHADER,
  51070. fragmentShader: FRAGMENT_SHADER,
  51071. side: THREE.DoubleSide
  51072. });
  51073. self.quad = new THREE.Mesh(
  51074. new THREE.PlaneBufferGeometry(1, 1),
  51075. self.material
  51076. );
  51077. self.quad.visible = false;
  51078. self.camera = new THREE.OrthographicCamera(-1 / 2, 1 / 2, 1 / 2, -1 / 2, -10000, 10000);
  51079. self.canvas = document.createElement('canvas');
  51080. self.ctx = self.canvas.getContext('2d');
  51081. el.object3D.add(self.quad);
  51082. self.onKeyDown = self.onKeyDown.bind(self);
  51083. }
  51084. },
  51085. getRenderTarget: function (width, height) {
  51086. return new THREE.WebGLRenderTarget(width, height, {
  51087. encoding: THREE.sRGBEncoding,
  51088. minFilter: THREE.LinearFilter,
  51089. magFilter: THREE.LinearFilter,
  51090. wrapS: THREE.ClampToEdgeWrapping,
  51091. wrapT: THREE.ClampToEdgeWrapping,
  51092. format: THREE.RGBAFormat,
  51093. type: THREE.UnsignedByteType
  51094. });
  51095. },
  51096. resize: function (width, height) {
  51097. // Resize quad.
  51098. this.quad.scale.set(width, height, 1);
  51099. // Resize camera.
  51100. this.camera.left = -1 * width / 2;
  51101. this.camera.right = width / 2;
  51102. this.camera.top = height / 2;
  51103. this.camera.bottom = -1 * height / 2;
  51104. this.camera.updateProjectionMatrix();
  51105. // Resize canvas.
  51106. this.canvas.width = width;
  51107. this.canvas.height = height;
  51108. },
  51109. play: function () {
  51110. window.addEventListener('keydown', this.onKeyDown);
  51111. },
  51112. /**
  51113. * <ctrl> + <alt> + s = Regular screenshot.
  51114. * <ctrl> + <alt> + <shift> + s = Equirectangular screenshot.
  51115. */
  51116. onKeyDown: function (evt) {
  51117. var shortcutPressed = evt.keyCode === 83 && evt.ctrlKey && evt.altKey;
  51118. if (!this.data || !shortcutPressed) { return; }
  51119. var projection = evt.shiftKey ? 'equirectangular' : 'perspective';
  51120. this.capture(projection);
  51121. },
  51122. /**
  51123. * Capture a screenshot of the scene.
  51124. *
  51125. * @param {string} projection - Screenshot projection (equirectangular or perspective).
  51126. */
  51127. setCapture: function (projection) {
  51128. var el = this.el;
  51129. var size;
  51130. var camera;
  51131. var cubeCamera;
  51132. var cubeRenderTarget;
  51133. // Configure camera.
  51134. if (projection === 'perspective') {
  51135. // Quad is only used in equirectangular mode. Hide it in this case.
  51136. this.quad.visible = false;
  51137. // Use scene camera.
  51138. camera = (this.data.camera && this.data.camera.components.camera.camera) || el.camera;
  51139. size = {width: this.data.width, height: this.data.height};
  51140. } else {
  51141. // Use ortho camera.
  51142. camera = this.camera;
  51143. cubeRenderTarget = new THREE.WebGLCubeRenderTarget(
  51144. Math.min(this.cubeMapSize, 2048),
  51145. {
  51146. format: THREE.RGBFormat,
  51147. generateMipmaps: true,
  51148. minFilter: THREE.LinearMipmapLinearFilter,
  51149. encoding: THREE.sRGBEncoding
  51150. });
  51151. // Create cube camera and copy position from scene camera.
  51152. cubeCamera = new THREE.CubeCamera(el.camera.near, el.camera.far, cubeRenderTarget);
  51153. // Copy camera position into cube camera;
  51154. el.camera.getWorldPosition(cubeCamera.position);
  51155. el.camera.getWorldQuaternion(cubeCamera.quaternion);
  51156. // Render scene with cube camera.
  51157. cubeCamera.update(el.renderer, el.object3D);
  51158. this.quad.material.uniforms.map.value = cubeCamera.renderTarget.texture;
  51159. size = {width: this.data.width, height: this.data.height};
  51160. // Use quad to project image taken by the cube camera.
  51161. this.quad.visible = true;
  51162. }
  51163. return {
  51164. camera: camera,
  51165. size: size,
  51166. projection: projection
  51167. };
  51168. },
  51169. /**
  51170. * Maintained for backwards compatibility.
  51171. */
  51172. capture: function (projection) {
  51173. var isVREnabled = this.el.renderer.xr.enabled;
  51174. var renderer = this.el.renderer;
  51175. var params;
  51176. // Disable VR.
  51177. renderer.xr.enabled = false;
  51178. params = this.setCapture(projection);
  51179. this.renderCapture(params.camera, params.size, params.projection);
  51180. // Trigger file download.
  51181. this.saveCapture();
  51182. // Restore VR.
  51183. renderer.xr.enabled = isVREnabled;
  51184. },
  51185. /**
  51186. * Return canvas instead of triggering download (e.g., for uploading blob to server).
  51187. */
  51188. getCanvas: function (projection) {
  51189. var isVREnabled = this.el.renderer.xr.enabled;
  51190. var renderer = this.el.renderer;
  51191. // Disable VR.
  51192. var params = this.setCapture(projection);
  51193. renderer.xr.enabled = false;
  51194. this.renderCapture(params.camera, params.size, params.projection);
  51195. // Restore VR.
  51196. renderer.xr.enabled = isVREnabled;
  51197. return this.canvas;
  51198. },
  51199. renderCapture: function (camera, size, projection) {
  51200. var autoClear = this.el.renderer.autoClear;
  51201. var el = this.el;
  51202. var imageData;
  51203. var output;
  51204. var pixels;
  51205. var renderer = el.renderer;
  51206. // Create rendering target and buffer to store the read pixels.
  51207. output = this.getRenderTarget(size.width, size.height);
  51208. pixels = new Uint8Array(4 * size.width * size.height);
  51209. // Resize quad, camera, and canvas.
  51210. this.resize(size.width, size.height);
  51211. // Render scene to render target.
  51212. renderer.autoClear = true;
  51213. renderer.clear();
  51214. renderer.setRenderTarget(output);
  51215. renderer.render(el.object3D, camera);
  51216. renderer.autoClear = autoClear;
  51217. // Read image pizels back.
  51218. renderer.readRenderTargetPixels(output, 0, 0, size.width, size.height, pixels);
  51219. renderer.setRenderTarget(null);
  51220. if (projection === 'perspective') {
  51221. pixels = this.flipPixelsVertically(pixels, size.width, size.height);
  51222. }
  51223. imageData = new ImageData(new Uint8ClampedArray(pixels), size.width, size.height);
  51224. // Hide quad after projecting the image.
  51225. this.quad.visible = false;
  51226. // Copy pixels into canvas.
  51227. this.ctx.putImageData(imageData, 0, 0);
  51228. },
  51229. flipPixelsVertically: function (pixels, width, height) {
  51230. var flippedPixels = pixels.slice(0);
  51231. for (var x = 0; x < width; ++x) {
  51232. for (var y = 0; y < height; ++y) {
  51233. flippedPixels[x * 4 + y * width * 4] = pixels[x * 4 + (height - y) * width * 4];
  51234. flippedPixels[x * 4 + 1 + y * width * 4] = pixels[x * 4 + 1 + (height - y) * width * 4];
  51235. flippedPixels[x * 4 + 2 + y * width * 4] = pixels[x * 4 + 2 + (height - y) * width * 4];
  51236. flippedPixels[x * 4 + 3 + y * width * 4] = pixels[x * 4 + 3 + (height - y) * width * 4];
  51237. }
  51238. }
  51239. return flippedPixels;
  51240. },
  51241. /**
  51242. * Download capture to file.
  51243. */
  51244. saveCapture: function () {
  51245. this.canvas.toBlob(function (blob) {
  51246. var fileName = 'screenshot-' + document.title.toLowerCase() + '-' + Date.now() + '.png';
  51247. var linkEl = document.createElement('a');
  51248. var url = URL.createObjectURL(blob);
  51249. linkEl.href = url;
  51250. linkEl.setAttribute('download', fileName);
  51251. linkEl.innerHTML = 'downloading...';
  51252. linkEl.style.display = 'none';
  51253. document.body.appendChild(linkEl);
  51254. setTimeout(function () {
  51255. linkEl.click();
  51256. document.body.removeChild(linkEl);
  51257. }, 1);
  51258. }, 'image/png');
  51259. }
  51260. });
  51261. },{"../../core/component":131,"../../lib/three":179}],109:[function(_dereq_,module,exports){
  51262. var registerComponent = _dereq_('../../core/component').registerComponent;
  51263. var RStats = _dereq_('../../../vendor/rStats');
  51264. var utils = _dereq_('../../utils');
  51265. _dereq_('../../../vendor/rStats.extras');
  51266. _dereq_('../../lib/rStatsAframe');
  51267. var AFrameStats = window.aframeStats;
  51268. var bind = utils.bind;
  51269. var HIDDEN_CLASS = 'a-hidden';
  51270. var ThreeStats = window.threeStats;
  51271. /**
  51272. * Stats appended to document.body by RStats.
  51273. */
  51274. module.exports.Component = registerComponent('stats', {
  51275. schema: {default: true},
  51276. init: function () {
  51277. var scene = this.el;
  51278. if (utils.getUrlParameter('stats') === 'false') { return; }
  51279. this.stats = createStats(scene);
  51280. this.statsEl = document.querySelector('.rs-base');
  51281. this.hideBound = bind(this.hide, this);
  51282. this.showBound = bind(this.show, this);
  51283. scene.addEventListener('enter-vr', this.hideBound);
  51284. scene.addEventListener('exit-vr', this.showBound);
  51285. },
  51286. update: function () {
  51287. if (!this.stats) { return; }
  51288. return (!this.data) ? this.hide() : this.show();
  51289. },
  51290. remove: function () {
  51291. this.el.removeEventListener('enter-vr', this.hideBound);
  51292. this.el.removeEventListener('exit-vr', this.showBound);
  51293. if (!this.statsEl) { return; } // Scene detached.
  51294. this.statsEl.parentNode.removeChild(this.statsEl);
  51295. },
  51296. tick: function () {
  51297. var stats = this.stats;
  51298. if (!stats) { return; }
  51299. stats('rAF').tick();
  51300. stats('FPS').frame();
  51301. stats().update();
  51302. },
  51303. hide: function () {
  51304. this.statsEl.classList.add(HIDDEN_CLASS);
  51305. },
  51306. show: function () {
  51307. this.statsEl.classList.remove(HIDDEN_CLASS);
  51308. }
  51309. });
  51310. function createStats (scene) {
  51311. var threeStats = new ThreeStats(scene.renderer);
  51312. var aframeStats = new AFrameStats(scene);
  51313. var plugins = scene.isMobile ? [] : [threeStats, aframeStats];
  51314. return new RStats({
  51315. css: [], // Our stylesheet is injected from `src/index.js`.
  51316. values: {
  51317. fps: {caption: 'fps', below: 30}
  51318. },
  51319. groups: [
  51320. {caption: 'Framerate', values: ['fps', 'raf']}
  51321. ],
  51322. plugins: plugins
  51323. });
  51324. }
  51325. },{"../../../vendor/rStats":217,"../../../vendor/rStats.extras":216,"../../core/component":131,"../../lib/rStatsAframe":178,"../../utils":205}],110:[function(_dereq_,module,exports){
  51326. var registerComponent = _dereq_('../../core/component').registerComponent;
  51327. var constants = _dereq_('../../constants/');
  51328. var utils = _dereq_('../../utils/');
  51329. var bind = utils.bind;
  51330. var ENTER_VR_CLASS = 'a-enter-vr';
  51331. var ENTER_AR_CLASS = 'a-enter-ar';
  51332. var ENTER_VR_BTN_CLASS = 'a-enter-vr-button';
  51333. var ENTER_AR_BTN_CLASS = 'a-enter-ar-button';
  51334. var HIDDEN_CLASS = 'a-hidden';
  51335. var ORIENTATION_MODAL_CLASS = 'a-orientation-modal';
  51336. /**
  51337. * UI for entering VR mode.
  51338. */
  51339. module.exports.Component = registerComponent('vr-mode-ui', {
  51340. dependencies: ['canvas'],
  51341. schema: {
  51342. enabled: {default: true},
  51343. enterVRButton: {default: ''},
  51344. enterARButton: {default: ''}
  51345. },
  51346. init: function () {
  51347. var self = this;
  51348. var sceneEl = this.el;
  51349. if (utils.getUrlParameter('ui') === 'false') { return; }
  51350. this.insideLoader = false;
  51351. this.enterVREl = null;
  51352. this.enterAREl = null;
  51353. this.orientationModalEl = null;
  51354. this.bindMethods();
  51355. // Hide/show VR UI when entering/exiting VR mode.
  51356. sceneEl.addEventListener('enter-vr', this.updateEnterInterfaces);
  51357. sceneEl.addEventListener('exit-vr', this.updateEnterInterfaces);
  51358. sceneEl.addEventListener('update-vr-devices', this.updateEnterInterfaces);
  51359. window.addEventListener('message', function (event) {
  51360. if (event.data.type === 'loaderReady') {
  51361. self.insideLoader = true;
  51362. self.remove();
  51363. }
  51364. });
  51365. // Modal that tells the user to change orientation if in portrait.
  51366. window.addEventListener('orientationchange', this.toggleOrientationModalIfNeeded);
  51367. },
  51368. bindMethods: function () {
  51369. this.onEnterVRButtonClick = bind(this.onEnterVRButtonClick, this);
  51370. this.onEnterARButtonClick = bind(this.onEnterARButtonClick, this);
  51371. this.onModalClick = bind(this.onModalClick, this);
  51372. this.toggleOrientationModalIfNeeded = bind(this.toggleOrientationModalIfNeeded, this);
  51373. this.updateEnterInterfaces = bind(this.updateEnterInterfaces, this);
  51374. },
  51375. /**
  51376. * Exit VR when modal clicked.
  51377. */
  51378. onModalClick: function () {
  51379. this.el.exitVR();
  51380. },
  51381. /**
  51382. * Enter VR when clicked.
  51383. */
  51384. onEnterVRButtonClick: function () {
  51385. this.el.enterVR();
  51386. },
  51387. /**
  51388. * Enter AR when clicked.
  51389. */
  51390. onEnterARButtonClick: function () {
  51391. this.el.enterAR();
  51392. },
  51393. update: function () {
  51394. var data = this.data;
  51395. var sceneEl = this.el;
  51396. if (!data.enabled || this.insideLoader || utils.getUrlParameter('ui') === 'false') {
  51397. return this.remove();
  51398. }
  51399. if (this.enterVREl || this.enterAREl || this.orientationModalEl) { return; }
  51400. // Add UI if enabled and not already present.
  51401. if (data.enterVRButton) {
  51402. // Custom button.
  51403. this.enterVREl = document.querySelector(data.enterVRButton);
  51404. this.enterVREl.addEventListener('click', this.onEnterVRButtonClick);
  51405. } else {
  51406. this.enterVREl = createEnterVRButton(this.onEnterVRButtonClick);
  51407. sceneEl.appendChild(this.enterVREl);
  51408. }
  51409. if (data.enterARButton) {
  51410. // Custom button.
  51411. this.enterAREl = document.querySelector(data.enterARButton);
  51412. this.enterAREl.addEventListener('click', this.onEnterARButtonClick);
  51413. } else {
  51414. this.enterAREl = createEnterARButton(this.onEnterARButtonClick);
  51415. sceneEl.appendChild(this.enterAREl);
  51416. }
  51417. this.orientationModalEl = createOrientationModal(this.onModalClick);
  51418. sceneEl.appendChild(this.orientationModalEl);
  51419. this.updateEnterInterfaces();
  51420. },
  51421. remove: function () {
  51422. [this.enterVREl, this.enterAREl, this.orientationModalEl].forEach(function (uiElement) {
  51423. if (uiElement && uiElement.parentNode) {
  51424. uiElement.parentNode.removeChild(uiElement);
  51425. }
  51426. });
  51427. this.enterVREl = undefined;
  51428. this.enterAREl = undefined;
  51429. this.orientationModalEl = undefined;
  51430. },
  51431. updateEnterInterfaces: function () {
  51432. this.toggleEnterVRButtonIfNeeded();
  51433. this.toggleEnterARButtonIfNeeded();
  51434. this.toggleOrientationModalIfNeeded();
  51435. },
  51436. toggleEnterVRButtonIfNeeded: function () {
  51437. var sceneEl = this.el;
  51438. if (!this.enterVREl) { return; }
  51439. if (sceneEl.is('vr-mode')) {
  51440. this.enterVREl.classList.add(HIDDEN_CLASS);
  51441. } else {
  51442. this.enterVREl.classList.remove(HIDDEN_CLASS);
  51443. }
  51444. },
  51445. toggleEnterARButtonIfNeeded: function () {
  51446. var sceneEl = this.el;
  51447. if (!this.enterAREl) { return; }
  51448. // Hide the button while in a session, or if AR is not supported.
  51449. if (sceneEl.is('vr-mode') || !utils.device.checkARSupport()) {
  51450. this.enterAREl.classList.add(HIDDEN_CLASS);
  51451. } else {
  51452. this.enterAREl.classList.remove(HIDDEN_CLASS);
  51453. }
  51454. },
  51455. toggleOrientationModalIfNeeded: function () {
  51456. var sceneEl = this.el;
  51457. var orientationModalEl = this.orientationModalEl;
  51458. if (!orientationModalEl || !sceneEl.isMobile) { return; }
  51459. if (!utils.device.isLandscape() && sceneEl.is('vr-mode')) {
  51460. // Show if in VR mode on portrait.
  51461. orientationModalEl.classList.remove(HIDDEN_CLASS);
  51462. } else {
  51463. orientationModalEl.classList.add(HIDDEN_CLASS);
  51464. }
  51465. }
  51466. });
  51467. /**
  51468. * Create a button that when clicked will enter into stereo-rendering mode for VR.
  51469. *
  51470. * Structure: <div><button></div>
  51471. *
  51472. * @param {function} onClick - click event handler
  51473. * @returns {Element} Wrapper <div>.
  51474. */
  51475. function createEnterVRButton (onClick) {
  51476. var vrButton;
  51477. var wrapper;
  51478. // Create elements.
  51479. wrapper = document.createElement('div');
  51480. wrapper.classList.add(ENTER_VR_CLASS);
  51481. wrapper.setAttribute(constants.AFRAME_INJECTED, '');
  51482. vrButton = document.createElement('button');
  51483. vrButton.className = ENTER_VR_BTN_CLASS;
  51484. vrButton.setAttribute('title',
  51485. 'Enter VR mode with a headset or fullscreen mode on a desktop. ' +
  51486. 'Visit https://webvr.rocks or https://webvr.info for more information.');
  51487. vrButton.setAttribute(constants.AFRAME_INJECTED, '');
  51488. if (utils.device.isMobile()) { applyStickyHoverFix(vrButton); }
  51489. // Insert elements.
  51490. wrapper.appendChild(vrButton);
  51491. vrButton.addEventListener('click', function (evt) {
  51492. onClick();
  51493. evt.stopPropagation();
  51494. });
  51495. return wrapper;
  51496. }
  51497. /**
  51498. * Create a button that when clicked will enter into AR mode
  51499. *
  51500. * Structure: <div><button></div>
  51501. *
  51502. * @param {function} onClick - click event handler
  51503. * @returns {Element} Wrapper <div>.
  51504. */
  51505. function createEnterARButton (onClick) {
  51506. var arButton;
  51507. var wrapper;
  51508. // Create elements.
  51509. wrapper = document.createElement('div');
  51510. wrapper.classList.add(ENTER_AR_CLASS);
  51511. wrapper.setAttribute(constants.AFRAME_INJECTED, '');
  51512. arButton = document.createElement('button');
  51513. arButton.className = ENTER_AR_BTN_CLASS;
  51514. arButton.setAttribute('title',
  51515. 'Enter AR mode with a headset or handheld device. ' +
  51516. 'Visit https://webvr.rocks or https://webvr.info for more information.');
  51517. arButton.setAttribute(constants.AFRAME_INJECTED, '');
  51518. if (utils.device.isMobile()) { applyStickyHoverFix(arButton); }
  51519. // Insert elements.
  51520. wrapper.appendChild(arButton);
  51521. arButton.addEventListener('click', function (evt) {
  51522. onClick();
  51523. evt.stopPropagation();
  51524. });
  51525. return wrapper;
  51526. }
  51527. /**
  51528. * Creates a modal dialog to request the user to switch to landscape orientation.
  51529. *
  51530. * @param {function} onClick - click event handler
  51531. * @returns {Element} Wrapper <div>.
  51532. */
  51533. function createOrientationModal (onClick) {
  51534. var modal = document.createElement('div');
  51535. modal.className = ORIENTATION_MODAL_CLASS;
  51536. modal.classList.add(HIDDEN_CLASS);
  51537. modal.setAttribute(constants.AFRAME_INJECTED, '');
  51538. var exit = document.createElement('button');
  51539. exit.setAttribute(constants.AFRAME_INJECTED, '');
  51540. exit.innerHTML = 'Exit VR';
  51541. // Exit VR on close.
  51542. exit.addEventListener('click', onClick);
  51543. modal.appendChild(exit);
  51544. return modal;
  51545. }
  51546. /**
  51547. * CSS hover state is sticky in iOS (as in 12/18/2019)
  51548. * They are not removed on mouseleave and this function applies a class
  51549. * to resets the style.
  51550. *
  51551. * @param {function} buttonEl - Button element
  51552. */
  51553. function applyStickyHoverFix (buttonEl) {
  51554. buttonEl.addEventListener('touchstart', function () {
  51555. buttonEl.classList.remove('resethover');
  51556. });
  51557. buttonEl.addEventListener('touchend', function () {
  51558. buttonEl.classList.add('resethover');
  51559. });
  51560. }
  51561. },{"../../constants/":123,"../../core/component":131,"../../utils/":205}],111:[function(_dereq_,module,exports){
  51562. var component = _dereq_('../core/component');
  51563. var THREE = _dereq_('../lib/three');
  51564. var bind = _dereq_('../utils/bind');
  51565. var registerComponent = component.registerComponent;
  51566. /**
  51567. * Shadow component.
  51568. *
  51569. * When applied to an entity, that entity's geometry and any descendants will cast or receive
  51570. * shadows as specified by the `cast` and `receive` properties.
  51571. */
  51572. module.exports.Component = registerComponent('shadow', {
  51573. schema: {
  51574. cast: {default: true},
  51575. receive: {default: true}
  51576. },
  51577. init: function () {
  51578. this.onMeshChanged = bind(this.update, this);
  51579. this.el.addEventListener('object3dset', this.onMeshChanged);
  51580. this.system.setShadowMapEnabled(true);
  51581. },
  51582. update: function () {
  51583. var data = this.data;
  51584. this.updateDescendants(data.cast, data.receive);
  51585. },
  51586. remove: function () {
  51587. var el = this.el;
  51588. el.removeEventListener('object3dset', this.onMeshChanged);
  51589. this.updateDescendants(false, false);
  51590. },
  51591. updateDescendants: function (cast, receive) {
  51592. var sceneEl = this.el.sceneEl;
  51593. this.el.object3D.traverse(function (node) {
  51594. if (!(node instanceof THREE.Mesh)) { return; }
  51595. node.castShadow = cast;
  51596. node.receiveShadow = receive;
  51597. // If scene has already rendered, materials must be updated.
  51598. if (sceneEl.hasLoaded && node.material) {
  51599. var materials = Array.isArray(node.material) ? node.material : [node.material];
  51600. for (var i = 0; i < materials.length; i++) {
  51601. materials[i].needsUpdate = true;
  51602. }
  51603. }
  51604. });
  51605. }
  51606. });
  51607. },{"../core/component":131,"../lib/three":179,"../utils/bind":199}],112:[function(_dereq_,module,exports){
  51608. var registerComponent = _dereq_('../core/component').registerComponent;
  51609. var debug = _dereq_('../utils/debug');
  51610. var THREE = _dereq_('../lib/three');
  51611. var warn = debug('components:sound:warn');
  51612. /**
  51613. * Sound component.
  51614. */
  51615. module.exports.Component = registerComponent('sound', {
  51616. schema: {
  51617. autoplay: {default: false},
  51618. distanceModel: {default: 'inverse', oneOf: ['linear', 'inverse', 'exponential']},
  51619. loop: {default: false},
  51620. maxDistance: {default: 10000},
  51621. on: {default: ''},
  51622. poolSize: {default: 1},
  51623. positional: {default: true},
  51624. refDistance: {default: 1},
  51625. rolloffFactor: {default: 1},
  51626. src: {type: 'audio'},
  51627. volume: {default: 1}
  51628. },
  51629. multiple: true,
  51630. init: function () {
  51631. var self = this;
  51632. this.listener = null;
  51633. this.audioLoader = new THREE.AudioLoader();
  51634. this.pool = new THREE.Group();
  51635. this.loaded = false;
  51636. this.mustPlay = false;
  51637. // Don't pass evt because playSound takes a function as parameter.
  51638. this.playSoundBound = function () { self.playSound(); };
  51639. },
  51640. update: function (oldData) {
  51641. var data = this.data;
  51642. var i;
  51643. var sound;
  51644. var srcChanged = data.src !== oldData.src;
  51645. // Create new sound if not yet created or changing `src`.
  51646. if (srcChanged) {
  51647. if (!data.src) { return; }
  51648. this.setupSound();
  51649. }
  51650. for (i = 0; i < this.pool.children.length; i++) {
  51651. sound = this.pool.children[i];
  51652. if (data.positional) {
  51653. sound.setDistanceModel(data.distanceModel);
  51654. sound.setMaxDistance(data.maxDistance);
  51655. sound.setRefDistance(data.refDistance);
  51656. sound.setRolloffFactor(data.rolloffFactor);
  51657. }
  51658. sound.setLoop(data.loop);
  51659. sound.setVolume(data.volume);
  51660. sound.isPaused = false;
  51661. }
  51662. if (data.on !== oldData.on) {
  51663. this.updateEventListener(oldData.on);
  51664. }
  51665. // All sound values set. Load in `src`.
  51666. if (srcChanged) {
  51667. var self = this;
  51668. this.loaded = false;
  51669. this.audioLoader.load(data.src, function (buffer) {
  51670. for (i = 0; i < self.pool.children.length; i++) {
  51671. sound = self.pool.children[i];
  51672. sound.setBuffer(buffer);
  51673. }
  51674. self.loaded = true;
  51675. // Remove this key from cache, otherwise we can't play it again
  51676. THREE.Cache.remove(data.src);
  51677. if (self.data.autoplay || self.mustPlay) { self.playSound(); }
  51678. self.el.emit('sound-loaded', self.evtDetail, false);
  51679. });
  51680. }
  51681. },
  51682. pause: function () {
  51683. this.stopSound();
  51684. this.removeEventListener();
  51685. },
  51686. play: function () {
  51687. if (this.data.autoplay) { this.playSound(); }
  51688. this.updateEventListener();
  51689. },
  51690. remove: function () {
  51691. var i;
  51692. var sound;
  51693. this.removeEventListener();
  51694. if (this.el.getObject3D(this.attrName)) {
  51695. this.el.removeObject3D(this.attrName);
  51696. }
  51697. try {
  51698. for (i = 0; i < this.pool.children.length; i++) {
  51699. sound = this.pool.children[i];
  51700. sound.disconnect();
  51701. }
  51702. } catch (e) {
  51703. // disconnect() will throw if it was never connected initially.
  51704. warn('Audio source not properly disconnected');
  51705. }
  51706. },
  51707. /**
  51708. * Update listener attached to the user defined on event.
  51709. */
  51710. updateEventListener: function (oldEvt) {
  51711. var el = this.el;
  51712. if (oldEvt) { el.removeEventListener(oldEvt, this.playSoundBound); }
  51713. el.addEventListener(this.data.on, this.playSoundBound);
  51714. },
  51715. removeEventListener: function () {
  51716. this.el.removeEventListener(this.data.on, this.playSoundBound);
  51717. },
  51718. /**
  51719. * Removes current sound object, creates new sound object, adds to entity.
  51720. *
  51721. * @returns {object} sound
  51722. */
  51723. setupSound: function () {
  51724. var el = this.el;
  51725. var i;
  51726. var sceneEl = el.sceneEl;
  51727. var self = this;
  51728. var sound;
  51729. if (this.pool.children.length > 0) {
  51730. this.stopSound();
  51731. el.removeObject3D('sound');
  51732. }
  51733. // Only want one AudioListener. Cache it on the scene.
  51734. var listener = this.listener = sceneEl.audioListener || new THREE.AudioListener();
  51735. sceneEl.audioListener = listener;
  51736. if (sceneEl.camera) {
  51737. sceneEl.camera.add(listener);
  51738. }
  51739. // Wait for camera if necessary.
  51740. sceneEl.addEventListener('camera-set-active', function (evt) {
  51741. evt.detail.cameraEl.getObject3D('camera').add(listener);
  51742. });
  51743. // Create [poolSize] audio instances and attach them to pool
  51744. this.pool = new THREE.Group();
  51745. for (i = 0; i < this.data.poolSize; i++) {
  51746. sound = this.data.positional
  51747. ? new THREE.PositionalAudio(listener)
  51748. : new THREE.Audio(listener);
  51749. this.pool.add(sound);
  51750. }
  51751. el.setObject3D(this.attrName, this.pool);
  51752. for (i = 0; i < this.pool.children.length; i++) {
  51753. sound = this.pool.children[i];
  51754. sound.onEnded = function () {
  51755. this.isPlaying = false;
  51756. self.el.emit('sound-ended', self.evtDetail, false);
  51757. };
  51758. }
  51759. },
  51760. /**
  51761. * Pause all the sounds in the pool.
  51762. */
  51763. pauseSound: function () {
  51764. var i;
  51765. var sound;
  51766. this.isPlaying = false;
  51767. for (i = 0; i < this.pool.children.length; i++) {
  51768. sound = this.pool.children[i];
  51769. if (!sound.source || !sound.source.buffer || !sound.isPlaying || sound.isPaused) {
  51770. continue;
  51771. }
  51772. sound.isPaused = true;
  51773. sound.pause();
  51774. }
  51775. },
  51776. /**
  51777. * Look for an unused sound in the pool and play it if found.
  51778. */
  51779. playSound: function (processSound) {
  51780. var found;
  51781. var i;
  51782. var sound;
  51783. if (!this.loaded) {
  51784. warn('Sound not loaded yet. It will be played once it finished loading');
  51785. this.mustPlay = true;
  51786. return;
  51787. }
  51788. found = false;
  51789. this.isPlaying = true;
  51790. for (i = 0; i < this.pool.children.length; i++) {
  51791. sound = this.pool.children[i];
  51792. if (!sound.isPlaying && sound.buffer && !found) {
  51793. if (processSound) { processSound(sound); }
  51794. sound.play();
  51795. sound.isPaused = false;
  51796. found = true;
  51797. continue;
  51798. }
  51799. }
  51800. if (!found) {
  51801. warn('All the sounds are playing. If you need to play more sounds simultaneously ' +
  51802. 'consider increasing the size of pool with the `poolSize` attribute.', this.el);
  51803. return;
  51804. }
  51805. this.mustPlay = false;
  51806. },
  51807. /**
  51808. * Stop all the sounds in the pool.
  51809. */
  51810. stopSound: function () {
  51811. var i;
  51812. var sound;
  51813. this.isPlaying = false;
  51814. for (i = 0; i < this.pool.children.length; i++) {
  51815. sound = this.pool.children[i];
  51816. if (!sound.source || !sound.source.buffer) { return; }
  51817. sound.stop();
  51818. }
  51819. }
  51820. });
  51821. },{"../core/component":131,"../lib/three":179,"../utils/debug":201}],113:[function(_dereq_,module,exports){
  51822. var createTextGeometry = _dereq_('three-bmfont-text');
  51823. var loadBMFont = _dereq_('load-bmfont');
  51824. var registerComponent = _dereq_('../core/component').registerComponent;
  51825. var coreShader = _dereq_('../core/shader');
  51826. var THREE = _dereq_('../lib/three');
  51827. var utils = _dereq_('../utils/');
  51828. var error = utils.debug('components:text:error');
  51829. var shaders = coreShader.shaders;
  51830. var warn = utils.debug('components:text:warn');
  51831. // 1 to match other A-Frame default widths.
  51832. var DEFAULT_WIDTH = 1;
  51833. // @bryik set anisotropy to 16. Improves look of large amounts of text when viewed from angle.
  51834. var MAX_ANISOTROPY = 16;
  51835. var FONT_BASE_URL = 'https://cdn.aframe.io/fonts/';
  51836. var FONTS = {
  51837. aileronsemibold: FONT_BASE_URL + 'Aileron-Semibold.fnt',
  51838. dejavu: FONT_BASE_URL + 'DejaVu-sdf.fnt',
  51839. exo2bold: FONT_BASE_URL + 'Exo2Bold.fnt',
  51840. exo2semibold: FONT_BASE_URL + 'Exo2SemiBold.fnt',
  51841. kelsonsans: FONT_BASE_URL + 'KelsonSans.fnt',
  51842. monoid: FONT_BASE_URL + 'Monoid.fnt',
  51843. mozillavr: FONT_BASE_URL + 'mozillavr.fnt',
  51844. roboto: FONT_BASE_URL + 'Roboto-msdf.json',
  51845. sourcecodepro: FONT_BASE_URL + 'SourceCodePro.fnt'
  51846. };
  51847. var MSDF_FONTS = ['roboto'];
  51848. var DEFAULT_FONT = 'roboto';
  51849. module.exports.FONTS = FONTS;
  51850. var cache = new PromiseCache();
  51851. var fontWidthFactors = {};
  51852. var textures = {};
  51853. // Regular expression for detecting a URLs with a protocol prefix.
  51854. var protocolRe = /^\w+:/;
  51855. /**
  51856. * SDF-based text component.
  51857. * Based on https://github.com/Jam3/three-bmfont-text.
  51858. *
  51859. * All the stock fonts are for the `sdf` registered shader, an improved version of jam3's
  51860. * original `sdf` shader.
  51861. */
  51862. module.exports.Component = registerComponent('text', {
  51863. multiple: true,
  51864. schema: {
  51865. align: {type: 'string', default: 'left', oneOf: ['left', 'right', 'center']},
  51866. alphaTest: {default: 0.5},
  51867. // `anchor` defaults to center to match geometries.
  51868. anchor: {default: 'center', oneOf: ['left', 'right', 'center', 'align']},
  51869. baseline: {default: 'center', oneOf: ['top', 'center', 'bottom']},
  51870. color: {type: 'color', default: '#FFF'},
  51871. font: {type: 'string', default: DEFAULT_FONT},
  51872. // `fontImage` defaults to the font name as a .png (e.g., mozillavr.fnt -> mozillavr.png).
  51873. fontImage: {type: 'string'},
  51874. // `height` has no default, will be populated at layout.
  51875. height: {type: 'number'},
  51876. letterSpacing: {type: 'number', default: 0},
  51877. // `lineHeight` defaults to font's `lineHeight` value.
  51878. lineHeight: {type: 'number'},
  51879. // `negate` must be true for fonts generated with older versions of msdfgen (white background).
  51880. negate: {type: 'boolean', default: true},
  51881. opacity: {type: 'number', default: 1.0},
  51882. shader: {default: 'sdf', oneOf: shaders},
  51883. side: {default: 'front', oneOf: ['front', 'back', 'double']},
  51884. tabSize: {default: 4},
  51885. transparent: {default: true},
  51886. value: {type: 'string'},
  51887. whiteSpace: {default: 'normal', oneOf: ['normal', 'pre', 'nowrap']},
  51888. // `width` defaults to geometry width if present, else `DEFAULT_WIDTH`.
  51889. width: {type: 'number'},
  51890. // `wrapCount` units are about one default font character. Wrap roughly at this number.
  51891. wrapCount: {type: 'number', default: 40},
  51892. // `wrapPixels` will wrap using bmfont pixel units (e.g., dejavu's is 32 pixels).
  51893. wrapPixels: {type: 'number'},
  51894. // `xOffset` to add padding.
  51895. xOffset: {type: 'number', default: 0},
  51896. // `yOffset` to adjust generated fonts from tools that may have incorrect metrics.
  51897. yOffset: {type: 'number', default: 0},
  51898. // `zOffset` will provide a small z offset to avoid z-fighting.
  51899. zOffset: {type: 'number', default: 0.001}
  51900. },
  51901. init: function () {
  51902. this.shaderData = {};
  51903. this.geometry = createTextGeometry();
  51904. this.createOrUpdateMaterial();
  51905. },
  51906. update: function (oldData) {
  51907. var data = this.data;
  51908. var font = this.currentFont;
  51909. if (textures[data.font]) {
  51910. this.texture = textures[data.font];
  51911. } else {
  51912. // Create texture per font.
  51913. this.texture = textures[data.font] = new THREE.Texture();
  51914. this.texture.anisotropy = MAX_ANISOTROPY;
  51915. }
  51916. // Update material.
  51917. this.createOrUpdateMaterial();
  51918. // New font. `updateFont` will later change data and layout.
  51919. if (oldData.font !== data.font) {
  51920. this.updateFont();
  51921. return;
  51922. }
  51923. // Update geometry and layout.
  51924. if (font) {
  51925. this.updateGeometry(this.geometry, font);
  51926. this.updateLayout();
  51927. }
  51928. },
  51929. /**
  51930. * Clean up geometry, material, texture, mesh, objects.
  51931. */
  51932. remove: function () {
  51933. this.geometry.dispose();
  51934. this.geometry = null;
  51935. this.el.removeObject3D(this.attrName);
  51936. this.material.dispose();
  51937. this.material = null;
  51938. this.texture.dispose();
  51939. this.texture = null;
  51940. if (this.shaderObject) { delete this.shaderObject; }
  51941. },
  51942. /**
  51943. * Update the shader of the material.
  51944. */
  51945. createOrUpdateMaterial: function () {
  51946. var data = this.data;
  51947. var hasChangedShader;
  51948. var material = this.material;
  51949. var NewShader;
  51950. var shaderData = this.shaderData;
  51951. var shaderName;
  51952. // Infer shader if using a stock font (or from `-msdf` filename convention).
  51953. shaderName = data.shader;
  51954. if (MSDF_FONTS.indexOf(data.font) !== -1 || data.font.indexOf('-msdf.') >= 0) {
  51955. shaderName = 'msdf';
  51956. } else if (data.font in FONTS && MSDF_FONTS.indexOf(data.font) === -1) {
  51957. shaderName = 'sdf';
  51958. }
  51959. hasChangedShader = (this.shaderObject && this.shaderObject.name) !== shaderName;
  51960. shaderData.alphaTest = data.alphaTest;
  51961. shaderData.color = data.color;
  51962. shaderData.map = this.texture;
  51963. shaderData.opacity = data.opacity;
  51964. shaderData.side = parseSide(data.side);
  51965. shaderData.transparent = data.transparent;
  51966. shaderData.negate = data.negate;
  51967. // Shader has not changed, do an update.
  51968. if (!hasChangedShader) {
  51969. // Update shader material.
  51970. this.shaderObject.update(shaderData);
  51971. // Apparently, was not set on `init` nor `update`.
  51972. material.transparent = shaderData.transparent;
  51973. material.side = shaderData.side;
  51974. return;
  51975. }
  51976. // Shader has changed. Create a shader material.
  51977. NewShader = createShader(this.el, shaderName, shaderData);
  51978. this.material = NewShader.material;
  51979. this.shaderObject = NewShader.shader;
  51980. // Set new shader material.
  51981. this.material.side = shaderData.side;
  51982. if (this.mesh) { this.mesh.material = this.material; }
  51983. },
  51984. /**
  51985. * Load font for geometry, load font image for material, and apply.
  51986. */
  51987. updateFont: function () {
  51988. var data = this.data;
  51989. var el = this.el;
  51990. var fontSrc;
  51991. var geometry = this.geometry;
  51992. var self = this;
  51993. if (!data.font) { warn('No font specified. Using the default font.'); }
  51994. // Make invisible during font swap.
  51995. if (this.mesh) { this.mesh.visible = false; }
  51996. // Look up font URL to use, and perform cached load.
  51997. fontSrc = this.lookupFont(data.font || DEFAULT_FONT) || data.font;
  51998. cache.get(fontSrc, function doLoadFont () {
  51999. return loadFont(fontSrc, data.yOffset);
  52000. }).then(function setFont (font) {
  52001. var fontImgSrc;
  52002. if (font.pages.length !== 1) {
  52003. throw new Error('Currently only single-page bitmap fonts are supported.');
  52004. }
  52005. if (!fontWidthFactors[fontSrc]) {
  52006. font.widthFactor = fontWidthFactors[font] = computeFontWidthFactor(font);
  52007. }
  52008. self.currentFont = font;
  52009. // Look up font image URL to use, and perform cached load.
  52010. fontImgSrc = self.getFontImageSrc();
  52011. cache.get(fontImgSrc, function () {
  52012. return loadTexture(fontImgSrc);
  52013. }).then(function (image) {
  52014. // Make mesh visible and apply font image as texture.
  52015. var texture = self.texture;
  52016. texture.image = image;
  52017. texture.needsUpdate = true;
  52018. textures[data.font] = texture;
  52019. self.texture = texture;
  52020. self.initMesh();
  52021. self.currentFont = font;
  52022. // Update geometry given font metrics.
  52023. self.updateGeometry(geometry, font);
  52024. self.updateLayout();
  52025. self.mesh.visible = true;
  52026. el.emit('textfontset', {font: data.font, fontObj: font});
  52027. }).catch(function (err) {
  52028. error(err.message);
  52029. error(err.stack);
  52030. });
  52031. }).catch(function (err) {
  52032. error(err.message);
  52033. error(err.stack);
  52034. });
  52035. },
  52036. initMesh: function () {
  52037. if (this.mesh) { return; }
  52038. this.mesh = new THREE.Mesh(this.geometry, this.material);
  52039. this.el.setObject3D(this.attrName, this.mesh);
  52040. },
  52041. getFontImageSrc: function () {
  52042. if (this.data.fontImage) { return this.data.fontImage; }
  52043. var fontSrc = this.lookupFont(this.data.font || DEFAULT_FONT) || this.data.font;
  52044. var imageSrc = this.currentFont.pages[0];
  52045. // If the image URL contains a non-HTTP(S) protocol, assume it's an absolute
  52046. // path on disk and try to infer the path from the font source instead.
  52047. if (imageSrc.match(protocolRe) && imageSrc.indexOf('http') !== 0) {
  52048. return fontSrc.replace(/(\.fnt)|(\.json)/, '.png');
  52049. }
  52050. return THREE.LoaderUtils.extractUrlBase(fontSrc) + imageSrc;
  52051. },
  52052. /**
  52053. * Update layout with anchor, alignment, baseline, and considering any meshes.
  52054. */
  52055. updateLayout: function () {
  52056. var anchor;
  52057. var baseline;
  52058. var el = this.el;
  52059. var data = this.data;
  52060. var geometry = this.geometry;
  52061. var geometryComponent;
  52062. var height;
  52063. var layout;
  52064. var mesh = this.mesh;
  52065. var textRenderWidth;
  52066. var textScale;
  52067. var width;
  52068. var x;
  52069. var y;
  52070. if (!mesh || !geometry.layout) { return; }
  52071. // Determine width to use (defined width, geometry's width, or default width).
  52072. geometryComponent = el.getAttribute('geometry');
  52073. width = data.width || (geometryComponent && geometryComponent.width) || DEFAULT_WIDTH;
  52074. // Determine wrap pixel count. Either specified or by experimental fudge factor.
  52075. // Note that experimental factor will never be correct for variable width fonts.
  52076. textRenderWidth = computeWidth(data.wrapPixels, data.wrapCount,
  52077. this.currentFont.widthFactor);
  52078. textScale = width / textRenderWidth;
  52079. // Determine height to use.
  52080. layout = geometry.layout;
  52081. height = textScale * (layout.height + layout.descender);
  52082. // Update geometry dimensions to match text layout if width and height are set to 0.
  52083. // For example, scales a plane to fit text.
  52084. if (geometryComponent && geometryComponent.primitive === 'plane') {
  52085. if (!geometryComponent.width) { el.setAttribute('geometry', 'width', width); }
  52086. if (!geometryComponent.height) { el.setAttribute('geometry', 'height', height); }
  52087. }
  52088. // Calculate X position to anchor text left, center, or right.
  52089. anchor = data.anchor === 'align' ? data.align : data.anchor;
  52090. if (anchor === 'left') {
  52091. x = 0;
  52092. } else if (anchor === 'right') {
  52093. x = -1 * layout.width;
  52094. } else if (anchor === 'center') {
  52095. x = -1 * layout.width / 2;
  52096. } else {
  52097. throw new TypeError('Invalid text.anchor property value', anchor);
  52098. }
  52099. // Calculate Y position to anchor text top, center, or bottom.
  52100. baseline = data.baseline;
  52101. if (baseline === 'bottom') {
  52102. y = 0;
  52103. } else if (baseline === 'top') {
  52104. y = -1 * layout.height + layout.ascender;
  52105. } else if (baseline === 'center') {
  52106. y = -1 * layout.height / 2;
  52107. } else {
  52108. throw new TypeError('Invalid text.baseline property value', baseline);
  52109. }
  52110. // Position and scale mesh to apply layout.
  52111. mesh.position.x = x * textScale + data.xOffset;
  52112. mesh.position.y = y * textScale;
  52113. // Place text slightly in front to avoid Z-fighting.
  52114. mesh.position.z = data.zOffset;
  52115. mesh.scale.set(textScale, -1 * textScale, textScale);
  52116. },
  52117. /**
  52118. * Grab font from the constant.
  52119. * Set as a method for test stubbing purposes.
  52120. */
  52121. lookupFont: function (key) {
  52122. return FONTS[key];
  52123. },
  52124. /**
  52125. * Update the text geometry using `three-bmfont-text.update`.
  52126. */
  52127. updateGeometry: (function () {
  52128. var geometryUpdateBase = {};
  52129. var geometryUpdateData = {};
  52130. var newLineRegex = /\\n/g;
  52131. var tabRegex = /\\t/g;
  52132. return function (geometry, font) {
  52133. var data = this.data;
  52134. geometryUpdateData.font = font;
  52135. geometryUpdateData.lineHeight = data.lineHeight && isFinite(data.lineHeight)
  52136. ? data.lineHeight
  52137. : font.common.lineHeight;
  52138. geometryUpdateData.text = data.value.toString().replace(newLineRegex, '\n')
  52139. .replace(tabRegex, '\t');
  52140. geometryUpdateData.width = computeWidth(data.wrapPixels, data.wrapCount,
  52141. font.widthFactor);
  52142. geometry.update(utils.extend(geometryUpdateBase, data, geometryUpdateData));
  52143. };
  52144. })()
  52145. });
  52146. /**
  52147. * Due to using negative scale, we return the opposite side specified.
  52148. * https://github.com/mrdoob/three.js/pull/12787/
  52149. */
  52150. function parseSide (side) {
  52151. switch (side) {
  52152. case 'back': {
  52153. return THREE.FrontSide;
  52154. }
  52155. case 'double': {
  52156. return THREE.DoubleSide;
  52157. }
  52158. default: {
  52159. return THREE.BackSide;
  52160. }
  52161. }
  52162. }
  52163. /**
  52164. * @returns {Promise}
  52165. */
  52166. function loadFont (src, yOffset) {
  52167. return new Promise(function (resolve, reject) {
  52168. loadBMFont(src, function (err, font) {
  52169. if (err) {
  52170. error('Error loading font', src);
  52171. reject(err);
  52172. return;
  52173. }
  52174. // Fix negative Y offsets for Roboto MSDF font from tool. Experimentally determined.
  52175. if (src.indexOf('/Roboto-msdf.json') >= 0) { yOffset = 30; }
  52176. if (yOffset) { font.chars.map(function doOffset (ch) { ch.yoffset += yOffset; }); }
  52177. resolve(font);
  52178. });
  52179. });
  52180. }
  52181. /**
  52182. * @returns {Promise}
  52183. */
  52184. function loadTexture (src) {
  52185. return new Promise(function (resolve, reject) {
  52186. new THREE.ImageLoader().load(src, function (image) {
  52187. resolve(image);
  52188. }, undefined, function () {
  52189. error('Error loading font image', src);
  52190. reject(null);
  52191. });
  52192. });
  52193. }
  52194. function createShader (el, shaderName, data) {
  52195. var shader;
  52196. var shaderObject;
  52197. // Set up Shader.
  52198. shaderObject = new shaders[shaderName].Shader();
  52199. shaderObject.el = el;
  52200. shaderObject.init(data);
  52201. shaderObject.update(data);
  52202. // Get material.
  52203. shader = shaderObject.material;
  52204. // Apparently, was not set on `init` nor `update`.
  52205. shader.transparent = data.transparent;
  52206. return {
  52207. material: shader,
  52208. shader: shaderObject
  52209. };
  52210. }
  52211. /**
  52212. * Determine wrap pixel count. Either specified or by experimental fudge factor.
  52213. * Note that experimental factor will never be correct for variable width fonts.
  52214. */
  52215. function computeWidth (wrapPixels, wrapCount, widthFactor) {
  52216. return wrapPixels || ((0.5 + wrapCount) * widthFactor);
  52217. }
  52218. /**
  52219. * Compute default font width factor to use.
  52220. */
  52221. function computeFontWidthFactor (font) {
  52222. var sum = 0;
  52223. var digitsum = 0;
  52224. var digits = 0;
  52225. font.chars.map(function (ch) {
  52226. sum += ch.xadvance;
  52227. if (ch.id >= 48 && ch.id <= 57) {
  52228. digits++;
  52229. digitsum += ch.xadvance;
  52230. }
  52231. });
  52232. return digits ? digitsum / digits : sum / font.chars.length;
  52233. }
  52234. /**
  52235. * Get or create a promise given a key and promise generator.
  52236. * @todo Move to a utility and use in other parts of A-Frame.
  52237. */
  52238. function PromiseCache () {
  52239. var cache = this.cache = {};
  52240. this.get = function (key, promiseGenerator) {
  52241. if (key in cache) {
  52242. return cache[key];
  52243. }
  52244. cache[key] = promiseGenerator();
  52245. return cache[key];
  52246. };
  52247. }
  52248. },{"../core/component":131,"../core/shader":141,"../lib/three":179,"../utils/":205,"load-bmfont":37,"three-bmfont-text":63}],114:[function(_dereq_,module,exports){
  52249. var registerComponent = _dereq_('../core/component').registerComponent;
  52250. var controllerUtils = _dereq_('../utils/tracked-controls');
  52251. var DEFAULT_CAMERA_HEIGHT = _dereq_('../constants').DEFAULT_CAMERA_HEIGHT;
  52252. var THREE = _dereq_('../lib/three');
  52253. var DEFAULT_HANDEDNESS = _dereq_('../constants').DEFAULT_HANDEDNESS;
  52254. // Vector from eyes to elbow (divided by user height).
  52255. var EYES_TO_ELBOW = {x: 0.175, y: -0.3, z: -0.03};
  52256. // Vector from eyes to elbow (divided by user height).
  52257. var FOREARM = {x: 0, y: 0, z: -0.175};
  52258. // Due to unfortunate name collision, add empty touches array to avoid Daydream error.
  52259. var EMPTY_DAYDREAM_TOUCHES = {touches: []};
  52260. var EVENTS = {
  52261. AXISMOVE: 'axismove',
  52262. BUTTONCHANGED: 'buttonchanged',
  52263. BUTTONDOWN: 'buttondown',
  52264. BUTTONUP: 'buttonup',
  52265. TOUCHSTART: 'touchstart',
  52266. TOUCHEND: 'touchend'
  52267. };
  52268. /**
  52269. * Tracked controls component.
  52270. * Wrap the gamepad API for pose and button states.
  52271. * Select the appropriate controller and apply pose to the entity.
  52272. * Observe button states and emit appropriate events.
  52273. *
  52274. * @property {number} controller - Index of controller in array returned by Gamepad API.
  52275. * Only used if hand property is not set.
  52276. * @property {string} id - Selected controller among those returned by Gamepad API.
  52277. * @property {number} hand - If multiple controllers found with id, choose the one with the
  52278. * given value for hand. If set, we ignore 'controller' property
  52279. */
  52280. module.exports.Component = registerComponent('tracked-controls-webvr', {
  52281. schema: {
  52282. autoHide: {default: true},
  52283. controller: {default: 0},
  52284. id: {type: 'string', default: ''},
  52285. hand: {type: 'string', default: ''},
  52286. idPrefix: {type: 'string', default: ''},
  52287. orientationOffset: {type: 'vec3'},
  52288. // Arm model parameters when not 6DoF.
  52289. armModel: {default: false},
  52290. headElement: {type: 'selector'}
  52291. },
  52292. init: function () {
  52293. // Copy variables back to tracked-controls for backwards compatibility.
  52294. // Some 3rd components rely on them.
  52295. this.axis = this.el.components['tracked-controls'].axis = [0, 0, 0];
  52296. this.buttonStates = this.el.components['tracked-controls'].buttonStates = {};
  52297. this.changedAxes = [];
  52298. this.targetControllerNumber = this.data.controller;
  52299. this.axisMoveEventDetail = {axis: this.axis, changed: this.changedAxes};
  52300. this.deltaControllerPosition = new THREE.Vector3();
  52301. this.controllerQuaternion = new THREE.Quaternion();
  52302. this.controllerEuler = new THREE.Euler();
  52303. this.updateGamepad();
  52304. this.buttonEventDetails = {};
  52305. },
  52306. tick: function (time, delta) {
  52307. var mesh = this.el.getObject3D('mesh');
  52308. // Update mesh animations.
  52309. if (mesh && mesh.update) { mesh.update(delta / 1000); }
  52310. this.updateGamepad();
  52311. this.updatePose();
  52312. this.updateButtons();
  52313. },
  52314. /**
  52315. * Return default user height to use for non-6DOF arm model.
  52316. */
  52317. defaultUserHeight: function () {
  52318. return DEFAULT_CAMERA_HEIGHT;
  52319. },
  52320. /**
  52321. * Return head element to use for non-6DOF arm model.
  52322. */
  52323. getHeadElement: function () {
  52324. return this.data.headElement || this.el.sceneEl.camera.el;
  52325. },
  52326. /**
  52327. * Handle update controller match criteria (such as `id`, `idPrefix`, `hand`, `controller`)
  52328. */
  52329. updateGamepad: function () {
  52330. var data = this.data;
  52331. var controller = controllerUtils.findMatchingControllerWebVR(
  52332. this.system.controllers,
  52333. data.id,
  52334. data.idPrefix,
  52335. data.hand,
  52336. data.controller
  52337. );
  52338. this.controller = controller;
  52339. // Legacy handle to the controller for old components.
  52340. this.el.components['tracked-controls'].controller = controller;
  52341. if (this.data.autoHide) { this.el.object3D.visible = !!this.controller; }
  52342. },
  52343. /**
  52344. * Applies an artificial arm model to simulate elbow to wrist positioning
  52345. * based on the orientation of the controller.
  52346. *
  52347. * @param {object} controllerPosition - Existing vector to update with controller position.
  52348. */
  52349. applyArmModel: function (controllerPosition) {
  52350. // Use controllerPosition and deltaControllerPosition to avoid creating variables.
  52351. var controller = this.controller;
  52352. var controllerEuler = this.controllerEuler;
  52353. var controllerQuaternion = this.controllerQuaternion;
  52354. var deltaControllerPosition = this.deltaControllerPosition;
  52355. var hand;
  52356. var headEl;
  52357. var headObject3D;
  52358. var pose;
  52359. var userHeight;
  52360. headEl = this.getHeadElement();
  52361. headObject3D = headEl.object3D;
  52362. userHeight = this.defaultUserHeight();
  52363. pose = controller.pose;
  52364. hand = (controller ? controller.hand : undefined) || DEFAULT_HANDEDNESS;
  52365. // Use camera position as head position.
  52366. controllerPosition.copy(headObject3D.position);
  52367. // Set offset for degenerate "arm model" to elbow.
  52368. deltaControllerPosition.set(
  52369. EYES_TO_ELBOW.x * (hand === 'left' ? -1 : hand === 'right' ? 1 : 0),
  52370. EYES_TO_ELBOW.y, // Lower than our eyes.
  52371. EYES_TO_ELBOW.z); // Slightly out in front.
  52372. // Scale offset by user height.
  52373. deltaControllerPosition.multiplyScalar(userHeight);
  52374. // Apply camera Y rotation (not X or Z, so you can look down at your hand).
  52375. deltaControllerPosition.applyAxisAngle(headObject3D.up, headObject3D.rotation.y);
  52376. // Apply rotated offset to position.
  52377. controllerPosition.add(deltaControllerPosition);
  52378. // Set offset for degenerate "arm model" forearm. Forearm sticking out from elbow.
  52379. deltaControllerPosition.set(FOREARM.x, FOREARM.y, FOREARM.z);
  52380. // Scale offset by user height.
  52381. deltaControllerPosition.multiplyScalar(userHeight);
  52382. // Apply controller X/Y rotation (tilting up/down/left/right is usually moving the arm).
  52383. if (pose.orientation) {
  52384. controllerQuaternion.fromArray(pose.orientation);
  52385. } else {
  52386. controllerQuaternion.copy(headObject3D.quaternion);
  52387. }
  52388. controllerEuler.setFromQuaternion(controllerQuaternion);
  52389. controllerEuler.set(controllerEuler.x, controllerEuler.y, 0);
  52390. deltaControllerPosition.applyEuler(controllerEuler);
  52391. // Apply rotated offset to position.
  52392. controllerPosition.add(deltaControllerPosition);
  52393. },
  52394. /**
  52395. * Read pose from controller (from Gamepad API), apply transforms, apply to entity.
  52396. */
  52397. updatePose: function () {
  52398. var controller = this.controller;
  52399. var data = this.data;
  52400. var object3D = this.el.object3D;
  52401. var pose;
  52402. var vrDisplay = this.system.vrDisplay;
  52403. var standingMatrix;
  52404. if (!controller) { return; }
  52405. // Compose pose from Gamepad.
  52406. pose = controller.pose;
  52407. if (pose.position) {
  52408. object3D.position.fromArray(pose.position);
  52409. } else {
  52410. // Controller not 6DOF, apply arm model.
  52411. if (data.armModel) { this.applyArmModel(object3D.position); }
  52412. }
  52413. if (pose.orientation) {
  52414. object3D.quaternion.fromArray(pose.orientation);
  52415. }
  52416. // Apply transforms, if 6DOF and in VR.
  52417. if (vrDisplay && pose.position) {
  52418. standingMatrix = this.el.sceneEl.renderer.xr.getStandingMatrix();
  52419. object3D.matrix.compose(object3D.position, object3D.quaternion, object3D.scale);
  52420. object3D.matrix.multiplyMatrices(standingMatrix, object3D.matrix);
  52421. object3D.matrix.decompose(object3D.position, object3D.quaternion, object3D.scale);
  52422. }
  52423. object3D.rotateX(this.data.orientationOffset.x * THREE.Math.DEG2RAD);
  52424. object3D.rotateY(this.data.orientationOffset.y * THREE.Math.DEG2RAD);
  52425. object3D.rotateZ(this.data.orientationOffset.z * THREE.Math.DEG2RAD);
  52426. },
  52427. /**
  52428. * Handle button changes including axes, presses, touches, values.
  52429. */
  52430. updateButtons: function () {
  52431. var buttonState;
  52432. var controller = this.controller;
  52433. var id;
  52434. if (!controller) { return; }
  52435. // Check every button.
  52436. for (id = 0; id < controller.buttons.length; ++id) {
  52437. // Initialize button state.
  52438. if (!this.buttonStates[id]) {
  52439. this.buttonStates[id] = {pressed: false, touched: false, value: 0};
  52440. }
  52441. if (!this.buttonEventDetails[id]) {
  52442. this.buttonEventDetails[id] = {id: id, state: this.buttonStates[id]};
  52443. }
  52444. buttonState = controller.buttons[id];
  52445. this.handleButton(id, buttonState);
  52446. }
  52447. // Check axes.
  52448. this.handleAxes();
  52449. },
  52450. /**
  52451. * Handle presses and touches for a single button.
  52452. *
  52453. * @param {number} id - Index of button in Gamepad button array.
  52454. * @param {number} buttonState - Value of button state from 0 to 1.
  52455. * @returns {boolean} Whether button has changed in any way.
  52456. */
  52457. handleButton: function (id, buttonState) {
  52458. var changed;
  52459. changed = this.handlePress(id, buttonState) |
  52460. this.handleTouch(id, buttonState) |
  52461. this.handleValue(id, buttonState);
  52462. if (!changed) { return false; }
  52463. this.el.emit(EVENTS.BUTTONCHANGED, this.buttonEventDetails[id], false);
  52464. return true;
  52465. },
  52466. /**
  52467. * An axis is an array of values from -1 (up, left) to 1 (down, right).
  52468. * Compare each component of the axis to the previous value to determine change.
  52469. *
  52470. * @returns {boolean} Whether axes changed.
  52471. */
  52472. handleAxes: function () {
  52473. var changed = false;
  52474. var controllerAxes = this.controller.axes;
  52475. var i;
  52476. var previousAxis = this.axis;
  52477. var changedAxes = this.changedAxes;
  52478. // Check if axis changed.
  52479. this.changedAxes.splice(0, this.changedAxes.length);
  52480. for (i = 0; i < controllerAxes.length; ++i) {
  52481. changedAxes.push(previousAxis[i] !== controllerAxes[i]);
  52482. if (changedAxes[i]) { changed = true; }
  52483. }
  52484. if (!changed) { return false; }
  52485. this.axis.splice(0, this.axis.length);
  52486. for (i = 0; i < controllerAxes.length; i++) {
  52487. this.axis.push(controllerAxes[i]);
  52488. }
  52489. this.el.emit(EVENTS.AXISMOVE, this.axisMoveEventDetail, false);
  52490. return true;
  52491. },
  52492. /**
  52493. * Determine whether a button press has occured and emit events as appropriate.
  52494. *
  52495. * @param {string} id - ID of the button to check.
  52496. * @param {object} buttonState - State of the button to check.
  52497. * @returns {boolean} Whether button press state changed.
  52498. */
  52499. handlePress: function (id, buttonState) {
  52500. var evtName;
  52501. var previousButtonState = this.buttonStates[id];
  52502. // Not changed.
  52503. if (buttonState.pressed === previousButtonState.pressed) { return false; }
  52504. evtName = buttonState.pressed ? EVENTS.BUTTONDOWN : EVENTS.BUTTONUP;
  52505. this.el.emit(evtName, this.buttonEventDetails[id], false);
  52506. previousButtonState.pressed = buttonState.pressed;
  52507. return true;
  52508. },
  52509. /**
  52510. * Determine whether a button touch has occured and emit events as appropriate.
  52511. *
  52512. * @param {string} id - ID of the button to check.
  52513. * @param {object} buttonState - State of the button to check.
  52514. * @returns {boolean} Whether button touch state changed.
  52515. */
  52516. handleTouch: function (id, buttonState) {
  52517. var evtName;
  52518. var previousButtonState = this.buttonStates[id];
  52519. // Not changed.
  52520. if (buttonState.touched === previousButtonState.touched) { return false; }
  52521. evtName = buttonState.touched ? EVENTS.TOUCHSTART : EVENTS.TOUCHEND;
  52522. this.el.emit(evtName, this.buttonEventDetails[id], false, EMPTY_DAYDREAM_TOUCHES);
  52523. previousButtonState.touched = buttonState.touched;
  52524. return true;
  52525. },
  52526. /**
  52527. * Determine whether a button value has changed.
  52528. *
  52529. * @param {string} id - Id of the button to check.
  52530. * @param {object} buttonState - State of the button to check.
  52531. * @returns {boolean} Whether button value changed.
  52532. */
  52533. handleValue: function (id, buttonState) {
  52534. var previousButtonState = this.buttonStates[id];
  52535. // Not changed.
  52536. if (buttonState.value === previousButtonState.value) { return false; }
  52537. previousButtonState.value = buttonState.value;
  52538. return true;
  52539. }
  52540. });
  52541. },{"../constants":123,"../core/component":131,"../lib/three":179,"../utils/tracked-controls":214}],115:[function(_dereq_,module,exports){
  52542. var controllerUtils = _dereq_('../utils/tracked-controls');
  52543. var registerComponent = _dereq_('../core/component').registerComponent;
  52544. var EVENTS = {
  52545. AXISMOVE: 'axismove',
  52546. BUTTONCHANGED: 'buttonchanged',
  52547. BUTTONDOWN: 'buttondown',
  52548. BUTTONUP: 'buttonup',
  52549. TOUCHSTART: 'touchstart',
  52550. TOUCHEND: 'touchend'
  52551. };
  52552. module.exports.Component = registerComponent('tracked-controls-webxr', {
  52553. schema: {
  52554. id: {type: 'string', default: ''},
  52555. hand: {type: 'string', default: ''},
  52556. handTrackingEnabled: {default: false},
  52557. index: {type: 'int', default: -1},
  52558. iterateControllerProfiles: {default: false}
  52559. },
  52560. init: function () {
  52561. this.updateController = this.updateController.bind(this);
  52562. this.buttonEventDetails = {};
  52563. this.buttonStates = this.el.components['tracked-controls'].buttonStates = {};
  52564. this.axis = this.el.components['tracked-controls'].axis = [0, 0, 0];
  52565. this.changedAxes = [];
  52566. this.axisMoveEventDetail = {axis: this.axis, changed: this.changedAxes};
  52567. },
  52568. update: function () {
  52569. this.updateController();
  52570. },
  52571. play: function () {
  52572. var sceneEl = this.el.sceneEl;
  52573. this.updateController();
  52574. sceneEl.addEventListener('controllersupdated', this.updateController);
  52575. },
  52576. pause: function () {
  52577. var sceneEl = this.el.sceneEl;
  52578. sceneEl.removeEventListener('controllersupdated', this.updateController);
  52579. },
  52580. isControllerPresent: function (evt) {
  52581. if (!this.controller || this.controller.gamepad) { return false; }
  52582. if (evt.inputSource.handedness !== 'none' &&
  52583. evt.inputSource.handedness !== this.data.hand) {
  52584. return false;
  52585. }
  52586. return true;
  52587. },
  52588. /**
  52589. * Handle update controller match criteria (such as `id`, `idPrefix`, `hand`, `controller`)
  52590. */
  52591. updateController: function () {
  52592. this.controller = controllerUtils.findMatchingControllerWebXR(
  52593. this.system.controllers,
  52594. this.data.id,
  52595. this.data.hand,
  52596. this.data.index,
  52597. this.data.iterateControllerProfiles,
  52598. this.data.handTrackingEnabled
  52599. );
  52600. // Legacy handle to the controller for old components.
  52601. this.el.components['tracked-controls'].controller = this.controller;
  52602. if (this.data.autoHide) { this.el.object3D.visible = !!this.controller; }
  52603. },
  52604. tick: function () {
  52605. var sceneEl = this.el.sceneEl;
  52606. var controller = this.controller;
  52607. var frame = sceneEl.frame;
  52608. if (!controller || !sceneEl.frame || !this.system.referenceSpace) { return; }
  52609. if (!controller.hand) {
  52610. this.pose = frame.getPose(controller.targetRaySpace, this.system.referenceSpace);
  52611. this.updatePose();
  52612. this.updateButtons();
  52613. }
  52614. },
  52615. updatePose: function () {
  52616. var object3D = this.el.object3D;
  52617. var pose = this.pose;
  52618. if (!pose) { return; }
  52619. object3D.matrix.elements = pose.transform.matrix;
  52620. object3D.matrix.decompose(object3D.position, object3D.rotation, object3D.scale);
  52621. },
  52622. /**
  52623. * Handle button changes including axes, presses, touches, values.
  52624. */
  52625. updateButtons: function () {
  52626. var buttonState;
  52627. var id;
  52628. var controller = this.controller;
  52629. var gamepad;
  52630. if (!controller || !controller.gamepad) { return; }
  52631. gamepad = controller.gamepad;
  52632. // Check every button.
  52633. for (id = 0; id < gamepad.buttons.length; ++id) {
  52634. // Initialize button state.
  52635. if (!this.buttonStates[id]) {
  52636. this.buttonStates[id] = {pressed: false, touched: false, value: 0};
  52637. }
  52638. if (!this.buttonEventDetails[id]) {
  52639. this.buttonEventDetails[id] = {id: id, state: this.buttonStates[id]};
  52640. }
  52641. buttonState = gamepad.buttons[id];
  52642. this.handleButton(id, buttonState);
  52643. }
  52644. // Check axes.
  52645. this.handleAxes();
  52646. },
  52647. /**
  52648. * Handle presses and touches for a single button.
  52649. *
  52650. * @param {number} id - Index of button in Gamepad button array.
  52651. * @param {number} buttonState - Value of button state from 0 to 1.
  52652. * @returns {boolean} Whether button has changed in any way.
  52653. */
  52654. handleButton: function (id, buttonState) {
  52655. var changed;
  52656. changed = this.handlePress(id, buttonState) |
  52657. this.handleTouch(id, buttonState) |
  52658. this.handleValue(id, buttonState);
  52659. if (!changed) { return false; }
  52660. this.el.emit(EVENTS.BUTTONCHANGED, this.buttonEventDetails[id], false);
  52661. return true;
  52662. },
  52663. /**
  52664. * An axis is an array of values from -1 (up, left) to 1 (down, right).
  52665. * Compare each component of the axis to the previous value to determine change.
  52666. *
  52667. * @returns {boolean} Whether axes changed.
  52668. */
  52669. handleAxes: function () {
  52670. var changed = false;
  52671. var controllerAxes = this.controller.gamepad.axes;
  52672. var i;
  52673. var previousAxis = this.axis;
  52674. var changedAxes = this.changedAxes;
  52675. // Check if axis changed.
  52676. this.changedAxes.splice(0, this.changedAxes.length);
  52677. for (i = 0; i < controllerAxes.length; ++i) {
  52678. changedAxes.push(previousAxis[i] !== controllerAxes[i]);
  52679. if (changedAxes[i]) { changed = true; }
  52680. }
  52681. if (!changed) { return false; }
  52682. this.axis.splice(0, this.axis.length);
  52683. for (i = 0; i < controllerAxes.length; i++) {
  52684. this.axis.push(controllerAxes[i]);
  52685. }
  52686. this.el.emit(EVENTS.AXISMOVE, this.axisMoveEventDetail, false);
  52687. return true;
  52688. },
  52689. /**
  52690. * Determine whether a button press has occured and emit events as appropriate.
  52691. *
  52692. * @param {string} id - ID of the button to check.
  52693. * @param {object} buttonState - State of the button to check.
  52694. * @returns {boolean} Whether button press state changed.
  52695. */
  52696. handlePress: function (id, buttonState) {
  52697. var evtName;
  52698. var previousButtonState = this.buttonStates[id];
  52699. // Not changed.
  52700. if (buttonState.pressed === previousButtonState.pressed) { return false; }
  52701. evtName = buttonState.pressed ? EVENTS.BUTTONDOWN : EVENTS.BUTTONUP;
  52702. this.el.emit(evtName, this.buttonEventDetails[id], false);
  52703. previousButtonState.pressed = buttonState.pressed;
  52704. return true;
  52705. },
  52706. /**
  52707. * Determine whether a button touch has occured and emit events as appropriate.
  52708. *
  52709. * @param {string} id - ID of the button to check.
  52710. * @param {object} buttonState - State of the button to check.
  52711. * @returns {boolean} Whether button touch state changed.
  52712. */
  52713. handleTouch: function (id, buttonState) {
  52714. var evtName;
  52715. var previousButtonState = this.buttonStates[id];
  52716. // Not changed.
  52717. if (buttonState.touched === previousButtonState.touched) { return false; }
  52718. evtName = buttonState.touched ? EVENTS.TOUCHSTART : EVENTS.TOUCHEND;
  52719. this.el.emit(evtName, this.buttonEventDetails[id], false);
  52720. previousButtonState.touched = buttonState.touched;
  52721. return true;
  52722. },
  52723. /**
  52724. * Determine whether a button value has changed.
  52725. *
  52726. * @param {string} id - Id of the button to check.
  52727. * @param {object} buttonState - State of the button to check.
  52728. * @returns {boolean} Whether button value changed.
  52729. */
  52730. handleValue: function (id, buttonState) {
  52731. var previousButtonState = this.buttonStates[id];
  52732. // Not changed.
  52733. if (buttonState.value === previousButtonState.value) { return false; }
  52734. previousButtonState.value = buttonState.value;
  52735. return true;
  52736. }
  52737. });
  52738. },{"../core/component":131,"../utils/tracked-controls":214}],116:[function(_dereq_,module,exports){
  52739. var registerComponent = _dereq_('../core/component').registerComponent;
  52740. /**
  52741. * Tracked controls.
  52742. * Abstract controls that decide if the WebVR or WebXR version is going to be applied.
  52743. *
  52744. * @property {number} controller - Index of controller in array returned by Gamepad API.
  52745. * Only used if hand property is not set.
  52746. * @property {string} id - Selected controller among those returned by Gamepad API.
  52747. * @property {number} hand - If multiple controllers found with id, choose the one with the
  52748. * given value for hand. If set, we ignore 'controller' property
  52749. */
  52750. module.exports.Component = registerComponent('tracked-controls', {
  52751. schema: {
  52752. autoHide: {default: true},
  52753. controller: {default: -1},
  52754. id: {type: 'string', default: ''},
  52755. hand: {type: 'string', default: ''},
  52756. idPrefix: {type: 'string', default: ''},
  52757. handTrackingEnabled: {default: false},
  52758. orientationOffset: {type: 'vec3'},
  52759. // Arm model parameters when not 6DoF.
  52760. armModel: {default: false},
  52761. headElement: {type: 'selector'},
  52762. iterateControllerProfiles: {default: false}
  52763. },
  52764. update: function () {
  52765. var data = this.data;
  52766. var el = this.el;
  52767. if (el.sceneEl.hasWebXR) {
  52768. el.setAttribute('tracked-controls-webxr', {
  52769. id: data.id,
  52770. hand: data.hand,
  52771. index: data.controller,
  52772. iterateControllerProfiles: data.iterateControllerProfiles,
  52773. handTrackingEnabled: data.handTrackingEnabled
  52774. });
  52775. } else {
  52776. el.setAttribute('tracked-controls-webvr', data);
  52777. }
  52778. }
  52779. });
  52780. },{"../core/component":131}],117:[function(_dereq_,module,exports){
  52781. var registerComponent = _dereq_('../core/component').registerComponent;
  52782. var bind = _dereq_('../utils/bind');
  52783. var THREE = _dereq_('../lib/three');
  52784. var trackedControlsUtils = _dereq_('../utils/tracked-controls');
  52785. var checkControllerPresentAndSetup = trackedControlsUtils.checkControllerPresentAndSetup;
  52786. var emitIfAxesChanged = trackedControlsUtils.emitIfAxesChanged;
  52787. var onButtonEvent = trackedControlsUtils.onButtonEvent;
  52788. var INDEX_CONTROLLER_MODEL_BASE_URL = 'https://cdn.aframe.io/controllers/valve/index/valve-index-';
  52789. var INDEX_CONTROLLER_MODEL_URL = {
  52790. left: INDEX_CONTROLLER_MODEL_BASE_URL + 'left.glb',
  52791. right: INDEX_CONTROLLER_MODEL_BASE_URL + 'right.glb'
  52792. };
  52793. var GAMEPAD_ID_PREFIX = 'valve';
  52794. var isWebXRAvailable = _dereq_('../utils/').device.isWebXRAvailable;
  52795. var INDEX_CONTROLLER_POSITION_OFFSET_WEBVR = {
  52796. left: {x: -0.00023692678902063457, y: 0.04724540367838371, z: -0.061959880395271096},
  52797. right: {x: 0.002471558599671131, y: 0.055765208987076195, z: -0.061068168708348844}
  52798. };
  52799. var INDEX_CONTROLLER_POSITION_OFFSET_WEBXR = {
  52800. left: {x: 0, y: -0.05, z: 0.06},
  52801. right: {x: 0, y: -0.05, z: 0.06}
  52802. };
  52803. var INDEX_CONTROLLER_ROTATION_OFFSET_WEBVR = {
  52804. left: {_x: 0.692295102620542, _y: -0.0627618864318427, _z: -0.06265893149611756, _order: 'XYZ'},
  52805. right: {_x: 0.6484021229942998, _y: -0.032563619881892894, _z: -0.1327973171917482, _order: 'XYZ'}
  52806. };
  52807. var INDEX_CONTROLLER_ROTATION_OFFSET_WEBXR = {
  52808. left: {_x: Math.PI / 3, _y: 0, _z: 0, _order: 'XYZ'},
  52809. right: {_x: Math.PI / 3, _y: 0, _z: 0, _order: 'XYZ'}
  52810. };
  52811. var INDEX_CONTROLLER_ROTATION_OFFSET = isWebXRAvailable ? INDEX_CONTROLLER_ROTATION_OFFSET_WEBXR : INDEX_CONTROLLER_ROTATION_OFFSET_WEBVR;
  52812. var INDEX_CONTROLLER_POSITION_OFFSET = isWebXRAvailable ? INDEX_CONTROLLER_POSITION_OFFSET_WEBXR : INDEX_CONTROLLER_POSITION_OFFSET_WEBVR;
  52813. /**
  52814. * Vive controls.
  52815. * Interface with Vive controllers and map Gamepad events to controller buttons:
  52816. * trackpad, trigger, grip, menu, system
  52817. * Load a controller model and highlight the pressed buttons.
  52818. */
  52819. module.exports.Component = registerComponent('valve-index-controls', {
  52820. schema: {
  52821. hand: {default: 'left'},
  52822. buttonColor: {type: 'color', default: '#FAFAFA'}, // Off-white.
  52823. buttonHighlightColor: {type: 'color', default: '#22D1EE'}, // Light blue.
  52824. model: {default: true},
  52825. orientationOffset: {type: 'vec3'}
  52826. },
  52827. mapping: {
  52828. axes: {
  52829. trackpad: [0, 1],
  52830. thumbstick: [2, 3]
  52831. },
  52832. buttons: ['trigger', 'grip', 'trackpad', 'thumbstick', 'abutton']
  52833. },
  52834. init: function () {
  52835. var self = this;
  52836. this.controllerPresent = false;
  52837. this.lastControllerCheck = 0;
  52838. this.onButtonChanged = bind(this.onButtonChanged, this);
  52839. this.onButtonDown = function (evt) { onButtonEvent(evt.detail.id, 'down', self); };
  52840. this.onButtonUp = function (evt) { onButtonEvent(evt.detail.id, 'up', self); };
  52841. this.onButtonTouchEnd = function (evt) { onButtonEvent(evt.detail.id, 'touchend', self); };
  52842. this.onButtonTouchStart = function (evt) { onButtonEvent(evt.detail.id, 'touchstart', self); };
  52843. this.previousButtonValues = {};
  52844. this.rendererSystem = this.el.sceneEl.systems.renderer;
  52845. this.bindMethods();
  52846. },
  52847. play: function () {
  52848. this.checkIfControllerPresent();
  52849. this.addControllersUpdateListener();
  52850. },
  52851. pause: function () {
  52852. this.removeEventListeners();
  52853. this.removeControllersUpdateListener();
  52854. },
  52855. bindMethods: function () {
  52856. this.onModelLoaded = bind(this.onModelLoaded, this);
  52857. this.onControllersUpdate = bind(this.onControllersUpdate, this);
  52858. this.checkIfControllerPresent = bind(this.checkIfControllerPresent, this);
  52859. this.removeControllersUpdateListener = bind(this.removeControllersUpdateListener, this);
  52860. this.onAxisMoved = bind(this.onAxisMoved, this);
  52861. },
  52862. addEventListeners: function () {
  52863. var el = this.el;
  52864. el.addEventListener('buttonchanged', this.onButtonChanged);
  52865. el.addEventListener('buttondown', this.onButtonDown);
  52866. el.addEventListener('buttonup', this.onButtonUp);
  52867. el.addEventListener('touchend', this.onButtonTouchEnd);
  52868. el.addEventListener('touchstart', this.onButtonTouchStart);
  52869. el.addEventListener('model-loaded', this.onModelLoaded);
  52870. el.addEventListener('axismove', this.onAxisMoved);
  52871. this.controllerEventsActive = true;
  52872. },
  52873. removeEventListeners: function () {
  52874. var el = this.el;
  52875. el.removeEventListener('buttonchanged', this.onButtonChanged);
  52876. el.removeEventListener('buttondown', this.onButtonDown);
  52877. el.removeEventListener('buttonup', this.onButtonUp);
  52878. el.removeEventListener('touchend', this.onButtonTouchEnd);
  52879. el.removeEventListener('touchstart', this.onButtonTouchStart);
  52880. el.removeEventListener('model-loaded', this.onModelLoaded);
  52881. el.removeEventListener('axismove', this.onAxisMoved);
  52882. this.controllerEventsActive = false;
  52883. },
  52884. /**
  52885. * Once OpenVR returns correct hand data in supporting browsers, we can use hand property.
  52886. * var isPresent = checkControllerPresentAndSetup(this.el.sceneEl, GAMEPAD_ID_PREFIX,
  52887. { hand: data.hand });
  52888. * Until then, use hardcoded index.
  52889. */
  52890. checkIfControllerPresent: function () {
  52891. var data = this.data;
  52892. var controllerIndex = data.hand === 'right' ? 0 : data.hand === 'left' ? 1 : 2;
  52893. checkControllerPresentAndSetup(this, GAMEPAD_ID_PREFIX, {index: controllerIndex, iterateControllerProfiles: true, hand: data.hand});
  52894. },
  52895. injectTrackedControls: function () {
  52896. var el = this.el;
  52897. var data = this.data;
  52898. // If we have an OpenVR Gamepad, use the fixed mapping.
  52899. el.setAttribute('tracked-controls', {
  52900. idPrefix: GAMEPAD_ID_PREFIX,
  52901. // Hand IDs: 1 = right, 0 = left, 2 = anything else.
  52902. controller: data.hand === 'right' ? 1 : data.hand === 'left' ? 0 : 2,
  52903. hand: data.hand,
  52904. orientationOffset: data.orientationOffset
  52905. });
  52906. this.loadModel();
  52907. },
  52908. loadModel: function () {
  52909. var data = this.data;
  52910. if (!data.model) { return; }
  52911. this.el.setAttribute('gltf-model', '' + INDEX_CONTROLLER_MODEL_URL[data.hand] + '');
  52912. },
  52913. addControllersUpdateListener: function () {
  52914. this.el.sceneEl.addEventListener('controllersupdated', this.onControllersUpdate, false);
  52915. },
  52916. removeControllersUpdateListener: function () {
  52917. this.el.sceneEl.removeEventListener('controllersupdated', this.onControllersUpdate, false);
  52918. },
  52919. onControllersUpdate: function () {
  52920. this.checkIfControllerPresent();
  52921. },
  52922. /**
  52923. * Rotate the trigger button based on how hard the trigger is pressed.
  52924. */
  52925. onButtonChanged: function (evt) {
  52926. var button = this.mapping.buttons[evt.detail.id];
  52927. var buttonMeshes = this.buttonMeshes;
  52928. var analogValue;
  52929. if (!button) { return; }
  52930. if (button === 'trigger') {
  52931. analogValue = evt.detail.state.value;
  52932. // Update trigger rotation depending on button value.
  52933. if (buttonMeshes && buttonMeshes.trigger) {
  52934. buttonMeshes.trigger.rotation.x = this.triggerOriginalRotationX - analogValue * (Math.PI / 40);
  52935. }
  52936. }
  52937. // Pass along changed event with button state, using button mapping for convenience.
  52938. this.el.emit(button + 'changed', evt.detail.state);
  52939. },
  52940. onModelLoaded: function (evt) {
  52941. var buttonMeshes;
  52942. var controllerObject3D = evt.detail.model;
  52943. var self = this;
  52944. if (!this.data.model) { return; }
  52945. // Store button meshes object to be able to change their colors.
  52946. buttonMeshes = this.buttonMeshes = {};
  52947. buttonMeshes.grip = {
  52948. left: controllerObject3D.getObjectByName('leftgrip'),
  52949. right: controllerObject3D.getObjectByName('rightgrip')
  52950. };
  52951. buttonMeshes.menu = controllerObject3D.getObjectByName('menubutton');
  52952. buttonMeshes.system = controllerObject3D.getObjectByName('systembutton');
  52953. buttonMeshes.trackpad = controllerObject3D.getObjectByName('touchpad');
  52954. buttonMeshes.trigger = controllerObject3D.getObjectByName('trigger');
  52955. this.triggerOriginalRotationX = buttonMeshes.trigger.rotation.x;
  52956. // Set default colors.
  52957. Object.keys(buttonMeshes).forEach(function (buttonName) {
  52958. self.setButtonColor(buttonName, self.data.buttonColor);
  52959. });
  52960. // Offset pivot point.
  52961. controllerObject3D.position.copy(INDEX_CONTROLLER_POSITION_OFFSET[this.data.hand]);
  52962. controllerObject3D.rotation.copy(INDEX_CONTROLLER_ROTATION_OFFSET[this.data.hand]);
  52963. this.el.emit('controllermodelready', {
  52964. name: 'valve-index-controlls',
  52965. model: this.data.model,
  52966. rayOrigin: new THREE.Vector3(0, 0, 0)
  52967. });
  52968. },
  52969. onAxisMoved: function (evt) {
  52970. emitIfAxesChanged(this, this.mapping.axes, evt);
  52971. },
  52972. updateModel: function (buttonName, evtName) {
  52973. var color;
  52974. var isTouch;
  52975. if (!this.data.model) { return; }
  52976. isTouch = evtName.indexOf('touch') !== -1;
  52977. // Don't change color for trackpad touch.
  52978. if (isTouch) { return; }
  52979. // Update colors.
  52980. color = evtName === 'up' ? this.data.buttonColor : this.data.buttonHighlightColor;
  52981. this.setButtonColor(buttonName, color);
  52982. },
  52983. setButtonColor: function (buttonName, color) {
  52984. // TODO: The meshes aren't set up correctly now, skipping for the moment
  52985. return;
  52986. }
  52987. });
  52988. },{"../core/component":131,"../lib/three":179,"../utils/":205,"../utils/bind":199,"../utils/tracked-controls":214}],118:[function(_dereq_,module,exports){
  52989. var registerComponent = _dereq_('../core/component').registerComponent;
  52990. /**
  52991. * Visibility component.
  52992. */
  52993. module.exports.Component = registerComponent('visible', {
  52994. schema: {default: true},
  52995. update: function () {
  52996. this.el.object3D.visible = this.data;
  52997. }
  52998. });
  52999. },{"../core/component":131}],119:[function(_dereq_,module,exports){
  53000. var registerComponent = _dereq_('../core/component').registerComponent;
  53001. var bind = _dereq_('../utils/bind');
  53002. var trackedControlsUtils = _dereq_('../utils/tracked-controls');
  53003. var checkControllerPresentAndSetup = trackedControlsUtils.checkControllerPresentAndSetup;
  53004. var emitIfAxesChanged = trackedControlsUtils.emitIfAxesChanged;
  53005. var onButtonEvent = trackedControlsUtils.onButtonEvent;
  53006. var VIVE_CONTROLLER_MODEL_OBJ_URL = 'https://cdn.aframe.io/controllers/vive/vr_controller_vive.obj';
  53007. var VIVE_CONTROLLER_MODEL_OBJ_MTL = 'https://cdn.aframe.io/controllers/vive/vr_controller_vive.mtl';
  53008. var isWebXRAvailable = _dereq_('../utils/').device.isWebXRAvailable;
  53009. var GAMEPAD_ID_WEBXR = 'htc-vive-controller-mv';
  53010. var GAMEPAD_ID_WEBVR = 'OpenVR ';
  53011. // Prefix for Gen1 and Gen2 Oculus Touch Controllers.
  53012. var GAMEPAD_ID_PREFIX = isWebXRAvailable ? GAMEPAD_ID_WEBXR : GAMEPAD_ID_WEBVR;
  53013. /**
  53014. * Button IDs:
  53015. * 0 - trackpad
  53016. * 1 - trigger (intensity value from 0.5 to 1)
  53017. * 2 - grip
  53018. * 3 - menu (dispatch but better for menu options)
  53019. * 4 - system (never dispatched on this layer)
  53020. */
  53021. var INPUT_MAPPING_WEBVR = {
  53022. axes: {trackpad: [0, 1]},
  53023. buttons: ['trackpad', 'trigger', 'grip', 'menu', 'system']
  53024. };
  53025. /**
  53026. * Button IDs:
  53027. * 0 - trigger
  53028. * 1 - squeeze
  53029. * 2 - touchpad
  53030. * 3 - none (dispatch but better for menu options)
  53031. * 4 - menu (never dispatched on this layer)
  53032. *
  53033. * Axis:
  53034. * 0 - touchpad x axis
  53035. * 1 - touchpad y axis
  53036. * Reference: https://github.com/immersive-web/webxr-input-profiles/blob/master/packages/registry/profiles/htc/htc-vive.json
  53037. */
  53038. var INPUT_MAPPING_WEBXR = {
  53039. axes: {thumbstick: [0, 1]},
  53040. buttons: ['trigger', 'grip', 'trackpad', 'none', 'menu']
  53041. };
  53042. var INPUT_MAPPING = isWebXRAvailable ? INPUT_MAPPING_WEBXR : INPUT_MAPPING_WEBVR;
  53043. /**
  53044. * Vive controls.
  53045. * Interface with Vive controllers and map Gamepad events to controller buttons:
  53046. * trackpad, trigger, grip, menu, system
  53047. * Load a controller model and highlight the pressed buttons.
  53048. */
  53049. module.exports.Component = registerComponent('vive-controls', {
  53050. schema: {
  53051. hand: {default: 'left'},
  53052. buttonColor: {type: 'color', default: '#FAFAFA'}, // Off-white.
  53053. buttonHighlightColor: {type: 'color', default: '#22D1EE'}, // Light blue.
  53054. model: {default: true},
  53055. orientationOffset: {type: 'vec3'}
  53056. },
  53057. mapping: INPUT_MAPPING,
  53058. init: function () {
  53059. var self = this;
  53060. this.controllerPresent = false;
  53061. this.lastControllerCheck = 0;
  53062. this.onButtonChanged = bind(this.onButtonChanged, this);
  53063. this.onButtonDown = function (evt) { onButtonEvent(evt.detail.id, 'down', self); };
  53064. this.onButtonUp = function (evt) { onButtonEvent(evt.detail.id, 'up', self); };
  53065. this.onButtonTouchEnd = function (evt) { onButtonEvent(evt.detail.id, 'touchend', self); };
  53066. this.onButtonTouchStart = function (evt) { onButtonEvent(evt.detail.id, 'touchstart', self); };
  53067. this.previousButtonValues = {};
  53068. this.rendererSystem = this.el.sceneEl.systems.renderer;
  53069. this.bindMethods();
  53070. },
  53071. update: function () {
  53072. var data = this.data;
  53073. this.controllerIndex = data.hand === 'right' ? 0 : data.hand === 'left' ? 1 : 2;
  53074. },
  53075. play: function () {
  53076. this.checkIfControllerPresent();
  53077. this.addControllersUpdateListener();
  53078. },
  53079. pause: function () {
  53080. this.removeEventListeners();
  53081. this.removeControllersUpdateListener();
  53082. },
  53083. bindMethods: function () {
  53084. this.onModelLoaded = bind(this.onModelLoaded, this);
  53085. this.onControllersUpdate = bind(this.onControllersUpdate, this);
  53086. this.checkIfControllerPresent = bind(this.checkIfControllerPresent, this);
  53087. this.removeControllersUpdateListener = bind(this.removeControllersUpdateListener, this);
  53088. this.onAxisMoved = bind(this.onAxisMoved, this);
  53089. },
  53090. addEventListeners: function () {
  53091. var el = this.el;
  53092. el.addEventListener('buttonchanged', this.onButtonChanged);
  53093. el.addEventListener('buttondown', this.onButtonDown);
  53094. el.addEventListener('buttonup', this.onButtonUp);
  53095. el.addEventListener('touchend', this.onButtonTouchEnd);
  53096. el.addEventListener('touchstart', this.onButtonTouchStart);
  53097. el.addEventListener('model-loaded', this.onModelLoaded);
  53098. el.addEventListener('axismove', this.onAxisMoved);
  53099. this.controllerEventsActive = true;
  53100. },
  53101. removeEventListeners: function () {
  53102. var el = this.el;
  53103. el.removeEventListener('buttonchanged', this.onButtonChanged);
  53104. el.removeEventListener('buttondown', this.onButtonDown);
  53105. el.removeEventListener('buttonup', this.onButtonUp);
  53106. el.removeEventListener('touchend', this.onButtonTouchEnd);
  53107. el.removeEventListener('touchstart', this.onButtonTouchStart);
  53108. el.removeEventListener('model-loaded', this.onModelLoaded);
  53109. el.removeEventListener('axismove', this.onAxisMoved);
  53110. this.controllerEventsActive = false;
  53111. },
  53112. /**
  53113. * Once OpenVR returns correct hand data in supporting browsers, we can use hand property.
  53114. * var isPresent = checkControllerPresentAndSetup(this.el.sceneEl, GAMEPAD_ID_PREFIX,
  53115. { hand: data.hand });
  53116. * Until then, use hardcoded index.
  53117. */
  53118. checkIfControllerPresent: function () {
  53119. var data = this.data;
  53120. checkControllerPresentAndSetup(this, GAMEPAD_ID_PREFIX, {index: this.controllerIndex, hand: data.hand});
  53121. },
  53122. injectTrackedControls: function () {
  53123. var el = this.el;
  53124. var data = this.data;
  53125. // If we have an OpenVR Gamepad, use the fixed mapping.
  53126. el.setAttribute('tracked-controls', {
  53127. idPrefix: GAMEPAD_ID_PREFIX,
  53128. hand: data.hand,
  53129. controller: this.controllerIndex,
  53130. orientationOffset: data.orientationOffset
  53131. });
  53132. // Load model.
  53133. if (!this.data.model) { return; }
  53134. this.el.setAttribute('obj-model', {
  53135. obj: VIVE_CONTROLLER_MODEL_OBJ_URL,
  53136. mtl: VIVE_CONTROLLER_MODEL_OBJ_MTL
  53137. });
  53138. },
  53139. addControllersUpdateListener: function () {
  53140. this.el.sceneEl.addEventListener('controllersupdated', this.onControllersUpdate, false);
  53141. },
  53142. removeControllersUpdateListener: function () {
  53143. this.el.sceneEl.removeEventListener('controllersupdated', this.onControllersUpdate, false);
  53144. },
  53145. onControllersUpdate: function () {
  53146. this.checkIfControllerPresent();
  53147. },
  53148. /**
  53149. * Rotate the trigger button based on how hard the trigger is pressed.
  53150. */
  53151. onButtonChanged: function (evt) {
  53152. var button = this.mapping.buttons[evt.detail.id];
  53153. var buttonMeshes = this.buttonMeshes;
  53154. var analogValue;
  53155. if (!button) { return; }
  53156. if (button === 'trigger') {
  53157. analogValue = evt.detail.state.value;
  53158. // Update trigger rotation depending on button value.
  53159. if (buttonMeshes && buttonMeshes.trigger) {
  53160. buttonMeshes.trigger.rotation.x = -analogValue * (Math.PI / 12);
  53161. }
  53162. }
  53163. // Pass along changed event with button state, using button mapping for convenience.
  53164. this.el.emit(button + 'changed', evt.detail.state);
  53165. },
  53166. onModelLoaded: function (evt) {
  53167. var buttonMeshes;
  53168. var controllerObject3D = evt.detail.model;
  53169. var self = this;
  53170. if (!this.data.model) { return; }
  53171. // Store button meshes object to be able to change their colors.
  53172. buttonMeshes = this.buttonMeshes = {};
  53173. buttonMeshes.grip = {
  53174. left: controllerObject3D.getObjectByName('leftgrip'),
  53175. right: controllerObject3D.getObjectByName('rightgrip')
  53176. };
  53177. buttonMeshes.menu = controllerObject3D.getObjectByName('menubutton');
  53178. buttonMeshes.system = controllerObject3D.getObjectByName('systembutton');
  53179. buttonMeshes.trackpad = controllerObject3D.getObjectByName('touchpad');
  53180. buttonMeshes.trigger = controllerObject3D.getObjectByName('trigger');
  53181. // Set default colors.
  53182. Object.keys(buttonMeshes).forEach(function (buttonName) {
  53183. self.setButtonColor(buttonName, self.data.buttonColor);
  53184. });
  53185. // Offset pivot point.
  53186. controllerObject3D.position.set(0, -0.015, 0.04);
  53187. },
  53188. onAxisMoved: function (evt) {
  53189. emitIfAxesChanged(this, this.mapping.axes, evt);
  53190. },
  53191. updateModel: function (buttonName, evtName) {
  53192. var color;
  53193. var isTouch;
  53194. if (!this.data.model) { return; }
  53195. isTouch = evtName.indexOf('touch') !== -1;
  53196. // Don't change color for trackpad touch.
  53197. if (isTouch) { return; }
  53198. // Update colors.
  53199. color = evtName === 'up' ? this.data.buttonColor : this.data.buttonHighlightColor;
  53200. this.setButtonColor(buttonName, color);
  53201. },
  53202. setButtonColor: function (buttonName, color) {
  53203. var buttonMeshes = this.buttonMeshes;
  53204. var rendererSystem = this.rendererSystem;
  53205. if (!buttonMeshes) { return; }
  53206. // Need to do both left and right sides for grip.
  53207. if (buttonName === 'grip') {
  53208. buttonMeshes.grip.left.material.color.set(color);
  53209. buttonMeshes.grip.right.material.color.set(color);
  53210. rendererSystem.applyColorCorrection(buttonMeshes.grip.left.material.color);
  53211. rendererSystem.applyColorCorrection(buttonMeshes.grip.right.material.color);
  53212. return;
  53213. }
  53214. buttonMeshes[buttonName].material.color.set(color);
  53215. rendererSystem.applyColorCorrection(buttonMeshes[buttonName].material.color);
  53216. }
  53217. });
  53218. },{"../core/component":131,"../utils/":205,"../utils/bind":199,"../utils/tracked-controls":214}],120:[function(_dereq_,module,exports){
  53219. var registerComponent = _dereq_('../core/component').registerComponent;
  53220. var bind = _dereq_('../utils/bind');
  53221. var trackedControlsUtils = _dereq_('../utils/tracked-controls');
  53222. var checkControllerPresentAndSetup = trackedControlsUtils.checkControllerPresentAndSetup;
  53223. var emitIfAxesChanged = trackedControlsUtils.emitIfAxesChanged;
  53224. var onButtonEvent = trackedControlsUtils.onButtonEvent;
  53225. var GAMEPAD_ID_PREFIX = 'HTC Vive Focus';
  53226. var VIVE_FOCUS_CONTROLLER_MODEL_URL = 'https://cdn.aframe.io/controllers/vive/focus-controller/focus-controller.gltf';
  53227. /**
  53228. * Vive Focus controls.
  53229. * Interface with Vive Focus controller and map Gamepad events to
  53230. * controller buttons: trackpad, trigger
  53231. * Load a controller model and highlight the pressed buttons.
  53232. */
  53233. module.exports.Component = registerComponent('vive-focus-controls', {
  53234. schema: {
  53235. hand: {default: ''}, // This informs the degenerate arm model.
  53236. buttonTouchedColor: {type: 'color', default: '#BBBBBB'},
  53237. buttonHighlightColor: {type: 'color', default: '#7A7A7A'},
  53238. model: {default: true},
  53239. orientationOffset: {type: 'vec3'},
  53240. armModel: {default: true}
  53241. },
  53242. /**
  53243. * Button IDs:
  53244. * 0 - trackpad
  53245. * 1 - trigger
  53246. */
  53247. mapping: {
  53248. axes: {trackpad: [0, 1]},
  53249. buttons: ['trackpad', 'trigger']
  53250. },
  53251. bindMethods: function () {
  53252. this.onModelLoaded = bind(this.onModelLoaded, this);
  53253. this.onControllersUpdate = bind(this.onControllersUpdate, this);
  53254. this.checkIfControllerPresent = bind(this.checkIfControllerPresent, this);
  53255. this.removeControllersUpdateListener = bind(this.removeControllersUpdateListener, this);
  53256. this.onAxisMoved = bind(this.onAxisMoved, this);
  53257. },
  53258. init: function () {
  53259. var self = this;
  53260. this.onButtonChanged = bind(this.onButtonChanged, this);
  53261. this.onButtonDown = function (evt) { onButtonEvent(evt.detail.id, 'down', self); };
  53262. this.onButtonUp = function (evt) { onButtonEvent(evt.detail.id, 'up', self); };
  53263. this.onButtonTouchStart = function (evt) { onButtonEvent(evt.detail.id, 'touchstart', self); };
  53264. this.onButtonTouchEnd = function (evt) { onButtonEvent(evt.detail.id, 'touchend', self); };
  53265. this.controllerPresent = false;
  53266. this.lastControllerCheck = 0;
  53267. this.bindMethods();
  53268. },
  53269. addEventListeners: function () {
  53270. var el = this.el;
  53271. el.addEventListener('buttonchanged', this.onButtonChanged);
  53272. el.addEventListener('buttondown', this.onButtonDown);
  53273. el.addEventListener('buttonup', this.onButtonUp);
  53274. el.addEventListener('touchstart', this.onButtonTouchStart);
  53275. el.addEventListener('touchend', this.onButtonTouchEnd);
  53276. el.addEventListener('model-loaded', this.onModelLoaded);
  53277. el.addEventListener('axismove', this.onAxisMoved);
  53278. this.controllerEventsActive = true;
  53279. this.addControllersUpdateListener();
  53280. },
  53281. removeEventListeners: function () {
  53282. var el = this.el;
  53283. el.removeEventListener('buttonchanged', this.onButtonChanged);
  53284. el.removeEventListener('buttondown', this.onButtonDown);
  53285. el.removeEventListener('buttonup', this.onButtonUp);
  53286. el.removeEventListener('touchstart', this.onButtonTouchStart);
  53287. el.removeEventListener('touchend', this.onButtonTouchEnd);
  53288. el.removeEventListener('model-loaded', this.onModelLoaded);
  53289. el.removeEventListener('axismove', this.onAxisMoved);
  53290. this.controllerEventsActive = false;
  53291. this.removeControllersUpdateListener();
  53292. },
  53293. checkIfControllerPresent: function () {
  53294. checkControllerPresentAndSetup(this, GAMEPAD_ID_PREFIX,
  53295. this.data.hand ? {hand: this.data.hand} : {});
  53296. },
  53297. play: function () {
  53298. this.checkIfControllerPresent();
  53299. this.addControllersUpdateListener();
  53300. },
  53301. pause: function () {
  53302. this.removeEventListeners();
  53303. this.removeControllersUpdateListener();
  53304. },
  53305. injectTrackedControls: function () {
  53306. var el = this.el;
  53307. var data = this.data;
  53308. el.setAttribute('tracked-controls', {
  53309. armModel: data.armModel,
  53310. idPrefix: GAMEPAD_ID_PREFIX,
  53311. orientationOffset: data.orientationOffset
  53312. });
  53313. if (!this.data.model) { return; }
  53314. this.el.setAttribute('gltf-model', VIVE_FOCUS_CONTROLLER_MODEL_URL);
  53315. },
  53316. addControllersUpdateListener: function () {
  53317. this.el.sceneEl.addEventListener('controllersupdated', this.onControllersUpdate, false);
  53318. },
  53319. removeControllersUpdateListener: function () {
  53320. this.el.sceneEl.removeEventListener('controllersupdated', this.onControllersUpdate, false);
  53321. },
  53322. onControllersUpdate: function () {
  53323. this.checkIfControllerPresent();
  53324. },
  53325. onModelLoaded: function (evt) {
  53326. var controllerObject3D = evt.detail.model;
  53327. var buttonMeshes;
  53328. if (!this.data.model) { return; }
  53329. buttonMeshes = this.buttonMeshes = {};
  53330. buttonMeshes.trigger = controllerObject3D.getObjectByName('BumperKey');
  53331. buttonMeshes.triggerPressed = controllerObject3D.getObjectByName('BumperKey_Press');
  53332. if (buttonMeshes.triggerPressed) {
  53333. buttonMeshes.triggerPressed.visible = false;
  53334. }
  53335. buttonMeshes.trackpad = controllerObject3D.getObjectByName('TouchPad');
  53336. buttonMeshes.trackpadPressed = controllerObject3D.getObjectByName('TouchPad_Press');
  53337. if (buttonMeshes.trackpadPressed) {
  53338. buttonMeshes.trackpadPressed.visible = false;
  53339. }
  53340. },
  53341. // No analog buttons, only emits 0/1 values
  53342. onButtonChanged: function (evt) {
  53343. var button = this.mapping.buttons[evt.detail.id];
  53344. if (!button) return;
  53345. // Pass along changed event with button state, using button mapping for convenience.
  53346. this.el.emit(button + 'changed', evt.detail.state);
  53347. },
  53348. onAxisMoved: function (evt) {
  53349. emitIfAxesChanged(this, this.mapping.axes, evt);
  53350. },
  53351. updateModel: function (buttonName, evtName) {
  53352. if (!this.data.model) { return; }
  53353. this.updateButtonModel(buttonName, evtName);
  53354. },
  53355. updateButtonModel: function (buttonName, state) {
  53356. var buttonMeshes = this.buttonMeshes;
  53357. var pressedName = buttonName + 'Pressed';
  53358. if (!buttonMeshes || !buttonMeshes[buttonName] || !buttonMeshes[pressedName]) {
  53359. return;
  53360. }
  53361. var color;
  53362. switch (state) {
  53363. case 'down':
  53364. color = this.data.buttonHighlightColor;
  53365. break;
  53366. case 'touchstart':
  53367. color = this.data.buttonTouchedColor;
  53368. break;
  53369. }
  53370. if (color) {
  53371. buttonMeshes[pressedName].material.color.set(color);
  53372. }
  53373. buttonMeshes[pressedName].visible = !!color;
  53374. buttonMeshes[buttonName].visible = !color;
  53375. }
  53376. });
  53377. },{"../core/component":131,"../utils/bind":199,"../utils/tracked-controls":214}],121:[function(_dereq_,module,exports){
  53378. var KEYCODE_TO_CODE = _dereq_('../constants').keyboardevent.KEYCODE_TO_CODE;
  53379. var registerComponent = _dereq_('../core/component').registerComponent;
  53380. var THREE = _dereq_('../lib/three');
  53381. var utils = _dereq_('../utils/');
  53382. var bind = utils.bind;
  53383. var shouldCaptureKeyEvent = utils.shouldCaptureKeyEvent;
  53384. var CLAMP_VELOCITY = 0.00001;
  53385. var MAX_DELTA = 0.2;
  53386. var KEYS = [
  53387. 'KeyW', 'KeyA', 'KeyS', 'KeyD',
  53388. 'ArrowUp', 'ArrowLeft', 'ArrowRight', 'ArrowDown'
  53389. ];
  53390. /**
  53391. * WASD component to control entities using WASD keys.
  53392. */
  53393. module.exports.Component = registerComponent('wasd-controls', {
  53394. schema: {
  53395. acceleration: {default: 65},
  53396. adAxis: {default: 'x', oneOf: ['x', 'y', 'z']},
  53397. adEnabled: {default: true},
  53398. adInverted: {default: false},
  53399. enabled: {default: true},
  53400. fly: {default: false},
  53401. wsAxis: {default: 'z', oneOf: ['x', 'y', 'z']},
  53402. wsEnabled: {default: true},
  53403. wsInverted: {default: false}
  53404. },
  53405. init: function () {
  53406. // To keep track of the pressed keys.
  53407. this.keys = {};
  53408. this.easing = 1.1;
  53409. this.velocity = new THREE.Vector3();
  53410. // Bind methods and add event listeners.
  53411. this.onBlur = bind(this.onBlur, this);
  53412. this.onContextMenu = bind(this.onContextMenu, this);
  53413. this.onFocus = bind(this.onFocus, this);
  53414. this.onKeyDown = bind(this.onKeyDown, this);
  53415. this.onKeyUp = bind(this.onKeyUp, this);
  53416. this.onVisibilityChange = bind(this.onVisibilityChange, this);
  53417. this.attachVisibilityEventListeners();
  53418. },
  53419. tick: function (time, delta) {
  53420. var data = this.data;
  53421. var el = this.el;
  53422. var velocity = this.velocity;
  53423. if (!velocity[data.adAxis] && !velocity[data.wsAxis] &&
  53424. isEmptyObject(this.keys)) { return; }
  53425. // Update velocity.
  53426. delta = delta / 1000;
  53427. this.updateVelocity(delta);
  53428. if (!velocity[data.adAxis] && !velocity[data.wsAxis]) { return; }
  53429. // Get movement vector and translate position.
  53430. el.object3D.position.add(this.getMovementVector(delta));
  53431. },
  53432. remove: function () {
  53433. this.removeKeyEventListeners();
  53434. this.removeVisibilityEventListeners();
  53435. },
  53436. play: function () {
  53437. this.attachKeyEventListeners();
  53438. },
  53439. pause: function () {
  53440. this.keys = {};
  53441. this.removeKeyEventListeners();
  53442. },
  53443. updateVelocity: function (delta) {
  53444. var acceleration;
  53445. var adAxis;
  53446. var adSign;
  53447. var data = this.data;
  53448. var keys = this.keys;
  53449. var velocity = this.velocity;
  53450. var wsAxis;
  53451. var wsSign;
  53452. adAxis = data.adAxis;
  53453. wsAxis = data.wsAxis;
  53454. // If FPS too low, reset velocity.
  53455. if (delta > MAX_DELTA) {
  53456. velocity[adAxis] = 0;
  53457. velocity[wsAxis] = 0;
  53458. return;
  53459. }
  53460. // https://gamedev.stackexchange.com/questions/151383/frame-rate-independant-movement-with-acceleration
  53461. var scaledEasing = Math.pow(1 / this.easing, delta * 60);
  53462. // Velocity Easing.
  53463. if (velocity[adAxis] !== 0) {
  53464. velocity[adAxis] = velocity[adAxis] * scaledEasing;
  53465. }
  53466. if (velocity[wsAxis] !== 0) {
  53467. velocity[wsAxis] = velocity[wsAxis] * scaledEasing;
  53468. }
  53469. // Clamp velocity easing.
  53470. if (Math.abs(velocity[adAxis]) < CLAMP_VELOCITY) { velocity[adAxis] = 0; }
  53471. if (Math.abs(velocity[wsAxis]) < CLAMP_VELOCITY) { velocity[wsAxis] = 0; }
  53472. if (!data.enabled) { return; }
  53473. // Update velocity using keys pressed.
  53474. acceleration = data.acceleration;
  53475. if (data.adEnabled) {
  53476. adSign = data.adInverted ? -1 : 1;
  53477. if (keys.KeyA || keys.ArrowLeft) { velocity[adAxis] -= adSign * acceleration * delta; }
  53478. if (keys.KeyD || keys.ArrowRight) { velocity[adAxis] += adSign * acceleration * delta; }
  53479. }
  53480. if (data.wsEnabled) {
  53481. wsSign = data.wsInverted ? -1 : 1;
  53482. if (keys.KeyW || keys.ArrowUp) { velocity[wsAxis] -= wsSign * acceleration * delta; }
  53483. if (keys.KeyS || keys.ArrowDown) { velocity[wsAxis] += wsSign * acceleration * delta; }
  53484. }
  53485. },
  53486. getMovementVector: (function () {
  53487. var directionVector = new THREE.Vector3(0, 0, 0);
  53488. var rotationEuler = new THREE.Euler(0, 0, 0, 'YXZ');
  53489. return function (delta) {
  53490. var rotation = this.el.getAttribute('rotation');
  53491. var velocity = this.velocity;
  53492. var xRotation;
  53493. directionVector.copy(velocity);
  53494. directionVector.multiplyScalar(delta);
  53495. // Absolute.
  53496. if (!rotation) { return directionVector; }
  53497. xRotation = this.data.fly ? rotation.x : 0;
  53498. // Transform direction relative to heading.
  53499. rotationEuler.set(THREE.Math.degToRad(xRotation), THREE.Math.degToRad(rotation.y), 0);
  53500. directionVector.applyEuler(rotationEuler);
  53501. return directionVector;
  53502. };
  53503. })(),
  53504. attachVisibilityEventListeners: function () {
  53505. window.oncontextmenu = this.onContextMenu;
  53506. window.addEventListener('blur', this.onBlur);
  53507. window.addEventListener('focus', this.onFocus);
  53508. document.addEventListener('visibilitychange', this.onVisibilityChange);
  53509. },
  53510. removeVisibilityEventListeners: function () {
  53511. window.removeEventListener('blur', this.onBlur);
  53512. window.removeEventListener('focus', this.onFocus);
  53513. document.removeEventListener('visibilitychange', this.onVisibilityChange);
  53514. },
  53515. attachKeyEventListeners: function () {
  53516. window.addEventListener('keydown', this.onKeyDown);
  53517. window.addEventListener('keyup', this.onKeyUp);
  53518. },
  53519. removeKeyEventListeners: function () {
  53520. window.removeEventListener('keydown', this.onKeyDown);
  53521. window.removeEventListener('keyup', this.onKeyUp);
  53522. },
  53523. onContextMenu: function () {
  53524. var keys = Object.keys(this.keys);
  53525. for (var i = 0; i < keys.length; i++) {
  53526. delete this.keys[keys[i]];
  53527. }
  53528. },
  53529. onBlur: function () {
  53530. this.pause();
  53531. },
  53532. onFocus: function () {
  53533. this.play();
  53534. },
  53535. onVisibilityChange: function () {
  53536. if (document.hidden) {
  53537. this.onBlur();
  53538. } else {
  53539. this.onFocus();
  53540. }
  53541. },
  53542. onKeyDown: function (event) {
  53543. var code;
  53544. if (!shouldCaptureKeyEvent(event)) { return; }
  53545. code = event.code || KEYCODE_TO_CODE[event.keyCode];
  53546. if (KEYS.indexOf(code) !== -1) { this.keys[code] = true; }
  53547. },
  53548. onKeyUp: function (event) {
  53549. var code;
  53550. code = event.code || KEYCODE_TO_CODE[event.keyCode];
  53551. delete this.keys[code];
  53552. }
  53553. });
  53554. function isEmptyObject (keys) {
  53555. var key;
  53556. for (key in keys) { return false; }
  53557. return true;
  53558. }
  53559. },{"../constants":123,"../core/component":131,"../lib/three":179,"../utils/":205}],122:[function(_dereq_,module,exports){
  53560. /* global THREE */
  53561. var registerComponent = _dereq_('../core/component').registerComponent;
  53562. var bind = _dereq_('../utils/bind');
  53563. var trackedControlsUtils = _dereq_('../utils/tracked-controls');
  53564. var checkControllerPresentAndSetup = trackedControlsUtils.checkControllerPresentAndSetup;
  53565. var emitIfAxesChanged = trackedControlsUtils.emitIfAxesChanged;
  53566. var onButtonEvent = trackedControlsUtils.onButtonEvent;
  53567. var utils = _dereq_('../utils/');
  53568. var debug = utils.debug('components:windows-motion-controls:debug');
  53569. var warn = utils.debug('components:windows-motion-controls:warn');
  53570. var DEFAULT_HANDEDNESS = _dereq_('../constants').DEFAULT_HANDEDNESS;
  53571. var MODEL_BASE_URL = 'https://cdn.aframe.io/controllers/microsoft/';
  53572. var MODEL_FILENAMES = { left: 'left.glb', right: 'right.glb', default: 'universal.glb' };
  53573. var isWebXRAvailable = _dereq_('../utils/').device.isWebXRAvailable;
  53574. var GAMEPAD_ID_WEBXR = 'windows-mixed-reality';
  53575. var GAMEPAD_ID_WEBVR = 'Spatial Controller (Spatial Interaction Source) ';
  53576. var GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  53577. var GAMEPAD_ID_PREFIX = isWebXRAvailable ? GAMEPAD_ID_WEBXR : GAMEPAD_ID_WEBVR;
  53578. var INPUT_MAPPING_WEBVR = {
  53579. // A-Frame specific semantic axis names
  53580. axes: {'thumbstick': [0, 1], 'trackpad': [2, 3]},
  53581. // A-Frame specific semantic button names
  53582. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  53583. // A mapping of the semantic name to node name in the glTF model file,
  53584. // that should be transformed by axis value.
  53585. // This array mirrors the browser Gamepad.axes array, such that
  53586. // the mesh corresponding to axis 0 is in this array index 0.
  53587. axisMeshNames: [
  53588. 'THUMBSTICK_X',
  53589. 'THUMBSTICK_Y',
  53590. 'TOUCHPAD_TOUCH_X',
  53591. 'TOUCHPAD_TOUCH_Y'
  53592. ],
  53593. // A mapping of the semantic name to button node name in the glTF model file,
  53594. // that should be transformed by button value.
  53595. buttonMeshNames: {
  53596. 'trigger': 'SELECT',
  53597. 'menu': 'MENU',
  53598. 'grip': 'GRASP',
  53599. 'thumbstick': 'THUMBSTICK_PRESS',
  53600. 'trackpad': 'TOUCHPAD_PRESS'
  53601. },
  53602. pointingPoseMeshName: 'POINTING_POSE'
  53603. };
  53604. var INPUT_MAPPING_WEBXR = {
  53605. // A-Frame specific semantic axis names
  53606. axes: {'touchpad': [0, 1], 'thumbstick': [2, 3]},
  53607. // A-Frame specific semantic button names
  53608. buttons: ['trigger', 'squeeze', 'touchpad', 'thumbstick', 'menu'],
  53609. // A mapping of the semantic name to node name in the glTF model file,
  53610. // that should be transformed by axis value.
  53611. // This array mirrors the browser Gamepad.axes array, such that
  53612. // the mesh corresponding to axis 0 is in this array index 0.
  53613. axisMeshNames: [
  53614. 'TOUCHPAD_TOUCH_X',
  53615. 'TOUCHPAD_TOUCH_X',
  53616. 'THUMBSTICK_X',
  53617. 'THUMBSTICK_Y'
  53618. ],
  53619. // A mapping of the semantic name to button node name in the glTF model file,
  53620. // that should be transformed by button value.
  53621. buttonMeshNames: {
  53622. 'trigger': 'SELECT',
  53623. 'menu': 'MENU',
  53624. 'squeeze': 'GRASP',
  53625. 'thumbstick': 'THUMBSTICK_PRESS',
  53626. 'touchpad': 'TOUCHPAD_PRESS'
  53627. },
  53628. pointingPoseMeshName: 'POINTING_POSE'
  53629. };
  53630. var INPUT_MAPPING = isWebXRAvailable ? INPUT_MAPPING_WEBXR : INPUT_MAPPING_WEBVR;
  53631. /**
  53632. * Windows Motion Controller controls.
  53633. * Interface with Windows Motion Controller controllers and map Gamepad events to
  53634. * controller buttons: trackpad, trigger, grip, menu, thumbstick
  53635. * Load a controller model and transform the pressed buttons.
  53636. */
  53637. module.exports.Component = registerComponent('windows-motion-controls', {
  53638. schema: {
  53639. hand: {default: DEFAULT_HANDEDNESS},
  53640. // It is possible to have multiple pairs of controllers attached (a pair has both left and right).
  53641. // Set this to 1 to use a controller from the second pair, 2 from the third pair, etc.
  53642. pair: {default: 0},
  53643. // If true, loads the controller glTF asset.
  53644. model: {default: true},
  53645. // If true, will hide the model from the scene if no matching gamepad (based on ID & hand) is connected.
  53646. hideDisconnected: {default: true}
  53647. },
  53648. mapping: INPUT_MAPPING,
  53649. bindMethods: function () {
  53650. this.onModelError = bind(this.onModelError, this);
  53651. this.onModelLoaded = bind(this.onModelLoaded, this);
  53652. this.onControllersUpdate = bind(this.onControllersUpdate, this);
  53653. this.checkIfControllerPresent = bind(this.checkIfControllerPresent, this);
  53654. this.onAxisMoved = bind(this.onAxisMoved, this);
  53655. },
  53656. init: function () {
  53657. var self = this;
  53658. var el = this.el;
  53659. this.onButtonChanged = bind(this.onButtonChanged, this);
  53660. this.onButtonDown = function (evt) { onButtonEvent(evt.detail.id, 'down', self); };
  53661. this.onButtonUp = function (evt) { onButtonEvent(evt.detail.id, 'up', self); };
  53662. this.onButtonTouchStart = function (evt) { onButtonEvent(evt.detail.id, 'touchstart', self); };
  53663. this.onButtonTouchEnd = function (evt) { onButtonEvent(evt.detail.id, 'touchend', self); };
  53664. this.onControllerConnected = function () { self.setModelVisibility(true); };
  53665. this.onControllerDisconnected = function () { self.setModelVisibility(false); };
  53666. this.controllerPresent = false;
  53667. this.lastControllerCheck = 0;
  53668. this.previousButtonValues = {};
  53669. this.bindMethods();
  53670. // Cache for submeshes that we have looked up by name.
  53671. this.loadedMeshInfo = {
  53672. buttonMeshes: null,
  53673. axisMeshes: null
  53674. };
  53675. // Pointing poses
  53676. this.rayOrigin = {
  53677. origin: new THREE.Vector3(),
  53678. direction: new THREE.Vector3(0, 0, -1),
  53679. createdFromMesh: false
  53680. };
  53681. el.addEventListener('controllerconnected', this.onControllerConnected);
  53682. el.addEventListener('controllerdisconnected', this.onControllerDisconnected);
  53683. },
  53684. addEventListeners: function () {
  53685. var el = this.el;
  53686. el.addEventListener('buttonchanged', this.onButtonChanged);
  53687. el.addEventListener('buttondown', this.onButtonDown);
  53688. el.addEventListener('buttonup', this.onButtonUp);
  53689. el.addEventListener('touchstart', this.onButtonTouchStart);
  53690. el.addEventListener('touchend', this.onButtonTouchEnd);
  53691. el.addEventListener('axismove', this.onAxisMoved);
  53692. el.addEventListener('model-error', this.onModelError);
  53693. el.addEventListener('model-loaded', this.onModelLoaded);
  53694. this.controllerEventsActive = true;
  53695. },
  53696. removeEventListeners: function () {
  53697. var el = this.el;
  53698. el.removeEventListener('buttonchanged', this.onButtonChanged);
  53699. el.removeEventListener('buttondown', this.onButtonDown);
  53700. el.removeEventListener('buttonup', this.onButtonUp);
  53701. el.removeEventListener('touchstart', this.onButtonTouchStart);
  53702. el.removeEventListener('touchend', this.onButtonTouchEnd);
  53703. el.removeEventListener('axismove', this.onAxisMoved);
  53704. el.removeEventListener('model-error', this.onModelError);
  53705. el.removeEventListener('model-loaded', this.onModelLoaded);
  53706. this.controllerEventsActive = false;
  53707. },
  53708. checkIfControllerPresent: function () {
  53709. checkControllerPresentAndSetup(this, GAMEPAD_ID_PREFIX, {
  53710. hand: this.data.hand,
  53711. index: this.data.pair,
  53712. iterateControllerProfiles: true
  53713. });
  53714. },
  53715. play: function () {
  53716. this.checkIfControllerPresent();
  53717. this.addControllersUpdateListener();
  53718. },
  53719. pause: function () {
  53720. this.removeEventListeners();
  53721. this.removeControllersUpdateListener();
  53722. },
  53723. updateControllerModel: function () {
  53724. // If we do not want to load a model, or, have already loaded the model, emit the controllermodelready event.
  53725. if (!this.data.model || this.rayOrigin.createdFromMesh) {
  53726. this.modelReady();
  53727. return;
  53728. }
  53729. var sourceUrl = this.createControllerModelUrl();
  53730. this.loadModel(sourceUrl);
  53731. },
  53732. /**
  53733. * Helper function that constructs a URL from the controller ID suffix, for future proofed
  53734. * art assets.
  53735. */
  53736. createControllerModelUrl: function (forceDefault) {
  53737. // Determine the device specific folder based on the ID suffix
  53738. var trackedControlsComponent = this.el.components['tracked-controls'];
  53739. var controller = trackedControlsComponent ? trackedControlsComponent.controller : null;
  53740. var device = 'default';
  53741. var hand = this.data.hand;
  53742. var filename;
  53743. if (controller && !window.hasNativeWebXRImplementation) {
  53744. // Read hand directly from the controller, rather than this.data, as in the case that the controller
  53745. // is unhanded this.data will still have 'left' or 'right' (depending on what the user inserted in to the scene).
  53746. // In this case, we want to load the universal model, so need to get the '' from the controller.
  53747. hand = controller.hand;
  53748. if (!forceDefault) {
  53749. var match = controller.id.match(GAMEPAD_ID_PATTERN);
  53750. device = ((match && match[0]) || device);
  53751. }
  53752. }
  53753. // Hand
  53754. filename = MODEL_FILENAMES[hand] || MODEL_FILENAMES.default;
  53755. // Final url
  53756. return MODEL_BASE_URL + device + '/' + filename;
  53757. },
  53758. injectTrackedControls: function () {
  53759. var data = this.data;
  53760. this.el.setAttribute('tracked-controls', {
  53761. idPrefix: GAMEPAD_ID_PREFIX,
  53762. controller: data.pair,
  53763. hand: data.hand,
  53764. armModel: false
  53765. });
  53766. this.updateControllerModel();
  53767. },
  53768. addControllersUpdateListener: function () {
  53769. this.el.sceneEl.addEventListener('controllersupdated', this.onControllersUpdate, false);
  53770. },
  53771. removeControllersUpdateListener: function () {
  53772. this.el.sceneEl.removeEventListener('controllersupdated', this.onControllersUpdate, false);
  53773. },
  53774. onControllersUpdate: function () {
  53775. this.checkIfControllerPresent();
  53776. },
  53777. onModelError: function (evt) {
  53778. var defaultUrl = this.createControllerModelUrl(true);
  53779. if (evt.detail.src !== defaultUrl) {
  53780. warn('Failed to load controller model for device, attempting to load default.');
  53781. this.loadModel(defaultUrl);
  53782. } else {
  53783. warn('Failed to load default controller model.');
  53784. }
  53785. },
  53786. loadModel: function (url) {
  53787. // The model is loaded by the gltf-model compoent when this attribute is initially set,
  53788. // removed and re-loaded if the given url changes.
  53789. this.el.setAttribute('gltf-model', 'url(' + url + ')');
  53790. },
  53791. onModelLoaded: function (evt) {
  53792. var rootNode = this.controllerModel = evt.detail.model;
  53793. var loadedMeshInfo = this.loadedMeshInfo;
  53794. var i;
  53795. var meshName;
  53796. var mesh;
  53797. var meshInfo;
  53798. debug('Processing model');
  53799. // Reset the caches
  53800. loadedMeshInfo.buttonMeshes = {};
  53801. loadedMeshInfo.axisMeshes = {};
  53802. // Cache our meshes so we aren't traversing the hierarchy per frame
  53803. if (rootNode) {
  53804. // Button Meshes
  53805. for (i = 0; i < this.mapping.buttons.length; i++) {
  53806. meshName = this.mapping.buttonMeshNames[this.mapping.buttons[i]];
  53807. if (!meshName) {
  53808. debug('Skipping unknown button at index: ' + i + ' with mapped name: ' + this.mapping.buttons[i]);
  53809. continue;
  53810. }
  53811. mesh = rootNode.getObjectByName(meshName);
  53812. if (!mesh) {
  53813. warn('Missing button mesh with name: ' + meshName);
  53814. continue;
  53815. }
  53816. meshInfo = {
  53817. index: i,
  53818. value: getImmediateChildByName(mesh, 'VALUE'),
  53819. pressed: getImmediateChildByName(mesh, 'PRESSED'),
  53820. unpressed: getImmediateChildByName(mesh, 'UNPRESSED')
  53821. };
  53822. if (meshInfo.value && meshInfo.pressed && meshInfo.unpressed) {
  53823. loadedMeshInfo.buttonMeshes[this.mapping.buttons[i]] = meshInfo;
  53824. } else {
  53825. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  53826. warn('Missing button submesh under mesh with name: ' + meshName +
  53827. '(VALUE: ' + !!meshInfo.value +
  53828. ', PRESSED: ' + !!meshInfo.pressed +
  53829. ', UNPRESSED:' + !!meshInfo.unpressed +
  53830. ')');
  53831. }
  53832. }
  53833. // Axis Meshes
  53834. for (i = 0; i < this.mapping.axisMeshNames.length; i++) {
  53835. meshName = this.mapping.axisMeshNames[i];
  53836. if (!meshName) {
  53837. debug('Skipping unknown axis at index: ' + i);
  53838. continue;
  53839. }
  53840. mesh = rootNode.getObjectByName(meshName);
  53841. if (!mesh) {
  53842. warn('Missing axis mesh with name: ' + meshName);
  53843. continue;
  53844. }
  53845. meshInfo = {
  53846. index: i,
  53847. value: getImmediateChildByName(mesh, 'VALUE'),
  53848. min: getImmediateChildByName(mesh, 'MIN'),
  53849. max: getImmediateChildByName(mesh, 'MAX')
  53850. };
  53851. if (meshInfo.value && meshInfo.min && meshInfo.max) {
  53852. loadedMeshInfo.axisMeshes[i] = meshInfo;
  53853. } else {
  53854. // If we didn't find the mesh, it simply means this axis won't have transforms applied as mapped axis values change.
  53855. warn('Missing axis submesh under mesh with name: ' + meshName +
  53856. '(VALUE: ' + !!meshInfo.value +
  53857. ', MIN: ' + !!meshInfo.min +
  53858. ', MAX:' + !!meshInfo.max +
  53859. ')');
  53860. }
  53861. }
  53862. this.calculateRayOriginFromMesh(rootNode);
  53863. // Determine if the model has to be visible or not.
  53864. this.setModelVisibility();
  53865. }
  53866. debug('Model load complete.');
  53867. // Look through only immediate children. This will return null if no mesh exists with the given name.
  53868. function getImmediateChildByName (object3d, value) {
  53869. for (var i = 0, l = object3d.children.length; i < l; i++) {
  53870. var obj = object3d.children[i];
  53871. if (obj && obj['name'] === value) {
  53872. return obj;
  53873. }
  53874. }
  53875. return undefined;
  53876. }
  53877. },
  53878. calculateRayOriginFromMesh: (function () {
  53879. var quaternion = new THREE.Quaternion();
  53880. return function (rootNode) {
  53881. var mesh;
  53882. // Calculate the pointer pose (used for rays), by applying the world transform of th POINTER_POSE node
  53883. // in the glTF (assumes that root node is at world origin)
  53884. this.rayOrigin.origin.set(0, 0, 0);
  53885. this.rayOrigin.direction.set(0, 0, -1);
  53886. this.rayOrigin.createdFromMesh = true;
  53887. // Try to read Pointing pose from the source model
  53888. mesh = rootNode.getObjectByName(this.mapping.pointingPoseMeshName);
  53889. if (mesh) {
  53890. var parent = rootNode.parent;
  53891. // We need to read pose transforms accumulated from the root of the glTF, not the scene.
  53892. if (parent) {
  53893. rootNode.parent = null;
  53894. rootNode.updateMatrixWorld(true);
  53895. rootNode.parent = parent;
  53896. }
  53897. mesh.getWorldPosition(this.rayOrigin.origin);
  53898. mesh.getWorldQuaternion(quaternion);
  53899. this.rayOrigin.direction.applyQuaternion(quaternion);
  53900. // Recalculate the world matrices now that the rootNode is re-attached to the parent.
  53901. if (parent) {
  53902. rootNode.updateMatrixWorld(true);
  53903. }
  53904. } else {
  53905. debug('Mesh does not contain pointing origin data, defaulting to none.');
  53906. }
  53907. // Emit event stating that our pointing ray is now accurate.
  53908. this.modelReady();
  53909. };
  53910. })(),
  53911. lerpAxisTransform: (function () {
  53912. var quaternion = new THREE.Quaternion();
  53913. return function (axis, axisValue) {
  53914. var axisMeshInfo = this.loadedMeshInfo.axisMeshes[axis];
  53915. if (!axisMeshInfo) return;
  53916. var min = axisMeshInfo.min;
  53917. var max = axisMeshInfo.max;
  53918. var target = axisMeshInfo.value;
  53919. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  53920. var lerpValue = axisValue * 0.5 + 0.5;
  53921. target.setRotationFromQuaternion(quaternion.copy(min.quaternion).slerp(max.quaternion, lerpValue));
  53922. target.position.lerpVectors(min.position, max.position, lerpValue);
  53923. };
  53924. })(),
  53925. lerpButtonTransform: (function () {
  53926. var quaternion = new THREE.Quaternion();
  53927. return function (buttonName, buttonValue) {
  53928. var buttonMeshInfo = this.loadedMeshInfo.buttonMeshes[buttonName];
  53929. if (!buttonMeshInfo) return;
  53930. var min = buttonMeshInfo.unpressed;
  53931. var max = buttonMeshInfo.pressed;
  53932. var target = buttonMeshInfo.value;
  53933. target.setRotationFromQuaternion(quaternion.copy(min.quaternion).slerp(max.quaternion, buttonValue));
  53934. target.position.lerpVectors(min.position, max.position, buttonValue);
  53935. };
  53936. })(),
  53937. modelReady: function () {
  53938. this.el.emit('controllermodelready', {
  53939. name: 'windows-motion-controls',
  53940. model: this.data.model,
  53941. rayOrigin: this.rayOrigin
  53942. });
  53943. },
  53944. onButtonChanged: function (evt) {
  53945. var buttonName = this.mapping.buttons[evt.detail.id];
  53946. if (buttonName) {
  53947. // Update the button mesh transform
  53948. if (this.loadedMeshInfo && this.loadedMeshInfo.buttonMeshes) {
  53949. this.lerpButtonTransform(buttonName, evt.detail.state.value);
  53950. }
  53951. // Only emit events for buttons that we know how to map from index to name
  53952. this.el.emit(buttonName + 'changed', evt.detail.state);
  53953. }
  53954. },
  53955. onAxisMoved: function (evt) {
  53956. var numAxes = this.mapping.axisMeshNames.length;
  53957. // Only attempt to update meshes if we have valid data.
  53958. if (this.loadedMeshInfo && this.loadedMeshInfo.axisMeshes) {
  53959. for (var axis = 0; axis < numAxes; axis++) {
  53960. // Update the button mesh transform
  53961. this.lerpAxisTransform(axis, evt.detail.axis[axis] || 0.0);
  53962. }
  53963. }
  53964. emitIfAxesChanged(this, this.mapping.axes, evt);
  53965. },
  53966. setModelVisibility: function (visible) {
  53967. var model = this.el.getObject3D('mesh');
  53968. visible = visible !== undefined ? visible : this.modelVisible;
  53969. this.modelVisible = visible;
  53970. if (!model) { return; }
  53971. model.visible = visible;
  53972. }
  53973. });
  53974. },{"../constants":123,"../core/component":131,"../utils/":205,"../utils/bind":199,"../utils/tracked-controls":214}],123:[function(_dereq_,module,exports){
  53975. module.exports = {
  53976. AFRAME_INJECTED: 'aframe-injected',
  53977. DEFAULT_CAMERA_HEIGHT: 1.6,
  53978. DEFAULT_HANDEDNESS: 'right',
  53979. keyboardevent: _dereq_('./keyboardevent')
  53980. };
  53981. },{"./keyboardevent":124}],124:[function(_dereq_,module,exports){
  53982. module.exports = {
  53983. // Tiny KeyboardEvent.code polyfill.
  53984. KEYCODE_TO_CODE: {
  53985. '38': 'ArrowUp',
  53986. '37': 'ArrowLeft',
  53987. '40': 'ArrowDown',
  53988. '39': 'ArrowRight',
  53989. '87': 'KeyW',
  53990. '65': 'KeyA',
  53991. '83': 'KeyS',
  53992. '68': 'KeyD'
  53993. }
  53994. };
  53995. },{}],125:[function(_dereq_,module,exports){
  53996. var ANode = _dereq_('./a-node');
  53997. var bind = _dereq_('../utils/bind');
  53998. var debug = _dereq_('../utils/debug');
  53999. var registerElement = _dereq_('./a-register-element').registerElement;
  54000. var THREE = _dereq_('../lib/three');
  54001. var fileLoader = new THREE.FileLoader();
  54002. var warn = debug('core:a-assets:warn');
  54003. /**
  54004. * Asset management system. Handles blocking on asset loading.
  54005. */
  54006. module.exports = registerElement('a-assets', {
  54007. prototype: Object.create(ANode.prototype, {
  54008. createdCallback: {
  54009. value: function () {
  54010. this.isAssets = true;
  54011. this.fileLoader = fileLoader;
  54012. this.timeout = null;
  54013. }
  54014. },
  54015. attachedCallback: {
  54016. value: function () {
  54017. var self = this;
  54018. var i;
  54019. var loaded = [];
  54020. var mediaEl;
  54021. var mediaEls;
  54022. var imgEl;
  54023. var imgEls;
  54024. var timeout;
  54025. if (!this.parentNode.isScene) {
  54026. throw new Error('<a-assets> must be a child of a <a-scene>.');
  54027. }
  54028. // Wait for <img>s.
  54029. imgEls = this.querySelectorAll('img');
  54030. for (i = 0; i < imgEls.length; i++) {
  54031. imgEl = fixUpMediaElement(imgEls[i]);
  54032. loaded.push(new Promise(function (resolve, reject) {
  54033. // Set in cache because we won't be needing to call three.js loader if we have.
  54034. // a loaded media element.
  54035. THREE.Cache.files[imgEls[i].getAttribute('src')] = imgEl;
  54036. imgEl.onload = resolve;
  54037. imgEl.onerror = reject;
  54038. }));
  54039. }
  54040. // Wait for <audio>s and <video>s.
  54041. mediaEls = this.querySelectorAll('audio, video');
  54042. for (i = 0; i < mediaEls.length; i++) {
  54043. mediaEl = fixUpMediaElement(mediaEls[i]);
  54044. if (!mediaEl.src && !mediaEl.srcObject) {
  54045. warn('Audio/video asset has neither `src` nor `srcObject` attributes.');
  54046. }
  54047. loaded.push(mediaElementLoaded(mediaEl));
  54048. }
  54049. // Trigger loaded for scene to start rendering.
  54050. Promise.all(loaded).then(bind(this.load, this));
  54051. // Timeout to start loading anyways.
  54052. timeout = parseInt(this.getAttribute('timeout'), 10) || 3000;
  54053. this.timeout = setTimeout(function () {
  54054. if (self.hasLoaded) { return; }
  54055. warn('Asset loading timed out in ', timeout, 'ms');
  54056. self.emit('timeout');
  54057. self.load();
  54058. }, timeout);
  54059. }
  54060. },
  54061. detachedCallback: {
  54062. value: function () {
  54063. if (this.timeout) { clearTimeout(this.timeout); }
  54064. }
  54065. },
  54066. load: {
  54067. value: function () {
  54068. ANode.prototype.load.call(this, null, function waitOnFilter (el) {
  54069. return el.isAssetItem && el.hasAttribute('src');
  54070. });
  54071. }
  54072. }
  54073. })
  54074. });
  54075. /**
  54076. * Preload using XHRLoader for any type of asset.
  54077. */
  54078. registerElement('a-asset-item', {
  54079. prototype: Object.create(ANode.prototype, {
  54080. createdCallback: {
  54081. value: function () {
  54082. this.data = null;
  54083. this.isAssetItem = true;
  54084. }
  54085. },
  54086. attachedCallback: {
  54087. value: function () {
  54088. var self = this;
  54089. var src = this.getAttribute('src');
  54090. fileLoader.setResponseType(
  54091. this.getAttribute('response-type') || inferResponseType(src));
  54092. fileLoader.load(src, function handleOnLoad (response) {
  54093. self.data = response;
  54094. /*
  54095. Workaround for a Chrome bug. If another XHR is sent to the same url before the
  54096. previous one closes, the second request never finishes.
  54097. setTimeout finishes the first request and lets the logic triggered by load open
  54098. subsequent requests.
  54099. setTimeout can be removed once the fix for the bug below ships:
  54100. https://bugs.chromium.org/p/chromium/issues/detail?id=633696&q=component%3ABlink%3ENetwork%3EXHR%20&colspec=ID%20Pri%20M%20Stars%20ReleaseBlock%20Component%20Status%20Owner%20Summary%20OS%20Modified
  54101. */
  54102. setTimeout(function load () { ANode.prototype.load.call(self); });
  54103. }, function handleOnProgress (xhr) {
  54104. self.emit('progress', {
  54105. loadedBytes: xhr.loaded,
  54106. totalBytes: xhr.total,
  54107. xhr: xhr
  54108. });
  54109. }, function handleOnError (xhr) {
  54110. self.emit('error', {xhr: xhr});
  54111. });
  54112. }
  54113. }
  54114. })
  54115. });
  54116. /**
  54117. * Create a Promise that resolves once the media element has finished buffering.
  54118. *
  54119. * @param {Element} el - HTMLMediaElement.
  54120. * @returns {Promise}
  54121. */
  54122. function mediaElementLoaded (el) {
  54123. if (!el.hasAttribute('autoplay') && el.getAttribute('preload') !== 'auto') {
  54124. return;
  54125. }
  54126. // If media specifies autoplay or preload, wait until media is completely buffered.
  54127. return new Promise(function (resolve, reject) {
  54128. if (el.readyState === 4) { return resolve(); } // Already loaded.
  54129. if (el.error) { return reject(); } // Error.
  54130. el.addEventListener('loadeddata', checkProgress, false);
  54131. el.addEventListener('progress', checkProgress, false);
  54132. el.addEventListener('error', reject, false);
  54133. function checkProgress () {
  54134. // Add up the seconds buffered.
  54135. var secondsBuffered = 0;
  54136. for (var i = 0; i < el.buffered.length; i++) {
  54137. secondsBuffered += el.buffered.end(i) - el.buffered.start(i);
  54138. }
  54139. // Compare seconds buffered to media duration.
  54140. if (secondsBuffered >= el.duration) {
  54141. // Set in cache because we won't be needing to call three.js loader if we have.
  54142. // a loaded media element.
  54143. // Store video elements only. three.js loader is used for audio elements.
  54144. // See assetParse too.
  54145. if (el.tagName === 'VIDEO') {
  54146. THREE.Cache.files[el.getAttribute('src')] = el;
  54147. }
  54148. resolve();
  54149. }
  54150. }
  54151. });
  54152. }
  54153. /**
  54154. * Automatically add attributes to media elements where convenient.
  54155. * crossorigin, playsinline.
  54156. */
  54157. function fixUpMediaElement (mediaEl) {
  54158. // Cross-origin.
  54159. var newMediaEl = setCrossOrigin(mediaEl);
  54160. // Plays inline for mobile.
  54161. if (newMediaEl.tagName && newMediaEl.tagName.toLowerCase() === 'video') {
  54162. newMediaEl.setAttribute('playsinline', '');
  54163. newMediaEl.setAttribute('webkit-playsinline', '');
  54164. }
  54165. if (newMediaEl !== mediaEl) {
  54166. mediaEl.parentNode.appendChild(newMediaEl);
  54167. mediaEl.parentNode.removeChild(mediaEl);
  54168. }
  54169. return newMediaEl;
  54170. }
  54171. /**
  54172. * Automatically set `crossorigin` if not defined on the media element.
  54173. * If it is not defined, we must create and re-append a new media element <img> and
  54174. * have the browser re-request it with `crossorigin` set.
  54175. *
  54176. * @param {Element} Media element (e.g., <img>, <audio>, <video>).
  54177. * @returns {Element} Media element to be used to listen to for loaded events.
  54178. */
  54179. function setCrossOrigin (mediaEl) {
  54180. var newMediaEl;
  54181. var src;
  54182. // Already has crossorigin set.
  54183. if (mediaEl.hasAttribute('crossorigin')) { return mediaEl; }
  54184. src = mediaEl.getAttribute('src');
  54185. if (src !== null) {
  54186. // Does not have protocol.
  54187. if (src.indexOf('://') === -1) { return mediaEl; }
  54188. // Determine if cross origin is actually needed.
  54189. if (extractDomain(src) === window.location.host) { return mediaEl; }
  54190. }
  54191. warn('Cross-origin element (e.g., <img>) was requested without `crossorigin` set. ' +
  54192. 'A-Frame will re-request the asset with `crossorigin` attribute set. ' +
  54193. 'Please set `crossorigin` on the element (e.g., <img crossorigin="anonymous">)', src);
  54194. mediaEl.crossOrigin = 'anonymous';
  54195. newMediaEl = mediaEl.cloneNode(true);
  54196. return newMediaEl;
  54197. }
  54198. /**
  54199. * Extract domain out of URL.
  54200. *
  54201. * @param {string} url
  54202. * @returns {string}
  54203. */
  54204. function extractDomain (url) {
  54205. // Find and remove protocol (e.g., http, ftp, etc.) to get domain.
  54206. var domain = url.indexOf('://') > -1 ? url.split('/')[2] : url.split('/')[0];
  54207. // Find and remove port number.
  54208. return domain.substring(0, domain.indexOf(':'));
  54209. }
  54210. /**
  54211. * Infer response-type attribute from src.
  54212. * Default is text (default XMLHttpRequest.responseType)
  54213. * and arraybuffer for .glb files.
  54214. *
  54215. * @param {string} src
  54216. * @returns {string}
  54217. */
  54218. function inferResponseType (src) {
  54219. var fileName = getFileNameFromURL(src);
  54220. var dotLastIndex = fileName.lastIndexOf('.');
  54221. if (dotLastIndex >= 0) {
  54222. var extension = fileName.slice(dotLastIndex, src.search(/\?|#|$/));
  54223. if (extension === '.glb') {
  54224. return 'arraybuffer';
  54225. }
  54226. }
  54227. return 'text';
  54228. }
  54229. module.exports.inferResponseType = inferResponseType;
  54230. /**
  54231. * Extract filename from URL
  54232. *
  54233. * @param {string} url
  54234. * @returns {string}
  54235. */
  54236. function getFileNameFromURL (url) {
  54237. var parser = document.createElement('a');
  54238. parser.href = url;
  54239. var query = parser.search.replace(/^\?/, '');
  54240. var filePath = url.replace(query, '').replace('?', '');
  54241. return filePath.substring(filePath.lastIndexOf('/') + 1);
  54242. }
  54243. module.exports.getFileNameFromURL = getFileNameFromURL;
  54244. },{"../lib/three":179,"../utils/bind":199,"../utils/debug":201,"./a-node":129,"./a-register-element":130}],126:[function(_dereq_,module,exports){
  54245. var debug = _dereq_('../utils/debug');
  54246. var registerElement = _dereq_('./a-register-element').registerElement;
  54247. var warn = debug('core:cubemap:warn');
  54248. /**
  54249. * Cubemap element that handles validation and exposes list of URLs.
  54250. * Does not listen to updates.
  54251. */
  54252. module.exports = registerElement('a-cubemap', {
  54253. prototype: Object.create(window.HTMLElement.prototype, {
  54254. /**
  54255. * Calculates this.srcs.
  54256. */
  54257. attachedCallback: {
  54258. value: function () {
  54259. this.srcs = this.validate();
  54260. },
  54261. writable: window.debug
  54262. },
  54263. /**
  54264. * Checks for exactly six elements with [src].
  54265. * Does not check explicitly for <img>s in case user does not want
  54266. * prefetching.
  54267. *
  54268. * @returns {Array|null} - six URLs if valid, else null.
  54269. */
  54270. validate: {
  54271. value: function () {
  54272. var elements = this.querySelectorAll('[src]');
  54273. var i;
  54274. var srcs = [];
  54275. if (elements.length === 6) {
  54276. for (i = 0; i < elements.length; i++) {
  54277. srcs.push(elements[i].getAttribute('src'));
  54278. }
  54279. return srcs;
  54280. }
  54281. // Else if there are not six elements, throw a warning.
  54282. warn(
  54283. '<a-cubemap> did not contain exactly six elements each with a ' +
  54284. '`src` attribute.');
  54285. },
  54286. writable: window.debug
  54287. }
  54288. })
  54289. });
  54290. },{"../utils/debug":201,"./a-register-element":130}],127:[function(_dereq_,module,exports){
  54291. var ANode = _dereq_('./a-node');
  54292. var COMPONENTS = _dereq_('./component').components;
  54293. var registerElement = _dereq_('./a-register-element').registerElement;
  54294. var THREE = _dereq_('../lib/three');
  54295. var utils = _dereq_('../utils/');
  54296. var AEntity;
  54297. var debug = utils.debug('core:a-entity:debug');
  54298. var warn = utils.debug('core:a-entity:warn');
  54299. var MULTIPLE_COMPONENT_DELIMITER = '__';
  54300. var OBJECT3D_COMPONENTS = ['position', 'rotation', 'scale', 'visible'];
  54301. var ONCE = {once: true};
  54302. /**
  54303. * Entity is a container object that components are plugged into to comprise everything in
  54304. * the scene. In A-Frame, they inherently have position, rotation, and scale.
  54305. *
  54306. * To be able to take components, the scene element inherits from the entity definition.
  54307. *
  54308. * @member {object} components - entity's currently initialized components.
  54309. * @member {object} object3D - three.js object.
  54310. * @member {array} states
  54311. * @member {boolean} isPlaying - false if dynamic behavior of the entity is paused.
  54312. */
  54313. var proto = Object.create(ANode.prototype, {
  54314. createdCallback: {
  54315. value: function () {
  54316. this.components = {};
  54317. // To avoid double initializations and infinite loops.
  54318. this.initializingComponents = {};
  54319. this.componentsToUpdate = {};
  54320. this.isEntity = true;
  54321. this.isPlaying = false;
  54322. this.object3D = new THREE.Group();
  54323. this.object3D.el = this;
  54324. this.object3DMap = {};
  54325. this.parentEl = null;
  54326. this.rotationObj = {};
  54327. this.states = [];
  54328. }
  54329. },
  54330. /**
  54331. * Handle changes coming from the browser DOM inspector.
  54332. */
  54333. attributeChangedCallback: {
  54334. value: function (attr, oldVal, newVal) {
  54335. var component = this.components[attr];
  54336. // If the empty string is passed by the component initialization
  54337. // logic we ignore the component update.
  54338. if (component && component.justInitialized && newVal === '') {
  54339. delete component.justInitialized;
  54340. return;
  54341. }
  54342. // When a component is removed after calling el.removeAttribute('material')
  54343. if (!component && newVal === null) { return; }
  54344. this.setEntityAttribute(attr, oldVal, newVal);
  54345. }
  54346. },
  54347. /**
  54348. * Add to parent, load, play.
  54349. */
  54350. attachedCallback: {
  54351. value: function () {
  54352. var assetsEl; // Asset management system element.
  54353. var sceneEl = this.sceneEl;
  54354. var self = this; // Component.
  54355. this.addToParent();
  54356. // Don't .load() scene on attachedCallback.
  54357. if (this.isScene) { return; }
  54358. // Gracefully not error when outside of <a-scene> (e.g., tests).
  54359. if (!sceneEl) {
  54360. this.load();
  54361. return;
  54362. }
  54363. // Wait for asset management system to finish before loading.
  54364. assetsEl = sceneEl.querySelector('a-assets');
  54365. if (assetsEl && !assetsEl.hasLoaded) {
  54366. assetsEl.addEventListener('loaded', function () { self.load(); });
  54367. return;
  54368. }
  54369. this.load();
  54370. }
  54371. },
  54372. /**
  54373. * Tell parent to remove this element's object3D from its object3D.
  54374. * Do not call on scene element because that will cause a call to document.body.remove().
  54375. */
  54376. detachedCallback: {
  54377. value: function () {
  54378. var componentName;
  54379. if (!this.parentEl) { return; }
  54380. // Remove components.
  54381. for (componentName in this.components) {
  54382. this.removeComponent(componentName, false);
  54383. }
  54384. if (this.isScene) { return; }
  54385. this.removeFromParent();
  54386. ANode.prototype.detachedCallback.call(this);
  54387. // Remove cyclic reference.
  54388. this.object3D.el = null;
  54389. }
  54390. },
  54391. getObject3D: {
  54392. value: function (type) {
  54393. return this.object3DMap[type];
  54394. }
  54395. },
  54396. /**
  54397. * Set a THREE.Object3D into the map.
  54398. *
  54399. * @param {string} type - Developer-set name of the type of object, will be unique per type.
  54400. * @param {object} obj - A THREE.Object3D.
  54401. */
  54402. setObject3D: {
  54403. value: function (type, obj) {
  54404. var oldObj;
  54405. var self = this;
  54406. if (!(obj instanceof THREE.Object3D)) {
  54407. throw new Error(
  54408. '`Entity.setObject3D` was called with an object that was not an instance of ' +
  54409. 'THREE.Object3D.'
  54410. );
  54411. }
  54412. // Remove existing object of the type.
  54413. oldObj = this.getObject3D(type);
  54414. if (oldObj) { this.object3D.remove(oldObj); }
  54415. // Set references to A-Frame entity.
  54416. obj.el = this;
  54417. if (obj.children.length) {
  54418. obj.traverse(function bindEl (child) {
  54419. child.el = self;
  54420. });
  54421. }
  54422. // Add.
  54423. this.object3D.add(obj);
  54424. this.object3DMap[type] = obj;
  54425. this.emit('object3dset', {object: obj, type: type});
  54426. }
  54427. },
  54428. /**
  54429. * Remove object from scene and entity object3D map.
  54430. */
  54431. removeObject3D: {
  54432. value: function (type) {
  54433. var obj = this.getObject3D(type);
  54434. if (!obj) {
  54435. warn('Tried to remove `Object3D` of type:', type, 'which was not defined.');
  54436. return;
  54437. }
  54438. this.object3D.remove(obj);
  54439. delete this.object3DMap[type];
  54440. this.emit('object3dremove', {type: type});
  54441. }
  54442. },
  54443. /**
  54444. * Gets or creates an object3D of a given type.
  54445. *
  54446. * @param {string} type - Type of the object3D.
  54447. * @param {string} Constructor - Constructor to use to create the object3D if needed.
  54448. * @returns {object}
  54449. */
  54450. getOrCreateObject3D: {
  54451. value: function (type, Constructor) {
  54452. var object3D = this.getObject3D(type);
  54453. if (!object3D && Constructor) {
  54454. object3D = new Constructor();
  54455. this.setObject3D(type, object3D);
  54456. }
  54457. warn('`getOrCreateObject3D` has been deprecated. Use `setObject3D()` ' +
  54458. 'and `object3dset` event instead.');
  54459. return object3D;
  54460. }
  54461. },
  54462. /**
  54463. * Add child entity.
  54464. *
  54465. * @param {Element} el - Child entity.
  54466. */
  54467. add: {
  54468. value: function (el) {
  54469. if (!el.object3D) {
  54470. throw new Error("Trying to add an element that doesn't have an `object3D`");
  54471. }
  54472. this.object3D.add(el.object3D);
  54473. this.emit('child-attached', {el: el});
  54474. }
  54475. },
  54476. /**
  54477. * Tell parentNode to add this entity to itself.
  54478. */
  54479. addToParent: {
  54480. value: function () {
  54481. var parentNode = this.parentEl = this.parentNode;
  54482. // `!parentNode` check primarily for unit tests.
  54483. if (!parentNode || !parentNode.add || this.attachedToParent) { return; }
  54484. parentNode.add(this);
  54485. this.attachedToParent = true; // To prevent multiple attachments to same parent.
  54486. }
  54487. },
  54488. /**
  54489. * Tell parentNode to remove this entity from itself.
  54490. */
  54491. removeFromParent: {
  54492. value: function () {
  54493. var parentEl = this.parentEl;
  54494. this.parentEl.remove(this);
  54495. this.attachedToParent = false;
  54496. this.parentEl = null;
  54497. parentEl.emit('child-detached', {el: this});
  54498. }
  54499. },
  54500. load: {
  54501. value: function () {
  54502. var self = this;
  54503. if (this.hasLoaded || !this.parentEl) { return; }
  54504. ANode.prototype.load.call(this, function entityLoadCallback () {
  54505. // Check if entity was detached while it was waiting to load.
  54506. if (!self.parentEl) { return; }
  54507. self.updateComponents();
  54508. if (self.isScene || self.parentEl.isPlaying) { self.play(); }
  54509. });
  54510. },
  54511. writable: window.debug
  54512. },
  54513. /**
  54514. * Remove child entity.
  54515. *
  54516. * @param {Element} el - Child entity.
  54517. */
  54518. remove: {
  54519. value: function (el) {
  54520. if (el) {
  54521. this.object3D.remove(el.object3D);
  54522. } else {
  54523. this.parentNode.removeChild(this);
  54524. }
  54525. }
  54526. },
  54527. /**
  54528. * @returns {array} Direct children that are entities.
  54529. */
  54530. getChildEntities: {
  54531. value: function () {
  54532. var children = this.children;
  54533. var childEntities = [];
  54534. for (var i = 0; i < children.length; i++) {
  54535. var child = children[i];
  54536. if (child instanceof AEntity) {
  54537. childEntities.push(child);
  54538. }
  54539. }
  54540. return childEntities;
  54541. }
  54542. },
  54543. /**
  54544. * Initialize component.
  54545. *
  54546. * @param {string} attrName - Attribute name asociated to the component.
  54547. * @param {object} data - Component data
  54548. * @param {boolean} isDependency - True if the component is a dependency.
  54549. */
  54550. initComponent: {
  54551. value: function (attrName, data, isDependency) {
  54552. var component;
  54553. var componentId;
  54554. var componentInfo;
  54555. var componentName;
  54556. var isComponentDefined;
  54557. componentInfo = utils.split(attrName, MULTIPLE_COMPONENT_DELIMITER);
  54558. componentName = componentInfo[0];
  54559. componentId = componentInfo.length > 2
  54560. ? componentInfo.slice(1).join('__')
  54561. : componentInfo[1];
  54562. // Not a registered component.
  54563. if (!COMPONENTS[componentName]) { return; }
  54564. // Component is not a dependency and is undefined.
  54565. // If a component is a dependency, then it is okay to have no data.
  54566. isComponentDefined = checkComponentDefined(this, attrName) ||
  54567. data !== undefined;
  54568. if (!isComponentDefined && !isDependency) { return; }
  54569. // Component already initialized.
  54570. if (attrName in this.components) { return; }
  54571. // Initialize dependencies first
  54572. this.initComponentDependencies(componentName);
  54573. // If component name has an id we check component type multiplic
  54574. if (componentId && !COMPONENTS[componentName].multiple) {
  54575. throw new Error('Trying to initialize multiple ' +
  54576. 'components of type `' + componentName +
  54577. '`. There can only be one component of this type per entity.');
  54578. }
  54579. component = new COMPONENTS[componentName].Component(this, data, componentId);
  54580. if (this.isPlaying) { component.play(); }
  54581. // Components are reflected in the DOM as attributes but the state is not shown
  54582. // hence we set the attribute to empty string.
  54583. // The flag justInitialized is for attributeChangedCallback to not overwrite
  54584. // the component with the empty string.
  54585. if (!this.hasAttribute(attrName)) {
  54586. component.justInitialized = true;
  54587. window.HTMLElement.prototype.setAttribute.call(this, attrName, '');
  54588. }
  54589. debug('Component initialized: %s', attrName);
  54590. },
  54591. writable: window.debug
  54592. },
  54593. /**
  54594. * Initialize dependencies of a component.
  54595. *
  54596. * @param {string} name - Root component name.
  54597. */
  54598. initComponentDependencies: {
  54599. value: function (name) {
  54600. var self = this;
  54601. var component = COMPONENTS[name];
  54602. var dependencies;
  54603. var i;
  54604. // Not a component.
  54605. if (!component) { return; }
  54606. // No dependencies.
  54607. dependencies = COMPONENTS[name].dependencies;
  54608. if (!dependencies) { return; }
  54609. // Initialize dependencies.
  54610. for (i = 0; i < dependencies.length; i++) {
  54611. // Call getAttribute to initialize the data from the DOM.
  54612. self.initComponent(
  54613. dependencies[i],
  54614. window.HTMLElement.prototype.getAttribute.call(self, dependencies[i]) || undefined,
  54615. true
  54616. );
  54617. }
  54618. }
  54619. },
  54620. removeComponent: {
  54621. value: function (name, destroy) {
  54622. var component;
  54623. component = this.components[name];
  54624. if (!component) { return; }
  54625. // Wait for component to initialize.
  54626. if (!component.initialized) {
  54627. this.addEventListener('componentinitialized', function tryRemoveLater (evt) {
  54628. if (evt.detail.name !== name) { return; }
  54629. this.removeComponent(name, destroy);
  54630. this.removeEventListener('componentinitialized', tryRemoveLater);
  54631. });
  54632. return;
  54633. }
  54634. component.pause();
  54635. component.remove();
  54636. // Keep component attached to entity in case of just full entity detach.
  54637. if (destroy) {
  54638. component.destroy();
  54639. delete this.components[name];
  54640. }
  54641. this.emit('componentremoved', component.evtDetail, false);
  54642. },
  54643. writable: window.debug
  54644. },
  54645. /**
  54646. * Initialize or update all components.
  54647. * Build data using initial components, defined attributes, mixins, and defaults.
  54648. * Update default components before the rest.
  54649. *
  54650. * @member {function} getExtraComponents - Can be implemented to include component data
  54651. * from other sources (e.g., implemented by primitives).
  54652. */
  54653. updateComponents: {
  54654. value: function () {
  54655. var data;
  54656. var extraComponents;
  54657. var i;
  54658. var name;
  54659. var componentsToUpdate = this.componentsToUpdate;
  54660. if (!this.hasLoaded) { return; }
  54661. // Gather mixin-defined components.
  54662. for (i = 0; i < this.mixinEls.length; i++) {
  54663. for (name in this.mixinEls[i].componentCache) {
  54664. if (isComponent(name)) { componentsToUpdate[name] = true; }
  54665. }
  54666. }
  54667. // Gather from extra initial component data if defined (e.g., primitives).
  54668. if (this.getExtraComponents) {
  54669. extraComponents = this.getExtraComponents();
  54670. for (name in extraComponents) {
  54671. if (isComponent(name)) { componentsToUpdate[name] = true; }
  54672. }
  54673. }
  54674. // Gather entity-defined components.
  54675. for (i = 0; i < this.attributes.length; ++i) {
  54676. name = this.attributes[i].name;
  54677. if (OBJECT3D_COMPONENTS.indexOf(name) !== -1) { continue; }
  54678. if (isComponent(name)) { componentsToUpdate[name] = true; }
  54679. }
  54680. // object3D components first (position, rotation, scale, visible).
  54681. for (i = 0; i < OBJECT3D_COMPONENTS.length; i++) {
  54682. name = OBJECT3D_COMPONENTS[i];
  54683. if (!this.hasAttribute(name)) { continue; }
  54684. this.updateComponent(name, this.getDOMAttribute(name));
  54685. }
  54686. // Initialize or update rest of components.
  54687. for (name in componentsToUpdate) {
  54688. data = mergeComponentData(this.getDOMAttribute(name),
  54689. extraComponents && extraComponents[name]);
  54690. this.updateComponent(name, data);
  54691. delete componentsToUpdate[name];
  54692. }
  54693. },
  54694. writable: window.debug
  54695. },
  54696. /**
  54697. * Initialize, update, or remove a single component.
  54698. *
  54699. * When initializing, we set the component on `this.components`.
  54700. *
  54701. * @param {string} attr - Component name.
  54702. * @param {object} attrValue - Value of the DOM attribute.
  54703. * @param {boolean} clobber - If new attrValue completely replaces previous properties.
  54704. */
  54705. updateComponent: {
  54706. value: function (attr, attrValue, clobber) {
  54707. var component = this.components[attr];
  54708. if (component) {
  54709. // Remove component.
  54710. if (attrValue === null && !checkComponentDefined(this, attr)) {
  54711. this.removeComponent(attr, true);
  54712. return;
  54713. }
  54714. // Component already initialized. Update component.
  54715. component.updateProperties(attrValue, clobber);
  54716. return;
  54717. }
  54718. // Component not yet initialized. Initialize component.
  54719. this.initComponent(attr, attrValue, false);
  54720. }
  54721. },
  54722. /**
  54723. * If `attr` is a component name, detach the component from the entity.
  54724. *
  54725. * If `propertyName` is given, reset the component property value to its default.
  54726. *
  54727. * @param {string} attr - Attribute name, which could also be a component name.
  54728. * @param {string} propertyName - Component prop name, if resetting an individual prop.
  54729. */
  54730. removeAttribute: {
  54731. value: function (attr, propertyName) {
  54732. var component = this.components[attr];
  54733. // Remove component.
  54734. if (component && propertyName === undefined) {
  54735. this.removeComponent(attr, true);
  54736. }
  54737. // Reset component property value.
  54738. if (component && propertyName !== undefined) {
  54739. component.resetProperty(propertyName);
  54740. return;
  54741. }
  54742. // Remove mixins.
  54743. if (attr === 'mixin') {
  54744. this.mixinUpdate('');
  54745. }
  54746. window.HTMLElement.prototype.removeAttribute.call(this, attr);
  54747. }
  54748. },
  54749. /**
  54750. * Start dynamic behavior associated with entity such as dynamic components and animations.
  54751. * Tell all children entities to also play.
  54752. */
  54753. play: {
  54754. value: function () {
  54755. var entities;
  54756. var i;
  54757. var key;
  54758. // Already playing.
  54759. if (this.isPlaying || !this.hasLoaded) { return; }
  54760. this.isPlaying = true;
  54761. // Wake up all components.
  54762. for (key in this.components) { this.components[key].play(); }
  54763. // Tell all child entities to play.
  54764. entities = this.getChildEntities();
  54765. for (i = 0; i < entities.length; i++) { entities[i].play(); }
  54766. this.emit('play');
  54767. },
  54768. writable: true
  54769. },
  54770. /**
  54771. * Pause dynamic behavior associated with entity such as dynamic components and animations.
  54772. * Tell all children entities to also pause.
  54773. */
  54774. pause: {
  54775. value: function () {
  54776. var entities;
  54777. var i;
  54778. var key;
  54779. if (!this.isPlaying) { return; }
  54780. this.isPlaying = false;
  54781. // Sleep all components.
  54782. for (key in this.components) { this.components[key].pause(); }
  54783. // Tell all child entities to pause.
  54784. entities = this.getChildEntities();
  54785. for (i = 0; i < entities.length; i++) { entities[i].pause(); }
  54786. this.emit('pause');
  54787. },
  54788. writable: true
  54789. },
  54790. /**
  54791. * Deals with updates on entity-specific attributes (i.e., components and mixins).
  54792. *
  54793. * @param {string} attr
  54794. * @param {string} oldVal
  54795. * @param {string|object} newVal
  54796. */
  54797. setEntityAttribute: {
  54798. value: function (attr, oldVal, newVal) {
  54799. if (COMPONENTS[attr] || this.components[attr]) {
  54800. this.updateComponent(attr, newVal);
  54801. return;
  54802. }
  54803. if (attr === 'mixin') {
  54804. // Ignore if `<a-node>` code is just updating computed mixin in the DOM.
  54805. if (newVal === this.computedMixinStr) { return; }
  54806. this.mixinUpdate(newVal, oldVal);
  54807. }
  54808. }
  54809. },
  54810. /**
  54811. * When mixins updated, trigger init or optimized-update of relevant components.
  54812. */
  54813. mixinUpdate: {
  54814. value: (function () {
  54815. var componentsUpdated = [];
  54816. return function (newMixins, oldMixins) {
  54817. var component;
  54818. var mixinEl;
  54819. var mixinIds;
  54820. var i;
  54821. var self = this;
  54822. if (!this.hasLoaded) {
  54823. this.addEventListener('loaded', function () {
  54824. self.mixinUpdate(newMixins, oldMixins);
  54825. }, ONCE);
  54826. return;
  54827. }
  54828. oldMixins = oldMixins || this.getAttribute('mixin');
  54829. mixinIds = this.updateMixins(newMixins, oldMixins);
  54830. // Loop over current mixins.
  54831. componentsUpdated.length = 0;
  54832. for (i = 0; i < this.mixinEls.length; i++) {
  54833. for (component in this.mixinEls[i].componentCache) {
  54834. if (componentsUpdated.indexOf(component) === -1) {
  54835. if (this.components[component]) {
  54836. // Update. Just rebuild data.
  54837. this.components[component].handleMixinUpdate();
  54838. } else {
  54839. // Init. buildData will gather mixin values.
  54840. this.initComponent(component, null);
  54841. }
  54842. componentsUpdated.push(component);
  54843. }
  54844. }
  54845. }
  54846. // Loop over old mixins to call for data rebuild.
  54847. for (i = 0; i < mixinIds.oldMixinIds.length; i++) {
  54848. mixinEl = document.getElementById(mixinIds.oldMixinIds[i]);
  54849. if (!mixinEl) { continue; }
  54850. for (component in mixinEl.componentCache) {
  54851. if (componentsUpdated.indexOf(component) === -1) {
  54852. if (this.components[component]) {
  54853. if (this.getDOMAttribute(component)) {
  54854. // Update component if explicitly defined.
  54855. this.components[component].handleMixinUpdate();
  54856. } else {
  54857. // Remove component if not explicitly defined.
  54858. this.removeComponent(component, true);
  54859. }
  54860. }
  54861. }
  54862. }
  54863. }
  54864. };
  54865. })()
  54866. },
  54867. /**
  54868. * setAttribute can:
  54869. *
  54870. * 1. Set a single property of a multi-property component.
  54871. * 2. Set multiple properties of a multi-property component.
  54872. * 3. Replace properties of a multi-property component.
  54873. * 4. Set a value for a single-property component, mixin, or normal HTML attribute.
  54874. *
  54875. * @param {string} attrName - Component or attribute name.
  54876. * @param {*} arg1 - Can be a value, property name, CSS-style property string, or
  54877. * object of properties.
  54878. * @param {*|bool} arg2 - If arg1 is a property name, this should be a value. Otherwise,
  54879. * it is a boolean indicating whether to clobber previous values (defaults to false).
  54880. */
  54881. setAttribute: {
  54882. value: (function () {
  54883. var singlePropUpdate = {};
  54884. return function (attrName, arg1, arg2) {
  54885. var newAttrValue;
  54886. var clobber;
  54887. var componentName;
  54888. var delimiterIndex;
  54889. var isDebugMode;
  54890. var key;
  54891. delimiterIndex = attrName.indexOf(MULTIPLE_COMPONENT_DELIMITER);
  54892. componentName = delimiterIndex > 0 ? attrName.substring(0, delimiterIndex) : attrName;
  54893. // Not a component. Normal set attribute.
  54894. if (!COMPONENTS[componentName]) {
  54895. if (attrName === 'mixin') { this.mixinUpdate(arg1); }
  54896. ANode.prototype.setAttribute.call(this, attrName, arg1);
  54897. return;
  54898. }
  54899. // Initialize component first if not yet initialized.
  54900. if (!this.components[attrName] && this.hasAttribute(attrName)) {
  54901. this.updateComponent(
  54902. attrName,
  54903. window.HTMLElement.prototype.getAttribute.call(this, attrName));
  54904. }
  54905. // Determine new attributes from the arguments
  54906. if (typeof arg2 !== 'undefined' &&
  54907. typeof arg1 === 'string' &&
  54908. arg1.length > 0 &&
  54909. typeof utils.styleParser.parse(arg1) === 'string') {
  54910. // Update a single property of a multi-property component
  54911. for (key in singlePropUpdate) { delete singlePropUpdate[key]; }
  54912. newAttrValue = singlePropUpdate;
  54913. newAttrValue[arg1] = arg2;
  54914. clobber = false;
  54915. } else {
  54916. // Update with a value, object, or CSS-style property string, with the possiblity
  54917. // of clobbering previous values.
  54918. newAttrValue = arg1;
  54919. clobber = (arg2 === true);
  54920. }
  54921. // Update component
  54922. this.updateComponent(attrName, newAttrValue, clobber);
  54923. // In debug mode, write component data up to the DOM.
  54924. isDebugMode = this.sceneEl && this.sceneEl.getAttribute('debug');
  54925. if (isDebugMode) { this.components[attrName].flushToDOM(); }
  54926. };
  54927. })(),
  54928. writable: window.debug
  54929. },
  54930. /**
  54931. * Reflect component data in the DOM (as seen from the browser DOM Inspector).
  54932. *
  54933. * @param {bool} recursive - Also flushToDOM on the children.
  54934. **/
  54935. flushToDOM: {
  54936. value: function (recursive) {
  54937. var components = this.components;
  54938. var child;
  54939. var children = this.children;
  54940. var i;
  54941. var key;
  54942. // Flush entity's components to DOM.
  54943. for (key in components) {
  54944. components[key].flushToDOM();
  54945. }
  54946. // Recurse.
  54947. if (!recursive) { return; }
  54948. for (i = 0; i < children.length; ++i) {
  54949. child = children[i];
  54950. if (!child.flushToDOM) { continue; }
  54951. child.flushToDOM(recursive);
  54952. }
  54953. }
  54954. },
  54955. /**
  54956. * If `attr` is a component, returns ALL component data including applied mixins and
  54957. * defaults.
  54958. *
  54959. * If `attr` is not a component, fall back to HTML getAttribute.
  54960. *
  54961. * @param {string} attr
  54962. * @returns {object|string} Object if component, else string.
  54963. */
  54964. getAttribute: {
  54965. value: function (attr) {
  54966. // If component, return component data.
  54967. var component;
  54968. if (attr === 'position') { return this.object3D.position; }
  54969. if (attr === 'rotation') { return getRotation(this); }
  54970. if (attr === 'scale') { return this.object3D.scale; }
  54971. if (attr === 'visible') { return this.object3D.visible; }
  54972. component = this.components[attr];
  54973. if (component) { return component.data; }
  54974. return window.HTMLElement.prototype.getAttribute.call(this, attr);
  54975. },
  54976. writable: window.debug
  54977. },
  54978. /**
  54979. * If `attr` is a component, returns JUST the component data defined on the entity.
  54980. * Like a partial version of `getComputedAttribute` as returned component data
  54981. * does not include applied mixins or defaults.
  54982. *
  54983. * If `attr` is not a component, fall back to HTML getAttribute.
  54984. *
  54985. * @param {string} attr
  54986. * @returns {object|string} Object if component, else string.
  54987. */
  54988. getDOMAttribute: {
  54989. value: function (attr) {
  54990. // If cached value exists, return partial component data.
  54991. var component = this.components[attr];
  54992. if (component) { return component.attrValue; }
  54993. return window.HTMLElement.prototype.getAttribute.call(this, attr);
  54994. },
  54995. writable: window.debug
  54996. },
  54997. addState: {
  54998. value: function (state) {
  54999. if (this.is(state)) { return; }
  55000. this.states.push(state);
  55001. this.emit('stateadded', state);
  55002. }
  55003. },
  55004. removeState: {
  55005. value: function (state) {
  55006. var stateIndex = this.states.indexOf(state);
  55007. if (stateIndex === -1) { return; }
  55008. this.states.splice(stateIndex, 1);
  55009. this.emit('stateremoved', state);
  55010. }
  55011. },
  55012. /**
  55013. * Checks if the element is in a given state. e.g. el.is('alive');
  55014. * @type {string} state - Name of the state we want to check
  55015. */
  55016. is: {
  55017. value: function (state) {
  55018. return this.states.indexOf(state) !== -1;
  55019. }
  55020. },
  55021. /**
  55022. * Open Inspector to this entity.
  55023. */
  55024. inspect: {
  55025. value: function () {
  55026. this.sceneEl.components.inspector.openInspector(this);
  55027. }
  55028. },
  55029. /**
  55030. * Clean up memory and return memory to object pools.
  55031. */
  55032. destroy: {
  55033. value: function () {
  55034. var key;
  55035. if (this.parentNode) {
  55036. warn('Entity can only be destroyed if detached from scenegraph.');
  55037. return;
  55038. }
  55039. for (key in this.components) {
  55040. this.components[key].destroy();
  55041. }
  55042. }
  55043. }
  55044. });
  55045. /**
  55046. * Check if a component is *defined* for an entity, including defaults and mixins.
  55047. * Does not check whether the component has been *initialized* for an entity.
  55048. *
  55049. * @param {string} el - Entity.
  55050. * @param {string} name - Component name.
  55051. * @returns {boolean}
  55052. */
  55053. function checkComponentDefined (el, name) {
  55054. // Check if element contains the component.
  55055. if (el.components[name] && el.components[name].attrValue) { return true; }
  55056. return isComponentMixedIn(name, el.mixinEls);
  55057. }
  55058. /**
  55059. * Check if any mixins contains a component.
  55060. *
  55061. * @param {string} name - Component name.
  55062. * @param {array} mixinEls - Array of <a-mixin>s.
  55063. */
  55064. function isComponentMixedIn (name, mixinEls) {
  55065. var i;
  55066. var inMixin = false;
  55067. for (i = 0; i < mixinEls.length; ++i) {
  55068. inMixin = mixinEls[i].hasAttribute(name);
  55069. if (inMixin) { break; }
  55070. }
  55071. return inMixin;
  55072. }
  55073. /**
  55074. * Given entity defined value, merge in extra data if necessary.
  55075. * Handle both single and multi-property components.
  55076. *
  55077. * @param {string} attrValue - Entity data.
  55078. * @param extraData - Entity data from another source to merge in.
  55079. */
  55080. function mergeComponentData (attrValue, extraData) {
  55081. // Extra data not defined, just return attrValue.
  55082. if (!extraData) { return attrValue; }
  55083. // Merge multi-property data.
  55084. if (extraData.constructor === Object) {
  55085. return utils.extend(extraData, utils.styleParser.parse(attrValue || {}));
  55086. }
  55087. // Return data, precendence to the defined value.
  55088. return attrValue || extraData;
  55089. }
  55090. function isComponent (componentName) {
  55091. if (componentName.indexOf(MULTIPLE_COMPONENT_DELIMITER) !== -1) {
  55092. componentName = utils.split(componentName, MULTIPLE_COMPONENT_DELIMITER)[0];
  55093. }
  55094. if (!COMPONENTS[componentName]) { return false; }
  55095. return true;
  55096. }
  55097. function getRotation (entityEl) {
  55098. var radToDeg = THREE.Math.radToDeg;
  55099. var rotation = entityEl.object3D.rotation;
  55100. var rotationObj = entityEl.rotationObj;
  55101. rotationObj.x = radToDeg(rotation.x);
  55102. rotationObj.y = radToDeg(rotation.y);
  55103. rotationObj.z = radToDeg(rotation.z);
  55104. return rotationObj;
  55105. }
  55106. AEntity = registerElement('a-entity', {prototype: proto});
  55107. module.exports = AEntity;
  55108. },{"../lib/three":179,"../utils/":205,"./a-node":129,"./a-register-element":130,"./component":131}],128:[function(_dereq_,module,exports){
  55109. var ANode = _dereq_('./a-node');
  55110. var registerElement = _dereq_('./a-register-element').registerElement;
  55111. var components = _dereq_('./component').components;
  55112. var utils = _dereq_('../utils');
  55113. var MULTIPLE_COMPONENT_DELIMITER = '__';
  55114. /**
  55115. * @member {object} componentCache - Cache of pre-parsed values. An object where the keys
  55116. * are component names and the values are already parsed by the component.
  55117. */
  55118. module.exports = registerElement('a-mixin', {
  55119. prototype: Object.create(ANode.prototype, {
  55120. createdCallback: {
  55121. value: function () {
  55122. this.componentCache = {};
  55123. this.id = this.getAttribute('id');
  55124. this.isMixin = true;
  55125. }
  55126. },
  55127. attributeChangedCallback: {
  55128. value: function (attr, oldVal, newVal) {
  55129. this.cacheAttribute(attr, newVal);
  55130. this.updateEntities();
  55131. }
  55132. },
  55133. attachedCallback: {
  55134. value: function () {
  55135. this.sceneEl = this.closestScene();
  55136. this.cacheAttributes();
  55137. this.updateEntities();
  55138. this.load();
  55139. }
  55140. },
  55141. /**
  55142. * setAttribute that parses and caches component values.
  55143. */
  55144. setAttribute: {
  55145. value: function (attr, value) {
  55146. window.HTMLElement.prototype.setAttribute.call(this, attr, value);
  55147. this.cacheAttribute(attr, value);
  55148. }
  55149. },
  55150. /**
  55151. * If `attr` is a component, then parse the value using the schema and store it.
  55152. */
  55153. cacheAttribute: {
  55154. value: function (attr, value) {
  55155. var component;
  55156. var componentName;
  55157. // Get component data.
  55158. componentName = utils.split(attr, MULTIPLE_COMPONENT_DELIMITER)[0];
  55159. component = components[componentName];
  55160. if (!component) { return; }
  55161. if (value === undefined) {
  55162. value = window.HTMLElement.prototype.getAttribute.call(this, attr);
  55163. }
  55164. this.componentCache[attr] = component.parseAttrValueForCache(value);
  55165. }
  55166. },
  55167. /**
  55168. * If `attr` is a component, then grab pre-parsed value from the cache.
  55169. * Else do a normal getAttribute.
  55170. */
  55171. getAttribute: {
  55172. value: function (attr) {
  55173. return this.componentCache[attr] ||
  55174. window.HTMLElement.prototype.getAttribute.call(this, attr);
  55175. }
  55176. },
  55177. /**
  55178. * Parse and cache every component defined on the mixin.
  55179. */
  55180. cacheAttributes: {
  55181. value: function () {
  55182. var attributes = this.attributes;
  55183. var attrName;
  55184. var i;
  55185. for (i = 0; i < attributes.length; i++) {
  55186. attrName = attributes[i].name;
  55187. this.cacheAttribute(attrName);
  55188. }
  55189. }
  55190. },
  55191. /**
  55192. * For entities that already have been loaded by the time the mixin was attached, tell
  55193. * those entities to register the mixin and refresh their component data.
  55194. */
  55195. updateEntities: {
  55196. value: function () {
  55197. var entity;
  55198. var entities;
  55199. var i;
  55200. if (!this.sceneEl) { return; }
  55201. entities = this.sceneEl.querySelectorAll('[mixin~=' + this.id + ']');
  55202. for (i = 0; i < entities.length; i++) {
  55203. entity = entities[i];
  55204. if (!entity.hasLoaded || entity.isMixin) { continue; }
  55205. entity.mixinUpdate(this.id);
  55206. }
  55207. }
  55208. }
  55209. })
  55210. });
  55211. },{"../utils":205,"./a-node":129,"./a-register-element":130,"./component":131}],129:[function(_dereq_,module,exports){
  55212. /* global CustomEvent */
  55213. var registerElement = _dereq_('./a-register-element').registerElement;
  55214. var isNode = _dereq_('./a-register-element').isNode;
  55215. var utils = _dereq_('../utils/');
  55216. var warn = utils.debug('core:a-node:warn');
  55217. var error = utils.debug('core:a-node:error');
  55218. /**
  55219. * Base class for A-Frame that manages loading of objects.
  55220. *
  55221. * Nodes can be modified using mixins.
  55222. * Nodes emit a `loaded` event when they and their children have initialized.
  55223. */
  55224. module.exports = registerElement('a-node', {
  55225. prototype: Object.create(window.HTMLElement.prototype, {
  55226. createdCallback: {
  55227. value: function () {
  55228. this.computedMixinStr = '';
  55229. this.hasLoaded = false;
  55230. this.isNode = true;
  55231. this.mixinEls = [];
  55232. },
  55233. writable: window.debug
  55234. },
  55235. attachedCallback: {
  55236. value: function () {
  55237. var mixins;
  55238. this.sceneEl = this.closestScene();
  55239. if (!this.sceneEl) {
  55240. warn('You are attempting to attach <' + this.tagName + '> outside of an A-Frame ' +
  55241. 'scene. Append this element to `<a-scene>` instead.');
  55242. }
  55243. this.hasLoaded = false;
  55244. this.emit('nodeready', undefined, false);
  55245. if (!this.isMixin) {
  55246. mixins = this.getAttribute('mixin');
  55247. if (mixins) { this.updateMixins(mixins); }
  55248. }
  55249. },
  55250. writable: window.debug
  55251. },
  55252. /**
  55253. * Handle mixin.
  55254. */
  55255. attributeChangedCallback: {
  55256. value: function (attr, oldVal, newVal) {
  55257. // Ignore if `<a-node>` code is just updating computed mixin in the DOM.
  55258. if (newVal === this.computedMixinStr) { return; }
  55259. if (attr === 'mixin' && !this.isMixin) {
  55260. this.updateMixins(newVal, oldVal);
  55261. }
  55262. }
  55263. },
  55264. /**
  55265. * Returns the first scene by traversing up the tree starting from and
  55266. * including receiver element.
  55267. */
  55268. closestScene: {
  55269. value: function closest () {
  55270. var element = this;
  55271. while (element) {
  55272. if (element.isScene) { break; }
  55273. element = element.parentElement;
  55274. }
  55275. return element;
  55276. }
  55277. },
  55278. /**
  55279. * Returns first element matching a selector by traversing up the tree starting
  55280. * from and including receiver element.
  55281. *
  55282. * @param {string} selector - Selector of element to find.
  55283. */
  55284. closest: {
  55285. value: function closest (selector) {
  55286. var matches = this.matches || this.mozMatchesSelector ||
  55287. this.msMatchesSelector || this.oMatchesSelector || this.webkitMatchesSelector;
  55288. var element = this;
  55289. while (element) {
  55290. if (matches.call(element, selector)) { break; }
  55291. element = element.parentElement;
  55292. }
  55293. return element;
  55294. }
  55295. },
  55296. detachedCallback: {
  55297. value: function () {
  55298. this.hasLoaded = false;
  55299. }
  55300. },
  55301. /**
  55302. * Wait for children to load, if any.
  55303. * Then emit `loaded` event and set `hasLoaded`.
  55304. */
  55305. load: {
  55306. value: function (cb, childFilter) {
  55307. var children;
  55308. var childrenLoaded;
  55309. var self = this;
  55310. if (this.hasLoaded) { return; }
  55311. // Default to waiting for all nodes.
  55312. childFilter = childFilter || isNode;
  55313. // Wait for children to load (if any), then load.
  55314. children = this.getChildren();
  55315. childrenLoaded = children.filter(childFilter).map(function (child) {
  55316. return new Promise(function waitForLoaded (resolve) {
  55317. if (child.hasLoaded) { return resolve(); }
  55318. child.addEventListener('loaded', resolve);
  55319. });
  55320. });
  55321. Promise.all(childrenLoaded).then(function emitLoaded () {
  55322. self.hasLoaded = true;
  55323. if (cb) { cb(); }
  55324. self.emit('loaded', undefined, false);
  55325. }).catch(function (err) {
  55326. error('Failure loading node: ', err);
  55327. });
  55328. },
  55329. writable: true
  55330. },
  55331. getChildren: {
  55332. value: function () {
  55333. return Array.prototype.slice.call(this.children, 0);
  55334. }
  55335. },
  55336. /**
  55337. * Unregister old mixins and listeners.
  55338. * Register new mixins and listeners.
  55339. * Registering means to update `this.mixinEls` with listeners.
  55340. */
  55341. updateMixins: {
  55342. value: (function () {
  55343. var newMixinIdArray = [];
  55344. var oldMixinIdArray = [];
  55345. var mixinIds = {};
  55346. return function (newMixins, oldMixins) {
  55347. var i;
  55348. var newMixinIds;
  55349. var oldMixinIds;
  55350. newMixinIdArray.length = 0;
  55351. oldMixinIdArray.length = 0;
  55352. newMixinIds = newMixins ? utils.split(newMixins.trim(), /\s+/) : newMixinIdArray;
  55353. oldMixinIds = oldMixins ? utils.split(oldMixins.trim(), /\s+/) : oldMixinIdArray;
  55354. mixinIds.newMixinIds = newMixinIds;
  55355. mixinIds.oldMixinIds = oldMixinIds;
  55356. // Unregister old mixins.
  55357. for (i = 0; i < oldMixinIds.length; i++) {
  55358. if (newMixinIds.indexOf(oldMixinIds[i]) === -1) {
  55359. this.unregisterMixin(oldMixinIds[i]);
  55360. }
  55361. }
  55362. // Register new mixins.
  55363. this.computedMixinStr = '';
  55364. this.mixinEls.length = 0;
  55365. for (i = 0; i < newMixinIds.length; i++) {
  55366. this.registerMixin(document.getElementById(newMixinIds[i]));
  55367. }
  55368. // Update DOM. Keep track of `computedMixinStr` to not recurse back here after
  55369. // update.
  55370. if (this.computedMixinStr) {
  55371. this.computedMixinStr = this.computedMixinStr.trim();
  55372. window.HTMLElement.prototype.setAttribute.call(this, 'mixin',
  55373. this.computedMixinStr);
  55374. }
  55375. return mixinIds;
  55376. };
  55377. })()
  55378. },
  55379. /**
  55380. * From mixin ID, add mixin element to `mixinEls`.
  55381. *
  55382. * @param {Element} mixinEl
  55383. */
  55384. registerMixin: {
  55385. value: function (mixinEl) {
  55386. var compositedMixinIds;
  55387. var i;
  55388. var mixin;
  55389. if (!mixinEl) { return; }
  55390. // Register composited mixins (if mixin has mixins).
  55391. mixin = mixinEl.getAttribute('mixin');
  55392. if (mixin) {
  55393. compositedMixinIds = utils.split(mixin.trim(), /\s+/);
  55394. for (i = 0; i < compositedMixinIds.length; i++) {
  55395. this.registerMixin(document.getElementById(compositedMixinIds[i]));
  55396. }
  55397. }
  55398. // Register mixin.
  55399. this.computedMixinStr = this.computedMixinStr + ' ' + mixinEl.id;
  55400. this.mixinEls.push(mixinEl);
  55401. }
  55402. },
  55403. setAttribute: {
  55404. value: function (attr, newValue) {
  55405. if (attr === 'mixin') { this.updateMixins(newValue); }
  55406. window.HTMLElement.prototype.setAttribute.call(this, attr, newValue);
  55407. }
  55408. },
  55409. unregisterMixin: {
  55410. value: function (mixinId) {
  55411. var i;
  55412. var mixinEls = this.mixinEls;
  55413. var mixinEl;
  55414. for (i = 0; i < mixinEls.length; ++i) {
  55415. mixinEl = mixinEls[i];
  55416. if (mixinId === mixinEl.id) {
  55417. mixinEls.splice(i, 1);
  55418. break;
  55419. }
  55420. }
  55421. }
  55422. },
  55423. /**
  55424. * Emit a DOM event.
  55425. *
  55426. * @param {string} name - Name of event.
  55427. * @param {object} [detail={}] - Custom data to pass as `detail` to the event.
  55428. * @param {boolean} [bubbles=true] - Whether the event should bubble.
  55429. * @param {object} [extraData] - Extra data to pass to the event, if any.
  55430. */
  55431. emit: {
  55432. value: (function () {
  55433. var data = {};
  55434. return function (name, detail, bubbles, extraData) {
  55435. if (bubbles === undefined) { bubbles = true; }
  55436. data.bubbles = !!bubbles;
  55437. data.detail = detail;
  55438. // If extra data is present, we need to create a new object.
  55439. if (extraData) { data = utils.extend({}, extraData, data); }
  55440. this.dispatchEvent(new CustomEvent(name, data));
  55441. };
  55442. })(),
  55443. writable: window.debug
  55444. }
  55445. })
  55446. });
  55447. },{"../utils/":205,"./a-register-element":130}],130:[function(_dereq_,module,exports){
  55448. /*
  55449. ------------------------------------------------------------
  55450. ------------- WARNING WARNING WARNING WARNING --------------
  55451. ------------------------------------------------------------
  55452. This module wraps registerElement to deal with components that inherit from
  55453. `ANode` and `AEntity`. It's a pass through in any other case.
  55454. It wraps some of the prototype methods of the created element to make sure
  55455. that the corresponding functions in the base prototypes (`AEntity` and `ANode`)
  55456. are also invoked. The method in the base prototype is always called before the one
  55457. in the derived prototype.
  55458. */
  55459. // Polyfill `document.registerElement`.
  55460. _dereq_('document-register-element');
  55461. var ANode; // Must declare before AEntity. Initialized at the bottom.
  55462. var AEntity;
  55463. var knownTags = module.exports.knownTags = {};
  55464. function addTagName (tagName) {
  55465. knownTags[tagName.toLowerCase()] = true;
  55466. }
  55467. /**
  55468. * Return whether the element type is one of our known registered ones.
  55469. *
  55470. * @param {string} node - The name of the tag to register.
  55471. * @returns {boolean} Whether the tag name matches that of our registered custom elements.
  55472. */
  55473. module.exports.isNode = function (node) {
  55474. return node.tagName.toLowerCase() in knownTags || node.isNode;
  55475. };
  55476. /**
  55477. * @param {string} tagName - The name of the tag to register.
  55478. * @param {object} obj - The prototype of the new element.
  55479. * @returns {object} The prototype of the new element.
  55480. */
  55481. module.exports.registerElement = function (tagName, obj) {
  55482. var proto = Object.getPrototypeOf(obj.prototype);
  55483. var newObj = obj;
  55484. var isANode = ANode && proto === ANode.prototype;
  55485. var isAEntity = AEntity && proto === AEntity.prototype;
  55486. if (isANode || isAEntity) { addTagName(tagName); }
  55487. // Wrap if element inherits from `ANode`.
  55488. if (isANode) {
  55489. newObj = wrapANodeMethods(obj.prototype);
  55490. newObj = {prototype: Object.create(proto, newObj)};
  55491. }
  55492. // Wrap if element inherits from `AEntity`.
  55493. if (isAEntity) {
  55494. newObj = wrapAEntityMethods(obj.prototype);
  55495. newObj = {prototype: Object.create(proto, newObj)};
  55496. }
  55497. // Give all functions their proper name.
  55498. Object.getOwnPropertyNames(newObj.prototype).forEach(function (propName) {
  55499. var propVal = newObj.prototype[propName];
  55500. if (typeof propVal === 'function') {
  55501. propVal.displayName = propName;
  55502. }
  55503. });
  55504. return document.registerElement(tagName, newObj);
  55505. };
  55506. /**
  55507. * Wrap some obj methods to call those on `ANode` base prototype.
  55508. *
  55509. * @param {object} obj - Object that contains the methods that will be wrapped.
  55510. * @return {object} An object with the same properties as the input parameter but
  55511. * with some of methods wrapped.
  55512. */
  55513. function wrapANodeMethods (obj) {
  55514. var newObj = {};
  55515. var ANodeMethods = [
  55516. 'attachedCallback',
  55517. 'attributeChangedCallback',
  55518. 'createdCallback',
  55519. 'detachedCallback'
  55520. ];
  55521. wrapMethods(newObj, ANodeMethods, obj, ANode.prototype);
  55522. copyProperties(obj, newObj);
  55523. return newObj;
  55524. }
  55525. /**
  55526. * This wraps some of the obj methods to call those on `AEntity` base prototype.
  55527. *
  55528. * @param {object} obj - The objects that contains the methods that will be wrapped.
  55529. * @return {object} - An object with the same properties as the input parameter but
  55530. * with some of methods wrapped.
  55531. */
  55532. function wrapAEntityMethods (obj) {
  55533. var newObj = {};
  55534. var ANodeMethods = [
  55535. 'attachedCallback',
  55536. 'attributeChangedCallback',
  55537. 'createdCallback',
  55538. 'detachedCallback'
  55539. ];
  55540. var AEntityMethods = [
  55541. 'attachedCallback',
  55542. 'attributeChangedCallback',
  55543. 'createdCallback',
  55544. 'detachedCallback'
  55545. ];
  55546. wrapMethods(newObj, ANodeMethods, obj, ANode.prototype);
  55547. wrapMethods(newObj, AEntityMethods, obj, AEntity.prototype);
  55548. // Copies the remaining properties into the new object.
  55549. copyProperties(obj, newObj);
  55550. return newObj;
  55551. }
  55552. /**
  55553. * Wrap a list a methods to ensure that those in the base prototype are called
  55554. * before the derived one.
  55555. *
  55556. * @param {object} targetObj - Object that will contain the wrapped methods.
  55557. * @param {array} methodList - List of methods from the derivedObj that will be wrapped.
  55558. * @param {object} derivedObject - Object that inherits from the baseObj.
  55559. * @param {object} baseObj - Object that derivedObj inherits from.
  55560. */
  55561. function wrapMethods (targetObj, methodList, derivedObj, baseObj) {
  55562. methodList.forEach(function (methodName) {
  55563. wrapMethod(targetObj, methodName, derivedObj, baseObj);
  55564. });
  55565. }
  55566. module.exports.wrapMethods = wrapMethods;
  55567. /**
  55568. * Wrap one method to ensure that the one in the base prototype is called before
  55569. * the one in the derived one.
  55570. *
  55571. * @param {object} obj - Object that will contain the wrapped method.
  55572. * @param {string} methodName - The name of the method that will be wrapped.
  55573. * @param {object} derivedObject - Object that inherits from the baseObj.
  55574. * @param {object} baseObj - Object that derivedObj inherits from.
  55575. */
  55576. function wrapMethod (obj, methodName, derivedObj, baseObj) {
  55577. var derivedMethod = derivedObj[methodName];
  55578. var baseMethod = baseObj[methodName];
  55579. // Derived prototype does not define method, no need to wrap.
  55580. if (!derivedMethod || !baseMethod) { return; }
  55581. // Derived prototype doesn't override the one in the base one, no need to wrap.
  55582. if (derivedMethod === baseMethod) { return; }
  55583. // Wrap to ensure the base method is called before the one in the derived prototype.
  55584. obj[methodName] = {
  55585. value: function wrappedMethod () {
  55586. baseMethod.apply(this, arguments);
  55587. return derivedMethod.apply(this, arguments);
  55588. },
  55589. writable: window.debug
  55590. };
  55591. }
  55592. /**
  55593. * It copies the properties from source to destination object if they don't
  55594. * exist already.
  55595. *
  55596. * @param {object} source - The object where properties are copied from.
  55597. * @param {type} destination - The object where properties are copied to.
  55598. */
  55599. function copyProperties (source, destination) {
  55600. var props = Object.getOwnPropertyNames(source);
  55601. props.forEach(function (prop) {
  55602. var desc;
  55603. if (!destination[prop]) {
  55604. desc = Object.getOwnPropertyDescriptor(source, prop);
  55605. destination[prop] = {value: source[prop], writable: desc.writable};
  55606. }
  55607. });
  55608. }
  55609. ANode = _dereq_('./a-node');
  55610. AEntity = _dereq_('./a-entity');
  55611. },{"./a-entity":127,"./a-node":129,"document-register-element":12}],131:[function(_dereq_,module,exports){
  55612. /* global Node */
  55613. var schema = _dereq_('./schema');
  55614. var scenes = _dereq_('./scene/scenes');
  55615. var systems = _dereq_('./system');
  55616. var utils = _dereq_('../utils/');
  55617. var components = module.exports.components = {}; // Keep track of registered components.
  55618. var parseProperties = schema.parseProperties;
  55619. var parseProperty = schema.parseProperty;
  55620. var processSchema = schema.process;
  55621. var isSingleProp = schema.isSingleProperty;
  55622. var stringifyProperties = schema.stringifyProperties;
  55623. var stringifyProperty = schema.stringifyProperty;
  55624. var styleParser = utils.styleParser;
  55625. var warn = utils.debug('core:component:warn');
  55626. var aframeScript = document.currentScript;
  55627. var upperCaseRegExp = new RegExp('[A-Z]+');
  55628. // Object pools by component, created upon registration.
  55629. var objectPools = {};
  55630. /**
  55631. * Component class definition.
  55632. *
  55633. * Components configure appearance, modify behavior, or add functionality to
  55634. * entities. The behavior and appearance of an entity can be changed at runtime
  55635. * by adding, removing, or updating components. Entities do not share instances
  55636. * of components.
  55637. *
  55638. * @member {object} el - Reference to the entity element.
  55639. * @member {string} attrValue - Value of the corresponding HTML attribute.
  55640. * @member {object} data - Component data populated by parsing the
  55641. * mapped attribute of the component plus applying defaults and mixins.
  55642. */
  55643. var Component = module.exports.Component = function (el, attrValue, id) {
  55644. var self = this;
  55645. this.el = el;
  55646. this.id = id;
  55647. this.attrName = this.name + (id ? '__' + id : '');
  55648. this.evtDetail = {id: this.id, name: this.name};
  55649. this.initialized = false;
  55650. this.isSingleProperty = isSingleProp(this.schema);
  55651. this.isSinglePropertyObject = this.isSingleProperty &&
  55652. isObject(parseProperty(undefined, this.schema)) &&
  55653. !(this.schema.default instanceof window.HTMLElement);
  55654. this.isObjectBased = !this.isSingleProperty || this.isSinglePropertyObject;
  55655. this.el.components[this.attrName] = this;
  55656. this.objectPool = objectPools[this.name];
  55657. const events = this.events;
  55658. this.events = {};
  55659. eventsBind(this, events);
  55660. // Store component data from previous update call.
  55661. this.attrValue = undefined;
  55662. if (this.isObjectBased) {
  55663. this.nextData = this.objectPool.use();
  55664. // Drop any properties added by dynamic schemas in previous use
  55665. utils.objectPool.removeUnusedKeys(this.nextData, this.schema);
  55666. this.oldData = this.objectPool.use();
  55667. utils.objectPool.removeUnusedKeys(this.oldData, this.schema);
  55668. this.previousOldData = this.objectPool.use();
  55669. utils.objectPool.removeUnusedKeys(this.previousOldData, this.schema);
  55670. this.parsingAttrValue = this.objectPool.use();
  55671. utils.objectPool.removeUnusedKeys(this.parsingAttrValue, this.schema);
  55672. } else {
  55673. this.nextData = undefined;
  55674. this.oldData = undefined;
  55675. this.previousOldData = undefined;
  55676. this.parsingAttrValue = undefined;
  55677. }
  55678. // Last value passed to updateProperties.
  55679. this.throttledEmitComponentChanged = utils.throttle(function emitChange () {
  55680. el.emit('componentchanged', self.evtDetail, false);
  55681. }, 200);
  55682. this.updateProperties(attrValue);
  55683. };
  55684. Component.prototype = {
  55685. /**
  55686. * Contains the type schema and defaults for the data values.
  55687. * Data is coerced into the types of the values of the defaults.
  55688. */
  55689. schema: {},
  55690. /**
  55691. * Init handler. Similar to attachedCallback.
  55692. * Called during component initialization and is only run once.
  55693. * Components can use this to set initial state.
  55694. */
  55695. init: function () { /* no-op */ },
  55696. /**
  55697. * Map of event names to binded event handlers that will be lifecycle-handled.
  55698. * Will be detached on pause / remove.
  55699. * Will be attached on play.
  55700. */
  55701. events: {},
  55702. /**
  55703. * Update handler. Similar to attributeChangedCallback.
  55704. * Called whenever component's data changes.
  55705. * Also called on component initialization when the component receives initial data.
  55706. *
  55707. * @param {object} prevData - Previous attributes of the component.
  55708. */
  55709. update: function (prevData) { /* no-op */ },
  55710. updateSchema: undefined,
  55711. /**
  55712. * Tick handler.
  55713. * Called on each tick of the scene render loop.
  55714. * Affected by play and pause.
  55715. *
  55716. * @param {number} time - Scene tick time.
  55717. * @param {number} timeDelta - Difference in current render time and previous render time.
  55718. */
  55719. tick: undefined,
  55720. /**
  55721. * Tock handler.
  55722. * Called on each tock of the scene render loop.
  55723. * Affected by play and pause.
  55724. *
  55725. * @param {number} time - Scene tick time.
  55726. * @param {number} timeDelta - Difference in current render time and previous render time.
  55727. * @param {object} camera - Camera used to render the last frame.
  55728. */
  55729. tock: undefined,
  55730. /**
  55731. * Called to start any dynamic behavior (e.g., animation, AI, events, physics).
  55732. */
  55733. play: function () { /* no-op */ },
  55734. /**
  55735. * Called to stop any dynamic behavior (e.g., animation, AI, events, physics).
  55736. */
  55737. pause: function () { /* no-op */ },
  55738. /**
  55739. * Remove handler. Similar to detachedCallback.
  55740. * Called whenever component is removed from the entity (i.e., removeAttribute).
  55741. * Components can use this to reset behavior on the entity.
  55742. */
  55743. remove: function () { /* no-op */ },
  55744. /**
  55745. * Parses each property based on property type.
  55746. * If component is single-property, then parses the single property value.
  55747. *
  55748. * @param {string} value - HTML attribute value.
  55749. * @param {boolean} silent - Suppress warning messages.
  55750. * @returns {object} Component data.
  55751. */
  55752. parse: function (value, silent) {
  55753. var schema = this.schema;
  55754. if (this.isSingleProperty) { return parseProperty(value, schema); }
  55755. return parseProperties(styleParser.parse(value), schema, true, this.name, silent);
  55756. },
  55757. /**
  55758. * Stringify properties if necessary.
  55759. *
  55760. * Only called from `Entity.setAttribute` for properties whose parsers accept a non-string
  55761. * value (e.g., selector, vec3 property types).
  55762. *
  55763. * @param {object} data - Complete component data.
  55764. * @returns {string}
  55765. */
  55766. stringify: function (data) {
  55767. var schema = this.schema;
  55768. if (typeof data === 'string') { return data; }
  55769. if (this.isSingleProperty) { return stringifyProperty(data, schema); }
  55770. data = stringifyProperties(data, schema);
  55771. return styleParser.stringify(data);
  55772. },
  55773. /**
  55774. * Update the cache of the pre-parsed attribute value.
  55775. *
  55776. * @param {string} value - New data.
  55777. * @param {boolean } clobber - Whether to wipe out and replace previous data.
  55778. */
  55779. updateCachedAttrValue: function (value, clobber) {
  55780. var newAttrValue;
  55781. var tempObject;
  55782. var property;
  55783. if (value === undefined) { return; }
  55784. // If null value is the new attribute value, make the attribute value falsy.
  55785. if (value === null) {
  55786. if (this.isObjectBased && this.attrValue) {
  55787. this.objectPool.recycle(this.attrValue);
  55788. }
  55789. this.attrValue = undefined;
  55790. return;
  55791. }
  55792. if (value instanceof Object && !(value instanceof window.HTMLElement)) {
  55793. // If value is an object, copy it to our pooled newAttrValue object to use to update
  55794. // the attrValue.
  55795. tempObject = this.objectPool.use();
  55796. newAttrValue = utils.extend(tempObject, value);
  55797. } else {
  55798. newAttrValue = this.parseAttrValueForCache(value);
  55799. }
  55800. // Merge new data with previous `attrValue` if updating and not clobbering.
  55801. if (this.isObjectBased && !clobber && this.attrValue) {
  55802. for (property in this.attrValue) {
  55803. if (newAttrValue[property] === undefined) {
  55804. newAttrValue[property] = this.attrValue[property];
  55805. }
  55806. }
  55807. }
  55808. // Update attrValue.
  55809. if (this.isObjectBased && !this.attrValue) {
  55810. this.attrValue = this.objectPool.use();
  55811. }
  55812. utils.objectPool.clearObject(this.attrValue);
  55813. this.attrValue = extendProperties(this.attrValue, newAttrValue, this.isObjectBased);
  55814. utils.objectPool.clearObject(tempObject);
  55815. },
  55816. /**
  55817. * Given an HTML attribute value parses the string based on the component schema.
  55818. * To avoid double parsings of strings into strings we store the original instead
  55819. * of the parsed one
  55820. *
  55821. * @param {string} value - HTML attribute value
  55822. */
  55823. parseAttrValueForCache: function (value) {
  55824. var parsedValue;
  55825. if (typeof value !== 'string') { return value; }
  55826. if (this.isSingleProperty) {
  55827. parsedValue = this.schema.parse(value);
  55828. /**
  55829. * To avoid bogus double parsings. Cached values will be parsed when building
  55830. * component data. For instance when parsing a src id to its url, we want to cache
  55831. * original string and not the parsed one (#monster -> models/monster.dae)
  55832. * so when building data we parse the expected value.
  55833. */
  55834. if (typeof parsedValue === 'string') { parsedValue = value; }
  55835. } else {
  55836. // Parse using the style parser to avoid double parsing of individual properties.
  55837. utils.objectPool.clearObject(this.parsingAttrValue);
  55838. parsedValue = styleParser.parse(value, this.parsingAttrValue);
  55839. }
  55840. return parsedValue;
  55841. },
  55842. /**
  55843. * Write cached attribute data to the entity DOM element.
  55844. *
  55845. * @param {boolean} isDefault - Whether component is a default component. Always flush for
  55846. * default components.
  55847. */
  55848. flushToDOM: function (isDefault) {
  55849. var attrValue = isDefault ? this.data : this.attrValue;
  55850. if (attrValue === null || attrValue === undefined) { return; }
  55851. window.HTMLElement.prototype.setAttribute.call(this.el, this.attrName,
  55852. this.stringify(attrValue));
  55853. },
  55854. /**
  55855. * Apply new component data if data has changed (from setAttribute).
  55856. *
  55857. * @param {string} attrValue - HTML attribute value.
  55858. * If undefined, use the cached attribute value and continue updating properties.
  55859. * @param {boolean} clobber - The previous component data is overwritten by the atrrValue
  55860. */
  55861. updateProperties: function (attrValue, clobber) {
  55862. var el = this.el;
  55863. // Just cache the attribute if the entity has not loaded
  55864. // Components are not initialized until the entity has loaded
  55865. if (!el.hasLoaded) {
  55866. this.updateCachedAttrValue(attrValue);
  55867. return;
  55868. }
  55869. // Parse the attribute value.
  55870. // Cache current attrValue for future updates. Updates `this.attrValue`.
  55871. // `null` means no value on purpose, do not set a default value, let mixins take over.
  55872. if (attrValue !== null) {
  55873. attrValue = this.parseAttrValueForCache(attrValue);
  55874. }
  55875. // Cache current attrValue for future updates.
  55876. this.updateCachedAttrValue(attrValue, clobber);
  55877. if (this.initialized) {
  55878. this.updateComponent(attrValue, clobber);
  55879. this.callUpdateHandler();
  55880. } else {
  55881. this.initComponent();
  55882. }
  55883. },
  55884. initComponent: function () {
  55885. var el = this.el;
  55886. var initialOldData;
  55887. // Build data.
  55888. if (this.updateSchema) { this.updateSchema(this.buildData(this.attrValue, false, true)); }
  55889. this.data = this.buildData(this.attrValue);
  55890. // Component is being already initialized.
  55891. if (el.initializingComponents[this.name]) { return; }
  55892. // Prevent infinite loop in case of init method setting same component on the entity.
  55893. el.initializingComponents[this.name] = true;
  55894. // Initialize component.
  55895. this.init();
  55896. this.initialized = true;
  55897. delete el.initializingComponents[this.name];
  55898. // Store current data as previous data for future updates.
  55899. this.oldData = extendProperties(this.oldData, this.data, this.isObjectBased);
  55900. // For oldData, pass empty object to multiple-prop schemas or object single-prop schema.
  55901. // Pass undefined to rest of types.
  55902. initialOldData = this.isObjectBased ? this.objectPool.use() : undefined;
  55903. this.update(initialOldData);
  55904. if (this.isObjectBased) { this.objectPool.recycle(initialOldData); }
  55905. // Play the component if the entity is playing.
  55906. if (el.isPlaying) { this.play(); }
  55907. el.emit('componentinitialized', this.evtDetail, false);
  55908. },
  55909. /**
  55910. * @param attrValue - Passed argument from setAttribute.
  55911. */
  55912. updateComponent: function (attrValue, clobber) {
  55913. var key;
  55914. var mayNeedSchemaUpdate;
  55915. if (clobber) {
  55916. // Clobber. Rebuild.
  55917. if (this.updateSchema) {
  55918. this.updateSchema(this.buildData(this.attrValue, true, true));
  55919. }
  55920. this.data = this.buildData(this.attrValue, true, false);
  55921. return;
  55922. }
  55923. // Apply new value to this.data in place since direct update.
  55924. if (this.isSingleProperty) {
  55925. if (this.isObjectBased) {
  55926. parseProperty(attrValue, this.schema);
  55927. }
  55928. // Single-property (already parsed).
  55929. this.data = attrValue;
  55930. return;
  55931. }
  55932. parseProperties(attrValue, this.schema, true, this.name);
  55933. // Check if we need to update schema.
  55934. if (this.schemaChangeKeys.length) {
  55935. for (key in attrValue) {
  55936. if (this.schema[key].schemaChange) {
  55937. mayNeedSchemaUpdate = true;
  55938. break;
  55939. }
  55940. }
  55941. }
  55942. if (mayNeedSchemaUpdate) {
  55943. // Rebuild data if need schema update.
  55944. if (this.updateSchema) {
  55945. this.updateSchema(this.buildData(this.attrValue, true, true));
  55946. }
  55947. this.data = this.buildData(this.attrValue, true, false);
  55948. return;
  55949. }
  55950. // Normal update.
  55951. for (key in attrValue) {
  55952. if (attrValue[key] === undefined) { continue; }
  55953. this.data[key] = attrValue[key];
  55954. }
  55955. },
  55956. /**
  55957. * Check if component should fire update and fire update lifecycle handler.
  55958. */
  55959. callUpdateHandler: function () {
  55960. var hasComponentChanged;
  55961. // Store the previous old data before we calculate the new oldData.
  55962. if (this.previousOldData instanceof Object) {
  55963. utils.objectPool.clearObject(this.previousOldData);
  55964. }
  55965. if (this.isObjectBased) {
  55966. copyData(this.previousOldData, this.oldData);
  55967. } else {
  55968. this.previousOldData = this.oldData;
  55969. }
  55970. hasComponentChanged = !utils.deepEqual(this.oldData, this.data);
  55971. // Don't update if properties haven't changed.
  55972. // Always update rotation, position, scale.
  55973. if (!this.isPositionRotationScale && !hasComponentChanged) { return; }
  55974. // Store current data as previous data for future updates.
  55975. // Reuse `this.oldData` object to try not to allocate another one.
  55976. if (this.oldData instanceof Object) { utils.objectPool.clearObject(this.oldData); }
  55977. this.oldData = extendProperties(this.oldData, this.data, this.isObjectBased);
  55978. // Update component with the previous old data.
  55979. this.update(this.previousOldData);
  55980. this.throttledEmitComponentChanged();
  55981. },
  55982. handleMixinUpdate: function () {
  55983. this.data = this.buildData(this.attrValue);
  55984. this.callUpdateHandler();
  55985. },
  55986. /**
  55987. * Reset value of a property to the property's default value.
  55988. * If single-prop component, reset value to component's default value.
  55989. *
  55990. * @param {string} propertyName - Name of property to reset.
  55991. */
  55992. resetProperty: function (propertyName) {
  55993. if (this.isObjectBased) {
  55994. if (!(propertyName in this.attrValue)) { return; }
  55995. delete this.attrValue[propertyName];
  55996. this.data[propertyName] = this.schema[propertyName].default;
  55997. } else {
  55998. this.attrValue = this.schema.default;
  55999. this.data = this.schema.default;
  56000. }
  56001. this.updateProperties(this.attrValue);
  56002. },
  56003. /**
  56004. * Extend schema of component given a partial schema.
  56005. *
  56006. * Some components might want to mutate their schema based on certain properties.
  56007. * e.g., Material component changes its schema based on `shader` to account for different
  56008. * uniforms
  56009. *
  56010. * @param {object} schemaAddon - Schema chunk that extend base schema.
  56011. */
  56012. extendSchema: function (schemaAddon) {
  56013. var extendedSchema;
  56014. // Clone base schema.
  56015. extendedSchema = utils.extend({}, components[this.name].schema);
  56016. // Extend base schema with new schema chunk.
  56017. utils.extend(extendedSchema, schemaAddon);
  56018. this.schema = processSchema(extendedSchema);
  56019. this.el.emit('schemachanged', this.evtDetail);
  56020. },
  56021. /**
  56022. * Build component data from the current state of the entity.data.
  56023. *
  56024. * Precedence:
  56025. * 1. Defaults data
  56026. * 2. Mixin data.
  56027. * 3. Attribute data.
  56028. *
  56029. * Finally coerce the data to the types of the defaults.
  56030. *
  56031. * @param {object} newData - Element new data.
  56032. * @param {boolean} clobber - The previous data is completely replaced by the new one.
  56033. * @param {boolean} silent - Suppress warning messages.
  56034. * @return {object} The component data
  56035. */
  56036. buildData: function (newData, clobber, silent) {
  56037. var componentDefined;
  56038. var data;
  56039. var defaultValue;
  56040. var key;
  56041. var mixinData;
  56042. var nextData = this.nextData;
  56043. var schema = this.schema;
  56044. var i;
  56045. var mixinEls = this.el.mixinEls;
  56046. var previousData;
  56047. // Whether component has a defined value. For arrays, treat empty as not defined.
  56048. componentDefined = newData && newData.constructor === Array
  56049. ? newData.length
  56050. : newData !== undefined && newData !== null;
  56051. if (this.isObjectBased) { utils.objectPool.clearObject(nextData); }
  56052. // 1. Gather default values (lowest precendence).
  56053. if (this.isSingleProperty) {
  56054. if (this.isObjectBased) {
  56055. // If object-based single-prop, then copy over the data to our pooled object.
  56056. data = copyData(nextData, schema.default);
  56057. } else {
  56058. // If is plain single-prop, copy by value the default.
  56059. data = isObjectOrArray(schema.default)
  56060. ? utils.clone(schema.default)
  56061. : schema.default;
  56062. }
  56063. } else {
  56064. // Preserve previously set properties if clobber not enabled.
  56065. previousData = !clobber && this.attrValue;
  56066. // Clone default value if object so components don't share object
  56067. data = previousData instanceof Object
  56068. ? copyData(nextData, previousData)
  56069. : nextData;
  56070. // Apply defaults.
  56071. for (key in schema) {
  56072. defaultValue = schema[key].default;
  56073. if (data[key] !== undefined) { continue; }
  56074. // Clone default value if object so components don't share object
  56075. data[key] = isObjectOrArray(defaultValue)
  56076. ? utils.clone(defaultValue)
  56077. : defaultValue;
  56078. }
  56079. }
  56080. // 2. Gather mixin values.
  56081. for (i = 0; i < mixinEls.length; i++) {
  56082. mixinData = mixinEls[i].getAttribute(this.attrName);
  56083. if (!mixinData) { continue; }
  56084. data = extendProperties(data, mixinData, this.isObjectBased);
  56085. }
  56086. // 3. Gather attribute values (highest precendence).
  56087. if (componentDefined) {
  56088. if (this.isSingleProperty) {
  56089. // If object-based, copy the value to not modify the original.
  56090. if (isObject(newData)) {
  56091. copyData(this.parsingAttrValue, newData);
  56092. return parseProperty(this.parsingAttrValue, schema);
  56093. }
  56094. return parseProperty(newData, schema);
  56095. }
  56096. data = extendProperties(data, newData, this.isObjectBased);
  56097. } else {
  56098. // Parse and coerce using the schema.
  56099. if (this.isSingleProperty) { return parseProperty(data, schema); }
  56100. }
  56101. return parseProperties(data, schema, undefined, this.name, silent);
  56102. },
  56103. /**
  56104. * Attach events from component-defined events map.
  56105. */
  56106. eventsAttach: function () {
  56107. var eventName;
  56108. // Safety detach to prevent double-registration.
  56109. this.eventsDetach();
  56110. for (eventName in this.events) {
  56111. this.el.addEventListener(eventName, this.events[eventName]);
  56112. }
  56113. },
  56114. /**
  56115. * Detach events from component-defined events map.
  56116. */
  56117. eventsDetach: function () {
  56118. var eventName;
  56119. for (eventName in this.events) {
  56120. this.el.removeEventListener(eventName, this.events[eventName]);
  56121. }
  56122. },
  56123. /**
  56124. * Release and free memory.
  56125. */
  56126. destroy: function () {
  56127. this.objectPool.recycle(this.attrValue);
  56128. this.objectPool.recycle(this.oldData);
  56129. this.objectPool.recycle(this.parsingAttrValue);
  56130. this.attrValue = this.oldData = this.parsingAttrValue = undefined;
  56131. }
  56132. };
  56133. function eventsBind (component, events) {
  56134. var eventName;
  56135. for (eventName in events) {
  56136. component.events[eventName] = events[eventName].bind(component);
  56137. }
  56138. }
  56139. // For testing.
  56140. if (window.debug) {
  56141. var registrationOrderWarnings = module.exports.registrationOrderWarnings = {};
  56142. }
  56143. /**
  56144. * Register a component to A-Frame.
  56145. *
  56146. * @param {string} name - Component name.
  56147. * @param {object} definition - Component schema and lifecycle method handlers.
  56148. * @returns {object} Component.
  56149. */
  56150. module.exports.registerComponent = function (name, definition) {
  56151. var NewComponent;
  56152. var propertyName;
  56153. var proto = {};
  56154. var schema;
  56155. var schemaIsSingleProp;
  56156. // Warning if component is statically registered after the scene.
  56157. if (document.currentScript && document.currentScript !== aframeScript) {
  56158. scenes.forEach(function checkPosition (sceneEl) {
  56159. // Okay to register component after the scene at runtime.
  56160. if (sceneEl.hasLoaded) { return; }
  56161. // Check that component is declared before the scene.
  56162. if (document.currentScript.compareDocumentPosition(sceneEl) ===
  56163. Node.DOCUMENT_POSITION_FOLLOWING) { return; }
  56164. warn('The component `' + name + '` was registered in a <script> tag after the scene. ' +
  56165. 'Component <script> tags in an HTML file should be declared *before* the scene ' +
  56166. 'such that the component is available to entities during scene initialization.');
  56167. // For testing.
  56168. if (window.debug) { registrationOrderWarnings[name] = true; }
  56169. });
  56170. }
  56171. if (upperCaseRegExp.test(name) === true) {
  56172. warn('The component name `' + name + '` contains uppercase characters, but ' +
  56173. 'HTML will ignore the capitalization of attribute names. ' +
  56174. 'Change the name to be lowercase: `' + name.toLowerCase() + '`');
  56175. }
  56176. if (name.indexOf('__') !== -1) {
  56177. throw new Error('The component name `' + name + '` is not allowed. ' +
  56178. 'The sequence __ (double underscore) is reserved to specify an id' +
  56179. ' for multiple components of the same type');
  56180. }
  56181. // Format definition object to prototype object.
  56182. Object.keys(definition).forEach(function (key) {
  56183. proto[key] = {
  56184. value: definition[key],
  56185. writable: true
  56186. };
  56187. });
  56188. if (components[name]) {
  56189. throw new Error('The component `' + name + '` has been already registered. ' +
  56190. 'Check that you are not loading two versions of the same component ' +
  56191. 'or two different components of the same name.');
  56192. }
  56193. NewComponent = function (el, attr, id) {
  56194. Component.call(this, el, attr, id);
  56195. };
  56196. NewComponent.prototype = Object.create(Component.prototype, proto);
  56197. NewComponent.prototype.name = name;
  56198. NewComponent.prototype.isPositionRotationScale =
  56199. name === 'position' || name === 'rotation' || name === 'scale';
  56200. NewComponent.prototype.constructor = NewComponent;
  56201. NewComponent.prototype.system = systems && systems.systems[name];
  56202. NewComponent.prototype.play = wrapPlay(NewComponent.prototype.play);
  56203. NewComponent.prototype.pause = wrapPause(NewComponent.prototype.pause);
  56204. schema = utils.extend(processSchema(NewComponent.prototype.schema,
  56205. NewComponent.prototype.name));
  56206. schemaIsSingleProp = isSingleProp(NewComponent.prototype.schema);
  56207. // Keep track of keys that may potentially change the schema.
  56208. if (!schemaIsSingleProp) {
  56209. NewComponent.prototype.schemaChangeKeys = [];
  56210. for (propertyName in schema) {
  56211. if (schema[propertyName].schemaChange) {
  56212. NewComponent.prototype.schemaChangeKeys.push(propertyName);
  56213. }
  56214. }
  56215. }
  56216. // Create object pool for class of components.
  56217. objectPools[name] = utils.objectPool.createPool();
  56218. components[name] = {
  56219. Component: NewComponent,
  56220. dependencies: NewComponent.prototype.dependencies,
  56221. isSingleProp: schemaIsSingleProp,
  56222. multiple: NewComponent.prototype.multiple,
  56223. name: name,
  56224. parse: NewComponent.prototype.parse,
  56225. parseAttrValueForCache: NewComponent.prototype.parseAttrValueForCache,
  56226. schema: schema,
  56227. stringify: NewComponent.prototype.stringify,
  56228. type: NewComponent.prototype.type
  56229. };
  56230. return NewComponent;
  56231. };
  56232. /**
  56233. * Clone component data.
  56234. * Clone only the properties that are plain objects while keeping a reference for the rest.
  56235. *
  56236. * @param data - Component data to clone.
  56237. * @returns Cloned data.
  56238. */
  56239. function copyData (dest, sourceData) {
  56240. var parsedProperty;
  56241. var key;
  56242. for (key in sourceData) {
  56243. if (sourceData[key] === undefined) { continue; }
  56244. parsedProperty = sourceData[key];
  56245. dest[key] = isObjectOrArray(parsedProperty)
  56246. ? utils.clone(parsedProperty)
  56247. : parsedProperty;
  56248. }
  56249. return dest;
  56250. }
  56251. /**
  56252. * Object extending with checking for single-property schema.
  56253. *
  56254. * @param dest - Destination object or value.
  56255. * @param source - Source object or value
  56256. * @param {boolean} isObjectBased - Whether values are objects.
  56257. * @returns Overridden object or value.
  56258. */
  56259. function extendProperties (dest, source, isObjectBased) {
  56260. var key;
  56261. if (isObjectBased && source.constructor === Object) {
  56262. for (key in source) {
  56263. if (source[key] === undefined) { continue; }
  56264. if (source[key] && source[key].constructor === Object) {
  56265. dest[key] = utils.clone(source[key]);
  56266. } else {
  56267. dest[key] = source[key];
  56268. }
  56269. }
  56270. return dest;
  56271. }
  56272. return source;
  56273. }
  56274. /**
  56275. * Checks if a component has defined a method that needs to run every frame.
  56276. */
  56277. function hasBehavior (component) {
  56278. return component.tick || component.tock;
  56279. }
  56280. /**
  56281. * Wrapper for defined pause method.
  56282. * Pause component by removing tick behavior and calling user's pause method.
  56283. *
  56284. * @param pauseMethod {function}
  56285. */
  56286. function wrapPause (pauseMethod) {
  56287. return function pause () {
  56288. var sceneEl = this.el.sceneEl;
  56289. if (!this.isPlaying) { return; }
  56290. pauseMethod.call(this);
  56291. this.isPlaying = false;
  56292. this.eventsDetach();
  56293. // Remove tick behavior.
  56294. if (!hasBehavior(this)) { return; }
  56295. sceneEl.removeBehavior(this);
  56296. };
  56297. }
  56298. /**
  56299. * Wrapper for defined play method.
  56300. * Play component by adding tick behavior and calling user's play method.
  56301. *
  56302. * @param playMethod {function}
  56303. */
  56304. function wrapPlay (playMethod) {
  56305. return function play () {
  56306. var sceneEl = this.el.sceneEl;
  56307. var shouldPlay = this.el.isPlaying && !this.isPlaying;
  56308. if (!this.initialized || !shouldPlay) { return; }
  56309. playMethod.call(this);
  56310. this.isPlaying = true;
  56311. this.eventsAttach();
  56312. // Add tick behavior.
  56313. if (!hasBehavior(this)) { return; }
  56314. sceneEl.addBehavior(this);
  56315. };
  56316. }
  56317. function isObject (value) {
  56318. return value && value.constructor === Object && !(value instanceof window.HTMLElement);
  56319. }
  56320. function isObjectOrArray (value) {
  56321. return value && (value.constructor === Object || value.constructor === Array) &&
  56322. !(value instanceof window.HTMLElement);
  56323. }
  56324. },{"../utils/":205,"./scene/scenes":138,"./schema":140,"./system":142}],132:[function(_dereq_,module,exports){
  56325. var schema = _dereq_('./schema');
  56326. var processSchema = schema.process;
  56327. var geometries = module.exports.geometries = {}; // Registered geometries.
  56328. var geometryNames = module.exports.geometryNames = []; // Names of registered geometries.
  56329. var THREE = _dereq_('../lib/three');
  56330. /**
  56331. * Geometry class definition.
  56332. *
  56333. * Geometries extend the geometry component API to create and register geometry types.
  56334. */
  56335. var Geometry = module.exports.Geometry = function () {};
  56336. Geometry.prototype = {
  56337. /**
  56338. * Contains the type schema and defaults for the data values.
  56339. * Data is coerced into the types of the values of the defaults.
  56340. */
  56341. schema: {},
  56342. /**
  56343. * Init handler. Similar to attachedCallback.
  56344. * Called during shader initialization and is only run once.
  56345. */
  56346. init: function (data) {
  56347. this.geometry = new THREE.BufferGeometry();
  56348. return this.geometry;
  56349. },
  56350. /**
  56351. * Update handler. Similar to attributeChangedCallback.
  56352. * Called whenever the associated geometry data changes.
  56353. *
  56354. * @param {object} data - New geometry data.
  56355. */
  56356. update: function (data) { /* no-op */ }
  56357. };
  56358. /**
  56359. * Registers a geometry to A-Frame.
  56360. *
  56361. * @param {string} name - Geometry name.
  56362. * @param {object} definition - Geometry property and methods.
  56363. * @returns {object} Geometry.
  56364. */
  56365. module.exports.registerGeometry = function (name, definition) {
  56366. var NewGeometry;
  56367. var proto = {};
  56368. // Format definition object to prototype object.
  56369. Object.keys(definition).forEach(function expandDefinition (key) {
  56370. proto[key] = {
  56371. value: definition[key],
  56372. writable: true
  56373. };
  56374. });
  56375. if (geometries[name]) {
  56376. throw new Error('The geometry `' + name + '` has been already registered');
  56377. }
  56378. NewGeometry = function () { Geometry.call(this); };
  56379. NewGeometry.prototype = Object.create(Geometry.prototype, proto);
  56380. NewGeometry.prototype.name = name;
  56381. NewGeometry.prototype.constructor = NewGeometry;
  56382. geometries[name] = {
  56383. Geometry: NewGeometry,
  56384. schema: processSchema(NewGeometry.prototype.schema)
  56385. };
  56386. geometryNames.push(name);
  56387. return NewGeometry;
  56388. };
  56389. },{"../lib/three":179,"./schema":140}],133:[function(_dereq_,module,exports){
  56390. var coordinates = _dereq_('../utils/coordinates');
  56391. var debug = _dereq_('debug');
  56392. var error = debug('core:propertyTypes:warn');
  56393. var warn = debug('core:propertyTypes:warn');
  56394. var propertyTypes = module.exports.propertyTypes = {};
  56395. var nonCharRegex = /[,> .[\]:]/;
  56396. var urlRegex = /\url\((.+)\)/;
  56397. // Built-in property types.
  56398. registerPropertyType('audio', '', assetParse);
  56399. registerPropertyType('array', [], arrayParse, arrayStringify);
  56400. registerPropertyType('asset', '', assetParse);
  56401. registerPropertyType('boolean', false, boolParse);
  56402. registerPropertyType('color', '#FFF', defaultParse, defaultStringify);
  56403. registerPropertyType('int', 0, intParse);
  56404. registerPropertyType('number', 0, numberParse);
  56405. registerPropertyType('map', '', assetParse);
  56406. registerPropertyType('model', '', assetParse);
  56407. registerPropertyType('selector', null, selectorParse, selectorStringify);
  56408. registerPropertyType('selectorAll', null, selectorAllParse, selectorAllStringify);
  56409. registerPropertyType('src', '', srcParse);
  56410. registerPropertyType('string', '', defaultParse, defaultStringify);
  56411. registerPropertyType('time', 0, intParse);
  56412. registerPropertyType('vec2', {x: 0, y: 0}, vecParse, coordinates.stringify);
  56413. registerPropertyType('vec3', {x: 0, y: 0, z: 0}, vecParse, coordinates.stringify);
  56414. registerPropertyType('vec4', {x: 0, y: 0, z: 0, w: 1}, vecParse, coordinates.stringify);
  56415. /**
  56416. * Register a parser for re-use such that when someone uses `type` in the schema,
  56417. * `schema.process` will set the property `parse` and `stringify`.
  56418. *
  56419. * @param {string} type - Type name.
  56420. * @param [defaultValue=null] -
  56421. * Default value to use if component does not define default value.
  56422. * @param {function} [parse=defaultParse] - Parse string function.
  56423. * @param {function} [stringify=defaultStringify] - Stringify to DOM function.
  56424. */
  56425. function registerPropertyType (type, defaultValue, parse, stringify) {
  56426. if ('type' in propertyTypes) {
  56427. error('Property type ' + type + ' is already registered.');
  56428. return;
  56429. }
  56430. propertyTypes[type] = {
  56431. default: defaultValue,
  56432. parse: parse || defaultParse,
  56433. stringify: stringify || defaultStringify
  56434. };
  56435. }
  56436. module.exports.registerPropertyType = registerPropertyType;
  56437. function arrayParse (value) {
  56438. if (Array.isArray(value)) { return value; }
  56439. if (!value || typeof value !== 'string') { return []; }
  56440. return value.split(',').map(trim);
  56441. function trim (str) { return str.trim(); }
  56442. }
  56443. function arrayStringify (value) {
  56444. return value.join(', ');
  56445. }
  56446. /**
  56447. * For general assets.
  56448. *
  56449. * @param {string} value - Can either be `url(<value>)`, an ID selector to an asset, or
  56450. * just string.
  56451. * @returns {string} Parsed value from `url(<value>)`, src from `<someasset src>`, or
  56452. * just string.
  56453. */
  56454. function assetParse (value) {
  56455. var el;
  56456. var parsedUrl;
  56457. // If an element was provided (e.g. canvas or video), just return it.
  56458. if (typeof value !== 'string') { return value; }
  56459. // Wrapped `url()` in case of data URI.
  56460. parsedUrl = value.match(urlRegex);
  56461. if (parsedUrl) { return parsedUrl[1]; }
  56462. // ID.
  56463. if (value.charAt(0) === '#') {
  56464. el = document.getElementById(value.substring(1));
  56465. if (el) {
  56466. // Pass through media elements. If we have the elements, we don't have to call
  56467. // three.js loaders which would re-request the assets.
  56468. if (el.tagName === 'CANVAS' || el.tagName === 'VIDEO' || el.tagName === 'IMG') {
  56469. return el;
  56470. }
  56471. return el.getAttribute('src');
  56472. }
  56473. warn('"' + value + '" asset not found.');
  56474. return;
  56475. }
  56476. // Non-wrapped url().
  56477. return value;
  56478. }
  56479. function defaultParse (value) {
  56480. return value;
  56481. }
  56482. function defaultStringify (value) {
  56483. if (value === null) { return 'null'; }
  56484. return value.toString();
  56485. }
  56486. function boolParse (value) {
  56487. return value !== 'false' && value !== false;
  56488. }
  56489. function intParse (value) {
  56490. return parseInt(value, 10);
  56491. }
  56492. function numberParse (value) {
  56493. return parseFloat(value, 10);
  56494. }
  56495. function selectorParse (value) {
  56496. if (!value) { return null; }
  56497. if (typeof value !== 'string') { return value; }
  56498. if (value[0] === '#' && !nonCharRegex.test(value)) {
  56499. // When selecting element by ID only, use getElementById for better performance.
  56500. // Don't match like #myId .child.
  56501. return document.getElementById(value.substring(1));
  56502. }
  56503. return document.querySelector(value);
  56504. }
  56505. function selectorAllParse (value) {
  56506. if (!value) { return null; }
  56507. if (typeof value !== 'string') { return value; }
  56508. return Array.prototype.slice.call(document.querySelectorAll(value), 0);
  56509. }
  56510. function selectorStringify (value) {
  56511. if (value.getAttribute) {
  56512. return '#' + value.getAttribute('id');
  56513. }
  56514. return defaultStringify(value);
  56515. }
  56516. function selectorAllStringify (value) {
  56517. if (value instanceof Array) {
  56518. return value.map(function (element) {
  56519. return '#' + element.getAttribute('id');
  56520. }).join(', ');
  56521. }
  56522. return defaultStringify(value);
  56523. }
  56524. function srcParse (value) {
  56525. warn('`src` property type is deprecated. Use `asset` instead.');
  56526. return assetParse(value);
  56527. }
  56528. function vecParse (value) {
  56529. return coordinates.parse(value, this.default);
  56530. }
  56531. /**
  56532. * Validate the default values in a schema to match their type.
  56533. *
  56534. * @param {string} type - Property type name.
  56535. * @param defaultVal - Property type default value.
  56536. * @returns {boolean} Whether default value is accurate given the type.
  56537. */
  56538. function isValidDefaultValue (type, defaultVal) {
  56539. if (type === 'audio' && typeof defaultVal !== 'string') { return false; }
  56540. if (type === 'array' && !Array.isArray(defaultVal)) { return false; }
  56541. if (type === 'asset' && typeof defaultVal !== 'string') { return false; }
  56542. if (type === 'boolean' && typeof defaultVal !== 'boolean') { return false; }
  56543. if (type === 'color' && typeof defaultVal !== 'string') { return false; }
  56544. if (type === 'int' && typeof defaultVal !== 'number') { return false; }
  56545. if (type === 'number' && typeof defaultVal !== 'number') { return false; }
  56546. if (type === 'map' && typeof defaultVal !== 'string') { return false; }
  56547. if (type === 'model' && typeof defaultVal !== 'string') { return false; }
  56548. if (type === 'selector' && typeof defaultVal !== 'string' &&
  56549. defaultVal !== null) { return false; }
  56550. if (type === 'selectorAll' && typeof defaultVal !== 'string' &&
  56551. defaultVal !== null) { return false; }
  56552. if (type === 'src' && typeof defaultVal !== 'string') { return false; }
  56553. if (type === 'string' && typeof defaultVal !== 'string') { return false; }
  56554. if (type === 'time' && typeof defaultVal !== 'number') { return false; }
  56555. if (type === 'vec2') { return isValidDefaultCoordinate(defaultVal, 2); }
  56556. if (type === 'vec3') { return isValidDefaultCoordinate(defaultVal, 3); }
  56557. if (type === 'vec4') { return isValidDefaultCoordinate(defaultVal, 4); }
  56558. return true;
  56559. }
  56560. module.exports.isValidDefaultValue = isValidDefaultValue;
  56561. /**
  56562. * Checks if default coordinates are valid.
  56563. *
  56564. * @param possibleCoordinates
  56565. * @param {number} dimensions - 2 for 2D Vector, 3 for 3D vector.
  56566. * @returns {boolean} Whether coordinates are parsed correctly.
  56567. */
  56568. function isValidDefaultCoordinate (possibleCoordinates, dimensions) {
  56569. if (possibleCoordinates === null) { return true; }
  56570. if (typeof possibleCoordinates !== 'object') { return false; }
  56571. if (Object.keys(possibleCoordinates).length !== dimensions) {
  56572. return false;
  56573. } else {
  56574. var x = possibleCoordinates.x;
  56575. var y = possibleCoordinates.y;
  56576. var z = possibleCoordinates.z;
  56577. var w = possibleCoordinates.w;
  56578. if (typeof x !== 'number' || typeof y !== 'number') { return false; }
  56579. if (dimensions > 2 && typeof z !== 'number') { return false; }
  56580. if (dimensions > 3 && typeof w !== 'number') { return false; }
  56581. }
  56582. return true;
  56583. }
  56584. module.exports.isValidDefaultCoordinate = isValidDefaultCoordinate;
  56585. },{"../utils/coordinates":200,"debug":8}],134:[function(_dereq_,module,exports){
  56586. /* global Promise, screen, CustomEvent */
  56587. var initMetaTags = _dereq_('./metaTags').inject;
  56588. var initWakelock = _dereq_('./wakelock');
  56589. var loadingScreen = _dereq_('./loadingScreen');
  56590. var re = _dereq_('../a-register-element');
  56591. var scenes = _dereq_('./scenes');
  56592. var systems = _dereq_('../system').systems;
  56593. var THREE = _dereq_('../../lib/three');
  56594. var utils = _dereq_('../../utils/');
  56595. // Require after.
  56596. var AEntity = _dereq_('../a-entity');
  56597. var ANode = _dereq_('../a-node');
  56598. var initPostMessageAPI = _dereq_('./postMessage');
  56599. var bind = utils.bind;
  56600. var isIOS = utils.device.isIOS();
  56601. var isMobile = utils.device.isMobile();
  56602. var isWebXRAvailable = utils.device.isWebXRAvailable;
  56603. var registerElement = re.registerElement;
  56604. var warn = utils.debug('core:a-scene:warn');
  56605. if (isIOS) { _dereq_('../../utils/ios-orientationchange-blank-bug'); }
  56606. /**
  56607. * Scene element, holds all entities.
  56608. *
  56609. * @member {array} behaviors - Component instances that have registered themselves to be
  56610. updated on every tick.
  56611. * @member {object} camera - three.js Camera object.
  56612. * @member {object} canvas
  56613. * @member {bool} isScene - Differentiates as scene entity as opposed to other entites.
  56614. * @member {bool} isMobile - Whether browser is mobile (via UA detection).
  56615. * @member {object} object3D - Root three.js Scene object.
  56616. * @member {object} renderer
  56617. * @member {bool} renderStarted
  56618. * @member {object} systems - Registered instantiated systems.
  56619. * @member {number} time
  56620. */
  56621. module.exports.AScene = registerElement('a-scene', {
  56622. prototype: Object.create(AEntity.prototype, {
  56623. createdCallback: {
  56624. value: function () {
  56625. this.clock = new THREE.Clock();
  56626. this.isIOS = isIOS;
  56627. this.isMobile = isMobile;
  56628. this.hasWebXR = isWebXRAvailable;
  56629. this.isAR = false;
  56630. this.isScene = true;
  56631. this.object3D = new THREE.Scene();
  56632. var self = this;
  56633. this.object3D.onAfterRender = function (renderer, scene, camera) {
  56634. // THREE may swap the camera used for the rendering if in VR, so we pass it to tock
  56635. if (self.isPlaying) { self.tock(self.time, self.delta, camera); }
  56636. };
  56637. this.resize = bind(this.resize, this);
  56638. this.render = bind(this.render, this);
  56639. this.systems = {};
  56640. this.systemNames = [];
  56641. this.time = this.delta = 0;
  56642. this.behaviors = {tick: [], tock: []};
  56643. this.hasLoaded = false;
  56644. this.isPlaying = false;
  56645. this.originalHTML = this.innerHTML;
  56646. // Default components.
  56647. this.setAttribute('inspector', '');
  56648. this.setAttribute('keyboard-shortcuts', '');
  56649. this.setAttribute('screenshot', '');
  56650. this.setAttribute('vr-mode-ui', '');
  56651. this.setAttribute('device-orientation-permission-ui', '');
  56652. }
  56653. },
  56654. addFullScreenStyles: {
  56655. value: function () {
  56656. document.documentElement.classList.add('a-fullscreen');
  56657. }
  56658. },
  56659. removeFullScreenStyles: {
  56660. value: function () {
  56661. document.documentElement.classList.remove('a-fullscreen');
  56662. }
  56663. },
  56664. attachedCallback: {
  56665. value: function () {
  56666. var self = this;
  56667. var embedded = this.hasAttribute('embedded');
  56668. // Renderer initialization
  56669. setupCanvas(this);
  56670. this.setupRenderer();
  56671. loadingScreen.setup(this, getCanvasSize);
  56672. this.resize();
  56673. if (!embedded) { this.addFullScreenStyles(); }
  56674. initPostMessageAPI(this);
  56675. initMetaTags(this);
  56676. initWakelock(this);
  56677. // Handler to exit VR (e.g., Oculus Browser back button).
  56678. this.onVRPresentChangeBound = bind(this.onVRPresentChange, this);
  56679. window.addEventListener('vrdisplaypresentchange', this.onVRPresentChangeBound);
  56680. // Bind functions.
  56681. this.enterVRBound = function () { self.enterVR(); };
  56682. this.exitVRBound = function () { self.exitVR(); };
  56683. this.exitVRTrueBound = function () { self.exitVR(true); };
  56684. this.pointerRestrictedBound = function () { self.pointerRestricted(); };
  56685. this.pointerUnrestrictedBound = function () { self.pointerUnrestricted(); };
  56686. if (!isWebXRAvailable) {
  56687. // Exit VR on `vrdisplaydeactivate` (e.g. taking off Rift headset).
  56688. window.addEventListener('vrdisplaydeactivate', this.exitVRBound);
  56689. // Exit VR on `vrdisplaydisconnect` (e.g. unplugging Rift headset).
  56690. window.addEventListener('vrdisplaydisconnect', this.exitVRTrueBound);
  56691. // Register for mouse restricted events while in VR
  56692. // (e.g. mouse no longer available on desktop 2D view)
  56693. window.addEventListener('vrdisplaypointerrestricted', this.pointerRestrictedBound);
  56694. // Register for mouse unrestricted events while in VR
  56695. // (e.g. mouse once again available on desktop 2D view)
  56696. window.addEventListener('vrdisplaypointerunrestricted',
  56697. this.pointerUnrestrictedBound);
  56698. }
  56699. window.addEventListener('sessionend', this.resize);
  56700. // Camera set up by camera system.
  56701. this.addEventListener('cameraready', function () {
  56702. self.attachedCallbackPostCamera();
  56703. });
  56704. this.initSystems();
  56705. // WebXR Immersive navigation handler.
  56706. if (this.hasWebXR && navigator.xr && navigator.xr.addEventListener) {
  56707. navigator.xr.addEventListener('sessiongranted', function () { self.enterVR(); });
  56708. }
  56709. }
  56710. },
  56711. attachedCallbackPostCamera: {
  56712. value: function () {
  56713. var resize;
  56714. var self = this;
  56715. window.addEventListener('load', resize);
  56716. window.addEventListener('resize', function () {
  56717. // Workaround for a Webkit bug (https://bugs.webkit.org/show_bug.cgi?id=170595)
  56718. // where the window does not contain the correct viewport size
  56719. // after an orientation change. The window size is correct if the operation
  56720. // is postponed a few milliseconds.
  56721. // self.resize can be called directly once the bug above is fixed.
  56722. if (self.isIOS) {
  56723. setTimeout(self.resize, 100);
  56724. } else {
  56725. self.resize();
  56726. }
  56727. });
  56728. this.play();
  56729. // Add to scene index.
  56730. scenes.push(this);
  56731. },
  56732. writable: window.debug
  56733. },
  56734. /**
  56735. * Initialize all systems.
  56736. */
  56737. initSystems: {
  56738. value: function () {
  56739. var name;
  56740. // Initialize camera system first.
  56741. this.initSystem('camera');
  56742. for (name in systems) {
  56743. if (name === 'camera') { continue; }
  56744. this.initSystem(name);
  56745. }
  56746. }
  56747. },
  56748. /**
  56749. * Initialize a system.
  56750. */
  56751. initSystem: {
  56752. value: function (name) {
  56753. if (this.systems[name]) { return; }
  56754. this.systems[name] = new systems[name](this);
  56755. this.systemNames.push(name);
  56756. }
  56757. },
  56758. /**
  56759. * Shut down scene on detach.
  56760. */
  56761. detachedCallback: {
  56762. value: function () {
  56763. // Remove from scene index.
  56764. var sceneIndex = scenes.indexOf(this);
  56765. scenes.splice(sceneIndex, 1);
  56766. window.removeEventListener('vrdisplaypresentchange', this.onVRPresentChangeBound);
  56767. window.removeEventListener('vrdisplayactivate', this.enterVRBound);
  56768. window.removeEventListener('vrdisplaydeactivate', this.exitVRBound);
  56769. window.removeEventListener('vrdisplayconnect', this.enterVRBound);
  56770. window.removeEventListener('vrdisplaydisconnect', this.exitVRTrueBound);
  56771. window.removeEventListener('vrdisplaypointerrestricted', this.pointerRestrictedBound);
  56772. window.removeEventListener('vrdisplaypointerunrestricted', this.pointerUnrestrictedBound);
  56773. window.removeEventListener('sessionend', this.resize);
  56774. this.renderer.xr.dispose();
  56775. }
  56776. },
  56777. /**
  56778. * Add ticks and tocks.
  56779. *
  56780. * @param {object} behavior - A component.
  56781. */
  56782. addBehavior: {
  56783. value: function (behavior) {
  56784. var behaviorArr;
  56785. var behaviors = this.behaviors;
  56786. var behaviorType;
  56787. // Check if behavior has tick and/or tock and add the behavior to the appropriate list.
  56788. for (behaviorType in behaviors) {
  56789. if (!behavior[behaviorType]) { continue; }
  56790. behaviorArr = this.behaviors[behaviorType];
  56791. if (behaviorArr.indexOf(behavior) === -1) {
  56792. behaviorArr.push(behavior);
  56793. }
  56794. }
  56795. }
  56796. },
  56797. /**
  56798. * For tests.
  56799. */
  56800. getPointerLockElement: {
  56801. value: function () {
  56802. return document.pointerLockElement;
  56803. },
  56804. writable: window.debug
  56805. },
  56806. /**
  56807. * For tests.
  56808. */
  56809. checkHeadsetConnected: {
  56810. value: utils.device.checkHeadsetConnected,
  56811. writable: window.debug
  56812. },
  56813. enterAR: {
  56814. value: function () {
  56815. var errorMessage;
  56816. if (!this.hasWebXR) {
  56817. errorMessage = 'Failed to enter AR mode, WebXR not supported.';
  56818. throw new Error(errorMessage);
  56819. }
  56820. if (!utils.device.checkARSupport()) {
  56821. errorMessage = 'Failed to enter AR, WebXR immersive-ar mode not supported in your browser or device.';
  56822. throw new Error(errorMessage);
  56823. }
  56824. return this.enterVR(true);
  56825. }
  56826. },
  56827. /**
  56828. * Call `requestPresent` if WebVR or WebVR polyfill.
  56829. * Call `requestFullscreen` on desktop.
  56830. * Handle events, states, fullscreen styles.
  56831. *
  56832. * @param {bool?} useAR - if true, try immersive-ar mode
  56833. * @returns {Promise}
  56834. */
  56835. enterVR: {
  56836. value: function (useAR) {
  56837. var self = this;
  56838. var vrDisplay;
  56839. var vrManager = self.renderer.xr;
  56840. var xrInit;
  56841. // Don't enter VR if already in VR.
  56842. if (this.is('vr-mode')) { return Promise.resolve('Already in VR.'); }
  56843. // Has VR.
  56844. if (this.checkHeadsetConnected() || this.isMobile) {
  56845. vrManager.enabled = true;
  56846. if (this.hasWebXR) {
  56847. // XR API.
  56848. if (this.xrSession) {
  56849. this.xrSession.removeEventListener('end', this.exitVRBound);
  56850. }
  56851. var refspace = this.sceneEl.systems.webxr.sessionReferenceSpaceType;
  56852. vrManager.setReferenceSpaceType(refspace);
  56853. var xrMode = useAR ? 'immersive-ar' : 'immersive-vr';
  56854. xrInit = this.sceneEl.systems.webxr.sessionConfiguration;
  56855. return new Promise(function (resolve, reject) {
  56856. navigator.xr.requestSession(xrMode, xrInit).then(
  56857. function requestSuccess (xrSession) {
  56858. self.xrSession = xrSession;
  56859. vrManager.layersEnabled = xrInit.requiredFeatures.indexOf('layers') !== -1;
  56860. vrManager.setSession(xrSession);
  56861. xrSession.addEventListener('end', self.exitVRBound);
  56862. enterVRSuccess(resolve);
  56863. },
  56864. function requestFail (error) {
  56865. var useAR = xrMode === 'immersive-ar';
  56866. var mode = useAR ? 'AR' : 'VR';
  56867. throw new Error('Failed to enter ' + mode + ' mode (`requestSession`) ' + error);
  56868. }
  56869. );
  56870. });
  56871. } else {
  56872. vrDisplay = utils.device.getVRDisplay();
  56873. vrManager.setDevice(vrDisplay);
  56874. if (vrDisplay.isPresenting &&
  56875. !window.hasNativeWebVRImplementation) {
  56876. enterVRSuccess();
  56877. return Promise.resolve();
  56878. }
  56879. var rendererSystem = this.getAttribute('renderer');
  56880. var presentationAttributes = {
  56881. highRefreshRate: rendererSystem.highRefreshRate,
  56882. foveationLevel: rendererSystem.foveationLevel
  56883. };
  56884. return vrDisplay.requestPresent([{
  56885. source: this.canvas,
  56886. attributes: presentationAttributes
  56887. }]).then(enterVRSuccess, enterVRFailure);
  56888. }
  56889. }
  56890. // No VR.
  56891. enterVRSuccess();
  56892. return Promise.resolve();
  56893. // Callback that happens on enter VR success or enter fullscreen (any API).
  56894. function enterVRSuccess (resolve) {
  56895. // vrdisplaypresentchange fires only once when the first requestPresent is completed;
  56896. // the first requestPresent could be called from ondisplayactivate and there is no way
  56897. // to setup everything from there. Thus, we need to emulate another vrdisplaypresentchange
  56898. // for the actual requestPresent. Need to make sure there are no issues with firing the
  56899. // vrdisplaypresentchange multiple times.
  56900. var event;
  56901. if (window.hasNativeWebVRImplementation && !window.hasNativeWebXRImplementation) {
  56902. event = new CustomEvent('vrdisplaypresentchange', {detail: {display: utils.device.getVRDisplay()}});
  56903. window.dispatchEvent(event);
  56904. }
  56905. if (useAR) {
  56906. self.addState('ar-mode');
  56907. } else {
  56908. self.addState('vr-mode');
  56909. }
  56910. self.emit('enter-vr', {target: self});
  56911. // Lock to landscape orientation on mobile.
  56912. if (!isWebXRAvailable && self.isMobile && screen.orientation && screen.orientation.lock) {
  56913. screen.orientation.lock('landscape');
  56914. }
  56915. self.addFullScreenStyles();
  56916. // On mobile, the polyfill handles fullscreen.
  56917. // TODO: 07/16 Chromium builds break when `requestFullscreen`ing on a canvas
  56918. // that we are also `requestPresent`ing. Until then, don't fullscreen if headset
  56919. // connected.
  56920. if (!self.isMobile && !self.checkHeadsetConnected()) {
  56921. requestFullscreen(self.canvas);
  56922. }
  56923. self.renderer.setAnimationLoop(self.render);
  56924. self.resize();
  56925. if (resolve) { resolve(); }
  56926. }
  56927. function enterVRFailure (err) {
  56928. self.removeState('vr-mode');
  56929. if (err && err.message) {
  56930. throw new Error('Failed to enter VR mode (`requestPresent`): ' + err.message);
  56931. } else {
  56932. throw new Error('Failed to enter VR mode (`requestPresent`).');
  56933. }
  56934. }
  56935. },
  56936. writable: true
  56937. },
  56938. /**
  56939. * Call `exitPresent` if WebVR / WebXR or WebVR polyfill.
  56940. * Handle events, states, fullscreen styles.
  56941. *
  56942. * @returns {Promise}
  56943. */
  56944. exitVR: {
  56945. value: function () {
  56946. var self = this;
  56947. var vrDisplay;
  56948. var vrManager = this.renderer.xr;
  56949. // Don't exit VR if not in VR.
  56950. if (!this.is('vr-mode') && !this.is('ar-mode')) { return Promise.resolve('Not in immersive mode.'); }
  56951. // Handle exiting VR if not yet already and in a headset or polyfill.
  56952. if (this.checkHeadsetConnected() || this.isMobile) {
  56953. vrManager.enabled = false;
  56954. vrDisplay = utils.device.getVRDisplay();
  56955. if (this.hasWebXR) {
  56956. this.xrSession.removeEventListener('end', this.exitVRBound);
  56957. // Capture promise to avoid errors.
  56958. this.xrSession.end().then(function () {}, function () {});
  56959. this.xrSession = undefined;
  56960. vrManager.setSession(null);
  56961. } else {
  56962. if (vrDisplay.isPresenting) {
  56963. return vrDisplay.exitPresent().then(exitVRSuccess, exitVRFailure);
  56964. }
  56965. }
  56966. } else {
  56967. exitFullscreen();
  56968. }
  56969. // Handle exiting VR in all other cases (2D fullscreen, external exit VR event).
  56970. exitVRSuccess();
  56971. return Promise.resolve();
  56972. function exitVRSuccess () {
  56973. self.removeState('vr-mode');
  56974. self.removeState('ar-mode');
  56975. // Lock to landscape orientation on mobile.
  56976. if (self.isMobile && screen.orientation && screen.orientation.unlock) {
  56977. screen.orientation.unlock();
  56978. }
  56979. // Exiting VR in embedded mode, no longer need fullscreen styles.
  56980. if (self.hasAttribute('embedded')) { self.removeFullScreenStyles(); }
  56981. self.resize();
  56982. if (self.isIOS) { utils.forceCanvasResizeSafariMobile(self.canvas); }
  56983. self.renderer.setPixelRatio(window.devicePixelRatio);
  56984. self.emit('exit-vr', {target: self});
  56985. }
  56986. function exitVRFailure (err) {
  56987. if (err && err.message) {
  56988. throw new Error('Failed to exit VR mode (`exitPresent`): ' + err.message);
  56989. } else {
  56990. throw new Error('Failed to exit VR mode (`exitPresent`).');
  56991. }
  56992. }
  56993. },
  56994. writable: true
  56995. },
  56996. pointerRestricted: {
  56997. value: function () {
  56998. if (this.canvas) {
  56999. var pointerLockElement = this.getPointerLockElement();
  57000. if (pointerLockElement && pointerLockElement !== this.canvas && document.exitPointerLock) {
  57001. // Recreate pointer lock on the canvas, if taken on another element.
  57002. document.exitPointerLock();
  57003. }
  57004. if (this.canvas.requestPointerLock) {
  57005. this.canvas.requestPointerLock();
  57006. }
  57007. }
  57008. }
  57009. },
  57010. pointerUnrestricted: {
  57011. value: function () {
  57012. var pointerLockElement = this.getPointerLockElement();
  57013. if (pointerLockElement && pointerLockElement === this.canvas && document.exitPointerLock) {
  57014. document.exitPointerLock();
  57015. }
  57016. }
  57017. },
  57018. /**
  57019. * Handle `vrdisplaypresentchange` event for exiting VR through other means than
  57020. * `<ESC>` key. For example, GearVR back button on Oculus Browser.
  57021. */
  57022. onVRPresentChange: {
  57023. value: function (evt) {
  57024. // Polyfill places display inside the detail property
  57025. var display = evt.display || evt.detail.display;
  57026. // Entering VR.
  57027. if (display && display.isPresenting) {
  57028. this.enterVR();
  57029. return;
  57030. }
  57031. // Exiting VR.
  57032. this.exitVR();
  57033. }
  57034. },
  57035. /**
  57036. * Wraps Entity.getAttribute to take into account for systems.
  57037. * If system exists, then return system data rather than possible component data.
  57038. */
  57039. getAttribute: {
  57040. value: function (attr) {
  57041. var system = this.systems[attr];
  57042. if (system) { return system.data; }
  57043. return AEntity.prototype.getAttribute.call(this, attr);
  57044. }
  57045. },
  57046. /**
  57047. * `getAttribute` used to be `getDOMAttribute` and `getComputedAttribute` used to be
  57048. * what `getAttribute` is now. Now legacy code.
  57049. */
  57050. getComputedAttribute: {
  57051. value: function (attr) {
  57052. warn('`getComputedAttribute` is deprecated. Use `getAttribute` instead.');
  57053. this.getAttribute(attr);
  57054. }
  57055. },
  57056. /**
  57057. * Wraps Entity.getDOMAttribute to take into account for systems.
  57058. * If system exists, then return system data rather than possible component data.
  57059. */
  57060. getDOMAttribute: {
  57061. value: function (attr) {
  57062. var system = this.systems[attr];
  57063. if (system) { return system.data; }
  57064. return AEntity.prototype.getDOMAttribute.call(this, attr);
  57065. }
  57066. },
  57067. /**
  57068. * Wrap Entity.setAttribute to take into account for systems.
  57069. * If system exists, then skip component initialization checks and do a normal
  57070. * setAttribute.
  57071. */
  57072. setAttribute: {
  57073. value: function (attr, value, componentPropValue) {
  57074. var system = this.systems[attr];
  57075. if (system) {
  57076. ANode.prototype.setAttribute.call(this, attr, value);
  57077. system.updateProperties(value);
  57078. return;
  57079. }
  57080. AEntity.prototype.setAttribute.call(this, attr, value, componentPropValue);
  57081. }
  57082. },
  57083. /**
  57084. * @param {object} behavior - A component.
  57085. */
  57086. removeBehavior: {
  57087. value: function (behavior) {
  57088. var behaviorArr;
  57089. var behaviorType;
  57090. var behaviors = this.behaviors;
  57091. var index;
  57092. // Check if behavior has tick and/or tock and remove the behavior from the appropriate
  57093. // array.
  57094. for (behaviorType in behaviors) {
  57095. if (!behavior[behaviorType]) { continue; }
  57096. behaviorArr = this.behaviors[behaviorType];
  57097. index = behaviorArr.indexOf(behavior);
  57098. if (index !== -1) { behaviorArr.splice(index, 1); }
  57099. }
  57100. }
  57101. },
  57102. resize: {
  57103. value: function () {
  57104. var camera = this.camera;
  57105. var canvas = this.canvas;
  57106. var embedded;
  57107. var isVRPresenting;
  57108. var size;
  57109. var isPresenting = this.renderer.xr.isPresenting;
  57110. isVRPresenting = this.renderer.xr.enabled && isPresenting;
  57111. // Do not update renderer, if a camera or a canvas have not been injected.
  57112. // In VR mode, three handles canvas resize based on the dimensions returned by
  57113. // the getEyeParameters function of the WebVR API. These dimensions are independent of
  57114. // the window size, therefore should not be overwritten with the window's width and
  57115. // height, // except when in fullscreen mode.
  57116. if (!camera || !canvas || (this.is('vr-mode') && (this.isMobile || isVRPresenting))) {
  57117. return;
  57118. }
  57119. // Update camera.
  57120. embedded = this.getAttribute('embedded') && !this.is('vr-mode');
  57121. size = getCanvasSize(canvas, embedded, this.maxCanvasSize, this.is('vr-mode'));
  57122. camera.aspect = size.width / size.height;
  57123. camera.updateProjectionMatrix();
  57124. // Notify renderer of size change.
  57125. this.renderer.setSize(size.width, size.height, false);
  57126. this.emit('rendererresize', null, false);
  57127. },
  57128. writable: true
  57129. },
  57130. setupRenderer: {
  57131. value: function () {
  57132. var self = this;
  57133. var renderer;
  57134. var rendererAttr;
  57135. var rendererAttrString;
  57136. var rendererConfig;
  57137. rendererConfig = {
  57138. alpha: true,
  57139. antialias: !isMobile,
  57140. canvas: this.canvas,
  57141. logarithmicDepthBuffer: false,
  57142. powerPreference: 'high-performance'
  57143. };
  57144. this.maxCanvasSize = {height: 1920, width: 1920};
  57145. if (this.hasAttribute('renderer')) {
  57146. rendererAttrString = this.getAttribute('renderer');
  57147. rendererAttr = utils.styleParser.parse(rendererAttrString);
  57148. if (rendererAttr.precision) {
  57149. rendererConfig.precision = rendererAttr.precision + 'p';
  57150. }
  57151. if (rendererAttr.antialias && rendererAttr.antialias !== 'auto') {
  57152. rendererConfig.antialias = rendererAttr.antialias === 'true';
  57153. }
  57154. if (rendererAttr.logarithmicDepthBuffer && rendererAttr.logarithmicDepthBuffer !== 'auto') {
  57155. rendererConfig.logarithmicDepthBuffer = rendererAttr.logarithmicDepthBuffer === 'true';
  57156. }
  57157. if (rendererAttr.alpha) {
  57158. rendererConfig.alpha = rendererAttr.alpha === 'true';
  57159. }
  57160. this.maxCanvasSize = {
  57161. width: rendererAttr.maxCanvasWidth
  57162. ? parseInt(rendererAttr.maxCanvasWidth)
  57163. : this.maxCanvasSize.width,
  57164. height: rendererAttr.maxCanvasHeight
  57165. ? parseInt(rendererAttr.maxCanvasHeight)
  57166. : this.maxCanvasSize.height
  57167. };
  57168. }
  57169. renderer = this.renderer = new THREE.WebGLRenderer(rendererConfig);
  57170. renderer.setPixelRatio(window.devicePixelRatio);
  57171. renderer.sortObjects = false;
  57172. if (this.camera) { renderer.xr.setPoseTarget(this.camera.el.object3D); }
  57173. this.addEventListener('camera-set-active', function () {
  57174. renderer.xr.setPoseTarget(self.camera.el.object3D);
  57175. });
  57176. },
  57177. writable: window.debug
  57178. },
  57179. /**
  57180. * Handler attached to elements to help scene know when to kick off.
  57181. * Scene waits for all entities to load.
  57182. */
  57183. play: {
  57184. value: function () {
  57185. var self = this;
  57186. var sceneEl = this;
  57187. if (this.renderStarted) {
  57188. AEntity.prototype.play.call(this);
  57189. return;
  57190. }
  57191. this.addEventListener('loaded', function () {
  57192. var renderer = this.renderer;
  57193. var vrDisplay;
  57194. var vrManager = this.renderer.xr;
  57195. AEntity.prototype.play.call(this); // .play() *before* render.
  57196. if (sceneEl.renderStarted) { return; }
  57197. sceneEl.resize();
  57198. // Kick off render loop.
  57199. if (sceneEl.renderer) {
  57200. if (window.performance) { window.performance.mark('render-started'); }
  57201. loadingScreen.remove();
  57202. vrDisplay = utils.device.getVRDisplay();
  57203. if (vrDisplay && vrDisplay.isPresenting) {
  57204. vrManager.setDevice(vrDisplay);
  57205. vrManager.enabled = true;
  57206. sceneEl.enterVR();
  57207. }
  57208. renderer.setAnimationLoop(this.render);
  57209. sceneEl.renderStarted = true;
  57210. sceneEl.emit('renderstart');
  57211. }
  57212. });
  57213. // setTimeout to wait for all nodes to attach and run their callbacks.
  57214. setTimeout(function () {
  57215. AEntity.prototype.load.call(self);
  57216. });
  57217. }
  57218. },
  57219. /**
  57220. * Wrap `updateComponent` to not initialize the component if the component has a system
  57221. * (aframevr/aframe#2365).
  57222. */
  57223. updateComponent: {
  57224. value: function (componentName) {
  57225. if (componentName in systems) { return; }
  57226. AEntity.prototype.updateComponent.apply(this, arguments);
  57227. }
  57228. },
  57229. /**
  57230. * Behavior-updater meant to be called from scene render.
  57231. * Abstracted to a different function to facilitate unit testing (`scene.tick()`) without
  57232. * needing to render.
  57233. */
  57234. tick: {
  57235. value: function (time, timeDelta) {
  57236. var i;
  57237. var systems = this.systems;
  57238. // Components.
  57239. for (i = 0; i < this.behaviors.tick.length; i++) {
  57240. if (!this.behaviors.tick[i].el.isPlaying) { continue; }
  57241. this.behaviors.tick[i].tick(time, timeDelta);
  57242. }
  57243. // Systems.
  57244. for (i = 0; i < this.systemNames.length; i++) {
  57245. if (!systems[this.systemNames[i]].tick) { continue; }
  57246. systems[this.systemNames[i]].tick(time, timeDelta);
  57247. }
  57248. }
  57249. },
  57250. /**
  57251. * Behavior-updater meant to be called after scene render for post processing purposes.
  57252. * Abstracted to a different function to facilitate unit testing (`scene.tock()`) without
  57253. * needing to render.
  57254. */
  57255. tock: {
  57256. value: function (time, timeDelta, camera) {
  57257. var i;
  57258. var systems = this.systems;
  57259. // Components.
  57260. for (i = 0; i < this.behaviors.tock.length; i++) {
  57261. if (!this.behaviors.tock[i].el.isPlaying) { continue; }
  57262. this.behaviors.tock[i].tock(time, timeDelta, camera);
  57263. }
  57264. // Systems.
  57265. for (i = 0; i < this.systemNames.length; i++) {
  57266. if (!systems[this.systemNames[i]].tock) { continue; }
  57267. systems[this.systemNames[i]].tock(time, timeDelta, camera);
  57268. }
  57269. }
  57270. },
  57271. /**
  57272. * The render loop.
  57273. *
  57274. * Updates animations.
  57275. * Updates behaviors.
  57276. * Renders with request animation frame.
  57277. */
  57278. render: {
  57279. value: function (time, frame) {
  57280. var renderer = this.renderer;
  57281. this.frame = frame;
  57282. this.delta = this.clock.getDelta() * 1000;
  57283. this.time = this.clock.elapsedTime * 1000;
  57284. if (this.isPlaying) { this.tick(this.time, this.delta); }
  57285. var savedBackground = null;
  57286. if (this.is('ar-mode')) {
  57287. // In AR mode, don't render the default background. Hide it, then
  57288. // restore it again after rendering.
  57289. savedBackground = this.object3D.background;
  57290. this.object3D.background = null;
  57291. }
  57292. renderer.render(this.object3D, this.camera);
  57293. if (savedBackground) {
  57294. this.object3D.background = savedBackground;
  57295. }
  57296. },
  57297. writable: true
  57298. }
  57299. })
  57300. });
  57301. /**
  57302. * Return the canvas size where the scene will be rendered.
  57303. * Will be always the window size except when the scene is embedded.
  57304. * The parent size (less than max size) will be returned in that case.
  57305. *
  57306. * @param {object} canvasEl - the canvas element
  57307. * @param {boolean} embedded - Is the scene embedded?
  57308. * @param {object} max - Max size parameters
  57309. * @param {boolean} isVR - If in VR
  57310. */
  57311. function getCanvasSize (canvasEl, embedded, maxSize, isVR) {
  57312. if (!canvasEl.parentElement) { return {height: 0, width: 0}; }
  57313. if (embedded) {
  57314. return {
  57315. height: canvasEl.parentElement.offsetHeight,
  57316. width: canvasEl.parentElement.offsetWidth
  57317. };
  57318. }
  57319. return getMaxSize(maxSize, isVR);
  57320. }
  57321. /**
  57322. * Return the canvas size. Will be the window size unless that size is greater than the
  57323. * maximum size (1920x1920 by default). The constrained size will be returned in that case,
  57324. * maintaining aspect ratio
  57325. *
  57326. * @param {object} maxSize - Max size parameters (width and height).
  57327. * @param {boolean} isVR - If in VR.
  57328. * @returns {object} Width and height.
  57329. */
  57330. function getMaxSize (maxSize, isVR) {
  57331. var aspectRatio;
  57332. var size;
  57333. var pixelRatio = window.devicePixelRatio;
  57334. size = {height: document.body.offsetHeight, width: document.body.offsetWidth};
  57335. if (!maxSize || isVR || (maxSize.width === -1 && maxSize.height === -1)) {
  57336. return size;
  57337. }
  57338. if (size.width * pixelRatio < maxSize.width &&
  57339. size.height * pixelRatio < maxSize.height) {
  57340. return size;
  57341. }
  57342. aspectRatio = size.width / size.height;
  57343. if ((size.width * pixelRatio) > maxSize.width && maxSize.width !== -1) {
  57344. size.width = Math.round(maxSize.width / pixelRatio);
  57345. size.height = Math.round(maxSize.width / aspectRatio / pixelRatio);
  57346. }
  57347. if ((size.height * pixelRatio) > maxSize.height && maxSize.height !== -1) {
  57348. size.height = Math.round(maxSize.height / pixelRatio);
  57349. size.width = Math.round(maxSize.height * aspectRatio / pixelRatio);
  57350. }
  57351. return size;
  57352. }
  57353. function requestFullscreen (canvas) {
  57354. var requestFullscreen =
  57355. canvas.requestFullscreen ||
  57356. canvas.webkitRequestFullscreen ||
  57357. canvas.mozRequestFullScreen || // The capitalized `S` is not a typo.
  57358. canvas.msRequestFullscreen;
  57359. // Hide navigation buttons on Android.
  57360. requestFullscreen.apply(canvas, [{navigationUI: 'hide'}]);
  57361. }
  57362. function exitFullscreen () {
  57363. var fullscreenEl =
  57364. document.fullscreenElement ||
  57365. document.webkitFullscreenElement ||
  57366. document.mozFullScreenElement;
  57367. if (!fullscreenEl) { return; }
  57368. if (document.exitFullscreen) {
  57369. document.exitFullscreen();
  57370. } else if (document.mozCancelFullScreen) {
  57371. document.mozCancelFullScreen();
  57372. } else if (document.webkitExitFullscreen) {
  57373. document.webkitExitFullscreen();
  57374. }
  57375. }
  57376. function setupCanvas (sceneEl) {
  57377. var canvasEl;
  57378. canvasEl = document.createElement('canvas');
  57379. canvasEl.classList.add('a-canvas');
  57380. // Mark canvas as provided/injected by A-Frame.
  57381. canvasEl.dataset.aframeCanvas = true;
  57382. sceneEl.appendChild(canvasEl);
  57383. document.addEventListener('fullscreenchange', onFullScreenChange);
  57384. document.addEventListener('mozfullscreenchange', onFullScreenChange);
  57385. document.addEventListener('webkitfullscreenchange', onFullScreenChange);
  57386. document.addEventListener('MSFullscreenChange', onFullScreenChange);
  57387. // Prevent overscroll on mobile.
  57388. canvasEl.addEventListener('touchmove', function (event) { event.preventDefault(); });
  57389. // Set canvas on scene.
  57390. sceneEl.canvas = canvasEl;
  57391. sceneEl.emit('render-target-loaded', {target: canvasEl});
  57392. // For unknown reasons a synchronous resize does not work on desktop when
  57393. // entering/exiting fullscreen.
  57394. setTimeout(bind(sceneEl.resize, sceneEl), 0);
  57395. function onFullScreenChange () {
  57396. var fullscreenEl =
  57397. document.fullscreenElement ||
  57398. document.mozFullScreenElement ||
  57399. document.webkitFullscreenElement;
  57400. // No fullscren element === exit fullscreen
  57401. if (!fullscreenEl) { sceneEl.exitVR(); }
  57402. document.activeElement.blur();
  57403. document.body.focus();
  57404. }
  57405. }
  57406. module.exports.setupCanvas = setupCanvas; // For testing.
  57407. },{"../../lib/three":179,"../../utils/":205,"../../utils/ios-orientationchange-blank-bug":206,"../a-entity":127,"../a-node":129,"../a-register-element":130,"../system":142,"./loadingScreen":135,"./metaTags":136,"./postMessage":137,"./scenes":138,"./wakelock":139}],135:[function(_dereq_,module,exports){
  57408. /* global THREE */
  57409. var utils = _dereq_('../../utils/');
  57410. var styleParser = utils.styleParser;
  57411. var sceneEl;
  57412. var titleEl;
  57413. var getSceneCanvasSize;
  57414. var ATTR_NAME = 'loading-screen';
  57415. var LOADER_TITLE_CLASS = 'a-loader-title';
  57416. module.exports.setup = function setup (el, getCanvasSize) {
  57417. sceneEl = el;
  57418. getSceneCanvasSize = getCanvasSize;
  57419. var loaderAttribute = sceneEl.hasAttribute(ATTR_NAME) ? styleParser.parse(sceneEl.getAttribute(ATTR_NAME)) : undefined;
  57420. var dotsColor = loaderAttribute && loaderAttribute.dotsColor || 'white';
  57421. var backgroundColor = loaderAttribute && loaderAttribute.backgroundColor || '#24CAFF';
  57422. var loaderEnabled = loaderAttribute === undefined || loaderAttribute.enabled === 'true' || loaderAttribute.enabled === undefined; // true default
  57423. var loaderScene;
  57424. var sphereGeometry;
  57425. var sphereMaterial;
  57426. var sphereMesh1;
  57427. var sphereMesh2;
  57428. var sphereMesh3;
  57429. var camera;
  57430. var clock;
  57431. var time;
  57432. var render;
  57433. if (!loaderEnabled) { return; }
  57434. // Setup Scene.
  57435. loaderScene = new THREE.Scene();
  57436. sphereGeometry = new THREE.SphereGeometry(0.20, 36, 18, 0, 2 * Math.PI, 0, Math.PI);
  57437. sphereMaterial = new THREE.MeshBasicMaterial({color: dotsColor});
  57438. sphereMesh1 = new THREE.Mesh(sphereGeometry, sphereMaterial);
  57439. sphereMesh2 = sphereMesh1.clone();
  57440. sphereMesh3 = sphereMesh1.clone();
  57441. camera = new THREE.PerspectiveCamera(80, window.innerWidth / window.innerHeight, 0.0005, 10000);
  57442. clock = new THREE.Clock();
  57443. time = 0;
  57444. render = function () {
  57445. sceneEl.renderer.render(loaderScene, camera);
  57446. time = clock.getElapsedTime() % 4;
  57447. sphereMesh1.visible = time >= 1;
  57448. sphereMesh2.visible = time >= 2;
  57449. sphereMesh3.visible = time >= 3;
  57450. };
  57451. loaderScene.background = new THREE.Color(backgroundColor);
  57452. loaderScene.add(camera);
  57453. sphereMesh1.position.set(-1, 0, -15);
  57454. sphereMesh2.position.set(0, 0, -15);
  57455. sphereMesh3.position.set(1, 0, -15);
  57456. camera.add(sphereMesh1);
  57457. camera.add(sphereMesh2);
  57458. camera.add(sphereMesh3);
  57459. setupTitle();
  57460. // Delay 200ms to avoid loader flashes.
  57461. setTimeout(function () {
  57462. if (sceneEl.hasLoaded) { return; }
  57463. resize(camera);
  57464. titleEl.style.display = 'block';
  57465. window.addEventListener('resize', function () { resize(camera); });
  57466. sceneEl.renderer.setAnimationLoop(render);
  57467. }, 200);
  57468. };
  57469. module.exports.remove = function remove () {
  57470. window.removeEventListener('resize', resize);
  57471. if (!titleEl) { return; }
  57472. // Hide title.
  57473. titleEl.style.display = 'none';
  57474. };
  57475. function resize (camera) {
  57476. var embedded = sceneEl.hasAttribute('embedded');
  57477. var size = getSceneCanvasSize(sceneEl.canvas, embedded, sceneEl.maxCanvasSize, sceneEl.is('vr-mode'));
  57478. camera.aspect = size.width / size.height;
  57479. camera.updateProjectionMatrix();
  57480. // Notify renderer of size change.
  57481. sceneEl.renderer.setSize(size.width, size.height, false);
  57482. }
  57483. function setupTitle () {
  57484. titleEl = document.createElement('div');
  57485. titleEl.className = LOADER_TITLE_CLASS;
  57486. titleEl.innerHTML = document.title;
  57487. titleEl.style.display = 'none';
  57488. sceneEl.appendChild(titleEl);
  57489. }
  57490. },{"../../utils/":205}],136:[function(_dereq_,module,exports){
  57491. var constants = _dereq_('../../constants/');
  57492. var extend = _dereq_('../../utils').extend;
  57493. var MOBILE_HEAD_TAGS = module.exports.MOBILE_HEAD_TAGS = [
  57494. Meta({name: 'viewport', content: 'width=device-width,initial-scale=1,maximum-scale=1,shrink-to-fit=no,user-scalable=no,minimal-ui,viewport-fit=cover'}),
  57495. // W3C-standardised meta tags.
  57496. Meta({name: 'mobile-web-app-capable', content: 'yes'}),
  57497. Meta({name: 'theme-color', content: 'black'})
  57498. ];
  57499. var MOBILE_IOS_HEAD_TAGS = [
  57500. // iOS-specific meta tags for fullscreen when pinning to homescreen.
  57501. Meta({name: 'apple-mobile-web-app-capable', content: 'yes'}),
  57502. Meta({name: 'apple-mobile-web-app-status-bar-style', content: 'black'}),
  57503. Link({rel: 'apple-touch-icon', href: 'https://aframe.io/images/aframe-logo-152.png'})
  57504. ];
  57505. function Meta (attrs) {
  57506. return {
  57507. tagName: 'meta',
  57508. attributes: attrs,
  57509. exists: function () { return document.querySelector('meta[name="' + attrs.name + '"]'); }
  57510. };
  57511. }
  57512. function Link (attrs) {
  57513. return {
  57514. tagName: 'link',
  57515. attributes: attrs,
  57516. exists: function () { return document.querySelector('link[rel="' + attrs.rel + '"]'); }
  57517. };
  57518. }
  57519. /**
  57520. * Injects the necessary metatags in the document for mobile support:
  57521. * 1. Prevent the user to zoom in the document.
  57522. * 2. Ensure that window.innerWidth and window.innerHeight have the correct
  57523. * values and the canvas is properly scaled.
  57524. * 3. To allow fullscreen mode when pinning a web app on the home screen on
  57525. * iOS.
  57526. * Adapted from https://www.reddit.com/r/web_design/comments/3la04p/
  57527. *
  57528. * @param {object} scene - Scene element
  57529. * @returns {Array}
  57530. */
  57531. module.exports.inject = function injectHeadTags (scene) {
  57532. var headEl = document.head;
  57533. var headScriptEl = headEl.querySelector('script');
  57534. var tag;
  57535. var headTags = [];
  57536. MOBILE_HEAD_TAGS.forEach(createAndInjectTag);
  57537. if (scene.isIOS) {
  57538. MOBILE_IOS_HEAD_TAGS.forEach(createAndInjectTag);
  57539. }
  57540. return headTags;
  57541. function createAndInjectTag (tagObj) {
  57542. if (!tagObj || tagObj.exists()) { return; }
  57543. tag = createTag(tagObj);
  57544. if (!tag) { return; }
  57545. if (headScriptEl) {
  57546. headScriptEl.parentNode.insertBefore(tag, headScriptEl);
  57547. } else {
  57548. headEl.appendChild(tag);
  57549. }
  57550. headTags.push(tag);
  57551. }
  57552. };
  57553. function createTag (tagObj) {
  57554. if (!tagObj || !tagObj.tagName) { return; }
  57555. var meta = document.createElement(tagObj.tagName);
  57556. meta.setAttribute(constants.AFRAME_INJECTED, '');
  57557. return extend(meta, tagObj.attributes);
  57558. }
  57559. },{"../../constants/":123,"../../utils":205}],137:[function(_dereq_,module,exports){
  57560. var bind = _dereq_('../../utils/bind');
  57561. var isIframed = _dereq_('../../utils/').isIframed;
  57562. /**
  57563. * Provides a post message API for scenes contained
  57564. * in an iframe.
  57565. */
  57566. module.exports = function initPostMessageAPI (scene) {
  57567. // Handles fullscreen behavior when inside an iframe.
  57568. if (!isIframed()) { return; }
  57569. // postMessage API handler
  57570. window.addEventListener('message', bind(postMessageAPIHandler, scene));
  57571. };
  57572. function postMessageAPIHandler (event) {
  57573. var scene = this;
  57574. if (!event.data) { return; }
  57575. switch (event.data.type) {
  57576. case 'vr': {
  57577. switch (event.data.data) {
  57578. case 'enter':
  57579. scene.enterVR();
  57580. break;
  57581. case 'exit':
  57582. scene.exitVR();
  57583. break;
  57584. }
  57585. }
  57586. }
  57587. }
  57588. },{"../../utils/":205,"../../utils/bind":199}],138:[function(_dereq_,module,exports){
  57589. /*
  57590. Scene index for keeping track of created scenes.
  57591. */
  57592. module.exports = [];
  57593. },{}],139:[function(_dereq_,module,exports){
  57594. var Wakelock = _dereq_('../../../vendor/wakelock/wakelock');
  57595. module.exports = function initWakelock (scene) {
  57596. if (!scene.isMobile) { return; }
  57597. var wakelock = scene.wakelock = new Wakelock();
  57598. scene.addEventListener('enter-vr', function () { wakelock.request(); });
  57599. scene.addEventListener('exit-vr', function () { wakelock.release(); });
  57600. };
  57601. },{"../../../vendor/wakelock/wakelock":220}],140:[function(_dereq_,module,exports){
  57602. var utils = _dereq_('../utils/');
  57603. var PropertyTypes = _dereq_('./propertyTypes');
  57604. var debug = utils.debug;
  57605. var isValidDefaultValue = PropertyTypes.isValidDefaultValue;
  57606. var propertyTypes = PropertyTypes.propertyTypes;
  57607. var warn = debug('core:schema:warn');
  57608. /**
  57609. * A schema is classified as a schema for a single property if:
  57610. * - `type` is defined on the schema as a string.
  57611. * - OR `default` is defined on the schema, as a reserved keyword.
  57612. * - OR schema is empty.
  57613. */
  57614. function isSingleProperty (schema) {
  57615. if ('type' in schema) {
  57616. return typeof schema.type === 'string';
  57617. }
  57618. return 'default' in schema;
  57619. }
  57620. module.exports.isSingleProperty = isSingleProperty;
  57621. /**
  57622. * Build step to schema to use `type` to inject default value, parser, and stringifier.
  57623. *
  57624. * @param {object} schema
  57625. * @param {string} componentName
  57626. * @returns {object} Schema.
  57627. */
  57628. module.exports.process = function (schema, componentName) {
  57629. var propName;
  57630. // For single property schema, run processPropDefinition over the whole schema.
  57631. if (isSingleProperty(schema)) {
  57632. return processPropertyDefinition(schema, componentName);
  57633. }
  57634. // For multi-property schema, run processPropDefinition over each property definition.
  57635. for (propName in schema) {
  57636. schema[propName] = processPropertyDefinition(schema[propName], componentName);
  57637. }
  57638. return schema;
  57639. };
  57640. /**
  57641. * Inject default value, parser, stringifier for single property.
  57642. *
  57643. * @param {object} propDefinition
  57644. * @param {string} componentName
  57645. */
  57646. function processPropertyDefinition (propDefinition, componentName) {
  57647. var defaultVal = propDefinition.default;
  57648. var isCustomType;
  57649. var propType;
  57650. var typeName = propDefinition.type;
  57651. // Type inference.
  57652. if (!propDefinition.type) {
  57653. if (defaultVal !== undefined &&
  57654. (typeof defaultVal === 'boolean' || typeof defaultVal === 'number')) {
  57655. // Type inference.
  57656. typeName = typeof defaultVal;
  57657. } else if (Array.isArray(defaultVal)) {
  57658. typeName = 'array';
  57659. } else {
  57660. // Fall back to string.
  57661. typeName = 'string';
  57662. }
  57663. } else if (propDefinition.type === 'bool') {
  57664. typeName = 'boolean';
  57665. } else if (propDefinition.type === 'float') {
  57666. typeName = 'number';
  57667. }
  57668. propType = propertyTypes[typeName];
  57669. if (!propType) {
  57670. warn('Unknown property type for component `' + componentName + '`: ' + typeName);
  57671. }
  57672. // Fill in parse and stringify using property types.
  57673. isCustomType = !!propDefinition.parse;
  57674. propDefinition.parse = propDefinition.parse || propType.parse;
  57675. propDefinition.stringify = propDefinition.stringify || propType.stringify;
  57676. // Fill in type name.
  57677. propDefinition.type = typeName;
  57678. // Check that default value exists.
  57679. if ('default' in propDefinition) {
  57680. // Check that default values are valid.
  57681. if (!isCustomType && !isValidDefaultValue(typeName, defaultVal)) {
  57682. warn('Default value `' + defaultVal + '` does not match type `' + typeName +
  57683. '` in component `' + componentName + '`');
  57684. }
  57685. } else {
  57686. // Fill in default value.
  57687. propDefinition.default = propType.default;
  57688. }
  57689. return propDefinition;
  57690. }
  57691. module.exports.processPropertyDefinition = processPropertyDefinition;
  57692. /**
  57693. * Parse propData using schema. Use default values if not existing in propData.
  57694. *
  57695. * @param {object} propData - Unparsed properties.
  57696. * @param {object} schema - Property types definition.
  57697. * @param {boolean} getPartialData - Whether to return full component data or just the data
  57698. * with keys in `propData`.
  57699. * @param {string } componentName - Name of the component, used for the property warning.
  57700. * @param {boolean} silent - Suppress warning messages.
  57701. */
  57702. module.exports.parseProperties = (function () {
  57703. var propNames = [];
  57704. return function (propData, schema, getPartialData, componentName, silent) {
  57705. var i;
  57706. var propName;
  57707. var propDefinition;
  57708. var propValue;
  57709. propNames.length = 0;
  57710. for (propName in (getPartialData ? propData : schema)) {
  57711. if (getPartialData && propData[propName] === undefined) { continue; }
  57712. propNames.push(propName);
  57713. }
  57714. if (propData === null || typeof propData !== 'object') { return propData; }
  57715. // Validation errors.
  57716. for (propName in propData) {
  57717. if (propData[propName] !== undefined && !schema[propName] && !silent) {
  57718. warn('Unknown property `' + propName +
  57719. '` for component/system `' + componentName + '`.');
  57720. }
  57721. }
  57722. for (i = 0; i < propNames.length; i++) {
  57723. propName = propNames[i];
  57724. propDefinition = schema[propName];
  57725. propValue = propData[propName];
  57726. if (!(schema[propName])) { return; }
  57727. propData[propName] = parseProperty(propValue, propDefinition);
  57728. }
  57729. return propData;
  57730. };
  57731. })();
  57732. /**
  57733. * Deserialize a single property.
  57734. */
  57735. function parseProperty (value, propDefinition) {
  57736. // Use default value if value is falsy.
  57737. if (value === undefined || value === null || value === '') {
  57738. value = propDefinition.default;
  57739. if (Array.isArray(value)) { value = value.slice(); }
  57740. }
  57741. // Invoke property type parser.
  57742. return propDefinition.parse(value, propDefinition.default);
  57743. }
  57744. module.exports.parseProperty = parseProperty;
  57745. /**
  57746. * Serialize a group of properties.
  57747. */
  57748. module.exports.stringifyProperties = function (propData, schema) {
  57749. var propName;
  57750. var propDefinition;
  57751. var propValue;
  57752. var stringifiedData = {};
  57753. var value;
  57754. for (propName in propData) {
  57755. propDefinition = schema[propName];
  57756. propValue = propData[propName];
  57757. value = propValue;
  57758. if (typeof value === 'object') {
  57759. value = stringifyProperty(propValue, propDefinition);
  57760. if (!propDefinition) { warn('Unknown component property: ' + propName); }
  57761. }
  57762. stringifiedData[propName] = value;
  57763. }
  57764. return stringifiedData;
  57765. };
  57766. /**
  57767. * Serialize a single property.
  57768. */
  57769. function stringifyProperty (value, propDefinition) {
  57770. // This function stringifies but it's used in a context where
  57771. // there's always second stringification pass. By returning the original
  57772. // value when it's not an object we save one unnecessary call
  57773. // to JSON.stringify.
  57774. if (typeof value !== 'object') { return value; }
  57775. // if there's no schema for the property we use standar JSON stringify
  57776. if (!propDefinition || value === null) { return JSON.stringify(value); }
  57777. return propDefinition.stringify(value);
  57778. }
  57779. module.exports.stringifyProperty = stringifyProperty;
  57780. },{"../utils/":205,"./propertyTypes":133}],141:[function(_dereq_,module,exports){
  57781. var schema = _dereq_('./schema');
  57782. var processSchema = schema.process;
  57783. var shaders = module.exports.shaders = {}; // Keep track of registered shaders.
  57784. var shaderNames = module.exports.shaderNames = []; // Keep track of the names of registered shaders.
  57785. var THREE = _dereq_('../lib/three');
  57786. var utils = _dereq_('../utils');
  57787. // A-Frame properties to three.js uniform types.
  57788. var propertyToThreeMapping = {
  57789. array: 'v3',
  57790. color: 'v3',
  57791. int: 'i',
  57792. number: 'f',
  57793. map: 't',
  57794. time: 'f',
  57795. vec2: 'v2',
  57796. vec3: 'v3',
  57797. vec4: 'v4'
  57798. };
  57799. /**
  57800. * Shader class definition.
  57801. *
  57802. * Shaders extend the material component API so you can create your own library
  57803. * of customized materials
  57804. *
  57805. */
  57806. var Shader = module.exports.Shader = function () {};
  57807. Shader.prototype = {
  57808. /**
  57809. * Contains the type schema and defaults for the data values.
  57810. * Data is coerced into the types of the values of the defaults.
  57811. */
  57812. schema: {},
  57813. vertexShader:
  57814. 'void main() {' +
  57815. 'gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);' +
  57816. '}',
  57817. fragmentShader:
  57818. 'void main() {' +
  57819. 'gl_FragColor = vec4(1.0, 0.0, 1.0, 1.0);' +
  57820. '}',
  57821. /**
  57822. * Init handler. Similar to attachedCallback.
  57823. * Called during shader initialization and is only run once.
  57824. */
  57825. init: function (data) {
  57826. this.attributes = this.initVariables(data, 'attribute');
  57827. this.uniforms = this.initVariables(data, 'uniform');
  57828. this.material = new (this.raw ? THREE.RawShaderMaterial : THREE.ShaderMaterial)({
  57829. // attributes: this.attributes,
  57830. uniforms: this.uniforms,
  57831. vertexShader: this.vertexShader,
  57832. fragmentShader: this.fragmentShader
  57833. });
  57834. return this.material;
  57835. },
  57836. initVariables: function (data, type) {
  57837. var key;
  57838. var schema = this.schema;
  57839. var variables = {};
  57840. var varType;
  57841. for (key in schema) {
  57842. if (schema[key].is !== type) { continue; }
  57843. varType = propertyToThreeMapping[schema[key].type];
  57844. variables[key] = {
  57845. type: varType,
  57846. value: undefined // Let updateVariables handle setting these.
  57847. };
  57848. }
  57849. return variables;
  57850. },
  57851. /**
  57852. * Update handler. Similar to attributeChangedCallback.
  57853. * Called whenever the associated material data changes.
  57854. *
  57855. * @param {object} data - New material data.
  57856. */
  57857. update: function (data) {
  57858. this.updateVariables(data, 'attribute');
  57859. this.updateVariables(data, 'uniform');
  57860. },
  57861. updateVariables: function (data, type) {
  57862. var key;
  57863. var materialKey;
  57864. var schema = this.schema;
  57865. var variables;
  57866. variables = type === 'uniform' ? this.uniforms : this.attributes;
  57867. for (key in data) {
  57868. if (!schema[key] || schema[key].is !== type) { continue; }
  57869. if (schema[key].type === 'map') {
  57870. // If data unchanged, get out early.
  57871. if (!variables[key] || variables[key].value === data[key]) { continue; }
  57872. // Special handling is needed for textures.
  57873. materialKey = '_texture_' + key;
  57874. // We can't actually set the variable correctly until we've loaded the texture.
  57875. this.setMapOnTextureLoad(variables, key, materialKey);
  57876. // Kick off the texture update now that handler is added.
  57877. utils.material.updateMapMaterialFromData(materialKey, key, this, data);
  57878. continue;
  57879. }
  57880. variables[key].value = this.parseValue(schema[key].type, data[key]);
  57881. variables[key].needsUpdate = true;
  57882. }
  57883. },
  57884. parseValue: function (type, value) {
  57885. var color;
  57886. switch (type) {
  57887. case 'vec2': {
  57888. return new THREE.Vector2(value.x, value.y);
  57889. }
  57890. case 'vec3': {
  57891. return new THREE.Vector3(value.x, value.y, value.z);
  57892. }
  57893. case 'vec4': {
  57894. return new THREE.Vector4(value.x, value.y, value.z, value.w);
  57895. }
  57896. case 'color': {
  57897. color = new THREE.Color(value);
  57898. return new THREE.Vector3(color.r, color.g, color.b);
  57899. }
  57900. case 'map': {
  57901. return THREE.ImageUtils.loadTexture(value);
  57902. }
  57903. default: {
  57904. return value;
  57905. }
  57906. }
  57907. },
  57908. setMapOnTextureLoad: function (variables, key, materialKey) {
  57909. var self = this;
  57910. this.el.addEventListener('materialtextureloaded', function () {
  57911. variables[key].value = self.material[materialKey];
  57912. variables[key].needsUpdate = true;
  57913. });
  57914. }
  57915. };
  57916. /**
  57917. * Registers a shader to A-Frame.
  57918. *
  57919. * @param {string} name - shader name.
  57920. * @param {object} definition - shader property and methods.
  57921. * @returns {object} Shader.
  57922. */
  57923. module.exports.registerShader = function (name, definition) {
  57924. var NewShader;
  57925. var proto = {};
  57926. // Format definition object to prototype object.
  57927. Object.keys(definition).forEach(function (key) {
  57928. proto[key] = {
  57929. value: definition[key],
  57930. writable: true
  57931. };
  57932. });
  57933. if (shaders[name]) {
  57934. throw new Error('The shader ' + name + ' has been already registered');
  57935. }
  57936. NewShader = function () { Shader.call(this); };
  57937. NewShader.prototype = Object.create(Shader.prototype, proto);
  57938. NewShader.prototype.name = name;
  57939. NewShader.prototype.constructor = NewShader;
  57940. shaders[name] = {
  57941. Shader: NewShader,
  57942. schema: processSchema(NewShader.prototype.schema)
  57943. };
  57944. shaderNames.push(name);
  57945. return NewShader;
  57946. };
  57947. },{"../lib/three":179,"../utils":205,"./schema":140}],142:[function(_dereq_,module,exports){
  57948. var components = _dereq_('./component');
  57949. var schema = _dereq_('./schema');
  57950. var utils = _dereq_('../utils/');
  57951. var parseProperties = schema.parseProperties;
  57952. var parseProperty = schema.parseProperty;
  57953. var processSchema = schema.process;
  57954. var isSingleProp = schema.isSingleProperty;
  57955. var styleParser = utils.styleParser;
  57956. var systems = module.exports.systems = {}; // Keep track of registered systems.
  57957. /**
  57958. * System class definition.
  57959. *
  57960. * Systems provide global scope and services to a group of instantiated components of the
  57961. * same class. They can also help abstract logic away from components such that components
  57962. * only have to worry about data.
  57963. *
  57964. * For example, a physics component that creates a physics world that oversees
  57965. * all entities with a physics or rigid body component.
  57966. *
  57967. * TODO: Have the System prototype reuse the Component prototype. Most code is copied
  57968. * and some pieces are missing from the Component facilities (e.g., attribute caching,
  57969. * setAttribute behavior).
  57970. *
  57971. * @member {string} name - Name that system is registered under.
  57972. * @member {Element} sceneEl - Handle to the scene element where system applies to.
  57973. */
  57974. var System = module.exports.System = function (sceneEl) {
  57975. var component = components && components.components[this.name];
  57976. // Set reference to scene.
  57977. this.el = sceneEl;
  57978. this.sceneEl = sceneEl;
  57979. // Set reference to matching component (if exists).
  57980. if (component) { component.Component.prototype.system = this; }
  57981. // Process system configuration.
  57982. this.buildData();
  57983. this.init();
  57984. this.update({});
  57985. };
  57986. System.prototype = {
  57987. /**
  57988. * Schema to configure system.
  57989. */
  57990. schema: {},
  57991. /**
  57992. * Init handler. Called during scene initialization and is only run once.
  57993. * Systems can use this to set initial state.
  57994. */
  57995. init: function () { /* no-op */ },
  57996. /**
  57997. * Update handler. Called during scene attribute updates.
  57998. * Systems can use this to dynamically update their state.
  57999. */
  58000. update: function (oldData) { /* no-op */ },
  58001. /**
  58002. * Build data and call update handler.
  58003. *
  58004. * @private
  58005. */
  58006. updateProperties: function (rawData) {
  58007. var oldData = this.data;
  58008. if (!Object.keys(schema).length) { return; }
  58009. this.buildData(rawData);
  58010. this.update(oldData);
  58011. },
  58012. /**
  58013. * Parse data.
  58014. */
  58015. buildData: function (rawData) {
  58016. var schema = this.schema;
  58017. if (!Object.keys(schema).length) { return; }
  58018. rawData = rawData || window.HTMLElement.prototype.getAttribute.call(this.sceneEl, this.name);
  58019. if (isSingleProp(schema)) {
  58020. this.data = parseProperty(rawData, schema);
  58021. } else {
  58022. this.data = parseProperties(styleParser.parse(rawData) || {}, schema);
  58023. }
  58024. },
  58025. /**
  58026. * Tick handler.
  58027. * Called on each tick of the scene render loop.
  58028. * Affected by play and pause.
  58029. *
  58030. * @param {number} time - Scene tick time.
  58031. * @param {number} timeDelta - Difference in current render time and previous render time.
  58032. */
  58033. tick: undefined,
  58034. /**
  58035. * Tock handler.
  58036. * Called on each tock of the scene render loop.
  58037. * Affected by play and pause.
  58038. *
  58039. * @param {number} time - Scene tick time.
  58040. * @param {number} timeDelta - Difference in current render time and previous render time.
  58041. */
  58042. tock: undefined,
  58043. /**
  58044. * Called to start any dynamic behavior (e.g., animation, AI, events, physics).
  58045. */
  58046. play: function () { /* no-op */ },
  58047. /**
  58048. * Called to stop any dynamic behavior (e.g., animation, AI, events, physics).
  58049. */
  58050. pause: function () { /* no-op */ }
  58051. };
  58052. /**
  58053. * Registers a system to A-Frame.
  58054. *
  58055. * @param {string} name - Component name.
  58056. * @param {object} definition - Component property and methods.
  58057. * @returns {object} Component.
  58058. */
  58059. module.exports.registerSystem = function (name, definition) {
  58060. var i;
  58061. var NewSystem;
  58062. var proto = {};
  58063. var scenes = utils.findAllScenes(document);
  58064. // Format definition object to prototype object.
  58065. Object.keys(definition).forEach(function (key) {
  58066. proto[key] = {
  58067. value: definition[key],
  58068. writable: true
  58069. };
  58070. });
  58071. if (systems[name]) {
  58072. throw new Error('The system `' + name + '` has been already registered. ' +
  58073. 'Check that you are not loading two versions of the same system ' +
  58074. 'or two different systems of the same name.');
  58075. }
  58076. NewSystem = function (sceneEl) { System.call(this, sceneEl); };
  58077. NewSystem.prototype = Object.create(System.prototype, proto);
  58078. NewSystem.prototype.name = name;
  58079. NewSystem.prototype.constructor = NewSystem;
  58080. NewSystem.prototype.schema = utils.extend(processSchema(NewSystem.prototype.schema));
  58081. systems[name] = NewSystem;
  58082. // Initialize systems for existing scenes
  58083. for (i = 0; i < scenes.length; i++) { scenes[i].initSystem(name); }
  58084. };
  58085. },{"../utils/":205,"./component":131,"./schema":140}],143:[function(_dereq_,module,exports){
  58086. _dereq_('./pivot');
  58087. },{"./pivot":144}],144:[function(_dereq_,module,exports){
  58088. var registerComponent = _dereq_('../../core/component').registerComponent;
  58089. var THREE = _dereq_('../../lib/three');
  58090. var originalPosition = new THREE.Vector3();
  58091. var originalRotation = new THREE.Vector3();
  58092. /**
  58093. * Wrap el.object3D within an outer group. Apply pivot to el.object3D as position.
  58094. */
  58095. registerComponent('pivot', {
  58096. dependencies: ['position'],
  58097. schema: {type: 'vec3'},
  58098. init: function () {
  58099. var data = this.data;
  58100. var el = this.el;
  58101. var originalParent = el.object3D.parent;
  58102. var originalGroup = el.object3D;
  58103. var outerGroup = new THREE.Group();
  58104. originalPosition.copy(originalGroup.position);
  58105. originalRotation.copy(originalGroup.rotation);
  58106. // Detach current group from parent.
  58107. originalParent.remove(originalGroup);
  58108. outerGroup.add(originalGroup);
  58109. // Set new group as the outer group.
  58110. originalParent.add(outerGroup);
  58111. // Set outer group as new object3D.
  58112. el.object3D = outerGroup;
  58113. // Apply pivot to original group.
  58114. originalGroup.position.set(-1 * data.x, -1 * data.y, -1 * data.z);
  58115. // Offset the pivot so that world position not affected.
  58116. // And restore position onto outer group.
  58117. outerGroup.position.set(data.x + originalPosition.x, data.y + originalPosition.y,
  58118. data.z + originalPosition.z);
  58119. // Transfer rotation to outer group.
  58120. outerGroup.rotation.copy(originalGroup.rotation);
  58121. originalGroup.rotation.set(0, 0, 0);
  58122. }
  58123. });
  58124. },{"../../core/component":131,"../../lib/three":179}],145:[function(_dereq_,module,exports){
  58125. /**
  58126. * Common mesh defaults, mappings, and transforms.
  58127. */
  58128. var components = _dereq_('../../core/component').components;
  58129. var shaders = _dereq_('../../core/shader').shaders;
  58130. var utils = _dereq_('../../utils/');
  58131. var materialMappings = {};
  58132. Object.keys(components.material.schema).forEach(addMapping);
  58133. Object.keys(shaders.standard.schema).forEach(addMapping);
  58134. function addMapping (prop) {
  58135. // To hyphenated.
  58136. var htmlAttrName = prop.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();
  58137. if (prop === 'fog') { htmlAttrName = 'material-fog'; }
  58138. if (prop === 'visible') { htmlAttrName = 'material-visible'; }
  58139. materialMappings[htmlAttrName] = 'material.' + prop;
  58140. }
  58141. module.exports = function getMeshMixin () {
  58142. return {
  58143. defaultComponents: {material: {}},
  58144. mappings: utils.extend({}, materialMappings)
  58145. };
  58146. };
  58147. },{"../../core/component":131,"../../core/shader":141,"../../utils/":205}],146:[function(_dereq_,module,exports){
  58148. _dereq_('./primitives/a-camera');
  58149. _dereq_('./primitives/a-cursor');
  58150. _dereq_('./primitives/a-curvedimage');
  58151. _dereq_('./primitives/a-gltf-model');
  58152. _dereq_('./primitives/a-image');
  58153. _dereq_('./primitives/a-light');
  58154. _dereq_('./primitives/a-link');
  58155. _dereq_('./primitives/a-obj-model');
  58156. _dereq_('./primitives/a-sky');
  58157. _dereq_('./primitives/a-sound');
  58158. _dereq_('./primitives/a-text');
  58159. _dereq_('./primitives/a-video');
  58160. _dereq_('./primitives/a-videosphere');
  58161. _dereq_('./primitives/meshPrimitives');
  58162. },{"./primitives/a-camera":148,"./primitives/a-cursor":149,"./primitives/a-curvedimage":150,"./primitives/a-gltf-model":151,"./primitives/a-image":152,"./primitives/a-light":153,"./primitives/a-link":154,"./primitives/a-obj-model":155,"./primitives/a-sky":156,"./primitives/a-sound":157,"./primitives/a-text":158,"./primitives/a-video":159,"./primitives/a-videosphere":160,"./primitives/meshPrimitives":161}],147:[function(_dereq_,module,exports){
  58163. var AEntity = _dereq_('../../core/a-entity');
  58164. var components = _dereq_('../../core/component').components;
  58165. var registerElement = _dereq_('../../core/a-register-element').registerElement;
  58166. var utils = _dereq_('../../utils/');
  58167. var debug = utils.debug;
  58168. var setComponentProperty = utils.entity.setComponentProperty;
  58169. var log = debug('extras:primitives:debug');
  58170. var warn = debug('extras:primitives:warn');
  58171. var primitives = module.exports.primitives = {};
  58172. module.exports.registerPrimitive = function registerPrimitive (name, definition) {
  58173. name = name.toLowerCase();
  58174. log('Registering <%s>', name);
  58175. // Deprecation warning for defaultAttributes usage.
  58176. if (definition.defaultAttributes) {
  58177. warn("The 'defaultAttributes' object is deprecated. Use 'defaultComponents' instead.");
  58178. }
  58179. var primitive = registerElement(name, {
  58180. prototype: Object.create(AEntity.prototype, {
  58181. defaultComponentsFromPrimitive: {
  58182. value: definition.defaultComponents || definition.defaultAttributes || {}
  58183. },
  58184. deprecated: {value: definition.deprecated || null},
  58185. deprecatedMappings: {value: definition.deprecatedMappings || {}},
  58186. mappings: {value: definition.mappings || {}},
  58187. createdCallback: {
  58188. value: function () {
  58189. if (definition.deprecated) { console.warn(definition.deprecated); }
  58190. this.resolveMappingCollisions();
  58191. }
  58192. },
  58193. /**
  58194. * If a mapping collides with a registered component name
  58195. * it renames the mapping to componentname-property
  58196. */
  58197. resolveMappingCollisions: {
  58198. value: function () {
  58199. var mappings = this.mappings;
  58200. var self = this;
  58201. Object.keys(mappings).forEach(function resolveCollision (key) {
  58202. var newAttribute;
  58203. if (key !== key.toLowerCase()) { warn('Mapping keys should be specified in lower case. The mapping key ' + key + ' may not be recognized'); }
  58204. if (components[key]) {
  58205. newAttribute = mappings[key].replace('.', '-');
  58206. mappings[newAttribute] = mappings[key];
  58207. delete mappings[key];
  58208. console.warn('The primitive ' + self.tagName.toLowerCase() + ' has a mapping collision. ' +
  58209. 'The attribute ' + key + ' has the same name as a registered component and' +
  58210. ' has been renamed to ' + newAttribute);
  58211. }
  58212. });
  58213. }
  58214. },
  58215. getExtraComponents: {
  58216. value: function () {
  58217. var attr;
  58218. var data;
  58219. var i;
  58220. var mapping;
  58221. var mixins;
  58222. var path;
  58223. var self = this;
  58224. // Gather component data from default components.
  58225. data = utils.clone(this.defaultComponentsFromPrimitive);
  58226. // Factor in mixins to overwrite default components.
  58227. mixins = this.getAttribute('mixin');
  58228. if (mixins) {
  58229. mixins = mixins.trim().split(' ');
  58230. mixins.forEach(function applyMixin (mixinId) {
  58231. var mixinComponents = self.sceneEl.querySelector('#' + mixinId).componentCache;
  58232. Object.keys(mixinComponents).forEach(function setComponent (name) {
  58233. data[name] = extend(data[name], mixinComponents[name]);
  58234. });
  58235. });
  58236. }
  58237. // Gather component data from mappings.
  58238. for (i = 0; i < this.attributes.length; i++) {
  58239. attr = this.attributes[i];
  58240. mapping = this.mappings[attr.name];
  58241. if (mapping) {
  58242. path = utils.entity.getComponentPropertyPath(mapping);
  58243. if (path.constructor === Array) {
  58244. data[path[0]] = data[path[0]] || {};
  58245. data[path[0]][path[1]] = attr.value.trim();
  58246. } else {
  58247. data[path] = attr.value.trim();
  58248. }
  58249. continue;
  58250. }
  58251. }
  58252. return data;
  58253. /**
  58254. * For the base to be extensible, both objects must be pure JavaScript objects.
  58255. * The function assumes that base is undefined, or null or a pure object.
  58256. */
  58257. function extend (base, extension) {
  58258. if (isUndefined(base)) {
  58259. return copy(extension);
  58260. }
  58261. if (isUndefined(extension)) {
  58262. return copy(base);
  58263. }
  58264. if (isPureObject(base) && isPureObject(extension)) {
  58265. return utils.extendDeep(base, extension);
  58266. }
  58267. return copy(extension);
  58268. }
  58269. function isUndefined (value) {
  58270. return typeof value === 'undefined';
  58271. }
  58272. function copy (value) {
  58273. if (isPureObject(value)) {
  58274. return utils.extendDeep({}, value);
  58275. }
  58276. return value;
  58277. }
  58278. function isPureObject (value) {
  58279. return value !== null && value.constructor === Object;
  58280. }
  58281. }
  58282. },
  58283. /**
  58284. * Sync to attribute to component property whenever mapped attribute changes.
  58285. * If attribute is mapped to a component property, set the component property using
  58286. * the attribute value.
  58287. */
  58288. attributeChangedCallback: {
  58289. value: function (attr, oldVal, value) {
  58290. var componentName = this.mappings[attr];
  58291. if (attr in this.deprecatedMappings) {
  58292. console.warn(this.deprecatedMappings[attr]);
  58293. }
  58294. if (!attr || !componentName) { return; }
  58295. // Set value.
  58296. setComponentProperty(this, componentName, value);
  58297. }
  58298. }
  58299. })
  58300. });
  58301. // Store.
  58302. primitives[name] = primitive;
  58303. return primitive;
  58304. };
  58305. /**
  58306. * Add component mappings using schema.
  58307. */
  58308. function addComponentMapping (componentName, mappings) {
  58309. var schema = components[componentName].schema;
  58310. Object.keys(schema).map(function (prop) {
  58311. // Hyphenate where there is camelCase.
  58312. var attrName = prop.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();
  58313. // If there is a mapping collision, prefix with component name and hyphen.
  58314. if (mappings[attrName] !== undefined) { attrName = componentName + '-' + prop; }
  58315. mappings[attrName] = componentName + '.' + prop;
  58316. });
  58317. }
  58318. /**
  58319. * Helper to define a primitive, building mappings using a component schema.
  58320. */
  58321. function definePrimitive (tagName, defaultComponents, mappings) {
  58322. // If no initial mappings provided, start from empty map.
  58323. mappings = mappings || {};
  58324. // From the default components, add mapping automagically.
  58325. Object.keys(defaultComponents).map(function buildMappings (componentName) {
  58326. addComponentMapping(componentName, mappings);
  58327. });
  58328. // Register the primitive.
  58329. module.exports.registerPrimitive(tagName, utils.extendDeep({}, null, {
  58330. defaultComponents: defaultComponents,
  58331. mappings: mappings
  58332. }));
  58333. }
  58334. module.exports.definePrimitive = definePrimitive;
  58335. },{"../../core/a-entity":127,"../../core/a-register-element":130,"../../core/component":131,"../../utils/":205}],148:[function(_dereq_,module,exports){
  58336. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  58337. registerPrimitive('a-camera', {
  58338. defaultComponents: {
  58339. 'camera': {},
  58340. 'look-controls': {},
  58341. 'wasd-controls': {},
  58342. 'position': {x: 0, y: 1.6, z: 0}
  58343. },
  58344. mappings: {
  58345. active: 'camera.active',
  58346. far: 'camera.far',
  58347. fov: 'camera.fov',
  58348. 'look-controls-enabled': 'look-controls.enabled',
  58349. near: 'camera.near',
  58350. 'pointer-lock-enabled': 'look-controls.pointerLockEnabled',
  58351. 'wasd-controls-enabled': 'wasd-controls.enabled',
  58352. 'reverse-mouse-drag': 'look-controls.reverseMouseDrag',
  58353. zoom: 'camera.zoom'
  58354. }
  58355. });
  58356. },{"../primitives":147}],149:[function(_dereq_,module,exports){
  58357. var getMeshMixin = _dereq_('../getMeshMixin');
  58358. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  58359. var utils = _dereq_('../../../utils/');
  58360. registerPrimitive('a-cursor', utils.extendDeep({}, getMeshMixin(), {
  58361. defaultComponents: {
  58362. cursor: {},
  58363. geometry: {
  58364. primitive: 'ring',
  58365. radiusOuter: 0.016,
  58366. radiusInner: 0.01,
  58367. segmentsTheta: 32
  58368. },
  58369. material: {
  58370. color: '#000',
  58371. shader: 'flat',
  58372. opacity: 0.8
  58373. },
  58374. position: {
  58375. x: 0,
  58376. y: 0,
  58377. z: -1
  58378. }
  58379. },
  58380. mappings: {
  58381. far: 'raycaster.far',
  58382. fuse: 'cursor.fuse',
  58383. 'fuse-timeout': 'cursor.fuseTimeout',
  58384. interval: 'raycaster.interval',
  58385. objects: 'raycaster.objects'
  58386. }
  58387. }));
  58388. },{"../../../utils/":205,"../getMeshMixin":145,"../primitives":147}],150:[function(_dereq_,module,exports){
  58389. var getMeshMixin = _dereq_('../getMeshMixin');
  58390. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  58391. var utils = _dereq_('../../../utils/');
  58392. registerPrimitive('a-curvedimage', utils.extendDeep({}, getMeshMixin(), {
  58393. defaultComponents: {
  58394. geometry: {
  58395. height: 1,
  58396. primitive: 'cylinder',
  58397. radius: 2,
  58398. segmentsRadial: 48,
  58399. thetaLength: 270,
  58400. openEnded: true,
  58401. thetaStart: 0
  58402. },
  58403. material: {
  58404. color: '#FFF',
  58405. shader: 'flat',
  58406. side: 'double',
  58407. transparent: true,
  58408. repeat: '-1 1'
  58409. }
  58410. },
  58411. mappings: {
  58412. height: 'geometry.height',
  58413. 'open-ended': 'geometry.openEnded',
  58414. radius: 'geometry.radius',
  58415. segments: 'geometry.segmentsRadial',
  58416. start: 'geometry.thetaStart',
  58417. 'theta-length': 'geometry.thetaLength',
  58418. 'theta-start': 'geometry.thetaStart',
  58419. 'width': 'geometry.thetaLength'
  58420. }
  58421. }));
  58422. },{"../../../utils/":205,"../getMeshMixin":145,"../primitives":147}],151:[function(_dereq_,module,exports){
  58423. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  58424. registerPrimitive('a-gltf-model', {
  58425. mappings: {
  58426. src: 'gltf-model'
  58427. }
  58428. });
  58429. },{"../primitives":147}],152:[function(_dereq_,module,exports){
  58430. var getMeshMixin = _dereq_('../getMeshMixin');
  58431. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  58432. var utils = _dereq_('../../../utils/');
  58433. registerPrimitive('a-image', utils.extendDeep({}, getMeshMixin(), {
  58434. defaultComponents: {
  58435. geometry: {
  58436. primitive: 'plane'
  58437. },
  58438. material: {
  58439. color: '#FFF',
  58440. shader: 'flat',
  58441. side: 'double',
  58442. transparent: true
  58443. }
  58444. },
  58445. mappings: {
  58446. height: 'geometry.height',
  58447. width: 'geometry.width'
  58448. }
  58449. }));
  58450. },{"../../../utils/":205,"../getMeshMixin":145,"../primitives":147}],153:[function(_dereq_,module,exports){
  58451. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  58452. registerPrimitive('a-light', {
  58453. defaultComponents: {
  58454. light: {}
  58455. },
  58456. mappings: {
  58457. angle: 'light.angle',
  58458. color: 'light.color',
  58459. 'ground-color': 'light.groundColor',
  58460. decay: 'light.decay',
  58461. distance: 'light.distance',
  58462. intensity: 'light.intensity',
  58463. penumbra: 'light.penumbra',
  58464. type: 'light.type',
  58465. target: 'light.target'
  58466. }
  58467. });
  58468. },{"../primitives":147}],154:[function(_dereq_,module,exports){
  58469. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  58470. registerPrimitive('a-link', {
  58471. defaultComponents: {
  58472. link: {
  58473. visualAspectEnabled: true
  58474. }
  58475. },
  58476. mappings: {
  58477. href: 'link.href',
  58478. image: 'link.image',
  58479. title: 'link.title'
  58480. }
  58481. });
  58482. },{"../primitives":147}],155:[function(_dereq_,module,exports){
  58483. var meshMixin = _dereq_('../getMeshMixin')();
  58484. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  58485. var utils = _dereq_('../../../utils/');
  58486. registerPrimitive('a-obj-model', utils.extendDeep({}, meshMixin, {
  58487. defaultComponents: {
  58488. 'obj-model': {}
  58489. },
  58490. mappings: {
  58491. src: 'obj-model.obj',
  58492. mtl: 'obj-model.mtl'
  58493. }
  58494. }));
  58495. },{"../../../utils/":205,"../getMeshMixin":145,"../primitives":147}],156:[function(_dereq_,module,exports){
  58496. var getMeshMixin = _dereq_('../getMeshMixin');
  58497. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  58498. var utils = _dereq_('../../../utils/');
  58499. var meshPrimitives = _dereq_('./meshPrimitives');
  58500. registerPrimitive('a-sky', utils.extendDeep({}, getMeshMixin(), {
  58501. defaultComponents: {
  58502. geometry: {
  58503. primitive: 'sphere',
  58504. radius: 500,
  58505. segmentsWidth: 64,
  58506. segmentsHeight: 32
  58507. },
  58508. material: {
  58509. color: '#FFF',
  58510. side: 'back',
  58511. shader: 'flat',
  58512. npot: true
  58513. },
  58514. scale: '-1 1 1'
  58515. },
  58516. mappings: utils.extendDeep({}, meshPrimitives['a-sphere'].prototype.mappings)
  58517. }));
  58518. },{"../../../utils/":205,"../getMeshMixin":145,"../primitives":147,"./meshPrimitives":161}],157:[function(_dereq_,module,exports){
  58519. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  58520. registerPrimitive('a-sound', {
  58521. defaultComponents: {
  58522. sound: {}
  58523. },
  58524. mappings: {
  58525. src: 'sound.src',
  58526. on: 'sound.on',
  58527. autoplay: 'sound.autoplay',
  58528. loop: 'sound.loop',
  58529. volume: 'sound.volume'
  58530. }
  58531. });
  58532. },{"../primitives":147}],158:[function(_dereq_,module,exports){
  58533. // <a-text> using `definePrimitive` helper.
  58534. var definePrimitive = _dereq_('../primitives').definePrimitive;
  58535. definePrimitive('a-text', {text: {anchor: 'align', width: 5}});
  58536. },{"../primitives":147}],159:[function(_dereq_,module,exports){
  58537. var getMeshMixin = _dereq_('../getMeshMixin');
  58538. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  58539. var utils = _dereq_('../../../utils/');
  58540. registerPrimitive('a-video', utils.extendDeep({}, getMeshMixin(), {
  58541. defaultComponents: {
  58542. geometry: {
  58543. primitive: 'plane'
  58544. },
  58545. material: {
  58546. color: '#FFF',
  58547. shader: 'flat',
  58548. side: 'double',
  58549. transparent: true
  58550. }
  58551. },
  58552. mappings: {
  58553. height: 'geometry.height',
  58554. width: 'geometry.width'
  58555. }
  58556. }));
  58557. },{"../../../utils/":205,"../getMeshMixin":145,"../primitives":147}],160:[function(_dereq_,module,exports){
  58558. var getMeshMixin = _dereq_('../getMeshMixin');
  58559. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  58560. var utils = _dereq_('../../../utils/');
  58561. registerPrimitive('a-videosphere', utils.extendDeep({}, getMeshMixin(), {
  58562. defaultComponents: {
  58563. geometry: {
  58564. primitive: 'sphere',
  58565. radius: 500,
  58566. segmentsWidth: 64,
  58567. segmentsHeight: 32
  58568. },
  58569. material: {
  58570. color: '#FFF',
  58571. shader: 'flat',
  58572. side: 'back',
  58573. npot: true
  58574. },
  58575. scale: '-1 1 1'
  58576. },
  58577. mappings: {
  58578. radius: 'geometry.radius',
  58579. 'segments-height': 'geometry.segmentsHeight',
  58580. 'segments-width': 'geometry.segmentsWidth'
  58581. }
  58582. }));
  58583. },{"../../../utils/":205,"../getMeshMixin":145,"../primitives":147}],161:[function(_dereq_,module,exports){
  58584. /**
  58585. * Automated mesh primitive registration.
  58586. */
  58587. var getMeshMixin = _dereq_('../getMeshMixin');
  58588. var geometries = _dereq_('../../../core/geometry').geometries;
  58589. var geometryNames = _dereq_('../../../core/geometry').geometryNames;
  58590. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  58591. var utils = _dereq_('../../../utils/');
  58592. // For testing.
  58593. var meshPrimitives = module.exports = {};
  58594. // Generate primitive for each geometry type.
  58595. geometryNames.forEach(function registerMeshPrimitive (geometryName) {
  58596. var geometry = geometries[geometryName];
  58597. var geometryHyphened = unCamelCase(geometryName);
  58598. // Generate mappings.
  58599. var mappings = {};
  58600. Object.keys(geometry.schema).forEach(function createMapping (property) {
  58601. mappings[unCamelCase(property)] = 'geometry.' + property;
  58602. });
  58603. // Register.
  58604. var tagName = 'a-' + geometryHyphened;
  58605. var primitive = registerPrimitive(tagName, utils.extendDeep({}, getMeshMixin(), {
  58606. defaultComponents: {geometry: {primitive: geometryName}},
  58607. mappings: mappings
  58608. }));
  58609. meshPrimitives[tagName] = primitive;
  58610. });
  58611. /**
  58612. * camelCase to hyphened-string.
  58613. */
  58614. function unCamelCase (str) {
  58615. return str.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();
  58616. }
  58617. },{"../../../core/geometry":132,"../../../utils/":205,"../getMeshMixin":145,"../primitives":147}],162:[function(_dereq_,module,exports){
  58618. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  58619. var THREE = _dereq_('../lib/three');
  58620. registerGeometry('box', {
  58621. schema: {
  58622. depth: {default: 1, min: 0},
  58623. height: {default: 1, min: 0},
  58624. width: {default: 1, min: 0},
  58625. segmentsHeight: {default: 1, min: 1, max: 20, type: 'int'},
  58626. segmentsWidth: {default: 1, min: 1, max: 20, type: 'int'},
  58627. segmentsDepth: {default: 1, min: 1, max: 20, type: 'int'}
  58628. },
  58629. init: function (data) {
  58630. this.geometry = new THREE.BoxGeometry(
  58631. data.width, data.height, data.depth,
  58632. data.segmentsWidth, data.segmentsHeight, data.segmentsDepth);
  58633. }
  58634. });
  58635. },{"../core/geometry":132,"../lib/three":179}],163:[function(_dereq_,module,exports){
  58636. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  58637. var THREE = _dereq_('../lib/three');
  58638. var degToRad = THREE.Math.degToRad;
  58639. registerGeometry('circle', {
  58640. schema: {
  58641. radius: {default: 1, min: 0},
  58642. segments: {default: 32, min: 3, type: 'int'},
  58643. thetaLength: {default: 360, min: 0},
  58644. thetaStart: {default: 0}
  58645. },
  58646. init: function (data) {
  58647. this.geometry = new THREE.CircleGeometry(
  58648. data.radius, data.segments, degToRad(data.thetaStart), degToRad(data.thetaLength));
  58649. }
  58650. });
  58651. },{"../core/geometry":132,"../lib/three":179}],164:[function(_dereq_,module,exports){
  58652. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  58653. var THREE = _dereq_('../lib/three');
  58654. var degToRad = THREE.Math.degToRad;
  58655. registerGeometry('cone', {
  58656. schema: {
  58657. height: {default: 1, min: 0},
  58658. openEnded: {default: false},
  58659. radiusBottom: {default: 1, min: 0},
  58660. radiusTop: {default: 0.01, min: 0},
  58661. segmentsHeight: {default: 18, min: 1, type: 'int'},
  58662. segmentsRadial: {default: 36, min: 3, type: 'int'},
  58663. thetaLength: {default: 360, min: 0},
  58664. thetaStart: {default: 0}
  58665. },
  58666. init: function (data) {
  58667. this.geometry = new THREE.CylinderGeometry(
  58668. data.radiusTop, data.radiusBottom, data.height, data.segmentsRadial,
  58669. data.segmentsHeight, data.openEnded, degToRad(data.thetaStart),
  58670. degToRad(data.thetaLength));
  58671. }
  58672. });
  58673. },{"../core/geometry":132,"../lib/three":179}],165:[function(_dereq_,module,exports){
  58674. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  58675. var THREE = _dereq_('../lib/three');
  58676. var degToRad = THREE.Math.degToRad;
  58677. registerGeometry('cylinder', {
  58678. schema: {
  58679. height: {default: 1, min: 0},
  58680. openEnded: {default: false},
  58681. radius: {default: 1, min: 0},
  58682. segmentsHeight: {default: 18, min: 1, type: 'int'},
  58683. segmentsRadial: {default: 36, min: 3, type: 'int'},
  58684. thetaLength: {default: 360, min: 0},
  58685. thetaStart: {default: 0}
  58686. },
  58687. init: function (data) {
  58688. this.geometry = new THREE.CylinderGeometry(
  58689. data.radius, data.radius, data.height, data.segmentsRadial, data.segmentsHeight,
  58690. data.openEnded, degToRad(data.thetaStart), degToRad(data.thetaLength));
  58691. }
  58692. });
  58693. },{"../core/geometry":132,"../lib/three":179}],166:[function(_dereq_,module,exports){
  58694. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  58695. var THREE = _dereq_('../lib/three');
  58696. registerGeometry('dodecahedron', {
  58697. schema: {
  58698. detail: {default: 0, min: 0, max: 5, type: 'int'},
  58699. radius: {default: 1, min: 0}
  58700. },
  58701. init: function (data) {
  58702. this.geometry = new THREE.DodecahedronGeometry(data.radius, data.detail);
  58703. }
  58704. });
  58705. },{"../core/geometry":132,"../lib/three":179}],167:[function(_dereq_,module,exports){
  58706. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  58707. var THREE = _dereq_('../lib/three');
  58708. registerGeometry('icosahedron', {
  58709. schema: {
  58710. detail: {default: 0, min: 0, max: 5, type: 'int'},
  58711. radius: {default: 1, min: 0}
  58712. },
  58713. init: function (data) {
  58714. this.geometry = new THREE.IcosahedronGeometry(data.radius, data.detail);
  58715. }
  58716. });
  58717. },{"../core/geometry":132,"../lib/three":179}],168:[function(_dereq_,module,exports){
  58718. _dereq_('./box.js');
  58719. _dereq_('./circle.js');
  58720. _dereq_('./cone.js');
  58721. _dereq_('./cylinder.js');
  58722. _dereq_('./dodecahedron.js');
  58723. _dereq_('./icosahedron.js');
  58724. _dereq_('./octahedron.js');
  58725. _dereq_('./plane.js');
  58726. _dereq_('./ring.js');
  58727. _dereq_('./sphere.js');
  58728. _dereq_('./tetrahedron.js');
  58729. _dereq_('./torus.js');
  58730. _dereq_('./torusKnot.js');
  58731. _dereq_('./triangle.js');
  58732. },{"./box.js":162,"./circle.js":163,"./cone.js":164,"./cylinder.js":165,"./dodecahedron.js":166,"./icosahedron.js":167,"./octahedron.js":169,"./plane.js":170,"./ring.js":171,"./sphere.js":172,"./tetrahedron.js":173,"./torus.js":174,"./torusKnot.js":175,"./triangle.js":176}],169:[function(_dereq_,module,exports){
  58733. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  58734. var THREE = _dereq_('../lib/three');
  58735. registerGeometry('octahedron', {
  58736. schema: {
  58737. detail: {default: 0, min: 0, max: 5, type: 'int'},
  58738. radius: {default: 1, min: 0}
  58739. },
  58740. init: function (data) {
  58741. this.geometry = new THREE.OctahedronGeometry(data.radius, data.detail);
  58742. }
  58743. });
  58744. },{"../core/geometry":132,"../lib/three":179}],170:[function(_dereq_,module,exports){
  58745. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  58746. var THREE = _dereq_('../lib/three');
  58747. registerGeometry('plane', {
  58748. schema: {
  58749. height: {default: 1, min: 0},
  58750. width: {default: 1, min: 0},
  58751. segmentsHeight: {default: 1, min: 1, max: 20, type: 'int'},
  58752. segmentsWidth: {default: 1, min: 1, max: 20, type: 'int'}
  58753. },
  58754. init: function (data) {
  58755. this.geometry = new THREE.PlaneGeometry(data.width, data.height, data.segmentsWidth, data.segmentsHeight);
  58756. }
  58757. });
  58758. },{"../core/geometry":132,"../lib/three":179}],171:[function(_dereq_,module,exports){
  58759. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  58760. var THREE = _dereq_('../lib/three');
  58761. var degToRad = THREE.Math.degToRad;
  58762. registerGeometry('ring', {
  58763. schema: {
  58764. radiusInner: {default: 0.8, min: 0},
  58765. radiusOuter: {default: 1.2, min: 0},
  58766. segmentsPhi: {default: 10, min: 1, type: 'int'},
  58767. segmentsTheta: {default: 32, min: 3, type: 'int'},
  58768. thetaLength: {default: 360, min: 0},
  58769. thetaStart: {default: 0}
  58770. },
  58771. init: function (data) {
  58772. this.geometry = new THREE.RingGeometry(
  58773. data.radiusInner, data.radiusOuter, data.segmentsTheta, data.segmentsPhi,
  58774. degToRad(data.thetaStart), degToRad(data.thetaLength));
  58775. }
  58776. });
  58777. },{"../core/geometry":132,"../lib/three":179}],172:[function(_dereq_,module,exports){
  58778. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  58779. var THREE = _dereq_('../lib/three');
  58780. var degToRad = THREE.Math.degToRad;
  58781. registerGeometry('sphere', {
  58782. schema: {
  58783. radius: {default: 1, min: 0},
  58784. phiLength: {default: 360},
  58785. phiStart: {default: 0, min: 0},
  58786. thetaLength: {default: 180, min: 0},
  58787. thetaStart: {default: 0},
  58788. segmentsHeight: {default: 18, min: 2, type: 'int'},
  58789. segmentsWidth: {default: 36, min: 3, type: 'int'}
  58790. },
  58791. init: function (data) {
  58792. this.geometry = new THREE.SphereGeometry(
  58793. data.radius, data.segmentsWidth, data.segmentsHeight, degToRad(data.phiStart),
  58794. degToRad(data.phiLength), degToRad(data.thetaStart), degToRad(data.thetaLength));
  58795. }
  58796. });
  58797. },{"../core/geometry":132,"../lib/three":179}],173:[function(_dereq_,module,exports){
  58798. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  58799. var THREE = _dereq_('../lib/three');
  58800. registerGeometry('tetrahedron', {
  58801. schema: {
  58802. detail: {default: 0, min: 0, max: 5, type: 'int'},
  58803. radius: {default: 1, min: 0}
  58804. },
  58805. init: function (data) {
  58806. this.geometry = new THREE.TetrahedronGeometry(data.radius, data.detail);
  58807. }
  58808. });
  58809. },{"../core/geometry":132,"../lib/three":179}],174:[function(_dereq_,module,exports){
  58810. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  58811. var THREE = _dereq_('../lib/three');
  58812. var degToRad = THREE.Math.degToRad;
  58813. registerGeometry('torus', {
  58814. schema: {
  58815. arc: {default: 360},
  58816. radius: {default: 1, min: 0},
  58817. radiusTubular: {default: 0.2, min: 0},
  58818. segmentsRadial: {default: 36, min: 2, type: 'int'},
  58819. segmentsTubular: {default: 32, min: 3, type: 'int'}
  58820. },
  58821. init: function (data) {
  58822. this.geometry = new THREE.TorusGeometry(
  58823. data.radius, data.radiusTubular * 2, data.segmentsRadial, data.segmentsTubular,
  58824. degToRad(data.arc));
  58825. }
  58826. });
  58827. },{"../core/geometry":132,"../lib/three":179}],175:[function(_dereq_,module,exports){
  58828. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  58829. var THREE = _dereq_('../lib/three');
  58830. registerGeometry('torusKnot', {
  58831. schema: {
  58832. p: {default: 2, min: 1},
  58833. q: {default: 3, min: 1},
  58834. radius: {default: 1, min: 0},
  58835. radiusTubular: {default: 0.2, min: 0},
  58836. segmentsRadial: {default: 8, min: 3, type: 'int'},
  58837. segmentsTubular: {default: 100, min: 3, type: 'int'}
  58838. },
  58839. init: function (data) {
  58840. this.geometry = new THREE.TorusKnotGeometry(
  58841. data.radius, data.radiusTubular * 2, data.segmentsTubular, data.segmentsRadial,
  58842. data.p, data.q);
  58843. }
  58844. });
  58845. },{"../core/geometry":132,"../lib/three":179}],176:[function(_dereq_,module,exports){
  58846. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  58847. var THREE = _dereq_('../lib/three');
  58848. var quaternion = new THREE.Quaternion();
  58849. var rotateVector = new THREE.Vector3(0, 0, 1);
  58850. var uvMinVector = new THREE.Vector2();
  58851. var uvMaxVector = new THREE.Vector2();
  58852. var uvScaleVector = new THREE.Vector2();
  58853. registerGeometry('triangle', {
  58854. schema: {
  58855. vertexA: {type: 'vec3', default: {x: 0, y: 0.5, z: 0}},
  58856. vertexB: {type: 'vec3', default: {x: -0.5, y: -0.5, z: 0}},
  58857. vertexC: {type: 'vec3', default: {x: 0.5, y: -0.5, z: 0}}
  58858. },
  58859. init: function (data) {
  58860. var geometry;
  58861. var normal;
  58862. var triangle;
  58863. var uvA;
  58864. var uvB;
  58865. var uvC;
  58866. var vertices;
  58867. var normals;
  58868. var uvs;
  58869. triangle = new THREE.Triangle();
  58870. triangle.a.set(data.vertexA.x, data.vertexA.y, data.vertexA.z);
  58871. triangle.b.set(data.vertexB.x, data.vertexB.y, data.vertexB.z);
  58872. triangle.c.set(data.vertexC.x, data.vertexC.y, data.vertexC.z);
  58873. normal = triangle.getNormal(new THREE.Vector3());
  58874. // Rotate the 3D triangle to be parallel to XY plane.
  58875. quaternion.setFromUnitVectors(normal, rotateVector);
  58876. uvA = triangle.a.clone().applyQuaternion(quaternion);
  58877. uvB = triangle.b.clone().applyQuaternion(quaternion);
  58878. uvC = triangle.c.clone().applyQuaternion(quaternion);
  58879. // Compute UVs.
  58880. // Normalize x/y values of UV so they are within 0 to 1.
  58881. uvMinVector.set(Math.min(uvA.x, uvB.x, uvC.x), Math.min(uvA.y, uvB.y, uvC.y));
  58882. uvMaxVector.set(Math.max(uvA.x, uvB.x, uvC.x), Math.max(uvA.y, uvB.y, uvC.y));
  58883. uvScaleVector.set(0, 0).subVectors(uvMaxVector, uvMinVector);
  58884. uvA = new THREE.Vector2().subVectors(uvA, uvMinVector).divide(uvScaleVector);
  58885. uvB = new THREE.Vector2().subVectors(uvB, uvMinVector).divide(uvScaleVector);
  58886. uvC = new THREE.Vector2().subVectors(uvC, uvMinVector).divide(uvScaleVector);
  58887. geometry = this.geometry = new THREE.BufferGeometry();
  58888. vertices = [
  58889. triangle.a.x, triangle.a.y, triangle.a.z,
  58890. triangle.b.x, triangle.b.y, triangle.b.z,
  58891. triangle.c.x, triangle.c.y, triangle.c.z
  58892. ];
  58893. normals = [
  58894. normal.x, normal.y, normal.z,
  58895. normal.x, normal.y, normal.z,
  58896. normal.x, normal.y, normal.z
  58897. ];
  58898. uvs = [
  58899. uvA.x, uvA.y,
  58900. uvB.x, uvB.y,
  58901. uvC.x, uvC.y
  58902. ];
  58903. geometry.setAttribute('position', new THREE.Float32BufferAttribute(vertices, 3));
  58904. geometry.setAttribute('normal', new THREE.Float32BufferAttribute(normals, 3));
  58905. geometry.setAttribute('uv', new THREE.Float32BufferAttribute(uvs, 2));
  58906. }
  58907. });
  58908. },{"../core/geometry":132,"../lib/three":179}],177:[function(_dereq_,module,exports){
  58909. // Polyfill `Promise`.
  58910. window.Promise = window.Promise || _dereq_('promise-polyfill');
  58911. // WebVR polyfill
  58912. // Check before the polyfill runs.
  58913. window.hasNativeWebVRImplementation = !!window.navigator.getVRDisplays ||
  58914. !!window.navigator.getVRDevices;
  58915. window.hasNativeWebXRImplementation = navigator.xr !== undefined;
  58916. // If native WebXR or WebVR are defined WebVRPolyfill does not initialize.
  58917. if (!window.hasNativeWebXRImplementation && !window.hasNativeWebVRImplementation) {
  58918. var isIOSOlderThan10 = _dereq_('./utils/isIOSOlderThan10');
  58919. // Workaround for iOS Safari canvas sizing issues in stereo (webvr-polyfill/issues/102).
  58920. // Only for iOS on versions older than 10.
  58921. var bufferScale = isIOSOlderThan10(window.navigator.userAgent) ? 1 / window.devicePixelRatio : 1;
  58922. var WebVRPolyfill = _dereq_('webvr-polyfill');
  58923. var polyfillConfig = {
  58924. BUFFER_SCALE: bufferScale,
  58925. CARDBOARD_UI_DISABLED: true,
  58926. ROTATE_INSTRUCTIONS_DISABLED: true,
  58927. MOBILE_WAKE_LOCK: !!window.cordova
  58928. };
  58929. window.webvrpolyfill = new WebVRPolyfill(polyfillConfig);
  58930. }
  58931. var utils = _dereq_('./utils/');
  58932. var debug = utils.debug;
  58933. if (utils.isIE11) {
  58934. // Polyfill `CustomEvent`.
  58935. _dereq_('custom-event-polyfill');
  58936. // Polyfill String.startsWith.
  58937. _dereq_('../vendor/starts-with-polyfill');
  58938. }
  58939. var error = debug('A-Frame:error');
  58940. var warn = debug('A-Frame:warn');
  58941. if (window.document.currentScript && window.document.currentScript.parentNode !==
  58942. window.document.head && !window.debug) {
  58943. warn('Put the A-Frame <script> tag in the <head> of the HTML *before* the scene to ' +
  58944. 'ensure everything for A-Frame is properly registered before they are used from ' +
  58945. 'HTML.');
  58946. }
  58947. // Error if not using a server.
  58948. if (!window.cordova && window.location.protocol === 'file:') {
  58949. error(
  58950. 'This HTML file is currently being served via the file:// protocol. ' +
  58951. 'Assets, textures, and models WILL NOT WORK due to cross-origin policy! ' +
  58952. 'Please use a local or hosted server: ' +
  58953. 'https://aframe.io/docs/0.5.0/introduction/getting-started.html#using-a-local-server.');
  58954. }
  58955. _dereq_('present'); // Polyfill `performance.now()`.
  58956. // CSS.
  58957. if (utils.device.isBrowserEnvironment) {
  58958. _dereq_('./style/aframe.css');
  58959. _dereq_('./style/rStats.css');
  58960. }
  58961. // Required before `AEntity` so that all components are registered.
  58962. var AScene = _dereq_('./core/scene/a-scene').AScene;
  58963. var components = _dereq_('./core/component').components;
  58964. var registerComponent = _dereq_('./core/component').registerComponent;
  58965. var registerGeometry = _dereq_('./core/geometry').registerGeometry;
  58966. var registerPrimitive = _dereq_('./extras/primitives/primitives').registerPrimitive;
  58967. var registerShader = _dereq_('./core/shader').registerShader;
  58968. var registerSystem = _dereq_('./core/system').registerSystem;
  58969. var shaders = _dereq_('./core/shader').shaders;
  58970. var systems = _dereq_('./core/system').systems;
  58971. // Exports THREE to window so three.js can be used without alteration.
  58972. var THREE = window.THREE = _dereq_('./lib/three');
  58973. var pkg = _dereq_('../package');
  58974. _dereq_('./components/index'); // Register standard components.
  58975. _dereq_('./geometries/index'); // Register standard geometries.
  58976. _dereq_('./shaders/index'); // Register standard shaders.
  58977. _dereq_('./systems/index'); // Register standard systems.
  58978. var ANode = _dereq_('./core/a-node');
  58979. var AEntity = _dereq_('./core/a-entity'); // Depends on ANode and core components.
  58980. _dereq_('./core/a-assets');
  58981. _dereq_('./core/a-cubemap');
  58982. _dereq_('./core/a-mixin');
  58983. // Extras.
  58984. _dereq_('./extras/components/');
  58985. _dereq_('./extras/primitives/');
  58986. console.log('A-Frame Version: 1.2.0 (Date 2021-03-16, Commit #ccdc1065)');
  58987. console.log('THREE Version (https://github.com/supermedium/three.js):',
  58988. pkg.dependencies['super-three']);
  58989. console.log('WebVR Polyfill Version:', pkg.dependencies['webvr-polyfill']);
  58990. module.exports = window.AFRAME = {
  58991. AComponent: _dereq_('./core/component').Component,
  58992. AEntity: AEntity,
  58993. ANode: ANode,
  58994. ANIME: _dereq_('super-animejs'),
  58995. AScene: AScene,
  58996. components: components,
  58997. coreComponents: Object.keys(components),
  58998. geometries: _dereq_('./core/geometry').geometries,
  58999. registerComponent: registerComponent,
  59000. registerElement: _dereq_('./core/a-register-element').registerElement,
  59001. registerGeometry: registerGeometry,
  59002. registerPrimitive: registerPrimitive,
  59003. registerShader: registerShader,
  59004. registerSystem: registerSystem,
  59005. primitives: {
  59006. getMeshMixin: _dereq_('./extras/primitives/getMeshMixin'),
  59007. primitives: _dereq_('./extras/primitives/primitives').primitives
  59008. },
  59009. scenes: _dereq_('./core/scene/scenes'),
  59010. schema: _dereq_('./core/schema'),
  59011. shaders: shaders,
  59012. systems: systems,
  59013. THREE: THREE,
  59014. utils: utils,
  59015. version: pkg.version
  59016. };
  59017. },{"../package":73,"../vendor/starts-with-polyfill":218,"./components/index":84,"./core/a-assets":125,"./core/a-cubemap":126,"./core/a-entity":127,"./core/a-mixin":128,"./core/a-node":129,"./core/a-register-element":130,"./core/component":131,"./core/geometry":132,"./core/scene/a-scene":134,"./core/scene/scenes":138,"./core/schema":140,"./core/shader":141,"./core/system":142,"./extras/components/":143,"./extras/primitives/":146,"./extras/primitives/getMeshMixin":145,"./extras/primitives/primitives":147,"./geometries/index":168,"./lib/three":179,"./shaders/index":181,"./style/aframe.css":186,"./style/rStats.css":187,"./systems/index":191,"./utils/":205,"./utils/isIOSOlderThan10":208,"custom-event-polyfill":7,"present":48,"promise-polyfill":50,"super-animejs":56,"webvr-polyfill":68}],178:[function(_dereq_,module,exports){
  59018. window.aframeStats = function (scene) {
  59019. var _rS = null;
  59020. var _scene = scene;
  59021. var _values = {
  59022. te: {
  59023. caption: 'Entities'
  59024. },
  59025. lt: {
  59026. caption: 'Load Time'
  59027. }
  59028. };
  59029. var _groups = [ {
  59030. caption: 'A-Frame',
  59031. values: [ 'te', 'lt' ]
  59032. } ];
  59033. function _update () {
  59034. _rS('te').set(getEntityCount());
  59035. if (window.performance.getEntriesByName) {
  59036. _rS('lt').set(window.performance.getEntriesByName('render-started')[0].startTime.toFixed(0));
  59037. }
  59038. }
  59039. function getEntityCount () {
  59040. var elements = _scene.querySelectorAll('*');
  59041. Array.prototype.slice.call(elements).filter(function (el) {
  59042. return el.isEntity;
  59043. });
  59044. return elements.length;
  59045. }
  59046. function _start () {}
  59047. function _end () {}
  59048. function _attach (r) {
  59049. _rS = r;
  59050. }
  59051. return {
  59052. update: _update,
  59053. start: _start,
  59054. end: _end,
  59055. attach: _attach,
  59056. values: _values,
  59057. groups: _groups,
  59058. fractions: []
  59059. };
  59060. };
  59061. if (typeof module === 'object') {
  59062. module.exports = {
  59063. aframeStats: window.aframeStats
  59064. };
  59065. }
  59066. },{}],179:[function(_dereq_,module,exports){
  59067. (function (global){
  59068. var THREE = global.THREE = _dereq_('super-three');
  59069. // Allow cross-origin images to be loaded.
  59070. // This should not be on `THREE.Loader` nor `THREE.ImageUtils`.
  59071. // Must be on `THREE.TextureLoader`.
  59072. if (THREE.TextureLoader) {
  59073. THREE.TextureLoader.prototype.crossOrigin = 'anonymous';
  59074. }
  59075. // This is for images loaded from the model loaders.
  59076. if (THREE.ImageLoader) {
  59077. THREE.ImageLoader.prototype.crossOrigin = 'anonymous';
  59078. }
  59079. // In-memory caching for XHRs (for images, audio files, textures, etc.).
  59080. if (THREE.Cache) {
  59081. THREE.Cache.enabled = true;
  59082. }
  59083. // TODO: Eventually include these only if they are needed by a component.
  59084. _dereq_('../../vendor/DeviceOrientationControls'); // THREE.DeviceOrientationControls
  59085. _dereq_('super-three/examples/js/loaders/DRACOLoader'); // THREE.DRACOLoader
  59086. _dereq_('super-three/examples/js/loaders/GLTFLoader'); // THREE.GLTFLoader
  59087. _dereq_('super-three/examples/js/loaders/OBJLoader'); // THREE.OBJLoader
  59088. _dereq_('super-three/examples/js/loaders/MTLLoader'); // THREE.MTLLoader
  59089. _dereq_('super-three/examples/js/utils/BufferGeometryUtils'); // THREE.BufferGeometryUtils
  59090. THREE.DRACOLoader.prototype.crossOrigin = 'anonymous';
  59091. THREE.GLTFLoader.prototype.crossOrigin = 'anonymous';
  59092. THREE.MTLLoader.prototype.crossOrigin = 'anonymous';
  59093. THREE.OBJLoader.prototype.crossOrigin = 'anonymous';
  59094. module.exports = THREE;
  59095. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  59096. },{"../../vendor/DeviceOrientationControls":215,"super-three":57,"super-three/examples/js/loaders/DRACOLoader":58,"super-three/examples/js/loaders/GLTFLoader":59,"super-three/examples/js/loaders/MTLLoader":60,"super-three/examples/js/loaders/OBJLoader":61,"super-three/examples/js/utils/BufferGeometryUtils":62}],180:[function(_dereq_,module,exports){
  59097. var registerShader = _dereq_('../core/shader').registerShader;
  59098. var THREE = _dereq_('../lib/three');
  59099. var utils = _dereq_('../utils/');
  59100. /**
  59101. * Flat shader using THREE.MeshBasicMaterial.
  59102. */
  59103. module.exports.Shader = registerShader('flat', {
  59104. schema: {
  59105. color: {type: 'color'},
  59106. fog: {default: true},
  59107. height: {default: 256},
  59108. offset: {type: 'vec2', default: {x: 0, y: 0}},
  59109. repeat: {type: 'vec2', default: {x: 1, y: 1}},
  59110. src: {type: 'map'},
  59111. width: {default: 512},
  59112. wireframe: {default: false},
  59113. wireframeLinewidth: {default: 2}
  59114. },
  59115. /**
  59116. * Initializes the shader.
  59117. * Adds a reference from the scene to this entity as the camera.
  59118. */
  59119. init: function (data) {
  59120. this.rendererSystem = this.el.sceneEl.systems.renderer;
  59121. this.materialData = {color: new THREE.Color()};
  59122. this.textureSrc = null;
  59123. getMaterialData(data, this.materialData);
  59124. this.rendererSystem.applyColorCorrection(this.materialData.color);
  59125. this.material = new THREE.MeshBasicMaterial(this.materialData);
  59126. utils.material.updateMap(this, data);
  59127. },
  59128. update: function (data) {
  59129. this.updateMaterial(data);
  59130. utils.material.updateMap(this, data);
  59131. },
  59132. /**
  59133. * Updating existing material.
  59134. *
  59135. * @param {object} data - Material component data.
  59136. */
  59137. updateMaterial: function (data) {
  59138. var key;
  59139. getMaterialData(data, this.materialData);
  59140. this.rendererSystem.applyColorCorrection(this.materialData.color);
  59141. for (key in this.materialData) {
  59142. this.material[key] = this.materialData[key];
  59143. }
  59144. }
  59145. });
  59146. /**
  59147. * Builds and normalize material data, normalizing stuff along the way.
  59148. *
  59149. * @param {object} data - Material data.
  59150. * @param {object} materialData - Object to reuse.
  59151. * @returns {object} Updated material data.
  59152. */
  59153. function getMaterialData (data, materialData) {
  59154. materialData.color.set(data.color);
  59155. materialData.fog = data.fog;
  59156. materialData.wireframe = data.wireframe;
  59157. materialData.wireframeLinewidth = data.wireframeLinewidth;
  59158. return materialData;
  59159. }
  59160. },{"../core/shader":141,"../lib/three":179,"../utils/":205}],181:[function(_dereq_,module,exports){
  59161. _dereq_('./flat');
  59162. _dereq_('./standard');
  59163. _dereq_('./sdf');
  59164. _dereq_('./msdf');
  59165. _dereq_('./ios10hls');
  59166. },{"./flat":180,"./ios10hls":182,"./msdf":183,"./sdf":184,"./standard":185}],182:[function(_dereq_,module,exports){
  59167. var registerShader = _dereq_('../core/shader').registerShader;
  59168. /**
  59169. * Custom shader for iOS 10 HTTP Live Streaming (HLS).
  59170. * For more information on HLS, see https://datatracker.ietf.org/doc/draft-pantos-http-live-streaming/
  59171. */
  59172. module.exports.Shader = registerShader('ios10hls', {
  59173. schema: {
  59174. src: {type: 'map', is: 'uniform'},
  59175. opacity: {type: 'number', is: 'uniform', default: 1}
  59176. },
  59177. vertexShader: [
  59178. 'varying vec2 vUV;',
  59179. 'void main(void) {',
  59180. ' gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);',
  59181. ' vUV = uv;',
  59182. '}'
  59183. ].join('\n'),
  59184. fragmentShader: [
  59185. 'uniform sampler2D src;',
  59186. 'uniform float opacity;',
  59187. 'varying vec2 vUV;',
  59188. 'void main() {',
  59189. ' vec2 offset = vec2(0, 0);',
  59190. ' vec2 repeat = vec2(1, 1);',
  59191. ' vec4 color = texture2D(src, vec2(vUV.x / repeat.x + offset.x, (1.0 - vUV.y) / repeat.y + offset.y)).bgra;',
  59192. ' gl_FragColor = vec4(color.rgb, opacity);',
  59193. '}'
  59194. ].join('\n')
  59195. });
  59196. },{"../core/shader":141}],183:[function(_dereq_,module,exports){
  59197. var registerShader = _dereq_('../core/shader').registerShader;
  59198. var isWebGL2AVailable = !!document.createElement('canvas').getContext('webgl2');
  59199. var VERTEX_SHADER_WEBGL1 = [
  59200. 'attribute vec2 uv;',
  59201. 'attribute vec3 position;',
  59202. 'uniform mat4 projectionMatrix;',
  59203. 'uniform mat4 modelViewMatrix;',
  59204. 'varying vec2 vUV;',
  59205. 'void main(void) {',
  59206. ' gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);',
  59207. ' vUV = uv;',
  59208. '}'
  59209. ].join('\n');
  59210. var VERTEX_SHADER_WEBGL2 = [
  59211. '#version 300 es',
  59212. 'in vec2 uv;',
  59213. 'in vec3 position;',
  59214. 'uniform mat4 projectionMatrix;',
  59215. 'uniform mat4 modelViewMatrix;',
  59216. 'out vec2 vUV;',
  59217. 'void main(void) {',
  59218. ' gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);',
  59219. ' vUV = uv;',
  59220. '}'
  59221. ].join('\n');
  59222. var VERTEX_SHADER = isWebGL2AVailable ? VERTEX_SHADER_WEBGL2 : VERTEX_SHADER_WEBGL1;
  59223. var FRAGMENT_SHADER_WEBGL1 = [
  59224. '#ifdef GL_OES_standard_derivatives',
  59225. '#extension GL_OES_standard_derivatives: enable',
  59226. '#endif',
  59227. 'precision highp float;',
  59228. 'uniform bool negate;',
  59229. 'uniform float alphaTest;',
  59230. 'uniform float opacity;',
  59231. 'uniform sampler2D map;',
  59232. 'uniform vec3 color;',
  59233. 'varying vec2 vUV;',
  59234. 'float median(float r, float g, float b) {',
  59235. ' return max(min(r, g), min(max(r, g), b));',
  59236. '}',
  59237. // FIXME: Experimentally determined constants.
  59238. '#define BIG_ENOUGH 0.001',
  59239. '#define MODIFIED_ALPHATEST (0.02 * isBigEnough / BIG_ENOUGH)',
  59240. 'void main() {',
  59241. ' vec3 sampleColor = texture2D(map, vUV).rgb;',
  59242. ' if (negate) { sampleColor = 1.0 - sampleColor; }',
  59243. ' float sigDist = median(sampleColor.r, sampleColor.g, sampleColor.b) - 0.5;',
  59244. ' float alpha = clamp(sigDist / fwidth(sigDist) + 0.5, 0.0, 1.0);',
  59245. ' float dscale = 0.353505;',
  59246. ' vec2 duv = dscale * (dFdx(vUV) + dFdy(vUV));',
  59247. ' float isBigEnough = max(abs(duv.x), abs(duv.y));',
  59248. // When texel is too small, blend raw alpha value rather than supersampling.
  59249. // FIXME: Experimentally determined constant.
  59250. ' // Do modified alpha test.',
  59251. ' if (isBigEnough > BIG_ENOUGH) {',
  59252. ' float ratio = BIG_ENOUGH / isBigEnough;',
  59253. ' alpha = ratio * alpha + (1.0 - ratio) * (sigDist + 0.5);',
  59254. ' }',
  59255. ' // Do modified alpha test.',
  59256. ' if (alpha < alphaTest * MODIFIED_ALPHATEST) { discard; return; }',
  59257. ' gl_FragColor = vec4(color.xyz, alpha * opacity);',
  59258. '}'
  59259. ].join('\n');
  59260. var FRAGMENT_SHADER_WEBGL2 = [
  59261. '#version 300 es',
  59262. 'precision highp float;',
  59263. 'uniform bool negate;',
  59264. 'uniform float alphaTest;',
  59265. 'uniform float opacity;',
  59266. 'uniform sampler2D map;',
  59267. 'uniform vec3 color;',
  59268. 'in vec2 vUV;',
  59269. 'out vec4 fragColor;',
  59270. 'float median(float r, float g, float b) {',
  59271. ' return max(min(r, g), min(max(r, g), b));',
  59272. '}',
  59273. // FIXME: Experimentally determined constants.
  59274. '#define BIG_ENOUGH 0.001',
  59275. '#define MODIFIED_ALPHATEST (0.02 * isBigEnough / BIG_ENOUGH)',
  59276. 'void main() {',
  59277. ' vec3 sampleColor = texture(map, vUV).rgb;',
  59278. ' if (negate) { sampleColor = 1.0 - sampleColor; }',
  59279. ' float sigDist = median(sampleColor.r, sampleColor.g, sampleColor.b) - 0.5;',
  59280. ' float alpha = clamp(sigDist / fwidth(sigDist) + 0.5, 0.0, 1.0);',
  59281. ' float dscale = 0.353505;',
  59282. ' vec2 duv = dscale * (dFdx(vUV) + dFdy(vUV));',
  59283. ' float isBigEnough = max(abs(duv.x), abs(duv.y));',
  59284. // When texel is too small, blend raw alpha value rather than supersampling.
  59285. // FIXME: Experimentally determined constant.
  59286. ' // Do modified alpha test.',
  59287. ' if (isBigEnough > BIG_ENOUGH) {',
  59288. ' float ratio = BIG_ENOUGH / isBigEnough;',
  59289. ' alpha = ratio * alpha + (1.0 - ratio) * (sigDist + 0.5);',
  59290. ' }',
  59291. ' // Do modified alpha test.',
  59292. ' if (alpha < alphaTest * MODIFIED_ALPHATEST) { discard; return; }',
  59293. ' fragColor = vec4(color.xyz, alpha * opacity);',
  59294. '}'
  59295. ].join('\n');
  59296. var FRAGMENT_SHADER = isWebGL2AVailable ? FRAGMENT_SHADER_WEBGL2 : FRAGMENT_SHADER_WEBGL1;
  59297. /**
  59298. * Multi-channel signed distance field.
  59299. * Used by text component.
  59300. */
  59301. module.exports.Shader = registerShader('msdf', {
  59302. schema: {
  59303. alphaTest: {type: 'number', is: 'uniform', default: 0.5},
  59304. color: {type: 'color', is: 'uniform', default: 'white'},
  59305. map: {type: 'map', is: 'uniform'},
  59306. negate: {type: 'boolean', is: 'uniform', default: true},
  59307. opacity: {type: 'number', is: 'uniform', default: 1.0}
  59308. },
  59309. raw: true,
  59310. vertexShader: VERTEX_SHADER,
  59311. fragmentShader: FRAGMENT_SHADER
  59312. });
  59313. },{"../core/shader":141}],184:[function(_dereq_,module,exports){
  59314. var registerShader = _dereq_('../core/shader').registerShader;
  59315. var isWebGL2AVailable = !!document.createElement('canvas').getContext('webgl2');
  59316. var VERTEX_SHADER_WEBGL1 = [
  59317. 'attribute vec2 uv;',
  59318. 'attribute vec3 position;',
  59319. 'uniform mat4 projectionMatrix;',
  59320. 'uniform mat4 modelViewMatrix;',
  59321. 'varying vec2 vUV;',
  59322. 'void main(void) {',
  59323. ' gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);',
  59324. ' vUV = uv;',
  59325. '}'
  59326. ].join('\n');
  59327. var VERTEX_SHADER_WEBGL2 = [
  59328. '#version 300 es',
  59329. 'in vec2 uv;',
  59330. 'in vec3 position;',
  59331. 'uniform mat4 projectionMatrix;',
  59332. 'uniform mat4 modelViewMatrix;',
  59333. 'out vec2 vUV;',
  59334. 'void main(void) {',
  59335. ' gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);',
  59336. ' vUV = uv;',
  59337. '}'
  59338. ].join('\n');
  59339. var VERTEX_SHADER = isWebGL2AVailable ? VERTEX_SHADER_WEBGL2 : VERTEX_SHADER_WEBGL1;
  59340. var FRAGMENT_SHADER_WEBGL1 = [
  59341. '#ifdef GL_OES_standard_derivatives',
  59342. '#extension GL_OES_standard_derivatives: enable',
  59343. '#endif',
  59344. 'precision highp float;',
  59345. 'uniform float alphaTest;',
  59346. 'uniform float opacity;',
  59347. 'uniform sampler2D map;',
  59348. 'uniform vec3 color;',
  59349. 'varying vec2 vUV;',
  59350. '#ifdef GL_OES_standard_derivatives',
  59351. ' float contour(float width, float value) {',
  59352. ' return smoothstep(0.5 - value, 0.5 + value, width);',
  59353. ' }',
  59354. '#else',
  59355. ' float aastep(float value, float afwidth) {',
  59356. ' return smoothstep(0.5 - afwidth, 0.5 + afwidth, value);',
  59357. ' }',
  59358. '#endif',
  59359. // FIXME: Experimentally determined constants.
  59360. '#define BIG_ENOUGH 0.001',
  59361. '#define MODIFIED_ALPHATEST (0.02 * isBigEnough / BIG_ENOUGH)',
  59362. '#define ALL_SMOOTH 0.4',
  59363. '#define ALL_ROUGH 0.02',
  59364. '#define DISCARD_ALPHA (alphaTest / (2.2 - 1.2 * ratio))',
  59365. 'void main() {',
  59366. // When we have derivatives and can get texel size for supersampling.
  59367. ' #ifdef GL_OES_standard_derivatives',
  59368. ' vec2 uv = vUV;',
  59369. ' vec4 texColor = texture2D(map, uv);',
  59370. ' float dist = texColor.a;',
  59371. ' float width = fwidth(dist);',
  59372. ' float alpha = contour(dist, width);',
  59373. ' float dscale = 0.353505;',
  59374. ' vec2 duv = dscale * (dFdx(uv) + dFdy(uv));',
  59375. ' float isBigEnough = max(abs(duv.x), abs(duv.y));',
  59376. // When texel is too small, blend raw alpha value rather than supersampling.
  59377. // FIXME: experimentally determined constant
  59378. ' if (isBigEnough > BIG_ENOUGH) {',
  59379. ' float ratio = BIG_ENOUGH / isBigEnough;',
  59380. ' alpha = ratio * alpha + (1.0 - ratio) * dist;',
  59381. ' }',
  59382. // Otherwise do weighted supersampling.
  59383. // FIXME: why this weighting?
  59384. ' if (isBigEnough <= BIG_ENOUGH) {',
  59385. ' vec4 box = vec4 (uv - duv, uv + duv);',
  59386. ' alpha = (alpha + 0.5 * (',
  59387. ' contour(texture2D(map, box.xy).a, width)',
  59388. ' + contour(texture2D(map, box.zw).a, width)',
  59389. ' + contour(texture2D(map, box.xw).a, width)',
  59390. ' + contour(texture2D(map, box.zy).a, width)',
  59391. ' )) / 3.0;',
  59392. ' }',
  59393. // Do modified alpha test.
  59394. ' if (alpha < alphaTest * MODIFIED_ALPHATEST) { discard; return; }',
  59395. ' #else',
  59396. // When we don't have derivatives, use approximations.
  59397. ' vec4 texColor = texture2D(map, vUV);',
  59398. ' float value = texColor.a;',
  59399. // FIXME: if we understood font pixel dimensions, this could probably be improved
  59400. ' float afwidth = (1.0 / 32.0) * (1.4142135623730951 / (2.0 * gl_FragCoord.w));',
  59401. ' float alpha = aastep(value, afwidth);',
  59402. // Use gl_FragCoord.w to guess when we should blend.
  59403. // FIXME: If we understood font pixel dimensions, this could probably be improved.
  59404. ' float ratio = (gl_FragCoord.w >= ALL_SMOOTH) ? 1.0 : (gl_FragCoord.w < ALL_ROUGH) ? 0.0 : (gl_FragCoord.w - ALL_ROUGH) / (ALL_SMOOTH - ALL_ROUGH);',
  59405. ' if (alpha < alphaTest) { if (ratio >= 1.0) { discard; return; } alpha = 0.0; }',
  59406. ' alpha = alpha * ratio + (1.0 - ratio) * value;',
  59407. ' if (ratio < 1.0 && alpha <= DISCARD_ALPHA) { discard; return; }',
  59408. ' #endif',
  59409. ' gl_FragColor = vec4(color, opacity * alpha);',
  59410. '}'
  59411. ].join('\n');
  59412. var FRAGMENT_SHADER_WEBGL2 = [
  59413. '#version 300 es',
  59414. 'precision highp float;',
  59415. 'uniform float alphaTest;',
  59416. 'uniform float opacity;',
  59417. 'uniform sampler2D map;',
  59418. 'uniform vec3 color;',
  59419. 'in vec2 vUV;',
  59420. 'out vec4 fragColor;',
  59421. '#ifdef GL_OES_standard_derivatives',
  59422. ' float contour(float width, float value) {',
  59423. ' return smoothstep(0.5 - value, 0.5 + value, width);',
  59424. ' }',
  59425. '#else',
  59426. ' float aastep(float value, float afwidth) {',
  59427. ' return smoothstep(0.5 - afwidth, 0.5 + afwidth, value);',
  59428. ' }',
  59429. '#endif',
  59430. // FIXME: Experimentally determined constants.
  59431. '#define BIG_ENOUGH 0.001',
  59432. '#define MODIFIED_ALPHATEST (0.02 * isBigEnough / BIG_ENOUGH)',
  59433. '#define ALL_SMOOTH 0.4',
  59434. '#define ALL_ROUGH 0.02',
  59435. '#define DISCARD_ALPHA (alphaTest / (2.2 - 1.2 * ratio))',
  59436. 'void main() {',
  59437. // When we have derivatives and can get texel size for supersampling.
  59438. ' #ifdef GL_OES_standard_derivatives',
  59439. ' vec2 uv = vUV;',
  59440. ' vec4 texColor = texture(map, uv);',
  59441. ' float dist = texColor.a;',
  59442. ' float width = fwidth(dist);',
  59443. ' float alpha = contour(dist, width);',
  59444. ' float dscale = 0.353505;',
  59445. ' vec2 duv = dscale * (dFdx(uv) + dFdy(uv));',
  59446. ' float isBigEnough = max(abs(duv.x), abs(duv.y));',
  59447. // When texel is too small, blend raw alpha value rather than supersampling.
  59448. // FIXME: experimentally determined constant
  59449. ' if (isBigEnough > BIG_ENOUGH) {',
  59450. ' float ratio = BIG_ENOUGH / isBigEnough;',
  59451. ' alpha = ratio * alpha + (1.0 - ratio) * dist;',
  59452. ' }',
  59453. // Otherwise do weighted supersampling.
  59454. // FIXME: why this weighting?
  59455. ' if (isBigEnough <= BIG_ENOUGH) {',
  59456. ' vec4 box = vec4 (uv - duv, uv + duv);',
  59457. ' alpha = (alpha + 0.5 * (',
  59458. ' contour(texture(map, box.xy).a, width)',
  59459. ' + contour(texture(map, box.zw).a, width)',
  59460. ' + contour(texture(map, box.xw).a, width)',
  59461. ' + contour(texture(map, box.zy).a, width)',
  59462. ' )) / 3.0;',
  59463. ' }',
  59464. // Do modified alpha test.
  59465. ' if (alpha < alphaTest * MODIFIED_ALPHATEST) { discard; return; }',
  59466. ' #else',
  59467. // When we don't have derivatives, use approximations.
  59468. ' vec4 texColor = texture(map, vUV);',
  59469. ' float value = texColor.a;',
  59470. // FIXME: if we understood font pixel dimensions, this could probably be improved
  59471. ' float afwidth = (1.0 / 32.0) * (1.4142135623730951 / (2.0 * gl_FragCoord.w));',
  59472. ' float alpha = aastep(value, afwidth);',
  59473. // Use gl_FragCoord.w to guess when we should blend.
  59474. // FIXME: If we understood font pixel dimensions, this could probably be improved.
  59475. ' float ratio = (gl_FragCoord.w >= ALL_SMOOTH) ? 1.0 : (gl_FragCoord.w < ALL_ROUGH) ? 0.0 : (gl_FragCoord.w - ALL_ROUGH) / (ALL_SMOOTH - ALL_ROUGH);',
  59476. ' if (alpha < alphaTest) { if (ratio >= 1.0) { discard; return; } alpha = 0.0; }',
  59477. ' alpha = alpha * ratio + (1.0 - ratio) * value;',
  59478. ' if (ratio < 1.0 && alpha <= DISCARD_ALPHA) { discard; return; }',
  59479. ' #endif',
  59480. ' fragColor = vec4(color, opacity * alpha);',
  59481. '}'
  59482. ].join('\n');
  59483. var FRAGMENT_SHADER = isWebGL2AVailable ? FRAGMENT_SHADER_WEBGL2 : FRAGMENT_SHADER_WEBGL1;
  59484. /**
  59485. * Signed distance field.
  59486. * Used by text component.
  59487. */
  59488. module.exports.Shader = registerShader('sdf', {
  59489. schema: {
  59490. alphaTest: {type: 'number', is: 'uniform', default: 0.5},
  59491. color: {type: 'color', is: 'uniform', default: 'white'},
  59492. map: {type: 'map', is: 'uniform'},
  59493. opacity: {type: 'number', is: 'uniform', default: 1.0}
  59494. },
  59495. raw: true,
  59496. vertexShader: VERTEX_SHADER,
  59497. fragmentShader: FRAGMENT_SHADER
  59498. });
  59499. },{"../core/shader":141}],185:[function(_dereq_,module,exports){
  59500. var registerShader = _dereq_('../core/shader').registerShader;
  59501. var THREE = _dereq_('../lib/three');
  59502. var utils = _dereq_('../utils/');
  59503. var CubeLoader = new THREE.CubeTextureLoader();
  59504. var texturePromises = {};
  59505. /**
  59506. * Standard (physically-based) shader using THREE.MeshStandardMaterial.
  59507. */
  59508. module.exports.Shader = registerShader('standard', {
  59509. schema: {
  59510. ambientOcclusionMap: {type: 'map'},
  59511. ambientOcclusionMapIntensity: {default: 1},
  59512. ambientOcclusionTextureOffset: {type: 'vec2'},
  59513. ambientOcclusionTextureRepeat: {type: 'vec2', default: {x: 1, y: 1}},
  59514. color: {type: 'color'},
  59515. displacementMap: {type: 'map'},
  59516. displacementScale: {default: 1},
  59517. displacementBias: {default: 0.5},
  59518. displacementTextureOffset: {type: 'vec2'},
  59519. displacementTextureRepeat: {type: 'vec2', default: {x: 1, y: 1}},
  59520. emissive: {type: 'color', default: '#000'},
  59521. emissiveIntensity: {default: 1},
  59522. envMap: {default: ''},
  59523. fog: {default: true},
  59524. height: {default: 256},
  59525. metalness: {default: 0.0, min: 0.0, max: 1.0},
  59526. metalnessMap: {type: 'map'},
  59527. metalnessTextureOffset: {type: 'vec2'},
  59528. metalnessTextureRepeat: {type: 'vec2', default: {x: 1, y: 1}},
  59529. normalMap: {type: 'map'},
  59530. normalScale: {type: 'vec2', default: {x: 1, y: 1}},
  59531. normalTextureOffset: {type: 'vec2'},
  59532. normalTextureRepeat: {type: 'vec2', default: {x: 1, y: 1}},
  59533. offset: {type: 'vec2', default: {x: 0, y: 0}},
  59534. repeat: {type: 'vec2', default: {x: 1, y: 1}},
  59535. roughness: {default: 0.5, min: 0.0, max: 1.0},
  59536. roughnessMap: {type: 'map'},
  59537. roughnessTextureOffset: {type: 'vec2'},
  59538. roughnessTextureRepeat: {type: 'vec2', default: {x: 1, y: 1}},
  59539. sphericalEnvMap: {type: 'map'},
  59540. src: {type: 'map'},
  59541. width: {default: 512},
  59542. wireframe: {default: false},
  59543. wireframeLinewidth: {default: 2}
  59544. },
  59545. /**
  59546. * Initializes the shader.
  59547. * Adds a reference from the scene to this entity as the camera.
  59548. */
  59549. init: function (data) {
  59550. this.rendererSystem = this.el.sceneEl.systems.renderer;
  59551. this.materialData = {color: new THREE.Color(), emissive: new THREE.Color()};
  59552. getMaterialData(data, this.materialData);
  59553. this.rendererSystem.applyColorCorrection(this.materialData.color);
  59554. this.rendererSystem.applyColorCorrection(this.materialData.emissive);
  59555. this.material = new THREE.MeshStandardMaterial(this.materialData);
  59556. utils.material.updateMap(this, data);
  59557. if (data.normalMap) { utils.material.updateDistortionMap('normal', this, data); }
  59558. if (data.displacementMap) { utils.material.updateDistortionMap('displacement', this, data); }
  59559. if (data.ambientOcclusionMap) { utils.material.updateDistortionMap('ambientOcclusion', this, data); }
  59560. if (data.metalnessMap) { utils.material.updateDistortionMap('metalness', this, data); }
  59561. if (data.roughnessMap) { utils.material.updateDistortionMap('roughness', this, data); }
  59562. this.updateEnvMap(data);
  59563. },
  59564. update: function (data) {
  59565. this.updateMaterial(data);
  59566. utils.material.updateMap(this, data);
  59567. if (data.normalMap) { utils.material.updateDistortionMap('normal', this, data); }
  59568. if (data.displacementMap) { utils.material.updateDistortionMap('displacement', this, data); }
  59569. if (data.ambientOcclusionMap) { utils.material.updateDistortionMap('ambientOcclusion', this, data); }
  59570. if (data.metalnessMap) { utils.material.updateDistortionMap('metalness', this, data); }
  59571. if (data.roughnessMap) { utils.material.updateDistortionMap('roughness', this, data); }
  59572. this.updateEnvMap(data);
  59573. },
  59574. /**
  59575. * Updating existing material.
  59576. *
  59577. * @param {object} data - Material component data.
  59578. * @returns {object} Material.
  59579. */
  59580. updateMaterial: function (data) {
  59581. var key;
  59582. var material = this.material;
  59583. getMaterialData(data, this.materialData);
  59584. this.rendererSystem.applyColorCorrection(this.materialData.color);
  59585. this.rendererSystem.applyColorCorrection(this.materialData.emissive);
  59586. for (key in this.materialData) {
  59587. material[key] = this.materialData[key];
  59588. }
  59589. },
  59590. /**
  59591. * Handle environment cubemap. Textures are cached in texturePromises.
  59592. */
  59593. updateEnvMap: function (data) {
  59594. var self = this;
  59595. var material = this.material;
  59596. var envMap = data.envMap;
  59597. var sphericalEnvMap = data.sphericalEnvMap;
  59598. // No envMap defined or already loading.
  59599. if ((!envMap && !sphericalEnvMap) || this.isLoadingEnvMap) {
  59600. material.envMap = null;
  59601. material.needsUpdate = true;
  59602. return;
  59603. }
  59604. this.isLoadingEnvMap = true;
  59605. // if a spherical env map is defined then use it.
  59606. if (sphericalEnvMap) {
  59607. this.el.sceneEl.systems.material.loadTexture(sphericalEnvMap, {src: sphericalEnvMap}, function textureLoaded (texture) {
  59608. self.isLoadingEnvMap = false;
  59609. texture.mapping = THREE.EquirectangularReflectionMapping;
  59610. material.envMap = texture;
  59611. utils.material.handleTextureEvents(self.el, texture);
  59612. material.needsUpdate = true;
  59613. });
  59614. return;
  59615. }
  59616. // Another material is already loading this texture. Wait on promise.
  59617. if (texturePromises[envMap]) {
  59618. texturePromises[envMap].then(function (cube) {
  59619. self.isLoadingEnvMap = false;
  59620. material.envMap = cube;
  59621. utils.material.handleTextureEvents(self.el, cube);
  59622. material.needsUpdate = true;
  59623. });
  59624. return;
  59625. }
  59626. // Material is first to load this texture. Load and resolve texture.
  59627. texturePromises[envMap] = new Promise(function (resolve) {
  59628. utils.srcLoader.validateCubemapSrc(envMap, function loadEnvMap (urls) {
  59629. CubeLoader.load(urls, function (cube) {
  59630. // Texture loaded.
  59631. self.isLoadingEnvMap = false;
  59632. material.envMap = cube;
  59633. utils.material.handleTextureEvents(self.el, cube);
  59634. resolve(cube);
  59635. });
  59636. });
  59637. });
  59638. }
  59639. });
  59640. /**
  59641. * Builds and normalize material data, normalizing stuff along the way.
  59642. *
  59643. * @param {object} data - Material data.
  59644. * @param {object} materialData - Object to use.
  59645. * @returns {object} Updated materialData.
  59646. */
  59647. function getMaterialData (data, materialData) {
  59648. materialData.color.set(data.color);
  59649. materialData.emissive.set(data.emissive);
  59650. materialData.emissiveIntensity = data.emissiveIntensity;
  59651. materialData.fog = data.fog;
  59652. materialData.metalness = data.metalness;
  59653. materialData.roughness = data.roughness;
  59654. materialData.wireframe = data.wireframe;
  59655. materialData.wireframeLinewidth = data.wireframeLinewidth;
  59656. if (data.normalMap) { materialData.normalScale = data.normalScale; }
  59657. if (data.ambientOcclusionMap) {
  59658. materialData.aoMapIntensity = data.ambientOcclusionMapIntensity;
  59659. }
  59660. if (data.displacementMap) {
  59661. materialData.displacementScale = data.displacementScale;
  59662. materialData.displacementBias = data.displacementBias;
  59663. }
  59664. return materialData;
  59665. }
  59666. },{"../core/shader":141,"../lib/three":179,"../utils/":205}],186:[function(_dereq_,module,exports){
  59667. var css = "html.a-fullscreen{bottom:0;left:0;position:fixed;right:0;top:0}html.a-fullscreen body{height:100%;margin:0;overflow:hidden;padding:0;width:100%}html.a-fullscreen .a-canvas{width:100%!important;height:100%!important;top:0!important;left:0!important;right:0!important;bottom:0!important;position:fixed!important}html:not(.a-fullscreen) .a-enter-ar,html:not(.a-fullscreen) .a-enter-vr{right:5px;bottom:5px}:-webkit-full-screen{background-color:transparent}.a-hidden{display:none!important}.a-canvas{height:100%;left:0;position:absolute;top:0;width:100%}.a-canvas.a-grab-cursor:hover{cursor:grab;cursor:-moz-grab;cursor:-webkit-grab}canvas.a-canvas.a-mouse-cursor-hover:hover{cursor:pointer}.a-inspector-loader{background-color:#ed3160;position:fixed;left:3px;top:3px;padding:6px 10px;color:#fff;text-decoration:none;font-size:12px;font-family:Roboto,sans-serif;text-align:center;z-index:99999;width:204px}@keyframes dots-1{from{opacity:0}25%{opacity:1}}@keyframes dots-2{from{opacity:0}50%{opacity:1}}@keyframes dots-3{from{opacity:0}75%{opacity:1}}@-webkit-keyframes dots-1{from{opacity:0}25%{opacity:1}}@-webkit-keyframes dots-2{from{opacity:0}50%{opacity:1}}@-webkit-keyframes dots-3{from{opacity:0}75%{opacity:1}}.a-inspector-loader .dots span{animation:dots-1 2s infinite steps(1);-webkit-animation:dots-1 2s infinite steps(1)}.a-inspector-loader .dots span:first-child+span{animation-name:dots-2;-webkit-animation-name:dots-2}.a-inspector-loader .dots span:first-child+span+span{animation-name:dots-3;-webkit-animation-name:dots-3}a-scene{display:block;position:relative;height:100%;width:100%}a-assets,a-scene audio,a-scene img,a-scene video{display:none}.a-enter-vr-modal,.a-orientation-modal{font-family:Consolas,Andale Mono,Courier New,monospace}.a-enter-vr-modal a{border-bottom:1px solid #fff;padding:2px 0;text-decoration:none;transition:.1s color ease-in}.a-enter-vr-modal a:hover{background-color:#fff;color:#111;padding:2px 4px;position:relative;left:-4px}.a-enter-ar,.a-enter-vr{font-family:sans-serif,monospace;font-size:13px;width:100%;font-weight:200;line-height:16px;position:absolute;right:20px;bottom:20px}.a-enter-ar{right:80px}.a-enter-vr-button,.a-enter-vr-modal,.a-enter-vr-modal a{color:#fff;user-select:none;outline:0}.a-enter-vr-button{background:url(\"data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='108' height='62' viewBox='0 0 108 62'%3E%3Ctitle%3Eaframe-vrmode-noborder-reduced-tracking%3C/title%3E%3Cpath d='M68.81,21.56H64.23v8.27h4.58a4.13,4.13,0,0,0,3.1-1.09,4.2,4.2,0,0,0,1-3,4.24,4.24,0,0,0-1-3A4.05,4.05,0,0,0,68.81,21.56Z' fill='%23fff'/%3E%3Cpath d='M96,0H12A12,12,0,0,0,0,12V50A12,12,0,0,0,12,62H96a12,12,0,0,0,12-12V12A12,12,0,0,0,96,0ZM41.9,46H34L24,16h8l6,21.84,6-21.84H52Zm39.29,0H73.44L68.15,35.39H64.23V46H57V16H68.81q5.32,0,8.34,2.37a8,8,0,0,1,3,6.69,9.68,9.68,0,0,1-1.27,5.18,8.9,8.9,0,0,1-4,3.34l6.26,12.11Z' fill='%23fff'/%3E%3C/svg%3E\") 50% 50% no-repeat rgba(0,0,0,.35)}.a-enter-ar-button{background:url(\"data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='108' height='62' viewBox='0 0 108 62'%3E%3Ctitle%3Eaframe-armode-noborder-reduced-tracking%3C/title%3E%3Cpath d='M96,0H12A12,12,0,0,0,0,12V50A12,12,0,0,0,12,62H96a12,12,0,0,0,12-12V12A12,12,0,0,0,96,0Zm8,50a8,8,0,0,1-8,8H12a8,8,0,0,1-8-8V12a8,8,0,0,1,8-8H96a8,8,0,0,1,8,8Z' fill='%23fff'/%3E%3Cpath d='M43.35,39.82H32.51L30.45,46H23.88L35,16h5.73L52,46H45.43Zm-9.17-5h7.5L37.91,23.58Z' fill='%23fff'/%3E%3Cpath d='M68.11,35H63.18V46H57V16H68.15q5.31,0,8.2,2.37a8.18,8.18,0,0,1,2.88,6.7,9.22,9.22,0,0,1-1.33,5.12,9.09,9.09,0,0,1-4,3.26l6.49,12.26V46H73.73Zm-4.93-5h5a5.09,5.09,0,0,0,3.6-1.18,4.21,4.21,0,0,0,1.28-3.27,4.56,4.56,0,0,0-1.2-3.34A5,5,0,0,0,68.15,21h-5Z' fill='%23fff'/%3E%3C/svg%3E\") 50% 50% no-repeat rgba(0,0,0,.2)}.a-enter-ar-button,.a-enter-vr-button{background-size:90% 90%;border:0;bottom:0;cursor:pointer;min-width:58px;min-height:34px;padding-right:0;padding-top:0;position:absolute;right:0;transition:background-color .05s ease;-webkit-transition:background-color .05s ease;z-index:9999;border-radius:8px;touch-action:manipulation}.a-enter-ar-button{background-size:100% 90%;margin-right:10px;border-radius:7px}.a-enter-ar-button:active,.a-enter-ar-button:hover,.a-enter-vr-button:active,.a-enter-vr-button:hover{background-color:#ef2d5e}.a-enter-vr-button.resethover{background-color:rgba(0,0,0,.35)}[data-a-enter-vr-no-webvr] .a-enter-vr-button{border-color:#666;opacity:.65}[data-a-enter-vr-no-webvr] .a-enter-vr-button:active,[data-a-enter-vr-no-webvr] .a-enter-vr-button:hover{background-color:rgba(0,0,0,.35);cursor:not-allowed}.a-enter-vr-modal{background-color:#666;border-radius:0;display:none;min-height:32px;margin-right:70px;padding:9px;width:280px;right:2%;position:absolute}.a-enter-vr-modal:after{border-bottom:10px solid transparent;border-left:10px solid #666;border-top:10px solid transparent;display:inline-block;content:'';position:absolute;right:-5px;top:5px;width:0;height:0}.a-enter-vr-modal a,.a-enter-vr-modal p{display:inline}.a-enter-vr-modal p{margin:0}.a-enter-vr-modal p:after{content:' '}[data-a-enter-vr-no-headset].a-enter-vr:hover .a-enter-vr-modal,[data-a-enter-vr-no-webvr].a-enter-vr:hover .a-enter-vr-modal{display:block}.a-orientation-modal{background:url(data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20xmlns%3Axlink%3D%22http%3A//www.w3.org/1999/xlink%22%20version%3D%221.1%22%20x%3D%220px%22%20y%3D%220px%22%20viewBox%3D%220%200%2090%2090%22%20enable-background%3D%22new%200%200%2090%2090%22%20xml%3Aspace%3D%22preserve%22%3E%3Cpolygon%20points%3D%220%2C0%200%2C0%200%2C0%20%22%3E%3C/polygon%3E%3Cg%3E%3Cpath%20d%3D%22M71.545%2C48.145h-31.98V20.743c0-2.627-2.138-4.765-4.765-4.765H18.456c-2.628%2C0-4.767%2C2.138-4.767%2C4.765v42.789%20%20%20c0%2C2.628%2C2.138%2C4.766%2C4.767%2C4.766h5.535v0.959c0%2C2.628%2C2.138%2C4.765%2C4.766%2C4.765h42.788c2.628%2C0%2C4.766-2.137%2C4.766-4.765V52.914%20%20%20C76.311%2C50.284%2C74.173%2C48.145%2C71.545%2C48.145z%20M18.455%2C16.935h16.344c2.1%2C0%2C3.808%2C1.708%2C3.808%2C3.808v27.401H37.25V22.636%20%20%20c0-0.264-0.215-0.478-0.479-0.478H16.482c-0.264%2C0-0.479%2C0.214-0.479%2C0.478v36.585c0%2C0.264%2C0.215%2C0.478%2C0.479%2C0.478h7.507v7.644%20%20%20h-5.534c-2.101%2C0-3.81-1.709-3.81-3.81V20.743C14.645%2C18.643%2C16.354%2C16.935%2C18.455%2C16.935z%20M16.96%2C23.116h19.331v25.031h-7.535%20%20%20c-2.628%2C0-4.766%2C2.139-4.766%2C4.768v5.828h-7.03V23.116z%20M71.545%2C73.064H28.757c-2.101%2C0-3.81-1.708-3.81-3.808V52.914%20%20%20c0-2.102%2C1.709-3.812%2C3.81-3.812h42.788c2.1%2C0%2C3.809%2C1.71%2C3.809%2C3.812v16.343C75.354%2C71.356%2C73.645%2C73.064%2C71.545%2C73.064z%22%3E%3C/path%3E%3Cpath%20d%3D%22M28.919%2C58.424c-1.466%2C0-2.659%2C1.193-2.659%2C2.66c0%2C1.466%2C1.193%2C2.658%2C2.659%2C2.658c1.468%2C0%2C2.662-1.192%2C2.662-2.658%20%20%20C31.581%2C59.617%2C30.387%2C58.424%2C28.919%2C58.424z%20M28.919%2C62.786c-0.939%2C0-1.703-0.764-1.703-1.702c0-0.939%2C0.764-1.704%2C1.703-1.704%20%20%20c0.94%2C0%2C1.705%2C0.765%2C1.705%2C1.704C30.623%2C62.022%2C29.858%2C62.786%2C28.919%2C62.786z%22%3E%3C/path%3E%3Cpath%20d%3D%22M69.654%2C50.461H33.069c-0.264%2C0-0.479%2C0.215-0.479%2C0.479v20.288c0%2C0.264%2C0.215%2C0.478%2C0.479%2C0.478h36.585%20%20%20c0.263%2C0%2C0.477-0.214%2C0.477-0.478V50.939C70.131%2C50.676%2C69.917%2C50.461%2C69.654%2C50.461z%20M69.174%2C51.417V70.75H33.548V51.417H69.174z%22%3E%3C/path%3E%3Cpath%20d%3D%22M45.201%2C30.296c6.651%2C0%2C12.233%2C5.351%2C12.551%2C11.977l-3.033-2.638c-0.193-0.165-0.507-0.142-0.675%2C0.048%20%20%20c-0.174%2C0.198-0.153%2C0.501%2C0.045%2C0.676l3.883%2C3.375c0.09%2C0.075%2C0.198%2C0.115%2C0.312%2C0.115c0.141%2C0%2C0.273-0.061%2C0.362-0.166%20%20%20l3.371-3.877c0.173-0.2%2C0.151-0.502-0.047-0.675c-0.194-0.166-0.508-0.144-0.676%2C0.048l-2.592%2C2.979%20%20%20c-0.18-3.417-1.629-6.605-4.099-9.001c-2.538-2.461-5.877-3.817-9.404-3.817c-0.264%2C0-0.479%2C0.215-0.479%2C0.479%20%20%20C44.72%2C30.083%2C44.936%2C30.296%2C45.201%2C30.296z%22%3E%3C/path%3E%3C/g%3E%3C/svg%3E) center/50% 50% no-repeat rgba(244,244,244,1);bottom:0;font-size:14px;font-weight:600;left:0;line-height:20px;right:0;position:fixed;top:0;z-index:9999999}.a-orientation-modal:after{color:#666;content:\"Insert phone into Cardboard holder.\";display:block;position:absolute;text-align:center;top:70%;transform:translateY(-70%);width:100%}.a-orientation-modal button{background:url(data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20xmlns%3Axlink%3D%22http%3A//www.w3.org/1999/xlink%22%20version%3D%221.1%22%20x%3D%220px%22%20y%3D%220px%22%20viewBox%3D%220%200%20100%20100%22%20enable-background%3D%22new%200%200%20100%20100%22%20xml%3Aspace%3D%22preserve%22%3E%3Cpath%20fill%3D%22%23000000%22%20d%3D%22M55.209%2C50l17.803-17.803c1.416-1.416%2C1.416-3.713%2C0-5.129c-1.416-1.417-3.713-1.417-5.129%2C0L50.08%2C44.872%20%20L32.278%2C27.069c-1.416-1.417-3.714-1.417-5.129%2C0c-1.417%2C1.416-1.417%2C3.713%2C0%2C5.129L44.951%2C50L27.149%2C67.803%20%20c-1.417%2C1.416-1.417%2C3.713%2C0%2C5.129c0.708%2C0.708%2C1.636%2C1.062%2C2.564%2C1.062c0.928%2C0%2C1.856-0.354%2C2.564-1.062L50.08%2C55.13l17.803%2C17.802%20%20c0.708%2C0.708%2C1.637%2C1.062%2C2.564%2C1.062s1.856-0.354%2C2.564-1.062c1.416-1.416%2C1.416-3.713%2C0-5.129L55.209%2C50z%22%3E%3C/path%3E%3C/svg%3E) no-repeat;border:none;height:50px;text-indent:-9999px;width:50px}.a-loader-title{background-color:rgba(0,0,0,.6);font-family:sans-serif,monospace;text-align:center;font-size:20px;height:50px;font-weight:300;line-height:50px;position:absolute;right:0;left:0;top:0;color:#fff}.a-modal{background:0 0/50% 50% rgba(0,0,0,.6);bottom:0;font-size:14px;font-weight:600;left:0;line-height:20px;right:0;position:fixed;top:0;z-index:9999999}.a-dialog{position:relative;left:50%;top:50%;transform:translate(-50%,-50%);z-index:199995;width:300px;height:200px;background-size:contain;background-color:#fff;font-family:sans-serif,monospace;font-size:20px;border-radius:3px;padding:6px}.a-dialog-text-container{width:100%;height:70%;align-self:flex-start;display:flex;justify-content:center;align-content:center;flex-direction:column}.a-dialog-text{display:inline-block;font-weight:400;font-size:14pt;margin:8px}.a-dialog-buttons-container{display:inline-flex;align-self:flex-end;width:100%;height:30%}.a-dialog-button{cursor:pointer;align-self:center;opacity:.9;height:80%;width:50%;font-size:12pt;margin:4px;border-radius:2px;text-align:center;border:none;display:inline-block;-webkit-transition:all .25s ease-in-out;transition:all .25s ease-in-out;box-shadow:0 1px 3px rgba(0,0,0,.1),0 1px 2px rgba(0,0,0,.2);user-select:none}.a-dialog-permission-button:hover{box-shadow:0 7px 14px rgba(0,0,0,.2),0 2px 2px rgba(0,0,0,.2)}.a-dialog-allow-button{background-color:#00ceff}.a-dialog-deny-button{background-color:#ff005b}.a-dialog-ok-button{background-color:#00ceff;width:100%}"; (_dereq_("browserify-css").createStyle(css, { "href": "src/style/aframe.css"})); module.exports = css;
  59668. },{"browserify-css":4}],187:[function(_dereq_,module,exports){
  59669. var css = ".rs-base{background-color:#333;color:#fafafa;border-radius:0;font:10px monospace;left:5px;line-height:1em;opacity:.85;overflow:hidden;padding:10px;position:fixed;top:5px;width:300px;z-index:10000}.rs-base div.hidden{display:none}.rs-base h1{color:#fff;cursor:pointer;font-size:1.4em;font-weight:300;margin:0 0 5px;padding:0}.rs-group{display:-webkit-box;display:-webkit-flex;display:flex;-webkit-flex-direction:column-reverse;flex-direction:column-reverse;margin-bottom:5px}.rs-group:last-child{margin-bottom:0}.rs-counter-base{align-items:center;display:-webkit-box;display:-webkit-flex;display:flex;height:10px;-webkit-justify-content:space-between;justify-content:space-between;margin:2px 0}.rs-counter-base.alarm{color:#b70000;text-shadow:0 0 0 #b70000,0 0 1px #fff,0 0 1px #fff,0 0 2px #fff,0 0 2px #fff,0 0 3px #fff,0 0 3px #fff,0 0 4px #fff,0 0 4px #fff}.rs-counter-id{font-weight:300;-webkit-box-ordinal-group:0;-webkit-order:0;order:0;width:54px}.rs-counter-value{font-weight:300;-webkit-box-ordinal-group:1;-webkit-order:1;order:1;text-align:right;width:35px}.rs-canvas{-webkit-box-ordinal-group:2;-webkit-order:2;order:2}@media (min-width:480px){.rs-base{left:20px;top:20px}}"; (_dereq_("browserify-css").createStyle(css, { "href": "src/style/rStats.css"})); module.exports = css;
  59670. },{"browserify-css":4}],188:[function(_dereq_,module,exports){
  59671. var constants = _dereq_('../constants/');
  59672. var registerSystem = _dereq_('../core/system').registerSystem;
  59673. var DEFAULT_CAMERA_ATTR = 'data-aframe-default-camera';
  59674. /**
  59675. * Camera system. Manages which camera is active among multiple cameras in scene.
  59676. *
  59677. * @member {object} activeCameraEl - Active camera entity.
  59678. */
  59679. module.exports.System = registerSystem('camera', {
  59680. init: function () {
  59681. this.activeCameraEl = null;
  59682. this.render = this.render.bind(this);
  59683. this.unwrapRender = this.unwrapRender.bind(this);
  59684. this.wrapRender = this.wrapRender.bind(this);
  59685. this.initialCameraFound = false;
  59686. this.numUserCameras = 0;
  59687. this.numUserCamerasChecked = 0;
  59688. this.setupInitialCamera();
  59689. },
  59690. /**
  59691. * Setup initial camera, either searching for camera or
  59692. * creating a default camera if user has not added one during the initial scene traversal.
  59693. * We want sceneEl.camera to be ready, set, and initialized before the rest of the scene
  59694. * loads.
  59695. *
  59696. * Default camera offset height is at average eye level (~1.6m).
  59697. */
  59698. setupInitialCamera: function () {
  59699. var cameraEls;
  59700. var i;
  59701. var sceneEl = this.sceneEl;
  59702. var self = this;
  59703. // Camera already defined or the one defined it is an spectator one.
  59704. if (sceneEl.camera && !sceneEl.camera.el.getAttribute('camera').spectator) {
  59705. sceneEl.emit('cameraready', {cameraEl: sceneEl.camera.el});
  59706. return;
  59707. }
  59708. // Search for initial user-defined camera.
  59709. cameraEls = sceneEl.querySelectorAll('a-camera, [camera]');
  59710. // No user cameras, create default one.
  59711. if (!cameraEls.length) {
  59712. this.createDefaultCamera();
  59713. return;
  59714. }
  59715. this.numUserCameras = cameraEls.length;
  59716. for (i = 0; i < cameraEls.length; i++) {
  59717. cameraEls[i].addEventListener('object3dset', function (evt) {
  59718. if (evt.detail.type !== 'camera') { return; }
  59719. self.checkUserCamera(this);
  59720. });
  59721. // Load camera and wait for camera to initialize.
  59722. if (cameraEls[i].isNode) {
  59723. cameraEls[i].load();
  59724. } else {
  59725. cameraEls[i].addEventListener('nodeready', function () {
  59726. this.load();
  59727. });
  59728. }
  59729. }
  59730. },
  59731. /**
  59732. * Check if a user-defined camera entity is appropriate to be initial camera.
  59733. * (active + non-spectator).
  59734. *
  59735. * Keep track of the number of cameras we checked and whether we found one.
  59736. */
  59737. checkUserCamera: function (cameraEl) {
  59738. var cameraData;
  59739. var sceneEl = this.el.sceneEl;
  59740. this.numUserCamerasChecked++;
  59741. // Already found one.
  59742. if (this.initialCameraFound) { return; }
  59743. // Check if camera is appropriate for being the initial camera.
  59744. cameraData = cameraEl.getAttribute('camera');
  59745. if (!cameraData.active || cameraData.spectator) {
  59746. // No user cameras eligible, create default camera.
  59747. if (this.numUserCamerasChecked === this.numUserCameras) {
  59748. this.createDefaultCamera();
  59749. }
  59750. return;
  59751. }
  59752. this.initialCameraFound = true;
  59753. sceneEl.camera = cameraEl.getObject3D('camera');
  59754. sceneEl.emit('cameraready', {cameraEl: cameraEl});
  59755. },
  59756. createDefaultCamera: function () {
  59757. var defaultCameraEl;
  59758. var sceneEl = this.sceneEl;
  59759. // Set up default camera.
  59760. defaultCameraEl = document.createElement('a-entity');
  59761. defaultCameraEl.setAttribute('camera', {active: true});
  59762. defaultCameraEl.setAttribute('position', {
  59763. x: 0,
  59764. y: constants.DEFAULT_CAMERA_HEIGHT,
  59765. z: 0
  59766. });
  59767. defaultCameraEl.setAttribute('wasd-controls', '');
  59768. defaultCameraEl.setAttribute('look-controls', '');
  59769. defaultCameraEl.setAttribute(constants.AFRAME_INJECTED, '');
  59770. defaultCameraEl.addEventListener('object3dset', function (evt) {
  59771. if (evt.detail.type !== 'camera') { return; }
  59772. sceneEl.camera = evt.detail.object;
  59773. sceneEl.emit('cameraready', {cameraEl: defaultCameraEl});
  59774. });
  59775. sceneEl.appendChild(defaultCameraEl);
  59776. },
  59777. /**
  59778. * Set a different active camera.
  59779. * When we choose a (sort of) random scene camera as the replacement, set its `active` to
  59780. * true. The camera component will call `setActiveCamera` and handle passing the torch to
  59781. * the new camera.
  59782. */
  59783. disableActiveCamera: function () {
  59784. var cameraEls;
  59785. var newActiveCameraEl;
  59786. cameraEls = this.sceneEl.querySelectorAll('[camera]');
  59787. newActiveCameraEl = cameraEls[cameraEls.length - 1];
  59788. newActiveCameraEl.setAttribute('camera', 'active', true);
  59789. },
  59790. /**
  59791. * Set active camera to be used by renderer.
  59792. * Removes the default camera (if present).
  59793. * Disables all other cameras in the scene.
  59794. *
  59795. * @param {Element} newCameraEl - Entity with camera component.
  59796. */
  59797. setActiveCamera: function (newCameraEl) {
  59798. var cameraEl;
  59799. var cameraEls;
  59800. var i;
  59801. var newCamera;
  59802. var previousCamera = this.activeCameraEl;
  59803. var sceneEl = this.sceneEl;
  59804. // Same camera.
  59805. newCamera = newCameraEl.getObject3D('camera');
  59806. if (!newCamera || newCameraEl === this.activeCameraEl) { return; }
  59807. // Grab the default camera.
  59808. var defaultCameraWrapper = sceneEl.querySelector('[' + DEFAULT_CAMERA_ATTR + ']');
  59809. var defaultCameraEl = defaultCameraWrapper &&
  59810. defaultCameraWrapper.querySelector('[camera]');
  59811. // Remove default camera if new camera is not the default camera.
  59812. if (newCameraEl !== defaultCameraEl) { removeDefaultCamera(sceneEl); }
  59813. // Make new camera active.
  59814. this.activeCameraEl = newCameraEl;
  59815. this.activeCameraEl.play();
  59816. sceneEl.camera = newCamera;
  59817. // Disable current camera
  59818. if (previousCamera) {
  59819. previousCamera.setAttribute('camera', 'active', false);
  59820. }
  59821. // Disable other cameras in the scene
  59822. cameraEls = sceneEl.querySelectorAll('[camera]');
  59823. for (i = 0; i < cameraEls.length; i++) {
  59824. cameraEl = cameraEls[i];
  59825. if (!cameraEl.isEntity || newCameraEl === cameraEl) { continue; }
  59826. cameraEl.setAttribute('camera', 'active', false);
  59827. cameraEl.pause();
  59828. }
  59829. sceneEl.emit('camera-set-active', {cameraEl: newCameraEl});
  59830. },
  59831. /**
  59832. * Set spectator camera to render the scene on a 2D display.
  59833. *
  59834. * @param {Element} newCameraEl - Entity with camera component.
  59835. */
  59836. setSpectatorCamera: function (newCameraEl) {
  59837. var newCamera;
  59838. var previousCamera = this.spectatorCameraEl;
  59839. var sceneEl = this.sceneEl;
  59840. var spectatorCameraEl;
  59841. // Same camera.
  59842. newCamera = newCameraEl.getObject3D('camera');
  59843. if (!newCamera || newCameraEl === this.spectatorCameraEl) { return; }
  59844. // Disable current camera
  59845. if (previousCamera) {
  59846. previousCamera.setAttribute('camera', 'spectator', false);
  59847. }
  59848. spectatorCameraEl = this.spectatorCameraEl = newCameraEl;
  59849. sceneEl.addEventListener('enter-vr', this.wrapRender);
  59850. sceneEl.addEventListener('exit-vr', this.unwrapRender);
  59851. spectatorCameraEl.setAttribute('camera', 'active', false);
  59852. spectatorCameraEl.play();
  59853. sceneEl.emit('camera-set-spectator', {cameraEl: newCameraEl});
  59854. },
  59855. /**
  59856. * Disables current spectator camera.
  59857. */
  59858. disableSpectatorCamera: function () {
  59859. this.spectatorCameraEl = undefined;
  59860. },
  59861. /**
  59862. * Wrap the render method of the renderer to render
  59863. * the spectator camera after vrDisplay.submitFrame.
  59864. */
  59865. wrapRender: function () {
  59866. if (!this.spectatorCameraEl || this.originalRender) { return; }
  59867. this.originalRender = this.sceneEl.renderer.render;
  59868. this.sceneEl.renderer.render = this.render;
  59869. },
  59870. unwrapRender: function () {
  59871. if (!this.originalRender) { return; }
  59872. this.sceneEl.renderer.render = this.originalRender;
  59873. this.originalRender = undefined;
  59874. },
  59875. render: function (scene, camera) {
  59876. var isVREnabled;
  59877. var sceneEl = this.sceneEl;
  59878. var spectatorCamera;
  59879. isVREnabled = sceneEl.renderer.xr.enabled;
  59880. this.originalRender.call(sceneEl.renderer, scene, camera);
  59881. if (!this.spectatorCameraEl || sceneEl.isMobile || !isVREnabled) { return; }
  59882. spectatorCamera = this.spectatorCameraEl.components.camera.camera;
  59883. sceneEl.renderer.xr.enabled = false;
  59884. this.originalRender.call(sceneEl.renderer, scene, spectatorCamera);
  59885. sceneEl.renderer.xr.enabled = isVREnabled;
  59886. }
  59887. });
  59888. /**
  59889. * Remove injected default camera from scene, if present.
  59890. *
  59891. * @param {Element} sceneEl
  59892. */
  59893. function removeDefaultCamera (sceneEl) {
  59894. var defaultCamera;
  59895. var camera = sceneEl.camera;
  59896. if (!camera) { return; }
  59897. // Remove default camera if present.
  59898. defaultCamera = sceneEl.querySelector('[' + DEFAULT_CAMERA_ATTR + ']');
  59899. if (!defaultCamera) { return; }
  59900. sceneEl.removeChild(defaultCamera);
  59901. }
  59902. },{"../constants/":123,"../core/system":142}],189:[function(_dereq_,module,exports){
  59903. var geometries = _dereq_('../core/geometry').geometries;
  59904. var registerSystem = _dereq_('../core/system').registerSystem;
  59905. /**
  59906. * System for geometry component.
  59907. * Handle geometry caching.
  59908. *
  59909. * @member {object} cache - Mapping of stringified component data to THREE.BufferGeometry objects.
  59910. * @member {object} cacheCount - Keep track of number of entities using a geometry to
  59911. * know whether to dispose on removal.
  59912. */
  59913. module.exports.System = registerSystem('geometry', {
  59914. init: function () {
  59915. this.cache = {};
  59916. this.cacheCount = {};
  59917. },
  59918. /**
  59919. * Reset cache. Mainly for testing.
  59920. */
  59921. clearCache: function () {
  59922. this.cache = {};
  59923. this.cacheCount = {};
  59924. },
  59925. /**
  59926. * Attempt to retrieve from cache.
  59927. *
  59928. * @returns {Object|null} A geometry if it exists, else null.
  59929. */
  59930. getOrCreateGeometry: function (data) {
  59931. var cache = this.cache;
  59932. var cachedGeometry;
  59933. var hash;
  59934. // Skip all caching logic.
  59935. if (data.skipCache) { return createGeometry(data); }
  59936. // Try to retrieve from cache first.
  59937. hash = this.hash(data);
  59938. cachedGeometry = cache[hash];
  59939. incrementCacheCount(this.cacheCount, hash);
  59940. if (cachedGeometry) { return cachedGeometry; }
  59941. // Create geometry.
  59942. cachedGeometry = createGeometry(data);
  59943. // Cache and return geometry.
  59944. cache[hash] = cachedGeometry;
  59945. return cachedGeometry;
  59946. },
  59947. /**
  59948. * Let system know that an entity is no longer using a geometry.
  59949. */
  59950. unuseGeometry: function (data) {
  59951. var cache = this.cache;
  59952. var cacheCount = this.cacheCount;
  59953. var geometry;
  59954. var hash;
  59955. if (data.skipCache) { return; }
  59956. hash = this.hash(data);
  59957. if (!cache[hash]) { return; }
  59958. decrementCacheCount(cacheCount, hash);
  59959. // Another entity is still using this geometry. No need to do anything.
  59960. if (cacheCount[hash] > 0) { return; }
  59961. // No more entities are using this geometry. Dispose.
  59962. geometry = cache[hash];
  59963. geometry.dispose();
  59964. delete cache[hash];
  59965. delete cacheCount[hash];
  59966. },
  59967. /**
  59968. * Use JSON.stringify to turn component data into hash.
  59969. * Should be deterministic within a single browser engine.
  59970. * If not, then look into json-stable-stringify.
  59971. */
  59972. hash: function (data) {
  59973. return JSON.stringify(data);
  59974. }
  59975. });
  59976. /**
  59977. * Create geometry using component data.
  59978. *
  59979. * @param {object} data - Component data.
  59980. * @returns {object} Geometry.
  59981. */
  59982. function createGeometry (data) {
  59983. var geometryType = data.primitive;
  59984. var GeometryClass = geometries[geometryType] && geometries[geometryType].Geometry;
  59985. var geometryInstance = new GeometryClass();
  59986. if (!GeometryClass) { throw new Error('Unknown geometry `' + geometryType + '`'); }
  59987. geometryInstance.init(data);
  59988. return geometryInstance.geometry;
  59989. }
  59990. /**
  59991. * Decreate count of entity using a geometry.
  59992. */
  59993. function decrementCacheCount (cacheCount, hash) {
  59994. cacheCount[hash]--;
  59995. }
  59996. /**
  59997. * Increase count of entity using a geometry.
  59998. */
  59999. function incrementCacheCount (cacheCount, hash) {
  60000. cacheCount[hash] = cacheCount[hash] === undefined ? 1 : cacheCount[hash] + 1;
  60001. }
  60002. },{"../core/geometry":132,"../core/system":142}],190:[function(_dereq_,module,exports){
  60003. var registerSystem = _dereq_('../core/system').registerSystem;
  60004. var THREE = _dereq_('../lib/three');
  60005. /**
  60006. * glTF model system.
  60007. *
  60008. * Configures glTF loading options. Models using glTF compression require that a Draco decoder be
  60009. * provided externally.
  60010. *
  60011. * @param {string} dracoDecoderPath - Base path from which to load Draco decoder library.
  60012. */
  60013. module.exports.System = registerSystem('gltf-model', {
  60014. schema: {
  60015. dracoDecoderPath: {default: ''}
  60016. },
  60017. init: function () {
  60018. var path = this.data.dracoDecoderPath;
  60019. this.dracoLoader = new THREE.DRACOLoader();
  60020. this.dracoLoader.setDecoderPath(path);
  60021. },
  60022. update: function () {
  60023. var path;
  60024. if (this.dracoLoader) { return; }
  60025. path = this.data.dracoDecoderPath;
  60026. this.dracoLoader = new THREE.DRACOLoader();
  60027. this.dracoLoader.setDecoderPath(path);
  60028. },
  60029. getDRACOLoader: function () {
  60030. return this.dracoLoader;
  60031. }
  60032. });
  60033. },{"../core/system":142,"../lib/three":179}],191:[function(_dereq_,module,exports){
  60034. _dereq_('./camera');
  60035. _dereq_('./geometry');
  60036. _dereq_('./gltf-model');
  60037. _dereq_('./light');
  60038. _dereq_('./material');
  60039. _dereq_('./renderer');
  60040. _dereq_('./shadow');
  60041. _dereq_('./tracked-controls-webvr');
  60042. _dereq_('./tracked-controls-webxr');
  60043. _dereq_('./webxr');
  60044. },{"./camera":188,"./geometry":189,"./gltf-model":190,"./light":192,"./material":193,"./renderer":194,"./shadow":195,"./tracked-controls-webvr":196,"./tracked-controls-webxr":197,"./webxr":198}],192:[function(_dereq_,module,exports){
  60045. var registerSystem = _dereq_('../core/system').registerSystem;
  60046. var bind = _dereq_('../utils/bind');
  60047. var constants = _dereq_('../constants/');
  60048. var DEFAULT_LIGHT_ATTR = 'data-aframe-default-light';
  60049. /**
  60050. * Light system.
  60051. *
  60052. * Prescribes default lighting if not specified (one ambient, one directional).
  60053. * Removes default lighting from the scene when a new light is added.
  60054. *
  60055. * @param {bool} defaultLights - Whether default lighting are defined.
  60056. * @param {bool} userDefinedLights - Whether user lighting is defined.
  60057. */
  60058. module.exports.System = registerSystem('light', {
  60059. schema: {
  60060. defaultLightsEnabled: {default: true}
  60061. },
  60062. init: function () {
  60063. this.defaultLights = false;
  60064. this.userDefinedLights = false;
  60065. // Wait for all entities to fully load before checking for existence of lights.
  60066. // Since entities wait for <a-assets> to load, any lights attaching to the scene
  60067. // will do so asynchronously.
  60068. this.sceneEl.addEventListener('loaded', bind(this.setupDefaultLights, this));
  60069. },
  60070. /**
  60071. * Notify scene that light has been added and to remove the default.
  60072. *
  60073. * @param {object} el - element holding the light component.
  60074. */
  60075. registerLight: function (el) {
  60076. if (!el.hasAttribute(DEFAULT_LIGHT_ATTR)) {
  60077. // User added a light, remove default lights through DOM.
  60078. this.removeDefaultLights();
  60079. this.userDefinedLights = true;
  60080. }
  60081. },
  60082. removeDefaultLights: function () {
  60083. var defaultLights;
  60084. var sceneEl = this.sceneEl;
  60085. if (!this.defaultLights) { return; }
  60086. defaultLights = document.querySelectorAll('[' + DEFAULT_LIGHT_ATTR + ']');
  60087. for (var i = 0; i < defaultLights.length; i++) {
  60088. sceneEl.removeChild(defaultLights[i]);
  60089. }
  60090. this.defaultLights = false;
  60091. },
  60092. /**
  60093. * Prescibe default lights to the scene.
  60094. * Does so by injecting markup such that this state is not invisible.
  60095. * These lights are removed if the user adds any lights.
  60096. */
  60097. setupDefaultLights: function () {
  60098. var sceneEl = this.sceneEl;
  60099. var ambientLight;
  60100. var directionalLight;
  60101. if (this.userDefinedLights || this.defaultLights || !this.data.defaultLightsEnabled) {
  60102. return;
  60103. }
  60104. ambientLight = document.createElement('a-entity');
  60105. ambientLight.setAttribute('light', {color: '#BBB', type: 'ambient'});
  60106. ambientLight.setAttribute(DEFAULT_LIGHT_ATTR, '');
  60107. ambientLight.setAttribute(constants.AFRAME_INJECTED, '');
  60108. sceneEl.appendChild(ambientLight);
  60109. directionalLight = document.createElement('a-entity');
  60110. directionalLight.setAttribute('light', {color: '#FFF', intensity: 0.6, castShadow: true});
  60111. directionalLight.setAttribute('position', {x: -0.5, y: 1, z: 1});
  60112. directionalLight.setAttribute(DEFAULT_LIGHT_ATTR, '');
  60113. directionalLight.setAttribute(constants.AFRAME_INJECTED, '');
  60114. sceneEl.appendChild(directionalLight);
  60115. this.defaultLights = true;
  60116. }
  60117. });
  60118. },{"../constants/":123,"../core/system":142,"../utils/bind":199}],193:[function(_dereq_,module,exports){
  60119. var registerSystem = _dereq_('../core/system').registerSystem;
  60120. var THREE = _dereq_('../lib/three');
  60121. var utils = _dereq_('../utils/');
  60122. var isHLS = _dereq_('../utils/material').isHLS;
  60123. var bind = utils.bind;
  60124. var debug = utils.debug;
  60125. var error = debug('components:texture:error');
  60126. var TextureLoader = new THREE.TextureLoader();
  60127. var warn = debug('components:texture:warn');
  60128. TextureLoader.setCrossOrigin('anonymous');
  60129. /**
  60130. * System for material component.
  60131. * Handle material registration, updates (for fog), and texture caching.
  60132. *
  60133. * @member {object} materials - Registered materials.
  60134. * @member {object} textureCounts - Number of times each texture is used. Tracked
  60135. * separately from textureCache, because the cache (1) is populated in
  60136. * multiple places, and (2) may be cleared at any time.
  60137. * @member {object} textureCache - Texture cache for:
  60138. * - Images: textureCache has mapping of src -> repeat -> cached three.js texture.
  60139. * - Videos: textureCache has mapping of videoElement -> cached three.js texture.
  60140. */
  60141. module.exports.System = registerSystem('material', {
  60142. init: function () {
  60143. this.materials = {};
  60144. this.textureCounts = {};
  60145. this.textureCache = {};
  60146. this.sceneEl.addEventListener(
  60147. 'materialtextureloaded',
  60148. bind(this.onMaterialTextureLoaded, this)
  60149. );
  60150. },
  60151. clearTextureCache: function () {
  60152. this.textureCache = {};
  60153. },
  60154. /**
  60155. * Determine whether `src` is a image or video. Then try to load the asset, then call back.
  60156. *
  60157. * @param {string, or element} src - Texture URL or element.
  60158. * @param {string} data - Relevant texture data used for caching.
  60159. * @param {function} cb - Callback to pass texture to.
  60160. */
  60161. loadTexture: function (src, data, cb) {
  60162. var self = this;
  60163. // Canvas.
  60164. if (src.tagName === 'CANVAS') {
  60165. this.loadCanvas(src, data, cb);
  60166. return;
  60167. }
  60168. // Video element.
  60169. if (src.tagName === 'VIDEO') {
  60170. if (!src.src && !src.srcObject && !src.childElementCount) {
  60171. warn('Video element was defined with neither `source` elements nor `src` / `srcObject` attributes.');
  60172. }
  60173. this.loadVideo(src, data, cb);
  60174. return;
  60175. }
  60176. utils.srcLoader.validateSrc(src, loadImageCb, loadVideoCb);
  60177. function loadImageCb (src) { self.loadImage(src, data, cb); }
  60178. function loadVideoCb (src) { self.loadVideo(src, data, cb); }
  60179. },
  60180. /**
  60181. * High-level function for loading image textures (THREE.Texture).
  60182. *
  60183. * @param {Element|string} src - Texture source.
  60184. * @param {object} data - Texture data.
  60185. * @param {function} cb - Callback to pass texture to.
  60186. */
  60187. loadImage: function (src, data, handleImageTextureLoaded) {
  60188. var hash = this.hash(data);
  60189. var textureCache = this.textureCache;
  60190. // Texture already being loaded or already loaded. Wait on promise.
  60191. if (textureCache[hash]) {
  60192. textureCache[hash].then(handleImageTextureLoaded);
  60193. return;
  60194. }
  60195. // Texture not yet being loaded. Start loading it.
  60196. textureCache[hash] = loadImageTexture(src, data);
  60197. textureCache[hash].then(handleImageTextureLoaded);
  60198. },
  60199. /**
  60200. * High-level function for loading canvas textures (THREE.Texture).
  60201. *
  60202. * @param {Element|string} src - Texture source.
  60203. * @param {object} data - Texture data.
  60204. * @param {function} cb - Callback to pass texture to.
  60205. */
  60206. loadCanvas: function (src, data, cb) {
  60207. var texture;
  60208. texture = new THREE.CanvasTexture(src);
  60209. setTextureProperties(texture, data);
  60210. cb(texture);
  60211. },
  60212. /**
  60213. * Load video texture (THREE.VideoTexture).
  60214. * Which is just an image texture that RAFs + needsUpdate.
  60215. * Note that creating a video texture is synchronous unlike loading an image texture.
  60216. * Made asynchronous to be consistent with image textures.
  60217. *
  60218. * @param {Element|string} src - Texture source.
  60219. * @param {object} data - Texture data.
  60220. * @param {function} cb - Callback to pass texture to.
  60221. */
  60222. loadVideo: function (src, data, cb) {
  60223. var hash;
  60224. var texture;
  60225. var textureCache = this.textureCache;
  60226. var videoEl;
  60227. var videoTextureResult;
  60228. function handleVideoTextureLoaded (result) {
  60229. result.texture.needsUpdate = true;
  60230. cb(result.texture, result.videoEl);
  60231. }
  60232. // Video element provided.
  60233. if (typeof src !== 'string') {
  60234. // Check cache before creating texture.
  60235. videoEl = src;
  60236. hash = this.hashVideo(data, videoEl);
  60237. if (textureCache[hash]) {
  60238. textureCache[hash].then(handleVideoTextureLoaded);
  60239. return;
  60240. }
  60241. // If not in cache, fix up the attributes then start to create the texture.
  60242. fixVideoAttributes(videoEl);
  60243. }
  60244. // Only URL provided. Use video element to create texture.
  60245. videoEl = videoEl || createVideoEl(src, data.width, data.height);
  60246. // Generated video element already cached. Use that.
  60247. hash = this.hashVideo(data, videoEl);
  60248. if (textureCache[hash]) {
  60249. textureCache[hash].then(handleVideoTextureLoaded);
  60250. return;
  60251. }
  60252. // Create new video texture.
  60253. texture = new THREE.VideoTexture(videoEl);
  60254. texture.minFilter = THREE.LinearFilter;
  60255. setTextureProperties(texture, data);
  60256. // If iOS and video is HLS, do some hacks.
  60257. if (this.sceneEl.isIOS &&
  60258. isHLS(videoEl.src || videoEl.getAttribute('src'),
  60259. videoEl.type || videoEl.getAttribute('type'))) {
  60260. // Actually BGRA. Tell shader to correct later.
  60261. texture.format = THREE.RGBAFormat;
  60262. texture.needsCorrectionBGRA = true;
  60263. // Apparently needed for HLS. Tell shader to correct later.
  60264. texture.flipY = false;
  60265. texture.needsCorrectionFlipY = true;
  60266. }
  60267. // Cache as promise to be consistent with image texture caching.
  60268. videoTextureResult = {texture: texture, videoEl: videoEl};
  60269. textureCache[hash] = Promise.resolve(videoTextureResult);
  60270. handleVideoTextureLoaded(videoTextureResult);
  60271. },
  60272. /**
  60273. * Create a hash of the material properties for texture cache key.
  60274. */
  60275. hash: function (data) {
  60276. if (data.src.tagName) {
  60277. // Since `data.src` can be an element, parse out the string if necessary for the hash.
  60278. data = utils.extendDeep({}, data);
  60279. data.src = data.src.src;
  60280. }
  60281. return JSON.stringify(data);
  60282. },
  60283. hashVideo: function (data, videoEl) {
  60284. return calculateVideoCacheHash(data, videoEl);
  60285. },
  60286. /**
  60287. * Keep track of material in case an update trigger is needed (e.g., fog).
  60288. *
  60289. * @param {object} material
  60290. */
  60291. registerMaterial: function (material) {
  60292. this.materials[material.uuid] = material;
  60293. },
  60294. /**
  60295. * Stop tracking material, and dispose of any textures not being used by
  60296. * another material component.
  60297. *
  60298. * @param {object} material
  60299. */
  60300. unregisterMaterial: function (material) {
  60301. delete this.materials[material.uuid];
  60302. // If any textures on this material are no longer in use, dispose of them.
  60303. var textureCounts = this.textureCounts;
  60304. Object.keys(material)
  60305. .filter(function (propName) {
  60306. return material[propName] && material[propName].isTexture;
  60307. })
  60308. .forEach(function (mapName) {
  60309. textureCounts[material[mapName].uuid]--;
  60310. if (textureCounts[material[mapName].uuid] <= 0) {
  60311. material[mapName].dispose();
  60312. }
  60313. });
  60314. },
  60315. /**
  60316. * Trigger update to all registered materials.
  60317. */
  60318. updateMaterials: function (material) {
  60319. var materials = this.materials;
  60320. Object.keys(materials).forEach(function (uuid) {
  60321. materials[uuid].needsUpdate = true;
  60322. });
  60323. },
  60324. /**
  60325. * Track textures used by material components, so that they can be safely
  60326. * disposed when no longer in use. Textures must be registered here, and not
  60327. * through registerMaterial(), because textures may not be attached at the
  60328. * time the material is registered.
  60329. *
  60330. * @param {Event} e
  60331. */
  60332. onMaterialTextureLoaded: function (e) {
  60333. if (!this.textureCounts[e.detail.texture.uuid]) {
  60334. this.textureCounts[e.detail.texture.uuid] = 0;
  60335. }
  60336. this.textureCounts[e.detail.texture.uuid]++;
  60337. }
  60338. });
  60339. /**
  60340. * Calculates consistent hash from a video element using its attributes.
  60341. * If the video element has an ID, use that.
  60342. * Else build a hash that looks like `src:myvideo.mp4;height:200;width:400;`.
  60343. *
  60344. * @param data {object} - Texture data such as repeat.
  60345. * @param videoEl {Element} - Video element.
  60346. * @returns {string}
  60347. */
  60348. function calculateVideoCacheHash (data, videoEl) {
  60349. var i;
  60350. var id = videoEl.getAttribute('id');
  60351. var hash;
  60352. var videoAttributes;
  60353. if (id) { return id; }
  60354. // Calculate hash using sorted video attributes.
  60355. hash = '';
  60356. videoAttributes = data || {};
  60357. for (i = 0; i < videoEl.attributes.length; i++) {
  60358. videoAttributes[videoEl.attributes[i].name] = videoEl.attributes[i].value;
  60359. }
  60360. Object.keys(videoAttributes).sort().forEach(function (name) {
  60361. hash += name + ':' + videoAttributes[name] + ';';
  60362. });
  60363. return hash;
  60364. }
  60365. /**
  60366. * Load image texture.
  60367. *
  60368. * @private
  60369. * @param {string|object} src - An <img> element or url to an image file.
  60370. * @param {object} data - Data to set texture properties like `repeat`.
  60371. * @returns {Promise} Resolves once texture is loaded.
  60372. */
  60373. function loadImageTexture (src, data) {
  60374. return new Promise(doLoadImageTexture);
  60375. function doLoadImageTexture (resolve, reject) {
  60376. var isEl = typeof src !== 'string';
  60377. function resolveTexture (texture) {
  60378. setTextureProperties(texture, data);
  60379. texture.needsUpdate = true;
  60380. resolve(texture);
  60381. }
  60382. // Create texture from an element.
  60383. if (isEl) {
  60384. resolveTexture(new THREE.Texture(src));
  60385. return;
  60386. }
  60387. // Request and load texture from src string. THREE will create underlying element.
  60388. // Use THREE.TextureLoader (src, onLoad, onProgress, onError) to load texture.
  60389. TextureLoader.load(
  60390. src,
  60391. resolveTexture,
  60392. function () { /* no-op */ },
  60393. function (xhr) {
  60394. error('`$s` could not be fetched (Error code: %s; Response: %s)', xhr.status,
  60395. xhr.statusText);
  60396. }
  60397. );
  60398. }
  60399. }
  60400. /**
  60401. * Set texture properties such as repeat and offset.
  60402. *
  60403. * @param {object} data - With keys like `repeat`.
  60404. */
  60405. function setTextureProperties (texture, data) {
  60406. var offset = data.offset || {x: 0, y: 0};
  60407. var repeat = data.repeat || {x: 1, y: 1};
  60408. var npot = data.npot || false;
  60409. // To support NPOT textures, wrap must be ClampToEdge (not Repeat),
  60410. // and filters must not use mipmaps (i.e. Nearest or Linear).
  60411. if (npot) {
  60412. texture.wrapS = THREE.ClampToEdgeWrapping;
  60413. texture.wrapT = THREE.ClampToEdgeWrapping;
  60414. texture.magFilter = THREE.LinearFilter;
  60415. texture.minFilter = THREE.LinearFilter;
  60416. }
  60417. // Don't bother setting repeat if it is 1/1. Power-of-two is required to repeat.
  60418. if (repeat.x !== 1 || repeat.y !== 1) {
  60419. texture.wrapS = THREE.RepeatWrapping;
  60420. texture.wrapT = THREE.RepeatWrapping;
  60421. texture.repeat.set(repeat.x, repeat.y);
  60422. }
  60423. // Don't bother setting offset if it is 0/0.
  60424. if (offset.x !== 0 || offset.y !== 0) {
  60425. texture.offset.set(offset.x, offset.y);
  60426. }
  60427. }
  60428. /**
  60429. * Create video element to be used as a texture.
  60430. *
  60431. * @param {string} src - Url to a video file.
  60432. * @param {number} width - Width of the video.
  60433. * @param {number} height - Height of the video.
  60434. * @returns {Element} Video element.
  60435. */
  60436. function createVideoEl (src, width, height) {
  60437. var videoEl = document.createElement('video');
  60438. videoEl.width = width;
  60439. videoEl.height = height;
  60440. // Support inline videos for iOS webviews.
  60441. videoEl.setAttribute('playsinline', '');
  60442. videoEl.setAttribute('webkit-playsinline', '');
  60443. videoEl.autoplay = true;
  60444. videoEl.loop = true;
  60445. videoEl.crossOrigin = 'anonymous';
  60446. videoEl.addEventListener('error', function () {
  60447. warn('`$s` is not a valid video', src);
  60448. }, true);
  60449. videoEl.src = src;
  60450. return videoEl;
  60451. }
  60452. /**
  60453. * Fixes a video element's attributes to prevent developers from accidentally passing the
  60454. * wrong attribute values to commonly misused video attributes.
  60455. *
  60456. * <video> does not treat `autoplay`, `controls`, `crossorigin`, `loop`, and `preload` as
  60457. * as booleans. Existence of those attributes will mean truthy.
  60458. *
  60459. * For example, translates <video loop="false"> to <video>.
  60460. *
  60461. * @see https://developer.mozilla.org/docs/Web/HTML/Element/video#Attributes
  60462. * @param {Element} videoEl - Video element.
  60463. * @returns {Element} Video element with the correct properties updated.
  60464. */
  60465. function fixVideoAttributes (videoEl) {
  60466. videoEl.autoplay = videoEl.hasAttribute('autoplay') && videoEl.getAttribute('autoplay') !== 'false';
  60467. videoEl.controls = videoEl.hasAttribute('controls') && videoEl.getAttribute('controls') !== 'false';
  60468. if (videoEl.getAttribute('loop') === 'false') {
  60469. videoEl.removeAttribute('loop');
  60470. }
  60471. if (videoEl.getAttribute('preload') === 'false') {
  60472. videoEl.preload = 'none';
  60473. }
  60474. videoEl.crossOrigin = videoEl.crossOrigin || 'anonymous';
  60475. // To support inline videos in iOS webviews.
  60476. videoEl.setAttribute('playsinline', '');
  60477. videoEl.setAttribute('webkit-playsinline', '');
  60478. return videoEl;
  60479. }
  60480. },{"../core/system":142,"../lib/three":179,"../utils/":205,"../utils/material":209}],194:[function(_dereq_,module,exports){
  60481. var registerSystem = _dereq_('../core/system').registerSystem;
  60482. var utils = _dereq_('../utils/');
  60483. var THREE = _dereq_('../lib/three');
  60484. var debug = utils.debug;
  60485. var warn = debug('components:renderer:warn');
  60486. /**
  60487. * Determines state of various renderer properties.
  60488. */
  60489. module.exports.System = registerSystem('renderer', {
  60490. schema: {
  60491. antialias: {default: 'auto', oneOf: ['true', 'false', 'auto']},
  60492. highRefreshRate: {default: utils.device.isOculusBrowser()},
  60493. logarithmicDepthBuffer: {default: 'auto', oneOf: ['true', 'false', 'auto']},
  60494. maxCanvasWidth: {default: 1920},
  60495. maxCanvasHeight: {default: 1920},
  60496. physicallyCorrectLights: {default: false},
  60497. precision: {default: 'high', oneOf: ['high', 'medium', 'low']},
  60498. sortObjects: {default: false},
  60499. colorManagement: {default: false},
  60500. gammaOutput: {default: false},
  60501. alpha: {default: true},
  60502. foveationLevel: {default: 0}
  60503. },
  60504. init: function () {
  60505. var data = this.data;
  60506. var sceneEl = this.el;
  60507. // This is the rendering engine, such as THREE.js so copy over any persistent properties from the rendering system.
  60508. var renderer = sceneEl.renderer;
  60509. renderer.sortObjects = data.sortObjects;
  60510. renderer.physicallyCorrectLights = data.physicallyCorrectLights;
  60511. if (data.colorManagement || data.gammaOutput) {
  60512. renderer.outputEncoding = THREE.sRGBEncoding;
  60513. if (data.gammaOutput) {
  60514. warn('Property `gammaOutput` is deprecated. Use `renderer="colorManagement: true;"` instead.');
  60515. }
  60516. }
  60517. if (sceneEl.hasAttribute('antialias')) {
  60518. warn('Component `antialias` is deprecated. Use `renderer="antialias: true"` instead.');
  60519. }
  60520. if (sceneEl.hasAttribute('logarithmicDepthBuffer')) {
  60521. warn('Component `logarithmicDepthBuffer` is deprecated. Use `renderer="logarithmicDepthBuffer: true"` instead.');
  60522. }
  60523. },
  60524. applyColorCorrection: function (colorOrTexture) {
  60525. if (!this.data.colorManagement || !colorOrTexture) {
  60526. return;
  60527. } else if (colorOrTexture.isColor) {
  60528. colorOrTexture.convertSRGBToLinear();
  60529. } else if (colorOrTexture.isTexture) {
  60530. colorOrTexture.encoding = THREE.sRGBEncoding;
  60531. }
  60532. }
  60533. });
  60534. },{"../core/system":142,"../lib/three":179,"../utils/":205}],195:[function(_dereq_,module,exports){
  60535. var registerSystem = _dereq_('../core/system').registerSystem;
  60536. var THREE = _dereq_('../lib/three');
  60537. var SHADOW_MAP_TYPE_MAP = {
  60538. basic: THREE.BasicShadowMap,
  60539. pcf: THREE.PCFShadowMap,
  60540. pcfsoft: THREE.PCFSoftShadowMap
  60541. };
  60542. /**
  60543. * Shadow system.
  60544. *
  60545. * Enabled automatically when one or more shadow components are added to the scene, the system sets
  60546. * options on the WebGLRenderer for configuring shadow appearance.
  60547. */
  60548. module.exports.System = registerSystem('shadow', {
  60549. schema: {
  60550. enabled: {default: true},
  60551. autoUpdate: {default: true},
  60552. type: {default: 'pcf', oneOf: ['basic', 'pcf', 'pcfsoft']}
  60553. },
  60554. init: function () {
  60555. var sceneEl = this.sceneEl;
  60556. var data = this.data;
  60557. this.shadowMapEnabled = false;
  60558. if (!sceneEl.renderer) { return; } // For tests.
  60559. sceneEl.renderer.shadowMap.type = SHADOW_MAP_TYPE_MAP[data.type];
  60560. sceneEl.renderer.shadowMap.autoUpdate = data.autoUpdate;
  60561. this.setShadowMapEnabled(this.shadowMapEnabled);
  60562. },
  60563. update: function (prevData) {
  60564. if (prevData.enabled !== this.data.enabled) {
  60565. this.setShadowMapEnabled(this.data.enabled);
  60566. }
  60567. },
  60568. /**
  60569. * Enables/disables the renderer shadow map.
  60570. * @param {boolean} enabled
  60571. */
  60572. setShadowMapEnabled: function (enabled) {
  60573. var renderer = this.sceneEl.renderer;
  60574. this.shadowMapEnabled = this.data.enabled && enabled;
  60575. if (renderer) {
  60576. renderer.shadowMap.enabled = this.shadowMapEnabled;
  60577. }
  60578. }
  60579. });
  60580. },{"../core/system":142,"../lib/three":179}],196:[function(_dereq_,module,exports){
  60581. var registerSystem = _dereq_('../core/system').registerSystem;
  60582. var utils = _dereq_('../utils');
  60583. var isWebXRAvailable = utils.device.isWebXRAvailable;
  60584. /**
  60585. * Tracked controls system.
  60586. * Maintain list with available tracked controllers.
  60587. */
  60588. module.exports.System = registerSystem('tracked-controls-webvr', {
  60589. init: function () {
  60590. var self = this;
  60591. this.controllers = [];
  60592. this.isChrome = navigator.userAgent.indexOf('Chrome') !== -1;
  60593. this.updateControllerList();
  60594. this.throttledUpdateControllerList = utils.throttle(this.updateControllerList, 500, this);
  60595. // Don't use WebVR if WebXR is available?
  60596. if (isWebXRAvailable) { return; }
  60597. if (!navigator.getVRDisplays) { return; }
  60598. this.sceneEl.addEventListener('enter-vr', function () {
  60599. navigator.getVRDisplays().then(function (displays) {
  60600. if (displays.length) { self.vrDisplay = displays[0]; }
  60601. });
  60602. });
  60603. },
  60604. tick: function () {
  60605. if (this.isChrome) {
  60606. // Retrieve new controller handlers with updated state (pose, buttons...)
  60607. this.updateControllerList();
  60608. } else {
  60609. this.throttledUpdateControllerList();
  60610. }
  60611. },
  60612. /**
  60613. * Update controller list.
  60614. */
  60615. updateControllerList: function () {
  60616. var controllers = this.controllers;
  60617. var gamepad;
  60618. var gamepads;
  60619. var i;
  60620. var prevCount;
  60621. gamepads = navigator.getGamepads && navigator.getGamepads();
  60622. if (!gamepads) { return; }
  60623. prevCount = controllers.length;
  60624. controllers.length = 0;
  60625. for (i = 0; i < gamepads.length; ++i) {
  60626. gamepad = gamepads[i];
  60627. if (gamepad && gamepad.pose) {
  60628. controllers.push(gamepad);
  60629. }
  60630. }
  60631. if (controllers.length !== prevCount) {
  60632. this.el.emit('controllersupdated', undefined, false);
  60633. }
  60634. }
  60635. });
  60636. },{"../core/system":142,"../utils":205}],197:[function(_dereq_,module,exports){
  60637. var registerSystem = _dereq_('../core/system').registerSystem;
  60638. var utils = _dereq_('../utils');
  60639. /**
  60640. * Tracked controls system.
  60641. * Maintain list with available tracked controllers.
  60642. */
  60643. module.exports.System = registerSystem('tracked-controls-webxr', {
  60644. init: function () {
  60645. this.controllers = [];
  60646. this.oldControllers = [];
  60647. this.oldControllersLength = 0;
  60648. this.throttledUpdateControllerList = utils.throttle(this.updateControllerList, 500, this);
  60649. this.updateReferenceSpace = this.updateReferenceSpace.bind(this);
  60650. this.el.addEventListener('enter-vr', this.updateReferenceSpace);
  60651. this.el.addEventListener('exit-vr', this.updateReferenceSpace);
  60652. },
  60653. tick: function () {
  60654. this.throttledUpdateControllerList();
  60655. },
  60656. updateReferenceSpace: function () {
  60657. var self = this;
  60658. var xrSession = this.el.xrSession;
  60659. if (!xrSession) {
  60660. this.referenceSpace = undefined;
  60661. this.controllers = [];
  60662. if (this.oldControllersLength > 0) {
  60663. this.oldControllersLength = 0;
  60664. this.el.emit('controllersupdated', undefined, false);
  60665. }
  60666. return;
  60667. }
  60668. var refspace = self.el.sceneEl.systems.webxr.sessionReferenceSpaceType;
  60669. xrSession.requestReferenceSpace(refspace).then(function (referenceSpace) {
  60670. self.referenceSpace = referenceSpace;
  60671. }).catch(function (err) {
  60672. self.el.sceneEl.systems.webxr.warnIfFeatureNotRequested(
  60673. refspace,
  60674. 'tracked-controls-webxr uses reference space "' + refspace + '".');
  60675. throw err;
  60676. });
  60677. },
  60678. updateControllerList: function () {
  60679. var xrSession = this.el.xrSession;
  60680. var oldControllers = this.oldControllers;
  60681. var i;
  60682. if (!xrSession) {
  60683. if (this.oldControllersLength === 0) { return; }
  60684. // Broadcast that we now have zero controllers connected if there is
  60685. // no session
  60686. this.oldControllersLength = 0;
  60687. this.controllers = [];
  60688. this.el.emit('controllersupdated', undefined, false);
  60689. return;
  60690. }
  60691. if (!xrSession.inputSources) { return; }
  60692. this.controllers = xrSession.inputSources;
  60693. if (this.oldControllersLength === this.controllers.length) {
  60694. var equal = true;
  60695. for (i = 0; i < this.controllers.length; ++i) {
  60696. if (this.controllers[i] === oldControllers[i] &&
  60697. this.controllers[i].gamepad === oldControllers[i].gamepad) { continue; }
  60698. equal = false;
  60699. break;
  60700. }
  60701. if (equal) { return; }
  60702. }
  60703. // Store reference to current controllers
  60704. oldControllers.length = 0;
  60705. for (i = 0; i < this.controllers.length; i++) {
  60706. oldControllers.push(this.controllers[i]);
  60707. }
  60708. this.oldControllersLength = this.controllers.length;
  60709. this.el.emit('controllersupdated', undefined, false);
  60710. }
  60711. });
  60712. },{"../core/system":142,"../utils":205}],198:[function(_dereq_,module,exports){
  60713. var registerSystem = _dereq_('../core/system').registerSystem;
  60714. var utils = _dereq_('../utils/');
  60715. var warn = utils.debug('systems:webxr:warn');
  60716. /**
  60717. * WebXR session initialization and XR module support.
  60718. */
  60719. module.exports.System = registerSystem('webxr', {
  60720. schema: {
  60721. referenceSpaceType: {type: 'string', default: 'local-floor'},
  60722. requiredFeatures: {type: 'array', default: ['local-floor']},
  60723. optionalFeatures: {type: 'array', default: ['bounded-floor']},
  60724. overlayElement: {type: 'selector'}
  60725. },
  60726. update: function () {
  60727. var data = this.data;
  60728. this.sessionConfiguration = {
  60729. requiredFeatures: data.requiredFeatures,
  60730. optionalFeatures: data.optionalFeatures
  60731. };
  60732. this.sessionReferenceSpaceType = data.referenceSpaceType;
  60733. if (data.overlayElement) {
  60734. this.warnIfFeatureNotRequested('dom-overlay');
  60735. this.sessionConfiguration.domOverlay = {root: data.overlayElement};
  60736. }
  60737. },
  60738. wasFeatureRequested: function (feature) {
  60739. // Features available by default for immersive sessions don't need to
  60740. // be requested explicitly.
  60741. if (feature === 'viewer' || feature === 'local') return true;
  60742. if (this.sessionConfiguration.requiredFeatures.includes(feature) ||
  60743. this.sessionConfiguration.optionalFeatures.includes(feature)) {
  60744. return true;
  60745. }
  60746. return false;
  60747. },
  60748. warnIfFeatureNotRequested: function (feature, optIntro) {
  60749. if (!this.wasFeatureRequested(feature)) {
  60750. var msg = 'Please add the feature "' + feature + '" to a-scene\'s ' +
  60751. 'webxr system options in requiredFeatures/optionalFeatures.';
  60752. warn((optIntro ? optIntro + ' ' : '') + msg);
  60753. }
  60754. }
  60755. });
  60756. },{"../core/system":142,"../utils/":205}],199:[function(_dereq_,module,exports){
  60757. /**
  60758. * Faster version of Function.prototype.bind
  60759. * @param {Function} fn - Function to wrap.
  60760. * @param {Object} ctx - What to bind as context.
  60761. * @param {...*} arguments - Arguments to pass through.
  60762. */
  60763. module.exports = function bind (fn, ctx/* , arg1, arg2 */) {
  60764. return (function (prependedArgs) {
  60765. return function bound () {
  60766. // Concat the bound function arguments with those passed to original bind
  60767. var args = prependedArgs.concat(Array.prototype.slice.call(arguments, 0));
  60768. return fn.apply(ctx, args);
  60769. };
  60770. })(Array.prototype.slice.call(arguments, 2));
  60771. };
  60772. },{}],200:[function(_dereq_,module,exports){
  60773. /* global THREE */
  60774. var debug = _dereq_('./debug');
  60775. var extend = _dereq_('object-assign');
  60776. var warn = debug('utils:coordinates:warn');
  60777. // Order of coordinates parsed by coordinates.parse.
  60778. var COORDINATE_KEYS = ['x', 'y', 'z', 'w'];
  60779. // Coordinate string regex. Handles negative, positive, and decimals.
  60780. var regex = /^\s*((-?\d*\.{0,1}\d+(e-?\d+)?)\s+){2,3}(-?\d*\.{0,1}\d+(e-?\d+)?)\s*$/;
  60781. module.exports.regex = regex;
  60782. var OBJECT = 'object';
  60783. var whitespaceRegex = /\s+/g;
  60784. /**
  60785. * Parses coordinates from an "x y z" string.
  60786. * Example: "3 10 -5" to {x: 3, y: 10, z: -5}.
  60787. *
  60788. * @param {string} val - An "x y z" string.
  60789. * @param {string} defaults - fallback value.
  60790. * @returns {object} An object with keys [x, y, z].
  60791. */
  60792. function parse (value, defaultVec) {
  60793. var coordinate;
  60794. var defaultVal;
  60795. var key;
  60796. var i;
  60797. var vec;
  60798. var x;
  60799. var y;
  60800. var z;
  60801. var w;
  60802. if (value && value instanceof Object) {
  60803. x = value.x === undefined ? defaultVec && defaultVec.x : value.x;
  60804. y = value.y === undefined ? defaultVec && defaultVec.y : value.y;
  60805. z = value.z === undefined ? defaultVec && defaultVec.z : value.z;
  60806. w = value.w === undefined ? defaultVec && defaultVec.w : value.w;
  60807. if (x !== undefined && x !== null) { value.x = parseIfString(x); }
  60808. if (y !== undefined && y !== null) { value.y = parseIfString(y); }
  60809. if (z !== undefined && z !== null) { value.z = parseIfString(z); }
  60810. if (w !== undefined && w !== null) { value.w = parseIfString(w); }
  60811. return value;
  60812. }
  60813. if (value === null || value === undefined) {
  60814. return typeof defaultVec === OBJECT ? extend({}, defaultVec) : defaultVec;
  60815. }
  60816. coordinate = value.trim().split(whitespaceRegex);
  60817. vec = {};
  60818. for (i = 0; i < COORDINATE_KEYS.length; i++) {
  60819. key = COORDINATE_KEYS[i];
  60820. if (coordinate[i]) {
  60821. vec[key] = parseFloat(coordinate[i], 10);
  60822. } else {
  60823. defaultVal = defaultVec && defaultVec[key];
  60824. if (defaultVal === undefined) { continue; }
  60825. vec[key] = parseIfString(defaultVal);
  60826. }
  60827. }
  60828. return vec;
  60829. }
  60830. module.exports.parse = parse;
  60831. /**
  60832. * Stringify coordinates from an object with keys [x y z].
  60833. * Example: {x: 3, y: 10, z: -5} to "3 10 -5".
  60834. *
  60835. * @param {object|string} data - An object with keys [x y z].
  60836. * @returns {string} An "x y z" string.
  60837. */
  60838. function stringify (data) {
  60839. var str;
  60840. if (typeof data !== OBJECT) { return data; }
  60841. str = data.x + ' ' + data.y;
  60842. if (data.z != null) { str += ' ' + data.z; }
  60843. if (data.w != null) { str += ' ' + data.w; }
  60844. return str;
  60845. }
  60846. module.exports.stringify = stringify;
  60847. /**
  60848. * @returns {bool}
  60849. */
  60850. function isCoordinates (value) {
  60851. return regex.test(value);
  60852. }
  60853. module.exports.isCoordinates = isCoordinates;
  60854. module.exports.isCoordinate = function (value) {
  60855. warn('`AFRAME.utils.isCoordinate` has been renamed to `AFRAME.utils.isCoordinates`');
  60856. return isCoordinates(value);
  60857. };
  60858. function parseIfString (val) {
  60859. if (val !== null && val !== undefined && val.constructor === String) {
  60860. return parseFloat(val, 10);
  60861. }
  60862. return val;
  60863. }
  60864. /**
  60865. * Convert {x, y, z} object to three.js Vector3.
  60866. */
  60867. module.exports.toVector3 = function (vec3) {
  60868. return new THREE.Vector3(vec3.x, vec3.y, vec3.z);
  60869. };
  60870. },{"./debug":201,"object-assign":39}],201:[function(_dereq_,module,exports){
  60871. (function (process){
  60872. var debugLib = _dereq_('debug');
  60873. var extend = _dereq_('object-assign');
  60874. var settings = {
  60875. colors: {
  60876. debug: 'gray',
  60877. error: 'red',
  60878. info: 'gray',
  60879. warn: 'orange'
  60880. }
  60881. };
  60882. /**
  60883. * Monkeypatches `debug` so we can colorize error/warning messages.
  60884. *
  60885. * (See issue: https://github.com/visionmedia/debug/issues/137)
  60886. */
  60887. var debug = function (namespace) {
  60888. var d = debugLib(namespace);
  60889. d.color = getDebugNamespaceColor(namespace);
  60890. return d;
  60891. };
  60892. extend(debug, debugLib);
  60893. /**
  60894. * Returns the type of the namespace (e.g., `error`, `warn`).
  60895. *
  60896. * @param {String} namespace
  60897. * The debug logger's namespace (e.g., `components:geometry:warn`).
  60898. * @returns {String} The type of the namespace (e.g., `warn`).
  60899. * @api private
  60900. */
  60901. function getDebugNamespaceType (namespace) {
  60902. var chunks = namespace.split(':');
  60903. return chunks[chunks.length - 1]; // Return the last one
  60904. }
  60905. /**
  60906. * Returns the color of the namespace (e.g., `orange`).
  60907. *
  60908. * @param {String} namespace
  60909. * The debug logger's namespace (e.g., `components:geometry:warn`).
  60910. * @returns {String} The color of the namespace (e.g., `orange`).
  60911. * @api private
  60912. */
  60913. function getDebugNamespaceColor (namespace) {
  60914. var type = getDebugNamespaceType(namespace);
  60915. var color = settings.colors && settings.colors[type];
  60916. return color || null;
  60917. }
  60918. /**
  60919. * Returns `localStorage` if possible.
  60920. *
  60921. * This is necessary because Safari throws when a user disables
  60922. * cookies or `localStorage` and you attempt to access it.
  60923. *
  60924. * @returns {localStorage}
  60925. * @api private
  60926. */
  60927. function storage () {
  60928. try {
  60929. return window.localStorage;
  60930. } catch (e) {
  60931. }
  60932. }
  60933. /**
  60934. * To enable console logging, type this in the Console of your Dev Tools:
  60935. *
  60936. * localStorage.logs = 1
  60937. *
  60938. * To disable console logging:
  60939. *
  60940. * localStorage.logs = 0
  60941. *
  60942. */
  60943. var ls = storage();
  60944. if (ls && (parseInt(ls.logs, 10) || ls.logs === 'true')) {
  60945. debug.enable('*');
  60946. } else {
  60947. debug.enable('*:error,*:info,*:warn');
  60948. }
  60949. if (process.browser) { window.logs = debug; }
  60950. module.exports = debug;
  60951. }).call(this,_dereq_('_process'))
  60952. },{"_process":49,"debug":8,"object-assign":39}],202:[function(_dereq_,module,exports){
  60953. (function (process){
  60954. var error = _dereq_('debug')('device:error');
  60955. var vrDisplay;
  60956. var supportsVRSession = false;
  60957. var supportsARSession = false;
  60958. /**
  60959. * Oculus Browser 7 doesn't support the WebXR gamepads module.
  60960. * We fallback to WebVR API and will hotfix when implementation is complete.
  60961. */
  60962. var isWebXRAvailable = module.exports.isWebXRAvailable = !window.debug && navigator.xr !== undefined;
  60963. // Catch vrdisplayactivate early to ensure we can enter VR mode after the scene loads.
  60964. window.addEventListener('vrdisplayactivate', function (evt) {
  60965. var canvasEl;
  60966. // WebXR takes priority if available.
  60967. if (isWebXRAvailable) { return; }
  60968. canvasEl = document.createElement('canvas');
  60969. vrDisplay = evt.display;
  60970. // We need to make sure the canvas has a WebGL context associated with it.
  60971. // Otherwise, the requestPresent could be denied.
  60972. canvasEl.getContext('webgl', {});
  60973. // Request present immediately. a-scene will be allowed to enter VR without user gesture.
  60974. vrDisplay.requestPresent([{source: canvasEl}]).then(function () {}, function () {});
  60975. });
  60976. // Support both WebVR and WebXR APIs.
  60977. if (isWebXRAvailable) {
  60978. var updateEnterInterfaces = function () {
  60979. var sceneEl = document.querySelector('a-scene');
  60980. if (!sceneEl) {
  60981. window.addEventListener('DOMContentLoaded', updateEnterInterfaces);
  60982. return;
  60983. }
  60984. if (sceneEl.hasLoaded) {
  60985. sceneEl.components['vr-mode-ui'].updateEnterInterfaces();
  60986. } else {
  60987. sceneEl.addEventListener('loaded', updateEnterInterfaces);
  60988. }
  60989. };
  60990. var errorHandler = function (err) {
  60991. error('WebXR session support error: ' + err.message);
  60992. };
  60993. if (navigator.xr.isSessionSupported) {
  60994. // Current WebXR spec uses a boolean-returning isSessionSupported promise
  60995. navigator.xr.isSessionSupported('immersive-vr').then(function (supported) {
  60996. supportsVRSession = supported;
  60997. updateEnterInterfaces();
  60998. }).catch(errorHandler);
  60999. navigator.xr.isSessionSupported('immersive-ar').then(function (supported) {
  61000. supportsARSession = supported;
  61001. updateEnterInterfaces();
  61002. }).catch(function () {});
  61003. } else if (navigator.xr.supportsSession) {
  61004. // Fallback for implementations that haven't updated to the new spec yet,
  61005. // the old version used supportsSession which is rejected for missing
  61006. // support.
  61007. navigator.xr.supportsSession('immersive-vr').then(function () {
  61008. supportsVRSession = true;
  61009. updateEnterInterfaces();
  61010. }).catch(errorHandler);
  61011. navigator.xr.supportsSession('immersive-ar').then(function () {
  61012. supportsARSession = true;
  61013. updateEnterInterfaces();
  61014. }).catch(function () {});
  61015. } else {
  61016. error('WebXR has neither isSessionSupported or supportsSession?!');
  61017. }
  61018. } else {
  61019. if (navigator.getVRDisplays) {
  61020. navigator.getVRDisplays().then(function (displays) {
  61021. var sceneEl = document.querySelector('a-scene');
  61022. vrDisplay = displays.length && displays[0];
  61023. if (sceneEl) { sceneEl.emit('displayconnected', {vrDisplay: vrDisplay}); }
  61024. });
  61025. }
  61026. }
  61027. function getVRDisplay () { return vrDisplay; }
  61028. module.exports.getVRDisplay = getVRDisplay;
  61029. /**
  61030. * Determine if a headset is connected by checking if a vrDisplay is available.
  61031. */
  61032. function checkHeadsetConnected () {
  61033. return supportsVRSession || supportsARSession || !!getVRDisplay();
  61034. }
  61035. module.exports.checkHeadsetConnected = checkHeadsetConnected;
  61036. function checkARSupport () { return supportsARSession; }
  61037. module.exports.checkARSupport = checkARSupport;
  61038. /**
  61039. * Checks if browser is mobile and not stand-alone dedicated vr device.
  61040. * @return {Boolean} True if mobile browser detected.
  61041. */
  61042. var isMobile = (function () {
  61043. var _isMobile = false;
  61044. (function (a) {
  61045. // eslint-disable-next-line no-useless-escape
  61046. if (/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(a) || /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(a.substr(0, 4))) {
  61047. _isMobile = true;
  61048. }
  61049. if (isIOS() || isTablet() || isR7()) {
  61050. _isMobile = true;
  61051. }
  61052. if (isMobileVR()) {
  61053. _isMobile = false;
  61054. }
  61055. })(window.navigator.userAgent || window.navigator.vendor || window.opera);
  61056. return function () { return _isMobile; };
  61057. })();
  61058. module.exports.isMobile = isMobile;
  61059. /**
  61060. * Detect tablet devices.
  61061. * @param {string} mockUserAgent - Allow passing a mock user agent for testing.
  61062. */
  61063. function isTablet (mockUserAgent) {
  61064. var userAgent = mockUserAgent || window.navigator.userAgent;
  61065. return /ipad|Nexus (7|9)|xoom|sch-i800|playbook|tablet|kindle/i.test(userAgent);
  61066. }
  61067. module.exports.isTablet = isTablet;
  61068. function isIOS () {
  61069. return /iPad|iPhone|iPod/.test(window.navigator.platform);
  61070. }
  61071. module.exports.isIOS = isIOS;
  61072. function isMobileDeviceRequestingDesktopSite () {
  61073. return !isMobile() && !isMobileVR() && window.orientation !== undefined;
  61074. }
  61075. module.exports.isMobileDeviceRequestingDesktopSite = isMobileDeviceRequestingDesktopSite;
  61076. /**
  61077. * Detect Oculus Browser (standalone headset)
  61078. */
  61079. function isOculusBrowser () {
  61080. return /(OculusBrowser)/i.test(window.navigator.userAgent);
  61081. }
  61082. module.exports.isOculusBrowser = isOculusBrowser;
  61083. /**
  61084. * Detect Firefox Reality (standalone headset)
  61085. */
  61086. function isFirefoxReality () {
  61087. return /(Mobile VR)/i.test(window.navigator.userAgent);
  61088. }
  61089. module.exports.isFirefoxReality = isFirefoxReality;
  61090. /**
  61091. * Detect browsers in Stand-Alone headsets
  61092. */
  61093. function isMobileVR () {
  61094. return isOculusBrowser() || isFirefoxReality();
  61095. }
  61096. module.exports.isMobileVR = isMobileVR;
  61097. function isR7 () {
  61098. return /R7 Build/.test(window.navigator.userAgent);
  61099. }
  61100. module.exports.isR7 = isR7;
  61101. /**
  61102. * Checks mobile device orientation.
  61103. * @return {Boolean} True if landscape orientation.
  61104. */
  61105. module.exports.isLandscape = function () {
  61106. var orientation = window.orientation;
  61107. if (isR7()) { orientation += 90; }
  61108. return orientation === 90 || orientation === -90;
  61109. };
  61110. /**
  61111. * Check if running in a browser or spoofed browser (bundler).
  61112. * We need to check a node api that isn't mocked on either side.
  61113. * `require` and `module.exports` are mocked in browser by bundlers.
  61114. * `window` is mocked in node.
  61115. * `process` is also mocked by browserify, but has custom properties.
  61116. */
  61117. module.exports.isBrowserEnvironment = !!(!process || process.browser);
  61118. /**
  61119. * Check if running in node on the server.
  61120. */
  61121. module.exports.isNodeEnvironment = !module.exports.isBrowserEnvironment;
  61122. }).call(this,_dereq_('_process'))
  61123. },{"_process":49,"debug":8}],203:[function(_dereq_,module,exports){
  61124. /**
  61125. * Split a delimited component property string (e.g., `material.color`) to an object
  61126. * containing `component` name and `property` name. If there is no delimiter, just return the
  61127. * string back.
  61128. *
  61129. * Cache arrays from splitting strings via delimiter to save on memory.
  61130. *
  61131. * @param {string} str - e.g., `material.opacity`.
  61132. * @param {string} delimiter - e.g., `.`.
  61133. * @returns {array} e.g., `['material', 'opacity']`.
  61134. */
  61135. var propertyPathCache = {};
  61136. function getComponentPropertyPath (str, delimiter) {
  61137. delimiter = delimiter || '.';
  61138. if (!propertyPathCache[delimiter]) { propertyPathCache[delimiter] = {}; }
  61139. if (str.indexOf(delimiter) !== -1) {
  61140. propertyPathCache[delimiter][str] = str.split(delimiter);
  61141. } else {
  61142. propertyPathCache[delimiter][str] = str;
  61143. }
  61144. return propertyPathCache[delimiter][str];
  61145. }
  61146. module.exports.getComponentPropertyPath = getComponentPropertyPath;
  61147. module.exports.propertyPathCache = propertyPathCache;
  61148. /**
  61149. * Get component property using encoded component name + component property name with a
  61150. * delimiter.
  61151. */
  61152. module.exports.getComponentProperty = function (el, name, delimiter) {
  61153. var splitName;
  61154. delimiter = delimiter || '.';
  61155. if (name.indexOf(delimiter) !== -1) {
  61156. splitName = getComponentPropertyPath(name, delimiter);
  61157. if (splitName.constructor === String) {
  61158. return el.getAttribute(splitName);
  61159. }
  61160. return el.getAttribute(splitName[0])[splitName[1]];
  61161. }
  61162. return el.getAttribute(name);
  61163. };
  61164. /**
  61165. * Set component property using encoded component name + component property name with a
  61166. * delimiter.
  61167. */
  61168. module.exports.setComponentProperty = function (el, name, value, delimiter) {
  61169. var splitName;
  61170. delimiter = delimiter || '.';
  61171. if (name.indexOf(delimiter) !== -1) {
  61172. splitName = getComponentPropertyPath(name, delimiter);
  61173. if (splitName.constructor === String) {
  61174. el.setAttribute(splitName, value);
  61175. } else {
  61176. el.setAttribute(splitName[0], splitName[1], value);
  61177. }
  61178. return;
  61179. }
  61180. el.setAttribute(name, value);
  61181. };
  61182. },{}],204:[function(_dereq_,module,exports){
  61183. module.exports = function forceCanvasResizeSafariMobile (canvasEl) {
  61184. var width = canvasEl.style.width;
  61185. var height = canvasEl.style.height;
  61186. // Taken from webvr-polyfill (https://github.com/borismus/webvr-polyfill/blob/85f657cd502ec9417bf26b87c3cb2afa6a70e079/src/util.js#L200)
  61187. // iOS only workaround for https://bugs.webkit.org/show_bug.cgi?id=152556
  61188. // By changing the size 1 pixel and restoring the previous value
  61189. // we trigger a size recalculation cycle.
  61190. canvasEl.style.width = (parseInt(width, 10) + 1) + 'px';
  61191. canvasEl.style.height = (parseInt(height, 10) + 1) + 'px';
  61192. setTimeout(function () {
  61193. canvasEl.style.width = width;
  61194. canvasEl.style.height = height;
  61195. }, 200);
  61196. };
  61197. },{}],205:[function(_dereq_,module,exports){
  61198. /* global location */
  61199. /* Centralized place to reference utilities since utils is exposed to the user. */
  61200. var debug = _dereq_('./debug');
  61201. var deepAssign = _dereq_('deep-assign');
  61202. var device = _dereq_('./device');
  61203. var objectAssign = _dereq_('object-assign');
  61204. var objectPool = _dereq_('./object-pool');
  61205. var warn = debug('utils:warn');
  61206. module.exports.bind = _dereq_('./bind');
  61207. module.exports.coordinates = _dereq_('./coordinates');
  61208. module.exports.debug = debug;
  61209. module.exports.device = device;
  61210. module.exports.entity = _dereq_('./entity');
  61211. module.exports.forceCanvasResizeSafariMobile = _dereq_('./forceCanvasResizeSafariMobile');
  61212. module.exports.isIE11 = _dereq_('./is-ie11');
  61213. module.exports.material = _dereq_('./material');
  61214. module.exports.objectPool = objectPool;
  61215. module.exports.split = _dereq_('./split').split;
  61216. module.exports.styleParser = _dereq_('./styleParser');
  61217. module.exports.trackedControls = _dereq_('./tracked-controls');
  61218. module.exports.checkHeadsetConnected = function () {
  61219. warn('`utils.checkHeadsetConnected` has moved to `utils.device.checkHeadsetConnected`');
  61220. return device.checkHeadsetConnected(arguments);
  61221. };
  61222. module.exports.isGearVR = module.exports.device.isGearVR = function () {
  61223. warn('`utils.isGearVR` has been deprecated, use `utils.device.isMobileVR`');
  61224. };
  61225. module.exports.isIOS = function () {
  61226. warn('`utils.isIOS` has moved to `utils.device.isIOS`');
  61227. return device.isIOS(arguments);
  61228. };
  61229. module.exports.isOculusGo = module.exports.device.isOculusGo = function () {
  61230. warn('`utils.isOculusGo` has been deprecated, use `utils.device.isMobileVR`');
  61231. };
  61232. module.exports.isMobile = function () {
  61233. warn('`utils.isMobile has moved to `utils.device.isMobile`');
  61234. return device.isMobile(arguments);
  61235. };
  61236. /**
  61237. * Returns throttle function that gets called at most once every interval.
  61238. *
  61239. * @param {function} functionToThrottle
  61240. * @param {number} minimumInterval - Minimal interval between calls (milliseconds).
  61241. * @param {object} optionalContext - If given, bind function to throttle to this context.
  61242. * @returns {function} Throttled function.
  61243. */
  61244. module.exports.throttle = function (functionToThrottle, minimumInterval, optionalContext) {
  61245. var lastTime;
  61246. if (optionalContext) {
  61247. functionToThrottle = module.exports.bind(functionToThrottle, optionalContext);
  61248. }
  61249. return function () {
  61250. var time = Date.now();
  61251. var sinceLastTime = typeof lastTime === 'undefined' ? minimumInterval : time - lastTime;
  61252. if (typeof lastTime === 'undefined' || (sinceLastTime >= minimumInterval)) {
  61253. lastTime = time;
  61254. functionToThrottle.apply(null, arguments);
  61255. }
  61256. };
  61257. };
  61258. /**
  61259. * Returns throttle function that gets called at most once every interval.
  61260. * Uses the time/timeDelta timestamps provided by the global render loop for better perf.
  61261. *
  61262. * @param {function} functionToThrottle
  61263. * @param {number} minimumInterval - Minimal interval between calls (milliseconds).
  61264. * @param {object} optionalContext - If given, bind function to throttle to this context.
  61265. * @returns {function} Throttled function.
  61266. */
  61267. module.exports.throttleTick = function (functionToThrottle, minimumInterval, optionalContext) {
  61268. var lastTime;
  61269. if (optionalContext) {
  61270. functionToThrottle = module.exports.bind(functionToThrottle, optionalContext);
  61271. }
  61272. return function (time, delta) {
  61273. var sinceLastTime = typeof lastTime === 'undefined' ? delta : time - lastTime;
  61274. if (typeof lastTime === 'undefined' || (sinceLastTime >= minimumInterval)) {
  61275. lastTime = time;
  61276. functionToThrottle(time, sinceLastTime);
  61277. }
  61278. };
  61279. };
  61280. /**
  61281. * Returns debounce function that gets called only once after a set of repeated calls.
  61282. *
  61283. * @param {function} functionToDebounce
  61284. * @param {number} wait - Time to wait for repeated function calls (milliseconds).
  61285. * @param {boolean} immediate - Calls the function immediately regardless of if it should be waiting.
  61286. * @returns {function} Debounced function.
  61287. */
  61288. module.exports.debounce = function (func, wait, immediate) {
  61289. var timeout;
  61290. return function () {
  61291. var context = this;
  61292. var args = arguments;
  61293. var later = function () {
  61294. timeout = null;
  61295. if (!immediate) func.apply(context, args);
  61296. };
  61297. var callNow = immediate && !timeout;
  61298. clearTimeout(timeout);
  61299. timeout = setTimeout(later, wait);
  61300. if (callNow) func.apply(context, args);
  61301. };
  61302. };
  61303. /**
  61304. * Mix the properties of source object(s) into a destination object.
  61305. *
  61306. * @param {object} dest - The object to which properties will be copied.
  61307. * @param {...object} source - The object(s) from which properties will be copied.
  61308. */
  61309. module.exports.extend = objectAssign;
  61310. module.exports.extendDeep = deepAssign;
  61311. module.exports.clone = function (obj) {
  61312. return JSON.parse(JSON.stringify(obj));
  61313. };
  61314. /**
  61315. * Checks if two values are equal.
  61316. * Includes objects and arrays and nested objects and arrays.
  61317. * Try to keep this function performant as it will be called often to see if a component
  61318. * should be updated.
  61319. *
  61320. * @param {object} a - First object.
  61321. * @param {object} b - Second object.
  61322. * @returns {boolean} Whether two objects are deeply equal.
  61323. */
  61324. var deepEqual = (function () {
  61325. var arrayPool = objectPool.createPool(function () { return []; });
  61326. return function (a, b) {
  61327. var key;
  61328. var keysA;
  61329. var keysB;
  61330. var i;
  61331. var valA;
  61332. var valB;
  61333. // If not objects or arrays, compare as values.
  61334. if (a === undefined || b === undefined || a === null || b === null ||
  61335. !(a && b && (a.constructor === Object && b.constructor === Object) ||
  61336. (a.constructor === Array && b.constructor === Array))) {
  61337. return a === b;
  61338. }
  61339. // Different number of keys, not equal.
  61340. keysA = arrayPool.use();
  61341. keysB = arrayPool.use();
  61342. keysA.length = 0;
  61343. keysB.length = 0;
  61344. for (key in a) { keysA.push(key); }
  61345. for (key in b) { keysB.push(key); }
  61346. if (keysA.length !== keysB.length) {
  61347. arrayPool.recycle(keysA);
  61348. arrayPool.recycle(keysB);
  61349. return false;
  61350. }
  61351. // Return `false` at the first sign of inequality.
  61352. for (i = 0; i < keysA.length; ++i) {
  61353. valA = a[keysA[i]];
  61354. valB = b[keysA[i]];
  61355. // Check nested array and object.
  61356. if ((typeof valA === 'object' || typeof valB === 'object') ||
  61357. (Array.isArray(valA) && Array.isArray(valB))) {
  61358. if (valA === valB) { continue; }
  61359. if (!deepEqual(valA, valB)) {
  61360. arrayPool.recycle(keysA);
  61361. arrayPool.recycle(keysB);
  61362. return false;
  61363. }
  61364. } else if (valA !== valB) {
  61365. arrayPool.recycle(keysA);
  61366. arrayPool.recycle(keysB);
  61367. return false;
  61368. }
  61369. }
  61370. arrayPool.recycle(keysA);
  61371. arrayPool.recycle(keysB);
  61372. return true;
  61373. };
  61374. })();
  61375. module.exports.deepEqual = deepEqual;
  61376. /**
  61377. * Computes the difference between two objects.
  61378. *
  61379. * @param {object} a - First object to compare (e.g., oldData).
  61380. * @param {object} b - Second object to compare (e.g., newData).
  61381. * @returns {object}
  61382. * Difference object where set of keys note which values were not equal, and values are
  61383. * `b`'s values.
  61384. */
  61385. module.exports.diff = (function () {
  61386. var keys = [];
  61387. return function (a, b, targetObject) {
  61388. var aVal;
  61389. var bVal;
  61390. var bKey;
  61391. var diff;
  61392. var key;
  61393. var i;
  61394. var isComparingObjects;
  61395. diff = targetObject || {};
  61396. // Collect A keys.
  61397. keys.length = 0;
  61398. for (key in a) { keys.push(key); }
  61399. if (!b) { return diff; }
  61400. // Collect B keys.
  61401. for (bKey in b) {
  61402. if (keys.indexOf(bKey) === -1) {
  61403. keys.push(bKey);
  61404. }
  61405. }
  61406. for (i = 0; i < keys.length; i++) {
  61407. key = keys[i];
  61408. aVal = a[key];
  61409. bVal = b[key];
  61410. isComparingObjects = aVal && bVal &&
  61411. aVal.constructor === Object && bVal.constructor === Object;
  61412. if ((isComparingObjects && !deepEqual(aVal, bVal)) ||
  61413. (!isComparingObjects && aVal !== bVal)) {
  61414. diff[key] = bVal;
  61415. }
  61416. }
  61417. return diff;
  61418. };
  61419. })();
  61420. /**
  61421. * Returns whether we should capture this keyboard event for keyboard shortcuts.
  61422. * @param {Event} event Event object.
  61423. * @returns {Boolean} Whether the key event should be captured.
  61424. */
  61425. module.exports.shouldCaptureKeyEvent = function (event) {
  61426. if (event.metaKey) { return false; }
  61427. return document.activeElement === document.body;
  61428. };
  61429. /**
  61430. * Splits a string into an array based on a delimiter.
  61431. *
  61432. * @param {string=} [str=''] Source string
  61433. * @param {string=} [delimiter=' '] Delimiter to use
  61434. * @returns {array} Array of delimited strings
  61435. */
  61436. module.exports.splitString = function (str, delimiter) {
  61437. if (typeof delimiter === 'undefined') { delimiter = ' '; }
  61438. // First collapse the whitespace (or whatever the delimiter is).
  61439. var regex = new RegExp(delimiter, 'g');
  61440. str = (str || '').replace(regex, delimiter);
  61441. // Then split.
  61442. return str.split(delimiter);
  61443. };
  61444. /**
  61445. * Extracts data from the element given an object that contains expected keys.
  61446. *
  61447. * @param {Element} Source element.
  61448. * @param {Object} [defaults={}] Object of default key-value pairs.
  61449. * @returns {Object}
  61450. */
  61451. module.exports.getElData = function (el, defaults) {
  61452. defaults = defaults || {};
  61453. var data = {};
  61454. Object.keys(defaults).forEach(copyAttribute);
  61455. function copyAttribute (key) {
  61456. if (el.hasAttribute(key)) {
  61457. data[key] = el.getAttribute(key);
  61458. }
  61459. }
  61460. return data;
  61461. };
  61462. /**
  61463. * Retrieves querystring value.
  61464. * @param {String} name Name of querystring key.
  61465. * @return {String} Value
  61466. */
  61467. module.exports.getUrlParameter = function (name) {
  61468. // eslint-disable-next-line no-useless-escape
  61469. name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
  61470. var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
  61471. var results = regex.exec(location.search);
  61472. return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
  61473. };
  61474. /**
  61475. * Detects whether context is within iframe.
  61476. */
  61477. module.exports.isIframed = function () {
  61478. return window.top !== window.self;
  61479. };
  61480. /**
  61481. * Finds all elements under the element that have the isScene
  61482. * property set to true
  61483. */
  61484. module.exports.findAllScenes = function (el) {
  61485. var matchingElements = [];
  61486. var allElements = el.getElementsByTagName('*');
  61487. for (var i = 0, n = allElements.length; i < n; i++) {
  61488. if (allElements[i].isScene) {
  61489. // Element exists with isScene set.
  61490. matchingElements.push(allElements[i]);
  61491. }
  61492. }
  61493. return matchingElements;
  61494. };
  61495. // Must be at bottom to avoid circular dependency.
  61496. module.exports.srcLoader = _dereq_('./src-loader');
  61497. },{"./bind":199,"./coordinates":200,"./debug":201,"./device":202,"./entity":203,"./forceCanvasResizeSafariMobile":204,"./is-ie11":207,"./material":209,"./object-pool":210,"./split":211,"./src-loader":212,"./styleParser":213,"./tracked-controls":214,"deep-assign":10,"object-assign":39}],206:[function(_dereq_,module,exports){
  61498. // Safari regression introduced in iOS 12 and remains in iOS 13.
  61499. // https://stackoverflow.com/questions/62717621/white-space-at-page-bottom-after-device-rotation-in-ios-safari
  61500. window.addEventListener('orientationchange', function () {
  61501. document.documentElement.style.height = `initial`;
  61502. setTimeout(function () {
  61503. document.documentElement.style.height = `100%`;
  61504. setTimeout(function () {
  61505. // this line prevents the content
  61506. // from hiding behind the address bar
  61507. window.scrollTo(0, 1);
  61508. }, 500);
  61509. }, 500);
  61510. });
  61511. },{}],207:[function(_dereq_,module,exports){
  61512. // https://stackoverflow.com/a/17907562
  61513. function getInternetExplorerVersion () {
  61514. var version = -1;
  61515. var userAgent = navigator.userAgent;
  61516. var re;
  61517. if (navigator.appName === 'Microsoft Internet Explorer') {
  61518. re = new RegExp('MSIE ([0-9]{1,}[\\.0-9]{0,})');
  61519. if (re.exec(userAgent) != null) { version = parseFloat(RegExp.$1); }
  61520. } else if (navigator.appName === 'Netscape') {
  61521. re = new RegExp('Trident/.*rv:([0-9]{1,}[\\.0-9]{0,})');
  61522. if (re.exec(userAgent) != null) { version = parseFloat(RegExp.$1); }
  61523. }
  61524. return version;
  61525. }
  61526. module.exports = getInternetExplorerVersion() === 11;
  61527. },{}],208:[function(_dereq_,module,exports){
  61528. /**
  61529. * Check if device is iOS and older than version 10.
  61530. */
  61531. module.exports = function isIOSOlderThan10 (userAgent) {
  61532. return /(iphone|ipod|ipad).*os.(7_|8_|9_)/i.test(userAgent);
  61533. };
  61534. },{}],209:[function(_dereq_,module,exports){
  61535. var THREE = _dereq_('../lib/three');
  61536. var HLS_MIMETYPES = ['application/x-mpegurl', 'application/vnd.apple.mpegurl'];
  61537. var COLOR_MAPS = new Set([
  61538. 'emissiveMap',
  61539. 'envMap',
  61540. 'map',
  61541. 'specularMap'
  61542. ]);
  61543. /**
  61544. * Update `material` texture property (usually but not always `map`)
  61545. * from `data` property (usually but not always `src`)
  61546. *
  61547. * @param {object} shader - A-Frame shader instance.
  61548. * @param {object} data
  61549. */
  61550. module.exports.updateMapMaterialFromData = function (materialName, dataName, shader, data) {
  61551. var el = shader.el;
  61552. var material = shader.material;
  61553. var rendererSystem = el.sceneEl.systems.renderer;
  61554. var src = data[dataName];
  61555. // Because a single material / shader may have multiple textures,
  61556. // we need to remember the source value for this data property
  61557. // to avoid redundant operations which can be expensive otherwise
  61558. // (e.g. video texture loads).
  61559. if (!shader.materialSrcs) { shader.materialSrcs = {}; }
  61560. if (!src) {
  61561. // Forget the prior material src.
  61562. delete shader.materialSrcs[materialName];
  61563. // Remove the texture.
  61564. setMap(null);
  61565. return;
  61566. }
  61567. // Don't process if material src hasn't changed.
  61568. if (src === shader.materialSrcs[materialName]) { return; }
  61569. // Remember the new src for this texture (there may be multiple).
  61570. shader.materialSrcs[materialName] = src;
  61571. // If the new material src is already a texture, just use it.
  61572. if (src instanceof THREE.Texture) { setMap(src); } else {
  61573. // Load texture for the new material src.
  61574. // (And check if we should still use it once available in callback.)
  61575. el.sceneEl.systems.material.loadTexture(src,
  61576. {src: src, repeat: data.repeat, offset: data.offset, npot: data.npot},
  61577. checkSetMap);
  61578. }
  61579. function checkSetMap (texture) {
  61580. // If the source has been changed, don't use loaded texture.
  61581. if (shader.materialSrcs[materialName] !== src) { return; }
  61582. setMap(texture);
  61583. }
  61584. function setMap (texture) {
  61585. material[materialName] = texture;
  61586. if (texture && COLOR_MAPS.has(materialName)) {
  61587. rendererSystem.applyColorCorrection(texture);
  61588. }
  61589. material.needsUpdate = true;
  61590. handleTextureEvents(el, texture);
  61591. }
  61592. };
  61593. /**
  61594. * Update `material.map` given `data.src`. For standard and flat shaders.
  61595. *
  61596. * @param {object} shader - A-Frame shader instance.
  61597. * @param {object} data
  61598. */
  61599. module.exports.updateMap = function (shader, data) {
  61600. return module.exports.updateMapMaterialFromData('map', 'src', shader, data);
  61601. };
  61602. /**
  61603. * Updates the material's maps which give the illusion of extra geometry.
  61604. *
  61605. * @param {string} longType - The friendly name of the map from the component e.g. ambientOcclusionMap becomes aoMap in THREE.js
  61606. * @param {object} shader - A-Frame shader instance
  61607. * @param {object} data
  61608. */
  61609. module.exports.updateDistortionMap = function (longType, shader, data) {
  61610. var shortType = longType;
  61611. if (longType === 'ambientOcclusion') { shortType = 'ao'; }
  61612. var el = shader.el;
  61613. var material = shader.material;
  61614. var rendererSystem = el.sceneEl.systems.renderer;
  61615. var src = data[longType + 'Map'];
  61616. var info = {};
  61617. info.src = src;
  61618. // Pass through the repeat and offset to be handled by the material loader.
  61619. info.offset = data[longType + 'TextureOffset'];
  61620. info.repeat = data[longType + 'TextureRepeat'];
  61621. info.wrap = data[longType + 'TextureWrap'];
  61622. if (src) {
  61623. if (src === shader[longType + 'TextureSrc']) { return; }
  61624. // Texture added or changed.
  61625. shader[longType + 'TextureSrc'] = src;
  61626. el.sceneEl.systems.material.loadTexture(src, info, setMap);
  61627. return;
  61628. }
  61629. // Texture removed.
  61630. if (!material.map) { return; }
  61631. setMap(null);
  61632. function setMap (texture) {
  61633. var slot = shortType + 'Map';
  61634. material[slot] = texture;
  61635. if (texture && COLOR_MAPS.has(slot)) {
  61636. rendererSystem.applyColorCorrection(texture);
  61637. }
  61638. material.needsUpdate = true;
  61639. handleTextureEvents(el, texture);
  61640. }
  61641. };
  61642. /**
  61643. * Emit event on entities on texture-related events.
  61644. *
  61645. * @param {Element} el - Entity.
  61646. * @param {object} texture - three.js Texture.
  61647. */
  61648. function handleTextureEvents (el, texture) {
  61649. if (!texture) { return; }
  61650. el.emit('materialtextureloaded', {src: texture.image, texture: texture});
  61651. // Video events.
  61652. if (!texture.image || texture.image.tagName !== 'VIDEO') { return; }
  61653. texture.image.addEventListener('loadeddata', function emitVideoTextureLoadedDataAll () {
  61654. // Check to see if we need to use iOS 10 HLS shader.
  61655. // Only override the shader if it is stock shader that we know doesn't correct.
  61656. if (!el.components || !el.components.material) { return; }
  61657. if (texture.needsCorrectionBGRA && texture.needsCorrectionFlipY &&
  61658. ['standard', 'flat'].indexOf(el.components.material.data.shader) !== -1) {
  61659. el.setAttribute('material', 'shader', 'ios10hls');
  61660. }
  61661. el.emit('materialvideoloadeddata', {src: texture.image, texture: texture});
  61662. });
  61663. texture.image.addEventListener('ended', function emitVideoTextureEndedAll () {
  61664. // Works for non-looping videos only.
  61665. el.emit('materialvideoended', {src: texture.image, texture: texture});
  61666. });
  61667. }
  61668. module.exports.handleTextureEvents = handleTextureEvents;
  61669. /**
  61670. * Given video element src and type, guess whether stream is HLS.
  61671. *
  61672. * @param {string} src - src from video element (generally URL to content).
  61673. * @param {string} type - type from video element (generally MIME type if present).
  61674. */
  61675. module.exports.isHLS = function (src, type) {
  61676. if (type && HLS_MIMETYPES.includes(type.toLowerCase())) { return true; }
  61677. if (src && src.toLowerCase().indexOf('.m3u8') > 0) { return true; }
  61678. return false;
  61679. };
  61680. },{"../lib/three":179}],210:[function(_dereq_,module,exports){
  61681. /*
  61682. Adapted deePool by Kyle Simpson.
  61683. MIT License: http://getify.mit-license.org
  61684. */
  61685. var EMPTY_SLOT = Object.freeze(Object.create(null));
  61686. // Default object factory.
  61687. function defaultObjectFactory () { return {}; }
  61688. /**
  61689. * Create a new pool.
  61690. */
  61691. module.exports.createPool = function createPool (objectFactory) {
  61692. var objPool = [];
  61693. var nextFreeSlot = null; // Pool location to look for a free object to use.
  61694. objectFactory = objectFactory || defaultObjectFactory;
  61695. function use () {
  61696. var objToUse;
  61697. if (nextFreeSlot === null || nextFreeSlot === objPool.length) {
  61698. grow(objPool.length || 5);
  61699. }
  61700. objToUse = objPool[nextFreeSlot];
  61701. objPool[nextFreeSlot++] = EMPTY_SLOT;
  61702. clearObject(objToUse);
  61703. return objToUse;
  61704. }
  61705. function recycle (obj) {
  61706. if (!(obj instanceof Object)) { return; }
  61707. if (nextFreeSlot === null || nextFreeSlot === -1) {
  61708. objPool[objPool.length] = obj;
  61709. return;
  61710. }
  61711. objPool[--nextFreeSlot] = obj;
  61712. }
  61713. function grow (count) {
  61714. var currentLength;
  61715. var i;
  61716. count = count === undefined ? objPool.length : count;
  61717. if (count > 0 && nextFreeSlot == null) {
  61718. nextFreeSlot = 0;
  61719. }
  61720. if (count > 0) {
  61721. currentLength = objPool.length;
  61722. objPool.length += Number(count);
  61723. for (i = currentLength; i < objPool.length; i++) {
  61724. // Add new obj to pool.
  61725. objPool[i] = objectFactory();
  61726. }
  61727. }
  61728. return objPool.length;
  61729. }
  61730. function size () {
  61731. return objPool.length;
  61732. }
  61733. return {
  61734. grow: grow,
  61735. pool: objPool,
  61736. recycle: recycle,
  61737. size: size,
  61738. use: use
  61739. };
  61740. };
  61741. function clearObject (obj) {
  61742. var key;
  61743. if (!obj || obj.constructor !== Object) { return; }
  61744. for (key in obj) { obj[key] = undefined; }
  61745. }
  61746. module.exports.clearObject = clearObject;
  61747. function removeUnusedKeys (obj, schema) {
  61748. var key;
  61749. if (!obj || obj.constructor !== Object) { return; }
  61750. for (key in obj) {
  61751. if (!(key in schema)) {
  61752. delete obj[key];
  61753. }
  61754. }
  61755. }
  61756. module.exports.removeUnusedKeys = removeUnusedKeys;
  61757. },{}],211:[function(_dereq_,module,exports){
  61758. /**
  61759. * String split with cached result.
  61760. */
  61761. module.exports.split = (function () {
  61762. var splitCache = {};
  61763. return function (str, delimiter) {
  61764. if (!(delimiter in splitCache)) { splitCache[delimiter] = {}; }
  61765. if (str in splitCache[delimiter]) { return splitCache[delimiter][str]; }
  61766. splitCache[delimiter][str] = str.split(delimiter);
  61767. return splitCache[delimiter][str];
  61768. };
  61769. })();
  61770. },{}],212:[function(_dereq_,module,exports){
  61771. /* global Image, XMLHttpRequest */
  61772. var debug = _dereq_('./debug');
  61773. var warn = debug('utils:src-loader:warn');
  61774. /**
  61775. * Validate a texture, either as a selector or as a URL.
  61776. * Detects whether `src` is pointing to an image or video and invokes the appropriate
  61777. * callback.
  61778. *
  61779. * `src` will be passed into the callback
  61780. *
  61781. * @params {string|Element} src - URL or media element.
  61782. * @params {function} isImageCb - callback if texture is an image.
  61783. * @params {function} isVideoCb - callback if texture is a video.
  61784. */
  61785. function validateSrc (src, isImageCb, isVideoCb) {
  61786. checkIsImage(src, function isAnImageUrl (isImage) {
  61787. if (isImage) {
  61788. isImageCb(src);
  61789. return;
  61790. }
  61791. isVideoCb(src);
  61792. });
  61793. }
  61794. /**
  61795. * Validates six images as a cubemap, either as selector or comma-separated
  61796. * URLs.
  61797. *
  61798. * @param {string} src - A selector or comma-separated image URLs. Image URLs
  61799. must be wrapped by `url()`.
  61800. * @param {string} src - A selector or comma-separated image URLs. Image URLs
  61801. must be wrapped by `url()`.
  61802. */
  61803. function validateCubemapSrc (src, cb) {
  61804. var aCubemap;
  61805. var cubemapSrcRegex = '';
  61806. var i;
  61807. var urls;
  61808. var validatedUrls = [];
  61809. for (i = 0; i < 5; i++) {
  61810. cubemapSrcRegex += '(url\\((?:[^\\)]+)\\),\\s*)';
  61811. }
  61812. cubemapSrcRegex += '(url\\((?:[^\\)]+)\\)\\s*)';
  61813. urls = src.match(new RegExp(cubemapSrcRegex));
  61814. // `src` is a comma-separated list of URLs.
  61815. // In this case, re-use validateSrc for each side of the cube.
  61816. function isImageCb (url) {
  61817. validatedUrls.push(url);
  61818. if (validatedUrls.length === 6) {
  61819. cb(validatedUrls);
  61820. }
  61821. }
  61822. if (urls) {
  61823. for (i = 1; i < 7; i++) {
  61824. validateSrc(parseUrl(urls[i]), isImageCb);
  61825. }
  61826. return;
  61827. }
  61828. // `src` is a query selector to <a-cubemap> containing six $([src])s.
  61829. aCubemap = validateAndGetQuerySelector(src);
  61830. if (!aCubemap) { return; }
  61831. if (aCubemap.tagName === 'A-CUBEMAP' && aCubemap.srcs) {
  61832. return cb(aCubemap.srcs);
  61833. }
  61834. // Else if aCubeMap is not a <a-cubemap>.
  61835. warn('Selector "%s" does not point to <a-cubemap>', src);
  61836. }
  61837. /**
  61838. * Parses src from `url(src)`.
  61839. * @param {string} src - String to parse.
  61840. * @return {string} The parsed src, if parseable.
  61841. */
  61842. function parseUrl (src) {
  61843. var parsedSrc = src.match(/\url\((.+)\)/);
  61844. if (!parsedSrc) { return; }
  61845. return parsedSrc[1];
  61846. }
  61847. /**
  61848. * Call back whether `src` is an image.
  61849. *
  61850. * @param {string|Element} src - URL or element that will be tested.
  61851. * @param {function} onResult - Callback with whether `src` is an image.
  61852. */
  61853. function checkIsImage (src, onResult) {
  61854. var request;
  61855. if (src.tagName) {
  61856. onResult(src.tagName === 'IMG');
  61857. return;
  61858. }
  61859. request = new XMLHttpRequest();
  61860. // Try to send HEAD request to check if image first.
  61861. request.open('HEAD', src);
  61862. request.addEventListener('load', function (event) {
  61863. var contentType;
  61864. if (request.status >= 200 && request.status < 300) {
  61865. contentType = request.getResponseHeader('Content-Type');
  61866. if (contentType == null) {
  61867. checkIsImageFallback(src, onResult);
  61868. } else {
  61869. if (contentType.startsWith('image')) {
  61870. onResult(true);
  61871. } else {
  61872. onResult(false);
  61873. }
  61874. }
  61875. } else {
  61876. checkIsImageFallback(src, onResult);
  61877. }
  61878. request.abort();
  61879. });
  61880. request.send();
  61881. }
  61882. function checkIsImageFallback (src, onResult) {
  61883. var tester = new Image();
  61884. tester.addEventListener('load', onLoad);
  61885. function onLoad () { onResult(true); }
  61886. tester.addEventListener('error', onError);
  61887. function onError () { onResult(false); }
  61888. tester.src = src;
  61889. }
  61890. /**
  61891. * Query and validate a query selector,
  61892. *
  61893. * @param {string} selector - DOM selector.
  61894. * @return {object|null|undefined} Selected DOM element if exists.
  61895. null if query yields no results.
  61896. undefined if `selector` is not a valid selector.
  61897. */
  61898. function validateAndGetQuerySelector (selector) {
  61899. try {
  61900. var el = document.querySelector(selector);
  61901. if (!el) {
  61902. warn('No element was found matching the selector: "%s"', selector);
  61903. }
  61904. return el;
  61905. } catch (e) { // Capture exception if it's not a valid selector.
  61906. warn('"%s" is not a valid selector', selector);
  61907. return undefined;
  61908. }
  61909. }
  61910. module.exports = {
  61911. parseUrl: parseUrl,
  61912. validateSrc: validateSrc,
  61913. validateCubemapSrc: validateCubemapSrc
  61914. };
  61915. },{"./debug":201}],213:[function(_dereq_,module,exports){
  61916. /**
  61917. * Utils for parsing style-like strings (e.g., "primitive: box; width: 5; height: 4.5").
  61918. * Some code adapted from `style-attr` (https://github.com/joshwnj/style-attr)
  61919. * by Josh Johnston (MIT License).
  61920. */
  61921. var DASH_REGEX = /-([a-z])/g;
  61922. /**
  61923. * Deserialize style-like string into an object of properties.
  61924. *
  61925. * @param {string} value - HTML attribute value.
  61926. * @param {object} obj - Reused object for object pooling.
  61927. * @returns {object} Property data.
  61928. */
  61929. module.exports.parse = function (value, obj) {
  61930. var parsedData;
  61931. if (typeof value !== 'string') { return value; }
  61932. parsedData = styleParse(value, obj);
  61933. // The style parser returns an object { "" : "test"} when fed a string
  61934. if (parsedData['']) { return value; }
  61935. return transformKeysToCamelCase(parsedData);
  61936. };
  61937. /**
  61938. * Serialize an object of properties into a style-like string.
  61939. *
  61940. * @param {object} data - Property data.
  61941. * @returns {string}
  61942. */
  61943. module.exports.stringify = function (data) {
  61944. if (typeof data === 'string') { return data; }
  61945. return styleStringify(data);
  61946. };
  61947. /**
  61948. * Converts string from hyphen to camelCase.
  61949. *
  61950. * @param {string} str - String to camelCase.
  61951. * @return {string} CamelCased string.
  61952. */
  61953. function toCamelCase (str) {
  61954. return str.replace(DASH_REGEX, upperCase);
  61955. }
  61956. module.exports.toCamelCase = toCamelCase;
  61957. /**
  61958. * Converts object's keys from hyphens to camelCase (e.g., `max-value` to
  61959. * `maxValue`).
  61960. *
  61961. * @param {object} obj - The object to camelCase keys.
  61962. * @return {object} The object with keys camelCased.
  61963. */
  61964. function transformKeysToCamelCase (obj) {
  61965. var camelKey;
  61966. var key;
  61967. for (key in obj) {
  61968. camelKey = toCamelCase(key);
  61969. if (key === camelKey) { continue; }
  61970. obj[camelKey] = obj[key];
  61971. delete obj[key];
  61972. }
  61973. return obj;
  61974. }
  61975. module.exports.transformKeysToCamelCase = transformKeysToCamelCase;
  61976. /**
  61977. * Split a string into chunks matching `<key>: <value>`
  61978. */
  61979. var getKeyValueChunks = (function () {
  61980. var chunks = [];
  61981. var hasUnclosedUrl = /url\([^)]+$/;
  61982. return function getKeyValueChunks (raw) {
  61983. var chunk = '';
  61984. var nextSplit;
  61985. var offset = 0;
  61986. var sep = ';';
  61987. chunks.length = 0;
  61988. while (offset < raw.length) {
  61989. nextSplit = raw.indexOf(sep, offset);
  61990. if (nextSplit === -1) { nextSplit = raw.length; }
  61991. chunk += raw.substring(offset, nextSplit);
  61992. // data URIs can contain semicolons, so make sure we get the whole thing
  61993. if (hasUnclosedUrl.test(chunk)) {
  61994. chunk += ';';
  61995. offset = nextSplit + 1;
  61996. continue;
  61997. }
  61998. chunks.push(chunk.trim());
  61999. chunk = '';
  62000. offset = nextSplit + 1;
  62001. }
  62002. return chunks;
  62003. };
  62004. })();
  62005. /**
  62006. * Convert a style attribute string to an object.
  62007. *
  62008. * @param {object} str - Attribute string.
  62009. * @param {object} obj - Object to reuse as a base, else a new one will be allocated.
  62010. */
  62011. function styleParse (str, obj) {
  62012. var chunks;
  62013. var i;
  62014. var item;
  62015. var pos;
  62016. var key;
  62017. var val;
  62018. obj = obj || {};
  62019. chunks = getKeyValueChunks(str);
  62020. for (i = 0; i < chunks.length; i++) {
  62021. item = chunks[i];
  62022. if (!item) { continue; }
  62023. // Split with `.indexOf` rather than `.split` because the value may also contain colons.
  62024. pos = item.indexOf(':');
  62025. key = item.substr(0, pos).trim();
  62026. val = item.substr(pos + 1).trim();
  62027. obj[key] = val;
  62028. }
  62029. return obj;
  62030. }
  62031. /**
  62032. * Convert an object into an attribute string
  62033. **/
  62034. function styleStringify (obj) {
  62035. var key;
  62036. var keyCount = 0;
  62037. var i = 0;
  62038. var str = '';
  62039. for (key in obj) { keyCount++; }
  62040. for (key in obj) {
  62041. str += (key + ': ' + obj[key]);
  62042. if (i < keyCount - 1) { str += '; '; }
  62043. i++;
  62044. }
  62045. return str;
  62046. }
  62047. function upperCase (str) { return str[1].toUpperCase(); }
  62048. },{}],214:[function(_dereq_,module,exports){
  62049. var DEFAULT_HANDEDNESS = _dereq_('../constants').DEFAULT_HANDEDNESS;
  62050. var AXIS_LABELS = ['x', 'y', 'z', 'w'];
  62051. var NUM_HANDS = 2; // Number of hands in a pair. Should always be 2.
  62052. /**
  62053. * Called on controller component `.play` handlers.
  62054. * Check if controller matches parameters and inject tracked-controls component.
  62055. * Handle event listeners.
  62056. * Generate controllerconnected or controllerdisconnected events.
  62057. *
  62058. * @param {object} component - Tracked controls component.
  62059. * @param {object} idPrefix - Prefix to match in gamepad id if any.
  62060. * @param {object} queryObject - Map of values to match.
  62061. */
  62062. module.exports.checkControllerPresentAndSetup = function (component, idPrefix, queryObject) {
  62063. var el = component.el;
  62064. var controller;
  62065. var hasWebXR = el.sceneEl.hasWebXR;
  62066. var isControllerPresent = hasWebXR ? isControllerPresentWebXR : isControllerPresentWebVR;
  62067. var isPresent;
  62068. controller = isControllerPresent(component, idPrefix, queryObject);
  62069. isPresent = !!controller;
  62070. // If component was previously paused and now playing, re-add event listeners.
  62071. // Handle the event listeners here since this helper method is control of calling
  62072. // `.addEventListeners` and `.removeEventListeners`.
  62073. if (component.controllerPresent && !component.controllerEventsActive && !hasWebXR) {
  62074. component.addEventListeners();
  62075. }
  62076. // Nothing changed, no need to do anything.
  62077. if (isPresent === component.controllerPresent) { return isPresent; }
  62078. component.controllerPresent = isPresent;
  62079. // Update controller presence.
  62080. if (isPresent) {
  62081. component.addEventListeners();
  62082. component.injectTrackedControls(controller);
  62083. el.emit('controllerconnected', {name: component.name, component: component});
  62084. } else {
  62085. component.removeEventListeners();
  62086. el.emit('controllerdisconnected', {name: component.name, component: component});
  62087. }
  62088. };
  62089. /**
  62090. * Enumerate controller (that have pose) and check if they match parameters for WebVR
  62091. *
  62092. * @param {object} component - Tracked controls component.
  62093. * @param {object} idPrefix - Prefix to match in gamepad id if any.
  62094. * @param {object} queryObject - Map of values to match.
  62095. */
  62096. function isControllerPresentWebVR (component, idPrefix, queryObject) {
  62097. var gamepads;
  62098. var sceneEl = component.el.sceneEl;
  62099. var trackedControlsSystem;
  62100. var filterControllerIndex = queryObject.index || 0;
  62101. if (!idPrefix) { return false; }
  62102. trackedControlsSystem = sceneEl && sceneEl.systems['tracked-controls-webvr'];
  62103. if (!trackedControlsSystem) { return false; }
  62104. gamepads = trackedControlsSystem.controllers;
  62105. if (!gamepads.length) { return false; }
  62106. return !!findMatchingControllerWebVR(gamepads, null, idPrefix, queryObject.hand,
  62107. filterControllerIndex);
  62108. }
  62109. /**
  62110. *
  62111. * @param {object} component - Tracked controls component.
  62112. */
  62113. function isControllerPresentWebXR (component, id, queryObject) {
  62114. var controllers;
  62115. var sceneEl = component.el.sceneEl;
  62116. var trackedControlsSystem = sceneEl && sceneEl.systems['tracked-controls-webxr'];
  62117. if (!trackedControlsSystem) { return false; }
  62118. controllers = trackedControlsSystem.controllers;
  62119. if (!controllers || !controllers.length) { return false; }
  62120. return findMatchingControllerWebXR(
  62121. controllers, id,
  62122. queryObject.hand, queryObject.index, queryObject.iterateControllerProfiles, queryObject.handTracking);
  62123. }
  62124. module.exports.isControllerPresentWebVR = isControllerPresentWebVR;
  62125. module.exports.isControllerPresentWebXR = isControllerPresentWebXR;
  62126. /**
  62127. * Walk through the given controllers to find any where the device ID equals
  62128. * filterIdExact, or startsWith filterIdPrefix.
  62129. * A controller where this considered true is considered a 'match'.
  62130. *
  62131. * For each matching controller:
  62132. * If filterHand is set, and the controller:
  62133. * is handed, we further verify that controller.hand equals filterHand.
  62134. * is unhanded (controller.hand is ''), we skip until we have found a
  62135. * number of matching controllers that equals filterControllerIndex
  62136. * If filterHand is not set, we skip until we have found the nth matching
  62137. * controller, where n equals filterControllerIndex
  62138. *
  62139. * The method should be called with one of: [filterIdExact, filterIdPrefix] AND
  62140. * one or both of: [filterHand, filterControllerIndex]
  62141. *
  62142. * @param {object} controllers - Array of gamepads to search
  62143. * @param {string} filterIdExact - If set, used to find controllers with id === this value
  62144. * @param {string} filterIdPrefix - If set, used to find controllers with id startsWith this value
  62145. * @param {object} filterHand - If set, further filters controllers with matching 'hand' property
  62146. * @param {object} filterControllerIndex - Find the nth matching controller,
  62147. * where n equals filterControllerIndex. defaults to 0.
  62148. */
  62149. function findMatchingControllerWebVR (controllers, filterIdExact, filterIdPrefix, filterHand,
  62150. filterControllerIndex) {
  62151. var controller;
  62152. var i;
  62153. var matchingControllerOccurence = 0;
  62154. var targetControllerMatch = filterControllerIndex >= 0 ? filterControllerIndex : 0;
  62155. for (i = 0; i < controllers.length; i++) {
  62156. controller = controllers[i];
  62157. // Determine if the controller ID matches our criteria.
  62158. if (filterIdPrefix && !controller.id.startsWith(filterIdPrefix)) {
  62159. continue;
  62160. }
  62161. if (!filterIdPrefix && controller.id !== filterIdExact) { continue; }
  62162. // If the hand filter and controller handedness are defined we compare them.
  62163. if (filterHand && controller.hand && filterHand !== controller.hand) { continue; }
  62164. // If we have detected an unhanded controller and the component was asking
  62165. // for a particular hand, we need to treat the controllers in the array as
  62166. // pairs of controllers. This effectively means that we need to skip
  62167. // NUM_HANDS matches for each controller number, instead of 1.
  62168. if (filterHand && !controller.hand) {
  62169. targetControllerMatch = NUM_HANDS * filterControllerIndex + ((filterHand === DEFAULT_HANDEDNESS) ? 0 : 1);
  62170. } else {
  62171. return controller;
  62172. }
  62173. // We are looking for the nth occurence of a matching controller
  62174. // (n equals targetControllerMatch).
  62175. if (matchingControllerOccurence === targetControllerMatch) { return controller; }
  62176. ++matchingControllerOccurence;
  62177. }
  62178. return undefined;
  62179. }
  62180. function findMatchingControllerWebXR (controllers, idPrefix, handedness, index, iterateProfiles, handTracking) {
  62181. var i;
  62182. var j;
  62183. var controller;
  62184. var controllerMatch = false;
  62185. var controllerHasHandedness;
  62186. var profiles;
  62187. for (i = 0; i < controllers.length; i++) {
  62188. controller = controllers[i];
  62189. profiles = controller.profiles;
  62190. if (handTracking) {
  62191. controllerMatch = controller.hand;
  62192. } else {
  62193. if (iterateProfiles) {
  62194. for (j = 0; j < profiles.length; j++) {
  62195. controllerMatch = profiles[j].startsWith(idPrefix);
  62196. if (controllerMatch) { break; }
  62197. }
  62198. } else {
  62199. controllerMatch = profiles.length > 0 && profiles[0].startsWith(idPrefix);
  62200. }
  62201. }
  62202. if (!controllerMatch) { continue; }
  62203. // Vive controllers are assigned handedness at runtime and it might not be always available.
  62204. controllerHasHandedness = controller.handedness === 'right' || controller.handedness === 'left';
  62205. if (controllerHasHandedness) {
  62206. if (controller.handedness === handedness) { return controllers[i]; }
  62207. } else { // Fallback to index if controller has no handedness.
  62208. if ((i === index)) { return controllers[i]; }
  62209. }
  62210. }
  62211. return undefined;
  62212. }
  62213. module.exports.findMatchingControllerWebVR = findMatchingControllerWebVR;
  62214. module.exports.findMatchingControllerWebXR = findMatchingControllerWebXR;
  62215. /**
  62216. * Emit specific `moved` event(s) if axes changed based on original axismoved event.
  62217. *
  62218. * @param {object} component - Controller component in use.
  62219. * @param {array} axesMapping - For example `{thumbstick: [0, 1]}`.
  62220. * @param {object} evt - Event to process.
  62221. */
  62222. module.exports.emitIfAxesChanged = function (component, axesMapping, evt) {
  62223. var axes;
  62224. var buttonType;
  62225. var changed;
  62226. var detail;
  62227. var j;
  62228. for (buttonType in axesMapping) {
  62229. axes = axesMapping[buttonType];
  62230. changed = false;
  62231. for (j = 0; j < axes.length; j++) {
  62232. if (evt.detail.changed[axes[j]]) { changed = true; }
  62233. }
  62234. if (!changed) { continue; }
  62235. // Axis has changed. Emit the specific moved event with axis values in detail.
  62236. detail = {};
  62237. for (j = 0; j < axes.length; j++) {
  62238. detail[AXIS_LABELS[j]] = evt.detail.axis[axes[j]];
  62239. }
  62240. component.el.emit(buttonType + 'moved', detail);
  62241. }
  62242. };
  62243. /**
  62244. * Handle a button event and reemits the events.
  62245. *
  62246. * @param {string} id - id of the button.
  62247. * @param {string} evtName - name of the reemitted event
  62248. * @param {object} component - reference to the component
  62249. * @param {string} hand - handedness of the controller: left or right.
  62250. */
  62251. module.exports.onButtonEvent = function (id, evtName, component, hand) {
  62252. var mapping = hand ? component.mapping[hand] : component.mapping;
  62253. var buttonName = mapping.buttons[id];
  62254. component.el.emit(buttonName + evtName);
  62255. if (component.updateModel) {
  62256. component.updateModel(buttonName, evtName);
  62257. }
  62258. };
  62259. },{"../constants":123}],215:[function(_dereq_,module,exports){
  62260. /**
  62261. * @author richt / http://richt.me
  62262. * @author WestLangley / http://github.com/WestLangley
  62263. *
  62264. * W3C Device Orientation control (http://w3c.github.io/deviceorientation/spec-source-orientation.html)
  62265. */
  62266. THREE.DeviceOrientationControls = function ( object ) {
  62267. var scope = this;
  62268. this.object = object;
  62269. this.object.rotation.reorder( 'YXZ' );
  62270. this.enabled = true;
  62271. this.deviceOrientation = {};
  62272. this.screenOrientation = 0;
  62273. this.alphaOffset = 0; // radians
  62274. var onDeviceOrientationChangeEvent = function ( event ) {
  62275. scope.deviceOrientation = event;
  62276. };
  62277. var onScreenOrientationChangeEvent = function () {
  62278. scope.screenOrientation = window.orientation || 0;
  62279. };
  62280. // The angles alpha, beta and gamma form a set of intrinsic Tait-Bryan angles of type Z-X'-Y''
  62281. var setObjectQuaternion = function () {
  62282. var zee = new THREE.Vector3( 0, 0, 1 );
  62283. var euler = new THREE.Euler();
  62284. var q0 = new THREE.Quaternion();
  62285. var q1 = new THREE.Quaternion( - Math.sqrt( 0.5 ), 0, 0, Math.sqrt( 0.5 ) ); // - PI/2 around the x-axis
  62286. return function ( quaternion, alpha, beta, gamma, orient ) {
  62287. euler.set( beta, alpha, - gamma, 'YXZ' ); // 'ZXY' for the device, but 'YXZ' for us
  62288. quaternion.setFromEuler( euler ); // orient the device
  62289. quaternion.multiply( q1 ); // camera looks out the back of the device, not the top
  62290. quaternion.multiply( q0.setFromAxisAngle( zee, - orient ) ); // adjust for screen orientation
  62291. };
  62292. }();
  62293. this.connect = function () {
  62294. onScreenOrientationChangeEvent();
  62295. window.addEventListener( 'orientationchange', onScreenOrientationChangeEvent, false );
  62296. window.addEventListener( 'deviceorientation', onDeviceOrientationChangeEvent, false );
  62297. scope.enabled = true;
  62298. };
  62299. this.disconnect = function () {
  62300. window.removeEventListener( 'orientationchange', onScreenOrientationChangeEvent, false );
  62301. window.removeEventListener( 'deviceorientation', onDeviceOrientationChangeEvent, false );
  62302. scope.enabled = false;
  62303. };
  62304. this.update = function () {
  62305. if ( scope.enabled === false ) return;
  62306. var device = scope.deviceOrientation;
  62307. if ( device ) {
  62308. var alpha = device.alpha ? THREE.Math.degToRad( device.alpha ) + scope.alphaOffset : 0; // Z
  62309. var beta = device.beta ? THREE.Math.degToRad( device.beta ) : 0; // X'
  62310. var gamma = device.gamma ? THREE.Math.degToRad( device.gamma ) : 0; // Y''
  62311. var orient = scope.screenOrientation ? THREE.Math.degToRad( scope.screenOrientation ) : 0; // O
  62312. setObjectQuaternion( scope.object.quaternion, alpha, beta, gamma, orient );
  62313. }
  62314. };
  62315. this.dispose = function () {
  62316. scope.disconnect();
  62317. };
  62318. this.connect();
  62319. };
  62320. },{}],216:[function(_dereq_,module,exports){
  62321. window.glStats = function () {
  62322. var _rS = null;
  62323. var _totalDrawArraysCalls = 0,
  62324. _totalDrawElementsCalls = 0,
  62325. _totalUseProgramCalls = 0,
  62326. _totalFaces = 0,
  62327. _totalVertices = 0,
  62328. _totalPoints = 0,
  62329. _totalBindTexures = 0;
  62330. function _h ( f, c ) {
  62331. return function () {
  62332. c.apply( this, arguments );
  62333. f.apply( this, arguments );
  62334. };
  62335. }
  62336. WebGLRenderingContext.prototype.drawArrays = _h( WebGLRenderingContext.prototype.drawArrays, function () {
  62337. _totalDrawArraysCalls++;
  62338. if ( arguments[ 0 ] == this.POINTS ) _totalPoints += arguments[ 2 ];
  62339. else _totalVertices += arguments[ 2 ];
  62340. } );
  62341. WebGLRenderingContext.prototype.drawElements = _h( WebGLRenderingContext.prototype.drawElements, function () {
  62342. _totalDrawElementsCalls++;
  62343. _totalFaces += arguments[ 1 ] / 3;
  62344. _totalVertices += arguments[ 1 ];
  62345. } );
  62346. WebGLRenderingContext.prototype.useProgram = _h( WebGLRenderingContext.prototype.useProgram, function () {
  62347. _totalUseProgramCalls++;
  62348. } );
  62349. WebGLRenderingContext.prototype.bindTexture = _h( WebGLRenderingContext.prototype.bindTexture, function () {
  62350. _totalBindTexures++;
  62351. } );
  62352. var _values = {
  62353. allcalls: {
  62354. over: 3000,
  62355. caption: 'Calls (hook)'
  62356. },
  62357. drawelements: {
  62358. caption: 'drawElements (hook)'
  62359. },
  62360. drawarrays: {
  62361. caption: 'drawArrays (hook)'
  62362. }
  62363. };
  62364. var _groups = [ {
  62365. caption: 'WebGL',
  62366. values: [ 'allcalls', 'drawelements', 'drawarrays', 'useprogram', 'bindtexture', 'glfaces', 'glvertices', 'glpoints' ]
  62367. } ];
  62368. var _fractions = [ {
  62369. base: 'allcalls',
  62370. steps: [ 'drawelements', 'drawarrays' ]
  62371. } ];
  62372. function _update () {
  62373. _rS( 'allcalls' ).set( _totalDrawArraysCalls + _totalDrawElementsCalls );
  62374. _rS( 'drawElements' ).set( _totalDrawElementsCalls );
  62375. _rS( 'drawArrays' ).set( _totalDrawArraysCalls );
  62376. _rS( 'bindTexture' ).set( _totalBindTexures );
  62377. _rS( 'useProgram' ).set( _totalUseProgramCalls );
  62378. _rS( 'glfaces' ).set( _totalFaces );
  62379. _rS( 'glvertices' ).set( _totalVertices );
  62380. _rS( 'glpoints' ).set( _totalPoints );
  62381. }
  62382. function _start () {
  62383. _totalDrawArraysCalls = 0;
  62384. _totalDrawElementsCalls = 0;
  62385. _totalUseProgramCalls = 0;
  62386. _totalFaces = 0;
  62387. _totalVertices = 0;
  62388. _totalPoints = 0;
  62389. _totalBindTexures = 0;
  62390. }
  62391. function _end () {}
  62392. function _attach ( r ) {
  62393. _rS = r;
  62394. }
  62395. return {
  62396. update: _update,
  62397. start: _start,
  62398. end: _end,
  62399. attach: _attach,
  62400. values: _values,
  62401. groups: _groups,
  62402. fractions: _fractions
  62403. };
  62404. };
  62405. window.threeStats = function ( renderer ) {
  62406. var _rS = null;
  62407. var _values = {
  62408. 'renderer.info.memory.geometries': {
  62409. caption: 'Geometries'
  62410. },
  62411. 'renderer.info.memory.textures': {
  62412. caption: 'Textures'
  62413. },
  62414. 'renderer.info.programs': {
  62415. caption: 'Programs'
  62416. },
  62417. 'renderer.info.render.calls': {
  62418. caption: 'Calls'
  62419. },
  62420. 'renderer.info.render.triangles': {
  62421. caption: 'Triangles',
  62422. over: 1000
  62423. },
  62424. 'renderer.info.render.points': {
  62425. caption: 'Points'
  62426. }
  62427. };
  62428. var _groups = [ {
  62429. caption: 'Three.js - Memory',
  62430. values: [ 'renderer.info.memory.geometries', 'renderer.info.programs', 'renderer.info.memory.textures' ]
  62431. }, {
  62432. caption: 'Three.js - Render',
  62433. values: [ 'renderer.info.render.calls', 'renderer.info.render.triangles', 'renderer.info.render.points' ]
  62434. } ];
  62435. var _fractions = [];
  62436. function _update () {
  62437. _rS( 'renderer.info.memory.geometries' ).set( renderer.info.memory.geometries );
  62438. _rS( 'renderer.info.programs' ).set( renderer.info.programs.length );
  62439. _rS( 'renderer.info.memory.textures' ).set( renderer.info.memory.textures );
  62440. _rS( 'renderer.info.render.calls' ).set( renderer.info.render.calls );
  62441. _rS( 'renderer.info.render.triangles' ).set( renderer.info.render.triangles );
  62442. _rS( 'renderer.info.render.points' ).set( renderer.info.render.points );
  62443. }
  62444. function _start () {}
  62445. function _end () {}
  62446. function _attach ( r ) {
  62447. _rS = r;
  62448. }
  62449. return {
  62450. update: _update,
  62451. start: _start,
  62452. end: _end,
  62453. attach: _attach,
  62454. values: _values,
  62455. groups: _groups,
  62456. fractions: _fractions
  62457. };
  62458. };
  62459. /*
  62460. * From https://github.com/paulirish/memory-stats.js
  62461. */
  62462. window.BrowserStats = function () {
  62463. var _rS = null;
  62464. var _usedJSHeapSize = 0,
  62465. _totalJSHeapSize = 0;
  62466. if ( window.performance && !performance.memory ) {
  62467. performance.memory = {
  62468. usedJSHeapSize: 0,
  62469. totalJSHeapSize: 0
  62470. };
  62471. }
  62472. if ( performance.memory.totalJSHeapSize === 0 ) {
  62473. console.warn( 'totalJSHeapSize === 0... performance.memory is only available in Chrome .' );
  62474. }
  62475. var _values = {
  62476. memory: {
  62477. caption: 'Used Memory',
  62478. average: true,
  62479. avgMs: 1000,
  62480. over: 22
  62481. },
  62482. total: {
  62483. caption: 'Total Memory'
  62484. }
  62485. };
  62486. var _groups = [ {
  62487. caption: 'Browser',
  62488. values: [ 'memory', 'total' ]
  62489. } ];
  62490. var _fractions = [ {
  62491. base: 'total',
  62492. steps: [ 'memory' ]
  62493. } ];
  62494. var log1024 = Math.log( 1024 );
  62495. function _size ( v ) {
  62496. var precision = 100; //Math.pow(10, 2);
  62497. var i = Math.floor( Math.log( v ) / log1024 );
  62498. return Math.round( v * precision / Math.pow( 1024, i ) ) / precision; // + ' ' + sizes[i];
  62499. }
  62500. function _update () {
  62501. _usedJSHeapSize = _size( performance.memory.usedJSHeapSize );
  62502. _totalJSHeapSize = _size( performance.memory.totalJSHeapSize );
  62503. _rS( 'memory' ).set( _usedJSHeapSize );
  62504. _rS( 'total' ).set( _totalJSHeapSize );
  62505. }
  62506. function _start () {
  62507. _usedJSHeapSize = 0;
  62508. }
  62509. function _end () {}
  62510. function _attach ( r ) {
  62511. _rS = r;
  62512. }
  62513. return {
  62514. update: _update,
  62515. start: _start,
  62516. end: _end,
  62517. attach: _attach,
  62518. values: _values,
  62519. groups: _groups,
  62520. fractions: _fractions
  62521. };
  62522. };
  62523. if (typeof module === 'object') {
  62524. module.exports = {
  62525. glStats: window.glStats,
  62526. threeStats: window.threeStats,
  62527. BrowserStats: window.BrowserStats
  62528. };
  62529. }
  62530. },{}],217:[function(_dereq_,module,exports){
  62531. // performance.now() polyfill from https://gist.github.com/paulirish/5438650
  62532. 'use strict';
  62533. ( function () {
  62534. if ( 'performance' in window == false ) {
  62535. window.performance = {};
  62536. }
  62537. var performance = window.performance;
  62538. if ( 'now' in performance == false ) {
  62539. var nowOffset = Date.now();
  62540. if ( performance.timing && performance.timing.navigationStart ) {
  62541. nowOffset = performance.timing.navigationStart;
  62542. }
  62543. performance.now = function now () {
  62544. return Date.now() - nowOffset;
  62545. };
  62546. }
  62547. if( !performance.mark ) {
  62548. performance.mark = function(){}
  62549. }
  62550. if( !performance.measure ) {
  62551. performance.measure = function(){}
  62552. }
  62553. } )();
  62554. window.rStats = function rStats ( settings ) {
  62555. function iterateKeys ( array, callback ) {
  62556. var keys = Object.keys( array );
  62557. for ( var j = 0, l = keys.length; j < l; j++ ) {
  62558. callback( keys[ j ] );
  62559. }
  62560. }
  62561. function importCSS ( url ) {
  62562. var element = document.createElement( 'link' );
  62563. element.href = url;
  62564. element.rel = 'stylesheet';
  62565. element.type = 'text/css';
  62566. document.getElementsByTagName( 'head' )[ 0 ].appendChild( element );
  62567. }
  62568. var _settings = settings || {};
  62569. var _colours = _settings.colours || [ '#850700', '#c74900', '#fcb300', '#284280', '#4c7c0c' ];
  62570. var _cssFont = 'https://fonts.googleapis.com/css?family=Roboto+Condensed:400,700,300';
  62571. var _cssRStats = ( _settings.CSSPath ? _settings.CSSPath : '' ) + 'rStats.css';
  62572. var _css = _settings.css || [ _cssFont, _cssRStats ];
  62573. _css.forEach(function (uri) {
  62574. importCSS( uri );
  62575. });
  62576. if ( !_settings.values ) _settings.values = {};
  62577. var _base, _div, _elHeight = 10, _elWidth = 200;
  62578. var _perfCounters = {};
  62579. function Graph ( _dom, _id, _defArg ) {
  62580. var _def = _defArg || {};
  62581. var _canvas = document.createElement( 'canvas' ),
  62582. _ctx = _canvas.getContext( '2d' ),
  62583. _max = 0,
  62584. _current = 0;
  62585. var c = _def.color ? _def.color : '#666666';
  62586. var _dotCanvas = document.createElement( 'canvas' ),
  62587. _dotCtx = _dotCanvas.getContext( '2d' );
  62588. _dotCanvas.width = 1;
  62589. _dotCanvas.height = 2 * _elHeight;
  62590. _dotCtx.fillStyle = '#444444';
  62591. _dotCtx.fillRect( 0, 0, 1, 2 * _elHeight );
  62592. _dotCtx.fillStyle = c;
  62593. _dotCtx.fillRect( 0, _elHeight, 1, _elHeight );
  62594. _dotCtx.fillStyle = '#ffffff';
  62595. _dotCtx.globalAlpha = 0.5;
  62596. _dotCtx.fillRect( 0, _elHeight, 1, 1 );
  62597. _dotCtx.globalAlpha = 1;
  62598. var _alarmCanvas = document.createElement( 'canvas' ),
  62599. _alarmCtx = _alarmCanvas.getContext( '2d' );
  62600. _alarmCanvas.width = 1;
  62601. _alarmCanvas.height = 2 * _elHeight;
  62602. _alarmCtx.fillStyle = '#444444';
  62603. _alarmCtx.fillRect( 0, 0, 1, 2 * _elHeight );
  62604. _alarmCtx.fillStyle = '#b70000';
  62605. _alarmCtx.fillRect( 0, _elHeight, 1, _elHeight );
  62606. _alarmCtx.globalAlpha = 0.5;
  62607. _alarmCtx.fillStyle = '#ffffff';
  62608. _alarmCtx.fillRect( 0, _elHeight, 1, 1 );
  62609. _alarmCtx.globalAlpha = 1;
  62610. function _init () {
  62611. _canvas.width = _elWidth;
  62612. _canvas.height = _elHeight;
  62613. _canvas.style.width = _canvas.width + 'px';
  62614. _canvas.style.height = _canvas.height + 'px';
  62615. _canvas.className = 'rs-canvas';
  62616. _dom.appendChild( _canvas );
  62617. _ctx.fillStyle = '#444444';
  62618. _ctx.fillRect( 0, 0, _canvas.width, _canvas.height );
  62619. }
  62620. function _draw ( v, alarm ) {
  62621. _current += ( v - _current ) * 0.1;
  62622. _max *= 0.99;
  62623. if ( _current > _max ) _max = _current;
  62624. _ctx.drawImage( _canvas, 1, 0, _canvas.width - 1, _canvas.height, 0, 0, _canvas.width - 1, _canvas.height );
  62625. if ( alarm ) {
  62626. _ctx.drawImage( _alarmCanvas, _canvas.width - 1, _canvas.height - _current * _canvas.height / _max - _elHeight );
  62627. } else {
  62628. _ctx.drawImage( _dotCanvas, _canvas.width - 1, _canvas.height - _current * _canvas.height / _max - _elHeight );
  62629. }
  62630. }
  62631. _init();
  62632. return {
  62633. draw: _draw
  62634. };
  62635. }
  62636. function StackGraph ( _dom, _num ) {
  62637. var _canvas = document.createElement( 'canvas' ),
  62638. _ctx = _canvas.getContext( '2d' );
  62639. function _init () {
  62640. _canvas.width = _elWidth;
  62641. _canvas.height = _elHeight * _num;
  62642. _canvas.style.width = _canvas.width + 'px';
  62643. _canvas.style.height = _canvas.height + 'px';
  62644. _canvas.className = 'rs-canvas';
  62645. _dom.appendChild( _canvas );
  62646. _ctx.fillStyle = '#444444';
  62647. _ctx.fillRect( 0, 0, _canvas.width, _canvas.height );
  62648. }
  62649. function _draw ( v ) {
  62650. _ctx.drawImage( _canvas, 1, 0, _canvas.width - 1, _canvas.height, 0, 0, _canvas.width - 1, _canvas.height );
  62651. var th = 0;
  62652. iterateKeys( v, function ( j ) {
  62653. var h = v[ j ] * _canvas.height;
  62654. _ctx.fillStyle = _colours[ j ];
  62655. _ctx.fillRect( _canvas.width - 1, th, 1, h );
  62656. th += h;
  62657. } );
  62658. }
  62659. _init();
  62660. return {
  62661. draw: _draw
  62662. };
  62663. }
  62664. function PerfCounter ( id, group ) {
  62665. var _id = id,
  62666. _time,
  62667. _value = 0,
  62668. _total = 0,
  62669. _averageValue = 0,
  62670. _accumValue = 0,
  62671. _accumStart = performance.now(),
  62672. _accumSamples = 0,
  62673. _dom = document.createElement( 'div' ),
  62674. _spanId = document.createElement( 'span' ),
  62675. _spanValue = document.createElement( 'div' ),
  62676. _spanValueText = document.createTextNode( '' ),
  62677. _def = _settings ? _settings.values[ _id.toLowerCase() ] : null,
  62678. _graph = new Graph( _dom, _id, _def ),
  62679. _started = false;
  62680. _spanId.className = 'rs-counter-id';
  62681. _spanId.textContent = ( _def && _def.caption ) ? _def.caption : _id;
  62682. _spanValue.className = 'rs-counter-value';
  62683. _spanValue.appendChild( _spanValueText );
  62684. _dom.appendChild( _spanId );
  62685. _dom.appendChild( _spanValue );
  62686. if ( group ) group.div.appendChild( _dom );
  62687. else _div.appendChild( _dom );
  62688. _time = performance.now();
  62689. function _average ( v ) {
  62690. if ( _def && _def.average ) {
  62691. _accumValue += v;
  62692. _accumSamples++;
  62693. var t = performance.now();
  62694. if ( t - _accumStart >= ( _def.avgMs || 1000 ) ) {
  62695. _averageValue = _accumValue / _accumSamples;
  62696. _accumValue = 0;
  62697. _accumStart = t;
  62698. _accumSamples = 0;
  62699. }
  62700. }
  62701. }
  62702. function _start () {
  62703. _time = performance.now();
  62704. if( _settings.userTimingAPI ) performance.mark( _id + '-start' );
  62705. _started = true;
  62706. }
  62707. function _end () {
  62708. _value = performance.now() - _time;
  62709. if( _settings.userTimingAPI ) {
  62710. performance.mark( _id + '-end' );
  62711. if( _started ) {
  62712. performance.measure( _id, _id + '-start', _id + '-end' );
  62713. }
  62714. }
  62715. _average( _value );
  62716. }
  62717. function _tick () {
  62718. _end();
  62719. _start();
  62720. }
  62721. function _draw () {
  62722. var v = ( _def && _def.average ) ? _averageValue : _value;
  62723. _spanValueText.nodeValue = Math.round( v * 100 ) / 100;
  62724. var a = ( _def && ( ( _def.below && _value < _def.below ) || ( _def.over && _value > _def.over ) ) );
  62725. _graph.draw( _value, a );
  62726. _dom.className = a ? 'rs-counter-base alarm' : 'rs-counter-base';
  62727. }
  62728. function _frame () {
  62729. var t = performance.now();
  62730. var e = t - _time;
  62731. _total++;
  62732. if ( e > 1000 ) {
  62733. if ( _def && _def.interpolate === false ) {
  62734. _value = _total;
  62735. } else {
  62736. _value = _total * 1000 / e;
  62737. }
  62738. _total = 0;
  62739. _time = t;
  62740. _average( _value );
  62741. }
  62742. }
  62743. function _set ( v ) {
  62744. _value = v;
  62745. _average( _value );
  62746. }
  62747. return {
  62748. set: _set,
  62749. start: _start,
  62750. tick: _tick,
  62751. end: _end,
  62752. frame: _frame,
  62753. value: function () {
  62754. return _value;
  62755. },
  62756. draw: _draw
  62757. };
  62758. }
  62759. function sample () {
  62760. var _value = 0;
  62761. function _set ( v ) {
  62762. _value = v;
  62763. }
  62764. return {
  62765. set: _set,
  62766. value: function () {
  62767. return _value;
  62768. }
  62769. };
  62770. }
  62771. function _perf ( idArg ) {
  62772. var id = idArg.toLowerCase();
  62773. if ( id === undefined ) id = 'default';
  62774. if ( _perfCounters[ id ] ) return _perfCounters[ id ];
  62775. var group = null;
  62776. if ( _settings && _settings.groups ) {
  62777. iterateKeys( _settings.groups, function ( j ) {
  62778. var g = _settings.groups[ parseInt( j, 10 ) ];
  62779. if ( !group && g.values.indexOf( id.toLowerCase() ) !== -1 ) {
  62780. group = g;
  62781. }
  62782. } );
  62783. }
  62784. var p = new PerfCounter( id, group );
  62785. _perfCounters[ id ] = p;
  62786. return p;
  62787. }
  62788. function _init () {
  62789. if ( _settings.plugins ) {
  62790. if ( !_settings.values ) _settings.values = {};
  62791. if ( !_settings.groups ) _settings.groups = [];
  62792. if ( !_settings.fractions ) _settings.fractions = [];
  62793. for ( var j = 0; j < _settings.plugins.length; j++ ) {
  62794. _settings.plugins[ j ].attach( _perf );
  62795. iterateKeys( _settings.plugins[ j ].values, function ( k ) {
  62796. _settings.values[ k ] = _settings.plugins[ j ].values[ k ];
  62797. } );
  62798. _settings.groups = _settings.groups.concat( _settings.plugins[ j ].groups );
  62799. _settings.fractions = _settings.fractions.concat( _settings.plugins[ j ].fractions );
  62800. }
  62801. } else {
  62802. _settings.plugins = {};
  62803. }
  62804. _base = document.createElement( 'div' );
  62805. _base.className = 'rs-base';
  62806. _div = document.createElement( 'div' );
  62807. _div.className = 'rs-container';
  62808. _div.style.height = 'auto';
  62809. _base.appendChild( _div );
  62810. document.body.appendChild( _base );
  62811. if ( !_settings ) return;
  62812. if ( _settings.groups ) {
  62813. iterateKeys( _settings.groups, function ( j ) {
  62814. var g = _settings.groups[ parseInt( j, 10 ) ];
  62815. var div = document.createElement( 'div' );
  62816. div.className = 'rs-group';
  62817. g.div = div;
  62818. var h1 = document.createElement( 'h1' );
  62819. h1.textContent = g.caption;
  62820. h1.addEventListener( 'click', function ( e ) {
  62821. this.classList.toggle( 'hidden' );
  62822. e.preventDefault();
  62823. }.bind( div ) );
  62824. _div.appendChild( h1 );
  62825. _div.appendChild( div );
  62826. } );
  62827. }
  62828. if ( _settings.fractions ) {
  62829. iterateKeys( _settings.fractions, function ( j ) {
  62830. var f = _settings.fractions[ parseInt( j, 10 ) ];
  62831. var div = document.createElement( 'div' );
  62832. div.className = 'rs-fraction';
  62833. var legend = document.createElement( 'div' );
  62834. legend.className = 'rs-legend';
  62835. var h = 0;
  62836. iterateKeys( _settings.fractions[ j ].steps, function ( k ) {
  62837. var p = document.createElement( 'p' );
  62838. p.textContent = _settings.fractions[ j ].steps[ k ];
  62839. p.style.color = _colours[ h ];
  62840. legend.appendChild( p );
  62841. h++;
  62842. } );
  62843. div.appendChild( legend );
  62844. div.style.height = h * _elHeight + 'px';
  62845. f.div = div;
  62846. var graph = new StackGraph( div, h );
  62847. f.graph = graph;
  62848. _div.appendChild( div );
  62849. } );
  62850. }
  62851. }
  62852. function _update () {
  62853. iterateKeys( _settings.plugins, function ( j ) {
  62854. _settings.plugins[ j ].update();
  62855. } );
  62856. iterateKeys( _perfCounters, function ( j ) {
  62857. _perfCounters[ j ].draw();
  62858. } );
  62859. if ( _settings && _settings.fractions ) {
  62860. iterateKeys( _settings.fractions, function ( j ) {
  62861. var f = _settings.fractions[ parseInt( j, 10 ) ];
  62862. var v = [];
  62863. var base = _perfCounters[ f.base.toLowerCase() ];
  62864. if ( base ) {
  62865. base = base.value();
  62866. iterateKeys( _settings.fractions[ j ].steps, function ( k ) {
  62867. var s = _settings.fractions[ j ].steps[ parseInt( k, 10 ) ].toLowerCase();
  62868. var val = _perfCounters[ s ];
  62869. if ( val ) {
  62870. v.push( val.value() / base );
  62871. }
  62872. } );
  62873. }
  62874. f.graph.draw( v );
  62875. } );
  62876. }
  62877. /*if( _height != _div.clientHeight ) {
  62878. _height = _div.clientHeight;
  62879. _base.style.height = _height + 2 * _elHeight + 'px';
  62880. console.log( _base.clientHeight );
  62881. }*/
  62882. }
  62883. _init();
  62884. return function ( id ) {
  62885. if ( id ) return _perf( id );
  62886. return {
  62887. element: _base,
  62888. update: _update
  62889. };
  62890. };
  62891. }
  62892. if (typeof module === 'object') {
  62893. module.exports = window.rStats;
  62894. }
  62895. },{}],218:[function(_dereq_,module,exports){
  62896. // https://stackoverflow.com/a/36213464
  62897. if (!String.prototype.startsWith) {
  62898. String.prototype.startsWith = function(searchString, position){
  62899. position = position || 0;
  62900. return this.substr(position, searchString.length) === searchString;
  62901. };
  62902. }
  62903. },{}],219:[function(_dereq_,module,exports){
  62904. /*
  62905. * Copyright 2015 Google Inc. All Rights Reserved.
  62906. * Licensed under the Apache License, Version 2.0 (the "License");
  62907. * you may not use this file except in compliance with the License.
  62908. * You may obtain a copy of the License at
  62909. *
  62910. * http://www.apache.org/licenses/LICENSE-2.0
  62911. *
  62912. * Unless required by applicable law or agreed to in writing, software
  62913. * distributed under the License is distributed on an "AS IS" BASIS,
  62914. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  62915. * See the License for the specific language governing permissions and
  62916. * limitations under the License.
  62917. */
  62918. var Util = {};
  62919. Util.base64 = function(mimeType, base64) {
  62920. return 'data:' + mimeType + ';base64,' + base64;
  62921. };
  62922. Util.isMobile = function() {
  62923. var check = false;
  62924. (function(a){if(/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(a)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(a.substr(0,4)))check = true})(navigator.userAgent||navigator.vendor||window.opera);
  62925. return check;
  62926. };
  62927. Util.isIOS = function() {
  62928. return /(iPad|iPhone|iPod)/g.test(navigator.userAgent);
  62929. };
  62930. Util.isIFrame = function() {
  62931. try {
  62932. return window.self !== window.top;
  62933. } catch (e) {
  62934. return true;
  62935. }
  62936. };
  62937. Util.appendQueryParameter = function(url, key, value) {
  62938. // Determine delimiter based on if the URL already GET parameters in it.
  62939. var delimiter = (url.indexOf('?') < 0 ? '?' : '&');
  62940. url += delimiter + key + '=' + value;
  62941. return url;
  62942. };
  62943. // From http://goo.gl/4WX3tg
  62944. Util.getQueryParameter = function(name) {
  62945. name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
  62946. var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
  62947. results = regex.exec(location.search);
  62948. return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
  62949. };
  62950. Util.isLandscapeMode = function() {
  62951. return (window.orientation == 90 || window.orientation == -90);
  62952. };
  62953. module.exports = Util;
  62954. },{}],220:[function(_dereq_,module,exports){
  62955. /*
  62956. * Copyright 2015 Google Inc. All Rights Reserved.
  62957. * Licensed under the Apache License, Version 2.0 (the "License");
  62958. * you may not use this file except in compliance with the License.
  62959. * You may obtain a copy of the License at
  62960. *
  62961. * http://www.apache.org/licenses/LICENSE-2.0
  62962. *
  62963. * Unless required by applicable law or agreed to in writing, software
  62964. * distributed under the License is distributed on an "AS IS" BASIS,
  62965. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  62966. * See the License for the specific language governing permissions and
  62967. * limitations under the License.
  62968. */
  62969. var Util = _dereq_('./util.js');
  62970. /**
  62971. * Android and iOS compatible wakelock implementation.
  62972. *
  62973. * Refactored thanks to dkovalev@.
  62974. */
  62975. function AndroidWakeLock() {
  62976. var video = document.createElement('video');
  62977. video.addEventListener('ended', function() {
  62978. video.play();
  62979. });
  62980. this.request = function() {
  62981. if (video.paused) {
  62982. // Base64 version of videos_src/no-sleep-60s.webm.
  62983. video.src = Util.base64('video/webm', 'GkXfowEAAAAAAAAfQoaBAUL3gQFC8oEEQvOBCEKChHdlYm1Ch4ECQoWBAhhTgGcBAAAAAAAH4xFNm3RALE27i1OrhBVJqWZTrIHfTbuMU6uEFlSua1OsggEwTbuMU6uEHFO7a1OsggfG7AEAAAAAAACkAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAVSalmAQAAAAAAAEUq17GDD0JATYCNTGF2ZjU2LjQwLjEwMVdBjUxhdmY1Ni40MC4xMDFzpJAGSJTMbsLpDt/ySkipgX1fRImIQO1MAAAAAAAWVK5rAQAAAAAAADuuAQAAAAAAADLXgQFzxYEBnIEAIrWcg3VuZIaFVl9WUDmDgQEj44OEO5rKAOABAAAAAAAABrCBsLqBkB9DtnUBAAAAAAAAo+eBAKOmgQAAgKJJg0IAAV4BHsAHBIODCoAACmH2MAAAZxgz4dPSTFi5JACjloED6ACmAECSnABMQAADYAAAWi0quoCjloEH0ACmAECSnABNwAADYAAAWi0quoCjloELuACmAECSnABNgAADYAAAWi0quoCjloEPoACmAECSnABNYAADYAAAWi0quoCjloETiACmAECSnABNIAADYAAAWi0quoAfQ7Z1AQAAAAAAAJTnghdwo5aBAAAApgBAkpwATOAAA2AAAFotKrqAo5aBA+gApgBAkpwATMAAA2AAAFotKrqAo5aBB9AApgBAkpwATIAAA2AAAFotKrqAo5aBC7gApgBAkpwATEAAA2AAAFotKrqAo5aBD6AApgDAkpwAQ2AAA2AAAFotKrqAo5aBE4gApgBAkpwATCAAA2AAAFotKrqAH0O2dQEAAAAAAACU54Iu4KOWgQAAAKYAQJKcAEvAAANgAABaLSq6gKOWgQPoAKYAQJKcAEtgAANgAABaLSq6gKOWgQfQAKYAQJKcAEsAAANgAABaLSq6gKOWgQu4AKYAQJKcAEqAAANgAABaLSq6gKOWgQ+gAKYAQJKcAEogAANgAABaLSq6gKOWgROIAKYAQJKcAEnAAANgAABaLSq6gB9DtnUBAAAAAAAAlOeCRlCjloEAAACmAECSnABJgAADYAAAWi0quoCjloED6ACmAECSnABJIAADYAAAWi0quoCjloEH0ACmAMCSnABDYAADYAAAWi0quoCjloELuACmAECSnABI4AADYAAAWi0quoCjloEPoACmAECSnABIoAADYAAAWi0quoCjloETiACmAECSnABIYAADYAAAWi0quoAfQ7Z1AQAAAAAAAJTngl3Ao5aBAAAApgBAkpwASCAAA2AAAFotKrqAo5aBA+gApgBAkpwASAAAA2AAAFotKrqAo5aBB9AApgBAkpwAR8AAA2AAAFotKrqAo5aBC7gApgBAkpwAR4AAA2AAAFotKrqAo5aBD6AApgBAkpwAR2AAA2AAAFotKrqAo5aBE4gApgBAkpwARyAAA2AAAFotKrqAH0O2dQEAAAAAAACU54J1MKOWgQAAAKYAwJKcAENgAANgAABaLSq6gKOWgQPoAKYAQJKcAEbgAANgAABaLSq6gKOWgQfQAKYAQJKcAEagAANgAABaLSq6gKOWgQu4AKYAQJKcAEaAAANgAABaLSq6gKOWgQ+gAKYAQJKcAEZAAANgAABaLSq6gKOWgROIAKYAQJKcAEYAAANgAABaLSq6gB9DtnUBAAAAAAAAlOeCjKCjloEAAACmAECSnABF4AADYAAAWi0quoCjloED6ACmAECSnABFwAADYAAAWi0quoCjloEH0ACmAECSnABFoAADYAAAWi0quoCjloELuACmAECSnABFgAADYAAAWi0quoCjloEPoACmAMCSnABDYAADYAAAWi0quoCjloETiACmAECSnABFYAADYAAAWi0quoAfQ7Z1AQAAAAAAAJTngqQQo5aBAAAApgBAkpwARUAAA2AAAFotKrqAo5aBA+gApgBAkpwARSAAA2AAAFotKrqAo5aBB9AApgBAkpwARQAAA2AAAFotKrqAo5aBC7gApgBAkpwARQAAA2AAAFotKrqAo5aBD6AApgBAkpwAROAAA2AAAFotKrqAo5aBE4gApgBAkpwARMAAA2AAAFotKrqAH0O2dQEAAAAAAACU54K7gKOWgQAAAKYAQJKcAESgAANgAABaLSq6gKOWgQPoAKYAQJKcAESAAANgAABaLSq6gKOWgQfQAKYAwJKcAENgAANgAABaLSq6gKOWgQu4AKYAQJKcAERgAANgAABaLSq6gKOWgQ+gAKYAQJKcAERAAANgAABaLSq6gKOWgROIAKYAQJKcAEQgAANgAABaLSq6gB9DtnUBAAAAAAAAlOeC0vCjloEAAACmAECSnABEIAADYAAAWi0quoCjloED6ACmAECSnABEAAADYAAAWi0quoCjloEH0ACmAECSnABD4AADYAAAWi0quoCjloELuACmAECSnABDwAADYAAAWi0quoCjloEPoACmAECSnABDoAADYAAAWi0quoCjloETiACmAECSnABDgAADYAAAWi0quoAcU7trAQAAAAAAABG7j7OBALeK94EB8YIBd/CBAw==');
  62984. video.play();
  62985. }
  62986. };
  62987. this.release = function() {
  62988. video.pause();
  62989. video.src = '';
  62990. };
  62991. }
  62992. function iOSWakeLock() {
  62993. var timer = null;
  62994. this.request = function() {
  62995. if (!timer) {
  62996. timer = setInterval(function() {
  62997. window.location.href = '/';
  62998. setTimeout(window.stop, 0);
  62999. }, 15000);
  63000. }
  63001. }
  63002. this.release = function() {
  63003. if (timer) {
  63004. clearInterval(timer);
  63005. timer = null;
  63006. }
  63007. }
  63008. }
  63009. function getWakeLock() {
  63010. var userAgent = navigator.userAgent || navigator.vendor || window.opera;
  63011. if (userAgent.match(/iPhone/i) || userAgent.match(/iPod/i)) {
  63012. return iOSWakeLock;
  63013. } else {
  63014. return AndroidWakeLock;
  63015. }
  63016. }
  63017. module.exports = getWakeLock();
  63018. },{"./util.js":219}]},{},[177])(177)
  63019. });
  63020. //# sourceMappingURL=aframe-master.js.map