aframe-master.js 2.3 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997399983999940000400014000240003400044000540006400074000840009400104001140012400134001440015400164001740018400194002040021400224002340024400254002640027400284002940030400314003240033400344003540036400374003840039400404004140042400434004440045400464004740048400494005040051400524005340054400554005640057400584005940060400614006240063400644006540066400674006840069400704007140072400734007440075400764007740078400794008040081400824008340084400854008640087400884008940090400914009240093400944009540096400974009840099401004010140102401034010440105401064010740108401094011040111401124011340114401154011640117401184011940120401214012240123401244012540126401274012840129401304013140132401334013440135401364013740138401394014040141401424014340144401454014640147401484014940150401514015240153401544015540156401574015840159401604016140162401634016440165401664016740168401694017040171401724017340174401754017640177401784017940180401814018240183401844018540186401874018840189401904019140192401934019440195401964019740198401994020040201402024020340204402054020640207402084020940210402114021240213402144021540216402174021840219402204022140222402234022440225402264022740228402294023040231402324023340234402354023640237402384023940240402414024240243402444024540246402474024840249402504025140252402534025440255402564025740258402594026040261402624026340264402654026640267402684026940270402714027240273402744027540276402774027840279402804028140282402834028440285402864028740288402894029040291402924029340294402954029640297402984029940300403014030240303403044030540306403074030840309403104031140312403134031440315403164031740318403194032040321403224032340324403254032640327403284032940330403314033240333403344033540336403374033840339403404034140342403434034440345403464034740348403494035040351403524035340354403554035640357403584035940360403614036240363403644036540366403674036840369403704037140372403734037440375403764037740378403794038040381403824038340384403854038640387403884038940390403914039240393403944039540396403974039840399404004040140402404034040440405404064040740408404094041040411404124041340414404154041640417404184041940420404214042240423404244042540426404274042840429404304043140432404334043440435404364043740438404394044040441404424044340444404454044640447404484044940450404514045240453404544045540456404574045840459404604046140462404634046440465404664046740468404694047040471404724047340474404754047640477404784047940480404814048240483404844048540486404874048840489404904049140492404934049440495404964049740498404994050040501405024050340504405054050640507405084050940510405114051240513405144051540516405174051840519405204052140522405234052440525405264052740528405294053040531405324053340534405354053640537405384053940540405414054240543405444054540546405474054840549405504055140552405534055440555405564055740558405594056040561405624056340564405654056640567405684056940570405714057240573405744057540576405774057840579405804058140582405834058440585405864058740588405894059040591405924059340594405954059640597405984059940600406014060240603406044060540606406074060840609406104061140612406134061440615406164061740618406194062040621406224062340624406254062640627406284062940630406314063240633406344063540636406374063840639406404064140642406434064440645406464064740648406494065040651406524065340654406554065640657406584065940660406614066240663406644066540666406674066840669406704067140672406734067440675406764067740678406794068040681406824068340684406854068640687406884068940690406914069240693406944069540696406974069840699407004070140702407034070440705407064070740708407094071040711407124071340714407154071640717407184071940720407214072240723407244072540726407274072840729407304073140732407334073440735407364073740738407394074040741407424074340744407454074640747407484074940750407514075240753407544075540756407574075840759407604076140762407634076440765407664076740768407694077040771407724077340774407754077640777407784077940780407814078240783407844078540786407874078840789407904079140792407934079440795407964079740798407994080040801408024080340804408054080640807408084080940810408114081240813408144081540816408174081840819408204082140822408234082440825408264082740828408294083040831408324083340834408354083640837408384083940840408414084240843408444084540846408474084840849408504085140852408534085440855408564085740858408594086040861408624086340864408654086640867408684086940870408714087240873408744087540876408774087840879408804088140882408834088440885408864088740888408894089040891408924089340894408954089640897408984089940900409014090240903409044090540906409074090840909409104091140912409134091440915409164091740918409194092040921409224092340924409254092640927409284092940930409314093240933409344093540936409374093840939409404094140942409434094440945409464094740948409494095040951409524095340954409554095640957409584095940960409614096240963409644096540966409674096840969409704097140972409734097440975409764097740978409794098040981409824098340984409854098640987409884098940990409914099240993409944099540996409974099840999410004100141002410034100441005410064100741008410094101041011410124101341014410154101641017410184101941020410214102241023410244102541026410274102841029410304103141032410334103441035410364103741038410394104041041410424104341044410454104641047410484104941050410514105241053410544105541056410574105841059410604106141062410634106441065410664106741068410694107041071410724107341074410754107641077410784107941080410814108241083410844108541086410874108841089410904109141092410934109441095410964109741098410994110041101411024110341104411054110641107411084110941110411114111241113411144111541116411174111841119411204112141122411234112441125411264112741128411294113041131411324113341134411354113641137411384113941140411414114241143411444114541146411474114841149411504115141152411534115441155411564115741158411594116041161411624116341164411654116641167411684116941170411714117241173411744117541176411774117841179411804118141182411834118441185411864118741188411894119041191411924119341194411954119641197411984119941200412014120241203412044120541206412074120841209412104121141212412134121441215412164121741218412194122041221412224122341224412254122641227412284122941230412314123241233412344123541236412374123841239412404124141242412434124441245412464124741248412494125041251412524125341254412554125641257412584125941260412614126241263412644126541266412674126841269412704127141272412734127441275412764127741278412794128041281412824128341284412854128641287412884128941290412914129241293412944129541296412974129841299413004130141302413034130441305413064130741308413094131041311413124131341314413154131641317413184131941320413214132241323413244132541326413274132841329413304133141332413334133441335413364133741338413394134041341413424134341344413454134641347413484134941350413514135241353413544135541356413574135841359413604136141362413634136441365413664136741368413694137041371413724137341374413754137641377413784137941380413814138241383413844138541386413874138841389413904139141392413934139441395413964139741398413994140041401414024140341404414054140641407414084140941410414114141241413414144141541416414174141841419414204142141422414234142441425414264142741428414294143041431414324143341434414354143641437414384143941440414414144241443414444144541446414474144841449414504145141452414534145441455414564145741458414594146041461414624146341464414654146641467414684146941470414714147241473414744147541476414774147841479414804148141482414834148441485414864148741488414894149041491414924149341494414954149641497414984149941500415014150241503415044150541506415074150841509415104151141512415134151441515415164151741518415194152041521415224152341524415254152641527415284152941530415314153241533415344153541536415374153841539415404154141542415434154441545415464154741548415494155041551415524155341554415554155641557415584155941560415614156241563415644156541566415674156841569415704157141572415734157441575415764157741578415794158041581415824158341584415854158641587415884158941590415914159241593415944159541596415974159841599416004160141602416034160441605416064160741608416094161041611416124161341614416154161641617416184161941620416214162241623416244162541626416274162841629416304163141632416334163441635416364163741638416394164041641416424164341644416454164641647416484164941650416514165241653416544165541656416574165841659416604166141662416634166441665416664166741668416694167041671416724167341674416754167641677416784167941680416814168241683416844168541686416874168841689416904169141692416934169441695416964169741698416994170041701417024170341704417054170641707417084170941710417114171241713417144171541716417174171841719417204172141722417234172441725417264172741728417294173041731417324173341734417354173641737417384173941740417414174241743417444174541746417474174841749417504175141752417534175441755417564175741758417594176041761417624176341764417654176641767417684176941770417714177241773417744177541776417774177841779417804178141782417834178441785417864178741788417894179041791417924179341794417954179641797417984179941800418014180241803418044180541806418074180841809418104181141812418134181441815418164181741818418194182041821418224182341824418254182641827418284182941830418314183241833418344183541836418374183841839418404184141842418434184441845418464184741848418494185041851418524185341854418554185641857418584185941860418614186241863418644186541866418674186841869418704187141872418734187441875418764187741878418794188041881418824188341884418854188641887418884188941890418914189241893418944189541896418974189841899419004190141902419034190441905419064190741908419094191041911419124191341914419154191641917419184191941920419214192241923419244192541926419274192841929419304193141932419334193441935419364193741938419394194041941419424194341944419454194641947419484194941950419514195241953419544195541956419574195841959419604196141962419634196441965419664196741968419694197041971419724197341974419754197641977419784197941980419814198241983419844198541986419874198841989419904199141992419934199441995419964199741998419994200042001420024200342004420054200642007420084200942010420114201242013420144201542016420174201842019420204202142022420234202442025420264202742028420294203042031420324203342034420354203642037420384203942040420414204242043420444204542046420474204842049420504205142052420534205442055420564205742058420594206042061420624206342064420654206642067420684206942070420714207242073420744207542076420774207842079420804208142082420834208442085420864208742088420894209042091420924209342094420954209642097420984209942100421014210242103421044210542106421074210842109421104211142112421134211442115421164211742118421194212042121421224212342124421254212642127421284212942130421314213242133421344213542136421374213842139421404214142142421434214442145421464214742148421494215042151421524215342154421554215642157421584215942160421614216242163421644216542166421674216842169421704217142172421734217442175421764217742178421794218042181421824218342184421854218642187421884218942190421914219242193421944219542196421974219842199422004220142202422034220442205422064220742208422094221042211422124221342214422154221642217422184221942220422214222242223422244222542226422274222842229422304223142232422334223442235422364223742238422394224042241422424224342244422454224642247422484224942250422514225242253422544225542256422574225842259422604226142262422634226442265422664226742268422694227042271422724227342274422754227642277422784227942280422814228242283422844228542286422874228842289422904229142292422934229442295422964229742298422994230042301423024230342304423054230642307423084230942310423114231242313423144231542316423174231842319423204232142322423234232442325423264232742328423294233042331423324233342334423354233642337423384233942340423414234242343423444234542346423474234842349423504235142352423534235442355423564235742358423594236042361423624236342364423654236642367423684236942370423714237242373423744237542376423774237842379423804238142382423834238442385423864238742388423894239042391423924239342394423954239642397423984239942400424014240242403424044240542406424074240842409424104241142412424134241442415424164241742418424194242042421424224242342424424254242642427424284242942430424314243242433424344243542436424374243842439424404244142442424434244442445424464244742448424494245042451424524245342454424554245642457424584245942460424614246242463424644246542466424674246842469424704247142472424734247442475424764247742478424794248042481424824248342484424854248642487424884248942490424914249242493424944249542496424974249842499425004250142502425034250442505425064250742508425094251042511425124251342514425154251642517425184251942520425214252242523425244252542526425274252842529425304253142532425334253442535425364253742538425394254042541425424254342544425454254642547425484254942550425514255242553425544255542556425574255842559425604256142562425634256442565425664256742568425694257042571425724257342574425754257642577425784257942580425814258242583425844258542586425874258842589425904259142592425934259442595425964259742598425994260042601426024260342604426054260642607426084260942610426114261242613426144261542616426174261842619426204262142622426234262442625426264262742628426294263042631426324263342634426354263642637426384263942640426414264242643426444264542646426474264842649426504265142652426534265442655426564265742658426594266042661426624266342664426654266642667426684266942670426714267242673426744267542676426774267842679426804268142682426834268442685426864268742688426894269042691426924269342694426954269642697426984269942700427014270242703427044270542706427074270842709427104271142712427134271442715427164271742718427194272042721427224272342724427254272642727427284272942730427314273242733427344273542736427374273842739427404274142742427434274442745427464274742748427494275042751427524275342754427554275642757427584275942760427614276242763427644276542766427674276842769427704277142772427734277442775427764277742778427794278042781427824278342784427854278642787427884278942790427914279242793427944279542796427974279842799428004280142802428034280442805428064280742808428094281042811428124281342814428154281642817428184281942820428214282242823428244282542826428274282842829428304283142832428334283442835428364283742838428394284042841428424284342844428454284642847428484284942850428514285242853428544285542856428574285842859428604286142862428634286442865428664286742868428694287042871428724287342874428754287642877428784287942880428814288242883428844288542886428874288842889428904289142892428934289442895428964289742898428994290042901429024290342904429054290642907429084290942910429114291242913429144291542916429174291842919429204292142922429234292442925429264292742928429294293042931429324293342934429354293642937429384293942940429414294242943429444294542946429474294842949429504295142952429534295442955429564295742958429594296042961429624296342964429654296642967429684296942970429714297242973429744297542976429774297842979429804298142982429834298442985429864298742988429894299042991429924299342994429954299642997429984299943000430014300243003430044300543006430074300843009430104301143012430134301443015430164301743018430194302043021430224302343024430254302643027430284302943030430314303243033430344303543036430374303843039430404304143042430434304443045430464304743048430494305043051430524305343054430554305643057430584305943060430614306243063430644306543066430674306843069430704307143072430734307443075430764307743078430794308043081430824308343084430854308643087430884308943090430914309243093430944309543096430974309843099431004310143102431034310443105431064310743108431094311043111431124311343114431154311643117431184311943120431214312243123431244312543126431274312843129431304313143132431334313443135431364313743138431394314043141431424314343144431454314643147431484314943150431514315243153431544315543156431574315843159431604316143162431634316443165431664316743168431694317043171431724317343174431754317643177431784317943180431814318243183431844318543186431874318843189431904319143192431934319443195431964319743198431994320043201432024320343204432054320643207432084320943210432114321243213432144321543216432174321843219432204322143222432234322443225432264322743228432294323043231432324323343234432354323643237432384323943240432414324243243432444324543246432474324843249432504325143252432534325443255432564325743258432594326043261432624326343264432654326643267432684326943270432714327243273432744327543276432774327843279432804328143282432834328443285432864328743288432894329043291432924329343294432954329643297432984329943300433014330243303433044330543306433074330843309433104331143312433134331443315433164331743318433194332043321433224332343324433254332643327433284332943330433314333243333433344333543336433374333843339433404334143342433434334443345433464334743348433494335043351433524335343354433554335643357433584335943360433614336243363433644336543366433674336843369433704337143372433734337443375433764337743378433794338043381433824338343384433854338643387433884338943390433914339243393433944339543396433974339843399434004340143402434034340443405434064340743408434094341043411434124341343414434154341643417434184341943420434214342243423434244342543426434274342843429434304343143432434334343443435434364343743438434394344043441434424344343444434454344643447434484344943450434514345243453434544345543456434574345843459434604346143462434634346443465434664346743468434694347043471434724347343474434754347643477434784347943480434814348243483434844348543486434874348843489434904349143492434934349443495434964349743498434994350043501435024350343504435054350643507435084350943510435114351243513435144351543516435174351843519435204352143522435234352443525435264352743528435294353043531435324353343534435354353643537435384353943540435414354243543435444354543546435474354843549435504355143552435534355443555435564355743558435594356043561435624356343564435654356643567435684356943570435714357243573435744357543576435774357843579435804358143582435834358443585435864358743588435894359043591435924359343594435954359643597435984359943600436014360243603436044360543606436074360843609436104361143612436134361443615436164361743618436194362043621436224362343624436254362643627436284362943630436314363243633436344363543636436374363843639436404364143642436434364443645436464364743648436494365043651436524365343654436554365643657436584365943660436614366243663436644366543666436674366843669436704367143672436734367443675436764367743678436794368043681436824368343684436854368643687436884368943690436914369243693436944369543696436974369843699437004370143702437034370443705437064370743708437094371043711437124371343714437154371643717437184371943720437214372243723437244372543726437274372843729437304373143732437334373443735437364373743738437394374043741437424374343744437454374643747437484374943750437514375243753437544375543756437574375843759437604376143762437634376443765437664376743768437694377043771437724377343774437754377643777437784377943780437814378243783437844378543786437874378843789437904379143792437934379443795437964379743798437994380043801438024380343804438054380643807438084380943810438114381243813438144381543816438174381843819438204382143822438234382443825438264382743828438294383043831438324383343834438354383643837438384383943840438414384243843438444384543846438474384843849438504385143852438534385443855438564385743858438594386043861438624386343864438654386643867438684386943870438714387243873438744387543876438774387843879438804388143882438834388443885438864388743888438894389043891438924389343894438954389643897438984389943900439014390243903439044390543906439074390843909439104391143912439134391443915439164391743918439194392043921439224392343924439254392643927439284392943930439314393243933439344393543936439374393843939439404394143942439434394443945439464394743948439494395043951439524395343954439554395643957439584395943960439614396243963439644396543966439674396843969439704397143972439734397443975439764397743978439794398043981439824398343984439854398643987439884398943990439914399243993439944399543996439974399843999440004400144002440034400444005440064400744008440094401044011440124401344014440154401644017440184401944020440214402244023440244402544026440274402844029440304403144032440334403444035440364403744038440394404044041440424404344044440454404644047440484404944050440514405244053440544405544056440574405844059440604406144062440634406444065440664406744068440694407044071440724407344074440754407644077440784407944080440814408244083440844408544086440874408844089440904409144092440934409444095440964409744098440994410044101441024410344104441054410644107441084410944110441114411244113441144411544116441174411844119441204412144122441234412444125441264412744128441294413044131441324413344134441354413644137441384413944140441414414244143441444414544146441474414844149441504415144152441534415444155441564415744158441594416044161441624416344164441654416644167441684416944170441714417244173441744417544176441774417844179441804418144182441834418444185441864418744188441894419044191441924419344194441954419644197441984419944200442014420244203442044420544206442074420844209442104421144212442134421444215442164421744218442194422044221442224422344224442254422644227442284422944230442314423244233442344423544236442374423844239442404424144242442434424444245442464424744248442494425044251442524425344254442554425644257442584425944260442614426244263442644426544266442674426844269442704427144272442734427444275442764427744278442794428044281442824428344284442854428644287442884428944290442914429244293442944429544296442974429844299443004430144302443034430444305443064430744308443094431044311443124431344314443154431644317443184431944320443214432244323443244432544326443274432844329443304433144332443334433444335443364433744338443394434044341443424434344344443454434644347443484434944350443514435244353443544435544356443574435844359443604436144362443634436444365443664436744368443694437044371443724437344374443754437644377443784437944380443814438244383443844438544386443874438844389443904439144392443934439444395443964439744398443994440044401444024440344404444054440644407444084440944410444114441244413444144441544416444174441844419444204442144422444234442444425444264442744428444294443044431444324443344434444354443644437444384443944440444414444244443444444444544446444474444844449444504445144452444534445444455444564445744458444594446044461444624446344464444654446644467444684446944470444714447244473444744447544476444774447844479444804448144482444834448444485444864448744488444894449044491444924449344494444954449644497444984449944500445014450244503445044450544506445074450844509445104451144512445134451444515445164451744518445194452044521445224452344524445254452644527445284452944530445314453244533445344453544536445374453844539445404454144542445434454444545445464454744548445494455044551445524455344554445554455644557445584455944560445614456244563445644456544566445674456844569445704457144572445734457444575445764457744578445794458044581445824458344584445854458644587445884458944590445914459244593445944459544596445974459844599446004460144602446034460444605446064460744608446094461044611446124461344614446154461644617446184461944620446214462244623446244462544626446274462844629446304463144632446334463444635446364463744638446394464044641446424464344644446454464644647446484464944650446514465244653446544465544656446574465844659446604466144662446634466444665446664466744668446694467044671446724467344674446754467644677446784467944680446814468244683446844468544686446874468844689446904469144692446934469444695446964469744698446994470044701447024470344704447054470644707447084470944710447114471244713447144471544716447174471844719447204472144722447234472444725447264472744728447294473044731447324473344734447354473644737447384473944740447414474244743447444474544746447474474844749447504475144752447534475444755447564475744758447594476044761447624476344764447654476644767447684476944770447714477244773447744477544776447774477844779447804478144782447834478444785447864478744788447894479044791447924479344794447954479644797447984479944800448014480244803448044480544806448074480844809448104481144812448134481444815448164481744818448194482044821448224482344824448254482644827448284482944830448314483244833448344483544836448374483844839448404484144842448434484444845448464484744848448494485044851448524485344854448554485644857448584485944860448614486244863448644486544866448674486844869448704487144872448734487444875448764487744878448794488044881448824488344884448854488644887448884488944890448914489244893448944489544896448974489844899449004490144902449034490444905449064490744908449094491044911449124491344914449154491644917449184491944920449214492244923449244492544926449274492844929449304493144932449334493444935449364493744938449394494044941449424494344944449454494644947449484494944950449514495244953449544495544956449574495844959449604496144962449634496444965449664496744968449694497044971449724497344974449754497644977449784497944980449814498244983449844498544986449874498844989449904499144992449934499444995449964499744998449994500045001450024500345004450054500645007450084500945010450114501245013450144501545016450174501845019450204502145022450234502445025450264502745028450294503045031450324503345034450354503645037450384503945040450414504245043450444504545046450474504845049450504505145052450534505445055450564505745058450594506045061450624506345064450654506645067450684506945070450714507245073450744507545076450774507845079450804508145082450834508445085450864508745088450894509045091450924509345094450954509645097450984509945100451014510245103451044510545106451074510845109451104511145112451134511445115451164511745118451194512045121451224512345124451254512645127451284512945130451314513245133451344513545136451374513845139451404514145142451434514445145451464514745148451494515045151451524515345154451554515645157451584515945160451614516245163451644516545166451674516845169451704517145172451734517445175451764517745178451794518045181451824518345184451854518645187451884518945190451914519245193451944519545196451974519845199452004520145202452034520445205452064520745208452094521045211452124521345214452154521645217452184521945220452214522245223452244522545226452274522845229452304523145232452334523445235452364523745238452394524045241452424524345244452454524645247452484524945250452514525245253452544525545256452574525845259452604526145262452634526445265452664526745268452694527045271452724527345274452754527645277452784527945280452814528245283452844528545286452874528845289452904529145292452934529445295452964529745298452994530045301453024530345304453054530645307453084530945310453114531245313453144531545316453174531845319453204532145322453234532445325453264532745328453294533045331453324533345334453354533645337453384533945340453414534245343453444534545346453474534845349453504535145352453534535445355453564535745358453594536045361453624536345364453654536645367453684536945370453714537245373453744537545376453774537845379453804538145382453834538445385453864538745388453894539045391453924539345394453954539645397453984539945400454014540245403454044540545406454074540845409454104541145412454134541445415454164541745418454194542045421454224542345424454254542645427454284542945430454314543245433454344543545436454374543845439454404544145442454434544445445454464544745448454494545045451454524545345454454554545645457454584545945460454614546245463454644546545466454674546845469454704547145472454734547445475454764547745478454794548045481454824548345484454854548645487454884548945490454914549245493454944549545496454974549845499455004550145502455034550445505455064550745508455094551045511455124551345514455154551645517455184551945520455214552245523455244552545526455274552845529455304553145532455334553445535455364553745538455394554045541455424554345544455454554645547455484554945550455514555245553455544555545556455574555845559455604556145562455634556445565455664556745568455694557045571455724557345574455754557645577455784557945580455814558245583455844558545586455874558845589455904559145592455934559445595455964559745598455994560045601456024560345604456054560645607456084560945610456114561245613456144561545616456174561845619456204562145622456234562445625456264562745628456294563045631456324563345634456354563645637456384563945640456414564245643456444564545646456474564845649456504565145652456534565445655456564565745658456594566045661456624566345664456654566645667456684566945670456714567245673456744567545676456774567845679456804568145682456834568445685456864568745688456894569045691456924569345694456954569645697456984569945700457014570245703457044570545706457074570845709457104571145712457134571445715457164571745718457194572045721457224572345724457254572645727457284572945730457314573245733457344573545736457374573845739457404574145742457434574445745457464574745748457494575045751457524575345754457554575645757457584575945760457614576245763457644576545766457674576845769457704577145772457734577445775457764577745778457794578045781457824578345784457854578645787457884578945790457914579245793457944579545796457974579845799458004580145802458034580445805458064580745808458094581045811458124581345814458154581645817458184581945820458214582245823458244582545826458274582845829458304583145832458334583445835458364583745838458394584045841458424584345844458454584645847458484584945850458514585245853458544585545856458574585845859458604586145862458634586445865458664586745868458694587045871458724587345874458754587645877458784587945880458814588245883458844588545886458874588845889458904589145892458934589445895458964589745898458994590045901459024590345904459054590645907459084590945910459114591245913459144591545916459174591845919459204592145922459234592445925459264592745928459294593045931459324593345934459354593645937459384593945940459414594245943459444594545946459474594845949459504595145952459534595445955459564595745958459594596045961459624596345964459654596645967459684596945970459714597245973459744597545976459774597845979459804598145982459834598445985459864598745988459894599045991459924599345994459954599645997459984599946000460014600246003460044600546006460074600846009460104601146012460134601446015460164601746018460194602046021460224602346024460254602646027460284602946030460314603246033460344603546036460374603846039460404604146042460434604446045460464604746048460494605046051460524605346054460554605646057460584605946060460614606246063460644606546066460674606846069460704607146072460734607446075460764607746078460794608046081460824608346084460854608646087460884608946090460914609246093460944609546096460974609846099461004610146102461034610446105461064610746108461094611046111461124611346114461154611646117461184611946120461214612246123461244612546126461274612846129461304613146132461334613446135461364613746138461394614046141461424614346144461454614646147461484614946150461514615246153461544615546156461574615846159461604616146162461634616446165461664616746168461694617046171461724617346174461754617646177461784617946180461814618246183461844618546186461874618846189461904619146192461934619446195461964619746198461994620046201462024620346204462054620646207462084620946210462114621246213462144621546216462174621846219462204622146222462234622446225462264622746228462294623046231462324623346234462354623646237462384623946240462414624246243462444624546246462474624846249462504625146252462534625446255462564625746258462594626046261462624626346264462654626646267462684626946270462714627246273462744627546276462774627846279462804628146282462834628446285462864628746288462894629046291462924629346294462954629646297462984629946300463014630246303463044630546306463074630846309463104631146312463134631446315463164631746318463194632046321463224632346324463254632646327463284632946330463314633246333463344633546336463374633846339463404634146342463434634446345463464634746348463494635046351463524635346354463554635646357463584635946360463614636246363463644636546366463674636846369463704637146372463734637446375463764637746378463794638046381463824638346384463854638646387463884638946390463914639246393463944639546396463974639846399464004640146402464034640446405464064640746408464094641046411464124641346414464154641646417464184641946420464214642246423464244642546426464274642846429464304643146432464334643446435464364643746438464394644046441464424644346444464454644646447464484644946450464514645246453464544645546456464574645846459464604646146462464634646446465464664646746468464694647046471464724647346474464754647646477464784647946480464814648246483464844648546486464874648846489464904649146492464934649446495464964649746498464994650046501465024650346504465054650646507465084650946510465114651246513465144651546516465174651846519465204652146522465234652446525465264652746528465294653046531465324653346534465354653646537465384653946540465414654246543465444654546546465474654846549465504655146552465534655446555465564655746558465594656046561465624656346564465654656646567465684656946570465714657246573465744657546576465774657846579465804658146582465834658446585465864658746588465894659046591465924659346594465954659646597465984659946600466014660246603466044660546606466074660846609466104661146612466134661446615466164661746618466194662046621466224662346624466254662646627466284662946630466314663246633466344663546636466374663846639466404664146642466434664446645466464664746648466494665046651466524665346654466554665646657466584665946660466614666246663466644666546666466674666846669466704667146672466734667446675466764667746678466794668046681466824668346684466854668646687466884668946690466914669246693466944669546696466974669846699467004670146702467034670446705467064670746708467094671046711467124671346714467154671646717467184671946720467214672246723467244672546726467274672846729467304673146732467334673446735467364673746738467394674046741467424674346744467454674646747467484674946750467514675246753467544675546756467574675846759467604676146762467634676446765467664676746768467694677046771467724677346774467754677646777467784677946780467814678246783467844678546786467874678846789467904679146792467934679446795467964679746798467994680046801468024680346804468054680646807468084680946810468114681246813468144681546816468174681846819468204682146822468234682446825468264682746828468294683046831468324683346834468354683646837468384683946840468414684246843468444684546846468474684846849468504685146852468534685446855468564685746858468594686046861468624686346864468654686646867468684686946870468714687246873468744687546876468774687846879468804688146882468834688446885468864688746888468894689046891468924689346894468954689646897468984689946900469014690246903469044690546906469074690846909469104691146912469134691446915469164691746918469194692046921469224692346924469254692646927469284692946930469314693246933469344693546936469374693846939469404694146942469434694446945469464694746948469494695046951469524695346954469554695646957469584695946960469614696246963469644696546966469674696846969469704697146972469734697446975469764697746978469794698046981469824698346984469854698646987469884698946990469914699246993469944699546996469974699846999470004700147002470034700447005470064700747008470094701047011470124701347014470154701647017470184701947020470214702247023470244702547026470274702847029470304703147032470334703447035470364703747038470394704047041470424704347044470454704647047470484704947050470514705247053470544705547056470574705847059470604706147062470634706447065470664706747068470694707047071470724707347074470754707647077470784707947080470814708247083470844708547086470874708847089470904709147092470934709447095470964709747098470994710047101471024710347104471054710647107471084710947110471114711247113471144711547116471174711847119471204712147122471234712447125471264712747128471294713047131471324713347134471354713647137471384713947140471414714247143471444714547146471474714847149471504715147152471534715447155471564715747158471594716047161471624716347164471654716647167471684716947170471714717247173471744717547176471774717847179471804718147182471834718447185471864718747188471894719047191471924719347194471954719647197471984719947200472014720247203472044720547206472074720847209472104721147212472134721447215472164721747218472194722047221472224722347224472254722647227472284722947230472314723247233472344723547236472374723847239472404724147242472434724447245472464724747248472494725047251472524725347254472554725647257472584725947260472614726247263472644726547266472674726847269472704727147272472734727447275472764727747278472794728047281472824728347284472854728647287472884728947290472914729247293472944729547296472974729847299473004730147302473034730447305473064730747308473094731047311473124731347314473154731647317473184731947320473214732247323473244732547326473274732847329473304733147332473334733447335473364733747338473394734047341473424734347344473454734647347473484734947350473514735247353473544735547356473574735847359473604736147362473634736447365473664736747368473694737047371473724737347374473754737647377473784737947380473814738247383473844738547386473874738847389473904739147392473934739447395473964739747398473994740047401474024740347404474054740647407474084740947410474114741247413474144741547416474174741847419474204742147422474234742447425474264742747428474294743047431474324743347434474354743647437474384743947440474414744247443474444744547446474474744847449474504745147452474534745447455474564745747458474594746047461474624746347464474654746647467474684746947470474714747247473474744747547476474774747847479474804748147482474834748447485474864748747488474894749047491474924749347494474954749647497474984749947500475014750247503475044750547506475074750847509475104751147512475134751447515475164751747518475194752047521475224752347524475254752647527475284752947530475314753247533475344753547536475374753847539475404754147542475434754447545475464754747548475494755047551475524755347554475554755647557475584755947560475614756247563475644756547566475674756847569475704757147572475734757447575475764757747578475794758047581475824758347584475854758647587475884758947590475914759247593475944759547596475974759847599476004760147602476034760447605476064760747608476094761047611476124761347614476154761647617476184761947620476214762247623476244762547626476274762847629476304763147632476334763447635476364763747638476394764047641476424764347644476454764647647476484764947650476514765247653476544765547656476574765847659476604766147662476634766447665476664766747668476694767047671476724767347674476754767647677476784767947680476814768247683476844768547686476874768847689476904769147692476934769447695476964769747698476994770047701477024770347704477054770647707477084770947710477114771247713477144771547716477174771847719477204772147722477234772447725477264772747728477294773047731477324773347734477354773647737477384773947740477414774247743477444774547746477474774847749477504775147752477534775447755477564775747758477594776047761477624776347764477654776647767477684776947770477714777247773477744777547776477774777847779477804778147782477834778447785477864778747788477894779047791477924779347794477954779647797477984779947800478014780247803478044780547806478074780847809478104781147812478134781447815478164781747818478194782047821478224782347824478254782647827478284782947830478314783247833478344783547836478374783847839478404784147842478434784447845478464784747848478494785047851478524785347854478554785647857478584785947860478614786247863478644786547866478674786847869478704787147872478734787447875478764787747878478794788047881478824788347884478854788647887478884788947890478914789247893478944789547896478974789847899479004790147902479034790447905479064790747908479094791047911479124791347914479154791647917479184791947920479214792247923479244792547926479274792847929479304793147932479334793447935479364793747938479394794047941479424794347944479454794647947479484794947950479514795247953479544795547956479574795847959479604796147962479634796447965479664796747968479694797047971479724797347974479754797647977479784797947980479814798247983479844798547986479874798847989479904799147992479934799447995479964799747998479994800048001480024800348004480054800648007480084800948010480114801248013480144801548016480174801848019480204802148022480234802448025480264802748028480294803048031480324803348034480354803648037480384803948040480414804248043480444804548046480474804848049480504805148052480534805448055480564805748058480594806048061480624806348064480654806648067480684806948070480714807248073480744807548076480774807848079480804808148082480834808448085480864808748088480894809048091480924809348094480954809648097480984809948100481014810248103481044810548106481074810848109481104811148112481134811448115481164811748118481194812048121481224812348124481254812648127481284812948130481314813248133481344813548136481374813848139481404814148142481434814448145481464814748148481494815048151481524815348154481554815648157481584815948160481614816248163481644816548166481674816848169481704817148172481734817448175481764817748178481794818048181481824818348184481854818648187481884818948190481914819248193481944819548196481974819848199482004820148202482034820448205482064820748208482094821048211482124821348214482154821648217482184821948220482214822248223482244822548226482274822848229482304823148232482334823448235482364823748238482394824048241482424824348244482454824648247482484824948250482514825248253482544825548256482574825848259482604826148262482634826448265482664826748268482694827048271482724827348274482754827648277482784827948280482814828248283482844828548286482874828848289482904829148292482934829448295482964829748298482994830048301483024830348304483054830648307483084830948310483114831248313483144831548316483174831848319483204832148322483234832448325483264832748328483294833048331483324833348334483354833648337483384833948340483414834248343483444834548346483474834848349483504835148352483534835448355483564835748358483594836048361483624836348364483654836648367483684836948370483714837248373483744837548376483774837848379483804838148382483834838448385483864838748388483894839048391483924839348394483954839648397483984839948400484014840248403484044840548406484074840848409484104841148412484134841448415484164841748418484194842048421484224842348424484254842648427484284842948430484314843248433484344843548436484374843848439484404844148442484434844448445484464844748448484494845048451484524845348454484554845648457484584845948460484614846248463484644846548466484674846848469484704847148472484734847448475484764847748478484794848048481484824848348484484854848648487484884848948490484914849248493484944849548496484974849848499485004850148502485034850448505485064850748508485094851048511485124851348514485154851648517485184851948520485214852248523485244852548526485274852848529485304853148532485334853448535485364853748538485394854048541485424854348544485454854648547485484854948550485514855248553485544855548556485574855848559485604856148562485634856448565485664856748568485694857048571485724857348574485754857648577485784857948580485814858248583485844858548586485874858848589485904859148592485934859448595485964859748598485994860048601486024860348604486054860648607486084860948610486114861248613486144861548616486174861848619486204862148622486234862448625486264862748628486294863048631486324863348634486354863648637486384863948640486414864248643486444864548646486474864848649486504865148652486534865448655486564865748658486594866048661486624866348664486654866648667486684866948670486714867248673486744867548676486774867848679486804868148682486834868448685486864868748688486894869048691486924869348694486954869648697486984869948700487014870248703487044870548706487074870848709487104871148712487134871448715487164871748718487194872048721487224872348724487254872648727487284872948730487314873248733487344873548736487374873848739487404874148742487434874448745487464874748748487494875048751487524875348754487554875648757487584875948760487614876248763487644876548766487674876848769487704877148772487734877448775487764877748778487794878048781487824878348784487854878648787487884878948790487914879248793487944879548796487974879848799488004880148802488034880448805488064880748808488094881048811488124881348814488154881648817488184881948820488214882248823488244882548826488274882848829488304883148832488334883448835488364883748838488394884048841488424884348844488454884648847488484884948850488514885248853488544885548856488574885848859488604886148862488634886448865488664886748868488694887048871488724887348874488754887648877488784887948880488814888248883488844888548886488874888848889488904889148892488934889448895488964889748898488994890048901489024890348904489054890648907489084890948910489114891248913489144891548916489174891848919489204892148922489234892448925489264892748928489294893048931489324893348934489354893648937489384893948940489414894248943489444894548946489474894848949489504895148952489534895448955489564895748958489594896048961489624896348964489654896648967489684896948970489714897248973489744897548976489774897848979489804898148982489834898448985489864898748988489894899048991489924899348994489954899648997489984899949000490014900249003490044900549006490074900849009490104901149012490134901449015490164901749018490194902049021490224902349024490254902649027490284902949030490314903249033490344903549036490374903849039490404904149042490434904449045490464904749048490494905049051490524905349054490554905649057490584905949060490614906249063490644906549066490674906849069490704907149072490734907449075490764907749078490794908049081490824908349084490854908649087490884908949090490914909249093490944909549096490974909849099491004910149102491034910449105491064910749108491094911049111491124911349114491154911649117491184911949120491214912249123491244912549126491274912849129491304913149132491334913449135491364913749138491394914049141491424914349144491454914649147491484914949150491514915249153491544915549156491574915849159491604916149162491634916449165491664916749168491694917049171491724917349174491754917649177491784917949180491814918249183491844918549186491874918849189491904919149192491934919449195491964919749198491994920049201492024920349204492054920649207492084920949210492114921249213492144921549216492174921849219492204922149222492234922449225492264922749228492294923049231492324923349234492354923649237492384923949240492414924249243492444924549246492474924849249492504925149252492534925449255492564925749258492594926049261492624926349264492654926649267492684926949270492714927249273492744927549276492774927849279492804928149282492834928449285492864928749288492894929049291492924929349294492954929649297492984929949300493014930249303493044930549306493074930849309493104931149312493134931449315493164931749318493194932049321493224932349324493254932649327493284932949330493314933249333493344933549336493374933849339493404934149342493434934449345493464934749348493494935049351493524935349354493554935649357493584935949360493614936249363493644936549366493674936849369493704937149372493734937449375493764937749378493794938049381493824938349384493854938649387493884938949390493914939249393493944939549396493974939849399494004940149402494034940449405494064940749408494094941049411494124941349414494154941649417494184941949420494214942249423494244942549426494274942849429494304943149432494334943449435494364943749438494394944049441494424944349444494454944649447494484944949450494514945249453494544945549456494574945849459494604946149462494634946449465494664946749468494694947049471494724947349474494754947649477494784947949480494814948249483494844948549486494874948849489494904949149492494934949449495494964949749498494994950049501495024950349504495054950649507495084950949510495114951249513495144951549516495174951849519495204952149522495234952449525495264952749528495294953049531495324953349534495354953649537495384953949540495414954249543495444954549546495474954849549495504955149552495534955449555495564955749558495594956049561495624956349564495654956649567495684956949570495714957249573495744957549576495774957849579495804958149582495834958449585495864958749588495894959049591495924959349594495954959649597495984959949600496014960249603496044960549606496074960849609496104961149612496134961449615496164961749618496194962049621496224962349624496254962649627496284962949630496314963249633496344963549636496374963849639496404964149642496434964449645496464964749648496494965049651496524965349654496554965649657496584965949660496614966249663496644966549666496674966849669496704967149672496734967449675496764967749678496794968049681496824968349684496854968649687496884968949690496914969249693496944969549696496974969849699497004970149702497034970449705497064970749708497094971049711497124971349714497154971649717497184971949720497214972249723497244972549726497274972849729497304973149732497334973449735497364973749738497394974049741497424974349744497454974649747497484974949750497514975249753497544975549756497574975849759497604976149762497634976449765497664976749768497694977049771497724977349774497754977649777497784977949780497814978249783497844978549786497874978849789497904979149792497934979449795497964979749798497994980049801498024980349804498054980649807498084980949810498114981249813498144981549816498174981849819498204982149822498234982449825498264982749828498294983049831498324983349834498354983649837498384983949840498414984249843498444984549846498474984849849498504985149852498534985449855498564985749858498594986049861498624986349864498654986649867498684986949870498714987249873498744987549876498774987849879498804988149882498834988449885498864988749888498894989049891498924989349894498954989649897498984989949900499014990249903499044990549906499074990849909499104991149912499134991449915499164991749918499194992049921499224992349924499254992649927499284992949930499314993249933499344993549936499374993849939499404994149942499434994449945499464994749948499494995049951499524995349954499554995649957499584995949960499614996249963499644996549966499674996849969499704997149972499734997449975499764997749978499794998049981499824998349984499854998649987499884998949990499914999249993499944999549996499974999849999500005000150002500035000450005500065000750008500095001050011500125001350014500155001650017500185001950020500215002250023500245002550026500275002850029500305003150032500335003450035500365003750038500395004050041500425004350044500455004650047500485004950050500515005250053500545005550056500575005850059500605006150062500635006450065500665006750068500695007050071500725007350074500755007650077500785007950080500815008250083500845008550086500875008850089500905009150092500935009450095500965009750098500995010050101501025010350104501055010650107501085010950110501115011250113501145011550116501175011850119501205012150122501235012450125501265012750128501295013050131501325013350134501355013650137501385013950140501415014250143501445014550146501475014850149501505015150152501535015450155501565015750158501595016050161501625016350164501655016650167501685016950170501715017250173501745017550176501775017850179501805018150182501835018450185501865018750188501895019050191501925019350194501955019650197501985019950200502015020250203502045020550206502075020850209502105021150212502135021450215502165021750218502195022050221502225022350224502255022650227502285022950230502315023250233502345023550236502375023850239502405024150242502435024450245502465024750248502495025050251502525025350254502555025650257502585025950260502615026250263502645026550266502675026850269502705027150272502735027450275502765027750278502795028050281502825028350284502855028650287502885028950290502915029250293502945029550296502975029850299503005030150302503035030450305503065030750308503095031050311503125031350314503155031650317503185031950320503215032250323503245032550326503275032850329503305033150332503335033450335503365033750338503395034050341503425034350344503455034650347503485034950350503515035250353503545035550356503575035850359503605036150362503635036450365503665036750368503695037050371503725037350374503755037650377503785037950380503815038250383503845038550386503875038850389503905039150392503935039450395503965039750398503995040050401504025040350404504055040650407504085040950410504115041250413504145041550416504175041850419504205042150422504235042450425504265042750428504295043050431504325043350434504355043650437504385043950440504415044250443504445044550446504475044850449504505045150452504535045450455504565045750458504595046050461504625046350464504655046650467504685046950470504715047250473504745047550476504775047850479504805048150482504835048450485504865048750488504895049050491504925049350494504955049650497504985049950500505015050250503505045050550506505075050850509505105051150512505135051450515505165051750518505195052050521505225052350524505255052650527505285052950530505315053250533505345053550536505375053850539505405054150542505435054450545505465054750548505495055050551505525055350554505555055650557505585055950560505615056250563505645056550566505675056850569505705057150572505735057450575505765057750578505795058050581505825058350584505855058650587505885058950590505915059250593505945059550596505975059850599506005060150602506035060450605506065060750608506095061050611506125061350614506155061650617506185061950620506215062250623506245062550626506275062850629506305063150632506335063450635506365063750638506395064050641506425064350644506455064650647506485064950650506515065250653506545065550656506575065850659506605066150662506635066450665506665066750668506695067050671506725067350674506755067650677506785067950680506815068250683506845068550686506875068850689506905069150692506935069450695506965069750698506995070050701507025070350704507055070650707507085070950710507115071250713507145071550716507175071850719507205072150722507235072450725507265072750728507295073050731507325073350734507355073650737507385073950740507415074250743507445074550746507475074850749507505075150752507535075450755507565075750758507595076050761507625076350764507655076650767507685076950770507715077250773507745077550776507775077850779507805078150782507835078450785507865078750788507895079050791507925079350794507955079650797507985079950800508015080250803508045080550806508075080850809508105081150812508135081450815508165081750818508195082050821508225082350824508255082650827508285082950830508315083250833508345083550836508375083850839508405084150842508435084450845508465084750848508495085050851508525085350854508555085650857508585085950860508615086250863508645086550866508675086850869508705087150872508735087450875508765087750878508795088050881508825088350884508855088650887508885088950890508915089250893508945089550896508975089850899509005090150902509035090450905509065090750908509095091050911509125091350914509155091650917509185091950920509215092250923509245092550926509275092850929509305093150932509335093450935509365093750938509395094050941509425094350944509455094650947509485094950950509515095250953509545095550956509575095850959509605096150962509635096450965509665096750968509695097050971509725097350974509755097650977509785097950980509815098250983509845098550986509875098850989509905099150992509935099450995509965099750998509995100051001510025100351004510055100651007510085100951010510115101251013510145101551016510175101851019510205102151022510235102451025510265102751028510295103051031510325103351034510355103651037510385103951040510415104251043510445104551046510475104851049510505105151052510535105451055510565105751058510595106051061510625106351064510655106651067510685106951070510715107251073510745107551076510775107851079510805108151082510835108451085510865108751088510895109051091510925109351094510955109651097510985109951100511015110251103511045110551106511075110851109511105111151112511135111451115511165111751118511195112051121511225112351124511255112651127511285112951130511315113251133511345113551136511375113851139511405114151142511435114451145511465114751148511495115051151511525115351154511555115651157511585115951160511615116251163511645116551166511675116851169511705117151172511735117451175511765117751178511795118051181511825118351184511855118651187511885118951190511915119251193511945119551196511975119851199512005120151202512035120451205512065120751208512095121051211512125121351214512155121651217512185121951220512215122251223512245122551226512275122851229512305123151232512335123451235512365123751238512395124051241512425124351244512455124651247512485124951250512515125251253512545125551256512575125851259512605126151262512635126451265512665126751268512695127051271512725127351274512755127651277512785127951280512815128251283512845128551286512875128851289512905129151292512935129451295512965129751298512995130051301513025130351304513055130651307513085130951310513115131251313513145131551316513175131851319513205132151322513235132451325513265132751328513295133051331513325133351334513355133651337513385133951340513415134251343513445134551346513475134851349513505135151352513535135451355513565135751358513595136051361513625136351364513655136651367513685136951370513715137251373513745137551376513775137851379513805138151382513835138451385513865138751388513895139051391513925139351394513955139651397513985139951400514015140251403514045140551406514075140851409514105141151412514135141451415514165141751418514195142051421514225142351424514255142651427514285142951430514315143251433514345143551436514375143851439514405144151442514435144451445514465144751448514495145051451514525145351454514555145651457514585145951460514615146251463514645146551466514675146851469514705147151472514735147451475514765147751478514795148051481514825148351484514855148651487514885148951490514915149251493514945149551496514975149851499515005150151502515035150451505515065150751508515095151051511515125151351514515155151651517515185151951520515215152251523515245152551526515275152851529515305153151532515335153451535515365153751538515395154051541515425154351544515455154651547515485154951550515515155251553515545155551556515575155851559515605156151562515635156451565515665156751568515695157051571515725157351574515755157651577515785157951580515815158251583515845158551586515875158851589515905159151592515935159451595515965159751598515995160051601516025160351604516055160651607516085160951610516115161251613516145161551616516175161851619516205162151622516235162451625516265162751628516295163051631516325163351634516355163651637516385163951640516415164251643516445164551646516475164851649516505165151652516535165451655516565165751658516595166051661516625166351664516655166651667516685166951670516715167251673516745167551676516775167851679516805168151682516835168451685516865168751688516895169051691516925169351694516955169651697516985169951700517015170251703517045170551706517075170851709517105171151712517135171451715517165171751718517195172051721517225172351724517255172651727517285172951730517315173251733517345173551736517375173851739517405174151742517435174451745517465174751748517495175051751517525175351754517555175651757517585175951760517615176251763517645176551766517675176851769517705177151772517735177451775517765177751778517795178051781517825178351784517855178651787517885178951790517915179251793517945179551796517975179851799518005180151802518035180451805518065180751808518095181051811518125181351814518155181651817518185181951820518215182251823518245182551826518275182851829518305183151832518335183451835518365183751838518395184051841518425184351844518455184651847518485184951850518515185251853518545185551856518575185851859518605186151862518635186451865518665186751868518695187051871518725187351874518755187651877518785187951880518815188251883518845188551886518875188851889518905189151892518935189451895518965189751898518995190051901519025190351904519055190651907519085190951910519115191251913519145191551916519175191851919519205192151922519235192451925519265192751928519295193051931519325193351934519355193651937519385193951940519415194251943519445194551946519475194851949519505195151952519535195451955519565195751958519595196051961519625196351964519655196651967519685196951970519715197251973519745197551976519775197851979519805198151982519835198451985519865198751988519895199051991519925199351994519955199651997519985199952000520015200252003520045200552006520075200852009520105201152012520135201452015520165201752018520195202052021520225202352024520255202652027520285202952030520315203252033520345203552036520375203852039520405204152042520435204452045520465204752048520495205052051520525205352054520555205652057520585205952060520615206252063520645206552066520675206852069520705207152072520735207452075520765207752078520795208052081520825208352084520855208652087520885208952090520915209252093520945209552096520975209852099521005210152102521035210452105521065210752108521095211052111521125211352114521155211652117521185211952120521215212252123521245212552126521275212852129521305213152132521335213452135521365213752138521395214052141521425214352144521455214652147521485214952150521515215252153521545215552156521575215852159521605216152162521635216452165521665216752168521695217052171521725217352174521755217652177521785217952180521815218252183521845218552186521875218852189521905219152192521935219452195521965219752198521995220052201522025220352204522055220652207522085220952210522115221252213522145221552216522175221852219522205222152222522235222452225522265222752228522295223052231522325223352234522355223652237522385223952240522415224252243522445224552246522475224852249522505225152252522535225452255522565225752258522595226052261522625226352264522655226652267522685226952270522715227252273522745227552276522775227852279522805228152282522835228452285522865228752288522895229052291522925229352294522955229652297522985229952300523015230252303523045230552306523075230852309523105231152312523135231452315523165231752318523195232052321523225232352324523255232652327523285232952330523315233252333523345233552336523375233852339523405234152342523435234452345523465234752348523495235052351523525235352354523555235652357523585235952360523615236252363523645236552366523675236852369523705237152372523735237452375523765237752378523795238052381523825238352384523855238652387523885238952390523915239252393523945239552396523975239852399524005240152402524035240452405524065240752408524095241052411524125241352414524155241652417524185241952420524215242252423524245242552426524275242852429524305243152432524335243452435524365243752438524395244052441524425244352444524455244652447524485244952450524515245252453524545245552456524575245852459524605246152462524635246452465524665246752468524695247052471524725247352474524755247652477524785247952480524815248252483524845248552486524875248852489524905249152492524935249452495524965249752498524995250052501525025250352504525055250652507525085250952510525115251252513525145251552516525175251852519525205252152522525235252452525525265252752528525295253052531525325253352534525355253652537525385253952540525415254252543525445254552546525475254852549525505255152552525535255452555525565255752558525595256052561525625256352564525655256652567525685256952570525715257252573525745257552576525775257852579525805258152582525835258452585525865258752588525895259052591525925259352594525955259652597525985259952600526015260252603526045260552606526075260852609526105261152612526135261452615526165261752618526195262052621526225262352624526255262652627526285262952630526315263252633526345263552636526375263852639526405264152642526435264452645526465264752648526495265052651526525265352654526555265652657526585265952660526615266252663526645266552666526675266852669526705267152672526735267452675526765267752678526795268052681526825268352684526855268652687526885268952690526915269252693526945269552696526975269852699527005270152702527035270452705527065270752708527095271052711527125271352714527155271652717527185271952720527215272252723527245272552726527275272852729527305273152732527335273452735527365273752738527395274052741527425274352744527455274652747527485274952750527515275252753527545275552756527575275852759527605276152762527635276452765527665276752768527695277052771527725277352774527755277652777527785277952780527815278252783527845278552786527875278852789527905279152792527935279452795527965279752798527995280052801528025280352804528055280652807528085280952810528115281252813528145281552816528175281852819528205282152822528235282452825528265282752828528295283052831528325283352834528355283652837528385283952840528415284252843528445284552846528475284852849528505285152852528535285452855528565285752858528595286052861528625286352864528655286652867528685286952870528715287252873528745287552876528775287852879528805288152882528835288452885528865288752888528895289052891528925289352894528955289652897528985289952900529015290252903529045290552906529075290852909529105291152912529135291452915529165291752918529195292052921529225292352924529255292652927529285292952930529315293252933529345293552936529375293852939529405294152942529435294452945529465294752948529495295052951529525295352954529555295652957529585295952960529615296252963529645296552966529675296852969529705297152972529735297452975529765297752978529795298052981529825298352984529855298652987529885298952990529915299252993529945299552996529975299852999530005300153002530035300453005530065300753008530095301053011530125301353014530155301653017530185301953020530215302253023530245302553026530275302853029530305303153032530335303453035530365303753038530395304053041530425304353044530455304653047530485304953050530515305253053530545305553056530575305853059530605306153062530635306453065530665306753068530695307053071530725307353074530755307653077530785307953080530815308253083530845308553086530875308853089530905309153092530935309453095530965309753098530995310053101531025310353104531055310653107531085310953110531115311253113531145311553116531175311853119531205312153122531235312453125531265312753128531295313053131531325313353134531355313653137531385313953140531415314253143531445314553146531475314853149531505315153152531535315453155531565315753158531595316053161531625316353164531655316653167531685316953170531715317253173531745317553176531775317853179531805318153182531835318453185531865318753188531895319053191531925319353194531955319653197531985319953200532015320253203532045320553206532075320853209532105321153212532135321453215532165321753218532195322053221532225322353224532255322653227532285322953230532315323253233532345323553236532375323853239532405324153242532435324453245532465324753248532495325053251532525325353254532555325653257532585325953260532615326253263532645326553266532675326853269532705327153272532735327453275532765327753278532795328053281532825328353284532855328653287532885328953290532915329253293532945329553296532975329853299533005330153302533035330453305533065330753308533095331053311533125331353314533155331653317533185331953320533215332253323533245332553326533275332853329533305333153332533335333453335533365333753338533395334053341533425334353344533455334653347533485334953350533515335253353533545335553356533575335853359533605336153362533635336453365533665336753368533695337053371533725337353374533755337653377533785337953380533815338253383533845338553386533875338853389533905339153392533935339453395533965339753398533995340053401534025340353404534055340653407534085340953410534115341253413534145341553416534175341853419534205342153422534235342453425534265342753428534295343053431534325343353434534355343653437534385343953440534415344253443534445344553446534475344853449534505345153452534535345453455534565345753458534595346053461534625346353464534655346653467534685346953470534715347253473534745347553476534775347853479534805348153482534835348453485534865348753488534895349053491534925349353494534955349653497534985349953500535015350253503535045350553506535075350853509535105351153512535135351453515535165351753518535195352053521535225352353524535255352653527535285352953530535315353253533535345353553536535375353853539535405354153542535435354453545535465354753548535495355053551535525355353554535555355653557535585355953560535615356253563535645356553566535675356853569535705357153572535735357453575535765357753578535795358053581535825358353584535855358653587535885358953590535915359253593535945359553596535975359853599536005360153602536035360453605536065360753608536095361053611536125361353614536155361653617536185361953620536215362253623536245362553626536275362853629536305363153632536335363453635536365363753638536395364053641536425364353644536455364653647536485364953650536515365253653536545365553656536575365853659536605366153662536635366453665536665366753668536695367053671536725367353674536755367653677536785367953680536815368253683536845368553686536875368853689536905369153692536935369453695536965369753698536995370053701537025370353704537055370653707537085370953710537115371253713537145371553716537175371853719537205372153722537235372453725537265372753728537295373053731537325373353734537355373653737537385373953740537415374253743537445374553746537475374853749537505375153752537535375453755537565375753758537595376053761537625376353764537655376653767537685376953770537715377253773537745377553776537775377853779537805378153782537835378453785537865378753788537895379053791537925379353794537955379653797537985379953800538015380253803538045380553806538075380853809538105381153812538135381453815538165381753818538195382053821538225382353824538255382653827538285382953830538315383253833538345383553836538375383853839538405384153842538435384453845538465384753848538495385053851538525385353854538555385653857538585385953860538615386253863538645386553866538675386853869538705387153872538735387453875538765387753878538795388053881538825388353884538855388653887538885388953890538915389253893538945389553896538975389853899539005390153902539035390453905539065390753908539095391053911539125391353914539155391653917539185391953920539215392253923539245392553926539275392853929539305393153932539335393453935539365393753938539395394053941539425394353944539455394653947539485394953950539515395253953539545395553956539575395853959539605396153962539635396453965539665396753968539695397053971539725397353974539755397653977539785397953980539815398253983539845398553986539875398853989539905399153992539935399453995539965399753998539995400054001540025400354004540055400654007540085400954010540115401254013540145401554016540175401854019540205402154022540235402454025540265402754028540295403054031540325403354034540355403654037540385403954040540415404254043540445404554046540475404854049540505405154052540535405454055540565405754058540595406054061540625406354064540655406654067540685406954070540715407254073540745407554076540775407854079540805408154082540835408454085540865408754088540895409054091540925409354094540955409654097540985409954100541015410254103541045410554106541075410854109541105411154112541135411454115541165411754118541195412054121541225412354124541255412654127541285412954130541315413254133541345413554136541375413854139541405414154142541435414454145541465414754148541495415054151541525415354154541555415654157541585415954160541615416254163541645416554166541675416854169541705417154172541735417454175541765417754178541795418054181541825418354184541855418654187541885418954190541915419254193541945419554196541975419854199542005420154202542035420454205542065420754208542095421054211542125421354214542155421654217542185421954220542215422254223542245422554226542275422854229542305423154232542335423454235542365423754238542395424054241542425424354244542455424654247542485424954250542515425254253542545425554256542575425854259542605426154262542635426454265542665426754268542695427054271542725427354274542755427654277542785427954280542815428254283542845428554286542875428854289542905429154292542935429454295542965429754298542995430054301543025430354304543055430654307543085430954310543115431254313543145431554316543175431854319543205432154322543235432454325543265432754328543295433054331543325433354334543355433654337543385433954340543415434254343543445434554346543475434854349543505435154352543535435454355543565435754358543595436054361543625436354364543655436654367543685436954370543715437254373543745437554376543775437854379543805438154382543835438454385543865438754388543895439054391543925439354394543955439654397543985439954400544015440254403544045440554406544075440854409544105441154412544135441454415544165441754418544195442054421544225442354424544255442654427544285442954430544315443254433544345443554436544375443854439544405444154442544435444454445544465444754448544495445054451544525445354454544555445654457544585445954460544615446254463544645446554466544675446854469544705447154472544735447454475544765447754478544795448054481544825448354484544855448654487544885448954490544915449254493544945449554496544975449854499545005450154502545035450454505545065450754508545095451054511545125451354514545155451654517545185451954520545215452254523545245452554526545275452854529545305453154532545335453454535545365453754538545395454054541545425454354544545455454654547545485454954550545515455254553545545455554556545575455854559545605456154562545635456454565545665456754568545695457054571545725457354574545755457654577545785457954580545815458254583545845458554586545875458854589545905459154592545935459454595545965459754598545995460054601546025460354604546055460654607546085460954610546115461254613546145461554616546175461854619546205462154622546235462454625546265462754628546295463054631546325463354634546355463654637546385463954640546415464254643546445464554646546475464854649546505465154652546535465454655546565465754658546595466054661546625466354664546655466654667546685466954670546715467254673546745467554676546775467854679546805468154682546835468454685546865468754688546895469054691546925469354694546955469654697546985469954700547015470254703547045470554706547075470854709547105471154712547135471454715547165471754718547195472054721547225472354724547255472654727547285472954730547315473254733547345473554736547375473854739547405474154742547435474454745547465474754748547495475054751547525475354754547555475654757547585475954760547615476254763547645476554766547675476854769547705477154772547735477454775547765477754778547795478054781547825478354784547855478654787547885478954790547915479254793547945479554796547975479854799548005480154802548035480454805548065480754808548095481054811548125481354814548155481654817548185481954820548215482254823548245482554826548275482854829548305483154832548335483454835548365483754838548395484054841548425484354844548455484654847548485484954850548515485254853548545485554856548575485854859548605486154862548635486454865548665486754868548695487054871548725487354874548755487654877548785487954880548815488254883548845488554886548875488854889548905489154892548935489454895548965489754898548995490054901549025490354904549055490654907549085490954910549115491254913549145491554916549175491854919549205492154922549235492454925549265492754928549295493054931549325493354934549355493654937549385493954940549415494254943549445494554946549475494854949549505495154952549535495454955549565495754958549595496054961549625496354964549655496654967549685496954970549715497254973549745497554976549775497854979549805498154982549835498454985549865498754988549895499054991549925499354994549955499654997549985499955000550015500255003550045500555006550075500855009550105501155012550135501455015550165501755018550195502055021550225502355024550255502655027550285502955030550315503255033550345503555036550375503855039550405504155042550435504455045550465504755048550495505055051550525505355054550555505655057550585505955060550615506255063550645506555066550675506855069550705507155072550735507455075550765507755078550795508055081550825508355084550855508655087550885508955090550915509255093550945509555096550975509855099551005510155102551035510455105551065510755108551095511055111551125511355114551155511655117551185511955120551215512255123551245512555126551275512855129551305513155132551335513455135551365513755138551395514055141551425514355144551455514655147551485514955150551515515255153551545515555156551575515855159551605516155162551635516455165551665516755168551695517055171551725517355174551755517655177551785517955180551815518255183551845518555186551875518855189551905519155192551935519455195551965519755198551995520055201552025520355204552055520655207552085520955210552115521255213552145521555216552175521855219552205522155222552235522455225552265522755228552295523055231552325523355234552355523655237552385523955240552415524255243552445524555246552475524855249552505525155252552535525455255552565525755258552595526055261552625526355264552655526655267552685526955270552715527255273552745527555276552775527855279552805528155282552835528455285552865528755288552895529055291552925529355294552955529655297552985529955300553015530255303553045530555306553075530855309553105531155312553135531455315553165531755318553195532055321553225532355324553255532655327553285532955330553315533255333553345533555336553375533855339553405534155342553435534455345553465534755348553495535055351553525535355354553555535655357553585535955360553615536255363553645536555366553675536855369553705537155372553735537455375553765537755378553795538055381553825538355384553855538655387553885538955390553915539255393553945539555396553975539855399554005540155402554035540455405554065540755408554095541055411554125541355414554155541655417554185541955420554215542255423554245542555426554275542855429554305543155432554335543455435554365543755438554395544055441554425544355444554455544655447554485544955450554515545255453554545545555456554575545855459554605546155462554635546455465554665546755468554695547055471554725547355474554755547655477554785547955480554815548255483554845548555486554875548855489554905549155492554935549455495554965549755498554995550055501555025550355504555055550655507555085550955510555115551255513555145551555516555175551855519555205552155522555235552455525555265552755528555295553055531555325553355534555355553655537555385553955540555415554255543555445554555546555475554855549555505555155552555535555455555555565555755558555595556055561555625556355564555655556655567555685556955570555715557255573555745557555576555775557855579555805558155582555835558455585555865558755588555895559055591555925559355594555955559655597555985559955600556015560255603556045560555606556075560855609556105561155612556135561455615556165561755618556195562055621556225562355624556255562655627556285562955630556315563255633556345563555636556375563855639556405564155642556435564455645556465564755648556495565055651556525565355654556555565655657556585565955660556615566255663556645566555666556675566855669556705567155672556735567455675556765567755678556795568055681556825568355684556855568655687556885568955690556915569255693556945569555696556975569855699557005570155702557035570455705557065570755708557095571055711557125571355714557155571655717557185571955720557215572255723557245572555726557275572855729557305573155732557335573455735557365573755738557395574055741557425574355744557455574655747557485574955750557515575255753557545575555756557575575855759557605576155762557635576455765557665576755768557695577055771557725577355774557755577655777557785577955780557815578255783557845578555786557875578855789557905579155792557935579455795557965579755798557995580055801558025580355804558055580655807558085580955810558115581255813558145581555816558175581855819558205582155822558235582455825558265582755828558295583055831558325583355834558355583655837558385583955840558415584255843558445584555846558475584855849558505585155852558535585455855558565585755858558595586055861558625586355864558655586655867558685586955870558715587255873558745587555876558775587855879558805588155882558835588455885558865588755888558895589055891558925589355894558955589655897558985589955900559015590255903559045590555906559075590855909559105591155912559135591455915559165591755918559195592055921559225592355924559255592655927559285592955930559315593255933559345593555936559375593855939559405594155942559435594455945559465594755948559495595055951559525595355954559555595655957559585595955960559615596255963559645596555966559675596855969559705597155972559735597455975559765597755978559795598055981559825598355984559855598655987559885598955990559915599255993559945599555996559975599855999560005600156002560035600456005560065600756008560095601056011560125601356014560155601656017560185601956020560215602256023560245602556026560275602856029560305603156032560335603456035560365603756038560395604056041560425604356044560455604656047560485604956050560515605256053560545605556056560575605856059560605606156062560635606456065560665606756068560695607056071560725607356074560755607656077560785607956080560815608256083560845608556086560875608856089560905609156092560935609456095560965609756098560995610056101561025610356104561055610656107561085610956110561115611256113561145611556116561175611856119561205612156122561235612456125561265612756128561295613056131561325613356134561355613656137561385613956140561415614256143561445614556146561475614856149561505615156152561535615456155561565615756158561595616056161561625616356164561655616656167561685616956170561715617256173561745617556176561775617856179561805618156182561835618456185561865618756188561895619056191561925619356194561955619656197561985619956200562015620256203562045620556206562075620856209562105621156212562135621456215562165621756218562195622056221562225622356224562255622656227562285622956230562315623256233562345623556236562375623856239562405624156242562435624456245562465624756248562495625056251562525625356254562555625656257562585625956260562615626256263562645626556266562675626856269562705627156272562735627456275562765627756278562795628056281562825628356284562855628656287562885628956290562915629256293562945629556296562975629856299563005630156302563035630456305563065630756308563095631056311563125631356314563155631656317563185631956320563215632256323563245632556326563275632856329563305633156332563335633456335563365633756338563395634056341563425634356344563455634656347563485634956350563515635256353563545635556356563575635856359563605636156362563635636456365563665636756368563695637056371563725637356374563755637656377563785637956380563815638256383563845638556386563875638856389563905639156392563935639456395563965639756398563995640056401564025640356404564055640656407564085640956410564115641256413564145641556416564175641856419564205642156422564235642456425564265642756428564295643056431564325643356434564355643656437564385643956440564415644256443564445644556446564475644856449564505645156452564535645456455564565645756458564595646056461564625646356464564655646656467564685646956470564715647256473564745647556476564775647856479564805648156482564835648456485564865648756488564895649056491564925649356494564955649656497564985649956500565015650256503565045650556506565075650856509565105651156512565135651456515565165651756518565195652056521565225652356524565255652656527565285652956530565315653256533565345653556536565375653856539565405654156542565435654456545565465654756548565495655056551565525655356554565555655656557565585655956560565615656256563565645656556566565675656856569565705657156572565735657456575565765657756578565795658056581565825658356584565855658656587565885658956590565915659256593565945659556596565975659856599566005660156602566035660456605566065660756608566095661056611566125661356614566155661656617566185661956620566215662256623566245662556626566275662856629566305663156632566335663456635566365663756638566395664056641566425664356644566455664656647566485664956650566515665256653566545665556656566575665856659566605666156662566635666456665566665666756668566695667056671566725667356674566755667656677566785667956680566815668256683566845668556686566875668856689566905669156692566935669456695566965669756698566995670056701567025670356704567055670656707567085670956710567115671256713567145671556716567175671856719567205672156722567235672456725567265672756728567295673056731567325673356734567355673656737567385673956740567415674256743567445674556746567475674856749567505675156752567535675456755567565675756758567595676056761567625676356764567655676656767567685676956770567715677256773567745677556776567775677856779567805678156782567835678456785567865678756788567895679056791567925679356794567955679656797567985679956800568015680256803568045680556806568075680856809568105681156812568135681456815568165681756818568195682056821568225682356824568255682656827568285682956830568315683256833568345683556836568375683856839568405684156842568435684456845568465684756848568495685056851568525685356854568555685656857568585685956860568615686256863568645686556866568675686856869568705687156872568735687456875568765687756878568795688056881568825688356884568855688656887568885688956890568915689256893568945689556896568975689856899569005690156902569035690456905569065690756908569095691056911569125691356914569155691656917569185691956920569215692256923569245692556926569275692856929569305693156932569335693456935569365693756938569395694056941569425694356944569455694656947569485694956950569515695256953569545695556956569575695856959569605696156962569635696456965569665696756968569695697056971569725697356974569755697656977569785697956980569815698256983569845698556986569875698856989569905699156992569935699456995569965699756998569995700057001570025700357004570055700657007570085700957010570115701257013570145701557016570175701857019570205702157022570235702457025570265702757028570295703057031570325703357034570355703657037570385703957040570415704257043570445704557046570475704857049570505705157052570535705457055570565705757058570595706057061570625706357064570655706657067570685706957070570715707257073570745707557076570775707857079570805708157082570835708457085570865708757088570895709057091570925709357094570955709657097570985709957100571015710257103571045710557106571075710857109571105711157112571135711457115571165711757118571195712057121571225712357124571255712657127571285712957130571315713257133571345713557136571375713857139571405714157142571435714457145571465714757148571495715057151571525715357154571555715657157571585715957160571615716257163571645716557166571675716857169571705717157172571735717457175571765717757178571795718057181571825718357184571855718657187571885718957190571915719257193571945719557196571975719857199572005720157202572035720457205572065720757208572095721057211572125721357214572155721657217572185721957220572215722257223572245722557226572275722857229572305723157232572335723457235572365723757238572395724057241572425724357244572455724657247572485724957250572515725257253572545725557256572575725857259572605726157262572635726457265572665726757268572695727057271572725727357274572755727657277572785727957280572815728257283572845728557286572875728857289572905729157292572935729457295572965729757298572995730057301573025730357304573055730657307573085730957310573115731257313573145731557316573175731857319573205732157322573235732457325573265732757328573295733057331573325733357334573355733657337573385733957340573415734257343573445734557346573475734857349573505735157352573535735457355573565735757358573595736057361573625736357364573655736657367573685736957370573715737257373573745737557376573775737857379573805738157382573835738457385573865738757388573895739057391573925739357394573955739657397573985739957400574015740257403574045740557406574075740857409574105741157412574135741457415574165741757418574195742057421574225742357424574255742657427574285742957430574315743257433574345743557436574375743857439574405744157442574435744457445574465744757448574495745057451574525745357454574555745657457574585745957460574615746257463574645746557466574675746857469574705747157472574735747457475574765747757478574795748057481574825748357484574855748657487574885748957490574915749257493574945749557496574975749857499575005750157502575035750457505575065750757508575095751057511575125751357514575155751657517575185751957520575215752257523575245752557526575275752857529575305753157532575335753457535575365753757538575395754057541575425754357544575455754657547575485754957550575515755257553575545755557556575575755857559575605756157562575635756457565575665756757568575695757057571575725757357574575755757657577575785757957580575815758257583575845758557586575875758857589575905759157592575935759457595575965759757598575995760057601576025760357604576055760657607576085760957610576115761257613576145761557616576175761857619576205762157622576235762457625576265762757628576295763057631576325763357634576355763657637576385763957640576415764257643576445764557646576475764857649576505765157652576535765457655576565765757658576595766057661576625766357664576655766657667576685766957670576715767257673576745767557676576775767857679576805768157682576835768457685576865768757688576895769057691576925769357694576955769657697576985769957700577015770257703577045770557706577075770857709577105771157712577135771457715577165771757718577195772057721577225772357724577255772657727577285772957730577315773257733577345773557736577375773857739577405774157742577435774457745577465774757748577495775057751577525775357754577555775657757577585775957760577615776257763577645776557766577675776857769577705777157772577735777457775577765777757778577795778057781577825778357784577855778657787577885778957790577915779257793577945779557796577975779857799578005780157802578035780457805578065780757808578095781057811578125781357814578155781657817578185781957820578215782257823578245782557826578275782857829578305783157832578335783457835578365783757838578395784057841578425784357844578455784657847578485784957850578515785257853578545785557856578575785857859578605786157862578635786457865578665786757868578695787057871578725787357874578755787657877578785787957880578815788257883578845788557886578875788857889578905789157892578935789457895578965789757898578995790057901579025790357904579055790657907579085790957910579115791257913579145791557916579175791857919579205792157922579235792457925579265792757928579295793057931579325793357934579355793657937579385793957940579415794257943579445794557946579475794857949579505795157952579535795457955579565795757958579595796057961579625796357964579655796657967579685796957970579715797257973579745797557976579775797857979579805798157982579835798457985579865798757988579895799057991579925799357994579955799657997579985799958000580015800258003580045800558006580075800858009580105801158012580135801458015580165801758018580195802058021580225802358024580255802658027580285802958030580315803258033580345803558036580375803858039580405804158042580435804458045580465804758048580495805058051580525805358054580555805658057580585805958060580615806258063580645806558066580675806858069580705807158072580735807458075580765807758078580795808058081580825808358084580855808658087580885808958090580915809258093580945809558096580975809858099581005810158102581035810458105581065810758108581095811058111581125811358114581155811658117581185811958120581215812258123581245812558126581275812858129581305813158132581335813458135581365813758138581395814058141581425814358144581455814658147581485814958150581515815258153581545815558156581575815858159581605816158162581635816458165581665816758168581695817058171581725817358174581755817658177581785817958180581815818258183581845818558186581875818858189581905819158192581935819458195581965819758198581995820058201582025820358204582055820658207582085820958210582115821258213582145821558216582175821858219582205822158222582235822458225582265822758228582295823058231582325823358234582355823658237582385823958240582415824258243582445824558246582475824858249582505825158252582535825458255582565825758258582595826058261582625826358264582655826658267582685826958270582715827258273582745827558276582775827858279582805828158282582835828458285582865828758288582895829058291582925829358294582955829658297582985829958300583015830258303583045830558306583075830858309583105831158312583135831458315583165831758318583195832058321583225832358324583255832658327583285832958330583315833258333583345833558336583375833858339583405834158342583435834458345583465834758348583495835058351583525835358354583555835658357583585835958360583615836258363583645836558366583675836858369583705837158372583735837458375583765837758378583795838058381583825838358384583855838658387583885838958390583915839258393583945839558396583975839858399584005840158402584035840458405584065840758408584095841058411584125841358414584155841658417584185841958420584215842258423584245842558426584275842858429584305843158432584335843458435584365843758438584395844058441584425844358444584455844658447584485844958450584515845258453584545845558456584575845858459584605846158462584635846458465584665846758468584695847058471584725847358474584755847658477584785847958480584815848258483584845848558486584875848858489584905849158492584935849458495584965849758498584995850058501585025850358504585055850658507585085850958510585115851258513585145851558516585175851858519585205852158522585235852458525585265852758528585295853058531585325853358534585355853658537585385853958540585415854258543585445854558546585475854858549585505855158552585535855458555585565855758558585595856058561585625856358564585655856658567585685856958570585715857258573585745857558576585775857858579585805858158582585835858458585585865858758588585895859058591585925859358594585955859658597585985859958600586015860258603586045860558606586075860858609586105861158612586135861458615586165861758618586195862058621586225862358624586255862658627586285862958630586315863258633586345863558636586375863858639586405864158642586435864458645586465864758648586495865058651586525865358654586555865658657586585865958660586615866258663586645866558666586675866858669586705867158672586735867458675586765867758678586795868058681586825868358684586855868658687586885868958690586915869258693586945869558696586975869858699587005870158702587035870458705587065870758708587095871058711587125871358714587155871658717587185871958720587215872258723587245872558726587275872858729587305873158732587335873458735587365873758738587395874058741587425874358744587455874658747587485874958750587515875258753587545875558756587575875858759587605876158762587635876458765587665876758768587695877058771587725877358774587755877658777587785877958780587815878258783587845878558786587875878858789587905879158792587935879458795587965879758798587995880058801588025880358804588055880658807588085880958810588115881258813588145881558816588175881858819588205882158822588235882458825588265882758828588295883058831588325883358834588355883658837588385883958840588415884258843588445884558846588475884858849588505885158852588535885458855588565885758858588595886058861588625886358864588655886658867588685886958870588715887258873588745887558876588775887858879588805888158882588835888458885588865888758888588895889058891588925889358894588955889658897588985889958900589015890258903589045890558906589075890858909589105891158912589135891458915589165891758918589195892058921589225892358924589255892658927589285892958930589315893258933589345893558936589375893858939589405894158942589435894458945589465894758948589495895058951589525895358954589555895658957589585895958960589615896258963589645896558966589675896858969589705897158972589735897458975589765897758978589795898058981589825898358984589855898658987589885898958990589915899258993589945899558996589975899858999590005900159002590035900459005590065900759008590095901059011590125901359014590155901659017590185901959020590215902259023590245902559026590275902859029590305903159032590335903459035590365903759038590395904059041590425904359044590455904659047590485904959050590515905259053590545905559056590575905859059590605906159062590635906459065590665906759068590695907059071590725907359074590755907659077590785907959080590815908259083590845908559086590875908859089590905909159092590935909459095590965909759098590995910059101591025910359104591055910659107591085910959110591115911259113591145911559116591175911859119591205912159122591235912459125591265912759128591295913059131591325913359134591355913659137591385913959140591415914259143591445914559146591475914859149591505915159152591535915459155591565915759158591595916059161591625916359164591655916659167591685916959170591715917259173591745917559176591775917859179591805918159182591835918459185591865918759188591895919059191591925919359194591955919659197591985919959200592015920259203592045920559206592075920859209592105921159212592135921459215592165921759218592195922059221592225922359224592255922659227592285922959230592315923259233592345923559236592375923859239592405924159242592435924459245592465924759248592495925059251592525925359254592555925659257592585925959260592615926259263592645926559266592675926859269592705927159272592735927459275592765927759278592795928059281592825928359284592855928659287592885928959290592915929259293592945929559296592975929859299593005930159302593035930459305593065930759308593095931059311593125931359314593155931659317593185931959320593215932259323593245932559326593275932859329593305933159332593335933459335593365933759338593395934059341593425934359344593455934659347593485934959350593515935259353593545935559356593575935859359593605936159362593635936459365593665936759368593695937059371593725937359374593755937659377593785937959380593815938259383593845938559386593875938859389593905939159392593935939459395593965939759398593995940059401594025940359404594055940659407594085940959410594115941259413594145941559416594175941859419594205942159422594235942459425594265942759428594295943059431594325943359434594355943659437594385943959440594415944259443594445944559446594475944859449594505945159452594535945459455594565945759458594595946059461594625946359464594655946659467594685946959470594715947259473594745947559476594775947859479594805948159482594835948459485594865948759488594895949059491594925949359494594955949659497594985949959500595015950259503595045950559506595075950859509595105951159512595135951459515595165951759518595195952059521595225952359524595255952659527595285952959530595315953259533595345953559536595375953859539595405954159542595435954459545595465954759548595495955059551595525955359554595555955659557595585955959560595615956259563595645956559566595675956859569595705957159572595735957459575595765957759578595795958059581595825958359584595855958659587595885958959590595915959259593595945959559596595975959859599596005960159602596035960459605596065960759608596095961059611596125961359614596155961659617596185961959620596215962259623596245962559626596275962859629596305963159632596335963459635596365963759638596395964059641596425964359644596455964659647596485964959650596515965259653596545965559656596575965859659596605966159662596635966459665596665966759668596695967059671596725967359674596755967659677596785967959680596815968259683596845968559686596875968859689596905969159692596935969459695596965969759698596995970059701597025970359704597055970659707597085970959710597115971259713597145971559716597175971859719597205972159722597235972459725597265972759728597295973059731597325973359734597355973659737597385973959740597415974259743597445974559746597475974859749597505975159752597535975459755597565975759758597595976059761597625976359764597655976659767597685976959770597715977259773597745977559776597775977859779597805978159782597835978459785597865978759788597895979059791597925979359794597955979659797597985979959800598015980259803598045980559806598075980859809598105981159812598135981459815598165981759818598195982059821598225982359824598255982659827598285982959830598315983259833598345983559836598375983859839598405984159842598435984459845598465984759848598495985059851598525985359854598555985659857598585985959860598615986259863598645986559866598675986859869598705987159872598735987459875598765987759878598795988059881598825988359884598855988659887598885988959890598915989259893598945989559896598975989859899599005990159902599035990459905599065990759908599095991059911599125991359914599155991659917599185991959920599215992259923599245992559926599275992859929599305993159932599335993459935599365993759938599395994059941599425994359944599455994659947599485994959950599515995259953599545995559956599575995859959599605996159962599635996459965599665996759968599695997059971599725997359974599755997659977599785997959980599815998259983599845998559986599875998859989599905999159992599935999459995599965999759998599996000060001600026000360004600056000660007600086000960010600116001260013600146001560016600176001860019600206002160022600236002460025600266002760028600296003060031600326003360034600356003660037600386003960040600416004260043600446004560046600476004860049600506005160052600536005460055600566005760058600596006060061600626006360064600656006660067600686006960070600716007260073600746007560076600776007860079600806008160082600836008460085600866008760088600896009060091600926009360094600956009660097600986009960100601016010260103601046010560106601076010860109601106011160112601136011460115601166011760118601196012060121601226012360124601256012660127601286012960130601316013260133601346013560136601376013860139601406014160142601436014460145601466014760148601496015060151601526015360154601556015660157601586015960160601616016260163601646016560166601676016860169601706017160172601736017460175601766017760178601796018060181601826018360184601856018660187601886018960190601916019260193601946019560196601976019860199602006020160202602036020460205602066020760208602096021060211602126021360214602156021660217602186021960220602216022260223602246022560226602276022860229602306023160232602336023460235602366023760238602396024060241602426024360244602456024660247602486024960250602516025260253602546025560256602576025860259602606026160262602636026460265602666026760268602696027060271602726027360274602756027660277602786027960280602816028260283602846028560286602876028860289602906029160292602936029460295602966029760298602996030060301603026030360304603056030660307603086030960310603116031260313603146031560316603176031860319603206032160322603236032460325603266032760328603296033060331603326033360334603356033660337603386033960340603416034260343603446034560346603476034860349603506035160352603536035460355603566035760358603596036060361603626036360364603656036660367603686036960370603716037260373603746037560376603776037860379603806038160382603836038460385603866038760388603896039060391603926039360394603956039660397603986039960400604016040260403604046040560406604076040860409604106041160412604136041460415604166041760418604196042060421604226042360424604256042660427604286042960430604316043260433604346043560436604376043860439604406044160442604436044460445604466044760448604496045060451604526045360454604556045660457604586045960460604616046260463604646046560466604676046860469604706047160472604736047460475604766047760478604796048060481604826048360484604856048660487604886048960490604916049260493604946049560496604976049860499605006050160502605036050460505605066050760508605096051060511605126051360514605156051660517605186051960520605216052260523605246052560526605276052860529605306053160532605336053460535605366053760538605396054060541605426054360544605456054660547605486054960550605516055260553605546055560556605576055860559605606056160562605636056460565605666056760568605696057060571605726057360574605756057660577605786057960580605816058260583605846058560586605876058860589605906059160592605936059460595605966059760598605996060060601606026060360604606056060660607606086060960610606116061260613606146061560616606176061860619606206062160622606236062460625606266062760628606296063060631606326063360634606356063660637606386063960640606416064260643606446064560646606476064860649606506065160652606536065460655606566065760658606596066060661606626066360664606656066660667606686066960670606716067260673606746067560676606776067860679606806068160682606836068460685606866068760688606896069060691606926069360694606956069660697606986069960700607016070260703607046070560706607076070860709607106071160712607136071460715607166071760718607196072060721607226072360724607256072660727607286072960730607316073260733607346073560736607376073860739607406074160742607436074460745607466074760748607496075060751607526075360754607556075660757607586075960760607616076260763607646076560766607676076860769607706077160772607736077460775607766077760778607796078060781607826078360784607856078660787607886078960790607916079260793607946079560796607976079860799608006080160802608036080460805608066080760808608096081060811608126081360814608156081660817608186081960820608216082260823608246082560826608276082860829608306083160832608336083460835608366083760838608396084060841608426084360844608456084660847608486084960850608516085260853608546085560856608576085860859608606086160862608636086460865608666086760868608696087060871608726087360874608756087660877608786087960880608816088260883608846088560886608876088860889608906089160892608936089460895608966089760898608996090060901609026090360904609056090660907609086090960910609116091260913609146091560916609176091860919609206092160922609236092460925609266092760928609296093060931609326093360934609356093660937609386093960940609416094260943609446094560946609476094860949609506095160952609536095460955609566095760958609596096060961609626096360964609656096660967609686096960970609716097260973609746097560976609776097860979609806098160982609836098460985609866098760988609896099060991609926099360994609956099660997609986099961000610016100261003610046100561006610076100861009610106101161012610136101461015610166101761018610196102061021610226102361024610256102661027610286102961030610316103261033610346103561036610376103861039610406104161042610436104461045610466104761048610496105061051610526105361054610556105661057610586105961060610616106261063610646106561066610676106861069610706107161072610736107461075610766107761078610796108061081610826108361084610856108661087610886108961090610916109261093610946109561096610976109861099611006110161102611036110461105611066110761108611096111061111611126111361114611156111661117611186111961120611216112261123611246112561126611276112861129611306113161132611336113461135611366113761138611396114061141611426114361144611456114661147611486114961150611516115261153611546115561156611576115861159611606116161162611636116461165611666116761168611696117061171611726117361174611756117661177611786117961180611816118261183611846118561186611876118861189611906119161192611936119461195611966119761198611996120061201612026120361204612056120661207612086120961210612116121261213612146121561216612176121861219612206122161222612236122461225612266122761228612296123061231612326123361234612356123661237612386123961240612416124261243612446124561246612476124861249612506125161252612536125461255612566125761258612596126061261612626126361264612656126661267612686126961270612716127261273612746127561276612776127861279612806128161282612836128461285612866128761288612896129061291612926129361294612956129661297612986129961300613016130261303613046130561306613076130861309613106131161312613136131461315613166131761318613196132061321613226132361324613256132661327613286132961330613316133261333613346133561336613376133861339613406134161342613436134461345613466134761348613496135061351613526135361354613556135661357613586135961360613616136261363613646136561366613676136861369613706137161372613736137461375613766137761378613796138061381613826138361384613856138661387613886138961390613916139261393613946139561396613976139861399614006140161402614036140461405614066140761408614096141061411614126141361414614156141661417614186141961420614216142261423614246142561426614276142861429614306143161432614336143461435614366143761438614396144061441614426144361444614456144661447614486144961450614516145261453614546145561456614576145861459614606146161462614636146461465614666146761468614696147061471614726147361474614756147661477614786147961480614816148261483614846148561486614876148861489614906149161492614936149461495614966149761498614996150061501615026150361504615056150661507615086150961510615116151261513615146151561516615176151861519615206152161522615236152461525615266152761528615296153061531615326153361534615356153661537615386153961540615416154261543615446154561546615476154861549615506155161552615536155461555615566155761558615596156061561615626156361564615656156661567615686156961570615716157261573615746157561576615776157861579615806158161582615836158461585615866158761588615896159061591615926159361594615956159661597615986159961600616016160261603616046160561606616076160861609616106161161612616136161461615616166161761618616196162061621616226162361624616256162661627616286162961630616316163261633616346163561636616376163861639616406164161642616436164461645616466164761648616496165061651616526165361654616556165661657616586165961660616616166261663616646166561666616676166861669616706167161672616736167461675616766167761678616796168061681616826168361684616856168661687616886168961690616916169261693616946169561696616976169861699617006170161702617036170461705617066170761708617096171061711617126171361714617156171661717617186171961720617216172261723617246172561726617276172861729617306173161732617336173461735617366173761738617396174061741617426174361744617456174661747617486174961750617516175261753617546175561756617576175861759617606176161762617636176461765617666176761768617696177061771617726177361774617756177661777617786177961780617816178261783617846178561786617876178861789617906179161792617936179461795617966179761798617996180061801618026180361804618056180661807618086180961810618116181261813618146181561816618176181861819618206182161822618236182461825618266182761828618296183061831618326183361834618356183661837618386183961840618416184261843618446184561846618476184861849618506185161852618536185461855618566185761858618596186061861618626186361864618656186661867618686186961870618716187261873618746187561876618776187861879618806188161882618836188461885618866188761888618896189061891618926189361894618956189661897618986189961900619016190261903619046190561906619076190861909619106191161912619136191461915619166191761918619196192061921619226192361924619256192661927619286192961930619316193261933619346193561936619376193861939619406194161942619436194461945619466194761948619496195061951619526195361954619556195661957619586195961960619616196261963619646196561966619676196861969619706197161972619736197461975619766197761978619796198061981619826198361984619856198661987619886198961990619916199261993619946199561996619976199861999620006200162002620036200462005620066200762008620096201062011620126201362014620156201662017620186201962020620216202262023620246202562026620276202862029620306203162032620336203462035620366203762038620396204062041620426204362044620456204662047620486204962050620516205262053620546205562056620576205862059620606206162062620636206462065620666206762068620696207062071620726207362074620756207662077620786207962080620816208262083620846208562086620876208862089620906209162092620936209462095620966209762098620996210062101621026210362104621056210662107621086210962110621116211262113621146211562116621176211862119621206212162122621236212462125621266212762128621296213062131621326213362134621356213662137621386213962140621416214262143621446214562146621476214862149621506215162152621536215462155621566215762158621596216062161621626216362164621656216662167621686216962170621716217262173621746217562176621776217862179621806218162182621836218462185621866218762188621896219062191621926219362194621956219662197621986219962200622016220262203622046220562206622076220862209622106221162212622136221462215622166221762218622196222062221622226222362224622256222662227622286222962230622316223262233622346223562236622376223862239622406224162242622436224462245622466224762248622496225062251622526225362254622556225662257622586225962260622616226262263622646226562266622676226862269622706227162272622736227462275622766227762278622796228062281622826228362284622856228662287622886228962290622916229262293622946229562296622976229862299623006230162302623036230462305623066230762308623096231062311623126231362314623156231662317623186231962320623216232262323623246232562326623276232862329623306233162332623336233462335623366233762338623396234062341623426234362344623456234662347623486234962350623516235262353623546235562356623576235862359623606236162362623636236462365623666236762368623696237062371623726237362374623756237662377623786237962380623816238262383623846238562386623876238862389623906239162392623936239462395623966239762398623996240062401624026240362404624056240662407624086240962410624116241262413624146241562416624176241862419624206242162422624236242462425624266242762428624296243062431624326243362434624356243662437624386243962440624416244262443624446244562446624476244862449624506245162452624536245462455624566245762458624596246062461624626246362464624656246662467624686246962470624716247262473624746247562476624776247862479624806248162482624836248462485624866248762488624896249062491624926249362494624956249662497624986249962500625016250262503625046250562506625076250862509625106251162512625136251462515625166251762518625196252062521625226252362524625256252662527625286252962530625316253262533625346253562536625376253862539625406254162542625436254462545625466254762548625496255062551625526255362554625556255662557625586255962560625616256262563625646256562566625676256862569625706257162572625736257462575625766257762578625796258062581625826258362584625856258662587625886258962590625916259262593625946259562596625976259862599626006260162602626036260462605626066260762608626096261062611626126261362614626156261662617626186261962620626216262262623626246262562626626276262862629626306263162632626336263462635626366263762638626396264062641626426264362644626456264662647626486264962650626516265262653626546265562656626576265862659626606266162662626636266462665626666266762668626696267062671626726267362674626756267662677626786267962680626816268262683626846268562686626876268862689626906269162692626936269462695626966269762698626996270062701627026270362704627056270662707627086270962710627116271262713627146271562716627176271862719627206272162722627236272462725627266272762728627296273062731627326273362734627356273662737627386273962740627416274262743627446274562746627476274862749627506275162752627536275462755627566275762758627596276062761627626276362764627656276662767627686276962770627716277262773627746277562776627776277862779627806278162782627836278462785627866278762788627896279062791627926279362794627956279662797627986279962800628016280262803628046280562806628076280862809628106281162812628136281462815628166281762818628196282062821628226282362824628256282662827628286282962830628316283262833628346283562836628376283862839628406284162842628436284462845628466284762848628496285062851628526285362854628556285662857628586285962860628616286262863628646286562866628676286862869628706287162872628736287462875628766287762878628796288062881628826288362884628856288662887628886288962890628916289262893628946289562896628976289862899629006290162902629036290462905629066290762908629096291062911629126291362914629156291662917629186291962920629216292262923629246292562926629276292862929629306293162932629336293462935629366293762938629396294062941629426294362944629456294662947629486294962950629516295262953629546295562956629576295862959629606296162962629636296462965629666296762968629696297062971629726297362974629756297662977629786297962980629816298262983629846298562986629876298862989629906299162992629936299462995629966299762998629996300063001630026300363004630056300663007630086300963010630116301263013630146301563016630176301863019630206302163022630236302463025630266302763028630296303063031630326303363034630356303663037630386303963040630416304263043630446304563046630476304863049630506305163052630536305463055630566305763058630596306063061630626306363064630656306663067630686306963070630716307263073630746307563076630776307863079630806308163082630836308463085630866308763088630896309063091630926309363094630956309663097630986309963100631016310263103631046310563106631076310863109631106311163112631136311463115631166311763118631196312063121631226312363124631256312663127631286312963130631316313263133631346313563136631376313863139631406314163142631436314463145631466314763148631496315063151631526315363154631556315663157631586315963160631616316263163631646316563166631676316863169631706317163172631736317463175631766317763178631796318063181631826318363184631856318663187631886318963190631916319263193631946319563196631976319863199632006320163202632036320463205632066320763208632096321063211632126321363214632156321663217632186321963220632216322263223632246322563226632276322863229632306323163232632336323463235632366323763238632396324063241632426324363244632456324663247632486324963250632516325263253632546325563256632576325863259632606326163262632636326463265632666326763268632696327063271632726327363274632756327663277632786327963280632816328263283632846328563286632876328863289632906329163292632936329463295632966329763298632996330063301633026330363304633056330663307633086330963310633116331263313633146331563316633176331863319633206332163322633236332463325633266332763328633296333063331633326333363334633356333663337633386333963340633416334263343633446334563346633476334863349633506335163352633536335463355633566335763358633596336063361633626336363364633656336663367633686336963370633716337263373633746337563376633776337863379633806338163382633836338463385633866338763388633896339063391633926339363394633956339663397633986339963400634016340263403634046340563406634076340863409634106341163412634136341463415634166341763418634196342063421634226342363424634256342663427634286342963430634316343263433634346343563436634376343863439634406344163442634436344463445634466344763448634496345063451634526345363454634556345663457634586345963460634616346263463634646346563466634676346863469634706347163472634736347463475634766347763478634796348063481634826348363484634856348663487634886348963490634916349263493634946349563496634976349863499635006350163502635036350463505635066350763508635096351063511635126351363514635156351663517635186351963520635216352263523635246352563526635276352863529635306353163532635336353463535635366353763538635396354063541635426354363544635456354663547635486354963550635516355263553635546355563556635576355863559635606356163562635636356463565635666356763568635696357063571635726357363574635756357663577635786357963580635816358263583635846358563586635876358863589635906359163592635936359463595635966359763598635996360063601636026360363604636056360663607636086360963610636116361263613636146361563616636176361863619636206362163622636236362463625636266362763628636296363063631636326363363634636356363663637636386363963640636416364263643636446364563646636476364863649636506365163652636536365463655636566365763658636596366063661636626366363664636656366663667636686366963670636716367263673636746367563676636776367863679636806368163682636836368463685636866368763688636896369063691636926369363694636956369663697636986369963700637016370263703637046370563706637076370863709637106371163712637136371463715637166371763718637196372063721637226372363724637256372663727637286372963730637316373263733637346373563736637376373863739637406374163742637436374463745637466374763748637496375063751637526375363754637556375663757637586375963760637616376263763637646376563766637676376863769637706377163772637736377463775637766377763778637796378063781637826378363784637856378663787637886378963790637916379263793637946379563796637976379863799638006380163802638036380463805638066380763808638096381063811638126381363814638156381663817638186381963820638216382263823638246382563826638276382863829638306383163832638336383463835638366383763838638396384063841638426384363844638456384663847638486384963850638516385263853638546385563856638576385863859638606386163862638636386463865638666386763868638696387063871638726387363874638756387663877638786387963880638816388263883638846388563886638876388863889638906389163892638936389463895638966389763898638996390063901639026390363904639056390663907639086390963910639116391263913639146391563916639176391863919639206392163922639236392463925639266392763928639296393063931639326393363934639356393663937639386393963940639416394263943639446394563946639476394863949639506395163952639536395463955639566395763958639596396063961639626396363964639656396663967639686396963970639716397263973639746397563976639776397863979639806398163982639836398463985639866398763988639896399063991639926399363994639956399663997639986399964000640016400264003640046400564006640076400864009640106401164012640136401464015640166401764018640196402064021640226402364024640256402664027640286402964030640316403264033640346403564036640376403864039640406404164042640436404464045640466404764048640496405064051640526405364054640556405664057640586405964060640616406264063640646406564066640676406864069640706407164072640736407464075640766407764078640796408064081640826408364084640856408664087640886408964090640916409264093640946409564096640976409864099641006410164102641036410464105641066410764108641096411064111641126411364114641156411664117641186411964120641216412264123641246412564126641276412864129641306413164132641336413464135641366413764138641396414064141641426414364144641456414664147641486414964150641516415264153641546415564156641576415864159641606416164162641636416464165641666416764168641696417064171641726417364174641756417664177641786417964180641816418264183641846418564186641876418864189641906419164192641936419464195641966419764198641996420064201642026420364204642056420664207642086420964210642116421264213642146421564216642176421864219642206422164222642236422464225642266422764228642296423064231642326423364234642356423664237642386423964240642416424264243642446424564246642476424864249642506425164252642536425464255642566425764258642596426064261642626426364264642656426664267642686426964270642716427264273642746427564276642776427864279642806428164282642836428464285642866428764288642896429064291642926429364294642956429664297642986429964300643016430264303643046430564306643076430864309643106431164312643136431464315643166431764318643196432064321643226432364324643256432664327643286432964330643316433264333643346433564336643376433864339643406434164342643436434464345643466434764348643496435064351643526435364354643556435664357643586435964360643616436264363643646436564366643676436864369643706437164372643736437464375643766437764378643796438064381643826438364384643856438664387643886438964390643916439264393643946439564396643976439864399644006440164402644036440464405644066440764408644096441064411644126441364414644156441664417644186441964420644216442264423644246442564426644276442864429644306443164432644336443464435644366443764438644396444064441644426444364444644456444664447644486444964450644516445264453644546445564456644576445864459644606446164462644636446464465644666446764468644696447064471644726447364474644756447664477644786447964480644816448264483644846448564486644876448864489644906449164492644936449464495644966449764498644996450064501645026450364504645056450664507645086450964510645116451264513645146451564516645176451864519645206452164522645236452464525645266452764528645296453064531645326453364534645356453664537645386453964540645416454264543645446454564546645476454864549645506455164552645536455464555645566455764558645596456064561645626456364564645656456664567645686456964570645716457264573645746457564576645776457864579645806458164582645836458464585645866458764588645896459064591645926459364594645956459664597645986459964600646016460264603646046460564606646076460864609646106461164612646136461464615646166461764618646196462064621646226462364624646256462664627646286462964630646316463264633646346463564636646376463864639646406464164642646436464464645646466464764648646496465064651646526465364654646556465664657646586465964660646616466264663646646466564666646676466864669646706467164672646736467464675646766467764678646796468064681646826468364684646856468664687646886468964690646916469264693646946469564696646976469864699647006470164702647036470464705647066470764708647096471064711647126471364714647156471664717647186471964720647216472264723647246472564726647276472864729647306473164732647336473464735647366473764738647396474064741647426474364744647456474664747647486474964750647516475264753647546475564756647576475864759647606476164762647636476464765647666476764768647696477064771647726477364774647756477664777647786477964780647816478264783647846478564786647876478864789647906479164792647936479464795647966479764798647996480064801648026480364804648056480664807648086480964810648116481264813648146481564816648176481864819648206482164822648236482464825648266482764828648296483064831648326483364834648356483664837648386483964840648416484264843648446484564846648476484864849648506485164852648536485464855648566485764858648596486064861648626486364864648656486664867648686486964870648716487264873648746487564876648776487864879648806488164882648836488464885648866488764888648896489064891648926489364894648956489664897648986489964900649016490264903649046490564906649076490864909649106491164912649136491464915649166491764918649196492064921649226492364924649256492664927649286492964930649316493264933649346493564936649376493864939649406494164942649436494464945649466494764948649496495064951649526495364954649556495664957649586495964960649616496264963649646496564966649676496864969649706497164972649736497464975649766497764978649796498064981649826498364984649856498664987649886498964990649916499264993649946499564996649976499864999650006500165002650036500465005650066500765008650096501065011650126501365014650156501665017650186501965020650216502265023650246502565026650276502865029650306503165032650336503465035650366503765038650396504065041650426504365044650456504665047650486504965050650516505265053650546505565056650576505865059650606506165062650636506465065650666506765068650696507065071650726507365074650756507665077650786507965080650816508265083650846508565086650876508865089650906509165092650936509465095650966509765098650996510065101651026510365104651056510665107651086510965110651116511265113651146511565116651176511865119651206512165122651236512465125651266512765128651296513065131651326513365134651356513665137651386513965140651416514265143651446514565146651476514865149651506515165152651536515465155651566515765158651596516065161651626516365164651656516665167651686516965170651716517265173651746517565176651776517865179651806518165182651836518465185651866518765188651896519065191651926519365194651956519665197651986519965200652016520265203652046520565206652076520865209652106521165212652136521465215652166521765218652196522065221652226522365224652256522665227652286522965230652316523265233652346523565236652376523865239652406524165242652436524465245652466524765248652496525065251652526525365254652556525665257652586525965260652616526265263652646526565266652676526865269652706527165272652736527465275652766527765278652796528065281652826528365284652856528665287652886528965290652916529265293652946529565296652976529865299653006530165302653036530465305653066530765308653096531065311653126531365314653156531665317653186531965320653216532265323653246532565326653276532865329653306533165332653336533465335653366533765338653396534065341653426534365344653456534665347653486534965350653516535265353653546535565356653576535865359653606536165362653636536465365653666536765368653696537065371653726537365374653756537665377653786537965380653816538265383653846538565386653876538865389653906539165392653936539465395653966539765398653996540065401654026540365404654056540665407654086540965410654116541265413654146541565416654176541865419654206542165422654236542465425654266542765428654296543065431654326543365434654356543665437654386543965440654416544265443654446544565446654476544865449654506545165452654536545465455654566545765458654596546065461654626546365464654656546665467654686546965470654716547265473654746547565476654776547865479654806548165482654836548465485654866548765488654896549065491654926549365494654956549665497654986549965500655016550265503655046550565506655076550865509655106551165512655136551465515655166551765518655196552065521655226552365524655256552665527655286552965530655316553265533655346553565536655376553865539655406554165542655436554465545655466554765548655496555065551655526555365554655556555665557655586555965560655616556265563655646556565566655676556865569655706557165572655736557465575655766557765578655796558065581655826558365584655856558665587655886558965590655916559265593655946559565596655976559865599656006560165602656036560465605656066560765608656096561065611656126561365614656156561665617656186561965620656216562265623656246562565626656276562865629656306563165632656336563465635656366563765638656396564065641656426564365644656456564665647656486564965650656516565265653656546565565656656576565865659656606566165662656636566465665656666566765668656696567065671656726567365674656756567665677656786567965680656816568265683656846568565686656876568865689656906569165692656936569465695656966569765698656996570065701657026570365704657056570665707657086570965710657116571265713657146571565716657176571865719657206572165722657236572465725657266572765728657296573065731657326573365734657356573665737657386573965740657416574265743657446574565746657476574865749657506575165752657536575465755657566575765758657596576065761657626576365764657656576665767657686576965770657716577265773657746577565776657776577865779657806578165782657836578465785657866578765788657896579065791657926579365794657956579665797657986579965800658016580265803658046580565806658076580865809658106581165812658136581465815658166581765818658196582065821658226582365824658256582665827658286582965830658316583265833658346583565836658376583865839658406584165842658436584465845658466584765848658496585065851658526585365854658556585665857658586585965860658616586265863658646586565866658676586865869658706587165872658736587465875658766587765878658796588065881658826588365884658856588665887658886588965890658916589265893658946589565896658976589865899659006590165902659036590465905659066590765908659096591065911659126591365914659156591665917659186591965920659216592265923659246592565926659276592865929659306593165932659336593465935659366593765938659396594065941659426594365944659456594665947659486594965950659516595265953659546595565956659576595865959659606596165962659636596465965659666596765968659696597065971659726597365974659756597665977659786597965980659816598265983659846598565986659876598865989659906599165992659936599465995659966599765998659996600066001660026600366004660056600666007660086600966010660116601266013660146601566016660176601866019660206602166022660236602466025660266602766028660296603066031660326603366034660356603666037660386603966040660416604266043660446604566046660476604866049660506605166052660536605466055660566605766058660596606066061660626606366064660656606666067660686606966070660716607266073660746607566076660776607866079660806608166082660836608466085660866608766088660896609066091660926609366094660956609666097660986609966100661016610266103661046610566106661076610866109661106611166112661136611466115661166611766118661196612066121661226612366124661256612666127661286612966130661316613266133661346613566136661376613866139661406614166142661436614466145661466614766148661496615066151661526615366154661556615666157661586615966160661616616266163661646616566166661676616866169661706617166172661736617466175661766617766178661796618066181661826618366184661856618666187661886618966190661916619266193661946619566196661976619866199662006620166202662036620466205662066620766208662096621066211662126621366214662156621666217662186621966220662216622266223662246622566226662276622866229662306623166232662336623466235662366623766238662396624066241662426624366244662456624666247662486624966250662516625266253662546625566256662576625866259662606626166262662636626466265662666626766268662696627066271662726627366274662756627666277662786627966280662816628266283662846628566286662876628866289662906629166292662936629466295662966629766298662996630066301663026630366304663056630666307663086630966310663116631266313663146631566316663176631866319663206632166322663236632466325663266632766328663296633066331663326633366334663356633666337663386633966340663416634266343663446634566346663476634866349663506635166352663536635466355663566635766358663596636066361663626636366364663656636666367663686636966370663716637266373663746637566376663776637866379663806638166382663836638466385663866638766388663896639066391663926639366394663956639666397663986639966400664016640266403664046640566406664076640866409664106641166412664136641466415664166641766418664196642066421664226642366424664256642666427664286642966430664316643266433664346643566436664376643866439664406644166442664436644466445664466644766448664496645066451664526645366454664556645666457664586645966460664616646266463664646646566466664676646866469664706647166472664736647466475664766647766478664796648066481664826648366484664856648666487664886648966490664916649266493664946649566496664976649866499665006650166502665036650466505665066650766508665096651066511665126651366514665156651666517665186651966520665216652266523665246652566526665276652866529665306653166532665336653466535665366653766538665396654066541665426654366544665456654666547665486654966550665516655266553665546655566556665576655866559665606656166562665636656466565665666656766568665696657066571665726657366574665756657666577665786657966580665816658266583665846658566586665876658866589665906659166592665936659466595665966659766598665996660066601666026660366604666056660666607666086660966610666116661266613666146661566616666176661866619666206662166622666236662466625666266662766628666296663066631666326663366634666356663666637666386663966640666416664266643666446664566646666476664866649666506665166652666536665466655666566665766658666596666066661666626666366664666656666666667666686666966670666716667266673666746667566676666776667866679666806668166682666836668466685666866668766688666896669066691666926669366694666956669666697666986669966700667016670266703667046670566706667076670866709667106671166712667136671466715667166671766718667196672066721667226672366724667256672666727667286672966730667316673266733667346673566736667376673866739667406674166742667436674466745667466674766748667496675066751667526675366754667556675666757667586675966760667616676266763667646676566766667676676866769667706677166772667736677466775667766677766778667796678066781667826678366784667856678666787667886678966790667916679266793667946679566796667976679866799668006680166802668036680466805668066680766808668096681066811668126681366814668156681666817668186681966820668216682266823668246682566826668276682866829668306683166832668336683466835668366683766838668396684066841668426684366844668456684666847668486684966850668516685266853668546685566856668576685866859668606686166862668636686466865668666686766868668696687066871668726687366874668756687666877668786687966880668816688266883668846688566886668876688866889668906689166892668936689466895668966689766898668996690066901669026690366904669056690666907669086690966910669116691266913669146691566916669176691866919669206692166922669236692466925669266692766928669296693066931669326693366934669356693666937669386693966940669416694266943669446694566946669476694866949669506695166952669536695466955669566695766958669596696066961669626696366964669656696666967669686696966970669716697266973669746697566976669776697866979669806698166982669836698466985669866698766988669896699066991669926699366994669956699666997669986699967000670016700267003670046700567006670076700867009670106701167012670136701467015670166701767018670196702067021670226702367024670256702667027670286702967030670316703267033670346703567036670376703867039670406704167042670436704467045670466704767048670496705067051670526705367054670556705667057670586705967060670616706267063670646706567066670676706867069670706707167072670736707467075670766707767078670796708067081670826708367084670856708667087670886708967090670916709267093670946709567096670976709867099671006710167102671036710467105671066710767108671096711067111671126711367114671156711667117671186711967120671216712267123671246712567126671276712867129671306713167132671336713467135671366713767138671396714067141671426714367144671456714667147671486714967150671516715267153671546715567156671576715867159671606716167162671636716467165671666716767168671696717067171671726717367174671756717667177671786717967180671816718267183671846718567186671876718867189671906719167192671936719467195671966719767198671996720067201672026720367204672056720667207672086720967210672116721267213672146721567216672176721867219672206722167222672236722467225672266722767228672296723067231672326723367234672356723667237672386723967240672416724267243672446724567246672476724867249672506725167252672536725467255672566725767258672596726067261672626726367264672656726667267672686726967270672716727267273672746727567276672776727867279672806728167282672836728467285672866728767288672896729067291672926729367294672956729667297672986729967300673016730267303673046730567306673076730867309673106731167312673136731467315673166731767318673196732067321673226732367324673256732667327673286732967330673316733267333673346733567336673376733867339673406734167342673436734467345673466734767348673496735067351673526735367354673556735667357673586735967360673616736267363673646736567366673676736867369673706737167372673736737467375673766737767378673796738067381673826738367384673856738667387673886738967390673916739267393673946739567396673976739867399674006740167402674036740467405674066740767408674096741067411674126741367414674156741667417674186741967420674216742267423674246742567426674276742867429674306743167432674336743467435674366743767438674396744067441674426744367444674456744667447674486744967450674516745267453674546745567456674576745867459674606746167462674636746467465674666746767468674696747067471674726747367474674756747667477674786747967480674816748267483674846748567486674876748867489674906749167492674936749467495674966749767498674996750067501675026750367504675056750667507675086750967510675116751267513675146751567516675176751867519675206752167522675236752467525675266752767528675296753067531675326753367534675356753667537675386753967540675416754267543675446754567546675476754867549675506755167552675536755467555675566755767558675596756067561675626756367564675656756667567675686756967570675716757267573675746757567576675776757867579675806758167582675836758467585675866758767588675896759067591675926759367594675956759667597675986759967600676016760267603676046760567606676076760867609676106761167612676136761467615676166761767618676196762067621676226762367624676256762667627676286762967630676316763267633676346763567636676376763867639676406764167642676436764467645676466764767648676496765067651676526765367654676556765667657676586765967660676616766267663676646766567666676676766867669676706767167672676736767467675676766767767678676796768067681676826768367684676856768667687676886768967690676916769267693676946769567696676976769867699677006770167702677036770467705677066770767708677096771067711677126771367714677156771667717677186771967720677216772267723677246772567726677276772867729677306773167732677336773467735677366773767738677396774067741677426774367744677456774667747677486774967750677516775267753677546775567756677576775867759677606776167762677636776467765677666776767768677696777067771677726777367774677756777667777677786777967780677816778267783677846778567786677876778867789677906779167792677936779467795677966779767798677996780067801678026780367804678056780667807678086780967810678116781267813678146781567816678176781867819678206782167822678236782467825678266782767828678296783067831678326783367834678356783667837678386783967840678416784267843678446784567846678476784867849678506785167852678536785467855678566785767858678596786067861678626786367864678656786667867678686786967870678716787267873678746787567876678776787867879678806788167882678836788467885678866788767888678896789067891678926789367894678956789667897678986789967900679016790267903679046790567906679076790867909679106791167912679136791467915679166791767918679196792067921679226792367924679256792667927679286792967930679316793267933679346793567936679376793867939679406794167942679436794467945679466794767948679496795067951679526795367954679556795667957679586795967960679616796267963679646796567966679676796867969679706797167972679736797467975679766797767978679796798067981679826798367984679856798667987679886798967990679916799267993679946799567996679976799867999680006800168002680036800468005680066800768008680096801068011680126801368014680156801668017680186801968020680216802268023680246802568026680276802868029680306803168032680336803468035680366803768038680396804068041680426804368044680456804668047680486804968050680516805268053680546805568056680576805868059680606806168062680636806468065680666806768068680696807068071680726807368074680756807668077680786807968080680816808268083680846808568086680876808868089680906809168092680936809468095680966809768098680996810068101681026810368104681056810668107681086810968110681116811268113681146811568116681176811868119681206812168122681236812468125681266812768128681296813068131681326813368134681356813668137681386813968140681416814268143681446814568146681476814868149681506815168152681536815468155681566815768158681596816068161681626816368164681656816668167681686816968170681716817268173681746817568176681776817868179681806818168182681836818468185681866818768188681896819068191681926819368194681956819668197681986819968200682016820268203682046820568206682076820868209682106821168212682136821468215682166821768218682196822068221682226822368224682256822668227682286822968230682316823268233682346823568236682376823868239682406824168242682436824468245682466824768248682496825068251682526825368254682556825668257682586825968260682616826268263682646826568266682676826868269682706827168272682736827468275682766827768278682796828068281682826828368284682856828668287682886828968290682916829268293682946829568296682976829868299683006830168302683036830468305683066830768308683096831068311683126831368314683156831668317683186831968320683216832268323683246832568326683276832868329683306833168332683336833468335683366833768338683396834068341683426834368344683456834668347683486834968350683516835268353683546835568356683576835868359683606836168362683636836468365683666836768368683696837068371683726837368374683756837668377683786837968380683816838268383683846838568386683876838868389683906839168392683936839468395683966839768398683996840068401684026840368404684056840668407684086840968410684116841268413684146841568416684176841868419684206842168422684236842468425684266842768428684296843068431684326843368434684356843668437684386843968440684416844268443684446844568446684476844868449684506845168452684536845468455684566845768458684596846068461684626846368464684656846668467684686846968470684716847268473684746847568476684776847868479684806848168482684836848468485684866848768488684896849068491684926849368494684956849668497684986849968500685016850268503685046850568506685076850868509685106851168512685136851468515685166851768518685196852068521685226852368524685256852668527685286852968530685316853268533685346853568536685376853868539685406854168542685436854468545685466854768548685496855068551685526855368554685556855668557685586855968560685616856268563685646856568566685676856868569685706857168572685736857468575685766857768578685796858068581685826858368584685856858668587685886858968590685916859268593685946859568596685976859868599686006860168602686036860468605686066860768608686096861068611686126861368614686156861668617686186861968620686216862268623686246862568626686276862868629686306863168632686336863468635686366863768638686396864068641686426864368644686456864668647686486864968650686516865268653686546865568656686576865868659686606866168662686636866468665686666866768668686696867068671686726867368674686756867668677686786867968680686816868268683686846868568686686876868868689686906869168692686936869468695686966869768698686996870068701687026870368704687056870668707687086870968710687116871268713687146871568716687176871868719687206872168722687236872468725687266872768728687296873068731687326873368734687356873668737687386873968740687416874268743687446874568746687476874868749687506875168752687536875468755687566875768758687596876068761687626876368764687656876668767687686876968770687716877268773687746877568776687776877868779687806878168782687836878468785687866878768788687896879068791687926879368794687956879668797687986879968800688016880268803688046880568806688076880868809688106881168812688136881468815688166881768818688196882068821688226882368824688256882668827688286882968830688316883268833688346883568836688376883868839688406884168842688436884468845688466884768848688496885068851688526885368854688556885668857688586885968860688616886268863688646886568866688676886868869688706887168872688736887468875688766887768878688796888068881688826888368884688856888668887688886888968890688916889268893688946889568896688976889868899689006890168902689036890468905689066890768908689096891068911689126891368914689156891668917689186891968920689216892268923689246892568926689276892868929689306893168932689336893468935689366893768938689396894068941689426894368944689456894668947689486894968950689516895268953689546895568956689576895868959689606896168962689636896468965689666896768968689696897068971689726897368974689756897668977689786897968980689816898268983689846898568986689876898868989689906899168992689936899468995689966899768998689996900069001690026900369004690056900669007690086900969010690116901269013690146901569016690176901869019690206902169022690236902469025690266902769028690296903069031690326903369034690356903669037690386903969040690416904269043690446904569046690476904869049690506905169052690536905469055690566905769058690596906069061690626906369064690656906669067690686906969070690716907269073690746907569076690776907869079690806908169082690836908469085690866908769088690896909069091690926909369094690956909669097690986909969100691016910269103691046910569106691076910869109691106911169112691136911469115691166911769118691196912069121691226912369124691256912669127691286912969130691316913269133691346913569136691376913869139691406914169142691436914469145691466914769148691496915069151691526915369154691556915669157691586915969160691616916269163691646916569166691676916869169691706917169172691736917469175691766917769178691796918069181691826918369184691856918669187691886918969190691916919269193691946919569196691976919869199692006920169202692036920469205692066920769208692096921069211692126921369214692156921669217692186921969220692216922269223692246922569226692276922869229692306923169232692336923469235692366923769238692396924069241692426924369244692456924669247692486924969250692516925269253692546925569256692576925869259692606926169262692636926469265692666926769268692696927069271692726927369274692756927669277692786927969280692816928269283692846928569286692876928869289692906929169292692936929469295692966929769298692996930069301693026930369304693056930669307693086930969310693116931269313693146931569316693176931869319693206932169322693236932469325693266932769328693296933069331693326933369334693356933669337693386933969340693416934269343693446934569346693476934869349693506935169352693536935469355693566935769358693596936069361693626936369364693656936669367693686936969370693716937269373693746937569376693776937869379693806938169382693836938469385693866938769388693896939069391693926939369394693956939669397693986939969400694016940269403694046940569406694076940869409694106941169412694136941469415694166941769418694196942069421694226942369424694256942669427694286942969430694316943269433694346943569436694376943869439694406944169442694436944469445694466944769448694496945069451694526945369454694556945669457694586945969460694616946269463694646946569466694676946869469694706947169472694736947469475694766947769478694796948069481694826948369484694856948669487694886948969490694916949269493694946949569496694976949869499695006950169502695036950469505695066950769508695096951069511695126951369514695156951669517695186951969520695216952269523695246952569526695276952869529695306953169532695336953469535695366953769538695396954069541695426954369544695456954669547695486954969550695516955269553695546955569556695576955869559695606956169562695636956469565695666956769568695696957069571695726957369574695756957669577695786957969580695816958269583695846958569586695876958869589695906959169592695936959469595695966959769598695996960069601696026960369604696056960669607696086960969610696116961269613696146961569616696176961869619696206962169622696236962469625696266962769628696296963069631696326963369634696356963669637696386963969640696416964269643696446964569646696476964869649696506965169652696536965469655696566965769658696596966069661696626966369664696656966669667696686966969670696716967269673696746967569676696776967869679696806968169682696836968469685696866968769688696896969069691696926969369694696956969669697696986969969700697016970269703697046970569706697076970869709697106971169712697136971469715697166971769718697196972069721697226972369724697256972669727697286972969730697316973269733697346973569736697376973869739697406974169742697436974469745697466974769748697496975069751697526975369754697556975669757697586975969760697616976269763697646976569766697676976869769697706977169772697736977469775697766977769778697796978069781697826978369784697856978669787697886978969790697916979269793697946979569796697976979869799698006980169802698036980469805698066980769808698096981069811698126981369814698156981669817698186981969820698216982269823698246982569826698276982869829698306983169832698336983469835698366983769838698396984069841698426984369844698456984669847698486984969850698516985269853698546985569856698576985869859698606986169862698636986469865698666986769868698696987069871698726987369874698756987669877698786987969880698816988269883698846988569886698876988869889698906989169892698936989469895698966989769898698996990069901699026990369904699056990669907699086990969910699116991269913699146991569916699176991869919699206992169922699236992469925699266992769928699296993069931699326993369934699356993669937699386993969940699416994269943699446994569946699476994869949699506995169952699536995469955699566995769958699596996069961699626996369964699656996669967699686996969970699716997269973699746997569976699776997869979699806998169982699836998469985699866998769988699896999069991699926999369994699956999669997699986999970000700017000270003700047000570006700077000870009700107001170012700137001470015700167001770018700197002070021700227002370024700257002670027700287002970030700317003270033700347003570036700377003870039700407004170042700437004470045700467004770048700497005070051700527005370054700557005670057700587005970060700617006270063700647006570066700677006870069700707007170072700737007470075700767007770078700797008070081700827008370084700857008670087700887008970090700917009270093700947009570096700977009870099701007010170102701037010470105701067010770108701097011070111701127011370114701157011670117701187011970120701217012270123701247012570126701277012870129701307013170132701337013470135701367013770138701397014070141701427014370144701457014670147701487014970150701517015270153701547015570156701577015870159701607016170162701637016470165701667016770168701697017070171701727017370174701757017670177701787017970180701817018270183701847018570186701877018870189701907019170192701937019470195701967019770198701997020070201702027020370204702057020670207702087020970210702117021270213702147021570216702177021870219702207022170222702237022470225702267022770228702297023070231702327023370234702357023670237702387023970240702417024270243702447024570246702477024870249702507025170252702537025470255702567025770258702597026070261702627026370264702657026670267702687026970270702717027270273702747027570276702777027870279702807028170282702837028470285702867028770288702897029070291702927029370294702957029670297702987029970300703017030270303703047030570306703077030870309703107031170312703137031470315703167031770318703197032070321703227032370324703257032670327703287032970330703317033270333703347033570336703377033870339703407034170342703437034470345703467034770348703497035070351703527035370354703557035670357703587035970360703617036270363703647036570366703677036870369703707037170372703737037470375703767037770378703797038070381703827038370384703857038670387703887038970390703917039270393703947039570396703977039870399704007040170402704037040470405704067040770408704097041070411704127041370414704157041670417704187041970420704217042270423704247042570426704277042870429704307043170432704337043470435704367043770438704397044070441704427044370444704457044670447704487044970450704517045270453704547045570456704577045870459704607046170462704637046470465704667046770468704697047070471704727047370474704757047670477704787047970480704817048270483704847048570486704877048870489704907049170492704937049470495704967049770498704997050070501705027050370504705057050670507705087050970510705117051270513705147051570516705177051870519705207052170522705237052470525705267052770528705297053070531705327053370534705357053670537705387053970540705417054270543705447054570546705477054870549705507055170552705537055470555705567055770558705597056070561705627056370564705657056670567705687056970570705717057270573705747057570576705777057870579705807058170582705837058470585705867058770588705897059070591705927059370594705957059670597705987059970600706017060270603706047060570606706077060870609706107061170612706137061470615706167061770618706197062070621706227062370624706257062670627706287062970630706317063270633706347063570636706377063870639706407064170642706437064470645706467064770648706497065070651706527065370654706557065670657706587065970660706617066270663706647066570666706677066870669706707067170672706737067470675706767067770678706797068070681706827068370684706857068670687706887068970690706917069270693706947069570696706977069870699707007070170702707037070470705707067070770708707097071070711707127071370714707157071670717707187071970720707217072270723707247072570726707277072870729707307073170732707337073470735707367073770738707397074070741707427074370744707457074670747707487074970750707517075270753707547075570756707577075870759707607076170762707637076470765707667076770768707697077070771707727077370774707757077670777707787077970780707817078270783707847078570786707877078870789707907079170792707937079470795707967079770798707997080070801708027080370804708057080670807708087080970810708117081270813708147081570816708177081870819708207082170822708237082470825708267082770828708297083070831708327083370834708357083670837708387083970840708417084270843708447084570846708477084870849708507085170852708537085470855708567085770858708597086070861708627086370864708657086670867708687086970870708717087270873708747087570876708777087870879708807088170882708837088470885708867088770888708897089070891708927089370894708957089670897708987089970900709017090270903709047090570906709077090870909709107091170912709137091470915709167091770918709197092070921709227092370924709257092670927709287092970930709317093270933709347093570936709377093870939709407094170942709437094470945709467094770948709497095070951709527095370954709557095670957709587095970960709617096270963709647096570966709677096870969709707097170972709737097470975709767097770978709797098070981709827098370984709857098670987709887098970990709917099270993709947099570996709977099870999710007100171002710037100471005710067100771008710097101071011710127101371014710157101671017710187101971020710217102271023710247102571026710277102871029710307103171032710337103471035710367103771038710397104071041710427104371044710457104671047710487104971050710517105271053710547105571056710577105871059710607106171062710637106471065710667106771068710697107071071710727107371074710757107671077710787107971080710817108271083710847108571086710877108871089710907109171092710937109471095710967109771098710997110071101711027110371104711057110671107711087110971110711117111271113711147111571116711177111871119711207112171122711237112471125711267112771128711297113071131711327113371134711357113671137711387113971140711417114271143711447114571146711477114871149711507115171152711537115471155711567115771158711597116071161711627116371164711657116671167711687116971170711717117271173711747117571176711777117871179711807118171182711837118471185711867118771188711897119071191711927119371194711957119671197711987119971200712017120271203712047120571206712077120871209712107121171212712137121471215712167121771218712197122071221712227122371224712257122671227712287122971230712317123271233712347123571236712377123871239712407124171242712437124471245712467124771248712497125071251712527125371254712557125671257712587125971260712617126271263712647126571266712677126871269712707127171272712737127471275712767127771278712797128071281712827128371284712857128671287712887128971290712917129271293712947129571296712977129871299713007130171302713037130471305713067130771308713097131071311713127131371314713157131671317713187131971320713217132271323713247132571326713277132871329713307133171332713337133471335713367133771338713397134071341713427134371344713457134671347713487134971350713517135271353713547135571356713577135871359713607136171362713637136471365713667136771368713697137071371713727137371374713757137671377713787137971380713817138271383713847138571386713877138871389713907139171392713937139471395713967139771398713997140071401714027140371404714057140671407714087140971410714117141271413714147141571416714177141871419714207142171422714237142471425714267142771428714297143071431714327143371434714357143671437714387143971440714417144271443714447144571446714477144871449714507145171452714537145471455714567145771458714597146071461714627146371464714657146671467714687146971470714717147271473714747147571476714777147871479714807148171482714837148471485714867148771488714897149071491714927149371494714957149671497714987149971500715017150271503715047150571506715077150871509715107151171512715137151471515715167151771518715197152071521715227152371524715257152671527715287152971530715317153271533715347153571536715377153871539715407154171542715437154471545715467154771548715497155071551715527155371554715557155671557715587155971560715617156271563715647156571566715677156871569715707157171572715737157471575715767157771578715797158071581715827158371584715857158671587715887158971590715917159271593715947159571596715977159871599716007160171602716037160471605716067160771608716097161071611716127161371614716157161671617716187161971620716217162271623716247162571626716277162871629716307163171632716337163471635716367163771638716397164071641716427164371644716457164671647716487164971650716517165271653716547165571656716577165871659716607166171662716637166471665716667166771668716697167071671716727167371674716757167671677716787167971680716817168271683716847168571686716877168871689716907169171692716937169471695716967169771698716997170071701717027170371704717057170671707717087170971710717117171271713717147171571716717177171871719717207172171722717237172471725717267172771728717297173071731717327173371734717357173671737717387173971740717417174271743717447174571746717477174871749717507175171752717537175471755717567175771758717597176071761717627176371764717657176671767717687176971770717717177271773717747177571776717777177871779717807178171782717837178471785717867178771788717897179071791717927179371794717957179671797717987179971800718017180271803718047180571806718077180871809718107181171812718137181471815718167181771818718197182071821718227182371824718257182671827718287182971830718317183271833718347183571836718377183871839718407184171842718437184471845718467184771848718497185071851718527185371854718557185671857718587185971860718617186271863718647186571866718677186871869718707187171872718737187471875718767187771878718797188071881718827188371884718857188671887718887188971890718917189271893718947189571896718977189871899719007190171902719037190471905719067190771908719097191071911719127191371914719157191671917719187191971920719217192271923719247192571926719277192871929719307193171932719337193471935719367193771938719397194071941719427194371944719457194671947719487194971950719517195271953719547195571956719577195871959719607196171962719637196471965719667196771968719697197071971719727197371974719757197671977719787197971980719817198271983719847198571986719877198871989719907199171992719937199471995719967199771998719997200072001720027200372004720057200672007720087200972010720117201272013720147201572016720177201872019720207202172022720237202472025720267202772028720297203072031720327203372034720357203672037720387203972040720417204272043720447204572046720477204872049720507205172052720537205472055720567205772058720597206072061720627206372064720657206672067720687206972070720717207272073720747207572076720777207872079720807208172082720837208472085720867208772088720897209072091720927209372094720957209672097720987209972100721017210272103721047210572106721077210872109721107211172112721137211472115721167211772118721197212072121721227212372124721257212672127721287212972130721317213272133721347213572136721377213872139721407214172142721437214472145721467214772148721497215072151721527215372154721557215672157721587215972160721617216272163721647216572166721677216872169721707217172172721737217472175721767217772178721797218072181721827218372184721857218672187721887218972190721917219272193721947219572196721977219872199722007220172202722037220472205722067220772208722097221072211722127221372214722157221672217722187221972220722217222272223722247222572226722277222872229722307223172232722337223472235722367223772238722397224072241722427224372244722457224672247722487224972250722517225272253722547225572256722577225872259722607226172262722637226472265722667226772268722697227072271722727227372274722757227672277722787227972280722817228272283722847228572286722877228872289722907229172292722937229472295722967229772298722997230072301723027230372304723057230672307723087230972310723117231272313723147231572316723177231872319723207232172322723237232472325723267232772328723297233072331723327233372334723357233672337723387233972340723417234272343723447234572346723477234872349723507235172352723537235472355723567235772358723597236072361723627236372364723657236672367723687236972370723717237272373723747237572376723777237872379723807238172382723837238472385723867238772388723897239072391723927239372394723957239672397723987239972400724017240272403724047240572406724077240872409724107241172412724137241472415724167241772418724197242072421724227242372424724257242672427724287242972430724317243272433724347243572436724377243872439724407244172442724437244472445724467244772448724497245072451724527245372454724557245672457724587245972460724617246272463724647246572466724677246872469724707247172472724737247472475724767247772478724797248072481724827248372484724857248672487724887248972490724917249272493724947249572496724977249872499725007250172502725037250472505725067250772508725097251072511725127251372514725157251672517725187251972520725217252272523725247252572526725277252872529725307253172532725337253472535725367253772538725397254072541725427254372544725457254672547725487254972550725517255272553725547255572556725577255872559725607256172562725637256472565725667256772568725697257072571725727257372574725757257672577725787257972580725817258272583725847258572586725877258872589725907259172592725937259472595725967259772598725997260072601726027260372604726057260672607726087260972610726117261272613726147261572616726177261872619726207262172622726237262472625726267262772628726297263072631726327263372634726357263672637726387263972640726417264272643726447264572646726477264872649726507265172652726537265472655726567265772658726597266072661726627266372664726657266672667726687266972670726717267272673726747267572676726777267872679726807268172682726837268472685726867268772688726897269072691726927269372694726957269672697726987269972700727017270272703727047270572706727077270872709727107271172712727137271472715727167271772718727197272072721727227272372724727257272672727727287272972730727317273272733727347273572736727377273872739727407274172742727437274472745727467274772748727497275072751727527275372754727557275672757727587275972760727617276272763727647276572766727677276872769727707277172772727737277472775727767277772778727797278072781727827278372784727857278672787727887278972790727917279272793727947279572796727977279872799728007280172802728037280472805728067280772808728097281072811728127281372814728157281672817728187281972820728217282272823728247282572826728277282872829728307283172832728337283472835728367283772838728397284072841728427284372844728457284672847728487284972850728517285272853728547285572856728577285872859728607286172862728637286472865728667286772868728697287072871728727287372874728757287672877728787287972880728817288272883728847288572886728877288872889728907289172892728937289472895728967289772898728997290072901729027290372904729057290672907729087290972910729117291272913729147291572916729177291872919729207292172922729237292472925729267292772928729297293072931729327293372934729357293672937729387293972940729417294272943729447294572946729477294872949729507295172952729537295472955729567295772958729597296072961729627296372964729657296672967729687296972970729717297272973729747297572976729777297872979729807298172982729837298472985729867298772988729897299072991729927299372994729957299672997729987299973000730017300273003730047300573006730077300873009730107301173012730137301473015730167301773018730197302073021730227302373024730257302673027730287302973030730317303273033730347303573036730377303873039730407304173042730437304473045730467304773048730497305073051730527305373054730557305673057730587305973060730617306273063730647306573066730677306873069730707307173072730737307473075730767307773078730797308073081730827308373084730857308673087730887308973090730917309273093730947309573096730977309873099731007310173102731037310473105731067310773108731097311073111731127311373114731157311673117731187311973120731217312273123731247312573126731277312873129731307313173132731337313473135731367313773138731397314073141731427314373144731457314673147731487314973150731517315273153731547315573156731577315873159731607316173162731637316473165731667316773168731697317073171731727317373174731757317673177731787317973180731817318273183731847318573186731877318873189731907319173192731937319473195731967319773198731997320073201732027320373204732057320673207732087320973210732117321273213732147321573216732177321873219732207322173222732237322473225732267322773228732297323073231732327323373234732357323673237732387323973240732417324273243732447324573246732477324873249732507325173252732537325473255732567325773258732597326073261732627326373264732657326673267732687326973270732717327273273732747327573276732777327873279732807328173282732837328473285732867328773288732897329073291732927329373294732957329673297732987329973300733017330273303733047330573306733077330873309733107331173312733137331473315733167331773318733197332073321733227332373324733257332673327733287332973330733317333273333733347333573336733377333873339733407334173342733437334473345733467334773348733497335073351733527335373354733557335673357733587335973360733617336273363733647336573366733677336873369733707337173372733737337473375733767337773378733797338073381733827338373384733857338673387733887338973390733917339273393733947339573396733977339873399734007340173402734037340473405734067340773408734097341073411734127341373414734157341673417734187341973420734217342273423734247342573426734277342873429734307343173432734337343473435734367343773438734397344073441734427344373444734457344673447734487344973450734517345273453734547345573456734577345873459734607346173462734637346473465734667346773468734697347073471734727347373474734757347673477734787347973480734817348273483734847348573486734877348873489734907349173492734937349473495734967349773498734997350073501735027350373504735057350673507735087350973510735117351273513735147351573516735177351873519735207352173522735237352473525735267352773528735297353073531735327353373534735357353673537735387353973540735417354273543735447354573546735477354873549735507355173552735537355473555735567355773558735597356073561735627356373564735657356673567735687356973570735717357273573735747357573576735777357873579735807358173582735837358473585735867358773588735897359073591735927359373594735957359673597735987359973600736017360273603736047360573606736077360873609736107361173612736137361473615736167361773618736197362073621736227362373624736257362673627736287362973630736317363273633736347363573636736377363873639736407364173642736437364473645736467364773648736497365073651736527365373654736557365673657736587365973660736617366273663736647366573666736677366873669736707367173672736737367473675736767367773678736797368073681736827368373684736857368673687736887368973690736917369273693736947369573696736977369873699737007370173702737037370473705737067370773708737097371073711737127371373714737157371673717737187371973720737217372273723737247372573726737277372873729737307373173732737337373473735737367373773738737397374073741737427374373744737457374673747737487374973750737517375273753737547375573756737577375873759737607376173762737637376473765737667376773768737697377073771737727377373774737757377673777737787377973780737817378273783737847378573786737877378873789737907379173792737937379473795737967379773798737997380073801738027380373804738057380673807738087380973810738117381273813738147381573816738177381873819738207382173822738237382473825738267382773828738297383073831738327383373834738357383673837738387383973840738417384273843738447384573846738477384873849738507385173852738537385473855738567385773858738597386073861738627386373864738657386673867738687386973870738717387273873738747387573876738777387873879738807388173882738837388473885738867388773888738897389073891738927389373894738957389673897738987389973900739017390273903739047390573906739077390873909739107391173912739137391473915739167391773918739197392073921739227392373924739257392673927739287392973930739317393273933739347393573936739377393873939739407394173942739437394473945739467394773948739497395073951739527395373954739557395673957739587395973960739617396273963739647396573966739677396873969739707397173972739737397473975739767397773978739797398073981739827398373984739857398673987739887398973990739917399273993739947399573996739977399873999740007400174002740037400474005740067400774008740097401074011740127401374014740157401674017740187401974020740217402274023740247402574026740277402874029740307403174032740337403474035740367403774038740397404074041740427404374044740457404674047740487404974050740517405274053740547405574056740577405874059740607406174062740637406474065740667406774068740697407074071740727407374074740757407674077740787407974080740817408274083740847408574086740877408874089740907409174092740937409474095740967409774098740997410074101741027410374104741057410674107741087410974110741117411274113741147411574116741177411874119741207412174122741237412474125741267412774128741297413074131741327413374134741357413674137741387413974140741417414274143741447414574146741477414874149741507415174152741537415474155741567415774158741597416074161741627416374164741657416674167741687416974170741717417274173741747417574176741777417874179741807418174182741837418474185741867418774188741897419074191741927419374194741957419674197741987419974200742017420274203742047420574206742077420874209742107421174212742137421474215742167421774218742197422074221742227422374224742257422674227742287422974230742317423274233742347423574236742377423874239742407424174242742437424474245742467424774248742497425074251742527425374254742557425674257742587425974260742617426274263742647426574266742677426874269742707427174272742737427474275742767427774278742797428074281742827428374284742857428674287742887428974290742917429274293742947429574296742977429874299743007430174302743037430474305743067430774308743097431074311743127431374314743157431674317743187431974320743217432274323743247432574326743277432874329743307433174332743337433474335743367433774338743397434074341743427434374344743457434674347743487434974350743517435274353743547435574356743577435874359743607436174362743637436474365743667436774368743697437074371743727437374374743757437674377743787437974380743817438274383743847438574386743877438874389743907439174392743937439474395743967439774398743997440074401744027440374404744057440674407744087440974410744117441274413744147441574416744177441874419744207442174422744237442474425744267442774428744297443074431744327443374434744357443674437744387443974440744417444274443744447444574446744477444874449744507445174452744537445474455744567445774458744597446074461744627446374464744657446674467744687446974470744717447274473744747447574476744777447874479744807448174482744837448474485744867448774488744897449074491744927449374494744957449674497744987449974500745017450274503745047450574506745077450874509745107451174512745137451474515745167451774518745197452074521745227452374524745257452674527745287452974530745317453274533745347453574536745377453874539745407454174542745437454474545745467454774548745497455074551745527455374554745557455674557745587455974560745617456274563745647456574566745677456874569745707457174572745737457474575745767457774578745797458074581745827458374584745857458674587745887458974590745917459274593745947459574596745977459874599746007460174602746037460474605746067460774608746097461074611746127461374614746157461674617746187461974620746217462274623746247462574626746277462874629746307463174632746337463474635746367463774638746397464074641746427464374644746457464674647746487464974650746517465274653746547465574656746577465874659746607466174662746637466474665746667466774668746697467074671746727467374674746757467674677746787467974680746817468274683746847468574686746877468874689746907469174692746937469474695746967469774698746997470074701747027470374704747057470674707747087470974710747117471274713747147471574716747177471874719747207472174722747237472474725747267472774728747297473074731747327473374734747357473674737747387473974740747417474274743747447474574746747477474874749747507475174752747537475474755747567475774758747597476074761747627476374764747657476674767747687476974770747717477274773747747477574776747777477874779747807478174782747837478474785747867478774788747897479074791747927479374794747957479674797747987479974800748017480274803748047480574806748077480874809748107481174812748137481474815748167481774818748197482074821748227482374824748257482674827748287482974830748317483274833748347483574836748377483874839748407484174842748437484474845748467484774848748497485074851748527485374854748557485674857748587485974860748617486274863748647486574866748677486874869748707487174872748737487474875748767487774878748797488074881748827488374884748857488674887748887488974890748917489274893748947489574896748977489874899749007490174902749037490474905749067490774908749097491074911749127491374914749157491674917749187491974920749217492274923749247492574926749277492874929749307493174932749337493474935749367493774938749397494074941749427494374944749457494674947749487494974950749517495274953749547495574956749577495874959749607496174962749637496474965749667496774968749697497074971749727497374974749757497674977749787497974980749817498274983749847498574986749877498874989749907499174992749937499474995749967499774998749997500075001750027500375004750057500675007750087500975010750117501275013750147501575016750177501875019750207502175022750237502475025750267502775028750297503075031750327503375034750357503675037750387503975040750417504275043750447504575046750477504875049750507505175052750537505475055750567505775058750597506075061750627506375064750657506675067750687506975070750717507275073750747507575076750777507875079750807508175082750837508475085750867508775088750897509075091750927509375094750957509675097750987509975100751017510275103751047510575106751077510875109751107511175112751137511475115751167511775118751197512075121751227512375124751257512675127751287512975130751317513275133751347513575136751377513875139751407514175142751437514475145751467514775148751497515075151751527515375154751557515675157751587515975160751617516275163751647516575166751677516875169751707517175172751737517475175751767517775178751797518075181751827518375184751857518675187751887518975190751917519275193751947519575196751977519875199752007520175202752037520475205752067520775208752097521075211752127521375214752157521675217752187521975220752217522275223752247522575226752277522875229752307523175232752337523475235752367523775238752397524075241752427524375244752457524675247752487524975250752517525275253752547525575256752577525875259752607526175262752637526475265752667526775268752697527075271752727527375274752757527675277752787527975280752817528275283752847528575286752877528875289752907529175292752937529475295752967529775298752997530075301753027530375304753057530675307753087530975310753117531275313753147531575316753177531875319753207532175322753237532475325753267532775328753297533075331753327533375334753357533675337753387533975340753417534275343753447534575346753477534875349753507535175352753537535475355753567535775358753597536075361753627536375364753657536675367753687536975370753717537275373753747537575376753777537875379753807538175382753837538475385753867538775388753897539075391753927539375394753957539675397753987539975400754017540275403754047540575406754077540875409754107541175412754137541475415754167541775418754197542075421754227542375424754257542675427754287542975430754317543275433754347543575436754377543875439754407544175442754437544475445754467544775448754497545075451754527545375454754557545675457754587545975460754617546275463754647546575466754677546875469754707547175472754737547475475754767547775478754797548075481754827548375484754857548675487754887548975490754917549275493754947549575496754977549875499755007550175502755037550475505755067550775508755097551075511755127551375514755157551675517755187551975520755217552275523755247552575526755277552875529755307553175532755337553475535755367553775538755397554075541755427554375544755457554675547755487554975550755517555275553755547555575556755577555875559755607556175562755637556475565755667556775568755697557075571755727557375574755757557675577755787557975580755817558275583755847558575586755877558875589755907559175592755937559475595755967559775598755997560075601756027560375604756057560675607756087560975610756117561275613756147561575616756177561875619756207562175622756237562475625756267562775628756297563075631756327563375634756357563675637756387563975640756417564275643756447564575646756477564875649756507565175652756537565475655756567565775658756597566075661756627566375664756657566675667756687566975670756717567275673756747567575676756777567875679756807568175682756837568475685756867568775688756897569075691756927569375694756957569675697756987569975700757017570275703757047570575706757077570875709757107571175712757137571475715757167571775718757197572075721757227572375724757257572675727757287572975730757317573275733757347573575736757377573875739757407574175742757437574475745757467574775748757497575075751757527575375754757557575675757757587575975760757617576275763757647576575766757677576875769757707577175772757737577475775757767577775778757797578075781757827578375784757857578675787757887578975790757917579275793757947579575796757977579875799758007580175802758037580475805758067580775808758097581075811758127581375814758157581675817758187581975820758217582275823758247582575826758277582875829758307583175832758337583475835758367583775838758397584075841758427584375844758457584675847758487584975850758517585275853758547585575856758577585875859758607586175862758637586475865758667586775868758697587075871758727587375874758757587675877758787587975880758817588275883758847588575886758877588875889758907589175892758937589475895758967589775898758997590075901759027590375904759057590675907759087590975910759117591275913759147591575916759177591875919759207592175922759237592475925759267592775928759297593075931759327593375934759357593675937759387593975940759417594275943759447594575946759477594875949759507595175952759537595475955759567595775958759597596075961759627596375964759657596675967759687596975970759717597275973759747597575976759777597875979759807598175982759837598475985759867598775988759897599075991759927599375994759957599675997759987599976000760017600276003760047600576006760077600876009760107601176012760137601476015760167601776018760197602076021760227602376024760257602676027760287602976030760317603276033760347603576036760377603876039760407604176042760437604476045760467604776048760497605076051760527605376054760557605676057760587605976060760617606276063760647606576066760677606876069760707607176072760737607476075760767607776078760797608076081760827608376084760857608676087760887608976090760917609276093760947609576096760977609876099761007610176102761037610476105761067610776108761097611076111761127611376114761157611676117761187611976120761217612276123761247612576126761277612876129761307613176132761337613476135761367613776138761397614076141761427614376144761457614676147761487614976150761517615276153761547615576156761577615876159761607616176162761637616476165761667616776168761697617076171761727617376174761757617676177761787617976180761817618276183761847618576186761877618876189761907619176192761937619476195761967619776198761997620076201762027620376204762057620676207762087620976210762117621276213762147621576216762177621876219762207622176222762237622476225762267622776228762297623076231762327623376234762357623676237762387623976240762417624276243762447624576246762477624876249762507625176252762537625476255762567625776258762597626076261762627626376264762657626676267762687626976270762717627276273762747627576276762777627876279762807628176282762837628476285762867628776288762897629076291762927629376294762957629676297762987629976300763017630276303763047630576306763077630876309763107631176312763137631476315763167631776318763197632076321763227632376324763257632676327763287632976330763317633276333763347633576336763377633876339763407634176342763437634476345763467634776348763497635076351763527635376354763557635676357763587635976360763617636276363763647636576366763677636876369763707637176372763737637476375763767637776378763797638076381763827638376384763857638676387763887638976390763917639276393763947639576396763977639876399764007640176402764037640476405764067640776408764097641076411764127641376414764157641676417764187641976420764217642276423764247642576426764277642876429764307643176432764337643476435764367643776438764397644076441764427644376444764457644676447764487644976450764517645276453764547645576456764577645876459764607646176462764637646476465764667646776468764697647076471764727647376474764757647676477764787647976480764817648276483764847648576486764877648876489764907649176492764937649476495764967649776498764997650076501765027650376504765057650676507765087650976510765117651276513765147651576516765177651876519765207652176522765237652476525765267652776528765297653076531765327653376534765357653676537765387653976540765417654276543765447654576546765477654876549765507655176552765537655476555765567655776558765597656076561765627656376564765657656676567765687656976570765717657276573765747657576576765777657876579765807658176582765837658476585765867658776588765897659076591765927659376594765957659676597765987659976600766017660276603766047660576606766077660876609766107661176612766137661476615766167661776618766197662076621766227662376624766257662676627766287662976630766317663276633766347663576636766377663876639766407664176642766437664476645766467664776648766497665076651766527665376654766557665676657766587665976660766617666276663766647666576666766677666876669766707667176672766737667476675766767667776678766797668076681766827668376684766857668676687766887668976690766917669276693766947669576696766977669876699767007670176702767037670476705767067670776708767097671076711767127671376714767157671676717767187671976720767217672276723767247672576726767277672876729767307673176732767337673476735767367673776738767397674076741767427674376744767457674676747767487674976750767517675276753767547675576756767577675876759767607676176762767637676476765767667676776768767697677076771767727677376774767757677676777767787677976780767817678276783767847678576786767877678876789767907679176792767937679476795767967679776798767997680076801768027680376804768057680676807768087680976810768117681276813768147681576816768177681876819768207682176822768237682476825768267682776828768297683076831768327683376834768357683676837768387683976840768417684276843768447684576846768477684876849768507685176852768537685476855768567685776858768597686076861768627686376864768657686676867768687686976870768717687276873768747687576876768777687876879768807688176882768837688476885768867688776888768897689076891768927689376894768957689676897768987689976900769017690276903769047690576906769077690876909769107691176912769137691476915769167691776918769197692076921769227692376924769257692676927769287692976930769317693276933769347693576936769377693876939769407694176942769437694476945769467694776948769497695076951769527695376954769557695676957769587695976960769617696276963769647696576966769677696876969769707697176972769737697476975769767697776978769797698076981769827698376984769857698676987769887698976990769917699276993769947699576996769977699876999770007700177002770037700477005770067700777008770097701077011770127701377014770157701677017770187701977020770217702277023770247702577026770277702877029770307703177032770337703477035770367703777038770397704077041770427704377044770457704677047770487704977050770517705277053770547705577056770577705877059770607706177062770637706477065770667706777068770697707077071770727707377074770757707677077770787707977080770817708277083770847708577086770877708877089770907709177092770937709477095770967709777098770997710077101771027710377104771057710677107771087710977110771117711277113771147711577116771177711877119771207712177122771237712477125771267712777128771297713077131771327713377134771357713677137771387713977140771417714277143771447714577146771477714877149771507715177152771537715477155771567715777158771597716077161771627716377164771657716677167771687716977170771717717277173771747717577176771777717877179771807718177182771837718477185771867718777188771897719077191771927719377194771957719677197771987719977200772017720277203772047720577206772077720877209772107721177212772137721477215772167721777218772197722077221772227722377224772257722677227772287722977230772317723277233772347723577236772377723877239772407724177242772437724477245772467724777248772497725077251772527725377254772557725677257772587725977260772617726277263772647726577266772677726877269772707727177272772737727477275772767727777278772797728077281772827728377284772857728677287772887728977290772917729277293772947729577296772977729877299773007730177302773037730477305773067730777308773097731077311773127731377314773157731677317773187731977320773217732277323773247732577326773277732877329773307733177332773337733477335773367733777338773397734077341773427734377344773457734677347773487734977350773517735277353773547735577356773577735877359773607736177362773637736477365773667736777368773697737077371773727737377374773757737677377773787737977380773817738277383773847738577386773877738877389773907739177392773937739477395773967739777398773997740077401774027740377404774057740677407774087740977410774117741277413774147741577416774177741877419774207742177422774237742477425774267742777428774297743077431774327743377434774357743677437774387743977440774417744277443774447744577446774477744877449774507745177452774537745477455774567745777458774597746077461774627746377464774657746677467774687746977470774717747277473774747747577476774777747877479774807748177482774837748477485774867748777488774897749077491774927749377494774957749677497774987749977500775017750277503775047750577506775077750877509775107751177512775137751477515775167751777518775197752077521775227752377524775257752677527775287752977530775317753277533775347753577536775377753877539775407754177542775437754477545775467754777548775497755077551775527755377554775557755677557775587755977560775617756277563775647756577566775677756877569775707757177572775737757477575775767757777578775797758077581775827758377584775857758677587775887758977590775917759277593775947759577596775977759877599776007760177602776037760477605776067760777608776097761077611776127761377614776157761677617776187761977620776217762277623776247762577626776277762877629776307763177632776337763477635776367763777638776397764077641776427764377644776457764677647776487764977650776517765277653776547765577656776577765877659776607766177662776637766477665776667766777668776697767077671776727767377674776757767677677776787767977680776817768277683776847768577686776877768877689776907769177692776937769477695776967769777698776997770077701777027770377704777057770677707777087770977710777117771277713777147771577716777177771877719777207772177722777237772477725777267772777728777297773077731777327773377734777357773677737777387773977740777417774277743777447774577746777477774877749777507775177752777537775477755777567775777758777597776077761777627776377764777657776677767777687776977770777717777277773777747777577776777777777877779777807778177782777837778477785777867778777788777897779077791777927779377794777957779677797777987779977800778017780277803778047780577806778077780877809778107781177812778137781477815778167781777818778197782077821778227782377824778257782677827778287782977830778317783277833778347783577836778377783877839778407784177842778437784477845778467784777848778497785077851778527785377854778557785677857778587785977860778617786277863778647786577866778677786877869778707787177872778737787477875778767787777878778797788077881778827788377884778857788677887778887788977890778917789277893778947789577896778977789877899779007790177902779037790477905779067790777908779097791077911779127791377914779157791677917779187791977920779217792277923779247792577926779277792877929779307793177932779337793477935779367793777938779397794077941779427794377944779457794677947779487794977950779517795277953779547795577956779577795877959779607796177962779637796477965779667796777968779697797077971779727797377974779757797677977779787797977980779817798277983779847798577986779877798877989779907799177992779937799477995779967799777998779997800078001780027800378004780057800678007780087800978010780117801278013780147801578016780177801878019780207802178022780237802478025780267802778028780297803078031780327803378034780357803678037780387803978040780417804278043780447804578046780477804878049780507805178052780537805478055780567805778058780597806078061780627806378064780657806678067780687806978070780717807278073780747807578076780777807878079780807808178082780837808478085780867808778088780897809078091780927809378094780957809678097780987809978100781017810278103781047810578106781077810878109781107811178112781137811478115781167811778118781197812078121781227812378124781257812678127781287812978130781317813278133781347813578136781377813878139781407814178142781437814478145781467814778148781497815078151781527815378154781557815678157781587815978160781617816278163781647816578166781677816878169781707817178172781737817478175781767817778178781797818078181781827818378184781857818678187781887818978190781917819278193781947819578196781977819878199782007820178202782037820478205782067820778208782097821078211782127821378214782157821678217782187821978220782217822278223782247822578226782277822878229782307823178232782337823478235782367823778238782397824078241782427824378244782457824678247782487824978250782517825278253782547825578256782577825878259782607826178262782637826478265782667826778268782697827078271782727827378274782757827678277782787827978280782817828278283782847828578286782877828878289782907829178292782937829478295782967829778298782997830078301783027830378304783057830678307783087830978310783117831278313783147831578316783177831878319783207832178322783237832478325783267832778328783297833078331783327833378334783357833678337783387833978340783417834278343783447834578346783477834878349783507835178352783537835478355783567835778358783597836078361783627836378364783657836678367783687836978370783717837278373783747837578376783777837878379783807838178382783837838478385783867838778388783897839078391783927839378394783957839678397783987839978400784017840278403784047840578406784077840878409784107841178412784137841478415784167841778418784197842078421784227842378424784257842678427784287842978430784317843278433784347843578436784377843878439784407844178442784437844478445784467844778448784497845078451784527845378454784557845678457784587845978460784617846278463784647846578466784677846878469784707847178472784737847478475784767847778478784797848078481784827848378484784857848678487784887848978490784917849278493784947849578496784977849878499785007850178502785037850478505785067850778508785097851078511785127851378514785157851678517785187851978520785217852278523785247852578526785277852878529785307853178532785337853478535785367853778538785397854078541785427854378544785457854678547785487854978550785517855278553785547855578556785577855878559785607856178562785637856478565785667856778568785697857078571785727857378574785757857678577785787857978580785817858278583785847858578586785877858878589785907859178592785937859478595785967859778598785997860078601786027860378604786057860678607786087860978610786117861278613786147861578616786177861878619786207862178622786237862478625786267862778628786297863078631786327863378634786357863678637786387863978640786417864278643786447864578646786477864878649786507865178652786537865478655786567865778658786597866078661786627866378664786657866678667786687866978670786717867278673786747867578676786777867878679786807868178682786837868478685786867868778688786897869078691786927869378694786957869678697786987869978700787017870278703787047870578706787077870878709787107871178712787137871478715787167871778718787197872078721787227872378724787257872678727787287872978730787317873278733787347873578736787377873878739787407874178742787437874478745787467874778748787497875078751787527875378754787557875678757787587875978760787617876278763787647876578766787677876878769787707877178772787737877478775787767877778778787797878078781787827878378784787857878678787787887878978790787917879278793787947879578796787977879878799788007880178802788037880478805788067880778808788097881078811788127881378814788157881678817788187881978820788217882278823788247882578826788277882878829788307883178832788337883478835788367883778838788397884078841788427884378844788457884678847788487884978850788517885278853788547885578856788577885878859788607886178862788637886478865788667886778868788697887078871788727887378874788757887678877788787887978880788817888278883788847888578886788877888878889788907889178892788937889478895788967889778898788997890078901789027890378904789057890678907789087890978910789117891278913789147891578916789177891878919789207892178922789237892478925789267892778928789297893078931789327893378934789357893678937789387893978940789417894278943789447894578946789477894878949789507895178952789537895478955789567895778958789597896078961789627896378964789657896678967789687896978970789717897278973789747897578976789777897878979789807898178982789837898478985789867898778988789897899078991789927899378994789957899678997789987899979000790017900279003790047900579006790077900879009790107901179012790137901479015790167901779018790197902079021790227902379024790257902679027790287902979030790317903279033790347903579036790377903879039790407904179042790437904479045790467904779048790497905079051790527905379054790557905679057790587905979060790617906279063790647906579066790677906879069790707907179072790737907479075790767907779078790797908079081790827908379084790857908679087790887908979090790917909279093790947909579096790977909879099791007910179102791037910479105791067910779108791097911079111791127911379114791157911679117791187911979120791217912279123791247912579126791277912879129791307913179132791337913479135791367913779138791397914079141791427914379144791457914679147791487914979150791517915279153791547915579156791577915879159791607916179162791637916479165791667916779168791697917079171791727917379174791757917679177791787917979180791817918279183791847918579186791877918879189791907919179192791937919479195791967919779198791997920079201792027920379204792057920679207792087920979210792117921279213792147921579216792177921879219792207922179222792237922479225792267922779228792297923079231792327923379234792357923679237792387923979240792417924279243792447924579246792477924879249792507925179252792537925479255792567925779258792597926079261792627926379264792657926679267792687926979270792717927279273792747927579276792777927879279792807928179282792837928479285792867928779288792897929079291792927929379294792957929679297792987929979300793017930279303793047930579306793077930879309793107931179312793137931479315793167931779318793197932079321793227932379324793257932679327793287932979330793317933279333793347933579336793377933879339793407934179342793437934479345793467934779348793497935079351793527935379354793557935679357793587935979360793617936279363793647936579366793677936879369793707937179372793737937479375793767937779378793797938079381793827938379384793857938679387793887938979390793917939279393793947939579396793977939879399794007940179402794037940479405794067940779408794097941079411794127941379414794157941679417794187941979420794217942279423794247942579426794277942879429794307943179432794337943479435794367943779438794397944079441794427944379444794457944679447794487944979450794517945279453794547945579456794577945879459794607946179462794637946479465794667946779468794697947079471794727947379474794757947679477794787947979480794817948279483794847948579486794877948879489794907949179492794937949479495794967949779498794997950079501795027950379504795057950679507795087950979510795117951279513795147951579516795177951879519795207952179522795237952479525795267952779528795297953079531795327953379534795357953679537795387953979540795417954279543795447954579546795477954879549795507955179552795537955479555795567955779558795597956079561795627956379564795657956679567795687956979570795717957279573795747957579576795777957879579795807958179582795837958479585795867958779588795897959079591795927959379594795957959679597795987959979600796017960279603796047960579606796077960879609796107961179612796137961479615796167961779618796197962079621796227962379624796257962679627796287962979630796317963279633796347963579636796377963879639796407964179642796437964479645796467964779648796497965079651796527965379654796557965679657796587965979660796617966279663796647966579666796677966879669796707967179672796737967479675796767967779678796797968079681796827968379684796857968679687796887968979690796917969279693796947969579696796977969879699797007970179702797037970479705797067970779708797097971079711797127971379714797157971679717797187971979720797217972279723797247972579726797277972879729797307973179732797337973479735797367973779738797397974079741797427974379744797457974679747797487974979750797517975279753797547975579756797577975879759797607976179762797637976479765797667976779768797697977079771797727977379774797757977679777797787977979780797817978279783797847978579786797877978879789797907979179792797937979479795797967979779798797997980079801798027980379804798057980679807798087980979810798117981279813798147981579816798177981879819798207982179822798237982479825798267982779828798297983079831798327983379834798357983679837798387983979840798417984279843798447984579846798477984879849798507985179852798537985479855798567985779858798597986079861798627986379864798657986679867798687986979870798717987279873798747987579876798777987879879798807988179882798837988479885798867988779888798897989079891798927989379894798957989679897798987989979900799017990279903799047990579906799077990879909799107991179912799137991479915799167991779918799197992079921799227992379924799257992679927799287992979930799317993279933799347993579936799377993879939799407994179942799437994479945799467994779948799497995079951799527995379954799557995679957799587995979960799617996279963799647996579966799677996879969799707997179972799737997479975799767997779978799797998079981799827998379984799857998679987799887998979990799917999279993799947999579996799977999879999800008000180002800038000480005800068000780008800098001080011800128001380014800158001680017800188001980020800218002280023800248002580026800278002880029800308003180032800338003480035800368003780038800398004080041800428004380044800458004680047800488004980050800518005280053800548005580056800578005880059800608006180062800638006480065800668006780068800698007080071800728007380074800758007680077800788007980080800818008280083800848008580086800878008880089800908009180092800938009480095800968009780098800998010080101801028010380104801058010680107801088010980110801118011280113801148011580116801178011880119801208012180122801238012480125801268012780128801298013080131801328013380134801358013680137801388013980140801418014280143801448014580146801478014880149801508015180152801538015480155801568015780158801598016080161801628016380164801658016680167801688016980170801718017280173801748017580176801778017880179801808018180182801838018480185801868018780188801898019080191801928019380194801958019680197801988019980200802018020280203802048020580206802078020880209802108021180212802138021480215802168021780218802198022080221802228022380224802258022680227802288022980230802318023280233802348023580236802378023880239802408024180242802438024480245802468024780248802498025080251802528025380254802558025680257802588025980260802618026280263802648026580266802678026880269802708027180272802738027480275802768027780278802798028080281802828028380284802858028680287802888028980290802918029280293802948029580296802978029880299803008030180302803038030480305803068030780308803098031080311803128031380314803158031680317803188031980320803218032280323803248032580326803278032880329803308033180332803338033480335803368033780338803398034080341803428034380344803458034680347803488034980350803518035280353803548035580356803578035880359803608036180362803638036480365803668036780368803698037080371803728037380374803758037680377803788037980380803818038280383803848038580386803878038880389803908039180392803938039480395803968039780398803998040080401804028040380404804058040680407804088040980410804118041280413804148041580416804178041880419804208042180422804238042480425804268042780428804298043080431804328043380434804358043680437804388043980440804418044280443804448044580446804478044880449804508045180452804538045480455804568045780458804598046080461804628046380464804658046680467804688046980470804718047280473804748047580476804778047880479804808048180482804838048480485804868048780488804898049080491804928049380494804958049680497804988049980500805018050280503805048050580506805078050880509805108051180512805138051480515805168051780518805198052080521805228052380524805258052680527805288052980530805318053280533805348053580536805378053880539805408054180542805438054480545805468054780548805498055080551805528055380554805558055680557805588055980560805618056280563805648056580566805678056880569805708057180572805738057480575805768057780578805798058080581805828058380584805858058680587805888058980590805918059280593805948059580596805978059880599806008060180602806038060480605806068060780608806098061080611806128061380614806158061680617806188061980620806218062280623806248062580626806278062880629806308063180632806338063480635806368063780638806398064080641806428064380644806458064680647806488064980650806518065280653806548065580656806578065880659806608066180662806638066480665806668066780668806698067080671806728067380674806758067680677806788067980680806818068280683806848068580686806878068880689806908069180692806938069480695806968069780698806998070080701807028070380704807058070680707807088070980710807118071280713807148071580716807178071880719807208072180722807238072480725807268072780728807298073080731807328073380734807358073680737807388073980740807418074280743807448074580746807478074880749807508075180752807538075480755807568075780758807598076080761807628076380764807658076680767807688076980770807718077280773807748077580776807778077880779807808078180782807838078480785807868078780788807898079080791807928079380794807958079680797807988079980800808018080280803808048080580806808078080880809808108081180812808138081480815808168081780818808198082080821808228082380824808258082680827808288082980830808318083280833808348083580836808378083880839808408084180842808438084480845808468084780848808498085080851808528085380854808558085680857808588085980860808618086280863808648086580866808678086880869808708087180872808738087480875808768087780878808798088080881808828088380884808858088680887808888088980890808918089280893808948089580896808978089880899809008090180902809038090480905809068090780908809098091080911809128091380914809158091680917809188091980920809218092280923809248092580926809278092880929809308093180932809338093480935809368093780938809398094080941809428094380944809458094680947809488094980950809518095280953809548095580956809578095880959809608096180962809638096480965809668096780968809698097080971809728097380974809758097680977809788097980980809818098280983809848098580986809878098880989809908099180992809938099480995809968099780998809998100081001810028100381004810058100681007810088100981010810118101281013810148101581016810178101881019810208102181022810238102481025810268102781028810298103081031810328103381034810358103681037810388103981040810418104281043810448104581046810478104881049810508105181052810538105481055810568105781058810598106081061810628106381064810658106681067810688106981070810718107281073810748107581076810778107881079810808108181082810838108481085810868108781088810898109081091810928109381094810958109681097810988109981100811018110281103811048110581106811078110881109811108111181112811138111481115811168111781118811198112081121811228112381124811258112681127811288112981130811318113281133811348113581136811378113881139811408114181142811438114481145811468114781148811498115081151811528115381154811558115681157811588115981160811618116281163811648116581166811678116881169811708117181172811738117481175811768117781178811798118081181811828118381184811858118681187811888118981190811918119281193811948119581196811978119881199812008120181202812038120481205812068120781208812098121081211812128121381214812158121681217812188121981220812218122281223812248122581226812278122881229812308123181232812338123481235812368123781238812398124081241812428124381244812458124681247812488124981250812518125281253812548125581256812578125881259812608126181262812638126481265812668126781268812698127081271812728127381274812758127681277812788127981280812818128281283812848128581286812878128881289812908129181292812938129481295812968129781298812998130081301813028130381304813058130681307813088130981310813118131281313813148131581316813178131881319813208132181322813238132481325813268132781328813298133081331813328133381334813358133681337813388133981340813418134281343813448134581346813478134881349813508135181352813538135481355813568135781358813598136081361813628136381364813658136681367813688136981370813718137281373813748137581376813778137881379813808138181382813838138481385813868138781388813898139081391813928139381394813958139681397813988139981400814018140281403814048140581406814078140881409814108141181412814138141481415814168141781418814198142081421814228142381424814258142681427814288142981430814318143281433814348143581436814378143881439814408144181442814438144481445814468144781448814498145081451814528145381454814558145681457814588145981460814618146281463814648146581466814678146881469814708147181472814738147481475814768147781478814798148081481814828148381484814858148681487814888148981490814918149281493814948149581496814978149881499815008150181502815038150481505815068150781508815098151081511815128151381514815158151681517815188151981520815218152281523815248152581526815278152881529815308153181532815338153481535815368153781538815398154081541815428154381544815458154681547815488154981550815518155281553815548155581556815578155881559815608156181562815638156481565815668156781568815698157081571815728157381574815758157681577815788157981580815818158281583815848158581586815878158881589815908159181592815938159481595815968159781598815998160081601816028160381604816058160681607816088160981610816118161281613816148161581616816178161881619816208162181622816238162481625816268162781628816298163081631816328163381634816358163681637816388163981640816418164281643816448164581646816478164881649816508165181652816538165481655816568165781658816598166081661816628166381664816658166681667816688166981670816718167281673816748167581676816778167881679816808168181682816838168481685816868168781688816898169081691816928169381694816958169681697816988169981700817018170281703817048170581706817078170881709817108171181712817138171481715817168171781718817198172081721817228172381724817258172681727817288172981730817318173281733817348173581736817378173881739817408174181742817438174481745817468174781748817498175081751817528175381754817558175681757817588175981760817618176281763817648176581766817678176881769817708177181772817738177481775817768177781778817798178081781817828178381784817858178681787817888178981790817918179281793817948179581796817978179881799818008180181802818038180481805818068180781808818098181081811818128181381814818158181681817818188181981820818218182281823818248182581826818278182881829818308183181832818338183481835818368183781838818398184081841818428184381844818458184681847818488184981850818518185281853818548185581856818578185881859818608186181862818638186481865818668186781868818698187081871818728187381874818758187681877818788187981880818818188281883818848188581886818878188881889818908189181892818938189481895818968189781898818998190081901819028190381904819058190681907819088190981910819118191281913819148191581916819178191881919819208192181922819238192481925819268192781928819298193081931819328193381934819358193681937819388193981940819418194281943819448194581946819478194881949819508195181952819538195481955819568195781958819598196081961819628196381964819658196681967819688196981970819718197281973819748197581976819778197881979819808198181982819838198481985819868198781988819898199081991819928199381994819958199681997819988199982000820018200282003820048200582006820078200882009820108201182012820138201482015820168201782018820198202082021820228202382024820258202682027820288202982030820318203282033820348203582036820378203882039820408204182042820438204482045820468204782048820498205082051820528205382054820558205682057820588205982060820618206282063820648206582066820678206882069820708207182072820738207482075820768207782078820798208082081820828208382084820858208682087820888208982090820918209282093820948209582096820978209882099821008210182102821038210482105821068210782108821098211082111821128211382114821158211682117821188211982120821218212282123821248212582126821278212882129821308213182132821338213482135821368213782138821398214082141821428214382144821458214682147821488214982150821518215282153821548215582156821578215882159821608216182162821638216482165821668216782168821698217082171821728217382174821758217682177821788217982180821818218282183821848218582186821878218882189821908219182192821938219482195821968219782198821998220082201822028220382204822058220682207822088220982210822118221282213822148221582216822178221882219822208222182222822238222482225822268222782228822298223082231822328223382234822358223682237822388223982240822418224282243822448224582246822478224882249822508225182252822538225482255822568225782258822598226082261822628226382264822658226682267822688226982270822718227282273822748227582276822778227882279822808228182282822838228482285822868228782288822898229082291822928229382294822958229682297822988229982300823018230282303823048230582306823078230882309823108231182312823138231482315823168231782318823198232082321823228232382324823258232682327823288232982330823318233282333823348233582336823378233882339823408234182342823438234482345823468234782348823498235082351823528235382354823558235682357823588235982360823618236282363823648236582366823678236882369823708237182372823738237482375823768237782378823798238082381823828238382384823858238682387823888238982390823918239282393823948239582396823978239882399824008240182402824038240482405824068240782408824098241082411824128241382414824158241682417824188241982420824218242282423824248242582426824278242882429824308243182432824338243482435824368243782438824398244082441824428244382444824458244682447824488244982450824518245282453824548245582456824578245882459824608246182462824638246482465824668246782468824698247082471824728247382474824758247682477824788247982480824818248282483824848248582486824878248882489824908249182492824938249482495824968249782498824998250082501825028250382504825058250682507825088250982510825118251282513825148251582516825178251882519825208252182522825238252482525825268252782528825298253082531825328253382534825358253682537825388253982540825418254282543825448254582546825478254882549825508255182552825538255482555825568255782558825598256082561825628256382564825658256682567825688256982570825718257282573825748257582576825778257882579825808258182582825838258482585825868258782588825898259082591825928259382594825958259682597825988259982600826018260282603826048260582606826078260882609826108261182612826138261482615826168261782618826198262082621826228262382624826258262682627826288262982630826318263282633826348263582636826378263882639826408264182642826438264482645826468264782648826498265082651826528265382654826558265682657826588265982660826618266282663826648266582666826678266882669826708267182672826738267482675826768267782678826798268082681826828268382684826858268682687826888268982690826918269282693826948269582696826978269882699827008270182702827038270482705827068270782708827098271082711827128271382714827158271682717827188271982720827218272282723827248272582726827278272882729827308273182732827338273482735827368273782738827398274082741827428274382744827458274682747827488274982750827518275282753827548275582756827578275882759827608276182762827638276482765827668276782768827698277082771827728277382774827758277682777827788277982780827818278282783827848278582786827878278882789827908279182792827938279482795827968279782798827998280082801828028280382804828058280682807828088280982810828118281282813828148281582816828178281882819828208282182822828238282482825828268282782828828298283082831828328283382834828358283682837828388283982840828418284282843828448284582846828478284882849828508285182852828538285482855828568285782858828598286082861828628286382864828658286682867828688286982870828718287282873828748287582876828778287882879828808288182882828838288482885828868288782888828898289082891828928289382894828958289682897828988289982900829018290282903829048290582906829078290882909829108291182912829138291482915829168291782918829198292082921829228292382924829258292682927829288292982930829318293282933829348293582936829378293882939829408294182942829438294482945829468294782948829498295082951829528295382954829558295682957829588295982960829618296282963829648296582966829678296882969829708297182972829738297482975829768297782978829798298082981829828298382984829858298682987829888298982990829918299282993829948299582996829978299882999830008300183002830038300483005830068300783008830098301083011830128301383014830158301683017830188301983020830218302283023830248302583026830278302883029830308303183032830338303483035830368303783038830398304083041830428304383044830458304683047830488304983050830518305283053830548305583056830578305883059830608306183062830638306483065830668306783068830698307083071830728307383074830758307683077830788307983080830818308283083830848308583086830878308883089830908309183092830938309483095830968309783098830998310083101831028310383104831058310683107831088310983110831118311283113831148311583116831178311883119831208312183122831238312483125831268312783128831298313083131831328313383134831358313683137831388313983140831418314283143831448314583146831478314883149831508315183152831538315483155831568315783158831598316083161831628316383164831658316683167831688316983170831718317283173831748317583176831778317883179831808318183182831838318483185831868318783188831898319083191831928319383194831958319683197831988319983200832018320283203832048320583206832078320883209832108321183212832138321483215832168321783218832198322083221832228322383224832258322683227832288322983230832318323283233832348323583236832378323883239832408324183242832438324483245832468324783248832498325083251832528325383254832558325683257832588325983260832618326283263832648326583266832678326883269832708327183272832738327483275832768327783278832798328083281832828328383284832858328683287832888328983290832918329283293832948329583296832978329883299833008330183302833038330483305833068330783308833098331083311833128331383314833158331683317833188331983320833218332283323833248332583326833278332883329833308333183332833338333483335833368333783338833398334083341833428334383344833458334683347833488334983350833518335283353833548335583356833578335883359833608336183362833638336483365833668336783368833698337083371833728337383374833758337683377833788337983380833818338283383833848338583386833878338883389833908339183392833938339483395833968339783398833998340083401834028340383404834058340683407834088340983410834118341283413834148341583416834178341883419834208342183422834238342483425834268342783428834298343083431834328343383434834358343683437834388343983440834418344283443834448344583446834478344883449834508345183452834538345483455834568345783458834598346083461834628346383464834658346683467834688346983470834718347283473834748347583476834778347883479834808348183482834838348483485834868348783488834898349083491834928349383494834958349683497834988349983500835018350283503835048350583506835078350883509835108351183512835138351483515835168351783518835198352083521835228352383524835258352683527835288352983530835318353283533835348353583536835378353883539835408354183542835438354483545835468354783548835498355083551835528355383554835558355683557835588355983560835618356283563835648356583566835678356883569835708357183572835738357483575835768357783578835798358083581835828358383584835858358683587835888358983590835918359283593835948359583596835978359883599836008360183602836038360483605836068360783608836098361083611836128361383614836158361683617836188361983620836218362283623836248362583626836278362883629836308363183632836338363483635836368363783638836398364083641836428364383644836458364683647836488364983650836518365283653836548365583656836578365883659836608366183662836638366483665836668366783668836698367083671836728367383674836758367683677836788367983680836818368283683836848368583686836878368883689836908369183692836938369483695836968369783698836998370083701837028370383704837058370683707837088370983710837118371283713837148371583716837178371883719837208372183722837238372483725837268372783728837298373083731837328373383734837358373683737837388373983740837418374283743837448374583746837478374883749837508375183752837538375483755837568375783758837598376083761837628376383764837658376683767837688376983770837718377283773837748377583776837778377883779837808378183782837838378483785837868378783788837898379083791837928379383794837958379683797837988379983800838018380283803838048380583806838078380883809838108381183812838138381483815838168381783818838198382083821838228382383824838258382683827838288382983830838318383283833838348383583836838378383883839838408384183842838438384483845838468384783848838498385083851838528385383854838558385683857838588385983860838618386283863838648386583866838678386883869838708387183872838738387483875838768387783878838798388083881838828388383884838858388683887838888388983890838918389283893838948389583896838978389883899839008390183902839038390483905839068390783908839098391083911839128391383914839158391683917839188391983920839218392283923839248392583926839278392883929839308393183932839338393483935839368393783938839398394083941839428394383944839458394683947839488394983950839518395283953839548395583956839578395883959839608396183962839638396483965839668396783968839698397083971839728397383974839758397683977839788397983980839818398283983839848398583986839878398883989839908399183992839938399483995839968399783998839998400084001840028400384004840058400684007840088400984010840118401284013840148401584016840178401884019840208402184022840238402484025840268402784028840298403084031840328403384034840358403684037840388403984040840418404284043840448404584046840478404884049840508405184052840538405484055840568405784058840598406084061840628406384064840658406684067840688406984070840718407284073840748407584076840778407884079840808408184082840838408484085840868408784088840898409084091840928409384094840958409684097840988409984100841018410284103841048410584106841078410884109841108411184112841138411484115841168411784118841198412084121841228412384124841258412684127841288412984130841318413284133841348413584136841378413884139841408414184142841438414484145841468414784148841498415084151841528415384154841558415684157841588415984160841618416284163841648416584166841678416884169841708417184172841738417484175841768417784178841798418084181841828418384184841858418684187841888418984190841918419284193841948419584196841978419884199842008420184202842038420484205842068420784208842098421084211842128421384214842158421684217842188421984220842218422284223842248422584226842278422884229842308423184232842338423484235842368423784238842398424084241842428424384244842458424684247842488424984250842518425284253842548425584256842578425884259842608426184262842638426484265842668426784268842698427084271842728427384274842758427684277842788427984280842818428284283842848428584286842878428884289842908429184292842938429484295842968429784298842998430084301843028430384304843058430684307843088430984310843118431284313843148431584316843178431884319843208432184322843238432484325843268432784328843298433084331843328433384334843358433684337843388433984340843418434284343843448434584346843478434884349843508435184352843538435484355843568435784358843598436084361843628436384364843658436684367843688436984370843718437284373843748437584376843778437884379843808438184382843838438484385843868438784388843898439084391843928439384394843958439684397843988439984400844018440284403844048440584406844078440884409844108441184412844138441484415844168441784418844198442084421844228442384424844258442684427844288442984430844318443284433844348443584436844378443884439844408444184442844438444484445844468444784448844498445084451844528445384454844558445684457844588445984460844618446284463844648446584466844678446884469844708447184472844738447484475844768447784478844798448084481844828448384484844858448684487844888448984490844918449284493844948449584496844978449884499845008450184502845038450484505845068450784508845098451084511845128451384514845158451684517845188451984520845218452284523845248452584526845278452884529845308453184532845338453484535845368453784538845398454084541845428454384544845458454684547845488454984550845518455284553845548455584556845578455884559845608456184562845638456484565845668456784568845698457084571845728457384574845758457684577845788457984580845818458284583845848458584586845878458884589845908459184592845938459484595845968459784598845998460084601846028460384604846058460684607846088460984610846118461284613846148461584616846178461884619846208462184622846238462484625846268462784628846298463084631846328463384634846358463684637846388463984640846418464284643846448464584646846478464884649846508465184652846538465484655846568465784658846598466084661846628466384664846658466684667846688466984670846718467284673846748467584676846778467884679846808468184682846838468484685846868468784688846898469084691846928469384694846958469684697846988469984700847018470284703847048470584706847078470884709847108471184712847138471484715847168471784718847198472084721847228472384724847258472684727847288472984730847318473284733847348473584736847378473884739847408474184742847438474484745847468474784748847498475084751847528475384754847558475684757847588475984760847618476284763847648476584766847678476884769847708477184772847738477484775847768477784778847798478084781847828478384784847858478684787847888478984790847918479284793847948479584796847978479884799848008480184802848038480484805848068480784808848098481084811848128481384814848158481684817848188481984820848218482284823848248482584826848278482884829848308483184832848338483484835848368483784838848398484084841848428484384844848458484684847848488484984850848518485284853848548485584856848578485884859848608486184862848638486484865848668486784868848698487084871848728487384874848758487684877848788487984880848818488284883848848488584886848878488884889848908489184892848938489484895848968489784898848998490084901849028490384904849058490684907849088490984910849118491284913849148491584916849178491884919849208492184922849238492484925849268492784928849298493084931849328493384934849358493684937849388493984940849418494284943849448494584946849478494884949849508495184952849538495484955849568495784958849598496084961849628496384964849658496684967849688496984970849718497284973849748497584976849778497884979849808498184982849838498484985849868498784988849898499084991849928499384994849958499684997849988499985000850018500285003850048500585006850078500885009850108501185012850138501485015850168501785018850198502085021850228502385024850258502685027850288502985030850318503285033850348503585036850378503885039850408504185042850438504485045850468504785048850498505085051850528505385054850558505685057850588505985060850618506285063850648506585066850678506885069850708507185072850738507485075850768507785078850798508085081850828508385084850858508685087850888508985090850918509285093850948509585096850978509885099851008510185102851038510485105851068510785108851098511085111851128511385114851158511685117851188511985120851218512285123851248512585126851278512885129851308513185132851338513485135851368513785138851398514085141851428514385144851458514685147851488514985150851518515285153851548515585156851578515885159851608516185162851638516485165851668516785168851698517085171851728517385174851758517685177851788517985180851818518285183851848518585186851878518885189851908519185192851938519485195851968519785198851998520085201852028520385204852058520685207852088520985210852118521285213852148521585216852178521885219852208522185222852238522485225852268522785228852298523085231852328523385234852358523685237852388523985240852418524285243852448524585246852478524885249852508525185252852538525485255852568525785258852598526085261852628526385264852658526685267852688526985270852718527285273852748527585276852778527885279852808528185282852838528485285852868528785288852898529085291852928529385294852958529685297852988529985300853018530285303853048530585306853078530885309853108531185312853138531485315853168531785318853198532085321853228532385324853258532685327853288532985330853318533285333853348533585336853378533885339853408534185342853438534485345853468534785348853498535085351853528535385354853558535685357853588535985360853618536285363853648536585366853678536885369853708537185372853738537485375853768537785378853798538085381853828538385384853858538685387853888538985390853918539285393853948539585396853978539885399854008540185402854038540485405854068540785408854098541085411854128541385414854158541685417854188541985420854218542285423854248542585426854278542885429854308543185432854338543485435854368543785438854398544085441854428544385444854458544685447854488544985450854518545285453854548545585456854578545885459854608546185462854638546485465854668546785468854698547085471854728547385474854758547685477854788547985480854818548285483854848548585486854878548885489854908549185492854938549485495854968549785498854998550085501855028550385504855058550685507855088550985510855118551285513855148551585516855178551885519855208552185522855238552485525855268552785528855298553085531855328553385534855358553685537855388553985540855418554285543855448554585546855478554885549855508555185552855538555485555855568555785558855598556085561855628556385564855658556685567855688556985570855718557285573855748557585576855778557885579855808558185582855838558485585855868558785588855898559085591855928559385594855958559685597855988559985600856018560285603856048560585606856078560885609856108561185612856138561485615856168561785618856198562085621856228562385624856258562685627856288562985630856318563285633856348563585636856378563885639856408564185642856438564485645856468564785648856498565085651856528565385654856558565685657856588565985660856618566285663856648566585666856678566885669856708567185672856738567485675856768567785678856798568085681856828568385684856858568685687856888568985690856918569285693856948569585696856978569885699857008570185702857038570485705857068570785708857098571085711857128571385714857158571685717857188571985720857218572285723857248572585726857278572885729857308573185732857338573485735857368573785738857398574085741857428574385744857458574685747857488574985750857518575285753857548575585756857578575885759857608576185762857638576485765857668576785768857698577085771857728577385774857758577685777857788577985780857818578285783857848578585786857878578885789857908579185792857938579485795857968579785798857998580085801858028580385804858058580685807858088580985810858118581285813858148581585816858178581885819858208582185822858238582485825858268582785828858298583085831858328583385834858358583685837858388583985840858418584285843858448584585846858478584885849858508585185852858538585485855858568585785858858598586085861858628586385864858658586685867858688586985870858718587285873858748587585876858778587885879858808588185882858838588485885858868588785888858898589085891858928589385894858958589685897858988589985900859018590285903859048590585906859078590885909859108591185912859138591485915859168591785918859198592085921859228592385924859258592685927859288592985930859318593285933859348593585936859378593885939859408594185942859438594485945859468594785948859498595085951859528595385954859558595685957859588595985960859618596285963859648596585966859678596885969859708597185972859738597485975859768597785978859798598085981859828598385984859858598685987859888598985990859918599285993859948599585996859978599885999860008600186002860038600486005860068600786008860098601086011860128601386014860158601686017860188601986020860218602286023860248602586026860278602886029860308603186032860338603486035860368603786038860398604086041860428604386044860458604686047860488604986050860518605286053860548605586056860578605886059860608606186062860638606486065860668606786068860698607086071860728607386074860758607686077860788607986080860818608286083860848608586086860878608886089860908609186092860938609486095860968609786098860998610086101861028610386104861058610686107861088610986110861118611286113861148611586116861178611886119861208612186122861238612486125861268612786128861298613086131861328613386134861358613686137861388613986140861418614286143861448614586146861478614886149861508615186152861538615486155861568615786158861598616086161861628616386164861658616686167861688616986170861718617286173861748617586176861778617886179861808618186182861838618486185861868618786188861898619086191861928619386194861958619686197861988619986200862018620286203862048620586206862078620886209862108621186212862138621486215862168621786218862198622086221862228622386224862258622686227862288622986230862318623286233862348623586236862378623886239862408624186242862438624486245862468624786248862498625086251862528625386254862558625686257862588625986260862618626286263862648626586266862678626886269862708627186272862738627486275862768627786278862798628086281862828628386284862858628686287862888628986290862918629286293862948629586296862978629886299863008630186302863038630486305863068630786308863098631086311863128631386314863158631686317863188631986320863218632286323863248632586326863278632886329863308633186332863338633486335863368633786338863398634086341863428634386344863458634686347863488634986350863518635286353863548635586356863578635886359863608636186362863638636486365863668636786368863698637086371863728637386374863758637686377863788637986380863818638286383863848638586386863878638886389863908639186392863938639486395863968639786398863998640086401864028640386404864058640686407864088640986410864118641286413864148641586416864178641886419864208642186422864238642486425864268642786428864298643086431864328643386434864358643686437864388643986440864418644286443864448644586446864478644886449864508645186452864538645486455864568645786458864598646086461864628646386464864658646686467864688646986470864718647286473864748647586476864778647886479864808648186482864838648486485864868648786488864898649086491864928649386494864958649686497864988649986500865018650286503865048650586506865078650886509865108651186512865138651486515865168651786518865198652086521865228652386524865258652686527865288652986530865318653286533865348653586536865378653886539865408654186542865438654486545865468654786548865498655086551865528655386554865558655686557865588655986560865618656286563865648656586566865678656886569865708657186572865738657486575865768657786578865798658086581865828658386584865858658686587865888658986590865918659286593865948659586596865978659886599866008660186602866038660486605866068660786608866098661086611866128661386614866158661686617866188661986620866218662286623866248662586626866278662886629866308663186632866338663486635866368663786638866398664086641866428664386644866458664686647866488664986650866518665286653866548665586656866578665886659866608666186662866638666486665866668666786668866698667086671866728667386674866758667686677
  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":68,"xtend":71}],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":69,"xtend":71}],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":70}],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":66}],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. (function (global, factory) {
  5587. typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
  5588. typeof define === 'function' && define.amd ? define(['exports'], factory) :
  5589. (global = global || self, factory(global.THREE = {}));
  5590. }(this, (function (exports) { 'use strict';
  5591. // Polyfills
  5592. if ( Number.EPSILON === undefined ) {
  5593. Number.EPSILON = Math.pow( 2, - 52 );
  5594. }
  5595. if ( Number.isInteger === undefined ) {
  5596. // Missing in IE
  5597. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isInteger
  5598. Number.isInteger = function ( value ) {
  5599. return typeof value === 'number' && isFinite( value ) && Math.floor( value ) === value;
  5600. };
  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 () {
  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. var REVISION = '115';
  5640. var MOUSE = { LEFT: 0, MIDDLE: 1, RIGHT: 2, ROTATE: 0, DOLLY: 1, PAN: 2 };
  5641. var TOUCH = { ROTATE: 0, PAN: 1, DOLLY_PAN: 2, DOLLY_ROTATE: 3 };
  5642. var CullFaceNone = 0;
  5643. var CullFaceBack = 1;
  5644. var CullFaceFront = 2;
  5645. var CullFaceFrontBack = 3;
  5646. var FrontFaceDirectionCW = 0;
  5647. var FrontFaceDirectionCCW = 1;
  5648. var BasicShadowMap = 0;
  5649. var PCFShadowMap = 1;
  5650. var PCFSoftShadowMap = 2;
  5651. var VSMShadowMap = 3;
  5652. var FrontSide = 0;
  5653. var BackSide = 1;
  5654. var DoubleSide = 2;
  5655. var FlatShading = 1;
  5656. var SmoothShading = 2;
  5657. var NoBlending = 0;
  5658. var NormalBlending = 1;
  5659. var AdditiveBlending = 2;
  5660. var SubtractiveBlending = 3;
  5661. var MultiplyBlending = 4;
  5662. var CustomBlending = 5;
  5663. var AddEquation = 100;
  5664. var SubtractEquation = 101;
  5665. var ReverseSubtractEquation = 102;
  5666. var MinEquation = 103;
  5667. var MaxEquation = 104;
  5668. var ZeroFactor = 200;
  5669. var OneFactor = 201;
  5670. var SrcColorFactor = 202;
  5671. var OneMinusSrcColorFactor = 203;
  5672. var SrcAlphaFactor = 204;
  5673. var OneMinusSrcAlphaFactor = 205;
  5674. var DstAlphaFactor = 206;
  5675. var OneMinusDstAlphaFactor = 207;
  5676. var DstColorFactor = 208;
  5677. var OneMinusDstColorFactor = 209;
  5678. var SrcAlphaSaturateFactor = 210;
  5679. var NeverDepth = 0;
  5680. var AlwaysDepth = 1;
  5681. var LessDepth = 2;
  5682. var LessEqualDepth = 3;
  5683. var EqualDepth = 4;
  5684. var GreaterEqualDepth = 5;
  5685. var GreaterDepth = 6;
  5686. var NotEqualDepth = 7;
  5687. var MultiplyOperation = 0;
  5688. var MixOperation = 1;
  5689. var AddOperation = 2;
  5690. var NoToneMapping = 0;
  5691. var LinearToneMapping = 1;
  5692. var ReinhardToneMapping = 2;
  5693. var Uncharted2ToneMapping = 3;
  5694. var CineonToneMapping = 4;
  5695. var ACESFilmicToneMapping = 5;
  5696. var UVMapping = 300;
  5697. var CubeReflectionMapping = 301;
  5698. var CubeRefractionMapping = 302;
  5699. var EquirectangularReflectionMapping = 303;
  5700. var EquirectangularRefractionMapping = 304;
  5701. var SphericalReflectionMapping = 305;
  5702. var CubeUVReflectionMapping = 306;
  5703. var CubeUVRefractionMapping = 307;
  5704. var RepeatWrapping = 1000;
  5705. var ClampToEdgeWrapping = 1001;
  5706. var MirroredRepeatWrapping = 1002;
  5707. var NearestFilter = 1003;
  5708. var NearestMipmapNearestFilter = 1004;
  5709. var NearestMipMapNearestFilter = 1004;
  5710. var NearestMipmapLinearFilter = 1005;
  5711. var NearestMipMapLinearFilter = 1005;
  5712. var LinearFilter = 1006;
  5713. var LinearMipmapNearestFilter = 1007;
  5714. var LinearMipMapNearestFilter = 1007;
  5715. var LinearMipmapLinearFilter = 1008;
  5716. var LinearMipMapLinearFilter = 1008;
  5717. var UnsignedByteType = 1009;
  5718. var ByteType = 1010;
  5719. var ShortType = 1011;
  5720. var UnsignedShortType = 1012;
  5721. var IntType = 1013;
  5722. var UnsignedIntType = 1014;
  5723. var FloatType = 1015;
  5724. var HalfFloatType = 1016;
  5725. var UnsignedShort4444Type = 1017;
  5726. var UnsignedShort5551Type = 1018;
  5727. var UnsignedShort565Type = 1019;
  5728. var UnsignedInt248Type = 1020;
  5729. var AlphaFormat = 1021;
  5730. var RGBFormat = 1022;
  5731. var RGBAFormat = 1023;
  5732. var LuminanceFormat = 1024;
  5733. var LuminanceAlphaFormat = 1025;
  5734. var RGBEFormat = RGBAFormat;
  5735. var DepthFormat = 1026;
  5736. var DepthStencilFormat = 1027;
  5737. var RedFormat = 1028;
  5738. var RedIntegerFormat = 1029;
  5739. var RGFormat = 1030;
  5740. var RGIntegerFormat = 1031;
  5741. var RGBIntegerFormat = 1032;
  5742. var RGBAIntegerFormat = 1033;
  5743. var RGB_S3TC_DXT1_Format = 33776;
  5744. var RGBA_S3TC_DXT1_Format = 33777;
  5745. var RGBA_S3TC_DXT3_Format = 33778;
  5746. var RGBA_S3TC_DXT5_Format = 33779;
  5747. var RGB_PVRTC_4BPPV1_Format = 35840;
  5748. var RGB_PVRTC_2BPPV1_Format = 35841;
  5749. var RGBA_PVRTC_4BPPV1_Format = 35842;
  5750. var RGBA_PVRTC_2BPPV1_Format = 35843;
  5751. var RGB_ETC1_Format = 36196;
  5752. var RGB_ETC2_Format = 37492;
  5753. var RGBA_ETC2_EAC_Format = 37496;
  5754. var RGBA_ASTC_4x4_Format = 37808;
  5755. var RGBA_ASTC_5x4_Format = 37809;
  5756. var RGBA_ASTC_5x5_Format = 37810;
  5757. var RGBA_ASTC_6x5_Format = 37811;
  5758. var RGBA_ASTC_6x6_Format = 37812;
  5759. var RGBA_ASTC_8x5_Format = 37813;
  5760. var RGBA_ASTC_8x6_Format = 37814;
  5761. var RGBA_ASTC_8x8_Format = 37815;
  5762. var RGBA_ASTC_10x5_Format = 37816;
  5763. var RGBA_ASTC_10x6_Format = 37817;
  5764. var RGBA_ASTC_10x8_Format = 37818;
  5765. var RGBA_ASTC_10x10_Format = 37819;
  5766. var RGBA_ASTC_12x10_Format = 37820;
  5767. var RGBA_ASTC_12x12_Format = 37821;
  5768. var RGBA_BPTC_Format = 36492;
  5769. var SRGB8_ALPHA8_ASTC_4x4_Format = 37840;
  5770. var SRGB8_ALPHA8_ASTC_5x4_Format = 37841;
  5771. var SRGB8_ALPHA8_ASTC_5x5_Format = 37842;
  5772. var SRGB8_ALPHA8_ASTC_6x5_Format = 37843;
  5773. var SRGB8_ALPHA8_ASTC_6x6_Format = 37844;
  5774. var SRGB8_ALPHA8_ASTC_8x5_Format = 37845;
  5775. var SRGB8_ALPHA8_ASTC_8x6_Format = 37846;
  5776. var SRGB8_ALPHA8_ASTC_8x8_Format = 37847;
  5777. var SRGB8_ALPHA8_ASTC_10x5_Format = 37848;
  5778. var SRGB8_ALPHA8_ASTC_10x6_Format = 37849;
  5779. var SRGB8_ALPHA8_ASTC_10x8_Format = 37850;
  5780. var SRGB8_ALPHA8_ASTC_10x10_Format = 37851;
  5781. var SRGB8_ALPHA8_ASTC_12x10_Format = 37852;
  5782. var SRGB8_ALPHA8_ASTC_12x12_Format = 37853;
  5783. var LoopOnce = 2200;
  5784. var LoopRepeat = 2201;
  5785. var LoopPingPong = 2202;
  5786. var InterpolateDiscrete = 2300;
  5787. var InterpolateLinear = 2301;
  5788. var InterpolateSmooth = 2302;
  5789. var ZeroCurvatureEnding = 2400;
  5790. var ZeroSlopeEnding = 2401;
  5791. var WrapAroundEnding = 2402;
  5792. var TrianglesDrawMode = 0;
  5793. var TriangleStripDrawMode = 1;
  5794. var TriangleFanDrawMode = 2;
  5795. var LinearEncoding = 3000;
  5796. var sRGBEncoding = 3001;
  5797. var GammaEncoding = 3007;
  5798. var RGBEEncoding = 3002;
  5799. var LogLuvEncoding = 3003;
  5800. var RGBM7Encoding = 3004;
  5801. var RGBM16Encoding = 3005;
  5802. var RGBDEncoding = 3006;
  5803. var BasicDepthPacking = 3200;
  5804. var RGBADepthPacking = 3201;
  5805. var TangentSpaceNormalMap = 0;
  5806. var ObjectSpaceNormalMap = 1;
  5807. var ZeroStencilOp = 0;
  5808. var KeepStencilOp = 7680;
  5809. var ReplaceStencilOp = 7681;
  5810. var IncrementStencilOp = 7682;
  5811. var DecrementStencilOp = 7683;
  5812. var IncrementWrapStencilOp = 34055;
  5813. var DecrementWrapStencilOp = 34056;
  5814. var InvertStencilOp = 5386;
  5815. var NeverStencilFunc = 512;
  5816. var LessStencilFunc = 513;
  5817. var EqualStencilFunc = 514;
  5818. var LessEqualStencilFunc = 515;
  5819. var GreaterStencilFunc = 516;
  5820. var NotEqualStencilFunc = 517;
  5821. var GreaterEqualStencilFunc = 518;
  5822. var AlwaysStencilFunc = 519;
  5823. var StaticDrawUsage = 35044;
  5824. var DynamicDrawUsage = 35048;
  5825. var StreamDrawUsage = 35040;
  5826. var StaticReadUsage = 35045;
  5827. var DynamicReadUsage = 35049;
  5828. var StreamReadUsage = 35041;
  5829. var StaticCopyUsage = 35046;
  5830. var DynamicCopyUsage = 35050;
  5831. var StreamCopyUsage = 35042;
  5832. /**
  5833. * https://github.com/mrdoob/eventdispatcher.js/
  5834. */
  5835. function EventDispatcher() {}
  5836. Object.assign( EventDispatcher.prototype, {
  5837. addEventListener: function ( type, listener ) {
  5838. if ( this._listeners === undefined ) { this._listeners = {}; }
  5839. var listeners = this._listeners;
  5840. if ( listeners[ type ] === undefined ) {
  5841. listeners[ type ] = [];
  5842. }
  5843. if ( listeners[ type ].indexOf( listener ) === - 1 ) {
  5844. listeners[ type ].push( listener );
  5845. }
  5846. },
  5847. hasEventListener: function ( type, listener ) {
  5848. if ( this._listeners === undefined ) { return false; }
  5849. var listeners = this._listeners;
  5850. return listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1;
  5851. },
  5852. removeEventListener: function ( type, listener ) {
  5853. if ( this._listeners === undefined ) { return; }
  5854. var listeners = this._listeners;
  5855. var listenerArray = listeners[ type ];
  5856. if ( listenerArray !== undefined ) {
  5857. var index = listenerArray.indexOf( listener );
  5858. if ( index !== - 1 ) {
  5859. listenerArray.splice( index, 1 );
  5860. }
  5861. }
  5862. },
  5863. dispatchEvent: function ( event ) {
  5864. if ( this._listeners === undefined ) { return; }
  5865. var listeners = this._listeners;
  5866. var listenerArray = listeners[ event.type ];
  5867. if ( listenerArray !== undefined ) {
  5868. event.target = this;
  5869. // Make a copy, in case listeners are removed while iterating.
  5870. var array = listenerArray.slice( 0 );
  5871. for ( var i = 0, l = array.length; i < l; i ++ ) {
  5872. array[ i ].call( this, event );
  5873. }
  5874. }
  5875. }
  5876. } );
  5877. /**
  5878. * @author alteredq / http://alteredqualia.com/
  5879. * @author mrdoob / http://mrdoob.com/
  5880. * @author WestLangley / http://github.com/WestLangley
  5881. * @author thezwap
  5882. */
  5883. var _lut = [];
  5884. for ( var i = 0; i < 256; i ++ ) {
  5885. _lut[ i ] = ( i < 16 ? '0' : '' ) + ( i ).toString( 16 );
  5886. }
  5887. var MathUtils = {
  5888. DEG2RAD: Math.PI / 180,
  5889. RAD2DEG: 180 / Math.PI,
  5890. generateUUID: function () {
  5891. // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/21963136#21963136
  5892. var d0 = Math.random() * 0xffffffff | 0;
  5893. var d1 = Math.random() * 0xffffffff | 0;
  5894. var d2 = Math.random() * 0xffffffff | 0;
  5895. var d3 = Math.random() * 0xffffffff | 0;
  5896. var uuid = _lut[ d0 & 0xff ] + _lut[ d0 >> 8 & 0xff ] + _lut[ d0 >> 16 & 0xff ] + _lut[ d0 >> 24 & 0xff ] + '-' +
  5897. _lut[ d1 & 0xff ] + _lut[ d1 >> 8 & 0xff ] + '-' + _lut[ d1 >> 16 & 0x0f | 0x40 ] + _lut[ d1 >> 24 & 0xff ] + '-' +
  5898. _lut[ d2 & 0x3f | 0x80 ] + _lut[ d2 >> 8 & 0xff ] + '-' + _lut[ d2 >> 16 & 0xff ] + _lut[ d2 >> 24 & 0xff ] +
  5899. _lut[ d3 & 0xff ] + _lut[ d3 >> 8 & 0xff ] + _lut[ d3 >> 16 & 0xff ] + _lut[ d3 >> 24 & 0xff ];
  5900. // .toUpperCase() here flattens concatenated strings to save heap memory space.
  5901. return uuid.toUpperCase();
  5902. },
  5903. clamp: function ( value, min, max ) {
  5904. return Math.max( min, Math.min( max, value ) );
  5905. },
  5906. // compute euclidian modulo of m % n
  5907. // https://en.wikipedia.org/wiki/Modulo_operation
  5908. euclideanModulo: function ( n, m ) {
  5909. return ( ( n % m ) + m ) % m;
  5910. },
  5911. // Linear mapping from range <a1, a2> to range <b1, b2>
  5912. mapLinear: function ( x, a1, a2, b1, b2 ) {
  5913. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  5914. },
  5915. // https://en.wikipedia.org/wiki/Linear_interpolation
  5916. lerp: function ( x, y, t ) {
  5917. return ( 1 - t ) * x + t * y;
  5918. },
  5919. // http://en.wikipedia.org/wiki/Smoothstep
  5920. smoothstep: function ( x, min, max ) {
  5921. if ( x <= min ) { return 0; }
  5922. if ( x >= max ) { return 1; }
  5923. x = ( x - min ) / ( max - min );
  5924. return x * x * ( 3 - 2 * x );
  5925. },
  5926. smootherstep: function ( x, min, max ) {
  5927. if ( x <= min ) { return 0; }
  5928. if ( x >= max ) { return 1; }
  5929. x = ( x - min ) / ( max - min );
  5930. return x * x * x * ( x * ( x * 6 - 15 ) + 10 );
  5931. },
  5932. // Random integer from <low, high> interval
  5933. randInt: function ( low, high ) {
  5934. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  5935. },
  5936. // Random float from <low, high> interval
  5937. randFloat: function ( low, high ) {
  5938. return low + Math.random() * ( high - low );
  5939. },
  5940. // Random float from <-range/2, range/2> interval
  5941. randFloatSpread: function ( range ) {
  5942. return range * ( 0.5 - Math.random() );
  5943. },
  5944. degToRad: function ( degrees ) {
  5945. return degrees * MathUtils.DEG2RAD;
  5946. },
  5947. radToDeg: function ( radians ) {
  5948. return radians * MathUtils.RAD2DEG;
  5949. },
  5950. isPowerOfTwo: function ( value ) {
  5951. return ( value & ( value - 1 ) ) === 0 && value !== 0;
  5952. },
  5953. ceilPowerOfTwo: function ( value ) {
  5954. return Math.pow( 2, Math.ceil( Math.log( value ) / Math.LN2 ) );
  5955. },
  5956. floorPowerOfTwo: function ( value ) {
  5957. return Math.pow( 2, Math.floor( Math.log( value ) / Math.LN2 ) );
  5958. },
  5959. setQuaternionFromProperEuler: function ( q, a, b, c, order ) {
  5960. // Intrinsic Proper Euler Angles - see https://en.wikipedia.org/wiki/Euler_angles
  5961. // rotations are applied to the axes in the order specified by 'order'
  5962. // rotation by angle 'a' is applied first, then by angle 'b', then by angle 'c'
  5963. // angles are in radians
  5964. var cos = Math.cos;
  5965. var sin = Math.sin;
  5966. var c2 = cos( b / 2 );
  5967. var s2 = sin( b / 2 );
  5968. var c13 = cos( ( a + c ) / 2 );
  5969. var s13 = sin( ( a + c ) / 2 );
  5970. var c1_3 = cos( ( a - c ) / 2 );
  5971. var s1_3 = sin( ( a - c ) / 2 );
  5972. var c3_1 = cos( ( c - a ) / 2 );
  5973. var s3_1 = sin( ( c - a ) / 2 );
  5974. if ( order === 'XYX' ) {
  5975. q.set( c2 * s13, s2 * c1_3, s2 * s1_3, c2 * c13 );
  5976. } else if ( order === 'YZY' ) {
  5977. q.set( s2 * s1_3, c2 * s13, s2 * c1_3, c2 * c13 );
  5978. } else if ( order === 'ZXZ' ) {
  5979. q.set( s2 * c1_3, s2 * s1_3, c2 * s13, c2 * c13 );
  5980. } else if ( order === 'XZX' ) {
  5981. q.set( c2 * s13, s2 * s3_1, s2 * c3_1, c2 * c13 );
  5982. } else if ( order === 'YXY' ) {
  5983. q.set( s2 * c3_1, c2 * s13, s2 * s3_1, c2 * c13 );
  5984. } else if ( order === 'ZYZ' ) {
  5985. q.set( s2 * s3_1, s2 * c3_1, c2 * s13, c2 * c13 );
  5986. } else {
  5987. console.warn( 'THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order.' );
  5988. }
  5989. }
  5990. };
  5991. /**
  5992. * @author mrdoob / http://mrdoob.com/
  5993. * @author philogb / http://blog.thejit.org/
  5994. * @author egraether / http://egraether.com/
  5995. * @author zz85 / http://www.lab4games.net/zz85/blog
  5996. */
  5997. function Vector2( x, y ) {
  5998. this.x = x || 0;
  5999. this.y = y || 0;
  6000. }
  6001. Object.defineProperties( Vector2.prototype, {
  6002. "width": {
  6003. get: function () {
  6004. return this.x;
  6005. },
  6006. set: function ( value ) {
  6007. this.x = value;
  6008. }
  6009. },
  6010. "height": {
  6011. get: function () {
  6012. return this.y;
  6013. },
  6014. set: function ( value ) {
  6015. this.y = value;
  6016. }
  6017. }
  6018. } );
  6019. Object.assign( Vector2.prototype, {
  6020. isVector2: true,
  6021. set: function ( x, y ) {
  6022. this.x = x;
  6023. this.y = y;
  6024. return this;
  6025. },
  6026. setScalar: function ( scalar ) {
  6027. this.x = scalar;
  6028. this.y = scalar;
  6029. return this;
  6030. },
  6031. setX: function ( x ) {
  6032. this.x = x;
  6033. return this;
  6034. },
  6035. setY: function ( y ) {
  6036. this.y = y;
  6037. return this;
  6038. },
  6039. setComponent: function ( index, value ) {
  6040. switch ( index ) {
  6041. case 0: this.x = value; break;
  6042. case 1: this.y = value; break;
  6043. default: throw new Error( 'index is out of range: ' + index );
  6044. }
  6045. return this;
  6046. },
  6047. getComponent: function ( index ) {
  6048. switch ( index ) {
  6049. case 0: return this.x;
  6050. case 1: return this.y;
  6051. default: throw new Error( 'index is out of range: ' + index );
  6052. }
  6053. },
  6054. clone: function () {
  6055. return new this.constructor( this.x, this.y );
  6056. },
  6057. copy: function ( v ) {
  6058. this.x = v.x;
  6059. this.y = v.y;
  6060. return this;
  6061. },
  6062. add: function ( v, w ) {
  6063. if ( w !== undefined ) {
  6064. console.warn( 'THREE.Vector2: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  6065. return this.addVectors( v, w );
  6066. }
  6067. this.x += v.x;
  6068. this.y += v.y;
  6069. return this;
  6070. },
  6071. addScalar: function ( s ) {
  6072. this.x += s;
  6073. this.y += s;
  6074. return this;
  6075. },
  6076. addVectors: function ( a, b ) {
  6077. this.x = a.x + b.x;
  6078. this.y = a.y + b.y;
  6079. return this;
  6080. },
  6081. addScaledVector: function ( v, s ) {
  6082. this.x += v.x * s;
  6083. this.y += v.y * s;
  6084. return this;
  6085. },
  6086. sub: function ( v, w ) {
  6087. if ( w !== undefined ) {
  6088. console.warn( 'THREE.Vector2: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  6089. return this.subVectors( v, w );
  6090. }
  6091. this.x -= v.x;
  6092. this.y -= v.y;
  6093. return this;
  6094. },
  6095. subScalar: function ( s ) {
  6096. this.x -= s;
  6097. this.y -= s;
  6098. return this;
  6099. },
  6100. subVectors: function ( a, b ) {
  6101. this.x = a.x - b.x;
  6102. this.y = a.y - b.y;
  6103. return this;
  6104. },
  6105. multiply: function ( v ) {
  6106. this.x *= v.x;
  6107. this.y *= v.y;
  6108. return this;
  6109. },
  6110. multiplyScalar: function ( scalar ) {
  6111. this.x *= scalar;
  6112. this.y *= scalar;
  6113. return this;
  6114. },
  6115. divide: function ( v ) {
  6116. this.x /= v.x;
  6117. this.y /= v.y;
  6118. return this;
  6119. },
  6120. divideScalar: function ( scalar ) {
  6121. return this.multiplyScalar( 1 / scalar );
  6122. },
  6123. applyMatrix3: function ( m ) {
  6124. var x = this.x, y = this.y;
  6125. var e = m.elements;
  6126. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ];
  6127. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ];
  6128. return this;
  6129. },
  6130. min: function ( v ) {
  6131. this.x = Math.min( this.x, v.x );
  6132. this.y = Math.min( this.y, v.y );
  6133. return this;
  6134. },
  6135. max: function ( v ) {
  6136. this.x = Math.max( this.x, v.x );
  6137. this.y = Math.max( this.y, v.y );
  6138. return this;
  6139. },
  6140. clamp: function ( min, max ) {
  6141. // assumes min < max, componentwise
  6142. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  6143. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  6144. return this;
  6145. },
  6146. clampScalar: function ( minVal, maxVal ) {
  6147. this.x = Math.max( minVal, Math.min( maxVal, this.x ) );
  6148. this.y = Math.max( minVal, Math.min( maxVal, this.y ) );
  6149. return this;
  6150. },
  6151. clampLength: function ( min, max ) {
  6152. var length = this.length();
  6153. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  6154. },
  6155. floor: function () {
  6156. this.x = Math.floor( this.x );
  6157. this.y = Math.floor( this.y );
  6158. return this;
  6159. },
  6160. ceil: function () {
  6161. this.x = Math.ceil( this.x );
  6162. this.y = Math.ceil( this.y );
  6163. return this;
  6164. },
  6165. round: function () {
  6166. this.x = Math.round( this.x );
  6167. this.y = Math.round( this.y );
  6168. return this;
  6169. },
  6170. roundToZero: function () {
  6171. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  6172. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  6173. return this;
  6174. },
  6175. negate: function () {
  6176. this.x = - this.x;
  6177. this.y = - this.y;
  6178. return this;
  6179. },
  6180. dot: function ( v ) {
  6181. return this.x * v.x + this.y * v.y;
  6182. },
  6183. cross: function ( v ) {
  6184. return this.x * v.y - this.y * v.x;
  6185. },
  6186. lengthSq: function () {
  6187. return this.x * this.x + this.y * this.y;
  6188. },
  6189. length: function () {
  6190. return Math.sqrt( this.x * this.x + this.y * this.y );
  6191. },
  6192. manhattanLength: function () {
  6193. return Math.abs( this.x ) + Math.abs( this.y );
  6194. },
  6195. normalize: function () {
  6196. return this.divideScalar( this.length() || 1 );
  6197. },
  6198. angle: function () {
  6199. // computes the angle in radians with respect to the positive x-axis
  6200. var angle = Math.atan2( - this.y, - this.x ) + Math.PI;
  6201. return angle;
  6202. },
  6203. distanceTo: function ( v ) {
  6204. return Math.sqrt( this.distanceToSquared( v ) );
  6205. },
  6206. distanceToSquared: function ( v ) {
  6207. var dx = this.x - v.x, dy = this.y - v.y;
  6208. return dx * dx + dy * dy;
  6209. },
  6210. manhattanDistanceTo: function ( v ) {
  6211. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y );
  6212. },
  6213. setLength: function ( length ) {
  6214. return this.normalize().multiplyScalar( length );
  6215. },
  6216. lerp: function ( v, alpha ) {
  6217. this.x += ( v.x - this.x ) * alpha;
  6218. this.y += ( v.y - this.y ) * alpha;
  6219. return this;
  6220. },
  6221. lerpVectors: function ( v1, v2, alpha ) {
  6222. return this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 );
  6223. },
  6224. equals: function ( v ) {
  6225. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  6226. },
  6227. fromArray: function ( array, offset ) {
  6228. if ( offset === undefined ) { offset = 0; }
  6229. this.x = array[ offset ];
  6230. this.y = array[ offset + 1 ];
  6231. return this;
  6232. },
  6233. toArray: function ( array, offset ) {
  6234. if ( array === undefined ) { array = []; }
  6235. if ( offset === undefined ) { offset = 0; }
  6236. array[ offset ] = this.x;
  6237. array[ offset + 1 ] = this.y;
  6238. return array;
  6239. },
  6240. fromBufferAttribute: function ( attribute, index, offset ) {
  6241. if ( offset !== undefined ) {
  6242. console.warn( 'THREE.Vector2: offset has been removed from .fromBufferAttribute().' );
  6243. }
  6244. this.x = attribute.getX( index );
  6245. this.y = attribute.getY( index );
  6246. return this;
  6247. },
  6248. rotateAround: function ( center, angle ) {
  6249. var c = Math.cos( angle ), s = Math.sin( angle );
  6250. var x = this.x - center.x;
  6251. var y = this.y - center.y;
  6252. this.x = x * c - y * s + center.x;
  6253. this.y = x * s + y * c + center.y;
  6254. return this;
  6255. }
  6256. } );
  6257. /**
  6258. * @author alteredq / http://alteredqualia.com/
  6259. * @author WestLangley / http://github.com/WestLangley
  6260. * @author bhouston / http://clara.io
  6261. * @author tschw
  6262. */
  6263. function Matrix3() {
  6264. this.elements = [
  6265. 1, 0, 0,
  6266. 0, 1, 0,
  6267. 0, 0, 1
  6268. ];
  6269. if ( arguments.length > 0 ) {
  6270. console.error( 'THREE.Matrix3: the constructor no longer reads arguments. use .set() instead.' );
  6271. }
  6272. }
  6273. Object.assign( Matrix3.prototype, {
  6274. isMatrix3: true,
  6275. set: function ( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  6276. var te = this.elements;
  6277. te[ 0 ] = n11; te[ 1 ] = n21; te[ 2 ] = n31;
  6278. te[ 3 ] = n12; te[ 4 ] = n22; te[ 5 ] = n32;
  6279. te[ 6 ] = n13; te[ 7 ] = n23; te[ 8 ] = n33;
  6280. return this;
  6281. },
  6282. identity: function () {
  6283. this.set(
  6284. 1, 0, 0,
  6285. 0, 1, 0,
  6286. 0, 0, 1
  6287. );
  6288. return this;
  6289. },
  6290. clone: function () {
  6291. return new this.constructor().fromArray( this.elements );
  6292. },
  6293. copy: function ( m ) {
  6294. var te = this.elements;
  6295. var me = m.elements;
  6296. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ];
  6297. te[ 3 ] = me[ 3 ]; te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ];
  6298. te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ]; te[ 8 ] = me[ 8 ];
  6299. return this;
  6300. },
  6301. extractBasis: function ( xAxis, yAxis, zAxis ) {
  6302. xAxis.setFromMatrix3Column( this, 0 );
  6303. yAxis.setFromMatrix3Column( this, 1 );
  6304. zAxis.setFromMatrix3Column( this, 2 );
  6305. return this;
  6306. },
  6307. setFromMatrix4: function ( m ) {
  6308. var me = m.elements;
  6309. this.set(
  6310. me[ 0 ], me[ 4 ], me[ 8 ],
  6311. me[ 1 ], me[ 5 ], me[ 9 ],
  6312. me[ 2 ], me[ 6 ], me[ 10 ]
  6313. );
  6314. return this;
  6315. },
  6316. multiply: function ( m ) {
  6317. return this.multiplyMatrices( this, m );
  6318. },
  6319. premultiply: function ( m ) {
  6320. return this.multiplyMatrices( m, this );
  6321. },
  6322. multiplyMatrices: function ( a, b ) {
  6323. var ae = a.elements;
  6324. var be = b.elements;
  6325. var te = this.elements;
  6326. var a11 = ae[ 0 ], a12 = ae[ 3 ], a13 = ae[ 6 ];
  6327. var a21 = ae[ 1 ], a22 = ae[ 4 ], a23 = ae[ 7 ];
  6328. var a31 = ae[ 2 ], a32 = ae[ 5 ], a33 = ae[ 8 ];
  6329. var b11 = be[ 0 ], b12 = be[ 3 ], b13 = be[ 6 ];
  6330. var b21 = be[ 1 ], b22 = be[ 4 ], b23 = be[ 7 ];
  6331. var b31 = be[ 2 ], b32 = be[ 5 ], b33 = be[ 8 ];
  6332. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31;
  6333. te[ 3 ] = a11 * b12 + a12 * b22 + a13 * b32;
  6334. te[ 6 ] = a11 * b13 + a12 * b23 + a13 * b33;
  6335. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31;
  6336. te[ 4 ] = a21 * b12 + a22 * b22 + a23 * b32;
  6337. te[ 7 ] = a21 * b13 + a22 * b23 + a23 * b33;
  6338. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31;
  6339. te[ 5 ] = a31 * b12 + a32 * b22 + a33 * b32;
  6340. te[ 8 ] = a31 * b13 + a32 * b23 + a33 * b33;
  6341. return this;
  6342. },
  6343. multiplyScalar: function ( s ) {
  6344. var te = this.elements;
  6345. te[ 0 ] *= s; te[ 3 ] *= s; te[ 6 ] *= s;
  6346. te[ 1 ] *= s; te[ 4 ] *= s; te[ 7 ] *= s;
  6347. te[ 2 ] *= s; te[ 5 ] *= s; te[ 8 ] *= s;
  6348. return this;
  6349. },
  6350. determinant: function () {
  6351. var te = this.elements;
  6352. var a = te[ 0 ], b = te[ 1 ], c = te[ 2 ],
  6353. d = te[ 3 ], e = te[ 4 ], f = te[ 5 ],
  6354. g = te[ 6 ], h = te[ 7 ], i = te[ 8 ];
  6355. return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;
  6356. },
  6357. getInverse: function ( matrix, throwOnDegenerate ) {
  6358. if ( throwOnDegenerate !== undefined ) {
  6359. console.warn( "THREE.Matrix3: .getInverse() can no longer be configured to throw on degenerate." );
  6360. }
  6361. var me = matrix.elements,
  6362. te = this.elements,
  6363. n11 = me[ 0 ], n21 = me[ 1 ], n31 = me[ 2 ],
  6364. n12 = me[ 3 ], n22 = me[ 4 ], n32 = me[ 5 ],
  6365. n13 = me[ 6 ], n23 = me[ 7 ], n33 = me[ 8 ],
  6366. t11 = n33 * n22 - n32 * n23,
  6367. t12 = n32 * n13 - n33 * n12,
  6368. t13 = n23 * n12 - n22 * n13,
  6369. det = n11 * t11 + n21 * t12 + n31 * t13;
  6370. if ( det === 0 ) { return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0 ); }
  6371. var detInv = 1 / det;
  6372. te[ 0 ] = t11 * detInv;
  6373. te[ 1 ] = ( n31 * n23 - n33 * n21 ) * detInv;
  6374. te[ 2 ] = ( n32 * n21 - n31 * n22 ) * detInv;
  6375. te[ 3 ] = t12 * detInv;
  6376. te[ 4 ] = ( n33 * n11 - n31 * n13 ) * detInv;
  6377. te[ 5 ] = ( n31 * n12 - n32 * n11 ) * detInv;
  6378. te[ 6 ] = t13 * detInv;
  6379. te[ 7 ] = ( n21 * n13 - n23 * n11 ) * detInv;
  6380. te[ 8 ] = ( n22 * n11 - n21 * n12 ) * detInv;
  6381. return this;
  6382. },
  6383. transpose: function () {
  6384. var tmp, m = this.elements;
  6385. tmp = m[ 1 ]; m[ 1 ] = m[ 3 ]; m[ 3 ] = tmp;
  6386. tmp = m[ 2 ]; m[ 2 ] = m[ 6 ]; m[ 6 ] = tmp;
  6387. tmp = m[ 5 ]; m[ 5 ] = m[ 7 ]; m[ 7 ] = tmp;
  6388. return this;
  6389. },
  6390. getNormalMatrix: function ( matrix4 ) {
  6391. return this.setFromMatrix4( matrix4 ).getInverse( this ).transpose();
  6392. },
  6393. transposeIntoArray: function ( r ) {
  6394. var m = this.elements;
  6395. r[ 0 ] = m[ 0 ];
  6396. r[ 1 ] = m[ 3 ];
  6397. r[ 2 ] = m[ 6 ];
  6398. r[ 3 ] = m[ 1 ];
  6399. r[ 4 ] = m[ 4 ];
  6400. r[ 5 ] = m[ 7 ];
  6401. r[ 6 ] = m[ 2 ];
  6402. r[ 7 ] = m[ 5 ];
  6403. r[ 8 ] = m[ 8 ];
  6404. return this;
  6405. },
  6406. setUvTransform: function ( tx, ty, sx, sy, rotation, cx, cy ) {
  6407. var c = Math.cos( rotation );
  6408. var s = Math.sin( rotation );
  6409. this.set(
  6410. sx * c, sx * s, - sx * ( c * cx + s * cy ) + cx + tx,
  6411. - sy * s, sy * c, - sy * ( - s * cx + c * cy ) + cy + ty,
  6412. 0, 0, 1
  6413. );
  6414. },
  6415. scale: function ( sx, sy ) {
  6416. var te = this.elements;
  6417. te[ 0 ] *= sx; te[ 3 ] *= sx; te[ 6 ] *= sx;
  6418. te[ 1 ] *= sy; te[ 4 ] *= sy; te[ 7 ] *= sy;
  6419. return this;
  6420. },
  6421. rotate: function ( theta ) {
  6422. var c = Math.cos( theta );
  6423. var s = Math.sin( theta );
  6424. var te = this.elements;
  6425. var a11 = te[ 0 ], a12 = te[ 3 ], a13 = te[ 6 ];
  6426. var a21 = te[ 1 ], a22 = te[ 4 ], a23 = te[ 7 ];
  6427. te[ 0 ] = c * a11 + s * a21;
  6428. te[ 3 ] = c * a12 + s * a22;
  6429. te[ 6 ] = c * a13 + s * a23;
  6430. te[ 1 ] = - s * a11 + c * a21;
  6431. te[ 4 ] = - s * a12 + c * a22;
  6432. te[ 7 ] = - s * a13 + c * a23;
  6433. return this;
  6434. },
  6435. translate: function ( tx, ty ) {
  6436. var te = this.elements;
  6437. te[ 0 ] += tx * te[ 2 ]; te[ 3 ] += tx * te[ 5 ]; te[ 6 ] += tx * te[ 8 ];
  6438. te[ 1 ] += ty * te[ 2 ]; te[ 4 ] += ty * te[ 5 ]; te[ 7 ] += ty * te[ 8 ];
  6439. return this;
  6440. },
  6441. equals: function ( matrix ) {
  6442. var te = this.elements;
  6443. var me = matrix.elements;
  6444. for ( var i = 0; i < 9; i ++ ) {
  6445. if ( te[ i ] !== me[ i ] ) { return false; }
  6446. }
  6447. return true;
  6448. },
  6449. fromArray: function ( array, offset ) {
  6450. if ( offset === undefined ) { offset = 0; }
  6451. for ( var i = 0; i < 9; i ++ ) {
  6452. this.elements[ i ] = array[ i + offset ];
  6453. }
  6454. return this;
  6455. },
  6456. toArray: function ( array, offset ) {
  6457. if ( array === undefined ) { array = []; }
  6458. if ( offset === undefined ) { offset = 0; }
  6459. var te = this.elements;
  6460. array[ offset ] = te[ 0 ];
  6461. array[ offset + 1 ] = te[ 1 ];
  6462. array[ offset + 2 ] = te[ 2 ];
  6463. array[ offset + 3 ] = te[ 3 ];
  6464. array[ offset + 4 ] = te[ 4 ];
  6465. array[ offset + 5 ] = te[ 5 ];
  6466. array[ offset + 6 ] = te[ 6 ];
  6467. array[ offset + 7 ] = te[ 7 ];
  6468. array[ offset + 8 ] = te[ 8 ];
  6469. return array;
  6470. }
  6471. } );
  6472. /**
  6473. * @author mrdoob / http://mrdoob.com/
  6474. * @author alteredq / http://alteredqualia.com/
  6475. * @author szimek / https://github.com/szimek/
  6476. */
  6477. var _canvas;
  6478. var ImageUtils = {
  6479. getDataURL: function ( image ) {
  6480. var canvas;
  6481. if ( typeof HTMLCanvasElement == 'undefined' ) {
  6482. return image.src;
  6483. } else if ( image instanceof HTMLCanvasElement ) {
  6484. canvas = image;
  6485. } else {
  6486. if ( _canvas === undefined ) { _canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' ); }
  6487. _canvas.width = image.width;
  6488. _canvas.height = image.height;
  6489. var context = _canvas.getContext( '2d' );
  6490. if ( image instanceof ImageData ) {
  6491. context.putImageData( image, 0, 0 );
  6492. } else {
  6493. context.drawImage( image, 0, 0, image.width, image.height );
  6494. }
  6495. canvas = _canvas;
  6496. }
  6497. if ( canvas.width > 2048 || canvas.height > 2048 ) {
  6498. return canvas.toDataURL( 'image/jpeg', 0.6 );
  6499. } else {
  6500. return canvas.toDataURL( 'image/png' );
  6501. }
  6502. }
  6503. };
  6504. /**
  6505. * @author mrdoob / http://mrdoob.com/
  6506. * @author alteredq / http://alteredqualia.com/
  6507. * @author szimek / https://github.com/szimek/
  6508. */
  6509. var textureId = 0;
  6510. function Texture( image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ) {
  6511. Object.defineProperty( this, 'id', { value: textureId ++ } );
  6512. this.uuid = MathUtils.generateUUID();
  6513. this.name = '';
  6514. this.image = image !== undefined ? image : Texture.DEFAULT_IMAGE;
  6515. this.mipmaps = [];
  6516. this.mapping = mapping !== undefined ? mapping : Texture.DEFAULT_MAPPING;
  6517. this.wrapS = wrapS !== undefined ? wrapS : ClampToEdgeWrapping;
  6518. this.wrapT = wrapT !== undefined ? wrapT : ClampToEdgeWrapping;
  6519. this.magFilter = magFilter !== undefined ? magFilter : LinearFilter;
  6520. this.minFilter = minFilter !== undefined ? minFilter : LinearMipmapLinearFilter;
  6521. this.anisotropy = anisotropy !== undefined ? anisotropy : 1;
  6522. this.format = format !== undefined ? format : RGBAFormat;
  6523. this.internalFormat = null;
  6524. this.type = type !== undefined ? type : UnsignedByteType;
  6525. this.offset = new Vector2( 0, 0 );
  6526. this.repeat = new Vector2( 1, 1 );
  6527. this.center = new Vector2( 0, 0 );
  6528. this.rotation = 0;
  6529. this.matrixAutoUpdate = true;
  6530. this.matrix = new Matrix3();
  6531. this.generateMipmaps = true;
  6532. this.premultiplyAlpha = false;
  6533. this.flipY = true;
  6534. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  6535. // Values of encoding !== THREE.LinearEncoding only supported on map, envMap and emissiveMap.
  6536. //
  6537. // Also changing the encoding after already used by a Material will not automatically make the Material
  6538. // update. You need to explicitly call Material.needsUpdate to trigger it to recompile.
  6539. this.encoding = encoding !== undefined ? encoding : LinearEncoding;
  6540. this.version = 0;
  6541. this.onUpdate = null;
  6542. }
  6543. Texture.DEFAULT_IMAGE = undefined;
  6544. Texture.DEFAULT_MAPPING = UVMapping;
  6545. Texture.prototype = Object.assign( Object.create( EventDispatcher.prototype ), {
  6546. constructor: Texture,
  6547. isTexture: true,
  6548. updateMatrix: function () {
  6549. this.matrix.setUvTransform( this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y );
  6550. },
  6551. clone: function () {
  6552. return new this.constructor().copy( this );
  6553. },
  6554. copy: function ( source ) {
  6555. this.name = source.name;
  6556. this.image = source.image;
  6557. this.mipmaps = source.mipmaps.slice( 0 );
  6558. this.mapping = source.mapping;
  6559. this.wrapS = source.wrapS;
  6560. this.wrapT = source.wrapT;
  6561. this.magFilter = source.magFilter;
  6562. this.minFilter = source.minFilter;
  6563. this.anisotropy = source.anisotropy;
  6564. this.format = source.format;
  6565. this.internalFormat = source.internalFormat;
  6566. this.type = source.type;
  6567. this.offset.copy( source.offset );
  6568. this.repeat.copy( source.repeat );
  6569. this.center.copy( source.center );
  6570. this.rotation = source.rotation;
  6571. this.matrixAutoUpdate = source.matrixAutoUpdate;
  6572. this.matrix.copy( source.matrix );
  6573. this.generateMipmaps = source.generateMipmaps;
  6574. this.premultiplyAlpha = source.premultiplyAlpha;
  6575. this.flipY = source.flipY;
  6576. this.unpackAlignment = source.unpackAlignment;
  6577. this.encoding = source.encoding;
  6578. return this;
  6579. },
  6580. toJSON: function ( meta ) {
  6581. var isRootObject = ( meta === undefined || typeof meta === 'string' );
  6582. if ( ! isRootObject && meta.textures[ this.uuid ] !== undefined ) {
  6583. return meta.textures[ this.uuid ];
  6584. }
  6585. var output = {
  6586. metadata: {
  6587. version: 4.5,
  6588. type: 'Texture',
  6589. generator: 'Texture.toJSON'
  6590. },
  6591. uuid: this.uuid,
  6592. name: this.name,
  6593. mapping: this.mapping,
  6594. repeat: [ this.repeat.x, this.repeat.y ],
  6595. offset: [ this.offset.x, this.offset.y ],
  6596. center: [ this.center.x, this.center.y ],
  6597. rotation: this.rotation,
  6598. wrap: [ this.wrapS, this.wrapT ],
  6599. format: this.format,
  6600. type: this.type,
  6601. encoding: this.encoding,
  6602. minFilter: this.minFilter,
  6603. magFilter: this.magFilter,
  6604. anisotropy: this.anisotropy,
  6605. flipY: this.flipY,
  6606. premultiplyAlpha: this.premultiplyAlpha,
  6607. unpackAlignment: this.unpackAlignment
  6608. };
  6609. if ( this.image !== undefined ) {
  6610. // TODO: Move to THREE.Image
  6611. var image = this.image;
  6612. if ( image.uuid === undefined ) {
  6613. image.uuid = MathUtils.generateUUID(); // UGH
  6614. }
  6615. if ( ! isRootObject && meta.images[ image.uuid ] === undefined ) {
  6616. var url;
  6617. if ( Array.isArray( image ) ) {
  6618. // process array of images e.g. CubeTexture
  6619. url = [];
  6620. for ( var i = 0, l = image.length; i < l; i ++ ) {
  6621. url.push( ImageUtils.getDataURL( image[ i ] ) );
  6622. }
  6623. } else {
  6624. // process single image
  6625. url = ImageUtils.getDataURL( image );
  6626. }
  6627. meta.images[ image.uuid ] = {
  6628. uuid: image.uuid,
  6629. url: url
  6630. };
  6631. }
  6632. output.image = image.uuid;
  6633. }
  6634. if ( ! isRootObject ) {
  6635. meta.textures[ this.uuid ] = output;
  6636. }
  6637. return output;
  6638. },
  6639. dispose: function () {
  6640. this.dispatchEvent( { type: 'dispose' } );
  6641. },
  6642. transformUv: function ( uv ) {
  6643. if ( this.mapping !== UVMapping ) { return uv; }
  6644. uv.applyMatrix3( this.matrix );
  6645. if ( uv.x < 0 || uv.x > 1 ) {
  6646. switch ( this.wrapS ) {
  6647. case RepeatWrapping:
  6648. uv.x = uv.x - Math.floor( uv.x );
  6649. break;
  6650. case ClampToEdgeWrapping:
  6651. uv.x = uv.x < 0 ? 0 : 1;
  6652. break;
  6653. case MirroredRepeatWrapping:
  6654. if ( Math.abs( Math.floor( uv.x ) % 2 ) === 1 ) {
  6655. uv.x = Math.ceil( uv.x ) - uv.x;
  6656. } else {
  6657. uv.x = uv.x - Math.floor( uv.x );
  6658. }
  6659. break;
  6660. }
  6661. }
  6662. if ( uv.y < 0 || uv.y > 1 ) {
  6663. switch ( this.wrapT ) {
  6664. case RepeatWrapping:
  6665. uv.y = uv.y - Math.floor( uv.y );
  6666. break;
  6667. case ClampToEdgeWrapping:
  6668. uv.y = uv.y < 0 ? 0 : 1;
  6669. break;
  6670. case MirroredRepeatWrapping:
  6671. if ( Math.abs( Math.floor( uv.y ) % 2 ) === 1 ) {
  6672. uv.y = Math.ceil( uv.y ) - uv.y;
  6673. } else {
  6674. uv.y = uv.y - Math.floor( uv.y );
  6675. }
  6676. break;
  6677. }
  6678. }
  6679. if ( this.flipY ) {
  6680. uv.y = 1 - uv.y;
  6681. }
  6682. return uv;
  6683. }
  6684. } );
  6685. Object.defineProperty( Texture.prototype, "needsUpdate", {
  6686. set: function ( value ) {
  6687. if ( value === true ) { this.version ++; }
  6688. }
  6689. } );
  6690. /**
  6691. * @author supereggbert / http://www.paulbrunt.co.uk/
  6692. * @author philogb / http://blog.thejit.org/
  6693. * @author mikael emtinger / http://gomo.se/
  6694. * @author egraether / http://egraether.com/
  6695. * @author WestLangley / http://github.com/WestLangley
  6696. */
  6697. function Vector4( x, y, z, w ) {
  6698. this.x = x || 0;
  6699. this.y = y || 0;
  6700. this.z = z || 0;
  6701. this.w = ( w !== undefined ) ? w : 1;
  6702. }
  6703. Object.defineProperties( Vector4.prototype, {
  6704. "width": {
  6705. get: function () {
  6706. return this.z;
  6707. },
  6708. set: function ( value ) {
  6709. this.z = value;
  6710. }
  6711. },
  6712. "height": {
  6713. get: function () {
  6714. return this.w;
  6715. },
  6716. set: function ( value ) {
  6717. this.w = value;
  6718. }
  6719. }
  6720. } );
  6721. Object.assign( Vector4.prototype, {
  6722. isVector4: true,
  6723. set: function ( x, y, z, w ) {
  6724. this.x = x;
  6725. this.y = y;
  6726. this.z = z;
  6727. this.w = w;
  6728. return this;
  6729. },
  6730. setScalar: function ( scalar ) {
  6731. this.x = scalar;
  6732. this.y = scalar;
  6733. this.z = scalar;
  6734. this.w = scalar;
  6735. return this;
  6736. },
  6737. setX: function ( x ) {
  6738. this.x = x;
  6739. return this;
  6740. },
  6741. setY: function ( y ) {
  6742. this.y = y;
  6743. return this;
  6744. },
  6745. setZ: function ( z ) {
  6746. this.z = z;
  6747. return this;
  6748. },
  6749. setW: function ( w ) {
  6750. this.w = w;
  6751. return this;
  6752. },
  6753. setComponent: function ( index, value ) {
  6754. switch ( index ) {
  6755. case 0: this.x = value; break;
  6756. case 1: this.y = value; break;
  6757. case 2: this.z = value; break;
  6758. case 3: this.w = value; break;
  6759. default: throw new Error( 'index is out of range: ' + index );
  6760. }
  6761. return this;
  6762. },
  6763. getComponent: function ( index ) {
  6764. switch ( index ) {
  6765. case 0: return this.x;
  6766. case 1: return this.y;
  6767. case 2: return this.z;
  6768. case 3: return this.w;
  6769. default: throw new Error( 'index is out of range: ' + index );
  6770. }
  6771. },
  6772. clone: function () {
  6773. return new this.constructor( this.x, this.y, this.z, this.w );
  6774. },
  6775. copy: function ( v ) {
  6776. this.x = v.x;
  6777. this.y = v.y;
  6778. this.z = v.z;
  6779. this.w = ( v.w !== undefined ) ? v.w : 1;
  6780. return this;
  6781. },
  6782. add: function ( v, w ) {
  6783. if ( w !== undefined ) {
  6784. console.warn( 'THREE.Vector4: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  6785. return this.addVectors( v, w );
  6786. }
  6787. this.x += v.x;
  6788. this.y += v.y;
  6789. this.z += v.z;
  6790. this.w += v.w;
  6791. return this;
  6792. },
  6793. addScalar: function ( s ) {
  6794. this.x += s;
  6795. this.y += s;
  6796. this.z += s;
  6797. this.w += s;
  6798. return this;
  6799. },
  6800. addVectors: function ( a, b ) {
  6801. this.x = a.x + b.x;
  6802. this.y = a.y + b.y;
  6803. this.z = a.z + b.z;
  6804. this.w = a.w + b.w;
  6805. return this;
  6806. },
  6807. addScaledVector: function ( v, s ) {
  6808. this.x += v.x * s;
  6809. this.y += v.y * s;
  6810. this.z += v.z * s;
  6811. this.w += v.w * s;
  6812. return this;
  6813. },
  6814. sub: function ( v, w ) {
  6815. if ( w !== undefined ) {
  6816. console.warn( 'THREE.Vector4: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  6817. return this.subVectors( v, w );
  6818. }
  6819. this.x -= v.x;
  6820. this.y -= v.y;
  6821. this.z -= v.z;
  6822. this.w -= v.w;
  6823. return this;
  6824. },
  6825. subScalar: function ( s ) {
  6826. this.x -= s;
  6827. this.y -= s;
  6828. this.z -= s;
  6829. this.w -= s;
  6830. return this;
  6831. },
  6832. subVectors: function ( a, b ) {
  6833. this.x = a.x - b.x;
  6834. this.y = a.y - b.y;
  6835. this.z = a.z - b.z;
  6836. this.w = a.w - b.w;
  6837. return this;
  6838. },
  6839. multiplyScalar: function ( scalar ) {
  6840. this.x *= scalar;
  6841. this.y *= scalar;
  6842. this.z *= scalar;
  6843. this.w *= scalar;
  6844. return this;
  6845. },
  6846. applyMatrix4: function ( m ) {
  6847. var x = this.x, y = this.y, z = this.z, w = this.w;
  6848. var e = m.elements;
  6849. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] * w;
  6850. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] * w;
  6851. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] * w;
  6852. this.w = e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] * w;
  6853. return this;
  6854. },
  6855. divideScalar: function ( scalar ) {
  6856. return this.multiplyScalar( 1 / scalar );
  6857. },
  6858. setAxisAngleFromQuaternion: function ( q ) {
  6859. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  6860. // q is assumed to be normalized
  6861. this.w = 2 * Math.acos( q.w );
  6862. var s = Math.sqrt( 1 - q.w * q.w );
  6863. if ( s < 0.0001 ) {
  6864. this.x = 1;
  6865. this.y = 0;
  6866. this.z = 0;
  6867. } else {
  6868. this.x = q.x / s;
  6869. this.y = q.y / s;
  6870. this.z = q.z / s;
  6871. }
  6872. return this;
  6873. },
  6874. setAxisAngleFromRotationMatrix: function ( m ) {
  6875. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  6876. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  6877. var angle, x, y, z, // variables for result
  6878. epsilon = 0.01, // margin to allow for rounding errors
  6879. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  6880. te = m.elements,
  6881. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  6882. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  6883. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  6884. if ( ( Math.abs( m12 - m21 ) < epsilon ) &&
  6885. ( Math.abs( m13 - m31 ) < epsilon ) &&
  6886. ( Math.abs( m23 - m32 ) < epsilon ) ) {
  6887. // singularity found
  6888. // first check for identity matrix which must have +1 for all terms
  6889. // in leading diagonal and zero in other terms
  6890. if ( ( Math.abs( m12 + m21 ) < epsilon2 ) &&
  6891. ( Math.abs( m13 + m31 ) < epsilon2 ) &&
  6892. ( Math.abs( m23 + m32 ) < epsilon2 ) &&
  6893. ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  6894. // this singularity is identity matrix so angle = 0
  6895. this.set( 1, 0, 0, 0 );
  6896. return this; // zero angle, arbitrary axis
  6897. }
  6898. // otherwise this singularity is angle = 180
  6899. angle = Math.PI;
  6900. var xx = ( m11 + 1 ) / 2;
  6901. var yy = ( m22 + 1 ) / 2;
  6902. var zz = ( m33 + 1 ) / 2;
  6903. var xy = ( m12 + m21 ) / 4;
  6904. var xz = ( m13 + m31 ) / 4;
  6905. var yz = ( m23 + m32 ) / 4;
  6906. if ( ( xx > yy ) && ( xx > zz ) ) {
  6907. // m11 is the largest diagonal term
  6908. if ( xx < epsilon ) {
  6909. x = 0;
  6910. y = 0.707106781;
  6911. z = 0.707106781;
  6912. } else {
  6913. x = Math.sqrt( xx );
  6914. y = xy / x;
  6915. z = xz / x;
  6916. }
  6917. } else if ( yy > zz ) {
  6918. // m22 is the largest diagonal term
  6919. if ( yy < epsilon ) {
  6920. x = 0.707106781;
  6921. y = 0;
  6922. z = 0.707106781;
  6923. } else {
  6924. y = Math.sqrt( yy );
  6925. x = xy / y;
  6926. z = yz / y;
  6927. }
  6928. } else {
  6929. // m33 is the largest diagonal term so base result on this
  6930. if ( zz < epsilon ) {
  6931. x = 0.707106781;
  6932. y = 0.707106781;
  6933. z = 0;
  6934. } else {
  6935. z = Math.sqrt( zz );
  6936. x = xz / z;
  6937. y = yz / z;
  6938. }
  6939. }
  6940. this.set( x, y, z, angle );
  6941. return this; // return 180 deg rotation
  6942. }
  6943. // as we have reached here there are no singularities so we can handle normally
  6944. var s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 ) +
  6945. ( m13 - m31 ) * ( m13 - m31 ) +
  6946. ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  6947. if ( Math.abs( s ) < 0.001 ) { s = 1; }
  6948. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  6949. // caught by singularity test above, but I've left it in just in case
  6950. this.x = ( m32 - m23 ) / s;
  6951. this.y = ( m13 - m31 ) / s;
  6952. this.z = ( m21 - m12 ) / s;
  6953. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  6954. return this;
  6955. },
  6956. min: function ( v ) {
  6957. this.x = Math.min( this.x, v.x );
  6958. this.y = Math.min( this.y, v.y );
  6959. this.z = Math.min( this.z, v.z );
  6960. this.w = Math.min( this.w, v.w );
  6961. return this;
  6962. },
  6963. max: function ( v ) {
  6964. this.x = Math.max( this.x, v.x );
  6965. this.y = Math.max( this.y, v.y );
  6966. this.z = Math.max( this.z, v.z );
  6967. this.w = Math.max( this.w, v.w );
  6968. return this;
  6969. },
  6970. clamp: function ( min, max ) {
  6971. // assumes min < max, componentwise
  6972. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  6973. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  6974. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  6975. this.w = Math.max( min.w, Math.min( max.w, this.w ) );
  6976. return this;
  6977. },
  6978. clampScalar: function ( minVal, maxVal ) {
  6979. this.x = Math.max( minVal, Math.min( maxVal, this.x ) );
  6980. this.y = Math.max( minVal, Math.min( maxVal, this.y ) );
  6981. this.z = Math.max( minVal, Math.min( maxVal, this.z ) );
  6982. this.w = Math.max( minVal, Math.min( maxVal, this.w ) );
  6983. return this;
  6984. },
  6985. clampLength: function ( min, max ) {
  6986. var length = this.length();
  6987. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  6988. },
  6989. floor: function () {
  6990. this.x = Math.floor( this.x );
  6991. this.y = Math.floor( this.y );
  6992. this.z = Math.floor( this.z );
  6993. this.w = Math.floor( this.w );
  6994. return this;
  6995. },
  6996. ceil: function () {
  6997. this.x = Math.ceil( this.x );
  6998. this.y = Math.ceil( this.y );
  6999. this.z = Math.ceil( this.z );
  7000. this.w = Math.ceil( this.w );
  7001. return this;
  7002. },
  7003. round: function () {
  7004. this.x = Math.round( this.x );
  7005. this.y = Math.round( this.y );
  7006. this.z = Math.round( this.z );
  7007. this.w = Math.round( this.w );
  7008. return this;
  7009. },
  7010. roundToZero: function () {
  7011. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  7012. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  7013. this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
  7014. this.w = ( this.w < 0 ) ? Math.ceil( this.w ) : Math.floor( this.w );
  7015. return this;
  7016. },
  7017. negate: function () {
  7018. this.x = - this.x;
  7019. this.y = - this.y;
  7020. this.z = - this.z;
  7021. this.w = - this.w;
  7022. return this;
  7023. },
  7024. dot: function ( v ) {
  7025. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  7026. },
  7027. lengthSq: function () {
  7028. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  7029. },
  7030. length: function () {
  7031. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  7032. },
  7033. manhattanLength: function () {
  7034. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  7035. },
  7036. normalize: function () {
  7037. return this.divideScalar( this.length() || 1 );
  7038. },
  7039. setLength: function ( length ) {
  7040. return this.normalize().multiplyScalar( length );
  7041. },
  7042. lerp: function ( v, alpha ) {
  7043. this.x += ( v.x - this.x ) * alpha;
  7044. this.y += ( v.y - this.y ) * alpha;
  7045. this.z += ( v.z - this.z ) * alpha;
  7046. this.w += ( v.w - this.w ) * alpha;
  7047. return this;
  7048. },
  7049. lerpVectors: function ( v1, v2, alpha ) {
  7050. return this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 );
  7051. },
  7052. equals: function ( v ) {
  7053. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  7054. },
  7055. fromArray: function ( array, offset ) {
  7056. if ( offset === undefined ) { offset = 0; }
  7057. this.x = array[ offset ];
  7058. this.y = array[ offset + 1 ];
  7059. this.z = array[ offset + 2 ];
  7060. this.w = array[ offset + 3 ];
  7061. return this;
  7062. },
  7063. toArray: function ( array, offset ) {
  7064. if ( array === undefined ) { array = []; }
  7065. if ( offset === undefined ) { offset = 0; }
  7066. array[ offset ] = this.x;
  7067. array[ offset + 1 ] = this.y;
  7068. array[ offset + 2 ] = this.z;
  7069. array[ offset + 3 ] = this.w;
  7070. return array;
  7071. },
  7072. fromBufferAttribute: function ( attribute, index, offset ) {
  7073. if ( offset !== undefined ) {
  7074. console.warn( 'THREE.Vector4: offset has been removed from .fromBufferAttribute().' );
  7075. }
  7076. this.x = attribute.getX( index );
  7077. this.y = attribute.getY( index );
  7078. this.z = attribute.getZ( index );
  7079. this.w = attribute.getW( index );
  7080. return this;
  7081. }
  7082. } );
  7083. /**
  7084. * @author szimek / https://github.com/szimek/
  7085. * @author alteredq / http://alteredqualia.com/
  7086. * @author Marius Kintel / https://github.com/kintel
  7087. */
  7088. /*
  7089. In options, we can specify:
  7090. * Texture parameters for an auto-generated target texture
  7091. * depthBuffer/stencilBuffer: Booleans to indicate if we should generate these buffers
  7092. */
  7093. function WebGLRenderTarget( width, height, options ) {
  7094. this.width = width;
  7095. this.height = height;
  7096. this.scissor = new Vector4( 0, 0, width, height );
  7097. this.scissorTest = false;
  7098. this.viewport = new Vector4( 0, 0, width, height );
  7099. options = options || {};
  7100. this.texture = new Texture( undefined, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding );
  7101. this.texture.image = {};
  7102. this.texture.image.width = width;
  7103. this.texture.image.height = height;
  7104. this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
  7105. this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
  7106. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  7107. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : true;
  7108. this.depthTexture = options.depthTexture !== undefined ? options.depthTexture : null;
  7109. }
  7110. WebGLRenderTarget.prototype = Object.assign( Object.create( EventDispatcher.prototype ), {
  7111. constructor: WebGLRenderTarget,
  7112. isWebGLRenderTarget: true,
  7113. setSize: function ( width, height ) {
  7114. if ( this.width !== width || this.height !== height ) {
  7115. this.width = width;
  7116. this.height = height;
  7117. this.texture.image.width = width;
  7118. this.texture.image.height = height;
  7119. this.dispose();
  7120. }
  7121. this.viewport.set( 0, 0, width, height );
  7122. this.scissor.set( 0, 0, width, height );
  7123. },
  7124. clone: function () {
  7125. return new this.constructor().copy( this );
  7126. },
  7127. copy: function ( source ) {
  7128. this.width = source.width;
  7129. this.height = source.height;
  7130. this.viewport.copy( source.viewport );
  7131. this.texture = source.texture.clone();
  7132. this.depthBuffer = source.depthBuffer;
  7133. this.stencilBuffer = source.stencilBuffer;
  7134. this.depthTexture = source.depthTexture;
  7135. return this;
  7136. },
  7137. dispose: function () {
  7138. this.dispatchEvent( { type: 'dispose' } );
  7139. }
  7140. } );
  7141. /**
  7142. * @author Mugen87 / https://github.com/Mugen87
  7143. * @author Matt DesLauriers / @mattdesl
  7144. */
  7145. function WebGLMultisampleRenderTarget( width, height, options ) {
  7146. WebGLRenderTarget.call( this, width, height, options );
  7147. this.samples = 4;
  7148. }
  7149. WebGLMultisampleRenderTarget.prototype = Object.assign( Object.create( WebGLRenderTarget.prototype ), {
  7150. constructor: WebGLMultisampleRenderTarget,
  7151. isWebGLMultisampleRenderTarget: true,
  7152. copy: function ( source ) {
  7153. WebGLRenderTarget.prototype.copy.call( this, source );
  7154. this.samples = source.samples;
  7155. return this;
  7156. }
  7157. } );
  7158. /**
  7159. * @author mikael emtinger / http://gomo.se/
  7160. * @author alteredq / http://alteredqualia.com/
  7161. * @author WestLangley / http://github.com/WestLangley
  7162. * @author bhouston / http://clara.io
  7163. */
  7164. function Quaternion( x, y, z, w ) {
  7165. this._x = x || 0;
  7166. this._y = y || 0;
  7167. this._z = z || 0;
  7168. this._w = ( w !== undefined ) ? w : 1;
  7169. }
  7170. Object.assign( Quaternion, {
  7171. slerp: function ( qa, qb, qm, t ) {
  7172. return qm.copy( qa ).slerp( qb, t );
  7173. },
  7174. slerpFlat: function ( dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t ) {
  7175. // fuzz-free, array-based Quaternion SLERP operation
  7176. var x0 = src0[ srcOffset0 + 0 ],
  7177. y0 = src0[ srcOffset0 + 1 ],
  7178. z0 = src0[ srcOffset0 + 2 ],
  7179. w0 = src0[ srcOffset0 + 3 ],
  7180. x1 = src1[ srcOffset1 + 0 ],
  7181. y1 = src1[ srcOffset1 + 1 ],
  7182. z1 = src1[ srcOffset1 + 2 ],
  7183. w1 = src1[ srcOffset1 + 3 ];
  7184. if ( w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1 ) {
  7185. var s = 1 - t,
  7186. cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1,
  7187. dir = ( cos >= 0 ? 1 : - 1 ),
  7188. sqrSin = 1 - cos * cos;
  7189. // Skip the Slerp for tiny steps to avoid numeric problems:
  7190. if ( sqrSin > Number.EPSILON ) {
  7191. var sin = Math.sqrt( sqrSin ),
  7192. len = Math.atan2( sin, cos * dir );
  7193. s = Math.sin( s * len ) / sin;
  7194. t = Math.sin( t * len ) / sin;
  7195. }
  7196. var tDir = t * dir;
  7197. x0 = x0 * s + x1 * tDir;
  7198. y0 = y0 * s + y1 * tDir;
  7199. z0 = z0 * s + z1 * tDir;
  7200. w0 = w0 * s + w1 * tDir;
  7201. // Normalize in case we just did a lerp:
  7202. if ( s === 1 - t ) {
  7203. var f = 1 / Math.sqrt( x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0 );
  7204. x0 *= f;
  7205. y0 *= f;
  7206. z0 *= f;
  7207. w0 *= f;
  7208. }
  7209. }
  7210. dst[ dstOffset ] = x0;
  7211. dst[ dstOffset + 1 ] = y0;
  7212. dst[ dstOffset + 2 ] = z0;
  7213. dst[ dstOffset + 3 ] = w0;
  7214. }
  7215. } );
  7216. Object.defineProperties( Quaternion.prototype, {
  7217. x: {
  7218. get: function () {
  7219. return this._x;
  7220. },
  7221. set: function ( value ) {
  7222. this._x = value;
  7223. this._onChangeCallback();
  7224. }
  7225. },
  7226. y: {
  7227. get: function () {
  7228. return this._y;
  7229. },
  7230. set: function ( value ) {
  7231. this._y = value;
  7232. this._onChangeCallback();
  7233. }
  7234. },
  7235. z: {
  7236. get: function () {
  7237. return this._z;
  7238. },
  7239. set: function ( value ) {
  7240. this._z = value;
  7241. this._onChangeCallback();
  7242. }
  7243. },
  7244. w: {
  7245. get: function () {
  7246. return this._w;
  7247. },
  7248. set: function ( value ) {
  7249. this._w = value;
  7250. this._onChangeCallback();
  7251. }
  7252. }
  7253. } );
  7254. Object.assign( Quaternion.prototype, {
  7255. isQuaternion: true,
  7256. set: function ( x, y, z, w ) {
  7257. this._x = x;
  7258. this._y = y;
  7259. this._z = z;
  7260. this._w = w;
  7261. this._onChangeCallback();
  7262. return this;
  7263. },
  7264. clone: function () {
  7265. return new this.constructor( this._x, this._y, this._z, this._w );
  7266. },
  7267. copy: function ( quaternion ) {
  7268. this._x = quaternion.x;
  7269. this._y = quaternion.y;
  7270. this._z = quaternion.z;
  7271. this._w = quaternion.w;
  7272. this._onChangeCallback();
  7273. return this;
  7274. },
  7275. setFromEuler: function ( euler, update ) {
  7276. if ( ! ( euler && euler.isEuler ) ) {
  7277. throw new Error( 'THREE.Quaternion: .setFromEuler() now expects an Euler rotation rather than a Vector3 and order.' );
  7278. }
  7279. var x = euler._x, y = euler._y, z = euler._z, order = euler.order;
  7280. // http://www.mathworks.com/matlabcentral/fileexchange/
  7281. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  7282. // content/SpinCalc.m
  7283. var cos = Math.cos;
  7284. var sin = Math.sin;
  7285. var c1 = cos( x / 2 );
  7286. var c2 = cos( y / 2 );
  7287. var c3 = cos( z / 2 );
  7288. var s1 = sin( x / 2 );
  7289. var s2 = sin( y / 2 );
  7290. var s3 = sin( z / 2 );
  7291. if ( order === 'XYZ' ) {
  7292. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  7293. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  7294. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  7295. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  7296. } else if ( order === 'YXZ' ) {
  7297. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  7298. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  7299. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  7300. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  7301. } else if ( order === 'ZXY' ) {
  7302. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  7303. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  7304. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  7305. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  7306. } else if ( order === 'ZYX' ) {
  7307. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  7308. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  7309. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  7310. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  7311. } else if ( order === 'YZX' ) {
  7312. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  7313. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  7314. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  7315. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  7316. } else if ( order === 'XZY' ) {
  7317. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  7318. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  7319. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  7320. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  7321. }
  7322. if ( update !== false ) { this._onChangeCallback(); }
  7323. return this;
  7324. },
  7325. setFromAxisAngle: function ( axis, angle ) {
  7326. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  7327. // assumes axis is normalized
  7328. var halfAngle = angle / 2, s = Math.sin( halfAngle );
  7329. this._x = axis.x * s;
  7330. this._y = axis.y * s;
  7331. this._z = axis.z * s;
  7332. this._w = Math.cos( halfAngle );
  7333. this._onChangeCallback();
  7334. return this;
  7335. },
  7336. setFromRotationMatrix: function ( m ) {
  7337. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  7338. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  7339. var te = m.elements,
  7340. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  7341. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  7342. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ],
  7343. trace = m11 + m22 + m33,
  7344. s;
  7345. if ( trace > 0 ) {
  7346. s = 0.5 / Math.sqrt( trace + 1.0 );
  7347. this._w = 0.25 / s;
  7348. this._x = ( m32 - m23 ) * s;
  7349. this._y = ( m13 - m31 ) * s;
  7350. this._z = ( m21 - m12 ) * s;
  7351. } else if ( m11 > m22 && m11 > m33 ) {
  7352. s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  7353. this._w = ( m32 - m23 ) / s;
  7354. this._x = 0.25 * s;
  7355. this._y = ( m12 + m21 ) / s;
  7356. this._z = ( m13 + m31 ) / s;
  7357. } else if ( m22 > m33 ) {
  7358. s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  7359. this._w = ( m13 - m31 ) / s;
  7360. this._x = ( m12 + m21 ) / s;
  7361. this._y = 0.25 * s;
  7362. this._z = ( m23 + m32 ) / s;
  7363. } else {
  7364. s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  7365. this._w = ( m21 - m12 ) / s;
  7366. this._x = ( m13 + m31 ) / s;
  7367. this._y = ( m23 + m32 ) / s;
  7368. this._z = 0.25 * s;
  7369. }
  7370. this._onChangeCallback();
  7371. return this;
  7372. },
  7373. setFromUnitVectors: function ( vFrom, vTo ) {
  7374. // assumes direction vectors vFrom and vTo are normalized
  7375. var EPS = 0.000001;
  7376. var r = vFrom.dot( vTo ) + 1;
  7377. if ( r < EPS ) {
  7378. r = 0;
  7379. if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) {
  7380. this._x = - vFrom.y;
  7381. this._y = vFrom.x;
  7382. this._z = 0;
  7383. this._w = r;
  7384. } else {
  7385. this._x = 0;
  7386. this._y = - vFrom.z;
  7387. this._z = vFrom.y;
  7388. this._w = r;
  7389. }
  7390. } else {
  7391. // crossVectors( vFrom, vTo ); // inlined to avoid cyclic dependency on Vector3
  7392. this._x = vFrom.y * vTo.z - vFrom.z * vTo.y;
  7393. this._y = vFrom.z * vTo.x - vFrom.x * vTo.z;
  7394. this._z = vFrom.x * vTo.y - vFrom.y * vTo.x;
  7395. this._w = r;
  7396. }
  7397. return this.normalize();
  7398. },
  7399. angleTo: function ( q ) {
  7400. return 2 * Math.acos( Math.abs( MathUtils.clamp( this.dot( q ), - 1, 1 ) ) );
  7401. },
  7402. rotateTowards: function ( q, step ) {
  7403. var angle = this.angleTo( q );
  7404. if ( angle === 0 ) { return this; }
  7405. var t = Math.min( 1, step / angle );
  7406. this.slerp( q, t );
  7407. return this;
  7408. },
  7409. inverse: function () {
  7410. // quaternion is assumed to have unit length
  7411. return this.conjugate();
  7412. },
  7413. conjugate: function () {
  7414. this._x *= - 1;
  7415. this._y *= - 1;
  7416. this._z *= - 1;
  7417. this._onChangeCallback();
  7418. return this;
  7419. },
  7420. dot: function ( v ) {
  7421. return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
  7422. },
  7423. lengthSq: function () {
  7424. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  7425. },
  7426. length: function () {
  7427. return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w );
  7428. },
  7429. normalize: function () {
  7430. var l = this.length();
  7431. if ( l === 0 ) {
  7432. this._x = 0;
  7433. this._y = 0;
  7434. this._z = 0;
  7435. this._w = 1;
  7436. } else {
  7437. l = 1 / l;
  7438. this._x = this._x * l;
  7439. this._y = this._y * l;
  7440. this._z = this._z * l;
  7441. this._w = this._w * l;
  7442. }
  7443. this._onChangeCallback();
  7444. return this;
  7445. },
  7446. multiply: function ( q, p ) {
  7447. if ( p !== undefined ) {
  7448. console.warn( 'THREE.Quaternion: .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead.' );
  7449. return this.multiplyQuaternions( q, p );
  7450. }
  7451. return this.multiplyQuaternions( this, q );
  7452. },
  7453. premultiply: function ( q ) {
  7454. return this.multiplyQuaternions( q, this );
  7455. },
  7456. multiplyQuaternions: function ( a, b ) {
  7457. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  7458. var qax = a._x, qay = a._y, qaz = a._z, qaw = a._w;
  7459. var qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w;
  7460. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  7461. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  7462. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  7463. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  7464. this._onChangeCallback();
  7465. return this;
  7466. },
  7467. slerp: function ( qb, t ) {
  7468. if ( t === 0 ) { return this; }
  7469. if ( t === 1 ) { return this.copy( qb ); }
  7470. var x = this._x, y = this._y, z = this._z, w = this._w;
  7471. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  7472. var cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  7473. if ( cosHalfTheta < 0 ) {
  7474. this._w = - qb._w;
  7475. this._x = - qb._x;
  7476. this._y = - qb._y;
  7477. this._z = - qb._z;
  7478. cosHalfTheta = - cosHalfTheta;
  7479. } else {
  7480. this.copy( qb );
  7481. }
  7482. if ( cosHalfTheta >= 1.0 ) {
  7483. this._w = w;
  7484. this._x = x;
  7485. this._y = y;
  7486. this._z = z;
  7487. return this;
  7488. }
  7489. var sqrSinHalfTheta = 1.0 - cosHalfTheta * cosHalfTheta;
  7490. if ( sqrSinHalfTheta <= Number.EPSILON ) {
  7491. var s = 1 - t;
  7492. this._w = s * w + t * this._w;
  7493. this._x = s * x + t * this._x;
  7494. this._y = s * y + t * this._y;
  7495. this._z = s * z + t * this._z;
  7496. this.normalize();
  7497. this._onChangeCallback();
  7498. return this;
  7499. }
  7500. var sinHalfTheta = Math.sqrt( sqrSinHalfTheta );
  7501. var halfTheta = Math.atan2( sinHalfTheta, cosHalfTheta );
  7502. var ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  7503. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  7504. this._w = ( w * ratioA + this._w * ratioB );
  7505. this._x = ( x * ratioA + this._x * ratioB );
  7506. this._y = ( y * ratioA + this._y * ratioB );
  7507. this._z = ( z * ratioA + this._z * ratioB );
  7508. this._onChangeCallback();
  7509. return this;
  7510. },
  7511. equals: function ( quaternion ) {
  7512. return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w );
  7513. },
  7514. fromArray: function ( array, offset ) {
  7515. if ( offset === undefined ) { offset = 0; }
  7516. this._x = array[ offset ];
  7517. this._y = array[ offset + 1 ];
  7518. this._z = array[ offset + 2 ];
  7519. this._w = array[ offset + 3 ];
  7520. this._onChangeCallback();
  7521. return this;
  7522. },
  7523. toArray: function ( array, offset ) {
  7524. if ( array === undefined ) { array = []; }
  7525. if ( offset === undefined ) { offset = 0; }
  7526. array[ offset ] = this._x;
  7527. array[ offset + 1 ] = this._y;
  7528. array[ offset + 2 ] = this._z;
  7529. array[ offset + 3 ] = this._w;
  7530. return array;
  7531. },
  7532. fromBufferAttribute: function ( attribute, index ) {
  7533. this._x = attribute.getX( index );
  7534. this._y = attribute.getY( index );
  7535. this._z = attribute.getZ( index );
  7536. this._w = attribute.getW( index );
  7537. return this;
  7538. },
  7539. _onChange: function ( callback ) {
  7540. this._onChangeCallback = callback;
  7541. return this;
  7542. },
  7543. _onChangeCallback: function () {}
  7544. } );
  7545. /**
  7546. * @author mrdoob / http://mrdoob.com/
  7547. * @author kile / http://kile.stravaganza.org/
  7548. * @author philogb / http://blog.thejit.org/
  7549. * @author mikael emtinger / http://gomo.se/
  7550. * @author egraether / http://egraether.com/
  7551. * @author WestLangley / http://github.com/WestLangley
  7552. */
  7553. var _vector = new Vector3();
  7554. var _quaternion = new Quaternion();
  7555. function Vector3( x, y, z ) {
  7556. this.x = x || 0;
  7557. this.y = y || 0;
  7558. this.z = z || 0;
  7559. }
  7560. Object.assign( Vector3.prototype, {
  7561. isVector3: true,
  7562. set: function ( x, y, z ) {
  7563. this.x = x;
  7564. this.y = y;
  7565. this.z = z;
  7566. return this;
  7567. },
  7568. setScalar: function ( scalar ) {
  7569. this.x = scalar;
  7570. this.y = scalar;
  7571. this.z = scalar;
  7572. return this;
  7573. },
  7574. setX: function ( x ) {
  7575. this.x = x;
  7576. return this;
  7577. },
  7578. setY: function ( y ) {
  7579. this.y = y;
  7580. return this;
  7581. },
  7582. setZ: function ( z ) {
  7583. this.z = z;
  7584. return this;
  7585. },
  7586. setComponent: function ( index, value ) {
  7587. switch ( index ) {
  7588. case 0: this.x = value; break;
  7589. case 1: this.y = value; break;
  7590. case 2: this.z = value; break;
  7591. default: throw new Error( 'index is out of range: ' + index );
  7592. }
  7593. return this;
  7594. },
  7595. getComponent: function ( index ) {
  7596. switch ( index ) {
  7597. case 0: return this.x;
  7598. case 1: return this.y;
  7599. case 2: return this.z;
  7600. default: throw new Error( 'index is out of range: ' + index );
  7601. }
  7602. },
  7603. clone: function () {
  7604. return new this.constructor( this.x, this.y, this.z );
  7605. },
  7606. copy: function ( v ) {
  7607. this.x = v.x;
  7608. this.y = v.y;
  7609. this.z = v.z;
  7610. return this;
  7611. },
  7612. add: function ( v, w ) {
  7613. if ( w !== undefined ) {
  7614. console.warn( 'THREE.Vector3: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  7615. return this.addVectors( v, w );
  7616. }
  7617. this.x += v.x;
  7618. this.y += v.y;
  7619. this.z += v.z;
  7620. return this;
  7621. },
  7622. addScalar: function ( s ) {
  7623. this.x += s;
  7624. this.y += s;
  7625. this.z += s;
  7626. return this;
  7627. },
  7628. addVectors: function ( a, b ) {
  7629. this.x = a.x + b.x;
  7630. this.y = a.y + b.y;
  7631. this.z = a.z + b.z;
  7632. return this;
  7633. },
  7634. addScaledVector: function ( v, s ) {
  7635. this.x += v.x * s;
  7636. this.y += v.y * s;
  7637. this.z += v.z * s;
  7638. return this;
  7639. },
  7640. sub: function ( v, w ) {
  7641. if ( w !== undefined ) {
  7642. console.warn( 'THREE.Vector3: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  7643. return this.subVectors( v, w );
  7644. }
  7645. this.x -= v.x;
  7646. this.y -= v.y;
  7647. this.z -= v.z;
  7648. return this;
  7649. },
  7650. subScalar: function ( s ) {
  7651. this.x -= s;
  7652. this.y -= s;
  7653. this.z -= s;
  7654. return this;
  7655. },
  7656. subVectors: function ( a, b ) {
  7657. this.x = a.x - b.x;
  7658. this.y = a.y - b.y;
  7659. this.z = a.z - b.z;
  7660. return this;
  7661. },
  7662. multiply: function ( v, w ) {
  7663. if ( w !== undefined ) {
  7664. console.warn( 'THREE.Vector3: .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead.' );
  7665. return this.multiplyVectors( v, w );
  7666. }
  7667. this.x *= v.x;
  7668. this.y *= v.y;
  7669. this.z *= v.z;
  7670. return this;
  7671. },
  7672. multiplyScalar: function ( scalar ) {
  7673. this.x *= scalar;
  7674. this.y *= scalar;
  7675. this.z *= scalar;
  7676. return this;
  7677. },
  7678. multiplyVectors: function ( a, b ) {
  7679. this.x = a.x * b.x;
  7680. this.y = a.y * b.y;
  7681. this.z = a.z * b.z;
  7682. return this;
  7683. },
  7684. applyEuler: function ( euler ) {
  7685. if ( ! ( euler && euler.isEuler ) ) {
  7686. console.error( 'THREE.Vector3: .applyEuler() now expects an Euler rotation rather than a Vector3 and order.' );
  7687. }
  7688. return this.applyQuaternion( _quaternion.setFromEuler( euler ) );
  7689. },
  7690. applyAxisAngle: function ( axis, angle ) {
  7691. return this.applyQuaternion( _quaternion.setFromAxisAngle( axis, angle ) );
  7692. },
  7693. applyMatrix3: function ( m ) {
  7694. var x = this.x, y = this.y, z = this.z;
  7695. var e = m.elements;
  7696. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ] * z;
  7697. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ] * z;
  7698. this.z = e[ 2 ] * x + e[ 5 ] * y + e[ 8 ] * z;
  7699. return this;
  7700. },
  7701. applyNormalMatrix: function ( m ) {
  7702. return this.applyMatrix3( m ).normalize();
  7703. },
  7704. applyMatrix4: function ( m ) {
  7705. var x = this.x, y = this.y, z = this.z;
  7706. var e = m.elements;
  7707. var w = 1 / ( e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] );
  7708. this.x = ( e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] ) * w;
  7709. this.y = ( e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] ) * w;
  7710. this.z = ( e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] ) * w;
  7711. return this;
  7712. },
  7713. applyQuaternion: function ( q ) {
  7714. var x = this.x, y = this.y, z = this.z;
  7715. var qx = q.x, qy = q.y, qz = q.z, qw = q.w;
  7716. // calculate quat * vector
  7717. var ix = qw * x + qy * z - qz * y;
  7718. var iy = qw * y + qz * x - qx * z;
  7719. var iz = qw * z + qx * y - qy * x;
  7720. var iw = - qx * x - qy * y - qz * z;
  7721. // calculate result * inverse quat
  7722. this.x = ix * qw + iw * - qx + iy * - qz - iz * - qy;
  7723. this.y = iy * qw + iw * - qy + iz * - qx - ix * - qz;
  7724. this.z = iz * qw + iw * - qz + ix * - qy - iy * - qx;
  7725. return this;
  7726. },
  7727. project: function ( camera ) {
  7728. return this.applyMatrix4( camera.matrixWorldInverse ).applyMatrix4( camera.projectionMatrix );
  7729. },
  7730. unproject: function ( camera ) {
  7731. return this.applyMatrix4( camera.projectionMatrixInverse ).applyMatrix4( camera.matrixWorld );
  7732. },
  7733. transformDirection: function ( m ) {
  7734. // input: THREE.Matrix4 affine matrix
  7735. // vector interpreted as a direction
  7736. var x = this.x, y = this.y, z = this.z;
  7737. var e = m.elements;
  7738. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z;
  7739. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z;
  7740. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z;
  7741. return this.normalize();
  7742. },
  7743. divide: function ( v ) {
  7744. this.x /= v.x;
  7745. this.y /= v.y;
  7746. this.z /= v.z;
  7747. return this;
  7748. },
  7749. divideScalar: function ( scalar ) {
  7750. return this.multiplyScalar( 1 / scalar );
  7751. },
  7752. min: function ( v ) {
  7753. this.x = Math.min( this.x, v.x );
  7754. this.y = Math.min( this.y, v.y );
  7755. this.z = Math.min( this.z, v.z );
  7756. return this;
  7757. },
  7758. max: function ( v ) {
  7759. this.x = Math.max( this.x, v.x );
  7760. this.y = Math.max( this.y, v.y );
  7761. this.z = Math.max( this.z, v.z );
  7762. return this;
  7763. },
  7764. clamp: function ( min, max ) {
  7765. // assumes min < max, componentwise
  7766. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  7767. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  7768. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  7769. return this;
  7770. },
  7771. clampScalar: function ( minVal, maxVal ) {
  7772. this.x = Math.max( minVal, Math.min( maxVal, this.x ) );
  7773. this.y = Math.max( minVal, Math.min( maxVal, this.y ) );
  7774. this.z = Math.max( minVal, Math.min( maxVal, this.z ) );
  7775. return this;
  7776. },
  7777. clampLength: function ( min, max ) {
  7778. var length = this.length();
  7779. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  7780. },
  7781. floor: function () {
  7782. this.x = Math.floor( this.x );
  7783. this.y = Math.floor( this.y );
  7784. this.z = Math.floor( this.z );
  7785. return this;
  7786. },
  7787. ceil: function () {
  7788. this.x = Math.ceil( this.x );
  7789. this.y = Math.ceil( this.y );
  7790. this.z = Math.ceil( this.z );
  7791. return this;
  7792. },
  7793. round: function () {
  7794. this.x = Math.round( this.x );
  7795. this.y = Math.round( this.y );
  7796. this.z = Math.round( this.z );
  7797. return this;
  7798. },
  7799. roundToZero: function () {
  7800. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  7801. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  7802. this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
  7803. return this;
  7804. },
  7805. negate: function () {
  7806. this.x = - this.x;
  7807. this.y = - this.y;
  7808. this.z = - this.z;
  7809. return this;
  7810. },
  7811. dot: function ( v ) {
  7812. return this.x * v.x + this.y * v.y + this.z * v.z;
  7813. },
  7814. // TODO lengthSquared?
  7815. lengthSq: function () {
  7816. return this.x * this.x + this.y * this.y + this.z * this.z;
  7817. },
  7818. length: function () {
  7819. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
  7820. },
  7821. manhattanLength: function () {
  7822. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  7823. },
  7824. normalize: function () {
  7825. return this.divideScalar( this.length() || 1 );
  7826. },
  7827. setLength: function ( length ) {
  7828. return this.normalize().multiplyScalar( length );
  7829. },
  7830. lerp: function ( v, alpha ) {
  7831. this.x += ( v.x - this.x ) * alpha;
  7832. this.y += ( v.y - this.y ) * alpha;
  7833. this.z += ( v.z - this.z ) * alpha;
  7834. return this;
  7835. },
  7836. lerpVectors: function ( v1, v2, alpha ) {
  7837. return this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 );
  7838. },
  7839. cross: function ( v, w ) {
  7840. if ( w !== undefined ) {
  7841. console.warn( 'THREE.Vector3: .cross() now only accepts one argument. Use .crossVectors( a, b ) instead.' );
  7842. return this.crossVectors( v, w );
  7843. }
  7844. return this.crossVectors( this, v );
  7845. },
  7846. crossVectors: function ( a, b ) {
  7847. var ax = a.x, ay = a.y, az = a.z;
  7848. var bx = b.x, by = b.y, bz = b.z;
  7849. this.x = ay * bz - az * by;
  7850. this.y = az * bx - ax * bz;
  7851. this.z = ax * by - ay * bx;
  7852. return this;
  7853. },
  7854. projectOnVector: function ( v ) {
  7855. var denominator = v.lengthSq();
  7856. if ( denominator === 0 ) { return this.set( 0, 0, 0 ); }
  7857. var scalar = v.dot( this ) / denominator;
  7858. return this.copy( v ).multiplyScalar( scalar );
  7859. },
  7860. projectOnPlane: function ( planeNormal ) {
  7861. _vector.copy( this ).projectOnVector( planeNormal );
  7862. return this.sub( _vector );
  7863. },
  7864. reflect: function ( normal ) {
  7865. // reflect incident vector off plane orthogonal to normal
  7866. // normal is assumed to have unit length
  7867. return this.sub( _vector.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) );
  7868. },
  7869. angleTo: function ( v ) {
  7870. var denominator = Math.sqrt( this.lengthSq() * v.lengthSq() );
  7871. if ( denominator === 0 ) { return Math.PI / 2; }
  7872. var theta = this.dot( v ) / denominator;
  7873. // clamp, to handle numerical problems
  7874. return Math.acos( MathUtils.clamp( theta, - 1, 1 ) );
  7875. },
  7876. distanceTo: function ( v ) {
  7877. return Math.sqrt( this.distanceToSquared( v ) );
  7878. },
  7879. distanceToSquared: function ( v ) {
  7880. var dx = this.x - v.x, dy = this.y - v.y, dz = this.z - v.z;
  7881. return dx * dx + dy * dy + dz * dz;
  7882. },
  7883. manhattanDistanceTo: function ( v ) {
  7884. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y ) + Math.abs( this.z - v.z );
  7885. },
  7886. setFromSpherical: function ( s ) {
  7887. return this.setFromSphericalCoords( s.radius, s.phi, s.theta );
  7888. },
  7889. setFromSphericalCoords: function ( radius, phi, theta ) {
  7890. var sinPhiRadius = Math.sin( phi ) * radius;
  7891. this.x = sinPhiRadius * Math.sin( theta );
  7892. this.y = Math.cos( phi ) * radius;
  7893. this.z = sinPhiRadius * Math.cos( theta );
  7894. return this;
  7895. },
  7896. setFromCylindrical: function ( c ) {
  7897. return this.setFromCylindricalCoords( c.radius, c.theta, c.y );
  7898. },
  7899. setFromCylindricalCoords: function ( radius, theta, y ) {
  7900. this.x = radius * Math.sin( theta );
  7901. this.y = y;
  7902. this.z = radius * Math.cos( theta );
  7903. return this;
  7904. },
  7905. setFromMatrixPosition: function ( m ) {
  7906. var e = m.elements;
  7907. this.x = e[ 12 ];
  7908. this.y = e[ 13 ];
  7909. this.z = e[ 14 ];
  7910. return this;
  7911. },
  7912. setFromMatrixScale: function ( m ) {
  7913. var sx = this.setFromMatrixColumn( m, 0 ).length();
  7914. var sy = this.setFromMatrixColumn( m, 1 ).length();
  7915. var sz = this.setFromMatrixColumn( m, 2 ).length();
  7916. this.x = sx;
  7917. this.y = sy;
  7918. this.z = sz;
  7919. return this;
  7920. },
  7921. setFromMatrixColumn: function ( m, index ) {
  7922. return this.fromArray( m.elements, index * 4 );
  7923. },
  7924. setFromMatrix3Column: function ( m, index ) {
  7925. return this.fromArray( m.elements, index * 3 );
  7926. },
  7927. equals: function ( v ) {
  7928. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  7929. },
  7930. fromArray: function ( array, offset ) {
  7931. if ( offset === undefined ) { offset = 0; }
  7932. this.x = array[ offset ];
  7933. this.y = array[ offset + 1 ];
  7934. this.z = array[ offset + 2 ];
  7935. return this;
  7936. },
  7937. toArray: function ( array, offset ) {
  7938. if ( array === undefined ) { array = []; }
  7939. if ( offset === undefined ) { offset = 0; }
  7940. array[ offset ] = this.x;
  7941. array[ offset + 1 ] = this.y;
  7942. array[ offset + 2 ] = this.z;
  7943. return array;
  7944. },
  7945. fromBufferAttribute: function ( attribute, index, offset ) {
  7946. if ( offset !== undefined ) {
  7947. console.warn( 'THREE.Vector3: offset has been removed from .fromBufferAttribute().' );
  7948. }
  7949. this.x = attribute.getX( index );
  7950. this.y = attribute.getY( index );
  7951. this.z = attribute.getZ( index );
  7952. return this;
  7953. }
  7954. } );
  7955. var _v1 = new Vector3();
  7956. var _m1 = new Matrix4();
  7957. var _zero = new Vector3( 0, 0, 0 );
  7958. var _one = new Vector3( 1, 1, 1 );
  7959. var _x = new Vector3();
  7960. var _y = new Vector3();
  7961. var _z = new Vector3();
  7962. /**
  7963. * @author mrdoob / http://mrdoob.com/
  7964. * @author supereggbert / http://www.paulbrunt.co.uk/
  7965. * @author philogb / http://blog.thejit.org/
  7966. * @author jordi_ros / http://plattsoft.com
  7967. * @author D1plo1d / http://github.com/D1plo1d
  7968. * @author alteredq / http://alteredqualia.com/
  7969. * @author mikael emtinger / http://gomo.se/
  7970. * @author timknip / http://www.floorplanner.com/
  7971. * @author bhouston / http://clara.io
  7972. * @author WestLangley / http://github.com/WestLangley
  7973. */
  7974. function Matrix4() {
  7975. this.elements = [
  7976. 1, 0, 0, 0,
  7977. 0, 1, 0, 0,
  7978. 0, 0, 1, 0,
  7979. 0, 0, 0, 1
  7980. ];
  7981. if ( arguments.length > 0 ) {
  7982. console.error( 'THREE.Matrix4: the constructor no longer reads arguments. use .set() instead.' );
  7983. }
  7984. }
  7985. Object.assign( Matrix4.prototype, {
  7986. isMatrix4: true,
  7987. set: function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  7988. var te = this.elements;
  7989. te[ 0 ] = n11; te[ 4 ] = n12; te[ 8 ] = n13; te[ 12 ] = n14;
  7990. te[ 1 ] = n21; te[ 5 ] = n22; te[ 9 ] = n23; te[ 13 ] = n24;
  7991. te[ 2 ] = n31; te[ 6 ] = n32; te[ 10 ] = n33; te[ 14 ] = n34;
  7992. te[ 3 ] = n41; te[ 7 ] = n42; te[ 11 ] = n43; te[ 15 ] = n44;
  7993. return this;
  7994. },
  7995. identity: function () {
  7996. this.set(
  7997. 1, 0, 0, 0,
  7998. 0, 1, 0, 0,
  7999. 0, 0, 1, 0,
  8000. 0, 0, 0, 1
  8001. );
  8002. return this;
  8003. },
  8004. clone: function () {
  8005. return new Matrix4().fromArray( this.elements );
  8006. },
  8007. copy: function ( m ) {
  8008. var te = this.elements;
  8009. var me = m.elements;
  8010. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ]; te[ 3 ] = me[ 3 ];
  8011. te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ]; te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ];
  8012. te[ 8 ] = me[ 8 ]; te[ 9 ] = me[ 9 ]; te[ 10 ] = me[ 10 ]; te[ 11 ] = me[ 11 ];
  8013. te[ 12 ] = me[ 12 ]; te[ 13 ] = me[ 13 ]; te[ 14 ] = me[ 14 ]; te[ 15 ] = me[ 15 ];
  8014. return this;
  8015. },
  8016. copyPosition: function ( m ) {
  8017. var te = this.elements, me = m.elements;
  8018. te[ 12 ] = me[ 12 ];
  8019. te[ 13 ] = me[ 13 ];
  8020. te[ 14 ] = me[ 14 ];
  8021. return this;
  8022. },
  8023. extractBasis: function ( xAxis, yAxis, zAxis ) {
  8024. xAxis.setFromMatrixColumn( this, 0 );
  8025. yAxis.setFromMatrixColumn( this, 1 );
  8026. zAxis.setFromMatrixColumn( this, 2 );
  8027. return this;
  8028. },
  8029. makeBasis: function ( xAxis, yAxis, zAxis ) {
  8030. this.set(
  8031. xAxis.x, yAxis.x, zAxis.x, 0,
  8032. xAxis.y, yAxis.y, zAxis.y, 0,
  8033. xAxis.z, yAxis.z, zAxis.z, 0,
  8034. 0, 0, 0, 1
  8035. );
  8036. return this;
  8037. },
  8038. extractRotation: function ( m ) {
  8039. // this method does not support reflection matrices
  8040. var te = this.elements;
  8041. var me = m.elements;
  8042. var scaleX = 1 / _v1.setFromMatrixColumn( m, 0 ).length();
  8043. var scaleY = 1 / _v1.setFromMatrixColumn( m, 1 ).length();
  8044. var scaleZ = 1 / _v1.setFromMatrixColumn( m, 2 ).length();
  8045. te[ 0 ] = me[ 0 ] * scaleX;
  8046. te[ 1 ] = me[ 1 ] * scaleX;
  8047. te[ 2 ] = me[ 2 ] * scaleX;
  8048. te[ 3 ] = 0;
  8049. te[ 4 ] = me[ 4 ] * scaleY;
  8050. te[ 5 ] = me[ 5 ] * scaleY;
  8051. te[ 6 ] = me[ 6 ] * scaleY;
  8052. te[ 7 ] = 0;
  8053. te[ 8 ] = me[ 8 ] * scaleZ;
  8054. te[ 9 ] = me[ 9 ] * scaleZ;
  8055. te[ 10 ] = me[ 10 ] * scaleZ;
  8056. te[ 11 ] = 0;
  8057. te[ 12 ] = 0;
  8058. te[ 13 ] = 0;
  8059. te[ 14 ] = 0;
  8060. te[ 15 ] = 1;
  8061. return this;
  8062. },
  8063. makeRotationFromEuler: function ( euler ) {
  8064. if ( ! ( euler && euler.isEuler ) ) {
  8065. console.error( 'THREE.Matrix4: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.' );
  8066. }
  8067. var te = this.elements;
  8068. var x = euler.x, y = euler.y, z = euler.z;
  8069. var a = Math.cos( x ), b = Math.sin( x );
  8070. var c = Math.cos( y ), d = Math.sin( y );
  8071. var e = Math.cos( z ), f = Math.sin( z );
  8072. if ( euler.order === 'XYZ' ) {
  8073. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  8074. te[ 0 ] = c * e;
  8075. te[ 4 ] = - c * f;
  8076. te[ 8 ] = d;
  8077. te[ 1 ] = af + be * d;
  8078. te[ 5 ] = ae - bf * d;
  8079. te[ 9 ] = - b * c;
  8080. te[ 2 ] = bf - ae * d;
  8081. te[ 6 ] = be + af * d;
  8082. te[ 10 ] = a * c;
  8083. } else if ( euler.order === 'YXZ' ) {
  8084. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  8085. te[ 0 ] = ce + df * b;
  8086. te[ 4 ] = de * b - cf;
  8087. te[ 8 ] = a * d;
  8088. te[ 1 ] = a * f;
  8089. te[ 5 ] = a * e;
  8090. te[ 9 ] = - b;
  8091. te[ 2 ] = cf * b - de;
  8092. te[ 6 ] = df + ce * b;
  8093. te[ 10 ] = a * c;
  8094. } else if ( euler.order === 'ZXY' ) {
  8095. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  8096. te[ 0 ] = ce - df * b;
  8097. te[ 4 ] = - a * f;
  8098. te[ 8 ] = de + cf * b;
  8099. te[ 1 ] = cf + de * b;
  8100. te[ 5 ] = a * e;
  8101. te[ 9 ] = df - ce * b;
  8102. te[ 2 ] = - a * d;
  8103. te[ 6 ] = b;
  8104. te[ 10 ] = a * c;
  8105. } else if ( euler.order === 'ZYX' ) {
  8106. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  8107. te[ 0 ] = c * e;
  8108. te[ 4 ] = be * d - af;
  8109. te[ 8 ] = ae * d + bf;
  8110. te[ 1 ] = c * f;
  8111. te[ 5 ] = bf * d + ae;
  8112. te[ 9 ] = af * d - be;
  8113. te[ 2 ] = - d;
  8114. te[ 6 ] = b * c;
  8115. te[ 10 ] = a * c;
  8116. } else if ( euler.order === 'YZX' ) {
  8117. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  8118. te[ 0 ] = c * e;
  8119. te[ 4 ] = bd - ac * f;
  8120. te[ 8 ] = bc * f + ad;
  8121. te[ 1 ] = f;
  8122. te[ 5 ] = a * e;
  8123. te[ 9 ] = - b * e;
  8124. te[ 2 ] = - d * e;
  8125. te[ 6 ] = ad * f + bc;
  8126. te[ 10 ] = ac - bd * f;
  8127. } else if ( euler.order === 'XZY' ) {
  8128. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  8129. te[ 0 ] = c * e;
  8130. te[ 4 ] = - f;
  8131. te[ 8 ] = d * e;
  8132. te[ 1 ] = ac * f + bd;
  8133. te[ 5 ] = a * e;
  8134. te[ 9 ] = ad * f - bc;
  8135. te[ 2 ] = bc * f - ad;
  8136. te[ 6 ] = b * e;
  8137. te[ 10 ] = bd * f + ac;
  8138. }
  8139. // bottom row
  8140. te[ 3 ] = 0;
  8141. te[ 7 ] = 0;
  8142. te[ 11 ] = 0;
  8143. // last column
  8144. te[ 12 ] = 0;
  8145. te[ 13 ] = 0;
  8146. te[ 14 ] = 0;
  8147. te[ 15 ] = 1;
  8148. return this;
  8149. },
  8150. makeRotationFromQuaternion: function ( q ) {
  8151. return this.compose( _zero, q, _one );
  8152. },
  8153. lookAt: function ( eye, target, up ) {
  8154. var te = this.elements;
  8155. _z.subVectors( eye, target );
  8156. if ( _z.lengthSq() === 0 ) {
  8157. // eye and target are in the same position
  8158. _z.z = 1;
  8159. }
  8160. _z.normalize();
  8161. _x.crossVectors( up, _z );
  8162. if ( _x.lengthSq() === 0 ) {
  8163. // up and z are parallel
  8164. if ( Math.abs( up.z ) === 1 ) {
  8165. _z.x += 0.0001;
  8166. } else {
  8167. _z.z += 0.0001;
  8168. }
  8169. _z.normalize();
  8170. _x.crossVectors( up, _z );
  8171. }
  8172. _x.normalize();
  8173. _y.crossVectors( _z, _x );
  8174. te[ 0 ] = _x.x; te[ 4 ] = _y.x; te[ 8 ] = _z.x;
  8175. te[ 1 ] = _x.y; te[ 5 ] = _y.y; te[ 9 ] = _z.y;
  8176. te[ 2 ] = _x.z; te[ 6 ] = _y.z; te[ 10 ] = _z.z;
  8177. return this;
  8178. },
  8179. multiply: function ( m, n ) {
  8180. if ( n !== undefined ) {
  8181. console.warn( 'THREE.Matrix4: .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead.' );
  8182. return this.multiplyMatrices( m, n );
  8183. }
  8184. return this.multiplyMatrices( this, m );
  8185. },
  8186. premultiply: function ( m ) {
  8187. return this.multiplyMatrices( m, this );
  8188. },
  8189. multiplyMatrices: function ( a, b ) {
  8190. var ae = a.elements;
  8191. var be = b.elements;
  8192. var te = this.elements;
  8193. var a11 = ae[ 0 ], a12 = ae[ 4 ], a13 = ae[ 8 ], a14 = ae[ 12 ];
  8194. var a21 = ae[ 1 ], a22 = ae[ 5 ], a23 = ae[ 9 ], a24 = ae[ 13 ];
  8195. var a31 = ae[ 2 ], a32 = ae[ 6 ], a33 = ae[ 10 ], a34 = ae[ 14 ];
  8196. var a41 = ae[ 3 ], a42 = ae[ 7 ], a43 = ae[ 11 ], a44 = ae[ 15 ];
  8197. var b11 = be[ 0 ], b12 = be[ 4 ], b13 = be[ 8 ], b14 = be[ 12 ];
  8198. var b21 = be[ 1 ], b22 = be[ 5 ], b23 = be[ 9 ], b24 = be[ 13 ];
  8199. var b31 = be[ 2 ], b32 = be[ 6 ], b33 = be[ 10 ], b34 = be[ 14 ];
  8200. var b41 = be[ 3 ], b42 = be[ 7 ], b43 = be[ 11 ], b44 = be[ 15 ];
  8201. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  8202. te[ 4 ] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  8203. te[ 8 ] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  8204. te[ 12 ] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  8205. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  8206. te[ 5 ] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  8207. te[ 9 ] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  8208. te[ 13 ] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  8209. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  8210. te[ 6 ] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  8211. te[ 10 ] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  8212. te[ 14 ] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  8213. te[ 3 ] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  8214. te[ 7 ] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  8215. te[ 11 ] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  8216. te[ 15 ] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  8217. return this;
  8218. },
  8219. multiplyScalar: function ( s ) {
  8220. var te = this.elements;
  8221. te[ 0 ] *= s; te[ 4 ] *= s; te[ 8 ] *= s; te[ 12 ] *= s;
  8222. te[ 1 ] *= s; te[ 5 ] *= s; te[ 9 ] *= s; te[ 13 ] *= s;
  8223. te[ 2 ] *= s; te[ 6 ] *= s; te[ 10 ] *= s; te[ 14 ] *= s;
  8224. te[ 3 ] *= s; te[ 7 ] *= s; te[ 11 ] *= s; te[ 15 ] *= s;
  8225. return this;
  8226. },
  8227. determinant: function () {
  8228. var te = this.elements;
  8229. var n11 = te[ 0 ], n12 = te[ 4 ], n13 = te[ 8 ], n14 = te[ 12 ];
  8230. var n21 = te[ 1 ], n22 = te[ 5 ], n23 = te[ 9 ], n24 = te[ 13 ];
  8231. var n31 = te[ 2 ], n32 = te[ 6 ], n33 = te[ 10 ], n34 = te[ 14 ];
  8232. var n41 = te[ 3 ], n42 = te[ 7 ], n43 = te[ 11 ], n44 = te[ 15 ];
  8233. //TODO: make this more efficient
  8234. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  8235. return (
  8236. n41 * (
  8237. + n14 * n23 * n32
  8238. - n13 * n24 * n32
  8239. - n14 * n22 * n33
  8240. + n12 * n24 * n33
  8241. + n13 * n22 * n34
  8242. - n12 * n23 * n34
  8243. ) +
  8244. n42 * (
  8245. + n11 * n23 * n34
  8246. - n11 * n24 * n33
  8247. + n14 * n21 * n33
  8248. - n13 * n21 * n34
  8249. + n13 * n24 * n31
  8250. - n14 * n23 * n31
  8251. ) +
  8252. n43 * (
  8253. + n11 * n24 * n32
  8254. - n11 * n22 * n34
  8255. - n14 * n21 * n32
  8256. + n12 * n21 * n34
  8257. + n14 * n22 * n31
  8258. - n12 * n24 * n31
  8259. ) +
  8260. n44 * (
  8261. - n13 * n22 * n31
  8262. - n11 * n23 * n32
  8263. + n11 * n22 * n33
  8264. + n13 * n21 * n32
  8265. - n12 * n21 * n33
  8266. + n12 * n23 * n31
  8267. )
  8268. );
  8269. },
  8270. transpose: function () {
  8271. var te = this.elements;
  8272. var tmp;
  8273. tmp = te[ 1 ]; te[ 1 ] = te[ 4 ]; te[ 4 ] = tmp;
  8274. tmp = te[ 2 ]; te[ 2 ] = te[ 8 ]; te[ 8 ] = tmp;
  8275. tmp = te[ 6 ]; te[ 6 ] = te[ 9 ]; te[ 9 ] = tmp;
  8276. tmp = te[ 3 ]; te[ 3 ] = te[ 12 ]; te[ 12 ] = tmp;
  8277. tmp = te[ 7 ]; te[ 7 ] = te[ 13 ]; te[ 13 ] = tmp;
  8278. tmp = te[ 11 ]; te[ 11 ] = te[ 14 ]; te[ 14 ] = tmp;
  8279. return this;
  8280. },
  8281. setPosition: function ( x, y, z ) {
  8282. var te = this.elements;
  8283. if ( x.isVector3 ) {
  8284. te[ 12 ] = x.x;
  8285. te[ 13 ] = x.y;
  8286. te[ 14 ] = x.z;
  8287. } else {
  8288. te[ 12 ] = x;
  8289. te[ 13 ] = y;
  8290. te[ 14 ] = z;
  8291. }
  8292. return this;
  8293. },
  8294. getInverse: function ( m, throwOnDegenerate ) {
  8295. if ( throwOnDegenerate !== undefined ) {
  8296. console.warn( "THREE.Matrix4: .getInverse() can no longer be configured to throw on degenerate." );
  8297. }
  8298. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  8299. var te = this.elements,
  8300. me = m.elements,
  8301. n11 = me[ 0 ], n21 = me[ 1 ], n31 = me[ 2 ], n41 = me[ 3 ],
  8302. n12 = me[ 4 ], n22 = me[ 5 ], n32 = me[ 6 ], n42 = me[ 7 ],
  8303. n13 = me[ 8 ], n23 = me[ 9 ], n33 = me[ 10 ], n43 = me[ 11 ],
  8304. n14 = me[ 12 ], n24 = me[ 13 ], n34 = me[ 14 ], n44 = me[ 15 ],
  8305. t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44,
  8306. t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44,
  8307. t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44,
  8308. t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;
  8309. var det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14;
  8310. if ( det === 0 ) { return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ); }
  8311. var detInv = 1 / det;
  8312. te[ 0 ] = t11 * detInv;
  8313. te[ 1 ] = ( n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44 ) * detInv;
  8314. te[ 2 ] = ( n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44 ) * detInv;
  8315. te[ 3 ] = ( n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43 ) * detInv;
  8316. te[ 4 ] = t12 * detInv;
  8317. te[ 5 ] = ( n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44 ) * detInv;
  8318. te[ 6 ] = ( n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44 ) * detInv;
  8319. te[ 7 ] = ( n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43 ) * detInv;
  8320. te[ 8 ] = t13 * detInv;
  8321. te[ 9 ] = ( n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44 ) * detInv;
  8322. te[ 10 ] = ( n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44 ) * detInv;
  8323. te[ 11 ] = ( n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43 ) * detInv;
  8324. te[ 12 ] = t14 * detInv;
  8325. te[ 13 ] = ( n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34 ) * detInv;
  8326. te[ 14 ] = ( n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34 ) * detInv;
  8327. te[ 15 ] = ( n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33 ) * detInv;
  8328. return this;
  8329. },
  8330. scale: function ( v ) {
  8331. var te = this.elements;
  8332. var x = v.x, y = v.y, z = v.z;
  8333. te[ 0 ] *= x; te[ 4 ] *= y; te[ 8 ] *= z;
  8334. te[ 1 ] *= x; te[ 5 ] *= y; te[ 9 ] *= z;
  8335. te[ 2 ] *= x; te[ 6 ] *= y; te[ 10 ] *= z;
  8336. te[ 3 ] *= x; te[ 7 ] *= y; te[ 11 ] *= z;
  8337. return this;
  8338. },
  8339. getMaxScaleOnAxis: function () {
  8340. var te = this.elements;
  8341. var scaleXSq = te[ 0 ] * te[ 0 ] + te[ 1 ] * te[ 1 ] + te[ 2 ] * te[ 2 ];
  8342. var scaleYSq = te[ 4 ] * te[ 4 ] + te[ 5 ] * te[ 5 ] + te[ 6 ] * te[ 6 ];
  8343. var scaleZSq = te[ 8 ] * te[ 8 ] + te[ 9 ] * te[ 9 ] + te[ 10 ] * te[ 10 ];
  8344. return Math.sqrt( Math.max( scaleXSq, scaleYSq, scaleZSq ) );
  8345. },
  8346. makeTranslation: function ( x, y, z ) {
  8347. this.set(
  8348. 1, 0, 0, x,
  8349. 0, 1, 0, y,
  8350. 0, 0, 1, z,
  8351. 0, 0, 0, 1
  8352. );
  8353. return this;
  8354. },
  8355. makeRotationX: function ( theta ) {
  8356. var c = Math.cos( theta ), s = Math.sin( theta );
  8357. this.set(
  8358. 1, 0, 0, 0,
  8359. 0, c, - s, 0,
  8360. 0, s, c, 0,
  8361. 0, 0, 0, 1
  8362. );
  8363. return this;
  8364. },
  8365. makeRotationY: function ( theta ) {
  8366. var c = Math.cos( theta ), s = Math.sin( theta );
  8367. this.set(
  8368. c, 0, s, 0,
  8369. 0, 1, 0, 0,
  8370. - s, 0, c, 0,
  8371. 0, 0, 0, 1
  8372. );
  8373. return this;
  8374. },
  8375. makeRotationZ: function ( theta ) {
  8376. var c = Math.cos( theta ), s = Math.sin( theta );
  8377. this.set(
  8378. c, - s, 0, 0,
  8379. s, c, 0, 0,
  8380. 0, 0, 1, 0,
  8381. 0, 0, 0, 1
  8382. );
  8383. return this;
  8384. },
  8385. makeRotationAxis: function ( axis, angle ) {
  8386. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  8387. var c = Math.cos( angle );
  8388. var s = Math.sin( angle );
  8389. var t = 1 - c;
  8390. var x = axis.x, y = axis.y, z = axis.z;
  8391. var tx = t * x, ty = t * y;
  8392. this.set(
  8393. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  8394. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  8395. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  8396. 0, 0, 0, 1
  8397. );
  8398. return this;
  8399. },
  8400. makeScale: function ( x, y, z ) {
  8401. this.set(
  8402. x, 0, 0, 0,
  8403. 0, y, 0, 0,
  8404. 0, 0, z, 0,
  8405. 0, 0, 0, 1
  8406. );
  8407. return this;
  8408. },
  8409. makeShear: function ( x, y, z ) {
  8410. this.set(
  8411. 1, y, z, 0,
  8412. x, 1, z, 0,
  8413. x, y, 1, 0,
  8414. 0, 0, 0, 1
  8415. );
  8416. return this;
  8417. },
  8418. compose: function ( position, quaternion, scale ) {
  8419. var te = this.elements;
  8420. var x = quaternion._x, y = quaternion._y, z = quaternion._z, w = quaternion._w;
  8421. var x2 = x + x, y2 = y + y, z2 = z + z;
  8422. var xx = x * x2, xy = x * y2, xz = x * z2;
  8423. var yy = y * y2, yz = y * z2, zz = z * z2;
  8424. var wx = w * x2, wy = w * y2, wz = w * z2;
  8425. var sx = scale.x, sy = scale.y, sz = scale.z;
  8426. te[ 0 ] = ( 1 - ( yy + zz ) ) * sx;
  8427. te[ 1 ] = ( xy + wz ) * sx;
  8428. te[ 2 ] = ( xz - wy ) * sx;
  8429. te[ 3 ] = 0;
  8430. te[ 4 ] = ( xy - wz ) * sy;
  8431. te[ 5 ] = ( 1 - ( xx + zz ) ) * sy;
  8432. te[ 6 ] = ( yz + wx ) * sy;
  8433. te[ 7 ] = 0;
  8434. te[ 8 ] = ( xz + wy ) * sz;
  8435. te[ 9 ] = ( yz - wx ) * sz;
  8436. te[ 10 ] = ( 1 - ( xx + yy ) ) * sz;
  8437. te[ 11 ] = 0;
  8438. te[ 12 ] = position.x;
  8439. te[ 13 ] = position.y;
  8440. te[ 14 ] = position.z;
  8441. te[ 15 ] = 1;
  8442. return this;
  8443. },
  8444. decompose: function ( position, quaternion, scale ) {
  8445. var te = this.elements;
  8446. var sx = _v1.set( te[ 0 ], te[ 1 ], te[ 2 ] ).length();
  8447. var sy = _v1.set( te[ 4 ], te[ 5 ], te[ 6 ] ).length();
  8448. var sz = _v1.set( te[ 8 ], te[ 9 ], te[ 10 ] ).length();
  8449. // if determine is negative, we need to invert one scale
  8450. var det = this.determinant();
  8451. if ( det < 0 ) { sx = - sx; }
  8452. position.x = te[ 12 ];
  8453. position.y = te[ 13 ];
  8454. position.z = te[ 14 ];
  8455. // scale the rotation part
  8456. _m1.copy( this );
  8457. var invSX = 1 / sx;
  8458. var invSY = 1 / sy;
  8459. var invSZ = 1 / sz;
  8460. _m1.elements[ 0 ] *= invSX;
  8461. _m1.elements[ 1 ] *= invSX;
  8462. _m1.elements[ 2 ] *= invSX;
  8463. _m1.elements[ 4 ] *= invSY;
  8464. _m1.elements[ 5 ] *= invSY;
  8465. _m1.elements[ 6 ] *= invSY;
  8466. _m1.elements[ 8 ] *= invSZ;
  8467. _m1.elements[ 9 ] *= invSZ;
  8468. _m1.elements[ 10 ] *= invSZ;
  8469. quaternion.setFromRotationMatrix( _m1 );
  8470. scale.x = sx;
  8471. scale.y = sy;
  8472. scale.z = sz;
  8473. return this;
  8474. },
  8475. makePerspective: function ( left, right, top, bottom, near, far ) {
  8476. if ( far === undefined ) {
  8477. console.warn( 'THREE.Matrix4: .makePerspective() has been redefined and has a new signature. Please check the docs.' );
  8478. }
  8479. var te = this.elements;
  8480. var x = 2 * near / ( right - left );
  8481. var y = 2 * near / ( top - bottom );
  8482. var a = ( right + left ) / ( right - left );
  8483. var b = ( top + bottom ) / ( top - bottom );
  8484. var c = - ( far + near ) / ( far - near );
  8485. var d = - 2 * far * near / ( far - near );
  8486. te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = a; te[ 12 ] = 0;
  8487. te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = b; te[ 13 ] = 0;
  8488. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d;
  8489. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = - 1; te[ 15 ] = 0;
  8490. return this;
  8491. },
  8492. makeOrthographic: function ( left, right, top, bottom, near, far ) {
  8493. var te = this.elements;
  8494. var w = 1.0 / ( right - left );
  8495. var h = 1.0 / ( top - bottom );
  8496. var p = 1.0 / ( far - near );
  8497. var x = ( right + left ) * w;
  8498. var y = ( top + bottom ) * h;
  8499. var z = ( far + near ) * p;
  8500. te[ 0 ] = 2 * w; te[ 4 ] = 0; te[ 8 ] = 0; te[ 12 ] = - x;
  8501. te[ 1 ] = 0; te[ 5 ] = 2 * h; te[ 9 ] = 0; te[ 13 ] = - y;
  8502. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = - 2 * p; te[ 14 ] = - z;
  8503. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = 0; te[ 15 ] = 1;
  8504. return this;
  8505. },
  8506. equals: function ( matrix ) {
  8507. var te = this.elements;
  8508. var me = matrix.elements;
  8509. for ( var i = 0; i < 16; i ++ ) {
  8510. if ( te[ i ] !== me[ i ] ) { return false; }
  8511. }
  8512. return true;
  8513. },
  8514. fromArray: function ( array, offset ) {
  8515. if ( offset === undefined ) { offset = 0; }
  8516. for ( var i = 0; i < 16; i ++ ) {
  8517. this.elements[ i ] = array[ i + offset ];
  8518. }
  8519. return this;
  8520. },
  8521. toArray: function ( array, offset ) {
  8522. if ( array === undefined ) { array = []; }
  8523. if ( offset === undefined ) { offset = 0; }
  8524. var te = this.elements;
  8525. array[ offset ] = te[ 0 ];
  8526. array[ offset + 1 ] = te[ 1 ];
  8527. array[ offset + 2 ] = te[ 2 ];
  8528. array[ offset + 3 ] = te[ 3 ];
  8529. array[ offset + 4 ] = te[ 4 ];
  8530. array[ offset + 5 ] = te[ 5 ];
  8531. array[ offset + 6 ] = te[ 6 ];
  8532. array[ offset + 7 ] = te[ 7 ];
  8533. array[ offset + 8 ] = te[ 8 ];
  8534. array[ offset + 9 ] = te[ 9 ];
  8535. array[ offset + 10 ] = te[ 10 ];
  8536. array[ offset + 11 ] = te[ 11 ];
  8537. array[ offset + 12 ] = te[ 12 ];
  8538. array[ offset + 13 ] = te[ 13 ];
  8539. array[ offset + 14 ] = te[ 14 ];
  8540. array[ offset + 15 ] = te[ 15 ];
  8541. return array;
  8542. }
  8543. } );
  8544. /**
  8545. * @author mrdoob / http://mrdoob.com/
  8546. * @author WestLangley / http://github.com/WestLangley
  8547. * @author bhouston / http://clara.io
  8548. */
  8549. var _matrix = new Matrix4();
  8550. var _quaternion$1 = new Quaternion();
  8551. function Euler( x, y, z, order ) {
  8552. this._x = x || 0;
  8553. this._y = y || 0;
  8554. this._z = z || 0;
  8555. this._order = order || Euler.DefaultOrder;
  8556. }
  8557. Euler.RotationOrders = [ 'XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX' ];
  8558. Euler.DefaultOrder = 'XYZ';
  8559. Object.defineProperties( Euler.prototype, {
  8560. x: {
  8561. get: function () {
  8562. return this._x;
  8563. },
  8564. set: function ( value ) {
  8565. this._x = value;
  8566. this._onChangeCallback();
  8567. }
  8568. },
  8569. y: {
  8570. get: function () {
  8571. return this._y;
  8572. },
  8573. set: function ( value ) {
  8574. this._y = value;
  8575. this._onChangeCallback();
  8576. }
  8577. },
  8578. z: {
  8579. get: function () {
  8580. return this._z;
  8581. },
  8582. set: function ( value ) {
  8583. this._z = value;
  8584. this._onChangeCallback();
  8585. }
  8586. },
  8587. order: {
  8588. get: function () {
  8589. return this._order;
  8590. },
  8591. set: function ( value ) {
  8592. this._order = value;
  8593. this._onChangeCallback();
  8594. }
  8595. }
  8596. } );
  8597. Object.assign( Euler.prototype, {
  8598. isEuler: true,
  8599. set: function ( x, y, z, order ) {
  8600. this._x = x;
  8601. this._y = y;
  8602. this._z = z;
  8603. this._order = order || this._order;
  8604. this._onChangeCallback();
  8605. return this;
  8606. },
  8607. clone: function () {
  8608. return new this.constructor( this._x, this._y, this._z, this._order );
  8609. },
  8610. copy: function ( euler ) {
  8611. this._x = euler._x;
  8612. this._y = euler._y;
  8613. this._z = euler._z;
  8614. this._order = euler._order;
  8615. this._onChangeCallback();
  8616. return this;
  8617. },
  8618. setFromRotationMatrix: function ( m, order, update ) {
  8619. var clamp = MathUtils.clamp;
  8620. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  8621. var te = m.elements;
  8622. var m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ];
  8623. var m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ];
  8624. var m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  8625. order = order || this._order;
  8626. if ( order === 'XYZ' ) {
  8627. this._y = Math.asin( clamp( m13, - 1, 1 ) );
  8628. if ( Math.abs( m13 ) < 0.9999999 ) {
  8629. this._x = Math.atan2( - m23, m33 );
  8630. this._z = Math.atan2( - m12, m11 );
  8631. } else {
  8632. this._x = Math.atan2( m32, m22 );
  8633. this._z = 0;
  8634. }
  8635. } else if ( order === 'YXZ' ) {
  8636. this._x = Math.asin( - clamp( m23, - 1, 1 ) );
  8637. if ( Math.abs( m23 ) < 0.9999999 ) {
  8638. this._y = Math.atan2( m13, m33 );
  8639. this._z = Math.atan2( m21, m22 );
  8640. } else {
  8641. this._y = Math.atan2( - m31, m11 );
  8642. this._z = 0;
  8643. }
  8644. } else if ( order === 'ZXY' ) {
  8645. this._x = Math.asin( clamp( m32, - 1, 1 ) );
  8646. if ( Math.abs( m32 ) < 0.9999999 ) {
  8647. this._y = Math.atan2( - m31, m33 );
  8648. this._z = Math.atan2( - m12, m22 );
  8649. } else {
  8650. this._y = 0;
  8651. this._z = Math.atan2( m21, m11 );
  8652. }
  8653. } else if ( order === 'ZYX' ) {
  8654. this._y = Math.asin( - clamp( m31, - 1, 1 ) );
  8655. if ( Math.abs( m31 ) < 0.9999999 ) {
  8656. this._x = Math.atan2( m32, m33 );
  8657. this._z = Math.atan2( m21, m11 );
  8658. } else {
  8659. this._x = 0;
  8660. this._z = Math.atan2( - m12, m22 );
  8661. }
  8662. } else if ( order === 'YZX' ) {
  8663. this._z = Math.asin( clamp( m21, - 1, 1 ) );
  8664. if ( Math.abs( m21 ) < 0.9999999 ) {
  8665. this._x = Math.atan2( - m23, m22 );
  8666. this._y = Math.atan2( - m31, m11 );
  8667. } else {
  8668. this._x = 0;
  8669. this._y = Math.atan2( m13, m33 );
  8670. }
  8671. } else if ( order === 'XZY' ) {
  8672. this._z = Math.asin( - clamp( m12, - 1, 1 ) );
  8673. if ( Math.abs( m12 ) < 0.9999999 ) {
  8674. this._x = Math.atan2( m32, m22 );
  8675. this._y = Math.atan2( m13, m11 );
  8676. } else {
  8677. this._x = Math.atan2( - m23, m33 );
  8678. this._y = 0;
  8679. }
  8680. } else {
  8681. console.warn( 'THREE.Euler: .setFromRotationMatrix() given unsupported order: ' + order );
  8682. }
  8683. this._order = order;
  8684. if ( update !== false ) { this._onChangeCallback(); }
  8685. return this;
  8686. },
  8687. setFromQuaternion: function ( q, order, update ) {
  8688. _matrix.makeRotationFromQuaternion( q );
  8689. return this.setFromRotationMatrix( _matrix, order, update );
  8690. },
  8691. setFromVector3: function ( v, order ) {
  8692. return this.set( v.x, v.y, v.z, order || this._order );
  8693. },
  8694. reorder: function ( newOrder ) {
  8695. // WARNING: this discards revolution information -bhouston
  8696. _quaternion$1.setFromEuler( this );
  8697. return this.setFromQuaternion( _quaternion$1, newOrder );
  8698. },
  8699. equals: function ( euler ) {
  8700. return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order );
  8701. },
  8702. fromArray: function ( array ) {
  8703. this._x = array[ 0 ];
  8704. this._y = array[ 1 ];
  8705. this._z = array[ 2 ];
  8706. if ( array[ 3 ] !== undefined ) { this._order = array[ 3 ]; }
  8707. this._onChangeCallback();
  8708. return this;
  8709. },
  8710. toArray: function ( array, offset ) {
  8711. if ( array === undefined ) { array = []; }
  8712. if ( offset === undefined ) { offset = 0; }
  8713. array[ offset ] = this._x;
  8714. array[ offset + 1 ] = this._y;
  8715. array[ offset + 2 ] = this._z;
  8716. array[ offset + 3 ] = this._order;
  8717. return array;
  8718. },
  8719. toVector3: function ( optionalResult ) {
  8720. if ( optionalResult ) {
  8721. return optionalResult.set( this._x, this._y, this._z );
  8722. } else {
  8723. return new Vector3( this._x, this._y, this._z );
  8724. }
  8725. },
  8726. _onChange: function ( callback ) {
  8727. this._onChangeCallback = callback;
  8728. return this;
  8729. },
  8730. _onChangeCallback: function () {}
  8731. } );
  8732. /**
  8733. * @author mrdoob / http://mrdoob.com/
  8734. */
  8735. function Layers() {
  8736. this.mask = 1 | 0;
  8737. }
  8738. Object.assign( Layers.prototype, {
  8739. set: function ( channel ) {
  8740. this.mask = 1 << channel | 0;
  8741. },
  8742. enable: function ( channel ) {
  8743. this.mask |= 1 << channel | 0;
  8744. },
  8745. enableAll: function () {
  8746. this.mask = 0xffffffff | 0;
  8747. },
  8748. toggle: function ( channel ) {
  8749. this.mask ^= 1 << channel | 0;
  8750. },
  8751. disable: function ( channel ) {
  8752. this.mask &= ~ ( 1 << channel | 0 );
  8753. },
  8754. disableAll: function () {
  8755. this.mask = 0;
  8756. },
  8757. test: function ( layers ) {
  8758. return ( this.mask & layers.mask ) !== 0;
  8759. }
  8760. } );
  8761. var _object3DId = 0;
  8762. var _v1$1 = new Vector3();
  8763. var _q1 = new Quaternion();
  8764. var _m1$1 = new Matrix4();
  8765. var _target = new Vector3();
  8766. var _position = new Vector3();
  8767. var _scale = new Vector3();
  8768. var _quaternion$2 = new Quaternion();
  8769. var _xAxis = new Vector3( 1, 0, 0 );
  8770. var _yAxis = new Vector3( 0, 1, 0 );
  8771. var _zAxis = new Vector3( 0, 0, 1 );
  8772. var _addedEvent = { type: 'added' };
  8773. var _removedEvent = { type: 'removed' };
  8774. /**
  8775. * @author mrdoob / http://mrdoob.com/
  8776. * @author mikael emtinger / http://gomo.se/
  8777. * @author alteredq / http://alteredqualia.com/
  8778. * @author WestLangley / http://github.com/WestLangley
  8779. * @author elephantatwork / www.elephantatwork.ch
  8780. */
  8781. function Object3D() {
  8782. Object.defineProperty( this, 'id', { value: _object3DId ++ } );
  8783. this.uuid = MathUtils.generateUUID();
  8784. this.name = '';
  8785. this.type = 'Object3D';
  8786. this.parent = null;
  8787. this.children = [];
  8788. this.up = Object3D.DefaultUp.clone();
  8789. var position = new Vector3();
  8790. var rotation = new Euler();
  8791. var quaternion = new Quaternion();
  8792. var scale = new Vector3( 1, 1, 1 );
  8793. function onRotationChange() {
  8794. quaternion.setFromEuler( rotation, false );
  8795. }
  8796. function onQuaternionChange() {
  8797. rotation.setFromQuaternion( quaternion, undefined, false );
  8798. }
  8799. rotation._onChange( onRotationChange );
  8800. quaternion._onChange( onQuaternionChange );
  8801. Object.defineProperties( this, {
  8802. position: {
  8803. configurable: true,
  8804. enumerable: true,
  8805. value: position
  8806. },
  8807. rotation: {
  8808. configurable: true,
  8809. enumerable: true,
  8810. value: rotation
  8811. },
  8812. quaternion: {
  8813. configurable: true,
  8814. enumerable: true,
  8815. value: quaternion
  8816. },
  8817. scale: {
  8818. configurable: true,
  8819. enumerable: true,
  8820. value: scale
  8821. },
  8822. modelViewMatrix: {
  8823. value: new Matrix4()
  8824. },
  8825. normalMatrix: {
  8826. value: new Matrix3()
  8827. }
  8828. } );
  8829. this.matrix = new Matrix4();
  8830. this.matrixWorld = new Matrix4();
  8831. this.matrixAutoUpdate = Object3D.DefaultMatrixAutoUpdate;
  8832. this.matrixWorldNeedsUpdate = false;
  8833. this.layers = new Layers();
  8834. this.visible = true;
  8835. this.castShadow = false;
  8836. this.receiveShadow = false;
  8837. this.frustumCulled = true;
  8838. this.renderOrder = 0;
  8839. this.userData = {};
  8840. }
  8841. Object3D.DefaultUp = new Vector3( 0, 1, 0 );
  8842. Object3D.DefaultMatrixAutoUpdate = true;
  8843. Object3D.prototype = Object.assign( Object.create( EventDispatcher.prototype ), {
  8844. constructor: Object3D,
  8845. isObject3D: true,
  8846. onBeforeRender: function () {},
  8847. onAfterRender: function () {},
  8848. applyMatrix4: function ( matrix ) {
  8849. if ( this.matrixAutoUpdate ) { this.updateMatrix(); }
  8850. this.matrix.premultiply( matrix );
  8851. this.matrix.decompose( this.position, this.quaternion, this.scale );
  8852. },
  8853. applyQuaternion: function ( q ) {
  8854. this.quaternion.premultiply( q );
  8855. return this;
  8856. },
  8857. setRotationFromAxisAngle: function ( axis, angle ) {
  8858. // assumes axis is normalized
  8859. this.quaternion.setFromAxisAngle( axis, angle );
  8860. },
  8861. setRotationFromEuler: function ( euler ) {
  8862. this.quaternion.setFromEuler( euler, true );
  8863. },
  8864. setRotationFromMatrix: function ( m ) {
  8865. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  8866. this.quaternion.setFromRotationMatrix( m );
  8867. },
  8868. setRotationFromQuaternion: function ( q ) {
  8869. // assumes q is normalized
  8870. this.quaternion.copy( q );
  8871. },
  8872. rotateOnAxis: function ( axis, angle ) {
  8873. // rotate object on axis in object space
  8874. // axis is assumed to be normalized
  8875. _q1.setFromAxisAngle( axis, angle );
  8876. this.quaternion.multiply( _q1 );
  8877. return this;
  8878. },
  8879. rotateOnWorldAxis: function ( axis, angle ) {
  8880. // rotate object on axis in world space
  8881. // axis is assumed to be normalized
  8882. // method assumes no rotated parent
  8883. _q1.setFromAxisAngle( axis, angle );
  8884. this.quaternion.premultiply( _q1 );
  8885. return this;
  8886. },
  8887. rotateX: function ( angle ) {
  8888. return this.rotateOnAxis( _xAxis, angle );
  8889. },
  8890. rotateY: function ( angle ) {
  8891. return this.rotateOnAxis( _yAxis, angle );
  8892. },
  8893. rotateZ: function ( angle ) {
  8894. return this.rotateOnAxis( _zAxis, angle );
  8895. },
  8896. translateOnAxis: function ( axis, distance ) {
  8897. // translate object by distance along axis in object space
  8898. // axis is assumed to be normalized
  8899. _v1$1.copy( axis ).applyQuaternion( this.quaternion );
  8900. this.position.add( _v1$1.multiplyScalar( distance ) );
  8901. return this;
  8902. },
  8903. translateX: function ( distance ) {
  8904. return this.translateOnAxis( _xAxis, distance );
  8905. },
  8906. translateY: function ( distance ) {
  8907. return this.translateOnAxis( _yAxis, distance );
  8908. },
  8909. translateZ: function ( distance ) {
  8910. return this.translateOnAxis( _zAxis, distance );
  8911. },
  8912. localToWorld: function ( vector ) {
  8913. return vector.applyMatrix4( this.matrixWorld );
  8914. },
  8915. worldToLocal: function ( vector ) {
  8916. return vector.applyMatrix4( _m1$1.getInverse( this.matrixWorld ) );
  8917. },
  8918. lookAt: function ( x, y, z ) {
  8919. // This method does not support objects having non-uniformly-scaled parent(s)
  8920. if ( x.isVector3 ) {
  8921. _target.copy( x );
  8922. } else {
  8923. _target.set( x, y, z );
  8924. }
  8925. var parent = this.parent;
  8926. this.updateWorldMatrix( true, false );
  8927. _position.setFromMatrixPosition( this.matrixWorld );
  8928. if ( this.isCamera || this.isLight ) {
  8929. _m1$1.lookAt( _position, _target, this.up );
  8930. } else {
  8931. _m1$1.lookAt( _target, _position, this.up );
  8932. }
  8933. this.quaternion.setFromRotationMatrix( _m1$1 );
  8934. if ( parent ) {
  8935. _m1$1.extractRotation( parent.matrixWorld );
  8936. _q1.setFromRotationMatrix( _m1$1 );
  8937. this.quaternion.premultiply( _q1.inverse() );
  8938. }
  8939. },
  8940. add: function ( object ) {
  8941. if ( arguments.length > 1 ) {
  8942. for ( var i = 0; i < arguments.length; i ++ ) {
  8943. this.add( arguments[ i ] );
  8944. }
  8945. return this;
  8946. }
  8947. if ( object === this ) {
  8948. console.error( "THREE.Object3D.add: object can't be added as a child of itself.", object );
  8949. return this;
  8950. }
  8951. if ( ( object && object.isObject3D ) ) {
  8952. if ( object.parent !== null ) {
  8953. object.parent.remove( object );
  8954. }
  8955. object.parent = this;
  8956. this.children.push( object );
  8957. object.dispatchEvent( _addedEvent );
  8958. } else {
  8959. console.error( "THREE.Object3D.add: object not an instance of THREE.Object3D.", object );
  8960. }
  8961. return this;
  8962. },
  8963. remove: function ( object ) {
  8964. if ( arguments.length > 1 ) {
  8965. for ( var i = 0; i < arguments.length; i ++ ) {
  8966. this.remove( arguments[ i ] );
  8967. }
  8968. return this;
  8969. }
  8970. var index = this.children.indexOf( object );
  8971. if ( index !== - 1 ) {
  8972. object.parent = null;
  8973. this.children.splice( index, 1 );
  8974. object.dispatchEvent( _removedEvent );
  8975. }
  8976. return this;
  8977. },
  8978. attach: function ( object ) {
  8979. // adds object as a child of this, while maintaining the object's world transform
  8980. this.updateWorldMatrix( true, false );
  8981. _m1$1.getInverse( this.matrixWorld );
  8982. if ( object.parent !== null ) {
  8983. object.parent.updateWorldMatrix( true, false );
  8984. _m1$1.multiply( object.parent.matrixWorld );
  8985. }
  8986. object.applyMatrix4( _m1$1 );
  8987. object.updateWorldMatrix( false, false );
  8988. this.add( object );
  8989. return this;
  8990. },
  8991. getObjectById: function ( id ) {
  8992. return this.getObjectByProperty( 'id', id );
  8993. },
  8994. getObjectByName: function ( name ) {
  8995. return this.getObjectByProperty( 'name', name );
  8996. },
  8997. getObjectByProperty: function ( name, value ) {
  8998. if ( this[ name ] === value ) { return this; }
  8999. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  9000. var child = this.children[ i ];
  9001. var object = child.getObjectByProperty( name, value );
  9002. if ( object !== undefined ) {
  9003. return object;
  9004. }
  9005. }
  9006. return undefined;
  9007. },
  9008. getWorldPosition: function ( target ) {
  9009. if ( target === undefined ) {
  9010. console.warn( 'THREE.Object3D: .getWorldPosition() target is now required' );
  9011. target = new Vector3();
  9012. }
  9013. this.updateMatrixWorld( true );
  9014. return target.setFromMatrixPosition( this.matrixWorld );
  9015. },
  9016. getWorldQuaternion: function ( target ) {
  9017. if ( target === undefined ) {
  9018. console.warn( 'THREE.Object3D: .getWorldQuaternion() target is now required' );
  9019. target = new Quaternion();
  9020. }
  9021. this.updateMatrixWorld( true );
  9022. this.matrixWorld.decompose( _position, target, _scale );
  9023. return target;
  9024. },
  9025. getWorldScale: function ( target ) {
  9026. if ( target === undefined ) {
  9027. console.warn( 'THREE.Object3D: .getWorldScale() target is now required' );
  9028. target = new Vector3();
  9029. }
  9030. this.updateMatrixWorld( true );
  9031. this.matrixWorld.decompose( _position, _quaternion$2, target );
  9032. return target;
  9033. },
  9034. getWorldDirection: function ( target ) {
  9035. if ( target === undefined ) {
  9036. console.warn( 'THREE.Object3D: .getWorldDirection() target is now required' );
  9037. target = new Vector3();
  9038. }
  9039. this.updateMatrixWorld( true );
  9040. var e = this.matrixWorld.elements;
  9041. return target.set( e[ 8 ], e[ 9 ], e[ 10 ] ).normalize();
  9042. },
  9043. raycast: function () {},
  9044. traverse: function ( callback ) {
  9045. callback( this );
  9046. var children = this.children;
  9047. for ( var i = 0, l = children.length; i < l; i ++ ) {
  9048. children[ i ].traverse( callback );
  9049. }
  9050. },
  9051. traverseVisible: function ( callback ) {
  9052. if ( this.visible === false ) { return; }
  9053. callback( this );
  9054. var children = this.children;
  9055. for ( var i = 0, l = children.length; i < l; i ++ ) {
  9056. children[ i ].traverseVisible( callback );
  9057. }
  9058. },
  9059. traverseAncestors: function ( callback ) {
  9060. var parent = this.parent;
  9061. if ( parent !== null ) {
  9062. callback( parent );
  9063. parent.traverseAncestors( callback );
  9064. }
  9065. },
  9066. updateMatrix: function () {
  9067. this.matrix.compose( this.position, this.quaternion, this.scale );
  9068. this.matrixWorldNeedsUpdate = true;
  9069. },
  9070. updateMatrixWorld: function ( force ) {
  9071. if ( this.matrixAutoUpdate ) { this.updateMatrix(); }
  9072. if ( this.matrixWorldNeedsUpdate || force ) {
  9073. if ( this.parent === null ) {
  9074. this.matrixWorld.copy( this.matrix );
  9075. } else {
  9076. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  9077. }
  9078. this.matrixWorldNeedsUpdate = false;
  9079. force = true;
  9080. }
  9081. // update children
  9082. var children = this.children;
  9083. for ( var i = 0, l = children.length; i < l; i ++ ) {
  9084. children[ i ].updateMatrixWorld( force );
  9085. }
  9086. },
  9087. updateWorldMatrix: function ( updateParents, updateChildren ) {
  9088. var parent = this.parent;
  9089. if ( updateParents === true && parent !== null ) {
  9090. parent.updateWorldMatrix( true, false );
  9091. }
  9092. if ( this.matrixAutoUpdate ) { this.updateMatrix(); }
  9093. if ( this.parent === null ) {
  9094. this.matrixWorld.copy( this.matrix );
  9095. } else {
  9096. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  9097. }
  9098. // update children
  9099. if ( updateChildren === true ) {
  9100. var children = this.children;
  9101. for ( var i = 0, l = children.length; i < l; i ++ ) {
  9102. children[ i ].updateWorldMatrix( false, true );
  9103. }
  9104. }
  9105. },
  9106. toJSON: function ( meta ) {
  9107. // meta is a string when called from JSON.stringify
  9108. var isRootObject = ( meta === undefined || typeof meta === 'string' );
  9109. var output = {};
  9110. // meta is a hash used to collect geometries, materials.
  9111. // not providing it implies that this is the root object
  9112. // being serialized.
  9113. if ( isRootObject ) {
  9114. // initialize meta obj
  9115. meta = {
  9116. geometries: {},
  9117. materials: {},
  9118. textures: {},
  9119. images: {},
  9120. shapes: {}
  9121. };
  9122. output.metadata = {
  9123. version: 4.5,
  9124. type: 'Object',
  9125. generator: 'Object3D.toJSON'
  9126. };
  9127. }
  9128. // standard Object3D serialization
  9129. var object = {};
  9130. object.uuid = this.uuid;
  9131. object.type = this.type;
  9132. if ( this.name !== '' ) { object.name = this.name; }
  9133. if ( this.castShadow === true ) { object.castShadow = true; }
  9134. if ( this.receiveShadow === true ) { object.receiveShadow = true; }
  9135. if ( this.visible === false ) { object.visible = false; }
  9136. if ( this.frustumCulled === false ) { object.frustumCulled = false; }
  9137. if ( this.renderOrder !== 0 ) { object.renderOrder = this.renderOrder; }
  9138. if ( JSON.stringify( this.userData ) !== '{}' ) { object.userData = this.userData; }
  9139. object.layers = this.layers.mask;
  9140. object.matrix = this.matrix.toArray();
  9141. if ( this.matrixAutoUpdate === false ) { object.matrixAutoUpdate = false; }
  9142. // object specific properties
  9143. if ( this.isInstancedMesh ) {
  9144. object.type = 'InstancedMesh';
  9145. object.count = this.count;
  9146. object.instanceMatrix = this.instanceMatrix.toJSON();
  9147. }
  9148. //
  9149. function serialize( library, element ) {
  9150. if ( library[ element.uuid ] === undefined ) {
  9151. library[ element.uuid ] = element.toJSON( meta );
  9152. }
  9153. return element.uuid;
  9154. }
  9155. if ( this.isMesh || this.isLine || this.isPoints ) {
  9156. object.geometry = serialize( meta.geometries, this.geometry );
  9157. var parameters = this.geometry.parameters;
  9158. if ( parameters !== undefined && parameters.shapes !== undefined ) {
  9159. var shapes = parameters.shapes;
  9160. if ( Array.isArray( shapes ) ) {
  9161. for ( var i = 0, l = shapes.length; i < l; i ++ ) {
  9162. var shape = shapes[ i ];
  9163. serialize( meta.shapes, shape );
  9164. }
  9165. } else {
  9166. serialize( meta.shapes, shapes );
  9167. }
  9168. }
  9169. }
  9170. if ( this.material !== undefined ) {
  9171. if ( Array.isArray( this.material ) ) {
  9172. var uuids = [];
  9173. for ( var i = 0, l = this.material.length; i < l; i ++ ) {
  9174. uuids.push( serialize( meta.materials, this.material[ i ] ) );
  9175. }
  9176. object.material = uuids;
  9177. } else {
  9178. object.material = serialize( meta.materials, this.material );
  9179. }
  9180. }
  9181. //
  9182. if ( this.children.length > 0 ) {
  9183. object.children = [];
  9184. for ( var i = 0; i < this.children.length; i ++ ) {
  9185. object.children.push( this.children[ i ].toJSON( meta ).object );
  9186. }
  9187. }
  9188. if ( isRootObject ) {
  9189. var geometries = extractFromCache( meta.geometries );
  9190. var materials = extractFromCache( meta.materials );
  9191. var textures = extractFromCache( meta.textures );
  9192. var images = extractFromCache( meta.images );
  9193. var shapes = extractFromCache( meta.shapes );
  9194. if ( geometries.length > 0 ) { output.geometries = geometries; }
  9195. if ( materials.length > 0 ) { output.materials = materials; }
  9196. if ( textures.length > 0 ) { output.textures = textures; }
  9197. if ( images.length > 0 ) { output.images = images; }
  9198. if ( shapes.length > 0 ) { output.shapes = shapes; }
  9199. }
  9200. output.object = object;
  9201. return output;
  9202. // extract data from the cache hash
  9203. // remove metadata on each item
  9204. // and return as array
  9205. function extractFromCache( cache ) {
  9206. var values = [];
  9207. for ( var key in cache ) {
  9208. var data = cache[ key ];
  9209. delete data.metadata;
  9210. values.push( data );
  9211. }
  9212. return values;
  9213. }
  9214. },
  9215. clone: function ( recursive ) {
  9216. return new this.constructor().copy( this, recursive );
  9217. },
  9218. copy: function ( source, recursive ) {
  9219. if ( recursive === undefined ) { recursive = true; }
  9220. this.name = source.name;
  9221. this.up.copy( source.up );
  9222. this.position.copy( source.position );
  9223. this.quaternion.copy( source.quaternion );
  9224. this.scale.copy( source.scale );
  9225. this.matrix.copy( source.matrix );
  9226. this.matrixWorld.copy( source.matrixWorld );
  9227. this.matrixAutoUpdate = source.matrixAutoUpdate;
  9228. this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  9229. this.layers.mask = source.layers.mask;
  9230. this.visible = source.visible;
  9231. this.castShadow = source.castShadow;
  9232. this.receiveShadow = source.receiveShadow;
  9233. this.frustumCulled = source.frustumCulled;
  9234. this.renderOrder = source.renderOrder;
  9235. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  9236. if ( recursive === true ) {
  9237. for ( var i = 0; i < source.children.length; i ++ ) {
  9238. var child = source.children[ i ];
  9239. this.add( child.clone() );
  9240. }
  9241. }
  9242. return this;
  9243. }
  9244. } );
  9245. /**
  9246. * @author mrdoob / http://mrdoob.com/
  9247. */
  9248. function Scene() {
  9249. Object3D.call( this );
  9250. this.type = 'Scene';
  9251. this.background = null;
  9252. this.environment = null;
  9253. this.fog = null;
  9254. this.overrideMaterial = null;
  9255. this.autoUpdate = true; // checked by the renderer
  9256. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  9257. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) ); // eslint-disable-line no-undef
  9258. }
  9259. }
  9260. Scene.prototype = Object.assign( Object.create( Object3D.prototype ), {
  9261. constructor: Scene,
  9262. isScene: true,
  9263. copy: function ( source, recursive ) {
  9264. Object3D.prototype.copy.call( this, source, recursive );
  9265. if ( source.background !== null ) { this.background = source.background.clone(); }
  9266. if ( source.environment !== null ) { this.environment = source.environment.clone(); }
  9267. if ( source.fog !== null ) { this.fog = source.fog.clone(); }
  9268. if ( source.overrideMaterial !== null ) { this.overrideMaterial = source.overrideMaterial.clone(); }
  9269. this.autoUpdate = source.autoUpdate;
  9270. this.matrixAutoUpdate = source.matrixAutoUpdate;
  9271. return this;
  9272. },
  9273. toJSON: function ( meta ) {
  9274. var data = Object3D.prototype.toJSON.call( this, meta );
  9275. if ( this.background !== null ) { data.object.background = this.background.toJSON( meta ); }
  9276. if ( this.environment !== null ) { data.object.environment = this.environment.toJSON( meta ); }
  9277. if ( this.fog !== null ) { data.object.fog = this.fog.toJSON(); }
  9278. return data;
  9279. },
  9280. dispose: function () {
  9281. this.dispatchEvent( { type: 'dispose' } );
  9282. }
  9283. } );
  9284. var _points = [
  9285. new Vector3(),
  9286. new Vector3(),
  9287. new Vector3(),
  9288. new Vector3(),
  9289. new Vector3(),
  9290. new Vector3(),
  9291. new Vector3(),
  9292. new Vector3()
  9293. ];
  9294. var _vector$1 = new Vector3();
  9295. var _box = new Box3();
  9296. // triangle centered vertices
  9297. var _v0 = new Vector3();
  9298. var _v1$2 = new Vector3();
  9299. var _v2 = new Vector3();
  9300. // triangle edge vectors
  9301. var _f0 = new Vector3();
  9302. var _f1 = new Vector3();
  9303. var _f2 = new Vector3();
  9304. var _center = new Vector3();
  9305. var _extents = new Vector3();
  9306. var _triangleNormal = new Vector3();
  9307. var _testAxis = new Vector3();
  9308. /**
  9309. * @author bhouston / http://clara.io
  9310. * @author WestLangley / http://github.com/WestLangley
  9311. */
  9312. function Box3( min, max ) {
  9313. this.min = ( min !== undefined ) ? min : new Vector3( + Infinity, + Infinity, + Infinity );
  9314. this.max = ( max !== undefined ) ? max : new Vector3( - Infinity, - Infinity, - Infinity );
  9315. }
  9316. Object.assign( Box3.prototype, {
  9317. isBox3: true,
  9318. set: function ( min, max ) {
  9319. this.min.copy( min );
  9320. this.max.copy( max );
  9321. return this;
  9322. },
  9323. setFromArray: function ( array ) {
  9324. var minX = + Infinity;
  9325. var minY = + Infinity;
  9326. var minZ = + Infinity;
  9327. var maxX = - Infinity;
  9328. var maxY = - Infinity;
  9329. var maxZ = - Infinity;
  9330. for ( var i = 0, l = array.length; i < l; i += 3 ) {
  9331. var x = array[ i ];
  9332. var y = array[ i + 1 ];
  9333. var z = array[ i + 2 ];
  9334. if ( x < minX ) { minX = x; }
  9335. if ( y < minY ) { minY = y; }
  9336. if ( z < minZ ) { minZ = z; }
  9337. if ( x > maxX ) { maxX = x; }
  9338. if ( y > maxY ) { maxY = y; }
  9339. if ( z > maxZ ) { maxZ = z; }
  9340. }
  9341. this.min.set( minX, minY, minZ );
  9342. this.max.set( maxX, maxY, maxZ );
  9343. return this;
  9344. },
  9345. setFromBufferAttribute: function ( attribute ) {
  9346. var minX = + Infinity;
  9347. var minY = + Infinity;
  9348. var minZ = + Infinity;
  9349. var maxX = - Infinity;
  9350. var maxY = - Infinity;
  9351. var maxZ = - Infinity;
  9352. for ( var i = 0, l = attribute.count; i < l; i ++ ) {
  9353. var x = attribute.getX( i );
  9354. var y = attribute.getY( i );
  9355. var z = attribute.getZ( i );
  9356. if ( x < minX ) { minX = x; }
  9357. if ( y < minY ) { minY = y; }
  9358. if ( z < minZ ) { minZ = z; }
  9359. if ( x > maxX ) { maxX = x; }
  9360. if ( y > maxY ) { maxY = y; }
  9361. if ( z > maxZ ) { maxZ = z; }
  9362. }
  9363. this.min.set( minX, minY, minZ );
  9364. this.max.set( maxX, maxY, maxZ );
  9365. return this;
  9366. },
  9367. setFromPoints: function ( points ) {
  9368. this.makeEmpty();
  9369. for ( var i = 0, il = points.length; i < il; i ++ ) {
  9370. this.expandByPoint( points[ i ] );
  9371. }
  9372. return this;
  9373. },
  9374. setFromCenterAndSize: function ( center, size ) {
  9375. var halfSize = _vector$1.copy( size ).multiplyScalar( 0.5 );
  9376. this.min.copy( center ).sub( halfSize );
  9377. this.max.copy( center ).add( halfSize );
  9378. return this;
  9379. },
  9380. setFromObject: function ( object ) {
  9381. this.makeEmpty();
  9382. return this.expandByObject( object );
  9383. },
  9384. clone: function () {
  9385. return new this.constructor().copy( this );
  9386. },
  9387. copy: function ( box ) {
  9388. this.min.copy( box.min );
  9389. this.max.copy( box.max );
  9390. return this;
  9391. },
  9392. makeEmpty: function () {
  9393. this.min.x = this.min.y = this.min.z = + Infinity;
  9394. this.max.x = this.max.y = this.max.z = - Infinity;
  9395. return this;
  9396. },
  9397. isEmpty: function () {
  9398. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  9399. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  9400. },
  9401. getCenter: function ( target ) {
  9402. if ( target === undefined ) {
  9403. console.warn( 'THREE.Box3: .getCenter() target is now required' );
  9404. target = new Vector3();
  9405. }
  9406. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  9407. },
  9408. getSize: function ( target ) {
  9409. if ( target === undefined ) {
  9410. console.warn( 'THREE.Box3: .getSize() target is now required' );
  9411. target = new Vector3();
  9412. }
  9413. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.subVectors( this.max, this.min );
  9414. },
  9415. expandByPoint: function ( point ) {
  9416. this.min.min( point );
  9417. this.max.max( point );
  9418. return this;
  9419. },
  9420. expandByVector: function ( vector ) {
  9421. this.min.sub( vector );
  9422. this.max.add( vector );
  9423. return this;
  9424. },
  9425. expandByScalar: function ( scalar ) {
  9426. this.min.addScalar( - scalar );
  9427. this.max.addScalar( scalar );
  9428. return this;
  9429. },
  9430. expandByObject: function ( object ) {
  9431. // Computes the world-axis-aligned bounding box of an object (including its children),
  9432. // accounting for both the object's, and children's, world transforms
  9433. object.updateWorldMatrix( false, false );
  9434. var geometry = object.geometry;
  9435. if ( geometry !== undefined ) {
  9436. if ( geometry.boundingBox === null ) {
  9437. geometry.computeBoundingBox();
  9438. }
  9439. _box.copy( geometry.boundingBox );
  9440. _box.applyMatrix4( object.matrixWorld );
  9441. this.union( _box );
  9442. }
  9443. var children = object.children;
  9444. for ( var i = 0, l = children.length; i < l; i ++ ) {
  9445. this.expandByObject( children[ i ] );
  9446. }
  9447. return this;
  9448. },
  9449. containsPoint: function ( point ) {
  9450. return point.x < this.min.x || point.x > this.max.x ||
  9451. point.y < this.min.y || point.y > this.max.y ||
  9452. point.z < this.min.z || point.z > this.max.z ? false : true;
  9453. },
  9454. containsBox: function ( box ) {
  9455. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  9456. this.min.y <= box.min.y && box.max.y <= this.max.y &&
  9457. this.min.z <= box.min.z && box.max.z <= this.max.z;
  9458. },
  9459. getParameter: function ( point, target ) {
  9460. // This can potentially have a divide by zero if the box
  9461. // has a size dimension of 0.
  9462. if ( target === undefined ) {
  9463. console.warn( 'THREE.Box3: .getParameter() target is now required' );
  9464. target = new Vector3();
  9465. }
  9466. return target.set(
  9467. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  9468. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  9469. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  9470. );
  9471. },
  9472. intersectsBox: function ( box ) {
  9473. // using 6 splitting planes to rule out intersections.
  9474. return box.max.x < this.min.x || box.min.x > this.max.x ||
  9475. box.max.y < this.min.y || box.min.y > this.max.y ||
  9476. box.max.z < this.min.z || box.min.z > this.max.z ? false : true;
  9477. },
  9478. intersectsSphere: function ( sphere ) {
  9479. // Find the point on the AABB closest to the sphere center.
  9480. this.clampPoint( sphere.center, _vector$1 );
  9481. // If that point is inside the sphere, the AABB and sphere intersect.
  9482. return _vector$1.distanceToSquared( sphere.center ) <= ( sphere.radius * sphere.radius );
  9483. },
  9484. intersectsPlane: function ( plane ) {
  9485. // We compute the minimum and maximum dot product values. If those values
  9486. // are on the same side (back or front) of the plane, then there is no intersection.
  9487. var min, max;
  9488. if ( plane.normal.x > 0 ) {
  9489. min = plane.normal.x * this.min.x;
  9490. max = plane.normal.x * this.max.x;
  9491. } else {
  9492. min = plane.normal.x * this.max.x;
  9493. max = plane.normal.x * this.min.x;
  9494. }
  9495. if ( plane.normal.y > 0 ) {
  9496. min += plane.normal.y * this.min.y;
  9497. max += plane.normal.y * this.max.y;
  9498. } else {
  9499. min += plane.normal.y * this.max.y;
  9500. max += plane.normal.y * this.min.y;
  9501. }
  9502. if ( plane.normal.z > 0 ) {
  9503. min += plane.normal.z * this.min.z;
  9504. max += plane.normal.z * this.max.z;
  9505. } else {
  9506. min += plane.normal.z * this.max.z;
  9507. max += plane.normal.z * this.min.z;
  9508. }
  9509. return ( min <= - plane.constant && max >= - plane.constant );
  9510. },
  9511. intersectsTriangle: function ( triangle ) {
  9512. if ( this.isEmpty() ) {
  9513. return false;
  9514. }
  9515. // compute box center and extents
  9516. this.getCenter( _center );
  9517. _extents.subVectors( this.max, _center );
  9518. // translate triangle to aabb origin
  9519. _v0.subVectors( triangle.a, _center );
  9520. _v1$2.subVectors( triangle.b, _center );
  9521. _v2.subVectors( triangle.c, _center );
  9522. // compute edge vectors for triangle
  9523. _f0.subVectors( _v1$2, _v0 );
  9524. _f1.subVectors( _v2, _v1$2 );
  9525. _f2.subVectors( _v0, _v2 );
  9526. // test against axes that are given by cross product combinations of the edges of the triangle and the edges of the aabb
  9527. // 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
  9528. // axis_ij = u_i x f_j (u0, u1, u2 = face normals of aabb = x,y,z axes vectors since aabb is axis aligned)
  9529. var axes = [
  9530. 0, - _f0.z, _f0.y, 0, - _f1.z, _f1.y, 0, - _f2.z, _f2.y,
  9531. _f0.z, 0, - _f0.x, _f1.z, 0, - _f1.x, _f2.z, 0, - _f2.x,
  9532. - _f0.y, _f0.x, 0, - _f1.y, _f1.x, 0, - _f2.y, _f2.x, 0
  9533. ];
  9534. if ( ! satForAxes( axes, _v0, _v1$2, _v2, _extents ) ) {
  9535. return false;
  9536. }
  9537. // test 3 face normals from the aabb
  9538. axes = [ 1, 0, 0, 0, 1, 0, 0, 0, 1 ];
  9539. if ( ! satForAxes( axes, _v0, _v1$2, _v2, _extents ) ) {
  9540. return false;
  9541. }
  9542. // finally testing the face normal of the triangle
  9543. // use already existing triangle edge vectors here
  9544. _triangleNormal.crossVectors( _f0, _f1 );
  9545. axes = [ _triangleNormal.x, _triangleNormal.y, _triangleNormal.z ];
  9546. return satForAxes( axes, _v0, _v1$2, _v2, _extents );
  9547. },
  9548. clampPoint: function ( point, target ) {
  9549. if ( target === undefined ) {
  9550. console.warn( 'THREE.Box3: .clampPoint() target is now required' );
  9551. target = new Vector3();
  9552. }
  9553. return target.copy( point ).clamp( this.min, this.max );
  9554. },
  9555. distanceToPoint: function ( point ) {
  9556. var clampedPoint = _vector$1.copy( point ).clamp( this.min, this.max );
  9557. return clampedPoint.sub( point ).length();
  9558. },
  9559. getBoundingSphere: function ( target ) {
  9560. if ( target === undefined ) {
  9561. console.error( 'THREE.Box3: .getBoundingSphere() target is now required' );
  9562. //target = new Sphere(); // removed to avoid cyclic dependency
  9563. }
  9564. this.getCenter( target.center );
  9565. target.radius = this.getSize( _vector$1 ).length() * 0.5;
  9566. return target;
  9567. },
  9568. intersect: function ( box ) {
  9569. this.min.max( box.min );
  9570. this.max.min( box.max );
  9571. // 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.
  9572. if ( this.isEmpty() ) { this.makeEmpty(); }
  9573. return this;
  9574. },
  9575. union: function ( box ) {
  9576. this.min.min( box.min );
  9577. this.max.max( box.max );
  9578. return this;
  9579. },
  9580. applyMatrix4: function ( matrix ) {
  9581. // transform of empty box is an empty box.
  9582. if ( this.isEmpty() ) { return this; }
  9583. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  9584. _points[ 0 ].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000
  9585. _points[ 1 ].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001
  9586. _points[ 2 ].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010
  9587. _points[ 3 ].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011
  9588. _points[ 4 ].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100
  9589. _points[ 5 ].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101
  9590. _points[ 6 ].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110
  9591. _points[ 7 ].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111
  9592. this.setFromPoints( _points );
  9593. return this;
  9594. },
  9595. translate: function ( offset ) {
  9596. this.min.add( offset );
  9597. this.max.add( offset );
  9598. return this;
  9599. },
  9600. equals: function ( box ) {
  9601. return box.min.equals( this.min ) && box.max.equals( this.max );
  9602. }
  9603. } );
  9604. function satForAxes( axes, v0, v1, v2, extents ) {
  9605. var i, j;
  9606. for ( i = 0, j = axes.length - 3; i <= j; i += 3 ) {
  9607. _testAxis.fromArray( axes, i );
  9608. // project the aabb onto the seperating axis
  9609. var r = extents.x * Math.abs( _testAxis.x ) + extents.y * Math.abs( _testAxis.y ) + extents.z * Math.abs( _testAxis.z );
  9610. // project all 3 vertices of the triangle onto the seperating axis
  9611. var p0 = v0.dot( _testAxis );
  9612. var p1 = v1.dot( _testAxis );
  9613. var p2 = v2.dot( _testAxis );
  9614. // actual test, basically see if either of the most extreme of the triangle points intersects r
  9615. if ( Math.max( - Math.max( p0, p1, p2 ), Math.min( p0, p1, p2 ) ) > r ) {
  9616. // points of the projected triangle are outside the projected half-length of the aabb
  9617. // the axis is seperating and we can exit
  9618. return false;
  9619. }
  9620. }
  9621. return true;
  9622. }
  9623. var _box$1 = new Box3();
  9624. /**
  9625. * @author bhouston / http://clara.io
  9626. * @author mrdoob / http://mrdoob.com/
  9627. */
  9628. function Sphere( center, radius ) {
  9629. this.center = ( center !== undefined ) ? center : new Vector3();
  9630. this.radius = ( radius !== undefined ) ? radius : 0;
  9631. }
  9632. Object.assign( Sphere.prototype, {
  9633. set: function ( center, radius ) {
  9634. this.center.copy( center );
  9635. this.radius = radius;
  9636. return this;
  9637. },
  9638. setFromPoints: function ( points, optionalCenter ) {
  9639. var center = this.center;
  9640. if ( optionalCenter !== undefined ) {
  9641. center.copy( optionalCenter );
  9642. } else {
  9643. _box$1.setFromPoints( points ).getCenter( center );
  9644. }
  9645. var maxRadiusSq = 0;
  9646. for ( var i = 0, il = points.length; i < il; i ++ ) {
  9647. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) );
  9648. }
  9649. this.radius = Math.sqrt( maxRadiusSq );
  9650. return this;
  9651. },
  9652. clone: function () {
  9653. return new this.constructor().copy( this );
  9654. },
  9655. copy: function ( sphere ) {
  9656. this.center.copy( sphere.center );
  9657. this.radius = sphere.radius;
  9658. return this;
  9659. },
  9660. empty: function () {
  9661. return ( this.radius <= 0 );
  9662. },
  9663. containsPoint: function ( point ) {
  9664. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  9665. },
  9666. distanceToPoint: function ( point ) {
  9667. return ( point.distanceTo( this.center ) - this.radius );
  9668. },
  9669. intersectsSphere: function ( sphere ) {
  9670. var radiusSum = this.radius + sphere.radius;
  9671. return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );
  9672. },
  9673. intersectsBox: function ( box ) {
  9674. return box.intersectsSphere( this );
  9675. },
  9676. intersectsPlane: function ( plane ) {
  9677. return Math.abs( plane.distanceToPoint( this.center ) ) <= this.radius;
  9678. },
  9679. clampPoint: function ( point, target ) {
  9680. var deltaLengthSq = this.center.distanceToSquared( point );
  9681. if ( target === undefined ) {
  9682. console.warn( 'THREE.Sphere: .clampPoint() target is now required' );
  9683. target = new Vector3();
  9684. }
  9685. target.copy( point );
  9686. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  9687. target.sub( this.center ).normalize();
  9688. target.multiplyScalar( this.radius ).add( this.center );
  9689. }
  9690. return target;
  9691. },
  9692. getBoundingBox: function ( target ) {
  9693. if ( target === undefined ) {
  9694. console.warn( 'THREE.Sphere: .getBoundingBox() target is now required' );
  9695. target = new Box3();
  9696. }
  9697. target.set( this.center, this.center );
  9698. target.expandByScalar( this.radius );
  9699. return target;
  9700. },
  9701. applyMatrix4: function ( matrix ) {
  9702. this.center.applyMatrix4( matrix );
  9703. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  9704. return this;
  9705. },
  9706. translate: function ( offset ) {
  9707. this.center.add( offset );
  9708. return this;
  9709. },
  9710. equals: function ( sphere ) {
  9711. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  9712. }
  9713. } );
  9714. var _vector$2 = new Vector3();
  9715. var _segCenter = new Vector3();
  9716. var _segDir = new Vector3();
  9717. var _diff = new Vector3();
  9718. var _edge1 = new Vector3();
  9719. var _edge2 = new Vector3();
  9720. var _normal = new Vector3();
  9721. /**
  9722. * @author bhouston / http://clara.io
  9723. */
  9724. function Ray( origin, direction ) {
  9725. this.origin = ( origin !== undefined ) ? origin : new Vector3();
  9726. this.direction = ( direction !== undefined ) ? direction : new Vector3( 0, 0, - 1 );
  9727. }
  9728. Object.assign( Ray.prototype, {
  9729. set: function ( origin, direction ) {
  9730. this.origin.copy( origin );
  9731. this.direction.copy( direction );
  9732. return this;
  9733. },
  9734. clone: function () {
  9735. return new this.constructor().copy( this );
  9736. },
  9737. copy: function ( ray ) {
  9738. this.origin.copy( ray.origin );
  9739. this.direction.copy( ray.direction );
  9740. return this;
  9741. },
  9742. at: function ( t, target ) {
  9743. if ( target === undefined ) {
  9744. console.warn( 'THREE.Ray: .at() target is now required' );
  9745. target = new Vector3();
  9746. }
  9747. return target.copy( this.direction ).multiplyScalar( t ).add( this.origin );
  9748. },
  9749. lookAt: function ( v ) {
  9750. this.direction.copy( v ).sub( this.origin ).normalize();
  9751. return this;
  9752. },
  9753. recast: function ( t ) {
  9754. this.origin.copy( this.at( t, _vector$2 ) );
  9755. return this;
  9756. },
  9757. closestPointToPoint: function ( point, target ) {
  9758. if ( target === undefined ) {
  9759. console.warn( 'THREE.Ray: .closestPointToPoint() target is now required' );
  9760. target = new Vector3();
  9761. }
  9762. target.subVectors( point, this.origin );
  9763. var directionDistance = target.dot( this.direction );
  9764. if ( directionDistance < 0 ) {
  9765. return target.copy( this.origin );
  9766. }
  9767. return target.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  9768. },
  9769. distanceToPoint: function ( point ) {
  9770. return Math.sqrt( this.distanceSqToPoint( point ) );
  9771. },
  9772. distanceSqToPoint: function ( point ) {
  9773. var directionDistance = _vector$2.subVectors( point, this.origin ).dot( this.direction );
  9774. // point behind the ray
  9775. if ( directionDistance < 0 ) {
  9776. return this.origin.distanceToSquared( point );
  9777. }
  9778. _vector$2.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  9779. return _vector$2.distanceToSquared( point );
  9780. },
  9781. distanceSqToSegment: function ( v0, v1, optionalPointOnRay, optionalPointOnSegment ) {
  9782. // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteDistRaySegment.h
  9783. // It returns the min distance between the ray and the segment
  9784. // defined by v0 and v1
  9785. // It can also set two optional targets :
  9786. // - The closest point on the ray
  9787. // - The closest point on the segment
  9788. _segCenter.copy( v0 ).add( v1 ).multiplyScalar( 0.5 );
  9789. _segDir.copy( v1 ).sub( v0 ).normalize();
  9790. _diff.copy( this.origin ).sub( _segCenter );
  9791. var segExtent = v0.distanceTo( v1 ) * 0.5;
  9792. var a01 = - this.direction.dot( _segDir );
  9793. var b0 = _diff.dot( this.direction );
  9794. var b1 = - _diff.dot( _segDir );
  9795. var c = _diff.lengthSq();
  9796. var det = Math.abs( 1 - a01 * a01 );
  9797. var s0, s1, sqrDist, extDet;
  9798. if ( det > 0 ) {
  9799. // The ray and segment are not parallel.
  9800. s0 = a01 * b1 - b0;
  9801. s1 = a01 * b0 - b1;
  9802. extDet = segExtent * det;
  9803. if ( s0 >= 0 ) {
  9804. if ( s1 >= - extDet ) {
  9805. if ( s1 <= extDet ) {
  9806. // region 0
  9807. // Minimum at interior points of ray and segment.
  9808. var invDet = 1 / det;
  9809. s0 *= invDet;
  9810. s1 *= invDet;
  9811. sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c;
  9812. } else {
  9813. // region 1
  9814. s1 = segExtent;
  9815. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  9816. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  9817. }
  9818. } else {
  9819. // region 5
  9820. s1 = - segExtent;
  9821. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  9822. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  9823. }
  9824. } else {
  9825. if ( s1 <= - extDet ) {
  9826. // region 4
  9827. s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) );
  9828. s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  9829. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  9830. } else if ( s1 <= extDet ) {
  9831. // region 3
  9832. s0 = 0;
  9833. s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent );
  9834. sqrDist = s1 * ( s1 + 2 * b1 ) + c;
  9835. } else {
  9836. // region 2
  9837. s0 = Math.max( 0, - ( a01 * segExtent + b0 ) );
  9838. s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  9839. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  9840. }
  9841. }
  9842. } else {
  9843. // Ray and segment are parallel.
  9844. s1 = ( a01 > 0 ) ? - segExtent : segExtent;
  9845. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  9846. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  9847. }
  9848. if ( optionalPointOnRay ) {
  9849. optionalPointOnRay.copy( this.direction ).multiplyScalar( s0 ).add( this.origin );
  9850. }
  9851. if ( optionalPointOnSegment ) {
  9852. optionalPointOnSegment.copy( _segDir ).multiplyScalar( s1 ).add( _segCenter );
  9853. }
  9854. return sqrDist;
  9855. },
  9856. intersectSphere: function ( sphere, target ) {
  9857. _vector$2.subVectors( sphere.center, this.origin );
  9858. var tca = _vector$2.dot( this.direction );
  9859. var d2 = _vector$2.dot( _vector$2 ) - tca * tca;
  9860. var radius2 = sphere.radius * sphere.radius;
  9861. if ( d2 > radius2 ) { return null; }
  9862. var thc = Math.sqrt( radius2 - d2 );
  9863. // t0 = first intersect point - entrance on front of sphere
  9864. var t0 = tca - thc;
  9865. // t1 = second intersect point - exit point on back of sphere
  9866. var t1 = tca + thc;
  9867. // test to see if both t0 and t1 are behind the ray - if so, return null
  9868. if ( t0 < 0 && t1 < 0 ) { return null; }
  9869. // test to see if t0 is behind the ray:
  9870. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  9871. // in order to always return an intersect point that is in front of the ray.
  9872. if ( t0 < 0 ) { return this.at( t1, target ); }
  9873. // else t0 is in front of the ray, so return the first collision point scaled by t0
  9874. return this.at( t0, target );
  9875. },
  9876. intersectsSphere: function ( sphere ) {
  9877. return this.distanceSqToPoint( sphere.center ) <= ( sphere.radius * sphere.radius );
  9878. },
  9879. distanceToPlane: function ( plane ) {
  9880. var denominator = plane.normal.dot( this.direction );
  9881. if ( denominator === 0 ) {
  9882. // line is coplanar, return origin
  9883. if ( plane.distanceToPoint( this.origin ) === 0 ) {
  9884. return 0;
  9885. }
  9886. // Null is preferable to undefined since undefined means.... it is undefined
  9887. return null;
  9888. }
  9889. var t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  9890. // Return if the ray never intersects the plane
  9891. return t >= 0 ? t : null;
  9892. },
  9893. intersectPlane: function ( plane, target ) {
  9894. var t = this.distanceToPlane( plane );
  9895. if ( t === null ) {
  9896. return null;
  9897. }
  9898. return this.at( t, target );
  9899. },
  9900. intersectsPlane: function ( plane ) {
  9901. // check if the ray lies on the plane first
  9902. var distToPoint = plane.distanceToPoint( this.origin );
  9903. if ( distToPoint === 0 ) {
  9904. return true;
  9905. }
  9906. var denominator = plane.normal.dot( this.direction );
  9907. if ( denominator * distToPoint < 0 ) {
  9908. return true;
  9909. }
  9910. // ray origin is behind the plane (and is pointing behind it)
  9911. return false;
  9912. },
  9913. intersectBox: function ( box, target ) {
  9914. var tmin, tmax, tymin, tymax, tzmin, tzmax;
  9915. var invdirx = 1 / this.direction.x,
  9916. invdiry = 1 / this.direction.y,
  9917. invdirz = 1 / this.direction.z;
  9918. var origin = this.origin;
  9919. if ( invdirx >= 0 ) {
  9920. tmin = ( box.min.x - origin.x ) * invdirx;
  9921. tmax = ( box.max.x - origin.x ) * invdirx;
  9922. } else {
  9923. tmin = ( box.max.x - origin.x ) * invdirx;
  9924. tmax = ( box.min.x - origin.x ) * invdirx;
  9925. }
  9926. if ( invdiry >= 0 ) {
  9927. tymin = ( box.min.y - origin.y ) * invdiry;
  9928. tymax = ( box.max.y - origin.y ) * invdiry;
  9929. } else {
  9930. tymin = ( box.max.y - origin.y ) * invdiry;
  9931. tymax = ( box.min.y - origin.y ) * invdiry;
  9932. }
  9933. if ( ( tmin > tymax ) || ( tymin > tmax ) ) { return null; }
  9934. // These lines also handle the case where tmin or tmax is NaN
  9935. // (result of 0 * Infinity). x !== x returns true if x is NaN
  9936. if ( tymin > tmin || tmin !== tmin ) { tmin = tymin; }
  9937. if ( tymax < tmax || tmax !== tmax ) { tmax = tymax; }
  9938. if ( invdirz >= 0 ) {
  9939. tzmin = ( box.min.z - origin.z ) * invdirz;
  9940. tzmax = ( box.max.z - origin.z ) * invdirz;
  9941. } else {
  9942. tzmin = ( box.max.z - origin.z ) * invdirz;
  9943. tzmax = ( box.min.z - origin.z ) * invdirz;
  9944. }
  9945. if ( ( tmin > tzmax ) || ( tzmin > tmax ) ) { return null; }
  9946. if ( tzmin > tmin || tmin !== tmin ) { tmin = tzmin; }
  9947. if ( tzmax < tmax || tmax !== tmax ) { tmax = tzmax; }
  9948. //return point closest to the ray (positive side)
  9949. if ( tmax < 0 ) { return null; }
  9950. return this.at( tmin >= 0 ? tmin : tmax, target );
  9951. },
  9952. intersectsBox: function ( box ) {
  9953. return this.intersectBox( box, _vector$2 ) !== null;
  9954. },
  9955. intersectTriangle: function ( a, b, c, backfaceCulling, target ) {
  9956. // Compute the offset origin, edges, and normal.
  9957. // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h
  9958. _edge1.subVectors( b, a );
  9959. _edge2.subVectors( c, a );
  9960. _normal.crossVectors( _edge1, _edge2 );
  9961. // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  9962. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  9963. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  9964. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  9965. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  9966. var DdN = this.direction.dot( _normal );
  9967. var sign;
  9968. if ( DdN > 0 ) {
  9969. if ( backfaceCulling ) { return null; }
  9970. sign = 1;
  9971. } else if ( DdN < 0 ) {
  9972. sign = - 1;
  9973. DdN = - DdN;
  9974. } else {
  9975. return null;
  9976. }
  9977. _diff.subVectors( this.origin, a );
  9978. var DdQxE2 = sign * this.direction.dot( _edge2.crossVectors( _diff, _edge2 ) );
  9979. // b1 < 0, no intersection
  9980. if ( DdQxE2 < 0 ) {
  9981. return null;
  9982. }
  9983. var DdE1xQ = sign * this.direction.dot( _edge1.cross( _diff ) );
  9984. // b2 < 0, no intersection
  9985. if ( DdE1xQ < 0 ) {
  9986. return null;
  9987. }
  9988. // b1+b2 > 1, no intersection
  9989. if ( DdQxE2 + DdE1xQ > DdN ) {
  9990. return null;
  9991. }
  9992. // Line intersects triangle, check if ray does.
  9993. var QdN = - sign * _diff.dot( _normal );
  9994. // t < 0, no intersection
  9995. if ( QdN < 0 ) {
  9996. return null;
  9997. }
  9998. // Ray intersects triangle.
  9999. return this.at( QdN / DdN, target );
  10000. },
  10001. applyMatrix4: function ( matrix4 ) {
  10002. this.origin.applyMatrix4( matrix4 );
  10003. this.direction.transformDirection( matrix4 );
  10004. return this;
  10005. },
  10006. equals: function ( ray ) {
  10007. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  10008. }
  10009. } );
  10010. /**
  10011. * @author bhouston / http://clara.io
  10012. */
  10013. var _vector1 = new Vector3();
  10014. var _vector2 = new Vector3();
  10015. var _normalMatrix = new Matrix3();
  10016. function Plane( normal, constant ) {
  10017. // normal is assumed to be normalized
  10018. this.normal = ( normal !== undefined ) ? normal : new Vector3( 1, 0, 0 );
  10019. this.constant = ( constant !== undefined ) ? constant : 0;
  10020. }
  10021. Object.assign( Plane.prototype, {
  10022. isPlane: true,
  10023. set: function ( normal, constant ) {
  10024. this.normal.copy( normal );
  10025. this.constant = constant;
  10026. return this;
  10027. },
  10028. setComponents: function ( x, y, z, w ) {
  10029. this.normal.set( x, y, z );
  10030. this.constant = w;
  10031. return this;
  10032. },
  10033. setFromNormalAndCoplanarPoint: function ( normal, point ) {
  10034. this.normal.copy( normal );
  10035. this.constant = - point.dot( this.normal );
  10036. return this;
  10037. },
  10038. setFromCoplanarPoints: function ( a, b, c ) {
  10039. var normal = _vector1.subVectors( c, b ).cross( _vector2.subVectors( a, b ) ).normalize();
  10040. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  10041. this.setFromNormalAndCoplanarPoint( normal, a );
  10042. return this;
  10043. },
  10044. clone: function () {
  10045. return new this.constructor().copy( this );
  10046. },
  10047. copy: function ( plane ) {
  10048. this.normal.copy( plane.normal );
  10049. this.constant = plane.constant;
  10050. return this;
  10051. },
  10052. normalize: function () {
  10053. // Note: will lead to a divide by zero if the plane is invalid.
  10054. var inverseNormalLength = 1.0 / this.normal.length();
  10055. this.normal.multiplyScalar( inverseNormalLength );
  10056. this.constant *= inverseNormalLength;
  10057. return this;
  10058. },
  10059. negate: function () {
  10060. this.constant *= - 1;
  10061. this.normal.negate();
  10062. return this;
  10063. },
  10064. distanceToPoint: function ( point ) {
  10065. return this.normal.dot( point ) + this.constant;
  10066. },
  10067. distanceToSphere: function ( sphere ) {
  10068. return this.distanceToPoint( sphere.center ) - sphere.radius;
  10069. },
  10070. projectPoint: function ( point, target ) {
  10071. if ( target === undefined ) {
  10072. console.warn( 'THREE.Plane: .projectPoint() target is now required' );
  10073. target = new Vector3();
  10074. }
  10075. return target.copy( this.normal ).multiplyScalar( - this.distanceToPoint( point ) ).add( point );
  10076. },
  10077. intersectLine: function ( line, target ) {
  10078. if ( target === undefined ) {
  10079. console.warn( 'THREE.Plane: .intersectLine() target is now required' );
  10080. target = new Vector3();
  10081. }
  10082. var direction = line.delta( _vector1 );
  10083. var denominator = this.normal.dot( direction );
  10084. if ( denominator === 0 ) {
  10085. // line is coplanar, return origin
  10086. if ( this.distanceToPoint( line.start ) === 0 ) {
  10087. return target.copy( line.start );
  10088. }
  10089. // Unsure if this is the correct method to handle this case.
  10090. return undefined;
  10091. }
  10092. var t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
  10093. if ( t < 0 || t > 1 ) {
  10094. return undefined;
  10095. }
  10096. return target.copy( direction ).multiplyScalar( t ).add( line.start );
  10097. },
  10098. intersectsLine: function ( line ) {
  10099. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  10100. var startSign = this.distanceToPoint( line.start );
  10101. var endSign = this.distanceToPoint( line.end );
  10102. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  10103. },
  10104. intersectsBox: function ( box ) {
  10105. return box.intersectsPlane( this );
  10106. },
  10107. intersectsSphere: function ( sphere ) {
  10108. return sphere.intersectsPlane( this );
  10109. },
  10110. coplanarPoint: function ( target ) {
  10111. if ( target === undefined ) {
  10112. console.warn( 'THREE.Plane: .coplanarPoint() target is now required' );
  10113. target = new Vector3();
  10114. }
  10115. return target.copy( this.normal ).multiplyScalar( - this.constant );
  10116. },
  10117. applyMatrix4: function ( matrix, optionalNormalMatrix ) {
  10118. var normalMatrix = optionalNormalMatrix || _normalMatrix.getNormalMatrix( matrix );
  10119. var referencePoint = this.coplanarPoint( _vector1 ).applyMatrix4( matrix );
  10120. var normal = this.normal.applyMatrix3( normalMatrix ).normalize();
  10121. this.constant = - referencePoint.dot( normal );
  10122. return this;
  10123. },
  10124. translate: function ( offset ) {
  10125. this.constant -= offset.dot( this.normal );
  10126. return this;
  10127. },
  10128. equals: function ( plane ) {
  10129. return plane.normal.equals( this.normal ) && ( plane.constant === this.constant );
  10130. }
  10131. } );
  10132. /**
  10133. * @author bhouston / http://clara.io
  10134. * @author mrdoob / http://mrdoob.com/
  10135. */
  10136. var _v0$1 = new Vector3();
  10137. var _v1$3 = new Vector3();
  10138. var _v2$1 = new Vector3();
  10139. var _v3 = new Vector3();
  10140. var _vab = new Vector3();
  10141. var _vac = new Vector3();
  10142. var _vbc = new Vector3();
  10143. var _vap = new Vector3();
  10144. var _vbp = new Vector3();
  10145. var _vcp = new Vector3();
  10146. function Triangle( a, b, c ) {
  10147. this.a = ( a !== undefined ) ? a : new Vector3();
  10148. this.b = ( b !== undefined ) ? b : new Vector3();
  10149. this.c = ( c !== undefined ) ? c : new Vector3();
  10150. }
  10151. Object.assign( Triangle, {
  10152. getNormal: function ( a, b, c, target ) {
  10153. if ( target === undefined ) {
  10154. console.warn( 'THREE.Triangle: .getNormal() target is now required' );
  10155. target = new Vector3();
  10156. }
  10157. target.subVectors( c, b );
  10158. _v0$1.subVectors( a, b );
  10159. target.cross( _v0$1 );
  10160. var targetLengthSq = target.lengthSq();
  10161. if ( targetLengthSq > 0 ) {
  10162. return target.multiplyScalar( 1 / Math.sqrt( targetLengthSq ) );
  10163. }
  10164. return target.set( 0, 0, 0 );
  10165. },
  10166. // static/instance method to calculate barycentric coordinates
  10167. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  10168. getBarycoord: function ( point, a, b, c, target ) {
  10169. _v0$1.subVectors( c, a );
  10170. _v1$3.subVectors( b, a );
  10171. _v2$1.subVectors( point, a );
  10172. var dot00 = _v0$1.dot( _v0$1 );
  10173. var dot01 = _v0$1.dot( _v1$3 );
  10174. var dot02 = _v0$1.dot( _v2$1 );
  10175. var dot11 = _v1$3.dot( _v1$3 );
  10176. var dot12 = _v1$3.dot( _v2$1 );
  10177. var denom = ( dot00 * dot11 - dot01 * dot01 );
  10178. if ( target === undefined ) {
  10179. console.warn( 'THREE.Triangle: .getBarycoord() target is now required' );
  10180. target = new Vector3();
  10181. }
  10182. // collinear or singular triangle
  10183. if ( denom === 0 ) {
  10184. // arbitrary location outside of triangle?
  10185. // not sure if this is the best idea, maybe should be returning undefined
  10186. return target.set( - 2, - 1, - 1 );
  10187. }
  10188. var invDenom = 1 / denom;
  10189. var u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  10190. var v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  10191. // barycentric coordinates must always sum to 1
  10192. return target.set( 1 - u - v, v, u );
  10193. },
  10194. containsPoint: function ( point, a, b, c ) {
  10195. Triangle.getBarycoord( point, a, b, c, _v3 );
  10196. return ( _v3.x >= 0 ) && ( _v3.y >= 0 ) && ( ( _v3.x + _v3.y ) <= 1 );
  10197. },
  10198. getUV: function ( point, p1, p2, p3, uv1, uv2, uv3, target ) {
  10199. this.getBarycoord( point, p1, p2, p3, _v3 );
  10200. target.set( 0, 0 );
  10201. target.addScaledVector( uv1, _v3.x );
  10202. target.addScaledVector( uv2, _v3.y );
  10203. target.addScaledVector( uv3, _v3.z );
  10204. return target;
  10205. },
  10206. isFrontFacing: function ( a, b, c, direction ) {
  10207. _v0$1.subVectors( c, b );
  10208. _v1$3.subVectors( a, b );
  10209. // strictly front facing
  10210. return ( _v0$1.cross( _v1$3 ).dot( direction ) < 0 ) ? true : false;
  10211. }
  10212. } );
  10213. Object.assign( Triangle.prototype, {
  10214. set: function ( a, b, c ) {
  10215. this.a.copy( a );
  10216. this.b.copy( b );
  10217. this.c.copy( c );
  10218. return this;
  10219. },
  10220. setFromPointsAndIndices: function ( points, i0, i1, i2 ) {
  10221. this.a.copy( points[ i0 ] );
  10222. this.b.copy( points[ i1 ] );
  10223. this.c.copy( points[ i2 ] );
  10224. return this;
  10225. },
  10226. clone: function () {
  10227. return new this.constructor().copy( this );
  10228. },
  10229. copy: function ( triangle ) {
  10230. this.a.copy( triangle.a );
  10231. this.b.copy( triangle.b );
  10232. this.c.copy( triangle.c );
  10233. return this;
  10234. },
  10235. getArea: function () {
  10236. _v0$1.subVectors( this.c, this.b );
  10237. _v1$3.subVectors( this.a, this.b );
  10238. return _v0$1.cross( _v1$3 ).length() * 0.5;
  10239. },
  10240. getMidpoint: function ( target ) {
  10241. if ( target === undefined ) {
  10242. console.warn( 'THREE.Triangle: .getMidpoint() target is now required' );
  10243. target = new Vector3();
  10244. }
  10245. return target.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  10246. },
  10247. getNormal: function ( target ) {
  10248. return Triangle.getNormal( this.a, this.b, this.c, target );
  10249. },
  10250. getPlane: function ( target ) {
  10251. if ( target === undefined ) {
  10252. console.warn( 'THREE.Triangle: .getPlane() target is now required' );
  10253. target = new Plane();
  10254. }
  10255. return target.setFromCoplanarPoints( this.a, this.b, this.c );
  10256. },
  10257. getBarycoord: function ( point, target ) {
  10258. return Triangle.getBarycoord( point, this.a, this.b, this.c, target );
  10259. },
  10260. getUV: function ( point, uv1, uv2, uv3, target ) {
  10261. return Triangle.getUV( point, this.a, this.b, this.c, uv1, uv2, uv3, target );
  10262. },
  10263. containsPoint: function ( point ) {
  10264. return Triangle.containsPoint( point, this.a, this.b, this.c );
  10265. },
  10266. isFrontFacing: function ( direction ) {
  10267. return Triangle.isFrontFacing( this.a, this.b, this.c, direction );
  10268. },
  10269. intersectsBox: function ( box ) {
  10270. return box.intersectsTriangle( this );
  10271. },
  10272. closestPointToPoint: function ( p, target ) {
  10273. if ( target === undefined ) {
  10274. console.warn( 'THREE.Triangle: .closestPointToPoint() target is now required' );
  10275. target = new Vector3();
  10276. }
  10277. var a = this.a, b = this.b, c = this.c;
  10278. var v, w;
  10279. // algorithm thanks to Real-Time Collision Detection by Christer Ericson,
  10280. // published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc.,
  10281. // under the accompanying license; see chapter 5.1.5 for detailed explanation.
  10282. // basically, we're distinguishing which of the voronoi regions of the triangle
  10283. // the point lies in with the minimum amount of redundant computation.
  10284. _vab.subVectors( b, a );
  10285. _vac.subVectors( c, a );
  10286. _vap.subVectors( p, a );
  10287. var d1 = _vab.dot( _vap );
  10288. var d2 = _vac.dot( _vap );
  10289. if ( d1 <= 0 && d2 <= 0 ) {
  10290. // vertex region of A; barycentric coords (1, 0, 0)
  10291. return target.copy( a );
  10292. }
  10293. _vbp.subVectors( p, b );
  10294. var d3 = _vab.dot( _vbp );
  10295. var d4 = _vac.dot( _vbp );
  10296. if ( d3 >= 0 && d4 <= d3 ) {
  10297. // vertex region of B; barycentric coords (0, 1, 0)
  10298. return target.copy( b );
  10299. }
  10300. var vc = d1 * d4 - d3 * d2;
  10301. if ( vc <= 0 && d1 >= 0 && d3 <= 0 ) {
  10302. v = d1 / ( d1 - d3 );
  10303. // edge region of AB; barycentric coords (1-v, v, 0)
  10304. return target.copy( a ).addScaledVector( _vab, v );
  10305. }
  10306. _vcp.subVectors( p, c );
  10307. var d5 = _vab.dot( _vcp );
  10308. var d6 = _vac.dot( _vcp );
  10309. if ( d6 >= 0 && d5 <= d6 ) {
  10310. // vertex region of C; barycentric coords (0, 0, 1)
  10311. return target.copy( c );
  10312. }
  10313. var vb = d5 * d2 - d1 * d6;
  10314. if ( vb <= 0 && d2 >= 0 && d6 <= 0 ) {
  10315. w = d2 / ( d2 - d6 );
  10316. // edge region of AC; barycentric coords (1-w, 0, w)
  10317. return target.copy( a ).addScaledVector( _vac, w );
  10318. }
  10319. var va = d3 * d6 - d5 * d4;
  10320. if ( va <= 0 && ( d4 - d3 ) >= 0 && ( d5 - d6 ) >= 0 ) {
  10321. _vbc.subVectors( c, b );
  10322. w = ( d4 - d3 ) / ( ( d4 - d3 ) + ( d5 - d6 ) );
  10323. // edge region of BC; barycentric coords (0, 1-w, w)
  10324. return target.copy( b ).addScaledVector( _vbc, w ); // edge region of BC
  10325. }
  10326. // face region
  10327. var denom = 1 / ( va + vb + vc );
  10328. // u = va * denom
  10329. v = vb * denom;
  10330. w = vc * denom;
  10331. return target.copy( a ).addScaledVector( _vab, v ).addScaledVector( _vac, w );
  10332. },
  10333. equals: function ( triangle ) {
  10334. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  10335. }
  10336. } );
  10337. /**
  10338. * @author mrdoob / http://mrdoob.com/
  10339. */
  10340. var _colorKeywords = { 'aliceblue': 0xF0F8FF, 'antiquewhite': 0xFAEBD7, 'aqua': 0x00FFFF, 'aquamarine': 0x7FFFD4, 'azure': 0xF0FFFF,
  10341. 'beige': 0xF5F5DC, 'bisque': 0xFFE4C4, 'black': 0x000000, 'blanchedalmond': 0xFFEBCD, 'blue': 0x0000FF, 'blueviolet': 0x8A2BE2,
  10342. 'brown': 0xA52A2A, 'burlywood': 0xDEB887, 'cadetblue': 0x5F9EA0, 'chartreuse': 0x7FFF00, 'chocolate': 0xD2691E, 'coral': 0xFF7F50,
  10343. 'cornflowerblue': 0x6495ED, 'cornsilk': 0xFFF8DC, 'crimson': 0xDC143C, 'cyan': 0x00FFFF, 'darkblue': 0x00008B, 'darkcyan': 0x008B8B,
  10344. 'darkgoldenrod': 0xB8860B, 'darkgray': 0xA9A9A9, 'darkgreen': 0x006400, 'darkgrey': 0xA9A9A9, 'darkkhaki': 0xBDB76B, 'darkmagenta': 0x8B008B,
  10345. 'darkolivegreen': 0x556B2F, 'darkorange': 0xFF8C00, 'darkorchid': 0x9932CC, 'darkred': 0x8B0000, 'darksalmon': 0xE9967A, 'darkseagreen': 0x8FBC8F,
  10346. 'darkslateblue': 0x483D8B, 'darkslategray': 0x2F4F4F, 'darkslategrey': 0x2F4F4F, 'darkturquoise': 0x00CED1, 'darkviolet': 0x9400D3,
  10347. 'deeppink': 0xFF1493, 'deepskyblue': 0x00BFFF, 'dimgray': 0x696969, 'dimgrey': 0x696969, 'dodgerblue': 0x1E90FF, 'firebrick': 0xB22222,
  10348. 'floralwhite': 0xFFFAF0, 'forestgreen': 0x228B22, 'fuchsia': 0xFF00FF, 'gainsboro': 0xDCDCDC, 'ghostwhite': 0xF8F8FF, 'gold': 0xFFD700,
  10349. 'goldenrod': 0xDAA520, 'gray': 0x808080, 'green': 0x008000, 'greenyellow': 0xADFF2F, 'grey': 0x808080, 'honeydew': 0xF0FFF0, 'hotpink': 0xFF69B4,
  10350. 'indianred': 0xCD5C5C, 'indigo': 0x4B0082, 'ivory': 0xFFFFF0, 'khaki': 0xF0E68C, 'lavender': 0xE6E6FA, 'lavenderblush': 0xFFF0F5, 'lawngreen': 0x7CFC00,
  10351. 'lemonchiffon': 0xFFFACD, 'lightblue': 0xADD8E6, 'lightcoral': 0xF08080, 'lightcyan': 0xE0FFFF, 'lightgoldenrodyellow': 0xFAFAD2, 'lightgray': 0xD3D3D3,
  10352. 'lightgreen': 0x90EE90, 'lightgrey': 0xD3D3D3, 'lightpink': 0xFFB6C1, 'lightsalmon': 0xFFA07A, 'lightseagreen': 0x20B2AA, 'lightskyblue': 0x87CEFA,
  10353. 'lightslategray': 0x778899, 'lightslategrey': 0x778899, 'lightsteelblue': 0xB0C4DE, 'lightyellow': 0xFFFFE0, 'lime': 0x00FF00, 'limegreen': 0x32CD32,
  10354. 'linen': 0xFAF0E6, 'magenta': 0xFF00FF, 'maroon': 0x800000, 'mediumaquamarine': 0x66CDAA, 'mediumblue': 0x0000CD, 'mediumorchid': 0xBA55D3,
  10355. 'mediumpurple': 0x9370DB, 'mediumseagreen': 0x3CB371, 'mediumslateblue': 0x7B68EE, 'mediumspringgreen': 0x00FA9A, 'mediumturquoise': 0x48D1CC,
  10356. 'mediumvioletred': 0xC71585, 'midnightblue': 0x191970, 'mintcream': 0xF5FFFA, 'mistyrose': 0xFFE4E1, 'moccasin': 0xFFE4B5, 'navajowhite': 0xFFDEAD,
  10357. 'navy': 0x000080, 'oldlace': 0xFDF5E6, 'olive': 0x808000, 'olivedrab': 0x6B8E23, 'orange': 0xFFA500, 'orangered': 0xFF4500, 'orchid': 0xDA70D6,
  10358. 'palegoldenrod': 0xEEE8AA, 'palegreen': 0x98FB98, 'paleturquoise': 0xAFEEEE, 'palevioletred': 0xDB7093, 'papayawhip': 0xFFEFD5, 'peachpuff': 0xFFDAB9,
  10359. 'peru': 0xCD853F, 'pink': 0xFFC0CB, 'plum': 0xDDA0DD, 'powderblue': 0xB0E0E6, 'purple': 0x800080, 'rebeccapurple': 0x663399, 'red': 0xFF0000, 'rosybrown': 0xBC8F8F,
  10360. 'royalblue': 0x4169E1, 'saddlebrown': 0x8B4513, 'salmon': 0xFA8072, 'sandybrown': 0xF4A460, 'seagreen': 0x2E8B57, 'seashell': 0xFFF5EE,
  10361. 'sienna': 0xA0522D, 'silver': 0xC0C0C0, 'skyblue': 0x87CEEB, 'slateblue': 0x6A5ACD, 'slategray': 0x708090, 'slategrey': 0x708090, 'snow': 0xFFFAFA,
  10362. 'springgreen': 0x00FF7F, 'steelblue': 0x4682B4, 'tan': 0xD2B48C, 'teal': 0x008080, 'thistle': 0xD8BFD8, 'tomato': 0xFF6347, 'turquoise': 0x40E0D0,
  10363. 'violet': 0xEE82EE, 'wheat': 0xF5DEB3, 'white': 0xFFFFFF, 'whitesmoke': 0xF5F5F5, 'yellow': 0xFFFF00, 'yellowgreen': 0x9ACD32 };
  10364. var _hslA = { h: 0, s: 0, l: 0 };
  10365. var _hslB = { h: 0, s: 0, l: 0 };
  10366. function Color( r, g, b ) {
  10367. if ( g === undefined && b === undefined ) {
  10368. // r is THREE.Color, hex or string
  10369. return this.set( r );
  10370. }
  10371. return this.setRGB( r, g, b );
  10372. }
  10373. function hue2rgb( p, q, t ) {
  10374. if ( t < 0 ) { t += 1; }
  10375. if ( t > 1 ) { t -= 1; }
  10376. if ( t < 1 / 6 ) { return p + ( q - p ) * 6 * t; }
  10377. if ( t < 1 / 2 ) { return q; }
  10378. if ( t < 2 / 3 ) { return p + ( q - p ) * 6 * ( 2 / 3 - t ); }
  10379. return p;
  10380. }
  10381. function SRGBToLinear( c ) {
  10382. return ( c < 0.04045 ) ? c * 0.0773993808 : Math.pow( c * 0.9478672986 + 0.0521327014, 2.4 );
  10383. }
  10384. function LinearToSRGB( c ) {
  10385. return ( c < 0.0031308 ) ? c * 12.92 : 1.055 * ( Math.pow( c, 0.41666 ) ) - 0.055;
  10386. }
  10387. Object.assign( Color.prototype, {
  10388. isColor: true,
  10389. r: 1, g: 1, b: 1,
  10390. set: function ( value ) {
  10391. if ( value && value.isColor ) {
  10392. this.copy( value );
  10393. } else if ( typeof value === 'number' ) {
  10394. this.setHex( value );
  10395. } else if ( typeof value === 'string' ) {
  10396. this.setStyle( value );
  10397. }
  10398. return this;
  10399. },
  10400. setScalar: function ( scalar ) {
  10401. this.r = scalar;
  10402. this.g = scalar;
  10403. this.b = scalar;
  10404. return this;
  10405. },
  10406. setHex: function ( hex ) {
  10407. hex = Math.floor( hex );
  10408. this.r = ( hex >> 16 & 255 ) / 255;
  10409. this.g = ( hex >> 8 & 255 ) / 255;
  10410. this.b = ( hex & 255 ) / 255;
  10411. return this;
  10412. },
  10413. setRGB: function ( r, g, b ) {
  10414. this.r = r;
  10415. this.g = g;
  10416. this.b = b;
  10417. return this;
  10418. },
  10419. setHSL: function ( h, s, l ) {
  10420. // h,s,l ranges are in 0.0 - 1.0
  10421. h = MathUtils.euclideanModulo( h, 1 );
  10422. s = MathUtils.clamp( s, 0, 1 );
  10423. l = MathUtils.clamp( l, 0, 1 );
  10424. if ( s === 0 ) {
  10425. this.r = this.g = this.b = l;
  10426. } else {
  10427. var p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s );
  10428. var q = ( 2 * l ) - p;
  10429. this.r = hue2rgb( q, p, h + 1 / 3 );
  10430. this.g = hue2rgb( q, p, h );
  10431. this.b = hue2rgb( q, p, h - 1 / 3 );
  10432. }
  10433. return this;
  10434. },
  10435. setStyle: function ( style ) {
  10436. function handleAlpha( string ) {
  10437. if ( string === undefined ) { return; }
  10438. if ( parseFloat( string ) < 1 ) {
  10439. console.warn( 'THREE.Color: Alpha component of ' + style + ' will be ignored.' );
  10440. }
  10441. }
  10442. var m;
  10443. if ( m = /^((?:rgb|hsl)a?)\(\s*([^\)]*)\)/.exec( style ) ) {
  10444. // rgb / hsl
  10445. var color;
  10446. var name = m[ 1 ];
  10447. var components = m[ 2 ];
  10448. switch ( name ) {
  10449. case 'rgb':
  10450. case 'rgba':
  10451. if ( color = /^(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec( components ) ) {
  10452. // rgb(255,0,0) rgba(255,0,0,0.5)
  10453. this.r = Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255;
  10454. this.g = Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255;
  10455. this.b = Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255;
  10456. handleAlpha( color[ 5 ] );
  10457. return this;
  10458. }
  10459. if ( color = /^(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec( components ) ) {
  10460. // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
  10461. this.r = Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100;
  10462. this.g = Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100;
  10463. this.b = Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100;
  10464. handleAlpha( color[ 5 ] );
  10465. return this;
  10466. }
  10467. break;
  10468. case 'hsl':
  10469. case 'hsla':
  10470. if ( color = /^([0-9]*\.?[0-9]+)\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec( components ) ) {
  10471. // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
  10472. var h = parseFloat( color[ 1 ] ) / 360;
  10473. var s = parseInt( color[ 2 ], 10 ) / 100;
  10474. var l = parseInt( color[ 3 ], 10 ) / 100;
  10475. handleAlpha( color[ 5 ] );
  10476. return this.setHSL( h, s, l );
  10477. }
  10478. break;
  10479. }
  10480. } else if ( m = /^\#([A-Fa-f0-9]+)$/.exec( style ) ) {
  10481. // hex color
  10482. var hex = m[ 1 ];
  10483. var size = hex.length;
  10484. if ( size === 3 ) {
  10485. // #ff0
  10486. this.r = parseInt( hex.charAt( 0 ) + hex.charAt( 0 ), 16 ) / 255;
  10487. this.g = parseInt( hex.charAt( 1 ) + hex.charAt( 1 ), 16 ) / 255;
  10488. this.b = parseInt( hex.charAt( 2 ) + hex.charAt( 2 ), 16 ) / 255;
  10489. return this;
  10490. } else if ( size === 6 ) {
  10491. // #ff0000
  10492. this.r = parseInt( hex.charAt( 0 ) + hex.charAt( 1 ), 16 ) / 255;
  10493. this.g = parseInt( hex.charAt( 2 ) + hex.charAt( 3 ), 16 ) / 255;
  10494. this.b = parseInt( hex.charAt( 4 ) + hex.charAt( 5 ), 16 ) / 255;
  10495. return this;
  10496. }
  10497. }
  10498. if ( style && style.length > 0 ) {
  10499. return this.setColorName( style );
  10500. }
  10501. return this;
  10502. },
  10503. setColorName: function ( style ) {
  10504. // color keywords
  10505. var hex = _colorKeywords[ style ];
  10506. if ( hex !== undefined ) {
  10507. // red
  10508. this.setHex( hex );
  10509. } else {
  10510. // unknown color
  10511. console.warn( 'THREE.Color: Unknown color ' + style );
  10512. }
  10513. return this;
  10514. },
  10515. clone: function () {
  10516. return new this.constructor( this.r, this.g, this.b );
  10517. },
  10518. copy: function ( color ) {
  10519. this.r = color.r;
  10520. this.g = color.g;
  10521. this.b = color.b;
  10522. return this;
  10523. },
  10524. copyGammaToLinear: function ( color, gammaFactor ) {
  10525. if ( gammaFactor === undefined ) { gammaFactor = 2.0; }
  10526. this.r = Math.pow( color.r, gammaFactor );
  10527. this.g = Math.pow( color.g, gammaFactor );
  10528. this.b = Math.pow( color.b, gammaFactor );
  10529. return this;
  10530. },
  10531. copyLinearToGamma: function ( color, gammaFactor ) {
  10532. if ( gammaFactor === undefined ) { gammaFactor = 2.0; }
  10533. var safeInverse = ( gammaFactor > 0 ) ? ( 1.0 / gammaFactor ) : 1.0;
  10534. this.r = Math.pow( color.r, safeInverse );
  10535. this.g = Math.pow( color.g, safeInverse );
  10536. this.b = Math.pow( color.b, safeInverse );
  10537. return this;
  10538. },
  10539. convertGammaToLinear: function ( gammaFactor ) {
  10540. this.copyGammaToLinear( this, gammaFactor );
  10541. return this;
  10542. },
  10543. convertLinearToGamma: function ( gammaFactor ) {
  10544. this.copyLinearToGamma( this, gammaFactor );
  10545. return this;
  10546. },
  10547. copySRGBToLinear: function ( color ) {
  10548. this.r = SRGBToLinear( color.r );
  10549. this.g = SRGBToLinear( color.g );
  10550. this.b = SRGBToLinear( color.b );
  10551. return this;
  10552. },
  10553. copyLinearToSRGB: function ( color ) {
  10554. this.r = LinearToSRGB( color.r );
  10555. this.g = LinearToSRGB( color.g );
  10556. this.b = LinearToSRGB( color.b );
  10557. return this;
  10558. },
  10559. convertSRGBToLinear: function () {
  10560. this.copySRGBToLinear( this );
  10561. return this;
  10562. },
  10563. convertLinearToSRGB: function () {
  10564. this.copyLinearToSRGB( this );
  10565. return this;
  10566. },
  10567. getHex: function () {
  10568. return ( this.r * 255 ) << 16 ^ ( this.g * 255 ) << 8 ^ ( this.b * 255 ) << 0;
  10569. },
  10570. getHexString: function () {
  10571. return ( '000000' + this.getHex().toString( 16 ) ).slice( - 6 );
  10572. },
  10573. getHSL: function ( target ) {
  10574. // h,s,l ranges are in 0.0 - 1.0
  10575. if ( target === undefined ) {
  10576. console.warn( 'THREE.Color: .getHSL() target is now required' );
  10577. target = { h: 0, s: 0, l: 0 };
  10578. }
  10579. var r = this.r, g = this.g, b = this.b;
  10580. var max = Math.max( r, g, b );
  10581. var min = Math.min( r, g, b );
  10582. var hue, saturation;
  10583. var lightness = ( min + max ) / 2.0;
  10584. if ( min === max ) {
  10585. hue = 0;
  10586. saturation = 0;
  10587. } else {
  10588. var delta = max - min;
  10589. saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min );
  10590. switch ( max ) {
  10591. case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break;
  10592. case g: hue = ( b - r ) / delta + 2; break;
  10593. case b: hue = ( r - g ) / delta + 4; break;
  10594. }
  10595. hue /= 6;
  10596. }
  10597. target.h = hue;
  10598. target.s = saturation;
  10599. target.l = lightness;
  10600. return target;
  10601. },
  10602. getStyle: function () {
  10603. return 'rgb(' + ( ( this.r * 255 ) | 0 ) + ',' + ( ( this.g * 255 ) | 0 ) + ',' + ( ( this.b * 255 ) | 0 ) + ')';
  10604. },
  10605. offsetHSL: function ( h, s, l ) {
  10606. this.getHSL( _hslA );
  10607. _hslA.h += h; _hslA.s += s; _hslA.l += l;
  10608. this.setHSL( _hslA.h, _hslA.s, _hslA.l );
  10609. return this;
  10610. },
  10611. add: function ( color ) {
  10612. this.r += color.r;
  10613. this.g += color.g;
  10614. this.b += color.b;
  10615. return this;
  10616. },
  10617. addColors: function ( color1, color2 ) {
  10618. this.r = color1.r + color2.r;
  10619. this.g = color1.g + color2.g;
  10620. this.b = color1.b + color2.b;
  10621. return this;
  10622. },
  10623. addScalar: function ( s ) {
  10624. this.r += s;
  10625. this.g += s;
  10626. this.b += s;
  10627. return this;
  10628. },
  10629. sub: function ( color ) {
  10630. this.r = Math.max( 0, this.r - color.r );
  10631. this.g = Math.max( 0, this.g - color.g );
  10632. this.b = Math.max( 0, this.b - color.b );
  10633. return this;
  10634. },
  10635. multiply: function ( color ) {
  10636. this.r *= color.r;
  10637. this.g *= color.g;
  10638. this.b *= color.b;
  10639. return this;
  10640. },
  10641. multiplyScalar: function ( s ) {
  10642. this.r *= s;
  10643. this.g *= s;
  10644. this.b *= s;
  10645. return this;
  10646. },
  10647. lerp: function ( color, alpha ) {
  10648. this.r += ( color.r - this.r ) * alpha;
  10649. this.g += ( color.g - this.g ) * alpha;
  10650. this.b += ( color.b - this.b ) * alpha;
  10651. return this;
  10652. },
  10653. lerpHSL: function ( color, alpha ) {
  10654. this.getHSL( _hslA );
  10655. color.getHSL( _hslB );
  10656. var h = MathUtils.lerp( _hslA.h, _hslB.h, alpha );
  10657. var s = MathUtils.lerp( _hslA.s, _hslB.s, alpha );
  10658. var l = MathUtils.lerp( _hslA.l, _hslB.l, alpha );
  10659. this.setHSL( h, s, l );
  10660. return this;
  10661. },
  10662. equals: function ( c ) {
  10663. return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b );
  10664. },
  10665. fromArray: function ( array, offset ) {
  10666. if ( offset === undefined ) { offset = 0; }
  10667. this.r = array[ offset ];
  10668. this.g = array[ offset + 1 ];
  10669. this.b = array[ offset + 2 ];
  10670. return this;
  10671. },
  10672. toArray: function ( array, offset ) {
  10673. if ( array === undefined ) { array = []; }
  10674. if ( offset === undefined ) { offset = 0; }
  10675. array[ offset ] = this.r;
  10676. array[ offset + 1 ] = this.g;
  10677. array[ offset + 2 ] = this.b;
  10678. return array;
  10679. },
  10680. toJSON: function () {
  10681. return this.getHex();
  10682. }
  10683. } );
  10684. Color.NAMES = _colorKeywords;
  10685. /**
  10686. * @author mrdoob / http://mrdoob.com/
  10687. * @author alteredq / http://alteredqualia.com/
  10688. */
  10689. function Face3( a, b, c, normal, color, materialIndex ) {
  10690. this.a = a;
  10691. this.b = b;
  10692. this.c = c;
  10693. this.normal = ( normal && normal.isVector3 ) ? normal : new Vector3();
  10694. this.vertexNormals = Array.isArray( normal ) ? normal : [];
  10695. this.color = ( color && color.isColor ) ? color : new Color();
  10696. this.vertexColors = Array.isArray( color ) ? color : [];
  10697. this.materialIndex = materialIndex !== undefined ? materialIndex : 0;
  10698. }
  10699. Object.assign( Face3.prototype, {
  10700. clone: function () {
  10701. return new this.constructor().copy( this );
  10702. },
  10703. copy: function ( source ) {
  10704. this.a = source.a;
  10705. this.b = source.b;
  10706. this.c = source.c;
  10707. this.normal.copy( source.normal );
  10708. this.color.copy( source.color );
  10709. this.materialIndex = source.materialIndex;
  10710. for ( var i = 0, il = source.vertexNormals.length; i < il; i ++ ) {
  10711. this.vertexNormals[ i ] = source.vertexNormals[ i ].clone();
  10712. }
  10713. for ( var i = 0, il = source.vertexColors.length; i < il; i ++ ) {
  10714. this.vertexColors[ i ] = source.vertexColors[ i ].clone();
  10715. }
  10716. return this;
  10717. }
  10718. } );
  10719. /**
  10720. * @author mrdoob / http://mrdoob.com/
  10721. * @author alteredq / http://alteredqualia.com/
  10722. */
  10723. var materialId = 0;
  10724. function Material() {
  10725. Object.defineProperty( this, 'id', { value: materialId ++ } );
  10726. this.uuid = MathUtils.generateUUID();
  10727. this.name = '';
  10728. this.type = 'Material';
  10729. this.fog = true;
  10730. this.blending = NormalBlending;
  10731. this.side = FrontSide;
  10732. this.flatShading = false;
  10733. this.vertexColors = false;
  10734. this.opacity = 1;
  10735. this.transparent = false;
  10736. this.blendSrc = SrcAlphaFactor;
  10737. this.blendDst = OneMinusSrcAlphaFactor;
  10738. this.blendEquation = AddEquation;
  10739. this.blendSrcAlpha = null;
  10740. this.blendDstAlpha = null;
  10741. this.blendEquationAlpha = null;
  10742. this.depthFunc = LessEqualDepth;
  10743. this.depthTest = true;
  10744. this.depthWrite = true;
  10745. this.stencilWriteMask = 0xff;
  10746. this.stencilFunc = AlwaysStencilFunc;
  10747. this.stencilRef = 0;
  10748. this.stencilFuncMask = 0xff;
  10749. this.stencilFail = KeepStencilOp;
  10750. this.stencilZFail = KeepStencilOp;
  10751. this.stencilZPass = KeepStencilOp;
  10752. this.stencilWrite = false;
  10753. this.clippingPlanes = null;
  10754. this.clipIntersection = false;
  10755. this.clipShadows = false;
  10756. this.shadowSide = null;
  10757. this.colorWrite = true;
  10758. this.precision = null; // override the renderer's default precision for this material
  10759. this.polygonOffset = false;
  10760. this.polygonOffsetFactor = 0;
  10761. this.polygonOffsetUnits = 0;
  10762. this.dithering = false;
  10763. this.alphaTest = 0;
  10764. this.premultipliedAlpha = false;
  10765. this.visible = true;
  10766. this.toneMapped = true;
  10767. this.userData = {};
  10768. this.version = 0;
  10769. }
  10770. Material.prototype = Object.assign( Object.create( EventDispatcher.prototype ), {
  10771. constructor: Material,
  10772. isMaterial: true,
  10773. onBeforeCompile: function () {},
  10774. setValues: function ( values ) {
  10775. if ( values === undefined ) { return; }
  10776. for ( var key in values ) {
  10777. var newValue = values[ key ];
  10778. if ( newValue === undefined ) {
  10779. console.warn( "THREE.Material: '" + key + "' parameter is undefined." );
  10780. continue;
  10781. }
  10782. // for backward compatability if shading is set in the constructor
  10783. if ( key === 'shading' ) {
  10784. console.warn( 'THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.' );
  10785. this.flatShading = ( newValue === FlatShading ) ? true : false;
  10786. continue;
  10787. }
  10788. var currentValue = this[ key ];
  10789. if ( currentValue === undefined ) {
  10790. console.warn( "THREE." + this.type + ": '" + key + "' is not a property of this material." );
  10791. continue;
  10792. }
  10793. if ( currentValue && currentValue.isColor ) {
  10794. currentValue.set( newValue );
  10795. } else if ( ( currentValue && currentValue.isVector3 ) && ( newValue && newValue.isVector3 ) ) {
  10796. currentValue.copy( newValue );
  10797. } else {
  10798. this[ key ] = newValue;
  10799. }
  10800. }
  10801. },
  10802. toJSON: function ( meta ) {
  10803. var isRoot = ( meta === undefined || typeof meta === 'string' );
  10804. if ( isRoot ) {
  10805. meta = {
  10806. textures: {},
  10807. images: {}
  10808. };
  10809. }
  10810. var data = {
  10811. metadata: {
  10812. version: 4.5,
  10813. type: 'Material',
  10814. generator: 'Material.toJSON'
  10815. }
  10816. };
  10817. // standard Material serialization
  10818. data.uuid = this.uuid;
  10819. data.type = this.type;
  10820. if ( this.name !== '' ) { data.name = this.name; }
  10821. if ( this.color && this.color.isColor ) { data.color = this.color.getHex(); }
  10822. if ( this.roughness !== undefined ) { data.roughness = this.roughness; }
  10823. if ( this.metalness !== undefined ) { data.metalness = this.metalness; }
  10824. if ( this.sheen && this.sheen.isColor ) { data.sheen = this.sheen.getHex(); }
  10825. if ( this.emissive && this.emissive.isColor ) { data.emissive = this.emissive.getHex(); }
  10826. if ( this.emissiveIntensity && this.emissiveIntensity !== 1 ) { data.emissiveIntensity = this.emissiveIntensity; }
  10827. if ( this.specular && this.specular.isColor ) { data.specular = this.specular.getHex(); }
  10828. if ( this.shininess !== undefined ) { data.shininess = this.shininess; }
  10829. if ( this.clearcoat !== undefined ) { data.clearcoat = this.clearcoat; }
  10830. if ( this.clearcoatRoughness !== undefined ) { data.clearcoatRoughness = this.clearcoatRoughness; }
  10831. if ( this.clearcoatMap && this.clearcoatMap.isTexture ) {
  10832. data.clearcoatMap = this.clearcoatMap.toJSON( meta ).uuid;
  10833. }
  10834. if ( this.clearcoatRoughnessMap && this.clearcoatRoughnessMap.isTexture ) {
  10835. data.clearcoatRoughnessMap = this.clearcoatRoughnessMap.toJSON( meta ).uuid;
  10836. }
  10837. if ( this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture ) {
  10838. data.clearcoatNormalMap = this.clearcoatNormalMap.toJSON( meta ).uuid;
  10839. data.clearcoatNormalScale = this.clearcoatNormalScale.toArray();
  10840. }
  10841. if ( this.map && this.map.isTexture ) { data.map = this.map.toJSON( meta ).uuid; }
  10842. if ( this.matcap && this.matcap.isTexture ) { data.matcap = this.matcap.toJSON( meta ).uuid; }
  10843. if ( this.alphaMap && this.alphaMap.isTexture ) { data.alphaMap = this.alphaMap.toJSON( meta ).uuid; }
  10844. if ( this.lightMap && this.lightMap.isTexture ) { data.lightMap = this.lightMap.toJSON( meta ).uuid; }
  10845. if ( this.aoMap && this.aoMap.isTexture ) {
  10846. data.aoMap = this.aoMap.toJSON( meta ).uuid;
  10847. data.aoMapIntensity = this.aoMapIntensity;
  10848. }
  10849. if ( this.bumpMap && this.bumpMap.isTexture ) {
  10850. data.bumpMap = this.bumpMap.toJSON( meta ).uuid;
  10851. data.bumpScale = this.bumpScale;
  10852. }
  10853. if ( this.normalMap && this.normalMap.isTexture ) {
  10854. data.normalMap = this.normalMap.toJSON( meta ).uuid;
  10855. data.normalMapType = this.normalMapType;
  10856. data.normalScale = this.normalScale.toArray();
  10857. }
  10858. if ( this.displacementMap && this.displacementMap.isTexture ) {
  10859. data.displacementMap = this.displacementMap.toJSON( meta ).uuid;
  10860. data.displacementScale = this.displacementScale;
  10861. data.displacementBias = this.displacementBias;
  10862. }
  10863. if ( this.roughnessMap && this.roughnessMap.isTexture ) { data.roughnessMap = this.roughnessMap.toJSON( meta ).uuid; }
  10864. if ( this.metalnessMap && this.metalnessMap.isTexture ) { data.metalnessMap = this.metalnessMap.toJSON( meta ).uuid; }
  10865. if ( this.emissiveMap && this.emissiveMap.isTexture ) { data.emissiveMap = this.emissiveMap.toJSON( meta ).uuid; }
  10866. if ( this.specularMap && this.specularMap.isTexture ) { data.specularMap = this.specularMap.toJSON( meta ).uuid; }
  10867. if ( this.envMap && this.envMap.isTexture ) {
  10868. data.envMap = this.envMap.toJSON( meta ).uuid;
  10869. data.reflectivity = this.reflectivity; // Scale behind envMap
  10870. data.refractionRatio = this.refractionRatio;
  10871. if ( this.combine !== undefined ) { data.combine = this.combine; }
  10872. if ( this.envMapIntensity !== undefined ) { data.envMapIntensity = this.envMapIntensity; }
  10873. }
  10874. if ( this.gradientMap && this.gradientMap.isTexture ) {
  10875. data.gradientMap = this.gradientMap.toJSON( meta ).uuid;
  10876. }
  10877. if ( this.size !== undefined ) { data.size = this.size; }
  10878. if ( this.sizeAttenuation !== undefined ) { data.sizeAttenuation = this.sizeAttenuation; }
  10879. if ( this.blending !== NormalBlending ) { data.blending = this.blending; }
  10880. if ( this.flatShading === true ) { data.flatShading = this.flatShading; }
  10881. if ( this.side !== FrontSide ) { data.side = this.side; }
  10882. if ( this.vertexColors ) { data.vertexColors = true; }
  10883. if ( this.opacity < 1 ) { data.opacity = this.opacity; }
  10884. if ( this.transparent === true ) { data.transparent = this.transparent; }
  10885. data.depthFunc = this.depthFunc;
  10886. data.depthTest = this.depthTest;
  10887. data.depthWrite = this.depthWrite;
  10888. data.stencilWrite = this.stencilWrite;
  10889. data.stencilWriteMask = this.stencilWriteMask;
  10890. data.stencilFunc = this.stencilFunc;
  10891. data.stencilRef = this.stencilRef;
  10892. data.stencilFuncMask = this.stencilFuncMask;
  10893. data.stencilFail = this.stencilFail;
  10894. data.stencilZFail = this.stencilZFail;
  10895. data.stencilZPass = this.stencilZPass;
  10896. // rotation (SpriteMaterial)
  10897. if ( this.rotation && this.rotation !== 0 ) { data.rotation = this.rotation; }
  10898. if ( this.polygonOffset === true ) { data.polygonOffset = true; }
  10899. if ( this.polygonOffsetFactor !== 0 ) { data.polygonOffsetFactor = this.polygonOffsetFactor; }
  10900. if ( this.polygonOffsetUnits !== 0 ) { data.polygonOffsetUnits = this.polygonOffsetUnits; }
  10901. if ( this.linewidth && this.linewidth !== 1 ) { data.linewidth = this.linewidth; }
  10902. if ( this.dashSize !== undefined ) { data.dashSize = this.dashSize; }
  10903. if ( this.gapSize !== undefined ) { data.gapSize = this.gapSize; }
  10904. if ( this.scale !== undefined ) { data.scale = this.scale; }
  10905. if ( this.dithering === true ) { data.dithering = true; }
  10906. if ( this.alphaTest > 0 ) { data.alphaTest = this.alphaTest; }
  10907. if ( this.premultipliedAlpha === true ) { data.premultipliedAlpha = this.premultipliedAlpha; }
  10908. if ( this.wireframe === true ) { data.wireframe = this.wireframe; }
  10909. if ( this.wireframeLinewidth > 1 ) { data.wireframeLinewidth = this.wireframeLinewidth; }
  10910. if ( this.wireframeLinecap !== 'round' ) { data.wireframeLinecap = this.wireframeLinecap; }
  10911. if ( this.wireframeLinejoin !== 'round' ) { data.wireframeLinejoin = this.wireframeLinejoin; }
  10912. if ( this.morphTargets === true ) { data.morphTargets = true; }
  10913. if ( this.morphNormals === true ) { data.morphNormals = true; }
  10914. if ( this.skinning === true ) { data.skinning = true; }
  10915. if ( this.visible === false ) { data.visible = false; }
  10916. if ( this.toneMapped === false ) { data.toneMapped = false; }
  10917. if ( JSON.stringify( this.userData ) !== '{}' ) { data.userData = this.userData; }
  10918. // TODO: Copied from Object3D.toJSON
  10919. function extractFromCache( cache ) {
  10920. var values = [];
  10921. for ( var key in cache ) {
  10922. var data = cache[ key ];
  10923. delete data.metadata;
  10924. values.push( data );
  10925. }
  10926. return values;
  10927. }
  10928. if ( isRoot ) {
  10929. var textures = extractFromCache( meta.textures );
  10930. var images = extractFromCache( meta.images );
  10931. if ( textures.length > 0 ) { data.textures = textures; }
  10932. if ( images.length > 0 ) { data.images = images; }
  10933. }
  10934. return data;
  10935. },
  10936. clone: function () {
  10937. return new this.constructor().copy( this );
  10938. },
  10939. copy: function ( source ) {
  10940. this.name = source.name;
  10941. this.fog = source.fog;
  10942. this.blending = source.blending;
  10943. this.side = source.side;
  10944. this.flatShading = source.flatShading;
  10945. this.vertexColors = source.vertexColors;
  10946. this.opacity = source.opacity;
  10947. this.transparent = source.transparent;
  10948. this.blendSrc = source.blendSrc;
  10949. this.blendDst = source.blendDst;
  10950. this.blendEquation = source.blendEquation;
  10951. this.blendSrcAlpha = source.blendSrcAlpha;
  10952. this.blendDstAlpha = source.blendDstAlpha;
  10953. this.blendEquationAlpha = source.blendEquationAlpha;
  10954. this.depthFunc = source.depthFunc;
  10955. this.depthTest = source.depthTest;
  10956. this.depthWrite = source.depthWrite;
  10957. this.stencilWriteMask = source.stencilWriteMask;
  10958. this.stencilFunc = source.stencilFunc;
  10959. this.stencilRef = source.stencilRef;
  10960. this.stencilFuncMask = source.stencilFuncMask;
  10961. this.stencilFail = source.stencilFail;
  10962. this.stencilZFail = source.stencilZFail;
  10963. this.stencilZPass = source.stencilZPass;
  10964. this.stencilWrite = source.stencilWrite;
  10965. var srcPlanes = source.clippingPlanes,
  10966. dstPlanes = null;
  10967. if ( srcPlanes !== null ) {
  10968. var n = srcPlanes.length;
  10969. dstPlanes = new Array( n );
  10970. for ( var i = 0; i !== n; ++ i )
  10971. { dstPlanes[ i ] = srcPlanes[ i ].clone(); }
  10972. }
  10973. this.clippingPlanes = dstPlanes;
  10974. this.clipIntersection = source.clipIntersection;
  10975. this.clipShadows = source.clipShadows;
  10976. this.shadowSide = source.shadowSide;
  10977. this.colorWrite = source.colorWrite;
  10978. this.precision = source.precision;
  10979. this.polygonOffset = source.polygonOffset;
  10980. this.polygonOffsetFactor = source.polygonOffsetFactor;
  10981. this.polygonOffsetUnits = source.polygonOffsetUnits;
  10982. this.dithering = source.dithering;
  10983. this.alphaTest = source.alphaTest;
  10984. this.premultipliedAlpha = source.premultipliedAlpha;
  10985. this.visible = source.visible;
  10986. this.toneMapped = source.toneMapped;
  10987. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  10988. return this;
  10989. },
  10990. dispose: function () {
  10991. this.dispatchEvent( { type: 'dispose' } );
  10992. }
  10993. } );
  10994. Object.defineProperty( Material.prototype, 'needsUpdate', {
  10995. set: function ( value ) {
  10996. if ( value === true ) { this.version ++; }
  10997. }
  10998. } );
  10999. /**
  11000. * @author mrdoob / http://mrdoob.com/
  11001. * @author alteredq / http://alteredqualia.com/
  11002. *
  11003. * parameters = {
  11004. * color: <hex>,
  11005. * opacity: <float>,
  11006. * map: new THREE.Texture( <Image> ),
  11007. *
  11008. * lightMap: new THREE.Texture( <Image> ),
  11009. * lightMapIntensity: <float>
  11010. *
  11011. * aoMap: new THREE.Texture( <Image> ),
  11012. * aoMapIntensity: <float>
  11013. *
  11014. * specularMap: new THREE.Texture( <Image> ),
  11015. *
  11016. * alphaMap: new THREE.Texture( <Image> ),
  11017. *
  11018. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  11019. * combine: THREE.Multiply,
  11020. * reflectivity: <float>,
  11021. * refractionRatio: <float>,
  11022. *
  11023. * depthTest: <bool>,
  11024. * depthWrite: <bool>,
  11025. *
  11026. * wireframe: <boolean>,
  11027. * wireframeLinewidth: <float>,
  11028. *
  11029. * skinning: <bool>,
  11030. * morphTargets: <bool>
  11031. * }
  11032. */
  11033. function MeshBasicMaterial( parameters ) {
  11034. Material.call( this );
  11035. this.type = 'MeshBasicMaterial';
  11036. this.color = new Color( 0xffffff ); // emissive
  11037. this.map = null;
  11038. this.lightMap = null;
  11039. this.lightMapIntensity = 1.0;
  11040. this.aoMap = null;
  11041. this.aoMapIntensity = 1.0;
  11042. this.specularMap = null;
  11043. this.alphaMap = null;
  11044. this.envMap = null;
  11045. this.combine = MultiplyOperation;
  11046. this.reflectivity = 1;
  11047. this.refractionRatio = 0.98;
  11048. this.wireframe = false;
  11049. this.wireframeLinewidth = 1;
  11050. this.wireframeLinecap = 'round';
  11051. this.wireframeLinejoin = 'round';
  11052. this.skinning = false;
  11053. this.morphTargets = false;
  11054. this.setValues( parameters );
  11055. }
  11056. MeshBasicMaterial.prototype = Object.create( Material.prototype );
  11057. MeshBasicMaterial.prototype.constructor = MeshBasicMaterial;
  11058. MeshBasicMaterial.prototype.isMeshBasicMaterial = true;
  11059. MeshBasicMaterial.prototype.copy = function ( source ) {
  11060. Material.prototype.copy.call( this, source );
  11061. this.color.copy( source.color );
  11062. this.map = source.map;
  11063. this.lightMap = source.lightMap;
  11064. this.lightMapIntensity = source.lightMapIntensity;
  11065. this.aoMap = source.aoMap;
  11066. this.aoMapIntensity = source.aoMapIntensity;
  11067. this.specularMap = source.specularMap;
  11068. this.alphaMap = source.alphaMap;
  11069. this.envMap = source.envMap;
  11070. this.combine = source.combine;
  11071. this.reflectivity = source.reflectivity;
  11072. this.refractionRatio = source.refractionRatio;
  11073. this.wireframe = source.wireframe;
  11074. this.wireframeLinewidth = source.wireframeLinewidth;
  11075. this.wireframeLinecap = source.wireframeLinecap;
  11076. this.wireframeLinejoin = source.wireframeLinejoin;
  11077. this.skinning = source.skinning;
  11078. this.morphTargets = source.morphTargets;
  11079. return this;
  11080. };
  11081. /**
  11082. * @author mrdoob / http://mrdoob.com/
  11083. */
  11084. var _vector$3 = new Vector3();
  11085. function BufferAttribute( array, itemSize, normalized ) {
  11086. if ( Array.isArray( array ) ) {
  11087. throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );
  11088. }
  11089. this.name = '';
  11090. this.array = array;
  11091. this.itemSize = itemSize;
  11092. this.count = array !== undefined ? array.length / itemSize : 0;
  11093. this.normalized = normalized === true;
  11094. this.usage = StaticDrawUsage;
  11095. this.updateRange = { offset: 0, count: - 1 };
  11096. this.version = 0;
  11097. }
  11098. Object.defineProperty( BufferAttribute.prototype, 'needsUpdate', {
  11099. set: function ( value ) {
  11100. if ( value === true ) { this.version ++; }
  11101. }
  11102. } );
  11103. Object.assign( BufferAttribute.prototype, {
  11104. isBufferAttribute: true,
  11105. onUploadCallback: function () {},
  11106. setUsage: function ( value ) {
  11107. this.usage = value;
  11108. return this;
  11109. },
  11110. copy: function ( source ) {
  11111. this.name = source.name;
  11112. this.array = new source.array.constructor( source.array );
  11113. this.itemSize = source.itemSize;
  11114. this.count = source.count;
  11115. this.normalized = source.normalized;
  11116. this.usage = source.usage;
  11117. return this;
  11118. },
  11119. copyAt: function ( index1, attribute, index2 ) {
  11120. index1 *= this.itemSize;
  11121. index2 *= attribute.itemSize;
  11122. for ( var i = 0, l = this.itemSize; i < l; i ++ ) {
  11123. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  11124. }
  11125. return this;
  11126. },
  11127. copyArray: function ( array ) {
  11128. this.array.set( array );
  11129. return this;
  11130. },
  11131. copyColorsArray: function ( colors ) {
  11132. var array = this.array, offset = 0;
  11133. for ( var i = 0, l = colors.length; i < l; i ++ ) {
  11134. var color = colors[ i ];
  11135. if ( color === undefined ) {
  11136. console.warn( 'THREE.BufferAttribute.copyColorsArray(): color is undefined', i );
  11137. color = new Color();
  11138. }
  11139. array[ offset ++ ] = color.r;
  11140. array[ offset ++ ] = color.g;
  11141. array[ offset ++ ] = color.b;
  11142. }
  11143. return this;
  11144. },
  11145. copyVector2sArray: function ( vectors ) {
  11146. var array = this.array, offset = 0;
  11147. for ( var i = 0, l = vectors.length; i < l; i ++ ) {
  11148. var vector = vectors[ i ];
  11149. if ( vector === undefined ) {
  11150. console.warn( 'THREE.BufferAttribute.copyVector2sArray(): vector is undefined', i );
  11151. vector = new Vector2();
  11152. }
  11153. array[ offset ++ ] = vector.x;
  11154. array[ offset ++ ] = vector.y;
  11155. }
  11156. return this;
  11157. },
  11158. copyVector3sArray: function ( vectors ) {
  11159. var array = this.array, offset = 0;
  11160. for ( var i = 0, l = vectors.length; i < l; i ++ ) {
  11161. var vector = vectors[ i ];
  11162. if ( vector === undefined ) {
  11163. console.warn( 'THREE.BufferAttribute.copyVector3sArray(): vector is undefined', i );
  11164. vector = new Vector3();
  11165. }
  11166. array[ offset ++ ] = vector.x;
  11167. array[ offset ++ ] = vector.y;
  11168. array[ offset ++ ] = vector.z;
  11169. }
  11170. return this;
  11171. },
  11172. copyVector4sArray: function ( vectors ) {
  11173. var array = this.array, offset = 0;
  11174. for ( var i = 0, l = vectors.length; i < l; i ++ ) {
  11175. var vector = vectors[ i ];
  11176. if ( vector === undefined ) {
  11177. console.warn( 'THREE.BufferAttribute.copyVector4sArray(): vector is undefined', i );
  11178. vector = new Vector4();
  11179. }
  11180. array[ offset ++ ] = vector.x;
  11181. array[ offset ++ ] = vector.y;
  11182. array[ offset ++ ] = vector.z;
  11183. array[ offset ++ ] = vector.w;
  11184. }
  11185. return this;
  11186. },
  11187. applyMatrix3: function ( m ) {
  11188. for ( var i = 0, l = this.count; i < l; i ++ ) {
  11189. _vector$3.x = this.getX( i );
  11190. _vector$3.y = this.getY( i );
  11191. _vector$3.z = this.getZ( i );
  11192. _vector$3.applyMatrix3( m );
  11193. this.setXYZ( i, _vector$3.x, _vector$3.y, _vector$3.z );
  11194. }
  11195. return this;
  11196. },
  11197. applyMatrix4: function ( m ) {
  11198. for ( var i = 0, l = this.count; i < l; i ++ ) {
  11199. _vector$3.x = this.getX( i );
  11200. _vector$3.y = this.getY( i );
  11201. _vector$3.z = this.getZ( i );
  11202. _vector$3.applyMatrix4( m );
  11203. this.setXYZ( i, _vector$3.x, _vector$3.y, _vector$3.z );
  11204. }
  11205. return this;
  11206. },
  11207. applyNormalMatrix: function ( m ) {
  11208. for ( var i = 0, l = this.count; i < l; i ++ ) {
  11209. _vector$3.x = this.getX( i );
  11210. _vector$3.y = this.getY( i );
  11211. _vector$3.z = this.getZ( i );
  11212. _vector$3.applyNormalMatrix( m );
  11213. this.setXYZ( i, _vector$3.x, _vector$3.y, _vector$3.z );
  11214. }
  11215. return this;
  11216. },
  11217. transformDirection: function ( m ) {
  11218. for ( var i = 0, l = this.count; i < l; i ++ ) {
  11219. _vector$3.x = this.getX( i );
  11220. _vector$3.y = this.getY( i );
  11221. _vector$3.z = this.getZ( i );
  11222. _vector$3.transformDirection( m );
  11223. this.setXYZ( i, _vector$3.x, _vector$3.y, _vector$3.z );
  11224. }
  11225. return this;
  11226. },
  11227. set: function ( value, offset ) {
  11228. if ( offset === undefined ) { offset = 0; }
  11229. this.array.set( value, offset );
  11230. return this;
  11231. },
  11232. getX: function ( index ) {
  11233. return this.array[ index * this.itemSize ];
  11234. },
  11235. setX: function ( index, x ) {
  11236. this.array[ index * this.itemSize ] = x;
  11237. return this;
  11238. },
  11239. getY: function ( index ) {
  11240. return this.array[ index * this.itemSize + 1 ];
  11241. },
  11242. setY: function ( index, y ) {
  11243. this.array[ index * this.itemSize + 1 ] = y;
  11244. return this;
  11245. },
  11246. getZ: function ( index ) {
  11247. return this.array[ index * this.itemSize + 2 ];
  11248. },
  11249. setZ: function ( index, z ) {
  11250. this.array[ index * this.itemSize + 2 ] = z;
  11251. return this;
  11252. },
  11253. getW: function ( index ) {
  11254. return this.array[ index * this.itemSize + 3 ];
  11255. },
  11256. setW: function ( index, w ) {
  11257. this.array[ index * this.itemSize + 3 ] = w;
  11258. return this;
  11259. },
  11260. setXY: function ( index, x, y ) {
  11261. index *= this.itemSize;
  11262. this.array[ index + 0 ] = x;
  11263. this.array[ index + 1 ] = y;
  11264. return this;
  11265. },
  11266. setXYZ: function ( index, x, y, z ) {
  11267. index *= this.itemSize;
  11268. this.array[ index + 0 ] = x;
  11269. this.array[ index + 1 ] = y;
  11270. this.array[ index + 2 ] = z;
  11271. return this;
  11272. },
  11273. setXYZW: function ( index, x, y, z, w ) {
  11274. index *= this.itemSize;
  11275. this.array[ index + 0 ] = x;
  11276. this.array[ index + 1 ] = y;
  11277. this.array[ index + 2 ] = z;
  11278. this.array[ index + 3 ] = w;
  11279. return this;
  11280. },
  11281. onUpload: function ( callback ) {
  11282. this.onUploadCallback = callback;
  11283. return this;
  11284. },
  11285. clone: function () {
  11286. return new this.constructor( this.array, this.itemSize ).copy( this );
  11287. },
  11288. toJSON: function () {
  11289. return {
  11290. itemSize: this.itemSize,
  11291. type: this.array.constructor.name,
  11292. array: Array.prototype.slice.call( this.array ),
  11293. normalized: this.normalized
  11294. };
  11295. }
  11296. } );
  11297. //
  11298. function Int8BufferAttribute( array, itemSize, normalized ) {
  11299. BufferAttribute.call( this, new Int8Array( array ), itemSize, normalized );
  11300. }
  11301. Int8BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  11302. Int8BufferAttribute.prototype.constructor = Int8BufferAttribute;
  11303. function Uint8BufferAttribute( array, itemSize, normalized ) {
  11304. BufferAttribute.call( this, new Uint8Array( array ), itemSize, normalized );
  11305. }
  11306. Uint8BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  11307. Uint8BufferAttribute.prototype.constructor = Uint8BufferAttribute;
  11308. function Uint8ClampedBufferAttribute( array, itemSize, normalized ) {
  11309. BufferAttribute.call( this, new Uint8ClampedArray( array ), itemSize, normalized );
  11310. }
  11311. Uint8ClampedBufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  11312. Uint8ClampedBufferAttribute.prototype.constructor = Uint8ClampedBufferAttribute;
  11313. function Int16BufferAttribute( array, itemSize, normalized ) {
  11314. BufferAttribute.call( this, new Int16Array( array ), itemSize, normalized );
  11315. }
  11316. Int16BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  11317. Int16BufferAttribute.prototype.constructor = Int16BufferAttribute;
  11318. function Uint16BufferAttribute( array, itemSize, normalized ) {
  11319. BufferAttribute.call( this, new Uint16Array( array ), itemSize, normalized );
  11320. }
  11321. Uint16BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  11322. Uint16BufferAttribute.prototype.constructor = Uint16BufferAttribute;
  11323. function Int32BufferAttribute( array, itemSize, normalized ) {
  11324. BufferAttribute.call( this, new Int32Array( array ), itemSize, normalized );
  11325. }
  11326. Int32BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  11327. Int32BufferAttribute.prototype.constructor = Int32BufferAttribute;
  11328. function Uint32BufferAttribute( array, itemSize, normalized ) {
  11329. BufferAttribute.call( this, new Uint32Array( array ), itemSize, normalized );
  11330. }
  11331. Uint32BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  11332. Uint32BufferAttribute.prototype.constructor = Uint32BufferAttribute;
  11333. function Float32BufferAttribute( array, itemSize, normalized ) {
  11334. BufferAttribute.call( this, new Float32Array( array ), itemSize, normalized );
  11335. }
  11336. Float32BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  11337. Float32BufferAttribute.prototype.constructor = Float32BufferAttribute;
  11338. function Float64BufferAttribute( array, itemSize, normalized ) {
  11339. BufferAttribute.call( this, new Float64Array( array ), itemSize, normalized );
  11340. }
  11341. Float64BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  11342. Float64BufferAttribute.prototype.constructor = Float64BufferAttribute;
  11343. /**
  11344. * @author mrdoob / http://mrdoob.com/
  11345. */
  11346. function DirectGeometry() {
  11347. this.vertices = [];
  11348. this.normals = [];
  11349. this.colors = [];
  11350. this.uvs = [];
  11351. this.uvs2 = [];
  11352. this.groups = [];
  11353. this.morphTargets = {};
  11354. this.skinWeights = [];
  11355. this.skinIndices = [];
  11356. // this.lineDistances = [];
  11357. this.boundingBox = null;
  11358. this.boundingSphere = null;
  11359. // update flags
  11360. this.verticesNeedUpdate = false;
  11361. this.normalsNeedUpdate = false;
  11362. this.colorsNeedUpdate = false;
  11363. this.uvsNeedUpdate = false;
  11364. this.groupsNeedUpdate = false;
  11365. }
  11366. Object.assign( DirectGeometry.prototype, {
  11367. computeGroups: function ( geometry ) {
  11368. var group;
  11369. var groups = [];
  11370. var materialIndex = undefined;
  11371. var faces = geometry.faces;
  11372. for ( var i = 0; i < faces.length; i ++ ) {
  11373. var face = faces[ i ];
  11374. // materials
  11375. if ( face.materialIndex !== materialIndex ) {
  11376. materialIndex = face.materialIndex;
  11377. if ( group !== undefined ) {
  11378. group.count = ( i * 3 ) - group.start;
  11379. groups.push( group );
  11380. }
  11381. group = {
  11382. start: i * 3,
  11383. materialIndex: materialIndex
  11384. };
  11385. }
  11386. }
  11387. if ( group !== undefined ) {
  11388. group.count = ( i * 3 ) - group.start;
  11389. groups.push( group );
  11390. }
  11391. this.groups = groups;
  11392. },
  11393. fromGeometry: function ( geometry ) {
  11394. var faces = geometry.faces;
  11395. var vertices = geometry.vertices;
  11396. var faceVertexUvs = geometry.faceVertexUvs;
  11397. var hasFaceVertexUv = faceVertexUvs[ 0 ] && faceVertexUvs[ 0 ].length > 0;
  11398. var hasFaceVertexUv2 = faceVertexUvs[ 1 ] && faceVertexUvs[ 1 ].length > 0;
  11399. // morphs
  11400. var morphTargets = geometry.morphTargets;
  11401. var morphTargetsLength = morphTargets.length;
  11402. var morphTargetsPosition;
  11403. if ( morphTargetsLength > 0 ) {
  11404. morphTargetsPosition = [];
  11405. for ( var i = 0; i < morphTargetsLength; i ++ ) {
  11406. morphTargetsPosition[ i ] = {
  11407. name: morphTargets[ i ].name,
  11408. data: []
  11409. };
  11410. }
  11411. this.morphTargets.position = morphTargetsPosition;
  11412. }
  11413. var morphNormals = geometry.morphNormals;
  11414. var morphNormalsLength = morphNormals.length;
  11415. var morphTargetsNormal;
  11416. if ( morphNormalsLength > 0 ) {
  11417. morphTargetsNormal = [];
  11418. for ( var i = 0; i < morphNormalsLength; i ++ ) {
  11419. morphTargetsNormal[ i ] = {
  11420. name: morphNormals[ i ].name,
  11421. data: []
  11422. };
  11423. }
  11424. this.morphTargets.normal = morphTargetsNormal;
  11425. }
  11426. // skins
  11427. var skinIndices = geometry.skinIndices;
  11428. var skinWeights = geometry.skinWeights;
  11429. var hasSkinIndices = skinIndices.length === vertices.length;
  11430. var hasSkinWeights = skinWeights.length === vertices.length;
  11431. //
  11432. if ( vertices.length > 0 && faces.length === 0 ) {
  11433. console.error( 'THREE.DirectGeometry: Faceless geometries are not supported.' );
  11434. }
  11435. for ( var i = 0; i < faces.length; i ++ ) {
  11436. var face = faces[ i ];
  11437. this.vertices.push( vertices[ face.a ], vertices[ face.b ], vertices[ face.c ] );
  11438. var vertexNormals = face.vertexNormals;
  11439. if ( vertexNormals.length === 3 ) {
  11440. this.normals.push( vertexNormals[ 0 ], vertexNormals[ 1 ], vertexNormals[ 2 ] );
  11441. } else {
  11442. var normal = face.normal;
  11443. this.normals.push( normal, normal, normal );
  11444. }
  11445. var vertexColors = face.vertexColors;
  11446. if ( vertexColors.length === 3 ) {
  11447. this.colors.push( vertexColors[ 0 ], vertexColors[ 1 ], vertexColors[ 2 ] );
  11448. } else {
  11449. var color = face.color;
  11450. this.colors.push( color, color, color );
  11451. }
  11452. if ( hasFaceVertexUv === true ) {
  11453. var vertexUvs = faceVertexUvs[ 0 ][ i ];
  11454. if ( vertexUvs !== undefined ) {
  11455. this.uvs.push( vertexUvs[ 0 ], vertexUvs[ 1 ], vertexUvs[ 2 ] );
  11456. } else {
  11457. console.warn( 'THREE.DirectGeometry.fromGeometry(): Undefined vertexUv ', i );
  11458. this.uvs.push( new Vector2(), new Vector2(), new Vector2() );
  11459. }
  11460. }
  11461. if ( hasFaceVertexUv2 === true ) {
  11462. var vertexUvs = faceVertexUvs[ 1 ][ i ];
  11463. if ( vertexUvs !== undefined ) {
  11464. this.uvs2.push( vertexUvs[ 0 ], vertexUvs[ 1 ], vertexUvs[ 2 ] );
  11465. } else {
  11466. console.warn( 'THREE.DirectGeometry.fromGeometry(): Undefined vertexUv2 ', i );
  11467. this.uvs2.push( new Vector2(), new Vector2(), new Vector2() );
  11468. }
  11469. }
  11470. // morphs
  11471. for ( var j = 0; j < morphTargetsLength; j ++ ) {
  11472. var morphTarget = morphTargets[ j ].vertices;
  11473. morphTargetsPosition[ j ].data.push( morphTarget[ face.a ], morphTarget[ face.b ], morphTarget[ face.c ] );
  11474. }
  11475. for ( var j = 0; j < morphNormalsLength; j ++ ) {
  11476. var morphNormal = morphNormals[ j ].vertexNormals[ i ];
  11477. morphTargetsNormal[ j ].data.push( morphNormal.a, morphNormal.b, morphNormal.c );
  11478. }
  11479. // skins
  11480. if ( hasSkinIndices ) {
  11481. this.skinIndices.push( skinIndices[ face.a ], skinIndices[ face.b ], skinIndices[ face.c ] );
  11482. }
  11483. if ( hasSkinWeights ) {
  11484. this.skinWeights.push( skinWeights[ face.a ], skinWeights[ face.b ], skinWeights[ face.c ] );
  11485. }
  11486. }
  11487. this.computeGroups( geometry );
  11488. this.verticesNeedUpdate = geometry.verticesNeedUpdate;
  11489. this.normalsNeedUpdate = geometry.normalsNeedUpdate;
  11490. this.colorsNeedUpdate = geometry.colorsNeedUpdate;
  11491. this.uvsNeedUpdate = geometry.uvsNeedUpdate;
  11492. this.groupsNeedUpdate = geometry.groupsNeedUpdate;
  11493. if ( geometry.boundingSphere !== null ) {
  11494. this.boundingSphere = geometry.boundingSphere.clone();
  11495. }
  11496. if ( geometry.boundingBox !== null ) {
  11497. this.boundingBox = geometry.boundingBox.clone();
  11498. }
  11499. return this;
  11500. }
  11501. } );
  11502. /**
  11503. * @author mrdoob / http://mrdoob.com/
  11504. */
  11505. function arrayMax( array ) {
  11506. if ( array.length === 0 ) { return - Infinity; }
  11507. var max = array[ 0 ];
  11508. for ( var i = 1, l = array.length; i < l; ++ i ) {
  11509. if ( array[ i ] > max ) { max = array[ i ]; }
  11510. }
  11511. return max;
  11512. }
  11513. /**
  11514. * @author alteredq / http://alteredqualia.com/
  11515. * @author mrdoob / http://mrdoob.com/
  11516. */
  11517. var _bufferGeometryId = 1; // BufferGeometry uses odd numbers as Id
  11518. var _m1$2 = new Matrix4();
  11519. var _obj = new Object3D();
  11520. var _offset = new Vector3();
  11521. var _box$2 = new Box3();
  11522. var _boxMorphTargets = new Box3();
  11523. var _vector$4 = new Vector3();
  11524. function BufferGeometry() {
  11525. Object.defineProperty( this, 'id', { value: _bufferGeometryId += 2 } );
  11526. this.uuid = MathUtils.generateUUID();
  11527. this.name = '';
  11528. this.type = 'BufferGeometry';
  11529. this.index = null;
  11530. this.attributes = {};
  11531. this.morphAttributes = {};
  11532. this.morphTargetsRelative = false;
  11533. this.groups = [];
  11534. this.boundingBox = null;
  11535. this.boundingSphere = null;
  11536. this.drawRange = { start: 0, count: Infinity };
  11537. this.userData = {};
  11538. }
  11539. BufferGeometry.prototype = Object.assign( Object.create( EventDispatcher.prototype ), {
  11540. constructor: BufferGeometry,
  11541. isBufferGeometry: true,
  11542. getIndex: function () {
  11543. return this.index;
  11544. },
  11545. setIndex: function ( index ) {
  11546. if ( Array.isArray( index ) ) {
  11547. this.index = new ( arrayMax( index ) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute )( index, 1 );
  11548. } else {
  11549. this.index = index;
  11550. }
  11551. },
  11552. getAttribute: function ( name ) {
  11553. return this.attributes[ name ];
  11554. },
  11555. setAttribute: function ( name, attribute ) {
  11556. this.attributes[ name ] = attribute;
  11557. return this;
  11558. },
  11559. deleteAttribute: function ( name ) {
  11560. delete this.attributes[ name ];
  11561. return this;
  11562. },
  11563. addGroup: function ( start, count, materialIndex ) {
  11564. this.groups.push( {
  11565. start: start,
  11566. count: count,
  11567. materialIndex: materialIndex !== undefined ? materialIndex : 0
  11568. } );
  11569. },
  11570. clearGroups: function () {
  11571. this.groups = [];
  11572. },
  11573. setDrawRange: function ( start, count ) {
  11574. this.drawRange.start = start;
  11575. this.drawRange.count = count;
  11576. },
  11577. applyMatrix4: function ( matrix ) {
  11578. var position = this.attributes.position;
  11579. if ( position !== undefined ) {
  11580. position.applyMatrix4( matrix );
  11581. position.needsUpdate = true;
  11582. }
  11583. var normal = this.attributes.normal;
  11584. if ( normal !== undefined ) {
  11585. var normalMatrix = new Matrix3().getNormalMatrix( matrix );
  11586. normal.applyNormalMatrix( normalMatrix );
  11587. normal.needsUpdate = true;
  11588. }
  11589. var tangent = this.attributes.tangent;
  11590. if ( tangent !== undefined ) {
  11591. tangent.transformDirection( matrix );
  11592. tangent.needsUpdate = true;
  11593. }
  11594. if ( this.boundingBox !== null ) {
  11595. this.computeBoundingBox();
  11596. }
  11597. if ( this.boundingSphere !== null ) {
  11598. this.computeBoundingSphere();
  11599. }
  11600. return this;
  11601. },
  11602. rotateX: function ( angle ) {
  11603. // rotate geometry around world x-axis
  11604. _m1$2.makeRotationX( angle );
  11605. this.applyMatrix4( _m1$2 );
  11606. return this;
  11607. },
  11608. rotateY: function ( angle ) {
  11609. // rotate geometry around world y-axis
  11610. _m1$2.makeRotationY( angle );
  11611. this.applyMatrix4( _m1$2 );
  11612. return this;
  11613. },
  11614. rotateZ: function ( angle ) {
  11615. // rotate geometry around world z-axis
  11616. _m1$2.makeRotationZ( angle );
  11617. this.applyMatrix4( _m1$2 );
  11618. return this;
  11619. },
  11620. translate: function ( x, y, z ) {
  11621. // translate geometry
  11622. _m1$2.makeTranslation( x, y, z );
  11623. this.applyMatrix4( _m1$2 );
  11624. return this;
  11625. },
  11626. scale: function ( x, y, z ) {
  11627. // scale geometry
  11628. _m1$2.makeScale( x, y, z );
  11629. this.applyMatrix4( _m1$2 );
  11630. return this;
  11631. },
  11632. lookAt: function ( vector ) {
  11633. _obj.lookAt( vector );
  11634. _obj.updateMatrix();
  11635. this.applyMatrix4( _obj.matrix );
  11636. return this;
  11637. },
  11638. center: function () {
  11639. this.computeBoundingBox();
  11640. this.boundingBox.getCenter( _offset ).negate();
  11641. this.translate( _offset.x, _offset.y, _offset.z );
  11642. return this;
  11643. },
  11644. setFromObject: function ( object ) {
  11645. // console.log( 'THREE.BufferGeometry.setFromObject(). Converting', object, this );
  11646. var geometry = object.geometry;
  11647. if ( object.isPoints || object.isLine ) {
  11648. var positions = new Float32BufferAttribute( geometry.vertices.length * 3, 3 );
  11649. var colors = new Float32BufferAttribute( geometry.colors.length * 3, 3 );
  11650. this.setAttribute( 'position', positions.copyVector3sArray( geometry.vertices ) );
  11651. this.setAttribute( 'color', colors.copyColorsArray( geometry.colors ) );
  11652. if ( geometry.lineDistances && geometry.lineDistances.length === geometry.vertices.length ) {
  11653. var lineDistances = new Float32BufferAttribute( geometry.lineDistances.length, 1 );
  11654. this.setAttribute( 'lineDistance', lineDistances.copyArray( geometry.lineDistances ) );
  11655. }
  11656. if ( geometry.boundingSphere !== null ) {
  11657. this.boundingSphere = geometry.boundingSphere.clone();
  11658. }
  11659. if ( geometry.boundingBox !== null ) {
  11660. this.boundingBox = geometry.boundingBox.clone();
  11661. }
  11662. } else if ( object.isMesh ) {
  11663. if ( geometry && geometry.isGeometry ) {
  11664. this.fromGeometry( geometry );
  11665. }
  11666. }
  11667. return this;
  11668. },
  11669. setFromPoints: function ( points ) {
  11670. var position = [];
  11671. for ( var i = 0, l = points.length; i < l; i ++ ) {
  11672. var point = points[ i ];
  11673. position.push( point.x, point.y, point.z || 0 );
  11674. }
  11675. this.setAttribute( 'position', new Float32BufferAttribute( position, 3 ) );
  11676. return this;
  11677. },
  11678. updateFromObject: function ( object ) {
  11679. var geometry = object.geometry;
  11680. if ( object.isMesh ) {
  11681. var direct = geometry.__directGeometry;
  11682. if ( geometry.elementsNeedUpdate === true ) {
  11683. direct = undefined;
  11684. geometry.elementsNeedUpdate = false;
  11685. }
  11686. if ( direct === undefined ) {
  11687. return this.fromGeometry( geometry );
  11688. }
  11689. direct.verticesNeedUpdate = geometry.verticesNeedUpdate;
  11690. direct.normalsNeedUpdate = geometry.normalsNeedUpdate;
  11691. direct.colorsNeedUpdate = geometry.colorsNeedUpdate;
  11692. direct.uvsNeedUpdate = geometry.uvsNeedUpdate;
  11693. direct.groupsNeedUpdate = geometry.groupsNeedUpdate;
  11694. geometry.verticesNeedUpdate = false;
  11695. geometry.normalsNeedUpdate = false;
  11696. geometry.colorsNeedUpdate = false;
  11697. geometry.uvsNeedUpdate = false;
  11698. geometry.groupsNeedUpdate = false;
  11699. geometry = direct;
  11700. }
  11701. var attribute;
  11702. if ( geometry.verticesNeedUpdate === true ) {
  11703. attribute = this.attributes.position;
  11704. if ( attribute !== undefined ) {
  11705. attribute.copyVector3sArray( geometry.vertices );
  11706. attribute.needsUpdate = true;
  11707. }
  11708. geometry.verticesNeedUpdate = false;
  11709. }
  11710. if ( geometry.normalsNeedUpdate === true ) {
  11711. attribute = this.attributes.normal;
  11712. if ( attribute !== undefined ) {
  11713. attribute.copyVector3sArray( geometry.normals );
  11714. attribute.needsUpdate = true;
  11715. }
  11716. geometry.normalsNeedUpdate = false;
  11717. }
  11718. if ( geometry.colorsNeedUpdate === true ) {
  11719. attribute = this.attributes.color;
  11720. if ( attribute !== undefined ) {
  11721. attribute.copyColorsArray( geometry.colors );
  11722. attribute.needsUpdate = true;
  11723. }
  11724. geometry.colorsNeedUpdate = false;
  11725. }
  11726. if ( geometry.uvsNeedUpdate ) {
  11727. attribute = this.attributes.uv;
  11728. if ( attribute !== undefined ) {
  11729. attribute.copyVector2sArray( geometry.uvs );
  11730. attribute.needsUpdate = true;
  11731. }
  11732. geometry.uvsNeedUpdate = false;
  11733. }
  11734. if ( geometry.lineDistancesNeedUpdate ) {
  11735. attribute = this.attributes.lineDistance;
  11736. if ( attribute !== undefined ) {
  11737. attribute.copyArray( geometry.lineDistances );
  11738. attribute.needsUpdate = true;
  11739. }
  11740. geometry.lineDistancesNeedUpdate = false;
  11741. }
  11742. if ( geometry.groupsNeedUpdate ) {
  11743. geometry.computeGroups( object.geometry );
  11744. this.groups = geometry.groups;
  11745. geometry.groupsNeedUpdate = false;
  11746. }
  11747. return this;
  11748. },
  11749. fromGeometry: function ( geometry ) {
  11750. geometry.__directGeometry = new DirectGeometry().fromGeometry( geometry );
  11751. return this.fromDirectGeometry( geometry.__directGeometry );
  11752. },
  11753. fromDirectGeometry: function ( geometry ) {
  11754. var positions = new Float32Array( geometry.vertices.length * 3 );
  11755. this.setAttribute( 'position', new BufferAttribute( positions, 3 ).copyVector3sArray( geometry.vertices ) );
  11756. if ( geometry.normals.length > 0 ) {
  11757. var normals = new Float32Array( geometry.normals.length * 3 );
  11758. this.setAttribute( 'normal', new BufferAttribute( normals, 3 ).copyVector3sArray( geometry.normals ) );
  11759. }
  11760. if ( geometry.colors.length > 0 ) {
  11761. var colors = new Float32Array( geometry.colors.length * 3 );
  11762. this.setAttribute( 'color', new BufferAttribute( colors, 3 ).copyColorsArray( geometry.colors ) );
  11763. }
  11764. if ( geometry.uvs.length > 0 ) {
  11765. var uvs = new Float32Array( geometry.uvs.length * 2 );
  11766. this.setAttribute( 'uv', new BufferAttribute( uvs, 2 ).copyVector2sArray( geometry.uvs ) );
  11767. }
  11768. if ( geometry.uvs2.length > 0 ) {
  11769. var uvs2 = new Float32Array( geometry.uvs2.length * 2 );
  11770. this.setAttribute( 'uv2', new BufferAttribute( uvs2, 2 ).copyVector2sArray( geometry.uvs2 ) );
  11771. }
  11772. // groups
  11773. this.groups = geometry.groups;
  11774. // morphs
  11775. for ( var name in geometry.morphTargets ) {
  11776. var array = [];
  11777. var morphTargets = geometry.morphTargets[ name ];
  11778. for ( var i = 0, l = morphTargets.length; i < l; i ++ ) {
  11779. var morphTarget = morphTargets[ i ];
  11780. var attribute = new Float32BufferAttribute( morphTarget.data.length * 3, 3 );
  11781. attribute.name = morphTarget.name;
  11782. array.push( attribute.copyVector3sArray( morphTarget.data ) );
  11783. }
  11784. this.morphAttributes[ name ] = array;
  11785. }
  11786. // skinning
  11787. if ( geometry.skinIndices.length > 0 ) {
  11788. var skinIndices = new Float32BufferAttribute( geometry.skinIndices.length * 4, 4 );
  11789. this.setAttribute( 'skinIndex', skinIndices.copyVector4sArray( geometry.skinIndices ) );
  11790. }
  11791. if ( geometry.skinWeights.length > 0 ) {
  11792. var skinWeights = new Float32BufferAttribute( geometry.skinWeights.length * 4, 4 );
  11793. this.setAttribute( 'skinWeight', skinWeights.copyVector4sArray( geometry.skinWeights ) );
  11794. }
  11795. //
  11796. if ( geometry.boundingSphere !== null ) {
  11797. this.boundingSphere = geometry.boundingSphere.clone();
  11798. }
  11799. if ( geometry.boundingBox !== null ) {
  11800. this.boundingBox = geometry.boundingBox.clone();
  11801. }
  11802. return this;
  11803. },
  11804. computeBoundingBox: function () {
  11805. if ( this.boundingBox === null ) {
  11806. this.boundingBox = new Box3();
  11807. }
  11808. var position = this.attributes.position;
  11809. var morphAttributesPosition = this.morphAttributes.position;
  11810. if ( position !== undefined ) {
  11811. this.boundingBox.setFromBufferAttribute( position );
  11812. // process morph attributes if present
  11813. if ( morphAttributesPosition ) {
  11814. for ( var i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  11815. var morphAttribute = morphAttributesPosition[ i ];
  11816. _box$2.setFromBufferAttribute( morphAttribute );
  11817. if ( this.morphTargetsRelative ) {
  11818. _vector$4.addVectors( this.boundingBox.min, _box$2.min );
  11819. this.boundingBox.expandByPoint( _vector$4 );
  11820. _vector$4.addVectors( this.boundingBox.max, _box$2.max );
  11821. this.boundingBox.expandByPoint( _vector$4 );
  11822. } else {
  11823. this.boundingBox.expandByPoint( _box$2.min );
  11824. this.boundingBox.expandByPoint( _box$2.max );
  11825. }
  11826. }
  11827. }
  11828. } else {
  11829. this.boundingBox.makeEmpty();
  11830. }
  11831. if ( isNaN( this.boundingBox.min.x ) || isNaN( this.boundingBox.min.y ) || isNaN( this.boundingBox.min.z ) ) {
  11832. console.error( 'THREE.BufferGeometry.computeBoundingBox: Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this );
  11833. }
  11834. },
  11835. computeBoundingSphere: function () {
  11836. if ( this.boundingSphere === null ) {
  11837. this.boundingSphere = new Sphere();
  11838. }
  11839. var position = this.attributes.position;
  11840. var morphAttributesPosition = this.morphAttributes.position;
  11841. if ( position ) {
  11842. // first, find the center of the bounding sphere
  11843. var center = this.boundingSphere.center;
  11844. _box$2.setFromBufferAttribute( position );
  11845. // process morph attributes if present
  11846. if ( morphAttributesPosition ) {
  11847. for ( var i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  11848. var morphAttribute = morphAttributesPosition[ i ];
  11849. _boxMorphTargets.setFromBufferAttribute( morphAttribute );
  11850. if ( this.morphTargetsRelative ) {
  11851. _vector$4.addVectors( _box$2.min, _boxMorphTargets.min );
  11852. _box$2.expandByPoint( _vector$4 );
  11853. _vector$4.addVectors( _box$2.max, _boxMorphTargets.max );
  11854. _box$2.expandByPoint( _vector$4 );
  11855. } else {
  11856. _box$2.expandByPoint( _boxMorphTargets.min );
  11857. _box$2.expandByPoint( _boxMorphTargets.max );
  11858. }
  11859. }
  11860. }
  11861. _box$2.getCenter( center );
  11862. // second, try to find a boundingSphere with a radius smaller than the
  11863. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  11864. var maxRadiusSq = 0;
  11865. for ( var i = 0, il = position.count; i < il; i ++ ) {
  11866. _vector$4.fromBufferAttribute( position, i );
  11867. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$4 ) );
  11868. }
  11869. // process morph attributes if present
  11870. if ( morphAttributesPosition ) {
  11871. for ( var i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  11872. var morphAttribute = morphAttributesPosition[ i ];
  11873. var morphTargetsRelative = this.morphTargetsRelative;
  11874. for ( var j = 0, jl = morphAttribute.count; j < jl; j ++ ) {
  11875. _vector$4.fromBufferAttribute( morphAttribute, j );
  11876. if ( morphTargetsRelative ) {
  11877. _offset.fromBufferAttribute( position, j );
  11878. _vector$4.add( _offset );
  11879. }
  11880. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$4 ) );
  11881. }
  11882. }
  11883. }
  11884. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  11885. if ( isNaN( this.boundingSphere.radius ) ) {
  11886. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this );
  11887. }
  11888. }
  11889. },
  11890. computeFaceNormals: function () {
  11891. // backwards compatibility
  11892. },
  11893. computeVertexNormals: function () {
  11894. var index = this.index;
  11895. var attributes = this.attributes;
  11896. if ( attributes.position ) {
  11897. var positions = attributes.position.array;
  11898. if ( attributes.normal === undefined ) {
  11899. this.setAttribute( 'normal', new BufferAttribute( new Float32Array( positions.length ), 3 ) );
  11900. } else {
  11901. // reset existing normals to zero
  11902. var array = attributes.normal.array;
  11903. for ( var i = 0, il = array.length; i < il; i ++ ) {
  11904. array[ i ] = 0;
  11905. }
  11906. }
  11907. var normals = attributes.normal.array;
  11908. var vA, vB, vC;
  11909. var pA = new Vector3(), pB = new Vector3(), pC = new Vector3();
  11910. var cb = new Vector3(), ab = new Vector3();
  11911. // indexed elements
  11912. if ( index ) {
  11913. var indices = index.array;
  11914. for ( var i = 0, il = index.count; i < il; i += 3 ) {
  11915. vA = indices[ i + 0 ] * 3;
  11916. vB = indices[ i + 1 ] * 3;
  11917. vC = indices[ i + 2 ] * 3;
  11918. pA.fromArray( positions, vA );
  11919. pB.fromArray( positions, vB );
  11920. pC.fromArray( positions, vC );
  11921. cb.subVectors( pC, pB );
  11922. ab.subVectors( pA, pB );
  11923. cb.cross( ab );
  11924. normals[ vA ] += cb.x;
  11925. normals[ vA + 1 ] += cb.y;
  11926. normals[ vA + 2 ] += cb.z;
  11927. normals[ vB ] += cb.x;
  11928. normals[ vB + 1 ] += cb.y;
  11929. normals[ vB + 2 ] += cb.z;
  11930. normals[ vC ] += cb.x;
  11931. normals[ vC + 1 ] += cb.y;
  11932. normals[ vC + 2 ] += cb.z;
  11933. }
  11934. } else {
  11935. // non-indexed elements (unconnected triangle soup)
  11936. for ( var i = 0, il = positions.length; i < il; i += 9 ) {
  11937. pA.fromArray( positions, i );
  11938. pB.fromArray( positions, i + 3 );
  11939. pC.fromArray( positions, i + 6 );
  11940. cb.subVectors( pC, pB );
  11941. ab.subVectors( pA, pB );
  11942. cb.cross( ab );
  11943. normals[ i ] = cb.x;
  11944. normals[ i + 1 ] = cb.y;
  11945. normals[ i + 2 ] = cb.z;
  11946. normals[ i + 3 ] = cb.x;
  11947. normals[ i + 4 ] = cb.y;
  11948. normals[ i + 5 ] = cb.z;
  11949. normals[ i + 6 ] = cb.x;
  11950. normals[ i + 7 ] = cb.y;
  11951. normals[ i + 8 ] = cb.z;
  11952. }
  11953. }
  11954. this.normalizeNormals();
  11955. attributes.normal.needsUpdate = true;
  11956. }
  11957. },
  11958. merge: function ( geometry, offset ) {
  11959. if ( ! ( geometry && geometry.isBufferGeometry ) ) {
  11960. console.error( 'THREE.BufferGeometry.merge(): geometry not an instance of THREE.BufferGeometry.', geometry );
  11961. return;
  11962. }
  11963. if ( offset === undefined ) {
  11964. offset = 0;
  11965. console.warn(
  11966. 'THREE.BufferGeometry.merge(): Overwriting original geometry, starting at offset=0. '
  11967. + 'Use BufferGeometryUtils.mergeBufferGeometries() for lossless merge.'
  11968. );
  11969. }
  11970. var attributes = this.attributes;
  11971. for ( var key in attributes ) {
  11972. if ( geometry.attributes[ key ] === undefined ) { continue; }
  11973. var attribute1 = attributes[ key ];
  11974. var attributeArray1 = attribute1.array;
  11975. var attribute2 = geometry.attributes[ key ];
  11976. var attributeArray2 = attribute2.array;
  11977. var attributeOffset = attribute2.itemSize * offset;
  11978. var length = Math.min( attributeArray2.length, attributeArray1.length - attributeOffset );
  11979. for ( var i = 0, j = attributeOffset; i < length; i ++, j ++ ) {
  11980. attributeArray1[ j ] = attributeArray2[ i ];
  11981. }
  11982. }
  11983. return this;
  11984. },
  11985. normalizeNormals: function () {
  11986. var normals = this.attributes.normal;
  11987. for ( var i = 0, il = normals.count; i < il; i ++ ) {
  11988. _vector$4.x = normals.getX( i );
  11989. _vector$4.y = normals.getY( i );
  11990. _vector$4.z = normals.getZ( i );
  11991. _vector$4.normalize();
  11992. normals.setXYZ( i, _vector$4.x, _vector$4.y, _vector$4.z );
  11993. }
  11994. },
  11995. toNonIndexed: function () {
  11996. function convertBufferAttribute( attribute, indices ) {
  11997. var array = attribute.array;
  11998. var itemSize = attribute.itemSize;
  11999. var array2 = new array.constructor( indices.length * itemSize );
  12000. var index = 0, index2 = 0;
  12001. for ( var i = 0, l = indices.length; i < l; i ++ ) {
  12002. index = indices[ i ] * itemSize;
  12003. for ( var j = 0; j < itemSize; j ++ ) {
  12004. array2[ index2 ++ ] = array[ index ++ ];
  12005. }
  12006. }
  12007. return new BufferAttribute( array2, itemSize );
  12008. }
  12009. //
  12010. if ( this.index === null ) {
  12011. console.warn( 'THREE.BufferGeometry.toNonIndexed(): Geometry is already non-indexed.' );
  12012. return this;
  12013. }
  12014. var geometry2 = new BufferGeometry();
  12015. var indices = this.index.array;
  12016. var attributes = this.attributes;
  12017. // attributes
  12018. for ( var name in attributes ) {
  12019. var attribute = attributes[ name ];
  12020. var newAttribute = convertBufferAttribute( attribute, indices );
  12021. geometry2.setAttribute( name, newAttribute );
  12022. }
  12023. // morph attributes
  12024. var morphAttributes = this.morphAttributes;
  12025. for ( name in morphAttributes ) {
  12026. var morphArray = [];
  12027. var morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  12028. for ( var i = 0, il = morphAttribute.length; i < il; i ++ ) {
  12029. var attribute = morphAttribute[ i ];
  12030. var newAttribute = convertBufferAttribute( attribute, indices );
  12031. morphArray.push( newAttribute );
  12032. }
  12033. geometry2.morphAttributes[ name ] = morphArray;
  12034. }
  12035. geometry2.morphTargetsRelative = this.morphTargetsRelative;
  12036. // groups
  12037. var groups = this.groups;
  12038. for ( var i = 0, l = groups.length; i < l; i ++ ) {
  12039. var group = groups[ i ];
  12040. geometry2.addGroup( group.start, group.count, group.materialIndex );
  12041. }
  12042. return geometry2;
  12043. },
  12044. toJSON: function () {
  12045. var data = {
  12046. metadata: {
  12047. version: 4.5,
  12048. type: 'BufferGeometry',
  12049. generator: 'BufferGeometry.toJSON'
  12050. }
  12051. };
  12052. // standard BufferGeometry serialization
  12053. data.uuid = this.uuid;
  12054. data.type = this.type;
  12055. if ( this.name !== '' ) { data.name = this.name; }
  12056. if ( Object.keys( this.userData ).length > 0 ) { data.userData = this.userData; }
  12057. if ( this.parameters !== undefined ) {
  12058. var parameters = this.parameters;
  12059. for ( var key in parameters ) {
  12060. if ( parameters[ key ] !== undefined ) { data[ key ] = parameters[ key ]; }
  12061. }
  12062. return data;
  12063. }
  12064. data.data = { attributes: {} };
  12065. var index = this.index;
  12066. if ( index !== null ) {
  12067. data.data.index = {
  12068. type: index.array.constructor.name,
  12069. array: Array.prototype.slice.call( index.array )
  12070. };
  12071. }
  12072. var attributes = this.attributes;
  12073. for ( var key in attributes ) {
  12074. var attribute = attributes[ key ];
  12075. var attributeData = attribute.toJSON();
  12076. if ( attribute.name !== '' ) { attributeData.name = attribute.name; }
  12077. data.data.attributes[ key ] = attributeData;
  12078. }
  12079. var morphAttributes = {};
  12080. var hasMorphAttributes = false;
  12081. for ( var key in this.morphAttributes ) {
  12082. var attributeArray = this.morphAttributes[ key ];
  12083. var array = [];
  12084. for ( var i = 0, il = attributeArray.length; i < il; i ++ ) {
  12085. var attribute = attributeArray[ i ];
  12086. var attributeData = attribute.toJSON();
  12087. if ( attribute.name !== '' ) { attributeData.name = attribute.name; }
  12088. array.push( attributeData );
  12089. }
  12090. if ( array.length > 0 ) {
  12091. morphAttributes[ key ] = array;
  12092. hasMorphAttributes = true;
  12093. }
  12094. }
  12095. if ( hasMorphAttributes ) {
  12096. data.data.morphAttributes = morphAttributes;
  12097. data.data.morphTargetsRelative = this.morphTargetsRelative;
  12098. }
  12099. var groups = this.groups;
  12100. if ( groups.length > 0 ) {
  12101. data.data.groups = JSON.parse( JSON.stringify( groups ) );
  12102. }
  12103. var boundingSphere = this.boundingSphere;
  12104. if ( boundingSphere !== null ) {
  12105. data.data.boundingSphere = {
  12106. center: boundingSphere.center.toArray(),
  12107. radius: boundingSphere.radius
  12108. };
  12109. }
  12110. return data;
  12111. },
  12112. clone: function () {
  12113. /*
  12114. // Handle primitives
  12115. var parameters = this.parameters;
  12116. if ( parameters !== undefined ) {
  12117. var values = [];
  12118. for ( var key in parameters ) {
  12119. values.push( parameters[ key ] );
  12120. }
  12121. var geometry = Object.create( this.constructor.prototype );
  12122. this.constructor.apply( geometry, values );
  12123. return geometry;
  12124. }
  12125. return new this.constructor().copy( this );
  12126. */
  12127. return new BufferGeometry().copy( this );
  12128. },
  12129. copy: function ( source ) {
  12130. var name, i, l;
  12131. // reset
  12132. this.index = null;
  12133. this.attributes = {};
  12134. this.morphAttributes = {};
  12135. this.groups = [];
  12136. this.boundingBox = null;
  12137. this.boundingSphere = null;
  12138. // name
  12139. this.name = source.name;
  12140. // index
  12141. var index = source.index;
  12142. if ( index !== null ) {
  12143. this.setIndex( index.clone() );
  12144. }
  12145. // attributes
  12146. var attributes = source.attributes;
  12147. for ( name in attributes ) {
  12148. var attribute = attributes[ name ];
  12149. this.setAttribute( name, attribute.clone() );
  12150. }
  12151. // morph attributes
  12152. var morphAttributes = source.morphAttributes;
  12153. for ( name in morphAttributes ) {
  12154. var array = [];
  12155. var morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  12156. for ( i = 0, l = morphAttribute.length; i < l; i ++ ) {
  12157. array.push( morphAttribute[ i ].clone() );
  12158. }
  12159. this.morphAttributes[ name ] = array;
  12160. }
  12161. this.morphTargetsRelative = source.morphTargetsRelative;
  12162. // groups
  12163. var groups = source.groups;
  12164. for ( i = 0, l = groups.length; i < l; i ++ ) {
  12165. var group = groups[ i ];
  12166. this.addGroup( group.start, group.count, group.materialIndex );
  12167. }
  12168. // bounding box
  12169. var boundingBox = source.boundingBox;
  12170. if ( boundingBox !== null ) {
  12171. this.boundingBox = boundingBox.clone();
  12172. }
  12173. // bounding sphere
  12174. var boundingSphere = source.boundingSphere;
  12175. if ( boundingSphere !== null ) {
  12176. this.boundingSphere = boundingSphere.clone();
  12177. }
  12178. // draw range
  12179. this.drawRange.start = source.drawRange.start;
  12180. this.drawRange.count = source.drawRange.count;
  12181. // user data
  12182. this.userData = source.userData;
  12183. return this;
  12184. },
  12185. dispose: function () {
  12186. this.dispatchEvent( { type: 'dispose' } );
  12187. }
  12188. } );
  12189. /**
  12190. * @author mrdoob / http://mrdoob.com/
  12191. * @author alteredq / http://alteredqualia.com/
  12192. * @author mikael emtinger / http://gomo.se/
  12193. * @author jonobr1 / http://jonobr1.com/
  12194. */
  12195. var _inverseMatrix = new Matrix4();
  12196. var _ray = new Ray();
  12197. var _sphere = new Sphere();
  12198. var _vA = new Vector3();
  12199. var _vB = new Vector3();
  12200. var _vC = new Vector3();
  12201. var _tempA = new Vector3();
  12202. var _tempB = new Vector3();
  12203. var _tempC = new Vector3();
  12204. var _morphA = new Vector3();
  12205. var _morphB = new Vector3();
  12206. var _morphC = new Vector3();
  12207. var _uvA = new Vector2();
  12208. var _uvB = new Vector2();
  12209. var _uvC = new Vector2();
  12210. var _intersectionPoint = new Vector3();
  12211. var _intersectionPointWorld = new Vector3();
  12212. function Mesh( geometry, material ) {
  12213. Object3D.call( this );
  12214. this.type = 'Mesh';
  12215. this.geometry = geometry !== undefined ? geometry : new BufferGeometry();
  12216. this.material = material !== undefined ? material : new MeshBasicMaterial();
  12217. this.updateMorphTargets();
  12218. }
  12219. Mesh.prototype = Object.assign( Object.create( Object3D.prototype ), {
  12220. constructor: Mesh,
  12221. isMesh: true,
  12222. copy: function ( source ) {
  12223. Object3D.prototype.copy.call( this, source );
  12224. if ( source.morphTargetInfluences !== undefined ) {
  12225. this.morphTargetInfluences = source.morphTargetInfluences.slice();
  12226. }
  12227. if ( source.morphTargetDictionary !== undefined ) {
  12228. this.morphTargetDictionary = Object.assign( {}, source.morphTargetDictionary );
  12229. }
  12230. return this;
  12231. },
  12232. updateMorphTargets: function () {
  12233. var geometry = this.geometry;
  12234. var m, ml, name;
  12235. if ( geometry.isBufferGeometry ) {
  12236. var morphAttributes = geometry.morphAttributes;
  12237. var keys = Object.keys( morphAttributes );
  12238. if ( keys.length > 0 ) {
  12239. var morphAttribute = morphAttributes[ keys[ 0 ] ];
  12240. if ( morphAttribute !== undefined ) {
  12241. this.morphTargetInfluences = [];
  12242. this.morphTargetDictionary = {};
  12243. for ( m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  12244. name = morphAttribute[ m ].name || String( m );
  12245. this.morphTargetInfluences.push( 0 );
  12246. this.morphTargetDictionary[ name ] = m;
  12247. }
  12248. }
  12249. }
  12250. } else {
  12251. var morphTargets = geometry.morphTargets;
  12252. if ( morphTargets !== undefined && morphTargets.length > 0 ) {
  12253. console.error( 'THREE.Mesh.updateMorphTargets() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.' );
  12254. }
  12255. }
  12256. },
  12257. raycast: function ( raycaster, intersects ) {
  12258. var geometry = this.geometry;
  12259. var material = this.material;
  12260. var matrixWorld = this.matrixWorld;
  12261. if ( material === undefined ) { return; }
  12262. // Checking boundingSphere distance to ray
  12263. if ( geometry.boundingSphere === null ) { geometry.computeBoundingSphere(); }
  12264. _sphere.copy( geometry.boundingSphere );
  12265. _sphere.applyMatrix4( matrixWorld );
  12266. if ( raycaster.ray.intersectsSphere( _sphere ) === false ) { return; }
  12267. //
  12268. _inverseMatrix.getInverse( matrixWorld );
  12269. _ray.copy( raycaster.ray ).applyMatrix4( _inverseMatrix );
  12270. // Check boundingBox before continuing
  12271. if ( geometry.boundingBox !== null ) {
  12272. if ( _ray.intersectsBox( geometry.boundingBox ) === false ) { return; }
  12273. }
  12274. var intersection;
  12275. if ( geometry.isBufferGeometry ) {
  12276. var a, b, c;
  12277. var index = geometry.index;
  12278. var position = geometry.attributes.position;
  12279. var morphPosition = geometry.morphAttributes.position;
  12280. var morphTargetsRelative = geometry.morphTargetsRelative;
  12281. var uv = geometry.attributes.uv;
  12282. var uv2 = geometry.attributes.uv2;
  12283. var groups = geometry.groups;
  12284. var drawRange = geometry.drawRange;
  12285. var i, j, il, jl;
  12286. var group, groupMaterial;
  12287. var start, end;
  12288. if ( index !== null ) {
  12289. // indexed buffer geometry
  12290. if ( Array.isArray( material ) ) {
  12291. for ( i = 0, il = groups.length; i < il; i ++ ) {
  12292. group = groups[ i ];
  12293. groupMaterial = material[ group.materialIndex ];
  12294. start = Math.max( group.start, drawRange.start );
  12295. end = Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) );
  12296. for ( j = start, jl = end; j < jl; j += 3 ) {
  12297. a = index.getX( j );
  12298. b = index.getX( j + 1 );
  12299. c = index.getX( j + 2 );
  12300. intersection = checkBufferGeometryIntersection( this, groupMaterial, raycaster, _ray, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c );
  12301. if ( intersection ) {
  12302. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in indexed buffer semantics
  12303. intersection.face.materialIndex = group.materialIndex;
  12304. intersects.push( intersection );
  12305. }
  12306. }
  12307. }
  12308. } else {
  12309. start = Math.max( 0, drawRange.start );
  12310. end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  12311. for ( i = start, il = end; i < il; i += 3 ) {
  12312. a = index.getX( i );
  12313. b = index.getX( i + 1 );
  12314. c = index.getX( i + 2 );
  12315. intersection = checkBufferGeometryIntersection( this, material, raycaster, _ray, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c );
  12316. if ( intersection ) {
  12317. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in indexed buffer semantics
  12318. intersects.push( intersection );
  12319. }
  12320. }
  12321. }
  12322. } else if ( position !== undefined ) {
  12323. // non-indexed buffer geometry
  12324. if ( Array.isArray( material ) ) {
  12325. for ( i = 0, il = groups.length; i < il; i ++ ) {
  12326. group = groups[ i ];
  12327. groupMaterial = material[ group.materialIndex ];
  12328. start = Math.max( group.start, drawRange.start );
  12329. end = Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) );
  12330. for ( j = start, jl = end; j < jl; j += 3 ) {
  12331. a = j;
  12332. b = j + 1;
  12333. c = j + 2;
  12334. intersection = checkBufferGeometryIntersection( this, groupMaterial, raycaster, _ray, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c );
  12335. if ( intersection ) {
  12336. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in non-indexed buffer semantics
  12337. intersection.face.materialIndex = group.materialIndex;
  12338. intersects.push( intersection );
  12339. }
  12340. }
  12341. }
  12342. } else {
  12343. start = Math.max( 0, drawRange.start );
  12344. end = Math.min( position.count, ( drawRange.start + drawRange.count ) );
  12345. for ( i = start, il = end; i < il; i += 3 ) {
  12346. a = i;
  12347. b = i + 1;
  12348. c = i + 2;
  12349. intersection = checkBufferGeometryIntersection( this, material, raycaster, _ray, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c );
  12350. if ( intersection ) {
  12351. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in non-indexed buffer semantics
  12352. intersects.push( intersection );
  12353. }
  12354. }
  12355. }
  12356. }
  12357. } else if ( geometry.isGeometry ) {
  12358. var fvA, fvB, fvC;
  12359. var isMultiMaterial = Array.isArray( material );
  12360. var vertices = geometry.vertices;
  12361. var faces = geometry.faces;
  12362. var uvs;
  12363. var faceVertexUvs = geometry.faceVertexUvs[ 0 ];
  12364. if ( faceVertexUvs.length > 0 ) { uvs = faceVertexUvs; }
  12365. for ( var f = 0, fl = faces.length; f < fl; f ++ ) {
  12366. var face = faces[ f ];
  12367. var faceMaterial = isMultiMaterial ? material[ face.materialIndex ] : material;
  12368. if ( faceMaterial === undefined ) { continue; }
  12369. fvA = vertices[ face.a ];
  12370. fvB = vertices[ face.b ];
  12371. fvC = vertices[ face.c ];
  12372. intersection = checkIntersection( this, faceMaterial, raycaster, _ray, fvA, fvB, fvC, _intersectionPoint );
  12373. if ( intersection ) {
  12374. if ( uvs && uvs[ f ] ) {
  12375. var uvs_f = uvs[ f ];
  12376. _uvA.copy( uvs_f[ 0 ] );
  12377. _uvB.copy( uvs_f[ 1 ] );
  12378. _uvC.copy( uvs_f[ 2 ] );
  12379. intersection.uv = Triangle.getUV( _intersectionPoint, fvA, fvB, fvC, _uvA, _uvB, _uvC, new Vector2() );
  12380. }
  12381. intersection.face = face;
  12382. intersection.faceIndex = f;
  12383. intersects.push( intersection );
  12384. }
  12385. }
  12386. }
  12387. },
  12388. clone: function () {
  12389. return new this.constructor( this.geometry, this.material ).copy( this );
  12390. }
  12391. } );
  12392. function checkIntersection( object, material, raycaster, ray, pA, pB, pC, point ) {
  12393. var intersect;
  12394. if ( material.side === BackSide ) {
  12395. intersect = ray.intersectTriangle( pC, pB, pA, true, point );
  12396. } else {
  12397. intersect = ray.intersectTriangle( pA, pB, pC, material.side !== DoubleSide, point );
  12398. }
  12399. if ( intersect === null ) { return null; }
  12400. _intersectionPointWorld.copy( point );
  12401. _intersectionPointWorld.applyMatrix4( object.matrixWorld );
  12402. var distance = raycaster.ray.origin.distanceTo( _intersectionPointWorld );
  12403. if ( distance < raycaster.near || distance > raycaster.far ) { return null; }
  12404. return {
  12405. distance: distance,
  12406. point: _intersectionPointWorld.clone(),
  12407. object: object
  12408. };
  12409. }
  12410. function checkBufferGeometryIntersection( object, material, raycaster, ray, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c ) {
  12411. _vA.fromBufferAttribute( position, a );
  12412. _vB.fromBufferAttribute( position, b );
  12413. _vC.fromBufferAttribute( position, c );
  12414. var morphInfluences = object.morphTargetInfluences;
  12415. if ( material.morphTargets && morphPosition && morphInfluences ) {
  12416. _morphA.set( 0, 0, 0 );
  12417. _morphB.set( 0, 0, 0 );
  12418. _morphC.set( 0, 0, 0 );
  12419. for ( var i = 0, il = morphPosition.length; i < il; i ++ ) {
  12420. var influence = morphInfluences[ i ];
  12421. var morphAttribute = morphPosition[ i ];
  12422. if ( influence === 0 ) { continue; }
  12423. _tempA.fromBufferAttribute( morphAttribute, a );
  12424. _tempB.fromBufferAttribute( morphAttribute, b );
  12425. _tempC.fromBufferAttribute( morphAttribute, c );
  12426. if ( morphTargetsRelative ) {
  12427. _morphA.addScaledVector( _tempA, influence );
  12428. _morphB.addScaledVector( _tempB, influence );
  12429. _morphC.addScaledVector( _tempC, influence );
  12430. } else {
  12431. _morphA.addScaledVector( _tempA.sub( _vA ), influence );
  12432. _morphB.addScaledVector( _tempB.sub( _vB ), influence );
  12433. _morphC.addScaledVector( _tempC.sub( _vC ), influence );
  12434. }
  12435. }
  12436. _vA.add( _morphA );
  12437. _vB.add( _morphB );
  12438. _vC.add( _morphC );
  12439. }
  12440. var intersection = checkIntersection( object, material, raycaster, ray, _vA, _vB, _vC, _intersectionPoint );
  12441. if ( intersection ) {
  12442. if ( uv ) {
  12443. _uvA.fromBufferAttribute( uv, a );
  12444. _uvB.fromBufferAttribute( uv, b );
  12445. _uvC.fromBufferAttribute( uv, c );
  12446. intersection.uv = Triangle.getUV( _intersectionPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2() );
  12447. }
  12448. if ( uv2 ) {
  12449. _uvA.fromBufferAttribute( uv2, a );
  12450. _uvB.fromBufferAttribute( uv2, b );
  12451. _uvC.fromBufferAttribute( uv2, c );
  12452. intersection.uv2 = Triangle.getUV( _intersectionPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2() );
  12453. }
  12454. var face = new Face3( a, b, c );
  12455. Triangle.getNormal( _vA, _vB, _vC, face.normal );
  12456. intersection.face = face;
  12457. }
  12458. return intersection;
  12459. }
  12460. /**
  12461. * @author mrdoob / http://mrdoob.com/
  12462. * @author kile / http://kile.stravaganza.org/
  12463. * @author alteredq / http://alteredqualia.com/
  12464. * @author mikael emtinger / http://gomo.se/
  12465. * @author zz85 / http://www.lab4games.net/zz85/blog
  12466. * @author bhouston / http://clara.io
  12467. */
  12468. var _geometryId = 0; // Geometry uses even numbers as Id
  12469. var _m1$3 = new Matrix4();
  12470. var _obj$1 = new Object3D();
  12471. var _offset$1 = new Vector3();
  12472. function Geometry() {
  12473. Object.defineProperty( this, 'id', { value: _geometryId += 2 } );
  12474. this.uuid = MathUtils.generateUUID();
  12475. this.name = '';
  12476. this.type = 'Geometry';
  12477. this.vertices = [];
  12478. this.colors = [];
  12479. this.faces = [];
  12480. this.faceVertexUvs = [[]];
  12481. this.morphTargets = [];
  12482. this.morphNormals = [];
  12483. this.skinWeights = [];
  12484. this.skinIndices = [];
  12485. this.lineDistances = [];
  12486. this.boundingBox = null;
  12487. this.boundingSphere = null;
  12488. // update flags
  12489. this.elementsNeedUpdate = false;
  12490. this.verticesNeedUpdate = false;
  12491. this.uvsNeedUpdate = false;
  12492. this.normalsNeedUpdate = false;
  12493. this.colorsNeedUpdate = false;
  12494. this.lineDistancesNeedUpdate = false;
  12495. this.groupsNeedUpdate = false;
  12496. }
  12497. Geometry.prototype = Object.assign( Object.create( EventDispatcher.prototype ), {
  12498. constructor: Geometry,
  12499. isGeometry: true,
  12500. applyMatrix4: function ( matrix ) {
  12501. var normalMatrix = new Matrix3().getNormalMatrix( matrix );
  12502. for ( var i = 0, il = this.vertices.length; i < il; i ++ ) {
  12503. var vertex = this.vertices[ i ];
  12504. vertex.applyMatrix4( matrix );
  12505. }
  12506. for ( var i = 0, il = this.faces.length; i < il; i ++ ) {
  12507. var face = this.faces[ i ];
  12508. face.normal.applyMatrix3( normalMatrix ).normalize();
  12509. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  12510. face.vertexNormals[ j ].applyMatrix3( normalMatrix ).normalize();
  12511. }
  12512. }
  12513. if ( this.boundingBox !== null ) {
  12514. this.computeBoundingBox();
  12515. }
  12516. if ( this.boundingSphere !== null ) {
  12517. this.computeBoundingSphere();
  12518. }
  12519. this.verticesNeedUpdate = true;
  12520. this.normalsNeedUpdate = true;
  12521. return this;
  12522. },
  12523. rotateX: function ( angle ) {
  12524. // rotate geometry around world x-axis
  12525. _m1$3.makeRotationX( angle );
  12526. this.applyMatrix4( _m1$3 );
  12527. return this;
  12528. },
  12529. rotateY: function ( angle ) {
  12530. // rotate geometry around world y-axis
  12531. _m1$3.makeRotationY( angle );
  12532. this.applyMatrix4( _m1$3 );
  12533. return this;
  12534. },
  12535. rotateZ: function ( angle ) {
  12536. // rotate geometry around world z-axis
  12537. _m1$3.makeRotationZ( angle );
  12538. this.applyMatrix4( _m1$3 );
  12539. return this;
  12540. },
  12541. translate: function ( x, y, z ) {
  12542. // translate geometry
  12543. _m1$3.makeTranslation( x, y, z );
  12544. this.applyMatrix4( _m1$3 );
  12545. return this;
  12546. },
  12547. scale: function ( x, y, z ) {
  12548. // scale geometry
  12549. _m1$3.makeScale( x, y, z );
  12550. this.applyMatrix4( _m1$3 );
  12551. return this;
  12552. },
  12553. lookAt: function ( vector ) {
  12554. _obj$1.lookAt( vector );
  12555. _obj$1.updateMatrix();
  12556. this.applyMatrix4( _obj$1.matrix );
  12557. return this;
  12558. },
  12559. fromBufferGeometry: function ( geometry ) {
  12560. var scope = this;
  12561. var indices = geometry.index !== null ? geometry.index.array : undefined;
  12562. var attributes = geometry.attributes;
  12563. if ( attributes.position === undefined ) {
  12564. console.error( 'THREE.Geometry.fromBufferGeometry(): Position attribute required for conversion.' );
  12565. return this;
  12566. }
  12567. var positions = attributes.position.array;
  12568. var normals = attributes.normal !== undefined ? attributes.normal.array : undefined;
  12569. var colors = attributes.color !== undefined ? attributes.color.array : undefined;
  12570. var uvs = attributes.uv !== undefined ? attributes.uv.array : undefined;
  12571. var uvs2 = attributes.uv2 !== undefined ? attributes.uv2.array : undefined;
  12572. if ( uvs2 !== undefined ) { this.faceVertexUvs[ 1 ] = []; }
  12573. for ( var i = 0; i < positions.length; i += 3 ) {
  12574. scope.vertices.push( new Vector3().fromArray( positions, i ) );
  12575. if ( colors !== undefined ) {
  12576. scope.colors.push( new Color().fromArray( colors, i ) );
  12577. }
  12578. }
  12579. function addFace( a, b, c, materialIndex ) {
  12580. var vertexColors = ( colors === undefined ) ? [] : [
  12581. scope.colors[ a ].clone(),
  12582. scope.colors[ b ].clone(),
  12583. scope.colors[ c ].clone() ];
  12584. var vertexNormals = ( normals === undefined ) ? [] : [
  12585. new Vector3().fromArray( normals, a * 3 ),
  12586. new Vector3().fromArray( normals, b * 3 ),
  12587. new Vector3().fromArray( normals, c * 3 )
  12588. ];
  12589. var face = new Face3( a, b, c, vertexNormals, vertexColors, materialIndex );
  12590. scope.faces.push( face );
  12591. if ( uvs !== undefined ) {
  12592. scope.faceVertexUvs[ 0 ].push( [
  12593. new Vector2().fromArray( uvs, a * 2 ),
  12594. new Vector2().fromArray( uvs, b * 2 ),
  12595. new Vector2().fromArray( uvs, c * 2 )
  12596. ] );
  12597. }
  12598. if ( uvs2 !== undefined ) {
  12599. scope.faceVertexUvs[ 1 ].push( [
  12600. new Vector2().fromArray( uvs2, a * 2 ),
  12601. new Vector2().fromArray( uvs2, b * 2 ),
  12602. new Vector2().fromArray( uvs2, c * 2 )
  12603. ] );
  12604. }
  12605. }
  12606. var groups = geometry.groups;
  12607. if ( groups.length > 0 ) {
  12608. for ( var i = 0; i < groups.length; i ++ ) {
  12609. var group = groups[ i ];
  12610. var start = group.start;
  12611. var count = group.count;
  12612. for ( var j = start, jl = start + count; j < jl; j += 3 ) {
  12613. if ( indices !== undefined ) {
  12614. addFace( indices[ j ], indices[ j + 1 ], indices[ j + 2 ], group.materialIndex );
  12615. } else {
  12616. addFace( j, j + 1, j + 2, group.materialIndex );
  12617. }
  12618. }
  12619. }
  12620. } else {
  12621. if ( indices !== undefined ) {
  12622. for ( var i = 0; i < indices.length; i += 3 ) {
  12623. addFace( indices[ i ], indices[ i + 1 ], indices[ i + 2 ] );
  12624. }
  12625. } else {
  12626. for ( var i = 0; i < positions.length / 3; i += 3 ) {
  12627. addFace( i, i + 1, i + 2 );
  12628. }
  12629. }
  12630. }
  12631. this.computeFaceNormals();
  12632. if ( geometry.boundingBox !== null ) {
  12633. this.boundingBox = geometry.boundingBox.clone();
  12634. }
  12635. if ( geometry.boundingSphere !== null ) {
  12636. this.boundingSphere = geometry.boundingSphere.clone();
  12637. }
  12638. return this;
  12639. },
  12640. center: function () {
  12641. this.computeBoundingBox();
  12642. this.boundingBox.getCenter( _offset$1 ).negate();
  12643. this.translate( _offset$1.x, _offset$1.y, _offset$1.z );
  12644. return this;
  12645. },
  12646. normalize: function () {
  12647. this.computeBoundingSphere();
  12648. var center = this.boundingSphere.center;
  12649. var radius = this.boundingSphere.radius;
  12650. var s = radius === 0 ? 1 : 1.0 / radius;
  12651. var matrix = new Matrix4();
  12652. matrix.set(
  12653. s, 0, 0, - s * center.x,
  12654. 0, s, 0, - s * center.y,
  12655. 0, 0, s, - s * center.z,
  12656. 0, 0, 0, 1
  12657. );
  12658. this.applyMatrix4( matrix );
  12659. return this;
  12660. },
  12661. computeFaceNormals: function () {
  12662. var cb = new Vector3(), ab = new Vector3();
  12663. for ( var f = 0, fl = this.faces.length; f < fl; f ++ ) {
  12664. var face = this.faces[ f ];
  12665. var vA = this.vertices[ face.a ];
  12666. var vB = this.vertices[ face.b ];
  12667. var vC = this.vertices[ face.c ];
  12668. cb.subVectors( vC, vB );
  12669. ab.subVectors( vA, vB );
  12670. cb.cross( ab );
  12671. cb.normalize();
  12672. face.normal.copy( cb );
  12673. }
  12674. },
  12675. computeVertexNormals: function ( areaWeighted ) {
  12676. if ( areaWeighted === undefined ) { areaWeighted = true; }
  12677. var v, vl, f, fl, face, vertices;
  12678. vertices = new Array( this.vertices.length );
  12679. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  12680. vertices[ v ] = new Vector3();
  12681. }
  12682. if ( areaWeighted ) {
  12683. // vertex normals weighted by triangle areas
  12684. // http://www.iquilezles.org/www/articles/normals/normals.htm
  12685. var vA, vB, vC;
  12686. var cb = new Vector3(), ab = new Vector3();
  12687. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  12688. face = this.faces[ f ];
  12689. vA = this.vertices[ face.a ];
  12690. vB = this.vertices[ face.b ];
  12691. vC = this.vertices[ face.c ];
  12692. cb.subVectors( vC, vB );
  12693. ab.subVectors( vA, vB );
  12694. cb.cross( ab );
  12695. vertices[ face.a ].add( cb );
  12696. vertices[ face.b ].add( cb );
  12697. vertices[ face.c ].add( cb );
  12698. }
  12699. } else {
  12700. this.computeFaceNormals();
  12701. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  12702. face = this.faces[ f ];
  12703. vertices[ face.a ].add( face.normal );
  12704. vertices[ face.b ].add( face.normal );
  12705. vertices[ face.c ].add( face.normal );
  12706. }
  12707. }
  12708. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  12709. vertices[ v ].normalize();
  12710. }
  12711. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  12712. face = this.faces[ f ];
  12713. var vertexNormals = face.vertexNormals;
  12714. if ( vertexNormals.length === 3 ) {
  12715. vertexNormals[ 0 ].copy( vertices[ face.a ] );
  12716. vertexNormals[ 1 ].copy( vertices[ face.b ] );
  12717. vertexNormals[ 2 ].copy( vertices[ face.c ] );
  12718. } else {
  12719. vertexNormals[ 0 ] = vertices[ face.a ].clone();
  12720. vertexNormals[ 1 ] = vertices[ face.b ].clone();
  12721. vertexNormals[ 2 ] = vertices[ face.c ].clone();
  12722. }
  12723. }
  12724. if ( this.faces.length > 0 ) {
  12725. this.normalsNeedUpdate = true;
  12726. }
  12727. },
  12728. computeFlatVertexNormals: function () {
  12729. var f, fl, face;
  12730. this.computeFaceNormals();
  12731. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  12732. face = this.faces[ f ];
  12733. var vertexNormals = face.vertexNormals;
  12734. if ( vertexNormals.length === 3 ) {
  12735. vertexNormals[ 0 ].copy( face.normal );
  12736. vertexNormals[ 1 ].copy( face.normal );
  12737. vertexNormals[ 2 ].copy( face.normal );
  12738. } else {
  12739. vertexNormals[ 0 ] = face.normal.clone();
  12740. vertexNormals[ 1 ] = face.normal.clone();
  12741. vertexNormals[ 2 ] = face.normal.clone();
  12742. }
  12743. }
  12744. if ( this.faces.length > 0 ) {
  12745. this.normalsNeedUpdate = true;
  12746. }
  12747. },
  12748. computeMorphNormals: function () {
  12749. var i, il, f, fl, face;
  12750. // save original normals
  12751. // - create temp variables on first access
  12752. // otherwise just copy (for faster repeated calls)
  12753. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  12754. face = this.faces[ f ];
  12755. if ( ! face.__originalFaceNormal ) {
  12756. face.__originalFaceNormal = face.normal.clone();
  12757. } else {
  12758. face.__originalFaceNormal.copy( face.normal );
  12759. }
  12760. if ( ! face.__originalVertexNormals ) { face.__originalVertexNormals = []; }
  12761. for ( i = 0, il = face.vertexNormals.length; i < il; i ++ ) {
  12762. if ( ! face.__originalVertexNormals[ i ] ) {
  12763. face.__originalVertexNormals[ i ] = face.vertexNormals[ i ].clone();
  12764. } else {
  12765. face.__originalVertexNormals[ i ].copy( face.vertexNormals[ i ] );
  12766. }
  12767. }
  12768. }
  12769. // use temp geometry to compute face and vertex normals for each morph
  12770. var tmpGeo = new Geometry();
  12771. tmpGeo.faces = this.faces;
  12772. for ( i = 0, il = this.morphTargets.length; i < il; i ++ ) {
  12773. // create on first access
  12774. if ( ! this.morphNormals[ i ] ) {
  12775. this.morphNormals[ i ] = {};
  12776. this.morphNormals[ i ].faceNormals = [];
  12777. this.morphNormals[ i ].vertexNormals = [];
  12778. var dstNormalsFace = this.morphNormals[ i ].faceNormals;
  12779. var dstNormalsVertex = this.morphNormals[ i ].vertexNormals;
  12780. var faceNormal, vertexNormals;
  12781. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  12782. faceNormal = new Vector3();
  12783. vertexNormals = { a: new Vector3(), b: new Vector3(), c: new Vector3() };
  12784. dstNormalsFace.push( faceNormal );
  12785. dstNormalsVertex.push( vertexNormals );
  12786. }
  12787. }
  12788. var morphNormals = this.morphNormals[ i ];
  12789. // set vertices to morph target
  12790. tmpGeo.vertices = this.morphTargets[ i ].vertices;
  12791. // compute morph normals
  12792. tmpGeo.computeFaceNormals();
  12793. tmpGeo.computeVertexNormals();
  12794. // store morph normals
  12795. var faceNormal, vertexNormals;
  12796. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  12797. face = this.faces[ f ];
  12798. faceNormal = morphNormals.faceNormals[ f ];
  12799. vertexNormals = morphNormals.vertexNormals[ f ];
  12800. faceNormal.copy( face.normal );
  12801. vertexNormals.a.copy( face.vertexNormals[ 0 ] );
  12802. vertexNormals.b.copy( face.vertexNormals[ 1 ] );
  12803. vertexNormals.c.copy( face.vertexNormals[ 2 ] );
  12804. }
  12805. }
  12806. // restore original normals
  12807. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  12808. face = this.faces[ f ];
  12809. face.normal = face.__originalFaceNormal;
  12810. face.vertexNormals = face.__originalVertexNormals;
  12811. }
  12812. },
  12813. computeBoundingBox: function () {
  12814. if ( this.boundingBox === null ) {
  12815. this.boundingBox = new Box3();
  12816. }
  12817. this.boundingBox.setFromPoints( this.vertices );
  12818. },
  12819. computeBoundingSphere: function () {
  12820. if ( this.boundingSphere === null ) {
  12821. this.boundingSphere = new Sphere();
  12822. }
  12823. this.boundingSphere.setFromPoints( this.vertices );
  12824. },
  12825. merge: function ( geometry, matrix, materialIndexOffset ) {
  12826. if ( ! ( geometry && geometry.isGeometry ) ) {
  12827. console.error( 'THREE.Geometry.merge(): geometry not an instance of THREE.Geometry.', geometry );
  12828. return;
  12829. }
  12830. var normalMatrix,
  12831. vertexOffset = this.vertices.length,
  12832. vertices1 = this.vertices,
  12833. vertices2 = geometry.vertices,
  12834. faces1 = this.faces,
  12835. faces2 = geometry.faces,
  12836. colors1 = this.colors,
  12837. colors2 = geometry.colors;
  12838. if ( materialIndexOffset === undefined ) { materialIndexOffset = 0; }
  12839. if ( matrix !== undefined ) {
  12840. normalMatrix = new Matrix3().getNormalMatrix( matrix );
  12841. }
  12842. // vertices
  12843. for ( var i = 0, il = vertices2.length; i < il; i ++ ) {
  12844. var vertex = vertices2[ i ];
  12845. var vertexCopy = vertex.clone();
  12846. if ( matrix !== undefined ) { vertexCopy.applyMatrix4( matrix ); }
  12847. vertices1.push( vertexCopy );
  12848. }
  12849. // colors
  12850. for ( var i = 0, il = colors2.length; i < il; i ++ ) {
  12851. colors1.push( colors2[ i ].clone() );
  12852. }
  12853. // faces
  12854. for ( i = 0, il = faces2.length; i < il; i ++ ) {
  12855. var face = faces2[ i ], faceCopy, normal, color,
  12856. faceVertexNormals = face.vertexNormals,
  12857. faceVertexColors = face.vertexColors;
  12858. faceCopy = new Face3( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset );
  12859. faceCopy.normal.copy( face.normal );
  12860. if ( normalMatrix !== undefined ) {
  12861. faceCopy.normal.applyMatrix3( normalMatrix ).normalize();
  12862. }
  12863. for ( var j = 0, jl = faceVertexNormals.length; j < jl; j ++ ) {
  12864. normal = faceVertexNormals[ j ].clone();
  12865. if ( normalMatrix !== undefined ) {
  12866. normal.applyMatrix3( normalMatrix ).normalize();
  12867. }
  12868. faceCopy.vertexNormals.push( normal );
  12869. }
  12870. faceCopy.color.copy( face.color );
  12871. for ( var j = 0, jl = faceVertexColors.length; j < jl; j ++ ) {
  12872. color = faceVertexColors[ j ];
  12873. faceCopy.vertexColors.push( color.clone() );
  12874. }
  12875. faceCopy.materialIndex = face.materialIndex + materialIndexOffset;
  12876. faces1.push( faceCopy );
  12877. }
  12878. // uvs
  12879. for ( var i = 0, il = geometry.faceVertexUvs.length; i < il; i ++ ) {
  12880. var faceVertexUvs2 = geometry.faceVertexUvs[ i ];
  12881. if ( this.faceVertexUvs[ i ] === undefined ) { this.faceVertexUvs[ i ] = []; }
  12882. for ( var j = 0, jl = faceVertexUvs2.length; j < jl; j ++ ) {
  12883. var uvs2 = faceVertexUvs2[ j ], uvsCopy = [];
  12884. for ( var k = 0, kl = uvs2.length; k < kl; k ++ ) {
  12885. uvsCopy.push( uvs2[ k ].clone() );
  12886. }
  12887. this.faceVertexUvs[ i ].push( uvsCopy );
  12888. }
  12889. }
  12890. },
  12891. mergeMesh: function ( mesh ) {
  12892. if ( ! ( mesh && mesh.isMesh ) ) {
  12893. console.error( 'THREE.Geometry.mergeMesh(): mesh not an instance of THREE.Mesh.', mesh );
  12894. return;
  12895. }
  12896. if ( mesh.matrixAutoUpdate ) { mesh.updateMatrix(); }
  12897. this.merge( mesh.geometry, mesh.matrix );
  12898. },
  12899. /*
  12900. * Checks for duplicate vertices with hashmap.
  12901. * Duplicated vertices are removed
  12902. * and faces' vertices are updated.
  12903. */
  12904. mergeVertices: function () {
  12905. var verticesMap = {}; // Hashmap for looking up vertices by position coordinates (and making sure they are unique)
  12906. var unique = [], changes = [];
  12907. var v, key;
  12908. var precisionPoints = 4; // number of decimal points, e.g. 4 for epsilon of 0.0001
  12909. var precision = Math.pow( 10, precisionPoints );
  12910. var i, il, face;
  12911. var indices, j, jl;
  12912. for ( i = 0, il = this.vertices.length; i < il; i ++ ) {
  12913. v = this.vertices[ i ];
  12914. key = Math.round( v.x * precision ) + '_' + Math.round( v.y * precision ) + '_' + Math.round( v.z * precision );
  12915. if ( verticesMap[ key ] === undefined ) {
  12916. verticesMap[ key ] = i;
  12917. unique.push( this.vertices[ i ] );
  12918. changes[ i ] = unique.length - 1;
  12919. } else {
  12920. //console.log('Duplicate vertex found. ', i, ' could be using ', verticesMap[key]);
  12921. changes[ i ] = changes[ verticesMap[ key ] ];
  12922. }
  12923. }
  12924. // if faces are completely degenerate after merging vertices, we
  12925. // have to remove them from the geometry.
  12926. var faceIndicesToRemove = [];
  12927. for ( i = 0, il = this.faces.length; i < il; i ++ ) {
  12928. face = this.faces[ i ];
  12929. face.a = changes[ face.a ];
  12930. face.b = changes[ face.b ];
  12931. face.c = changes[ face.c ];
  12932. indices = [ face.a, face.b, face.c ];
  12933. // if any duplicate vertices are found in a Face3
  12934. // we have to remove the face as nothing can be saved
  12935. for ( var n = 0; n < 3; n ++ ) {
  12936. if ( indices[ n ] === indices[ ( n + 1 ) % 3 ] ) {
  12937. faceIndicesToRemove.push( i );
  12938. break;
  12939. }
  12940. }
  12941. }
  12942. for ( i = faceIndicesToRemove.length - 1; i >= 0; i -- ) {
  12943. var idx = faceIndicesToRemove[ i ];
  12944. this.faces.splice( idx, 1 );
  12945. for ( j = 0, jl = this.faceVertexUvs.length; j < jl; j ++ ) {
  12946. this.faceVertexUvs[ j ].splice( idx, 1 );
  12947. }
  12948. }
  12949. // Use unique set of vertices
  12950. var diff = this.vertices.length - unique.length;
  12951. this.vertices = unique;
  12952. return diff;
  12953. },
  12954. setFromPoints: function ( points ) {
  12955. this.vertices = [];
  12956. for ( var i = 0, l = points.length; i < l; i ++ ) {
  12957. var point = points[ i ];
  12958. this.vertices.push( new Vector3( point.x, point.y, point.z || 0 ) );
  12959. }
  12960. return this;
  12961. },
  12962. sortFacesByMaterialIndex: function () {
  12963. var faces = this.faces;
  12964. var length = faces.length;
  12965. // tag faces
  12966. for ( var i = 0; i < length; i ++ ) {
  12967. faces[ i ]._id = i;
  12968. }
  12969. // sort faces
  12970. function materialIndexSort( a, b ) {
  12971. return a.materialIndex - b.materialIndex;
  12972. }
  12973. faces.sort( materialIndexSort );
  12974. // sort uvs
  12975. var uvs1 = this.faceVertexUvs[ 0 ];
  12976. var uvs2 = this.faceVertexUvs[ 1 ];
  12977. var newUvs1, newUvs2;
  12978. if ( uvs1 && uvs1.length === length ) { newUvs1 = []; }
  12979. if ( uvs2 && uvs2.length === length ) { newUvs2 = []; }
  12980. for ( var i = 0; i < length; i ++ ) {
  12981. var id = faces[ i ]._id;
  12982. if ( newUvs1 ) { newUvs1.push( uvs1[ id ] ); }
  12983. if ( newUvs2 ) { newUvs2.push( uvs2[ id ] ); }
  12984. }
  12985. if ( newUvs1 ) { this.faceVertexUvs[ 0 ] = newUvs1; }
  12986. if ( newUvs2 ) { this.faceVertexUvs[ 1 ] = newUvs2; }
  12987. },
  12988. toJSON: function () {
  12989. var data = {
  12990. metadata: {
  12991. version: 4.5,
  12992. type: 'Geometry',
  12993. generator: 'Geometry.toJSON'
  12994. }
  12995. };
  12996. // standard Geometry serialization
  12997. data.uuid = this.uuid;
  12998. data.type = this.type;
  12999. if ( this.name !== '' ) { data.name = this.name; }
  13000. if ( this.parameters !== undefined ) {
  13001. var parameters = this.parameters;
  13002. for ( var key in parameters ) {
  13003. if ( parameters[ key ] !== undefined ) { data[ key ] = parameters[ key ]; }
  13004. }
  13005. return data;
  13006. }
  13007. var vertices = [];
  13008. for ( var i = 0; i < this.vertices.length; i ++ ) {
  13009. var vertex = this.vertices[ i ];
  13010. vertices.push( vertex.x, vertex.y, vertex.z );
  13011. }
  13012. var faces = [];
  13013. var normals = [];
  13014. var normalsHash = {};
  13015. var colors = [];
  13016. var colorsHash = {};
  13017. var uvs = [];
  13018. var uvsHash = {};
  13019. for ( var i = 0; i < this.faces.length; i ++ ) {
  13020. var face = this.faces[ i ];
  13021. var hasMaterial = true;
  13022. var hasFaceUv = false; // deprecated
  13023. var hasFaceVertexUv = this.faceVertexUvs[ 0 ][ i ] !== undefined;
  13024. var hasFaceNormal = face.normal.length() > 0;
  13025. var hasFaceVertexNormal = face.vertexNormals.length > 0;
  13026. var hasFaceColor = face.color.r !== 1 || face.color.g !== 1 || face.color.b !== 1;
  13027. var hasFaceVertexColor = face.vertexColors.length > 0;
  13028. var faceType = 0;
  13029. faceType = setBit( faceType, 0, 0 ); // isQuad
  13030. faceType = setBit( faceType, 1, hasMaterial );
  13031. faceType = setBit( faceType, 2, hasFaceUv );
  13032. faceType = setBit( faceType, 3, hasFaceVertexUv );
  13033. faceType = setBit( faceType, 4, hasFaceNormal );
  13034. faceType = setBit( faceType, 5, hasFaceVertexNormal );
  13035. faceType = setBit( faceType, 6, hasFaceColor );
  13036. faceType = setBit( faceType, 7, hasFaceVertexColor );
  13037. faces.push( faceType );
  13038. faces.push( face.a, face.b, face.c );
  13039. faces.push( face.materialIndex );
  13040. if ( hasFaceVertexUv ) {
  13041. var faceVertexUvs = this.faceVertexUvs[ 0 ][ i ];
  13042. faces.push(
  13043. getUvIndex( faceVertexUvs[ 0 ] ),
  13044. getUvIndex( faceVertexUvs[ 1 ] ),
  13045. getUvIndex( faceVertexUvs[ 2 ] )
  13046. );
  13047. }
  13048. if ( hasFaceNormal ) {
  13049. faces.push( getNormalIndex( face.normal ) );
  13050. }
  13051. if ( hasFaceVertexNormal ) {
  13052. var vertexNormals = face.vertexNormals;
  13053. faces.push(
  13054. getNormalIndex( vertexNormals[ 0 ] ),
  13055. getNormalIndex( vertexNormals[ 1 ] ),
  13056. getNormalIndex( vertexNormals[ 2 ] )
  13057. );
  13058. }
  13059. if ( hasFaceColor ) {
  13060. faces.push( getColorIndex( face.color ) );
  13061. }
  13062. if ( hasFaceVertexColor ) {
  13063. var vertexColors = face.vertexColors;
  13064. faces.push(
  13065. getColorIndex( vertexColors[ 0 ] ),
  13066. getColorIndex( vertexColors[ 1 ] ),
  13067. getColorIndex( vertexColors[ 2 ] )
  13068. );
  13069. }
  13070. }
  13071. function setBit( value, position, enabled ) {
  13072. return enabled ? value | ( 1 << position ) : value & ( ~ ( 1 << position ) );
  13073. }
  13074. function getNormalIndex( normal ) {
  13075. var hash = normal.x.toString() + normal.y.toString() + normal.z.toString();
  13076. if ( normalsHash[ hash ] !== undefined ) {
  13077. return normalsHash[ hash ];
  13078. }
  13079. normalsHash[ hash ] = normals.length / 3;
  13080. normals.push( normal.x, normal.y, normal.z );
  13081. return normalsHash[ hash ];
  13082. }
  13083. function getColorIndex( color ) {
  13084. var hash = color.r.toString() + color.g.toString() + color.b.toString();
  13085. if ( colorsHash[ hash ] !== undefined ) {
  13086. return colorsHash[ hash ];
  13087. }
  13088. colorsHash[ hash ] = colors.length;
  13089. colors.push( color.getHex() );
  13090. return colorsHash[ hash ];
  13091. }
  13092. function getUvIndex( uv ) {
  13093. var hash = uv.x.toString() + uv.y.toString();
  13094. if ( uvsHash[ hash ] !== undefined ) {
  13095. return uvsHash[ hash ];
  13096. }
  13097. uvsHash[ hash ] = uvs.length / 2;
  13098. uvs.push( uv.x, uv.y );
  13099. return uvsHash[ hash ];
  13100. }
  13101. data.data = {};
  13102. data.data.vertices = vertices;
  13103. data.data.normals = normals;
  13104. if ( colors.length > 0 ) { data.data.colors = colors; }
  13105. if ( uvs.length > 0 ) { data.data.uvs = [ uvs ]; } // temporal backward compatibility
  13106. data.data.faces = faces;
  13107. return data;
  13108. },
  13109. clone: function () {
  13110. /*
  13111. // Handle primitives
  13112. var parameters = this.parameters;
  13113. if ( parameters !== undefined ) {
  13114. var values = [];
  13115. for ( var key in parameters ) {
  13116. values.push( parameters[ key ] );
  13117. }
  13118. var geometry = Object.create( this.constructor.prototype );
  13119. this.constructor.apply( geometry, values );
  13120. return geometry;
  13121. }
  13122. return new this.constructor().copy( this );
  13123. */
  13124. return new Geometry().copy( this );
  13125. },
  13126. copy: function ( source ) {
  13127. var i, il, j, jl, k, kl;
  13128. // reset
  13129. this.vertices = [];
  13130. this.colors = [];
  13131. this.faces = [];
  13132. this.faceVertexUvs = [[]];
  13133. this.morphTargets = [];
  13134. this.morphNormals = [];
  13135. this.skinWeights = [];
  13136. this.skinIndices = [];
  13137. this.lineDistances = [];
  13138. this.boundingBox = null;
  13139. this.boundingSphere = null;
  13140. // name
  13141. this.name = source.name;
  13142. // vertices
  13143. var vertices = source.vertices;
  13144. for ( i = 0, il = vertices.length; i < il; i ++ ) {
  13145. this.vertices.push( vertices[ i ].clone() );
  13146. }
  13147. // colors
  13148. var colors = source.colors;
  13149. for ( i = 0, il = colors.length; i < il; i ++ ) {
  13150. this.colors.push( colors[ i ].clone() );
  13151. }
  13152. // faces
  13153. var faces = source.faces;
  13154. for ( i = 0, il = faces.length; i < il; i ++ ) {
  13155. this.faces.push( faces[ i ].clone() );
  13156. }
  13157. // face vertex uvs
  13158. for ( i = 0, il = source.faceVertexUvs.length; i < il; i ++ ) {
  13159. var faceVertexUvs = source.faceVertexUvs[ i ];
  13160. if ( this.faceVertexUvs[ i ] === undefined ) {
  13161. this.faceVertexUvs[ i ] = [];
  13162. }
  13163. for ( j = 0, jl = faceVertexUvs.length; j < jl; j ++ ) {
  13164. var uvs = faceVertexUvs[ j ], uvsCopy = [];
  13165. for ( k = 0, kl = uvs.length; k < kl; k ++ ) {
  13166. var uv = uvs[ k ];
  13167. uvsCopy.push( uv.clone() );
  13168. }
  13169. this.faceVertexUvs[ i ].push( uvsCopy );
  13170. }
  13171. }
  13172. // morph targets
  13173. var morphTargets = source.morphTargets;
  13174. for ( i = 0, il = morphTargets.length; i < il; i ++ ) {
  13175. var morphTarget = {};
  13176. morphTarget.name = morphTargets[ i ].name;
  13177. // vertices
  13178. if ( morphTargets[ i ].vertices !== undefined ) {
  13179. morphTarget.vertices = [];
  13180. for ( j = 0, jl = morphTargets[ i ].vertices.length; j < jl; j ++ ) {
  13181. morphTarget.vertices.push( morphTargets[ i ].vertices[ j ].clone() );
  13182. }
  13183. }
  13184. // normals
  13185. if ( morphTargets[ i ].normals !== undefined ) {
  13186. morphTarget.normals = [];
  13187. for ( j = 0, jl = morphTargets[ i ].normals.length; j < jl; j ++ ) {
  13188. morphTarget.normals.push( morphTargets[ i ].normals[ j ].clone() );
  13189. }
  13190. }
  13191. this.morphTargets.push( morphTarget );
  13192. }
  13193. // morph normals
  13194. var morphNormals = source.morphNormals;
  13195. for ( i = 0, il = morphNormals.length; i < il; i ++ ) {
  13196. var morphNormal = {};
  13197. // vertex normals
  13198. if ( morphNormals[ i ].vertexNormals !== undefined ) {
  13199. morphNormal.vertexNormals = [];
  13200. for ( j = 0, jl = morphNormals[ i ].vertexNormals.length; j < jl; j ++ ) {
  13201. var srcVertexNormal = morphNormals[ i ].vertexNormals[ j ];
  13202. var destVertexNormal = {};
  13203. destVertexNormal.a = srcVertexNormal.a.clone();
  13204. destVertexNormal.b = srcVertexNormal.b.clone();
  13205. destVertexNormal.c = srcVertexNormal.c.clone();
  13206. morphNormal.vertexNormals.push( destVertexNormal );
  13207. }
  13208. }
  13209. // face normals
  13210. if ( morphNormals[ i ].faceNormals !== undefined ) {
  13211. morphNormal.faceNormals = [];
  13212. for ( j = 0, jl = morphNormals[ i ].faceNormals.length; j < jl; j ++ ) {
  13213. morphNormal.faceNormals.push( morphNormals[ i ].faceNormals[ j ].clone() );
  13214. }
  13215. }
  13216. this.morphNormals.push( morphNormal );
  13217. }
  13218. // skin weights
  13219. var skinWeights = source.skinWeights;
  13220. for ( i = 0, il = skinWeights.length; i < il; i ++ ) {
  13221. this.skinWeights.push( skinWeights[ i ].clone() );
  13222. }
  13223. // skin indices
  13224. var skinIndices = source.skinIndices;
  13225. for ( i = 0, il = skinIndices.length; i < il; i ++ ) {
  13226. this.skinIndices.push( skinIndices[ i ].clone() );
  13227. }
  13228. // line distances
  13229. var lineDistances = source.lineDistances;
  13230. for ( i = 0, il = lineDistances.length; i < il; i ++ ) {
  13231. this.lineDistances.push( lineDistances[ i ] );
  13232. }
  13233. // bounding box
  13234. var boundingBox = source.boundingBox;
  13235. if ( boundingBox !== null ) {
  13236. this.boundingBox = boundingBox.clone();
  13237. }
  13238. // bounding sphere
  13239. var boundingSphere = source.boundingSphere;
  13240. if ( boundingSphere !== null ) {
  13241. this.boundingSphere = boundingSphere.clone();
  13242. }
  13243. // update flags
  13244. this.elementsNeedUpdate = source.elementsNeedUpdate;
  13245. this.verticesNeedUpdate = source.verticesNeedUpdate;
  13246. this.uvsNeedUpdate = source.uvsNeedUpdate;
  13247. this.normalsNeedUpdate = source.normalsNeedUpdate;
  13248. this.colorsNeedUpdate = source.colorsNeedUpdate;
  13249. this.lineDistancesNeedUpdate = source.lineDistancesNeedUpdate;
  13250. this.groupsNeedUpdate = source.groupsNeedUpdate;
  13251. return this;
  13252. },
  13253. dispose: function () {
  13254. this.dispatchEvent( { type: 'dispose' } );
  13255. }
  13256. } );
  13257. /**
  13258. * @author mrdoob / http://mrdoob.com/
  13259. * @author Mugen87 / https://github.com/Mugen87
  13260. */
  13261. // BoxGeometry
  13262. var BoxGeometry = /*@__PURE__*/(function (Geometry) {
  13263. function BoxGeometry( width, height, depth, widthSegments, heightSegments, depthSegments ) {
  13264. Geometry.call(this);
  13265. this.type = 'BoxGeometry';
  13266. this.parameters = {
  13267. width: width,
  13268. height: height,
  13269. depth: depth,
  13270. widthSegments: widthSegments,
  13271. heightSegments: heightSegments,
  13272. depthSegments: depthSegments
  13273. };
  13274. this.fromBufferGeometry( new BoxBufferGeometry( width, height, depth, widthSegments, heightSegments, depthSegments ) );
  13275. this.mergeVertices();
  13276. }
  13277. if ( Geometry ) BoxGeometry.__proto__ = Geometry;
  13278. BoxGeometry.prototype = Object.create( Geometry && Geometry.prototype );
  13279. BoxGeometry.prototype.constructor = BoxGeometry;
  13280. return BoxGeometry;
  13281. }(Geometry));
  13282. // BoxBufferGeometry
  13283. var BoxBufferGeometry = /*@__PURE__*/(function (BufferGeometry) {
  13284. function BoxBufferGeometry( width, height, depth, widthSegments, heightSegments, depthSegments ) {
  13285. BufferGeometry.call(this);
  13286. this.type = 'BoxBufferGeometry';
  13287. this.parameters = {
  13288. width: width,
  13289. height: height,
  13290. depth: depth,
  13291. widthSegments: widthSegments,
  13292. heightSegments: heightSegments,
  13293. depthSegments: depthSegments
  13294. };
  13295. var scope = this;
  13296. width = width || 1;
  13297. height = height || 1;
  13298. depth = depth || 1;
  13299. // segments
  13300. widthSegments = Math.floor( widthSegments ) || 1;
  13301. heightSegments = Math.floor( heightSegments ) || 1;
  13302. depthSegments = Math.floor( depthSegments ) || 1;
  13303. // buffers
  13304. var indices = [];
  13305. var vertices = [];
  13306. var normals = [];
  13307. var uvs = [];
  13308. // helper variables
  13309. var numberOfVertices = 0;
  13310. var groupStart = 0;
  13311. // build each side of the box geometry
  13312. buildPlane( 'z', 'y', 'x', - 1, - 1, depth, height, width, depthSegments, heightSegments, 0 ); // px
  13313. buildPlane( 'z', 'y', 'x', 1, - 1, depth, height, - width, depthSegments, heightSegments, 1 ); // nx
  13314. buildPlane( 'x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2 ); // py
  13315. buildPlane( 'x', 'z', 'y', 1, - 1, width, depth, - height, widthSegments, depthSegments, 3 ); // ny
  13316. buildPlane( 'x', 'y', 'z', 1, - 1, width, height, depth, widthSegments, heightSegments, 4 ); // pz
  13317. buildPlane( 'x', 'y', 'z', - 1, - 1, width, height, - depth, widthSegments, heightSegments, 5 ); // nz
  13318. // build geometry
  13319. this.setIndex( indices );
  13320. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  13321. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  13322. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  13323. function buildPlane( u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex ) {
  13324. var segmentWidth = width / gridX;
  13325. var segmentHeight = height / gridY;
  13326. var widthHalf = width / 2;
  13327. var heightHalf = height / 2;
  13328. var depthHalf = depth / 2;
  13329. var gridX1 = gridX + 1;
  13330. var gridY1 = gridY + 1;
  13331. var vertexCounter = 0;
  13332. var groupCount = 0;
  13333. var ix, iy;
  13334. var vector = new Vector3();
  13335. // generate vertices, normals and uvs
  13336. for ( iy = 0; iy < gridY1; iy ++ ) {
  13337. var y = iy * segmentHeight - heightHalf;
  13338. for ( ix = 0; ix < gridX1; ix ++ ) {
  13339. var x = ix * segmentWidth - widthHalf;
  13340. // set values to correct vector component
  13341. vector[ u ] = x * udir;
  13342. vector[ v ] = y * vdir;
  13343. vector[ w ] = depthHalf;
  13344. // now apply vector to vertex buffer
  13345. vertices.push( vector.x, vector.y, vector.z );
  13346. // set values to correct vector component
  13347. vector[ u ] = 0;
  13348. vector[ v ] = 0;
  13349. vector[ w ] = depth > 0 ? 1 : - 1;
  13350. // now apply vector to normal buffer
  13351. normals.push( vector.x, vector.y, vector.z );
  13352. // uvs
  13353. uvs.push( ix / gridX );
  13354. uvs.push( 1 - ( iy / gridY ) );
  13355. // counters
  13356. vertexCounter += 1;
  13357. }
  13358. }
  13359. // indices
  13360. // 1. you need three indices to draw a single face
  13361. // 2. a single segment consists of two faces
  13362. // 3. so we need to generate six (2*3) indices per segment
  13363. for ( iy = 0; iy < gridY; iy ++ ) {
  13364. for ( ix = 0; ix < gridX; ix ++ ) {
  13365. var a = numberOfVertices + ix + gridX1 * iy;
  13366. var b = numberOfVertices + ix + gridX1 * ( iy + 1 );
  13367. var c = numberOfVertices + ( ix + 1 ) + gridX1 * ( iy + 1 );
  13368. var d = numberOfVertices + ( ix + 1 ) + gridX1 * iy;
  13369. // faces
  13370. indices.push( a, b, d );
  13371. indices.push( b, c, d );
  13372. // increase counter
  13373. groupCount += 6;
  13374. }
  13375. }
  13376. // add a group to the geometry. this will ensure multi material support
  13377. scope.addGroup( groupStart, groupCount, materialIndex );
  13378. // calculate new start value for groups
  13379. groupStart += groupCount;
  13380. // update total number of vertices
  13381. numberOfVertices += vertexCounter;
  13382. }
  13383. }
  13384. if ( BufferGeometry ) BoxBufferGeometry.__proto__ = BufferGeometry;
  13385. BoxBufferGeometry.prototype = Object.create( BufferGeometry && BufferGeometry.prototype );
  13386. BoxBufferGeometry.prototype.constructor = BoxBufferGeometry;
  13387. return BoxBufferGeometry;
  13388. }(BufferGeometry));
  13389. /**
  13390. * Uniform Utilities
  13391. */
  13392. function cloneUniforms( src ) {
  13393. var dst = {};
  13394. for ( var u in src ) {
  13395. dst[ u ] = {};
  13396. for ( var p in src[ u ] ) {
  13397. var property = src[ u ][ p ];
  13398. if ( property && ( property.isColor ||
  13399. property.isMatrix3 || property.isMatrix4 ||
  13400. property.isVector2 || property.isVector3 || property.isVector4 ||
  13401. property.isTexture ) ) {
  13402. dst[ u ][ p ] = property.clone();
  13403. } else if ( Array.isArray( property ) ) {
  13404. dst[ u ][ p ] = property.slice();
  13405. } else {
  13406. dst[ u ][ p ] = property;
  13407. }
  13408. }
  13409. }
  13410. return dst;
  13411. }
  13412. function mergeUniforms( uniforms ) {
  13413. var merged = {};
  13414. for ( var u = 0; u < uniforms.length; u ++ ) {
  13415. var tmp = cloneUniforms( uniforms[ u ] );
  13416. for ( var p in tmp ) {
  13417. merged[ p ] = tmp[ p ];
  13418. }
  13419. }
  13420. return merged;
  13421. }
  13422. // Legacy
  13423. var UniformsUtils = { clone: cloneUniforms, merge: mergeUniforms };
  13424. var default_vertex = "void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}";
  13425. var default_fragment = "void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}";
  13426. /**
  13427. * @author alteredq / http://alteredqualia.com/
  13428. *
  13429. * parameters = {
  13430. * defines: { "label" : "value" },
  13431. * uniforms: { "parameter1": { value: 1.0 }, "parameter2": { value2: 2 } },
  13432. *
  13433. * fragmentShader: <string>,
  13434. * vertexShader: <string>,
  13435. *
  13436. * wireframe: <boolean>,
  13437. * wireframeLinewidth: <float>,
  13438. *
  13439. * lights: <bool>,
  13440. *
  13441. * skinning: <bool>,
  13442. * morphTargets: <bool>,
  13443. * morphNormals: <bool>
  13444. * }
  13445. */
  13446. function ShaderMaterial( parameters ) {
  13447. Material.call( this );
  13448. this.type = 'ShaderMaterial';
  13449. this.defines = {};
  13450. this.uniforms = {};
  13451. this.vertexShader = default_vertex;
  13452. this.fragmentShader = default_fragment;
  13453. this.linewidth = 1;
  13454. this.wireframe = false;
  13455. this.wireframeLinewidth = 1;
  13456. this.fog = false; // set to use scene fog
  13457. this.lights = false; // set to use scene lights
  13458. this.clipping = false; // set to use user-defined clipping planes
  13459. this.skinning = false; // set to use skinning attribute streams
  13460. this.morphTargets = false; // set to use morph targets
  13461. this.morphNormals = false; // set to use morph normals
  13462. this.extensions = {
  13463. derivatives: false, // set to use derivatives
  13464. fragDepth: false, // set to use fragment depth values
  13465. drawBuffers: false, // set to use draw buffers
  13466. shaderTextureLOD: false // set to use shader texture LOD
  13467. };
  13468. // When rendered geometry doesn't include these attributes but the material does,
  13469. // use these default values in WebGL. This avoids errors when buffer data is missing.
  13470. this.defaultAttributeValues = {
  13471. 'color': [ 1, 1, 1 ],
  13472. 'uv': [ 0, 0 ],
  13473. 'uv2': [ 0, 0 ]
  13474. };
  13475. this.index0AttributeName = undefined;
  13476. this.uniformsNeedUpdate = false;
  13477. if ( parameters !== undefined ) {
  13478. if ( parameters.attributes !== undefined ) {
  13479. console.error( 'THREE.ShaderMaterial: attributes should now be defined in THREE.BufferGeometry instead.' );
  13480. }
  13481. this.setValues( parameters );
  13482. }
  13483. }
  13484. ShaderMaterial.prototype = Object.create( Material.prototype );
  13485. ShaderMaterial.prototype.constructor = ShaderMaterial;
  13486. ShaderMaterial.prototype.isShaderMaterial = true;
  13487. ShaderMaterial.prototype.copy = function ( source ) {
  13488. Material.prototype.copy.call( this, source );
  13489. this.fragmentShader = source.fragmentShader;
  13490. this.vertexShader = source.vertexShader;
  13491. this.uniforms = cloneUniforms( source.uniforms );
  13492. this.defines = Object.assign( {}, source.defines );
  13493. this.wireframe = source.wireframe;
  13494. this.wireframeLinewidth = source.wireframeLinewidth;
  13495. this.lights = source.lights;
  13496. this.clipping = source.clipping;
  13497. this.skinning = source.skinning;
  13498. this.morphTargets = source.morphTargets;
  13499. this.morphNormals = source.morphNormals;
  13500. this.extensions = source.extensions;
  13501. return this;
  13502. };
  13503. ShaderMaterial.prototype.toJSON = function ( meta ) {
  13504. var data = Material.prototype.toJSON.call( this, meta );
  13505. data.uniforms = {};
  13506. for ( var name in this.uniforms ) {
  13507. var uniform = this.uniforms[ name ];
  13508. var value = uniform.value;
  13509. if ( value && value.isTexture ) {
  13510. data.uniforms[ name ] = {
  13511. type: 't',
  13512. value: value.toJSON( meta ).uuid
  13513. };
  13514. } else if ( value && value.isColor ) {
  13515. data.uniforms[ name ] = {
  13516. type: 'c',
  13517. value: value.getHex()
  13518. };
  13519. } else if ( value && value.isVector2 ) {
  13520. data.uniforms[ name ] = {
  13521. type: 'v2',
  13522. value: value.toArray()
  13523. };
  13524. } else if ( value && value.isVector3 ) {
  13525. data.uniforms[ name ] = {
  13526. type: 'v3',
  13527. value: value.toArray()
  13528. };
  13529. } else if ( value && value.isVector4 ) {
  13530. data.uniforms[ name ] = {
  13531. type: 'v4',
  13532. value: value.toArray()
  13533. };
  13534. } else if ( value && value.isMatrix3 ) {
  13535. data.uniforms[ name ] = {
  13536. type: 'm3',
  13537. value: value.toArray()
  13538. };
  13539. } else if ( value && value.isMatrix4 ) {
  13540. data.uniforms[ name ] = {
  13541. type: 'm4',
  13542. value: value.toArray()
  13543. };
  13544. } else {
  13545. data.uniforms[ name ] = {
  13546. value: value
  13547. };
  13548. // note: the array variants v2v, v3v, v4v, m4v and tv are not supported so far
  13549. }
  13550. }
  13551. if ( Object.keys( this.defines ).length > 0 ) { data.defines = this.defines; }
  13552. data.vertexShader = this.vertexShader;
  13553. data.fragmentShader = this.fragmentShader;
  13554. var extensions = {};
  13555. for ( var key in this.extensions ) {
  13556. if ( this.extensions[ key ] === true ) { extensions[ key ] = true; }
  13557. }
  13558. if ( Object.keys( extensions ).length > 0 ) { data.extensions = extensions; }
  13559. return data;
  13560. };
  13561. /**
  13562. * @author mrdoob / http://mrdoob.com/
  13563. * @author mikael emtinger / http://gomo.se/
  13564. * @author WestLangley / http://github.com/WestLangley
  13565. */
  13566. function Camera() {
  13567. Object3D.call( this );
  13568. this.type = 'Camera';
  13569. this.matrixWorldInverse = new Matrix4();
  13570. this.projectionMatrix = new Matrix4();
  13571. this.projectionMatrixInverse = new Matrix4();
  13572. }
  13573. Camera.prototype = Object.assign( Object.create( Object3D.prototype ), {
  13574. constructor: Camera,
  13575. isCamera: true,
  13576. copy: function ( source, recursive ) {
  13577. Object3D.prototype.copy.call( this, source, recursive );
  13578. this.matrixWorldInverse.copy( source.matrixWorldInverse );
  13579. this.projectionMatrix.copy( source.projectionMatrix );
  13580. this.projectionMatrixInverse.copy( source.projectionMatrixInverse );
  13581. return this;
  13582. },
  13583. getWorldDirection: function ( target ) {
  13584. if ( target === undefined ) {
  13585. console.warn( 'THREE.Camera: .getWorldDirection() target is now required' );
  13586. target = new Vector3();
  13587. }
  13588. this.updateMatrixWorld( true );
  13589. var e = this.matrixWorld.elements;
  13590. return target.set( - e[ 8 ], - e[ 9 ], - e[ 10 ] ).normalize();
  13591. },
  13592. updateMatrixWorld: function ( force ) {
  13593. Object3D.prototype.updateMatrixWorld.call( this, force );
  13594. this.matrixWorldInverse.getInverse( this.matrixWorld );
  13595. },
  13596. updateWorldMatrix: function ( updateParents, updateChildren ) {
  13597. Object3D.prototype.updateWorldMatrix.call( this, updateParents, updateChildren );
  13598. this.matrixWorldInverse.getInverse( this.matrixWorld );
  13599. },
  13600. clone: function () {
  13601. return new this.constructor().copy( this );
  13602. }
  13603. } );
  13604. /**
  13605. * @author mrdoob / http://mrdoob.com/
  13606. * @author greggman / http://games.greggman.com/
  13607. * @author zz85 / http://www.lab4games.net/zz85/blog
  13608. * @author tschw
  13609. */
  13610. function PerspectiveCamera( fov, aspect, near, far ) {
  13611. Camera.call( this );
  13612. this.type = 'PerspectiveCamera';
  13613. this.fov = fov !== undefined ? fov : 50;
  13614. this.zoom = 1;
  13615. this.near = near !== undefined ? near : 0.1;
  13616. this.far = far !== undefined ? far : 2000;
  13617. this.focus = 10;
  13618. this.aspect = aspect !== undefined ? aspect : 1;
  13619. this.view = null;
  13620. this.filmGauge = 35; // width of the film (default in millimeters)
  13621. this.filmOffset = 0; // horizontal film offset (same unit as gauge)
  13622. this.updateProjectionMatrix();
  13623. }
  13624. PerspectiveCamera.prototype = Object.assign( Object.create( Camera.prototype ), {
  13625. constructor: PerspectiveCamera,
  13626. isPerspectiveCamera: true,
  13627. copy: function ( source, recursive ) {
  13628. Camera.prototype.copy.call( this, source, recursive );
  13629. this.fov = source.fov;
  13630. this.zoom = source.zoom;
  13631. this.near = source.near;
  13632. this.far = source.far;
  13633. this.focus = source.focus;
  13634. this.aspect = source.aspect;
  13635. this.view = source.view === null ? null : Object.assign( {}, source.view );
  13636. this.filmGauge = source.filmGauge;
  13637. this.filmOffset = source.filmOffset;
  13638. return this;
  13639. },
  13640. /**
  13641. * Sets the FOV by focal length in respect to the current .filmGauge.
  13642. *
  13643. * The default film gauge is 35, so that the focal length can be specified for
  13644. * a 35mm (full frame) camera.
  13645. *
  13646. * Values for focal length and film gauge must have the same unit.
  13647. */
  13648. setFocalLength: function ( focalLength ) {
  13649. // see http://www.bobatkins.com/photography/technical/field_of_view.html
  13650. var vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
  13651. this.fov = MathUtils.RAD2DEG * 2 * Math.atan( vExtentSlope );
  13652. this.updateProjectionMatrix();
  13653. },
  13654. /**
  13655. * Calculates the focal length from the current .fov and .filmGauge.
  13656. */
  13657. getFocalLength: function () {
  13658. var vExtentSlope = Math.tan( MathUtils.DEG2RAD * 0.5 * this.fov );
  13659. return 0.5 * this.getFilmHeight() / vExtentSlope;
  13660. },
  13661. getEffectiveFOV: function () {
  13662. return MathUtils.RAD2DEG * 2 * Math.atan(
  13663. Math.tan( MathUtils.DEG2RAD * 0.5 * this.fov ) / this.zoom );
  13664. },
  13665. getFilmWidth: function () {
  13666. // film not completely covered in portrait format (aspect < 1)
  13667. return this.filmGauge * Math.min( this.aspect, 1 );
  13668. },
  13669. getFilmHeight: function () {
  13670. // film not completely covered in landscape format (aspect > 1)
  13671. return this.filmGauge / Math.max( this.aspect, 1 );
  13672. },
  13673. /**
  13674. * Sets an offset in a larger frustum. This is useful for multi-window or
  13675. * multi-monitor/multi-machine setups.
  13676. *
  13677. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  13678. * the monitors are in grid like this
  13679. *
  13680. * +---+---+---+
  13681. * | A | B | C |
  13682. * +---+---+---+
  13683. * | D | E | F |
  13684. * +---+---+---+
  13685. *
  13686. * then for each monitor you would call it like this
  13687. *
  13688. * var w = 1920;
  13689. * var h = 1080;
  13690. * var fullWidth = w * 3;
  13691. * var fullHeight = h * 2;
  13692. *
  13693. * --A--
  13694. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  13695. * --B--
  13696. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  13697. * --C--
  13698. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  13699. * --D--
  13700. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  13701. * --E--
  13702. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  13703. * --F--
  13704. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  13705. *
  13706. * Note there is no reason monitors have to be the same size or in a grid.
  13707. */
  13708. setViewOffset: function ( fullWidth, fullHeight, x, y, width, height ) {
  13709. this.aspect = fullWidth / fullHeight;
  13710. if ( this.view === null ) {
  13711. this.view = {
  13712. enabled: true,
  13713. fullWidth: 1,
  13714. fullHeight: 1,
  13715. offsetX: 0,
  13716. offsetY: 0,
  13717. width: 1,
  13718. height: 1
  13719. };
  13720. }
  13721. this.view.enabled = true;
  13722. this.view.fullWidth = fullWidth;
  13723. this.view.fullHeight = fullHeight;
  13724. this.view.offsetX = x;
  13725. this.view.offsetY = y;
  13726. this.view.width = width;
  13727. this.view.height = height;
  13728. this.updateProjectionMatrix();
  13729. },
  13730. clearViewOffset: function () {
  13731. if ( this.view !== null ) {
  13732. this.view.enabled = false;
  13733. }
  13734. this.updateProjectionMatrix();
  13735. },
  13736. updateProjectionMatrix: function () {
  13737. var near = this.near,
  13738. top = near * Math.tan( MathUtils.DEG2RAD * 0.5 * this.fov ) / this.zoom,
  13739. height = 2 * top,
  13740. width = this.aspect * height,
  13741. left = - 0.5 * width,
  13742. view = this.view;
  13743. if ( this.view !== null && this.view.enabled ) {
  13744. var fullWidth = view.fullWidth,
  13745. fullHeight = view.fullHeight;
  13746. left += view.offsetX * width / fullWidth;
  13747. top -= view.offsetY * height / fullHeight;
  13748. width *= view.width / fullWidth;
  13749. height *= view.height / fullHeight;
  13750. }
  13751. var skew = this.filmOffset;
  13752. if ( skew !== 0 ) { left += near * skew / this.getFilmWidth(); }
  13753. this.projectionMatrix.makePerspective( left, left + width, top, top - height, near, this.far );
  13754. this.projectionMatrixInverse.getInverse( this.projectionMatrix );
  13755. },
  13756. toJSON: function ( meta ) {
  13757. var data = Object3D.prototype.toJSON.call( this, meta );
  13758. data.object.fov = this.fov;
  13759. data.object.zoom = this.zoom;
  13760. data.object.near = this.near;
  13761. data.object.far = this.far;
  13762. data.object.focus = this.focus;
  13763. data.object.aspect = this.aspect;
  13764. if ( this.view !== null ) { data.object.view = Object.assign( {}, this.view ); }
  13765. data.object.filmGauge = this.filmGauge;
  13766. data.object.filmOffset = this.filmOffset;
  13767. return data;
  13768. }
  13769. } );
  13770. /**
  13771. * Camera for rendering cube maps
  13772. * - renders scene into axis-aligned cube
  13773. *
  13774. * @author alteredq / http://alteredqualia.com/
  13775. */
  13776. var fov = 90, aspect = 1;
  13777. function CubeCamera( near, far, cubeResolution, options ) {
  13778. Object3D.call( this );
  13779. this.type = 'CubeCamera';
  13780. var cameraPX = new PerspectiveCamera( fov, aspect, near, far );
  13781. cameraPX.up.set( 0, - 1, 0 );
  13782. cameraPX.lookAt( new Vector3( 1, 0, 0 ) );
  13783. this.add( cameraPX );
  13784. var cameraNX = new PerspectiveCamera( fov, aspect, near, far );
  13785. cameraNX.up.set( 0, - 1, 0 );
  13786. cameraNX.lookAt( new Vector3( - 1, 0, 0 ) );
  13787. this.add( cameraNX );
  13788. var cameraPY = new PerspectiveCamera( fov, aspect, near, far );
  13789. cameraPY.up.set( 0, 0, 1 );
  13790. cameraPY.lookAt( new Vector3( 0, 1, 0 ) );
  13791. this.add( cameraPY );
  13792. var cameraNY = new PerspectiveCamera( fov, aspect, near, far );
  13793. cameraNY.up.set( 0, 0, - 1 );
  13794. cameraNY.lookAt( new Vector3( 0, - 1, 0 ) );
  13795. this.add( cameraNY );
  13796. var cameraPZ = new PerspectiveCamera( fov, aspect, near, far );
  13797. cameraPZ.up.set( 0, - 1, 0 );
  13798. cameraPZ.lookAt( new Vector3( 0, 0, 1 ) );
  13799. this.add( cameraPZ );
  13800. var cameraNZ = new PerspectiveCamera( fov, aspect, near, far );
  13801. cameraNZ.up.set( 0, - 1, 0 );
  13802. cameraNZ.lookAt( new Vector3( 0, 0, - 1 ) );
  13803. this.add( cameraNZ );
  13804. options = options || { format: RGBFormat, magFilter: LinearFilter, minFilter: LinearFilter };
  13805. this.renderTarget = new WebGLCubeRenderTarget( cubeResolution, options );
  13806. this.renderTarget.texture.name = "CubeCamera";
  13807. this.update = function ( renderer, scene ) {
  13808. if ( this.parent === null ) { this.updateMatrixWorld(); }
  13809. var currentRenderTarget = renderer.getRenderTarget();
  13810. var renderTarget = this.renderTarget;
  13811. var generateMipmaps = renderTarget.texture.generateMipmaps;
  13812. renderTarget.texture.generateMipmaps = false;
  13813. renderer.setRenderTarget( renderTarget, 0 );
  13814. renderer.render( scene, cameraPX );
  13815. renderer.setRenderTarget( renderTarget, 1 );
  13816. renderer.render( scene, cameraNX );
  13817. renderer.setRenderTarget( renderTarget, 2 );
  13818. renderer.render( scene, cameraPY );
  13819. renderer.setRenderTarget( renderTarget, 3 );
  13820. renderer.render( scene, cameraNY );
  13821. renderer.setRenderTarget( renderTarget, 4 );
  13822. renderer.render( scene, cameraPZ );
  13823. renderTarget.texture.generateMipmaps = generateMipmaps;
  13824. renderer.setRenderTarget( renderTarget, 5 );
  13825. renderer.render( scene, cameraNZ );
  13826. renderer.setRenderTarget( currentRenderTarget );
  13827. };
  13828. this.clear = function ( renderer, color, depth, stencil ) {
  13829. var currentRenderTarget = renderer.getRenderTarget();
  13830. var renderTarget = this.renderTarget;
  13831. for ( var i = 0; i < 6; i ++ ) {
  13832. renderer.setRenderTarget( renderTarget, i );
  13833. renderer.clear( color, depth, stencil );
  13834. }
  13835. renderer.setRenderTarget( currentRenderTarget );
  13836. };
  13837. }
  13838. CubeCamera.prototype = Object.create( Object3D.prototype );
  13839. CubeCamera.prototype.constructor = CubeCamera;
  13840. /**
  13841. * @author alteredq / http://alteredqualia.com
  13842. * @author WestLangley / http://github.com/WestLangley
  13843. */
  13844. function WebGLCubeRenderTarget( size, options, dummy ) {
  13845. if ( Number.isInteger( options ) ) {
  13846. console.warn( 'THREE.WebGLCubeRenderTarget: constructor signature is now WebGLCubeRenderTarget( size, options )' );
  13847. options = dummy;
  13848. }
  13849. WebGLRenderTarget.call( this, size, size, options );
  13850. }
  13851. WebGLCubeRenderTarget.prototype = Object.create( WebGLRenderTarget.prototype );
  13852. WebGLCubeRenderTarget.prototype.constructor = WebGLCubeRenderTarget;
  13853. WebGLCubeRenderTarget.prototype.isWebGLCubeRenderTarget = true;
  13854. WebGLCubeRenderTarget.prototype.fromEquirectangularTexture = function ( renderer, texture ) {
  13855. this.texture.type = texture.type;
  13856. this.texture.format = texture.format;
  13857. this.texture.encoding = texture.encoding;
  13858. var scene = new Scene();
  13859. var shader = {
  13860. uniforms: {
  13861. tEquirect: { value: null },
  13862. },
  13863. vertexShader: [
  13864. "varying vec3 vWorldDirection;",
  13865. "vec3 transformDirection( in vec3 dir, in mat4 matrix ) {",
  13866. " return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );",
  13867. "}",
  13868. "void main() {",
  13869. " vWorldDirection = transformDirection( position, modelMatrix );",
  13870. " #include <begin_vertex>",
  13871. " #include <project_vertex>",
  13872. "}"
  13873. ].join( '\n' ),
  13874. fragmentShader: [
  13875. "uniform sampler2D tEquirect;",
  13876. "varying vec3 vWorldDirection;",
  13877. "#define RECIPROCAL_PI 0.31830988618",
  13878. "#define RECIPROCAL_PI2 0.15915494",
  13879. "void main() {",
  13880. " vec3 direction = normalize( vWorldDirection );",
  13881. " vec2 sampleUV;",
  13882. " sampleUV.y = asin( clamp( direction.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;",
  13883. " sampleUV.x = atan( direction.z, direction.x ) * RECIPROCAL_PI2 + 0.5;",
  13884. " gl_FragColor = texture2D( tEquirect, sampleUV );",
  13885. "}"
  13886. ].join( '\n' ),
  13887. };
  13888. var material = new ShaderMaterial( {
  13889. type: 'CubemapFromEquirect',
  13890. uniforms: cloneUniforms( shader.uniforms ),
  13891. vertexShader: shader.vertexShader,
  13892. fragmentShader: shader.fragmentShader,
  13893. side: BackSide,
  13894. blending: NoBlending
  13895. } );
  13896. material.uniforms.tEquirect.value = texture;
  13897. var mesh = new Mesh( new BoxBufferGeometry( 5, 5, 5 ), material );
  13898. scene.add( mesh );
  13899. var camera = new CubeCamera( 1, 10, 1 );
  13900. camera.renderTarget = this;
  13901. camera.renderTarget.texture.name = 'CubeCameraTexture';
  13902. camera.update( renderer, scene );
  13903. mesh.geometry.dispose();
  13904. mesh.material.dispose();
  13905. return this;
  13906. };
  13907. /**
  13908. * @author alteredq / http://alteredqualia.com/
  13909. */
  13910. function DataTexture( data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding ) {
  13911. Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  13912. this.image = { data: data || null, width: width || 1, height: height || 1 };
  13913. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  13914. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  13915. this.generateMipmaps = false;
  13916. this.flipY = false;
  13917. this.unpackAlignment = 1;
  13918. this.needsUpdate = true;
  13919. }
  13920. DataTexture.prototype = Object.create( Texture.prototype );
  13921. DataTexture.prototype.constructor = DataTexture;
  13922. DataTexture.prototype.isDataTexture = true;
  13923. /**
  13924. * @author mrdoob / http://mrdoob.com/
  13925. * @author alteredq / http://alteredqualia.com/
  13926. * @author bhouston / http://clara.io
  13927. */
  13928. var _sphere$1 = new Sphere();
  13929. var _vector$5 = new Vector3();
  13930. function Frustum( p0, p1, p2, p3, p4, p5 ) {
  13931. this.planes = [
  13932. ( p0 !== undefined ) ? p0 : new Plane(),
  13933. ( p1 !== undefined ) ? p1 : new Plane(),
  13934. ( p2 !== undefined ) ? p2 : new Plane(),
  13935. ( p3 !== undefined ) ? p3 : new Plane(),
  13936. ( p4 !== undefined ) ? p4 : new Plane(),
  13937. ( p5 !== undefined ) ? p5 : new Plane()
  13938. ];
  13939. }
  13940. Object.assign( Frustum.prototype, {
  13941. set: function ( p0, p1, p2, p3, p4, p5 ) {
  13942. var planes = this.planes;
  13943. planes[ 0 ].copy( p0 );
  13944. planes[ 1 ].copy( p1 );
  13945. planes[ 2 ].copy( p2 );
  13946. planes[ 3 ].copy( p3 );
  13947. planes[ 4 ].copy( p4 );
  13948. planes[ 5 ].copy( p5 );
  13949. return this;
  13950. },
  13951. clone: function () {
  13952. return new this.constructor().copy( this );
  13953. },
  13954. copy: function ( frustum ) {
  13955. var planes = this.planes;
  13956. for ( var i = 0; i < 6; i ++ ) {
  13957. planes[ i ].copy( frustum.planes[ i ] );
  13958. }
  13959. return this;
  13960. },
  13961. setFromProjectionMatrix: function ( m ) {
  13962. var planes = this.planes;
  13963. var me = m.elements;
  13964. var me0 = me[ 0 ], me1 = me[ 1 ], me2 = me[ 2 ], me3 = me[ 3 ];
  13965. var me4 = me[ 4 ], me5 = me[ 5 ], me6 = me[ 6 ], me7 = me[ 7 ];
  13966. var me8 = me[ 8 ], me9 = me[ 9 ], me10 = me[ 10 ], me11 = me[ 11 ];
  13967. var me12 = me[ 12 ], me13 = me[ 13 ], me14 = me[ 14 ], me15 = me[ 15 ];
  13968. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  13969. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  13970. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  13971. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  13972. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize();
  13973. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize();
  13974. return this;
  13975. },
  13976. intersectsObject: function ( object ) {
  13977. var geometry = object.geometry;
  13978. if ( geometry.boundingSphere === null ) { geometry.computeBoundingSphere(); }
  13979. _sphere$1.copy( geometry.boundingSphere ).applyMatrix4( object.matrixWorld );
  13980. return this.intersectsSphere( _sphere$1 );
  13981. },
  13982. intersectsSprite: function ( sprite ) {
  13983. _sphere$1.center.set( 0, 0, 0 );
  13984. _sphere$1.radius = 0.7071067811865476;
  13985. _sphere$1.applyMatrix4( sprite.matrixWorld );
  13986. return this.intersectsSphere( _sphere$1 );
  13987. },
  13988. intersectsSphere: function ( sphere ) {
  13989. var planes = this.planes;
  13990. var center = sphere.center;
  13991. var negRadius = - sphere.radius;
  13992. for ( var i = 0; i < 6; i ++ ) {
  13993. var distance = planes[ i ].distanceToPoint( center );
  13994. if ( distance < negRadius ) {
  13995. return false;
  13996. }
  13997. }
  13998. return true;
  13999. },
  14000. intersectsBox: function ( box ) {
  14001. var planes = this.planes;
  14002. for ( var i = 0; i < 6; i ++ ) {
  14003. var plane = planes[ i ];
  14004. // corner at max distance
  14005. _vector$5.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  14006. _vector$5.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  14007. _vector$5.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  14008. if ( plane.distanceToPoint( _vector$5 ) < 0 ) {
  14009. return false;
  14010. }
  14011. }
  14012. return true;
  14013. },
  14014. containsPoint: function ( point ) {
  14015. var planes = this.planes;
  14016. for ( var i = 0; i < 6; i ++ ) {
  14017. if ( planes[ i ].distanceToPoint( point ) < 0 ) {
  14018. return false;
  14019. }
  14020. }
  14021. return true;
  14022. }
  14023. } );
  14024. /**
  14025. * Uniforms library for shared webgl shaders
  14026. */
  14027. var UniformsLib = {
  14028. common: {
  14029. diffuse: { value: new Color( 0xeeeeee ) },
  14030. opacity: { value: 1.0 },
  14031. map: { value: null },
  14032. uvTransform: { value: new Matrix3() },
  14033. uv2Transform: { value: new Matrix3() },
  14034. alphaMap: { value: null },
  14035. },
  14036. specularmap: {
  14037. specularMap: { value: null },
  14038. },
  14039. envmap: {
  14040. envMap: { value: null },
  14041. flipEnvMap: { value: - 1 },
  14042. reflectivity: { value: 1.0 },
  14043. refractionRatio: { value: 0.98 },
  14044. maxMipLevel: { value: 0 }
  14045. },
  14046. aomap: {
  14047. aoMap: { value: null },
  14048. aoMapIntensity: { value: 1 }
  14049. },
  14050. lightmap: {
  14051. lightMap: { value: null },
  14052. lightMapIntensity: { value: 1 }
  14053. },
  14054. emissivemap: {
  14055. emissiveMap: { value: null }
  14056. },
  14057. bumpmap: {
  14058. bumpMap: { value: null },
  14059. bumpScale: { value: 1 }
  14060. },
  14061. normalmap: {
  14062. normalMap: { value: null },
  14063. normalScale: { value: new Vector2( 1, 1 ) }
  14064. },
  14065. displacementmap: {
  14066. displacementMap: { value: null },
  14067. displacementScale: { value: 1 },
  14068. displacementBias: { value: 0 }
  14069. },
  14070. roughnessmap: {
  14071. roughnessMap: { value: null }
  14072. },
  14073. metalnessmap: {
  14074. metalnessMap: { value: null }
  14075. },
  14076. gradientmap: {
  14077. gradientMap: { value: null }
  14078. },
  14079. fog: {
  14080. fogDensity: { value: 0.00025 },
  14081. fogNear: { value: 1 },
  14082. fogFar: { value: 2000 },
  14083. fogColor: { value: new Color( 0xffffff ) }
  14084. },
  14085. lights: {
  14086. ambientLightColor: { value: [] },
  14087. lightProbe: { value: [] },
  14088. directionalLights: { value: [], properties: {
  14089. direction: {},
  14090. color: {}
  14091. } },
  14092. directionalLightShadows: { value: [], properties: {
  14093. shadowBias: {},
  14094. shadowRadius: {},
  14095. shadowMapSize: {}
  14096. } },
  14097. directionalShadowMap: { value: [] },
  14098. directionalShadowMatrix: { value: [] },
  14099. spotLights: { value: [], properties: {
  14100. color: {},
  14101. position: {},
  14102. direction: {},
  14103. distance: {},
  14104. coneCos: {},
  14105. penumbraCos: {},
  14106. decay: {}
  14107. } },
  14108. spotLightShadows: { value: [], properties: {
  14109. shadowBias: {},
  14110. shadowRadius: {},
  14111. shadowMapSize: {}
  14112. } },
  14113. spotShadowMap: { value: [] },
  14114. spotShadowMatrix: { value: [] },
  14115. pointLights: { value: [], properties: {
  14116. color: {},
  14117. position: {},
  14118. decay: {},
  14119. distance: {}
  14120. } },
  14121. pointLightShadows: { value: [], properties: {
  14122. shadowBias: {},
  14123. shadowRadius: {},
  14124. shadowMapSize: {},
  14125. shadowCameraNear: {},
  14126. shadowCameraFar: {}
  14127. } },
  14128. pointShadowMap: { value: [] },
  14129. pointShadowMatrix: { value: [] },
  14130. hemisphereLights: { value: [], properties: {
  14131. direction: {},
  14132. skyColor: {},
  14133. groundColor: {}
  14134. } },
  14135. // TODO (abelnation): RectAreaLight BRDF data needs to be moved from example to main src
  14136. rectAreaLights: { value: [], properties: {
  14137. color: {},
  14138. position: {},
  14139. width: {},
  14140. height: {}
  14141. } }
  14142. },
  14143. points: {
  14144. diffuse: { value: new Color( 0xeeeeee ) },
  14145. opacity: { value: 1.0 },
  14146. size: { value: 1.0 },
  14147. scale: { value: 1.0 },
  14148. map: { value: null },
  14149. alphaMap: { value: null },
  14150. uvTransform: { value: new Matrix3() }
  14151. },
  14152. sprite: {
  14153. diffuse: { value: new Color( 0xeeeeee ) },
  14154. opacity: { value: 1.0 },
  14155. center: { value: new Vector2( 0.5, 0.5 ) },
  14156. rotation: { value: 0.0 },
  14157. map: { value: null },
  14158. alphaMap: { value: null },
  14159. uvTransform: { value: new Matrix3() }
  14160. }
  14161. };
  14162. /**
  14163. * @author mrdoob / http://mrdoob.com/
  14164. */
  14165. function WebGLAnimation() {
  14166. var context = null;
  14167. var isAnimating = false;
  14168. var animationLoop = null;
  14169. function onAnimationFrame( time, frame ) {
  14170. if ( isAnimating === false ) { return; }
  14171. animationLoop( time, frame );
  14172. context.requestAnimationFrame( onAnimationFrame );
  14173. }
  14174. return {
  14175. start: function () {
  14176. if ( isAnimating === true ) { return; }
  14177. if ( animationLoop === null ) { return; }
  14178. context.requestAnimationFrame( onAnimationFrame );
  14179. isAnimating = true;
  14180. },
  14181. stop: function () {
  14182. isAnimating = false;
  14183. },
  14184. setAnimationLoop: function ( callback ) {
  14185. animationLoop = callback;
  14186. },
  14187. setContext: function ( value ) {
  14188. context = value;
  14189. }
  14190. };
  14191. }
  14192. /**
  14193. * @author mrdoob / http://mrdoob.com/
  14194. */
  14195. function WebGLAttributes( gl, capabilities ) {
  14196. var isWebGL2 = capabilities.isWebGL2;
  14197. var buffers = new WeakMap();
  14198. function createBuffer( attribute, bufferType ) {
  14199. var array = attribute.array;
  14200. var usage = attribute.usage;
  14201. var buffer = gl.createBuffer();
  14202. gl.bindBuffer( bufferType, buffer );
  14203. gl.bufferData( bufferType, array, usage );
  14204. attribute.onUploadCallback();
  14205. var type = 5126;
  14206. if ( array instanceof Float32Array ) {
  14207. type = 5126;
  14208. } else if ( array instanceof Float64Array ) {
  14209. console.warn( 'THREE.WebGLAttributes: Unsupported data buffer format: Float64Array.' );
  14210. } else if ( array instanceof Uint16Array ) {
  14211. type = 5123;
  14212. } else if ( array instanceof Int16Array ) {
  14213. type = 5122;
  14214. } else if ( array instanceof Uint32Array ) {
  14215. type = 5125;
  14216. } else if ( array instanceof Int32Array ) {
  14217. type = 5124;
  14218. } else if ( array instanceof Int8Array ) {
  14219. type = 5120;
  14220. } else if ( array instanceof Uint8Array ) {
  14221. type = 5121;
  14222. }
  14223. return {
  14224. buffer: buffer,
  14225. type: type,
  14226. bytesPerElement: array.BYTES_PER_ELEMENT,
  14227. version: attribute.version
  14228. };
  14229. }
  14230. function updateBuffer( buffer, attribute, bufferType ) {
  14231. var array = attribute.array;
  14232. var updateRange = attribute.updateRange;
  14233. gl.bindBuffer( bufferType, buffer );
  14234. if ( updateRange.count === - 1 ) {
  14235. // Not using update ranges
  14236. gl.bufferSubData( bufferType, 0, array );
  14237. } else {
  14238. if ( isWebGL2 ) {
  14239. gl.bufferSubData( bufferType, updateRange.offset * array.BYTES_PER_ELEMENT,
  14240. array, updateRange.offset, updateRange.count );
  14241. } else {
  14242. gl.bufferSubData( bufferType, updateRange.offset * array.BYTES_PER_ELEMENT,
  14243. array.subarray( updateRange.offset, updateRange.offset + updateRange.count ) );
  14244. }
  14245. updateRange.count = - 1; // reset range
  14246. }
  14247. }
  14248. //
  14249. function get( attribute ) {
  14250. if ( attribute.isInterleavedBufferAttribute ) { attribute = attribute.data; }
  14251. return buffers.get( attribute );
  14252. }
  14253. function remove( attribute ) {
  14254. if ( attribute.isInterleavedBufferAttribute ) { attribute = attribute.data; }
  14255. var data = buffers.get( attribute );
  14256. if ( data ) {
  14257. gl.deleteBuffer( data.buffer );
  14258. buffers.delete( attribute );
  14259. }
  14260. }
  14261. function update( attribute, bufferType ) {
  14262. if ( attribute.isInterleavedBufferAttribute ) { attribute = attribute.data; }
  14263. var data = buffers.get( attribute );
  14264. if ( data === undefined ) {
  14265. buffers.set( attribute, createBuffer( attribute, bufferType ) );
  14266. } else if ( data.version < attribute.version ) {
  14267. updateBuffer( data.buffer, attribute, bufferType );
  14268. data.version = attribute.version;
  14269. }
  14270. }
  14271. return {
  14272. get: get,
  14273. remove: remove,
  14274. update: update
  14275. };
  14276. }
  14277. /**
  14278. * @author mrdoob / http://mrdoob.com/
  14279. * @author Mugen87 / https://github.com/Mugen87
  14280. */
  14281. // PlaneGeometry
  14282. function PlaneGeometry( width, height, widthSegments, heightSegments ) {
  14283. Geometry.call( this );
  14284. this.type = 'PlaneGeometry';
  14285. this.parameters = {
  14286. width: width,
  14287. height: height,
  14288. widthSegments: widthSegments,
  14289. heightSegments: heightSegments
  14290. };
  14291. this.fromBufferGeometry( new PlaneBufferGeometry( width, height, widthSegments, heightSegments ) );
  14292. this.mergeVertices();
  14293. }
  14294. PlaneGeometry.prototype = Object.create( Geometry.prototype );
  14295. PlaneGeometry.prototype.constructor = PlaneGeometry;
  14296. // PlaneBufferGeometry
  14297. function PlaneBufferGeometry( width, height, widthSegments, heightSegments ) {
  14298. BufferGeometry.call( this );
  14299. this.type = 'PlaneBufferGeometry';
  14300. this.parameters = {
  14301. width: width,
  14302. height: height,
  14303. widthSegments: widthSegments,
  14304. heightSegments: heightSegments
  14305. };
  14306. width = width || 1;
  14307. height = height || 1;
  14308. var width_half = width / 2;
  14309. var height_half = height / 2;
  14310. var gridX = Math.floor( widthSegments ) || 1;
  14311. var gridY = Math.floor( heightSegments ) || 1;
  14312. var gridX1 = gridX + 1;
  14313. var gridY1 = gridY + 1;
  14314. var segment_width = width / gridX;
  14315. var segment_height = height / gridY;
  14316. var ix, iy;
  14317. // buffers
  14318. var indices = [];
  14319. var vertices = [];
  14320. var normals = [];
  14321. var uvs = [];
  14322. // generate vertices, normals and uvs
  14323. for ( iy = 0; iy < gridY1; iy ++ ) {
  14324. var y = iy * segment_height - height_half;
  14325. for ( ix = 0; ix < gridX1; ix ++ ) {
  14326. var x = ix * segment_width - width_half;
  14327. vertices.push( x, - y, 0 );
  14328. normals.push( 0, 0, 1 );
  14329. uvs.push( ix / gridX );
  14330. uvs.push( 1 - ( iy / gridY ) );
  14331. }
  14332. }
  14333. // indices
  14334. for ( iy = 0; iy < gridY; iy ++ ) {
  14335. for ( ix = 0; ix < gridX; ix ++ ) {
  14336. var a = ix + gridX1 * iy;
  14337. var b = ix + gridX1 * ( iy + 1 );
  14338. var c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  14339. var d = ( ix + 1 ) + gridX1 * iy;
  14340. // faces
  14341. indices.push( a, b, d );
  14342. indices.push( b, c, d );
  14343. }
  14344. }
  14345. // build geometry
  14346. this.setIndex( indices );
  14347. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  14348. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  14349. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  14350. }
  14351. PlaneBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  14352. PlaneBufferGeometry.prototype.constructor = PlaneBufferGeometry;
  14353. var alphamap_fragment = "#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vUv ).g;\n#endif";
  14354. var alphamap_pars_fragment = "#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif";
  14355. var alphatest_fragment = "#ifdef ALPHATEST\n\tif ( diffuseColor.a < ALPHATEST ) discard;\n#endif";
  14356. 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";
  14357. var aomap_pars_fragment = "#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif";
  14358. var begin_vertex = "vec3 transformed = vec3( position );";
  14359. var beginnormal_vertex = "vec3 objectNormal = vec3( normal );\n#ifdef USE_TANGENT\n\tvec3 objectTangent = vec3( tangent.xyz );\n#endif";
  14360. 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";
  14361. 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";
  14362. 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";
  14363. var clipping_planes_pars_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif";
  14364. var clipping_planes_pars_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n#endif";
  14365. var clipping_planes_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvClipPosition = - mvPosition.xyz;\n#endif";
  14366. var color_fragment = "#ifdef USE_COLOR\n\tdiffuseColor.rgb *= vColor;\n#endif";
  14367. var color_pars_fragment = "#ifdef USE_COLOR\n\tvarying vec3 vColor;\n#endif";
  14368. var color_pars_vertex = "#ifdef USE_COLOR\n\tvarying vec3 vColor;\n#endif";
  14369. var color_vertex = "#ifdef USE_COLOR\n\tvColor.xyz = color.xyz;\n#endif";
  14370. var common = "#define PI 3.14159265359\n#define PI2 6.28318530718\n#define PI_HALF 1.5707963267949\n#define RECIPROCAL_PI 0.31830988618\n#define RECIPROCAL_PI2 0.15915494\n#define LOG2 1.442695\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 return m[ 2 ][ 3 ] == - 1.0;\n}";
  14371. var cube_uv_reflection_fragment = "#ifdef ENVMAP_TYPE_CUBE_UV\n#define cubeUV_maxMipLevel 8.0\n#define cubeUV_minMipLevel 4.0\n#define cubeUV_maxTileSize 256.0\n#define cubeUV_minTileSize 16.0\nfloat getFace(vec3 direction) {\n vec3 absDirection = abs(direction);\n float face = -1.0;\n if (absDirection.x > absDirection.z) {\n if (absDirection.x > absDirection.y)\n face = direction.x > 0.0 ? 0.0 : 3.0;\n else\n face = direction.y > 0.0 ? 1.0 : 4.0;\n } else {\n if (absDirection.z > absDirection.y)\n face = direction.z > 0.0 ? 2.0 : 5.0;\n else\n face = direction.y > 0.0 ? 1.0 : 4.0;\n }\n return face;\n}\nvec2 getUV(vec3 direction, float face) {\n vec2 uv;\n if (face == 0.0) {\n uv = vec2(-direction.z, direction.y) / abs(direction.x);\n } else if (face == 1.0) {\n uv = vec2(direction.x, -direction.z) / abs(direction.y);\n } else if (face == 2.0) {\n uv = direction.xy / abs(direction.z);\n } else if (face == 3.0) {\n uv = vec2(direction.z, direction.y) / abs(direction.x);\n } else if (face == 4.0) {\n uv = direction.xz / abs(direction.y);\n } else {\n uv = vec2(-direction.x, direction.y) / abs(direction.z);\n }\n return 0.5 * (uv + 1.0);\n}\nvec3 bilinearCubeUV(sampler2D envMap, vec3 direction, float mipInt) {\n float face = getFace(direction);\n float filterInt = max(cubeUV_minMipLevel - mipInt, 0.0);\n mipInt = max(mipInt, cubeUV_minMipLevel);\n float faceSize = exp2(mipInt);\n float texelSize = 1.0 / (3.0 * cubeUV_maxTileSize);\n vec2 uv = getUV(direction, face) * (faceSize - 1.0);\n vec2 f = fract(uv);\n uv += 0.5 - f;\n if (face > 2.0) {\n uv.y += faceSize;\n face -= 3.0;\n }\n uv.x += face * faceSize;\n if(mipInt < cubeUV_maxMipLevel){\n uv.y += 2.0 * cubeUV_maxTileSize;\n }\n uv.y += filterInt * 2.0 * cubeUV_minTileSize;\n uv.x += 3.0 * max(0.0, cubeUV_maxTileSize - 2.0 * faceSize);\n uv *= texelSize;\n vec3 tl = envMapTexelToLinear(texture2D(envMap, uv)).rgb;\n uv.x += texelSize;\n vec3 tr = envMapTexelToLinear(texture2D(envMap, uv)).rgb;\n uv.y += texelSize;\n vec3 br = envMapTexelToLinear(texture2D(envMap, uv)).rgb;\n uv.x -= texelSize;\n vec3 bl = envMapTexelToLinear(texture2D(envMap, uv)).rgb;\n vec3 tm = mix(tl, tr, f.x);\n vec3 bm = mix(bl, br, f.x);\n return mix(tm, bm, f.y);\n}\n#define r0 1.0\n#define v0 0.339\n#define m0 -2.0\n#define r1 0.8\n#define v1 0.276\n#define m1 -1.0\n#define r4 0.4\n#define v4 0.046\n#define m4 2.0\n#define r5 0.305\n#define v5 0.016\n#define m5 3.0\n#define r6 0.21\n#define v6 0.0038\n#define m6 4.0\nfloat roughnessToMip(float roughness) {\n float mip = 0.0;\n if (roughness >= r1) {\n mip = (r0 - roughness) * (m1 - m0) / (r0 - r1) + m0;\n } else if (roughness >= r4) {\n mip = (r1 - roughness) * (m4 - m1) / (r1 - r4) + m1;\n } else if (roughness >= r5) {\n mip = (r4 - roughness) * (m5 - m4) / (r4 - r5) + m4;\n } else if (roughness >= r6) {\n mip = (r5 - roughness) * (m6 - m5) / (r5 - r6) + m5;\n } else {\n mip = -2.0 * log2(1.16 * roughness); }\n return mip;\n}\nvec4 textureCubeUV(sampler2D envMap, vec3 sampleDir, float roughness) {\n float mip = clamp(roughnessToMip(roughness), m0, cubeUV_maxMipLevel);\n float mipF = fract(mip);\n float mipInt = floor(mip);\n vec3 color0 = bilinearCubeUV(envMap, sampleDir, mipInt);\n if (mipF == 0.0) {\n return vec4(color0, 1.0);\n } else {\n vec3 color1 = bilinearCubeUV(envMap, sampleDir, mipInt + 1.0);\n return vec4(mix(color0, color1, mipF), 1.0);\n }\n}\n#endif";
  14372. 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";
  14373. var displacementmap_pars_vertex = "#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif";
  14374. var displacementmap_vertex = "#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normalize( objectNormal ) * ( texture2D( displacementMap, vUv ).x * displacementScale + displacementBias );\n#endif";
  14375. var emissivemap_fragment = "#ifdef USE_EMISSIVEMAP\n\tvec4 emissiveColor = texture2D( emissiveMap, vUv );\n\temissiveColor.rgb = emissiveMapTexelToLinear( emissiveColor ).rgb;\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n#endif";
  14376. var emissivemap_pars_fragment = "#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif";
  14377. var encodings_fragment = "gl_FragColor = linearToOutputTexel( gl_FragColor );";
  14378. 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}";
  14379. var envmap_fragment = "#ifdef USE_ENVMAP\n\t#ifdef ENV_WORLDPOS\n\t\tvec3 cameraToFrag;\n\t\t\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#elif defined( ENVMAP_TYPE_EQUIREC )\n\t\tvec2 sampleUV;\n\t\treflectVec = normalize( reflectVec );\n\t\tsampleUV.y = asin( clamp( reflectVec.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;\n\t\tsampleUV.x = atan( reflectVec.z, reflectVec.x ) * RECIPROCAL_PI2 + 0.5;\n\t\tvec4 envColor = texture2D( envMap, sampleUV );\n\t#elif defined( ENVMAP_TYPE_SPHERE )\n\t\treflectVec = normalize( reflectVec );\n\t\tvec3 reflectView = normalize( ( viewMatrix * vec4( reflectVec, 0.0 ) ).xyz + vec3( 0.0, 0.0, 1.0 ) );\n\t\tvec4 envColor = texture2D( envMap, reflectView.xy * 0.5 + 0.5 );\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";
  14380. 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";
  14381. 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";
  14382. 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";
  14383. 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";
  14384. var fog_vertex = "#ifdef USE_FOG\n\tfogDepth = -mvPosition.z;\n#endif";
  14385. var fog_pars_vertex = "#ifdef USE_FOG\n\tvarying float fogDepth;\n#endif";
  14386. 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";
  14387. 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";
  14388. 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}";
  14389. var lightmap_fragment = "#ifdef USE_LIGHTMAP\n\tvec4 lightMapTexel= texture2D( lightMap, vUv2 );\n\treflectedLight.indirectDiffuse += PI * lightMapTexelToLinear( lightMapTexel ).rgb * lightMapIntensity;\n#endif";
  14390. var lightmap_pars_fragment = "#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif";
  14391. 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;\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";
  14392. 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\t#if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0\n\t\tstruct DirectionalLightShadow {\n\t\t\tfloat shadowBias;\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\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\t#if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0\n\t\tstruct PointLightShadow {\n\t\t\tfloat shadowBias;\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\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\t#if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0\n\t\tstruct SpotLightShadow {\n\t\t\tfloat shadowBias;\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\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";
  14393. 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 vec3 reflectVec = reflect( -viewDir, normal );\n\t\t reflectVec = normalize( mix( reflectVec, normal, roughness * roughness) );\n\t\t#else\n\t\t vec3 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#elif defined( ENVMAP_TYPE_EQUIREC )\n\t\t\tvec2 sampleUV;\n\t\t\tsampleUV.y = asin( clamp( reflectVec.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;\n\t\t\tsampleUV.x = atan( reflectVec.z, reflectVec.x ) * RECIPROCAL_PI2 + 0.5;\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = texture2DLodEXT( envMap, sampleUV, specularMIPLevel );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = texture2D( envMap, sampleUV, specularMIPLevel );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#elif defined( ENVMAP_TYPE_SPHERE )\n\t\t\tvec3 reflectView = normalize( ( viewMatrix * vec4( reflectVec, 0.0 ) ).xyz + vec3( 0.0,0.0,1.0 ) );\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = texture2DLodEXT( envMap, reflectView.xy * 0.5 + 0.5, specularMIPLevel );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = texture2D( envMap, reflectView.xy * 0.5 + 0.5, specularMIPLevel );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#endif\n\t\treturn envMapColor.rgb * envMapIntensity;\n\t}\n#endif";
  14394. var lights_toon_fragment = "ToonMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;";
  14395. var lights_toon_pars_fragment = "varying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\nstruct ToonMaterial {\n\tvec3\tdiffuseColor;\n\tvec3\tspecularColor;\n\tfloat\tspecularShininess;\n\tfloat\tspecularStrength;\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\treflectedLight.directSpecular += irradiance * BRDF_Specular_BlinnPhong( directLight, geometry, material.specularColor, material.specularShininess ) * material.specularStrength;\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)";
  14396. var lights_phong_fragment = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;";
  14397. var lights_phong_pars_fragment = "varying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\nstruct BlinnPhongMaterial {\n\tvec3\tdiffuseColor;\n\tvec3\tspecularColor;\n\tfloat\tspecularShininess;\n\tfloat\tspecularStrength;\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)";
  14398. 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";
  14399. var lights_physical_pars_fragment = "struct PhysicalMaterial {\n\tvec3\tdiffuseColor;\n\tfloat\tspecularRoughness;\n\tvec3\tspecularColor;\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}";
  14400. 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";
  14401. 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";
  14402. 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";
  14403. 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";
  14404. 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";
  14405. 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";
  14406. 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";
  14407. var map_fragment = "#ifdef USE_MAP\n\tvec4 texelColor = texture2D( map, vUv );\n\ttexelColor = mapTexelToLinear( texelColor );\n\tdiffuseColor *= texelColor;\n#endif";
  14408. var map_pars_fragment = "#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif";
  14409. 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";
  14410. 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";
  14411. var metalnessmap_fragment = "float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vUv );\n\tmetalnessFactor *= texelMetalness.b;\n#endif";
  14412. var metalnessmap_pars_fragment = "#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif";
  14413. 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";
  14414. var morphtarget_pars_vertex = "#ifdef USE_MORPHTARGETS\n\tuniform float morphTargetBaseInfluence;\n\t#ifndef USE_MORPHNORMALS\n\tuniform float morphTargetInfluences[ 8 ];\n\t#else\n\tuniform float morphTargetInfluences[ 4 ];\n\t#endif\n#endif";
  14415. 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\ttransformed += morphTarget4 * morphTargetInfluences[ 4 ];\n\ttransformed += morphTarget5 * morphTargetInfluences[ 5 ];\n\ttransformed += morphTarget6 * morphTargetInfluences[ 6 ];\n\ttransformed += morphTarget7 * morphTargetInfluences[ 7 ];\n\t#endif\n#endif";
  14416. 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;";
  14417. 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";
  14418. 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";
  14419. var clearcoat_normal_fragment_begin = "#ifdef CLEARCOAT\n\tvec3 clearcoatNormal = geometryNormal;\n#endif";
  14420. 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";
  14421. 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";
  14422. 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}";
  14423. var premultiplied_alpha_fragment = "#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif";
  14424. 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;";
  14425. var dithering_fragment = "#ifdef DITHERING\n\tgl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif";
  14426. 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";
  14427. var roughnessmap_fragment = "float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vUv );\n\troughnessFactor *= texelRoughness.g;\n#endif";
  14428. var roughnessmap_pars_fragment = "#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif";
  14429. 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#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#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#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";
  14430. 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#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#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#endif\n#endif";
  14431. var shadowmap_vertex = "#ifdef USE_SHADOWMAP\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\tvDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * worldPosition;\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\tvSpotShadowCoord[ i ] = spotShadowMatrix[ i ] * worldPosition;\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\tvPointShadowCoord[ i ] = pointShadowMatrix[ i ] * worldPosition;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n#endif";
  14432. 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}";
  14433. 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";
  14434. 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";
  14435. 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";
  14436. 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";
  14437. 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";
  14438. var specularmap_pars_fragment = "#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif";
  14439. var tonemapping_fragment = "#if defined( TONE_MAPPING )\n\tgl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif";
  14440. var tonemapping_pars_fragment = "#ifndef saturate\n#define saturate(a) clamp( a, 0.0, 1.0 )\n#endif\nuniform float toneMappingExposure;\nuniform float toneMappingWhitePoint;\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}\n#define Uncharted2Helper( x ) max( ( ( x * ( 0.15 * x + 0.10 * 0.50 ) + 0.20 * 0.02 ) / ( x * ( 0.15 * x + 0.50 ) + 0.20 * 0.30 ) ) - 0.02 / 0.30, vec3( 0.0 ) )\nvec3 Uncharted2ToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\treturn saturate( Uncharted2Helper( color ) / Uncharted2Helper( vec3( toneMappingWhitePoint ) ) );\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 ACESFilmicToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\treturn saturate( ( color * ( 2.51 * color + 0.03 ) ) / ( color * ( 2.43 * color + 0.59 ) + 0.14 ) );\n}";
  14441. var uv_pars_fragment = "#if ( defined( USE_UV ) && ! defined( UVS_VERTEX_ONLY ) )\n\tvarying vec2 vUv;\n#endif";
  14442. 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";
  14443. var uv_vertex = "#ifdef USE_UV\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n#endif";
  14444. var uv2_pars_fragment = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvarying vec2 vUv2;\n#endif";
  14445. 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";
  14446. var uv2_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvUv2 = ( uv2Transform * vec3( uv2, 1 ) ).xy;\n#endif";
  14447. 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";
  14448. 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}";
  14449. 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}";
  14450. 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}";
  14451. 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}";
  14452. 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}";
  14453. 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}";
  14454. 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}";
  14455. 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}";
  14456. var equirect_frag = "uniform sampler2D tEquirect;\nvarying vec3 vWorldDirection;\n#include <common>\nvoid main() {\n\tvec3 direction = normalize( vWorldDirection );\n\tvec2 sampleUV;\n\tsampleUV.y = asin( clamp( direction.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;\n\tsampleUV.x = atan( direction.z, direction.x ) * RECIPROCAL_PI2 + 0.5;\n\tvec4 texColor = texture2D( tEquirect, sampleUV );\n\tgl_FragColor = mapTexelToLinear( texColor );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n}";
  14457. 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}";
  14458. 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}";
  14459. 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 <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 <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <fog_vertex>\n}";
  14460. var meshbasic_frag = "uniform vec3 diffuse;\nuniform float opacity;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\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}";
  14461. 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}";
  14462. 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\treflectedLight.indirectDiffuse = getAmbientLightIrradiance( ambientLightColor );\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}";
  14463. 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}";
  14464. 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 <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}";
  14465. 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}";
  14466. var meshtoon_frag = "#define TOON\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 <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 <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_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 + reflectedLight.directSpecular + reflectedLight.indirectSpecular + 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}";
  14467. 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}";
  14468. 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}";
  14469. 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}";
  14470. var meshphysical_frag = "#define STANDARD\n#ifdef PHYSICAL\n\t#define REFLECTIVITY\n\t#define CLEARCOAT\n\t#define TRANSPARENCY\n#endif\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float roughness;\nuniform float metalness;\nuniform float opacity;\n#ifdef TRANSPARENCY\n\tuniform float transparency;\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 <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#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 <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 TRANSPARENCY\n\t\tdiffuseColor.a *= saturate( 1. - transparency + linearToRelativeLuminance( reflectedLight.directSpecular + reflectedLight.indirectSpecular ) );\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}";
  14471. 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}";
  14472. 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}";
  14473. 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}";
  14474. 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}";
  14475. 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}";
  14476. 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}";
  14477. var shadow_vert = "#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 <shadowmap_vertex>\n\t#include <fog_vertex>\n}";
  14478. 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}";
  14479. 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}";
  14480. var ShaderChunk = {
  14481. alphamap_fragment: alphamap_fragment,
  14482. alphamap_pars_fragment: alphamap_pars_fragment,
  14483. alphatest_fragment: alphatest_fragment,
  14484. aomap_fragment: aomap_fragment,
  14485. aomap_pars_fragment: aomap_pars_fragment,
  14486. begin_vertex: begin_vertex,
  14487. beginnormal_vertex: beginnormal_vertex,
  14488. bsdfs: bsdfs,
  14489. bumpmap_pars_fragment: bumpmap_pars_fragment,
  14490. clipping_planes_fragment: clipping_planes_fragment,
  14491. clipping_planes_pars_fragment: clipping_planes_pars_fragment,
  14492. clipping_planes_pars_vertex: clipping_planes_pars_vertex,
  14493. clipping_planes_vertex: clipping_planes_vertex,
  14494. color_fragment: color_fragment,
  14495. color_pars_fragment: color_pars_fragment,
  14496. color_pars_vertex: color_pars_vertex,
  14497. color_vertex: color_vertex,
  14498. common: common,
  14499. cube_uv_reflection_fragment: cube_uv_reflection_fragment,
  14500. defaultnormal_vertex: defaultnormal_vertex,
  14501. displacementmap_pars_vertex: displacementmap_pars_vertex,
  14502. displacementmap_vertex: displacementmap_vertex,
  14503. emissivemap_fragment: emissivemap_fragment,
  14504. emissivemap_pars_fragment: emissivemap_pars_fragment,
  14505. encodings_fragment: encodings_fragment,
  14506. encodings_pars_fragment: encodings_pars_fragment,
  14507. envmap_fragment: envmap_fragment,
  14508. envmap_common_pars_fragment: envmap_common_pars_fragment,
  14509. envmap_pars_fragment: envmap_pars_fragment,
  14510. envmap_pars_vertex: envmap_pars_vertex,
  14511. envmap_physical_pars_fragment: envmap_physical_pars_fragment,
  14512. envmap_vertex: envmap_vertex,
  14513. fog_vertex: fog_vertex,
  14514. fog_pars_vertex: fog_pars_vertex,
  14515. fog_fragment: fog_fragment,
  14516. fog_pars_fragment: fog_pars_fragment,
  14517. gradientmap_pars_fragment: gradientmap_pars_fragment,
  14518. lightmap_fragment: lightmap_fragment,
  14519. lightmap_pars_fragment: lightmap_pars_fragment,
  14520. lights_lambert_vertex: lights_lambert_vertex,
  14521. lights_pars_begin: lights_pars_begin,
  14522. lights_toon_fragment: lights_toon_fragment,
  14523. lights_toon_pars_fragment: lights_toon_pars_fragment,
  14524. lights_phong_fragment: lights_phong_fragment,
  14525. lights_phong_pars_fragment: lights_phong_pars_fragment,
  14526. lights_physical_fragment: lights_physical_fragment,
  14527. lights_physical_pars_fragment: lights_physical_pars_fragment,
  14528. lights_fragment_begin: lights_fragment_begin,
  14529. lights_fragment_maps: lights_fragment_maps,
  14530. lights_fragment_end: lights_fragment_end,
  14531. logdepthbuf_fragment: logdepthbuf_fragment,
  14532. logdepthbuf_pars_fragment: logdepthbuf_pars_fragment,
  14533. logdepthbuf_pars_vertex: logdepthbuf_pars_vertex,
  14534. logdepthbuf_vertex: logdepthbuf_vertex,
  14535. map_fragment: map_fragment,
  14536. map_pars_fragment: map_pars_fragment,
  14537. map_particle_fragment: map_particle_fragment,
  14538. map_particle_pars_fragment: map_particle_pars_fragment,
  14539. metalnessmap_fragment: metalnessmap_fragment,
  14540. metalnessmap_pars_fragment: metalnessmap_pars_fragment,
  14541. morphnormal_vertex: morphnormal_vertex,
  14542. morphtarget_pars_vertex: morphtarget_pars_vertex,
  14543. morphtarget_vertex: morphtarget_vertex,
  14544. normal_fragment_begin: normal_fragment_begin,
  14545. normal_fragment_maps: normal_fragment_maps,
  14546. normalmap_pars_fragment: normalmap_pars_fragment,
  14547. clearcoat_normal_fragment_begin: clearcoat_normal_fragment_begin,
  14548. clearcoat_normal_fragment_maps: clearcoat_normal_fragment_maps,
  14549. clearcoat_pars_fragment: clearcoat_pars_fragment,
  14550. packing: packing,
  14551. premultiplied_alpha_fragment: premultiplied_alpha_fragment,
  14552. project_vertex: project_vertex,
  14553. dithering_fragment: dithering_fragment,
  14554. dithering_pars_fragment: dithering_pars_fragment,
  14555. roughnessmap_fragment: roughnessmap_fragment,
  14556. roughnessmap_pars_fragment: roughnessmap_pars_fragment,
  14557. shadowmap_pars_fragment: shadowmap_pars_fragment,
  14558. shadowmap_pars_vertex: shadowmap_pars_vertex,
  14559. shadowmap_vertex: shadowmap_vertex,
  14560. shadowmask_pars_fragment: shadowmask_pars_fragment,
  14561. skinbase_vertex: skinbase_vertex,
  14562. skinning_pars_vertex: skinning_pars_vertex,
  14563. skinning_vertex: skinning_vertex,
  14564. skinnormal_vertex: skinnormal_vertex,
  14565. specularmap_fragment: specularmap_fragment,
  14566. specularmap_pars_fragment: specularmap_pars_fragment,
  14567. tonemapping_fragment: tonemapping_fragment,
  14568. tonemapping_pars_fragment: tonemapping_pars_fragment,
  14569. uv_pars_fragment: uv_pars_fragment,
  14570. uv_pars_vertex: uv_pars_vertex,
  14571. uv_vertex: uv_vertex,
  14572. uv2_pars_fragment: uv2_pars_fragment,
  14573. uv2_pars_vertex: uv2_pars_vertex,
  14574. uv2_vertex: uv2_vertex,
  14575. worldpos_vertex: worldpos_vertex,
  14576. background_frag: background_frag,
  14577. background_vert: background_vert,
  14578. cube_frag: cube_frag,
  14579. cube_vert: cube_vert,
  14580. depth_frag: depth_frag,
  14581. depth_vert: depth_vert,
  14582. distanceRGBA_frag: distanceRGBA_frag,
  14583. distanceRGBA_vert: distanceRGBA_vert,
  14584. equirect_frag: equirect_frag,
  14585. equirect_vert: equirect_vert,
  14586. linedashed_frag: linedashed_frag,
  14587. linedashed_vert: linedashed_vert,
  14588. meshbasic_frag: meshbasic_frag,
  14589. meshbasic_vert: meshbasic_vert,
  14590. meshlambert_frag: meshlambert_frag,
  14591. meshlambert_vert: meshlambert_vert,
  14592. meshmatcap_frag: meshmatcap_frag,
  14593. meshmatcap_vert: meshmatcap_vert,
  14594. meshtoon_frag: meshtoon_frag,
  14595. meshtoon_vert: meshtoon_vert,
  14596. meshphong_frag: meshphong_frag,
  14597. meshphong_vert: meshphong_vert,
  14598. meshphysical_frag: meshphysical_frag,
  14599. meshphysical_vert: meshphysical_vert,
  14600. normal_frag: normal_frag,
  14601. normal_vert: normal_vert,
  14602. points_frag: points_frag,
  14603. points_vert: points_vert,
  14604. shadow_frag: shadow_frag,
  14605. shadow_vert: shadow_vert,
  14606. sprite_frag: sprite_frag,
  14607. sprite_vert: sprite_vert
  14608. };
  14609. /**
  14610. * @author alteredq / http://alteredqualia.com/
  14611. * @author mrdoob / http://mrdoob.com/
  14612. * @author mikael emtinger / http://gomo.se/
  14613. */
  14614. var ShaderLib = {
  14615. basic: {
  14616. uniforms: mergeUniforms( [
  14617. UniformsLib.common,
  14618. UniformsLib.specularmap,
  14619. UniformsLib.envmap,
  14620. UniformsLib.aomap,
  14621. UniformsLib.lightmap,
  14622. UniformsLib.fog
  14623. ] ),
  14624. vertexShader: ShaderChunk.meshbasic_vert,
  14625. fragmentShader: ShaderChunk.meshbasic_frag
  14626. },
  14627. lambert: {
  14628. uniforms: mergeUniforms( [
  14629. UniformsLib.common,
  14630. UniformsLib.specularmap,
  14631. UniformsLib.envmap,
  14632. UniformsLib.aomap,
  14633. UniformsLib.lightmap,
  14634. UniformsLib.emissivemap,
  14635. UniformsLib.fog,
  14636. UniformsLib.lights,
  14637. {
  14638. emissive: { value: new Color( 0x000000 ) }
  14639. }
  14640. ] ),
  14641. vertexShader: ShaderChunk.meshlambert_vert,
  14642. fragmentShader: ShaderChunk.meshlambert_frag
  14643. },
  14644. phong: {
  14645. uniforms: mergeUniforms( [
  14646. UniformsLib.common,
  14647. UniformsLib.specularmap,
  14648. UniformsLib.envmap,
  14649. UniformsLib.aomap,
  14650. UniformsLib.lightmap,
  14651. UniformsLib.emissivemap,
  14652. UniformsLib.bumpmap,
  14653. UniformsLib.normalmap,
  14654. UniformsLib.displacementmap,
  14655. UniformsLib.fog,
  14656. UniformsLib.lights,
  14657. {
  14658. emissive: { value: new Color( 0x000000 ) },
  14659. specular: { value: new Color( 0x111111 ) },
  14660. shininess: { value: 30 }
  14661. }
  14662. ] ),
  14663. vertexShader: ShaderChunk.meshphong_vert,
  14664. fragmentShader: ShaderChunk.meshphong_frag
  14665. },
  14666. standard: {
  14667. uniforms: mergeUniforms( [
  14668. UniformsLib.common,
  14669. UniformsLib.envmap,
  14670. UniformsLib.aomap,
  14671. UniformsLib.lightmap,
  14672. UniformsLib.emissivemap,
  14673. UniformsLib.bumpmap,
  14674. UniformsLib.normalmap,
  14675. UniformsLib.displacementmap,
  14676. UniformsLib.roughnessmap,
  14677. UniformsLib.metalnessmap,
  14678. UniformsLib.fog,
  14679. UniformsLib.lights,
  14680. {
  14681. emissive: { value: new Color( 0x000000 ) },
  14682. roughness: { value: 0.5 },
  14683. metalness: { value: 0.5 },
  14684. envMapIntensity: { value: 1 } // temporary
  14685. }
  14686. ] ),
  14687. vertexShader: ShaderChunk.meshphysical_vert,
  14688. fragmentShader: ShaderChunk.meshphysical_frag
  14689. },
  14690. toon: {
  14691. uniforms: mergeUniforms( [
  14692. UniformsLib.common,
  14693. UniformsLib.specularmap,
  14694. UniformsLib.aomap,
  14695. UniformsLib.lightmap,
  14696. UniformsLib.emissivemap,
  14697. UniformsLib.bumpmap,
  14698. UniformsLib.normalmap,
  14699. UniformsLib.displacementmap,
  14700. UniformsLib.gradientmap,
  14701. UniformsLib.fog,
  14702. UniformsLib.lights,
  14703. {
  14704. emissive: { value: new Color( 0x000000 ) },
  14705. specular: { value: new Color( 0x111111 ) },
  14706. shininess: { value: 30 }
  14707. }
  14708. ] ),
  14709. vertexShader: ShaderChunk.meshtoon_vert,
  14710. fragmentShader: ShaderChunk.meshtoon_frag
  14711. },
  14712. matcap: {
  14713. uniforms: mergeUniforms( [
  14714. UniformsLib.common,
  14715. UniformsLib.bumpmap,
  14716. UniformsLib.normalmap,
  14717. UniformsLib.displacementmap,
  14718. UniformsLib.fog,
  14719. {
  14720. matcap: { value: null }
  14721. }
  14722. ] ),
  14723. vertexShader: ShaderChunk.meshmatcap_vert,
  14724. fragmentShader: ShaderChunk.meshmatcap_frag
  14725. },
  14726. points: {
  14727. uniforms: mergeUniforms( [
  14728. UniformsLib.points,
  14729. UniformsLib.fog
  14730. ] ),
  14731. vertexShader: ShaderChunk.points_vert,
  14732. fragmentShader: ShaderChunk.points_frag
  14733. },
  14734. dashed: {
  14735. uniforms: mergeUniforms( [
  14736. UniformsLib.common,
  14737. UniformsLib.fog,
  14738. {
  14739. scale: { value: 1 },
  14740. dashSize: { value: 1 },
  14741. totalSize: { value: 2 }
  14742. }
  14743. ] ),
  14744. vertexShader: ShaderChunk.linedashed_vert,
  14745. fragmentShader: ShaderChunk.linedashed_frag
  14746. },
  14747. depth: {
  14748. uniforms: mergeUniforms( [
  14749. UniformsLib.common,
  14750. UniformsLib.displacementmap
  14751. ] ),
  14752. vertexShader: ShaderChunk.depth_vert,
  14753. fragmentShader: ShaderChunk.depth_frag
  14754. },
  14755. normal: {
  14756. uniforms: mergeUniforms( [
  14757. UniformsLib.common,
  14758. UniformsLib.bumpmap,
  14759. UniformsLib.normalmap,
  14760. UniformsLib.displacementmap,
  14761. {
  14762. opacity: { value: 1.0 }
  14763. }
  14764. ] ),
  14765. vertexShader: ShaderChunk.normal_vert,
  14766. fragmentShader: ShaderChunk.normal_frag
  14767. },
  14768. sprite: {
  14769. uniforms: mergeUniforms( [
  14770. UniformsLib.sprite,
  14771. UniformsLib.fog
  14772. ] ),
  14773. vertexShader: ShaderChunk.sprite_vert,
  14774. fragmentShader: ShaderChunk.sprite_frag
  14775. },
  14776. background: {
  14777. uniforms: {
  14778. uvTransform: { value: new Matrix3() },
  14779. t2D: { value: null },
  14780. },
  14781. vertexShader: ShaderChunk.background_vert,
  14782. fragmentShader: ShaderChunk.background_frag
  14783. },
  14784. /* -------------------------------------------------------------------------
  14785. // Cube map shader
  14786. ------------------------------------------------------------------------- */
  14787. cube: {
  14788. uniforms: mergeUniforms( [
  14789. UniformsLib.envmap,
  14790. {
  14791. opacity: { value: 1.0 }
  14792. }
  14793. ] ),
  14794. vertexShader: ShaderChunk.cube_vert,
  14795. fragmentShader: ShaderChunk.cube_frag
  14796. },
  14797. equirect: {
  14798. uniforms: {
  14799. tEquirect: { value: null },
  14800. },
  14801. vertexShader: ShaderChunk.equirect_vert,
  14802. fragmentShader: ShaderChunk.equirect_frag
  14803. },
  14804. distanceRGBA: {
  14805. uniforms: mergeUniforms( [
  14806. UniformsLib.common,
  14807. UniformsLib.displacementmap,
  14808. {
  14809. referencePosition: { value: new Vector3() },
  14810. nearDistance: { value: 1 },
  14811. farDistance: { value: 1000 }
  14812. }
  14813. ] ),
  14814. vertexShader: ShaderChunk.distanceRGBA_vert,
  14815. fragmentShader: ShaderChunk.distanceRGBA_frag
  14816. },
  14817. shadow: {
  14818. uniforms: mergeUniforms( [
  14819. UniformsLib.lights,
  14820. UniformsLib.fog,
  14821. {
  14822. color: { value: new Color( 0x00000 ) },
  14823. opacity: { value: 1.0 }
  14824. } ] ),
  14825. vertexShader: ShaderChunk.shadow_vert,
  14826. fragmentShader: ShaderChunk.shadow_frag
  14827. }
  14828. };
  14829. ShaderLib.physical = {
  14830. uniforms: mergeUniforms( [
  14831. ShaderLib.standard.uniforms,
  14832. {
  14833. clearcoat: { value: 0 },
  14834. clearcoatMap: { value: null },
  14835. clearcoatRoughness: { value: 0 },
  14836. clearcoatRoughnessMap: { value: null },
  14837. clearcoatNormalScale: { value: new Vector2( 1, 1 ) },
  14838. clearcoatNormalMap: { value: null },
  14839. sheen: { value: new Color( 0x000000 ) },
  14840. transparency: { value: 0 },
  14841. }
  14842. ] ),
  14843. vertexShader: ShaderChunk.meshphysical_vert,
  14844. fragmentShader: ShaderChunk.meshphysical_frag
  14845. };
  14846. /**
  14847. * @author mrdoob / http://mrdoob.com/
  14848. */
  14849. function WebGLBackground( renderer, state, objects, premultipliedAlpha ) {
  14850. var clearColor = new Color( 0x000000 );
  14851. var clearAlpha = 0;
  14852. var planeMesh;
  14853. var boxMesh;
  14854. var currentBackground = null;
  14855. var currentBackgroundVersion = 0;
  14856. var currentTonemapping = null;
  14857. function render( renderList, scene, camera, forceClear ) {
  14858. var background = scene.background;
  14859. // Ignore background in AR
  14860. // TODO: Reconsider this.
  14861. var xr = renderer.xr;
  14862. var session = xr.getSession && xr.getSession();
  14863. if ( session && session.environmentBlendMode === 'additive' ) {
  14864. background = null;
  14865. }
  14866. if ( background === null ) {
  14867. setClear( clearColor, clearAlpha );
  14868. } else if ( background && background.isColor ) {
  14869. setClear( background, 1 );
  14870. forceClear = true;
  14871. }
  14872. if ( renderer.autoClear || forceClear ) {
  14873. renderer.clear( renderer.autoClearColor, renderer.autoClearDepth, renderer.autoClearStencil );
  14874. }
  14875. if ( background && ( background.isCubeTexture || background.isWebGLCubeRenderTarget || background.mapping === CubeUVReflectionMapping ) ) {
  14876. if ( boxMesh === undefined ) {
  14877. boxMesh = new Mesh(
  14878. new BoxBufferGeometry( 1, 1, 1 ),
  14879. new ShaderMaterial( {
  14880. type: 'BackgroundCubeMaterial',
  14881. uniforms: cloneUniforms( ShaderLib.cube.uniforms ),
  14882. vertexShader: ShaderLib.cube.vertexShader,
  14883. fragmentShader: ShaderLib.cube.fragmentShader,
  14884. side: BackSide,
  14885. depthTest: false,
  14886. depthWrite: false,
  14887. fog: false
  14888. } )
  14889. );
  14890. boxMesh.geometry.deleteAttribute( 'normal' );
  14891. boxMesh.geometry.deleteAttribute( 'uv' );
  14892. boxMesh.onBeforeRender = function ( renderer, scene, camera ) {
  14893. this.matrixWorld.copyPosition( camera.matrixWorld );
  14894. };
  14895. // enable code injection for non-built-in material
  14896. Object.defineProperty( boxMesh.material, 'envMap', {
  14897. get: function () {
  14898. return this.uniforms.envMap.value;
  14899. }
  14900. } );
  14901. objects.update( boxMesh );
  14902. }
  14903. var texture = background.isWebGLCubeRenderTarget ? background.texture : background;
  14904. boxMesh.material.uniforms.envMap.value = texture;
  14905. boxMesh.material.uniforms.flipEnvMap.value = texture.isCubeTexture ? - 1 : 1;
  14906. if ( currentBackground !== background ||
  14907. currentBackgroundVersion !== texture.version ||
  14908. currentTonemapping !== renderer.toneMapping ) {
  14909. boxMesh.material.needsUpdate = true;
  14910. currentBackground = background;
  14911. currentBackgroundVersion = texture.version;
  14912. currentTonemapping = renderer.toneMapping;
  14913. }
  14914. // push to the pre-sorted opaque render list
  14915. renderList.unshift( boxMesh, boxMesh.geometry, boxMesh.material, 0, 0, null );
  14916. } else if ( background && background.isTexture ) {
  14917. if ( planeMesh === undefined ) {
  14918. planeMesh = new Mesh(
  14919. new PlaneBufferGeometry( 2, 2 ),
  14920. new ShaderMaterial( {
  14921. type: 'BackgroundMaterial',
  14922. uniforms: cloneUniforms( ShaderLib.background.uniforms ),
  14923. vertexShader: ShaderLib.background.vertexShader,
  14924. fragmentShader: ShaderLib.background.fragmentShader,
  14925. side: FrontSide,
  14926. depthTest: false,
  14927. depthWrite: false,
  14928. fog: false
  14929. } )
  14930. );
  14931. planeMesh.geometry.deleteAttribute( 'normal' );
  14932. // enable code injection for non-built-in material
  14933. Object.defineProperty( planeMesh.material, 'map', {
  14934. get: function () {
  14935. return this.uniforms.t2D.value;
  14936. }
  14937. } );
  14938. objects.update( planeMesh );
  14939. }
  14940. planeMesh.material.uniforms.t2D.value = background;
  14941. if ( background.matrixAutoUpdate === true ) {
  14942. background.updateMatrix();
  14943. }
  14944. planeMesh.material.uniforms.uvTransform.value.copy( background.matrix );
  14945. if ( currentBackground !== background ||
  14946. currentBackgroundVersion !== background.version ||
  14947. currentTonemapping !== renderer.toneMapping ) {
  14948. planeMesh.material.needsUpdate = true;
  14949. currentBackground = background;
  14950. currentBackgroundVersion = background.version;
  14951. currentTonemapping = renderer.toneMapping;
  14952. }
  14953. // push to the pre-sorted opaque render list
  14954. renderList.unshift( planeMesh, planeMesh.geometry, planeMesh.material, 0, 0, null );
  14955. }
  14956. }
  14957. function setClear( color, alpha ) {
  14958. state.buffers.color.setClear( color.r, color.g, color.b, alpha, premultipliedAlpha );
  14959. }
  14960. return {
  14961. getClearColor: function () {
  14962. return clearColor;
  14963. },
  14964. setClearColor: function ( color, alpha ) {
  14965. clearColor.set( color );
  14966. clearAlpha = alpha !== undefined ? alpha : 1;
  14967. setClear( clearColor, clearAlpha );
  14968. },
  14969. getClearAlpha: function () {
  14970. return clearAlpha;
  14971. },
  14972. setClearAlpha: function ( alpha ) {
  14973. clearAlpha = alpha;
  14974. setClear( clearColor, clearAlpha );
  14975. },
  14976. render: render
  14977. };
  14978. }
  14979. /**
  14980. * @author mrdoob / http://mrdoob.com/
  14981. */
  14982. function WebGLBufferRenderer( gl, extensions, info, capabilities ) {
  14983. var isWebGL2 = capabilities.isWebGL2;
  14984. var mode;
  14985. function setMode( value ) {
  14986. mode = value;
  14987. }
  14988. function render( start, count ) {
  14989. gl.drawArrays( mode, start, count );
  14990. info.update( count, mode );
  14991. }
  14992. function renderInstances( geometry, start, count, primcount ) {
  14993. if ( primcount === 0 ) { return; }
  14994. var extension, methodName;
  14995. if ( isWebGL2 ) {
  14996. extension = gl;
  14997. methodName = 'drawArraysInstanced';
  14998. } else {
  14999. extension = extensions.get( 'ANGLE_instanced_arrays' );
  15000. methodName = 'drawArraysInstancedANGLE';
  15001. if ( extension === null ) {
  15002. console.error( 'THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  15003. return;
  15004. }
  15005. }
  15006. extension[ methodName ]( mode, start, count, primcount );
  15007. info.update( count, mode, primcount );
  15008. }
  15009. //
  15010. this.setMode = setMode;
  15011. this.render = render;
  15012. this.renderInstances = renderInstances;
  15013. }
  15014. /**
  15015. * @author mrdoob / http://mrdoob.com/
  15016. */
  15017. function WebGLCapabilities( gl, extensions, parameters ) {
  15018. var maxAnisotropy;
  15019. function getMaxAnisotropy() {
  15020. if ( maxAnisotropy !== undefined ) { return maxAnisotropy; }
  15021. var extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  15022. if ( extension !== null ) {
  15023. maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  15024. } else {
  15025. maxAnisotropy = 0;
  15026. }
  15027. return maxAnisotropy;
  15028. }
  15029. function getMaxPrecision( precision ) {
  15030. if ( precision === 'highp' ) {
  15031. if ( gl.getShaderPrecisionFormat( 35633, 36338 ).precision > 0 &&
  15032. gl.getShaderPrecisionFormat( 35632, 36338 ).precision > 0 ) {
  15033. return 'highp';
  15034. }
  15035. precision = 'mediump';
  15036. }
  15037. if ( precision === 'mediump' ) {
  15038. if ( gl.getShaderPrecisionFormat( 35633, 36337 ).precision > 0 &&
  15039. gl.getShaderPrecisionFormat( 35632, 36337 ).precision > 0 ) {
  15040. return 'mediump';
  15041. }
  15042. }
  15043. return 'lowp';
  15044. }
  15045. /* eslint-disable no-undef */
  15046. var isWebGL2 = ( typeof WebGL2RenderingContext !== 'undefined' && gl instanceof WebGL2RenderingContext ) ||
  15047. ( typeof WebGL2ComputeRenderingContext !== 'undefined' && gl instanceof WebGL2ComputeRenderingContext );
  15048. /* eslint-enable no-undef */
  15049. var precision = parameters.precision !== undefined ? parameters.precision : 'highp';
  15050. var maxPrecision = getMaxPrecision( precision );
  15051. if ( maxPrecision !== precision ) {
  15052. console.warn( 'THREE.WebGLRenderer:', precision, 'not supported, using', maxPrecision, 'instead.' );
  15053. precision = maxPrecision;
  15054. }
  15055. var logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true;
  15056. var maxTextures = gl.getParameter( 34930 );
  15057. var maxVertexTextures = gl.getParameter( 35660 );
  15058. var maxTextureSize = gl.getParameter( 3379 );
  15059. var maxCubemapSize = gl.getParameter( 34076 );
  15060. var maxAttributes = gl.getParameter( 34921 );
  15061. var maxVertexUniforms = gl.getParameter( 36347 );
  15062. var maxVaryings = gl.getParameter( 36348 );
  15063. var maxFragmentUniforms = gl.getParameter( 36349 );
  15064. var vertexTextures = maxVertexTextures > 0;
  15065. var floatFragmentTextures = isWebGL2 || !! extensions.get( 'OES_texture_float' );
  15066. var floatVertexTextures = vertexTextures && floatFragmentTextures;
  15067. var maxSamples = isWebGL2 ? gl.getParameter( 36183 ) : 0;
  15068. return {
  15069. isWebGL2: isWebGL2,
  15070. getMaxAnisotropy: getMaxAnisotropy,
  15071. getMaxPrecision: getMaxPrecision,
  15072. precision: precision,
  15073. logarithmicDepthBuffer: logarithmicDepthBuffer,
  15074. maxTextures: maxTextures,
  15075. maxVertexTextures: maxVertexTextures,
  15076. maxTextureSize: maxTextureSize,
  15077. maxCubemapSize: maxCubemapSize,
  15078. maxAttributes: maxAttributes,
  15079. maxVertexUniforms: maxVertexUniforms,
  15080. maxVaryings: maxVaryings,
  15081. maxFragmentUniforms: maxFragmentUniforms,
  15082. vertexTextures: vertexTextures,
  15083. floatFragmentTextures: floatFragmentTextures,
  15084. floatVertexTextures: floatVertexTextures,
  15085. maxSamples: maxSamples
  15086. };
  15087. }
  15088. /**
  15089. * @author tschw
  15090. */
  15091. function WebGLClipping() {
  15092. var scope = this,
  15093. globalState = null,
  15094. numGlobalPlanes = 0,
  15095. localClippingEnabled = false,
  15096. renderingShadows = false,
  15097. plane = new Plane(),
  15098. viewNormalMatrix = new Matrix3(),
  15099. uniform = { value: null, needsUpdate: false };
  15100. this.uniform = uniform;
  15101. this.numPlanes = 0;
  15102. this.numIntersection = 0;
  15103. this.init = function ( planes, enableLocalClipping, camera ) {
  15104. var enabled =
  15105. planes.length !== 0 ||
  15106. enableLocalClipping ||
  15107. // enable state of previous frame - the clipping code has to
  15108. // run another frame in order to reset the state:
  15109. numGlobalPlanes !== 0 ||
  15110. localClippingEnabled;
  15111. localClippingEnabled = enableLocalClipping;
  15112. globalState = projectPlanes( planes, camera, 0 );
  15113. numGlobalPlanes = planes.length;
  15114. return enabled;
  15115. };
  15116. this.beginShadows = function () {
  15117. renderingShadows = true;
  15118. projectPlanes( null );
  15119. };
  15120. this.endShadows = function () {
  15121. renderingShadows = false;
  15122. resetGlobalState();
  15123. };
  15124. this.setState = function ( planes, clipIntersection, clipShadows, camera, cache, fromCache ) {
  15125. if ( ! localClippingEnabled || planes === null || planes.length === 0 || renderingShadows && ! clipShadows ) {
  15126. // there's no local clipping
  15127. if ( renderingShadows ) {
  15128. // there's no global clipping
  15129. projectPlanes( null );
  15130. } else {
  15131. resetGlobalState();
  15132. }
  15133. } else {
  15134. var nGlobal = renderingShadows ? 0 : numGlobalPlanes,
  15135. lGlobal = nGlobal * 4,
  15136. dstArray = cache.clippingState || null;
  15137. uniform.value = dstArray; // ensure unique state
  15138. dstArray = projectPlanes( planes, camera, lGlobal, fromCache );
  15139. for ( var i = 0; i !== lGlobal; ++ i ) {
  15140. dstArray[ i ] = globalState[ i ];
  15141. }
  15142. cache.clippingState = dstArray;
  15143. this.numIntersection = clipIntersection ? this.numPlanes : 0;
  15144. this.numPlanes += nGlobal;
  15145. }
  15146. };
  15147. function resetGlobalState() {
  15148. if ( uniform.value !== globalState ) {
  15149. uniform.value = globalState;
  15150. uniform.needsUpdate = numGlobalPlanes > 0;
  15151. }
  15152. scope.numPlanes = numGlobalPlanes;
  15153. scope.numIntersection = 0;
  15154. }
  15155. function projectPlanes( planes, camera, dstOffset, skipTransform ) {
  15156. var nPlanes = planes !== null ? planes.length : 0,
  15157. dstArray = null;
  15158. if ( nPlanes !== 0 ) {
  15159. dstArray = uniform.value;
  15160. if ( skipTransform !== true || dstArray === null ) {
  15161. var flatSize = dstOffset + nPlanes * 4,
  15162. viewMatrix = camera.matrixWorldInverse;
  15163. viewNormalMatrix.getNormalMatrix( viewMatrix );
  15164. if ( dstArray === null || dstArray.length < flatSize ) {
  15165. dstArray = new Float32Array( flatSize );
  15166. }
  15167. for ( var i = 0, i4 = dstOffset; i !== nPlanes; ++ i, i4 += 4 ) {
  15168. plane.copy( planes[ i ] ).applyMatrix4( viewMatrix, viewNormalMatrix );
  15169. plane.normal.toArray( dstArray, i4 );
  15170. dstArray[ i4 + 3 ] = plane.constant;
  15171. }
  15172. }
  15173. uniform.value = dstArray;
  15174. uniform.needsUpdate = true;
  15175. }
  15176. scope.numPlanes = nPlanes;
  15177. scope.numIntersection = 0;
  15178. return dstArray;
  15179. }
  15180. }
  15181. /**
  15182. * @author mrdoob / http://mrdoob.com/
  15183. */
  15184. function WebGLExtensions( gl ) {
  15185. var extensions = {};
  15186. return {
  15187. get: function ( name ) {
  15188. if ( extensions[ name ] !== undefined ) {
  15189. return extensions[ name ];
  15190. }
  15191. var extension;
  15192. switch ( name ) {
  15193. case 'WEBGL_depth_texture':
  15194. extension = gl.getExtension( 'WEBGL_depth_texture' ) || gl.getExtension( 'MOZ_WEBGL_depth_texture' ) || gl.getExtension( 'WEBKIT_WEBGL_depth_texture' );
  15195. break;
  15196. case 'EXT_texture_filter_anisotropic':
  15197. extension = gl.getExtension( 'EXT_texture_filter_anisotropic' ) || gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) || gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' );
  15198. break;
  15199. case 'WEBGL_compressed_texture_s3tc':
  15200. extension = gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' );
  15201. break;
  15202. case 'WEBGL_compressed_texture_pvrtc':
  15203. extension = gl.getExtension( 'WEBGL_compressed_texture_pvrtc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_pvrtc' );
  15204. break;
  15205. default:
  15206. extension = gl.getExtension( name );
  15207. }
  15208. if ( extension === null ) {
  15209. console.warn( 'THREE.WebGLRenderer: ' + name + ' extension not supported.' );
  15210. }
  15211. extensions[ name ] = extension;
  15212. return extension;
  15213. }
  15214. };
  15215. }
  15216. /**
  15217. * @author mrdoob / http://mrdoob.com/
  15218. */
  15219. function WebGLGeometries( gl, attributes, info ) {
  15220. var geometries = new WeakMap();
  15221. var wireframeAttributes = new WeakMap();
  15222. function onGeometryDispose( event ) {
  15223. var geometry = event.target;
  15224. var buffergeometry = geometries.get( geometry );
  15225. if ( buffergeometry.index !== null ) {
  15226. attributes.remove( buffergeometry.index );
  15227. }
  15228. for ( var name in buffergeometry.attributes ) {
  15229. attributes.remove( buffergeometry.attributes[ name ] );
  15230. }
  15231. geometry.removeEventListener( 'dispose', onGeometryDispose );
  15232. geometries.delete( geometry );
  15233. var attribute = wireframeAttributes.get( buffergeometry );
  15234. if ( attribute ) {
  15235. attributes.remove( attribute );
  15236. wireframeAttributes.delete( buffergeometry );
  15237. }
  15238. //
  15239. info.memory.geometries --;
  15240. }
  15241. function get( object, geometry ) {
  15242. var buffergeometry = geometries.get( geometry );
  15243. if ( buffergeometry ) { return buffergeometry; }
  15244. geometry.addEventListener( 'dispose', onGeometryDispose );
  15245. if ( geometry.isBufferGeometry ) {
  15246. buffergeometry = geometry;
  15247. } else if ( geometry.isGeometry ) {
  15248. if ( geometry._bufferGeometry === undefined ) {
  15249. geometry._bufferGeometry = new BufferGeometry().setFromObject( object );
  15250. }
  15251. buffergeometry = geometry._bufferGeometry;
  15252. }
  15253. geometries.set( geometry, buffergeometry );
  15254. info.memory.geometries ++;
  15255. return buffergeometry;
  15256. }
  15257. function update( geometry ) {
  15258. var index = geometry.index;
  15259. var geometryAttributes = geometry.attributes;
  15260. if ( index !== null ) {
  15261. attributes.update( index, 34963 );
  15262. }
  15263. for ( var name in geometryAttributes ) {
  15264. attributes.update( geometryAttributes[ name ], 34962 );
  15265. }
  15266. // morph targets
  15267. var morphAttributes = geometry.morphAttributes;
  15268. for ( var name in morphAttributes ) {
  15269. var array = morphAttributes[ name ];
  15270. for ( var i = 0, l = array.length; i < l; i ++ ) {
  15271. attributes.update( array[ i ], 34962 );
  15272. }
  15273. }
  15274. }
  15275. function updateWireframeAttribute( geometry ) {
  15276. var indices = [];
  15277. var geometryIndex = geometry.index;
  15278. var geometryPosition = geometry.attributes.position;
  15279. var version = 0;
  15280. if ( geometryIndex !== null ) {
  15281. var array = geometryIndex.array;
  15282. version = geometryIndex.version;
  15283. for ( var i = 0, l = array.length; i < l; i += 3 ) {
  15284. var a = array[ i + 0 ];
  15285. var b = array[ i + 1 ];
  15286. var c = array[ i + 2 ];
  15287. indices.push( a, b, b, c, c, a );
  15288. }
  15289. } else {
  15290. var array = geometryPosition.array;
  15291. version = geometryPosition.version;
  15292. for ( var i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
  15293. var a = i + 0;
  15294. var b = i + 1;
  15295. var c = i + 2;
  15296. indices.push( a, b, b, c, c, a );
  15297. }
  15298. }
  15299. var attribute = new ( arrayMax( indices ) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 );
  15300. attribute.version = version;
  15301. attributes.update( attribute, 34963 );
  15302. //
  15303. var previousAttribute = wireframeAttributes.get( geometry );
  15304. if ( previousAttribute ) { attributes.remove( previousAttribute ); }
  15305. //
  15306. wireframeAttributes.set( geometry, attribute );
  15307. }
  15308. function getWireframeAttribute( geometry ) {
  15309. var currentAttribute = wireframeAttributes.get( geometry );
  15310. if ( currentAttribute ) {
  15311. var geometryIndex = geometry.index;
  15312. if ( geometryIndex !== null ) {
  15313. // if the attribute is obsolete, create a new one
  15314. if ( currentAttribute.version < geometryIndex.version ) {
  15315. updateWireframeAttribute( geometry );
  15316. }
  15317. }
  15318. } else {
  15319. updateWireframeAttribute( geometry );
  15320. }
  15321. return wireframeAttributes.get( geometry );
  15322. }
  15323. return {
  15324. get: get,
  15325. update: update,
  15326. getWireframeAttribute: getWireframeAttribute
  15327. };
  15328. }
  15329. /**
  15330. * @author mrdoob / http://mrdoob.com/
  15331. */
  15332. function WebGLIndexedBufferRenderer( gl, extensions, info, capabilities ) {
  15333. var isWebGL2 = capabilities.isWebGL2;
  15334. var mode;
  15335. function setMode( value ) {
  15336. mode = value;
  15337. }
  15338. var type, bytesPerElement;
  15339. function setIndex( value ) {
  15340. type = value.type;
  15341. bytesPerElement = value.bytesPerElement;
  15342. }
  15343. function render( start, count ) {
  15344. gl.drawElements( mode, count, type, start * bytesPerElement );
  15345. info.update( count, mode );
  15346. }
  15347. function renderInstances( geometry, start, count, primcount ) {
  15348. if ( primcount === 0 ) { return; }
  15349. var extension, methodName;
  15350. if ( isWebGL2 ) {
  15351. extension = gl;
  15352. methodName = 'drawElementsInstanced';
  15353. } else {
  15354. extension = extensions.get( 'ANGLE_instanced_arrays' );
  15355. methodName = 'drawElementsInstancedANGLE';
  15356. if ( extension === null ) {
  15357. console.error( 'THREE.WebGLIndexedBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  15358. return;
  15359. }
  15360. }
  15361. extension[ methodName ]( mode, count, type, start * bytesPerElement, primcount );
  15362. info.update( count, mode, primcount );
  15363. }
  15364. //
  15365. this.setMode = setMode;
  15366. this.setIndex = setIndex;
  15367. this.render = render;
  15368. this.renderInstances = renderInstances;
  15369. }
  15370. /**
  15371. * @author Mugen87 / https://github.com/Mugen87
  15372. */
  15373. function WebGLInfo( gl ) {
  15374. var memory = {
  15375. geometries: 0,
  15376. textures: 0
  15377. };
  15378. var render = {
  15379. frame: 0,
  15380. calls: 0,
  15381. triangles: 0,
  15382. points: 0,
  15383. lines: 0
  15384. };
  15385. function update( count, mode, instanceCount ) {
  15386. instanceCount = instanceCount || 1;
  15387. render.calls ++;
  15388. switch ( mode ) {
  15389. case 4:
  15390. render.triangles += instanceCount * ( count / 3 );
  15391. break;
  15392. case 1:
  15393. render.lines += instanceCount * ( count / 2 );
  15394. break;
  15395. case 3:
  15396. render.lines += instanceCount * ( count - 1 );
  15397. break;
  15398. case 2:
  15399. render.lines += instanceCount * count;
  15400. break;
  15401. case 0:
  15402. render.points += instanceCount * count;
  15403. break;
  15404. default:
  15405. console.error( 'THREE.WebGLInfo: Unknown draw mode:', mode );
  15406. break;
  15407. }
  15408. }
  15409. function reset() {
  15410. render.frame ++;
  15411. render.calls = 0;
  15412. render.triangles = 0;
  15413. render.points = 0;
  15414. render.lines = 0;
  15415. }
  15416. return {
  15417. memory: memory,
  15418. render: render,
  15419. programs: null,
  15420. autoReset: true,
  15421. reset: reset,
  15422. update: update
  15423. };
  15424. }
  15425. /**
  15426. * @author mrdoob / http://mrdoob.com/
  15427. */
  15428. function absNumericalSort( a, b ) {
  15429. return Math.abs( b[ 1 ] ) - Math.abs( a[ 1 ] );
  15430. }
  15431. function WebGLMorphtargets( gl ) {
  15432. var influencesList = {};
  15433. var morphInfluences = new Float32Array( 8 );
  15434. function update( object, geometry, material, program ) {
  15435. var objectInfluences = object.morphTargetInfluences;
  15436. // When object doesn't have morph target influences defined, we treat it as a 0-length array
  15437. // This is important to make sure we set up morphTargetBaseInfluence / morphTargetInfluences
  15438. var length = objectInfluences === undefined ? 0 : objectInfluences.length;
  15439. var influences = influencesList[ geometry.id ];
  15440. if ( influences === undefined ) {
  15441. // initialise list
  15442. influences = [];
  15443. for ( var i = 0; i < length; i ++ ) {
  15444. influences[ i ] = [ i, 0 ];
  15445. }
  15446. influencesList[ geometry.id ] = influences;
  15447. }
  15448. var morphTargets = material.morphTargets && geometry.morphAttributes.position;
  15449. var morphNormals = material.morphNormals && geometry.morphAttributes.normal;
  15450. // Remove current morphAttributes
  15451. for ( var i = 0; i < length; i ++ ) {
  15452. var influence = influences[ i ];
  15453. if ( influence[ 1 ] !== 0 ) {
  15454. if ( morphTargets ) { geometry.deleteAttribute( 'morphTarget' + i ); }
  15455. if ( morphNormals ) { geometry.deleteAttribute( 'morphNormal' + i ); }
  15456. }
  15457. }
  15458. // Collect influences
  15459. for ( var i = 0; i < length; i ++ ) {
  15460. var influence = influences[ i ];
  15461. influence[ 0 ] = i;
  15462. influence[ 1 ] = objectInfluences[ i ];
  15463. }
  15464. influences.sort( absNumericalSort );
  15465. // Add morphAttributes
  15466. var morphInfluencesSum = 0;
  15467. for ( var i = 0; i < 8; i ++ ) {
  15468. var influence = influences[ i ];
  15469. if ( influence ) {
  15470. var index = influence[ 0 ];
  15471. var value = influence[ 1 ];
  15472. if ( value ) {
  15473. if ( morphTargets ) { geometry.setAttribute( 'morphTarget' + i, morphTargets[ index ] ); }
  15474. if ( morphNormals ) { geometry.setAttribute( 'morphNormal' + i, morphNormals[ index ] ); }
  15475. morphInfluences[ i ] = value;
  15476. morphInfluencesSum += value;
  15477. continue;
  15478. }
  15479. }
  15480. morphInfluences[ i ] = 0;
  15481. }
  15482. // GLSL shader uses formula baseinfluence * base + sum(target * influence)
  15483. // This allows us to switch between absolute morphs and relative morphs without changing shader code
  15484. // When baseinfluence = 1 - sum(influence), the above is equivalent to sum((target - base) * influence)
  15485. var morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  15486. program.getUniforms().setValue( gl, 'morphTargetBaseInfluence', morphBaseInfluence );
  15487. program.getUniforms().setValue( gl, 'morphTargetInfluences', morphInfluences );
  15488. }
  15489. return {
  15490. update: update
  15491. };
  15492. }
  15493. /**
  15494. * @author mrdoob / http://mrdoob.com/
  15495. */
  15496. function WebGLObjects( gl, geometries, attributes, info ) {
  15497. var updateMap = new WeakMap();
  15498. function update( object ) {
  15499. var frame = info.render.frame;
  15500. var geometry = object.geometry;
  15501. var buffergeometry = geometries.get( object, geometry );
  15502. // Update once per frame
  15503. if ( updateMap.get( buffergeometry ) !== frame ) {
  15504. if ( geometry.isGeometry ) {
  15505. buffergeometry.updateFromObject( object );
  15506. }
  15507. geometries.update( buffergeometry );
  15508. updateMap.set( buffergeometry, frame );
  15509. }
  15510. if ( object.isInstancedMesh ) {
  15511. attributes.update( object.instanceMatrix, 34962 );
  15512. }
  15513. return buffergeometry;
  15514. }
  15515. function dispose() {
  15516. updateMap = new WeakMap();
  15517. }
  15518. return {
  15519. update: update,
  15520. dispose: dispose
  15521. };
  15522. }
  15523. /**
  15524. * @author mrdoob / http://mrdoob.com/
  15525. */
  15526. function CubeTexture( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ) {
  15527. images = images !== undefined ? images : [];
  15528. mapping = mapping !== undefined ? mapping : CubeReflectionMapping;
  15529. format = format !== undefined ? format : RGBFormat;
  15530. Texture.call( this, images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  15531. this.flipY = false;
  15532. }
  15533. CubeTexture.prototype = Object.create( Texture.prototype );
  15534. CubeTexture.prototype.constructor = CubeTexture;
  15535. CubeTexture.prototype.isCubeTexture = true;
  15536. Object.defineProperty( CubeTexture.prototype, 'images', {
  15537. get: function () {
  15538. return this.image;
  15539. },
  15540. set: function ( value ) {
  15541. this.image = value;
  15542. }
  15543. } );
  15544. /**
  15545. * @author Takahiro https://github.com/takahirox
  15546. */
  15547. function DataTexture2DArray( data, width, height, depth ) {
  15548. Texture.call( this, null );
  15549. this.image = { data: data || null, width: width || 1, height: height || 1, depth: depth || 1 };
  15550. this.magFilter = NearestFilter;
  15551. this.minFilter = NearestFilter;
  15552. this.wrapR = ClampToEdgeWrapping;
  15553. this.generateMipmaps = false;
  15554. this.flipY = false;
  15555. this.needsUpdate = true;
  15556. }
  15557. DataTexture2DArray.prototype = Object.create( Texture.prototype );
  15558. DataTexture2DArray.prototype.constructor = DataTexture2DArray;
  15559. DataTexture2DArray.prototype.isDataTexture2DArray = true;
  15560. /**
  15561. * @author Artur Trzesiok
  15562. */
  15563. function DataTexture3D( data, width, height, depth ) {
  15564. // We're going to add .setXXX() methods for setting properties later.
  15565. // Users can still set in DataTexture3D directly.
  15566. //
  15567. // var texture = new THREE.DataTexture3D( data, width, height, depth );
  15568. // texture.anisotropy = 16;
  15569. //
  15570. // See #14839
  15571. Texture.call( this, null );
  15572. this.image = { data: data || null, width: width || 1, height: height || 1, depth: depth || 1 };
  15573. this.magFilter = NearestFilter;
  15574. this.minFilter = NearestFilter;
  15575. this.wrapR = ClampToEdgeWrapping;
  15576. this.generateMipmaps = false;
  15577. this.flipY = false;
  15578. this.needsUpdate = true;
  15579. }
  15580. DataTexture3D.prototype = Object.create( Texture.prototype );
  15581. DataTexture3D.prototype.constructor = DataTexture3D;
  15582. DataTexture3D.prototype.isDataTexture3D = true;
  15583. /**
  15584. * @author tschw
  15585. * @author Mugen87 / https://github.com/Mugen87
  15586. * @author mrdoob / http://mrdoob.com/
  15587. *
  15588. * Uniforms of a program.
  15589. * Those form a tree structure with a special top-level container for the root,
  15590. * which you get by calling 'new WebGLUniforms( gl, program )'.
  15591. *
  15592. *
  15593. * Properties of inner nodes including the top-level container:
  15594. *
  15595. * .seq - array of nested uniforms
  15596. * .map - nested uniforms by name
  15597. *
  15598. *
  15599. * Methods of all nodes except the top-level container:
  15600. *
  15601. * .setValue( gl, value, [textures] )
  15602. *
  15603. * uploads a uniform value(s)
  15604. * the 'textures' parameter is needed for sampler uniforms
  15605. *
  15606. *
  15607. * Static methods of the top-level container (textures factorizations):
  15608. *
  15609. * .upload( gl, seq, values, textures )
  15610. *
  15611. * sets uniforms in 'seq' to 'values[id].value'
  15612. *
  15613. * .seqWithValue( seq, values ) : filteredSeq
  15614. *
  15615. * filters 'seq' entries with corresponding entry in values
  15616. *
  15617. *
  15618. * Methods of the top-level container (textures factorizations):
  15619. *
  15620. * .setValue( gl, name, value, textures )
  15621. *
  15622. * sets uniform with name 'name' to 'value'
  15623. *
  15624. * .setOptional( gl, obj, prop )
  15625. *
  15626. * like .set for an optional property of the object
  15627. *
  15628. */
  15629. var emptyTexture = new Texture();
  15630. var emptyTexture2dArray = new DataTexture2DArray();
  15631. var emptyTexture3d = new DataTexture3D();
  15632. var emptyCubeTexture = new CubeTexture();
  15633. // --- Utilities ---
  15634. // Array Caches (provide typed arrays for temporary by size)
  15635. var arrayCacheF32 = [];
  15636. var arrayCacheI32 = [];
  15637. // Float32Array caches used for uploading Matrix uniforms
  15638. var mat4array = new Float32Array( 16 );
  15639. var mat3array = new Float32Array( 9 );
  15640. var mat2array = new Float32Array( 4 );
  15641. // Flattening for arrays of vectors and matrices
  15642. function flatten( array, nBlocks, blockSize ) {
  15643. var firstElem = array[ 0 ];
  15644. if ( firstElem <= 0 || firstElem > 0 ) { return array; }
  15645. // unoptimized: ! isNaN( firstElem )
  15646. // see http://jacksondunstan.com/articles/983
  15647. var n = nBlocks * blockSize,
  15648. r = arrayCacheF32[ n ];
  15649. if ( r === undefined ) {
  15650. r = new Float32Array( n );
  15651. arrayCacheF32[ n ] = r;
  15652. }
  15653. if ( nBlocks !== 0 ) {
  15654. firstElem.toArray( r, 0 );
  15655. for ( var i = 1, offset = 0; i !== nBlocks; ++ i ) {
  15656. offset += blockSize;
  15657. array[ i ].toArray( r, offset );
  15658. }
  15659. }
  15660. return r;
  15661. }
  15662. function arraysEqual( a, b ) {
  15663. if ( a.length !== b.length ) { return false; }
  15664. for ( var i = 0, l = a.length; i < l; i ++ ) {
  15665. if ( a[ i ] !== b[ i ] ) { return false; }
  15666. }
  15667. return true;
  15668. }
  15669. function copyArray( a, b ) {
  15670. for ( var i = 0, l = b.length; i < l; i ++ ) {
  15671. a[ i ] = b[ i ];
  15672. }
  15673. }
  15674. // Texture unit allocation
  15675. function allocTexUnits( textures, n ) {
  15676. var r = arrayCacheI32[ n ];
  15677. if ( r === undefined ) {
  15678. r = new Int32Array( n );
  15679. arrayCacheI32[ n ] = r;
  15680. }
  15681. for ( var i = 0; i !== n; ++ i )
  15682. { r[ i ] = textures.allocateTextureUnit(); }
  15683. return r;
  15684. }
  15685. // --- Setters ---
  15686. // Note: Defining these methods externally, because they come in a bunch
  15687. // and this way their names minify.
  15688. // Single scalar
  15689. function setValueV1f( gl, v ) {
  15690. var cache = this.cache;
  15691. if ( cache[ 0 ] === v ) { return; }
  15692. gl.uniform1f( this.addr, v );
  15693. cache[ 0 ] = v;
  15694. }
  15695. // Single float vector (from flat array or THREE.VectorN)
  15696. function setValueV2f( gl, v ) {
  15697. var cache = this.cache;
  15698. if ( v.x !== undefined ) {
  15699. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) {
  15700. gl.uniform2f( this.addr, v.x, v.y );
  15701. cache[ 0 ] = v.x;
  15702. cache[ 1 ] = v.y;
  15703. }
  15704. } else {
  15705. if ( arraysEqual( cache, v ) ) { return; }
  15706. gl.uniform2fv( this.addr, v );
  15707. copyArray( cache, v );
  15708. }
  15709. }
  15710. function setValueV3f( gl, v ) {
  15711. var cache = this.cache;
  15712. if ( v.x !== undefined ) {
  15713. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) {
  15714. gl.uniform3f( this.addr, v.x, v.y, v.z );
  15715. cache[ 0 ] = v.x;
  15716. cache[ 1 ] = v.y;
  15717. cache[ 2 ] = v.z;
  15718. }
  15719. } else if ( v.r !== undefined ) {
  15720. if ( cache[ 0 ] !== v.r || cache[ 1 ] !== v.g || cache[ 2 ] !== v.b ) {
  15721. gl.uniform3f( this.addr, v.r, v.g, v.b );
  15722. cache[ 0 ] = v.r;
  15723. cache[ 1 ] = v.g;
  15724. cache[ 2 ] = v.b;
  15725. }
  15726. } else {
  15727. if ( arraysEqual( cache, v ) ) { return; }
  15728. gl.uniform3fv( this.addr, v );
  15729. copyArray( cache, v );
  15730. }
  15731. }
  15732. function setValueV4f( gl, v ) {
  15733. var cache = this.cache;
  15734. if ( v.x !== undefined ) {
  15735. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) {
  15736. gl.uniform4f( this.addr, v.x, v.y, v.z, v.w );
  15737. cache[ 0 ] = v.x;
  15738. cache[ 1 ] = v.y;
  15739. cache[ 2 ] = v.z;
  15740. cache[ 3 ] = v.w;
  15741. }
  15742. } else {
  15743. if ( arraysEqual( cache, v ) ) { return; }
  15744. gl.uniform4fv( this.addr, v );
  15745. copyArray( cache, v );
  15746. }
  15747. }
  15748. // Single matrix (from flat array or MatrixN)
  15749. function setValueM2( gl, v ) {
  15750. var cache = this.cache;
  15751. var elements = v.elements;
  15752. if ( elements === undefined ) {
  15753. if ( arraysEqual( cache, v ) ) { return; }
  15754. gl.uniformMatrix2fv( this.addr, false, v );
  15755. copyArray( cache, v );
  15756. } else {
  15757. if ( arraysEqual( cache, elements ) ) { return; }
  15758. mat2array.set( elements );
  15759. gl.uniformMatrix2fv( this.addr, false, mat2array );
  15760. copyArray( cache, elements );
  15761. }
  15762. }
  15763. function setValueM3( gl, v ) {
  15764. var cache = this.cache;
  15765. var elements = v.elements;
  15766. if ( elements === undefined ) {
  15767. if ( arraysEqual( cache, v ) ) { return; }
  15768. gl.uniformMatrix3fv( this.addr, false, v );
  15769. copyArray( cache, v );
  15770. } else {
  15771. if ( arraysEqual( cache, elements ) ) { return; }
  15772. mat3array.set( elements );
  15773. gl.uniformMatrix3fv( this.addr, false, mat3array );
  15774. copyArray( cache, elements );
  15775. }
  15776. }
  15777. function setValueM4( gl, v ) {
  15778. var cache = this.cache;
  15779. var elements = v.elements;
  15780. if ( elements === undefined ) {
  15781. if ( arraysEqual( cache, v ) ) { return; }
  15782. gl.uniformMatrix4fv( this.addr, false, v );
  15783. copyArray( cache, v );
  15784. } else {
  15785. if ( arraysEqual( cache, elements ) ) { return; }
  15786. mat4array.set( elements );
  15787. gl.uniformMatrix4fv( this.addr, false, mat4array );
  15788. copyArray( cache, elements );
  15789. }
  15790. }
  15791. // Single texture (2D / Cube)
  15792. function setValueT1( gl, v, textures ) {
  15793. var cache = this.cache;
  15794. var unit = textures.allocateTextureUnit();
  15795. if ( cache[ 0 ] !== unit ) {
  15796. gl.uniform1i( this.addr, unit );
  15797. cache[ 0 ] = unit;
  15798. }
  15799. textures.safeSetTexture2D( v || emptyTexture, unit );
  15800. }
  15801. function setValueT2DArray1( gl, v, textures ) {
  15802. var cache = this.cache;
  15803. var unit = textures.allocateTextureUnit();
  15804. if ( cache[ 0 ] !== unit ) {
  15805. gl.uniform1i( this.addr, unit );
  15806. cache[ 0 ] = unit;
  15807. }
  15808. textures.setTexture2DArray( v || emptyTexture2dArray, unit );
  15809. }
  15810. function setValueT3D1( gl, v, textures ) {
  15811. var cache = this.cache;
  15812. var unit = textures.allocateTextureUnit();
  15813. if ( cache[ 0 ] !== unit ) {
  15814. gl.uniform1i( this.addr, unit );
  15815. cache[ 0 ] = unit;
  15816. }
  15817. textures.setTexture3D( v || emptyTexture3d, unit );
  15818. }
  15819. function setValueT6( gl, v, textures ) {
  15820. var cache = this.cache;
  15821. var unit = textures.allocateTextureUnit();
  15822. if ( cache[ 0 ] !== unit ) {
  15823. gl.uniform1i( this.addr, unit );
  15824. cache[ 0 ] = unit;
  15825. }
  15826. textures.safeSetTextureCube( v || emptyCubeTexture, unit );
  15827. }
  15828. // Integer / Boolean vectors or arrays thereof (always flat arrays)
  15829. function setValueV1i( gl, v ) {
  15830. var cache = this.cache;
  15831. if ( cache[ 0 ] === v ) { return; }
  15832. gl.uniform1i( this.addr, v );
  15833. cache[ 0 ] = v;
  15834. }
  15835. function setValueV2i( gl, v ) {
  15836. var cache = this.cache;
  15837. if ( arraysEqual( cache, v ) ) { return; }
  15838. gl.uniform2iv( this.addr, v );
  15839. copyArray( cache, v );
  15840. }
  15841. function setValueV3i( gl, v ) {
  15842. var cache = this.cache;
  15843. if ( arraysEqual( cache, v ) ) { return; }
  15844. gl.uniform3iv( this.addr, v );
  15845. copyArray( cache, v );
  15846. }
  15847. function setValueV4i( gl, v ) {
  15848. var cache = this.cache;
  15849. if ( arraysEqual( cache, v ) ) { return; }
  15850. gl.uniform4iv( this.addr, v );
  15851. copyArray( cache, v );
  15852. }
  15853. // uint
  15854. function setValueV1ui( gl, v ) {
  15855. var cache = this.cache;
  15856. if ( cache[ 0 ] === v ) { return; }
  15857. gl.uniform1ui( this.addr, v );
  15858. cache[ 0 ] = v;
  15859. }
  15860. // Helper to pick the right setter for the singular case
  15861. function getSingularSetter( type ) {
  15862. switch ( type ) {
  15863. case 0x1406: return setValueV1f; // FLOAT
  15864. case 0x8b50: return setValueV2f; // _VEC2
  15865. case 0x8b51: return setValueV3f; // _VEC3
  15866. case 0x8b52: return setValueV4f; // _VEC4
  15867. case 0x8b5a: return setValueM2; // _MAT2
  15868. case 0x8b5b: return setValueM3; // _MAT3
  15869. case 0x8b5c: return setValueM4; // _MAT4
  15870. case 0x1404: case 0x8b56: return setValueV1i; // INT, BOOL
  15871. case 0x8b53: case 0x8b57: return setValueV2i; // _VEC2
  15872. case 0x8b54: case 0x8b58: return setValueV3i; // _VEC3
  15873. case 0x8b55: case 0x8b59: return setValueV4i; // _VEC4
  15874. case 0x1405: return setValueV1ui; // UINT
  15875. case 0x8b5e: // SAMPLER_2D
  15876. case 0x8d66: // SAMPLER_EXTERNAL_OES
  15877. case 0x8dca: // INT_SAMPLER_2D
  15878. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  15879. case 0x8b62: // SAMPLER_2D_SHADOW
  15880. return setValueT1;
  15881. case 0x8b5f: // SAMPLER_3D
  15882. case 0x8dcb: // INT_SAMPLER_3D
  15883. case 0x8dd3: // UNSIGNED_INT_SAMPLER_3D
  15884. return setValueT3D1;
  15885. case 0x8b60: // SAMPLER_CUBE
  15886. case 0x8dcc: // INT_SAMPLER_CUBE
  15887. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  15888. case 0x8dc5: // SAMPLER_CUBE_SHADOW
  15889. return setValueT6;
  15890. case 0x8dc1: // SAMPLER_2D_ARRAY
  15891. case 0x8dcf: // INT_SAMPLER_2D_ARRAY
  15892. case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY
  15893. case 0x8dc4: // SAMPLER_2D_ARRAY_SHADOW
  15894. return setValueT2DArray1;
  15895. }
  15896. }
  15897. // Array of scalars
  15898. function setValueV1fArray( gl, v ) {
  15899. gl.uniform1fv( this.addr, v );
  15900. }
  15901. // Integer / Boolean vectors or arrays thereof (always flat arrays)
  15902. function setValueV1iArray( gl, v ) {
  15903. gl.uniform1iv( this.addr, v );
  15904. }
  15905. function setValueV2iArray( gl, v ) {
  15906. gl.uniform2iv( this.addr, v );
  15907. }
  15908. function setValueV3iArray( gl, v ) {
  15909. gl.uniform3iv( this.addr, v );
  15910. }
  15911. function setValueV4iArray( gl, v ) {
  15912. gl.uniform4iv( this.addr, v );
  15913. }
  15914. // Array of vectors (flat or from THREE classes)
  15915. function setValueV2fArray( gl, v ) {
  15916. var data = flatten( v, this.size, 2 );
  15917. gl.uniform2fv( this.addr, data );
  15918. }
  15919. function setValueV3fArray( gl, v ) {
  15920. var data = flatten( v, this.size, 3 );
  15921. gl.uniform3fv( this.addr, data );
  15922. }
  15923. function setValueV4fArray( gl, v ) {
  15924. var data = flatten( v, this.size, 4 );
  15925. gl.uniform4fv( this.addr, data );
  15926. }
  15927. // Array of matrices (flat or from THREE clases)
  15928. function setValueM2Array( gl, v ) {
  15929. var data = flatten( v, this.size, 4 );
  15930. gl.uniformMatrix2fv( this.addr, false, data );
  15931. }
  15932. function setValueM3Array( gl, v ) {
  15933. var data = flatten( v, this.size, 9 );
  15934. gl.uniformMatrix3fv( this.addr, false, data );
  15935. }
  15936. function setValueM4Array( gl, v ) {
  15937. var data = flatten( v, this.size, 16 );
  15938. gl.uniformMatrix4fv( this.addr, false, data );
  15939. }
  15940. // Array of textures (2D / Cube)
  15941. function setValueT1Array( gl, v, textures ) {
  15942. var n = v.length;
  15943. var units = allocTexUnits( textures, n );
  15944. gl.uniform1iv( this.addr, units );
  15945. for ( var i = 0; i !== n; ++ i ) {
  15946. textures.safeSetTexture2D( v[ i ] || emptyTexture, units[ i ] );
  15947. }
  15948. }
  15949. function setValueT6Array( gl, v, textures ) {
  15950. var n = v.length;
  15951. var units = allocTexUnits( textures, n );
  15952. gl.uniform1iv( this.addr, units );
  15953. for ( var i = 0; i !== n; ++ i ) {
  15954. textures.safeSetTextureCube( v[ i ] || emptyCubeTexture, units[ i ] );
  15955. }
  15956. }
  15957. // Helper to pick the right setter for a pure (bottom-level) array
  15958. function getPureArraySetter( type ) {
  15959. switch ( type ) {
  15960. case 0x1406: return setValueV1fArray; // FLOAT
  15961. case 0x8b50: return setValueV2fArray; // _VEC2
  15962. case 0x8b51: return setValueV3fArray; // _VEC3
  15963. case 0x8b52: return setValueV4fArray; // _VEC4
  15964. case 0x8b5a: return setValueM2Array; // _MAT2
  15965. case 0x8b5b: return setValueM3Array; // _MAT3
  15966. case 0x8b5c: return setValueM4Array; // _MAT4
  15967. case 0x1404: case 0x8b56: return setValueV1iArray; // INT, BOOL
  15968. case 0x8b53: case 0x8b57: return setValueV2iArray; // _VEC2
  15969. case 0x8b54: case 0x8b58: return setValueV3iArray; // _VEC3
  15970. case 0x8b55: case 0x8b59: return setValueV4iArray; // _VEC4
  15971. case 0x8b5e: // SAMPLER_2D
  15972. case 0x8d66: // SAMPLER_EXTERNAL_OES
  15973. case 0x8dca: // INT_SAMPLER_2D
  15974. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  15975. case 0x8b62: // SAMPLER_2D_SHADOW
  15976. return setValueT1Array;
  15977. case 0x8b60: // SAMPLER_CUBE
  15978. case 0x8dcc: // INT_SAMPLER_CUBE
  15979. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  15980. case 0x8dc5: // SAMPLER_CUBE_SHADOW
  15981. return setValueT6Array;
  15982. }
  15983. }
  15984. // --- Uniform Classes ---
  15985. function SingleUniform( id, activeInfo, addr ) {
  15986. this.id = id;
  15987. this.addr = addr;
  15988. this.cache = [];
  15989. this.setValue = getSingularSetter( activeInfo.type );
  15990. // this.path = activeInfo.name; // DEBUG
  15991. }
  15992. function PureArrayUniform( id, activeInfo, addr ) {
  15993. this.id = id;
  15994. this.addr = addr;
  15995. this.cache = [];
  15996. this.size = activeInfo.size;
  15997. this.setValue = getPureArraySetter( activeInfo.type );
  15998. // this.path = activeInfo.name; // DEBUG
  15999. }
  16000. PureArrayUniform.prototype.updateCache = function ( data ) {
  16001. var cache = this.cache;
  16002. if ( data instanceof Float32Array && cache.length !== data.length ) {
  16003. this.cache = new Float32Array( data.length );
  16004. }
  16005. copyArray( cache, data );
  16006. };
  16007. function StructuredUniform( id ) {
  16008. this.id = id;
  16009. this.seq = [];
  16010. this.map = {};
  16011. }
  16012. StructuredUniform.prototype.setValue = function ( gl, value, textures ) {
  16013. var seq = this.seq;
  16014. for ( var i = 0, n = seq.length; i !== n; ++ i ) {
  16015. var u = seq[ i ];
  16016. u.setValue( gl, value[ u.id ], textures );
  16017. }
  16018. };
  16019. // --- Top-level ---
  16020. // Parser - builds up the property tree from the path strings
  16021. var RePathPart = /([\w\d_]+)(\])?(\[|\.)?/g;
  16022. // extracts
  16023. // - the identifier (member name or array index)
  16024. // - followed by an optional right bracket (found when array index)
  16025. // - followed by an optional left bracket or dot (type of subscript)
  16026. //
  16027. // Note: These portions can be read in a non-overlapping fashion and
  16028. // allow straightforward parsing of the hierarchy that WebGL encodes
  16029. // in the uniform names.
  16030. function addUniform( container, uniformObject ) {
  16031. container.seq.push( uniformObject );
  16032. container.map[ uniformObject.id ] = uniformObject;
  16033. }
  16034. function parseUniform( activeInfo, addr, container ) {
  16035. var path = activeInfo.name,
  16036. pathLength = path.length;
  16037. // reset RegExp object, because of the early exit of a previous run
  16038. RePathPart.lastIndex = 0;
  16039. while ( true ) {
  16040. var match = RePathPart.exec( path ),
  16041. matchEnd = RePathPart.lastIndex,
  16042. id = match[ 1 ],
  16043. idIsIndex = match[ 2 ] === ']',
  16044. subscript = match[ 3 ];
  16045. if ( idIsIndex ) { id = id | 0; } // convert to integer
  16046. if ( subscript === undefined || subscript === '[' && matchEnd + 2 === pathLength ) {
  16047. // bare name or "pure" bottom-level array "[0]" suffix
  16048. addUniform( container, subscript === undefined ?
  16049. new SingleUniform( id, activeInfo, addr ) :
  16050. new PureArrayUniform( id, activeInfo, addr ) );
  16051. break;
  16052. } else {
  16053. // step into inner node / create it in case it doesn't exist
  16054. var map = container.map, next = map[ id ];
  16055. if ( next === undefined ) {
  16056. next = new StructuredUniform( id );
  16057. addUniform( container, next );
  16058. }
  16059. container = next;
  16060. }
  16061. }
  16062. }
  16063. // Root Container
  16064. function WebGLUniforms( gl, program ) {
  16065. this.seq = [];
  16066. this.map = {};
  16067. var n = gl.getProgramParameter( program, 35718 );
  16068. for ( var i = 0; i < n; ++ i ) {
  16069. var info = gl.getActiveUniform( program, i ),
  16070. addr = gl.getUniformLocation( program, info.name );
  16071. parseUniform( info, addr, this );
  16072. }
  16073. }
  16074. WebGLUniforms.prototype.setValue = function ( gl, name, value, textures ) {
  16075. var u = this.map[ name ];
  16076. if ( u !== undefined ) { u.setValue( gl, value, textures ); }
  16077. };
  16078. WebGLUniforms.prototype.setOptional = function ( gl, object, name ) {
  16079. var v = object[ name ];
  16080. if ( v !== undefined ) { this.setValue( gl, name, v ); }
  16081. };
  16082. // Static interface
  16083. WebGLUniforms.upload = function ( gl, seq, values, textures ) {
  16084. for ( var i = 0, n = seq.length; i !== n; ++ i ) {
  16085. var u = seq[ i ],
  16086. v = values[ u.id ];
  16087. if ( v.needsUpdate !== false ) {
  16088. // note: always updating when .needsUpdate is undefined
  16089. u.setValue( gl, v.value, textures );
  16090. }
  16091. }
  16092. };
  16093. WebGLUniforms.seqWithValue = function ( seq, values ) {
  16094. var r = [];
  16095. for ( var i = 0, n = seq.length; i !== n; ++ i ) {
  16096. var u = seq[ i ];
  16097. if ( u.id in values ) { r.push( u ); }
  16098. }
  16099. return r;
  16100. };
  16101. /**
  16102. * @author mrdoob / http://mrdoob.com/
  16103. */
  16104. function WebGLShader( gl, type, string ) {
  16105. var shader = gl.createShader( type );
  16106. gl.shaderSource( shader, string );
  16107. gl.compileShader( shader );
  16108. return shader;
  16109. }
  16110. /**
  16111. * @author mrdoob / http://mrdoob.com/
  16112. */
  16113. var programIdCount = 0;
  16114. function addLineNumbers( string ) {
  16115. var lines = string.split( '\n' );
  16116. for ( var i = 0; i < lines.length; i ++ ) {
  16117. lines[ i ] = ( i + 1 ) + ': ' + lines[ i ];
  16118. }
  16119. return lines.join( '\n' );
  16120. }
  16121. function getEncodingComponents( encoding ) {
  16122. switch ( encoding ) {
  16123. case LinearEncoding:
  16124. return [ 'Linear', '( value )' ];
  16125. case sRGBEncoding:
  16126. return [ 'sRGB', '( value )' ];
  16127. case RGBEEncoding:
  16128. return [ 'RGBE', '( value )' ];
  16129. case RGBM7Encoding:
  16130. return [ 'RGBM', '( value, 7.0 )' ];
  16131. case RGBM16Encoding:
  16132. return [ 'RGBM', '( value, 16.0 )' ];
  16133. case RGBDEncoding:
  16134. return [ 'RGBD', '( value, 256.0 )' ];
  16135. case GammaEncoding:
  16136. return [ 'Gamma', '( value, float( GAMMA_FACTOR ) )' ];
  16137. case LogLuvEncoding:
  16138. return [ 'LogLuv', '( value )' ];
  16139. default:
  16140. throw new Error( 'unsupported encoding: ' + encoding );
  16141. }
  16142. }
  16143. function getShaderErrors( gl, shader, type ) {
  16144. var status = gl.getShaderParameter( shader, 35713 );
  16145. var log = gl.getShaderInfoLog( shader ).trim();
  16146. if ( status && log === '' ) { return ''; }
  16147. // --enable-privileged-webgl-extension
  16148. // console.log( '**' + type + '**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) );
  16149. var source = gl.getShaderSource( shader );
  16150. return 'THREE.WebGLShader: gl.getShaderInfoLog() ' + type + '\n' + log + addLineNumbers( source );
  16151. }
  16152. function getTexelDecodingFunction( functionName, encoding ) {
  16153. var components = getEncodingComponents( encoding );
  16154. return 'vec4 ' + functionName + '( vec4 value ) { return ' + components[ 0 ] + 'ToLinear' + components[ 1 ] + '; }';
  16155. }
  16156. function getTexelEncodingFunction( functionName, encoding ) {
  16157. var components = getEncodingComponents( encoding );
  16158. return 'vec4 ' + functionName + '( vec4 value ) { return LinearTo' + components[ 0 ] + components[ 1 ] + '; }';
  16159. }
  16160. function getToneMappingFunction( functionName, toneMapping ) {
  16161. var toneMappingName;
  16162. switch ( toneMapping ) {
  16163. case LinearToneMapping:
  16164. toneMappingName = 'Linear';
  16165. break;
  16166. case ReinhardToneMapping:
  16167. toneMappingName = 'Reinhard';
  16168. break;
  16169. case Uncharted2ToneMapping:
  16170. toneMappingName = 'Uncharted2';
  16171. break;
  16172. case CineonToneMapping:
  16173. toneMappingName = 'OptimizedCineon';
  16174. break;
  16175. case ACESFilmicToneMapping:
  16176. toneMappingName = 'ACESFilmic';
  16177. break;
  16178. default:
  16179. throw new Error( 'unsupported toneMapping: ' + toneMapping );
  16180. }
  16181. return 'vec3 ' + functionName + '( vec3 color ) { return ' + toneMappingName + 'ToneMapping( color ); }';
  16182. }
  16183. function generateExtensions( parameters ) {
  16184. var chunks = [
  16185. ( parameters.extensionDerivatives || parameters.envMapCubeUV || parameters.bumpMap || parameters.tangentSpaceNormalMap || parameters.clearcoatNormalMap || parameters.flatShading || parameters.shaderID === 'physical' ) ? '#extension GL_OES_standard_derivatives : enable' : '',
  16186. ( parameters.extensionFragDepth || parameters.logarithmicDepthBuffer ) && parameters.rendererExtensionFragDepth ? '#extension GL_EXT_frag_depth : enable' : '',
  16187. ( parameters.extensionDrawBuffers && parameters.rendererExtensionDrawBuffers ) ? '#extension GL_EXT_draw_buffers : require' : '',
  16188. ( parameters.extensionShaderTextureLOD || parameters.envMap ) && parameters.rendererExtensionShaderTextureLod ? '#extension GL_EXT_shader_texture_lod : enable' : ''
  16189. ];
  16190. return chunks.filter( filterEmptyLine ).join( '\n' );
  16191. }
  16192. function generateDefines( defines ) {
  16193. var chunks = [];
  16194. for ( var name in defines ) {
  16195. var value = defines[ name ];
  16196. if ( value === false ) { continue; }
  16197. chunks.push( '#define ' + name + ' ' + value );
  16198. }
  16199. return chunks.join( '\n' );
  16200. }
  16201. function fetchAttributeLocations( gl, program ) {
  16202. var attributes = {};
  16203. var n = gl.getProgramParameter( program, 35721 );
  16204. for ( var i = 0; i < n; i ++ ) {
  16205. var info = gl.getActiveAttrib( program, i );
  16206. var name = info.name;
  16207. // console.log( 'THREE.WebGLProgram: ACTIVE VERTEX ATTRIBUTE:', name, i );
  16208. attributes[ name ] = gl.getAttribLocation( program, name );
  16209. }
  16210. return attributes;
  16211. }
  16212. function filterEmptyLine( string ) {
  16213. return string !== '';
  16214. }
  16215. function replaceLightNums( string, parameters ) {
  16216. return string
  16217. .replace( /NUM_DIR_LIGHTS/g, parameters.numDirLights )
  16218. .replace( /NUM_SPOT_LIGHTS/g, parameters.numSpotLights )
  16219. .replace( /NUM_RECT_AREA_LIGHTS/g, parameters.numRectAreaLights )
  16220. .replace( /NUM_POINT_LIGHTS/g, parameters.numPointLights )
  16221. .replace( /NUM_HEMI_LIGHTS/g, parameters.numHemiLights )
  16222. .replace( /NUM_DIR_LIGHT_SHADOWS/g, parameters.numDirLightShadows )
  16223. .replace( /NUM_SPOT_LIGHT_SHADOWS/g, parameters.numSpotLightShadows )
  16224. .replace( /NUM_POINT_LIGHT_SHADOWS/g, parameters.numPointLightShadows );
  16225. }
  16226. function replaceClippingPlaneNums( string, parameters ) {
  16227. return string
  16228. .replace( /NUM_CLIPPING_PLANES/g, parameters.numClippingPlanes )
  16229. .replace( /UNION_CLIPPING_PLANES/g, ( parameters.numClippingPlanes - parameters.numClipIntersection ) );
  16230. }
  16231. // Resolve Includes
  16232. var includePattern = /^[ \t]*#include +<([\w\d./]+)>/gm;
  16233. function resolveIncludes( string ) {
  16234. return string.replace( includePattern, includeReplacer );
  16235. }
  16236. function includeReplacer( match, include ) {
  16237. var string = ShaderChunk[ include ];
  16238. if ( string === undefined ) {
  16239. throw new Error( 'Can not resolve #include <' + include + '>' );
  16240. }
  16241. return resolveIncludes( string );
  16242. }
  16243. // Unroll Loops
  16244. var deprecatedUnrollLoopPattern = /#pragma unroll_loop[\s]+?for \( int i \= (\d+)\; i < (\d+)\; i \+\+ \) \{([\s\S]+?)(?=\})\}/g;
  16245. var unrollLoopPattern = /#pragma unroll_loop_start[\s]+?for \( int i \= (\d+)\; i < (\d+)\; i \+\+ \) \{([\s\S]+?)(?=\})\}[\s]+?#pragma unroll_loop_end/g;
  16246. function unrollLoops( string ) {
  16247. return string
  16248. .replace( unrollLoopPattern, loopReplacer )
  16249. .replace( deprecatedUnrollLoopPattern, deprecatedLoopReplacer );
  16250. }
  16251. function deprecatedLoopReplacer( match, start, end, snippet ) {
  16252. console.warn( 'WebGLProgram: #pragma unroll_loop shader syntax is deprecated. Please use #pragma unroll_loop_start syntax instead.' );
  16253. return loopReplacer( match, start, end, snippet );
  16254. }
  16255. function loopReplacer( match, start, end, snippet ) {
  16256. var string = '';
  16257. for ( var i = parseInt( start ); i < parseInt( end ); i ++ ) {
  16258. string += snippet
  16259. .replace( /\[ i \]/g, '[ ' + i + ' ]' )
  16260. .replace( /UNROLLED_LOOP_INDEX/g, i );
  16261. }
  16262. return string;
  16263. }
  16264. //
  16265. function generatePrecision( parameters ) {
  16266. var precisionstring = "precision " + parameters.precision + " float;\nprecision " + parameters.precision + " int;";
  16267. if ( parameters.precision === "highp" ) {
  16268. precisionstring += "\n#define HIGH_PRECISION";
  16269. } else if ( parameters.precision === "mediump" ) {
  16270. precisionstring += "\n#define MEDIUM_PRECISION";
  16271. } else if ( parameters.precision === "lowp" ) {
  16272. precisionstring += "\n#define LOW_PRECISION";
  16273. }
  16274. return precisionstring;
  16275. }
  16276. function generateShadowMapTypeDefine( parameters ) {
  16277. var shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC';
  16278. if ( parameters.shadowMapType === PCFShadowMap ) {
  16279. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF';
  16280. } else if ( parameters.shadowMapType === PCFSoftShadowMap ) {
  16281. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT';
  16282. } else if ( parameters.shadowMapType === VSMShadowMap ) {
  16283. shadowMapTypeDefine = 'SHADOWMAP_TYPE_VSM';
  16284. }
  16285. return shadowMapTypeDefine;
  16286. }
  16287. function generateEnvMapTypeDefine( parameters ) {
  16288. var envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  16289. if ( parameters.envMap ) {
  16290. switch ( parameters.envMapMode ) {
  16291. case CubeReflectionMapping:
  16292. case CubeRefractionMapping:
  16293. envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  16294. break;
  16295. case CubeUVReflectionMapping:
  16296. case CubeUVRefractionMapping:
  16297. envMapTypeDefine = 'ENVMAP_TYPE_CUBE_UV';
  16298. break;
  16299. case EquirectangularReflectionMapping:
  16300. case EquirectangularRefractionMapping:
  16301. envMapTypeDefine = 'ENVMAP_TYPE_EQUIREC';
  16302. break;
  16303. case SphericalReflectionMapping:
  16304. envMapTypeDefine = 'ENVMAP_TYPE_SPHERE';
  16305. break;
  16306. }
  16307. }
  16308. return envMapTypeDefine;
  16309. }
  16310. function generateEnvMapModeDefine( parameters ) {
  16311. var envMapModeDefine = 'ENVMAP_MODE_REFLECTION';
  16312. if ( parameters.envMap ) {
  16313. switch ( parameters.envMapMode ) {
  16314. case CubeRefractionMapping:
  16315. case EquirectangularRefractionMapping:
  16316. envMapModeDefine = 'ENVMAP_MODE_REFRACTION';
  16317. break;
  16318. }
  16319. }
  16320. return envMapModeDefine;
  16321. }
  16322. function generateEnvMapBlendingDefine( parameters ) {
  16323. var envMapBlendingDefine = 'ENVMAP_BLENDING_NONE';
  16324. if ( parameters.envMap ) {
  16325. switch ( parameters.combine ) {
  16326. case MultiplyOperation:
  16327. envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  16328. break;
  16329. case MixOperation:
  16330. envMapBlendingDefine = 'ENVMAP_BLENDING_MIX';
  16331. break;
  16332. case AddOperation:
  16333. envMapBlendingDefine = 'ENVMAP_BLENDING_ADD';
  16334. break;
  16335. }
  16336. }
  16337. return envMapBlendingDefine;
  16338. }
  16339. function WebGLProgram( renderer, cacheKey, parameters ) {
  16340. var gl = renderer.getContext();
  16341. var defines = parameters.defines;
  16342. var vertexShader = parameters.vertexShader;
  16343. var fragmentShader = parameters.fragmentShader;
  16344. var shadowMapTypeDefine = generateShadowMapTypeDefine( parameters );
  16345. var envMapTypeDefine = generateEnvMapTypeDefine( parameters );
  16346. var envMapModeDefine = generateEnvMapModeDefine( parameters );
  16347. var envMapBlendingDefine = generateEnvMapBlendingDefine( parameters );
  16348. var gammaFactorDefine = ( renderer.gammaFactor > 0 ) ? renderer.gammaFactor : 1.0;
  16349. var customExtensions = parameters.isWebGL2 ? '' : generateExtensions( parameters );
  16350. var customDefines = generateDefines( defines );
  16351. var program = gl.createProgram();
  16352. var prefixVertex, prefixFragment;
  16353. if ( parameters.isRawShaderMaterial ) {
  16354. prefixVertex = [
  16355. customDefines
  16356. ].filter( filterEmptyLine ).join( '\n' );
  16357. if ( prefixVertex.length > 0 ) {
  16358. prefixVertex += '\n';
  16359. }
  16360. prefixFragment = [
  16361. customExtensions,
  16362. customDefines
  16363. ].filter( filterEmptyLine ).join( '\n' );
  16364. if ( prefixFragment.length > 0 ) {
  16365. prefixFragment += '\n';
  16366. }
  16367. } else {
  16368. prefixVertex = [
  16369. generatePrecision( parameters ),
  16370. '#define SHADER_NAME ' + parameters.shaderName,
  16371. customDefines,
  16372. parameters.instancing ? '#define USE_INSTANCING' : '',
  16373. parameters.supportsVertexTextures ? '#define VERTEX_TEXTURES' : '',
  16374. '#define GAMMA_FACTOR ' + gammaFactorDefine,
  16375. '#define MAX_BONES ' + parameters.maxBones,
  16376. ( parameters.useFog && parameters.fog ) ? '#define USE_FOG' : '',
  16377. ( parameters.useFog && parameters.fogExp2 ) ? '#define FOG_EXP2' : '',
  16378. parameters.map ? '#define USE_MAP' : '',
  16379. parameters.envMap ? '#define USE_ENVMAP' : '',
  16380. parameters.envMap ? '#define ' + envMapModeDefine : '',
  16381. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  16382. parameters.aoMap ? '#define USE_AOMAP' : '',
  16383. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  16384. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  16385. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  16386. ( parameters.normalMap && parameters.objectSpaceNormalMap ) ? '#define OBJECTSPACE_NORMALMAP' : '',
  16387. ( parameters.normalMap && parameters.tangentSpaceNormalMap ) ? '#define TANGENTSPACE_NORMALMAP' : '',
  16388. parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '',
  16389. parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '',
  16390. parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '',
  16391. parameters.displacementMap && parameters.supportsVertexTextures ? '#define USE_DISPLACEMENTMAP' : '',
  16392. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  16393. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  16394. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  16395. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  16396. parameters.vertexTangents ? '#define USE_TANGENT' : '',
  16397. parameters.vertexColors ? '#define USE_COLOR' : '',
  16398. parameters.vertexUvs ? '#define USE_UV' : '',
  16399. parameters.uvsVertexOnly ? '#define UVS_VERTEX_ONLY' : '',
  16400. parameters.flatShading ? '#define FLAT_SHADED' : '',
  16401. parameters.skinning ? '#define USE_SKINNING' : '',
  16402. parameters.useVertexTexture ? '#define BONE_TEXTURE' : '',
  16403. parameters.morphTargets ? '#define USE_MORPHTARGETS' : '',
  16404. parameters.morphNormals && parameters.flatShading === false ? '#define USE_MORPHNORMALS' : '',
  16405. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  16406. parameters.flipSided ? '#define FLIP_SIDED' : '',
  16407. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  16408. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  16409. parameters.sizeAttenuation ? '#define USE_SIZEATTENUATION' : '',
  16410. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  16411. ( parameters.logarithmicDepthBuffer && parameters.rendererExtensionFragDepth ) ? '#define USE_LOGDEPTHBUF_EXT' : '',
  16412. 'uniform mat4 modelMatrix;',
  16413. 'uniform mat4 modelViewMatrix;',
  16414. 'uniform mat4 projectionMatrix;',
  16415. 'uniform mat4 viewMatrix;',
  16416. 'uniform mat3 normalMatrix;',
  16417. 'uniform vec3 cameraPosition;',
  16418. 'uniform bool isOrthographic;',
  16419. '#ifdef USE_INSTANCING',
  16420. ' attribute mat4 instanceMatrix;',
  16421. '#endif',
  16422. 'attribute vec3 position;',
  16423. 'attribute vec3 normal;',
  16424. 'attribute vec2 uv;',
  16425. '#ifdef USE_TANGENT',
  16426. ' attribute vec4 tangent;',
  16427. '#endif',
  16428. '#ifdef USE_COLOR',
  16429. ' attribute vec3 color;',
  16430. '#endif',
  16431. '#ifdef USE_MORPHTARGETS',
  16432. ' attribute vec3 morphTarget0;',
  16433. ' attribute vec3 morphTarget1;',
  16434. ' attribute vec3 morphTarget2;',
  16435. ' attribute vec3 morphTarget3;',
  16436. ' #ifdef USE_MORPHNORMALS',
  16437. ' attribute vec3 morphNormal0;',
  16438. ' attribute vec3 morphNormal1;',
  16439. ' attribute vec3 morphNormal2;',
  16440. ' attribute vec3 morphNormal3;',
  16441. ' #else',
  16442. ' attribute vec3 morphTarget4;',
  16443. ' attribute vec3 morphTarget5;',
  16444. ' attribute vec3 morphTarget6;',
  16445. ' attribute vec3 morphTarget7;',
  16446. ' #endif',
  16447. '#endif',
  16448. '#ifdef USE_SKINNING',
  16449. ' attribute vec4 skinIndex;',
  16450. ' attribute vec4 skinWeight;',
  16451. '#endif',
  16452. '\n'
  16453. ].filter( filterEmptyLine ).join( '\n' );
  16454. prefixFragment = [
  16455. customExtensions,
  16456. generatePrecision( parameters ),
  16457. '#define SHADER_NAME ' + parameters.shaderName,
  16458. customDefines,
  16459. parameters.alphaTest ? '#define ALPHATEST ' + parameters.alphaTest + ( parameters.alphaTest % 1 ? '' : '.0' ) : '', // add '.0' if integer
  16460. '#define GAMMA_FACTOR ' + gammaFactorDefine,
  16461. ( parameters.useFog && parameters.fog ) ? '#define USE_FOG' : '',
  16462. ( parameters.useFog && parameters.fogExp2 ) ? '#define FOG_EXP2' : '',
  16463. parameters.map ? '#define USE_MAP' : '',
  16464. parameters.matcap ? '#define USE_MATCAP' : '',
  16465. parameters.envMap ? '#define USE_ENVMAP' : '',
  16466. parameters.envMap ? '#define ' + envMapTypeDefine : '',
  16467. parameters.envMap ? '#define ' + envMapModeDefine : '',
  16468. parameters.envMap ? '#define ' + envMapBlendingDefine : '',
  16469. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  16470. parameters.aoMap ? '#define USE_AOMAP' : '',
  16471. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  16472. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  16473. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  16474. ( parameters.normalMap && parameters.objectSpaceNormalMap ) ? '#define OBJECTSPACE_NORMALMAP' : '',
  16475. ( parameters.normalMap && parameters.tangentSpaceNormalMap ) ? '#define TANGENTSPACE_NORMALMAP' : '',
  16476. parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '',
  16477. parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '',
  16478. parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '',
  16479. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  16480. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  16481. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  16482. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  16483. parameters.sheen ? '#define USE_SHEEN' : '',
  16484. parameters.vertexTangents ? '#define USE_TANGENT' : '',
  16485. parameters.vertexColors ? '#define USE_COLOR' : '',
  16486. parameters.vertexUvs ? '#define USE_UV' : '',
  16487. parameters.uvsVertexOnly ? '#define UVS_VERTEX_ONLY' : '',
  16488. parameters.gradientMap ? '#define USE_GRADIENTMAP' : '',
  16489. parameters.flatShading ? '#define FLAT_SHADED' : '',
  16490. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  16491. parameters.flipSided ? '#define FLIP_SIDED' : '',
  16492. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  16493. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  16494. parameters.premultipliedAlpha ? '#define PREMULTIPLIED_ALPHA' : '',
  16495. parameters.physicallyCorrectLights ? '#define PHYSICALLY_CORRECT_LIGHTS' : '',
  16496. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  16497. ( parameters.logarithmicDepthBuffer && parameters.rendererExtensionFragDepth ) ? '#define USE_LOGDEPTHBUF_EXT' : '',
  16498. ( ( parameters.extensionShaderTextureLOD || parameters.envMap ) && parameters.rendererExtensionShaderTextureLod ) ? '#define TEXTURE_LOD_EXT' : '',
  16499. 'uniform mat4 viewMatrix;',
  16500. 'uniform vec3 cameraPosition;',
  16501. 'uniform bool isOrthographic;',
  16502. ( parameters.toneMapping !== NoToneMapping ) ? '#define TONE_MAPPING' : '',
  16503. ( parameters.toneMapping !== NoToneMapping ) ? ShaderChunk[ 'tonemapping_pars_fragment' ] : '', // this code is required here because it is used by the toneMapping() function defined below
  16504. ( parameters.toneMapping !== NoToneMapping ) ? getToneMappingFunction( 'toneMapping', parameters.toneMapping ) : '',
  16505. parameters.dithering ? '#define DITHERING' : '',
  16506. ( parameters.outputEncoding || parameters.mapEncoding || parameters.matcapEncoding || parameters.envMapEncoding || parameters.emissiveMapEncoding || parameters.lightMapEncoding ) ?
  16507. ShaderChunk[ 'encodings_pars_fragment' ] : '', // this code is required here because it is used by the various encoding/decoding function defined below
  16508. parameters.mapEncoding ? getTexelDecodingFunction( 'mapTexelToLinear', parameters.mapEncoding ) : '',
  16509. parameters.matcapEncoding ? getTexelDecodingFunction( 'matcapTexelToLinear', parameters.matcapEncoding ) : '',
  16510. parameters.envMapEncoding ? getTexelDecodingFunction( 'envMapTexelToLinear', parameters.envMapEncoding ) : '',
  16511. parameters.emissiveMapEncoding ? getTexelDecodingFunction( 'emissiveMapTexelToLinear', parameters.emissiveMapEncoding ) : '',
  16512. parameters.lightMapEncoding ? getTexelDecodingFunction( 'lightMapTexelToLinear', parameters.lightMapEncoding ) : '',
  16513. parameters.outputEncoding ? getTexelEncodingFunction( 'linearToOutputTexel', parameters.outputEncoding ) : '',
  16514. parameters.depthPacking ? '#define DEPTH_PACKING ' + parameters.depthPacking : '',
  16515. '\n'
  16516. ].filter( filterEmptyLine ).join( '\n' );
  16517. }
  16518. vertexShader = resolveIncludes( vertexShader );
  16519. vertexShader = replaceLightNums( vertexShader, parameters );
  16520. vertexShader = replaceClippingPlaneNums( vertexShader, parameters );
  16521. fragmentShader = resolveIncludes( fragmentShader );
  16522. fragmentShader = replaceLightNums( fragmentShader, parameters );
  16523. fragmentShader = replaceClippingPlaneNums( fragmentShader, parameters );
  16524. vertexShader = unrollLoops( vertexShader );
  16525. fragmentShader = unrollLoops( fragmentShader );
  16526. if ( parameters.isWebGL2 && ! parameters.isRawShaderMaterial ) {
  16527. var isGLSL3ShaderMaterial = false;
  16528. var versionRegex = /^\s*#version\s+300\s+es\s*\n/;
  16529. if ( parameters.isShaderMaterial &&
  16530. vertexShader.match( versionRegex ) !== null &&
  16531. fragmentShader.match( versionRegex ) !== null ) {
  16532. isGLSL3ShaderMaterial = true;
  16533. vertexShader = vertexShader.replace( versionRegex, '' );
  16534. fragmentShader = fragmentShader.replace( versionRegex, '' );
  16535. }
  16536. // GLSL 3.0 conversion
  16537. prefixVertex = [
  16538. '#version 300 es\n',
  16539. '#define attribute in',
  16540. '#define varying out',
  16541. '#define texture2D texture'
  16542. ].join( '\n' ) + '\n' + prefixVertex;
  16543. prefixFragment = [
  16544. '#version 300 es\n',
  16545. '#define varying in',
  16546. isGLSL3ShaderMaterial ? '' : 'out highp vec4 pc_fragColor;',
  16547. isGLSL3ShaderMaterial ? '' : '#define gl_FragColor pc_fragColor',
  16548. '#define gl_FragDepthEXT gl_FragDepth',
  16549. '#define texture2D texture',
  16550. '#define textureCube texture',
  16551. '#define texture2DProj textureProj',
  16552. '#define texture2DLodEXT textureLod',
  16553. '#define texture2DProjLodEXT textureProjLod',
  16554. '#define textureCubeLodEXT textureLod',
  16555. '#define texture2DGradEXT textureGrad',
  16556. '#define texture2DProjGradEXT textureProjGrad',
  16557. '#define textureCubeGradEXT textureGrad'
  16558. ].join( '\n' ) + '\n' + prefixFragment;
  16559. }
  16560. var vertexGlsl = prefixVertex + vertexShader;
  16561. var fragmentGlsl = prefixFragment + fragmentShader;
  16562. // console.log( '*VERTEX*', vertexGlsl );
  16563. // console.log( '*FRAGMENT*', fragmentGlsl );
  16564. var glVertexShader = WebGLShader( gl, 35633, vertexGlsl );
  16565. var glFragmentShader = WebGLShader( gl, 35632, fragmentGlsl );
  16566. gl.attachShader( program, glVertexShader );
  16567. gl.attachShader( program, glFragmentShader );
  16568. // Force a particular attribute to index 0.
  16569. if ( parameters.index0AttributeName !== undefined ) {
  16570. gl.bindAttribLocation( program, 0, parameters.index0AttributeName );
  16571. } else if ( parameters.morphTargets === true ) {
  16572. // programs with morphTargets displace position out of attribute 0
  16573. gl.bindAttribLocation( program, 0, 'position' );
  16574. }
  16575. gl.linkProgram( program );
  16576. // check for link errors
  16577. if ( renderer.debug.checkShaderErrors ) {
  16578. var programLog = gl.getProgramInfoLog( program ).trim();
  16579. var vertexLog = gl.getShaderInfoLog( glVertexShader ).trim();
  16580. var fragmentLog = gl.getShaderInfoLog( glFragmentShader ).trim();
  16581. var runnable = true;
  16582. var haveDiagnostics = true;
  16583. if ( gl.getProgramParameter( program, 35714 ) === false ) {
  16584. runnable = false;
  16585. var vertexErrors = getShaderErrors( gl, glVertexShader, 'vertex' );
  16586. var fragmentErrors = getShaderErrors( gl, glFragmentShader, 'fragment' );
  16587. console.error( 'THREE.WebGLProgram: shader error: ', gl.getError(), '35715', gl.getProgramParameter( program, 35715 ), 'gl.getProgramInfoLog', programLog, vertexErrors, fragmentErrors );
  16588. } else if ( programLog !== '' ) {
  16589. console.warn( 'THREE.WebGLProgram: gl.getProgramInfoLog()', programLog );
  16590. } else if ( vertexLog === '' || fragmentLog === '' ) {
  16591. haveDiagnostics = false;
  16592. }
  16593. if ( haveDiagnostics ) {
  16594. this.diagnostics = {
  16595. runnable: runnable,
  16596. programLog: programLog,
  16597. vertexShader: {
  16598. log: vertexLog,
  16599. prefix: prefixVertex
  16600. },
  16601. fragmentShader: {
  16602. log: fragmentLog,
  16603. prefix: prefixFragment
  16604. }
  16605. };
  16606. }
  16607. }
  16608. // clean up
  16609. gl.detachShader( program, glVertexShader );
  16610. gl.detachShader( program, glFragmentShader );
  16611. gl.deleteShader( glVertexShader );
  16612. gl.deleteShader( glFragmentShader );
  16613. // set up caching for uniform locations
  16614. var cachedUniforms;
  16615. this.getUniforms = function () {
  16616. if ( cachedUniforms === undefined ) {
  16617. cachedUniforms = new WebGLUniforms( gl, program );
  16618. }
  16619. return cachedUniforms;
  16620. };
  16621. // set up caching for attribute locations
  16622. var cachedAttributes;
  16623. this.getAttributes = function () {
  16624. if ( cachedAttributes === undefined ) {
  16625. cachedAttributes = fetchAttributeLocations( gl, program );
  16626. }
  16627. return cachedAttributes;
  16628. };
  16629. // free resource
  16630. this.destroy = function () {
  16631. gl.deleteProgram( program );
  16632. this.program = undefined;
  16633. };
  16634. //
  16635. this.name = parameters.shaderName;
  16636. this.id = programIdCount ++;
  16637. this.cacheKey = cacheKey;
  16638. this.usedTimes = 1;
  16639. this.program = program;
  16640. this.vertexShader = glVertexShader;
  16641. this.fragmentShader = glFragmentShader;
  16642. return this;
  16643. }
  16644. /**
  16645. * @author mrdoob / http://mrdoob.com/
  16646. */
  16647. function WebGLPrograms( renderer, extensions, capabilities ) {
  16648. var programs = [];
  16649. var isWebGL2 = capabilities.isWebGL2;
  16650. var logarithmicDepthBuffer = capabilities.logarithmicDepthBuffer;
  16651. var floatVertexTextures = capabilities.floatVertexTextures;
  16652. var precision = capabilities.precision;
  16653. var maxVertexUniforms = capabilities.maxVertexUniforms;
  16654. var vertexTextures = capabilities.vertexTextures;
  16655. var shaderIDs = {
  16656. MeshDepthMaterial: 'depth',
  16657. MeshDistanceMaterial: 'distanceRGBA',
  16658. MeshNormalMaterial: 'normal',
  16659. MeshBasicMaterial: 'basic',
  16660. MeshLambertMaterial: 'lambert',
  16661. MeshPhongMaterial: 'phong',
  16662. MeshToonMaterial: 'toon',
  16663. MeshStandardMaterial: 'physical',
  16664. MeshPhysicalMaterial: 'physical',
  16665. MeshMatcapMaterial: 'matcap',
  16666. LineBasicMaterial: 'basic',
  16667. LineDashedMaterial: 'dashed',
  16668. PointsMaterial: 'points',
  16669. ShadowMaterial: 'shadow',
  16670. SpriteMaterial: 'sprite'
  16671. };
  16672. var parameterNames = [
  16673. "precision", "isWebGL2", "supportsVertexTextures", "outputEncoding", "instancing",
  16674. "map", "mapEncoding", "matcap", "matcapEncoding", "envMap", "envMapMode", "envMapEncoding", "envMapCubeUV",
  16675. "lightMap", "lightMapEncoding", "aoMap", "emissiveMap", "emissiveMapEncoding", "bumpMap", "normalMap", "objectSpaceNormalMap", "tangentSpaceNormalMap", "clearcoatMap", "clearcoatRoughnessMap", "clearcoatNormalMap", "displacementMap", "specularMap",
  16676. "roughnessMap", "metalnessMap", "gradientMap",
  16677. "alphaMap", "combine", "vertexColors", "vertexTangents", "vertexUvs", "uvsVertexOnly", "fog", "useFog", "fogExp2",
  16678. "flatShading", "sizeAttenuation", "logarithmicDepthBuffer", "skinning",
  16679. "maxBones", "useVertexTexture", "morphTargets", "morphNormals",
  16680. "maxMorphTargets", "maxMorphNormals", "premultipliedAlpha",
  16681. "numDirLights", "numPointLights", "numSpotLights", "numHemiLights", "numRectAreaLights",
  16682. "numDirLightShadows", "numPointLightShadows", "numSpotLightShadows",
  16683. "shadowMapEnabled", "shadowMapType", "toneMapping", 'physicallyCorrectLights',
  16684. "alphaTest", "doubleSided", "flipSided", "numClippingPlanes", "numClipIntersection", "depthPacking", "dithering",
  16685. "sheen"
  16686. ];
  16687. function getShaderObject( material, shaderID ) {
  16688. var shaderobject;
  16689. if ( shaderID ) {
  16690. var shader = ShaderLib[ shaderID ];
  16691. shaderobject = {
  16692. name: material.type,
  16693. uniforms: UniformsUtils.clone( shader.uniforms ),
  16694. vertexShader: shader.vertexShader,
  16695. fragmentShader: shader.fragmentShader
  16696. };
  16697. } else {
  16698. shaderobject = {
  16699. name: material.type,
  16700. uniforms: material.uniforms,
  16701. vertexShader: material.vertexShader,
  16702. fragmentShader: material.fragmentShader
  16703. };
  16704. }
  16705. return shaderobject;
  16706. }
  16707. function allocateBones( object ) {
  16708. var skeleton = object.skeleton;
  16709. var bones = skeleton.bones;
  16710. if ( floatVertexTextures ) {
  16711. return 1024;
  16712. } else {
  16713. // default for when object is not specified
  16714. // ( for example when prebuilding shader to be used with multiple objects )
  16715. //
  16716. // - leave some extra space for other uniforms
  16717. // - limit here is ANGLE's 254 max uniform vectors
  16718. // (up to 54 should be safe)
  16719. var nVertexUniforms = maxVertexUniforms;
  16720. var nVertexMatrices = Math.floor( ( nVertexUniforms - 20 ) / 4 );
  16721. var maxBones = Math.min( nVertexMatrices, bones.length );
  16722. if ( maxBones < bones.length ) {
  16723. console.warn( 'THREE.WebGLRenderer: Skeleton has ' + bones.length + ' bones. This GPU supports ' + maxBones + '.' );
  16724. return 0;
  16725. }
  16726. return maxBones;
  16727. }
  16728. }
  16729. function getTextureEncodingFromMap( map ) {
  16730. var encoding;
  16731. if ( ! map ) {
  16732. encoding = LinearEncoding;
  16733. } else if ( map.isTexture ) {
  16734. encoding = map.encoding;
  16735. } else if ( map.isWebGLRenderTarget ) {
  16736. console.warn( "THREE.WebGLPrograms.getTextureEncodingFromMap: don't use render targets as textures. Use their .texture property instead." );
  16737. encoding = map.texture.encoding;
  16738. }
  16739. return encoding;
  16740. }
  16741. this.getParameters = function ( material, lights, shadows, scene, nClipPlanes, nClipIntersection, object ) {
  16742. var fog = scene.fog;
  16743. var environment = material.isMeshStandardMaterial ? scene.environment : null;
  16744. var envMap = material.envMap || environment;
  16745. var shaderID = shaderIDs[ material.type ];
  16746. // heuristics to create shader parameters according to lights in the scene
  16747. // (not to blow over maxLights budget)
  16748. var maxBones = object.isSkinnedMesh ? allocateBones( object ) : 0;
  16749. if ( material.precision !== null ) {
  16750. precision = capabilities.getMaxPrecision( material.precision );
  16751. if ( precision !== material.precision ) {
  16752. console.warn( 'THREE.WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.' );
  16753. }
  16754. }
  16755. var shaderobject = getShaderObject( material, shaderID );
  16756. material.onBeforeCompile( shaderobject, renderer );
  16757. var currentRenderTarget = renderer.getRenderTarget();
  16758. var parameters = {
  16759. isWebGL2: isWebGL2,
  16760. shaderID: shaderID,
  16761. shaderName: shaderobject.name,
  16762. uniforms: shaderobject.uniforms,
  16763. vertexShader: shaderobject.vertexShader,
  16764. fragmentShader: shaderobject.fragmentShader,
  16765. defines: material.defines,
  16766. isRawShaderMaterial: material.isRawShaderMaterial,
  16767. isShaderMaterial: material.isShaderMaterial,
  16768. precision: precision,
  16769. instancing: object.isInstancedMesh === true,
  16770. supportsVertexTextures: vertexTextures,
  16771. outputEncoding: ( currentRenderTarget !== null ) ? getTextureEncodingFromMap( currentRenderTarget.texture ) : renderer.outputEncoding,
  16772. map: !! material.map,
  16773. mapEncoding: getTextureEncodingFromMap( material.map ),
  16774. matcap: !! material.matcap,
  16775. matcapEncoding: getTextureEncodingFromMap( material.matcap ),
  16776. envMap: !! envMap,
  16777. envMapMode: envMap && envMap.mapping,
  16778. envMapEncoding: getTextureEncodingFromMap( envMap ),
  16779. envMapCubeUV: ( !! envMap ) && ( ( envMap.mapping === CubeUVReflectionMapping ) || ( envMap.mapping === CubeUVRefractionMapping ) ),
  16780. lightMap: !! material.lightMap,
  16781. lightMapEncoding: getTextureEncodingFromMap( material.lightMap ),
  16782. aoMap: !! material.aoMap,
  16783. emissiveMap: !! material.emissiveMap,
  16784. emissiveMapEncoding: getTextureEncodingFromMap( material.emissiveMap ),
  16785. bumpMap: !! material.bumpMap,
  16786. normalMap: !! material.normalMap,
  16787. objectSpaceNormalMap: material.normalMapType === ObjectSpaceNormalMap,
  16788. tangentSpaceNormalMap: material.normalMapType === TangentSpaceNormalMap,
  16789. clearcoatMap: !! material.clearcoatMap,
  16790. clearcoatRoughnessMap: !! material.clearcoatRoughnessMap,
  16791. clearcoatNormalMap: !! material.clearcoatNormalMap,
  16792. displacementMap: !! material.displacementMap,
  16793. roughnessMap: !! material.roughnessMap,
  16794. metalnessMap: !! material.metalnessMap,
  16795. specularMap: !! material.specularMap,
  16796. alphaMap: !! material.alphaMap,
  16797. gradientMap: !! material.gradientMap,
  16798. sheen: !! material.sheen,
  16799. combine: material.combine,
  16800. vertexTangents: ( material.normalMap && material.vertexTangents ),
  16801. vertexColors: material.vertexColors,
  16802. 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,
  16803. uvsVertexOnly: ! ( !! material.map || !! material.bumpMap || !! material.normalMap || !! material.specularMap || !! material.alphaMap || !! material.emissiveMap || !! material.roughnessMap || !! material.metalnessMap || !! material.clearcoatNormalMap ) && !! material.displacementMap,
  16804. fog: !! fog,
  16805. useFog: material.fog,
  16806. fogExp2: ( fog && fog.isFogExp2 ),
  16807. flatShading: material.flatShading,
  16808. sizeAttenuation: material.sizeAttenuation,
  16809. logarithmicDepthBuffer: logarithmicDepthBuffer,
  16810. skinning: material.skinning && maxBones > 0,
  16811. maxBones: maxBones,
  16812. useVertexTexture: floatVertexTextures,
  16813. morphTargets: material.morphTargets,
  16814. morphNormals: material.morphNormals,
  16815. maxMorphTargets: renderer.maxMorphTargets,
  16816. maxMorphNormals: renderer.maxMorphNormals,
  16817. numDirLights: lights.directional.length,
  16818. numPointLights: lights.point.length,
  16819. numSpotLights: lights.spot.length,
  16820. numRectAreaLights: lights.rectArea.length,
  16821. numHemiLights: lights.hemi.length,
  16822. numDirLightShadows: lights.directionalShadowMap.length,
  16823. numPointLightShadows: lights.pointShadowMap.length,
  16824. numSpotLightShadows: lights.spotShadowMap.length,
  16825. numClippingPlanes: nClipPlanes,
  16826. numClipIntersection: nClipIntersection,
  16827. dithering: material.dithering,
  16828. shadowMapEnabled: renderer.shadowMap.enabled && shadows.length > 0,
  16829. shadowMapType: renderer.shadowMap.type,
  16830. toneMapping: material.toneMapped ? renderer.toneMapping : NoToneMapping,
  16831. physicallyCorrectLights: renderer.physicallyCorrectLights,
  16832. premultipliedAlpha: material.premultipliedAlpha,
  16833. alphaTest: material.alphaTest,
  16834. doubleSided: material.side === DoubleSide,
  16835. flipSided: material.side === BackSide,
  16836. depthPacking: ( material.depthPacking !== undefined ) ? material.depthPacking : false,
  16837. index0AttributeName: material.index0AttributeName,
  16838. extensionDerivatives: material.extensions && material.extensions.derivatives,
  16839. extensionFragDepth: material.extensions && material.extensions.fragDepth,
  16840. extensionDrawBuffers: material.extensions && material.extensions.drawBuffers,
  16841. extensionShaderTextureLOD: material.extensions && material.extensions.shaderTextureLOD,
  16842. rendererExtensionFragDepth: isWebGL2 || extensions.get( 'EXT_frag_depth' ) !== null,
  16843. rendererExtensionDrawBuffers: isWebGL2 || extensions.get( 'WEBGL_draw_buffers' ) !== null,
  16844. rendererExtensionShaderTextureLod: isWebGL2 || extensions.get( 'EXT_shader_texture_lod' ) !== null,
  16845. onBeforeCompile: material.onBeforeCompile
  16846. };
  16847. return parameters;
  16848. };
  16849. this.getProgramCacheKey = function ( parameters ) {
  16850. var array = [];
  16851. if ( parameters.shaderID ) {
  16852. array.push( parameters.shaderID );
  16853. } else {
  16854. array.push( parameters.fragmentShader );
  16855. array.push( parameters.vertexShader );
  16856. }
  16857. if ( parameters.defines !== undefined ) {
  16858. for ( var name in parameters.defines ) {
  16859. array.push( name );
  16860. array.push( parameters.defines[ name ] );
  16861. }
  16862. }
  16863. if ( parameters.isRawShaderMaterial === undefined ) {
  16864. for ( var i = 0; i < parameterNames.length; i ++ ) {
  16865. array.push( parameters[ parameterNames[ i ] ] );
  16866. }
  16867. array.push( renderer.outputEncoding );
  16868. array.push( renderer.gammaFactor );
  16869. }
  16870. array.push( parameters.onBeforeCompile.toString() );
  16871. return array.join();
  16872. };
  16873. this.acquireProgram = function ( parameters, cacheKey ) {
  16874. var program;
  16875. // Check if code has been already compiled
  16876. for ( var p = 0, pl = programs.length; p < pl; p ++ ) {
  16877. var preexistingProgram = programs[ p ];
  16878. if ( preexistingProgram.cacheKey === cacheKey ) {
  16879. program = preexistingProgram;
  16880. ++ program.usedTimes;
  16881. break;
  16882. }
  16883. }
  16884. if ( program === undefined ) {
  16885. program = new WebGLProgram( renderer, cacheKey, parameters );
  16886. programs.push( program );
  16887. }
  16888. return program;
  16889. };
  16890. this.releaseProgram = function ( program ) {
  16891. if ( -- program.usedTimes === 0 ) {
  16892. // Remove from unordered set
  16893. var i = programs.indexOf( program );
  16894. programs[ i ] = programs[ programs.length - 1 ];
  16895. programs.pop();
  16896. // Free WebGL resources
  16897. program.destroy();
  16898. }
  16899. };
  16900. // Exposed for resource monitoring & error feedback via renderer.info:
  16901. this.programs = programs;
  16902. }
  16903. /**
  16904. * @author fordacious / fordacious.github.io
  16905. */
  16906. function WebGLProperties() {
  16907. var properties = new WeakMap();
  16908. function get( object ) {
  16909. var map = properties.get( object );
  16910. if ( map === undefined ) {
  16911. map = {};
  16912. properties.set( object, map );
  16913. }
  16914. return map;
  16915. }
  16916. function remove( object ) {
  16917. properties.delete( object );
  16918. }
  16919. function update( object, key, value ) {
  16920. properties.get( object )[ key ] = value;
  16921. }
  16922. function dispose() {
  16923. properties = new WeakMap();
  16924. }
  16925. return {
  16926. get: get,
  16927. remove: remove,
  16928. update: update,
  16929. dispose: dispose
  16930. };
  16931. }
  16932. /**
  16933. * @author mrdoob / http://mrdoob.com/
  16934. */
  16935. function painterSortStable( a, b ) {
  16936. if ( a.groupOrder !== b.groupOrder ) {
  16937. return a.groupOrder - b.groupOrder;
  16938. } else if ( a.renderOrder !== b.renderOrder ) {
  16939. return a.renderOrder - b.renderOrder;
  16940. } else if ( a.program !== b.program ) {
  16941. return a.program.id - b.program.id;
  16942. } else if ( a.material.id !== b.material.id ) {
  16943. return a.material.id - b.material.id;
  16944. } else if ( a.z !== b.z ) {
  16945. return a.z - b.z;
  16946. } else {
  16947. return a.id - b.id;
  16948. }
  16949. }
  16950. function reversePainterSortStable( a, b ) {
  16951. if ( a.groupOrder !== b.groupOrder ) {
  16952. return a.groupOrder - b.groupOrder;
  16953. } else if ( a.renderOrder !== b.renderOrder ) {
  16954. return a.renderOrder - b.renderOrder;
  16955. } else if ( a.z !== b.z ) {
  16956. return b.z - a.z;
  16957. } else {
  16958. return a.id - b.id;
  16959. }
  16960. }
  16961. function WebGLRenderList() {
  16962. var renderItems = [];
  16963. var renderItemsIndex = 0;
  16964. var opaque = [];
  16965. var transparent = [];
  16966. var defaultProgram = { id: - 1 };
  16967. function init() {
  16968. renderItemsIndex = 0;
  16969. opaque.length = 0;
  16970. transparent.length = 0;
  16971. }
  16972. function getNextRenderItem( object, geometry, material, groupOrder, z, group ) {
  16973. var renderItem = renderItems[ renderItemsIndex ];
  16974. if ( renderItem === undefined ) {
  16975. renderItem = {
  16976. id: object.id,
  16977. object: object,
  16978. geometry: geometry,
  16979. material: material,
  16980. program: material.program || defaultProgram,
  16981. groupOrder: groupOrder,
  16982. renderOrder: object.renderOrder,
  16983. z: z,
  16984. group: group
  16985. };
  16986. renderItems[ renderItemsIndex ] = renderItem;
  16987. } else {
  16988. renderItem.id = object.id;
  16989. renderItem.object = object;
  16990. renderItem.geometry = geometry;
  16991. renderItem.material = material;
  16992. renderItem.program = material.program || defaultProgram;
  16993. renderItem.groupOrder = groupOrder;
  16994. renderItem.renderOrder = object.renderOrder;
  16995. renderItem.z = z;
  16996. renderItem.group = group;
  16997. }
  16998. renderItemsIndex ++;
  16999. return renderItem;
  17000. }
  17001. function push( object, geometry, material, groupOrder, z, group ) {
  17002. var renderItem = getNextRenderItem( object, geometry, material, groupOrder, z, group );
  17003. ( material.transparent === true ? transparent : opaque ).push( renderItem );
  17004. }
  17005. function unshift( object, geometry, material, groupOrder, z, group ) {
  17006. var renderItem = getNextRenderItem( object, geometry, material, groupOrder, z, group );
  17007. ( material.transparent === true ? transparent : opaque ).unshift( renderItem );
  17008. }
  17009. function sort( customOpaqueSort, customTransparentSort ) {
  17010. if ( opaque.length > 1 ) { opaque.sort( customOpaqueSort || painterSortStable ); }
  17011. if ( transparent.length > 1 ) { transparent.sort( customTransparentSort || reversePainterSortStable ); }
  17012. }
  17013. function finish() {
  17014. // Clear references from inactive renderItems in the list
  17015. for ( var i = renderItemsIndex, il = renderItems.length; i < il; i ++ ) {
  17016. var renderItem = renderItems[ i ];
  17017. if ( renderItem.id === null ) { break; }
  17018. renderItem.id = null;
  17019. renderItem.object = null;
  17020. renderItem.geometry = null;
  17021. renderItem.material = null;
  17022. renderItem.program = null;
  17023. renderItem.group = null;
  17024. }
  17025. }
  17026. return {
  17027. opaque: opaque,
  17028. transparent: transparent,
  17029. init: init,
  17030. push: push,
  17031. unshift: unshift,
  17032. finish: finish,
  17033. sort: sort
  17034. };
  17035. }
  17036. function WebGLRenderLists() {
  17037. var lists = new WeakMap();
  17038. function onSceneDispose( event ) {
  17039. var scene = event.target;
  17040. scene.removeEventListener( 'dispose', onSceneDispose );
  17041. lists.delete( scene );
  17042. }
  17043. function get( scene, camera ) {
  17044. var cameras = lists.get( scene );
  17045. var list;
  17046. if ( cameras === undefined ) {
  17047. list = new WebGLRenderList();
  17048. lists.set( scene, new WeakMap() );
  17049. lists.get( scene ).set( camera, list );
  17050. scene.addEventListener( 'dispose', onSceneDispose );
  17051. } else {
  17052. list = cameras.get( camera );
  17053. if ( list === undefined ) {
  17054. list = new WebGLRenderList();
  17055. cameras.set( camera, list );
  17056. }
  17057. }
  17058. return list;
  17059. }
  17060. function dispose() {
  17061. lists = new WeakMap();
  17062. }
  17063. return {
  17064. get: get,
  17065. dispose: dispose
  17066. };
  17067. }
  17068. /**
  17069. * @author mrdoob / http://mrdoob.com/
  17070. */
  17071. function UniformsCache() {
  17072. var lights = {};
  17073. return {
  17074. get: function ( light ) {
  17075. if ( lights[ light.id ] !== undefined ) {
  17076. return lights[ light.id ];
  17077. }
  17078. var uniforms;
  17079. switch ( light.type ) {
  17080. case 'DirectionalLight':
  17081. uniforms = {
  17082. direction: new Vector3(),
  17083. color: new Color()
  17084. };
  17085. break;
  17086. case 'SpotLight':
  17087. uniforms = {
  17088. position: new Vector3(),
  17089. direction: new Vector3(),
  17090. color: new Color(),
  17091. distance: 0,
  17092. coneCos: 0,
  17093. penumbraCos: 0,
  17094. decay: 0
  17095. };
  17096. break;
  17097. case 'PointLight':
  17098. uniforms = {
  17099. position: new Vector3(),
  17100. color: new Color(),
  17101. distance: 0,
  17102. decay: 0
  17103. };
  17104. break;
  17105. case 'HemisphereLight':
  17106. uniforms = {
  17107. direction: new Vector3(),
  17108. skyColor: new Color(),
  17109. groundColor: new Color()
  17110. };
  17111. break;
  17112. case 'RectAreaLight':
  17113. uniforms = {
  17114. color: new Color(),
  17115. position: new Vector3(),
  17116. halfWidth: new Vector3(),
  17117. halfHeight: new Vector3()
  17118. };
  17119. break;
  17120. }
  17121. lights[ light.id ] = uniforms;
  17122. return uniforms;
  17123. }
  17124. };
  17125. }
  17126. function ShadowUniformsCache() {
  17127. var lights = {};
  17128. return {
  17129. get: function ( light ) {
  17130. if ( lights[ light.id ] !== undefined ) {
  17131. return lights[ light.id ];
  17132. }
  17133. var uniforms;
  17134. switch ( light.type ) {
  17135. case 'DirectionalLight':
  17136. uniforms = {
  17137. shadowBias: 0,
  17138. shadowRadius: 1,
  17139. shadowMapSize: new Vector2()
  17140. };
  17141. break;
  17142. case 'SpotLight':
  17143. uniforms = {
  17144. shadowBias: 0,
  17145. shadowRadius: 1,
  17146. shadowMapSize: new Vector2()
  17147. };
  17148. break;
  17149. case 'PointLight':
  17150. uniforms = {
  17151. shadowBias: 0,
  17152. shadowRadius: 1,
  17153. shadowMapSize: new Vector2(),
  17154. shadowCameraNear: 1,
  17155. shadowCameraFar: 1000
  17156. };
  17157. break;
  17158. // TODO (abelnation): set RectAreaLight shadow uniforms
  17159. }
  17160. lights[ light.id ] = uniforms;
  17161. return uniforms;
  17162. }
  17163. };
  17164. }
  17165. var nextVersion = 0;
  17166. function shadowCastingLightsFirst( lightA, lightB ) {
  17167. return ( lightB.castShadow ? 1 : 0 ) - ( lightA.castShadow ? 1 : 0 );
  17168. }
  17169. function WebGLLights() {
  17170. var cache = new UniformsCache();
  17171. var shadowCache = ShadowUniformsCache();
  17172. var state = {
  17173. version: 0,
  17174. hash: {
  17175. directionalLength: - 1,
  17176. pointLength: - 1,
  17177. spotLength: - 1,
  17178. rectAreaLength: - 1,
  17179. hemiLength: - 1,
  17180. numDirectionalShadows: - 1,
  17181. numPointShadows: - 1,
  17182. numSpotShadows: - 1
  17183. },
  17184. ambient: [ 0, 0, 0 ],
  17185. probe: [],
  17186. directional: [],
  17187. directionalShadow: [],
  17188. directionalShadowMap: [],
  17189. directionalShadowMatrix: [],
  17190. spot: [],
  17191. spotShadow: [],
  17192. spotShadowMap: [],
  17193. spotShadowMatrix: [],
  17194. rectArea: [],
  17195. point: [],
  17196. pointShadow: [],
  17197. pointShadowMap: [],
  17198. pointShadowMatrix: [],
  17199. hemi: []
  17200. };
  17201. for ( var i = 0; i < 9; i ++ ) { state.probe.push( new Vector3() ); }
  17202. var vector3 = new Vector3();
  17203. var matrix4 = new Matrix4();
  17204. var matrix42 = new Matrix4();
  17205. function setup( lights, shadows, camera ) {
  17206. var r = 0, g = 0, b = 0;
  17207. for ( var i = 0; i < 9; i ++ ) { state.probe[ i ].set( 0, 0, 0 ); }
  17208. var directionalLength = 0;
  17209. var pointLength = 0;
  17210. var spotLength = 0;
  17211. var rectAreaLength = 0;
  17212. var hemiLength = 0;
  17213. var numDirectionalShadows = 0;
  17214. var numPointShadows = 0;
  17215. var numSpotShadows = 0;
  17216. var viewMatrix = camera.matrixWorldInverse;
  17217. lights.sort( shadowCastingLightsFirst );
  17218. for ( var i = 0, l = lights.length; i < l; i ++ ) {
  17219. var light = lights[ i ];
  17220. var color = light.color;
  17221. var intensity = light.intensity;
  17222. var distance = light.distance;
  17223. var shadowMap = ( light.shadow && light.shadow.map ) ? light.shadow.map.texture : null;
  17224. if ( light.isAmbientLight ) {
  17225. r += color.r * intensity;
  17226. g += color.g * intensity;
  17227. b += color.b * intensity;
  17228. } else if ( light.isLightProbe ) {
  17229. for ( var j = 0; j < 9; j ++ ) {
  17230. state.probe[ j ].addScaledVector( light.sh.coefficients[ j ], intensity );
  17231. }
  17232. } else if ( light.isDirectionalLight ) {
  17233. var uniforms = cache.get( light );
  17234. uniforms.color.copy( light.color ).multiplyScalar( light.intensity );
  17235. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  17236. vector3.setFromMatrixPosition( light.target.matrixWorld );
  17237. uniforms.direction.sub( vector3 );
  17238. uniforms.direction.transformDirection( viewMatrix );
  17239. if ( light.castShadow ) {
  17240. var shadow = light.shadow;
  17241. var shadowUniforms = shadowCache.get( light );
  17242. shadowUniforms.shadowBias = shadow.bias;
  17243. shadowUniforms.shadowRadius = shadow.radius;
  17244. shadowUniforms.shadowMapSize = shadow.mapSize;
  17245. state.directionalShadow[ directionalLength ] = shadowUniforms;
  17246. state.directionalShadowMap[ directionalLength ] = shadowMap;
  17247. state.directionalShadowMatrix[ directionalLength ] = light.shadow.matrix;
  17248. numDirectionalShadows ++;
  17249. }
  17250. state.directional[ directionalLength ] = uniforms;
  17251. directionalLength ++;
  17252. } else if ( light.isSpotLight ) {
  17253. var uniforms = cache.get( light );
  17254. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  17255. uniforms.position.applyMatrix4( viewMatrix );
  17256. uniforms.color.copy( color ).multiplyScalar( intensity );
  17257. uniforms.distance = distance;
  17258. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  17259. vector3.setFromMatrixPosition( light.target.matrixWorld );
  17260. uniforms.direction.sub( vector3 );
  17261. uniforms.direction.transformDirection( viewMatrix );
  17262. uniforms.coneCos = Math.cos( light.angle );
  17263. uniforms.penumbraCos = Math.cos( light.angle * ( 1 - light.penumbra ) );
  17264. uniforms.decay = light.decay;
  17265. if ( light.castShadow ) {
  17266. var shadow = light.shadow;
  17267. var shadowUniforms = shadowCache.get( light );
  17268. shadowUniforms.shadowBias = shadow.bias;
  17269. shadowUniforms.shadowRadius = shadow.radius;
  17270. shadowUniforms.shadowMapSize = shadow.mapSize;
  17271. state.spotShadow[ spotLength ] = shadowUniforms;
  17272. state.spotShadowMap[ spotLength ] = shadowMap;
  17273. state.spotShadowMatrix[ spotLength ] = light.shadow.matrix;
  17274. numSpotShadows ++;
  17275. }
  17276. state.spot[ spotLength ] = uniforms;
  17277. spotLength ++;
  17278. } else if ( light.isRectAreaLight ) {
  17279. var uniforms = cache.get( light );
  17280. // (a) intensity is the total visible light emitted
  17281. //uniforms.color.copy( color ).multiplyScalar( intensity / ( light.width * light.height * Math.PI ) );
  17282. // (b) intensity is the brightness of the light
  17283. uniforms.color.copy( color ).multiplyScalar( intensity );
  17284. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  17285. uniforms.position.applyMatrix4( viewMatrix );
  17286. // extract local rotation of light to derive width/height half vectors
  17287. matrix42.identity();
  17288. matrix4.copy( light.matrixWorld );
  17289. matrix4.premultiply( viewMatrix );
  17290. matrix42.extractRotation( matrix4 );
  17291. uniforms.halfWidth.set( light.width * 0.5, 0.0, 0.0 );
  17292. uniforms.halfHeight.set( 0.0, light.height * 0.5, 0.0 );
  17293. uniforms.halfWidth.applyMatrix4( matrix42 );
  17294. uniforms.halfHeight.applyMatrix4( matrix42 );
  17295. // TODO (abelnation): RectAreaLight distance?
  17296. // uniforms.distance = distance;
  17297. state.rectArea[ rectAreaLength ] = uniforms;
  17298. rectAreaLength ++;
  17299. } else if ( light.isPointLight ) {
  17300. var uniforms = cache.get( light );
  17301. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  17302. uniforms.position.applyMatrix4( viewMatrix );
  17303. uniforms.color.copy( light.color ).multiplyScalar( light.intensity );
  17304. uniforms.distance = light.distance;
  17305. uniforms.decay = light.decay;
  17306. if ( light.castShadow ) {
  17307. var shadow = light.shadow;
  17308. var shadowUniforms = shadowCache.get( light );
  17309. shadowUniforms.shadowBias = shadow.bias;
  17310. shadowUniforms.shadowRadius = shadow.radius;
  17311. shadowUniforms.shadowMapSize = shadow.mapSize;
  17312. shadowUniforms.shadowCameraNear = shadow.camera.near;
  17313. shadowUniforms.shadowCameraFar = shadow.camera.far;
  17314. state.pointShadow[ pointLength ] = shadowUniforms;
  17315. state.pointShadowMap[ pointLength ] = shadowMap;
  17316. state.pointShadowMatrix[ pointLength ] = light.shadow.matrix;
  17317. numPointShadows ++;
  17318. }
  17319. state.point[ pointLength ] = uniforms;
  17320. pointLength ++;
  17321. } else if ( light.isHemisphereLight ) {
  17322. var uniforms = cache.get( light );
  17323. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  17324. uniforms.direction.transformDirection( viewMatrix );
  17325. uniforms.direction.normalize();
  17326. uniforms.skyColor.copy( light.color ).multiplyScalar( intensity );
  17327. uniforms.groundColor.copy( light.groundColor ).multiplyScalar( intensity );
  17328. state.hemi[ hemiLength ] = uniforms;
  17329. hemiLength ++;
  17330. }
  17331. }
  17332. state.ambient[ 0 ] = r;
  17333. state.ambient[ 1 ] = g;
  17334. state.ambient[ 2 ] = b;
  17335. var hash = state.hash;
  17336. if ( hash.directionalLength !== directionalLength ||
  17337. hash.pointLength !== pointLength ||
  17338. hash.spotLength !== spotLength ||
  17339. hash.rectAreaLength !== rectAreaLength ||
  17340. hash.hemiLength !== hemiLength ||
  17341. hash.numDirectionalShadows !== numDirectionalShadows ||
  17342. hash.numPointShadows !== numPointShadows ||
  17343. hash.numSpotShadows !== numSpotShadows ) {
  17344. state.directional.length = directionalLength;
  17345. state.spot.length = spotLength;
  17346. state.rectArea.length = rectAreaLength;
  17347. state.point.length = pointLength;
  17348. state.hemi.length = hemiLength;
  17349. state.directionalShadow.length = numDirectionalShadows;
  17350. state.directionalShadowMap.length = numDirectionalShadows;
  17351. state.pointShadow.length = numPointShadows;
  17352. state.pointShadowMap.length = numPointShadows;
  17353. state.spotShadow.length = numSpotShadows;
  17354. state.spotShadowMap.length = numSpotShadows;
  17355. state.directionalShadowMatrix.length = numDirectionalShadows;
  17356. state.pointShadowMatrix.length = numPointShadows;
  17357. state.spotShadowMatrix.length = numSpotShadows;
  17358. hash.directionalLength = directionalLength;
  17359. hash.pointLength = pointLength;
  17360. hash.spotLength = spotLength;
  17361. hash.rectAreaLength = rectAreaLength;
  17362. hash.hemiLength = hemiLength;
  17363. hash.numDirectionalShadows = numDirectionalShadows;
  17364. hash.numPointShadows = numPointShadows;
  17365. hash.numSpotShadows = numSpotShadows;
  17366. state.version = nextVersion ++;
  17367. }
  17368. }
  17369. return {
  17370. setup: setup,
  17371. state: state
  17372. };
  17373. }
  17374. /**
  17375. * @author Mugen87 / https://github.com/Mugen87
  17376. */
  17377. function WebGLRenderState() {
  17378. var lights = new WebGLLights();
  17379. var lightsArray = [];
  17380. var shadowsArray = [];
  17381. function init() {
  17382. lightsArray.length = 0;
  17383. shadowsArray.length = 0;
  17384. }
  17385. function pushLight( light ) {
  17386. lightsArray.push( light );
  17387. }
  17388. function pushShadow( shadowLight ) {
  17389. shadowsArray.push( shadowLight );
  17390. }
  17391. function setupLights( camera ) {
  17392. lights.setup( lightsArray, shadowsArray, camera );
  17393. }
  17394. var state = {
  17395. lightsArray: lightsArray,
  17396. shadowsArray: shadowsArray,
  17397. lights: lights
  17398. };
  17399. return {
  17400. init: init,
  17401. state: state,
  17402. setupLights: setupLights,
  17403. pushLight: pushLight,
  17404. pushShadow: pushShadow
  17405. };
  17406. }
  17407. function WebGLRenderStates() {
  17408. var renderStates = new WeakMap();
  17409. function onSceneDispose( event ) {
  17410. var scene = event.target;
  17411. scene.removeEventListener( 'dispose', onSceneDispose );
  17412. renderStates.delete( scene );
  17413. }
  17414. function get( scene, camera ) {
  17415. var renderState;
  17416. if ( renderStates.has( scene ) === false ) {
  17417. renderState = new WebGLRenderState();
  17418. renderStates.set( scene, new WeakMap() );
  17419. renderStates.get( scene ).set( camera, renderState );
  17420. scene.addEventListener( 'dispose', onSceneDispose );
  17421. } else {
  17422. if ( renderStates.get( scene ).has( camera ) === false ) {
  17423. renderState = new WebGLRenderState();
  17424. renderStates.get( scene ).set( camera, renderState );
  17425. } else {
  17426. renderState = renderStates.get( scene ).get( camera );
  17427. }
  17428. }
  17429. return renderState;
  17430. }
  17431. function dispose() {
  17432. renderStates = new WeakMap();
  17433. }
  17434. return {
  17435. get: get,
  17436. dispose: dispose
  17437. };
  17438. }
  17439. /**
  17440. * @author mrdoob / http://mrdoob.com/
  17441. * @author alteredq / http://alteredqualia.com/
  17442. * @author bhouston / https://clara.io
  17443. * @author WestLangley / http://github.com/WestLangley
  17444. *
  17445. * parameters = {
  17446. *
  17447. * opacity: <float>,
  17448. *
  17449. * map: new THREE.Texture( <Image> ),
  17450. *
  17451. * alphaMap: new THREE.Texture( <Image> ),
  17452. *
  17453. * displacementMap: new THREE.Texture( <Image> ),
  17454. * displacementScale: <float>,
  17455. * displacementBias: <float>,
  17456. *
  17457. * wireframe: <boolean>,
  17458. * wireframeLinewidth: <float>
  17459. * }
  17460. */
  17461. function MeshDepthMaterial( parameters ) {
  17462. Material.call( this );
  17463. this.type = 'MeshDepthMaterial';
  17464. this.depthPacking = BasicDepthPacking;
  17465. this.skinning = false;
  17466. this.morphTargets = false;
  17467. this.map = null;
  17468. this.alphaMap = null;
  17469. this.displacementMap = null;
  17470. this.displacementScale = 1;
  17471. this.displacementBias = 0;
  17472. this.wireframe = false;
  17473. this.wireframeLinewidth = 1;
  17474. this.fog = false;
  17475. this.setValues( parameters );
  17476. }
  17477. MeshDepthMaterial.prototype = Object.create( Material.prototype );
  17478. MeshDepthMaterial.prototype.constructor = MeshDepthMaterial;
  17479. MeshDepthMaterial.prototype.isMeshDepthMaterial = true;
  17480. MeshDepthMaterial.prototype.copy = function ( source ) {
  17481. Material.prototype.copy.call( this, source );
  17482. this.depthPacking = source.depthPacking;
  17483. this.skinning = source.skinning;
  17484. this.morphTargets = source.morphTargets;
  17485. this.map = source.map;
  17486. this.alphaMap = source.alphaMap;
  17487. this.displacementMap = source.displacementMap;
  17488. this.displacementScale = source.displacementScale;
  17489. this.displacementBias = source.displacementBias;
  17490. this.wireframe = source.wireframe;
  17491. this.wireframeLinewidth = source.wireframeLinewidth;
  17492. return this;
  17493. };
  17494. /**
  17495. * @author WestLangley / http://github.com/WestLangley
  17496. *
  17497. * parameters = {
  17498. *
  17499. * referencePosition: <float>,
  17500. * nearDistance: <float>,
  17501. * farDistance: <float>,
  17502. *
  17503. * skinning: <bool>,
  17504. * morphTargets: <bool>,
  17505. *
  17506. * map: new THREE.Texture( <Image> ),
  17507. *
  17508. * alphaMap: new THREE.Texture( <Image> ),
  17509. *
  17510. * displacementMap: new THREE.Texture( <Image> ),
  17511. * displacementScale: <float>,
  17512. * displacementBias: <float>
  17513. *
  17514. * }
  17515. */
  17516. function MeshDistanceMaterial( parameters ) {
  17517. Material.call( this );
  17518. this.type = 'MeshDistanceMaterial';
  17519. this.referencePosition = new Vector3();
  17520. this.nearDistance = 1;
  17521. this.farDistance = 1000;
  17522. this.skinning = false;
  17523. this.morphTargets = false;
  17524. this.map = null;
  17525. this.alphaMap = null;
  17526. this.displacementMap = null;
  17527. this.displacementScale = 1;
  17528. this.displacementBias = 0;
  17529. this.fog = false;
  17530. this.setValues( parameters );
  17531. }
  17532. MeshDistanceMaterial.prototype = Object.create( Material.prototype );
  17533. MeshDistanceMaterial.prototype.constructor = MeshDistanceMaterial;
  17534. MeshDistanceMaterial.prototype.isMeshDistanceMaterial = true;
  17535. MeshDistanceMaterial.prototype.copy = function ( source ) {
  17536. Material.prototype.copy.call( this, source );
  17537. this.referencePosition.copy( source.referencePosition );
  17538. this.nearDistance = source.nearDistance;
  17539. this.farDistance = source.farDistance;
  17540. this.skinning = source.skinning;
  17541. this.morphTargets = source.morphTargets;
  17542. this.map = source.map;
  17543. this.alphaMap = source.alphaMap;
  17544. this.displacementMap = source.displacementMap;
  17545. this.displacementScale = source.displacementScale;
  17546. this.displacementBias = source.displacementBias;
  17547. return this;
  17548. };
  17549. var vsm_frag = "uniform sampler2D shadow_pass;\nuniform vec2 resolution;\nuniform float radius;\n#include <packing>\nvoid main() {\n float mean = 0.0;\n float squared_mean = 0.0;\n\tfloat depth = unpackRGBAToDepth( texture2D( shadow_pass, ( gl_FragCoord.xy ) / resolution ) );\n for ( float i = -1.0; i < 1.0 ; i += SAMPLE_RATE) {\n #ifdef HORIZONAL_PASS\n vec2 distribution = unpackRGBATo2Half( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( i, 0.0 ) * radius ) / resolution ) );\n mean += distribution.x;\n squared_mean += distribution.y * distribution.y + distribution.x * distribution.x;\n #else\n float depth = unpackRGBAToDepth( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( 0.0, i ) * radius ) / resolution ) );\n mean += depth;\n squared_mean += depth * depth;\n #endif\n }\n mean = mean * HALF_SAMPLE_RATE;\n squared_mean = squared_mean * HALF_SAMPLE_RATE;\n float std_dev = sqrt( squared_mean - mean * mean );\n gl_FragColor = pack2HalfToRGBA( vec2( mean, std_dev ) );\n}";
  17550. var vsm_vert = "void main() {\n\tgl_Position = vec4( position, 1.0 );\n}";
  17551. /**
  17552. * @author alteredq / http://alteredqualia.com/
  17553. * @author mrdoob / http://mrdoob.com/
  17554. */
  17555. function WebGLShadowMap( _renderer, _objects, maxTextureSize ) {
  17556. var _frustum = new Frustum(),
  17557. _shadowMapSize = new Vector2(),
  17558. _viewportSize = new Vector2(),
  17559. _viewport = new Vector4(),
  17560. _depthMaterials = [],
  17561. _distanceMaterials = [],
  17562. _materialCache = {};
  17563. var shadowSide = { 0: BackSide, 1: FrontSide, 2: DoubleSide };
  17564. var shadowMaterialVertical = new ShaderMaterial( {
  17565. defines: {
  17566. SAMPLE_RATE: 2.0 / 8.0,
  17567. HALF_SAMPLE_RATE: 1.0 / 8.0
  17568. },
  17569. uniforms: {
  17570. shadow_pass: { value: null },
  17571. resolution: { value: new Vector2() },
  17572. radius: { value: 4.0 }
  17573. },
  17574. vertexShader: vsm_vert,
  17575. fragmentShader: vsm_frag
  17576. } );
  17577. var shadowMaterialHorizonal = shadowMaterialVertical.clone();
  17578. shadowMaterialHorizonal.defines.HORIZONAL_PASS = 1;
  17579. var fullScreenTri = new BufferGeometry();
  17580. fullScreenTri.setAttribute(
  17581. "position",
  17582. new BufferAttribute(
  17583. new Float32Array( [ - 1, - 1, 0.5, 3, - 1, 0.5, - 1, 3, 0.5 ] ),
  17584. 3
  17585. )
  17586. );
  17587. var fullScreenMesh = new Mesh( fullScreenTri, shadowMaterialVertical );
  17588. var scope = this;
  17589. this.enabled = false;
  17590. this.autoUpdate = true;
  17591. this.needsUpdate = false;
  17592. this.type = PCFShadowMap;
  17593. this.render = function ( lights, scene, camera ) {
  17594. if ( scope.enabled === false ) { return; }
  17595. if ( scope.autoUpdate === false && scope.needsUpdate === false ) { return; }
  17596. if ( lights.length === 0 ) { return; }
  17597. var currentRenderTarget = _renderer.getRenderTarget();
  17598. var activeCubeFace = _renderer.getActiveCubeFace();
  17599. var activeMipmapLevel = _renderer.getActiveMipmapLevel();
  17600. var _state = _renderer.state;
  17601. // Set GL state for depth map.
  17602. _state.setBlending( NoBlending );
  17603. _state.buffers.color.setClear( 1, 1, 1, 1 );
  17604. _state.buffers.depth.setTest( true );
  17605. _state.setScissorTest( false );
  17606. // render depth map
  17607. for ( var i = 0, il = lights.length; i < il; i ++ ) {
  17608. var light = lights[ i ];
  17609. var shadow = light.shadow;
  17610. if ( shadow === undefined ) {
  17611. console.warn( 'THREE.WebGLShadowMap:', light, 'has no shadow.' );
  17612. continue;
  17613. }
  17614. _shadowMapSize.copy( shadow.mapSize );
  17615. var shadowFrameExtents = shadow.getFrameExtents();
  17616. _shadowMapSize.multiply( shadowFrameExtents );
  17617. _viewportSize.copy( shadow.mapSize );
  17618. if ( _shadowMapSize.x > maxTextureSize || _shadowMapSize.y > maxTextureSize ) {
  17619. console.warn( 'THREE.WebGLShadowMap:', light, 'has shadow exceeding max texture size, reducing' );
  17620. if ( _shadowMapSize.x > maxTextureSize ) {
  17621. _viewportSize.x = Math.floor( maxTextureSize / shadowFrameExtents.x );
  17622. _shadowMapSize.x = _viewportSize.x * shadowFrameExtents.x;
  17623. shadow.mapSize.x = _viewportSize.x;
  17624. }
  17625. if ( _shadowMapSize.y > maxTextureSize ) {
  17626. _viewportSize.y = Math.floor( maxTextureSize / shadowFrameExtents.y );
  17627. _shadowMapSize.y = _viewportSize.y * shadowFrameExtents.y;
  17628. shadow.mapSize.y = _viewportSize.y;
  17629. }
  17630. }
  17631. if ( shadow.map === null && ! shadow.isPointLightShadow && this.type === VSMShadowMap ) {
  17632. var pars = { minFilter: LinearFilter, magFilter: LinearFilter, format: RGBAFormat };
  17633. shadow.map = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars );
  17634. shadow.map.texture.name = light.name + ".shadowMap";
  17635. shadow.mapPass = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars );
  17636. shadow.camera.updateProjectionMatrix();
  17637. }
  17638. if ( shadow.map === null ) {
  17639. var pars = { minFilter: NearestFilter, magFilter: NearestFilter, format: RGBAFormat };
  17640. shadow.map = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars );
  17641. shadow.map.texture.name = light.name + ".shadowMap";
  17642. shadow.camera.updateProjectionMatrix();
  17643. }
  17644. _renderer.setRenderTarget( shadow.map );
  17645. _renderer.clear();
  17646. var viewportCount = shadow.getViewportCount();
  17647. for ( var vp = 0; vp < viewportCount; vp ++ ) {
  17648. var viewport = shadow.getViewport( vp );
  17649. _viewport.set(
  17650. _viewportSize.x * viewport.x,
  17651. _viewportSize.y * viewport.y,
  17652. _viewportSize.x * viewport.z,
  17653. _viewportSize.y * viewport.w
  17654. );
  17655. _state.viewport( _viewport );
  17656. shadow.updateMatrices( light, vp );
  17657. _frustum = shadow.getFrustum();
  17658. renderObject( scene, camera, shadow.camera, light, this.type );
  17659. }
  17660. // do blur pass for VSM
  17661. if ( ! shadow.isPointLightShadow && this.type === VSMShadowMap ) {
  17662. VSMPass( shadow, camera );
  17663. }
  17664. }
  17665. scope.needsUpdate = false;
  17666. _renderer.setRenderTarget( currentRenderTarget, activeCubeFace, activeMipmapLevel );
  17667. };
  17668. function VSMPass( shadow, camera ) {
  17669. var geometry = _objects.update( fullScreenMesh );
  17670. // vertical pass
  17671. shadowMaterialVertical.uniforms.shadow_pass.value = shadow.map.texture;
  17672. shadowMaterialVertical.uniforms.resolution.value = shadow.mapSize;
  17673. shadowMaterialVertical.uniforms.radius.value = shadow.radius;
  17674. _renderer.setRenderTarget( shadow.mapPass );
  17675. _renderer.clear();
  17676. _renderer.renderBufferDirect( camera, null, geometry, shadowMaterialVertical, fullScreenMesh, null );
  17677. // horizonal pass
  17678. shadowMaterialHorizonal.uniforms.shadow_pass.value = shadow.mapPass.texture;
  17679. shadowMaterialHorizonal.uniforms.resolution.value = shadow.mapSize;
  17680. shadowMaterialHorizonal.uniforms.radius.value = shadow.radius;
  17681. _renderer.setRenderTarget( shadow.map );
  17682. _renderer.clear();
  17683. _renderer.renderBufferDirect( camera, null, geometry, shadowMaterialHorizonal, fullScreenMesh, null );
  17684. }
  17685. function getDepthMaterialVariant( useMorphing, useSkinning, useInstancing ) {
  17686. var index = useMorphing << 0 | useSkinning << 1 | useInstancing << 2;
  17687. var material = _depthMaterials[ index ];
  17688. if ( material === undefined ) {
  17689. material = new MeshDepthMaterial( {
  17690. depthPacking: RGBADepthPacking,
  17691. morphTargets: useMorphing,
  17692. skinning: useSkinning
  17693. } );
  17694. _depthMaterials[ index ] = material;
  17695. }
  17696. return material;
  17697. }
  17698. function getDistanceMaterialVariant( useMorphing, useSkinning, useInstancing ) {
  17699. var index = useMorphing << 0 | useSkinning << 1 | useInstancing << 2;
  17700. var material = _distanceMaterials[ index ];
  17701. if ( material === undefined ) {
  17702. material = new MeshDistanceMaterial( {
  17703. morphTargets: useMorphing,
  17704. skinning: useSkinning
  17705. } );
  17706. _distanceMaterials[ index ] = material;
  17707. }
  17708. return material;
  17709. }
  17710. function getDepthMaterial( object, material, light, shadowCameraNear, shadowCameraFar, type ) {
  17711. var geometry = object.geometry;
  17712. var result = null;
  17713. var getMaterialVariant = getDepthMaterialVariant;
  17714. var customMaterial = object.customDepthMaterial;
  17715. if ( light.isPointLight === true ) {
  17716. getMaterialVariant = getDistanceMaterialVariant;
  17717. customMaterial = object.customDistanceMaterial;
  17718. }
  17719. if ( customMaterial === undefined ) {
  17720. var useMorphing = false;
  17721. if ( material.morphTargets === true ) {
  17722. if ( geometry.isBufferGeometry === true ) {
  17723. useMorphing = geometry.morphAttributes && geometry.morphAttributes.position && geometry.morphAttributes.position.length > 0;
  17724. } else if ( geometry.isGeometry === true ) {
  17725. useMorphing = geometry.morphTargets && geometry.morphTargets.length > 0;
  17726. }
  17727. }
  17728. var useSkinning = false;
  17729. if ( object.isSkinnedMesh === true ) {
  17730. if ( material.skinning === true ) {
  17731. useSkinning = true;
  17732. } else {
  17733. console.warn( 'THREE.WebGLShadowMap: THREE.SkinnedMesh with material.skinning set to false:', object );
  17734. }
  17735. }
  17736. var useInstancing = object.isInstancedMesh === true;
  17737. result = getMaterialVariant( useMorphing, useSkinning, useInstancing );
  17738. } else {
  17739. result = customMaterial;
  17740. }
  17741. if ( _renderer.localClippingEnabled &&
  17742. material.clipShadows === true &&
  17743. material.clippingPlanes.length !== 0 ) {
  17744. // in this case we need a unique material instance reflecting the
  17745. // appropriate state
  17746. var keyA = result.uuid, keyB = material.uuid;
  17747. var materialsForVariant = _materialCache[ keyA ];
  17748. if ( materialsForVariant === undefined ) {
  17749. materialsForVariant = {};
  17750. _materialCache[ keyA ] = materialsForVariant;
  17751. }
  17752. var cachedMaterial = materialsForVariant[ keyB ];
  17753. if ( cachedMaterial === undefined ) {
  17754. cachedMaterial = result.clone();
  17755. materialsForVariant[ keyB ] = cachedMaterial;
  17756. }
  17757. result = cachedMaterial;
  17758. }
  17759. result.visible = material.visible;
  17760. result.wireframe = material.wireframe;
  17761. if ( type === VSMShadowMap ) {
  17762. result.side = ( material.shadowSide !== null ) ? material.shadowSide : material.side;
  17763. } else {
  17764. result.side = ( material.shadowSide !== null ) ? material.shadowSide : shadowSide[ material.side ];
  17765. }
  17766. result.clipShadows = material.clipShadows;
  17767. result.clippingPlanes = material.clippingPlanes;
  17768. result.clipIntersection = material.clipIntersection;
  17769. result.wireframeLinewidth = material.wireframeLinewidth;
  17770. result.linewidth = material.linewidth;
  17771. if ( light.isPointLight === true && result.isMeshDistanceMaterial === true ) {
  17772. result.referencePosition.setFromMatrixPosition( light.matrixWorld );
  17773. result.nearDistance = shadowCameraNear;
  17774. result.farDistance = shadowCameraFar;
  17775. }
  17776. return result;
  17777. }
  17778. function renderObject( object, camera, shadowCamera, light, type ) {
  17779. if ( object.visible === false ) { return; }
  17780. var visible = object.layers.test( camera.layers );
  17781. if ( visible && ( object.isMesh || object.isLine || object.isPoints ) ) {
  17782. if ( ( object.castShadow || ( object.receiveShadow && type === VSMShadowMap ) ) && ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) ) {
  17783. object.modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  17784. var geometry = _objects.update( object );
  17785. var material = object.material;
  17786. if ( Array.isArray( material ) ) {
  17787. var groups = geometry.groups;
  17788. for ( var k = 0, kl = groups.length; k < kl; k ++ ) {
  17789. var group = groups[ k ];
  17790. var groupMaterial = material[ group.materialIndex ];
  17791. if ( groupMaterial && groupMaterial.visible ) {
  17792. var depthMaterial = getDepthMaterial( object, groupMaterial, light, shadowCamera.near, shadowCamera.far, type );
  17793. _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, group );
  17794. }
  17795. }
  17796. } else if ( material.visible ) {
  17797. var depthMaterial = getDepthMaterial( object, material, light, shadowCamera.near, shadowCamera.far, type );
  17798. _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, null );
  17799. }
  17800. }
  17801. }
  17802. var children = object.children;
  17803. for ( var i = 0, l = children.length; i < l; i ++ ) {
  17804. renderObject( children[ i ], camera, shadowCamera, light, type );
  17805. }
  17806. }
  17807. }
  17808. /**
  17809. * @author mrdoob / http://mrdoob.com/
  17810. */
  17811. function WebGLState( gl, extensions, capabilities ) {
  17812. var isWebGL2 = capabilities.isWebGL2;
  17813. function ColorBuffer() {
  17814. var locked = false;
  17815. var color = new Vector4();
  17816. var currentColorMask = null;
  17817. var currentColorClear = new Vector4( 0, 0, 0, 0 );
  17818. return {
  17819. setMask: function ( colorMask ) {
  17820. if ( currentColorMask !== colorMask && ! locked ) {
  17821. gl.colorMask( colorMask, colorMask, colorMask, colorMask );
  17822. currentColorMask = colorMask;
  17823. }
  17824. },
  17825. setLocked: function ( lock ) {
  17826. locked = lock;
  17827. },
  17828. setClear: function ( r, g, b, a, premultipliedAlpha ) {
  17829. if ( premultipliedAlpha === true ) {
  17830. r *= a; g *= a; b *= a;
  17831. }
  17832. color.set( r, g, b, a );
  17833. if ( currentColorClear.equals( color ) === false ) {
  17834. gl.clearColor( r, g, b, a );
  17835. currentColorClear.copy( color );
  17836. }
  17837. },
  17838. reset: function () {
  17839. locked = false;
  17840. currentColorMask = null;
  17841. currentColorClear.set( - 1, 0, 0, 0 ); // set to invalid state
  17842. }
  17843. };
  17844. }
  17845. function DepthBuffer() {
  17846. var locked = false;
  17847. var currentDepthMask = null;
  17848. var currentDepthFunc = null;
  17849. var currentDepthClear = null;
  17850. return {
  17851. setTest: function ( depthTest ) {
  17852. if ( depthTest ) {
  17853. enable( 2929 );
  17854. } else {
  17855. disable( 2929 );
  17856. }
  17857. },
  17858. setMask: function ( depthMask ) {
  17859. if ( currentDepthMask !== depthMask && ! locked ) {
  17860. gl.depthMask( depthMask );
  17861. currentDepthMask = depthMask;
  17862. }
  17863. },
  17864. setFunc: function ( depthFunc ) {
  17865. if ( currentDepthFunc !== depthFunc ) {
  17866. if ( depthFunc ) {
  17867. switch ( depthFunc ) {
  17868. case NeverDepth:
  17869. gl.depthFunc( 512 );
  17870. break;
  17871. case AlwaysDepth:
  17872. gl.depthFunc( 519 );
  17873. break;
  17874. case LessDepth:
  17875. gl.depthFunc( 513 );
  17876. break;
  17877. case LessEqualDepth:
  17878. gl.depthFunc( 515 );
  17879. break;
  17880. case EqualDepth:
  17881. gl.depthFunc( 514 );
  17882. break;
  17883. case GreaterEqualDepth:
  17884. gl.depthFunc( 518 );
  17885. break;
  17886. case GreaterDepth:
  17887. gl.depthFunc( 516 );
  17888. break;
  17889. case NotEqualDepth:
  17890. gl.depthFunc( 517 );
  17891. break;
  17892. default:
  17893. gl.depthFunc( 515 );
  17894. }
  17895. } else {
  17896. gl.depthFunc( 515 );
  17897. }
  17898. currentDepthFunc = depthFunc;
  17899. }
  17900. },
  17901. setLocked: function ( lock ) {
  17902. locked = lock;
  17903. },
  17904. setClear: function ( depth ) {
  17905. if ( currentDepthClear !== depth ) {
  17906. gl.clearDepth( depth );
  17907. currentDepthClear = depth;
  17908. }
  17909. },
  17910. reset: function () {
  17911. locked = false;
  17912. currentDepthMask = null;
  17913. currentDepthFunc = null;
  17914. currentDepthClear = null;
  17915. }
  17916. };
  17917. }
  17918. function StencilBuffer() {
  17919. var locked = false;
  17920. var currentStencilMask = null;
  17921. var currentStencilFunc = null;
  17922. var currentStencilRef = null;
  17923. var currentStencilFuncMask = null;
  17924. var currentStencilFail = null;
  17925. var currentStencilZFail = null;
  17926. var currentStencilZPass = null;
  17927. var currentStencilClear = null;
  17928. return {
  17929. setTest: function ( stencilTest ) {
  17930. if ( ! locked ) {
  17931. if ( stencilTest ) {
  17932. enable( 2960 );
  17933. } else {
  17934. disable( 2960 );
  17935. }
  17936. }
  17937. },
  17938. setMask: function ( stencilMask ) {
  17939. if ( currentStencilMask !== stencilMask && ! locked ) {
  17940. gl.stencilMask( stencilMask );
  17941. currentStencilMask = stencilMask;
  17942. }
  17943. },
  17944. setFunc: function ( stencilFunc, stencilRef, stencilMask ) {
  17945. if ( currentStencilFunc !== stencilFunc ||
  17946. currentStencilRef !== stencilRef ||
  17947. currentStencilFuncMask !== stencilMask ) {
  17948. gl.stencilFunc( stencilFunc, stencilRef, stencilMask );
  17949. currentStencilFunc = stencilFunc;
  17950. currentStencilRef = stencilRef;
  17951. currentStencilFuncMask = stencilMask;
  17952. }
  17953. },
  17954. setOp: function ( stencilFail, stencilZFail, stencilZPass ) {
  17955. if ( currentStencilFail !== stencilFail ||
  17956. currentStencilZFail !== stencilZFail ||
  17957. currentStencilZPass !== stencilZPass ) {
  17958. gl.stencilOp( stencilFail, stencilZFail, stencilZPass );
  17959. currentStencilFail = stencilFail;
  17960. currentStencilZFail = stencilZFail;
  17961. currentStencilZPass = stencilZPass;
  17962. }
  17963. },
  17964. setLocked: function ( lock ) {
  17965. locked = lock;
  17966. },
  17967. setClear: function ( stencil ) {
  17968. if ( currentStencilClear !== stencil ) {
  17969. gl.clearStencil( stencil );
  17970. currentStencilClear = stencil;
  17971. }
  17972. },
  17973. reset: function () {
  17974. locked = false;
  17975. currentStencilMask = null;
  17976. currentStencilFunc = null;
  17977. currentStencilRef = null;
  17978. currentStencilFuncMask = null;
  17979. currentStencilFail = null;
  17980. currentStencilZFail = null;
  17981. currentStencilZPass = null;
  17982. currentStencilClear = null;
  17983. }
  17984. };
  17985. }
  17986. //
  17987. var colorBuffer = new ColorBuffer();
  17988. var depthBuffer = new DepthBuffer();
  17989. var stencilBuffer = new StencilBuffer();
  17990. var maxVertexAttributes = gl.getParameter( 34921 );
  17991. var newAttributes = new Uint8Array( maxVertexAttributes );
  17992. var enabledAttributes = new Uint8Array( maxVertexAttributes );
  17993. var attributeDivisors = new Uint8Array( maxVertexAttributes );
  17994. var enabledCapabilities = {};
  17995. var currentProgram = null;
  17996. var currentBlendingEnabled = null;
  17997. var currentBlending = null;
  17998. var currentBlendEquation = null;
  17999. var currentBlendSrc = null;
  18000. var currentBlendDst = null;
  18001. var currentBlendEquationAlpha = null;
  18002. var currentBlendSrcAlpha = null;
  18003. var currentBlendDstAlpha = null;
  18004. var currentPremultipledAlpha = false;
  18005. var currentFlipSided = null;
  18006. var currentCullFace = null;
  18007. var currentLineWidth = null;
  18008. var currentPolygonOffsetFactor = null;
  18009. var currentPolygonOffsetUnits = null;
  18010. var maxTextures = gl.getParameter( 35661 );
  18011. var lineWidthAvailable = false;
  18012. var version = 0;
  18013. var glVersion = gl.getParameter( 7938 );
  18014. if ( glVersion.indexOf( 'WebGL' ) !== - 1 ) {
  18015. version = parseFloat( /^WebGL\ ([0-9])/.exec( glVersion )[ 1 ] );
  18016. lineWidthAvailable = ( version >= 1.0 );
  18017. } else if ( glVersion.indexOf( 'OpenGL ES' ) !== - 1 ) {
  18018. version = parseFloat( /^OpenGL\ ES\ ([0-9])/.exec( glVersion )[ 1 ] );
  18019. lineWidthAvailable = ( version >= 2.0 );
  18020. }
  18021. var currentTextureSlot = null;
  18022. var currentBoundTextures = {};
  18023. var currentScissor = new Vector4();
  18024. var currentViewport = new Vector4();
  18025. function createTexture( type, target, count ) {
  18026. var data = new Uint8Array( 4 ); // 4 is required to match default unpack alignment of 4.
  18027. var texture = gl.createTexture();
  18028. gl.bindTexture( type, texture );
  18029. gl.texParameteri( type, 10241, 9728 );
  18030. gl.texParameteri( type, 10240, 9728 );
  18031. for ( var i = 0; i < count; i ++ ) {
  18032. gl.texImage2D( target + i, 0, 6408, 1, 1, 0, 6408, 5121, data );
  18033. }
  18034. return texture;
  18035. }
  18036. var emptyTextures = {};
  18037. emptyTextures[ 3553 ] = createTexture( 3553, 3553, 1 );
  18038. emptyTextures[ 34067 ] = createTexture( 34067, 34069, 6 );
  18039. // init
  18040. colorBuffer.setClear( 0, 0, 0, 1 );
  18041. depthBuffer.setClear( 1 );
  18042. stencilBuffer.setClear( 0 );
  18043. enable( 2929 );
  18044. depthBuffer.setFunc( LessEqualDepth );
  18045. setFlipSided( false );
  18046. setCullFace( CullFaceBack );
  18047. enable( 2884 );
  18048. setBlending( NoBlending );
  18049. //
  18050. function initAttributes() {
  18051. for ( var i = 0, l = newAttributes.length; i < l; i ++ ) {
  18052. newAttributes[ i ] = 0;
  18053. }
  18054. }
  18055. function enableAttribute( attribute ) {
  18056. enableAttributeAndDivisor( attribute, 0 );
  18057. }
  18058. function enableAttributeAndDivisor( attribute, meshPerAttribute ) {
  18059. newAttributes[ attribute ] = 1;
  18060. if ( enabledAttributes[ attribute ] === 0 ) {
  18061. gl.enableVertexAttribArray( attribute );
  18062. enabledAttributes[ attribute ] = 1;
  18063. }
  18064. if ( attributeDivisors[ attribute ] !== meshPerAttribute ) {
  18065. var extension = isWebGL2 ? gl : extensions.get( 'ANGLE_instanced_arrays' );
  18066. extension[ isWebGL2 ? 'vertexAttribDivisor' : 'vertexAttribDivisorANGLE' ]( attribute, meshPerAttribute );
  18067. attributeDivisors[ attribute ] = meshPerAttribute;
  18068. }
  18069. }
  18070. function disableUnusedAttributes() {
  18071. for ( var i = 0, l = enabledAttributes.length; i !== l; ++ i ) {
  18072. if ( enabledAttributes[ i ] !== newAttributes[ i ] ) {
  18073. gl.disableVertexAttribArray( i );
  18074. enabledAttributes[ i ] = 0;
  18075. }
  18076. }
  18077. }
  18078. function enable( id ) {
  18079. if ( enabledCapabilities[ id ] !== true ) {
  18080. gl.enable( id );
  18081. enabledCapabilities[ id ] = true;
  18082. }
  18083. }
  18084. function disable( id ) {
  18085. if ( enabledCapabilities[ id ] !== false ) {
  18086. gl.disable( id );
  18087. enabledCapabilities[ id ] = false;
  18088. }
  18089. }
  18090. function useProgram( program ) {
  18091. if ( currentProgram !== program ) {
  18092. gl.useProgram( program );
  18093. currentProgram = program;
  18094. return true;
  18095. }
  18096. return false;
  18097. }
  18098. var equationToGL = {};
  18099. equationToGL[ AddEquation ] = 32774;
  18100. equationToGL[ SubtractEquation ] = 32778;
  18101. equationToGL[ ReverseSubtractEquation ] = 32779;
  18102. if ( isWebGL2 ) {
  18103. equationToGL[ MinEquation ] = 32775;
  18104. equationToGL[ MaxEquation ] = 32776;
  18105. } else {
  18106. var extension = extensions.get( 'EXT_blend_minmax' );
  18107. if ( extension !== null ) {
  18108. equationToGL[ MinEquation ] = extension.MIN_EXT;
  18109. equationToGL[ MaxEquation ] = extension.MAX_EXT;
  18110. }
  18111. }
  18112. var factorToGL = {};
  18113. factorToGL[ ZeroFactor ] = 0;
  18114. factorToGL[ OneFactor ] = 1;
  18115. factorToGL[ SrcColorFactor ] = 768;
  18116. factorToGL[ SrcAlphaFactor ] = 770;
  18117. factorToGL[ SrcAlphaSaturateFactor ] = 776;
  18118. factorToGL[ DstColorFactor ] = 774;
  18119. factorToGL[ DstAlphaFactor ] = 772;
  18120. factorToGL[ OneMinusSrcColorFactor ] = 769;
  18121. factorToGL[ OneMinusSrcAlphaFactor ] = 771;
  18122. factorToGL[ OneMinusDstColorFactor ] = 775;
  18123. factorToGL[ OneMinusDstAlphaFactor ] = 773;
  18124. function setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha ) {
  18125. if ( blending === NoBlending ) {
  18126. if ( currentBlendingEnabled ) {
  18127. disable( 3042 );
  18128. currentBlendingEnabled = false;
  18129. }
  18130. return;
  18131. }
  18132. if ( ! currentBlendingEnabled ) {
  18133. enable( 3042 );
  18134. currentBlendingEnabled = true;
  18135. }
  18136. if ( blending !== CustomBlending ) {
  18137. if ( blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha ) {
  18138. if ( currentBlendEquation !== AddEquation || currentBlendEquationAlpha !== AddEquation ) {
  18139. gl.blendEquation( 32774 );
  18140. currentBlendEquation = AddEquation;
  18141. currentBlendEquationAlpha = AddEquation;
  18142. }
  18143. if ( premultipliedAlpha ) {
  18144. switch ( blending ) {
  18145. case NormalBlending:
  18146. gl.blendFuncSeparate( 1, 771, 1, 771 );
  18147. break;
  18148. case AdditiveBlending:
  18149. gl.blendFunc( 1, 1 );
  18150. break;
  18151. case SubtractiveBlending:
  18152. gl.blendFuncSeparate( 0, 0, 769, 771 );
  18153. break;
  18154. case MultiplyBlending:
  18155. gl.blendFuncSeparate( 0, 768, 0, 770 );
  18156. break;
  18157. default:
  18158. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  18159. break;
  18160. }
  18161. } else {
  18162. switch ( blending ) {
  18163. case NormalBlending:
  18164. gl.blendFuncSeparate( 770, 771, 1, 771 );
  18165. break;
  18166. case AdditiveBlending:
  18167. gl.blendFunc( 770, 1 );
  18168. break;
  18169. case SubtractiveBlending:
  18170. gl.blendFunc( 0, 769 );
  18171. break;
  18172. case MultiplyBlending:
  18173. gl.blendFunc( 0, 768 );
  18174. break;
  18175. default:
  18176. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  18177. break;
  18178. }
  18179. }
  18180. currentBlendSrc = null;
  18181. currentBlendDst = null;
  18182. currentBlendSrcAlpha = null;
  18183. currentBlendDstAlpha = null;
  18184. currentBlending = blending;
  18185. currentPremultipledAlpha = premultipliedAlpha;
  18186. }
  18187. return;
  18188. }
  18189. // custom blending
  18190. blendEquationAlpha = blendEquationAlpha || blendEquation;
  18191. blendSrcAlpha = blendSrcAlpha || blendSrc;
  18192. blendDstAlpha = blendDstAlpha || blendDst;
  18193. if ( blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha ) {
  18194. gl.blendEquationSeparate( equationToGL[ blendEquation ], equationToGL[ blendEquationAlpha ] );
  18195. currentBlendEquation = blendEquation;
  18196. currentBlendEquationAlpha = blendEquationAlpha;
  18197. }
  18198. if ( blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha ) {
  18199. gl.blendFuncSeparate( factorToGL[ blendSrc ], factorToGL[ blendDst ], factorToGL[ blendSrcAlpha ], factorToGL[ blendDstAlpha ] );
  18200. currentBlendSrc = blendSrc;
  18201. currentBlendDst = blendDst;
  18202. currentBlendSrcAlpha = blendSrcAlpha;
  18203. currentBlendDstAlpha = blendDstAlpha;
  18204. }
  18205. currentBlending = blending;
  18206. currentPremultipledAlpha = null;
  18207. }
  18208. function setMaterial( material, frontFaceCW ) {
  18209. material.side === DoubleSide
  18210. ? disable( 2884 )
  18211. : enable( 2884 );
  18212. var flipSided = ( material.side === BackSide );
  18213. if ( frontFaceCW ) { flipSided = ! flipSided; }
  18214. setFlipSided( flipSided );
  18215. ( material.blending === NormalBlending && material.transparent === false )
  18216. ? setBlending( NoBlending )
  18217. : setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha );
  18218. depthBuffer.setFunc( material.depthFunc );
  18219. depthBuffer.setTest( material.depthTest );
  18220. depthBuffer.setMask( material.depthWrite );
  18221. colorBuffer.setMask( material.colorWrite );
  18222. var stencilWrite = material.stencilWrite;
  18223. stencilBuffer.setTest( stencilWrite );
  18224. if ( stencilWrite ) {
  18225. stencilBuffer.setMask( material.stencilWriteMask );
  18226. stencilBuffer.setFunc( material.stencilFunc, material.stencilRef, material.stencilFuncMask );
  18227. stencilBuffer.setOp( material.stencilFail, material.stencilZFail, material.stencilZPass );
  18228. }
  18229. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  18230. }
  18231. //
  18232. function setFlipSided( flipSided ) {
  18233. if ( currentFlipSided !== flipSided ) {
  18234. if ( flipSided ) {
  18235. gl.frontFace( 2304 );
  18236. } else {
  18237. gl.frontFace( 2305 );
  18238. }
  18239. currentFlipSided = flipSided;
  18240. }
  18241. }
  18242. function setCullFace( cullFace ) {
  18243. if ( cullFace !== CullFaceNone ) {
  18244. enable( 2884 );
  18245. if ( cullFace !== currentCullFace ) {
  18246. if ( cullFace === CullFaceBack ) {
  18247. gl.cullFace( 1029 );
  18248. } else if ( cullFace === CullFaceFront ) {
  18249. gl.cullFace( 1028 );
  18250. } else {
  18251. gl.cullFace( 1032 );
  18252. }
  18253. }
  18254. } else {
  18255. disable( 2884 );
  18256. }
  18257. currentCullFace = cullFace;
  18258. }
  18259. function setLineWidth( width ) {
  18260. if ( width !== currentLineWidth ) {
  18261. if ( lineWidthAvailable ) { gl.lineWidth( width ); }
  18262. currentLineWidth = width;
  18263. }
  18264. }
  18265. function setPolygonOffset( polygonOffset, factor, units ) {
  18266. if ( polygonOffset ) {
  18267. enable( 32823 );
  18268. if ( currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units ) {
  18269. gl.polygonOffset( factor, units );
  18270. currentPolygonOffsetFactor = factor;
  18271. currentPolygonOffsetUnits = units;
  18272. }
  18273. } else {
  18274. disable( 32823 );
  18275. }
  18276. }
  18277. function setScissorTest( scissorTest ) {
  18278. if ( scissorTest ) {
  18279. enable( 3089 );
  18280. } else {
  18281. disable( 3089 );
  18282. }
  18283. }
  18284. // texture
  18285. function activeTexture( webglSlot ) {
  18286. if ( webglSlot === undefined ) { webglSlot = 33984 + maxTextures - 1; }
  18287. if ( currentTextureSlot !== webglSlot ) {
  18288. gl.activeTexture( webglSlot );
  18289. currentTextureSlot = webglSlot;
  18290. }
  18291. }
  18292. function bindTexture( webglType, webglTexture ) {
  18293. if ( currentTextureSlot === null ) {
  18294. activeTexture();
  18295. }
  18296. var boundTexture = currentBoundTextures[ currentTextureSlot ];
  18297. if ( boundTexture === undefined ) {
  18298. boundTexture = { type: undefined, texture: undefined };
  18299. currentBoundTextures[ currentTextureSlot ] = boundTexture;
  18300. }
  18301. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  18302. gl.bindTexture( webglType, webglTexture || emptyTextures[ webglType ] );
  18303. boundTexture.type = webglType;
  18304. boundTexture.texture = webglTexture;
  18305. }
  18306. }
  18307. function unbindTexture() {
  18308. var boundTexture = currentBoundTextures[ currentTextureSlot ];
  18309. if ( boundTexture !== undefined && boundTexture.type !== undefined ) {
  18310. gl.bindTexture( boundTexture.type, null );
  18311. boundTexture.type = undefined;
  18312. boundTexture.texture = undefined;
  18313. }
  18314. }
  18315. function compressedTexImage2D() {
  18316. try {
  18317. gl.compressedTexImage2D.apply( gl, arguments );
  18318. } catch ( error ) {
  18319. console.error( 'THREE.WebGLState:', error );
  18320. }
  18321. }
  18322. function texImage2D() {
  18323. try {
  18324. gl.texImage2D.apply( gl, arguments );
  18325. } catch ( error ) {
  18326. console.error( 'THREE.WebGLState:', error );
  18327. }
  18328. }
  18329. function texImage3D() {
  18330. try {
  18331. gl.texImage3D.apply( gl, arguments );
  18332. } catch ( error ) {
  18333. console.error( 'THREE.WebGLState:', error );
  18334. }
  18335. }
  18336. //
  18337. function scissor( scissor ) {
  18338. if ( currentScissor.equals( scissor ) === false ) {
  18339. gl.scissor( scissor.x, scissor.y, scissor.z, scissor.w );
  18340. currentScissor.copy( scissor );
  18341. }
  18342. }
  18343. function viewport( viewport ) {
  18344. if ( currentViewport.equals( viewport ) === false ) {
  18345. gl.viewport( viewport.x, viewport.y, viewport.z, viewport.w );
  18346. currentViewport.copy( viewport );
  18347. }
  18348. }
  18349. //
  18350. function reset() {
  18351. for ( var i = 0; i < enabledAttributes.length; i ++ ) {
  18352. if ( enabledAttributes[ i ] === 1 ) {
  18353. gl.disableVertexAttribArray( i );
  18354. enabledAttributes[ i ] = 0;
  18355. }
  18356. }
  18357. enabledCapabilities = {};
  18358. currentTextureSlot = null;
  18359. currentBoundTextures = {};
  18360. currentProgram = null;
  18361. currentBlending = null;
  18362. currentFlipSided = null;
  18363. currentCullFace = null;
  18364. colorBuffer.reset();
  18365. depthBuffer.reset();
  18366. stencilBuffer.reset();
  18367. }
  18368. return {
  18369. buffers: {
  18370. color: colorBuffer,
  18371. depth: depthBuffer,
  18372. stencil: stencilBuffer
  18373. },
  18374. initAttributes: initAttributes,
  18375. enableAttribute: enableAttribute,
  18376. enableAttributeAndDivisor: enableAttributeAndDivisor,
  18377. disableUnusedAttributes: disableUnusedAttributes,
  18378. enable: enable,
  18379. disable: disable,
  18380. useProgram: useProgram,
  18381. setBlending: setBlending,
  18382. setMaterial: setMaterial,
  18383. setFlipSided: setFlipSided,
  18384. setCullFace: setCullFace,
  18385. setLineWidth: setLineWidth,
  18386. setPolygonOffset: setPolygonOffset,
  18387. setScissorTest: setScissorTest,
  18388. activeTexture: activeTexture,
  18389. bindTexture: bindTexture,
  18390. unbindTexture: unbindTexture,
  18391. compressedTexImage2D: compressedTexImage2D,
  18392. texImage2D: texImage2D,
  18393. texImage3D: texImage3D,
  18394. scissor: scissor,
  18395. viewport: viewport,
  18396. reset: reset
  18397. };
  18398. }
  18399. /**
  18400. * @author mrdoob / http://mrdoob.com/
  18401. */
  18402. function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info ) {
  18403. var isWebGL2 = capabilities.isWebGL2;
  18404. var maxTextures = capabilities.maxTextures;
  18405. var maxCubemapSize = capabilities.maxCubemapSize;
  18406. var maxTextureSize = capabilities.maxTextureSize;
  18407. var maxSamples = capabilities.maxSamples;
  18408. var _videoTextures = new WeakMap();
  18409. var _canvas;
  18410. // cordova iOS (as of 5.0) still uses UIWebView, which provides OffscreenCanvas,
  18411. // also OffscreenCanvas.getContext("webgl"), but not OffscreenCanvas.getContext("2d")!
  18412. // Some implementations may only implement OffscreenCanvas partially (e.g. lacking 2d).
  18413. var useOffscreenCanvas = false;
  18414. try {
  18415. useOffscreenCanvas = typeof OffscreenCanvas !== 'undefined'
  18416. && ( new OffscreenCanvas( 1, 1 ).getContext( "2d" ) ) !== null;
  18417. } catch ( err ) {
  18418. // Ignore any errors
  18419. }
  18420. function createCanvas( width, height ) {
  18421. // Use OffscreenCanvas when available. Specially needed in web workers
  18422. return useOffscreenCanvas ?
  18423. new OffscreenCanvas( width, height ) :
  18424. document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  18425. }
  18426. function resizeImage( image, needsPowerOfTwo, needsNewCanvas, maxSize ) {
  18427. var scale = 1;
  18428. // handle case if texture exceeds max size
  18429. if ( image.width > maxSize || image.height > maxSize ) {
  18430. scale = maxSize / Math.max( image.width, image.height );
  18431. }
  18432. // only perform resize if necessary
  18433. if ( scale < 1 || needsPowerOfTwo === true ) {
  18434. // only perform resize for certain image types
  18435. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  18436. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  18437. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  18438. var floor = needsPowerOfTwo ? MathUtils.floorPowerOfTwo : Math.floor;
  18439. var width = floor( scale * image.width );
  18440. var height = floor( scale * image.height );
  18441. if ( _canvas === undefined ) { _canvas = createCanvas( width, height ); }
  18442. // cube textures can't reuse the same canvas
  18443. var canvas = needsNewCanvas ? createCanvas( width, height ) : _canvas;
  18444. canvas.width = width;
  18445. canvas.height = height;
  18446. var context = canvas.getContext( '2d' );
  18447. context.drawImage( image, 0, 0, width, height );
  18448. console.warn( 'THREE.WebGLRenderer: Texture has been resized from (' + image.width + 'x' + image.height + ') to (' + width + 'x' + height + ').' );
  18449. return canvas;
  18450. } else {
  18451. if ( 'data' in image ) {
  18452. console.warn( 'THREE.WebGLRenderer: Image in DataTexture is too big (' + image.width + 'x' + image.height + ').' );
  18453. }
  18454. return image;
  18455. }
  18456. }
  18457. return image;
  18458. }
  18459. function isPowerOfTwo( image ) {
  18460. return MathUtils.isPowerOfTwo( image.width ) && MathUtils.isPowerOfTwo( image.height );
  18461. }
  18462. function textureNeedsPowerOfTwo( texture ) {
  18463. if ( isWebGL2 ) { return false; }
  18464. return ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) ||
  18465. ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter );
  18466. }
  18467. function textureNeedsGenerateMipmaps( texture, supportsMips ) {
  18468. return texture.generateMipmaps && supportsMips &&
  18469. texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter;
  18470. }
  18471. function generateMipmap( target, texture, width, height ) {
  18472. _gl.generateMipmap( target );
  18473. var textureProperties = properties.get( texture );
  18474. // Note: Math.log( x ) * Math.LOG2E used instead of Math.log2( x ) which is not supported by IE11
  18475. textureProperties.__maxMipLevel = Math.log( Math.max( width, height ) ) * Math.LOG2E;
  18476. }
  18477. function getInternalFormat( internalFormatName, glFormat, glType ) {
  18478. if ( isWebGL2 === false ) { return glFormat; }
  18479. if ( internalFormatName !== null ) {
  18480. if ( _gl[ internalFormatName ] !== undefined ) { return _gl[ internalFormatName ]; }
  18481. console.warn( 'THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'' );
  18482. }
  18483. var internalFormat = glFormat;
  18484. if ( glFormat === 6403 ) {
  18485. if ( glType === 5126 ) { internalFormat = 33326; }
  18486. if ( glType === 5131 ) { internalFormat = 33325; }
  18487. if ( glType === 5121 ) { internalFormat = 33321; }
  18488. }
  18489. if ( glFormat === 6407 ) {
  18490. if ( glType === 5126 ) { internalFormat = 34837; }
  18491. if ( glType === 5131 ) { internalFormat = 34843; }
  18492. if ( glType === 5121 ) { internalFormat = 32849; }
  18493. }
  18494. if ( glFormat === 6408 ) {
  18495. if ( glType === 5126 ) { internalFormat = 34836; }
  18496. if ( glType === 5131 ) { internalFormat = 34842; }
  18497. if ( glType === 5121 ) { internalFormat = 32856; }
  18498. }
  18499. if ( internalFormat === 33325 || internalFormat === 33326 ||
  18500. internalFormat === 34842 || internalFormat === 34836 ) {
  18501. extensions.get( 'EXT_color_buffer_float' );
  18502. }
  18503. return internalFormat;
  18504. }
  18505. // Fallback filters for non-power-of-2 textures
  18506. function filterFallback( f ) {
  18507. if ( f === NearestFilter || f === NearestMipmapNearestFilter || f === NearestMipmapLinearFilter ) {
  18508. return 9728;
  18509. }
  18510. return 9729;
  18511. }
  18512. //
  18513. function onTextureDispose( event ) {
  18514. var texture = event.target;
  18515. texture.removeEventListener( 'dispose', onTextureDispose );
  18516. deallocateTexture( texture );
  18517. if ( texture.isVideoTexture ) {
  18518. _videoTextures.delete( texture );
  18519. }
  18520. info.memory.textures --;
  18521. }
  18522. function onRenderTargetDispose( event ) {
  18523. var renderTarget = event.target;
  18524. renderTarget.removeEventListener( 'dispose', onRenderTargetDispose );
  18525. deallocateRenderTarget( renderTarget );
  18526. info.memory.textures --;
  18527. }
  18528. //
  18529. function deallocateTexture( texture ) {
  18530. var textureProperties = properties.get( texture );
  18531. if ( textureProperties.__webglInit === undefined ) { return; }
  18532. _gl.deleteTexture( textureProperties.__webglTexture );
  18533. properties.remove( texture );
  18534. }
  18535. function deallocateRenderTarget( renderTarget ) {
  18536. var renderTargetProperties = properties.get( renderTarget );
  18537. var textureProperties = properties.get( renderTarget.texture );
  18538. if ( ! renderTarget ) { return; }
  18539. if ( textureProperties.__webglTexture !== undefined ) {
  18540. _gl.deleteTexture( textureProperties.__webglTexture );
  18541. }
  18542. if ( renderTarget.depthTexture ) {
  18543. renderTarget.depthTexture.dispose();
  18544. }
  18545. if ( renderTarget.isWebGLCubeRenderTarget ) {
  18546. for ( var i = 0; i < 6; i ++ ) {
  18547. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ i ] );
  18548. if ( renderTargetProperties.__webglDepthbuffer ) { _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer[ i ] ); }
  18549. }
  18550. } else {
  18551. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer );
  18552. if ( renderTargetProperties.__webglDepthbuffer ) { _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer ); }
  18553. if ( renderTargetProperties.__webglMultisampledFramebuffer ) { _gl.deleteFramebuffer( renderTargetProperties.__webglMultisampledFramebuffer ); }
  18554. if ( renderTargetProperties.__webglColorRenderbuffer ) { _gl.deleteRenderbuffer( renderTargetProperties.__webglColorRenderbuffer ); }
  18555. if ( renderTargetProperties.__webglDepthRenderbuffer ) { _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthRenderbuffer ); }
  18556. }
  18557. properties.remove( renderTarget.texture );
  18558. properties.remove( renderTarget );
  18559. }
  18560. //
  18561. var textureUnits = 0;
  18562. function resetTextureUnits() {
  18563. textureUnits = 0;
  18564. }
  18565. function allocateTextureUnit() {
  18566. var textureUnit = textureUnits;
  18567. if ( textureUnit >= maxTextures ) {
  18568. console.warn( 'THREE.WebGLTextures: Trying to use ' + textureUnit + ' texture units while this GPU supports only ' + maxTextures );
  18569. }
  18570. textureUnits += 1;
  18571. return textureUnit;
  18572. }
  18573. //
  18574. function setTexture2D( texture, slot ) {
  18575. var textureProperties = properties.get( texture );
  18576. if ( texture.isVideoTexture ) { updateVideoTexture( texture ); }
  18577. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  18578. var image = texture.image;
  18579. if ( image === undefined ) {
  18580. console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is undefined' );
  18581. } else if ( image.complete === false ) {
  18582. console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is incomplete' );
  18583. } else {
  18584. uploadTexture( textureProperties, texture, slot );
  18585. return;
  18586. }
  18587. }
  18588. state.activeTexture( 33984 + slot );
  18589. state.bindTexture( 3553, textureProperties.__webglTexture );
  18590. }
  18591. function setTexture2DArray( texture, slot ) {
  18592. var textureProperties = properties.get( texture );
  18593. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  18594. uploadTexture( textureProperties, texture, slot );
  18595. return;
  18596. }
  18597. state.activeTexture( 33984 + slot );
  18598. state.bindTexture( 35866, textureProperties.__webglTexture );
  18599. }
  18600. function setTexture3D( texture, slot ) {
  18601. var textureProperties = properties.get( texture );
  18602. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  18603. uploadTexture( textureProperties, texture, slot );
  18604. return;
  18605. }
  18606. state.activeTexture( 33984 + slot );
  18607. state.bindTexture( 32879, textureProperties.__webglTexture );
  18608. }
  18609. function setTextureCube( texture, slot ) {
  18610. if ( texture.image.length !== 6 ) { return; }
  18611. var textureProperties = properties.get( texture );
  18612. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  18613. initTexture( textureProperties, texture );
  18614. state.activeTexture( 33984 + slot );
  18615. state.bindTexture( 34067, textureProperties.__webglTexture );
  18616. _gl.pixelStorei( 37440, texture.flipY );
  18617. var isCompressed = ( texture && ( texture.isCompressedTexture || texture.image[ 0 ].isCompressedTexture ) );
  18618. var isDataTexture = ( texture.image[ 0 ] && texture.image[ 0 ].isDataTexture );
  18619. var cubeImage = [];
  18620. for ( var i = 0; i < 6; i ++ ) {
  18621. if ( ! isCompressed && ! isDataTexture ) {
  18622. cubeImage[ i ] = resizeImage( texture.image[ i ], false, true, maxCubemapSize );
  18623. } else {
  18624. cubeImage[ i ] = isDataTexture ? texture.image[ i ].image : texture.image[ i ];
  18625. }
  18626. }
  18627. var image = cubeImage[ 0 ],
  18628. supportsMips = isPowerOfTwo( image ) || isWebGL2,
  18629. glFormat = utils.convert( texture.format ),
  18630. glType = utils.convert( texture.type ),
  18631. glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType );
  18632. setTextureParameters( 34067, texture, supportsMips );
  18633. var mipmaps;
  18634. if ( isCompressed ) {
  18635. for ( var i = 0; i < 6; i ++ ) {
  18636. mipmaps = cubeImage[ i ].mipmaps;
  18637. for ( var j = 0; j < mipmaps.length; j ++ ) {
  18638. var mipmap = mipmaps[ j ];
  18639. if ( texture.format !== RGBAFormat && texture.format !== RGBFormat ) {
  18640. if ( glFormat !== null ) {
  18641. state.compressedTexImage2D( 34069 + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  18642. } else {
  18643. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()' );
  18644. }
  18645. } else {
  18646. state.texImage2D( 34069 + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  18647. }
  18648. }
  18649. }
  18650. textureProperties.__maxMipLevel = mipmaps.length - 1;
  18651. } else {
  18652. mipmaps = texture.mipmaps;
  18653. for ( var i = 0; i < 6; i ++ ) {
  18654. if ( isDataTexture ) {
  18655. state.texImage2D( 34069 + i, 0, glInternalFormat, cubeImage[ i ].width, cubeImage[ i ].height, 0, glFormat, glType, cubeImage[ i ].data );
  18656. for ( var j = 0; j < mipmaps.length; j ++ ) {
  18657. var mipmap = mipmaps[ j ];
  18658. var mipmapImage = mipmap.image[ i ].image;
  18659. state.texImage2D( 34069 + i, j + 1, glInternalFormat, mipmapImage.width, mipmapImage.height, 0, glFormat, glType, mipmapImage.data );
  18660. }
  18661. } else {
  18662. state.texImage2D( 34069 + i, 0, glInternalFormat, glFormat, glType, cubeImage[ i ] );
  18663. for ( var j = 0; j < mipmaps.length; j ++ ) {
  18664. var mipmap = mipmaps[ j ];
  18665. state.texImage2D( 34069 + i, j + 1, glInternalFormat, glFormat, glType, mipmap.image[ i ] );
  18666. }
  18667. }
  18668. }
  18669. textureProperties.__maxMipLevel = mipmaps.length;
  18670. }
  18671. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  18672. // We assume images for cube map have the same size.
  18673. generateMipmap( 34067, texture, image.width, image.height );
  18674. }
  18675. textureProperties.__version = texture.version;
  18676. if ( texture.onUpdate ) { texture.onUpdate( texture ); }
  18677. } else {
  18678. state.activeTexture( 33984 + slot );
  18679. state.bindTexture( 34067, textureProperties.__webglTexture );
  18680. }
  18681. }
  18682. function setTextureCubeDynamic( texture, slot ) {
  18683. state.activeTexture( 33984 + slot );
  18684. state.bindTexture( 34067, properties.get( texture ).__webglTexture );
  18685. }
  18686. var wrappingToGL = {};
  18687. wrappingToGL[ RepeatWrapping ] = 10497;
  18688. wrappingToGL[ ClampToEdgeWrapping ] = 33071;
  18689. wrappingToGL[ MirroredRepeatWrapping ] = 33648;
  18690. var filterToGL = {};
  18691. filterToGL[ NearestFilter ] = 9728;
  18692. filterToGL[ NearestMipmapNearestFilter ] = 9984;
  18693. filterToGL[ NearestMipmapLinearFilter ] = 9986;
  18694. filterToGL[ LinearFilter ] = 9729;
  18695. filterToGL[ LinearMipmapNearestFilter ] = 9985;
  18696. filterToGL[ LinearMipmapLinearFilter ] = 9987;
  18697. function setTextureParameters( textureType, texture, supportsMips ) {
  18698. if ( supportsMips ) {
  18699. _gl.texParameteri( textureType, 10242, wrappingToGL[ texture.wrapS ] );
  18700. _gl.texParameteri( textureType, 10243, wrappingToGL[ texture.wrapT ] );
  18701. if ( textureType === 32879 || textureType === 35866 ) {
  18702. _gl.texParameteri( textureType, 32882, wrappingToGL[ texture.wrapR ] );
  18703. }
  18704. _gl.texParameteri( textureType, 10240, filterToGL[ texture.magFilter ] );
  18705. _gl.texParameteri( textureType, 10241, filterToGL[ texture.minFilter ] );
  18706. } else {
  18707. _gl.texParameteri( textureType, 10242, 33071 );
  18708. _gl.texParameteri( textureType, 10243, 33071 );
  18709. if ( textureType === 32879 || textureType === 35866 ) {
  18710. _gl.texParameteri( textureType, 32882, 33071 );
  18711. }
  18712. if ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) {
  18713. console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping.' );
  18714. }
  18715. _gl.texParameteri( textureType, 10240, filterFallback( texture.magFilter ) );
  18716. _gl.texParameteri( textureType, 10241, filterFallback( texture.minFilter ) );
  18717. if ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ) {
  18718. console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.' );
  18719. }
  18720. }
  18721. var extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  18722. if ( extension ) {
  18723. if ( texture.type === FloatType && extensions.get( 'OES_texture_float_linear' ) === null ) { return; }
  18724. if ( texture.type === HalfFloatType && ( isWebGL2 || extensions.get( 'OES_texture_half_float_linear' ) ) === null ) { return; }
  18725. if ( texture.anisotropy > 1 || properties.get( texture ).__currentAnisotropy ) {
  18726. _gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, capabilities.getMaxAnisotropy() ) );
  18727. properties.get( texture ).__currentAnisotropy = texture.anisotropy;
  18728. }
  18729. }
  18730. }
  18731. function initTexture( textureProperties, texture ) {
  18732. if ( textureProperties.__webglInit === undefined ) {
  18733. textureProperties.__webglInit = true;
  18734. texture.addEventListener( 'dispose', onTextureDispose );
  18735. textureProperties.__webglTexture = _gl.createTexture();
  18736. info.memory.textures ++;
  18737. }
  18738. }
  18739. function uploadTexture( textureProperties, texture, slot ) {
  18740. var textureType = 3553;
  18741. if ( texture.isDataTexture2DArray ) { textureType = 35866; }
  18742. if ( texture.isDataTexture3D ) { textureType = 32879; }
  18743. initTexture( textureProperties, texture );
  18744. state.activeTexture( 33984 + slot );
  18745. state.bindTexture( textureType, textureProperties.__webglTexture );
  18746. _gl.pixelStorei( 37440, texture.flipY );
  18747. _gl.pixelStorei( 37441, texture.premultiplyAlpha );
  18748. _gl.pixelStorei( 3317, texture.unpackAlignment );
  18749. var needsPowerOfTwo = textureNeedsPowerOfTwo( texture ) && isPowerOfTwo( texture.image ) === false;
  18750. var image = resizeImage( texture.image, needsPowerOfTwo, false, maxTextureSize );
  18751. var supportsMips = isPowerOfTwo( image ) || isWebGL2,
  18752. glFormat = utils.convert( texture.format ),
  18753. glType = utils.convert( texture.type ),
  18754. glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType );
  18755. setTextureParameters( textureType, texture, supportsMips );
  18756. var mipmap, mipmaps = texture.mipmaps;
  18757. if ( texture.isDepthTexture ) {
  18758. // populate depth texture with dummy data
  18759. glInternalFormat = 6402;
  18760. if ( isWebGL2 ) {
  18761. if ( texture.type === FloatType ) {
  18762. glInternalFormat = 36012;
  18763. } else if ( texture.type === UnsignedIntType ) {
  18764. glInternalFormat = 33190;
  18765. } else if ( texture.type === UnsignedInt248Type ) {
  18766. glInternalFormat = 35056;
  18767. } else {
  18768. glInternalFormat = 33189; // WebGL2 requires sized internalformat for glTexImage2D
  18769. }
  18770. } else {
  18771. if ( texture.type === FloatType ) {
  18772. console.error( 'WebGLRenderer: Floating point depth texture requires WebGL2.' );
  18773. }
  18774. }
  18775. // validation checks for WebGL 1
  18776. if ( texture.format === DepthFormat && glInternalFormat === 6402 ) {
  18777. // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  18778. // DEPTH_COMPONENT and type is not UNSIGNED_SHORT or UNSIGNED_INT
  18779. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  18780. if ( texture.type !== UnsignedShortType && texture.type !== UnsignedIntType ) {
  18781. console.warn( 'THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture.' );
  18782. texture.type = UnsignedShortType;
  18783. glType = utils.convert( texture.type );
  18784. }
  18785. }
  18786. if ( texture.format === DepthStencilFormat && glInternalFormat === 6402 ) {
  18787. // Depth stencil textures need the DEPTH_STENCIL internal format
  18788. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  18789. glInternalFormat = 34041;
  18790. // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  18791. // DEPTH_STENCIL and type is not UNSIGNED_INT_24_8_WEBGL.
  18792. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  18793. if ( texture.type !== UnsignedInt248Type ) {
  18794. console.warn( 'THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture.' );
  18795. texture.type = UnsignedInt248Type;
  18796. glType = utils.convert( texture.type );
  18797. }
  18798. }
  18799. //
  18800. state.texImage2D( 3553, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, null );
  18801. } else if ( texture.isDataTexture ) {
  18802. // use manually created mipmaps if available
  18803. // if there are no manual mipmaps
  18804. // set 0 level mipmap and then use GL to generate other mipmap levels
  18805. if ( mipmaps.length > 0 && supportsMips ) {
  18806. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  18807. mipmap = mipmaps[ i ];
  18808. state.texImage2D( 3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  18809. }
  18810. texture.generateMipmaps = false;
  18811. textureProperties.__maxMipLevel = mipmaps.length - 1;
  18812. } else {
  18813. state.texImage2D( 3553, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, image.data );
  18814. textureProperties.__maxMipLevel = 0;
  18815. }
  18816. } else if ( texture.isCompressedTexture ) {
  18817. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  18818. mipmap = mipmaps[ i ];
  18819. if ( texture.format !== RGBAFormat && texture.format !== RGBFormat ) {
  18820. if ( glFormat !== null ) {
  18821. state.compressedTexImage2D( 3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  18822. } else {
  18823. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  18824. }
  18825. } else {
  18826. state.texImage2D( 3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  18827. }
  18828. }
  18829. textureProperties.__maxMipLevel = mipmaps.length - 1;
  18830. } else if ( texture.isDataTexture2DArray ) {
  18831. state.texImage3D( 35866, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data );
  18832. textureProperties.__maxMipLevel = 0;
  18833. } else if ( texture.isDataTexture3D ) {
  18834. state.texImage3D( 32879, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data );
  18835. textureProperties.__maxMipLevel = 0;
  18836. } else {
  18837. // regular Texture (image, video, canvas)
  18838. // use manually created mipmaps if available
  18839. // if there are no manual mipmaps
  18840. // set 0 level mipmap and then use GL to generate other mipmap levels
  18841. if ( mipmaps.length > 0 && supportsMips ) {
  18842. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  18843. mipmap = mipmaps[ i ];
  18844. state.texImage2D( 3553, i, glInternalFormat, glFormat, glType, mipmap );
  18845. }
  18846. texture.generateMipmaps = false;
  18847. textureProperties.__maxMipLevel = mipmaps.length - 1;
  18848. } else {
  18849. state.texImage2D( 3553, 0, glInternalFormat, glFormat, glType, image );
  18850. textureProperties.__maxMipLevel = 0;
  18851. }
  18852. }
  18853. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  18854. generateMipmap( textureType, texture, image.width, image.height );
  18855. }
  18856. textureProperties.__version = texture.version;
  18857. if ( texture.onUpdate ) { texture.onUpdate( texture ); }
  18858. }
  18859. // Render targets
  18860. // Setup storage for target texture and bind it to correct framebuffer
  18861. function setupFrameBufferTexture( framebuffer, renderTarget, attachment, textureTarget ) {
  18862. var glFormat = utils.convert( renderTarget.texture.format );
  18863. var glType = utils.convert( renderTarget.texture.type );
  18864. var glInternalFormat = getInternalFormat( renderTarget.texture.internalFormat, glFormat, glType );
  18865. state.texImage2D( textureTarget, 0, glInternalFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  18866. _gl.bindFramebuffer( 36160, framebuffer );
  18867. _gl.framebufferTexture2D( 36160, attachment, textureTarget, properties.get( renderTarget.texture ).__webglTexture, 0 );
  18868. _gl.bindFramebuffer( 36160, null );
  18869. }
  18870. // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  18871. function setupRenderBufferStorage( renderbuffer, renderTarget, isMultisample ) {
  18872. _gl.bindRenderbuffer( 36161, renderbuffer );
  18873. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  18874. var glInternalFormat = 33189;
  18875. if ( isMultisample ) {
  18876. var depthTexture = renderTarget.depthTexture;
  18877. if ( depthTexture && depthTexture.isDepthTexture ) {
  18878. if ( depthTexture.type === FloatType ) {
  18879. glInternalFormat = 36012;
  18880. } else if ( depthTexture.type === UnsignedIntType ) {
  18881. glInternalFormat = 33190;
  18882. }
  18883. }
  18884. var samples = getRenderTargetSamples( renderTarget );
  18885. _gl.renderbufferStorageMultisample( 36161, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  18886. } else {
  18887. _gl.renderbufferStorage( 36161, glInternalFormat, renderTarget.width, renderTarget.height );
  18888. }
  18889. _gl.framebufferRenderbuffer( 36160, 36096, 36161, renderbuffer );
  18890. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  18891. if ( isMultisample ) {
  18892. var samples = getRenderTargetSamples( renderTarget );
  18893. _gl.renderbufferStorageMultisample( 36161, samples, 35056, renderTarget.width, renderTarget.height );
  18894. } else {
  18895. _gl.renderbufferStorage( 36161, 34041, renderTarget.width, renderTarget.height );
  18896. }
  18897. _gl.framebufferRenderbuffer( 36160, 33306, 36161, renderbuffer );
  18898. } else {
  18899. var glFormat = utils.convert( renderTarget.texture.format );
  18900. var glType = utils.convert( renderTarget.texture.type );
  18901. var glInternalFormat = getInternalFormat( renderTarget.texture.internalFormat, glFormat, glType );
  18902. if ( isMultisample ) {
  18903. var samples = getRenderTargetSamples( renderTarget );
  18904. _gl.renderbufferStorageMultisample( 36161, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  18905. } else {
  18906. _gl.renderbufferStorage( 36161, glInternalFormat, renderTarget.width, renderTarget.height );
  18907. }
  18908. }
  18909. _gl.bindRenderbuffer( 36161, null );
  18910. }
  18911. // Setup resources for a Depth Texture for a FBO (needs an extension)
  18912. function setupDepthTexture( framebuffer, renderTarget ) {
  18913. var isCube = ( renderTarget && renderTarget.isWebGLCubeRenderTarget );
  18914. if ( isCube ) { throw new Error( 'Depth Texture with cube render targets is not supported' ); }
  18915. _gl.bindFramebuffer( 36160, framebuffer );
  18916. if ( ! ( renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture ) ) {
  18917. throw new Error( 'renderTarget.depthTexture must be an instance of THREE.DepthTexture' );
  18918. }
  18919. // upload an empty depth texture with framebuffer size
  18920. if ( ! properties.get( renderTarget.depthTexture ).__webglTexture ||
  18921. renderTarget.depthTexture.image.width !== renderTarget.width ||
  18922. renderTarget.depthTexture.image.height !== renderTarget.height ) {
  18923. renderTarget.depthTexture.image.width = renderTarget.width;
  18924. renderTarget.depthTexture.image.height = renderTarget.height;
  18925. renderTarget.depthTexture.needsUpdate = true;
  18926. }
  18927. setTexture2D( renderTarget.depthTexture, 0 );
  18928. var webglDepthTexture = properties.get( renderTarget.depthTexture ).__webglTexture;
  18929. if ( renderTarget.depthTexture.format === DepthFormat ) {
  18930. _gl.framebufferTexture2D( 36160, 36096, 3553, webglDepthTexture, 0 );
  18931. } else if ( renderTarget.depthTexture.format === DepthStencilFormat ) {
  18932. _gl.framebufferTexture2D( 36160, 33306, 3553, webglDepthTexture, 0 );
  18933. } else {
  18934. throw new Error( 'Unknown depthTexture format' );
  18935. }
  18936. }
  18937. // Setup GL resources for a non-texture depth buffer
  18938. function setupDepthRenderbuffer( renderTarget ) {
  18939. var renderTargetProperties = properties.get( renderTarget );
  18940. var isCube = ( renderTarget.isWebGLCubeRenderTarget === true );
  18941. if ( renderTarget.depthTexture ) {
  18942. if ( isCube ) { throw new Error( 'target.depthTexture not supported in Cube render targets' ); }
  18943. setupDepthTexture( renderTargetProperties.__webglFramebuffer, renderTarget );
  18944. } else {
  18945. if ( isCube ) {
  18946. renderTargetProperties.__webglDepthbuffer = [];
  18947. for ( var i = 0; i < 6; i ++ ) {
  18948. _gl.bindFramebuffer( 36160, renderTargetProperties.__webglFramebuffer[ i ] );
  18949. renderTargetProperties.__webglDepthbuffer[ i ] = _gl.createRenderbuffer();
  18950. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer[ i ], renderTarget, false );
  18951. }
  18952. } else {
  18953. _gl.bindFramebuffer( 36160, renderTargetProperties.__webglFramebuffer );
  18954. renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer();
  18955. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer, renderTarget, false );
  18956. }
  18957. }
  18958. _gl.bindFramebuffer( 36160, null );
  18959. }
  18960. // Set up GL resources for the render target
  18961. function setupRenderTarget( renderTarget ) {
  18962. var renderTargetProperties = properties.get( renderTarget );
  18963. var textureProperties = properties.get( renderTarget.texture );
  18964. renderTarget.addEventListener( 'dispose', onRenderTargetDispose );
  18965. textureProperties.__webglTexture = _gl.createTexture();
  18966. info.memory.textures ++;
  18967. var isCube = ( renderTarget.isWebGLCubeRenderTarget === true );
  18968. var isMultisample = ( renderTarget.isWebGLMultisampleRenderTarget === true );
  18969. var supportsMips = isPowerOfTwo( renderTarget ) || isWebGL2;
  18970. // Handles WebGL2 RGBFormat fallback - #18858
  18971. if ( isWebGL2 && renderTarget.texture.format === RGBFormat && ( renderTarget.texture.type === FloatType || renderTarget.texture.type === HalfFloatType ) ) {
  18972. renderTarget.texture.format = RGBAFormat;
  18973. console.warn( 'THREE.WebGLRenderer: Rendering to textures with RGB format is not supported. Using RGBA format instead.' );
  18974. }
  18975. // Setup framebuffer
  18976. if ( isCube ) {
  18977. renderTargetProperties.__webglFramebuffer = [];
  18978. for ( var i = 0; i < 6; i ++ ) {
  18979. renderTargetProperties.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  18980. }
  18981. } else {
  18982. renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer();
  18983. if ( isMultisample ) {
  18984. if ( isWebGL2 ) {
  18985. renderTargetProperties.__webglMultisampledFramebuffer = _gl.createFramebuffer();
  18986. renderTargetProperties.__webglColorRenderbuffer = _gl.createRenderbuffer();
  18987. _gl.bindRenderbuffer( 36161, renderTargetProperties.__webglColorRenderbuffer );
  18988. var glFormat = utils.convert( renderTarget.texture.format );
  18989. var glType = utils.convert( renderTarget.texture.type );
  18990. var glInternalFormat = getInternalFormat( renderTarget.texture.internalFormat, glFormat, glType );
  18991. var samples = getRenderTargetSamples( renderTarget );
  18992. _gl.renderbufferStorageMultisample( 36161, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  18993. _gl.bindFramebuffer( 36160, renderTargetProperties.__webglMultisampledFramebuffer );
  18994. _gl.framebufferRenderbuffer( 36160, 36064, 36161, renderTargetProperties.__webglColorRenderbuffer );
  18995. _gl.bindRenderbuffer( 36161, null );
  18996. if ( renderTarget.depthBuffer ) {
  18997. renderTargetProperties.__webglDepthRenderbuffer = _gl.createRenderbuffer();
  18998. setupRenderBufferStorage( renderTargetProperties.__webglDepthRenderbuffer, renderTarget, true );
  18999. }
  19000. _gl.bindFramebuffer( 36160, null );
  19001. } else {
  19002. console.warn( 'THREE.WebGLRenderer: WebGLMultisampleRenderTarget can only be used with WebGL2.' );
  19003. }
  19004. }
  19005. }
  19006. // Setup color buffer
  19007. if ( isCube ) {
  19008. state.bindTexture( 34067, textureProperties.__webglTexture );
  19009. setTextureParameters( 34067, renderTarget.texture, supportsMips );
  19010. for ( var i = 0; i < 6; i ++ ) {
  19011. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ i ], renderTarget, 36064, 34069 + i );
  19012. }
  19013. if ( textureNeedsGenerateMipmaps( renderTarget.texture, supportsMips ) ) {
  19014. generateMipmap( 34067, renderTarget.texture, renderTarget.width, renderTarget.height );
  19015. }
  19016. state.bindTexture( 34067, null );
  19017. } else {
  19018. state.bindTexture( 3553, textureProperties.__webglTexture );
  19019. setTextureParameters( 3553, renderTarget.texture, supportsMips );
  19020. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, 36064, 3553 );
  19021. if ( textureNeedsGenerateMipmaps( renderTarget.texture, supportsMips ) ) {
  19022. generateMipmap( 3553, renderTarget.texture, renderTarget.width, renderTarget.height );
  19023. }
  19024. state.bindTexture( 3553, null );
  19025. }
  19026. // Setup depth and stencil buffers
  19027. if ( renderTarget.depthBuffer ) {
  19028. setupDepthRenderbuffer( renderTarget );
  19029. }
  19030. }
  19031. function updateRenderTargetMipmap( renderTarget ) {
  19032. var texture = renderTarget.texture;
  19033. var supportsMips = isPowerOfTwo( renderTarget ) || isWebGL2;
  19034. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  19035. var target = renderTarget.isWebGLCubeRenderTarget ? 34067 : 3553;
  19036. var webglTexture = properties.get( texture ).__webglTexture;
  19037. state.bindTexture( target, webglTexture );
  19038. generateMipmap( target, texture, renderTarget.width, renderTarget.height );
  19039. state.bindTexture( target, null );
  19040. }
  19041. }
  19042. function updateMultisampleRenderTarget( renderTarget ) {
  19043. if ( renderTarget.isWebGLMultisampleRenderTarget ) {
  19044. if ( isWebGL2 ) {
  19045. var renderTargetProperties = properties.get( renderTarget );
  19046. _gl.bindFramebuffer( 36008, renderTargetProperties.__webglMultisampledFramebuffer );
  19047. _gl.bindFramebuffer( 36009, renderTargetProperties.__webglFramebuffer );
  19048. var width = renderTarget.width;
  19049. var height = renderTarget.height;
  19050. var mask = 16384;
  19051. if ( renderTarget.depthBuffer ) { mask |= 256; }
  19052. if ( renderTarget.stencilBuffer ) { mask |= 1024; }
  19053. _gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, mask, 9728 );
  19054. _gl.bindFramebuffer( 36160, renderTargetProperties.__webglMultisampledFramebuffer ); // see #18905
  19055. } else {
  19056. console.warn( 'THREE.WebGLRenderer: WebGLMultisampleRenderTarget can only be used with WebGL2.' );
  19057. }
  19058. }
  19059. }
  19060. function getRenderTargetSamples( renderTarget ) {
  19061. return ( isWebGL2 && renderTarget.isWebGLMultisampleRenderTarget ) ?
  19062. Math.min( maxSamples, renderTarget.samples ) : 0;
  19063. }
  19064. function updateVideoTexture( texture ) {
  19065. var frame = info.render.frame;
  19066. // Check the last frame we updated the VideoTexture
  19067. if ( _videoTextures.get( texture ) !== frame ) {
  19068. _videoTextures.set( texture, frame );
  19069. texture.update();
  19070. }
  19071. }
  19072. // backwards compatibility
  19073. var warnedTexture2D = false;
  19074. var warnedTextureCube = false;
  19075. function safeSetTexture2D( texture, slot ) {
  19076. if ( texture && texture.isWebGLRenderTarget ) {
  19077. if ( warnedTexture2D === false ) {
  19078. console.warn( "THREE.WebGLTextures.safeSetTexture2D: don't use render targets as textures. Use their .texture property instead." );
  19079. warnedTexture2D = true;
  19080. }
  19081. texture = texture.texture;
  19082. }
  19083. setTexture2D( texture, slot );
  19084. }
  19085. function safeSetTextureCube( texture, slot ) {
  19086. if ( texture && texture.isWebGLCubeRenderTarget ) {
  19087. if ( warnedTextureCube === false ) {
  19088. console.warn( "THREE.WebGLTextures.safeSetTextureCube: don't use cube render targets as textures. Use their .texture property instead." );
  19089. warnedTextureCube = true;
  19090. }
  19091. texture = texture.texture;
  19092. }
  19093. // currently relying on the fact that WebGLCubeRenderTarget.texture is a Texture and NOT a CubeTexture
  19094. // TODO: unify these code paths
  19095. if ( ( texture && texture.isCubeTexture ) ||
  19096. ( Array.isArray( texture.image ) && texture.image.length === 6 ) ) {
  19097. // CompressedTexture can have Array in image :/
  19098. // this function alone should take care of cube textures
  19099. setTextureCube( texture, slot );
  19100. } else {
  19101. // assumed: texture property of THREE.WebGLCubeRenderTarget
  19102. setTextureCubeDynamic( texture, slot );
  19103. }
  19104. }
  19105. //
  19106. this.allocateTextureUnit = allocateTextureUnit;
  19107. this.resetTextureUnits = resetTextureUnits;
  19108. this.setTexture2D = setTexture2D;
  19109. this.setTexture2DArray = setTexture2DArray;
  19110. this.setTexture3D = setTexture3D;
  19111. this.setTextureCube = setTextureCube;
  19112. this.setTextureCubeDynamic = setTextureCubeDynamic;
  19113. this.setupRenderTarget = setupRenderTarget;
  19114. this.updateRenderTargetMipmap = updateRenderTargetMipmap;
  19115. this.updateMultisampleRenderTarget = updateMultisampleRenderTarget;
  19116. this.safeSetTexture2D = safeSetTexture2D;
  19117. this.safeSetTextureCube = safeSetTextureCube;
  19118. }
  19119. /**
  19120. * @author thespite / http://www.twitter.com/thespite
  19121. */
  19122. function WebGLUtils( gl, extensions, capabilities ) {
  19123. var isWebGL2 = capabilities.isWebGL2;
  19124. function convert( p ) {
  19125. var extension;
  19126. if ( p === UnsignedByteType ) { return 5121; }
  19127. if ( p === UnsignedShort4444Type ) { return 32819; }
  19128. if ( p === UnsignedShort5551Type ) { return 32820; }
  19129. if ( p === UnsignedShort565Type ) { return 33635; }
  19130. if ( p === ByteType ) { return 5120; }
  19131. if ( p === ShortType ) { return 5122; }
  19132. if ( p === UnsignedShortType ) { return 5123; }
  19133. if ( p === IntType ) { return 5124; }
  19134. if ( p === UnsignedIntType ) { return 5125; }
  19135. if ( p === FloatType ) { return 5126; }
  19136. if ( p === HalfFloatType ) {
  19137. if ( isWebGL2 ) { return 5131; }
  19138. extension = extensions.get( 'OES_texture_half_float' );
  19139. if ( extension !== null ) {
  19140. return extension.HALF_FLOAT_OES;
  19141. } else {
  19142. return null;
  19143. }
  19144. }
  19145. if ( p === AlphaFormat ) { return 6406; }
  19146. if ( p === RGBFormat ) { return 6407; }
  19147. if ( p === RGBAFormat ) { return 6408; }
  19148. if ( p === LuminanceFormat ) { return 6409; }
  19149. if ( p === LuminanceAlphaFormat ) { return 6410; }
  19150. if ( p === DepthFormat ) { return 6402; }
  19151. if ( p === DepthStencilFormat ) { return 34041; }
  19152. if ( p === RedFormat ) { return 6403; }
  19153. // WebGL2 formats.
  19154. if ( p === RedIntegerFormat ) { return 36244; }
  19155. if ( p === RGFormat ) { return 33319; }
  19156. if ( p === RGIntegerFormat ) { return 33320; }
  19157. if ( p === RGBIntegerFormat ) { return 36248; }
  19158. if ( p === RGBAIntegerFormat ) { return 36249; }
  19159. if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format ||
  19160. p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) {
  19161. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  19162. if ( extension !== null ) {
  19163. if ( p === RGB_S3TC_DXT1_Format ) { return extension.COMPRESSED_RGB_S3TC_DXT1_EXT; }
  19164. if ( p === RGBA_S3TC_DXT1_Format ) { return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT; }
  19165. if ( p === RGBA_S3TC_DXT3_Format ) { return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT; }
  19166. if ( p === RGBA_S3TC_DXT5_Format ) { return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT; }
  19167. } else {
  19168. return null;
  19169. }
  19170. }
  19171. if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format ||
  19172. p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {
  19173. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  19174. if ( extension !== null ) {
  19175. if ( p === RGB_PVRTC_4BPPV1_Format ) { return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG; }
  19176. if ( p === RGB_PVRTC_2BPPV1_Format ) { return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG; }
  19177. if ( p === RGBA_PVRTC_4BPPV1_Format ) { return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG; }
  19178. if ( p === RGBA_PVRTC_2BPPV1_Format ) { return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG; }
  19179. } else {
  19180. return null;
  19181. }
  19182. }
  19183. if ( p === RGB_ETC1_Format ) {
  19184. extension = extensions.get( 'WEBGL_compressed_texture_etc1' );
  19185. if ( extension !== null ) {
  19186. return extension.COMPRESSED_RGB_ETC1_WEBGL;
  19187. } else {
  19188. return null;
  19189. }
  19190. }
  19191. if ( p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format ) {
  19192. extension = extensions.get( 'WEBGL_compressed_texture_etc' );
  19193. if ( extension !== null ) {
  19194. if ( p === RGB_ETC2_Format ) { return extension.COMPRESSED_RGB8_ETC2; }
  19195. if ( p === RGBA_ETC2_EAC_Format ) { return extension.COMPRESSED_RGBA8_ETC2_EAC; }
  19196. }
  19197. }
  19198. if ( p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format ||
  19199. p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format ||
  19200. p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format ||
  19201. p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format ||
  19202. p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format ||
  19203. p === SRGB8_ALPHA8_ASTC_4x4_Format || p === SRGB8_ALPHA8_ASTC_5x4_Format || p === SRGB8_ALPHA8_ASTC_5x5_Format ||
  19204. p === SRGB8_ALPHA8_ASTC_6x5_Format || p === SRGB8_ALPHA8_ASTC_6x6_Format || p === SRGB8_ALPHA8_ASTC_8x5_Format ||
  19205. p === SRGB8_ALPHA8_ASTC_8x6_Format || p === SRGB8_ALPHA8_ASTC_8x8_Format || p === SRGB8_ALPHA8_ASTC_10x5_Format ||
  19206. p === SRGB8_ALPHA8_ASTC_10x6_Format || p === SRGB8_ALPHA8_ASTC_10x8_Format || p === SRGB8_ALPHA8_ASTC_10x10_Format ||
  19207. p === SRGB8_ALPHA8_ASTC_12x10_Format || p === SRGB8_ALPHA8_ASTC_12x12_Format ) {
  19208. extension = extensions.get( 'WEBGL_compressed_texture_astc' );
  19209. if ( extension !== null ) {
  19210. // TODO Complete?
  19211. return p;
  19212. } else {
  19213. return null;
  19214. }
  19215. }
  19216. if ( p === RGBA_BPTC_Format ) {
  19217. extension = extensions.get( 'EXT_texture_compression_bptc' );
  19218. if ( extension !== null ) {
  19219. // TODO Complete?
  19220. return p;
  19221. } else {
  19222. return null;
  19223. }
  19224. }
  19225. if ( p === UnsignedInt248Type ) {
  19226. if ( isWebGL2 ) { return 34042; }
  19227. extension = extensions.get( 'WEBGL_depth_texture' );
  19228. if ( extension !== null ) {
  19229. return extension.UNSIGNED_INT_24_8_WEBGL;
  19230. } else {
  19231. return null;
  19232. }
  19233. }
  19234. }
  19235. return { convert: convert };
  19236. }
  19237. /**
  19238. * @author mrdoob / http://mrdoob.com/
  19239. */
  19240. function Group() {
  19241. Object3D.call( this );
  19242. this.type = 'Group';
  19243. }
  19244. Group.prototype = Object.assign( Object.create( Object3D.prototype ), {
  19245. constructor: Group,
  19246. isGroup: true
  19247. } );
  19248. /**
  19249. * @author mrdoob / http://mrdoob.com/
  19250. */
  19251. function ArrayCamera( array ) {
  19252. PerspectiveCamera.call( this );
  19253. this.cameras = array || [];
  19254. }
  19255. ArrayCamera.prototype = Object.assign( Object.create( PerspectiveCamera.prototype ), {
  19256. constructor: ArrayCamera,
  19257. isArrayCamera: true
  19258. } );
  19259. /**
  19260. * @author jsantell / https://www.jsantell.com/
  19261. * @author mrdoob / http://mrdoob.com/
  19262. */
  19263. var cameraLPos = new Vector3();
  19264. var cameraRPos = new Vector3();
  19265. /**
  19266. * Assumes 2 cameras that are parallel and share an X-axis, and that
  19267. * the cameras' projection and world matrices have already been set.
  19268. * And that near and far planes are identical for both cameras.
  19269. * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765
  19270. */
  19271. function setProjectionFromUnion( camera, cameraL, cameraR ) {
  19272. cameraLPos.setFromMatrixPosition( cameraL.matrixWorld );
  19273. cameraRPos.setFromMatrixPosition( cameraR.matrixWorld );
  19274. var ipd = cameraLPos.distanceTo( cameraRPos );
  19275. var projL = cameraL.projectionMatrix.elements;
  19276. var projR = cameraR.projectionMatrix.elements;
  19277. // VR systems will have identical far and near planes, and
  19278. // most likely identical top and bottom frustum extents.
  19279. // Use the left camera for these values.
  19280. var near = projL[ 14 ] / ( projL[ 10 ] - 1 );
  19281. var far = projL[ 14 ] / ( projL[ 10 ] + 1 );
  19282. var topFov = ( projL[ 9 ] + 1 ) / projL[ 5 ];
  19283. var bottomFov = ( projL[ 9 ] - 1 ) / projL[ 5 ];
  19284. var leftFov = ( projL[ 8 ] - 1 ) / projL[ 0 ];
  19285. var rightFov = ( projR[ 8 ] + 1 ) / projR[ 0 ];
  19286. var left = near * leftFov;
  19287. var right = near * rightFov;
  19288. // Calculate the new camera's position offset from the
  19289. // left camera. xOffset should be roughly half `ipd`.
  19290. var zOffset = ipd / ( - leftFov + rightFov );
  19291. var xOffset = zOffset * - leftFov;
  19292. // TODO: Better way to apply this offset?
  19293. cameraL.matrixWorld.decompose( camera.position, camera.quaternion, camera.scale );
  19294. camera.translateX( xOffset );
  19295. camera.translateZ( zOffset );
  19296. camera.matrixWorld.compose( camera.position, camera.quaternion, camera.scale );
  19297. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  19298. // Find the union of the frustum values of the cameras and scale
  19299. // the values so that the near plane's position does not change in world space,
  19300. // although must now be relative to the new union camera.
  19301. var near2 = near + zOffset;
  19302. var far2 = far + zOffset;
  19303. var left2 = left - xOffset;
  19304. var right2 = right + ( ipd - xOffset );
  19305. var top2 = topFov * far / far2 * near2;
  19306. var bottom2 = bottomFov * far / far2 * near2;
  19307. camera.projectionMatrix.makePerspective( left2, right2, top2, bottom2, near2, far2 );
  19308. }
  19309. /**
  19310. * @author mrdoob / http://mrdoob.com/
  19311. */
  19312. function WebVRManager( renderer ) {
  19313. var renderWidth, renderHeight;
  19314. var scope = this;
  19315. var device = null;
  19316. var frameData = null;
  19317. var poseTarget = null;
  19318. var controllers = [];
  19319. var standingMatrix = new Matrix4();
  19320. var standingMatrixInverse = new Matrix4();
  19321. var framebufferScaleFactor = 1.0;
  19322. var referenceSpaceType = 'local-floor';
  19323. if ( typeof window !== 'undefined' && 'VRFrameData' in window ) {
  19324. frameData = new window.VRFrameData();
  19325. window.addEventListener( 'vrdisplaypresentchange', onVRDisplayPresentChange, false );
  19326. }
  19327. var matrixWorldInverse = new Matrix4();
  19328. var tempQuaternion = new Quaternion();
  19329. var tempPosition = new Vector3();
  19330. var cameraL = new PerspectiveCamera();
  19331. cameraL.viewport = new Vector4();
  19332. cameraL.layers.enable( 1 );
  19333. var cameraR = new PerspectiveCamera();
  19334. cameraR.viewport = new Vector4();
  19335. cameraR.layers.enable( 2 );
  19336. var cameraVR = new ArrayCamera( [ cameraL, cameraR ] );
  19337. cameraVR.layers.enable( 1 );
  19338. cameraVR.layers.enable( 2 );
  19339. var currentSize = new Vector2(), currentPixelRatio;
  19340. function onVRDisplayPresentChange() {
  19341. var isPresenting = scope.isPresenting = device !== null && device.isPresenting === true;
  19342. if ( isPresenting ) {
  19343. var eyeParameters = device.getEyeParameters( 'left' );
  19344. renderWidth = 2 * eyeParameters.renderWidth * framebufferScaleFactor;
  19345. renderHeight = eyeParameters.renderHeight * framebufferScaleFactor;
  19346. currentPixelRatio = renderer.getPixelRatio();
  19347. renderer.getSize( currentSize );
  19348. renderer.setDrawingBufferSize( renderWidth, renderHeight, 1 );
  19349. cameraL.viewport.set( 0, 0, renderWidth / 2, renderHeight );
  19350. cameraR.viewport.set( renderWidth / 2, 0, renderWidth / 2, renderHeight );
  19351. animation.start();
  19352. scope.dispatchEvent( { type: 'sessionstart' } );
  19353. } else {
  19354. if ( scope.enabled ) {
  19355. renderer.setDrawingBufferSize( currentSize.width, currentSize.height, currentPixelRatio );
  19356. }
  19357. animation.stop();
  19358. scope.dispatchEvent( { type: 'sessionend' } );
  19359. }
  19360. }
  19361. //
  19362. var triggers = [];
  19363. var grips = [];
  19364. function findGamepad( id ) {
  19365. var gamepads = navigator.getGamepads && navigator.getGamepads();
  19366. for ( var i = 0, l = gamepads.length; i < l; i ++ ) {
  19367. var gamepad = gamepads[ i ];
  19368. if ( gamepad && ( gamepad.id === 'Daydream Controller' ||
  19369. gamepad.id === 'Gear VR Controller' || gamepad.id === 'Oculus Go Controller' ||
  19370. gamepad.id === 'OpenVR Gamepad' || gamepad.id.startsWith( 'Oculus Touch' ) ||
  19371. gamepad.id.startsWith( 'HTC Vive Focus' ) ||
  19372. gamepad.id.startsWith( 'Spatial Controller' ) ) ) {
  19373. var hand = gamepad.hand;
  19374. if ( id === 0 && ( hand === '' || hand === 'right' ) ) { return gamepad; }
  19375. if ( id === 1 && ( hand === 'left' ) ) { return gamepad; }
  19376. }
  19377. }
  19378. }
  19379. function updateControllers() {
  19380. for ( var i = 0; i < controllers.length; i ++ ) {
  19381. var controller = controllers[ i ];
  19382. var gamepad = findGamepad( i );
  19383. if ( gamepad !== undefined && gamepad.pose !== undefined ) {
  19384. if ( gamepad.pose === null ) { return; }
  19385. // Pose
  19386. var pose = gamepad.pose;
  19387. if ( pose.hasPosition === false ) { controller.position.set( 0.2, - 0.6, - 0.05 ); }
  19388. if ( pose.position !== null ) { controller.position.fromArray( pose.position ); }
  19389. if ( pose.orientation !== null ) { controller.quaternion.fromArray( pose.orientation ); }
  19390. controller.matrix.compose( controller.position, controller.quaternion, controller.scale );
  19391. controller.matrix.premultiply( standingMatrix );
  19392. controller.matrix.decompose( controller.position, controller.quaternion, controller.scale );
  19393. controller.matrixWorldNeedsUpdate = true;
  19394. controller.visible = true;
  19395. // Trigger
  19396. var buttonId = gamepad.id === 'Daydream Controller' ? 0 : 1;
  19397. if ( triggers[ i ] === undefined ) { triggers[ i ] = false; }
  19398. if ( triggers[ i ] !== gamepad.buttons[ buttonId ].pressed ) {
  19399. triggers[ i ] = gamepad.buttons[ buttonId ].pressed;
  19400. if ( triggers[ i ] === true ) {
  19401. controller.dispatchEvent( { type: 'selectstart' } );
  19402. } else {
  19403. controller.dispatchEvent( { type: 'selectend' } );
  19404. controller.dispatchEvent( { type: 'select' } );
  19405. }
  19406. }
  19407. // Grip
  19408. buttonId = 2;
  19409. if ( grips[ i ] === undefined ) { grips[ i ] = false; }
  19410. // Skip if the grip button doesn't exist on this controller
  19411. if ( gamepad.buttons[ buttonId ] !== undefined ) {
  19412. if ( grips[ i ] !== gamepad.buttons[ buttonId ].pressed ) {
  19413. grips[ i ] = gamepad.buttons[ buttonId ].pressed;
  19414. if ( grips[ i ] === true ) {
  19415. controller.dispatchEvent( { type: 'squeezestart' } );
  19416. } else {
  19417. controller.dispatchEvent( { type: 'squeezeend' } );
  19418. controller.dispatchEvent( { type: 'squeeze' } );
  19419. }
  19420. }
  19421. }
  19422. } else {
  19423. controller.visible = false;
  19424. }
  19425. }
  19426. }
  19427. function updateViewportFromBounds( viewport, bounds ) {
  19428. if ( bounds !== null && bounds.length === 4 ) {
  19429. viewport.set( bounds[ 0 ] * renderWidth, bounds[ 1 ] * renderHeight, bounds[ 2 ] * renderWidth, bounds[ 3 ] * renderHeight );
  19430. }
  19431. }
  19432. //
  19433. this.enabled = false;
  19434. this.getController = function ( id ) {
  19435. var controller = controllers[ id ];
  19436. if ( controller === undefined ) {
  19437. controller = new Group();
  19438. controller.matrixAutoUpdate = false;
  19439. controller.visible = false;
  19440. controllers[ id ] = controller;
  19441. }
  19442. return controller;
  19443. };
  19444. this.getDevice = function () {
  19445. return device;
  19446. };
  19447. this.setDevice = function ( value ) {
  19448. if ( value !== undefined ) { device = value; }
  19449. animation.setContext( value );
  19450. };
  19451. this.setFramebufferScaleFactor = function ( value ) {
  19452. framebufferScaleFactor = value;
  19453. };
  19454. this.setReferenceSpaceType = function ( value ) {
  19455. referenceSpaceType = value;
  19456. };
  19457. this.setPoseTarget = function ( object ) {
  19458. if ( object !== undefined ) { poseTarget = object; }
  19459. };
  19460. this.getCamera = function ( camera ) {
  19461. var userHeight = referenceSpaceType === 'local-floor' ? 1.6 : 0;
  19462. device.depthNear = camera.near;
  19463. device.depthFar = camera.far;
  19464. device.getFrameData( frameData );
  19465. //
  19466. if ( referenceSpaceType === 'local-floor' ) {
  19467. var stageParameters = device.stageParameters;
  19468. if ( stageParameters ) {
  19469. standingMatrix.fromArray( stageParameters.sittingToStandingTransform );
  19470. } else {
  19471. standingMatrix.makeTranslation( 0, userHeight, 0 );
  19472. }
  19473. }
  19474. var pose = frameData.pose;
  19475. var poseObject = poseTarget !== null ? poseTarget : camera;
  19476. // We want to manipulate poseObject by its position and quaternion components since users may rely on them.
  19477. poseObject.matrix.copy( standingMatrix );
  19478. poseObject.matrix.decompose( poseObject.position, poseObject.quaternion, poseObject.scale );
  19479. if ( pose.orientation !== null ) {
  19480. tempQuaternion.fromArray( pose.orientation );
  19481. poseObject.quaternion.multiply( tempQuaternion );
  19482. }
  19483. if ( pose.position !== null ) {
  19484. tempQuaternion.setFromRotationMatrix( standingMatrix );
  19485. tempPosition.fromArray( pose.position );
  19486. tempPosition.applyQuaternion( tempQuaternion );
  19487. poseObject.position.add( tempPosition );
  19488. }
  19489. poseObject.updateMatrixWorld();
  19490. var children = poseObject.children;
  19491. for ( var i = 0, l = children.length; i < l; i ++ ) {
  19492. children[ i ].updateMatrixWorld( true );
  19493. }
  19494. //
  19495. cameraL.near = camera.near;
  19496. cameraR.near = camera.near;
  19497. cameraL.far = camera.far;
  19498. cameraR.far = camera.far;
  19499. cameraL.matrixWorldInverse.fromArray( frameData.leftViewMatrix );
  19500. cameraR.matrixWorldInverse.fromArray( frameData.rightViewMatrix );
  19501. // TODO (mrdoob) Double check this code
  19502. standingMatrixInverse.getInverse( standingMatrix );
  19503. if ( referenceSpaceType === 'local-floor' ) {
  19504. cameraL.matrixWorldInverse.multiply( standingMatrixInverse );
  19505. cameraR.matrixWorldInverse.multiply( standingMatrixInverse );
  19506. }
  19507. var parent = poseObject.parent;
  19508. if ( parent !== null ) {
  19509. matrixWorldInverse.getInverse( parent.matrixWorld );
  19510. cameraL.matrixWorldInverse.multiply( matrixWorldInverse );
  19511. cameraR.matrixWorldInverse.multiply( matrixWorldInverse );
  19512. }
  19513. // envMap and Mirror needs camera.matrixWorld
  19514. cameraL.matrixWorld.getInverse( cameraL.matrixWorldInverse );
  19515. cameraR.matrixWorld.getInverse( cameraR.matrixWorldInverse );
  19516. cameraL.projectionMatrix.fromArray( frameData.leftProjectionMatrix );
  19517. cameraR.projectionMatrix.fromArray( frameData.rightProjectionMatrix );
  19518. setProjectionFromUnion( cameraVR, cameraL, cameraR );
  19519. //
  19520. var layers = device.getLayers();
  19521. if ( layers.length ) {
  19522. var layer = layers[ 0 ];
  19523. updateViewportFromBounds( cameraL.viewport, layer.leftBounds );
  19524. updateViewportFromBounds( cameraR.viewport, layer.rightBounds );
  19525. }
  19526. updateControllers();
  19527. return cameraVR;
  19528. };
  19529. this.getStandingMatrix = function () {
  19530. return standingMatrix;
  19531. };
  19532. this.isPresenting = false;
  19533. // Animation Loop
  19534. var animation = new WebGLAnimation();
  19535. this.setAnimationLoop = function ( callback ) {
  19536. animation.setAnimationLoop( callback );
  19537. if ( this.isPresenting ) { animation.start(); }
  19538. };
  19539. this.submitFrame = function () {
  19540. if ( this.isPresenting ) { device.submitFrame(); }
  19541. };
  19542. this.dispose = function () {
  19543. if ( typeof window !== 'undefined' ) {
  19544. window.removeEventListener( 'vrdisplaypresentchange', onVRDisplayPresentChange );
  19545. }
  19546. };
  19547. // DEPRECATED
  19548. this.setFrameOfReferenceType = function () {
  19549. console.warn( 'THREE.WebVRManager: setFrameOfReferenceType() has been deprecated.' );
  19550. };
  19551. }
  19552. Object.assign( WebVRManager.prototype, EventDispatcher.prototype );
  19553. /**
  19554. * @author mrdoob / http://mrdoob.com/
  19555. */
  19556. function WebXRManager( renderer, gl ) {
  19557. var scope = this;
  19558. var session = null;
  19559. var framebufferScaleFactor = 1.0;
  19560. var referenceSpace = null;
  19561. var referenceSpaceType = 'local-floor';
  19562. var pose = null;
  19563. var poseTarget = null;
  19564. var controllers = [];
  19565. var inputSourcesMap = new Map();
  19566. //
  19567. var cameraL = new PerspectiveCamera();
  19568. cameraL.layers.enable( 1 );
  19569. cameraL.viewport = new Vector4();
  19570. var cameraR = new PerspectiveCamera();
  19571. cameraR.layers.enable( 2 );
  19572. cameraR.viewport = new Vector4();
  19573. var cameraVR = new ArrayCamera( [ cameraL, cameraR ] );
  19574. cameraVR.layers.enable( 1 );
  19575. cameraVR.layers.enable( 2 );
  19576. var _currentDepthNear = null;
  19577. var _currentDepthFar = null;
  19578. //
  19579. this.enabled = false;
  19580. this.isPresenting = false;
  19581. this.getCameraPose = function ( ) {
  19582. return pose;
  19583. };
  19584. this.getController = function ( id ) {
  19585. var controller = controllers[ id ];
  19586. if ( controller === undefined ) {
  19587. controller = {};
  19588. controllers[ id ] = controller;
  19589. }
  19590. if ( controller.targetRay === undefined ) {
  19591. controller.targetRay = new Group();
  19592. controller.targetRay.matrixAutoUpdate = false;
  19593. controller.targetRay.visible = false;
  19594. }
  19595. return controller.targetRay;
  19596. };
  19597. this.getControllerGrip = function ( id ) {
  19598. var controller = controllers[ id ];
  19599. if ( controller === undefined ) {
  19600. controller = {};
  19601. controllers[ id ] = controller;
  19602. }
  19603. if ( controller.grip === undefined ) {
  19604. controller.grip = new Group();
  19605. controller.grip.matrixAutoUpdate = false;
  19606. controller.grip.visible = false;
  19607. }
  19608. return controller.grip;
  19609. };
  19610. //
  19611. function onSessionEvent( event ) {
  19612. var controller = inputSourcesMap.get( event.inputSource );
  19613. if ( controller ) {
  19614. if ( controller.targetRay ) {
  19615. controller.targetRay.dispatchEvent( { type: event.type } );
  19616. }
  19617. if ( controller.grip ) {
  19618. controller.grip.dispatchEvent( { type: event.type } );
  19619. }
  19620. }
  19621. }
  19622. function onSessionEnd() {
  19623. inputSourcesMap.forEach( function ( controller, inputSource ) {
  19624. if ( controller.targetRay ) {
  19625. controller.targetRay.dispatchEvent( { type: 'disconnected', data: inputSource } );
  19626. controller.targetRay.visible = false;
  19627. }
  19628. if ( controller.grip ) {
  19629. controller.grip.dispatchEvent( { type: 'disconnected', data: inputSource } );
  19630. controller.grip.visible = false;
  19631. }
  19632. } );
  19633. inputSourcesMap.clear();
  19634. //
  19635. renderer.setFramebuffer( null );
  19636. renderer.setRenderTarget( renderer.getRenderTarget() ); // Hack #15830
  19637. animation.stop();
  19638. scope.isPresenting = false;
  19639. scope.dispatchEvent( { type: 'sessionend' } );
  19640. }
  19641. function onRequestReferenceSpace( value ) {
  19642. referenceSpace = value;
  19643. animation.setContext( session );
  19644. animation.start();
  19645. scope.isPresenting = true;
  19646. scope.dispatchEvent( { type: 'sessionstart' } );
  19647. }
  19648. this.setFramebufferScaleFactor = function ( value ) {
  19649. framebufferScaleFactor = value;
  19650. // Warn if function is used while presenting
  19651. if ( scope.isPresenting == true ) {
  19652. console.warn( "WebXRManager: Cannot change framebuffer scale while presenting VR content" );
  19653. }
  19654. };
  19655. this.setReferenceSpaceType = function ( value ) {
  19656. referenceSpaceType = value;
  19657. };
  19658. this.getReferenceSpace = function () {
  19659. return referenceSpace;
  19660. };
  19661. this.getSession = function () {
  19662. return session;
  19663. };
  19664. this.setSession = function ( value ) {
  19665. session = value;
  19666. if ( session !== null ) {
  19667. session.addEventListener( 'select', onSessionEvent );
  19668. session.addEventListener( 'selectstart', onSessionEvent );
  19669. session.addEventListener( 'selectend', onSessionEvent );
  19670. session.addEventListener( 'squeeze', onSessionEvent );
  19671. session.addEventListener( 'squeezestart', onSessionEvent );
  19672. session.addEventListener( 'squeezeend', onSessionEvent );
  19673. session.addEventListener( 'end', onSessionEnd );
  19674. var attributes = gl.getContextAttributes();
  19675. var layerInit = {
  19676. antialias: attributes.antialias,
  19677. alpha: attributes.alpha,
  19678. depth: attributes.depth,
  19679. stencil: attributes.stencil,
  19680. framebufferScaleFactor: framebufferScaleFactor
  19681. };
  19682. // eslint-disable-next-line no-undef
  19683. var baseLayer = new XRWebGLLayer( session, gl, layerInit );
  19684. session.updateRenderState( { baseLayer: baseLayer } );
  19685. session.requestReferenceSpace( referenceSpaceType ).then( onRequestReferenceSpace );
  19686. //
  19687. session.addEventListener( 'inputsourceschange', updateInputSources );
  19688. }
  19689. };
  19690. function updateInputSources( event ) {
  19691. var inputSources = session.inputSources;
  19692. // Assign inputSources to available controllers
  19693. for ( var i = 0; i < controllers.length; i ++ ) {
  19694. inputSourcesMap.set( inputSources[ i ], controllers[ i ] );
  19695. }
  19696. // Notify disconnected
  19697. for ( var i = 0; i < event.removed.length; i ++ ) {
  19698. var inputSource = event.removed[ i ];
  19699. var controller = inputSourcesMap.get( inputSource );
  19700. if ( controller ) {
  19701. if ( controller.targetRay ) {
  19702. controller.targetRay.dispatchEvent( { type: 'disconnected', data: inputSource } );
  19703. }
  19704. if ( controller.grip ) {
  19705. controller.grip.dispatchEvent( { type: 'disconnected', data: inputSource } );
  19706. }
  19707. inputSourcesMap.delete( inputSource );
  19708. }
  19709. }
  19710. // Notify connected
  19711. for ( var i = 0; i < event.added.length; i ++ ) {
  19712. var inputSource = event.added[ i ];
  19713. var controller = inputSourcesMap.get( inputSource );
  19714. if ( controller ) {
  19715. if ( controller.targetRay ) {
  19716. controller.targetRay.dispatchEvent( { type: 'connected', data: inputSource } );
  19717. }
  19718. if ( controller.grip ) {
  19719. controller.grip.dispatchEvent( { type: 'connected', data: inputSource } );
  19720. }
  19721. }
  19722. }
  19723. }
  19724. //
  19725. var cameraLPos = new Vector3();
  19726. var cameraRPos = new Vector3();
  19727. /**
  19728. * @author jsantell / https://www.jsantell.com/
  19729. *
  19730. * Assumes 2 cameras that are parallel and share an X-axis, and that
  19731. * the cameras' projection and world matrices have already been set.
  19732. * And that near and far planes are identical for both cameras.
  19733. * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765
  19734. */
  19735. function setProjectionFromUnion( camera, cameraL, cameraR ) {
  19736. cameraLPos.setFromMatrixPosition( cameraL.matrixWorld );
  19737. cameraRPos.setFromMatrixPosition( cameraR.matrixWorld );
  19738. var ipd = cameraLPos.distanceTo( cameraRPos );
  19739. var projL = cameraL.projectionMatrix.elements;
  19740. var projR = cameraR.projectionMatrix.elements;
  19741. // VR systems will have identical far and near planes, and
  19742. // most likely identical top and bottom frustum extents.
  19743. // Use the left camera for these values.
  19744. var near = projL[ 14 ] / ( projL[ 10 ] - 1 );
  19745. var far = projL[ 14 ] / ( projL[ 10 ] + 1 );
  19746. var topFov = ( projL[ 9 ] + 1 ) / projL[ 5 ];
  19747. var bottomFov = ( projL[ 9 ] - 1 ) / projL[ 5 ];
  19748. var leftFov = ( projL[ 8 ] - 1 ) / projL[ 0 ];
  19749. var rightFov = ( projR[ 8 ] + 1 ) / projR[ 0 ];
  19750. var left = near * leftFov;
  19751. var right = near * rightFov;
  19752. // Calculate the new camera's position offset from the
  19753. // left camera. xOffset should be roughly half `ipd`.
  19754. var zOffset = ipd / ( - leftFov + rightFov );
  19755. var xOffset = zOffset * - leftFov;
  19756. // TODO: Better way to apply this offset?
  19757. cameraL.matrixWorld.decompose( camera.position, camera.quaternion, camera.scale );
  19758. camera.translateX( xOffset );
  19759. camera.translateZ( zOffset );
  19760. camera.matrixWorld.compose( camera.position, camera.quaternion, camera.scale );
  19761. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  19762. // Find the union of the frustum values of the cameras and scale
  19763. // the values so that the near plane's position does not change in world space,
  19764. // although must now be relative to the new union camera.
  19765. var near2 = near + zOffset;
  19766. var far2 = far + zOffset;
  19767. var left2 = left - xOffset;
  19768. var right2 = right + ( ipd - xOffset );
  19769. var top2 = topFov * far / far2 * near2;
  19770. var bottom2 = bottomFov * far / far2 * near2;
  19771. camera.projectionMatrix.makePerspective( left2, right2, top2, bottom2, near2, far2 );
  19772. }
  19773. function updateCamera( camera, parent ) {
  19774. if ( parent === null ) {
  19775. camera.matrixWorld.copy( camera.matrix );
  19776. } else {
  19777. camera.matrixWorld.multiplyMatrices( parent.matrixWorld, camera.matrix );
  19778. }
  19779. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  19780. }
  19781. this.setPoseTarget = function ( object ) {
  19782. if ( object !== undefined ) { poseTarget = object; }
  19783. };
  19784. this.getCamera = function ( camera ) {
  19785. cameraVR.near = cameraR.near = cameraL.near = camera.near;
  19786. cameraVR.far = cameraR.far = cameraL.far = camera.far;
  19787. if ( _currentDepthNear !== cameraVR.near || _currentDepthFar !== cameraVR.far ) {
  19788. // Note that the new renderState won't apply until the next frame. See #18320
  19789. session.updateRenderState( {
  19790. depthNear: cameraVR.near,
  19791. depthFar: cameraVR.far
  19792. } );
  19793. _currentDepthNear = cameraVR.near;
  19794. _currentDepthFar = cameraVR.far;
  19795. }
  19796. var parent = camera.parent;
  19797. var cameras = cameraVR.cameras;
  19798. var object = poseTarget || camera;
  19799. updateCamera( cameraVR, parent );
  19800. for ( var i = 0; i < cameras.length; i ++ ) {
  19801. updateCamera( cameras[ i ], parent );
  19802. }
  19803. // update camera and its children
  19804. object.matrixWorld.copy( cameraVR.matrixWorld );
  19805. var children = object.children;
  19806. for ( var i = 0, l = children.length; i < l; i ++ ) {
  19807. children[ i ].updateMatrixWorld( true );
  19808. }
  19809. setProjectionFromUnion( cameraVR, cameraL, cameraR );
  19810. return cameraVR;
  19811. };
  19812. // Animation Loop
  19813. var onAnimationFrameCallback = null;
  19814. function onAnimationFrame( time, frame ) {
  19815. pose = frame.getViewerPose( referenceSpace );
  19816. if ( pose !== null ) {
  19817. var views = pose.views;
  19818. var baseLayer = session.renderState.baseLayer;
  19819. renderer.setFramebuffer( baseLayer.framebuffer );
  19820. for ( var i = 0; i < views.length; i ++ ) {
  19821. var view = views[ i ];
  19822. var viewport = baseLayer.getViewport( view );
  19823. var camera = cameraVR.cameras[ i ];
  19824. camera.matrix.fromArray( view.transform.matrix );
  19825. camera.projectionMatrix.fromArray( view.projectionMatrix );
  19826. camera.viewport.set( viewport.x, viewport.y, viewport.width, viewport.height );
  19827. if ( i === 0 ) {
  19828. cameraVR.matrix.copy( camera.matrix );
  19829. }
  19830. }
  19831. }
  19832. //
  19833. var inputSources = session.inputSources;
  19834. for ( var i = 0; i < controllers.length; i ++ ) {
  19835. var controller = controllers[ i ];
  19836. var inputSource = inputSources[ i ];
  19837. var inputPose = null;
  19838. var gripPose = null;
  19839. if ( inputSource ) {
  19840. if ( controller.targetRay ) {
  19841. inputPose = frame.getPose( inputSource.targetRaySpace, referenceSpace );
  19842. if ( inputPose !== null ) {
  19843. controller.targetRay.matrix.fromArray( inputPose.transform.matrix );
  19844. controller.targetRay.matrix.decompose( controller.targetRay.position, controller.targetRay.rotation, controller.targetRay.scale );
  19845. }
  19846. }
  19847. if ( controller.grip && inputSource.gripSpace ) {
  19848. gripPose = frame.getPose( inputSource.gripSpace, referenceSpace );
  19849. if ( gripPose !== null ) {
  19850. controller.grip.matrix.fromArray( gripPose.transform.matrix );
  19851. controller.grip.matrix.decompose( controller.grip.position, controller.grip.rotation, controller.grip.scale );
  19852. }
  19853. }
  19854. }
  19855. if ( controller.targetRay ) {
  19856. controller.targetRay.visible = inputPose !== null;
  19857. }
  19858. if ( controller.grip ) {
  19859. controller.grip.visible = gripPose !== null;
  19860. }
  19861. }
  19862. if ( onAnimationFrameCallback ) { onAnimationFrameCallback( time, frame ); }
  19863. }
  19864. var animation = new WebGLAnimation();
  19865. animation.setAnimationLoop( onAnimationFrame );
  19866. this.setAnimationLoop = function ( callback ) {
  19867. onAnimationFrameCallback = callback;
  19868. };
  19869. this.dispose = function () {};
  19870. }
  19871. Object.assign( WebXRManager.prototype, EventDispatcher.prototype );
  19872. /**
  19873. * @author supereggbert / http://www.paulbrunt.co.uk/
  19874. * @author mrdoob / http://mrdoob.com/
  19875. * @author alteredq / http://alteredqualia.com/
  19876. * @author szimek / https://github.com/szimek/
  19877. * @author tschw
  19878. */
  19879. function WebGLRenderer( parameters ) {
  19880. parameters = parameters || {};
  19881. var _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' ),
  19882. _context = parameters.context !== undefined ? parameters.context : null,
  19883. _alpha = parameters.alpha !== undefined ? parameters.alpha : false,
  19884. _depth = parameters.depth !== undefined ? parameters.depth : true,
  19885. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  19886. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  19887. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  19888. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
  19889. _powerPreference = parameters.powerPreference !== undefined ? parameters.powerPreference : 'default',
  19890. _failIfMajorPerformanceCaveat = parameters.failIfMajorPerformanceCaveat !== undefined ? parameters.failIfMajorPerformanceCaveat : false;
  19891. var currentRenderList = null;
  19892. var currentRenderState = null;
  19893. // public properties
  19894. this.domElement = _canvas;
  19895. // Debug configuration container
  19896. this.debug = {
  19897. /**
  19898. * Enables error checking and reporting when shader programs are being compiled
  19899. * @type {boolean}
  19900. */
  19901. checkShaderErrors: true
  19902. };
  19903. // clearing
  19904. this.autoClear = true;
  19905. this.autoClearColor = true;
  19906. this.autoClearDepth = true;
  19907. this.autoClearStencil = true;
  19908. // scene graph
  19909. this.sortObjects = true;
  19910. // user-defined clipping
  19911. this.clippingPlanes = [];
  19912. this.localClippingEnabled = false;
  19913. // physically based shading
  19914. this.gammaFactor = 2.0; // for backwards compatibility
  19915. this.outputEncoding = LinearEncoding;
  19916. // physical lights
  19917. this.physicallyCorrectLights = false;
  19918. // tone mapping
  19919. this.toneMapping = LinearToneMapping;
  19920. this.toneMappingExposure = 1.0;
  19921. this.toneMappingWhitePoint = 1.0;
  19922. // morphs
  19923. this.maxMorphTargets = 8;
  19924. this.maxMorphNormals = 4;
  19925. // internal properties
  19926. var _this = this,
  19927. _isContextLost = false,
  19928. // internal state cache
  19929. _framebuffer = null,
  19930. _currentActiveCubeFace = 0,
  19931. _currentActiveMipmapLevel = 0,
  19932. _currentRenderTarget = null,
  19933. _currentFramebuffer = null,
  19934. _currentMaterialId = - 1,
  19935. // geometry and program caching
  19936. _currentGeometryProgram = {
  19937. geometry: null,
  19938. program: null,
  19939. wireframe: false
  19940. },
  19941. _currentCamera = null,
  19942. _currentArrayCamera = null,
  19943. _currentViewport = new Vector4(),
  19944. _currentScissor = new Vector4(),
  19945. _currentScissorTest = null,
  19946. //
  19947. _width = _canvas.width,
  19948. _height = _canvas.height,
  19949. _pixelRatio = 1,
  19950. _opaqueSort = null,
  19951. _transparentSort = null,
  19952. _viewport = new Vector4( 0, 0, _width, _height ),
  19953. _scissor = new Vector4( 0, 0, _width, _height ),
  19954. _scissorTest = false,
  19955. // frustum
  19956. _frustum = new Frustum(),
  19957. // clipping
  19958. _clipping = new WebGLClipping(),
  19959. _clippingEnabled = false,
  19960. _localClippingEnabled = false,
  19961. // camera matrices cache
  19962. _projScreenMatrix = new Matrix4(),
  19963. _vector3 = new Vector3();
  19964. function getTargetPixelRatio() {
  19965. return _currentRenderTarget === null ? _pixelRatio : 1;
  19966. }
  19967. // initialize
  19968. var _gl;
  19969. try {
  19970. var contextAttributes = {
  19971. alpha: _alpha,
  19972. depth: _depth,
  19973. stencil: _stencil,
  19974. antialias: _antialias,
  19975. premultipliedAlpha: _premultipliedAlpha,
  19976. preserveDrawingBuffer: _preserveDrawingBuffer,
  19977. powerPreference: _powerPreference,
  19978. failIfMajorPerformanceCaveat: _failIfMajorPerformanceCaveat,
  19979. xrCompatible: true
  19980. };
  19981. // event listeners must be registered before WebGL context is created, see #12753
  19982. _canvas.addEventListener( 'webglcontextlost', onContextLost, false );
  19983. _canvas.addEventListener( 'webglcontextrestored', onContextRestore, false );
  19984. _gl = _context || _canvas.getContext( 'webgl', contextAttributes ) || _canvas.getContext( 'experimental-webgl', contextAttributes );
  19985. if ( _gl === null ) {
  19986. if ( _canvas.getContext( 'webgl' ) !== null ) {
  19987. throw new Error( 'Error creating WebGL context with your selected attributes.' );
  19988. } else {
  19989. throw new Error( 'Error creating WebGL context.' );
  19990. }
  19991. }
  19992. // Some experimental-webgl implementations do not have getShaderPrecisionFormat
  19993. if ( _gl.getShaderPrecisionFormat === undefined ) {
  19994. _gl.getShaderPrecisionFormat = function () {
  19995. return { 'rangeMin': 1, 'rangeMax': 1, 'precision': 1 };
  19996. };
  19997. }
  19998. } catch ( error ) {
  19999. console.error( 'THREE.WebGLRenderer: ' + error.message );
  20000. throw error;
  20001. }
  20002. var extensions, capabilities, state, info;
  20003. var properties, textures, attributes, geometries, objects;
  20004. var programCache, renderLists, renderStates;
  20005. var background, morphtargets, bufferRenderer, indexedBufferRenderer;
  20006. var utils;
  20007. function initGLContext() {
  20008. extensions = new WebGLExtensions( _gl );
  20009. capabilities = new WebGLCapabilities( _gl, extensions, parameters );
  20010. if ( capabilities.isWebGL2 === false ) {
  20011. extensions.get( 'WEBGL_depth_texture' );
  20012. extensions.get( 'OES_texture_float' );
  20013. extensions.get( 'OES_texture_half_float' );
  20014. extensions.get( 'OES_texture_half_float_linear' );
  20015. extensions.get( 'OES_standard_derivatives' );
  20016. extensions.get( 'OES_element_index_uint' );
  20017. extensions.get( 'ANGLE_instanced_arrays' );
  20018. }
  20019. extensions.get( 'OES_texture_float_linear' );
  20020. utils = new WebGLUtils( _gl, extensions, capabilities );
  20021. state = new WebGLState( _gl, extensions, capabilities );
  20022. state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).floor() );
  20023. state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).floor() );
  20024. info = new WebGLInfo( _gl );
  20025. properties = new WebGLProperties();
  20026. textures = new WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info );
  20027. attributes = new WebGLAttributes( _gl, capabilities );
  20028. geometries = new WebGLGeometries( _gl, attributes, info );
  20029. objects = new WebGLObjects( _gl, geometries, attributes, info );
  20030. morphtargets = new WebGLMorphtargets( _gl );
  20031. programCache = new WebGLPrograms( _this, extensions, capabilities );
  20032. renderLists = new WebGLRenderLists();
  20033. renderStates = new WebGLRenderStates();
  20034. background = new WebGLBackground( _this, state, objects, _premultipliedAlpha );
  20035. bufferRenderer = new WebGLBufferRenderer( _gl, extensions, info, capabilities );
  20036. indexedBufferRenderer = new WebGLIndexedBufferRenderer( _gl, extensions, info, capabilities );
  20037. info.programs = programCache.programs;
  20038. _this.capabilities = capabilities;
  20039. _this.extensions = extensions;
  20040. _this.properties = properties;
  20041. _this.renderLists = renderLists;
  20042. _this.state = state;
  20043. _this.info = info;
  20044. }
  20045. initGLContext();
  20046. // xr
  20047. var xr = ( typeof navigator !== 'undefined' && 'xr' in navigator ) ? new WebXRManager( _this, _gl ) : new WebVRManager( _this );
  20048. this.xr = xr;
  20049. // shadow map
  20050. var shadowMap = new WebGLShadowMap( _this, objects, capabilities.maxTextureSize );
  20051. this.shadowMap = shadowMap;
  20052. // API
  20053. this.getContext = function () {
  20054. return _gl;
  20055. };
  20056. this.getContextAttributes = function () {
  20057. return _gl.getContextAttributes();
  20058. };
  20059. this.forceContextLoss = function () {
  20060. var extension = extensions.get( 'WEBGL_lose_context' );
  20061. if ( extension ) { extension.loseContext(); }
  20062. };
  20063. this.forceContextRestore = function () {
  20064. var extension = extensions.get( 'WEBGL_lose_context' );
  20065. if ( extension ) { extension.restoreContext(); }
  20066. };
  20067. this.getPixelRatio = function () {
  20068. return _pixelRatio;
  20069. };
  20070. this.setPixelRatio = function ( value ) {
  20071. if ( value === undefined ) { return; }
  20072. _pixelRatio = value;
  20073. this.setSize( _width, _height, false );
  20074. };
  20075. this.getSize = function ( target ) {
  20076. if ( target === undefined ) {
  20077. console.warn( 'WebGLRenderer: .getsize() now requires a Vector2 as an argument' );
  20078. target = new Vector2();
  20079. }
  20080. return target.set( _width, _height );
  20081. };
  20082. this.setSize = function ( width, height, updateStyle ) {
  20083. if ( xr.isPresenting ) {
  20084. console.warn( 'THREE.WebGLRenderer: Can\'t change size while VR device is presenting.' );
  20085. return;
  20086. }
  20087. _width = width;
  20088. _height = height;
  20089. _canvas.width = Math.floor( width * _pixelRatio );
  20090. _canvas.height = Math.floor( height * _pixelRatio );
  20091. if ( updateStyle !== false ) {
  20092. _canvas.style.width = width + 'px';
  20093. _canvas.style.height = height + 'px';
  20094. }
  20095. this.setViewport( 0, 0, width, height );
  20096. };
  20097. this.getDrawingBufferSize = function ( target ) {
  20098. if ( target === undefined ) {
  20099. console.warn( 'WebGLRenderer: .getdrawingBufferSize() now requires a Vector2 as an argument' );
  20100. target = new Vector2();
  20101. }
  20102. return target.set( _width * _pixelRatio, _height * _pixelRatio ).floor();
  20103. };
  20104. this.setDrawingBufferSize = function ( width, height, pixelRatio ) {
  20105. _width = width;
  20106. _height = height;
  20107. _pixelRatio = pixelRatio;
  20108. _canvas.width = Math.floor( width * pixelRatio );
  20109. _canvas.height = Math.floor( height * pixelRatio );
  20110. this.setViewport( 0, 0, width, height );
  20111. };
  20112. this.getCurrentViewport = function ( target ) {
  20113. if ( target === undefined ) {
  20114. console.warn( 'WebGLRenderer: .getCurrentViewport() now requires a Vector4 as an argument' );
  20115. target = new Vector4();
  20116. }
  20117. return target.copy( _currentViewport );
  20118. };
  20119. this.getViewport = function ( target ) {
  20120. return target.copy( _viewport );
  20121. };
  20122. this.setViewport = function ( x, y, width, height ) {
  20123. if ( x.isVector4 ) {
  20124. _viewport.set( x.x, x.y, x.z, x.w );
  20125. } else {
  20126. _viewport.set( x, y, width, height );
  20127. }
  20128. state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).floor() );
  20129. };
  20130. this.getScissor = function ( target ) {
  20131. return target.copy( _scissor );
  20132. };
  20133. this.setScissor = function ( x, y, width, height ) {
  20134. if ( x.isVector4 ) {
  20135. _scissor.set( x.x, x.y, x.z, x.w );
  20136. } else {
  20137. _scissor.set( x, y, width, height );
  20138. }
  20139. state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).floor() );
  20140. };
  20141. this.getScissorTest = function () {
  20142. return _scissorTest;
  20143. };
  20144. this.setScissorTest = function ( boolean ) {
  20145. state.setScissorTest( _scissorTest = boolean );
  20146. };
  20147. this.setOpaqueSort = function ( method ) {
  20148. _opaqueSort = method;
  20149. };
  20150. this.setTransparentSort = function ( method ) {
  20151. _transparentSort = method;
  20152. };
  20153. // Clearing
  20154. this.getClearColor = function () {
  20155. return background.getClearColor();
  20156. };
  20157. this.setClearColor = function () {
  20158. background.setClearColor.apply( background, arguments );
  20159. };
  20160. this.getClearAlpha = function () {
  20161. return background.getClearAlpha();
  20162. };
  20163. this.setClearAlpha = function () {
  20164. background.setClearAlpha.apply( background, arguments );
  20165. };
  20166. this.clear = function ( color, depth, stencil ) {
  20167. var bits = 0;
  20168. if ( color === undefined || color ) { bits |= 16384; }
  20169. if ( depth === undefined || depth ) { bits |= 256; }
  20170. if ( stencil === undefined || stencil ) { bits |= 1024; }
  20171. _gl.clear( bits );
  20172. };
  20173. this.clearColor = function () {
  20174. this.clear( true, false, false );
  20175. };
  20176. this.clearDepth = function () {
  20177. this.clear( false, true, false );
  20178. };
  20179. this.clearStencil = function () {
  20180. this.clear( false, false, true );
  20181. };
  20182. //
  20183. this.dispose = function () {
  20184. _canvas.removeEventListener( 'webglcontextlost', onContextLost, false );
  20185. _canvas.removeEventListener( 'webglcontextrestored', onContextRestore, false );
  20186. renderLists.dispose();
  20187. renderStates.dispose();
  20188. properties.dispose();
  20189. objects.dispose();
  20190. xr.dispose();
  20191. animation.stop();
  20192. this.forceContextLoss();
  20193. };
  20194. // Events
  20195. function onContextLost( event ) {
  20196. event.preventDefault();
  20197. console.log( 'THREE.WebGLRenderer: Context Lost.' );
  20198. _isContextLost = true;
  20199. }
  20200. function onContextRestore( /* event */ ) {
  20201. console.log( 'THREE.WebGLRenderer: Context Restored.' );
  20202. _isContextLost = false;
  20203. initGLContext();
  20204. }
  20205. function onMaterialDispose( event ) {
  20206. var material = event.target;
  20207. material.removeEventListener( 'dispose', onMaterialDispose );
  20208. deallocateMaterial( material );
  20209. }
  20210. // Buffer deallocation
  20211. function deallocateMaterial( material ) {
  20212. releaseMaterialProgramReference( material );
  20213. properties.remove( material );
  20214. }
  20215. function releaseMaterialProgramReference( material ) {
  20216. var programInfo = properties.get( material ).program;
  20217. material.program = undefined;
  20218. if ( programInfo !== undefined ) {
  20219. programCache.releaseProgram( programInfo );
  20220. }
  20221. }
  20222. // Buffer rendering
  20223. function renderObjectImmediate( object, program ) {
  20224. object.render( function ( object ) {
  20225. _this.renderBufferImmediate( object, program );
  20226. } );
  20227. }
  20228. this.renderBufferImmediate = function ( object, program ) {
  20229. state.initAttributes();
  20230. var buffers = properties.get( object );
  20231. if ( object.hasPositions && ! buffers.position ) { buffers.position = _gl.createBuffer(); }
  20232. if ( object.hasNormals && ! buffers.normal ) { buffers.normal = _gl.createBuffer(); }
  20233. if ( object.hasUvs && ! buffers.uv ) { buffers.uv = _gl.createBuffer(); }
  20234. if ( object.hasColors && ! buffers.color ) { buffers.color = _gl.createBuffer(); }
  20235. var programAttributes = program.getAttributes();
  20236. if ( object.hasPositions ) {
  20237. _gl.bindBuffer( 34962, buffers.position );
  20238. _gl.bufferData( 34962, object.positionArray, 35048 );
  20239. state.enableAttribute( programAttributes.position );
  20240. _gl.vertexAttribPointer( programAttributes.position, 3, 5126, false, 0, 0 );
  20241. }
  20242. if ( object.hasNormals ) {
  20243. _gl.bindBuffer( 34962, buffers.normal );
  20244. _gl.bufferData( 34962, object.normalArray, 35048 );
  20245. state.enableAttribute( programAttributes.normal );
  20246. _gl.vertexAttribPointer( programAttributes.normal, 3, 5126, false, 0, 0 );
  20247. }
  20248. if ( object.hasUvs ) {
  20249. _gl.bindBuffer( 34962, buffers.uv );
  20250. _gl.bufferData( 34962, object.uvArray, 35048 );
  20251. state.enableAttribute( programAttributes.uv );
  20252. _gl.vertexAttribPointer( programAttributes.uv, 2, 5126, false, 0, 0 );
  20253. }
  20254. if ( object.hasColors ) {
  20255. _gl.bindBuffer( 34962, buffers.color );
  20256. _gl.bufferData( 34962, object.colorArray, 35048 );
  20257. state.enableAttribute( programAttributes.color );
  20258. _gl.vertexAttribPointer( programAttributes.color, 3, 5126, false, 0, 0 );
  20259. }
  20260. state.disableUnusedAttributes();
  20261. _gl.drawArrays( 4, 0, object.count );
  20262. object.count = 0;
  20263. };
  20264. var tempScene = new Scene();
  20265. this.renderBufferDirect = function ( camera, scene, geometry, material, object, group ) {
  20266. if ( scene === null ) { scene = tempScene; } // renderBufferDirect second parameter used to be fog (could be null)
  20267. var frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  20268. var program = setProgram( camera, scene, material, object );
  20269. state.setMaterial( material, frontFaceCW );
  20270. var updateBuffers = false;
  20271. if ( _currentGeometryProgram.geometry !== geometry.id ||
  20272. _currentGeometryProgram.program !== program.id ||
  20273. _currentGeometryProgram.wireframe !== ( material.wireframe === true ) ) {
  20274. _currentGeometryProgram.geometry = geometry.id;
  20275. _currentGeometryProgram.program = program.id;
  20276. _currentGeometryProgram.wireframe = material.wireframe === true;
  20277. updateBuffers = true;
  20278. }
  20279. if ( material.morphTargets || material.morphNormals ) {
  20280. morphtargets.update( object, geometry, material, program );
  20281. updateBuffers = true;
  20282. }
  20283. //
  20284. var index = geometry.index;
  20285. var position = geometry.attributes.position;
  20286. //
  20287. if ( index === null ) {
  20288. if ( position === undefined || position.count === 0 ) { return; }
  20289. } else if ( index.count === 0 ) {
  20290. return;
  20291. }
  20292. //
  20293. var rangeFactor = 1;
  20294. if ( material.wireframe === true ) {
  20295. index = geometries.getWireframeAttribute( geometry );
  20296. rangeFactor = 2;
  20297. }
  20298. var attribute;
  20299. var renderer = bufferRenderer;
  20300. if ( index !== null ) {
  20301. attribute = attributes.get( index );
  20302. renderer = indexedBufferRenderer;
  20303. renderer.setIndex( attribute );
  20304. }
  20305. if ( updateBuffers ) {
  20306. setupVertexAttributes( object, geometry, material, program );
  20307. if ( index !== null ) {
  20308. _gl.bindBuffer( 34963, attribute.buffer );
  20309. }
  20310. }
  20311. //
  20312. var dataCount = ( index !== null ) ? index.count : position.count;
  20313. var rangeStart = geometry.drawRange.start * rangeFactor;
  20314. var rangeCount = geometry.drawRange.count * rangeFactor;
  20315. var groupStart = group !== null ? group.start * rangeFactor : 0;
  20316. var groupCount = group !== null ? group.count * rangeFactor : Infinity;
  20317. var drawStart = Math.max( rangeStart, groupStart );
  20318. var drawEnd = Math.min( dataCount, rangeStart + rangeCount, groupStart + groupCount ) - 1;
  20319. var drawCount = Math.max( 0, drawEnd - drawStart + 1 );
  20320. if ( drawCount === 0 ) { return; }
  20321. //
  20322. if ( object.isMesh ) {
  20323. if ( material.wireframe === true ) {
  20324. state.setLineWidth( material.wireframeLinewidth * getTargetPixelRatio() );
  20325. renderer.setMode( 1 );
  20326. } else {
  20327. renderer.setMode( 4 );
  20328. }
  20329. } else if ( object.isLine ) {
  20330. var lineWidth = material.linewidth;
  20331. if ( lineWidth === undefined ) { lineWidth = 1; } // Not using Line*Material
  20332. state.setLineWidth( lineWidth * getTargetPixelRatio() );
  20333. if ( object.isLineSegments ) {
  20334. renderer.setMode( 1 );
  20335. } else if ( object.isLineLoop ) {
  20336. renderer.setMode( 2 );
  20337. } else {
  20338. renderer.setMode( 3 );
  20339. }
  20340. } else if ( object.isPoints ) {
  20341. renderer.setMode( 0 );
  20342. } else if ( object.isSprite ) {
  20343. renderer.setMode( 4 );
  20344. }
  20345. if ( object.isInstancedMesh ) {
  20346. renderer.renderInstances( geometry, drawStart, drawCount, object.count );
  20347. } else if ( geometry.isInstancedBufferGeometry ) {
  20348. renderer.renderInstances( geometry, drawStart, drawCount, geometry.maxInstancedCount );
  20349. } else {
  20350. renderer.render( drawStart, drawCount );
  20351. }
  20352. };
  20353. function setupVertexAttributes( object, geometry, material, program ) {
  20354. if ( capabilities.isWebGL2 === false && ( object.isInstancedMesh || geometry.isInstancedBufferGeometry ) ) {
  20355. if ( extensions.get( 'ANGLE_instanced_arrays' ) === null ) { return; }
  20356. }
  20357. state.initAttributes();
  20358. var geometryAttributes = geometry.attributes;
  20359. var programAttributes = program.getAttributes();
  20360. var materialDefaultAttributeValues = material.defaultAttributeValues;
  20361. for ( var name in programAttributes ) {
  20362. var programAttribute = programAttributes[ name ];
  20363. if ( programAttribute >= 0 ) {
  20364. var geometryAttribute = geometryAttributes[ name ];
  20365. if ( geometryAttribute !== undefined ) {
  20366. var normalized = geometryAttribute.normalized;
  20367. var size = geometryAttribute.itemSize;
  20368. var attribute = attributes.get( geometryAttribute );
  20369. // TODO Attribute may not be available on context restore
  20370. if ( attribute === undefined ) { continue; }
  20371. var buffer = attribute.buffer;
  20372. var type = attribute.type;
  20373. var bytesPerElement = attribute.bytesPerElement;
  20374. if ( geometryAttribute.isInterleavedBufferAttribute ) {
  20375. var data = geometryAttribute.data;
  20376. var stride = data.stride;
  20377. var offset = geometryAttribute.offset;
  20378. if ( data && data.isInstancedInterleavedBuffer ) {
  20379. state.enableAttributeAndDivisor( programAttribute, data.meshPerAttribute );
  20380. if ( geometry.maxInstancedCount === undefined ) {
  20381. geometry.maxInstancedCount = data.meshPerAttribute * data.count;
  20382. }
  20383. } else {
  20384. state.enableAttribute( programAttribute );
  20385. }
  20386. _gl.bindBuffer( 34962, buffer );
  20387. _gl.vertexAttribPointer( programAttribute, size, type, normalized, stride * bytesPerElement, offset * bytesPerElement );
  20388. } else {
  20389. if ( geometryAttribute.isInstancedBufferAttribute ) {
  20390. state.enableAttributeAndDivisor( programAttribute, geometryAttribute.meshPerAttribute );
  20391. if ( geometry.maxInstancedCount === undefined ) {
  20392. geometry.maxInstancedCount = geometryAttribute.meshPerAttribute * geometryAttribute.count;
  20393. }
  20394. } else {
  20395. state.enableAttribute( programAttribute );
  20396. }
  20397. _gl.bindBuffer( 34962, buffer );
  20398. _gl.vertexAttribPointer( programAttribute, size, type, normalized, 0, 0 );
  20399. }
  20400. } else if ( name === 'instanceMatrix' ) {
  20401. var attribute = attributes.get( object.instanceMatrix );
  20402. // TODO Attribute may not be available on context restore
  20403. if ( attribute === undefined ) { continue; }
  20404. var buffer = attribute.buffer;
  20405. var type = attribute.type;
  20406. state.enableAttributeAndDivisor( programAttribute + 0, 1 );
  20407. state.enableAttributeAndDivisor( programAttribute + 1, 1 );
  20408. state.enableAttributeAndDivisor( programAttribute + 2, 1 );
  20409. state.enableAttributeAndDivisor( programAttribute + 3, 1 );
  20410. _gl.bindBuffer( 34962, buffer );
  20411. _gl.vertexAttribPointer( programAttribute + 0, 4, type, false, 64, 0 );
  20412. _gl.vertexAttribPointer( programAttribute + 1, 4, type, false, 64, 16 );
  20413. _gl.vertexAttribPointer( programAttribute + 2, 4, type, false, 64, 32 );
  20414. _gl.vertexAttribPointer( programAttribute + 3, 4, type, false, 64, 48 );
  20415. } else if ( materialDefaultAttributeValues !== undefined ) {
  20416. var value = materialDefaultAttributeValues[ name ];
  20417. if ( value !== undefined ) {
  20418. switch ( value.length ) {
  20419. case 2:
  20420. _gl.vertexAttrib2fv( programAttribute, value );
  20421. break;
  20422. case 3:
  20423. _gl.vertexAttrib3fv( programAttribute, value );
  20424. break;
  20425. case 4:
  20426. _gl.vertexAttrib4fv( programAttribute, value );
  20427. break;
  20428. default:
  20429. _gl.vertexAttrib1fv( programAttribute, value );
  20430. }
  20431. }
  20432. }
  20433. }
  20434. }
  20435. state.disableUnusedAttributes();
  20436. }
  20437. // Compile
  20438. this.compile = function ( scene, camera ) {
  20439. currentRenderState = renderStates.get( scene, camera );
  20440. currentRenderState.init();
  20441. scene.traverse( function ( object ) {
  20442. if ( object.isLight ) {
  20443. currentRenderState.pushLight( object );
  20444. if ( object.castShadow ) {
  20445. currentRenderState.pushShadow( object );
  20446. }
  20447. }
  20448. } );
  20449. currentRenderState.setupLights( camera );
  20450. var compiled = {};
  20451. scene.traverse( function ( object ) {
  20452. if ( object.material ) {
  20453. if ( Array.isArray( object.material ) ) {
  20454. for ( var i = 0; i < object.material.length; i ++ ) {
  20455. if ( object.material[ i ].uuid in compiled === false ) {
  20456. initMaterial( object.material[ i ], scene, object );
  20457. compiled[ object.material[ i ].uuid ] = true;
  20458. }
  20459. }
  20460. } else if ( object.material.uuid in compiled === false ) {
  20461. initMaterial( object.material, scene, object );
  20462. compiled[ object.material.uuid ] = true;
  20463. }
  20464. }
  20465. } );
  20466. };
  20467. // Animation Loop
  20468. var onAnimationFrameCallback = null;
  20469. function onAnimationFrame( time ) {
  20470. if ( xr.isPresenting ) { return; }
  20471. if ( onAnimationFrameCallback ) { onAnimationFrameCallback( time ); }
  20472. }
  20473. var animation = new WebGLAnimation();
  20474. animation.setAnimationLoop( onAnimationFrame );
  20475. if ( typeof window !== 'undefined' ) { animation.setContext( window ); }
  20476. this.setAnimationLoop = function ( callback ) {
  20477. onAnimationFrameCallback = callback;
  20478. xr.setAnimationLoop( callback );
  20479. animation.start();
  20480. };
  20481. // Rendering
  20482. this.render = function ( scene, camera ) {
  20483. var renderTarget, forceClear;
  20484. if ( arguments[ 2 ] !== undefined ) {
  20485. console.warn( 'THREE.WebGLRenderer.render(): the renderTarget argument has been removed. Use .setRenderTarget() instead.' );
  20486. renderTarget = arguments[ 2 ];
  20487. }
  20488. if ( arguments[ 3 ] !== undefined ) {
  20489. console.warn( 'THREE.WebGLRenderer.render(): the forceClear argument has been removed. Use .clear() instead.' );
  20490. forceClear = arguments[ 3 ];
  20491. }
  20492. if ( ! ( camera && camera.isCamera ) ) {
  20493. console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  20494. return;
  20495. }
  20496. if ( _isContextLost ) { return; }
  20497. // reset caching for this frame
  20498. _currentGeometryProgram.geometry = null;
  20499. _currentGeometryProgram.program = null;
  20500. _currentGeometryProgram.wireframe = false;
  20501. _currentMaterialId = - 1;
  20502. _currentCamera = null;
  20503. // update scene graph
  20504. if ( scene.autoUpdate === true ) { scene.updateMatrixWorld(); }
  20505. // update camera matrices and frustum
  20506. if ( camera.parent === null ) { camera.updateMatrixWorld(); }
  20507. if ( xr.enabled && xr.isPresenting ) {
  20508. camera = xr.getCamera( camera );
  20509. }
  20510. //
  20511. currentRenderState = renderStates.get( scene, camera );
  20512. currentRenderState.init();
  20513. scene.onBeforeRender( _this, scene, camera, renderTarget || _currentRenderTarget );
  20514. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  20515. _frustum.setFromProjectionMatrix( _projScreenMatrix );
  20516. _localClippingEnabled = this.localClippingEnabled;
  20517. _clippingEnabled = _clipping.init( this.clippingPlanes, _localClippingEnabled, camera );
  20518. currentRenderList = renderLists.get( scene, camera );
  20519. currentRenderList.init();
  20520. projectObject( scene, camera, 0, _this.sortObjects );
  20521. currentRenderList.finish();
  20522. if ( _this.sortObjects === true ) {
  20523. currentRenderList.sort( _opaqueSort, _transparentSort );
  20524. }
  20525. //
  20526. if ( _clippingEnabled ) { _clipping.beginShadows(); }
  20527. var shadowsArray = currentRenderState.state.shadowsArray;
  20528. shadowMap.render( shadowsArray, scene, camera );
  20529. currentRenderState.setupLights( camera );
  20530. if ( _clippingEnabled ) { _clipping.endShadows(); }
  20531. //
  20532. if ( this.info.autoReset ) { this.info.reset(); }
  20533. if ( renderTarget !== undefined ) {
  20534. this.setRenderTarget( renderTarget );
  20535. }
  20536. //
  20537. background.render( currentRenderList, scene, camera, forceClear );
  20538. // render scene
  20539. var opaqueObjects = currentRenderList.opaque;
  20540. var transparentObjects = currentRenderList.transparent;
  20541. if ( scene.overrideMaterial ) {
  20542. var overrideMaterial = scene.overrideMaterial;
  20543. if ( opaqueObjects.length ) { renderObjects( opaqueObjects, scene, camera, overrideMaterial ); }
  20544. if ( transparentObjects.length ) { renderObjects( transparentObjects, scene, camera, overrideMaterial ); }
  20545. } else {
  20546. // opaque pass (front-to-back order)
  20547. if ( opaqueObjects.length ) { renderObjects( opaqueObjects, scene, camera ); }
  20548. // transparent pass (back-to-front order)
  20549. if ( transparentObjects.length ) { renderObjects( transparentObjects, scene, camera ); }
  20550. }
  20551. //
  20552. scene.onAfterRender( _this, scene, camera );
  20553. //
  20554. if ( _currentRenderTarget !== null ) {
  20555. // Generate mipmap if we're using any kind of mipmap filtering
  20556. textures.updateRenderTargetMipmap( _currentRenderTarget );
  20557. // resolve multisample renderbuffers to a single-sample texture if necessary
  20558. textures.updateMultisampleRenderTarget( _currentRenderTarget );
  20559. }
  20560. // Ensure depth buffer writing is enabled so it can be cleared on next render
  20561. state.buffers.depth.setTest( true );
  20562. state.buffers.depth.setMask( true );
  20563. state.buffers.color.setMask( true );
  20564. state.setPolygonOffset( false );
  20565. if ( xr.enabled && xr.submitFrame ) {
  20566. xr.submitFrame();
  20567. }
  20568. // _gl.finish();
  20569. currentRenderList = null;
  20570. currentRenderState = null;
  20571. };
  20572. function projectObject( object, camera, groupOrder, sortObjects ) {
  20573. if ( object.visible === false ) { return; }
  20574. var visible = object.layers.test( camera.layers );
  20575. if ( visible ) {
  20576. if ( object.isGroup ) {
  20577. groupOrder = object.renderOrder;
  20578. } else if ( object.isLOD ) {
  20579. if ( object.autoUpdate === true ) { object.update( camera ); }
  20580. } else if ( object.isLight ) {
  20581. currentRenderState.pushLight( object );
  20582. if ( object.castShadow ) {
  20583. currentRenderState.pushShadow( object );
  20584. }
  20585. } else if ( object.isSprite ) {
  20586. if ( ! object.frustumCulled || _frustum.intersectsSprite( object ) ) {
  20587. if ( sortObjects ) {
  20588. _vector3.setFromMatrixPosition( object.matrixWorld )
  20589. .applyMatrix4( _projScreenMatrix );
  20590. }
  20591. var geometry = objects.update( object );
  20592. var material = object.material;
  20593. if ( material.visible ) {
  20594. currentRenderList.push( object, geometry, material, groupOrder, _vector3.z, null );
  20595. }
  20596. }
  20597. } else if ( object.isImmediateRenderObject ) {
  20598. if ( sortObjects ) {
  20599. _vector3.setFromMatrixPosition( object.matrixWorld )
  20600. .applyMatrix4( _projScreenMatrix );
  20601. }
  20602. currentRenderList.push( object, null, object.material, groupOrder, _vector3.z, null );
  20603. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  20604. if ( object.isSkinnedMesh ) {
  20605. // update skeleton only once in a frame
  20606. if ( object.skeleton.frame !== info.render.frame ) {
  20607. object.skeleton.update();
  20608. object.skeleton.frame = info.render.frame;
  20609. }
  20610. }
  20611. if ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) {
  20612. if ( sortObjects ) {
  20613. _vector3.setFromMatrixPosition( object.matrixWorld )
  20614. .applyMatrix4( _projScreenMatrix );
  20615. }
  20616. var geometry = objects.update( object );
  20617. var material = object.material;
  20618. if ( Array.isArray( material ) ) {
  20619. var groups = geometry.groups;
  20620. for ( var i = 0, l = groups.length; i < l; i ++ ) {
  20621. var group = groups[ i ];
  20622. var groupMaterial = material[ group.materialIndex ];
  20623. if ( groupMaterial && groupMaterial.visible ) {
  20624. currentRenderList.push( object, geometry, groupMaterial, groupOrder, _vector3.z, group );
  20625. }
  20626. }
  20627. } else if ( material.visible ) {
  20628. currentRenderList.push( object, geometry, material, groupOrder, _vector3.z, null );
  20629. }
  20630. }
  20631. }
  20632. }
  20633. var children = object.children;
  20634. for ( var i = 0, l = children.length; i < l; i ++ ) {
  20635. projectObject( children[ i ], camera, groupOrder, sortObjects );
  20636. }
  20637. }
  20638. function renderObjects( renderList, scene, camera, overrideMaterial ) {
  20639. for ( var i = 0, l = renderList.length; i < l; i ++ ) {
  20640. var renderItem = renderList[ i ];
  20641. var object = renderItem.object;
  20642. var geometry = renderItem.geometry;
  20643. var material = overrideMaterial === undefined ? renderItem.material : overrideMaterial;
  20644. var group = renderItem.group;
  20645. if ( camera.isArrayCamera ) {
  20646. _currentArrayCamera = camera;
  20647. var cameras = camera.cameras;
  20648. for ( var j = 0, jl = cameras.length; j < jl; j ++ ) {
  20649. var camera2 = cameras[ j ];
  20650. if ( object.layers.test( camera2.layers ) ) {
  20651. state.viewport( _currentViewport.copy( camera2.viewport ) );
  20652. currentRenderState.setupLights( camera2 );
  20653. renderObject( object, scene, camera2, geometry, material, group );
  20654. }
  20655. }
  20656. } else {
  20657. _currentArrayCamera = null;
  20658. renderObject( object, scene, camera, geometry, material, group );
  20659. }
  20660. }
  20661. }
  20662. function renderObject( object, scene, camera, geometry, material, group ) {
  20663. object.onBeforeRender( _this, scene, camera, geometry, material, group );
  20664. currentRenderState = renderStates.get( scene, _currentArrayCamera || camera );
  20665. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  20666. object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  20667. if ( object.isImmediateRenderObject ) {
  20668. var program = setProgram( camera, scene, material, object );
  20669. state.setMaterial( material );
  20670. _currentGeometryProgram.geometry = null;
  20671. _currentGeometryProgram.program = null;
  20672. _currentGeometryProgram.wireframe = false;
  20673. renderObjectImmediate( object, program );
  20674. } else {
  20675. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  20676. }
  20677. object.onAfterRender( _this, scene, camera, geometry, material, group );
  20678. currentRenderState = renderStates.get( scene, _currentArrayCamera || camera );
  20679. }
  20680. function initMaterial( material, scene, object ) {
  20681. var materialProperties = properties.get( material );
  20682. var lights = currentRenderState.state.lights;
  20683. var shadowsArray = currentRenderState.state.shadowsArray;
  20684. var lightsStateVersion = lights.state.version;
  20685. var parameters = programCache.getParameters( material, lights.state, shadowsArray, scene, _clipping.numPlanes, _clipping.numIntersection, object );
  20686. var programCacheKey = programCache.getProgramCacheKey( parameters );
  20687. var program = materialProperties.program;
  20688. var programChange = true;
  20689. if ( program === undefined ) {
  20690. // new material
  20691. material.addEventListener( 'dispose', onMaterialDispose );
  20692. } else if ( program.cacheKey !== programCacheKey ) {
  20693. // changed glsl or parameters
  20694. releaseMaterialProgramReference( material );
  20695. } else if ( materialProperties.lightsStateVersion !== lightsStateVersion ) {
  20696. materialProperties.lightsStateVersion = lightsStateVersion;
  20697. programChange = false;
  20698. } else if ( parameters.shaderID !== undefined ) {
  20699. // same glsl and uniform list
  20700. return;
  20701. } else {
  20702. // only rebuild uniform list
  20703. programChange = false;
  20704. }
  20705. if ( programChange ) {
  20706. program = programCache.acquireProgram( parameters, programCacheKey );
  20707. materialProperties.program = program;
  20708. materialProperties.uniforms = parameters.uniforms;
  20709. materialProperties.environment = material.isMeshStandardMaterial ? scene.environment : null;
  20710. materialProperties.outputEncoding = _this.outputEncoding;
  20711. material.program = program;
  20712. }
  20713. var programAttributes = program.getAttributes();
  20714. if ( material.morphTargets ) {
  20715. material.numSupportedMorphTargets = 0;
  20716. for ( var i = 0; i < _this.maxMorphTargets; i ++ ) {
  20717. if ( programAttributes[ 'morphTarget' + i ] >= 0 ) {
  20718. material.numSupportedMorphTargets ++;
  20719. }
  20720. }
  20721. }
  20722. if ( material.morphNormals ) {
  20723. material.numSupportedMorphNormals = 0;
  20724. for ( var i = 0; i < _this.maxMorphNormals; i ++ ) {
  20725. if ( programAttributes[ 'morphNormal' + i ] >= 0 ) {
  20726. material.numSupportedMorphNormals ++;
  20727. }
  20728. }
  20729. }
  20730. var uniforms = materialProperties.uniforms;
  20731. if ( ! material.isShaderMaterial &&
  20732. ! material.isRawShaderMaterial ||
  20733. material.clipping === true ) {
  20734. materialProperties.numClippingPlanes = _clipping.numPlanes;
  20735. materialProperties.numIntersection = _clipping.numIntersection;
  20736. uniforms.clippingPlanes = _clipping.uniform;
  20737. }
  20738. materialProperties.fog = scene.fog;
  20739. // store the light setup it was created for
  20740. materialProperties.needsLights = materialNeedsLights( material );
  20741. materialProperties.lightsStateVersion = lightsStateVersion;
  20742. if ( materialProperties.needsLights ) {
  20743. // wire up the material to this renderer's lighting state
  20744. uniforms.ambientLightColor.value = lights.state.ambient;
  20745. uniforms.lightProbe.value = lights.state.probe;
  20746. uniforms.directionalLights.value = lights.state.directional;
  20747. uniforms.directionalLightShadows.value = lights.state.directionalShadow;
  20748. uniforms.spotLights.value = lights.state.spot;
  20749. uniforms.spotLightShadows.value = lights.state.spotShadow;
  20750. uniforms.rectAreaLights.value = lights.state.rectArea;
  20751. uniforms.pointLights.value = lights.state.point;
  20752. uniforms.pointLightShadows.value = lights.state.pointShadow;
  20753. uniforms.hemisphereLights.value = lights.state.hemi;
  20754. uniforms.directionalShadowMap.value = lights.state.directionalShadowMap;
  20755. uniforms.directionalShadowMatrix.value = lights.state.directionalShadowMatrix;
  20756. uniforms.spotShadowMap.value = lights.state.spotShadowMap;
  20757. uniforms.spotShadowMatrix.value = lights.state.spotShadowMatrix;
  20758. uniforms.pointShadowMap.value = lights.state.pointShadowMap;
  20759. uniforms.pointShadowMatrix.value = lights.state.pointShadowMatrix;
  20760. // TODO (abelnation): add area lights shadow info to uniforms
  20761. }
  20762. var progUniforms = materialProperties.program.getUniforms(),
  20763. uniformsList =
  20764. WebGLUniforms.seqWithValue( progUniforms.seq, uniforms );
  20765. materialProperties.uniformsList = uniformsList;
  20766. }
  20767. function setProgram( camera, scene, material, object ) {
  20768. textures.resetTextureUnits();
  20769. var fog = scene.fog;
  20770. var environment = material.isMeshStandardMaterial ? scene.environment : null;
  20771. var materialProperties = properties.get( material );
  20772. var lights = currentRenderState.state.lights;
  20773. if ( _clippingEnabled ) {
  20774. if ( _localClippingEnabled || camera !== _currentCamera ) {
  20775. var useCache =
  20776. camera === _currentCamera &&
  20777. material.id === _currentMaterialId;
  20778. // we might want to call this function with some ClippingGroup
  20779. // object instead of the material, once it becomes feasible
  20780. // (#8465, #8379)
  20781. _clipping.setState(
  20782. material.clippingPlanes, material.clipIntersection, material.clipShadows,
  20783. camera, materialProperties, useCache );
  20784. }
  20785. }
  20786. if ( material.version === materialProperties.__version ) {
  20787. if ( materialProperties.program === undefined ) {
  20788. initMaterial( material, scene, object );
  20789. } else if ( material.fog && materialProperties.fog !== fog ) {
  20790. initMaterial( material, scene, object );
  20791. } else if ( materialProperties.environment !== environment ) {
  20792. initMaterial( material, scene, object );
  20793. } else if ( materialProperties.needsLights && ( materialProperties.lightsStateVersion !== lights.state.version ) ) {
  20794. initMaterial( material, scene, object );
  20795. } else if ( materialProperties.numClippingPlanes !== undefined &&
  20796. ( materialProperties.numClippingPlanes !== _clipping.numPlanes ||
  20797. materialProperties.numIntersection !== _clipping.numIntersection ) ) {
  20798. initMaterial( material, scene, object );
  20799. } else if ( materialProperties.outputEncoding !== _this.outputEncoding ) {
  20800. initMaterial( material, scene, object );
  20801. }
  20802. } else {
  20803. initMaterial( material, scene, object );
  20804. materialProperties.__version = material.version;
  20805. }
  20806. var refreshProgram = false;
  20807. var refreshMaterial = false;
  20808. var refreshLights = false;
  20809. var program = materialProperties.program,
  20810. p_uniforms = program.getUniforms(),
  20811. m_uniforms = materialProperties.uniforms;
  20812. if ( state.useProgram( program.program ) ) {
  20813. refreshProgram = true;
  20814. refreshMaterial = true;
  20815. refreshLights = true;
  20816. }
  20817. if ( material.id !== _currentMaterialId ) {
  20818. _currentMaterialId = material.id;
  20819. refreshMaterial = true;
  20820. }
  20821. if ( refreshProgram || _currentCamera !== camera ) {
  20822. p_uniforms.setValue( _gl, 'projectionMatrix', camera.projectionMatrix );
  20823. if ( capabilities.logarithmicDepthBuffer ) {
  20824. p_uniforms.setValue( _gl, 'logDepthBufFC',
  20825. 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) );
  20826. }
  20827. if ( _currentCamera !== camera ) {
  20828. _currentCamera = camera;
  20829. // lighting uniforms depend on the camera so enforce an update
  20830. // now, in case this material supports lights - or later, when
  20831. // the next material that does gets activated:
  20832. refreshMaterial = true; // set to true on material change
  20833. refreshLights = true; // remains set until update done
  20834. }
  20835. // load material specific uniforms
  20836. // (shader material also gets them for the sake of genericity)
  20837. if ( material.isShaderMaterial ||
  20838. material.isMeshPhongMaterial ||
  20839. material.isMeshToonMaterial ||
  20840. material.isMeshStandardMaterial ||
  20841. material.envMap ) {
  20842. var uCamPos = p_uniforms.map.cameraPosition;
  20843. if ( uCamPos !== undefined ) {
  20844. uCamPos.setValue( _gl,
  20845. _vector3.setFromMatrixPosition( camera.matrixWorld ) );
  20846. }
  20847. }
  20848. if ( material.isMeshPhongMaterial ||
  20849. material.isMeshToonMaterial ||
  20850. material.isMeshLambertMaterial ||
  20851. material.isMeshBasicMaterial ||
  20852. material.isMeshStandardMaterial ||
  20853. material.isShaderMaterial ) {
  20854. p_uniforms.setValue( _gl, 'isOrthographic', camera.isOrthographicCamera === true );
  20855. }
  20856. if ( material.isMeshPhongMaterial ||
  20857. material.isMeshToonMaterial ||
  20858. material.isMeshLambertMaterial ||
  20859. material.isMeshBasicMaterial ||
  20860. material.isMeshStandardMaterial ||
  20861. material.isShaderMaterial ||
  20862. material.skinning ) {
  20863. p_uniforms.setValue( _gl, 'viewMatrix', camera.matrixWorldInverse );
  20864. }
  20865. }
  20866. // skinning uniforms must be set even if material didn't change
  20867. // auto-setting of texture unit for bone texture must go before other textures
  20868. // otherwise textures used for skinning can take over texture units reserved for other material textures
  20869. if ( material.skinning ) {
  20870. p_uniforms.setOptional( _gl, object, 'bindMatrix' );
  20871. p_uniforms.setOptional( _gl, object, 'bindMatrixInverse' );
  20872. var skeleton = object.skeleton;
  20873. if ( skeleton ) {
  20874. var bones = skeleton.bones;
  20875. if ( capabilities.floatVertexTextures ) {
  20876. if ( skeleton.boneTexture === undefined ) {
  20877. // layout (1 matrix = 4 pixels)
  20878. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  20879. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  20880. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  20881. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  20882. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  20883. var size = Math.sqrt( bones.length * 4 ); // 4 pixels needed for 1 matrix
  20884. size = MathUtils.ceilPowerOfTwo( size );
  20885. size = Math.max( size, 4 );
  20886. var boneMatrices = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  20887. boneMatrices.set( skeleton.boneMatrices ); // copy current values
  20888. var boneTexture = new DataTexture( boneMatrices, size, size, RGBAFormat, FloatType );
  20889. skeleton.boneMatrices = boneMatrices;
  20890. skeleton.boneTexture = boneTexture;
  20891. skeleton.boneTextureSize = size;
  20892. }
  20893. p_uniforms.setValue( _gl, 'boneTexture', skeleton.boneTexture, textures );
  20894. p_uniforms.setValue( _gl, 'boneTextureSize', skeleton.boneTextureSize );
  20895. } else {
  20896. p_uniforms.setOptional( _gl, skeleton, 'boneMatrices' );
  20897. }
  20898. }
  20899. }
  20900. if ( refreshMaterial || materialProperties.receiveShadow !== object.receiveShadow ) {
  20901. materialProperties.receiveShadow = object.receiveShadow;
  20902. p_uniforms.setValue( _gl, 'receiveShadow', object.receiveShadow );
  20903. }
  20904. if ( refreshMaterial ) {
  20905. p_uniforms.setValue( _gl, 'toneMappingExposure', _this.toneMappingExposure );
  20906. p_uniforms.setValue( _gl, 'toneMappingWhitePoint', _this.toneMappingWhitePoint );
  20907. if ( materialProperties.needsLights ) {
  20908. // the current material requires lighting info
  20909. // note: all lighting uniforms are always set correctly
  20910. // they simply reference the renderer's state for their
  20911. // values
  20912. //
  20913. // use the current material's .needsUpdate flags to set
  20914. // the GL state when required
  20915. markUniformsLightsNeedsUpdate( m_uniforms, refreshLights );
  20916. }
  20917. // refresh uniforms common to several materials
  20918. if ( fog && material.fog ) {
  20919. refreshUniformsFog( m_uniforms, fog );
  20920. }
  20921. if ( material.isMeshBasicMaterial ) {
  20922. refreshUniformsCommon( m_uniforms, material );
  20923. } else if ( material.isMeshLambertMaterial ) {
  20924. refreshUniformsCommon( m_uniforms, material );
  20925. refreshUniformsLambert( m_uniforms, material );
  20926. } else if ( material.isMeshToonMaterial ) {
  20927. refreshUniformsCommon( m_uniforms, material );
  20928. refreshUniformsToon( m_uniforms, material );
  20929. } else if ( material.isMeshPhongMaterial ) {
  20930. refreshUniformsCommon( m_uniforms, material );
  20931. refreshUniformsPhong( m_uniforms, material );
  20932. } else if ( material.isMeshStandardMaterial ) {
  20933. refreshUniformsCommon( m_uniforms, material, environment );
  20934. if ( material.isMeshPhysicalMaterial ) {
  20935. refreshUniformsPhysical( m_uniforms, material, environment );
  20936. } else {
  20937. refreshUniformsStandard( m_uniforms, material, environment );
  20938. }
  20939. } else if ( material.isMeshMatcapMaterial ) {
  20940. refreshUniformsCommon( m_uniforms, material );
  20941. refreshUniformsMatcap( m_uniforms, material );
  20942. } else if ( material.isMeshDepthMaterial ) {
  20943. refreshUniformsCommon( m_uniforms, material );
  20944. refreshUniformsDepth( m_uniforms, material );
  20945. } else if ( material.isMeshDistanceMaterial ) {
  20946. refreshUniformsCommon( m_uniforms, material );
  20947. refreshUniformsDistance( m_uniforms, material );
  20948. } else if ( material.isMeshNormalMaterial ) {
  20949. refreshUniformsCommon( m_uniforms, material );
  20950. refreshUniformsNormal( m_uniforms, material );
  20951. } else if ( material.isLineBasicMaterial ) {
  20952. refreshUniformsLine( m_uniforms, material );
  20953. if ( material.isLineDashedMaterial ) {
  20954. refreshUniformsDash( m_uniforms, material );
  20955. }
  20956. } else if ( material.isPointsMaterial ) {
  20957. refreshUniformsPoints( m_uniforms, material );
  20958. } else if ( material.isSpriteMaterial ) {
  20959. refreshUniformsSprites( m_uniforms, material );
  20960. } else if ( material.isShadowMaterial ) {
  20961. m_uniforms.color.value.copy( material.color );
  20962. m_uniforms.opacity.value = material.opacity;
  20963. }
  20964. // RectAreaLight Texture
  20965. // TODO (mrdoob): Find a nicer implementation
  20966. if ( m_uniforms.ltc_1 !== undefined ) { m_uniforms.ltc_1.value = UniformsLib.LTC_1; }
  20967. if ( m_uniforms.ltc_2 !== undefined ) { m_uniforms.ltc_2.value = UniformsLib.LTC_2; }
  20968. WebGLUniforms.upload( _gl, materialProperties.uniformsList, m_uniforms, textures );
  20969. if ( material.isShaderMaterial ) {
  20970. material.uniformsNeedUpdate = false; // #15581
  20971. }
  20972. }
  20973. if ( material.isShaderMaterial && material.uniformsNeedUpdate === true ) {
  20974. WebGLUniforms.upload( _gl, materialProperties.uniformsList, m_uniforms, textures );
  20975. material.uniformsNeedUpdate = false;
  20976. }
  20977. if ( material.isSpriteMaterial ) {
  20978. p_uniforms.setValue( _gl, 'center', object.center );
  20979. }
  20980. // common matrices
  20981. p_uniforms.setValue( _gl, 'modelViewMatrix', object.modelViewMatrix );
  20982. p_uniforms.setValue( _gl, 'normalMatrix', object.normalMatrix );
  20983. p_uniforms.setValue( _gl, 'modelMatrix', object.matrixWorld );
  20984. return program;
  20985. }
  20986. // Uniforms (refresh uniforms objects)
  20987. function refreshUniformsCommon( uniforms, material, environment ) {
  20988. uniforms.opacity.value = material.opacity;
  20989. if ( material.color ) {
  20990. uniforms.diffuse.value.copy( material.color );
  20991. }
  20992. if ( material.emissive ) {
  20993. uniforms.emissive.value.copy( material.emissive ).multiplyScalar( material.emissiveIntensity );
  20994. }
  20995. if ( material.map ) {
  20996. uniforms.map.value = material.map;
  20997. }
  20998. if ( material.alphaMap ) {
  20999. uniforms.alphaMap.value = material.alphaMap;
  21000. }
  21001. if ( material.specularMap ) {
  21002. uniforms.specularMap.value = material.specularMap;
  21003. }
  21004. var envMap = material.envMap || environment;
  21005. if ( envMap ) {
  21006. uniforms.envMap.value = envMap;
  21007. uniforms.flipEnvMap.value = envMap.isCubeTexture ? - 1 : 1;
  21008. uniforms.reflectivity.value = material.reflectivity;
  21009. uniforms.refractionRatio.value = material.refractionRatio;
  21010. uniforms.maxMipLevel.value = properties.get( envMap ).__maxMipLevel;
  21011. }
  21012. if ( material.lightMap ) {
  21013. uniforms.lightMap.value = material.lightMap;
  21014. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  21015. }
  21016. if ( material.aoMap ) {
  21017. uniforms.aoMap.value = material.aoMap;
  21018. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  21019. }
  21020. // uv repeat and offset setting priorities
  21021. // 1. color map
  21022. // 2. specular map
  21023. // 3. normal map
  21024. // 4. bump map
  21025. // 5. alpha map
  21026. // 6. emissive map
  21027. var uvScaleMap;
  21028. if ( material.map ) {
  21029. uvScaleMap = material.map;
  21030. } else if ( material.specularMap ) {
  21031. uvScaleMap = material.specularMap;
  21032. } else if ( material.displacementMap ) {
  21033. uvScaleMap = material.displacementMap;
  21034. } else if ( material.normalMap ) {
  21035. uvScaleMap = material.normalMap;
  21036. } else if ( material.bumpMap ) {
  21037. uvScaleMap = material.bumpMap;
  21038. } else if ( material.roughnessMap ) {
  21039. uvScaleMap = material.roughnessMap;
  21040. } else if ( material.metalnessMap ) {
  21041. uvScaleMap = material.metalnessMap;
  21042. } else if ( material.alphaMap ) {
  21043. uvScaleMap = material.alphaMap;
  21044. } else if ( material.emissiveMap ) {
  21045. uvScaleMap = material.emissiveMap;
  21046. }
  21047. if ( uvScaleMap !== undefined ) {
  21048. // backwards compatibility
  21049. if ( uvScaleMap.isWebGLRenderTarget ) {
  21050. uvScaleMap = uvScaleMap.texture;
  21051. }
  21052. if ( uvScaleMap.matrixAutoUpdate === true ) {
  21053. uvScaleMap.updateMatrix();
  21054. }
  21055. uniforms.uvTransform.value.copy( uvScaleMap.matrix );
  21056. }
  21057. // uv repeat and offset setting priorities for uv2
  21058. // 1. ao map
  21059. // 2. light map
  21060. var uv2ScaleMap;
  21061. if ( material.aoMap ) {
  21062. uv2ScaleMap = material.aoMap;
  21063. } else if ( material.lightMap ) {
  21064. uv2ScaleMap = material.lightMap;
  21065. }
  21066. if ( uv2ScaleMap !== undefined ) {
  21067. // backwards compatibility
  21068. if ( uv2ScaleMap.isWebGLRenderTarget ) {
  21069. uv2ScaleMap = uv2ScaleMap.texture;
  21070. }
  21071. if ( uv2ScaleMap.matrixAutoUpdate === true ) {
  21072. uv2ScaleMap.updateMatrix();
  21073. }
  21074. uniforms.uv2Transform.value.copy( uv2ScaleMap.matrix );
  21075. }
  21076. }
  21077. function refreshUniformsLine( uniforms, material ) {
  21078. uniforms.diffuse.value.copy( material.color );
  21079. uniforms.opacity.value = material.opacity;
  21080. }
  21081. function refreshUniformsDash( uniforms, material ) {
  21082. uniforms.dashSize.value = material.dashSize;
  21083. uniforms.totalSize.value = material.dashSize + material.gapSize;
  21084. uniforms.scale.value = material.scale;
  21085. }
  21086. function refreshUniformsPoints( uniforms, material ) {
  21087. uniforms.diffuse.value.copy( material.color );
  21088. uniforms.opacity.value = material.opacity;
  21089. uniforms.size.value = material.size * _pixelRatio;
  21090. uniforms.scale.value = _height * 0.5;
  21091. if ( material.map ) {
  21092. uniforms.map.value = material.map;
  21093. }
  21094. if ( material.alphaMap ) {
  21095. uniforms.alphaMap.value = material.alphaMap;
  21096. }
  21097. // uv repeat and offset setting priorities
  21098. // 1. color map
  21099. // 2. alpha map
  21100. var uvScaleMap;
  21101. if ( material.map ) {
  21102. uvScaleMap = material.map;
  21103. } else if ( material.alphaMap ) {
  21104. uvScaleMap = material.alphaMap;
  21105. }
  21106. if ( uvScaleMap !== undefined ) {
  21107. if ( uvScaleMap.matrixAutoUpdate === true ) {
  21108. uvScaleMap.updateMatrix();
  21109. }
  21110. uniforms.uvTransform.value.copy( uvScaleMap.matrix );
  21111. }
  21112. }
  21113. function refreshUniformsSprites( uniforms, material ) {
  21114. uniforms.diffuse.value.copy( material.color );
  21115. uniforms.opacity.value = material.opacity;
  21116. uniforms.rotation.value = material.rotation;
  21117. if ( material.map ) {
  21118. uniforms.map.value = material.map;
  21119. }
  21120. if ( material.alphaMap ) {
  21121. uniforms.alphaMap.value = material.alphaMap;
  21122. }
  21123. // uv repeat and offset setting priorities
  21124. // 1. color map
  21125. // 2. alpha map
  21126. var uvScaleMap;
  21127. if ( material.map ) {
  21128. uvScaleMap = material.map;
  21129. } else if ( material.alphaMap ) {
  21130. uvScaleMap = material.alphaMap;
  21131. }
  21132. if ( uvScaleMap !== undefined ) {
  21133. if ( uvScaleMap.matrixAutoUpdate === true ) {
  21134. uvScaleMap.updateMatrix();
  21135. }
  21136. uniforms.uvTransform.value.copy( uvScaleMap.matrix );
  21137. }
  21138. }
  21139. function refreshUniformsFog( uniforms, fog ) {
  21140. uniforms.fogColor.value.copy( fog.color );
  21141. if ( fog.isFog ) {
  21142. uniforms.fogNear.value = fog.near;
  21143. uniforms.fogFar.value = fog.far;
  21144. } else if ( fog.isFogExp2 ) {
  21145. uniforms.fogDensity.value = fog.density;
  21146. }
  21147. }
  21148. function refreshUniformsLambert( uniforms, material ) {
  21149. if ( material.emissiveMap ) {
  21150. uniforms.emissiveMap.value = material.emissiveMap;
  21151. }
  21152. }
  21153. function refreshUniformsPhong( uniforms, material ) {
  21154. uniforms.specular.value.copy( material.specular );
  21155. uniforms.shininess.value = Math.max( material.shininess, 1e-4 ); // to prevent pow( 0.0, 0.0 )
  21156. if ( material.emissiveMap ) {
  21157. uniforms.emissiveMap.value = material.emissiveMap;
  21158. }
  21159. if ( material.bumpMap ) {
  21160. uniforms.bumpMap.value = material.bumpMap;
  21161. uniforms.bumpScale.value = material.bumpScale;
  21162. if ( material.side === BackSide ) { uniforms.bumpScale.value *= - 1; }
  21163. }
  21164. if ( material.normalMap ) {
  21165. uniforms.normalMap.value = material.normalMap;
  21166. uniforms.normalScale.value.copy( material.normalScale );
  21167. if ( material.side === BackSide ) { uniforms.normalScale.value.negate(); }
  21168. }
  21169. if ( material.displacementMap ) {
  21170. uniforms.displacementMap.value = material.displacementMap;
  21171. uniforms.displacementScale.value = material.displacementScale;
  21172. uniforms.displacementBias.value = material.displacementBias;
  21173. }
  21174. }
  21175. function refreshUniformsToon( uniforms, material ) {
  21176. uniforms.specular.value.copy( material.specular );
  21177. uniforms.shininess.value = Math.max( material.shininess, 1e-4 ); // to prevent pow( 0.0, 0.0 )
  21178. if ( material.gradientMap ) {
  21179. uniforms.gradientMap.value = material.gradientMap;
  21180. }
  21181. if ( material.emissiveMap ) {
  21182. uniforms.emissiveMap.value = material.emissiveMap;
  21183. }
  21184. if ( material.bumpMap ) {
  21185. uniforms.bumpMap.value = material.bumpMap;
  21186. uniforms.bumpScale.value = material.bumpScale;
  21187. if ( material.side === BackSide ) { uniforms.bumpScale.value *= - 1; }
  21188. }
  21189. if ( material.normalMap ) {
  21190. uniforms.normalMap.value = material.normalMap;
  21191. uniforms.normalScale.value.copy( material.normalScale );
  21192. if ( material.side === BackSide ) { uniforms.normalScale.value.negate(); }
  21193. }
  21194. if ( material.displacementMap ) {
  21195. uniforms.displacementMap.value = material.displacementMap;
  21196. uniforms.displacementScale.value = material.displacementScale;
  21197. uniforms.displacementBias.value = material.displacementBias;
  21198. }
  21199. }
  21200. function refreshUniformsStandard( uniforms, material, environment ) {
  21201. uniforms.roughness.value = material.roughness;
  21202. uniforms.metalness.value = material.metalness;
  21203. if ( material.roughnessMap ) {
  21204. uniforms.roughnessMap.value = material.roughnessMap;
  21205. }
  21206. if ( material.metalnessMap ) {
  21207. uniforms.metalnessMap.value = material.metalnessMap;
  21208. }
  21209. if ( material.emissiveMap ) {
  21210. uniforms.emissiveMap.value = material.emissiveMap;
  21211. }
  21212. if ( material.bumpMap ) {
  21213. uniforms.bumpMap.value = material.bumpMap;
  21214. uniforms.bumpScale.value = material.bumpScale;
  21215. if ( material.side === BackSide ) { uniforms.bumpScale.value *= - 1; }
  21216. }
  21217. if ( material.normalMap ) {
  21218. uniforms.normalMap.value = material.normalMap;
  21219. uniforms.normalScale.value.copy( material.normalScale );
  21220. if ( material.side === BackSide ) { uniforms.normalScale.value.negate(); }
  21221. }
  21222. if ( material.displacementMap ) {
  21223. uniforms.displacementMap.value = material.displacementMap;
  21224. uniforms.displacementScale.value = material.displacementScale;
  21225. uniforms.displacementBias.value = material.displacementBias;
  21226. }
  21227. if ( material.envMap || environment ) {
  21228. //uniforms.envMap.value = material.envMap; // part of uniforms common
  21229. uniforms.envMapIntensity.value = material.envMapIntensity;
  21230. }
  21231. }
  21232. function refreshUniformsPhysical( uniforms, material, environment ) {
  21233. refreshUniformsStandard( uniforms, material, environment );
  21234. uniforms.reflectivity.value = material.reflectivity; // also part of uniforms common
  21235. uniforms.clearcoat.value = material.clearcoat;
  21236. uniforms.clearcoatRoughness.value = material.clearcoatRoughness;
  21237. if ( material.sheen ) { uniforms.sheen.value.copy( material.sheen ); }
  21238. if ( material.clearcoatMap ) {
  21239. uniforms.clearcoatMap.value = material.clearcoatMap;
  21240. }
  21241. if ( material.clearcoatRoughnessMap ) {
  21242. uniforms.clearcoatRoughnessMap.value = material.clearcoatRoughnessMap;
  21243. }
  21244. if ( material.clearcoatNormalMap ) {
  21245. uniforms.clearcoatNormalScale.value.copy( material.clearcoatNormalScale );
  21246. uniforms.clearcoatNormalMap.value = material.clearcoatNormalMap;
  21247. if ( material.side === BackSide ) {
  21248. uniforms.clearcoatNormalScale.value.negate();
  21249. }
  21250. }
  21251. uniforms.transparency.value = material.transparency;
  21252. }
  21253. function refreshUniformsMatcap( uniforms, material ) {
  21254. if ( material.matcap ) {
  21255. uniforms.matcap.value = material.matcap;
  21256. }
  21257. if ( material.bumpMap ) {
  21258. uniforms.bumpMap.value = material.bumpMap;
  21259. uniforms.bumpScale.value = material.bumpScale;
  21260. if ( material.side === BackSide ) { uniforms.bumpScale.value *= - 1; }
  21261. }
  21262. if ( material.normalMap ) {
  21263. uniforms.normalMap.value = material.normalMap;
  21264. uniforms.normalScale.value.copy( material.normalScale );
  21265. if ( material.side === BackSide ) { uniforms.normalScale.value.negate(); }
  21266. }
  21267. if ( material.displacementMap ) {
  21268. uniforms.displacementMap.value = material.displacementMap;
  21269. uniforms.displacementScale.value = material.displacementScale;
  21270. uniforms.displacementBias.value = material.displacementBias;
  21271. }
  21272. }
  21273. function refreshUniformsDepth( uniforms, material ) {
  21274. if ( material.displacementMap ) {
  21275. uniforms.displacementMap.value = material.displacementMap;
  21276. uniforms.displacementScale.value = material.displacementScale;
  21277. uniforms.displacementBias.value = material.displacementBias;
  21278. }
  21279. }
  21280. function refreshUniformsDistance( uniforms, material ) {
  21281. if ( material.displacementMap ) {
  21282. uniforms.displacementMap.value = material.displacementMap;
  21283. uniforms.displacementScale.value = material.displacementScale;
  21284. uniforms.displacementBias.value = material.displacementBias;
  21285. }
  21286. uniforms.referencePosition.value.copy( material.referencePosition );
  21287. uniforms.nearDistance.value = material.nearDistance;
  21288. uniforms.farDistance.value = material.farDistance;
  21289. }
  21290. function refreshUniformsNormal( uniforms, material ) {
  21291. if ( material.bumpMap ) {
  21292. uniforms.bumpMap.value = material.bumpMap;
  21293. uniforms.bumpScale.value = material.bumpScale;
  21294. if ( material.side === BackSide ) { uniforms.bumpScale.value *= - 1; }
  21295. }
  21296. if ( material.normalMap ) {
  21297. uniforms.normalMap.value = material.normalMap;
  21298. uniforms.normalScale.value.copy( material.normalScale );
  21299. if ( material.side === BackSide ) { uniforms.normalScale.value.negate(); }
  21300. }
  21301. if ( material.displacementMap ) {
  21302. uniforms.displacementMap.value = material.displacementMap;
  21303. uniforms.displacementScale.value = material.displacementScale;
  21304. uniforms.displacementBias.value = material.displacementBias;
  21305. }
  21306. }
  21307. // If uniforms are marked as clean, they don't need to be loaded to the GPU.
  21308. function markUniformsLightsNeedsUpdate( uniforms, value ) {
  21309. uniforms.ambientLightColor.needsUpdate = value;
  21310. uniforms.lightProbe.needsUpdate = value;
  21311. uniforms.directionalLights.needsUpdate = value;
  21312. uniforms.directionalLightShadows.needsUpdate = value;
  21313. uniforms.pointLights.needsUpdate = value;
  21314. uniforms.pointLightShadows.needsUpdate = value;
  21315. uniforms.spotLights.needsUpdate = value;
  21316. uniforms.spotLightShadows.needsUpdate = value;
  21317. uniforms.rectAreaLights.needsUpdate = value;
  21318. uniforms.hemisphereLights.needsUpdate = value;
  21319. }
  21320. function materialNeedsLights( material ) {
  21321. return material.isMeshLambertMaterial || material.isMeshToonMaterial || material.isMeshPhongMaterial ||
  21322. material.isMeshStandardMaterial || material.isShadowMaterial ||
  21323. ( material.isShaderMaterial && material.lights === true );
  21324. }
  21325. // this.setTexture2D = setTexture2D;
  21326. this.setTexture2D = ( function () {
  21327. var warned = false;
  21328. // backwards compatibility: peel texture.texture
  21329. return function setTexture2D( texture, slot ) {
  21330. if ( texture && texture.isWebGLRenderTarget ) {
  21331. if ( ! warned ) {
  21332. console.warn( "THREE.WebGLRenderer.setTexture2D: don't use render targets as textures. Use their .texture property instead." );
  21333. warned = true;
  21334. }
  21335. texture = texture.texture;
  21336. }
  21337. textures.setTexture2D( texture, slot );
  21338. };
  21339. }() );
  21340. //
  21341. this.setFramebuffer = function ( value ) {
  21342. if ( _framebuffer !== value && _currentRenderTarget === null ) { _gl.bindFramebuffer( 36160, value ); }
  21343. _framebuffer = value;
  21344. };
  21345. this.getActiveCubeFace = function () {
  21346. return _currentActiveCubeFace;
  21347. };
  21348. this.getActiveMipmapLevel = function () {
  21349. return _currentActiveMipmapLevel;
  21350. };
  21351. this.getRenderTarget = function () {
  21352. return _currentRenderTarget;
  21353. };
  21354. this.setRenderTarget = function ( renderTarget, activeCubeFace, activeMipmapLevel ) {
  21355. _currentRenderTarget = renderTarget;
  21356. _currentActiveCubeFace = activeCubeFace;
  21357. _currentActiveMipmapLevel = activeMipmapLevel;
  21358. if ( renderTarget && properties.get( renderTarget ).__webglFramebuffer === undefined ) {
  21359. textures.setupRenderTarget( renderTarget );
  21360. }
  21361. var framebuffer = _framebuffer;
  21362. var isCube = false;
  21363. if ( renderTarget ) {
  21364. var __webglFramebuffer = properties.get( renderTarget ).__webglFramebuffer;
  21365. if ( renderTarget.isWebGLCubeRenderTarget ) {
  21366. framebuffer = __webglFramebuffer[ activeCubeFace || 0 ];
  21367. isCube = true;
  21368. } else if ( renderTarget.isWebGLMultisampleRenderTarget ) {
  21369. framebuffer = properties.get( renderTarget ).__webglMultisampledFramebuffer;
  21370. } else {
  21371. framebuffer = __webglFramebuffer;
  21372. }
  21373. _currentViewport.copy( renderTarget.viewport );
  21374. _currentScissor.copy( renderTarget.scissor );
  21375. _currentScissorTest = renderTarget.scissorTest;
  21376. } else {
  21377. _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).floor();
  21378. _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).floor();
  21379. _currentScissorTest = _scissorTest;
  21380. }
  21381. if ( _currentFramebuffer !== framebuffer ) {
  21382. _gl.bindFramebuffer( 36160, framebuffer );
  21383. _currentFramebuffer = framebuffer;
  21384. }
  21385. state.viewport( _currentViewport );
  21386. state.scissor( _currentScissor );
  21387. state.setScissorTest( _currentScissorTest );
  21388. if ( isCube ) {
  21389. var textureProperties = properties.get( renderTarget.texture );
  21390. _gl.framebufferTexture2D( 36160, 36064, 34069 + ( activeCubeFace || 0 ), textureProperties.__webglTexture, activeMipmapLevel || 0 );
  21391. }
  21392. };
  21393. this.readRenderTargetPixels = function ( renderTarget, x, y, width, height, buffer, activeCubeFaceIndex ) {
  21394. if ( ! ( renderTarget && renderTarget.isWebGLRenderTarget ) ) {
  21395. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' );
  21396. return;
  21397. }
  21398. var framebuffer = properties.get( renderTarget ).__webglFramebuffer;
  21399. if ( renderTarget.isWebGLCubeRenderTarget && activeCubeFaceIndex !== undefined ) {
  21400. framebuffer = framebuffer[ activeCubeFaceIndex ];
  21401. }
  21402. if ( framebuffer ) {
  21403. var restore = false;
  21404. if ( framebuffer !== _currentFramebuffer ) {
  21405. _gl.bindFramebuffer( 36160, framebuffer );
  21406. restore = true;
  21407. }
  21408. try {
  21409. var texture = renderTarget.texture;
  21410. var textureFormat = texture.format;
  21411. var textureType = texture.type;
  21412. if ( textureFormat !== RGBAFormat && utils.convert( textureFormat ) !== _gl.getParameter( 35739 ) ) {
  21413. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.' );
  21414. return;
  21415. }
  21416. if ( textureType !== UnsignedByteType && utils.convert( textureType ) !== _gl.getParameter( 35738 ) && // IE11, Edge and Chrome Mac < 52 (#9513)
  21417. ! ( textureType === FloatType && ( capabilities.isWebGL2 || extensions.get( 'OES_texture_float' ) || extensions.get( 'WEBGL_color_buffer_float' ) ) ) && // Chrome Mac >= 52 and Firefox
  21418. ! ( textureType === HalfFloatType && ( capabilities.isWebGL2 ? extensions.get( 'EXT_color_buffer_float' ) : extensions.get( 'EXT_color_buffer_half_float' ) ) ) ) {
  21419. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.' );
  21420. return;
  21421. }
  21422. if ( _gl.checkFramebufferStatus( 36160 ) === 36053 ) {
  21423. // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  21424. if ( ( x >= 0 && x <= ( renderTarget.width - width ) ) && ( y >= 0 && y <= ( renderTarget.height - height ) ) ) {
  21425. _gl.readPixels( x, y, width, height, utils.convert( textureFormat ), utils.convert( textureType ), buffer );
  21426. }
  21427. } else {
  21428. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete.' );
  21429. }
  21430. } finally {
  21431. if ( restore ) {
  21432. _gl.bindFramebuffer( 36160, _currentFramebuffer );
  21433. }
  21434. }
  21435. }
  21436. };
  21437. this.copyFramebufferToTexture = function ( position, texture, level ) {
  21438. if ( level === undefined ) { level = 0; }
  21439. var levelScale = Math.pow( 2, - level );
  21440. var width = Math.floor( texture.image.width * levelScale );
  21441. var height = Math.floor( texture.image.height * levelScale );
  21442. var glFormat = utils.convert( texture.format );
  21443. textures.setTexture2D( texture, 0 );
  21444. _gl.copyTexImage2D( 3553, level, glFormat, position.x, position.y, width, height, 0 );
  21445. state.unbindTexture();
  21446. };
  21447. this.copyTextureToTexture = function ( position, srcTexture, dstTexture, level ) {
  21448. var width = srcTexture.image.width;
  21449. var height = srcTexture.image.height;
  21450. var glFormat = utils.convert( dstTexture.format );
  21451. var glType = utils.convert( dstTexture.type );
  21452. textures.setTexture2D( dstTexture, 0 );
  21453. if ( srcTexture.isDataTexture ) {
  21454. _gl.texSubImage2D( 3553, level || 0, position.x, position.y, width, height, glFormat, glType, srcTexture.image.data );
  21455. } else {
  21456. _gl.texSubImage2D( 3553, level || 0, position.x, position.y, glFormat, glType, srcTexture.image );
  21457. }
  21458. state.unbindTexture();
  21459. };
  21460. this.initTexture = function ( texture ) {
  21461. textures.setTexture2D( texture, 0 );
  21462. state.unbindTexture();
  21463. };
  21464. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  21465. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) ); // eslint-disable-line no-undef
  21466. }
  21467. }
  21468. /**
  21469. * @author mrdoob / http://mrdoob.com/
  21470. * @author alteredq / http://alteredqualia.com/
  21471. */
  21472. function FogExp2( color, density ) {
  21473. this.name = '';
  21474. this.color = new Color( color );
  21475. this.density = ( density !== undefined ) ? density : 0.00025;
  21476. }
  21477. Object.assign( FogExp2.prototype, {
  21478. isFogExp2: true,
  21479. clone: function () {
  21480. return new FogExp2( this.color, this.density );
  21481. },
  21482. toJSON: function ( /* meta */ ) {
  21483. return {
  21484. type: 'FogExp2',
  21485. color: this.color.getHex(),
  21486. density: this.density
  21487. };
  21488. }
  21489. } );
  21490. /**
  21491. * @author mrdoob / http://mrdoob.com/
  21492. * @author alteredq / http://alteredqualia.com/
  21493. */
  21494. function Fog( color, near, far ) {
  21495. this.name = '';
  21496. this.color = new Color( color );
  21497. this.near = ( near !== undefined ) ? near : 1;
  21498. this.far = ( far !== undefined ) ? far : 1000;
  21499. }
  21500. Object.assign( Fog.prototype, {
  21501. isFog: true,
  21502. clone: function () {
  21503. return new Fog( this.color, this.near, this.far );
  21504. },
  21505. toJSON: function ( /* meta */ ) {
  21506. return {
  21507. type: 'Fog',
  21508. color: this.color.getHex(),
  21509. near: this.near,
  21510. far: this.far
  21511. };
  21512. }
  21513. } );
  21514. /**
  21515. * @author benaadams / https://twitter.com/ben_a_adams
  21516. */
  21517. function InterleavedBuffer( array, stride ) {
  21518. this.array = array;
  21519. this.stride = stride;
  21520. this.count = array !== undefined ? array.length / stride : 0;
  21521. this.usage = StaticDrawUsage;
  21522. this.updateRange = { offset: 0, count: - 1 };
  21523. this.version = 0;
  21524. }
  21525. Object.defineProperty( InterleavedBuffer.prototype, 'needsUpdate', {
  21526. set: function ( value ) {
  21527. if ( value === true ) { this.version ++; }
  21528. }
  21529. } );
  21530. Object.assign( InterleavedBuffer.prototype, {
  21531. isInterleavedBuffer: true,
  21532. onUploadCallback: function () {},
  21533. setUsage: function ( value ) {
  21534. this.usage = value;
  21535. return this;
  21536. },
  21537. copy: function ( source ) {
  21538. this.array = new source.array.constructor( source.array );
  21539. this.count = source.count;
  21540. this.stride = source.stride;
  21541. this.usage = source.usage;
  21542. return this;
  21543. },
  21544. copyAt: function ( index1, attribute, index2 ) {
  21545. index1 *= this.stride;
  21546. index2 *= attribute.stride;
  21547. for ( var i = 0, l = this.stride; i < l; i ++ ) {
  21548. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  21549. }
  21550. return this;
  21551. },
  21552. set: function ( value, offset ) {
  21553. if ( offset === undefined ) { offset = 0; }
  21554. this.array.set( value, offset );
  21555. return this;
  21556. },
  21557. clone: function () {
  21558. return new this.constructor().copy( this );
  21559. },
  21560. onUpload: function ( callback ) {
  21561. this.onUploadCallback = callback;
  21562. return this;
  21563. }
  21564. } );
  21565. /**
  21566. * @author benaadams / https://twitter.com/ben_a_adams
  21567. */
  21568. var _vector$6 = new Vector3();
  21569. function InterleavedBufferAttribute( interleavedBuffer, itemSize, offset, normalized ) {
  21570. this.data = interleavedBuffer;
  21571. this.itemSize = itemSize;
  21572. this.offset = offset;
  21573. this.normalized = normalized === true;
  21574. }
  21575. Object.defineProperties( InterleavedBufferAttribute.prototype, {
  21576. count: {
  21577. get: function () {
  21578. return this.data.count;
  21579. }
  21580. },
  21581. array: {
  21582. get: function () {
  21583. return this.data.array;
  21584. }
  21585. }
  21586. } );
  21587. Object.assign( InterleavedBufferAttribute.prototype, {
  21588. isInterleavedBufferAttribute: true,
  21589. applyMatrix4: function ( m ) {
  21590. for ( var i = 0, l = this.data.count; i < l; i ++ ) {
  21591. _vector$6.x = this.getX( i );
  21592. _vector$6.y = this.getY( i );
  21593. _vector$6.z = this.getZ( i );
  21594. _vector$6.applyMatrix4( m );
  21595. this.setXYZ( i, _vector$6.x, _vector$6.y, _vector$6.z );
  21596. }
  21597. return this;
  21598. },
  21599. setX: function ( index, x ) {
  21600. this.data.array[ index * this.data.stride + this.offset ] = x;
  21601. return this;
  21602. },
  21603. setY: function ( index, y ) {
  21604. this.data.array[ index * this.data.stride + this.offset + 1 ] = y;
  21605. return this;
  21606. },
  21607. setZ: function ( index, z ) {
  21608. this.data.array[ index * this.data.stride + this.offset + 2 ] = z;
  21609. return this;
  21610. },
  21611. setW: function ( index, w ) {
  21612. this.data.array[ index * this.data.stride + this.offset + 3 ] = w;
  21613. return this;
  21614. },
  21615. getX: function ( index ) {
  21616. return this.data.array[ index * this.data.stride + this.offset ];
  21617. },
  21618. getY: function ( index ) {
  21619. return this.data.array[ index * this.data.stride + this.offset + 1 ];
  21620. },
  21621. getZ: function ( index ) {
  21622. return this.data.array[ index * this.data.stride + this.offset + 2 ];
  21623. },
  21624. getW: function ( index ) {
  21625. return this.data.array[ index * this.data.stride + this.offset + 3 ];
  21626. },
  21627. setXY: function ( index, x, y ) {
  21628. index = index * this.data.stride + this.offset;
  21629. this.data.array[ index + 0 ] = x;
  21630. this.data.array[ index + 1 ] = y;
  21631. return this;
  21632. },
  21633. setXYZ: function ( index, x, y, z ) {
  21634. index = index * this.data.stride + this.offset;
  21635. this.data.array[ index + 0 ] = x;
  21636. this.data.array[ index + 1 ] = y;
  21637. this.data.array[ index + 2 ] = z;
  21638. return this;
  21639. },
  21640. setXYZW: function ( index, x, y, z, w ) {
  21641. index = index * this.data.stride + this.offset;
  21642. this.data.array[ index + 0 ] = x;
  21643. this.data.array[ index + 1 ] = y;
  21644. this.data.array[ index + 2 ] = z;
  21645. this.data.array[ index + 3 ] = w;
  21646. return this;
  21647. }
  21648. } );
  21649. /**
  21650. * @author alteredq / http://alteredqualia.com/
  21651. *
  21652. * parameters = {
  21653. * color: <hex>,
  21654. * map: new THREE.Texture( <Image> ),
  21655. * alphaMap: new THREE.Texture( <Image> ),
  21656. * rotation: <float>,
  21657. * sizeAttenuation: <bool>
  21658. * }
  21659. */
  21660. function SpriteMaterial( parameters ) {
  21661. Material.call( this );
  21662. this.type = 'SpriteMaterial';
  21663. this.color = new Color( 0xffffff );
  21664. this.map = null;
  21665. this.alphaMap = null;
  21666. this.rotation = 0;
  21667. this.sizeAttenuation = true;
  21668. this.transparent = true;
  21669. this.setValues( parameters );
  21670. }
  21671. SpriteMaterial.prototype = Object.create( Material.prototype );
  21672. SpriteMaterial.prototype.constructor = SpriteMaterial;
  21673. SpriteMaterial.prototype.isSpriteMaterial = true;
  21674. SpriteMaterial.prototype.copy = function ( source ) {
  21675. Material.prototype.copy.call( this, source );
  21676. this.color.copy( source.color );
  21677. this.map = source.map;
  21678. this.alphaMap = source.alphaMap;
  21679. this.rotation = source.rotation;
  21680. this.sizeAttenuation = source.sizeAttenuation;
  21681. return this;
  21682. };
  21683. /**
  21684. * @author mikael emtinger / http://gomo.se/
  21685. * @author alteredq / http://alteredqualia.com/
  21686. */
  21687. var _geometry;
  21688. var _intersectPoint = new Vector3();
  21689. var _worldScale = new Vector3();
  21690. var _mvPosition = new Vector3();
  21691. var _alignedPosition = new Vector2();
  21692. var _rotatedPosition = new Vector2();
  21693. var _viewWorldMatrix = new Matrix4();
  21694. var _vA$1 = new Vector3();
  21695. var _vB$1 = new Vector3();
  21696. var _vC$1 = new Vector3();
  21697. var _uvA$1 = new Vector2();
  21698. var _uvB$1 = new Vector2();
  21699. var _uvC$1 = new Vector2();
  21700. function Sprite( material ) {
  21701. Object3D.call( this );
  21702. this.type = 'Sprite';
  21703. if ( _geometry === undefined ) {
  21704. _geometry = new BufferGeometry();
  21705. var float32Array = new Float32Array( [
  21706. - 0.5, - 0.5, 0, 0, 0,
  21707. 0.5, - 0.5, 0, 1, 0,
  21708. 0.5, 0.5, 0, 1, 1,
  21709. - 0.5, 0.5, 0, 0, 1
  21710. ] );
  21711. var interleavedBuffer = new InterleavedBuffer( float32Array, 5 );
  21712. _geometry.setIndex( [ 0, 1, 2, 0, 2, 3 ] );
  21713. _geometry.setAttribute( 'position', new InterleavedBufferAttribute( interleavedBuffer, 3, 0, false ) );
  21714. _geometry.setAttribute( 'uv', new InterleavedBufferAttribute( interleavedBuffer, 2, 3, false ) );
  21715. }
  21716. this.geometry = _geometry;
  21717. this.material = ( material !== undefined ) ? material : new SpriteMaterial();
  21718. this.center = new Vector2( 0.5, 0.5 );
  21719. }
  21720. Sprite.prototype = Object.assign( Object.create( Object3D.prototype ), {
  21721. constructor: Sprite,
  21722. isSprite: true,
  21723. raycast: function ( raycaster, intersects ) {
  21724. if ( raycaster.camera === null ) {
  21725. console.error( 'THREE.Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.' );
  21726. }
  21727. _worldScale.setFromMatrixScale( this.matrixWorld );
  21728. _viewWorldMatrix.copy( raycaster.camera.matrixWorld );
  21729. this.modelViewMatrix.multiplyMatrices( raycaster.camera.matrixWorldInverse, this.matrixWorld );
  21730. _mvPosition.setFromMatrixPosition( this.modelViewMatrix );
  21731. if ( raycaster.camera.isPerspectiveCamera && this.material.sizeAttenuation === false ) {
  21732. _worldScale.multiplyScalar( - _mvPosition.z );
  21733. }
  21734. var rotation = this.material.rotation;
  21735. var sin, cos;
  21736. if ( rotation !== 0 ) {
  21737. cos = Math.cos( rotation );
  21738. sin = Math.sin( rotation );
  21739. }
  21740. var center = this.center;
  21741. transformVertex( _vA$1.set( - 0.5, - 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  21742. transformVertex( _vB$1.set( 0.5, - 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  21743. transformVertex( _vC$1.set( 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  21744. _uvA$1.set( 0, 0 );
  21745. _uvB$1.set( 1, 0 );
  21746. _uvC$1.set( 1, 1 );
  21747. // check first triangle
  21748. var intersect = raycaster.ray.intersectTriangle( _vA$1, _vB$1, _vC$1, false, _intersectPoint );
  21749. if ( intersect === null ) {
  21750. // check second triangle
  21751. transformVertex( _vB$1.set( - 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  21752. _uvB$1.set( 0, 1 );
  21753. intersect = raycaster.ray.intersectTriangle( _vA$1, _vC$1, _vB$1, false, _intersectPoint );
  21754. if ( intersect === null ) {
  21755. return;
  21756. }
  21757. }
  21758. var distance = raycaster.ray.origin.distanceTo( _intersectPoint );
  21759. if ( distance < raycaster.near || distance > raycaster.far ) { return; }
  21760. intersects.push( {
  21761. distance: distance,
  21762. point: _intersectPoint.clone(),
  21763. uv: Triangle.getUV( _intersectPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2() ),
  21764. face: null,
  21765. object: this
  21766. } );
  21767. },
  21768. clone: function () {
  21769. return new this.constructor( this.material ).copy( this );
  21770. },
  21771. copy: function ( source ) {
  21772. Object3D.prototype.copy.call( this, source );
  21773. if ( source.center !== undefined ) { this.center.copy( source.center ); }
  21774. return this;
  21775. }
  21776. } );
  21777. function transformVertex( vertexPosition, mvPosition, center, scale, sin, cos ) {
  21778. // compute position in camera space
  21779. _alignedPosition.subVectors( vertexPosition, center ).addScalar( 0.5 ).multiply( scale );
  21780. // to check if rotation is not zero
  21781. if ( sin !== undefined ) {
  21782. _rotatedPosition.x = ( cos * _alignedPosition.x ) - ( sin * _alignedPosition.y );
  21783. _rotatedPosition.y = ( sin * _alignedPosition.x ) + ( cos * _alignedPosition.y );
  21784. } else {
  21785. _rotatedPosition.copy( _alignedPosition );
  21786. }
  21787. vertexPosition.copy( mvPosition );
  21788. vertexPosition.x += _rotatedPosition.x;
  21789. vertexPosition.y += _rotatedPosition.y;
  21790. // transform to world space
  21791. vertexPosition.applyMatrix4( _viewWorldMatrix );
  21792. }
  21793. /**
  21794. * @author mikael emtinger / http://gomo.se/
  21795. * @author alteredq / http://alteredqualia.com/
  21796. * @author mrdoob / http://mrdoob.com/
  21797. */
  21798. var _v1$4 = new Vector3();
  21799. var _v2$2 = new Vector3();
  21800. function LOD() {
  21801. Object3D.call( this );
  21802. this._currentLevel = 0;
  21803. this.type = 'LOD';
  21804. Object.defineProperties( this, {
  21805. levels: {
  21806. enumerable: true,
  21807. value: []
  21808. }
  21809. } );
  21810. this.autoUpdate = true;
  21811. }
  21812. LOD.prototype = Object.assign( Object.create( Object3D.prototype ), {
  21813. constructor: LOD,
  21814. isLOD: true,
  21815. copy: function ( source ) {
  21816. Object3D.prototype.copy.call( this, source, false );
  21817. var levels = source.levels;
  21818. for ( var i = 0, l = levels.length; i < l; i ++ ) {
  21819. var level = levels[ i ];
  21820. this.addLevel( level.object.clone(), level.distance );
  21821. }
  21822. this.autoUpdate = source.autoUpdate;
  21823. return this;
  21824. },
  21825. addLevel: function ( object, distance ) {
  21826. if ( distance === undefined ) { distance = 0; }
  21827. distance = Math.abs( distance );
  21828. var levels = this.levels;
  21829. for ( var l = 0; l < levels.length; l ++ ) {
  21830. if ( distance < levels[ l ].distance ) {
  21831. break;
  21832. }
  21833. }
  21834. levels.splice( l, 0, { distance: distance, object: object } );
  21835. this.add( object );
  21836. return this;
  21837. },
  21838. getCurrentLevel: function () {
  21839. return this._currentLevel;
  21840. },
  21841. getObjectForDistance: function ( distance ) {
  21842. var levels = this.levels;
  21843. if ( levels.length > 0 ) {
  21844. for ( var i = 1, l = levels.length; i < l; i ++ ) {
  21845. if ( distance < levels[ i ].distance ) {
  21846. break;
  21847. }
  21848. }
  21849. return levels[ i - 1 ].object;
  21850. }
  21851. return null;
  21852. },
  21853. raycast: function ( raycaster, intersects ) {
  21854. var levels = this.levels;
  21855. if ( levels.length > 0 ) {
  21856. _v1$4.setFromMatrixPosition( this.matrixWorld );
  21857. var distance = raycaster.ray.origin.distanceTo( _v1$4 );
  21858. this.getObjectForDistance( distance ).raycast( raycaster, intersects );
  21859. }
  21860. },
  21861. update: function ( camera ) {
  21862. var levels = this.levels;
  21863. if ( levels.length > 1 ) {
  21864. _v1$4.setFromMatrixPosition( camera.matrixWorld );
  21865. _v2$2.setFromMatrixPosition( this.matrixWorld );
  21866. var distance = _v1$4.distanceTo( _v2$2 ) / camera.zoom;
  21867. levels[ 0 ].object.visible = true;
  21868. for ( var i = 1, l = levels.length; i < l; i ++ ) {
  21869. if ( distance >= levels[ i ].distance ) {
  21870. levels[ i - 1 ].object.visible = false;
  21871. levels[ i ].object.visible = true;
  21872. } else {
  21873. break;
  21874. }
  21875. }
  21876. this._currentLevel = i - 1;
  21877. for ( ; i < l; i ++ ) {
  21878. levels[ i ].object.visible = false;
  21879. }
  21880. }
  21881. },
  21882. toJSON: function ( meta ) {
  21883. var data = Object3D.prototype.toJSON.call( this, meta );
  21884. if ( this.autoUpdate === false ) { data.object.autoUpdate = false; }
  21885. data.object.levels = [];
  21886. var levels = this.levels;
  21887. for ( var i = 0, l = levels.length; i < l; i ++ ) {
  21888. var level = levels[ i ];
  21889. data.object.levels.push( {
  21890. object: level.object.uuid,
  21891. distance: level.distance
  21892. } );
  21893. }
  21894. return data;
  21895. }
  21896. } );
  21897. /**
  21898. * @author mikael emtinger / http://gomo.se/
  21899. * @author alteredq / http://alteredqualia.com/
  21900. * @author ikerr / http://verold.com
  21901. */
  21902. function SkinnedMesh( geometry, material ) {
  21903. if ( geometry && geometry.isGeometry ) {
  21904. console.error( 'THREE.SkinnedMesh no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.' );
  21905. }
  21906. Mesh.call( this, geometry, material );
  21907. this.type = 'SkinnedMesh';
  21908. this.bindMode = 'attached';
  21909. this.bindMatrix = new Matrix4();
  21910. this.bindMatrixInverse = new Matrix4();
  21911. }
  21912. SkinnedMesh.prototype = Object.assign( Object.create( Mesh.prototype ), {
  21913. constructor: SkinnedMesh,
  21914. isSkinnedMesh: true,
  21915. bind: function ( skeleton, bindMatrix ) {
  21916. this.skeleton = skeleton;
  21917. if ( bindMatrix === undefined ) {
  21918. this.updateMatrixWorld( true );
  21919. this.skeleton.calculateInverses();
  21920. bindMatrix = this.matrixWorld;
  21921. }
  21922. this.bindMatrix.copy( bindMatrix );
  21923. this.bindMatrixInverse.getInverse( bindMatrix );
  21924. },
  21925. pose: function () {
  21926. this.skeleton.pose();
  21927. },
  21928. normalizeSkinWeights: function () {
  21929. var vector = new Vector4();
  21930. var skinWeight = this.geometry.attributes.skinWeight;
  21931. for ( var i = 0, l = skinWeight.count; i < l; i ++ ) {
  21932. vector.x = skinWeight.getX( i );
  21933. vector.y = skinWeight.getY( i );
  21934. vector.z = skinWeight.getZ( i );
  21935. vector.w = skinWeight.getW( i );
  21936. var scale = 1.0 / vector.manhattanLength();
  21937. if ( scale !== Infinity ) {
  21938. vector.multiplyScalar( scale );
  21939. } else {
  21940. vector.set( 1, 0, 0, 0 ); // do something reasonable
  21941. }
  21942. skinWeight.setXYZW( i, vector.x, vector.y, vector.z, vector.w );
  21943. }
  21944. },
  21945. updateMatrixWorld: function ( force ) {
  21946. Mesh.prototype.updateMatrixWorld.call( this, force );
  21947. if ( this.bindMode === 'attached' ) {
  21948. this.bindMatrixInverse.getInverse( this.matrixWorld );
  21949. } else if ( this.bindMode === 'detached' ) {
  21950. this.bindMatrixInverse.getInverse( this.bindMatrix );
  21951. } else {
  21952. console.warn( 'THREE.SkinnedMesh: Unrecognized bindMode: ' + this.bindMode );
  21953. }
  21954. },
  21955. clone: function () {
  21956. return new this.constructor( this.geometry, this.material ).copy( this );
  21957. }
  21958. } );
  21959. /**
  21960. * @author mikael emtinger / http://gomo.se/
  21961. * @author alteredq / http://alteredqualia.com/
  21962. * @author michael guerrero / http://realitymeltdown.com
  21963. * @author ikerr / http://verold.com
  21964. */
  21965. var _offsetMatrix = new Matrix4();
  21966. var _identityMatrix = new Matrix4();
  21967. function Skeleton( bones, boneInverses ) {
  21968. // copy the bone array
  21969. bones = bones || [];
  21970. this.bones = bones.slice( 0 );
  21971. this.boneMatrices = new Float32Array( this.bones.length * 16 );
  21972. this.frame = - 1;
  21973. // use the supplied bone inverses or calculate the inverses
  21974. if ( boneInverses === undefined ) {
  21975. this.calculateInverses();
  21976. } else {
  21977. if ( this.bones.length === boneInverses.length ) {
  21978. this.boneInverses = boneInverses.slice( 0 );
  21979. } else {
  21980. console.warn( 'THREE.Skeleton boneInverses is the wrong length.' );
  21981. this.boneInverses = [];
  21982. for ( var i = 0, il = this.bones.length; i < il; i ++ ) {
  21983. this.boneInverses.push( new Matrix4() );
  21984. }
  21985. }
  21986. }
  21987. }
  21988. Object.assign( Skeleton.prototype, {
  21989. calculateInverses: function () {
  21990. this.boneInverses = [];
  21991. for ( var i = 0, il = this.bones.length; i < il; i ++ ) {
  21992. var inverse = new Matrix4();
  21993. if ( this.bones[ i ] ) {
  21994. inverse.getInverse( this.bones[ i ].matrixWorld );
  21995. }
  21996. this.boneInverses.push( inverse );
  21997. }
  21998. },
  21999. pose: function () {
  22000. var bone, i, il;
  22001. // recover the bind-time world matrices
  22002. for ( i = 0, il = this.bones.length; i < il; i ++ ) {
  22003. bone = this.bones[ i ];
  22004. if ( bone ) {
  22005. bone.matrixWorld.getInverse( this.boneInverses[ i ] );
  22006. }
  22007. }
  22008. // compute the local matrices, positions, rotations and scales
  22009. for ( i = 0, il = this.bones.length; i < il; i ++ ) {
  22010. bone = this.bones[ i ];
  22011. if ( bone ) {
  22012. if ( bone.parent && bone.parent.isBone ) {
  22013. bone.matrix.getInverse( bone.parent.matrixWorld );
  22014. bone.matrix.multiply( bone.matrixWorld );
  22015. } else {
  22016. bone.matrix.copy( bone.matrixWorld );
  22017. }
  22018. bone.matrix.decompose( bone.position, bone.quaternion, bone.scale );
  22019. }
  22020. }
  22021. },
  22022. update: function () {
  22023. var bones = this.bones;
  22024. var boneInverses = this.boneInverses;
  22025. var boneMatrices = this.boneMatrices;
  22026. var boneTexture = this.boneTexture;
  22027. // flatten bone matrices to array
  22028. for ( var i = 0, il = bones.length; i < il; i ++ ) {
  22029. // compute the offset between the current and the original transform
  22030. var matrix = bones[ i ] ? bones[ i ].matrixWorld : _identityMatrix;
  22031. _offsetMatrix.multiplyMatrices( matrix, boneInverses[ i ] );
  22032. _offsetMatrix.toArray( boneMatrices, i * 16 );
  22033. }
  22034. if ( boneTexture !== undefined ) {
  22035. boneTexture.needsUpdate = true;
  22036. }
  22037. },
  22038. clone: function () {
  22039. return new Skeleton( this.bones, this.boneInverses );
  22040. },
  22041. getBoneByName: function ( name ) {
  22042. for ( var i = 0, il = this.bones.length; i < il; i ++ ) {
  22043. var bone = this.bones[ i ];
  22044. if ( bone.name === name ) {
  22045. return bone;
  22046. }
  22047. }
  22048. return undefined;
  22049. },
  22050. dispose: function ( ) {
  22051. if ( this.boneTexture ) {
  22052. this.boneTexture.dispose();
  22053. this.boneTexture = undefined;
  22054. }
  22055. }
  22056. } );
  22057. /**
  22058. * @author mikael emtinger / http://gomo.se/
  22059. * @author alteredq / http://alteredqualia.com/
  22060. * @author ikerr / http://verold.com
  22061. */
  22062. function Bone() {
  22063. Object3D.call( this );
  22064. this.type = 'Bone';
  22065. }
  22066. Bone.prototype = Object.assign( Object.create( Object3D.prototype ), {
  22067. constructor: Bone,
  22068. isBone: true
  22069. } );
  22070. /**
  22071. * @author mrdoob / http://mrdoob.com/
  22072. */
  22073. var _instanceLocalMatrix = new Matrix4();
  22074. var _instanceWorldMatrix = new Matrix4();
  22075. var _instanceIntersects = [];
  22076. var _mesh = new Mesh();
  22077. function InstancedMesh( geometry, material, count ) {
  22078. Mesh.call( this, geometry, material );
  22079. this.instanceMatrix = new BufferAttribute( new Float32Array( count * 16 ), 16 );
  22080. this.count = count;
  22081. this.frustumCulled = false;
  22082. }
  22083. InstancedMesh.prototype = Object.assign( Object.create( Mesh.prototype ), {
  22084. constructor: InstancedMesh,
  22085. isInstancedMesh: true,
  22086. getMatrixAt: function ( index, matrix ) {
  22087. matrix.fromArray( this.instanceMatrix.array, index * 16 );
  22088. },
  22089. raycast: function ( raycaster, intersects ) {
  22090. var matrixWorld = this.matrixWorld;
  22091. var raycastTimes = this.count;
  22092. _mesh.geometry = this.geometry;
  22093. _mesh.material = this.material;
  22094. if ( _mesh.material === undefined ) { return; }
  22095. for ( var instanceId = 0; instanceId < raycastTimes; instanceId ++ ) {
  22096. // calculate the world matrix for each instance
  22097. this.getMatrixAt( instanceId, _instanceLocalMatrix );
  22098. _instanceWorldMatrix.multiplyMatrices( matrixWorld, _instanceLocalMatrix );
  22099. // the mesh represents this single instance
  22100. _mesh.matrixWorld = _instanceWorldMatrix;
  22101. _mesh.raycast( raycaster, _instanceIntersects );
  22102. // process the result of raycast
  22103. if ( _instanceIntersects.length > 0 ) {
  22104. _instanceIntersects[ 0 ].instanceId = instanceId;
  22105. _instanceIntersects[ 0 ].object = this;
  22106. intersects.push( _instanceIntersects[ 0 ] );
  22107. _instanceIntersects.length = 0;
  22108. }
  22109. }
  22110. },
  22111. setMatrixAt: function ( index, matrix ) {
  22112. matrix.toArray( this.instanceMatrix.array, index * 16 );
  22113. },
  22114. updateMorphTargets: function () {
  22115. }
  22116. } );
  22117. /**
  22118. * @author mrdoob / http://mrdoob.com/
  22119. * @author alteredq / http://alteredqualia.com/
  22120. *
  22121. * parameters = {
  22122. * color: <hex>,
  22123. * opacity: <float>,
  22124. *
  22125. * linewidth: <float>,
  22126. * linecap: "round",
  22127. * linejoin: "round"
  22128. * }
  22129. */
  22130. function LineBasicMaterial( parameters ) {
  22131. Material.call( this );
  22132. this.type = 'LineBasicMaterial';
  22133. this.color = new Color( 0xffffff );
  22134. this.linewidth = 1;
  22135. this.linecap = 'round';
  22136. this.linejoin = 'round';
  22137. this.setValues( parameters );
  22138. }
  22139. LineBasicMaterial.prototype = Object.create( Material.prototype );
  22140. LineBasicMaterial.prototype.constructor = LineBasicMaterial;
  22141. LineBasicMaterial.prototype.isLineBasicMaterial = true;
  22142. LineBasicMaterial.prototype.copy = function ( source ) {
  22143. Material.prototype.copy.call( this, source );
  22144. this.color.copy( source.color );
  22145. this.linewidth = source.linewidth;
  22146. this.linecap = source.linecap;
  22147. this.linejoin = source.linejoin;
  22148. return this;
  22149. };
  22150. /**
  22151. * @author mrdoob / http://mrdoob.com/
  22152. */
  22153. var _start = new Vector3();
  22154. var _end = new Vector3();
  22155. var _inverseMatrix$1 = new Matrix4();
  22156. var _ray$1 = new Ray();
  22157. var _sphere$2 = new Sphere();
  22158. function Line( geometry, material, mode ) {
  22159. if ( mode === 1 ) {
  22160. console.error( 'THREE.Line: parameter THREE.LinePieces no longer supported. Use THREE.LineSegments instead.' );
  22161. }
  22162. Object3D.call( this );
  22163. this.type = 'Line';
  22164. this.geometry = geometry !== undefined ? geometry : new BufferGeometry();
  22165. this.material = material !== undefined ? material : new LineBasicMaterial();
  22166. }
  22167. Line.prototype = Object.assign( Object.create( Object3D.prototype ), {
  22168. constructor: Line,
  22169. isLine: true,
  22170. computeLineDistances: function () {
  22171. var geometry = this.geometry;
  22172. if ( geometry.isBufferGeometry ) {
  22173. // we assume non-indexed geometry
  22174. if ( geometry.index === null ) {
  22175. var positionAttribute = geometry.attributes.position;
  22176. var lineDistances = [ 0 ];
  22177. for ( var i = 1, l = positionAttribute.count; i < l; i ++ ) {
  22178. _start.fromBufferAttribute( positionAttribute, i - 1 );
  22179. _end.fromBufferAttribute( positionAttribute, i );
  22180. lineDistances[ i ] = lineDistances[ i - 1 ];
  22181. lineDistances[ i ] += _start.distanceTo( _end );
  22182. }
  22183. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  22184. } else {
  22185. console.warn( 'THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  22186. }
  22187. } else if ( geometry.isGeometry ) {
  22188. var vertices = geometry.vertices;
  22189. var lineDistances = geometry.lineDistances;
  22190. lineDistances[ 0 ] = 0;
  22191. for ( var i = 1, l = vertices.length; i < l; i ++ ) {
  22192. lineDistances[ i ] = lineDistances[ i - 1 ];
  22193. lineDistances[ i ] += vertices[ i - 1 ].distanceTo( vertices[ i ] );
  22194. }
  22195. }
  22196. return this;
  22197. },
  22198. raycast: function ( raycaster, intersects ) {
  22199. var geometry = this.geometry;
  22200. var matrixWorld = this.matrixWorld;
  22201. var threshold = raycaster.params.Line.threshold;
  22202. // Checking boundingSphere distance to ray
  22203. if ( geometry.boundingSphere === null ) { geometry.computeBoundingSphere(); }
  22204. _sphere$2.copy( geometry.boundingSphere );
  22205. _sphere$2.applyMatrix4( matrixWorld );
  22206. _sphere$2.radius += threshold;
  22207. if ( raycaster.ray.intersectsSphere( _sphere$2 ) === false ) { return; }
  22208. //
  22209. _inverseMatrix$1.getInverse( matrixWorld );
  22210. _ray$1.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$1 );
  22211. var localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  22212. var localThresholdSq = localThreshold * localThreshold;
  22213. var vStart = new Vector3();
  22214. var vEnd = new Vector3();
  22215. var interSegment = new Vector3();
  22216. var interRay = new Vector3();
  22217. var step = ( this && this.isLineSegments ) ? 2 : 1;
  22218. if ( geometry.isBufferGeometry ) {
  22219. var index = geometry.index;
  22220. var attributes = geometry.attributes;
  22221. var positions = attributes.position.array;
  22222. if ( index !== null ) {
  22223. var indices = index.array;
  22224. for ( var i = 0, l = indices.length - 1; i < l; i += step ) {
  22225. var a = indices[ i ];
  22226. var b = indices[ i + 1 ];
  22227. vStart.fromArray( positions, a * 3 );
  22228. vEnd.fromArray( positions, b * 3 );
  22229. var distSq = _ray$1.distanceSqToSegment( vStart, vEnd, interRay, interSegment );
  22230. if ( distSq > localThresholdSq ) { continue; }
  22231. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  22232. var distance = raycaster.ray.origin.distanceTo( interRay );
  22233. if ( distance < raycaster.near || distance > raycaster.far ) { continue; }
  22234. intersects.push( {
  22235. distance: distance,
  22236. // What do we want? intersection point on the ray or on the segment??
  22237. // point: raycaster.ray.at( distance ),
  22238. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  22239. index: i,
  22240. face: null,
  22241. faceIndex: null,
  22242. object: this
  22243. } );
  22244. }
  22245. } else {
  22246. for ( var i = 0, l = positions.length / 3 - 1; i < l; i += step ) {
  22247. vStart.fromArray( positions, 3 * i );
  22248. vEnd.fromArray( positions, 3 * i + 3 );
  22249. var distSq = _ray$1.distanceSqToSegment( vStart, vEnd, interRay, interSegment );
  22250. if ( distSq > localThresholdSq ) { continue; }
  22251. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  22252. var distance = raycaster.ray.origin.distanceTo( interRay );
  22253. if ( distance < raycaster.near || distance > raycaster.far ) { continue; }
  22254. intersects.push( {
  22255. distance: distance,
  22256. // What do we want? intersection point on the ray or on the segment??
  22257. // point: raycaster.ray.at( distance ),
  22258. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  22259. index: i,
  22260. face: null,
  22261. faceIndex: null,
  22262. object: this
  22263. } );
  22264. }
  22265. }
  22266. } else if ( geometry.isGeometry ) {
  22267. var vertices = geometry.vertices;
  22268. var nbVertices = vertices.length;
  22269. for ( var i = 0; i < nbVertices - 1; i += step ) {
  22270. var distSq = _ray$1.distanceSqToSegment( vertices[ i ], vertices[ i + 1 ], interRay, interSegment );
  22271. if ( distSq > localThresholdSq ) { continue; }
  22272. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  22273. var distance = raycaster.ray.origin.distanceTo( interRay );
  22274. if ( distance < raycaster.near || distance > raycaster.far ) { continue; }
  22275. intersects.push( {
  22276. distance: distance,
  22277. // What do we want? intersection point on the ray or on the segment??
  22278. // point: raycaster.ray.at( distance ),
  22279. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  22280. index: i,
  22281. face: null,
  22282. faceIndex: null,
  22283. object: this
  22284. } );
  22285. }
  22286. }
  22287. },
  22288. clone: function () {
  22289. return new this.constructor( this.geometry, this.material ).copy( this );
  22290. }
  22291. } );
  22292. /**
  22293. * @author mrdoob / http://mrdoob.com/
  22294. */
  22295. var _start$1 = new Vector3();
  22296. var _end$1 = new Vector3();
  22297. function LineSegments( geometry, material ) {
  22298. Line.call( this, geometry, material );
  22299. this.type = 'LineSegments';
  22300. }
  22301. LineSegments.prototype = Object.assign( Object.create( Line.prototype ), {
  22302. constructor: LineSegments,
  22303. isLineSegments: true,
  22304. computeLineDistances: function () {
  22305. var geometry = this.geometry;
  22306. if ( geometry.isBufferGeometry ) {
  22307. // we assume non-indexed geometry
  22308. if ( geometry.index === null ) {
  22309. var positionAttribute = geometry.attributes.position;
  22310. var lineDistances = [];
  22311. for ( var i = 0, l = positionAttribute.count; i < l; i += 2 ) {
  22312. _start$1.fromBufferAttribute( positionAttribute, i );
  22313. _end$1.fromBufferAttribute( positionAttribute, i + 1 );
  22314. lineDistances[ i ] = ( i === 0 ) ? 0 : lineDistances[ i - 1 ];
  22315. lineDistances[ i + 1 ] = lineDistances[ i ] + _start$1.distanceTo( _end$1 );
  22316. }
  22317. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  22318. } else {
  22319. console.warn( 'THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  22320. }
  22321. } else if ( geometry.isGeometry ) {
  22322. var vertices = geometry.vertices;
  22323. var lineDistances = geometry.lineDistances;
  22324. for ( var i = 0, l = vertices.length; i < l; i += 2 ) {
  22325. _start$1.copy( vertices[ i ] );
  22326. _end$1.copy( vertices[ i + 1 ] );
  22327. lineDistances[ i ] = ( i === 0 ) ? 0 : lineDistances[ i - 1 ];
  22328. lineDistances[ i + 1 ] = lineDistances[ i ] + _start$1.distanceTo( _end$1 );
  22329. }
  22330. }
  22331. return this;
  22332. }
  22333. } );
  22334. /**
  22335. * @author mgreter / http://github.com/mgreter
  22336. */
  22337. function LineLoop( geometry, material ) {
  22338. Line.call( this, geometry, material );
  22339. this.type = 'LineLoop';
  22340. }
  22341. LineLoop.prototype = Object.assign( Object.create( Line.prototype ), {
  22342. constructor: LineLoop,
  22343. isLineLoop: true,
  22344. } );
  22345. /**
  22346. * @author mrdoob / http://mrdoob.com/
  22347. * @author alteredq / http://alteredqualia.com/
  22348. *
  22349. * parameters = {
  22350. * color: <hex>,
  22351. * opacity: <float>,
  22352. * map: new THREE.Texture( <Image> ),
  22353. * alphaMap: new THREE.Texture( <Image> ),
  22354. *
  22355. * size: <float>,
  22356. * sizeAttenuation: <bool>
  22357. *
  22358. * morphTargets: <bool>
  22359. * }
  22360. */
  22361. function PointsMaterial( parameters ) {
  22362. Material.call( this );
  22363. this.type = 'PointsMaterial';
  22364. this.color = new Color( 0xffffff );
  22365. this.map = null;
  22366. this.alphaMap = null;
  22367. this.size = 1;
  22368. this.sizeAttenuation = true;
  22369. this.morphTargets = false;
  22370. this.setValues( parameters );
  22371. }
  22372. PointsMaterial.prototype = Object.create( Material.prototype );
  22373. PointsMaterial.prototype.constructor = PointsMaterial;
  22374. PointsMaterial.prototype.isPointsMaterial = true;
  22375. PointsMaterial.prototype.copy = function ( source ) {
  22376. Material.prototype.copy.call( this, source );
  22377. this.color.copy( source.color );
  22378. this.map = source.map;
  22379. this.alphaMap = source.alphaMap;
  22380. this.size = source.size;
  22381. this.sizeAttenuation = source.sizeAttenuation;
  22382. this.morphTargets = source.morphTargets;
  22383. return this;
  22384. };
  22385. /**
  22386. * @author alteredq / http://alteredqualia.com/
  22387. */
  22388. var _inverseMatrix$2 = new Matrix4();
  22389. var _ray$2 = new Ray();
  22390. var _sphere$3 = new Sphere();
  22391. var _position$1 = new Vector3();
  22392. function Points( geometry, material ) {
  22393. Object3D.call( this );
  22394. this.type = 'Points';
  22395. this.geometry = geometry !== undefined ? geometry : new BufferGeometry();
  22396. this.material = material !== undefined ? material : new PointsMaterial();
  22397. this.updateMorphTargets();
  22398. }
  22399. Points.prototype = Object.assign( Object.create( Object3D.prototype ), {
  22400. constructor: Points,
  22401. isPoints: true,
  22402. raycast: function ( raycaster, intersects ) {
  22403. var geometry = this.geometry;
  22404. var matrixWorld = this.matrixWorld;
  22405. var threshold = raycaster.params.Points.threshold;
  22406. // Checking boundingSphere distance to ray
  22407. if ( geometry.boundingSphere === null ) { geometry.computeBoundingSphere(); }
  22408. _sphere$3.copy( geometry.boundingSphere );
  22409. _sphere$3.applyMatrix4( matrixWorld );
  22410. _sphere$3.radius += threshold;
  22411. if ( raycaster.ray.intersectsSphere( _sphere$3 ) === false ) { return; }
  22412. //
  22413. _inverseMatrix$2.getInverse( matrixWorld );
  22414. _ray$2.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$2 );
  22415. var localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  22416. var localThresholdSq = localThreshold * localThreshold;
  22417. if ( geometry.isBufferGeometry ) {
  22418. var index = geometry.index;
  22419. var attributes = geometry.attributes;
  22420. var positions = attributes.position.array;
  22421. if ( index !== null ) {
  22422. var indices = index.array;
  22423. for ( var i = 0, il = indices.length; i < il; i ++ ) {
  22424. var a = indices[ i ];
  22425. _position$1.fromArray( positions, a * 3 );
  22426. testPoint( _position$1, a, localThresholdSq, matrixWorld, raycaster, intersects, this );
  22427. }
  22428. } else {
  22429. for ( var i = 0, l = positions.length / 3; i < l; i ++ ) {
  22430. _position$1.fromArray( positions, i * 3 );
  22431. testPoint( _position$1, i, localThresholdSq, matrixWorld, raycaster, intersects, this );
  22432. }
  22433. }
  22434. } else {
  22435. var vertices = geometry.vertices;
  22436. for ( var i = 0, l = vertices.length; i < l; i ++ ) {
  22437. testPoint( vertices[ i ], i, localThresholdSq, matrixWorld, raycaster, intersects, this );
  22438. }
  22439. }
  22440. },
  22441. updateMorphTargets: function () {
  22442. var geometry = this.geometry;
  22443. var m, ml, name;
  22444. if ( geometry.isBufferGeometry ) {
  22445. var morphAttributes = geometry.morphAttributes;
  22446. var keys = Object.keys( morphAttributes );
  22447. if ( keys.length > 0 ) {
  22448. var morphAttribute = morphAttributes[ keys[ 0 ] ];
  22449. if ( morphAttribute !== undefined ) {
  22450. this.morphTargetInfluences = [];
  22451. this.morphTargetDictionary = {};
  22452. for ( m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  22453. name = morphAttribute[ m ].name || String( m );
  22454. this.morphTargetInfluences.push( 0 );
  22455. this.morphTargetDictionary[ name ] = m;
  22456. }
  22457. }
  22458. }
  22459. } else {
  22460. var morphTargets = geometry.morphTargets;
  22461. if ( morphTargets !== undefined && morphTargets.length > 0 ) {
  22462. console.error( 'THREE.Points.updateMorphTargets() does not support THREE.Geometry. Use THREE.BufferGeometry instead.' );
  22463. }
  22464. }
  22465. },
  22466. clone: function () {
  22467. return new this.constructor( this.geometry, this.material ).copy( this );
  22468. }
  22469. } );
  22470. function testPoint( point, index, localThresholdSq, matrixWorld, raycaster, intersects, object ) {
  22471. var rayPointDistanceSq = _ray$2.distanceSqToPoint( point );
  22472. if ( rayPointDistanceSq < localThresholdSq ) {
  22473. var intersectPoint = new Vector3();
  22474. _ray$2.closestPointToPoint( point, intersectPoint );
  22475. intersectPoint.applyMatrix4( matrixWorld );
  22476. var distance = raycaster.ray.origin.distanceTo( intersectPoint );
  22477. if ( distance < raycaster.near || distance > raycaster.far ) { return; }
  22478. intersects.push( {
  22479. distance: distance,
  22480. distanceToRay: Math.sqrt( rayPointDistanceSq ),
  22481. point: intersectPoint,
  22482. index: index,
  22483. face: null,
  22484. object: object
  22485. } );
  22486. }
  22487. }
  22488. /**
  22489. * @author mrdoob / http://mrdoob.com/
  22490. */
  22491. function VideoTexture( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  22492. Texture.call( this, video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  22493. this.format = format !== undefined ? format : RGBFormat;
  22494. this.minFilter = minFilter !== undefined ? minFilter : LinearFilter;
  22495. this.magFilter = magFilter !== undefined ? magFilter : LinearFilter;
  22496. this.generateMipmaps = false;
  22497. }
  22498. VideoTexture.prototype = Object.assign( Object.create( Texture.prototype ), {
  22499. constructor: VideoTexture,
  22500. isVideoTexture: true,
  22501. update: function () {
  22502. var video = this.image;
  22503. if ( video.readyState >= video.HAVE_CURRENT_DATA ) {
  22504. this.needsUpdate = true;
  22505. }
  22506. }
  22507. } );
  22508. /**
  22509. * @author alteredq / http://alteredqualia.com/
  22510. */
  22511. function CompressedTexture( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding ) {
  22512. Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  22513. this.image = { width: width, height: height };
  22514. this.mipmaps = mipmaps;
  22515. // no flipping for cube textures
  22516. // (also flipping doesn't work for compressed textures )
  22517. this.flipY = false;
  22518. // can't generate mipmaps for compressed textures
  22519. // mips must be embedded in DDS files
  22520. this.generateMipmaps = false;
  22521. }
  22522. CompressedTexture.prototype = Object.create( Texture.prototype );
  22523. CompressedTexture.prototype.constructor = CompressedTexture;
  22524. CompressedTexture.prototype.isCompressedTexture = true;
  22525. /**
  22526. * @author mrdoob / http://mrdoob.com/
  22527. */
  22528. function CanvasTexture( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  22529. Texture.call( this, canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  22530. this.needsUpdate = true;
  22531. }
  22532. CanvasTexture.prototype = Object.create( Texture.prototype );
  22533. CanvasTexture.prototype.constructor = CanvasTexture;
  22534. CanvasTexture.prototype.isCanvasTexture = true;
  22535. /**
  22536. * @author Matt DesLauriers / @mattdesl
  22537. * @author atix / arthursilber.de
  22538. */
  22539. function DepthTexture( width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format ) {
  22540. format = format !== undefined ? format : DepthFormat;
  22541. if ( format !== DepthFormat && format !== DepthStencilFormat ) {
  22542. throw new Error( 'DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat' );
  22543. }
  22544. if ( type === undefined && format === DepthFormat ) { type = UnsignedShortType; }
  22545. if ( type === undefined && format === DepthStencilFormat ) { type = UnsignedInt248Type; }
  22546. Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  22547. this.image = { width: width, height: height };
  22548. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  22549. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  22550. this.flipY = false;
  22551. this.generateMipmaps = false;
  22552. }
  22553. DepthTexture.prototype = Object.create( Texture.prototype );
  22554. DepthTexture.prototype.constructor = DepthTexture;
  22555. DepthTexture.prototype.isDepthTexture = true;
  22556. /**
  22557. * @author mrdoob / http://mrdoob.com/
  22558. * @author Mugen87 / https://github.com/Mugen87
  22559. */
  22560. function WireframeGeometry( geometry ) {
  22561. BufferGeometry.call( this );
  22562. this.type = 'WireframeGeometry';
  22563. // buffer
  22564. var vertices = [];
  22565. // helper variables
  22566. var i, j, l, o, ol;
  22567. var edge = [ 0, 0 ], edges = {}, e, edge1, edge2;
  22568. var key, keys = [ 'a', 'b', 'c' ];
  22569. var vertex;
  22570. // different logic for Geometry and BufferGeometry
  22571. if ( geometry && geometry.isGeometry ) {
  22572. // create a data structure that contains all edges without duplicates
  22573. var faces = geometry.faces;
  22574. for ( i = 0, l = faces.length; i < l; i ++ ) {
  22575. var face = faces[ i ];
  22576. for ( j = 0; j < 3; j ++ ) {
  22577. edge1 = face[ keys[ j ] ];
  22578. edge2 = face[ keys[ ( j + 1 ) % 3 ] ];
  22579. edge[ 0 ] = Math.min( edge1, edge2 ); // sorting prevents duplicates
  22580. edge[ 1 ] = Math.max( edge1, edge2 );
  22581. key = edge[ 0 ] + ',' + edge[ 1 ];
  22582. if ( edges[ key ] === undefined ) {
  22583. edges[ key ] = { index1: edge[ 0 ], index2: edge[ 1 ] };
  22584. }
  22585. }
  22586. }
  22587. // generate vertices
  22588. for ( key in edges ) {
  22589. e = edges[ key ];
  22590. vertex = geometry.vertices[ e.index1 ];
  22591. vertices.push( vertex.x, vertex.y, vertex.z );
  22592. vertex = geometry.vertices[ e.index2 ];
  22593. vertices.push( vertex.x, vertex.y, vertex.z );
  22594. }
  22595. } else if ( geometry && geometry.isBufferGeometry ) {
  22596. var position, indices, groups;
  22597. var group, start, count;
  22598. var index1, index2;
  22599. vertex = new Vector3();
  22600. if ( geometry.index !== null ) {
  22601. // indexed BufferGeometry
  22602. position = geometry.attributes.position;
  22603. indices = geometry.index;
  22604. groups = geometry.groups;
  22605. if ( groups.length === 0 ) {
  22606. groups = [ { start: 0, count: indices.count, materialIndex: 0 } ];
  22607. }
  22608. // create a data structure that contains all eges without duplicates
  22609. for ( o = 0, ol = groups.length; o < ol; ++ o ) {
  22610. group = groups[ o ];
  22611. start = group.start;
  22612. count = group.count;
  22613. for ( i = start, l = ( start + count ); i < l; i += 3 ) {
  22614. for ( j = 0; j < 3; j ++ ) {
  22615. edge1 = indices.getX( i + j );
  22616. edge2 = indices.getX( i + ( j + 1 ) % 3 );
  22617. edge[ 0 ] = Math.min( edge1, edge2 ); // sorting prevents duplicates
  22618. edge[ 1 ] = Math.max( edge1, edge2 );
  22619. key = edge[ 0 ] + ',' + edge[ 1 ];
  22620. if ( edges[ key ] === undefined ) {
  22621. edges[ key ] = { index1: edge[ 0 ], index2: edge[ 1 ] };
  22622. }
  22623. }
  22624. }
  22625. }
  22626. // generate vertices
  22627. for ( key in edges ) {
  22628. e = edges[ key ];
  22629. vertex.fromBufferAttribute( position, e.index1 );
  22630. vertices.push( vertex.x, vertex.y, vertex.z );
  22631. vertex.fromBufferAttribute( position, e.index2 );
  22632. vertices.push( vertex.x, vertex.y, vertex.z );
  22633. }
  22634. } else {
  22635. // non-indexed BufferGeometry
  22636. position = geometry.attributes.position;
  22637. for ( i = 0, l = ( position.count / 3 ); i < l; i ++ ) {
  22638. for ( j = 0; j < 3; j ++ ) {
  22639. // three edges per triangle, an edge is represented as (index1, index2)
  22640. // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0)
  22641. index1 = 3 * i + j;
  22642. vertex.fromBufferAttribute( position, index1 );
  22643. vertices.push( vertex.x, vertex.y, vertex.z );
  22644. index2 = 3 * i + ( ( j + 1 ) % 3 );
  22645. vertex.fromBufferAttribute( position, index2 );
  22646. vertices.push( vertex.x, vertex.y, vertex.z );
  22647. }
  22648. }
  22649. }
  22650. }
  22651. // build geometry
  22652. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22653. }
  22654. WireframeGeometry.prototype = Object.create( BufferGeometry.prototype );
  22655. WireframeGeometry.prototype.constructor = WireframeGeometry;
  22656. /**
  22657. * @author zz85 / https://github.com/zz85
  22658. * @author Mugen87 / https://github.com/Mugen87
  22659. *
  22660. * Parametric Surfaces Geometry
  22661. * based on the brilliant article by @prideout https://prideout.net/blog/old/blog/index.html@p=44.html
  22662. */
  22663. // ParametricGeometry
  22664. function ParametricGeometry( func, slices, stacks ) {
  22665. Geometry.call( this );
  22666. this.type = 'ParametricGeometry';
  22667. this.parameters = {
  22668. func: func,
  22669. slices: slices,
  22670. stacks: stacks
  22671. };
  22672. this.fromBufferGeometry( new ParametricBufferGeometry( func, slices, stacks ) );
  22673. this.mergeVertices();
  22674. }
  22675. ParametricGeometry.prototype = Object.create( Geometry.prototype );
  22676. ParametricGeometry.prototype.constructor = ParametricGeometry;
  22677. // ParametricBufferGeometry
  22678. function ParametricBufferGeometry( func, slices, stacks ) {
  22679. BufferGeometry.call( this );
  22680. this.type = 'ParametricBufferGeometry';
  22681. this.parameters = {
  22682. func: func,
  22683. slices: slices,
  22684. stacks: stacks
  22685. };
  22686. // buffers
  22687. var indices = [];
  22688. var vertices = [];
  22689. var normals = [];
  22690. var uvs = [];
  22691. var EPS = 0.00001;
  22692. var normal = new Vector3();
  22693. var p0 = new Vector3(), p1 = new Vector3();
  22694. var pu = new Vector3(), pv = new Vector3();
  22695. var i, j;
  22696. if ( func.length < 3 ) {
  22697. console.error( 'THREE.ParametricGeometry: Function must now modify a Vector3 as third parameter.' );
  22698. }
  22699. // generate vertices, normals and uvs
  22700. var sliceCount = slices + 1;
  22701. for ( i = 0; i <= stacks; i ++ ) {
  22702. var v = i / stacks;
  22703. for ( j = 0; j <= slices; j ++ ) {
  22704. var u = j / slices;
  22705. // vertex
  22706. func( u, v, p0 );
  22707. vertices.push( p0.x, p0.y, p0.z );
  22708. // normal
  22709. // approximate tangent vectors via finite differences
  22710. if ( u - EPS >= 0 ) {
  22711. func( u - EPS, v, p1 );
  22712. pu.subVectors( p0, p1 );
  22713. } else {
  22714. func( u + EPS, v, p1 );
  22715. pu.subVectors( p1, p0 );
  22716. }
  22717. if ( v - EPS >= 0 ) {
  22718. func( u, v - EPS, p1 );
  22719. pv.subVectors( p0, p1 );
  22720. } else {
  22721. func( u, v + EPS, p1 );
  22722. pv.subVectors( p1, p0 );
  22723. }
  22724. // cross product of tangent vectors returns surface normal
  22725. normal.crossVectors( pu, pv ).normalize();
  22726. normals.push( normal.x, normal.y, normal.z );
  22727. // uv
  22728. uvs.push( u, v );
  22729. }
  22730. }
  22731. // generate indices
  22732. for ( i = 0; i < stacks; i ++ ) {
  22733. for ( j = 0; j < slices; j ++ ) {
  22734. var a = i * sliceCount + j;
  22735. var b = i * sliceCount + j + 1;
  22736. var c = ( i + 1 ) * sliceCount + j + 1;
  22737. var d = ( i + 1 ) * sliceCount + j;
  22738. // faces one and two
  22739. indices.push( a, b, d );
  22740. indices.push( b, c, d );
  22741. }
  22742. }
  22743. // build geometry
  22744. this.setIndex( indices );
  22745. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22746. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  22747. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  22748. }
  22749. ParametricBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  22750. ParametricBufferGeometry.prototype.constructor = ParametricBufferGeometry;
  22751. /**
  22752. * @author clockworkgeek / https://github.com/clockworkgeek
  22753. * @author timothypratley / https://github.com/timothypratley
  22754. * @author WestLangley / http://github.com/WestLangley
  22755. * @author Mugen87 / https://github.com/Mugen87
  22756. */
  22757. // PolyhedronGeometry
  22758. function PolyhedronGeometry( vertices, indices, radius, detail ) {
  22759. Geometry.call( this );
  22760. this.type = 'PolyhedronGeometry';
  22761. this.parameters = {
  22762. vertices: vertices,
  22763. indices: indices,
  22764. radius: radius,
  22765. detail: detail
  22766. };
  22767. this.fromBufferGeometry( new PolyhedronBufferGeometry( vertices, indices, radius, detail ) );
  22768. this.mergeVertices();
  22769. }
  22770. PolyhedronGeometry.prototype = Object.create( Geometry.prototype );
  22771. PolyhedronGeometry.prototype.constructor = PolyhedronGeometry;
  22772. // PolyhedronBufferGeometry
  22773. function PolyhedronBufferGeometry( vertices, indices, radius, detail ) {
  22774. BufferGeometry.call( this );
  22775. this.type = 'PolyhedronBufferGeometry';
  22776. this.parameters = {
  22777. vertices: vertices,
  22778. indices: indices,
  22779. radius: radius,
  22780. detail: detail
  22781. };
  22782. radius = radius || 1;
  22783. detail = detail || 0;
  22784. // default buffer data
  22785. var vertexBuffer = [];
  22786. var uvBuffer = [];
  22787. // the subdivision creates the vertex buffer data
  22788. subdivide( detail );
  22789. // all vertices should lie on a conceptual sphere with a given radius
  22790. applyRadius( radius );
  22791. // finally, create the uv data
  22792. generateUVs();
  22793. // build non-indexed geometry
  22794. this.setAttribute( 'position', new Float32BufferAttribute( vertexBuffer, 3 ) );
  22795. this.setAttribute( 'normal', new Float32BufferAttribute( vertexBuffer.slice(), 3 ) );
  22796. this.setAttribute( 'uv', new Float32BufferAttribute( uvBuffer, 2 ) );
  22797. if ( detail === 0 ) {
  22798. this.computeVertexNormals(); // flat normals
  22799. } else {
  22800. this.normalizeNormals(); // smooth normals
  22801. }
  22802. // helper functions
  22803. function subdivide( detail ) {
  22804. var a = new Vector3();
  22805. var b = new Vector3();
  22806. var c = new Vector3();
  22807. // iterate over all faces and apply a subdivison with the given detail value
  22808. for ( var i = 0; i < indices.length; i += 3 ) {
  22809. // get the vertices of the face
  22810. getVertexByIndex( indices[ i + 0 ], a );
  22811. getVertexByIndex( indices[ i + 1 ], b );
  22812. getVertexByIndex( indices[ i + 2 ], c );
  22813. // perform subdivision
  22814. subdivideFace( a, b, c, detail );
  22815. }
  22816. }
  22817. function subdivideFace( a, b, c, detail ) {
  22818. var cols = Math.pow( 2, detail );
  22819. // we use this multidimensional array as a data structure for creating the subdivision
  22820. var v = [];
  22821. var i, j;
  22822. // construct all of the vertices for this subdivision
  22823. for ( i = 0; i <= cols; i ++ ) {
  22824. v[ i ] = [];
  22825. var aj = a.clone().lerp( c, i / cols );
  22826. var bj = b.clone().lerp( c, i / cols );
  22827. var rows = cols - i;
  22828. for ( j = 0; j <= rows; j ++ ) {
  22829. if ( j === 0 && i === cols ) {
  22830. v[ i ][ j ] = aj;
  22831. } else {
  22832. v[ i ][ j ] = aj.clone().lerp( bj, j / rows );
  22833. }
  22834. }
  22835. }
  22836. // construct all of the faces
  22837. for ( i = 0; i < cols; i ++ ) {
  22838. for ( j = 0; j < 2 * ( cols - i ) - 1; j ++ ) {
  22839. var k = Math.floor( j / 2 );
  22840. if ( j % 2 === 0 ) {
  22841. pushVertex( v[ i ][ k + 1 ] );
  22842. pushVertex( v[ i + 1 ][ k ] );
  22843. pushVertex( v[ i ][ k ] );
  22844. } else {
  22845. pushVertex( v[ i ][ k + 1 ] );
  22846. pushVertex( v[ i + 1 ][ k + 1 ] );
  22847. pushVertex( v[ i + 1 ][ k ] );
  22848. }
  22849. }
  22850. }
  22851. }
  22852. function applyRadius( radius ) {
  22853. var vertex = new Vector3();
  22854. // iterate over the entire buffer and apply the radius to each vertex
  22855. for ( var i = 0; i < vertexBuffer.length; i += 3 ) {
  22856. vertex.x = vertexBuffer[ i + 0 ];
  22857. vertex.y = vertexBuffer[ i + 1 ];
  22858. vertex.z = vertexBuffer[ i + 2 ];
  22859. vertex.normalize().multiplyScalar( radius );
  22860. vertexBuffer[ i + 0 ] = vertex.x;
  22861. vertexBuffer[ i + 1 ] = vertex.y;
  22862. vertexBuffer[ i + 2 ] = vertex.z;
  22863. }
  22864. }
  22865. function generateUVs() {
  22866. var vertex = new Vector3();
  22867. for ( var i = 0; i < vertexBuffer.length; i += 3 ) {
  22868. vertex.x = vertexBuffer[ i + 0 ];
  22869. vertex.y = vertexBuffer[ i + 1 ];
  22870. vertex.z = vertexBuffer[ i + 2 ];
  22871. var u = azimuth( vertex ) / 2 / Math.PI + 0.5;
  22872. var v = inclination( vertex ) / Math.PI + 0.5;
  22873. uvBuffer.push( u, 1 - v );
  22874. }
  22875. correctUVs();
  22876. correctSeam();
  22877. }
  22878. function correctSeam() {
  22879. // handle case when face straddles the seam, see #3269
  22880. for ( var i = 0; i < uvBuffer.length; i += 6 ) {
  22881. // uv data of a single face
  22882. var x0 = uvBuffer[ i + 0 ];
  22883. var x1 = uvBuffer[ i + 2 ];
  22884. var x2 = uvBuffer[ i + 4 ];
  22885. var max = Math.max( x0, x1, x2 );
  22886. var min = Math.min( x0, x1, x2 );
  22887. // 0.9 is somewhat arbitrary
  22888. if ( max > 0.9 && min < 0.1 ) {
  22889. if ( x0 < 0.2 ) { uvBuffer[ i + 0 ] += 1; }
  22890. if ( x1 < 0.2 ) { uvBuffer[ i + 2 ] += 1; }
  22891. if ( x2 < 0.2 ) { uvBuffer[ i + 4 ] += 1; }
  22892. }
  22893. }
  22894. }
  22895. function pushVertex( vertex ) {
  22896. vertexBuffer.push( vertex.x, vertex.y, vertex.z );
  22897. }
  22898. function getVertexByIndex( index, vertex ) {
  22899. var stride = index * 3;
  22900. vertex.x = vertices[ stride + 0 ];
  22901. vertex.y = vertices[ stride + 1 ];
  22902. vertex.z = vertices[ stride + 2 ];
  22903. }
  22904. function correctUVs() {
  22905. var a = new Vector3();
  22906. var b = new Vector3();
  22907. var c = new Vector3();
  22908. var centroid = new Vector3();
  22909. var uvA = new Vector2();
  22910. var uvB = new Vector2();
  22911. var uvC = new Vector2();
  22912. for ( var i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6 ) {
  22913. a.set( vertexBuffer[ i + 0 ], vertexBuffer[ i + 1 ], vertexBuffer[ i + 2 ] );
  22914. b.set( vertexBuffer[ i + 3 ], vertexBuffer[ i + 4 ], vertexBuffer[ i + 5 ] );
  22915. c.set( vertexBuffer[ i + 6 ], vertexBuffer[ i + 7 ], vertexBuffer[ i + 8 ] );
  22916. uvA.set( uvBuffer[ j + 0 ], uvBuffer[ j + 1 ] );
  22917. uvB.set( uvBuffer[ j + 2 ], uvBuffer[ j + 3 ] );
  22918. uvC.set( uvBuffer[ j + 4 ], uvBuffer[ j + 5 ] );
  22919. centroid.copy( a ).add( b ).add( c ).divideScalar( 3 );
  22920. var azi = azimuth( centroid );
  22921. correctUV( uvA, j + 0, a, azi );
  22922. correctUV( uvB, j + 2, b, azi );
  22923. correctUV( uvC, j + 4, c, azi );
  22924. }
  22925. }
  22926. function correctUV( uv, stride, vector, azimuth ) {
  22927. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) {
  22928. uvBuffer[ stride ] = uv.x - 1;
  22929. }
  22930. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) {
  22931. uvBuffer[ stride ] = azimuth / 2 / Math.PI + 0.5;
  22932. }
  22933. }
  22934. // Angle around the Y axis, counter-clockwise when looking from above.
  22935. function azimuth( vector ) {
  22936. return Math.atan2( vector.z, - vector.x );
  22937. }
  22938. // Angle above the XZ plane.
  22939. function inclination( vector ) {
  22940. return Math.atan2( - vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  22941. }
  22942. }
  22943. PolyhedronBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  22944. PolyhedronBufferGeometry.prototype.constructor = PolyhedronBufferGeometry;
  22945. /**
  22946. * @author timothypratley / https://github.com/timothypratley
  22947. * @author Mugen87 / https://github.com/Mugen87
  22948. */
  22949. // TetrahedronGeometry
  22950. function TetrahedronGeometry( radius, detail ) {
  22951. Geometry.call( this );
  22952. this.type = 'TetrahedronGeometry';
  22953. this.parameters = {
  22954. radius: radius,
  22955. detail: detail
  22956. };
  22957. this.fromBufferGeometry( new TetrahedronBufferGeometry( radius, detail ) );
  22958. this.mergeVertices();
  22959. }
  22960. TetrahedronGeometry.prototype = Object.create( Geometry.prototype );
  22961. TetrahedronGeometry.prototype.constructor = TetrahedronGeometry;
  22962. // TetrahedronBufferGeometry
  22963. function TetrahedronBufferGeometry( radius, detail ) {
  22964. var vertices = [
  22965. 1, 1, 1, - 1, - 1, 1, - 1, 1, - 1, 1, - 1, - 1
  22966. ];
  22967. var indices = [
  22968. 2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1
  22969. ];
  22970. PolyhedronBufferGeometry.call( this, vertices, indices, radius, detail );
  22971. this.type = 'TetrahedronBufferGeometry';
  22972. this.parameters = {
  22973. radius: radius,
  22974. detail: detail
  22975. };
  22976. }
  22977. TetrahedronBufferGeometry.prototype = Object.create( PolyhedronBufferGeometry.prototype );
  22978. TetrahedronBufferGeometry.prototype.constructor = TetrahedronBufferGeometry;
  22979. /**
  22980. * @author timothypratley / https://github.com/timothypratley
  22981. * @author Mugen87 / https://github.com/Mugen87
  22982. */
  22983. // OctahedronGeometry
  22984. function OctahedronGeometry( radius, detail ) {
  22985. Geometry.call( this );
  22986. this.type = 'OctahedronGeometry';
  22987. this.parameters = {
  22988. radius: radius,
  22989. detail: detail
  22990. };
  22991. this.fromBufferGeometry( new OctahedronBufferGeometry( radius, detail ) );
  22992. this.mergeVertices();
  22993. }
  22994. OctahedronGeometry.prototype = Object.create( Geometry.prototype );
  22995. OctahedronGeometry.prototype.constructor = OctahedronGeometry;
  22996. // OctahedronBufferGeometry
  22997. function OctahedronBufferGeometry( radius, detail ) {
  22998. var vertices = [
  22999. 1, 0, 0, - 1, 0, 0, 0, 1, 0,
  23000. 0, - 1, 0, 0, 0, 1, 0, 0, - 1
  23001. ];
  23002. var indices = [
  23003. 0, 2, 4, 0, 4, 3, 0, 3, 5,
  23004. 0, 5, 2, 1, 2, 5, 1, 5, 3,
  23005. 1, 3, 4, 1, 4, 2
  23006. ];
  23007. PolyhedronBufferGeometry.call( this, vertices, indices, radius, detail );
  23008. this.type = 'OctahedronBufferGeometry';
  23009. this.parameters = {
  23010. radius: radius,
  23011. detail: detail
  23012. };
  23013. }
  23014. OctahedronBufferGeometry.prototype = Object.create( PolyhedronBufferGeometry.prototype );
  23015. OctahedronBufferGeometry.prototype.constructor = OctahedronBufferGeometry;
  23016. /**
  23017. * @author timothypratley / https://github.com/timothypratley
  23018. * @author Mugen87 / https://github.com/Mugen87
  23019. */
  23020. // IcosahedronGeometry
  23021. function IcosahedronGeometry( radius, detail ) {
  23022. Geometry.call( this );
  23023. this.type = 'IcosahedronGeometry';
  23024. this.parameters = {
  23025. radius: radius,
  23026. detail: detail
  23027. };
  23028. this.fromBufferGeometry( new IcosahedronBufferGeometry( radius, detail ) );
  23029. this.mergeVertices();
  23030. }
  23031. IcosahedronGeometry.prototype = Object.create( Geometry.prototype );
  23032. IcosahedronGeometry.prototype.constructor = IcosahedronGeometry;
  23033. // IcosahedronBufferGeometry
  23034. function IcosahedronBufferGeometry( radius, detail ) {
  23035. var t = ( 1 + Math.sqrt( 5 ) ) / 2;
  23036. var vertices = [
  23037. - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t, 0,
  23038. 0, - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t,
  23039. t, 0, - 1, t, 0, 1, - t, 0, - 1, - t, 0, 1
  23040. ];
  23041. var indices = [
  23042. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11,
  23043. 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8,
  23044. 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9,
  23045. 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1
  23046. ];
  23047. PolyhedronBufferGeometry.call( this, vertices, indices, radius, detail );
  23048. this.type = 'IcosahedronBufferGeometry';
  23049. this.parameters = {
  23050. radius: radius,
  23051. detail: detail
  23052. };
  23053. }
  23054. IcosahedronBufferGeometry.prototype = Object.create( PolyhedronBufferGeometry.prototype );
  23055. IcosahedronBufferGeometry.prototype.constructor = IcosahedronBufferGeometry;
  23056. /**
  23057. * @author Abe Pazos / https://hamoid.com
  23058. * @author Mugen87 / https://github.com/Mugen87
  23059. */
  23060. // DodecahedronGeometry
  23061. function DodecahedronGeometry( radius, detail ) {
  23062. Geometry.call( this );
  23063. this.type = 'DodecahedronGeometry';
  23064. this.parameters = {
  23065. radius: radius,
  23066. detail: detail
  23067. };
  23068. this.fromBufferGeometry( new DodecahedronBufferGeometry( radius, detail ) );
  23069. this.mergeVertices();
  23070. }
  23071. DodecahedronGeometry.prototype = Object.create( Geometry.prototype );
  23072. DodecahedronGeometry.prototype.constructor = DodecahedronGeometry;
  23073. // DodecahedronBufferGeometry
  23074. function DodecahedronBufferGeometry( radius, detail ) {
  23075. var t = ( 1 + Math.sqrt( 5 ) ) / 2;
  23076. var r = 1 / t;
  23077. var vertices = [
  23078. // (±1, ±1, ±1)
  23079. - 1, - 1, - 1, - 1, - 1, 1,
  23080. - 1, 1, - 1, - 1, 1, 1,
  23081. 1, - 1, - 1, 1, - 1, 1,
  23082. 1, 1, - 1, 1, 1, 1,
  23083. // (0, ±1/φ, ±φ)
  23084. 0, - r, - t, 0, - r, t,
  23085. 0, r, - t, 0, r, t,
  23086. // (±1/φ, ±φ, 0)
  23087. - r, - t, 0, - r, t, 0,
  23088. r, - t, 0, r, t, 0,
  23089. // (±φ, 0, ±1/φ)
  23090. - t, 0, - r, t, 0, - r,
  23091. - t, 0, r, t, 0, r
  23092. ];
  23093. var indices = [
  23094. 3, 11, 7, 3, 7, 15, 3, 15, 13,
  23095. 7, 19, 17, 7, 17, 6, 7, 6, 15,
  23096. 17, 4, 8, 17, 8, 10, 17, 10, 6,
  23097. 8, 0, 16, 8, 16, 2, 8, 2, 10,
  23098. 0, 12, 1, 0, 1, 18, 0, 18, 16,
  23099. 6, 10, 2, 6, 2, 13, 6, 13, 15,
  23100. 2, 16, 18, 2, 18, 3, 2, 3, 13,
  23101. 18, 1, 9, 18, 9, 11, 18, 11, 3,
  23102. 4, 14, 12, 4, 12, 0, 4, 0, 8,
  23103. 11, 9, 5, 11, 5, 19, 11, 19, 7,
  23104. 19, 5, 14, 19, 14, 4, 19, 4, 17,
  23105. 1, 12, 14, 1, 14, 5, 1, 5, 9
  23106. ];
  23107. PolyhedronBufferGeometry.call( this, vertices, indices, radius, detail );
  23108. this.type = 'DodecahedronBufferGeometry';
  23109. this.parameters = {
  23110. radius: radius,
  23111. detail: detail
  23112. };
  23113. }
  23114. DodecahedronBufferGeometry.prototype = Object.create( PolyhedronBufferGeometry.prototype );
  23115. DodecahedronBufferGeometry.prototype.constructor = DodecahedronBufferGeometry;
  23116. /**
  23117. * @author oosmoxiecode / https://github.com/oosmoxiecode
  23118. * @author WestLangley / https://github.com/WestLangley
  23119. * @author zz85 / https://github.com/zz85
  23120. * @author miningold / https://github.com/miningold
  23121. * @author jonobr1 / https://github.com/jonobr1
  23122. * @author Mugen87 / https://github.com/Mugen87
  23123. *
  23124. */
  23125. // TubeGeometry
  23126. function TubeGeometry( path, tubularSegments, radius, radialSegments, closed, taper ) {
  23127. Geometry.call( this );
  23128. this.type = 'TubeGeometry';
  23129. this.parameters = {
  23130. path: path,
  23131. tubularSegments: tubularSegments,
  23132. radius: radius,
  23133. radialSegments: radialSegments,
  23134. closed: closed
  23135. };
  23136. if ( taper !== undefined ) { console.warn( 'THREE.TubeGeometry: taper has been removed.' ); }
  23137. var bufferGeometry = new TubeBufferGeometry( path, tubularSegments, radius, radialSegments, closed );
  23138. // expose internals
  23139. this.tangents = bufferGeometry.tangents;
  23140. this.normals = bufferGeometry.normals;
  23141. this.binormals = bufferGeometry.binormals;
  23142. // create geometry
  23143. this.fromBufferGeometry( bufferGeometry );
  23144. this.mergeVertices();
  23145. }
  23146. TubeGeometry.prototype = Object.create( Geometry.prototype );
  23147. TubeGeometry.prototype.constructor = TubeGeometry;
  23148. // TubeBufferGeometry
  23149. function TubeBufferGeometry( path, tubularSegments, radius, radialSegments, closed ) {
  23150. BufferGeometry.call( this );
  23151. this.type = 'TubeBufferGeometry';
  23152. this.parameters = {
  23153. path: path,
  23154. tubularSegments: tubularSegments,
  23155. radius: radius,
  23156. radialSegments: radialSegments,
  23157. closed: closed
  23158. };
  23159. tubularSegments = tubularSegments || 64;
  23160. radius = radius || 1;
  23161. radialSegments = radialSegments || 8;
  23162. closed = closed || false;
  23163. var frames = path.computeFrenetFrames( tubularSegments, closed );
  23164. // expose internals
  23165. this.tangents = frames.tangents;
  23166. this.normals = frames.normals;
  23167. this.binormals = frames.binormals;
  23168. // helper variables
  23169. var vertex = new Vector3();
  23170. var normal = new Vector3();
  23171. var uv = new Vector2();
  23172. var P = new Vector3();
  23173. var i, j;
  23174. // buffer
  23175. var vertices = [];
  23176. var normals = [];
  23177. var uvs = [];
  23178. var indices = [];
  23179. // create buffer data
  23180. generateBufferData();
  23181. // build geometry
  23182. this.setIndex( indices );
  23183. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  23184. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  23185. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  23186. // functions
  23187. function generateBufferData() {
  23188. for ( i = 0; i < tubularSegments; i ++ ) {
  23189. generateSegment( i );
  23190. }
  23191. // if the geometry is not closed, generate the last row of vertices and normals
  23192. // at the regular position on the given path
  23193. //
  23194. // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ)
  23195. generateSegment( ( closed === false ) ? tubularSegments : 0 );
  23196. // uvs are generated in a separate function.
  23197. // this makes it easy compute correct values for closed geometries
  23198. generateUVs();
  23199. // finally create faces
  23200. generateIndices();
  23201. }
  23202. function generateSegment( i ) {
  23203. // we use getPointAt to sample evenly distributed points from the given path
  23204. P = path.getPointAt( i / tubularSegments, P );
  23205. // retrieve corresponding normal and binormal
  23206. var N = frames.normals[ i ];
  23207. var B = frames.binormals[ i ];
  23208. // generate normals and vertices for the current segment
  23209. for ( j = 0; j <= radialSegments; j ++ ) {
  23210. var v = j / radialSegments * Math.PI * 2;
  23211. var sin = Math.sin( v );
  23212. var cos = - Math.cos( v );
  23213. // normal
  23214. normal.x = ( cos * N.x + sin * B.x );
  23215. normal.y = ( cos * N.y + sin * B.y );
  23216. normal.z = ( cos * N.z + sin * B.z );
  23217. normal.normalize();
  23218. normals.push( normal.x, normal.y, normal.z );
  23219. // vertex
  23220. vertex.x = P.x + radius * normal.x;
  23221. vertex.y = P.y + radius * normal.y;
  23222. vertex.z = P.z + radius * normal.z;
  23223. vertices.push( vertex.x, vertex.y, vertex.z );
  23224. }
  23225. }
  23226. function generateIndices() {
  23227. for ( j = 1; j <= tubularSegments; j ++ ) {
  23228. for ( i = 1; i <= radialSegments; i ++ ) {
  23229. var a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  23230. var b = ( radialSegments + 1 ) * j + ( i - 1 );
  23231. var c = ( radialSegments + 1 ) * j + i;
  23232. var d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  23233. // faces
  23234. indices.push( a, b, d );
  23235. indices.push( b, c, d );
  23236. }
  23237. }
  23238. }
  23239. function generateUVs() {
  23240. for ( i = 0; i <= tubularSegments; i ++ ) {
  23241. for ( j = 0; j <= radialSegments; j ++ ) {
  23242. uv.x = i / tubularSegments;
  23243. uv.y = j / radialSegments;
  23244. uvs.push( uv.x, uv.y );
  23245. }
  23246. }
  23247. }
  23248. }
  23249. TubeBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  23250. TubeBufferGeometry.prototype.constructor = TubeBufferGeometry;
  23251. TubeBufferGeometry.prototype.toJSON = function () {
  23252. var data = BufferGeometry.prototype.toJSON.call( this );
  23253. data.path = this.parameters.path.toJSON();
  23254. return data;
  23255. };
  23256. /**
  23257. * @author oosmoxiecode
  23258. * @author Mugen87 / https://github.com/Mugen87
  23259. *
  23260. * based on http://www.blackpawn.com/texts/pqtorus/
  23261. */
  23262. // TorusKnotGeometry
  23263. function TorusKnotGeometry( radius, tube, tubularSegments, radialSegments, p, q, heightScale ) {
  23264. Geometry.call( this );
  23265. this.type = 'TorusKnotGeometry';
  23266. this.parameters = {
  23267. radius: radius,
  23268. tube: tube,
  23269. tubularSegments: tubularSegments,
  23270. radialSegments: radialSegments,
  23271. p: p,
  23272. q: q
  23273. };
  23274. if ( heightScale !== undefined ) { console.warn( 'THREE.TorusKnotGeometry: heightScale has been deprecated. Use .scale( x, y, z ) instead.' ); }
  23275. this.fromBufferGeometry( new TorusKnotBufferGeometry( radius, tube, tubularSegments, radialSegments, p, q ) );
  23276. this.mergeVertices();
  23277. }
  23278. TorusKnotGeometry.prototype = Object.create( Geometry.prototype );
  23279. TorusKnotGeometry.prototype.constructor = TorusKnotGeometry;
  23280. // TorusKnotBufferGeometry
  23281. function TorusKnotBufferGeometry( radius, tube, tubularSegments, radialSegments, p, q ) {
  23282. BufferGeometry.call( this );
  23283. this.type = 'TorusKnotBufferGeometry';
  23284. this.parameters = {
  23285. radius: radius,
  23286. tube: tube,
  23287. tubularSegments: tubularSegments,
  23288. radialSegments: radialSegments,
  23289. p: p,
  23290. q: q
  23291. };
  23292. radius = radius || 1;
  23293. tube = tube || 0.4;
  23294. tubularSegments = Math.floor( tubularSegments ) || 64;
  23295. radialSegments = Math.floor( radialSegments ) || 8;
  23296. p = p || 2;
  23297. q = q || 3;
  23298. // buffers
  23299. var indices = [];
  23300. var vertices = [];
  23301. var normals = [];
  23302. var uvs = [];
  23303. // helper variables
  23304. var i, j;
  23305. var vertex = new Vector3();
  23306. var normal = new Vector3();
  23307. var P1 = new Vector3();
  23308. var P2 = new Vector3();
  23309. var B = new Vector3();
  23310. var T = new Vector3();
  23311. var N = new Vector3();
  23312. // generate vertices, normals and uvs
  23313. for ( i = 0; i <= tubularSegments; ++ i ) {
  23314. // the radian "u" is used to calculate the position on the torus curve of the current tubular segement
  23315. var u = i / tubularSegments * p * Math.PI * 2;
  23316. // now we calculate two points. P1 is our current position on the curve, P2 is a little farther ahead.
  23317. // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions
  23318. calculatePositionOnCurve( u, p, q, radius, P1 );
  23319. calculatePositionOnCurve( u + 0.01, p, q, radius, P2 );
  23320. // calculate orthonormal basis
  23321. T.subVectors( P2, P1 );
  23322. N.addVectors( P2, P1 );
  23323. B.crossVectors( T, N );
  23324. N.crossVectors( B, T );
  23325. // normalize B, N. T can be ignored, we don't use it
  23326. B.normalize();
  23327. N.normalize();
  23328. for ( j = 0; j <= radialSegments; ++ j ) {
  23329. // now calculate the vertices. they are nothing more than an extrusion of the torus curve.
  23330. // because we extrude a shape in the xy-plane, there is no need to calculate a z-value.
  23331. var v = j / radialSegments * Math.PI * 2;
  23332. var cx = - tube * Math.cos( v );
  23333. var cy = tube * Math.sin( v );
  23334. // now calculate the final vertex position.
  23335. // first we orient the extrusion with our basis vectos, then we add it to the current position on the curve
  23336. vertex.x = P1.x + ( cx * N.x + cy * B.x );
  23337. vertex.y = P1.y + ( cx * N.y + cy * B.y );
  23338. vertex.z = P1.z + ( cx * N.z + cy * B.z );
  23339. vertices.push( vertex.x, vertex.y, vertex.z );
  23340. // normal (P1 is always the center/origin of the extrusion, thus we can use it to calculate the normal)
  23341. normal.subVectors( vertex, P1 ).normalize();
  23342. normals.push( normal.x, normal.y, normal.z );
  23343. // uv
  23344. uvs.push( i / tubularSegments );
  23345. uvs.push( j / radialSegments );
  23346. }
  23347. }
  23348. // generate indices
  23349. for ( j = 1; j <= tubularSegments; j ++ ) {
  23350. for ( i = 1; i <= radialSegments; i ++ ) {
  23351. // indices
  23352. var a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  23353. var b = ( radialSegments + 1 ) * j + ( i - 1 );
  23354. var c = ( radialSegments + 1 ) * j + i;
  23355. var d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  23356. // faces
  23357. indices.push( a, b, d );
  23358. indices.push( b, c, d );
  23359. }
  23360. }
  23361. // build geometry
  23362. this.setIndex( indices );
  23363. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  23364. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  23365. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  23366. // this function calculates the current position on the torus curve
  23367. function calculatePositionOnCurve( u, p, q, radius, position ) {
  23368. var cu = Math.cos( u );
  23369. var su = Math.sin( u );
  23370. var quOverP = q / p * u;
  23371. var cs = Math.cos( quOverP );
  23372. position.x = radius * ( 2 + cs ) * 0.5 * cu;
  23373. position.y = radius * ( 2 + cs ) * su * 0.5;
  23374. position.z = radius * Math.sin( quOverP ) * 0.5;
  23375. }
  23376. }
  23377. TorusKnotBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  23378. TorusKnotBufferGeometry.prototype.constructor = TorusKnotBufferGeometry;
  23379. /**
  23380. * @author oosmoxiecode
  23381. * @author mrdoob / http://mrdoob.com/
  23382. * @author Mugen87 / https://github.com/Mugen87
  23383. */
  23384. // TorusGeometry
  23385. function TorusGeometry( radius, tube, radialSegments, tubularSegments, arc ) {
  23386. Geometry.call( this );
  23387. this.type = 'TorusGeometry';
  23388. this.parameters = {
  23389. radius: radius,
  23390. tube: tube,
  23391. radialSegments: radialSegments,
  23392. tubularSegments: tubularSegments,
  23393. arc: arc
  23394. };
  23395. this.fromBufferGeometry( new TorusBufferGeometry( radius, tube, radialSegments, tubularSegments, arc ) );
  23396. this.mergeVertices();
  23397. }
  23398. TorusGeometry.prototype = Object.create( Geometry.prototype );
  23399. TorusGeometry.prototype.constructor = TorusGeometry;
  23400. // TorusBufferGeometry
  23401. function TorusBufferGeometry( radius, tube, radialSegments, tubularSegments, arc ) {
  23402. BufferGeometry.call( this );
  23403. this.type = 'TorusBufferGeometry';
  23404. this.parameters = {
  23405. radius: radius,
  23406. tube: tube,
  23407. radialSegments: radialSegments,
  23408. tubularSegments: tubularSegments,
  23409. arc: arc
  23410. };
  23411. radius = radius || 1;
  23412. tube = tube || 0.4;
  23413. radialSegments = Math.floor( radialSegments ) || 8;
  23414. tubularSegments = Math.floor( tubularSegments ) || 6;
  23415. arc = arc || Math.PI * 2;
  23416. // buffers
  23417. var indices = [];
  23418. var vertices = [];
  23419. var normals = [];
  23420. var uvs = [];
  23421. // helper variables
  23422. var center = new Vector3();
  23423. var vertex = new Vector3();
  23424. var normal = new Vector3();
  23425. var j, i;
  23426. // generate vertices, normals and uvs
  23427. for ( j = 0; j <= radialSegments; j ++ ) {
  23428. for ( i = 0; i <= tubularSegments; i ++ ) {
  23429. var u = i / tubularSegments * arc;
  23430. var v = j / radialSegments * Math.PI * 2;
  23431. // vertex
  23432. vertex.x = ( radius + tube * Math.cos( v ) ) * Math.cos( u );
  23433. vertex.y = ( radius + tube * Math.cos( v ) ) * Math.sin( u );
  23434. vertex.z = tube * Math.sin( v );
  23435. vertices.push( vertex.x, vertex.y, vertex.z );
  23436. // normal
  23437. center.x = radius * Math.cos( u );
  23438. center.y = radius * Math.sin( u );
  23439. normal.subVectors( vertex, center ).normalize();
  23440. normals.push( normal.x, normal.y, normal.z );
  23441. // uv
  23442. uvs.push( i / tubularSegments );
  23443. uvs.push( j / radialSegments );
  23444. }
  23445. }
  23446. // generate indices
  23447. for ( j = 1; j <= radialSegments; j ++ ) {
  23448. for ( i = 1; i <= tubularSegments; i ++ ) {
  23449. // indices
  23450. var a = ( tubularSegments + 1 ) * j + i - 1;
  23451. var b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  23452. var c = ( tubularSegments + 1 ) * ( j - 1 ) + i;
  23453. var d = ( tubularSegments + 1 ) * j + i;
  23454. // faces
  23455. indices.push( a, b, d );
  23456. indices.push( b, c, d );
  23457. }
  23458. }
  23459. // build geometry
  23460. this.setIndex( indices );
  23461. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  23462. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  23463. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  23464. }
  23465. TorusBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  23466. TorusBufferGeometry.prototype.constructor = TorusBufferGeometry;
  23467. /**
  23468. * @author Mugen87 / https://github.com/Mugen87
  23469. * Port from https://github.com/mapbox/earcut (v2.1.5)
  23470. */
  23471. var Earcut = {
  23472. triangulate: function ( data, holeIndices, dim ) {
  23473. dim = dim || 2;
  23474. var hasHoles = holeIndices && holeIndices.length,
  23475. outerLen = hasHoles ? holeIndices[ 0 ] * dim : data.length,
  23476. outerNode = linkedList( data, 0, outerLen, dim, true ),
  23477. triangles = [];
  23478. if ( ! outerNode || outerNode.next === outerNode.prev ) { return triangles; }
  23479. var minX, minY, maxX, maxY, x, y, invSize;
  23480. if ( hasHoles ) { outerNode = eliminateHoles( data, holeIndices, outerNode, dim ); }
  23481. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  23482. if ( data.length > 80 * dim ) {
  23483. minX = maxX = data[ 0 ];
  23484. minY = maxY = data[ 1 ];
  23485. for ( var i = dim; i < outerLen; i += dim ) {
  23486. x = data[ i ];
  23487. y = data[ i + 1 ];
  23488. if ( x < minX ) { minX = x; }
  23489. if ( y < minY ) { minY = y; }
  23490. if ( x > maxX ) { maxX = x; }
  23491. if ( y > maxY ) { maxY = y; }
  23492. }
  23493. // minX, minY and invSize are later used to transform coords into integers for z-order calculation
  23494. invSize = Math.max( maxX - minX, maxY - minY );
  23495. invSize = invSize !== 0 ? 1 / invSize : 0;
  23496. }
  23497. earcutLinked( outerNode, triangles, dim, minX, minY, invSize );
  23498. return triangles;
  23499. }
  23500. };
  23501. // create a circular doubly linked list from polygon points in the specified winding order
  23502. function linkedList( data, start, end, dim, clockwise ) {
  23503. var i, last;
  23504. if ( clockwise === ( signedArea( data, start, end, dim ) > 0 ) ) {
  23505. for ( i = start; i < end; i += dim ) { last = insertNode( i, data[ i ], data[ i + 1 ], last ); }
  23506. } else {
  23507. for ( i = end - dim; i >= start; i -= dim ) { last = insertNode( i, data[ i ], data[ i + 1 ], last ); }
  23508. }
  23509. if ( last && equals( last, last.next ) ) {
  23510. removeNode( last );
  23511. last = last.next;
  23512. }
  23513. return last;
  23514. }
  23515. // eliminate colinear or duplicate points
  23516. function filterPoints( start, end ) {
  23517. if ( ! start ) { return start; }
  23518. if ( ! end ) { end = start; }
  23519. var p = start,
  23520. again;
  23521. do {
  23522. again = false;
  23523. if ( ! p.steiner && ( equals( p, p.next ) || area( p.prev, p, p.next ) === 0 ) ) {
  23524. removeNode( p );
  23525. p = end = p.prev;
  23526. if ( p === p.next ) { break; }
  23527. again = true;
  23528. } else {
  23529. p = p.next;
  23530. }
  23531. } while ( again || p !== end );
  23532. return end;
  23533. }
  23534. // main ear slicing loop which triangulates a polygon (given as a linked list)
  23535. function earcutLinked( ear, triangles, dim, minX, minY, invSize, pass ) {
  23536. if ( ! ear ) { return; }
  23537. // interlink polygon nodes in z-order
  23538. if ( ! pass && invSize ) { indexCurve( ear, minX, minY, invSize ); }
  23539. var stop = ear,
  23540. prev, next;
  23541. // iterate through ears, slicing them one by one
  23542. while ( ear.prev !== ear.next ) {
  23543. prev = ear.prev;
  23544. next = ear.next;
  23545. if ( invSize ? isEarHashed( ear, minX, minY, invSize ) : isEar( ear ) ) {
  23546. // cut off the triangle
  23547. triangles.push( prev.i / dim );
  23548. triangles.push( ear.i / dim );
  23549. triangles.push( next.i / dim );
  23550. removeNode( ear );
  23551. // skipping the next vertex leads to less sliver triangles
  23552. ear = next.next;
  23553. stop = next.next;
  23554. continue;
  23555. }
  23556. ear = next;
  23557. // if we looped through the whole remaining polygon and can't find any more ears
  23558. if ( ear === stop ) {
  23559. // try filtering points and slicing again
  23560. if ( ! pass ) {
  23561. earcutLinked( filterPoints( ear ), triangles, dim, minX, minY, invSize, 1 );
  23562. // if this didn't work, try curing all small self-intersections locally
  23563. } else if ( pass === 1 ) {
  23564. ear = cureLocalIntersections( ear, triangles, dim );
  23565. earcutLinked( ear, triangles, dim, minX, minY, invSize, 2 );
  23566. // as a last resort, try splitting the remaining polygon into two
  23567. } else if ( pass === 2 ) {
  23568. splitEarcut( ear, triangles, dim, minX, minY, invSize );
  23569. }
  23570. break;
  23571. }
  23572. }
  23573. }
  23574. // check whether a polygon node forms a valid ear with adjacent nodes
  23575. function isEar( ear ) {
  23576. var a = ear.prev,
  23577. b = ear,
  23578. c = ear.next;
  23579. if ( area( a, b, c ) >= 0 ) { return false; } // reflex, can't be an ear
  23580. // now make sure we don't have other points inside the potential ear
  23581. var p = ear.next.next;
  23582. while ( p !== ear.prev ) {
  23583. if ( pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y ) &&
  23584. area( p.prev, p, p.next ) >= 0 ) { return false; }
  23585. p = p.next;
  23586. }
  23587. return true;
  23588. }
  23589. function isEarHashed( ear, minX, minY, invSize ) {
  23590. var a = ear.prev,
  23591. b = ear,
  23592. c = ear.next;
  23593. if ( area( a, b, c ) >= 0 ) { return false; } // reflex, can't be an ear
  23594. // triangle bbox; min & max are calculated like this for speed
  23595. var minTX = a.x < b.x ? ( a.x < c.x ? a.x : c.x ) : ( b.x < c.x ? b.x : c.x ),
  23596. minTY = a.y < b.y ? ( a.y < c.y ? a.y : c.y ) : ( b.y < c.y ? b.y : c.y ),
  23597. maxTX = a.x > b.x ? ( a.x > c.x ? a.x : c.x ) : ( b.x > c.x ? b.x : c.x ),
  23598. maxTY = a.y > b.y ? ( a.y > c.y ? a.y : c.y ) : ( b.y > c.y ? b.y : c.y );
  23599. // z-order range for the current triangle bbox;
  23600. var minZ = zOrder( minTX, minTY, minX, minY, invSize ),
  23601. maxZ = zOrder( maxTX, maxTY, minX, minY, invSize );
  23602. var p = ear.prevZ,
  23603. n = ear.nextZ;
  23604. // look for points inside the triangle in both directions
  23605. while ( p && p.z >= minZ && n && n.z <= maxZ ) {
  23606. if ( p !== ear.prev && p !== ear.next &&
  23607. pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y ) &&
  23608. area( p.prev, p, p.next ) >= 0 ) { return false; }
  23609. p = p.prevZ;
  23610. if ( n !== ear.prev && n !== ear.next &&
  23611. pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, n.x, n.y ) &&
  23612. area( n.prev, n, n.next ) >= 0 ) { return false; }
  23613. n = n.nextZ;
  23614. }
  23615. // look for remaining points in decreasing z-order
  23616. while ( p && p.z >= minZ ) {
  23617. if ( p !== ear.prev && p !== ear.next &&
  23618. pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y ) &&
  23619. area( p.prev, p, p.next ) >= 0 ) { return false; }
  23620. p = p.prevZ;
  23621. }
  23622. // look for remaining points in increasing z-order
  23623. while ( n && n.z <= maxZ ) {
  23624. if ( n !== ear.prev && n !== ear.next &&
  23625. pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, n.x, n.y ) &&
  23626. area( n.prev, n, n.next ) >= 0 ) { return false; }
  23627. n = n.nextZ;
  23628. }
  23629. return true;
  23630. }
  23631. // go through all polygon nodes and cure small local self-intersections
  23632. function cureLocalIntersections( start, triangles, dim ) {
  23633. var p = start;
  23634. do {
  23635. var a = p.prev,
  23636. b = p.next.next;
  23637. if ( ! equals( a, b ) && intersects( a, p, p.next, b ) && locallyInside( a, b ) && locallyInside( b, a ) ) {
  23638. triangles.push( a.i / dim );
  23639. triangles.push( p.i / dim );
  23640. triangles.push( b.i / dim );
  23641. // remove two nodes involved
  23642. removeNode( p );
  23643. removeNode( p.next );
  23644. p = start = b;
  23645. }
  23646. p = p.next;
  23647. } while ( p !== start );
  23648. return p;
  23649. }
  23650. // try splitting polygon into two and triangulate them independently
  23651. function splitEarcut( start, triangles, dim, minX, minY, invSize ) {
  23652. // look for a valid diagonal that divides the polygon into two
  23653. var a = start;
  23654. do {
  23655. var b = a.next.next;
  23656. while ( b !== a.prev ) {
  23657. if ( a.i !== b.i && isValidDiagonal( a, b ) ) {
  23658. // split the polygon in two by the diagonal
  23659. var c = splitPolygon( a, b );
  23660. // filter colinear points around the cuts
  23661. a = filterPoints( a, a.next );
  23662. c = filterPoints( c, c.next );
  23663. // run earcut on each half
  23664. earcutLinked( a, triangles, dim, minX, minY, invSize );
  23665. earcutLinked( c, triangles, dim, minX, minY, invSize );
  23666. return;
  23667. }
  23668. b = b.next;
  23669. }
  23670. a = a.next;
  23671. } while ( a !== start );
  23672. }
  23673. // link every hole into the outer loop, producing a single-ring polygon without holes
  23674. function eliminateHoles( data, holeIndices, outerNode, dim ) {
  23675. var queue = [],
  23676. i, len, start, end, list;
  23677. for ( i = 0, len = holeIndices.length; i < len; i ++ ) {
  23678. start = holeIndices[ i ] * dim;
  23679. end = i < len - 1 ? holeIndices[ i + 1 ] * dim : data.length;
  23680. list = linkedList( data, start, end, dim, false );
  23681. if ( list === list.next ) { list.steiner = true; }
  23682. queue.push( getLeftmost( list ) );
  23683. }
  23684. queue.sort( compareX );
  23685. // process holes from left to right
  23686. for ( i = 0; i < queue.length; i ++ ) {
  23687. eliminateHole( queue[ i ], outerNode );
  23688. outerNode = filterPoints( outerNode, outerNode.next );
  23689. }
  23690. return outerNode;
  23691. }
  23692. function compareX( a, b ) {
  23693. return a.x - b.x;
  23694. }
  23695. // find a bridge between vertices that connects hole with an outer ring and and link it
  23696. function eliminateHole( hole, outerNode ) {
  23697. outerNode = findHoleBridge( hole, outerNode );
  23698. if ( outerNode ) {
  23699. var b = splitPolygon( outerNode, hole );
  23700. filterPoints( b, b.next );
  23701. }
  23702. }
  23703. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  23704. function findHoleBridge( hole, outerNode ) {
  23705. var p = outerNode,
  23706. hx = hole.x,
  23707. hy = hole.y,
  23708. qx = - Infinity,
  23709. m;
  23710. // find a segment intersected by a ray from the hole's leftmost point to the left;
  23711. // segment's endpoint with lesser x will be potential connection point
  23712. do {
  23713. if ( hy <= p.y && hy >= p.next.y && p.next.y !== p.y ) {
  23714. var x = p.x + ( hy - p.y ) * ( p.next.x - p.x ) / ( p.next.y - p.y );
  23715. if ( x <= hx && x > qx ) {
  23716. qx = x;
  23717. if ( x === hx ) {
  23718. if ( hy === p.y ) { return p; }
  23719. if ( hy === p.next.y ) { return p.next; }
  23720. }
  23721. m = p.x < p.next.x ? p : p.next;
  23722. }
  23723. }
  23724. p = p.next;
  23725. } while ( p !== outerNode );
  23726. if ( ! m ) { return null; }
  23727. if ( hx === qx ) { return m.prev; } // hole touches outer segment; pick lower endpoint
  23728. // look for points inside the triangle of hole point, segment intersection and endpoint;
  23729. // if there are no points found, we have a valid connection;
  23730. // otherwise choose the point of the minimum angle with the ray as connection point
  23731. var stop = m,
  23732. mx = m.x,
  23733. my = m.y,
  23734. tanMin = Infinity,
  23735. tan;
  23736. p = m.next;
  23737. while ( p !== stop ) {
  23738. if ( hx >= p.x && p.x >= mx && hx !== p.x &&
  23739. pointInTriangle( hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y ) ) {
  23740. tan = Math.abs( hy - p.y ) / ( hx - p.x ); // tangential
  23741. if ( ( tan < tanMin || ( tan === tanMin && p.x > m.x ) ) && locallyInside( p, hole ) ) {
  23742. m = p;
  23743. tanMin = tan;
  23744. }
  23745. }
  23746. p = p.next;
  23747. }
  23748. return m;
  23749. }
  23750. // interlink polygon nodes in z-order
  23751. function indexCurve( start, minX, minY, invSize ) {
  23752. var p = start;
  23753. do {
  23754. if ( p.z === null ) { p.z = zOrder( p.x, p.y, minX, minY, invSize ); }
  23755. p.prevZ = p.prev;
  23756. p.nextZ = p.next;
  23757. p = p.next;
  23758. } while ( p !== start );
  23759. p.prevZ.nextZ = null;
  23760. p.prevZ = null;
  23761. sortLinked( p );
  23762. }
  23763. // Simon Tatham's linked list merge sort algorithm
  23764. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  23765. function sortLinked( list ) {
  23766. var i, p, q, e, tail, numMerges, pSize, qSize,
  23767. inSize = 1;
  23768. do {
  23769. p = list;
  23770. list = null;
  23771. tail = null;
  23772. numMerges = 0;
  23773. while ( p ) {
  23774. numMerges ++;
  23775. q = p;
  23776. pSize = 0;
  23777. for ( i = 0; i < inSize; i ++ ) {
  23778. pSize ++;
  23779. q = q.nextZ;
  23780. if ( ! q ) { break; }
  23781. }
  23782. qSize = inSize;
  23783. while ( pSize > 0 || ( qSize > 0 && q ) ) {
  23784. if ( pSize !== 0 && ( qSize === 0 || ! q || p.z <= q.z ) ) {
  23785. e = p;
  23786. p = p.nextZ;
  23787. pSize --;
  23788. } else {
  23789. e = q;
  23790. q = q.nextZ;
  23791. qSize --;
  23792. }
  23793. if ( tail ) { tail.nextZ = e; }
  23794. else { list = e; }
  23795. e.prevZ = tail;
  23796. tail = e;
  23797. }
  23798. p = q;
  23799. }
  23800. tail.nextZ = null;
  23801. inSize *= 2;
  23802. } while ( numMerges > 1 );
  23803. return list;
  23804. }
  23805. // z-order of a point given coords and inverse of the longer side of data bbox
  23806. function zOrder( x, y, minX, minY, invSize ) {
  23807. // coords are transformed into non-negative 15-bit integer range
  23808. x = 32767 * ( x - minX ) * invSize;
  23809. y = 32767 * ( y - minY ) * invSize;
  23810. x = ( x | ( x << 8 ) ) & 0x00FF00FF;
  23811. x = ( x | ( x << 4 ) ) & 0x0F0F0F0F;
  23812. x = ( x | ( x << 2 ) ) & 0x33333333;
  23813. x = ( x | ( x << 1 ) ) & 0x55555555;
  23814. y = ( y | ( y << 8 ) ) & 0x00FF00FF;
  23815. y = ( y | ( y << 4 ) ) & 0x0F0F0F0F;
  23816. y = ( y | ( y << 2 ) ) & 0x33333333;
  23817. y = ( y | ( y << 1 ) ) & 0x55555555;
  23818. return x | ( y << 1 );
  23819. }
  23820. // find the leftmost node of a polygon ring
  23821. function getLeftmost( start ) {
  23822. var p = start,
  23823. leftmost = start;
  23824. do {
  23825. if ( p.x < leftmost.x || ( p.x === leftmost.x && p.y < leftmost.y ) ) { leftmost = p; }
  23826. p = p.next;
  23827. } while ( p !== start );
  23828. return leftmost;
  23829. }
  23830. // check if a point lies within a convex triangle
  23831. function pointInTriangle( ax, ay, bx, by, cx, cy, px, py ) {
  23832. return ( cx - px ) * ( ay - py ) - ( ax - px ) * ( cy - py ) >= 0 &&
  23833. ( ax - px ) * ( by - py ) - ( bx - px ) * ( ay - py ) >= 0 &&
  23834. ( bx - px ) * ( cy - py ) - ( cx - px ) * ( by - py ) >= 0;
  23835. }
  23836. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  23837. function isValidDiagonal( a, b ) {
  23838. return a.next.i !== b.i && a.prev.i !== b.i && ! intersectsPolygon( a, b ) &&
  23839. locallyInside( a, b ) && locallyInside( b, a ) && middleInside( a, b );
  23840. }
  23841. // signed area of a triangle
  23842. function area( p, q, r ) {
  23843. return ( q.y - p.y ) * ( r.x - q.x ) - ( q.x - p.x ) * ( r.y - q.y );
  23844. }
  23845. // check if two points are equal
  23846. function equals( p1, p2 ) {
  23847. return p1.x === p2.x && p1.y === p2.y;
  23848. }
  23849. // check if two segments intersect
  23850. function intersects( p1, q1, p2, q2 ) {
  23851. if ( ( equals( p1, p2 ) && equals( q1, q2 ) ) ||
  23852. ( equals( p1, q2 ) && equals( p2, q1 ) ) ) { return true; }
  23853. return area( p1, q1, p2 ) > 0 !== area( p1, q1, q2 ) > 0 &&
  23854. area( p2, q2, p1 ) > 0 !== area( p2, q2, q1 ) > 0;
  23855. }
  23856. // check if a polygon diagonal intersects any polygon segments
  23857. function intersectsPolygon( a, b ) {
  23858. var p = a;
  23859. do {
  23860. if ( p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i &&
  23861. intersects( p, p.next, a, b ) ) { return true; }
  23862. p = p.next;
  23863. } while ( p !== a );
  23864. return false;
  23865. }
  23866. // check if a polygon diagonal is locally inside the polygon
  23867. function locallyInside( a, b ) {
  23868. return area( a.prev, a, a.next ) < 0 ?
  23869. area( a, b, a.next ) >= 0 && area( a, a.prev, b ) >= 0 :
  23870. area( a, b, a.prev ) < 0 || area( a, a.next, b ) < 0;
  23871. }
  23872. // check if the middle point of a polygon diagonal is inside the polygon
  23873. function middleInside( a, b ) {
  23874. var p = a,
  23875. inside = false,
  23876. px = ( a.x + b.x ) / 2,
  23877. py = ( a.y + b.y ) / 2;
  23878. do {
  23879. if ( ( ( p.y > py ) !== ( p.next.y > py ) ) && p.next.y !== p.y &&
  23880. ( px < ( p.next.x - p.x ) * ( py - p.y ) / ( p.next.y - p.y ) + p.x ) )
  23881. { inside = ! inside; }
  23882. p = p.next;
  23883. } while ( p !== a );
  23884. return inside;
  23885. }
  23886. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  23887. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  23888. function splitPolygon( a, b ) {
  23889. var a2 = new Node( a.i, a.x, a.y ),
  23890. b2 = new Node( b.i, b.x, b.y ),
  23891. an = a.next,
  23892. bp = b.prev;
  23893. a.next = b;
  23894. b.prev = a;
  23895. a2.next = an;
  23896. an.prev = a2;
  23897. b2.next = a2;
  23898. a2.prev = b2;
  23899. bp.next = b2;
  23900. b2.prev = bp;
  23901. return b2;
  23902. }
  23903. // create a node and optionally link it with previous one (in a circular doubly linked list)
  23904. function insertNode( i, x, y, last ) {
  23905. var p = new Node( i, x, y );
  23906. if ( ! last ) {
  23907. p.prev = p;
  23908. p.next = p;
  23909. } else {
  23910. p.next = last.next;
  23911. p.prev = last;
  23912. last.next.prev = p;
  23913. last.next = p;
  23914. }
  23915. return p;
  23916. }
  23917. function removeNode( p ) {
  23918. p.next.prev = p.prev;
  23919. p.prev.next = p.next;
  23920. if ( p.prevZ ) { p.prevZ.nextZ = p.nextZ; }
  23921. if ( p.nextZ ) { p.nextZ.prevZ = p.prevZ; }
  23922. }
  23923. function Node( i, x, y ) {
  23924. // vertex index in coordinates array
  23925. this.i = i;
  23926. // vertex coordinates
  23927. this.x = x;
  23928. this.y = y;
  23929. // previous and next vertex nodes in a polygon ring
  23930. this.prev = null;
  23931. this.next = null;
  23932. // z-order curve value
  23933. this.z = null;
  23934. // previous and next nodes in z-order
  23935. this.prevZ = null;
  23936. this.nextZ = null;
  23937. // indicates whether this is a steiner point
  23938. this.steiner = false;
  23939. }
  23940. function signedArea( data, start, end, dim ) {
  23941. var sum = 0;
  23942. for ( var i = start, j = end - dim; i < end; i += dim ) {
  23943. sum += ( data[ j ] - data[ i ] ) * ( data[ i + 1 ] + data[ j + 1 ] );
  23944. j = i;
  23945. }
  23946. return sum;
  23947. }
  23948. /**
  23949. * @author zz85 / http://www.lab4games.net/zz85/blog
  23950. */
  23951. var ShapeUtils = {
  23952. // calculate area of the contour polygon
  23953. area: function ( contour ) {
  23954. var n = contour.length;
  23955. var a = 0.0;
  23956. for ( var p = n - 1, q = 0; q < n; p = q ++ ) {
  23957. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  23958. }
  23959. return a * 0.5;
  23960. },
  23961. isClockWise: function ( pts ) {
  23962. return ShapeUtils.area( pts ) < 0;
  23963. },
  23964. triangulateShape: function ( contour, holes ) {
  23965. var vertices = []; // flat array of vertices like [ x0,y0, x1,y1, x2,y2, ... ]
  23966. var holeIndices = []; // array of hole indices
  23967. var faces = []; // final array of vertex indices like [ [ a,b,d ], [ b,c,d ] ]
  23968. removeDupEndPts( contour );
  23969. addContour( vertices, contour );
  23970. //
  23971. var holeIndex = contour.length;
  23972. holes.forEach( removeDupEndPts );
  23973. for ( var i = 0; i < holes.length; i ++ ) {
  23974. holeIndices.push( holeIndex );
  23975. holeIndex += holes[ i ].length;
  23976. addContour( vertices, holes[ i ] );
  23977. }
  23978. //
  23979. var triangles = Earcut.triangulate( vertices, holeIndices );
  23980. //
  23981. for ( var i = 0; i < triangles.length; i += 3 ) {
  23982. faces.push( triangles.slice( i, i + 3 ) );
  23983. }
  23984. return faces;
  23985. }
  23986. };
  23987. function removeDupEndPts( points ) {
  23988. var l = points.length;
  23989. if ( l > 2 && points[ l - 1 ].equals( points[ 0 ] ) ) {
  23990. points.pop();
  23991. }
  23992. }
  23993. function addContour( vertices, contour ) {
  23994. for ( var i = 0; i < contour.length; i ++ ) {
  23995. vertices.push( contour[ i ].x );
  23996. vertices.push( contour[ i ].y );
  23997. }
  23998. }
  23999. /**
  24000. * @author zz85 / http://www.lab4games.net/zz85/blog
  24001. *
  24002. * Creates extruded geometry from a path shape.
  24003. *
  24004. * parameters = {
  24005. *
  24006. * curveSegments: <int>, // number of points on the curves
  24007. * steps: <int>, // number of points for z-side extrusions / used for subdividing segments of extrude spline too
  24008. * depth: <float>, // Depth to extrude the shape
  24009. *
  24010. * bevelEnabled: <bool>, // turn on bevel
  24011. * bevelThickness: <float>, // how deep into the original shape bevel goes
  24012. * bevelSize: <float>, // how far from shape outline (including bevelOffset) is bevel
  24013. * bevelOffset: <float>, // how far from shape outline does bevel start
  24014. * bevelSegments: <int>, // number of bevel layers
  24015. *
  24016. * extrudePath: <THREE.Curve> // curve to extrude shape along
  24017. *
  24018. * UVGenerator: <Object> // object that provides UV generator functions
  24019. *
  24020. * }
  24021. */
  24022. // ExtrudeGeometry
  24023. function ExtrudeGeometry( shapes, options ) {
  24024. Geometry.call( this );
  24025. this.type = 'ExtrudeGeometry';
  24026. this.parameters = {
  24027. shapes: shapes,
  24028. options: options
  24029. };
  24030. this.fromBufferGeometry( new ExtrudeBufferGeometry( shapes, options ) );
  24031. this.mergeVertices();
  24032. }
  24033. ExtrudeGeometry.prototype = Object.create( Geometry.prototype );
  24034. ExtrudeGeometry.prototype.constructor = ExtrudeGeometry;
  24035. ExtrudeGeometry.prototype.toJSON = function () {
  24036. var data = Geometry.prototype.toJSON.call( this );
  24037. var shapes = this.parameters.shapes;
  24038. var options = this.parameters.options;
  24039. return toJSON( shapes, options, data );
  24040. };
  24041. // ExtrudeBufferGeometry
  24042. function ExtrudeBufferGeometry( shapes, options ) {
  24043. BufferGeometry.call( this );
  24044. this.type = 'ExtrudeBufferGeometry';
  24045. this.parameters = {
  24046. shapes: shapes,
  24047. options: options
  24048. };
  24049. shapes = Array.isArray( shapes ) ? shapes : [ shapes ];
  24050. var scope = this;
  24051. var verticesArray = [];
  24052. var uvArray = [];
  24053. for ( var i = 0, l = shapes.length; i < l; i ++ ) {
  24054. var shape = shapes[ i ];
  24055. addShape( shape );
  24056. }
  24057. // build geometry
  24058. this.setAttribute( 'position', new Float32BufferAttribute( verticesArray, 3 ) );
  24059. this.setAttribute( 'uv', new Float32BufferAttribute( uvArray, 2 ) );
  24060. this.computeVertexNormals();
  24061. // functions
  24062. function addShape( shape ) {
  24063. var placeholder = [];
  24064. // options
  24065. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  24066. var steps = options.steps !== undefined ? options.steps : 1;
  24067. var depth = options.depth !== undefined ? options.depth : 100;
  24068. var bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true;
  24069. var bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6;
  24070. var bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2;
  24071. var bevelOffset = options.bevelOffset !== undefined ? options.bevelOffset : 0;
  24072. var bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  24073. var extrudePath = options.extrudePath;
  24074. var uvgen = options.UVGenerator !== undefined ? options.UVGenerator : WorldUVGenerator;
  24075. // deprecated options
  24076. if ( options.amount !== undefined ) {
  24077. console.warn( 'THREE.ExtrudeBufferGeometry: amount has been renamed to depth.' );
  24078. depth = options.amount;
  24079. }
  24080. //
  24081. var extrudePts, extrudeByPath = false;
  24082. var splineTube, binormal, normal, position2;
  24083. if ( extrudePath ) {
  24084. extrudePts = extrudePath.getSpacedPoints( steps );
  24085. extrudeByPath = true;
  24086. bevelEnabled = false; // bevels not supported for path extrusion
  24087. // SETUP TNB variables
  24088. // TODO1 - have a .isClosed in spline?
  24089. splineTube = extrudePath.computeFrenetFrames( steps, false );
  24090. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  24091. binormal = new Vector3();
  24092. normal = new Vector3();
  24093. position2 = new Vector3();
  24094. }
  24095. // Safeguards if bevels are not enabled
  24096. if ( ! bevelEnabled ) {
  24097. bevelSegments = 0;
  24098. bevelThickness = 0;
  24099. bevelSize = 0;
  24100. bevelOffset = 0;
  24101. }
  24102. // Variables initialization
  24103. var ahole, h, hl; // looping of holes
  24104. var shapePoints = shape.extractPoints( curveSegments );
  24105. var vertices = shapePoints.shape;
  24106. var holes = shapePoints.holes;
  24107. var reverse = ! ShapeUtils.isClockWise( vertices );
  24108. if ( reverse ) {
  24109. vertices = vertices.reverse();
  24110. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  24111. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  24112. ahole = holes[ h ];
  24113. if ( ShapeUtils.isClockWise( ahole ) ) {
  24114. holes[ h ] = ahole.reverse();
  24115. }
  24116. }
  24117. }
  24118. var faces = ShapeUtils.triangulateShape( vertices, holes );
  24119. /* Vertices */
  24120. var contour = vertices; // vertices has all points but contour has only points of circumference
  24121. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  24122. ahole = holes[ h ];
  24123. vertices = vertices.concat( ahole );
  24124. }
  24125. function scalePt2( pt, vec, size ) {
  24126. if ( ! vec ) { console.error( "THREE.ExtrudeGeometry: vec does not exist" ); }
  24127. return vec.clone().multiplyScalar( size ).add( pt );
  24128. }
  24129. var b, bs, t, z,
  24130. vert, vlen = vertices.length,
  24131. face, flen = faces.length;
  24132. // Find directions for point movement
  24133. function getBevelVec( inPt, inPrev, inNext ) {
  24134. // computes for inPt the corresponding point inPt' on a new contour
  24135. // shifted by 1 unit (length of normalized vector) to the left
  24136. // if we walk along contour clockwise, this new contour is outside the old one
  24137. //
  24138. // inPt' is the intersection of the two lines parallel to the two
  24139. // adjacent edges of inPt at a distance of 1 unit on the left side.
  24140. var v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPt
  24141. // good reading for geometry algorithms (here: line-line intersection)
  24142. // http://geomalgorithms.com/a05-_intersect-1.html
  24143. var v_prev_x = inPt.x - inPrev.x,
  24144. v_prev_y = inPt.y - inPrev.y;
  24145. var v_next_x = inNext.x - inPt.x,
  24146. v_next_y = inNext.y - inPt.y;
  24147. var v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y );
  24148. // check for collinear edges
  24149. var collinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  24150. if ( Math.abs( collinear0 ) > Number.EPSILON ) {
  24151. // not collinear
  24152. // length of vectors for normalizing
  24153. var v_prev_len = Math.sqrt( v_prev_lensq );
  24154. var v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y );
  24155. // shift adjacent points by unit vectors to the left
  24156. var ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len );
  24157. var ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len );
  24158. var ptNextShift_x = ( inNext.x - v_next_y / v_next_len );
  24159. var ptNextShift_y = ( inNext.y + v_next_x / v_next_len );
  24160. // scaling factor for v_prev to intersection point
  24161. var sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y -
  24162. ( ptNextShift_y - ptPrevShift_y ) * v_next_x ) /
  24163. ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  24164. // vector from inPt to intersection point
  24165. v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x );
  24166. v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y );
  24167. // Don't normalize!, otherwise sharp corners become ugly
  24168. // but prevent crazy spikes
  24169. var v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y );
  24170. if ( v_trans_lensq <= 2 ) {
  24171. return new Vector2( v_trans_x, v_trans_y );
  24172. } else {
  24173. shrink_by = Math.sqrt( v_trans_lensq / 2 );
  24174. }
  24175. } else {
  24176. // handle special case of collinear edges
  24177. var direction_eq = false; // assumes: opposite
  24178. if ( v_prev_x > Number.EPSILON ) {
  24179. if ( v_next_x > Number.EPSILON ) {
  24180. direction_eq = true;
  24181. }
  24182. } else {
  24183. if ( v_prev_x < - Number.EPSILON ) {
  24184. if ( v_next_x < - Number.EPSILON ) {
  24185. direction_eq = true;
  24186. }
  24187. } else {
  24188. if ( Math.sign( v_prev_y ) === Math.sign( v_next_y ) ) {
  24189. direction_eq = true;
  24190. }
  24191. }
  24192. }
  24193. if ( direction_eq ) {
  24194. // console.log("Warning: lines are a straight sequence");
  24195. v_trans_x = - v_prev_y;
  24196. v_trans_y = v_prev_x;
  24197. shrink_by = Math.sqrt( v_prev_lensq );
  24198. } else {
  24199. // console.log("Warning: lines are a straight spike");
  24200. v_trans_x = v_prev_x;
  24201. v_trans_y = v_prev_y;
  24202. shrink_by = Math.sqrt( v_prev_lensq / 2 );
  24203. }
  24204. }
  24205. return new Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by );
  24206. }
  24207. var contourMovements = [];
  24208. for ( var i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  24209. if ( j === il ) { j = 0; }
  24210. if ( k === il ) { k = 0; }
  24211. // (j)---(i)---(k)
  24212. // console.log('i,j,k', i, j , k)
  24213. contourMovements[ i ] = getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  24214. }
  24215. var holesMovements = [],
  24216. oneHoleMovements, verticesMovements = contourMovements.concat();
  24217. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  24218. ahole = holes[ h ];
  24219. oneHoleMovements = [];
  24220. for ( i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  24221. if ( j === il ) { j = 0; }
  24222. if ( k === il ) { k = 0; }
  24223. // (j)---(i)---(k)
  24224. oneHoleMovements[ i ] = getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  24225. }
  24226. holesMovements.push( oneHoleMovements );
  24227. verticesMovements = verticesMovements.concat( oneHoleMovements );
  24228. }
  24229. // Loop bevelSegments, 1 for the front, 1 for the back
  24230. for ( b = 0; b < bevelSegments; b ++ ) {
  24231. //for ( b = bevelSegments; b > 0; b -- ) {
  24232. t = b / bevelSegments;
  24233. z = bevelThickness * Math.cos( t * Math.PI / 2 );
  24234. bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  24235. // contract shape
  24236. for ( i = 0, il = contour.length; i < il; i ++ ) {
  24237. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  24238. v( vert.x, vert.y, - z );
  24239. }
  24240. // expand holes
  24241. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  24242. ahole = holes[ h ];
  24243. oneHoleMovements = holesMovements[ h ];
  24244. for ( i = 0, il = ahole.length; i < il; i ++ ) {
  24245. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  24246. v( vert.x, vert.y, - z );
  24247. }
  24248. }
  24249. }
  24250. bs = bevelSize + bevelOffset;
  24251. // Back facing vertices
  24252. for ( i = 0; i < vlen; i ++ ) {
  24253. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  24254. if ( ! extrudeByPath ) {
  24255. v( vert.x, vert.y, 0 );
  24256. } else {
  24257. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  24258. normal.copy( splineTube.normals[ 0 ] ).multiplyScalar( vert.x );
  24259. binormal.copy( splineTube.binormals[ 0 ] ).multiplyScalar( vert.y );
  24260. position2.copy( extrudePts[ 0 ] ).add( normal ).add( binormal );
  24261. v( position2.x, position2.y, position2.z );
  24262. }
  24263. }
  24264. // Add stepped vertices...
  24265. // Including front facing vertices
  24266. var s;
  24267. for ( s = 1; s <= steps; s ++ ) {
  24268. for ( i = 0; i < vlen; i ++ ) {
  24269. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  24270. if ( ! extrudeByPath ) {
  24271. v( vert.x, vert.y, depth / steps * s );
  24272. } else {
  24273. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  24274. normal.copy( splineTube.normals[ s ] ).multiplyScalar( vert.x );
  24275. binormal.copy( splineTube.binormals[ s ] ).multiplyScalar( vert.y );
  24276. position2.copy( extrudePts[ s ] ).add( normal ).add( binormal );
  24277. v( position2.x, position2.y, position2.z );
  24278. }
  24279. }
  24280. }
  24281. // Add bevel segments planes
  24282. //for ( b = 1; b <= bevelSegments; b ++ ) {
  24283. for ( b = bevelSegments - 1; b >= 0; b -- ) {
  24284. t = b / bevelSegments;
  24285. z = bevelThickness * Math.cos( t * Math.PI / 2 );
  24286. bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  24287. // contract shape
  24288. for ( i = 0, il = contour.length; i < il; i ++ ) {
  24289. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  24290. v( vert.x, vert.y, depth + z );
  24291. }
  24292. // expand holes
  24293. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  24294. ahole = holes[ h ];
  24295. oneHoleMovements = holesMovements[ h ];
  24296. for ( i = 0, il = ahole.length; i < il; i ++ ) {
  24297. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  24298. if ( ! extrudeByPath ) {
  24299. v( vert.x, vert.y, depth + z );
  24300. } else {
  24301. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  24302. }
  24303. }
  24304. }
  24305. }
  24306. /* Faces */
  24307. // Top and bottom faces
  24308. buildLidFaces();
  24309. // Sides faces
  24310. buildSideFaces();
  24311. ///// Internal functions
  24312. function buildLidFaces() {
  24313. var start = verticesArray.length / 3;
  24314. if ( bevelEnabled ) {
  24315. var layer = 0; // steps + 1
  24316. var offset = vlen * layer;
  24317. // Bottom faces
  24318. for ( i = 0; i < flen; i ++ ) {
  24319. face = faces[ i ];
  24320. f3( face[ 2 ] + offset, face[ 1 ] + offset, face[ 0 ] + offset );
  24321. }
  24322. layer = steps + bevelSegments * 2;
  24323. offset = vlen * layer;
  24324. // Top faces
  24325. for ( i = 0; i < flen; i ++ ) {
  24326. face = faces[ i ];
  24327. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset );
  24328. }
  24329. } else {
  24330. // Bottom faces
  24331. for ( i = 0; i < flen; i ++ ) {
  24332. face = faces[ i ];
  24333. f3( face[ 2 ], face[ 1 ], face[ 0 ] );
  24334. }
  24335. // Top faces
  24336. for ( i = 0; i < flen; i ++ ) {
  24337. face = faces[ i ];
  24338. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps );
  24339. }
  24340. }
  24341. scope.addGroup( start, verticesArray.length / 3 - start, 0 );
  24342. }
  24343. // Create faces for the z-sides of the shape
  24344. function buildSideFaces() {
  24345. var start = verticesArray.length / 3;
  24346. var layeroffset = 0;
  24347. sidewalls( contour, layeroffset );
  24348. layeroffset += contour.length;
  24349. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  24350. ahole = holes[ h ];
  24351. sidewalls( ahole, layeroffset );
  24352. //, true
  24353. layeroffset += ahole.length;
  24354. }
  24355. scope.addGroup( start, verticesArray.length / 3 - start, 1 );
  24356. }
  24357. function sidewalls( contour, layeroffset ) {
  24358. var j, k;
  24359. i = contour.length;
  24360. while ( -- i >= 0 ) {
  24361. j = i;
  24362. k = i - 1;
  24363. if ( k < 0 ) { k = contour.length - 1; }
  24364. //console.log('b', i,j, i-1, k,vertices.length);
  24365. var s = 0,
  24366. sl = steps + bevelSegments * 2;
  24367. for ( s = 0; s < sl; s ++ ) {
  24368. var slen1 = vlen * s;
  24369. var slen2 = vlen * ( s + 1 );
  24370. var a = layeroffset + j + slen1,
  24371. b = layeroffset + k + slen1,
  24372. c = layeroffset + k + slen2,
  24373. d = layeroffset + j + slen2;
  24374. f4( a, b, c, d );
  24375. }
  24376. }
  24377. }
  24378. function v( x, y, z ) {
  24379. placeholder.push( x );
  24380. placeholder.push( y );
  24381. placeholder.push( z );
  24382. }
  24383. function f3( a, b, c ) {
  24384. addVertex( a );
  24385. addVertex( b );
  24386. addVertex( c );
  24387. var nextIndex = verticesArray.length / 3;
  24388. var uvs = uvgen.generateTopUV( scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  24389. addUV( uvs[ 0 ] );
  24390. addUV( uvs[ 1 ] );
  24391. addUV( uvs[ 2 ] );
  24392. }
  24393. function f4( a, b, c, d ) {
  24394. addVertex( a );
  24395. addVertex( b );
  24396. addVertex( d );
  24397. addVertex( b );
  24398. addVertex( c );
  24399. addVertex( d );
  24400. var nextIndex = verticesArray.length / 3;
  24401. var uvs = uvgen.generateSideWallUV( scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  24402. addUV( uvs[ 0 ] );
  24403. addUV( uvs[ 1 ] );
  24404. addUV( uvs[ 3 ] );
  24405. addUV( uvs[ 1 ] );
  24406. addUV( uvs[ 2 ] );
  24407. addUV( uvs[ 3 ] );
  24408. }
  24409. function addVertex( index ) {
  24410. verticesArray.push( placeholder[ index * 3 + 0 ] );
  24411. verticesArray.push( placeholder[ index * 3 + 1 ] );
  24412. verticesArray.push( placeholder[ index * 3 + 2 ] );
  24413. }
  24414. function addUV( vector2 ) {
  24415. uvArray.push( vector2.x );
  24416. uvArray.push( vector2.y );
  24417. }
  24418. }
  24419. }
  24420. ExtrudeBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  24421. ExtrudeBufferGeometry.prototype.constructor = ExtrudeBufferGeometry;
  24422. ExtrudeBufferGeometry.prototype.toJSON = function () {
  24423. var data = BufferGeometry.prototype.toJSON.call( this );
  24424. var shapes = this.parameters.shapes;
  24425. var options = this.parameters.options;
  24426. return toJSON( shapes, options, data );
  24427. };
  24428. //
  24429. var WorldUVGenerator = {
  24430. generateTopUV: function ( geometry, vertices, indexA, indexB, indexC ) {
  24431. var a_x = vertices[ indexA * 3 ];
  24432. var a_y = vertices[ indexA * 3 + 1 ];
  24433. var b_x = vertices[ indexB * 3 ];
  24434. var b_y = vertices[ indexB * 3 + 1 ];
  24435. var c_x = vertices[ indexC * 3 ];
  24436. var c_y = vertices[ indexC * 3 + 1 ];
  24437. return [
  24438. new Vector2( a_x, a_y ),
  24439. new Vector2( b_x, b_y ),
  24440. new Vector2( c_x, c_y )
  24441. ];
  24442. },
  24443. generateSideWallUV: function ( geometry, vertices, indexA, indexB, indexC, indexD ) {
  24444. var a_x = vertices[ indexA * 3 ];
  24445. var a_y = vertices[ indexA * 3 + 1 ];
  24446. var a_z = vertices[ indexA * 3 + 2 ];
  24447. var b_x = vertices[ indexB * 3 ];
  24448. var b_y = vertices[ indexB * 3 + 1 ];
  24449. var b_z = vertices[ indexB * 3 + 2 ];
  24450. var c_x = vertices[ indexC * 3 ];
  24451. var c_y = vertices[ indexC * 3 + 1 ];
  24452. var c_z = vertices[ indexC * 3 + 2 ];
  24453. var d_x = vertices[ indexD * 3 ];
  24454. var d_y = vertices[ indexD * 3 + 1 ];
  24455. var d_z = vertices[ indexD * 3 + 2 ];
  24456. if ( Math.abs( a_y - b_y ) < 0.01 ) {
  24457. return [
  24458. new Vector2( a_x, 1 - a_z ),
  24459. new Vector2( b_x, 1 - b_z ),
  24460. new Vector2( c_x, 1 - c_z ),
  24461. new Vector2( d_x, 1 - d_z )
  24462. ];
  24463. } else {
  24464. return [
  24465. new Vector2( a_y, 1 - a_z ),
  24466. new Vector2( b_y, 1 - b_z ),
  24467. new Vector2( c_y, 1 - c_z ),
  24468. new Vector2( d_y, 1 - d_z )
  24469. ];
  24470. }
  24471. }
  24472. };
  24473. function toJSON( shapes, options, data ) {
  24474. //
  24475. data.shapes = [];
  24476. if ( Array.isArray( shapes ) ) {
  24477. for ( var i = 0, l = shapes.length; i < l; i ++ ) {
  24478. var shape = shapes[ i ];
  24479. data.shapes.push( shape.uuid );
  24480. }
  24481. } else {
  24482. data.shapes.push( shapes.uuid );
  24483. }
  24484. //
  24485. if ( options.extrudePath !== undefined ) { data.options.extrudePath = options.extrudePath.toJSON(); }
  24486. return data;
  24487. }
  24488. /**
  24489. * @author zz85 / http://www.lab4games.net/zz85/blog
  24490. * @author alteredq / http://alteredqualia.com/
  24491. *
  24492. * Text = 3D Text
  24493. *
  24494. * parameters = {
  24495. * font: <THREE.Font>, // font
  24496. *
  24497. * size: <float>, // size of the text
  24498. * height: <float>, // thickness to extrude text
  24499. * curveSegments: <int>, // number of points on the curves
  24500. *
  24501. * bevelEnabled: <bool>, // turn on bevel
  24502. * bevelThickness: <float>, // how deep into text bevel goes
  24503. * bevelSize: <float>, // how far from text outline (including bevelOffset) is bevel
  24504. * bevelOffset: <float> // how far from text outline does bevel start
  24505. * }
  24506. */
  24507. // TextGeometry
  24508. function TextGeometry( text, parameters ) {
  24509. Geometry.call( this );
  24510. this.type = 'TextGeometry';
  24511. this.parameters = {
  24512. text: text,
  24513. parameters: parameters
  24514. };
  24515. this.fromBufferGeometry( new TextBufferGeometry( text, parameters ) );
  24516. this.mergeVertices();
  24517. }
  24518. TextGeometry.prototype = Object.create( Geometry.prototype );
  24519. TextGeometry.prototype.constructor = TextGeometry;
  24520. // TextBufferGeometry
  24521. function TextBufferGeometry( text, parameters ) {
  24522. parameters = parameters || {};
  24523. var font = parameters.font;
  24524. if ( ! ( font && font.isFont ) ) {
  24525. console.error( 'THREE.TextGeometry: font parameter is not an instance of THREE.Font.' );
  24526. return new Geometry();
  24527. }
  24528. var shapes = font.generateShapes( text, parameters.size );
  24529. // translate parameters to ExtrudeGeometry API
  24530. parameters.depth = parameters.height !== undefined ? parameters.height : 50;
  24531. // defaults
  24532. if ( parameters.bevelThickness === undefined ) { parameters.bevelThickness = 10; }
  24533. if ( parameters.bevelSize === undefined ) { parameters.bevelSize = 8; }
  24534. if ( parameters.bevelEnabled === undefined ) { parameters.bevelEnabled = false; }
  24535. ExtrudeBufferGeometry.call( this, shapes, parameters );
  24536. this.type = 'TextBufferGeometry';
  24537. }
  24538. TextBufferGeometry.prototype = Object.create( ExtrudeBufferGeometry.prototype );
  24539. TextBufferGeometry.prototype.constructor = TextBufferGeometry;
  24540. /**
  24541. * @author mrdoob / http://mrdoob.com/
  24542. * @author benaadams / https://twitter.com/ben_a_adams
  24543. * @author Mugen87 / https://github.com/Mugen87
  24544. */
  24545. // SphereGeometry
  24546. function SphereGeometry( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {
  24547. Geometry.call( this );
  24548. this.type = 'SphereGeometry';
  24549. this.parameters = {
  24550. radius: radius,
  24551. widthSegments: widthSegments,
  24552. heightSegments: heightSegments,
  24553. phiStart: phiStart,
  24554. phiLength: phiLength,
  24555. thetaStart: thetaStart,
  24556. thetaLength: thetaLength
  24557. };
  24558. this.fromBufferGeometry( new SphereBufferGeometry( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) );
  24559. this.mergeVertices();
  24560. }
  24561. SphereGeometry.prototype = Object.create( Geometry.prototype );
  24562. SphereGeometry.prototype.constructor = SphereGeometry;
  24563. // SphereBufferGeometry
  24564. function SphereBufferGeometry( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {
  24565. BufferGeometry.call( this );
  24566. this.type = 'SphereBufferGeometry';
  24567. this.parameters = {
  24568. radius: radius,
  24569. widthSegments: widthSegments,
  24570. heightSegments: heightSegments,
  24571. phiStart: phiStart,
  24572. phiLength: phiLength,
  24573. thetaStart: thetaStart,
  24574. thetaLength: thetaLength
  24575. };
  24576. radius = radius || 1;
  24577. widthSegments = Math.max( 3, Math.floor( widthSegments ) || 8 );
  24578. heightSegments = Math.max( 2, Math.floor( heightSegments ) || 6 );
  24579. phiStart = phiStart !== undefined ? phiStart : 0;
  24580. phiLength = phiLength !== undefined ? phiLength : Math.PI * 2;
  24581. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  24582. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI;
  24583. var thetaEnd = Math.min( thetaStart + thetaLength, Math.PI );
  24584. var ix, iy;
  24585. var index = 0;
  24586. var grid = [];
  24587. var vertex = new Vector3();
  24588. var normal = new Vector3();
  24589. // buffers
  24590. var indices = [];
  24591. var vertices = [];
  24592. var normals = [];
  24593. var uvs = [];
  24594. // generate vertices, normals and uvs
  24595. for ( iy = 0; iy <= heightSegments; iy ++ ) {
  24596. var verticesRow = [];
  24597. var v = iy / heightSegments;
  24598. // special case for the poles
  24599. var uOffset = 0;
  24600. if ( iy == 0 && thetaStart == 0 ) {
  24601. uOffset = 0.5 / widthSegments;
  24602. } else if ( iy == heightSegments && thetaEnd == Math.PI ) {
  24603. uOffset = - 0.5 / widthSegments;
  24604. }
  24605. for ( ix = 0; ix <= widthSegments; ix ++ ) {
  24606. var u = ix / widthSegments;
  24607. // vertex
  24608. vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  24609. vertex.y = radius * Math.cos( thetaStart + v * thetaLength );
  24610. vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  24611. vertices.push( vertex.x, vertex.y, vertex.z );
  24612. // normal
  24613. normal.copy( vertex ).normalize();
  24614. normals.push( normal.x, normal.y, normal.z );
  24615. // uv
  24616. uvs.push( u + uOffset, 1 - v );
  24617. verticesRow.push( index ++ );
  24618. }
  24619. grid.push( verticesRow );
  24620. }
  24621. // indices
  24622. for ( iy = 0; iy < heightSegments; iy ++ ) {
  24623. for ( ix = 0; ix < widthSegments; ix ++ ) {
  24624. var a = grid[ iy ][ ix + 1 ];
  24625. var b = grid[ iy ][ ix ];
  24626. var c = grid[ iy + 1 ][ ix ];
  24627. var d = grid[ iy + 1 ][ ix + 1 ];
  24628. if ( iy !== 0 || thetaStart > 0 ) { indices.push( a, b, d ); }
  24629. if ( iy !== heightSegments - 1 || thetaEnd < Math.PI ) { indices.push( b, c, d ); }
  24630. }
  24631. }
  24632. // build geometry
  24633. this.setIndex( indices );
  24634. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  24635. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  24636. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  24637. }
  24638. SphereBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  24639. SphereBufferGeometry.prototype.constructor = SphereBufferGeometry;
  24640. /**
  24641. * @author Kaleb Murphy
  24642. * @author Mugen87 / https://github.com/Mugen87
  24643. */
  24644. // RingGeometry
  24645. function RingGeometry( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) {
  24646. Geometry.call( this );
  24647. this.type = 'RingGeometry';
  24648. this.parameters = {
  24649. innerRadius: innerRadius,
  24650. outerRadius: outerRadius,
  24651. thetaSegments: thetaSegments,
  24652. phiSegments: phiSegments,
  24653. thetaStart: thetaStart,
  24654. thetaLength: thetaLength
  24655. };
  24656. this.fromBufferGeometry( new RingBufferGeometry( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) );
  24657. this.mergeVertices();
  24658. }
  24659. RingGeometry.prototype = Object.create( Geometry.prototype );
  24660. RingGeometry.prototype.constructor = RingGeometry;
  24661. // RingBufferGeometry
  24662. function RingBufferGeometry( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) {
  24663. BufferGeometry.call( this );
  24664. this.type = 'RingBufferGeometry';
  24665. this.parameters = {
  24666. innerRadius: innerRadius,
  24667. outerRadius: outerRadius,
  24668. thetaSegments: thetaSegments,
  24669. phiSegments: phiSegments,
  24670. thetaStart: thetaStart,
  24671. thetaLength: thetaLength
  24672. };
  24673. innerRadius = innerRadius || 0.5;
  24674. outerRadius = outerRadius || 1;
  24675. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  24676. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  24677. thetaSegments = thetaSegments !== undefined ? Math.max( 3, thetaSegments ) : 8;
  24678. phiSegments = phiSegments !== undefined ? Math.max( 1, phiSegments ) : 1;
  24679. // buffers
  24680. var indices = [];
  24681. var vertices = [];
  24682. var normals = [];
  24683. var uvs = [];
  24684. // some helper variables
  24685. var segment;
  24686. var radius = innerRadius;
  24687. var radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
  24688. var vertex = new Vector3();
  24689. var uv = new Vector2();
  24690. var j, i;
  24691. // generate vertices, normals and uvs
  24692. for ( j = 0; j <= phiSegments; j ++ ) {
  24693. for ( i = 0; i <= thetaSegments; i ++ ) {
  24694. // values are generate from the inside of the ring to the outside
  24695. segment = thetaStart + i / thetaSegments * thetaLength;
  24696. // vertex
  24697. vertex.x = radius * Math.cos( segment );
  24698. vertex.y = radius * Math.sin( segment );
  24699. vertices.push( vertex.x, vertex.y, vertex.z );
  24700. // normal
  24701. normals.push( 0, 0, 1 );
  24702. // uv
  24703. uv.x = ( vertex.x / outerRadius + 1 ) / 2;
  24704. uv.y = ( vertex.y / outerRadius + 1 ) / 2;
  24705. uvs.push( uv.x, uv.y );
  24706. }
  24707. // increase the radius for next row of vertices
  24708. radius += radiusStep;
  24709. }
  24710. // indices
  24711. for ( j = 0; j < phiSegments; j ++ ) {
  24712. var thetaSegmentLevel = j * ( thetaSegments + 1 );
  24713. for ( i = 0; i < thetaSegments; i ++ ) {
  24714. segment = i + thetaSegmentLevel;
  24715. var a = segment;
  24716. var b = segment + thetaSegments + 1;
  24717. var c = segment + thetaSegments + 2;
  24718. var d = segment + 1;
  24719. // faces
  24720. indices.push( a, b, d );
  24721. indices.push( b, c, d );
  24722. }
  24723. }
  24724. // build geometry
  24725. this.setIndex( indices );
  24726. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  24727. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  24728. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  24729. }
  24730. RingBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  24731. RingBufferGeometry.prototype.constructor = RingBufferGeometry;
  24732. /**
  24733. * @author zz85 / https://github.com/zz85
  24734. * @author bhouston / http://clara.io
  24735. * @author Mugen87 / https://github.com/Mugen87
  24736. */
  24737. // LatheGeometry
  24738. function LatheGeometry( points, segments, phiStart, phiLength ) {
  24739. Geometry.call( this );
  24740. this.type = 'LatheGeometry';
  24741. this.parameters = {
  24742. points: points,
  24743. segments: segments,
  24744. phiStart: phiStart,
  24745. phiLength: phiLength
  24746. };
  24747. this.fromBufferGeometry( new LatheBufferGeometry( points, segments, phiStart, phiLength ) );
  24748. this.mergeVertices();
  24749. }
  24750. LatheGeometry.prototype = Object.create( Geometry.prototype );
  24751. LatheGeometry.prototype.constructor = LatheGeometry;
  24752. // LatheBufferGeometry
  24753. function LatheBufferGeometry( points, segments, phiStart, phiLength ) {
  24754. BufferGeometry.call( this );
  24755. this.type = 'LatheBufferGeometry';
  24756. this.parameters = {
  24757. points: points,
  24758. segments: segments,
  24759. phiStart: phiStart,
  24760. phiLength: phiLength
  24761. };
  24762. segments = Math.floor( segments ) || 12;
  24763. phiStart = phiStart || 0;
  24764. phiLength = phiLength || Math.PI * 2;
  24765. // clamp phiLength so it's in range of [ 0, 2PI ]
  24766. phiLength = MathUtils.clamp( phiLength, 0, Math.PI * 2 );
  24767. // buffers
  24768. var indices = [];
  24769. var vertices = [];
  24770. var uvs = [];
  24771. // helper variables
  24772. var base;
  24773. var inverseSegments = 1.0 / segments;
  24774. var vertex = new Vector3();
  24775. var uv = new Vector2();
  24776. var i, j;
  24777. // generate vertices and uvs
  24778. for ( i = 0; i <= segments; i ++ ) {
  24779. var phi = phiStart + i * inverseSegments * phiLength;
  24780. var sin = Math.sin( phi );
  24781. var cos = Math.cos( phi );
  24782. for ( j = 0; j <= ( points.length - 1 ); j ++ ) {
  24783. // vertex
  24784. vertex.x = points[ j ].x * sin;
  24785. vertex.y = points[ j ].y;
  24786. vertex.z = points[ j ].x * cos;
  24787. vertices.push( vertex.x, vertex.y, vertex.z );
  24788. // uv
  24789. uv.x = i / segments;
  24790. uv.y = j / ( points.length - 1 );
  24791. uvs.push( uv.x, uv.y );
  24792. }
  24793. }
  24794. // indices
  24795. for ( i = 0; i < segments; i ++ ) {
  24796. for ( j = 0; j < ( points.length - 1 ); j ++ ) {
  24797. base = j + i * points.length;
  24798. var a = base;
  24799. var b = base + points.length;
  24800. var c = base + points.length + 1;
  24801. var d = base + 1;
  24802. // faces
  24803. indices.push( a, b, d );
  24804. indices.push( b, c, d );
  24805. }
  24806. }
  24807. // build geometry
  24808. this.setIndex( indices );
  24809. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  24810. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  24811. // generate normals
  24812. this.computeVertexNormals();
  24813. // if the geometry is closed, we need to average the normals along the seam.
  24814. // because the corresponding vertices are identical (but still have different UVs).
  24815. if ( phiLength === Math.PI * 2 ) {
  24816. var normals = this.attributes.normal.array;
  24817. var n1 = new Vector3();
  24818. var n2 = new Vector3();
  24819. var n = new Vector3();
  24820. // this is the buffer offset for the last line of vertices
  24821. base = segments * points.length * 3;
  24822. for ( i = 0, j = 0; i < points.length; i ++, j += 3 ) {
  24823. // select the normal of the vertex in the first line
  24824. n1.x = normals[ j + 0 ];
  24825. n1.y = normals[ j + 1 ];
  24826. n1.z = normals[ j + 2 ];
  24827. // select the normal of the vertex in the last line
  24828. n2.x = normals[ base + j + 0 ];
  24829. n2.y = normals[ base + j + 1 ];
  24830. n2.z = normals[ base + j + 2 ];
  24831. // average normals
  24832. n.addVectors( n1, n2 ).normalize();
  24833. // assign the new values to both normals
  24834. normals[ j + 0 ] = normals[ base + j + 0 ] = n.x;
  24835. normals[ j + 1 ] = normals[ base + j + 1 ] = n.y;
  24836. normals[ j + 2 ] = normals[ base + j + 2 ] = n.z;
  24837. }
  24838. }
  24839. }
  24840. LatheBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  24841. LatheBufferGeometry.prototype.constructor = LatheBufferGeometry;
  24842. /**
  24843. * @author jonobr1 / http://jonobr1.com
  24844. * @author Mugen87 / https://github.com/Mugen87
  24845. */
  24846. // ShapeGeometry
  24847. function ShapeGeometry( shapes, curveSegments ) {
  24848. Geometry.call( this );
  24849. this.type = 'ShapeGeometry';
  24850. if ( typeof curveSegments === 'object' ) {
  24851. console.warn( 'THREE.ShapeGeometry: Options parameter has been removed.' );
  24852. curveSegments = curveSegments.curveSegments;
  24853. }
  24854. this.parameters = {
  24855. shapes: shapes,
  24856. curveSegments: curveSegments
  24857. };
  24858. this.fromBufferGeometry( new ShapeBufferGeometry( shapes, curveSegments ) );
  24859. this.mergeVertices();
  24860. }
  24861. ShapeGeometry.prototype = Object.create( Geometry.prototype );
  24862. ShapeGeometry.prototype.constructor = ShapeGeometry;
  24863. ShapeGeometry.prototype.toJSON = function () {
  24864. var data = Geometry.prototype.toJSON.call( this );
  24865. var shapes = this.parameters.shapes;
  24866. return toJSON$1( shapes, data );
  24867. };
  24868. // ShapeBufferGeometry
  24869. function ShapeBufferGeometry( shapes, curveSegments ) {
  24870. BufferGeometry.call( this );
  24871. this.type = 'ShapeBufferGeometry';
  24872. this.parameters = {
  24873. shapes: shapes,
  24874. curveSegments: curveSegments
  24875. };
  24876. curveSegments = curveSegments || 12;
  24877. // buffers
  24878. var indices = [];
  24879. var vertices = [];
  24880. var normals = [];
  24881. var uvs = [];
  24882. // helper variables
  24883. var groupStart = 0;
  24884. var groupCount = 0;
  24885. // allow single and array values for "shapes" parameter
  24886. if ( Array.isArray( shapes ) === false ) {
  24887. addShape( shapes );
  24888. } else {
  24889. for ( var i = 0; i < shapes.length; i ++ ) {
  24890. addShape( shapes[ i ] );
  24891. this.addGroup( groupStart, groupCount, i ); // enables MultiMaterial support
  24892. groupStart += groupCount;
  24893. groupCount = 0;
  24894. }
  24895. }
  24896. // build geometry
  24897. this.setIndex( indices );
  24898. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  24899. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  24900. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  24901. // helper functions
  24902. function addShape( shape ) {
  24903. var i, l, shapeHole;
  24904. var indexOffset = vertices.length / 3;
  24905. var points = shape.extractPoints( curveSegments );
  24906. var shapeVertices = points.shape;
  24907. var shapeHoles = points.holes;
  24908. // check direction of vertices
  24909. if ( ShapeUtils.isClockWise( shapeVertices ) === false ) {
  24910. shapeVertices = shapeVertices.reverse();
  24911. }
  24912. for ( i = 0, l = shapeHoles.length; i < l; i ++ ) {
  24913. shapeHole = shapeHoles[ i ];
  24914. if ( ShapeUtils.isClockWise( shapeHole ) === true ) {
  24915. shapeHoles[ i ] = shapeHole.reverse();
  24916. }
  24917. }
  24918. var faces = ShapeUtils.triangulateShape( shapeVertices, shapeHoles );
  24919. // join vertices of inner and outer paths to a single array
  24920. for ( i = 0, l = shapeHoles.length; i < l; i ++ ) {
  24921. shapeHole = shapeHoles[ i ];
  24922. shapeVertices = shapeVertices.concat( shapeHole );
  24923. }
  24924. // vertices, normals, uvs
  24925. for ( i = 0, l = shapeVertices.length; i < l; i ++ ) {
  24926. var vertex = shapeVertices[ i ];
  24927. vertices.push( vertex.x, vertex.y, 0 );
  24928. normals.push( 0, 0, 1 );
  24929. uvs.push( vertex.x, vertex.y ); // world uvs
  24930. }
  24931. // incides
  24932. for ( i = 0, l = faces.length; i < l; i ++ ) {
  24933. var face = faces[ i ];
  24934. var a = face[ 0 ] + indexOffset;
  24935. var b = face[ 1 ] + indexOffset;
  24936. var c = face[ 2 ] + indexOffset;
  24937. indices.push( a, b, c );
  24938. groupCount += 3;
  24939. }
  24940. }
  24941. }
  24942. ShapeBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  24943. ShapeBufferGeometry.prototype.constructor = ShapeBufferGeometry;
  24944. ShapeBufferGeometry.prototype.toJSON = function () {
  24945. var data = BufferGeometry.prototype.toJSON.call( this );
  24946. var shapes = this.parameters.shapes;
  24947. return toJSON$1( shapes, data );
  24948. };
  24949. //
  24950. function toJSON$1( shapes, data ) {
  24951. data.shapes = [];
  24952. if ( Array.isArray( shapes ) ) {
  24953. for ( var i = 0, l = shapes.length; i < l; i ++ ) {
  24954. var shape = shapes[ i ];
  24955. data.shapes.push( shape.uuid );
  24956. }
  24957. } else {
  24958. data.shapes.push( shapes.uuid );
  24959. }
  24960. return data;
  24961. }
  24962. /**
  24963. * @author WestLangley / http://github.com/WestLangley
  24964. * @author Mugen87 / https://github.com/Mugen87
  24965. */
  24966. function EdgesGeometry( geometry, thresholdAngle ) {
  24967. BufferGeometry.call( this );
  24968. this.type = 'EdgesGeometry';
  24969. this.parameters = {
  24970. thresholdAngle: thresholdAngle
  24971. };
  24972. thresholdAngle = ( thresholdAngle !== undefined ) ? thresholdAngle : 1;
  24973. // buffer
  24974. var vertices = [];
  24975. // helper variables
  24976. var thresholdDot = Math.cos( MathUtils.DEG2RAD * thresholdAngle );
  24977. var edge = [ 0, 0 ], edges = {}, edge1, edge2;
  24978. var key, keys = [ 'a', 'b', 'c' ];
  24979. // prepare source geometry
  24980. var geometry2;
  24981. if ( geometry.isBufferGeometry ) {
  24982. geometry2 = new Geometry();
  24983. geometry2.fromBufferGeometry( geometry );
  24984. } else {
  24985. geometry2 = geometry.clone();
  24986. }
  24987. geometry2.mergeVertices();
  24988. geometry2.computeFaceNormals();
  24989. var sourceVertices = geometry2.vertices;
  24990. var faces = geometry2.faces;
  24991. // now create a data structure where each entry represents an edge with its adjoining faces
  24992. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  24993. var face = faces[ i ];
  24994. for ( var j = 0; j < 3; j ++ ) {
  24995. edge1 = face[ keys[ j ] ];
  24996. edge2 = face[ keys[ ( j + 1 ) % 3 ] ];
  24997. edge[ 0 ] = Math.min( edge1, edge2 );
  24998. edge[ 1 ] = Math.max( edge1, edge2 );
  24999. key = edge[ 0 ] + ',' + edge[ 1 ];
  25000. if ( edges[ key ] === undefined ) {
  25001. edges[ key ] = { index1: edge[ 0 ], index2: edge[ 1 ], face1: i, face2: undefined };
  25002. } else {
  25003. edges[ key ].face2 = i;
  25004. }
  25005. }
  25006. }
  25007. // generate vertices
  25008. for ( key in edges ) {
  25009. var e = edges[ key ];
  25010. // an edge is only rendered if the angle (in degrees) between the face normals of the adjoining faces exceeds this value. default = 1 degree.
  25011. if ( e.face2 === undefined || faces[ e.face1 ].normal.dot( faces[ e.face2 ].normal ) <= thresholdDot ) {
  25012. var vertex = sourceVertices[ e.index1 ];
  25013. vertices.push( vertex.x, vertex.y, vertex.z );
  25014. vertex = sourceVertices[ e.index2 ];
  25015. vertices.push( vertex.x, vertex.y, vertex.z );
  25016. }
  25017. }
  25018. // build geometry
  25019. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  25020. }
  25021. EdgesGeometry.prototype = Object.create( BufferGeometry.prototype );
  25022. EdgesGeometry.prototype.constructor = EdgesGeometry;
  25023. /**
  25024. * @author mrdoob / http://mrdoob.com/
  25025. * @author Mugen87 / https://github.com/Mugen87
  25026. */
  25027. // CylinderGeometry
  25028. function CylinderGeometry( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  25029. Geometry.call( this );
  25030. this.type = 'CylinderGeometry';
  25031. this.parameters = {
  25032. radiusTop: radiusTop,
  25033. radiusBottom: radiusBottom,
  25034. height: height,
  25035. radialSegments: radialSegments,
  25036. heightSegments: heightSegments,
  25037. openEnded: openEnded,
  25038. thetaStart: thetaStart,
  25039. thetaLength: thetaLength
  25040. };
  25041. this.fromBufferGeometry( new CylinderBufferGeometry( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) );
  25042. this.mergeVertices();
  25043. }
  25044. CylinderGeometry.prototype = Object.create( Geometry.prototype );
  25045. CylinderGeometry.prototype.constructor = CylinderGeometry;
  25046. // CylinderBufferGeometry
  25047. function CylinderBufferGeometry( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  25048. BufferGeometry.call( this );
  25049. this.type = 'CylinderBufferGeometry';
  25050. this.parameters = {
  25051. radiusTop: radiusTop,
  25052. radiusBottom: radiusBottom,
  25053. height: height,
  25054. radialSegments: radialSegments,
  25055. heightSegments: heightSegments,
  25056. openEnded: openEnded,
  25057. thetaStart: thetaStart,
  25058. thetaLength: thetaLength
  25059. };
  25060. var scope = this;
  25061. radiusTop = radiusTop !== undefined ? radiusTop : 1;
  25062. radiusBottom = radiusBottom !== undefined ? radiusBottom : 1;
  25063. height = height || 1;
  25064. radialSegments = Math.floor( radialSegments ) || 8;
  25065. heightSegments = Math.floor( heightSegments ) || 1;
  25066. openEnded = openEnded !== undefined ? openEnded : false;
  25067. thetaStart = thetaStart !== undefined ? thetaStart : 0.0;
  25068. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  25069. // buffers
  25070. var indices = [];
  25071. var vertices = [];
  25072. var normals = [];
  25073. var uvs = [];
  25074. // helper variables
  25075. var index = 0;
  25076. var indexArray = [];
  25077. var halfHeight = height / 2;
  25078. var groupStart = 0;
  25079. // generate geometry
  25080. generateTorso();
  25081. if ( openEnded === false ) {
  25082. if ( radiusTop > 0 ) { generateCap( true ); }
  25083. if ( radiusBottom > 0 ) { generateCap( false ); }
  25084. }
  25085. // build geometry
  25086. this.setIndex( indices );
  25087. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  25088. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  25089. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  25090. function generateTorso() {
  25091. var x, y;
  25092. var normal = new Vector3();
  25093. var vertex = new Vector3();
  25094. var groupCount = 0;
  25095. // this will be used to calculate the normal
  25096. var slope = ( radiusBottom - radiusTop ) / height;
  25097. // generate vertices, normals and uvs
  25098. for ( y = 0; y <= heightSegments; y ++ ) {
  25099. var indexRow = [];
  25100. var v = y / heightSegments;
  25101. // calculate the radius of the current row
  25102. var radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  25103. for ( x = 0; x <= radialSegments; x ++ ) {
  25104. var u = x / radialSegments;
  25105. var theta = u * thetaLength + thetaStart;
  25106. var sinTheta = Math.sin( theta );
  25107. var cosTheta = Math.cos( theta );
  25108. // vertex
  25109. vertex.x = radius * sinTheta;
  25110. vertex.y = - v * height + halfHeight;
  25111. vertex.z = radius * cosTheta;
  25112. vertices.push( vertex.x, vertex.y, vertex.z );
  25113. // normal
  25114. normal.set( sinTheta, slope, cosTheta ).normalize();
  25115. normals.push( normal.x, normal.y, normal.z );
  25116. // uv
  25117. uvs.push( u, 1 - v );
  25118. // save index of vertex in respective row
  25119. indexRow.push( index ++ );
  25120. }
  25121. // now save vertices of the row in our index array
  25122. indexArray.push( indexRow );
  25123. }
  25124. // generate indices
  25125. for ( x = 0; x < radialSegments; x ++ ) {
  25126. for ( y = 0; y < heightSegments; y ++ ) {
  25127. // we use the index array to access the correct indices
  25128. var a = indexArray[ y ][ x ];
  25129. var b = indexArray[ y + 1 ][ x ];
  25130. var c = indexArray[ y + 1 ][ x + 1 ];
  25131. var d = indexArray[ y ][ x + 1 ];
  25132. // faces
  25133. indices.push( a, b, d );
  25134. indices.push( b, c, d );
  25135. // update group counter
  25136. groupCount += 6;
  25137. }
  25138. }
  25139. // add a group to the geometry. this will ensure multi material support
  25140. scope.addGroup( groupStart, groupCount, 0 );
  25141. // calculate new start value for groups
  25142. groupStart += groupCount;
  25143. }
  25144. function generateCap( top ) {
  25145. var x, centerIndexStart, centerIndexEnd;
  25146. var uv = new Vector2();
  25147. var vertex = new Vector3();
  25148. var groupCount = 0;
  25149. var radius = ( top === true ) ? radiusTop : radiusBottom;
  25150. var sign = ( top === true ) ? 1 : - 1;
  25151. // save the index of the first center vertex
  25152. centerIndexStart = index;
  25153. // first we generate the center vertex data of the cap.
  25154. // because the geometry needs one set of uvs per face,
  25155. // we must generate a center vertex per face/segment
  25156. for ( x = 1; x <= radialSegments; x ++ ) {
  25157. // vertex
  25158. vertices.push( 0, halfHeight * sign, 0 );
  25159. // normal
  25160. normals.push( 0, sign, 0 );
  25161. // uv
  25162. uvs.push( 0.5, 0.5 );
  25163. // increase index
  25164. index ++;
  25165. }
  25166. // save the index of the last center vertex
  25167. centerIndexEnd = index;
  25168. // now we generate the surrounding vertices, normals and uvs
  25169. for ( x = 0; x <= radialSegments; x ++ ) {
  25170. var u = x / radialSegments;
  25171. var theta = u * thetaLength + thetaStart;
  25172. var cosTheta = Math.cos( theta );
  25173. var sinTheta = Math.sin( theta );
  25174. // vertex
  25175. vertex.x = radius * sinTheta;
  25176. vertex.y = halfHeight * sign;
  25177. vertex.z = radius * cosTheta;
  25178. vertices.push( vertex.x, vertex.y, vertex.z );
  25179. // normal
  25180. normals.push( 0, sign, 0 );
  25181. // uv
  25182. uv.x = ( cosTheta * 0.5 ) + 0.5;
  25183. uv.y = ( sinTheta * 0.5 * sign ) + 0.5;
  25184. uvs.push( uv.x, uv.y );
  25185. // increase index
  25186. index ++;
  25187. }
  25188. // generate indices
  25189. for ( x = 0; x < radialSegments; x ++ ) {
  25190. var c = centerIndexStart + x;
  25191. var i = centerIndexEnd + x;
  25192. if ( top === true ) {
  25193. // face top
  25194. indices.push( i, i + 1, c );
  25195. } else {
  25196. // face bottom
  25197. indices.push( i + 1, i, c );
  25198. }
  25199. groupCount += 3;
  25200. }
  25201. // add a group to the geometry. this will ensure multi material support
  25202. scope.addGroup( groupStart, groupCount, top === true ? 1 : 2 );
  25203. // calculate new start value for groups
  25204. groupStart += groupCount;
  25205. }
  25206. }
  25207. CylinderBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  25208. CylinderBufferGeometry.prototype.constructor = CylinderBufferGeometry;
  25209. /**
  25210. * @author abelnation / http://github.com/abelnation
  25211. */
  25212. // ConeGeometry
  25213. function ConeGeometry( radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  25214. CylinderGeometry.call( this, 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  25215. this.type = 'ConeGeometry';
  25216. this.parameters = {
  25217. radius: radius,
  25218. height: height,
  25219. radialSegments: radialSegments,
  25220. heightSegments: heightSegments,
  25221. openEnded: openEnded,
  25222. thetaStart: thetaStart,
  25223. thetaLength: thetaLength
  25224. };
  25225. }
  25226. ConeGeometry.prototype = Object.create( CylinderGeometry.prototype );
  25227. ConeGeometry.prototype.constructor = ConeGeometry;
  25228. // ConeBufferGeometry
  25229. function ConeBufferGeometry( radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  25230. CylinderBufferGeometry.call( this, 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  25231. this.type = 'ConeBufferGeometry';
  25232. this.parameters = {
  25233. radius: radius,
  25234. height: height,
  25235. radialSegments: radialSegments,
  25236. heightSegments: heightSegments,
  25237. openEnded: openEnded,
  25238. thetaStart: thetaStart,
  25239. thetaLength: thetaLength
  25240. };
  25241. }
  25242. ConeBufferGeometry.prototype = Object.create( CylinderBufferGeometry.prototype );
  25243. ConeBufferGeometry.prototype.constructor = ConeBufferGeometry;
  25244. /**
  25245. * @author benaadams / https://twitter.com/ben_a_adams
  25246. * @author Mugen87 / https://github.com/Mugen87
  25247. * @author hughes
  25248. */
  25249. // CircleGeometry
  25250. function CircleGeometry( radius, segments, thetaStart, thetaLength ) {
  25251. Geometry.call( this );
  25252. this.type = 'CircleGeometry';
  25253. this.parameters = {
  25254. radius: radius,
  25255. segments: segments,
  25256. thetaStart: thetaStart,
  25257. thetaLength: thetaLength
  25258. };
  25259. this.fromBufferGeometry( new CircleBufferGeometry( radius, segments, thetaStart, thetaLength ) );
  25260. this.mergeVertices();
  25261. }
  25262. CircleGeometry.prototype = Object.create( Geometry.prototype );
  25263. CircleGeometry.prototype.constructor = CircleGeometry;
  25264. // CircleBufferGeometry
  25265. function CircleBufferGeometry( radius, segments, thetaStart, thetaLength ) {
  25266. BufferGeometry.call( this );
  25267. this.type = 'CircleBufferGeometry';
  25268. this.parameters = {
  25269. radius: radius,
  25270. segments: segments,
  25271. thetaStart: thetaStart,
  25272. thetaLength: thetaLength
  25273. };
  25274. radius = radius || 1;
  25275. segments = segments !== undefined ? Math.max( 3, segments ) : 8;
  25276. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  25277. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  25278. // buffers
  25279. var indices = [];
  25280. var vertices = [];
  25281. var normals = [];
  25282. var uvs = [];
  25283. // helper variables
  25284. var i, s;
  25285. var vertex = new Vector3();
  25286. var uv = new Vector2();
  25287. // center point
  25288. vertices.push( 0, 0, 0 );
  25289. normals.push( 0, 0, 1 );
  25290. uvs.push( 0.5, 0.5 );
  25291. for ( s = 0, i = 3; s <= segments; s ++, i += 3 ) {
  25292. var segment = thetaStart + s / segments * thetaLength;
  25293. // vertex
  25294. vertex.x = radius * Math.cos( segment );
  25295. vertex.y = radius * Math.sin( segment );
  25296. vertices.push( vertex.x, vertex.y, vertex.z );
  25297. // normal
  25298. normals.push( 0, 0, 1 );
  25299. // uvs
  25300. uv.x = ( vertices[ i ] / radius + 1 ) / 2;
  25301. uv.y = ( vertices[ i + 1 ] / radius + 1 ) / 2;
  25302. uvs.push( uv.x, uv.y );
  25303. }
  25304. // indices
  25305. for ( i = 1; i <= segments; i ++ ) {
  25306. indices.push( i, i + 1, 0 );
  25307. }
  25308. // build geometry
  25309. this.setIndex( indices );
  25310. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  25311. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  25312. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  25313. }
  25314. CircleBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  25315. CircleBufferGeometry.prototype.constructor = CircleBufferGeometry;
  25316. var Geometries = /*#__PURE__*/Object.freeze({
  25317. __proto__: null,
  25318. WireframeGeometry: WireframeGeometry,
  25319. ParametricGeometry: ParametricGeometry,
  25320. ParametricBufferGeometry: ParametricBufferGeometry,
  25321. TetrahedronGeometry: TetrahedronGeometry,
  25322. TetrahedronBufferGeometry: TetrahedronBufferGeometry,
  25323. OctahedronGeometry: OctahedronGeometry,
  25324. OctahedronBufferGeometry: OctahedronBufferGeometry,
  25325. IcosahedronGeometry: IcosahedronGeometry,
  25326. IcosahedronBufferGeometry: IcosahedronBufferGeometry,
  25327. DodecahedronGeometry: DodecahedronGeometry,
  25328. DodecahedronBufferGeometry: DodecahedronBufferGeometry,
  25329. PolyhedronGeometry: PolyhedronGeometry,
  25330. PolyhedronBufferGeometry: PolyhedronBufferGeometry,
  25331. TubeGeometry: TubeGeometry,
  25332. TubeBufferGeometry: TubeBufferGeometry,
  25333. TorusKnotGeometry: TorusKnotGeometry,
  25334. TorusKnotBufferGeometry: TorusKnotBufferGeometry,
  25335. TorusGeometry: TorusGeometry,
  25336. TorusBufferGeometry: TorusBufferGeometry,
  25337. TextGeometry: TextGeometry,
  25338. TextBufferGeometry: TextBufferGeometry,
  25339. SphereGeometry: SphereGeometry,
  25340. SphereBufferGeometry: SphereBufferGeometry,
  25341. RingGeometry: RingGeometry,
  25342. RingBufferGeometry: RingBufferGeometry,
  25343. PlaneGeometry: PlaneGeometry,
  25344. PlaneBufferGeometry: PlaneBufferGeometry,
  25345. LatheGeometry: LatheGeometry,
  25346. LatheBufferGeometry: LatheBufferGeometry,
  25347. ShapeGeometry: ShapeGeometry,
  25348. ShapeBufferGeometry: ShapeBufferGeometry,
  25349. ExtrudeGeometry: ExtrudeGeometry,
  25350. ExtrudeBufferGeometry: ExtrudeBufferGeometry,
  25351. EdgesGeometry: EdgesGeometry,
  25352. ConeGeometry: ConeGeometry,
  25353. ConeBufferGeometry: ConeBufferGeometry,
  25354. CylinderGeometry: CylinderGeometry,
  25355. CylinderBufferGeometry: CylinderBufferGeometry,
  25356. CircleGeometry: CircleGeometry,
  25357. CircleBufferGeometry: CircleBufferGeometry,
  25358. BoxGeometry: BoxGeometry,
  25359. BoxBufferGeometry: BoxBufferGeometry
  25360. });
  25361. /**
  25362. * @author mrdoob / http://mrdoob.com/
  25363. *
  25364. * parameters = {
  25365. * color: <THREE.Color>
  25366. * }
  25367. */
  25368. function ShadowMaterial( parameters ) {
  25369. Material.call( this );
  25370. this.type = 'ShadowMaterial';
  25371. this.color = new Color( 0x000000 );
  25372. this.transparent = true;
  25373. this.setValues( parameters );
  25374. }
  25375. ShadowMaterial.prototype = Object.create( Material.prototype );
  25376. ShadowMaterial.prototype.constructor = ShadowMaterial;
  25377. ShadowMaterial.prototype.isShadowMaterial = true;
  25378. ShadowMaterial.prototype.copy = function ( source ) {
  25379. Material.prototype.copy.call( this, source );
  25380. this.color.copy( source.color );
  25381. return this;
  25382. };
  25383. /**
  25384. * @author mrdoob / http://mrdoob.com/
  25385. */
  25386. function RawShaderMaterial( parameters ) {
  25387. ShaderMaterial.call( this, parameters );
  25388. this.type = 'RawShaderMaterial';
  25389. }
  25390. RawShaderMaterial.prototype = Object.create( ShaderMaterial.prototype );
  25391. RawShaderMaterial.prototype.constructor = RawShaderMaterial;
  25392. RawShaderMaterial.prototype.isRawShaderMaterial = true;
  25393. /**
  25394. * @author WestLangley / http://github.com/WestLangley
  25395. *
  25396. * parameters = {
  25397. * color: <hex>,
  25398. * roughness: <float>,
  25399. * metalness: <float>,
  25400. * opacity: <float>,
  25401. *
  25402. * map: new THREE.Texture( <Image> ),
  25403. *
  25404. * lightMap: new THREE.Texture( <Image> ),
  25405. * lightMapIntensity: <float>
  25406. *
  25407. * aoMap: new THREE.Texture( <Image> ),
  25408. * aoMapIntensity: <float>
  25409. *
  25410. * emissive: <hex>,
  25411. * emissiveIntensity: <float>
  25412. * emissiveMap: new THREE.Texture( <Image> ),
  25413. *
  25414. * bumpMap: new THREE.Texture( <Image> ),
  25415. * bumpScale: <float>,
  25416. *
  25417. * normalMap: new THREE.Texture( <Image> ),
  25418. * normalMapType: THREE.TangentSpaceNormalMap,
  25419. * normalScale: <Vector2>,
  25420. *
  25421. * displacementMap: new THREE.Texture( <Image> ),
  25422. * displacementScale: <float>,
  25423. * displacementBias: <float>,
  25424. *
  25425. * roughnessMap: new THREE.Texture( <Image> ),
  25426. *
  25427. * metalnessMap: new THREE.Texture( <Image> ),
  25428. *
  25429. * alphaMap: new THREE.Texture( <Image> ),
  25430. *
  25431. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  25432. * envMapIntensity: <float>
  25433. *
  25434. * refractionRatio: <float>,
  25435. *
  25436. * wireframe: <boolean>,
  25437. * wireframeLinewidth: <float>,
  25438. *
  25439. * skinning: <bool>,
  25440. * morphTargets: <bool>,
  25441. * morphNormals: <bool>
  25442. * }
  25443. */
  25444. function MeshStandardMaterial( parameters ) {
  25445. Material.call( this );
  25446. this.defines = { 'STANDARD': '' };
  25447. this.type = 'MeshStandardMaterial';
  25448. this.color = new Color( 0xffffff ); // diffuse
  25449. this.roughness = 1.0;
  25450. this.metalness = 0.0;
  25451. this.map = null;
  25452. this.lightMap = null;
  25453. this.lightMapIntensity = 1.0;
  25454. this.aoMap = null;
  25455. this.aoMapIntensity = 1.0;
  25456. this.emissive = new Color( 0x000000 );
  25457. this.emissiveIntensity = 1.0;
  25458. this.emissiveMap = null;
  25459. this.bumpMap = null;
  25460. this.bumpScale = 1;
  25461. this.normalMap = null;
  25462. this.normalMapType = TangentSpaceNormalMap;
  25463. this.normalScale = new Vector2( 1, 1 );
  25464. this.displacementMap = null;
  25465. this.displacementScale = 1;
  25466. this.displacementBias = 0;
  25467. this.roughnessMap = null;
  25468. this.metalnessMap = null;
  25469. this.alphaMap = null;
  25470. this.envMap = null;
  25471. this.envMapIntensity = 1.0;
  25472. this.refractionRatio = 0.98;
  25473. this.wireframe = false;
  25474. this.wireframeLinewidth = 1;
  25475. this.wireframeLinecap = 'round';
  25476. this.wireframeLinejoin = 'round';
  25477. this.skinning = false;
  25478. this.morphTargets = false;
  25479. this.morphNormals = false;
  25480. this.vertexTangents = false;
  25481. this.setValues( parameters );
  25482. }
  25483. MeshStandardMaterial.prototype = Object.create( Material.prototype );
  25484. MeshStandardMaterial.prototype.constructor = MeshStandardMaterial;
  25485. MeshStandardMaterial.prototype.isMeshStandardMaterial = true;
  25486. MeshStandardMaterial.prototype.copy = function ( source ) {
  25487. Material.prototype.copy.call( this, source );
  25488. this.defines = { 'STANDARD': '' };
  25489. this.color.copy( source.color );
  25490. this.roughness = source.roughness;
  25491. this.metalness = source.metalness;
  25492. this.map = source.map;
  25493. this.lightMap = source.lightMap;
  25494. this.lightMapIntensity = source.lightMapIntensity;
  25495. this.aoMap = source.aoMap;
  25496. this.aoMapIntensity = source.aoMapIntensity;
  25497. this.emissive.copy( source.emissive );
  25498. this.emissiveMap = source.emissiveMap;
  25499. this.emissiveIntensity = source.emissiveIntensity;
  25500. this.bumpMap = source.bumpMap;
  25501. this.bumpScale = source.bumpScale;
  25502. this.normalMap = source.normalMap;
  25503. this.normalMapType = source.normalMapType;
  25504. this.normalScale.copy( source.normalScale );
  25505. this.displacementMap = source.displacementMap;
  25506. this.displacementScale = source.displacementScale;
  25507. this.displacementBias = source.displacementBias;
  25508. this.roughnessMap = source.roughnessMap;
  25509. this.metalnessMap = source.metalnessMap;
  25510. this.alphaMap = source.alphaMap;
  25511. this.envMap = source.envMap;
  25512. this.envMapIntensity = source.envMapIntensity;
  25513. this.refractionRatio = source.refractionRatio;
  25514. this.wireframe = source.wireframe;
  25515. this.wireframeLinewidth = source.wireframeLinewidth;
  25516. this.wireframeLinecap = source.wireframeLinecap;
  25517. this.wireframeLinejoin = source.wireframeLinejoin;
  25518. this.skinning = source.skinning;
  25519. this.morphTargets = source.morphTargets;
  25520. this.morphNormals = source.morphNormals;
  25521. this.vertexTangents = source.vertexTangents;
  25522. return this;
  25523. };
  25524. /**
  25525. * @author WestLangley / http://github.com/WestLangley
  25526. *
  25527. * parameters = {
  25528. * clearcoat: <float>,
  25529. * clearcoatMap: new THREE.Texture( <Image> ),
  25530. * clearcoatRoughness: <float>,
  25531. * clearcoatRoughnessMap: new THREE.Texture( <Image> ),
  25532. * clearcoatNormalScale: <Vector2>,
  25533. * clearcoatNormalMap: new THREE.Texture( <Image> ),
  25534. *
  25535. * reflectivity: <float>,
  25536. *
  25537. * sheen: <Color>,
  25538. *
  25539. * transparency: <float>
  25540. * }
  25541. */
  25542. function MeshPhysicalMaterial( parameters ) {
  25543. MeshStandardMaterial.call( this );
  25544. this.defines = {
  25545. 'STANDARD': '',
  25546. 'PHYSICAL': ''
  25547. };
  25548. this.type = 'MeshPhysicalMaterial';
  25549. this.clearcoat = 0.0;
  25550. this.clearcoatMap = null;
  25551. this.clearcoatRoughness = 0.0;
  25552. this.clearcoatRoughnessMap = null;
  25553. this.clearcoatNormalScale = new Vector2( 1, 1 );
  25554. this.clearcoatNormalMap = null;
  25555. this.reflectivity = 0.5; // maps to F0 = 0.04
  25556. this.sheen = null; // null will disable sheen bsdf
  25557. this.transparency = 0.0;
  25558. this.setValues( parameters );
  25559. }
  25560. MeshPhysicalMaterial.prototype = Object.create( MeshStandardMaterial.prototype );
  25561. MeshPhysicalMaterial.prototype.constructor = MeshPhysicalMaterial;
  25562. MeshPhysicalMaterial.prototype.isMeshPhysicalMaterial = true;
  25563. MeshPhysicalMaterial.prototype.copy = function ( source ) {
  25564. MeshStandardMaterial.prototype.copy.call( this, source );
  25565. this.defines = {
  25566. 'STANDARD': '',
  25567. 'PHYSICAL': ''
  25568. };
  25569. this.clearcoat = source.clearcoat;
  25570. this.clearcoatMap = source.clearcoatMap;
  25571. this.clearcoatRoughness = source.clearcoatRoughness;
  25572. this.clearcoatRoughnessMap = source.clearcoatRoughnessMap;
  25573. this.clearcoatNormalMap = source.clearcoatNormalMap;
  25574. this.clearcoatNormalScale.copy( source.clearcoatNormalScale );
  25575. this.reflectivity = source.reflectivity;
  25576. if ( source.sheen ) {
  25577. this.sheen = ( this.sheen || new Color() ).copy( source.sheen );
  25578. } else {
  25579. this.sheen = null;
  25580. }
  25581. this.transparency = source.transparency;
  25582. return this;
  25583. };
  25584. /**
  25585. * @author mrdoob / http://mrdoob.com/
  25586. * @author alteredq / http://alteredqualia.com/
  25587. *
  25588. * parameters = {
  25589. * color: <hex>,
  25590. * specular: <hex>,
  25591. * shininess: <float>,
  25592. * opacity: <float>,
  25593. *
  25594. * map: new THREE.Texture( <Image> ),
  25595. *
  25596. * lightMap: new THREE.Texture( <Image> ),
  25597. * lightMapIntensity: <float>
  25598. *
  25599. * aoMap: new THREE.Texture( <Image> ),
  25600. * aoMapIntensity: <float>
  25601. *
  25602. * emissive: <hex>,
  25603. * emissiveIntensity: <float>
  25604. * emissiveMap: new THREE.Texture( <Image> ),
  25605. *
  25606. * bumpMap: new THREE.Texture( <Image> ),
  25607. * bumpScale: <float>,
  25608. *
  25609. * normalMap: new THREE.Texture( <Image> ),
  25610. * normalMapType: THREE.TangentSpaceNormalMap,
  25611. * normalScale: <Vector2>,
  25612. *
  25613. * displacementMap: new THREE.Texture( <Image> ),
  25614. * displacementScale: <float>,
  25615. * displacementBias: <float>,
  25616. *
  25617. * specularMap: new THREE.Texture( <Image> ),
  25618. *
  25619. * alphaMap: new THREE.Texture( <Image> ),
  25620. *
  25621. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  25622. * combine: THREE.MultiplyOperation,
  25623. * reflectivity: <float>,
  25624. * refractionRatio: <float>,
  25625. *
  25626. * wireframe: <boolean>,
  25627. * wireframeLinewidth: <float>,
  25628. *
  25629. * skinning: <bool>,
  25630. * morphTargets: <bool>,
  25631. * morphNormals: <bool>
  25632. * }
  25633. */
  25634. function MeshPhongMaterial( parameters ) {
  25635. Material.call( this );
  25636. this.type = 'MeshPhongMaterial';
  25637. this.color = new Color( 0xffffff ); // diffuse
  25638. this.specular = new Color( 0x111111 );
  25639. this.shininess = 30;
  25640. this.map = null;
  25641. this.lightMap = null;
  25642. this.lightMapIntensity = 1.0;
  25643. this.aoMap = null;
  25644. this.aoMapIntensity = 1.0;
  25645. this.emissive = new Color( 0x000000 );
  25646. this.emissiveIntensity = 1.0;
  25647. this.emissiveMap = null;
  25648. this.bumpMap = null;
  25649. this.bumpScale = 1;
  25650. this.normalMap = null;
  25651. this.normalMapType = TangentSpaceNormalMap;
  25652. this.normalScale = new Vector2( 1, 1 );
  25653. this.displacementMap = null;
  25654. this.displacementScale = 1;
  25655. this.displacementBias = 0;
  25656. this.specularMap = null;
  25657. this.alphaMap = null;
  25658. this.envMap = null;
  25659. this.combine = MultiplyOperation;
  25660. this.reflectivity = 1;
  25661. this.refractionRatio = 0.98;
  25662. this.wireframe = false;
  25663. this.wireframeLinewidth = 1;
  25664. this.wireframeLinecap = 'round';
  25665. this.wireframeLinejoin = 'round';
  25666. this.skinning = false;
  25667. this.morphTargets = false;
  25668. this.morphNormals = false;
  25669. this.setValues( parameters );
  25670. }
  25671. MeshPhongMaterial.prototype = Object.create( Material.prototype );
  25672. MeshPhongMaterial.prototype.constructor = MeshPhongMaterial;
  25673. MeshPhongMaterial.prototype.isMeshPhongMaterial = true;
  25674. MeshPhongMaterial.prototype.copy = function ( source ) {
  25675. Material.prototype.copy.call( this, source );
  25676. this.color.copy( source.color );
  25677. this.specular.copy( source.specular );
  25678. this.shininess = source.shininess;
  25679. this.map = source.map;
  25680. this.lightMap = source.lightMap;
  25681. this.lightMapIntensity = source.lightMapIntensity;
  25682. this.aoMap = source.aoMap;
  25683. this.aoMapIntensity = source.aoMapIntensity;
  25684. this.emissive.copy( source.emissive );
  25685. this.emissiveMap = source.emissiveMap;
  25686. this.emissiveIntensity = source.emissiveIntensity;
  25687. this.bumpMap = source.bumpMap;
  25688. this.bumpScale = source.bumpScale;
  25689. this.normalMap = source.normalMap;
  25690. this.normalMapType = source.normalMapType;
  25691. this.normalScale.copy( source.normalScale );
  25692. this.displacementMap = source.displacementMap;
  25693. this.displacementScale = source.displacementScale;
  25694. this.displacementBias = source.displacementBias;
  25695. this.specularMap = source.specularMap;
  25696. this.alphaMap = source.alphaMap;
  25697. this.envMap = source.envMap;
  25698. this.combine = source.combine;
  25699. this.reflectivity = source.reflectivity;
  25700. this.refractionRatio = source.refractionRatio;
  25701. this.wireframe = source.wireframe;
  25702. this.wireframeLinewidth = source.wireframeLinewidth;
  25703. this.wireframeLinecap = source.wireframeLinecap;
  25704. this.wireframeLinejoin = source.wireframeLinejoin;
  25705. this.skinning = source.skinning;
  25706. this.morphTargets = source.morphTargets;
  25707. this.morphNormals = source.morphNormals;
  25708. return this;
  25709. };
  25710. /**
  25711. * @author takahirox / http://github.com/takahirox
  25712. *
  25713. * parameters = {
  25714. * color: <hex>,
  25715. * specular: <hex>,
  25716. * shininess: <float>,
  25717. *
  25718. * map: new THREE.Texture( <Image> ),
  25719. * gradientMap: new THREE.Texture( <Image> ),
  25720. *
  25721. * lightMap: new THREE.Texture( <Image> ),
  25722. * lightMapIntensity: <float>
  25723. *
  25724. * aoMap: new THREE.Texture( <Image> ),
  25725. * aoMapIntensity: <float>
  25726. *
  25727. * emissive: <hex>,
  25728. * emissiveIntensity: <float>
  25729. * emissiveMap: new THREE.Texture( <Image> ),
  25730. *
  25731. * bumpMap: new THREE.Texture( <Image> ),
  25732. * bumpScale: <float>,
  25733. *
  25734. * normalMap: new THREE.Texture( <Image> ),
  25735. * normalMapType: THREE.TangentSpaceNormalMap,
  25736. * normalScale: <Vector2>,
  25737. *
  25738. * displacementMap: new THREE.Texture( <Image> ),
  25739. * displacementScale: <float>,
  25740. * displacementBias: <float>,
  25741. *
  25742. * specularMap: new THREE.Texture( <Image> ),
  25743. *
  25744. * alphaMap: new THREE.Texture( <Image> ),
  25745. *
  25746. * wireframe: <boolean>,
  25747. * wireframeLinewidth: <float>,
  25748. *
  25749. * skinning: <bool>,
  25750. * morphTargets: <bool>,
  25751. * morphNormals: <bool>
  25752. * }
  25753. */
  25754. function MeshToonMaterial( parameters ) {
  25755. Material.call( this );
  25756. this.defines = { 'TOON': '' };
  25757. this.type = 'MeshToonMaterial';
  25758. this.color = new Color( 0xffffff );
  25759. this.specular = new Color( 0x111111 );
  25760. this.shininess = 30;
  25761. this.map = null;
  25762. this.gradientMap = null;
  25763. this.lightMap = null;
  25764. this.lightMapIntensity = 1.0;
  25765. this.aoMap = null;
  25766. this.aoMapIntensity = 1.0;
  25767. this.emissive = new Color( 0x000000 );
  25768. this.emissiveIntensity = 1.0;
  25769. this.emissiveMap = null;
  25770. this.bumpMap = null;
  25771. this.bumpScale = 1;
  25772. this.normalMap = null;
  25773. this.normalMapType = TangentSpaceNormalMap;
  25774. this.normalScale = new Vector2( 1, 1 );
  25775. this.displacementMap = null;
  25776. this.displacementScale = 1;
  25777. this.displacementBias = 0;
  25778. this.specularMap = null;
  25779. this.alphaMap = null;
  25780. this.wireframe = false;
  25781. this.wireframeLinewidth = 1;
  25782. this.wireframeLinecap = 'round';
  25783. this.wireframeLinejoin = 'round';
  25784. this.skinning = false;
  25785. this.morphTargets = false;
  25786. this.morphNormals = false;
  25787. this.setValues( parameters );
  25788. }
  25789. MeshToonMaterial.prototype = Object.create( Material.prototype );
  25790. MeshToonMaterial.prototype.constructor = MeshToonMaterial;
  25791. MeshToonMaterial.prototype.isMeshToonMaterial = true;
  25792. MeshToonMaterial.prototype.copy = function ( source ) {
  25793. Material.prototype.copy.call( this, source );
  25794. this.color.copy( source.color );
  25795. this.specular.copy( source.specular );
  25796. this.shininess = source.shininess;
  25797. this.map = source.map;
  25798. this.gradientMap = source.gradientMap;
  25799. this.lightMap = source.lightMap;
  25800. this.lightMapIntensity = source.lightMapIntensity;
  25801. this.aoMap = source.aoMap;
  25802. this.aoMapIntensity = source.aoMapIntensity;
  25803. this.emissive.copy( source.emissive );
  25804. this.emissiveMap = source.emissiveMap;
  25805. this.emissiveIntensity = source.emissiveIntensity;
  25806. this.bumpMap = source.bumpMap;
  25807. this.bumpScale = source.bumpScale;
  25808. this.normalMap = source.normalMap;
  25809. this.normalMapType = source.normalMapType;
  25810. this.normalScale.copy( source.normalScale );
  25811. this.displacementMap = source.displacementMap;
  25812. this.displacementScale = source.displacementScale;
  25813. this.displacementBias = source.displacementBias;
  25814. this.specularMap = source.specularMap;
  25815. this.alphaMap = source.alphaMap;
  25816. this.wireframe = source.wireframe;
  25817. this.wireframeLinewidth = source.wireframeLinewidth;
  25818. this.wireframeLinecap = source.wireframeLinecap;
  25819. this.wireframeLinejoin = source.wireframeLinejoin;
  25820. this.skinning = source.skinning;
  25821. this.morphTargets = source.morphTargets;
  25822. this.morphNormals = source.morphNormals;
  25823. return this;
  25824. };
  25825. /**
  25826. * @author mrdoob / http://mrdoob.com/
  25827. * @author WestLangley / http://github.com/WestLangley
  25828. *
  25829. * parameters = {
  25830. * opacity: <float>,
  25831. *
  25832. * bumpMap: new THREE.Texture( <Image> ),
  25833. * bumpScale: <float>,
  25834. *
  25835. * normalMap: new THREE.Texture( <Image> ),
  25836. * normalMapType: THREE.TangentSpaceNormalMap,
  25837. * normalScale: <Vector2>,
  25838. *
  25839. * displacementMap: new THREE.Texture( <Image> ),
  25840. * displacementScale: <float>,
  25841. * displacementBias: <float>,
  25842. *
  25843. * wireframe: <boolean>,
  25844. * wireframeLinewidth: <float>
  25845. *
  25846. * skinning: <bool>,
  25847. * morphTargets: <bool>,
  25848. * morphNormals: <bool>
  25849. * }
  25850. */
  25851. function MeshNormalMaterial( parameters ) {
  25852. Material.call( this );
  25853. this.type = 'MeshNormalMaterial';
  25854. this.bumpMap = null;
  25855. this.bumpScale = 1;
  25856. this.normalMap = null;
  25857. this.normalMapType = TangentSpaceNormalMap;
  25858. this.normalScale = new Vector2( 1, 1 );
  25859. this.displacementMap = null;
  25860. this.displacementScale = 1;
  25861. this.displacementBias = 0;
  25862. this.wireframe = false;
  25863. this.wireframeLinewidth = 1;
  25864. this.fog = false;
  25865. this.skinning = false;
  25866. this.morphTargets = false;
  25867. this.morphNormals = false;
  25868. this.setValues( parameters );
  25869. }
  25870. MeshNormalMaterial.prototype = Object.create( Material.prototype );
  25871. MeshNormalMaterial.prototype.constructor = MeshNormalMaterial;
  25872. MeshNormalMaterial.prototype.isMeshNormalMaterial = true;
  25873. MeshNormalMaterial.prototype.copy = function ( source ) {
  25874. Material.prototype.copy.call( this, source );
  25875. this.bumpMap = source.bumpMap;
  25876. this.bumpScale = source.bumpScale;
  25877. this.normalMap = source.normalMap;
  25878. this.normalMapType = source.normalMapType;
  25879. this.normalScale.copy( source.normalScale );
  25880. this.displacementMap = source.displacementMap;
  25881. this.displacementScale = source.displacementScale;
  25882. this.displacementBias = source.displacementBias;
  25883. this.wireframe = source.wireframe;
  25884. this.wireframeLinewidth = source.wireframeLinewidth;
  25885. this.skinning = source.skinning;
  25886. this.morphTargets = source.morphTargets;
  25887. this.morphNormals = source.morphNormals;
  25888. return this;
  25889. };
  25890. /**
  25891. * @author mrdoob / http://mrdoob.com/
  25892. * @author alteredq / http://alteredqualia.com/
  25893. *
  25894. * parameters = {
  25895. * color: <hex>,
  25896. * opacity: <float>,
  25897. *
  25898. * map: new THREE.Texture( <Image> ),
  25899. *
  25900. * lightMap: new THREE.Texture( <Image> ),
  25901. * lightMapIntensity: <float>
  25902. *
  25903. * aoMap: new THREE.Texture( <Image> ),
  25904. * aoMapIntensity: <float>
  25905. *
  25906. * emissive: <hex>,
  25907. * emissiveIntensity: <float>
  25908. * emissiveMap: new THREE.Texture( <Image> ),
  25909. *
  25910. * specularMap: new THREE.Texture( <Image> ),
  25911. *
  25912. * alphaMap: new THREE.Texture( <Image> ),
  25913. *
  25914. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  25915. * combine: THREE.Multiply,
  25916. * reflectivity: <float>,
  25917. * refractionRatio: <float>,
  25918. *
  25919. * wireframe: <boolean>,
  25920. * wireframeLinewidth: <float>,
  25921. *
  25922. * skinning: <bool>,
  25923. * morphTargets: <bool>,
  25924. * morphNormals: <bool>
  25925. * }
  25926. */
  25927. function MeshLambertMaterial( parameters ) {
  25928. Material.call( this );
  25929. this.type = 'MeshLambertMaterial';
  25930. this.color = new Color( 0xffffff ); // diffuse
  25931. this.map = null;
  25932. this.lightMap = null;
  25933. this.lightMapIntensity = 1.0;
  25934. this.aoMap = null;
  25935. this.aoMapIntensity = 1.0;
  25936. this.emissive = new Color( 0x000000 );
  25937. this.emissiveIntensity = 1.0;
  25938. this.emissiveMap = null;
  25939. this.specularMap = null;
  25940. this.alphaMap = null;
  25941. this.envMap = null;
  25942. this.combine = MultiplyOperation;
  25943. this.reflectivity = 1;
  25944. this.refractionRatio = 0.98;
  25945. this.wireframe = false;
  25946. this.wireframeLinewidth = 1;
  25947. this.wireframeLinecap = 'round';
  25948. this.wireframeLinejoin = 'round';
  25949. this.skinning = false;
  25950. this.morphTargets = false;
  25951. this.morphNormals = false;
  25952. this.setValues( parameters );
  25953. }
  25954. MeshLambertMaterial.prototype = Object.create( Material.prototype );
  25955. MeshLambertMaterial.prototype.constructor = MeshLambertMaterial;
  25956. MeshLambertMaterial.prototype.isMeshLambertMaterial = true;
  25957. MeshLambertMaterial.prototype.copy = function ( source ) {
  25958. Material.prototype.copy.call( this, source );
  25959. this.color.copy( source.color );
  25960. this.map = source.map;
  25961. this.lightMap = source.lightMap;
  25962. this.lightMapIntensity = source.lightMapIntensity;
  25963. this.aoMap = source.aoMap;
  25964. this.aoMapIntensity = source.aoMapIntensity;
  25965. this.emissive.copy( source.emissive );
  25966. this.emissiveMap = source.emissiveMap;
  25967. this.emissiveIntensity = source.emissiveIntensity;
  25968. this.specularMap = source.specularMap;
  25969. this.alphaMap = source.alphaMap;
  25970. this.envMap = source.envMap;
  25971. this.combine = source.combine;
  25972. this.reflectivity = source.reflectivity;
  25973. this.refractionRatio = source.refractionRatio;
  25974. this.wireframe = source.wireframe;
  25975. this.wireframeLinewidth = source.wireframeLinewidth;
  25976. this.wireframeLinecap = source.wireframeLinecap;
  25977. this.wireframeLinejoin = source.wireframeLinejoin;
  25978. this.skinning = source.skinning;
  25979. this.morphTargets = source.morphTargets;
  25980. this.morphNormals = source.morphNormals;
  25981. return this;
  25982. };
  25983. /**
  25984. * @author WestLangley / http://github.com/WestLangley
  25985. *
  25986. * parameters = {
  25987. * color: <hex>,
  25988. * opacity: <float>,
  25989. *
  25990. * matcap: new THREE.Texture( <Image> ),
  25991. *
  25992. * map: new THREE.Texture( <Image> ),
  25993. *
  25994. * bumpMap: new THREE.Texture( <Image> ),
  25995. * bumpScale: <float>,
  25996. *
  25997. * normalMap: new THREE.Texture( <Image> ),
  25998. * normalMapType: THREE.TangentSpaceNormalMap,
  25999. * normalScale: <Vector2>,
  26000. *
  26001. * displacementMap: new THREE.Texture( <Image> ),
  26002. * displacementScale: <float>,
  26003. * displacementBias: <float>,
  26004. *
  26005. * alphaMap: new THREE.Texture( <Image> ),
  26006. *
  26007. * skinning: <bool>,
  26008. * morphTargets: <bool>,
  26009. * morphNormals: <bool>
  26010. * }
  26011. */
  26012. function MeshMatcapMaterial( parameters ) {
  26013. Material.call( this );
  26014. this.defines = { 'MATCAP': '' };
  26015. this.type = 'MeshMatcapMaterial';
  26016. this.color = new Color( 0xffffff ); // diffuse
  26017. this.matcap = null;
  26018. this.map = null;
  26019. this.bumpMap = null;
  26020. this.bumpScale = 1;
  26021. this.normalMap = null;
  26022. this.normalMapType = TangentSpaceNormalMap;
  26023. this.normalScale = new Vector2( 1, 1 );
  26024. this.displacementMap = null;
  26025. this.displacementScale = 1;
  26026. this.displacementBias = 0;
  26027. this.alphaMap = null;
  26028. this.skinning = false;
  26029. this.morphTargets = false;
  26030. this.morphNormals = false;
  26031. this.setValues( parameters );
  26032. }
  26033. MeshMatcapMaterial.prototype = Object.create( Material.prototype );
  26034. MeshMatcapMaterial.prototype.constructor = MeshMatcapMaterial;
  26035. MeshMatcapMaterial.prototype.isMeshMatcapMaterial = true;
  26036. MeshMatcapMaterial.prototype.copy = function ( source ) {
  26037. Material.prototype.copy.call( this, source );
  26038. this.defines = { 'MATCAP': '' };
  26039. this.color.copy( source.color );
  26040. this.matcap = source.matcap;
  26041. this.map = source.map;
  26042. this.bumpMap = source.bumpMap;
  26043. this.bumpScale = source.bumpScale;
  26044. this.normalMap = source.normalMap;
  26045. this.normalMapType = source.normalMapType;
  26046. this.normalScale.copy( source.normalScale );
  26047. this.displacementMap = source.displacementMap;
  26048. this.displacementScale = source.displacementScale;
  26049. this.displacementBias = source.displacementBias;
  26050. this.alphaMap = source.alphaMap;
  26051. this.skinning = source.skinning;
  26052. this.morphTargets = source.morphTargets;
  26053. this.morphNormals = source.morphNormals;
  26054. return this;
  26055. };
  26056. /**
  26057. * @author alteredq / http://alteredqualia.com/
  26058. *
  26059. * parameters = {
  26060. * color: <hex>,
  26061. * opacity: <float>,
  26062. *
  26063. * linewidth: <float>,
  26064. *
  26065. * scale: <float>,
  26066. * dashSize: <float>,
  26067. * gapSize: <float>
  26068. * }
  26069. */
  26070. function LineDashedMaterial( parameters ) {
  26071. LineBasicMaterial.call( this );
  26072. this.type = 'LineDashedMaterial';
  26073. this.scale = 1;
  26074. this.dashSize = 3;
  26075. this.gapSize = 1;
  26076. this.setValues( parameters );
  26077. }
  26078. LineDashedMaterial.prototype = Object.create( LineBasicMaterial.prototype );
  26079. LineDashedMaterial.prototype.constructor = LineDashedMaterial;
  26080. LineDashedMaterial.prototype.isLineDashedMaterial = true;
  26081. LineDashedMaterial.prototype.copy = function ( source ) {
  26082. LineBasicMaterial.prototype.copy.call( this, source );
  26083. this.scale = source.scale;
  26084. this.dashSize = source.dashSize;
  26085. this.gapSize = source.gapSize;
  26086. return this;
  26087. };
  26088. var Materials = /*#__PURE__*/Object.freeze({
  26089. __proto__: null,
  26090. ShadowMaterial: ShadowMaterial,
  26091. SpriteMaterial: SpriteMaterial,
  26092. RawShaderMaterial: RawShaderMaterial,
  26093. ShaderMaterial: ShaderMaterial,
  26094. PointsMaterial: PointsMaterial,
  26095. MeshPhysicalMaterial: MeshPhysicalMaterial,
  26096. MeshStandardMaterial: MeshStandardMaterial,
  26097. MeshPhongMaterial: MeshPhongMaterial,
  26098. MeshToonMaterial: MeshToonMaterial,
  26099. MeshNormalMaterial: MeshNormalMaterial,
  26100. MeshLambertMaterial: MeshLambertMaterial,
  26101. MeshDepthMaterial: MeshDepthMaterial,
  26102. MeshDistanceMaterial: MeshDistanceMaterial,
  26103. MeshBasicMaterial: MeshBasicMaterial,
  26104. MeshMatcapMaterial: MeshMatcapMaterial,
  26105. LineDashedMaterial: LineDashedMaterial,
  26106. LineBasicMaterial: LineBasicMaterial,
  26107. Material: Material
  26108. });
  26109. /**
  26110. * @author tschw
  26111. * @author Ben Houston / http://clara.io/
  26112. * @author David Sarno / http://lighthaus.us/
  26113. */
  26114. var AnimationUtils = {
  26115. // same as Array.prototype.slice, but also works on typed arrays
  26116. arraySlice: function ( array, from, to ) {
  26117. if ( AnimationUtils.isTypedArray( array ) ) {
  26118. // in ios9 array.subarray(from, undefined) will return empty array
  26119. // but array.subarray(from) or array.subarray(from, len) is correct
  26120. return new array.constructor( array.subarray( from, to !== undefined ? to : array.length ) );
  26121. }
  26122. return array.slice( from, to );
  26123. },
  26124. // converts an array to a specific type
  26125. convertArray: function ( array, type, forceClone ) {
  26126. if ( ! array || // let 'undefined' and 'null' pass
  26127. ! forceClone && array.constructor === type ) { return array; }
  26128. if ( typeof type.BYTES_PER_ELEMENT === 'number' ) {
  26129. return new type( array ); // create typed array
  26130. }
  26131. return Array.prototype.slice.call( array ); // create Array
  26132. },
  26133. isTypedArray: function ( object ) {
  26134. return ArrayBuffer.isView( object ) &&
  26135. ! ( object instanceof DataView );
  26136. },
  26137. // returns an array by which times and values can be sorted
  26138. getKeyframeOrder: function ( times ) {
  26139. function compareTime( i, j ) {
  26140. return times[ i ] - times[ j ];
  26141. }
  26142. var n = times.length;
  26143. var result = new Array( n );
  26144. for ( var i = 0; i !== n; ++ i ) { result[ i ] = i; }
  26145. result.sort( compareTime );
  26146. return result;
  26147. },
  26148. // uses the array previously returned by 'getKeyframeOrder' to sort data
  26149. sortedArray: function ( values, stride, order ) {
  26150. var nValues = values.length;
  26151. var result = new values.constructor( nValues );
  26152. for ( var i = 0, dstOffset = 0; dstOffset !== nValues; ++ i ) {
  26153. var srcOffset = order[ i ] * stride;
  26154. for ( var j = 0; j !== stride; ++ j ) {
  26155. result[ dstOffset ++ ] = values[ srcOffset + j ];
  26156. }
  26157. }
  26158. return result;
  26159. },
  26160. // function for parsing AOS keyframe formats
  26161. flattenJSON: function ( jsonKeys, times, values, valuePropertyName ) {
  26162. var i = 1, key = jsonKeys[ 0 ];
  26163. while ( key !== undefined && key[ valuePropertyName ] === undefined ) {
  26164. key = jsonKeys[ i ++ ];
  26165. }
  26166. if ( key === undefined ) { return; } // no data
  26167. var value = key[ valuePropertyName ];
  26168. if ( value === undefined ) { return; } // no data
  26169. if ( Array.isArray( value ) ) {
  26170. do {
  26171. value = key[ valuePropertyName ];
  26172. if ( value !== undefined ) {
  26173. times.push( key.time );
  26174. values.push.apply( values, value ); // push all elements
  26175. }
  26176. key = jsonKeys[ i ++ ];
  26177. } while ( key !== undefined );
  26178. } else if ( value.toArray !== undefined ) {
  26179. // ...assume THREE.Math-ish
  26180. do {
  26181. value = key[ valuePropertyName ];
  26182. if ( value !== undefined ) {
  26183. times.push( key.time );
  26184. value.toArray( values, values.length );
  26185. }
  26186. key = jsonKeys[ i ++ ];
  26187. } while ( key !== undefined );
  26188. } else {
  26189. // otherwise push as-is
  26190. do {
  26191. value = key[ valuePropertyName ];
  26192. if ( value !== undefined ) {
  26193. times.push( key.time );
  26194. values.push( value );
  26195. }
  26196. key = jsonKeys[ i ++ ];
  26197. } while ( key !== undefined );
  26198. }
  26199. },
  26200. subclip: function ( sourceClip, name, startFrame, endFrame, fps ) {
  26201. fps = fps || 30;
  26202. var clip = sourceClip.clone();
  26203. clip.name = name;
  26204. var tracks = [];
  26205. for ( var i = 0; i < clip.tracks.length; ++ i ) {
  26206. var track = clip.tracks[ i ];
  26207. var valueSize = track.getValueSize();
  26208. var times = [];
  26209. var values = [];
  26210. for ( var j = 0; j < track.times.length; ++ j ) {
  26211. var frame = track.times[ j ] * fps;
  26212. if ( frame < startFrame || frame >= endFrame ) { continue; }
  26213. times.push( track.times[ j ] );
  26214. for ( var k = 0; k < valueSize; ++ k ) {
  26215. values.push( track.values[ j * valueSize + k ] );
  26216. }
  26217. }
  26218. if ( times.length === 0 ) { continue; }
  26219. track.times = AnimationUtils.convertArray( times, track.times.constructor );
  26220. track.values = AnimationUtils.convertArray( values, track.values.constructor );
  26221. tracks.push( track );
  26222. }
  26223. clip.tracks = tracks;
  26224. // find minimum .times value across all tracks in the trimmed clip
  26225. var minStartTime = Infinity;
  26226. for ( var i = 0; i < clip.tracks.length; ++ i ) {
  26227. if ( minStartTime > clip.tracks[ i ].times[ 0 ] ) {
  26228. minStartTime = clip.tracks[ i ].times[ 0 ];
  26229. }
  26230. }
  26231. // shift all tracks such that clip begins at t=0
  26232. for ( var i = 0; i < clip.tracks.length; ++ i ) {
  26233. clip.tracks[ i ].shift( - 1 * minStartTime );
  26234. }
  26235. clip.resetDuration();
  26236. return clip;
  26237. }
  26238. };
  26239. /**
  26240. * Abstract base class of interpolants over parametric samples.
  26241. *
  26242. * The parameter domain is one dimensional, typically the time or a path
  26243. * along a curve defined by the data.
  26244. *
  26245. * The sample values can have any dimensionality and derived classes may
  26246. * apply special interpretations to the data.
  26247. *
  26248. * This class provides the interval seek in a Template Method, deferring
  26249. * the actual interpolation to derived classes.
  26250. *
  26251. * Time complexity is O(1) for linear access crossing at most two points
  26252. * and O(log N) for random access, where N is the number of positions.
  26253. *
  26254. * References:
  26255. *
  26256. * http://www.oodesign.com/template-method-pattern.html
  26257. *
  26258. * @author tschw
  26259. */
  26260. function Interpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  26261. this.parameterPositions = parameterPositions;
  26262. this._cachedIndex = 0;
  26263. this.resultBuffer = resultBuffer !== undefined ?
  26264. resultBuffer : new sampleValues.constructor( sampleSize );
  26265. this.sampleValues = sampleValues;
  26266. this.valueSize = sampleSize;
  26267. }
  26268. Object.assign( Interpolant.prototype, {
  26269. evaluate: function ( t ) {
  26270. var pp = this.parameterPositions,
  26271. i1 = this._cachedIndex,
  26272. t1 = pp[ i1 ],
  26273. t0 = pp[ i1 - 1 ];
  26274. validate_interval: {
  26275. seek: {
  26276. var right;
  26277. linear_scan: {
  26278. //- See http://jsperf.com/comparison-to-undefined/3
  26279. //- slower code:
  26280. //-
  26281. //- if ( t >= t1 || t1 === undefined ) {
  26282. forward_scan: if ( ! ( t < t1 ) ) {
  26283. for ( var giveUpAt = i1 + 2; ; ) {
  26284. if ( t1 === undefined ) {
  26285. if ( t < t0 ) { break forward_scan; }
  26286. // after end
  26287. i1 = pp.length;
  26288. this._cachedIndex = i1;
  26289. return this.afterEnd_( i1 - 1, t, t0 );
  26290. }
  26291. if ( i1 === giveUpAt ) { break; } // this loop
  26292. t0 = t1;
  26293. t1 = pp[ ++ i1 ];
  26294. if ( t < t1 ) {
  26295. // we have arrived at the sought interval
  26296. break seek;
  26297. }
  26298. }
  26299. // prepare binary search on the right side of the index
  26300. right = pp.length;
  26301. break linear_scan;
  26302. }
  26303. //- slower code:
  26304. //- if ( t < t0 || t0 === undefined ) {
  26305. if ( ! ( t >= t0 ) ) {
  26306. // looping?
  26307. var t1global = pp[ 1 ];
  26308. if ( t < t1global ) {
  26309. i1 = 2; // + 1, using the scan for the details
  26310. t0 = t1global;
  26311. }
  26312. // linear reverse scan
  26313. for ( var giveUpAt = i1 - 2; ; ) {
  26314. if ( t0 === undefined ) {
  26315. // before start
  26316. this._cachedIndex = 0;
  26317. return this.beforeStart_( 0, t, t1 );
  26318. }
  26319. if ( i1 === giveUpAt ) { break; } // this loop
  26320. t1 = t0;
  26321. t0 = pp[ -- i1 - 1 ];
  26322. if ( t >= t0 ) {
  26323. // we have arrived at the sought interval
  26324. break seek;
  26325. }
  26326. }
  26327. // prepare binary search on the left side of the index
  26328. right = i1;
  26329. i1 = 0;
  26330. break linear_scan;
  26331. }
  26332. // the interval is valid
  26333. break validate_interval;
  26334. } // linear scan
  26335. // binary search
  26336. while ( i1 < right ) {
  26337. var mid = ( i1 + right ) >>> 1;
  26338. if ( t < pp[ mid ] ) {
  26339. right = mid;
  26340. } else {
  26341. i1 = mid + 1;
  26342. }
  26343. }
  26344. t1 = pp[ i1 ];
  26345. t0 = pp[ i1 - 1 ];
  26346. // check boundary cases, again
  26347. if ( t0 === undefined ) {
  26348. this._cachedIndex = 0;
  26349. return this.beforeStart_( 0, t, t1 );
  26350. }
  26351. if ( t1 === undefined ) {
  26352. i1 = pp.length;
  26353. this._cachedIndex = i1;
  26354. return this.afterEnd_( i1 - 1, t0, t );
  26355. }
  26356. } // seek
  26357. this._cachedIndex = i1;
  26358. this.intervalChanged_( i1, t0, t1 );
  26359. } // validate_interval
  26360. return this.interpolate_( i1, t0, t, t1 );
  26361. },
  26362. settings: null, // optional, subclass-specific settings structure
  26363. // Note: The indirection allows central control of many interpolants.
  26364. // --- Protected interface
  26365. DefaultSettings_: {},
  26366. getSettings_: function () {
  26367. return this.settings || this.DefaultSettings_;
  26368. },
  26369. copySampleValue_: function ( index ) {
  26370. // copies a sample value to the result buffer
  26371. var result = this.resultBuffer,
  26372. values = this.sampleValues,
  26373. stride = this.valueSize,
  26374. offset = index * stride;
  26375. for ( var i = 0; i !== stride; ++ i ) {
  26376. result[ i ] = values[ offset + i ];
  26377. }
  26378. return result;
  26379. },
  26380. // Template methods for derived classes:
  26381. interpolate_: function ( /* i1, t0, t, t1 */ ) {
  26382. throw new Error( 'call to abstract method' );
  26383. // implementations shall return this.resultBuffer
  26384. },
  26385. intervalChanged_: function ( /* i1, t0, t1 */ ) {
  26386. // empty
  26387. }
  26388. } );
  26389. // DECLARE ALIAS AFTER assign prototype
  26390. Object.assign( Interpolant.prototype, {
  26391. //( 0, t, t0 ), returns this.resultBuffer
  26392. beforeStart_: Interpolant.prototype.copySampleValue_,
  26393. //( N-1, tN-1, t ), returns this.resultBuffer
  26394. afterEnd_: Interpolant.prototype.copySampleValue_,
  26395. } );
  26396. /**
  26397. * Fast and simple cubic spline interpolant.
  26398. *
  26399. * It was derived from a Hermitian construction setting the first derivative
  26400. * at each sample position to the linear slope between neighboring positions
  26401. * over their parameter interval.
  26402. *
  26403. * @author tschw
  26404. */
  26405. function CubicInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  26406. Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  26407. this._weightPrev = - 0;
  26408. this._offsetPrev = - 0;
  26409. this._weightNext = - 0;
  26410. this._offsetNext = - 0;
  26411. }
  26412. CubicInterpolant.prototype = Object.assign( Object.create( Interpolant.prototype ), {
  26413. constructor: CubicInterpolant,
  26414. DefaultSettings_: {
  26415. endingStart: ZeroCurvatureEnding,
  26416. endingEnd: ZeroCurvatureEnding
  26417. },
  26418. intervalChanged_: function ( i1, t0, t1 ) {
  26419. var pp = this.parameterPositions,
  26420. iPrev = i1 - 2,
  26421. iNext = i1 + 1,
  26422. tPrev = pp[ iPrev ],
  26423. tNext = pp[ iNext ];
  26424. if ( tPrev === undefined ) {
  26425. switch ( this.getSettings_().endingStart ) {
  26426. case ZeroSlopeEnding:
  26427. // f'(t0) = 0
  26428. iPrev = i1;
  26429. tPrev = 2 * t0 - t1;
  26430. break;
  26431. case WrapAroundEnding:
  26432. // use the other end of the curve
  26433. iPrev = pp.length - 2;
  26434. tPrev = t0 + pp[ iPrev ] - pp[ iPrev + 1 ];
  26435. break;
  26436. default: // ZeroCurvatureEnding
  26437. // f''(t0) = 0 a.k.a. Natural Spline
  26438. iPrev = i1;
  26439. tPrev = t1;
  26440. }
  26441. }
  26442. if ( tNext === undefined ) {
  26443. switch ( this.getSettings_().endingEnd ) {
  26444. case ZeroSlopeEnding:
  26445. // f'(tN) = 0
  26446. iNext = i1;
  26447. tNext = 2 * t1 - t0;
  26448. break;
  26449. case WrapAroundEnding:
  26450. // use the other end of the curve
  26451. iNext = 1;
  26452. tNext = t1 + pp[ 1 ] - pp[ 0 ];
  26453. break;
  26454. default: // ZeroCurvatureEnding
  26455. // f''(tN) = 0, a.k.a. Natural Spline
  26456. iNext = i1 - 1;
  26457. tNext = t0;
  26458. }
  26459. }
  26460. var halfDt = ( t1 - t0 ) * 0.5,
  26461. stride = this.valueSize;
  26462. this._weightPrev = halfDt / ( t0 - tPrev );
  26463. this._weightNext = halfDt / ( tNext - t1 );
  26464. this._offsetPrev = iPrev * stride;
  26465. this._offsetNext = iNext * stride;
  26466. },
  26467. interpolate_: function ( i1, t0, t, t1 ) {
  26468. var result = this.resultBuffer,
  26469. values = this.sampleValues,
  26470. stride = this.valueSize,
  26471. o1 = i1 * stride, o0 = o1 - stride,
  26472. oP = this._offsetPrev, oN = this._offsetNext,
  26473. wP = this._weightPrev, wN = this._weightNext,
  26474. p = ( t - t0 ) / ( t1 - t0 ),
  26475. pp = p * p,
  26476. ppp = pp * p;
  26477. // evaluate polynomials
  26478. var sP = - wP * ppp + 2 * wP * pp - wP * p;
  26479. var s0 = ( 1 + wP ) * ppp + ( - 1.5 - 2 * wP ) * pp + ( - 0.5 + wP ) * p + 1;
  26480. var s1 = ( - 1 - wN ) * ppp + ( 1.5 + wN ) * pp + 0.5 * p;
  26481. var sN = wN * ppp - wN * pp;
  26482. // combine data linearly
  26483. for ( var i = 0; i !== stride; ++ i ) {
  26484. result[ i ] =
  26485. sP * values[ oP + i ] +
  26486. s0 * values[ o0 + i ] +
  26487. s1 * values[ o1 + i ] +
  26488. sN * values[ oN + i ];
  26489. }
  26490. return result;
  26491. }
  26492. } );
  26493. /**
  26494. * @author tschw
  26495. */
  26496. function LinearInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  26497. Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  26498. }
  26499. LinearInterpolant.prototype = Object.assign( Object.create( Interpolant.prototype ), {
  26500. constructor: LinearInterpolant,
  26501. interpolate_: function ( i1, t0, t, t1 ) {
  26502. var result = this.resultBuffer,
  26503. values = this.sampleValues,
  26504. stride = this.valueSize,
  26505. offset1 = i1 * stride,
  26506. offset0 = offset1 - stride,
  26507. weight1 = ( t - t0 ) / ( t1 - t0 ),
  26508. weight0 = 1 - weight1;
  26509. for ( var i = 0; i !== stride; ++ i ) {
  26510. result[ i ] =
  26511. values[ offset0 + i ] * weight0 +
  26512. values[ offset1 + i ] * weight1;
  26513. }
  26514. return result;
  26515. }
  26516. } );
  26517. /**
  26518. *
  26519. * Interpolant that evaluates to the sample value at the position preceeding
  26520. * the parameter.
  26521. *
  26522. * @author tschw
  26523. */
  26524. function DiscreteInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  26525. Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  26526. }
  26527. DiscreteInterpolant.prototype = Object.assign( Object.create( Interpolant.prototype ), {
  26528. constructor: DiscreteInterpolant,
  26529. interpolate_: function ( i1 /*, t0, t, t1 */ ) {
  26530. return this.copySampleValue_( i1 - 1 );
  26531. }
  26532. } );
  26533. /**
  26534. *
  26535. * A timed sequence of keyframes for a specific property.
  26536. *
  26537. *
  26538. * @author Ben Houston / http://clara.io/
  26539. * @author David Sarno / http://lighthaus.us/
  26540. * @author tschw
  26541. */
  26542. function KeyframeTrack( name, times, values, interpolation ) {
  26543. if ( name === undefined ) { throw new Error( 'THREE.KeyframeTrack: track name is undefined' ); }
  26544. if ( times === undefined || times.length === 0 ) { throw new Error( 'THREE.KeyframeTrack: no keyframes in track named ' + name ); }
  26545. this.name = name;
  26546. this.times = AnimationUtils.convertArray( times, this.TimeBufferType );
  26547. this.values = AnimationUtils.convertArray( values, this.ValueBufferType );
  26548. this.setInterpolation( interpolation || this.DefaultInterpolation );
  26549. }
  26550. // Static methods
  26551. Object.assign( KeyframeTrack, {
  26552. // Serialization (in static context, because of constructor invocation
  26553. // and automatic invocation of .toJSON):
  26554. toJSON: function ( track ) {
  26555. var trackType = track.constructor;
  26556. var json;
  26557. // derived classes can define a static toJSON method
  26558. if ( trackType.toJSON !== undefined ) {
  26559. json = trackType.toJSON( track );
  26560. } else {
  26561. // by default, we assume the data can be serialized as-is
  26562. json = {
  26563. 'name': track.name,
  26564. 'times': AnimationUtils.convertArray( track.times, Array ),
  26565. 'values': AnimationUtils.convertArray( track.values, Array )
  26566. };
  26567. var interpolation = track.getInterpolation();
  26568. if ( interpolation !== track.DefaultInterpolation ) {
  26569. json.interpolation = interpolation;
  26570. }
  26571. }
  26572. json.type = track.ValueTypeName; // mandatory
  26573. return json;
  26574. }
  26575. } );
  26576. Object.assign( KeyframeTrack.prototype, {
  26577. constructor: KeyframeTrack,
  26578. TimeBufferType: Float32Array,
  26579. ValueBufferType: Float32Array,
  26580. DefaultInterpolation: InterpolateLinear,
  26581. InterpolantFactoryMethodDiscrete: function ( result ) {
  26582. return new DiscreteInterpolant( this.times, this.values, this.getValueSize(), result );
  26583. },
  26584. InterpolantFactoryMethodLinear: function ( result ) {
  26585. return new LinearInterpolant( this.times, this.values, this.getValueSize(), result );
  26586. },
  26587. InterpolantFactoryMethodSmooth: function ( result ) {
  26588. return new CubicInterpolant( this.times, this.values, this.getValueSize(), result );
  26589. },
  26590. setInterpolation: function ( interpolation ) {
  26591. var factoryMethod;
  26592. switch ( interpolation ) {
  26593. case InterpolateDiscrete:
  26594. factoryMethod = this.InterpolantFactoryMethodDiscrete;
  26595. break;
  26596. case InterpolateLinear:
  26597. factoryMethod = this.InterpolantFactoryMethodLinear;
  26598. break;
  26599. case InterpolateSmooth:
  26600. factoryMethod = this.InterpolantFactoryMethodSmooth;
  26601. break;
  26602. }
  26603. if ( factoryMethod === undefined ) {
  26604. var message = "unsupported interpolation for " +
  26605. this.ValueTypeName + " keyframe track named " + this.name;
  26606. if ( this.createInterpolant === undefined ) {
  26607. // fall back to default, unless the default itself is messed up
  26608. if ( interpolation !== this.DefaultInterpolation ) {
  26609. this.setInterpolation( this.DefaultInterpolation );
  26610. } else {
  26611. throw new Error( message ); // fatal, in this case
  26612. }
  26613. }
  26614. console.warn( 'THREE.KeyframeTrack:', message );
  26615. return this;
  26616. }
  26617. this.createInterpolant = factoryMethod;
  26618. return this;
  26619. },
  26620. getInterpolation: function () {
  26621. switch ( this.createInterpolant ) {
  26622. case this.InterpolantFactoryMethodDiscrete:
  26623. return InterpolateDiscrete;
  26624. case this.InterpolantFactoryMethodLinear:
  26625. return InterpolateLinear;
  26626. case this.InterpolantFactoryMethodSmooth:
  26627. return InterpolateSmooth;
  26628. }
  26629. },
  26630. getValueSize: function () {
  26631. return this.values.length / this.times.length;
  26632. },
  26633. // move all keyframes either forwards or backwards in time
  26634. shift: function ( timeOffset ) {
  26635. if ( timeOffset !== 0.0 ) {
  26636. var times = this.times;
  26637. for ( var i = 0, n = times.length; i !== n; ++ i ) {
  26638. times[ i ] += timeOffset;
  26639. }
  26640. }
  26641. return this;
  26642. },
  26643. // scale all keyframe times by a factor (useful for frame <-> seconds conversions)
  26644. scale: function ( timeScale ) {
  26645. if ( timeScale !== 1.0 ) {
  26646. var times = this.times;
  26647. for ( var i = 0, n = times.length; i !== n; ++ i ) {
  26648. times[ i ] *= timeScale;
  26649. }
  26650. }
  26651. return this;
  26652. },
  26653. // removes keyframes before and after animation without changing any values within the range [startTime, endTime].
  26654. // IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values
  26655. trim: function ( startTime, endTime ) {
  26656. var times = this.times,
  26657. nKeys = times.length,
  26658. from = 0,
  26659. to = nKeys - 1;
  26660. while ( from !== nKeys && times[ from ] < startTime ) {
  26661. ++ from;
  26662. }
  26663. while ( to !== - 1 && times[ to ] > endTime ) {
  26664. -- to;
  26665. }
  26666. ++ to; // inclusive -> exclusive bound
  26667. if ( from !== 0 || to !== nKeys ) {
  26668. // empty tracks are forbidden, so keep at least one keyframe
  26669. if ( from >= to ) {
  26670. to = Math.max( to, 1 );
  26671. from = to - 1;
  26672. }
  26673. var stride = this.getValueSize();
  26674. this.times = AnimationUtils.arraySlice( times, from, to );
  26675. this.values = AnimationUtils.arraySlice( this.values, from * stride, to * stride );
  26676. }
  26677. return this;
  26678. },
  26679. // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable
  26680. validate: function () {
  26681. var valid = true;
  26682. var valueSize = this.getValueSize();
  26683. if ( valueSize - Math.floor( valueSize ) !== 0 ) {
  26684. console.error( 'THREE.KeyframeTrack: Invalid value size in track.', this );
  26685. valid = false;
  26686. }
  26687. var times = this.times,
  26688. values = this.values,
  26689. nKeys = times.length;
  26690. if ( nKeys === 0 ) {
  26691. console.error( 'THREE.KeyframeTrack: Track is empty.', this );
  26692. valid = false;
  26693. }
  26694. var prevTime = null;
  26695. for ( var i = 0; i !== nKeys; i ++ ) {
  26696. var currTime = times[ i ];
  26697. if ( typeof currTime === 'number' && isNaN( currTime ) ) {
  26698. console.error( 'THREE.KeyframeTrack: Time is not a valid number.', this, i, currTime );
  26699. valid = false;
  26700. break;
  26701. }
  26702. if ( prevTime !== null && prevTime > currTime ) {
  26703. console.error( 'THREE.KeyframeTrack: Out of order keys.', this, i, currTime, prevTime );
  26704. valid = false;
  26705. break;
  26706. }
  26707. prevTime = currTime;
  26708. }
  26709. if ( values !== undefined ) {
  26710. if ( AnimationUtils.isTypedArray( values ) ) {
  26711. for ( var i = 0, n = values.length; i !== n; ++ i ) {
  26712. var value = values[ i ];
  26713. if ( isNaN( value ) ) {
  26714. console.error( 'THREE.KeyframeTrack: Value is not a valid number.', this, i, value );
  26715. valid = false;
  26716. break;
  26717. }
  26718. }
  26719. }
  26720. }
  26721. return valid;
  26722. },
  26723. // removes equivalent sequential keys as common in morph target sequences
  26724. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  26725. optimize: function () {
  26726. // times or values may be shared with other tracks, so overwriting is unsafe
  26727. var times = AnimationUtils.arraySlice( this.times ),
  26728. values = AnimationUtils.arraySlice( this.values ),
  26729. stride = this.getValueSize(),
  26730. smoothInterpolation = this.getInterpolation() === InterpolateSmooth,
  26731. writeIndex = 1,
  26732. lastIndex = times.length - 1;
  26733. for ( var i = 1; i < lastIndex; ++ i ) {
  26734. var keep = false;
  26735. var time = times[ i ];
  26736. var timeNext = times[ i + 1 ];
  26737. // remove adjacent keyframes scheduled at the same time
  26738. if ( time !== timeNext && ( i !== 1 || time !== time[ 0 ] ) ) {
  26739. if ( ! smoothInterpolation ) {
  26740. // remove unnecessary keyframes same as their neighbors
  26741. var offset = i * stride,
  26742. offsetP = offset - stride,
  26743. offsetN = offset + stride;
  26744. for ( var j = 0; j !== stride; ++ j ) {
  26745. var value = values[ offset + j ];
  26746. if ( value !== values[ offsetP + j ] ||
  26747. value !== values[ offsetN + j ] ) {
  26748. keep = true;
  26749. break;
  26750. }
  26751. }
  26752. } else {
  26753. keep = true;
  26754. }
  26755. }
  26756. // in-place compaction
  26757. if ( keep ) {
  26758. if ( i !== writeIndex ) {
  26759. times[ writeIndex ] = times[ i ];
  26760. var readOffset = i * stride,
  26761. writeOffset = writeIndex * stride;
  26762. for ( var j = 0; j !== stride; ++ j ) {
  26763. values[ writeOffset + j ] = values[ readOffset + j ];
  26764. }
  26765. }
  26766. ++ writeIndex;
  26767. }
  26768. }
  26769. // flush last keyframe (compaction looks ahead)
  26770. if ( lastIndex > 0 ) {
  26771. times[ writeIndex ] = times[ lastIndex ];
  26772. for ( var readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++ j ) {
  26773. values[ writeOffset + j ] = values[ readOffset + j ];
  26774. }
  26775. ++ writeIndex;
  26776. }
  26777. if ( writeIndex !== times.length ) {
  26778. this.times = AnimationUtils.arraySlice( times, 0, writeIndex );
  26779. this.values = AnimationUtils.arraySlice( values, 0, writeIndex * stride );
  26780. } else {
  26781. this.times = times;
  26782. this.values = values;
  26783. }
  26784. return this;
  26785. },
  26786. clone: function () {
  26787. var times = AnimationUtils.arraySlice( this.times, 0 );
  26788. var values = AnimationUtils.arraySlice( this.values, 0 );
  26789. var TypedKeyframeTrack = this.constructor;
  26790. var track = new TypedKeyframeTrack( this.name, times, values );
  26791. // Interpolant argument to constructor is not saved, so copy the factory method directly.
  26792. track.createInterpolant = this.createInterpolant;
  26793. return track;
  26794. }
  26795. } );
  26796. /**
  26797. *
  26798. * A Track of Boolean keyframe values.
  26799. *
  26800. *
  26801. * @author Ben Houston / http://clara.io/
  26802. * @author David Sarno / http://lighthaus.us/
  26803. * @author tschw
  26804. */
  26805. function BooleanKeyframeTrack( name, times, values ) {
  26806. KeyframeTrack.call( this, name, times, values );
  26807. }
  26808. BooleanKeyframeTrack.prototype = Object.assign( Object.create( KeyframeTrack.prototype ), {
  26809. constructor: BooleanKeyframeTrack,
  26810. ValueTypeName: 'bool',
  26811. ValueBufferType: Array,
  26812. DefaultInterpolation: InterpolateDiscrete,
  26813. InterpolantFactoryMethodLinear: undefined,
  26814. InterpolantFactoryMethodSmooth: undefined
  26815. // Note: Actually this track could have a optimized / compressed
  26816. // representation of a single value and a custom interpolant that
  26817. // computes "firstValue ^ isOdd( index )".
  26818. } );
  26819. /**
  26820. *
  26821. * A Track of keyframe values that represent color.
  26822. *
  26823. *
  26824. * @author Ben Houston / http://clara.io/
  26825. * @author David Sarno / http://lighthaus.us/
  26826. * @author tschw
  26827. */
  26828. function ColorKeyframeTrack( name, times, values, interpolation ) {
  26829. KeyframeTrack.call( this, name, times, values, interpolation );
  26830. }
  26831. ColorKeyframeTrack.prototype = Object.assign( Object.create( KeyframeTrack.prototype ), {
  26832. constructor: ColorKeyframeTrack,
  26833. ValueTypeName: 'color'
  26834. // ValueBufferType is inherited
  26835. // DefaultInterpolation is inherited
  26836. // Note: Very basic implementation and nothing special yet.
  26837. // However, this is the place for color space parameterization.
  26838. } );
  26839. /**
  26840. *
  26841. * A Track of numeric keyframe values.
  26842. *
  26843. * @author Ben Houston / http://clara.io/
  26844. * @author David Sarno / http://lighthaus.us/
  26845. * @author tschw
  26846. */
  26847. function NumberKeyframeTrack( name, times, values, interpolation ) {
  26848. KeyframeTrack.call( this, name, times, values, interpolation );
  26849. }
  26850. NumberKeyframeTrack.prototype = Object.assign( Object.create( KeyframeTrack.prototype ), {
  26851. constructor: NumberKeyframeTrack,
  26852. ValueTypeName: 'number'
  26853. // ValueBufferType is inherited
  26854. // DefaultInterpolation is inherited
  26855. } );
  26856. /**
  26857. * Spherical linear unit quaternion interpolant.
  26858. *
  26859. * @author tschw
  26860. */
  26861. function QuaternionLinearInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  26862. Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  26863. }
  26864. QuaternionLinearInterpolant.prototype = Object.assign( Object.create( Interpolant.prototype ), {
  26865. constructor: QuaternionLinearInterpolant,
  26866. interpolate_: function ( i1, t0, t, t1 ) {
  26867. var result = this.resultBuffer,
  26868. values = this.sampleValues,
  26869. stride = this.valueSize,
  26870. offset = i1 * stride,
  26871. alpha = ( t - t0 ) / ( t1 - t0 );
  26872. for ( var end = offset + stride; offset !== end; offset += 4 ) {
  26873. Quaternion.slerpFlat( result, 0, values, offset - stride, values, offset, alpha );
  26874. }
  26875. return result;
  26876. }
  26877. } );
  26878. /**
  26879. *
  26880. * A Track of quaternion keyframe values.
  26881. *
  26882. * @author Ben Houston / http://clara.io/
  26883. * @author David Sarno / http://lighthaus.us/
  26884. * @author tschw
  26885. */
  26886. function QuaternionKeyframeTrack( name, times, values, interpolation ) {
  26887. KeyframeTrack.call( this, name, times, values, interpolation );
  26888. }
  26889. QuaternionKeyframeTrack.prototype = Object.assign( Object.create( KeyframeTrack.prototype ), {
  26890. constructor: QuaternionKeyframeTrack,
  26891. ValueTypeName: 'quaternion',
  26892. // ValueBufferType is inherited
  26893. DefaultInterpolation: InterpolateLinear,
  26894. InterpolantFactoryMethodLinear: function ( result ) {
  26895. return new QuaternionLinearInterpolant( this.times, this.values, this.getValueSize(), result );
  26896. },
  26897. InterpolantFactoryMethodSmooth: undefined // not yet implemented
  26898. } );
  26899. /**
  26900. *
  26901. * A Track that interpolates Strings
  26902. *
  26903. *
  26904. * @author Ben Houston / http://clara.io/
  26905. * @author David Sarno / http://lighthaus.us/
  26906. * @author tschw
  26907. */
  26908. function StringKeyframeTrack( name, times, values, interpolation ) {
  26909. KeyframeTrack.call( this, name, times, values, interpolation );
  26910. }
  26911. StringKeyframeTrack.prototype = Object.assign( Object.create( KeyframeTrack.prototype ), {
  26912. constructor: StringKeyframeTrack,
  26913. ValueTypeName: 'string',
  26914. ValueBufferType: Array,
  26915. DefaultInterpolation: InterpolateDiscrete,
  26916. InterpolantFactoryMethodLinear: undefined,
  26917. InterpolantFactoryMethodSmooth: undefined
  26918. } );
  26919. /**
  26920. *
  26921. * A Track of vectored keyframe values.
  26922. *
  26923. *
  26924. * @author Ben Houston / http://clara.io/
  26925. * @author David Sarno / http://lighthaus.us/
  26926. * @author tschw
  26927. */
  26928. function VectorKeyframeTrack( name, times, values, interpolation ) {
  26929. KeyframeTrack.call( this, name, times, values, interpolation );
  26930. }
  26931. VectorKeyframeTrack.prototype = Object.assign( Object.create( KeyframeTrack.prototype ), {
  26932. constructor: VectorKeyframeTrack,
  26933. ValueTypeName: 'vector'
  26934. // ValueBufferType is inherited
  26935. // DefaultInterpolation is inherited
  26936. } );
  26937. /**
  26938. *
  26939. * Reusable set of Tracks that represent an animation.
  26940. *
  26941. * @author Ben Houston / http://clara.io/
  26942. * @author David Sarno / http://lighthaus.us/
  26943. */
  26944. function AnimationClip( name, duration, tracks ) {
  26945. this.name = name;
  26946. this.tracks = tracks;
  26947. this.duration = ( duration !== undefined ) ? duration : - 1;
  26948. this.uuid = MathUtils.generateUUID();
  26949. // this means it should figure out its duration by scanning the tracks
  26950. if ( this.duration < 0 ) {
  26951. this.resetDuration();
  26952. }
  26953. }
  26954. function getTrackTypeForValueTypeName( typeName ) {
  26955. switch ( typeName.toLowerCase() ) {
  26956. case 'scalar':
  26957. case 'double':
  26958. case 'float':
  26959. case 'number':
  26960. case 'integer':
  26961. return NumberKeyframeTrack;
  26962. case 'vector':
  26963. case 'vector2':
  26964. case 'vector3':
  26965. case 'vector4':
  26966. return VectorKeyframeTrack;
  26967. case 'color':
  26968. return ColorKeyframeTrack;
  26969. case 'quaternion':
  26970. return QuaternionKeyframeTrack;
  26971. case 'bool':
  26972. case 'boolean':
  26973. return BooleanKeyframeTrack;
  26974. case 'string':
  26975. return StringKeyframeTrack;
  26976. }
  26977. throw new Error( 'THREE.KeyframeTrack: Unsupported typeName: ' + typeName );
  26978. }
  26979. function parseKeyframeTrack( json ) {
  26980. if ( json.type === undefined ) {
  26981. throw new Error( 'THREE.KeyframeTrack: track type undefined, can not parse' );
  26982. }
  26983. var trackType = getTrackTypeForValueTypeName( json.type );
  26984. if ( json.times === undefined ) {
  26985. var times = [], values = [];
  26986. AnimationUtils.flattenJSON( json.keys, times, values, 'value' );
  26987. json.times = times;
  26988. json.values = values;
  26989. }
  26990. // derived classes can define a static parse method
  26991. if ( trackType.parse !== undefined ) {
  26992. return trackType.parse( json );
  26993. } else {
  26994. // by default, we assume a constructor compatible with the base
  26995. return new trackType( json.name, json.times, json.values, json.interpolation );
  26996. }
  26997. }
  26998. Object.assign( AnimationClip, {
  26999. parse: function ( json ) {
  27000. var tracks = [],
  27001. jsonTracks = json.tracks,
  27002. frameTime = 1.0 / ( json.fps || 1.0 );
  27003. for ( var i = 0, n = jsonTracks.length; i !== n; ++ i ) {
  27004. tracks.push( parseKeyframeTrack( jsonTracks[ i ] ).scale( frameTime ) );
  27005. }
  27006. return new AnimationClip( json.name, json.duration, tracks );
  27007. },
  27008. toJSON: function ( clip ) {
  27009. var tracks = [],
  27010. clipTracks = clip.tracks;
  27011. var json = {
  27012. 'name': clip.name,
  27013. 'duration': clip.duration,
  27014. 'tracks': tracks,
  27015. 'uuid': clip.uuid
  27016. };
  27017. for ( var i = 0, n = clipTracks.length; i !== n; ++ i ) {
  27018. tracks.push( KeyframeTrack.toJSON( clipTracks[ i ] ) );
  27019. }
  27020. return json;
  27021. },
  27022. CreateFromMorphTargetSequence: function ( name, morphTargetSequence, fps, noLoop ) {
  27023. var numMorphTargets = morphTargetSequence.length;
  27024. var tracks = [];
  27025. for ( var i = 0; i < numMorphTargets; i ++ ) {
  27026. var times = [];
  27027. var values = [];
  27028. times.push(
  27029. ( i + numMorphTargets - 1 ) % numMorphTargets,
  27030. i,
  27031. ( i + 1 ) % numMorphTargets );
  27032. values.push( 0, 1, 0 );
  27033. var order = AnimationUtils.getKeyframeOrder( times );
  27034. times = AnimationUtils.sortedArray( times, 1, order );
  27035. values = AnimationUtils.sortedArray( values, 1, order );
  27036. // if there is a key at the first frame, duplicate it as the
  27037. // last frame as well for perfect loop.
  27038. if ( ! noLoop && times[ 0 ] === 0 ) {
  27039. times.push( numMorphTargets );
  27040. values.push( values[ 0 ] );
  27041. }
  27042. tracks.push(
  27043. new NumberKeyframeTrack(
  27044. '.morphTargetInfluences[' + morphTargetSequence[ i ].name + ']',
  27045. times, values
  27046. ).scale( 1.0 / fps ) );
  27047. }
  27048. return new AnimationClip( name, - 1, tracks );
  27049. },
  27050. findByName: function ( objectOrClipArray, name ) {
  27051. var clipArray = objectOrClipArray;
  27052. if ( ! Array.isArray( objectOrClipArray ) ) {
  27053. var o = objectOrClipArray;
  27054. clipArray = o.geometry && o.geometry.animations || o.animations;
  27055. }
  27056. for ( var i = 0; i < clipArray.length; i ++ ) {
  27057. if ( clipArray[ i ].name === name ) {
  27058. return clipArray[ i ];
  27059. }
  27060. }
  27061. return null;
  27062. },
  27063. CreateClipsFromMorphTargetSequences: function ( morphTargets, fps, noLoop ) {
  27064. var animationToMorphTargets = {};
  27065. // tested with https://regex101.com/ on trick sequences
  27066. // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  27067. var pattern = /^([\w-]*?)([\d]+)$/;
  27068. // sort morph target names into animation groups based
  27069. // patterns like Walk_001, Walk_002, Run_001, Run_002
  27070. for ( var i = 0, il = morphTargets.length; i < il; i ++ ) {
  27071. var morphTarget = morphTargets[ i ];
  27072. var parts = morphTarget.name.match( pattern );
  27073. if ( parts && parts.length > 1 ) {
  27074. var name = parts[ 1 ];
  27075. var animationMorphTargets = animationToMorphTargets[ name ];
  27076. if ( ! animationMorphTargets ) {
  27077. animationToMorphTargets[ name ] = animationMorphTargets = [];
  27078. }
  27079. animationMorphTargets.push( morphTarget );
  27080. }
  27081. }
  27082. var clips = [];
  27083. for ( var name in animationToMorphTargets ) {
  27084. clips.push( AnimationClip.CreateFromMorphTargetSequence( name, animationToMorphTargets[ name ], fps, noLoop ) );
  27085. }
  27086. return clips;
  27087. },
  27088. // parse the animation.hierarchy format
  27089. parseAnimation: function ( animation, bones ) {
  27090. if ( ! animation ) {
  27091. console.error( 'THREE.AnimationClip: No animation in JSONLoader data.' );
  27092. return null;
  27093. }
  27094. var addNonemptyTrack = function ( trackType, trackName, animationKeys, propertyName, destTracks ) {
  27095. // only return track if there are actually keys.
  27096. if ( animationKeys.length !== 0 ) {
  27097. var times = [];
  27098. var values = [];
  27099. AnimationUtils.flattenJSON( animationKeys, times, values, propertyName );
  27100. // empty keys are filtered out, so check again
  27101. if ( times.length !== 0 ) {
  27102. destTracks.push( new trackType( trackName, times, values ) );
  27103. }
  27104. }
  27105. };
  27106. var tracks = [];
  27107. var clipName = animation.name || 'default';
  27108. // automatic length determination in AnimationClip.
  27109. var duration = animation.length || - 1;
  27110. var fps = animation.fps || 30;
  27111. var hierarchyTracks = animation.hierarchy || [];
  27112. for ( var h = 0; h < hierarchyTracks.length; h ++ ) {
  27113. var animationKeys = hierarchyTracks[ h ].keys;
  27114. // skip empty tracks
  27115. if ( ! animationKeys || animationKeys.length === 0 ) { continue; }
  27116. // process morph targets
  27117. if ( animationKeys[ 0 ].morphTargets ) {
  27118. // figure out all morph targets used in this track
  27119. var morphTargetNames = {};
  27120. for ( var k = 0; k < animationKeys.length; k ++ ) {
  27121. if ( animationKeys[ k ].morphTargets ) {
  27122. for ( var m = 0; m < animationKeys[ k ].morphTargets.length; m ++ ) {
  27123. morphTargetNames[ animationKeys[ k ].morphTargets[ m ] ] = - 1;
  27124. }
  27125. }
  27126. }
  27127. // create a track for each morph target with all zero
  27128. // morphTargetInfluences except for the keys in which
  27129. // the morphTarget is named.
  27130. for ( var morphTargetName in morphTargetNames ) {
  27131. var times = [];
  27132. var values = [];
  27133. for ( var m = 0; m !== animationKeys[ k ].morphTargets.length; ++ m ) {
  27134. var animationKey = animationKeys[ k ];
  27135. times.push( animationKey.time );
  27136. values.push( ( animationKey.morphTarget === morphTargetName ) ? 1 : 0 );
  27137. }
  27138. tracks.push( new NumberKeyframeTrack( '.morphTargetInfluence[' + morphTargetName + ']', times, values ) );
  27139. }
  27140. duration = morphTargetNames.length * ( fps || 1.0 );
  27141. } else {
  27142. // ...assume skeletal animation
  27143. var boneName = '.bones[' + bones[ h ].name + ']';
  27144. addNonemptyTrack(
  27145. VectorKeyframeTrack, boneName + '.position',
  27146. animationKeys, 'pos', tracks );
  27147. addNonemptyTrack(
  27148. QuaternionKeyframeTrack, boneName + '.quaternion',
  27149. animationKeys, 'rot', tracks );
  27150. addNonemptyTrack(
  27151. VectorKeyframeTrack, boneName + '.scale',
  27152. animationKeys, 'scl', tracks );
  27153. }
  27154. }
  27155. if ( tracks.length === 0 ) {
  27156. return null;
  27157. }
  27158. var clip = new AnimationClip( clipName, duration, tracks );
  27159. return clip;
  27160. }
  27161. } );
  27162. Object.assign( AnimationClip.prototype, {
  27163. resetDuration: function () {
  27164. var tracks = this.tracks, duration = 0;
  27165. for ( var i = 0, n = tracks.length; i !== n; ++ i ) {
  27166. var track = this.tracks[ i ];
  27167. duration = Math.max( duration, track.times[ track.times.length - 1 ] );
  27168. }
  27169. this.duration = duration;
  27170. return this;
  27171. },
  27172. trim: function () {
  27173. for ( var i = 0; i < this.tracks.length; i ++ ) {
  27174. this.tracks[ i ].trim( 0, this.duration );
  27175. }
  27176. return this;
  27177. },
  27178. validate: function () {
  27179. var valid = true;
  27180. for ( var i = 0; i < this.tracks.length; i ++ ) {
  27181. valid = valid && this.tracks[ i ].validate();
  27182. }
  27183. return valid;
  27184. },
  27185. optimize: function () {
  27186. for ( var i = 0; i < this.tracks.length; i ++ ) {
  27187. this.tracks[ i ].optimize();
  27188. }
  27189. return this;
  27190. },
  27191. clone: function () {
  27192. var tracks = [];
  27193. for ( var i = 0; i < this.tracks.length; i ++ ) {
  27194. tracks.push( this.tracks[ i ].clone() );
  27195. }
  27196. return new AnimationClip( this.name, this.duration, tracks );
  27197. }
  27198. } );
  27199. /**
  27200. * @author mrdoob / http://mrdoob.com/
  27201. */
  27202. var Cache = {
  27203. enabled: false,
  27204. files: {},
  27205. add: function ( key, file ) {
  27206. if ( this.enabled === false ) { return; }
  27207. // console.log( 'THREE.Cache', 'Adding key:', key );
  27208. this.files[ key ] = file;
  27209. },
  27210. get: function ( key ) {
  27211. if ( this.enabled === false ) { return; }
  27212. // console.log( 'THREE.Cache', 'Checking key:', key );
  27213. return this.files[ key ];
  27214. },
  27215. remove: function ( key ) {
  27216. delete this.files[ key ];
  27217. },
  27218. clear: function () {
  27219. this.files = {};
  27220. }
  27221. };
  27222. /**
  27223. * @author mrdoob / http://mrdoob.com/
  27224. */
  27225. function LoadingManager( onLoad, onProgress, onError ) {
  27226. var scope = this;
  27227. var isLoading = false;
  27228. var itemsLoaded = 0;
  27229. var itemsTotal = 0;
  27230. var urlModifier = undefined;
  27231. var handlers = [];
  27232. // Refer to #5689 for the reason why we don't set .onStart
  27233. // in the constructor
  27234. this.onStart = undefined;
  27235. this.onLoad = onLoad;
  27236. this.onProgress = onProgress;
  27237. this.onError = onError;
  27238. this.itemStart = function ( url ) {
  27239. itemsTotal ++;
  27240. if ( isLoading === false ) {
  27241. if ( scope.onStart !== undefined ) {
  27242. scope.onStart( url, itemsLoaded, itemsTotal );
  27243. }
  27244. }
  27245. isLoading = true;
  27246. };
  27247. this.itemEnd = function ( url ) {
  27248. itemsLoaded ++;
  27249. if ( scope.onProgress !== undefined ) {
  27250. scope.onProgress( url, itemsLoaded, itemsTotal );
  27251. }
  27252. if ( itemsLoaded === itemsTotal ) {
  27253. isLoading = false;
  27254. if ( scope.onLoad !== undefined ) {
  27255. scope.onLoad();
  27256. }
  27257. }
  27258. };
  27259. this.itemError = function ( url ) {
  27260. if ( scope.onError !== undefined ) {
  27261. scope.onError( url );
  27262. }
  27263. };
  27264. this.resolveURL = function ( url ) {
  27265. if ( urlModifier ) {
  27266. return urlModifier( url );
  27267. }
  27268. return url;
  27269. };
  27270. this.setURLModifier = function ( transform ) {
  27271. urlModifier = transform;
  27272. return this;
  27273. };
  27274. this.addHandler = function ( regex, loader ) {
  27275. handlers.push( regex, loader );
  27276. return this;
  27277. };
  27278. this.removeHandler = function ( regex ) {
  27279. var index = handlers.indexOf( regex );
  27280. if ( index !== - 1 ) {
  27281. handlers.splice( index, 2 );
  27282. }
  27283. return this;
  27284. };
  27285. this.getHandler = function ( file ) {
  27286. for ( var i = 0, l = handlers.length; i < l; i += 2 ) {
  27287. var regex = handlers[ i ];
  27288. var loader = handlers[ i + 1 ];
  27289. if ( regex.global ) { regex.lastIndex = 0; } // see #17920
  27290. if ( regex.test( file ) ) {
  27291. return loader;
  27292. }
  27293. }
  27294. return null;
  27295. };
  27296. }
  27297. var DefaultLoadingManager = new LoadingManager();
  27298. /**
  27299. * @author alteredq / http://alteredqualia.com/
  27300. */
  27301. function Loader( manager ) {
  27302. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  27303. this.crossOrigin = 'anonymous';
  27304. this.path = '';
  27305. this.resourcePath = '';
  27306. }
  27307. Object.assign( Loader.prototype, {
  27308. load: function ( /* url, onLoad, onProgress, onError */ ) {},
  27309. parse: function ( /* data */ ) {},
  27310. setCrossOrigin: function ( crossOrigin ) {
  27311. this.crossOrigin = crossOrigin;
  27312. return this;
  27313. },
  27314. setPath: function ( path ) {
  27315. this.path = path;
  27316. return this;
  27317. },
  27318. setResourcePath: function ( resourcePath ) {
  27319. this.resourcePath = resourcePath;
  27320. return this;
  27321. }
  27322. } );
  27323. /**
  27324. * @author mrdoob / http://mrdoob.com/
  27325. */
  27326. var loading = {};
  27327. function FileLoader( manager ) {
  27328. Loader.call( this, manager );
  27329. }
  27330. FileLoader.prototype = Object.assign( Object.create( Loader.prototype ), {
  27331. constructor: FileLoader,
  27332. load: function ( url, onLoad, onProgress, onError ) {
  27333. if ( url === undefined ) { url = ''; }
  27334. if ( this.path !== undefined ) { url = this.path + url; }
  27335. url = this.manager.resolveURL( url );
  27336. var scope = this;
  27337. var cached = Cache.get( url );
  27338. if ( cached !== undefined ) {
  27339. scope.manager.itemStart( url );
  27340. setTimeout( function () {
  27341. if ( onLoad ) { onLoad( cached ); }
  27342. scope.manager.itemEnd( url );
  27343. }, 0 );
  27344. return cached;
  27345. }
  27346. // Check if request is duplicate
  27347. if ( loading[ url ] !== undefined ) {
  27348. loading[ url ].push( {
  27349. onLoad: onLoad,
  27350. onProgress: onProgress,
  27351. onError: onError
  27352. } );
  27353. return;
  27354. }
  27355. // Check for data: URI
  27356. var dataUriRegex = /^data:(.*?)(;base64)?,(.*)$/;
  27357. var dataUriRegexResult = url.match( dataUriRegex );
  27358. // Safari can not handle Data URIs through XMLHttpRequest so process manually
  27359. if ( dataUriRegexResult ) {
  27360. var mimeType = dataUriRegexResult[ 1 ];
  27361. var isBase64 = !! dataUriRegexResult[ 2 ];
  27362. var data = dataUriRegexResult[ 3 ];
  27363. data = decodeURIComponent( data );
  27364. if ( isBase64 ) { data = atob( data ); }
  27365. try {
  27366. var response;
  27367. var responseType = ( this.responseType || '' ).toLowerCase();
  27368. switch ( responseType ) {
  27369. case 'arraybuffer':
  27370. case 'blob':
  27371. var view = new Uint8Array( data.length );
  27372. for ( var i = 0; i < data.length; i ++ ) {
  27373. view[ i ] = data.charCodeAt( i );
  27374. }
  27375. if ( responseType === 'blob' ) {
  27376. response = new Blob( [ view.buffer ], { type: mimeType } );
  27377. } else {
  27378. response = view.buffer;
  27379. }
  27380. break;
  27381. case 'document':
  27382. var parser = new DOMParser();
  27383. response = parser.parseFromString( data, mimeType );
  27384. break;
  27385. case 'json':
  27386. response = JSON.parse( data );
  27387. break;
  27388. default: // 'text' or other
  27389. response = data;
  27390. break;
  27391. }
  27392. // Wait for next browser tick like standard XMLHttpRequest event dispatching does
  27393. setTimeout( function () {
  27394. if ( onLoad ) { onLoad( response ); }
  27395. scope.manager.itemEnd( url );
  27396. }, 0 );
  27397. } catch ( error ) {
  27398. // Wait for next browser tick like standard XMLHttpRequest event dispatching does
  27399. setTimeout( function () {
  27400. if ( onError ) { onError( error ); }
  27401. scope.manager.itemError( url );
  27402. scope.manager.itemEnd( url );
  27403. }, 0 );
  27404. }
  27405. } else {
  27406. // Initialise array for duplicate requests
  27407. loading[ url ] = [];
  27408. loading[ url ].push( {
  27409. onLoad: onLoad,
  27410. onProgress: onProgress,
  27411. onError: onError
  27412. } );
  27413. var request = new XMLHttpRequest();
  27414. request.open( 'GET', url, true );
  27415. request.addEventListener( 'load', function ( event ) {
  27416. var response = this.response;
  27417. var callbacks = loading[ url ];
  27418. delete loading[ url ];
  27419. if ( this.status === 200 || this.status === 0 ) {
  27420. // Some browsers return HTTP Status 0 when using non-http protocol
  27421. // e.g. 'file://' or 'data://'. Handle as success.
  27422. if ( this.status === 0 ) { console.warn( 'THREE.FileLoader: HTTP Status 0 received.' ); }
  27423. // Add to cache only on HTTP success, so that we do not cache
  27424. // error response bodies as proper responses to requests.
  27425. Cache.add( url, response );
  27426. for ( var i = 0, il = callbacks.length; i < il; i ++ ) {
  27427. var callback = callbacks[ i ];
  27428. if ( callback.onLoad ) { callback.onLoad( response ); }
  27429. }
  27430. scope.manager.itemEnd( url );
  27431. } else {
  27432. for ( var i = 0, il = callbacks.length; i < il; i ++ ) {
  27433. var callback = callbacks[ i ];
  27434. if ( callback.onError ) { callback.onError( event ); }
  27435. }
  27436. scope.manager.itemError( url );
  27437. scope.manager.itemEnd( url );
  27438. }
  27439. }, false );
  27440. request.addEventListener( 'progress', function ( event ) {
  27441. var callbacks = loading[ url ];
  27442. for ( var i = 0, il = callbacks.length; i < il; i ++ ) {
  27443. var callback = callbacks[ i ];
  27444. if ( callback.onProgress ) { callback.onProgress( event ); }
  27445. }
  27446. }, false );
  27447. request.addEventListener( 'error', function ( event ) {
  27448. var callbacks = loading[ url ];
  27449. delete loading[ url ];
  27450. for ( var i = 0, il = callbacks.length; i < il; i ++ ) {
  27451. var callback = callbacks[ i ];
  27452. if ( callback.onError ) { callback.onError( event ); }
  27453. }
  27454. scope.manager.itemError( url );
  27455. scope.manager.itemEnd( url );
  27456. }, false );
  27457. request.addEventListener( 'abort', function ( event ) {
  27458. var callbacks = loading[ url ];
  27459. delete loading[ url ];
  27460. for ( var i = 0, il = callbacks.length; i < il; i ++ ) {
  27461. var callback = callbacks[ i ];
  27462. if ( callback.onError ) { callback.onError( event ); }
  27463. }
  27464. scope.manager.itemError( url );
  27465. scope.manager.itemEnd( url );
  27466. }, false );
  27467. if ( this.responseType !== undefined ) { request.responseType = this.responseType; }
  27468. if ( this.withCredentials !== undefined ) { request.withCredentials = this.withCredentials; }
  27469. if ( request.overrideMimeType ) { request.overrideMimeType( this.mimeType !== undefined ? this.mimeType : 'text/plain' ); }
  27470. for ( var header in this.requestHeader ) {
  27471. request.setRequestHeader( header, this.requestHeader[ header ] );
  27472. }
  27473. request.send( null );
  27474. }
  27475. scope.manager.itemStart( url );
  27476. return request;
  27477. },
  27478. setResponseType: function ( value ) {
  27479. this.responseType = value;
  27480. return this;
  27481. },
  27482. setWithCredentials: function ( value ) {
  27483. this.withCredentials = value;
  27484. return this;
  27485. },
  27486. setMimeType: function ( value ) {
  27487. this.mimeType = value;
  27488. return this;
  27489. },
  27490. setRequestHeader: function ( value ) {
  27491. this.requestHeader = value;
  27492. return this;
  27493. }
  27494. } );
  27495. /**
  27496. * @author bhouston / http://clara.io/
  27497. */
  27498. function AnimationLoader( manager ) {
  27499. Loader.call( this, manager );
  27500. }
  27501. AnimationLoader.prototype = Object.assign( Object.create( Loader.prototype ), {
  27502. constructor: AnimationLoader,
  27503. load: function ( url, onLoad, onProgress, onError ) {
  27504. var scope = this;
  27505. var loader = new FileLoader( scope.manager );
  27506. loader.setPath( scope.path );
  27507. loader.load( url, function ( text ) {
  27508. onLoad( scope.parse( JSON.parse( text ) ) );
  27509. }, onProgress, onError );
  27510. },
  27511. parse: function ( json ) {
  27512. var animations = [];
  27513. for ( var i = 0; i < json.length; i ++ ) {
  27514. var clip = AnimationClip.parse( json[ i ] );
  27515. animations.push( clip );
  27516. }
  27517. return animations;
  27518. }
  27519. } );
  27520. /**
  27521. * @author mrdoob / http://mrdoob.com/
  27522. *
  27523. * Abstract Base class to block based textures loader (dds, pvr, ...)
  27524. *
  27525. * Sub classes have to implement the parse() method which will be used in load().
  27526. */
  27527. function CompressedTextureLoader( manager ) {
  27528. Loader.call( this, manager );
  27529. }
  27530. CompressedTextureLoader.prototype = Object.assign( Object.create( Loader.prototype ), {
  27531. constructor: CompressedTextureLoader,
  27532. load: function ( url, onLoad, onProgress, onError ) {
  27533. var scope = this;
  27534. var images = [];
  27535. var texture = new CompressedTexture();
  27536. texture.image = images;
  27537. var loader = new FileLoader( this.manager );
  27538. loader.setPath( this.path );
  27539. loader.setResponseType( 'arraybuffer' );
  27540. function loadTexture( i ) {
  27541. loader.load( url[ i ], function ( buffer ) {
  27542. var texDatas = scope.parse( buffer, true );
  27543. images[ i ] = {
  27544. width: texDatas.width,
  27545. height: texDatas.height,
  27546. format: texDatas.format,
  27547. mipmaps: texDatas.mipmaps
  27548. };
  27549. loaded += 1;
  27550. if ( loaded === 6 ) {
  27551. if ( texDatas.mipmapCount === 1 )
  27552. { texture.minFilter = LinearFilter; }
  27553. texture.format = texDatas.format;
  27554. texture.needsUpdate = true;
  27555. if ( onLoad ) { onLoad( texture ); }
  27556. }
  27557. }, onProgress, onError );
  27558. }
  27559. if ( Array.isArray( url ) ) {
  27560. var loaded = 0;
  27561. for ( var i = 0, il = url.length; i < il; ++ i ) {
  27562. loadTexture( i );
  27563. }
  27564. } else {
  27565. // compressed cubemap texture stored in a single DDS file
  27566. loader.load( url, function ( buffer ) {
  27567. var texDatas = scope.parse( buffer, true );
  27568. if ( texDatas.isCubemap ) {
  27569. var faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  27570. for ( var f = 0; f < faces; f ++ ) {
  27571. images[ f ] = { mipmaps: [] };
  27572. for ( var i = 0; i < texDatas.mipmapCount; i ++ ) {
  27573. images[ f ].mipmaps.push( texDatas.mipmaps[ f * texDatas.mipmapCount + i ] );
  27574. images[ f ].format = texDatas.format;
  27575. images[ f ].width = texDatas.width;
  27576. images[ f ].height = texDatas.height;
  27577. }
  27578. }
  27579. } else {
  27580. texture.image.width = texDatas.width;
  27581. texture.image.height = texDatas.height;
  27582. texture.mipmaps = texDatas.mipmaps;
  27583. }
  27584. if ( texDatas.mipmapCount === 1 ) {
  27585. texture.minFilter = LinearFilter;
  27586. }
  27587. texture.format = texDatas.format;
  27588. texture.needsUpdate = true;
  27589. if ( onLoad ) { onLoad( texture ); }
  27590. }, onProgress, onError );
  27591. }
  27592. return texture;
  27593. }
  27594. } );
  27595. /**
  27596. * @author Nikos M. / https://github.com/foo123/
  27597. *
  27598. * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...)
  27599. *
  27600. * Sub classes have to implement the parse() method which will be used in load().
  27601. */
  27602. function DataTextureLoader( manager ) {
  27603. Loader.call( this, manager );
  27604. }
  27605. DataTextureLoader.prototype = Object.assign( Object.create( Loader.prototype ), {
  27606. constructor: DataTextureLoader,
  27607. load: function ( url, onLoad, onProgress, onError ) {
  27608. var scope = this;
  27609. var texture = new DataTexture();
  27610. var loader = new FileLoader( this.manager );
  27611. loader.setResponseType( 'arraybuffer' );
  27612. loader.setPath( this.path );
  27613. loader.load( url, function ( buffer ) {
  27614. var texData = scope.parse( buffer );
  27615. if ( ! texData ) { return; }
  27616. if ( texData.image !== undefined ) {
  27617. texture.image = texData.image;
  27618. } else if ( texData.data !== undefined ) {
  27619. texture.image.width = texData.width;
  27620. texture.image.height = texData.height;
  27621. texture.image.data = texData.data;
  27622. }
  27623. texture.wrapS = texData.wrapS !== undefined ? texData.wrapS : ClampToEdgeWrapping;
  27624. texture.wrapT = texData.wrapT !== undefined ? texData.wrapT : ClampToEdgeWrapping;
  27625. texture.magFilter = texData.magFilter !== undefined ? texData.magFilter : LinearFilter;
  27626. texture.minFilter = texData.minFilter !== undefined ? texData.minFilter : LinearFilter;
  27627. texture.anisotropy = texData.anisotropy !== undefined ? texData.anisotropy : 1;
  27628. if ( texData.format !== undefined ) {
  27629. texture.format = texData.format;
  27630. }
  27631. if ( texData.type !== undefined ) {
  27632. texture.type = texData.type;
  27633. }
  27634. if ( texData.mipmaps !== undefined ) {
  27635. texture.mipmaps = texData.mipmaps;
  27636. texture.minFilter = LinearMipmapLinearFilter; // presumably...
  27637. }
  27638. if ( texData.mipmapCount === 1 ) {
  27639. texture.minFilter = LinearFilter;
  27640. }
  27641. texture.needsUpdate = true;
  27642. if ( onLoad ) { onLoad( texture, texData ); }
  27643. }, onProgress, onError );
  27644. return texture;
  27645. }
  27646. } );
  27647. /**
  27648. * @author mrdoob / http://mrdoob.com/
  27649. */
  27650. function ImageLoader( manager ) {
  27651. Loader.call( this, manager );
  27652. }
  27653. ImageLoader.prototype = Object.assign( Object.create( Loader.prototype ), {
  27654. constructor: ImageLoader,
  27655. load: function ( url, onLoad, onProgress, onError ) {
  27656. if ( this.path !== undefined ) { url = this.path + url; }
  27657. url = this.manager.resolveURL( url );
  27658. var scope = this;
  27659. var cached = Cache.get( url );
  27660. if ( cached !== undefined ) {
  27661. scope.manager.itemStart( url );
  27662. setTimeout( function () {
  27663. if ( onLoad ) { onLoad( cached ); }
  27664. scope.manager.itemEnd( url );
  27665. }, 0 );
  27666. return cached;
  27667. }
  27668. var image = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'img' );
  27669. function onImageLoad() {
  27670. image.removeEventListener( 'load', onImageLoad, false );
  27671. image.removeEventListener( 'error', onImageError, false );
  27672. Cache.add( url, this );
  27673. if ( onLoad ) { onLoad( this ); }
  27674. scope.manager.itemEnd( url );
  27675. }
  27676. function onImageError( event ) {
  27677. image.removeEventListener( 'load', onImageLoad, false );
  27678. image.removeEventListener( 'error', onImageError, false );
  27679. if ( onError ) { onError( event ); }
  27680. scope.manager.itemError( url );
  27681. scope.manager.itemEnd( url );
  27682. }
  27683. image.addEventListener( 'load', onImageLoad, false );
  27684. image.addEventListener( 'error', onImageError, false );
  27685. if ( url.substr( 0, 5 ) !== 'data:' ) {
  27686. if ( this.crossOrigin !== undefined ) { image.crossOrigin = this.crossOrigin; }
  27687. }
  27688. scope.manager.itemStart( url );
  27689. image.src = url;
  27690. return image;
  27691. }
  27692. } );
  27693. /**
  27694. * @author mrdoob / http://mrdoob.com/
  27695. */
  27696. function CubeTextureLoader( manager ) {
  27697. Loader.call( this, manager );
  27698. }
  27699. CubeTextureLoader.prototype = Object.assign( Object.create( Loader.prototype ), {
  27700. constructor: CubeTextureLoader,
  27701. load: function ( urls, onLoad, onProgress, onError ) {
  27702. var texture = new CubeTexture();
  27703. var loader = new ImageLoader( this.manager );
  27704. loader.setCrossOrigin( this.crossOrigin );
  27705. loader.setPath( this.path );
  27706. var loaded = 0;
  27707. function loadTexture( i ) {
  27708. loader.load( urls[ i ], function ( image ) {
  27709. texture.images[ i ] = image;
  27710. loaded ++;
  27711. if ( loaded === 6 ) {
  27712. texture.needsUpdate = true;
  27713. if ( onLoad ) { onLoad( texture ); }
  27714. }
  27715. }, undefined, onError );
  27716. }
  27717. for ( var i = 0; i < urls.length; ++ i ) {
  27718. loadTexture( i );
  27719. }
  27720. return texture;
  27721. }
  27722. } );
  27723. /**
  27724. * @author mrdoob / http://mrdoob.com/
  27725. */
  27726. function TextureLoader( manager ) {
  27727. Loader.call( this, manager );
  27728. }
  27729. TextureLoader.prototype = Object.assign( Object.create( Loader.prototype ), {
  27730. constructor: TextureLoader,
  27731. load: function ( url, onLoad, onProgress, onError ) {
  27732. var texture = new Texture();
  27733. var loader = new ImageLoader( this.manager );
  27734. loader.setCrossOrigin( this.crossOrigin );
  27735. loader.setPath( this.path );
  27736. loader.load( url, function ( image ) {
  27737. texture.image = image;
  27738. // JPEGs can't have an alpha channel, so memory can be saved by storing them as RGB.
  27739. var isJPEG = url.search( /\.jpe?g($|\?)/i ) > 0 || url.search( /^data\:image\/jpeg/ ) === 0;
  27740. texture.format = isJPEG ? RGBFormat : RGBAFormat;
  27741. texture.needsUpdate = true;
  27742. if ( onLoad !== undefined ) {
  27743. onLoad( texture );
  27744. }
  27745. }, onProgress, onError );
  27746. return texture;
  27747. }
  27748. } );
  27749. /**
  27750. * @author zz85 / http://www.lab4games.net/zz85/blog
  27751. * Extensible curve object
  27752. *
  27753. * Some common of curve methods:
  27754. * .getPoint( t, optionalTarget ), .getTangent( t )
  27755. * .getPointAt( u, optionalTarget ), .getTangentAt( u )
  27756. * .getPoints(), .getSpacedPoints()
  27757. * .getLength()
  27758. * .updateArcLengths()
  27759. *
  27760. * This following curves inherit from THREE.Curve:
  27761. *
  27762. * -- 2D curves --
  27763. * THREE.ArcCurve
  27764. * THREE.CubicBezierCurve
  27765. * THREE.EllipseCurve
  27766. * THREE.LineCurve
  27767. * THREE.QuadraticBezierCurve
  27768. * THREE.SplineCurve
  27769. *
  27770. * -- 3D curves --
  27771. * THREE.CatmullRomCurve3
  27772. * THREE.CubicBezierCurve3
  27773. * THREE.LineCurve3
  27774. * THREE.QuadraticBezierCurve3
  27775. *
  27776. * A series of curves can be represented as a THREE.CurvePath.
  27777. *
  27778. **/
  27779. /**************************************************************
  27780. * Abstract Curve base class
  27781. **************************************************************/
  27782. function Curve() {
  27783. this.type = 'Curve';
  27784. this.arcLengthDivisions = 200;
  27785. }
  27786. Object.assign( Curve.prototype, {
  27787. // Virtual base class method to overwrite and implement in subclasses
  27788. // - t [0 .. 1]
  27789. getPoint: function ( /* t, optionalTarget */ ) {
  27790. console.warn( 'THREE.Curve: .getPoint() not implemented.' );
  27791. return null;
  27792. },
  27793. // Get point at relative position in curve according to arc length
  27794. // - u [0 .. 1]
  27795. getPointAt: function ( u, optionalTarget ) {
  27796. var t = this.getUtoTmapping( u );
  27797. return this.getPoint( t, optionalTarget );
  27798. },
  27799. // Get sequence of points using getPoint( t )
  27800. getPoints: function ( divisions ) {
  27801. if ( divisions === undefined ) { divisions = 5; }
  27802. var points = [];
  27803. for ( var d = 0; d <= divisions; d ++ ) {
  27804. points.push( this.getPoint( d / divisions ) );
  27805. }
  27806. return points;
  27807. },
  27808. // Get sequence of points using getPointAt( u )
  27809. getSpacedPoints: function ( divisions ) {
  27810. if ( divisions === undefined ) { divisions = 5; }
  27811. var points = [];
  27812. for ( var d = 0; d <= divisions; d ++ ) {
  27813. points.push( this.getPointAt( d / divisions ) );
  27814. }
  27815. return points;
  27816. },
  27817. // Get total curve arc length
  27818. getLength: function () {
  27819. var lengths = this.getLengths();
  27820. return lengths[ lengths.length - 1 ];
  27821. },
  27822. // Get list of cumulative segment lengths
  27823. getLengths: function ( divisions ) {
  27824. if ( divisions === undefined ) { divisions = this.arcLengthDivisions; }
  27825. if ( this.cacheArcLengths &&
  27826. ( this.cacheArcLengths.length === divisions + 1 ) &&
  27827. ! this.needsUpdate ) {
  27828. return this.cacheArcLengths;
  27829. }
  27830. this.needsUpdate = false;
  27831. var cache = [];
  27832. var current, last = this.getPoint( 0 );
  27833. var p, sum = 0;
  27834. cache.push( 0 );
  27835. for ( p = 1; p <= divisions; p ++ ) {
  27836. current = this.getPoint( p / divisions );
  27837. sum += current.distanceTo( last );
  27838. cache.push( sum );
  27839. last = current;
  27840. }
  27841. this.cacheArcLengths = cache;
  27842. return cache; // { sums: cache, sum: sum }; Sum is in the last element.
  27843. },
  27844. updateArcLengths: function () {
  27845. this.needsUpdate = true;
  27846. this.getLengths();
  27847. },
  27848. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant
  27849. getUtoTmapping: function ( u, distance ) {
  27850. var arcLengths = this.getLengths();
  27851. var i = 0, il = arcLengths.length;
  27852. var targetArcLength; // The targeted u distance value to get
  27853. if ( distance ) {
  27854. targetArcLength = distance;
  27855. } else {
  27856. targetArcLength = u * arcLengths[ il - 1 ];
  27857. }
  27858. // binary search for the index with largest value smaller than target u distance
  27859. var low = 0, high = il - 1, comparison;
  27860. while ( low <= high ) {
  27861. 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
  27862. comparison = arcLengths[ i ] - targetArcLength;
  27863. if ( comparison < 0 ) {
  27864. low = i + 1;
  27865. } else if ( comparison > 0 ) {
  27866. high = i - 1;
  27867. } else {
  27868. high = i;
  27869. break;
  27870. // DONE
  27871. }
  27872. }
  27873. i = high;
  27874. if ( arcLengths[ i ] === targetArcLength ) {
  27875. return i / ( il - 1 );
  27876. }
  27877. // we could get finer grain at lengths, or use simple interpolation between two points
  27878. var lengthBefore = arcLengths[ i ];
  27879. var lengthAfter = arcLengths[ i + 1 ];
  27880. var segmentLength = lengthAfter - lengthBefore;
  27881. // determine where we are between the 'before' and 'after' points
  27882. var segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  27883. // add that fractional amount to t
  27884. var t = ( i + segmentFraction ) / ( il - 1 );
  27885. return t;
  27886. },
  27887. // Returns a unit vector tangent at t
  27888. // In case any sub curve does not implement its tangent derivation,
  27889. // 2 points a small delta apart will be used to find its gradient
  27890. // which seems to give a reasonable approximation
  27891. getTangent: function ( t ) {
  27892. var delta = 0.0001;
  27893. var t1 = t - delta;
  27894. var t2 = t + delta;
  27895. // Capping in case of danger
  27896. if ( t1 < 0 ) { t1 = 0; }
  27897. if ( t2 > 1 ) { t2 = 1; }
  27898. var pt1 = this.getPoint( t1 );
  27899. var pt2 = this.getPoint( t2 );
  27900. var vec = pt2.clone().sub( pt1 );
  27901. return vec.normalize();
  27902. },
  27903. getTangentAt: function ( u ) {
  27904. var t = this.getUtoTmapping( u );
  27905. return this.getTangent( t );
  27906. },
  27907. computeFrenetFrames: function ( segments, closed ) {
  27908. // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  27909. var normal = new Vector3();
  27910. var tangents = [];
  27911. var normals = [];
  27912. var binormals = [];
  27913. var vec = new Vector3();
  27914. var mat = new Matrix4();
  27915. var i, u, theta;
  27916. // compute the tangent vectors for each segment on the curve
  27917. for ( i = 0; i <= segments; i ++ ) {
  27918. u = i / segments;
  27919. tangents[ i ] = this.getTangentAt( u );
  27920. tangents[ i ].normalize();
  27921. }
  27922. // select an initial normal vector perpendicular to the first tangent vector,
  27923. // and in the direction of the minimum tangent xyz component
  27924. normals[ 0 ] = new Vector3();
  27925. binormals[ 0 ] = new Vector3();
  27926. var min = Number.MAX_VALUE;
  27927. var tx = Math.abs( tangents[ 0 ].x );
  27928. var ty = Math.abs( tangents[ 0 ].y );
  27929. var tz = Math.abs( tangents[ 0 ].z );
  27930. if ( tx <= min ) {
  27931. min = tx;
  27932. normal.set( 1, 0, 0 );
  27933. }
  27934. if ( ty <= min ) {
  27935. min = ty;
  27936. normal.set( 0, 1, 0 );
  27937. }
  27938. if ( tz <= min ) {
  27939. normal.set( 0, 0, 1 );
  27940. }
  27941. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  27942. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  27943. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  27944. // compute the slowly-varying normal and binormal vectors for each segment on the curve
  27945. for ( i = 1; i <= segments; i ++ ) {
  27946. normals[ i ] = normals[ i - 1 ].clone();
  27947. binormals[ i ] = binormals[ i - 1 ].clone();
  27948. vec.crossVectors( tangents[ i - 1 ], tangents[ i ] );
  27949. if ( vec.length() > Number.EPSILON ) {
  27950. vec.normalize();
  27951. theta = Math.acos( MathUtils.clamp( tangents[ i - 1 ].dot( tangents[ i ] ), - 1, 1 ) ); // clamp for floating pt errors
  27952. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  27953. }
  27954. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  27955. }
  27956. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  27957. if ( closed === true ) {
  27958. theta = Math.acos( MathUtils.clamp( normals[ 0 ].dot( normals[ segments ] ), - 1, 1 ) );
  27959. theta /= segments;
  27960. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ segments ] ) ) > 0 ) {
  27961. theta = - theta;
  27962. }
  27963. for ( i = 1; i <= segments; i ++ ) {
  27964. // twist a little...
  27965. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  27966. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  27967. }
  27968. }
  27969. return {
  27970. tangents: tangents,
  27971. normals: normals,
  27972. binormals: binormals
  27973. };
  27974. },
  27975. clone: function () {
  27976. return new this.constructor().copy( this );
  27977. },
  27978. copy: function ( source ) {
  27979. this.arcLengthDivisions = source.arcLengthDivisions;
  27980. return this;
  27981. },
  27982. toJSON: function () {
  27983. var data = {
  27984. metadata: {
  27985. version: 4.5,
  27986. type: 'Curve',
  27987. generator: 'Curve.toJSON'
  27988. }
  27989. };
  27990. data.arcLengthDivisions = this.arcLengthDivisions;
  27991. data.type = this.type;
  27992. return data;
  27993. },
  27994. fromJSON: function ( json ) {
  27995. this.arcLengthDivisions = json.arcLengthDivisions;
  27996. return this;
  27997. }
  27998. } );
  27999. function EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  28000. Curve.call( this );
  28001. this.type = 'EllipseCurve';
  28002. this.aX = aX || 0;
  28003. this.aY = aY || 0;
  28004. this.xRadius = xRadius || 1;
  28005. this.yRadius = yRadius || 1;
  28006. this.aStartAngle = aStartAngle || 0;
  28007. this.aEndAngle = aEndAngle || 2 * Math.PI;
  28008. this.aClockwise = aClockwise || false;
  28009. this.aRotation = aRotation || 0;
  28010. }
  28011. EllipseCurve.prototype = Object.create( Curve.prototype );
  28012. EllipseCurve.prototype.constructor = EllipseCurve;
  28013. EllipseCurve.prototype.isEllipseCurve = true;
  28014. EllipseCurve.prototype.getPoint = function ( t, optionalTarget ) {
  28015. var point = optionalTarget || new Vector2();
  28016. var twoPi = Math.PI * 2;
  28017. var deltaAngle = this.aEndAngle - this.aStartAngle;
  28018. var samePoints = Math.abs( deltaAngle ) < Number.EPSILON;
  28019. // ensures that deltaAngle is 0 .. 2 PI
  28020. while ( deltaAngle < 0 ) { deltaAngle += twoPi; }
  28021. while ( deltaAngle > twoPi ) { deltaAngle -= twoPi; }
  28022. if ( deltaAngle < Number.EPSILON ) {
  28023. if ( samePoints ) {
  28024. deltaAngle = 0;
  28025. } else {
  28026. deltaAngle = twoPi;
  28027. }
  28028. }
  28029. if ( this.aClockwise === true && ! samePoints ) {
  28030. if ( deltaAngle === twoPi ) {
  28031. deltaAngle = - twoPi;
  28032. } else {
  28033. deltaAngle = deltaAngle - twoPi;
  28034. }
  28035. }
  28036. var angle = this.aStartAngle + t * deltaAngle;
  28037. var x = this.aX + this.xRadius * Math.cos( angle );
  28038. var y = this.aY + this.yRadius * Math.sin( angle );
  28039. if ( this.aRotation !== 0 ) {
  28040. var cos = Math.cos( this.aRotation );
  28041. var sin = Math.sin( this.aRotation );
  28042. var tx = x - this.aX;
  28043. var ty = y - this.aY;
  28044. // Rotate the point about the center of the ellipse.
  28045. x = tx * cos - ty * sin + this.aX;
  28046. y = tx * sin + ty * cos + this.aY;
  28047. }
  28048. return point.set( x, y );
  28049. };
  28050. EllipseCurve.prototype.copy = function ( source ) {
  28051. Curve.prototype.copy.call( this, source );
  28052. this.aX = source.aX;
  28053. this.aY = source.aY;
  28054. this.xRadius = source.xRadius;
  28055. this.yRadius = source.yRadius;
  28056. this.aStartAngle = source.aStartAngle;
  28057. this.aEndAngle = source.aEndAngle;
  28058. this.aClockwise = source.aClockwise;
  28059. this.aRotation = source.aRotation;
  28060. return this;
  28061. };
  28062. EllipseCurve.prototype.toJSON = function () {
  28063. var data = Curve.prototype.toJSON.call( this );
  28064. data.aX = this.aX;
  28065. data.aY = this.aY;
  28066. data.xRadius = this.xRadius;
  28067. data.yRadius = this.yRadius;
  28068. data.aStartAngle = this.aStartAngle;
  28069. data.aEndAngle = this.aEndAngle;
  28070. data.aClockwise = this.aClockwise;
  28071. data.aRotation = this.aRotation;
  28072. return data;
  28073. };
  28074. EllipseCurve.prototype.fromJSON = function ( json ) {
  28075. Curve.prototype.fromJSON.call( this, json );
  28076. this.aX = json.aX;
  28077. this.aY = json.aY;
  28078. this.xRadius = json.xRadius;
  28079. this.yRadius = json.yRadius;
  28080. this.aStartAngle = json.aStartAngle;
  28081. this.aEndAngle = json.aEndAngle;
  28082. this.aClockwise = json.aClockwise;
  28083. this.aRotation = json.aRotation;
  28084. return this;
  28085. };
  28086. function ArcCurve( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  28087. EllipseCurve.call( this, aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  28088. this.type = 'ArcCurve';
  28089. }
  28090. ArcCurve.prototype = Object.create( EllipseCurve.prototype );
  28091. ArcCurve.prototype.constructor = ArcCurve;
  28092. ArcCurve.prototype.isArcCurve = true;
  28093. /**
  28094. * @author zz85 https://github.com/zz85
  28095. *
  28096. * Centripetal CatmullRom Curve - which is useful for avoiding
  28097. * cusps and self-intersections in non-uniform catmull rom curves.
  28098. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  28099. *
  28100. * curve.type accepts centripetal(default), chordal and catmullrom
  28101. * curve.tension is used for catmullrom which defaults to 0.5
  28102. */
  28103. /*
  28104. Based on an optimized c++ solution in
  28105. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  28106. - http://ideone.com/NoEbVM
  28107. This CubicPoly class could be used for reusing some variables and calculations,
  28108. but for three.js curve use, it could be possible inlined and flatten into a single function call
  28109. which can be placed in CurveUtils.
  28110. */
  28111. function CubicPoly() {
  28112. var c0 = 0, c1 = 0, c2 = 0, c3 = 0;
  28113. /*
  28114. * Compute coefficients for a cubic polynomial
  28115. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  28116. * such that
  28117. * p(0) = x0, p(1) = x1
  28118. * and
  28119. * p'(0) = t0, p'(1) = t1.
  28120. */
  28121. function init( x0, x1, t0, t1 ) {
  28122. c0 = x0;
  28123. c1 = t0;
  28124. c2 = - 3 * x0 + 3 * x1 - 2 * t0 - t1;
  28125. c3 = 2 * x0 - 2 * x1 + t0 + t1;
  28126. }
  28127. return {
  28128. initCatmullRom: function ( x0, x1, x2, x3, tension ) {
  28129. init( x1, x2, tension * ( x2 - x0 ), tension * ( x3 - x1 ) );
  28130. },
  28131. initNonuniformCatmullRom: function ( x0, x1, x2, x3, dt0, dt1, dt2 ) {
  28132. // compute tangents when parameterized in [t1,t2]
  28133. var t1 = ( x1 - x0 ) / dt0 - ( x2 - x0 ) / ( dt0 + dt1 ) + ( x2 - x1 ) / dt1;
  28134. var t2 = ( x2 - x1 ) / dt1 - ( x3 - x1 ) / ( dt1 + dt2 ) + ( x3 - x2 ) / dt2;
  28135. // rescale tangents for parametrization in [0,1]
  28136. t1 *= dt1;
  28137. t2 *= dt1;
  28138. init( x1, x2, t1, t2 );
  28139. },
  28140. calc: function ( t ) {
  28141. var t2 = t * t;
  28142. var t3 = t2 * t;
  28143. return c0 + c1 * t + c2 * t2 + c3 * t3;
  28144. }
  28145. };
  28146. }
  28147. //
  28148. var tmp = new Vector3();
  28149. var px = new CubicPoly(), py = new CubicPoly(), pz = new CubicPoly();
  28150. function CatmullRomCurve3( points, closed, curveType, tension ) {
  28151. Curve.call( this );
  28152. this.type = 'CatmullRomCurve3';
  28153. this.points = points || [];
  28154. this.closed = closed || false;
  28155. this.curveType = curveType || 'centripetal';
  28156. this.tension = tension || 0.5;
  28157. }
  28158. CatmullRomCurve3.prototype = Object.create( Curve.prototype );
  28159. CatmullRomCurve3.prototype.constructor = CatmullRomCurve3;
  28160. CatmullRomCurve3.prototype.isCatmullRomCurve3 = true;
  28161. CatmullRomCurve3.prototype.getPoint = function ( t, optionalTarget ) {
  28162. var point = optionalTarget || new Vector3();
  28163. var points = this.points;
  28164. var l = points.length;
  28165. var p = ( l - ( this.closed ? 0 : 1 ) ) * t;
  28166. var intPoint = Math.floor( p );
  28167. var weight = p - intPoint;
  28168. if ( this.closed ) {
  28169. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / l ) + 1 ) * l;
  28170. } else if ( weight === 0 && intPoint === l - 1 ) {
  28171. intPoint = l - 2;
  28172. weight = 1;
  28173. }
  28174. var p0, p1, p2, p3; // 4 points
  28175. if ( this.closed || intPoint > 0 ) {
  28176. p0 = points[ ( intPoint - 1 ) % l ];
  28177. } else {
  28178. // extrapolate first point
  28179. tmp.subVectors( points[ 0 ], points[ 1 ] ).add( points[ 0 ] );
  28180. p0 = tmp;
  28181. }
  28182. p1 = points[ intPoint % l ];
  28183. p2 = points[ ( intPoint + 1 ) % l ];
  28184. if ( this.closed || intPoint + 2 < l ) {
  28185. p3 = points[ ( intPoint + 2 ) % l ];
  28186. } else {
  28187. // extrapolate last point
  28188. tmp.subVectors( points[ l - 1 ], points[ l - 2 ] ).add( points[ l - 1 ] );
  28189. p3 = tmp;
  28190. }
  28191. if ( this.curveType === 'centripetal' || this.curveType === 'chordal' ) {
  28192. // init Centripetal / Chordal Catmull-Rom
  28193. var pow = this.curveType === 'chordal' ? 0.5 : 0.25;
  28194. var dt0 = Math.pow( p0.distanceToSquared( p1 ), pow );
  28195. var dt1 = Math.pow( p1.distanceToSquared( p2 ), pow );
  28196. var dt2 = Math.pow( p2.distanceToSquared( p3 ), pow );
  28197. // safety check for repeated points
  28198. if ( dt1 < 1e-4 ) { dt1 = 1.0; }
  28199. if ( dt0 < 1e-4 ) { dt0 = dt1; }
  28200. if ( dt2 < 1e-4 ) { dt2 = dt1; }
  28201. px.initNonuniformCatmullRom( p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2 );
  28202. py.initNonuniformCatmullRom( p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2 );
  28203. pz.initNonuniformCatmullRom( p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2 );
  28204. } else if ( this.curveType === 'catmullrom' ) {
  28205. px.initCatmullRom( p0.x, p1.x, p2.x, p3.x, this.tension );
  28206. py.initCatmullRom( p0.y, p1.y, p2.y, p3.y, this.tension );
  28207. pz.initCatmullRom( p0.z, p1.z, p2.z, p3.z, this.tension );
  28208. }
  28209. point.set(
  28210. px.calc( weight ),
  28211. py.calc( weight ),
  28212. pz.calc( weight )
  28213. );
  28214. return point;
  28215. };
  28216. CatmullRomCurve3.prototype.copy = function ( source ) {
  28217. Curve.prototype.copy.call( this, source );
  28218. this.points = [];
  28219. for ( var i = 0, l = source.points.length; i < l; i ++ ) {
  28220. var point = source.points[ i ];
  28221. this.points.push( point.clone() );
  28222. }
  28223. this.closed = source.closed;
  28224. this.curveType = source.curveType;
  28225. this.tension = source.tension;
  28226. return this;
  28227. };
  28228. CatmullRomCurve3.prototype.toJSON = function () {
  28229. var data = Curve.prototype.toJSON.call( this );
  28230. data.points = [];
  28231. for ( var i = 0, l = this.points.length; i < l; i ++ ) {
  28232. var point = this.points[ i ];
  28233. data.points.push( point.toArray() );
  28234. }
  28235. data.closed = this.closed;
  28236. data.curveType = this.curveType;
  28237. data.tension = this.tension;
  28238. return data;
  28239. };
  28240. CatmullRomCurve3.prototype.fromJSON = function ( json ) {
  28241. Curve.prototype.fromJSON.call( this, json );
  28242. this.points = [];
  28243. for ( var i = 0, l = json.points.length; i < l; i ++ ) {
  28244. var point = json.points[ i ];
  28245. this.points.push( new Vector3().fromArray( point ) );
  28246. }
  28247. this.closed = json.closed;
  28248. this.curveType = json.curveType;
  28249. this.tension = json.tension;
  28250. return this;
  28251. };
  28252. /**
  28253. * @author zz85 / http://www.lab4games.net/zz85/blog
  28254. *
  28255. * Bezier Curves formulas obtained from
  28256. * http://en.wikipedia.org/wiki/Bézier_curve
  28257. */
  28258. function CatmullRom( t, p0, p1, p2, p3 ) {
  28259. var v0 = ( p2 - p0 ) * 0.5;
  28260. var v1 = ( p3 - p1 ) * 0.5;
  28261. var t2 = t * t;
  28262. var t3 = t * t2;
  28263. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  28264. }
  28265. //
  28266. function QuadraticBezierP0( t, p ) {
  28267. var k = 1 - t;
  28268. return k * k * p;
  28269. }
  28270. function QuadraticBezierP1( t, p ) {
  28271. return 2 * ( 1 - t ) * t * p;
  28272. }
  28273. function QuadraticBezierP2( t, p ) {
  28274. return t * t * p;
  28275. }
  28276. function QuadraticBezier( t, p0, p1, p2 ) {
  28277. return QuadraticBezierP0( t, p0 ) + QuadraticBezierP1( t, p1 ) +
  28278. QuadraticBezierP2( t, p2 );
  28279. }
  28280. //
  28281. function CubicBezierP0( t, p ) {
  28282. var k = 1 - t;
  28283. return k * k * k * p;
  28284. }
  28285. function CubicBezierP1( t, p ) {
  28286. var k = 1 - t;
  28287. return 3 * k * k * t * p;
  28288. }
  28289. function CubicBezierP2( t, p ) {
  28290. return 3 * ( 1 - t ) * t * t * p;
  28291. }
  28292. function CubicBezierP3( t, p ) {
  28293. return t * t * t * p;
  28294. }
  28295. function CubicBezier( t, p0, p1, p2, p3 ) {
  28296. return CubicBezierP0( t, p0 ) + CubicBezierP1( t, p1 ) + CubicBezierP2( t, p2 ) +
  28297. CubicBezierP3( t, p3 );
  28298. }
  28299. function CubicBezierCurve( v0, v1, v2, v3 ) {
  28300. Curve.call( this );
  28301. this.type = 'CubicBezierCurve';
  28302. this.v0 = v0 || new Vector2();
  28303. this.v1 = v1 || new Vector2();
  28304. this.v2 = v2 || new Vector2();
  28305. this.v3 = v3 || new Vector2();
  28306. }
  28307. CubicBezierCurve.prototype = Object.create( Curve.prototype );
  28308. CubicBezierCurve.prototype.constructor = CubicBezierCurve;
  28309. CubicBezierCurve.prototype.isCubicBezierCurve = true;
  28310. CubicBezierCurve.prototype.getPoint = function ( t, optionalTarget ) {
  28311. var point = optionalTarget || new Vector2();
  28312. var v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  28313. point.set(
  28314. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  28315. CubicBezier( t, v0.y, v1.y, v2.y, v3.y )
  28316. );
  28317. return point;
  28318. };
  28319. CubicBezierCurve.prototype.copy = function ( source ) {
  28320. Curve.prototype.copy.call( this, source );
  28321. this.v0.copy( source.v0 );
  28322. this.v1.copy( source.v1 );
  28323. this.v2.copy( source.v2 );
  28324. this.v3.copy( source.v3 );
  28325. return this;
  28326. };
  28327. CubicBezierCurve.prototype.toJSON = function () {
  28328. var data = Curve.prototype.toJSON.call( this );
  28329. data.v0 = this.v0.toArray();
  28330. data.v1 = this.v1.toArray();
  28331. data.v2 = this.v2.toArray();
  28332. data.v3 = this.v3.toArray();
  28333. return data;
  28334. };
  28335. CubicBezierCurve.prototype.fromJSON = function ( json ) {
  28336. Curve.prototype.fromJSON.call( this, json );
  28337. this.v0.fromArray( json.v0 );
  28338. this.v1.fromArray( json.v1 );
  28339. this.v2.fromArray( json.v2 );
  28340. this.v3.fromArray( json.v3 );
  28341. return this;
  28342. };
  28343. function CubicBezierCurve3( v0, v1, v2, v3 ) {
  28344. Curve.call( this );
  28345. this.type = 'CubicBezierCurve3';
  28346. this.v0 = v0 || new Vector3();
  28347. this.v1 = v1 || new Vector3();
  28348. this.v2 = v2 || new Vector3();
  28349. this.v3 = v3 || new Vector3();
  28350. }
  28351. CubicBezierCurve3.prototype = Object.create( Curve.prototype );
  28352. CubicBezierCurve3.prototype.constructor = CubicBezierCurve3;
  28353. CubicBezierCurve3.prototype.isCubicBezierCurve3 = true;
  28354. CubicBezierCurve3.prototype.getPoint = function ( t, optionalTarget ) {
  28355. var point = optionalTarget || new Vector3();
  28356. var v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  28357. point.set(
  28358. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  28359. CubicBezier( t, v0.y, v1.y, v2.y, v3.y ),
  28360. CubicBezier( t, v0.z, v1.z, v2.z, v3.z )
  28361. );
  28362. return point;
  28363. };
  28364. CubicBezierCurve3.prototype.copy = function ( source ) {
  28365. Curve.prototype.copy.call( this, source );
  28366. this.v0.copy( source.v0 );
  28367. this.v1.copy( source.v1 );
  28368. this.v2.copy( source.v2 );
  28369. this.v3.copy( source.v3 );
  28370. return this;
  28371. };
  28372. CubicBezierCurve3.prototype.toJSON = function () {
  28373. var data = Curve.prototype.toJSON.call( this );
  28374. data.v0 = this.v0.toArray();
  28375. data.v1 = this.v1.toArray();
  28376. data.v2 = this.v2.toArray();
  28377. data.v3 = this.v3.toArray();
  28378. return data;
  28379. };
  28380. CubicBezierCurve3.prototype.fromJSON = function ( json ) {
  28381. Curve.prototype.fromJSON.call( this, json );
  28382. this.v0.fromArray( json.v0 );
  28383. this.v1.fromArray( json.v1 );
  28384. this.v2.fromArray( json.v2 );
  28385. this.v3.fromArray( json.v3 );
  28386. return this;
  28387. };
  28388. function LineCurve( v1, v2 ) {
  28389. Curve.call( this );
  28390. this.type = 'LineCurve';
  28391. this.v1 = v1 || new Vector2();
  28392. this.v2 = v2 || new Vector2();
  28393. }
  28394. LineCurve.prototype = Object.create( Curve.prototype );
  28395. LineCurve.prototype.constructor = LineCurve;
  28396. LineCurve.prototype.isLineCurve = true;
  28397. LineCurve.prototype.getPoint = function ( t, optionalTarget ) {
  28398. var point = optionalTarget || new Vector2();
  28399. if ( t === 1 ) {
  28400. point.copy( this.v2 );
  28401. } else {
  28402. point.copy( this.v2 ).sub( this.v1 );
  28403. point.multiplyScalar( t ).add( this.v1 );
  28404. }
  28405. return point;
  28406. };
  28407. // Line curve is linear, so we can overwrite default getPointAt
  28408. LineCurve.prototype.getPointAt = function ( u, optionalTarget ) {
  28409. return this.getPoint( u, optionalTarget );
  28410. };
  28411. LineCurve.prototype.getTangent = function ( /* t */ ) {
  28412. var tangent = this.v2.clone().sub( this.v1 );
  28413. return tangent.normalize();
  28414. };
  28415. LineCurve.prototype.copy = function ( source ) {
  28416. Curve.prototype.copy.call( this, source );
  28417. this.v1.copy( source.v1 );
  28418. this.v2.copy( source.v2 );
  28419. return this;
  28420. };
  28421. LineCurve.prototype.toJSON = function () {
  28422. var data = Curve.prototype.toJSON.call( this );
  28423. data.v1 = this.v1.toArray();
  28424. data.v2 = this.v2.toArray();
  28425. return data;
  28426. };
  28427. LineCurve.prototype.fromJSON = function ( json ) {
  28428. Curve.prototype.fromJSON.call( this, json );
  28429. this.v1.fromArray( json.v1 );
  28430. this.v2.fromArray( json.v2 );
  28431. return this;
  28432. };
  28433. function LineCurve3( v1, v2 ) {
  28434. Curve.call( this );
  28435. this.type = 'LineCurve3';
  28436. this.v1 = v1 || new Vector3();
  28437. this.v2 = v2 || new Vector3();
  28438. }
  28439. LineCurve3.prototype = Object.create( Curve.prototype );
  28440. LineCurve3.prototype.constructor = LineCurve3;
  28441. LineCurve3.prototype.isLineCurve3 = true;
  28442. LineCurve3.prototype.getPoint = function ( t, optionalTarget ) {
  28443. var point = optionalTarget || new Vector3();
  28444. if ( t === 1 ) {
  28445. point.copy( this.v2 );
  28446. } else {
  28447. point.copy( this.v2 ).sub( this.v1 );
  28448. point.multiplyScalar( t ).add( this.v1 );
  28449. }
  28450. return point;
  28451. };
  28452. // Line curve is linear, so we can overwrite default getPointAt
  28453. LineCurve3.prototype.getPointAt = function ( u, optionalTarget ) {
  28454. return this.getPoint( u, optionalTarget );
  28455. };
  28456. LineCurve3.prototype.copy = function ( source ) {
  28457. Curve.prototype.copy.call( this, source );
  28458. this.v1.copy( source.v1 );
  28459. this.v2.copy( source.v2 );
  28460. return this;
  28461. };
  28462. LineCurve3.prototype.toJSON = function () {
  28463. var data = Curve.prototype.toJSON.call( this );
  28464. data.v1 = this.v1.toArray();
  28465. data.v2 = this.v2.toArray();
  28466. return data;
  28467. };
  28468. LineCurve3.prototype.fromJSON = function ( json ) {
  28469. Curve.prototype.fromJSON.call( this, json );
  28470. this.v1.fromArray( json.v1 );
  28471. this.v2.fromArray( json.v2 );
  28472. return this;
  28473. };
  28474. function QuadraticBezierCurve( v0, v1, v2 ) {
  28475. Curve.call( this );
  28476. this.type = 'QuadraticBezierCurve';
  28477. this.v0 = v0 || new Vector2();
  28478. this.v1 = v1 || new Vector2();
  28479. this.v2 = v2 || new Vector2();
  28480. }
  28481. QuadraticBezierCurve.prototype = Object.create( Curve.prototype );
  28482. QuadraticBezierCurve.prototype.constructor = QuadraticBezierCurve;
  28483. QuadraticBezierCurve.prototype.isQuadraticBezierCurve = true;
  28484. QuadraticBezierCurve.prototype.getPoint = function ( t, optionalTarget ) {
  28485. var point = optionalTarget || new Vector2();
  28486. var v0 = this.v0, v1 = this.v1, v2 = this.v2;
  28487. point.set(
  28488. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  28489. QuadraticBezier( t, v0.y, v1.y, v2.y )
  28490. );
  28491. return point;
  28492. };
  28493. QuadraticBezierCurve.prototype.copy = function ( source ) {
  28494. Curve.prototype.copy.call( this, source );
  28495. this.v0.copy( source.v0 );
  28496. this.v1.copy( source.v1 );
  28497. this.v2.copy( source.v2 );
  28498. return this;
  28499. };
  28500. QuadraticBezierCurve.prototype.toJSON = function () {
  28501. var data = Curve.prototype.toJSON.call( this );
  28502. data.v0 = this.v0.toArray();
  28503. data.v1 = this.v1.toArray();
  28504. data.v2 = this.v2.toArray();
  28505. return data;
  28506. };
  28507. QuadraticBezierCurve.prototype.fromJSON = function ( json ) {
  28508. Curve.prototype.fromJSON.call( this, json );
  28509. this.v0.fromArray( json.v0 );
  28510. this.v1.fromArray( json.v1 );
  28511. this.v2.fromArray( json.v2 );
  28512. return this;
  28513. };
  28514. function QuadraticBezierCurve3( v0, v1, v2 ) {
  28515. Curve.call( this );
  28516. this.type = 'QuadraticBezierCurve3';
  28517. this.v0 = v0 || new Vector3();
  28518. this.v1 = v1 || new Vector3();
  28519. this.v2 = v2 || new Vector3();
  28520. }
  28521. QuadraticBezierCurve3.prototype = Object.create( Curve.prototype );
  28522. QuadraticBezierCurve3.prototype.constructor = QuadraticBezierCurve3;
  28523. QuadraticBezierCurve3.prototype.isQuadraticBezierCurve3 = true;
  28524. QuadraticBezierCurve3.prototype.getPoint = function ( t, optionalTarget ) {
  28525. var point = optionalTarget || new Vector3();
  28526. var v0 = this.v0, v1 = this.v1, v2 = this.v2;
  28527. point.set(
  28528. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  28529. QuadraticBezier( t, v0.y, v1.y, v2.y ),
  28530. QuadraticBezier( t, v0.z, v1.z, v2.z )
  28531. );
  28532. return point;
  28533. };
  28534. QuadraticBezierCurve3.prototype.copy = function ( source ) {
  28535. Curve.prototype.copy.call( this, source );
  28536. this.v0.copy( source.v0 );
  28537. this.v1.copy( source.v1 );
  28538. this.v2.copy( source.v2 );
  28539. return this;
  28540. };
  28541. QuadraticBezierCurve3.prototype.toJSON = function () {
  28542. var data = Curve.prototype.toJSON.call( this );
  28543. data.v0 = this.v0.toArray();
  28544. data.v1 = this.v1.toArray();
  28545. data.v2 = this.v2.toArray();
  28546. return data;
  28547. };
  28548. QuadraticBezierCurve3.prototype.fromJSON = function ( json ) {
  28549. Curve.prototype.fromJSON.call( this, json );
  28550. this.v0.fromArray( json.v0 );
  28551. this.v1.fromArray( json.v1 );
  28552. this.v2.fromArray( json.v2 );
  28553. return this;
  28554. };
  28555. function SplineCurve( points /* array of Vector2 */ ) {
  28556. Curve.call( this );
  28557. this.type = 'SplineCurve';
  28558. this.points = points || [];
  28559. }
  28560. SplineCurve.prototype = Object.create( Curve.prototype );
  28561. SplineCurve.prototype.constructor = SplineCurve;
  28562. SplineCurve.prototype.isSplineCurve = true;
  28563. SplineCurve.prototype.getPoint = function ( t, optionalTarget ) {
  28564. var point = optionalTarget || new Vector2();
  28565. var points = this.points;
  28566. var p = ( points.length - 1 ) * t;
  28567. var intPoint = Math.floor( p );
  28568. var weight = p - intPoint;
  28569. var p0 = points[ intPoint === 0 ? intPoint : intPoint - 1 ];
  28570. var p1 = points[ intPoint ];
  28571. var p2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ];
  28572. var p3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ];
  28573. point.set(
  28574. CatmullRom( weight, p0.x, p1.x, p2.x, p3.x ),
  28575. CatmullRom( weight, p0.y, p1.y, p2.y, p3.y )
  28576. );
  28577. return point;
  28578. };
  28579. SplineCurve.prototype.copy = function ( source ) {
  28580. Curve.prototype.copy.call( this, source );
  28581. this.points = [];
  28582. for ( var i = 0, l = source.points.length; i < l; i ++ ) {
  28583. var point = source.points[ i ];
  28584. this.points.push( point.clone() );
  28585. }
  28586. return this;
  28587. };
  28588. SplineCurve.prototype.toJSON = function () {
  28589. var data = Curve.prototype.toJSON.call( this );
  28590. data.points = [];
  28591. for ( var i = 0, l = this.points.length; i < l; i ++ ) {
  28592. var point = this.points[ i ];
  28593. data.points.push( point.toArray() );
  28594. }
  28595. return data;
  28596. };
  28597. SplineCurve.prototype.fromJSON = function ( json ) {
  28598. Curve.prototype.fromJSON.call( this, json );
  28599. this.points = [];
  28600. for ( var i = 0, l = json.points.length; i < l; i ++ ) {
  28601. var point = json.points[ i ];
  28602. this.points.push( new Vector2().fromArray( point ) );
  28603. }
  28604. return this;
  28605. };
  28606. var Curves = /*#__PURE__*/Object.freeze({
  28607. __proto__: null,
  28608. ArcCurve: ArcCurve,
  28609. CatmullRomCurve3: CatmullRomCurve3,
  28610. CubicBezierCurve: CubicBezierCurve,
  28611. CubicBezierCurve3: CubicBezierCurve3,
  28612. EllipseCurve: EllipseCurve,
  28613. LineCurve: LineCurve,
  28614. LineCurve3: LineCurve3,
  28615. QuadraticBezierCurve: QuadraticBezierCurve,
  28616. QuadraticBezierCurve3: QuadraticBezierCurve3,
  28617. SplineCurve: SplineCurve
  28618. });
  28619. /**
  28620. * @author zz85 / http://www.lab4games.net/zz85/blog
  28621. *
  28622. **/
  28623. /**************************************************************
  28624. * Curved Path - a curve path is simply a array of connected
  28625. * curves, but retains the api of a curve
  28626. **************************************************************/
  28627. function CurvePath() {
  28628. Curve.call( this );
  28629. this.type = 'CurvePath';
  28630. this.curves = [];
  28631. this.autoClose = false; // Automatically closes the path
  28632. }
  28633. CurvePath.prototype = Object.assign( Object.create( Curve.prototype ), {
  28634. constructor: CurvePath,
  28635. add: function ( curve ) {
  28636. this.curves.push( curve );
  28637. },
  28638. closePath: function () {
  28639. // Add a line curve if start and end of lines are not connected
  28640. var startPoint = this.curves[ 0 ].getPoint( 0 );
  28641. var endPoint = this.curves[ this.curves.length - 1 ].getPoint( 1 );
  28642. if ( ! startPoint.equals( endPoint ) ) {
  28643. this.curves.push( new LineCurve( endPoint, startPoint ) );
  28644. }
  28645. },
  28646. // To get accurate point with reference to
  28647. // entire path distance at time t,
  28648. // following has to be done:
  28649. // 1. Length of each sub path have to be known
  28650. // 2. Locate and identify type of curve
  28651. // 3. Get t for the curve
  28652. // 4. Return curve.getPointAt(t')
  28653. getPoint: function ( t ) {
  28654. var d = t * this.getLength();
  28655. var curveLengths = this.getCurveLengths();
  28656. var i = 0;
  28657. // To think about boundaries points.
  28658. while ( i < curveLengths.length ) {
  28659. if ( curveLengths[ i ] >= d ) {
  28660. var diff = curveLengths[ i ] - d;
  28661. var curve = this.curves[ i ];
  28662. var segmentLength = curve.getLength();
  28663. var u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;
  28664. return curve.getPointAt( u );
  28665. }
  28666. i ++;
  28667. }
  28668. return null;
  28669. // loop where sum != 0, sum > d , sum+1 <d
  28670. },
  28671. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  28672. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  28673. // getPoint() depends on getLength
  28674. getLength: function () {
  28675. var lens = this.getCurveLengths();
  28676. return lens[ lens.length - 1 ];
  28677. },
  28678. // cacheLengths must be recalculated.
  28679. updateArcLengths: function () {
  28680. this.needsUpdate = true;
  28681. this.cacheLengths = null;
  28682. this.getCurveLengths();
  28683. },
  28684. // Compute lengths and cache them
  28685. // We cannot overwrite getLengths() because UtoT mapping uses it.
  28686. getCurveLengths: function () {
  28687. // We use cache values if curves and cache array are same length
  28688. if ( this.cacheLengths && this.cacheLengths.length === this.curves.length ) {
  28689. return this.cacheLengths;
  28690. }
  28691. // Get length of sub-curve
  28692. // Push sums into cached array
  28693. var lengths = [], sums = 0;
  28694. for ( var i = 0, l = this.curves.length; i < l; i ++ ) {
  28695. sums += this.curves[ i ].getLength();
  28696. lengths.push( sums );
  28697. }
  28698. this.cacheLengths = lengths;
  28699. return lengths;
  28700. },
  28701. getSpacedPoints: function ( divisions ) {
  28702. if ( divisions === undefined ) { divisions = 40; }
  28703. var points = [];
  28704. for ( var i = 0; i <= divisions; i ++ ) {
  28705. points.push( this.getPoint( i / divisions ) );
  28706. }
  28707. if ( this.autoClose ) {
  28708. points.push( points[ 0 ] );
  28709. }
  28710. return points;
  28711. },
  28712. getPoints: function ( divisions ) {
  28713. divisions = divisions || 12;
  28714. var points = [], last;
  28715. for ( var i = 0, curves = this.curves; i < curves.length; i ++ ) {
  28716. var curve = curves[ i ];
  28717. var resolution = ( curve && curve.isEllipseCurve ) ? divisions * 2
  28718. : ( curve && ( curve.isLineCurve || curve.isLineCurve3 ) ) ? 1
  28719. : ( curve && curve.isSplineCurve ) ? divisions * curve.points.length
  28720. : divisions;
  28721. var pts = curve.getPoints( resolution );
  28722. for ( var j = 0; j < pts.length; j ++ ) {
  28723. var point = pts[ j ];
  28724. if ( last && last.equals( point ) ) { continue; } // ensures no consecutive points are duplicates
  28725. points.push( point );
  28726. last = point;
  28727. }
  28728. }
  28729. if ( this.autoClose && points.length > 1 && ! points[ points.length - 1 ].equals( points[ 0 ] ) ) {
  28730. points.push( points[ 0 ] );
  28731. }
  28732. return points;
  28733. },
  28734. copy: function ( source ) {
  28735. Curve.prototype.copy.call( this, source );
  28736. this.curves = [];
  28737. for ( var i = 0, l = source.curves.length; i < l; i ++ ) {
  28738. var curve = source.curves[ i ];
  28739. this.curves.push( curve.clone() );
  28740. }
  28741. this.autoClose = source.autoClose;
  28742. return this;
  28743. },
  28744. toJSON: function () {
  28745. var data = Curve.prototype.toJSON.call( this );
  28746. data.autoClose = this.autoClose;
  28747. data.curves = [];
  28748. for ( var i = 0, l = this.curves.length; i < l; i ++ ) {
  28749. var curve = this.curves[ i ];
  28750. data.curves.push( curve.toJSON() );
  28751. }
  28752. return data;
  28753. },
  28754. fromJSON: function ( json ) {
  28755. Curve.prototype.fromJSON.call( this, json );
  28756. this.autoClose = json.autoClose;
  28757. this.curves = [];
  28758. for ( var i = 0, l = json.curves.length; i < l; i ++ ) {
  28759. var curve = json.curves[ i ];
  28760. this.curves.push( new Curves[ curve.type ]().fromJSON( curve ) );
  28761. }
  28762. return this;
  28763. }
  28764. } );
  28765. /**
  28766. * @author zz85 / http://www.lab4games.net/zz85/blog
  28767. * Creates free form 2d path using series of points, lines or curves.
  28768. **/
  28769. function Path( points ) {
  28770. CurvePath.call( this );
  28771. this.type = 'Path';
  28772. this.currentPoint = new Vector2();
  28773. if ( points ) {
  28774. this.setFromPoints( points );
  28775. }
  28776. }
  28777. Path.prototype = Object.assign( Object.create( CurvePath.prototype ), {
  28778. constructor: Path,
  28779. setFromPoints: function ( points ) {
  28780. this.moveTo( points[ 0 ].x, points[ 0 ].y );
  28781. for ( var i = 1, l = points.length; i < l; i ++ ) {
  28782. this.lineTo( points[ i ].x, points[ i ].y );
  28783. }
  28784. return this;
  28785. },
  28786. moveTo: function ( x, y ) {
  28787. this.currentPoint.set( x, y ); // TODO consider referencing vectors instead of copying?
  28788. return this;
  28789. },
  28790. lineTo: function ( x, y ) {
  28791. var curve = new LineCurve( this.currentPoint.clone(), new Vector2( x, y ) );
  28792. this.curves.push( curve );
  28793. this.currentPoint.set( x, y );
  28794. return this;
  28795. },
  28796. quadraticCurveTo: function ( aCPx, aCPy, aX, aY ) {
  28797. var curve = new QuadraticBezierCurve(
  28798. this.currentPoint.clone(),
  28799. new Vector2( aCPx, aCPy ),
  28800. new Vector2( aX, aY )
  28801. );
  28802. this.curves.push( curve );
  28803. this.currentPoint.set( aX, aY );
  28804. return this;
  28805. },
  28806. bezierCurveTo: function ( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  28807. var curve = new CubicBezierCurve(
  28808. this.currentPoint.clone(),
  28809. new Vector2( aCP1x, aCP1y ),
  28810. new Vector2( aCP2x, aCP2y ),
  28811. new Vector2( aX, aY )
  28812. );
  28813. this.curves.push( curve );
  28814. this.currentPoint.set( aX, aY );
  28815. return this;
  28816. },
  28817. splineThru: function ( pts /*Array of Vector*/ ) {
  28818. var npts = [ this.currentPoint.clone() ].concat( pts );
  28819. var curve = new SplineCurve( npts );
  28820. this.curves.push( curve );
  28821. this.currentPoint.copy( pts[ pts.length - 1 ] );
  28822. return this;
  28823. },
  28824. arc: function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  28825. var x0 = this.currentPoint.x;
  28826. var y0 = this.currentPoint.y;
  28827. this.absarc( aX + x0, aY + y0, aRadius,
  28828. aStartAngle, aEndAngle, aClockwise );
  28829. return this;
  28830. },
  28831. absarc: function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  28832. this.absellipse( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  28833. return this;
  28834. },
  28835. ellipse: function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  28836. var x0 = this.currentPoint.x;
  28837. var y0 = this.currentPoint.y;
  28838. this.absellipse( aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  28839. return this;
  28840. },
  28841. absellipse: function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  28842. var curve = new EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  28843. if ( this.curves.length > 0 ) {
  28844. // if a previous curve is present, attempt to join
  28845. var firstPoint = curve.getPoint( 0 );
  28846. if ( ! firstPoint.equals( this.currentPoint ) ) {
  28847. this.lineTo( firstPoint.x, firstPoint.y );
  28848. }
  28849. }
  28850. this.curves.push( curve );
  28851. var lastPoint = curve.getPoint( 1 );
  28852. this.currentPoint.copy( lastPoint );
  28853. return this;
  28854. },
  28855. copy: function ( source ) {
  28856. CurvePath.prototype.copy.call( this, source );
  28857. this.currentPoint.copy( source.currentPoint );
  28858. return this;
  28859. },
  28860. toJSON: function () {
  28861. var data = CurvePath.prototype.toJSON.call( this );
  28862. data.currentPoint = this.currentPoint.toArray();
  28863. return data;
  28864. },
  28865. fromJSON: function ( json ) {
  28866. CurvePath.prototype.fromJSON.call( this, json );
  28867. this.currentPoint.fromArray( json.currentPoint );
  28868. return this;
  28869. }
  28870. } );
  28871. /**
  28872. * @author zz85 / http://www.lab4games.net/zz85/blog
  28873. * Defines a 2d shape plane using paths.
  28874. **/
  28875. // STEP 1 Create a path.
  28876. // STEP 2 Turn path into shape.
  28877. // STEP 3 ExtrudeGeometry takes in Shape/Shapes
  28878. // STEP 3a - Extract points from each shape, turn to vertices
  28879. // STEP 3b - Triangulate each shape, add faces.
  28880. function Shape( points ) {
  28881. Path.call( this, points );
  28882. this.uuid = MathUtils.generateUUID();
  28883. this.type = 'Shape';
  28884. this.holes = [];
  28885. }
  28886. Shape.prototype = Object.assign( Object.create( Path.prototype ), {
  28887. constructor: Shape,
  28888. getPointsHoles: function ( divisions ) {
  28889. var holesPts = [];
  28890. for ( var i = 0, l = this.holes.length; i < l; i ++ ) {
  28891. holesPts[ i ] = this.holes[ i ].getPoints( divisions );
  28892. }
  28893. return holesPts;
  28894. },
  28895. // get points of shape and holes (keypoints based on segments parameter)
  28896. extractPoints: function ( divisions ) {
  28897. return {
  28898. shape: this.getPoints( divisions ),
  28899. holes: this.getPointsHoles( divisions )
  28900. };
  28901. },
  28902. copy: function ( source ) {
  28903. Path.prototype.copy.call( this, source );
  28904. this.holes = [];
  28905. for ( var i = 0, l = source.holes.length; i < l; i ++ ) {
  28906. var hole = source.holes[ i ];
  28907. this.holes.push( hole.clone() );
  28908. }
  28909. return this;
  28910. },
  28911. toJSON: function () {
  28912. var data = Path.prototype.toJSON.call( this );
  28913. data.uuid = this.uuid;
  28914. data.holes = [];
  28915. for ( var i = 0, l = this.holes.length; i < l; i ++ ) {
  28916. var hole = this.holes[ i ];
  28917. data.holes.push( hole.toJSON() );
  28918. }
  28919. return data;
  28920. },
  28921. fromJSON: function ( json ) {
  28922. Path.prototype.fromJSON.call( this, json );
  28923. this.uuid = json.uuid;
  28924. this.holes = [];
  28925. for ( var i = 0, l = json.holes.length; i < l; i ++ ) {
  28926. var hole = json.holes[ i ];
  28927. this.holes.push( new Path().fromJSON( hole ) );
  28928. }
  28929. return this;
  28930. }
  28931. } );
  28932. /**
  28933. * @author mrdoob / http://mrdoob.com/
  28934. * @author alteredq / http://alteredqualia.com/
  28935. */
  28936. function Light( color, intensity ) {
  28937. Object3D.call( this );
  28938. this.type = 'Light';
  28939. this.color = new Color( color );
  28940. this.intensity = intensity !== undefined ? intensity : 1;
  28941. this.receiveShadow = undefined;
  28942. }
  28943. Light.prototype = Object.assign( Object.create( Object3D.prototype ), {
  28944. constructor: Light,
  28945. isLight: true,
  28946. copy: function ( source ) {
  28947. Object3D.prototype.copy.call( this, source );
  28948. this.color.copy( source.color );
  28949. this.intensity = source.intensity;
  28950. return this;
  28951. },
  28952. toJSON: function ( meta ) {
  28953. var data = Object3D.prototype.toJSON.call( this, meta );
  28954. data.object.color = this.color.getHex();
  28955. data.object.intensity = this.intensity;
  28956. if ( this.groundColor !== undefined ) { data.object.groundColor = this.groundColor.getHex(); }
  28957. if ( this.distance !== undefined ) { data.object.distance = this.distance; }
  28958. if ( this.angle !== undefined ) { data.object.angle = this.angle; }
  28959. if ( this.decay !== undefined ) { data.object.decay = this.decay; }
  28960. if ( this.penumbra !== undefined ) { data.object.penumbra = this.penumbra; }
  28961. if ( this.shadow !== undefined ) { data.object.shadow = this.shadow.toJSON(); }
  28962. return data;
  28963. }
  28964. } );
  28965. /**
  28966. * @author alteredq / http://alteredqualia.com/
  28967. */
  28968. function HemisphereLight( skyColor, groundColor, intensity ) {
  28969. Light.call( this, skyColor, intensity );
  28970. this.type = 'HemisphereLight';
  28971. this.castShadow = undefined;
  28972. this.position.copy( Object3D.DefaultUp );
  28973. this.updateMatrix();
  28974. this.groundColor = new Color( groundColor );
  28975. }
  28976. HemisphereLight.prototype = Object.assign( Object.create( Light.prototype ), {
  28977. constructor: HemisphereLight,
  28978. isHemisphereLight: true,
  28979. copy: function ( source ) {
  28980. Light.prototype.copy.call( this, source );
  28981. this.groundColor.copy( source.groundColor );
  28982. return this;
  28983. }
  28984. } );
  28985. /**
  28986. * @author mrdoob / http://mrdoob.com/
  28987. */
  28988. function LightShadow( camera ) {
  28989. this.camera = camera;
  28990. this.bias = 0;
  28991. this.radius = 1;
  28992. this.mapSize = new Vector2( 512, 512 );
  28993. this.map = null;
  28994. this.mapPass = null;
  28995. this.matrix = new Matrix4();
  28996. this._frustum = new Frustum();
  28997. this._frameExtents = new Vector2( 1, 1 );
  28998. this._viewportCount = 1;
  28999. this._viewports = [
  29000. new Vector4( 0, 0, 1, 1 )
  29001. ];
  29002. }
  29003. Object.assign( LightShadow.prototype, {
  29004. _projScreenMatrix: new Matrix4(),
  29005. _lightPositionWorld: new Vector3(),
  29006. _lookTarget: new Vector3(),
  29007. getViewportCount: function () {
  29008. return this._viewportCount;
  29009. },
  29010. getFrustum: function () {
  29011. return this._frustum;
  29012. },
  29013. updateMatrices: function ( light ) {
  29014. var shadowCamera = this.camera,
  29015. shadowMatrix = this.matrix,
  29016. projScreenMatrix = this._projScreenMatrix,
  29017. lookTarget = this._lookTarget,
  29018. lightPositionWorld = this._lightPositionWorld;
  29019. lightPositionWorld.setFromMatrixPosition( light.matrixWorld );
  29020. shadowCamera.position.copy( lightPositionWorld );
  29021. lookTarget.setFromMatrixPosition( light.target.matrixWorld );
  29022. shadowCamera.lookAt( lookTarget );
  29023. shadowCamera.updateMatrixWorld();
  29024. projScreenMatrix.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  29025. this._frustum.setFromProjectionMatrix( projScreenMatrix );
  29026. shadowMatrix.set(
  29027. 0.5, 0.0, 0.0, 0.5,
  29028. 0.0, 0.5, 0.0, 0.5,
  29029. 0.0, 0.0, 0.5, 0.5,
  29030. 0.0, 0.0, 0.0, 1.0
  29031. );
  29032. shadowMatrix.multiply( shadowCamera.projectionMatrix );
  29033. shadowMatrix.multiply( shadowCamera.matrixWorldInverse );
  29034. },
  29035. getViewport: function ( viewportIndex ) {
  29036. return this._viewports[ viewportIndex ];
  29037. },
  29038. getFrameExtents: function () {
  29039. return this._frameExtents;
  29040. },
  29041. copy: function ( source ) {
  29042. this.camera = source.camera.clone();
  29043. this.bias = source.bias;
  29044. this.radius = source.radius;
  29045. this.mapSize.copy( source.mapSize );
  29046. return this;
  29047. },
  29048. clone: function () {
  29049. return new this.constructor().copy( this );
  29050. },
  29051. toJSON: function () {
  29052. var object = {};
  29053. if ( this.bias !== 0 ) { object.bias = this.bias; }
  29054. if ( this.radius !== 1 ) { object.radius = this.radius; }
  29055. if ( this.mapSize.x !== 512 || this.mapSize.y !== 512 ) { object.mapSize = this.mapSize.toArray(); }
  29056. object.camera = this.camera.toJSON( false ).object;
  29057. delete object.camera.matrix;
  29058. return object;
  29059. }
  29060. } );
  29061. /**
  29062. * @author mrdoob / http://mrdoob.com/
  29063. */
  29064. function SpotLightShadow() {
  29065. LightShadow.call( this, new PerspectiveCamera( 50, 1, 0.5, 500 ) );
  29066. }
  29067. SpotLightShadow.prototype = Object.assign( Object.create( LightShadow.prototype ), {
  29068. constructor: SpotLightShadow,
  29069. isSpotLightShadow: true,
  29070. updateMatrices: function ( light ) {
  29071. var camera = this.camera;
  29072. var fov = MathUtils.RAD2DEG * 2 * light.angle;
  29073. var aspect = this.mapSize.width / this.mapSize.height;
  29074. var far = light.distance || camera.far;
  29075. if ( fov !== camera.fov || aspect !== camera.aspect || far !== camera.far ) {
  29076. camera.fov = fov;
  29077. camera.aspect = aspect;
  29078. camera.far = far;
  29079. camera.updateProjectionMatrix();
  29080. }
  29081. LightShadow.prototype.updateMatrices.call( this, light );
  29082. }
  29083. } );
  29084. /**
  29085. * @author alteredq / http://alteredqualia.com/
  29086. */
  29087. function SpotLight( color, intensity, distance, angle, penumbra, decay ) {
  29088. Light.call( this, color, intensity );
  29089. this.type = 'SpotLight';
  29090. this.position.copy( Object3D.DefaultUp );
  29091. this.updateMatrix();
  29092. this.target = new Object3D();
  29093. Object.defineProperty( this, 'power', {
  29094. get: function () {
  29095. // intensity = power per solid angle.
  29096. // ref: equation (17) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  29097. return this.intensity * Math.PI;
  29098. },
  29099. set: function ( power ) {
  29100. // intensity = power per solid angle.
  29101. // ref: equation (17) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  29102. this.intensity = power / Math.PI;
  29103. }
  29104. } );
  29105. this.distance = ( distance !== undefined ) ? distance : 0;
  29106. this.angle = ( angle !== undefined ) ? angle : Math.PI / 3;
  29107. this.penumbra = ( penumbra !== undefined ) ? penumbra : 0;
  29108. this.decay = ( decay !== undefined ) ? decay : 1; // for physically correct lights, should be 2.
  29109. this.shadow = new SpotLightShadow();
  29110. }
  29111. SpotLight.prototype = Object.assign( Object.create( Light.prototype ), {
  29112. constructor: SpotLight,
  29113. isSpotLight: true,
  29114. copy: function ( source ) {
  29115. Light.prototype.copy.call( this, source );
  29116. this.distance = source.distance;
  29117. this.angle = source.angle;
  29118. this.penumbra = source.penumbra;
  29119. this.decay = source.decay;
  29120. this.target = source.target.clone();
  29121. this.shadow = source.shadow.clone();
  29122. return this;
  29123. }
  29124. } );
  29125. function PointLightShadow() {
  29126. LightShadow.call( this, new PerspectiveCamera( 90, 1, 0.5, 500 ) );
  29127. this._frameExtents = new Vector2( 4, 2 );
  29128. this._viewportCount = 6;
  29129. this._viewports = [
  29130. // These viewports map a cube-map onto a 2D texture with the
  29131. // following orientation:
  29132. //
  29133. // xzXZ
  29134. // y Y
  29135. //
  29136. // X - Positive x direction
  29137. // x - Negative x direction
  29138. // Y - Positive y direction
  29139. // y - Negative y direction
  29140. // Z - Positive z direction
  29141. // z - Negative z direction
  29142. // positive X
  29143. new Vector4( 2, 1, 1, 1 ),
  29144. // negative X
  29145. new Vector4( 0, 1, 1, 1 ),
  29146. // positive Z
  29147. new Vector4( 3, 1, 1, 1 ),
  29148. // negative Z
  29149. new Vector4( 1, 1, 1, 1 ),
  29150. // positive Y
  29151. new Vector4( 3, 0, 1, 1 ),
  29152. // negative Y
  29153. new Vector4( 1, 0, 1, 1 )
  29154. ];
  29155. this._cubeDirections = [
  29156. new Vector3( 1, 0, 0 ), new Vector3( - 1, 0, 0 ), new Vector3( 0, 0, 1 ),
  29157. new Vector3( 0, 0, - 1 ), new Vector3( 0, 1, 0 ), new Vector3( 0, - 1, 0 )
  29158. ];
  29159. this._cubeUps = [
  29160. new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ),
  29161. new Vector3( 0, 1, 0 ), new Vector3( 0, 0, 1 ), new Vector3( 0, 0, - 1 )
  29162. ];
  29163. }
  29164. PointLightShadow.prototype = Object.assign( Object.create( LightShadow.prototype ), {
  29165. constructor: PointLightShadow,
  29166. isPointLightShadow: true,
  29167. updateMatrices: function ( light, viewportIndex ) {
  29168. if ( viewportIndex === undefined ) { viewportIndex = 0; }
  29169. var camera = this.camera,
  29170. shadowMatrix = this.matrix,
  29171. lightPositionWorld = this._lightPositionWorld,
  29172. lookTarget = this._lookTarget,
  29173. projScreenMatrix = this._projScreenMatrix;
  29174. lightPositionWorld.setFromMatrixPosition( light.matrixWorld );
  29175. camera.position.copy( lightPositionWorld );
  29176. lookTarget.copy( camera.position );
  29177. lookTarget.add( this._cubeDirections[ viewportIndex ] );
  29178. camera.up.copy( this._cubeUps[ viewportIndex ] );
  29179. camera.lookAt( lookTarget );
  29180. camera.updateMatrixWorld();
  29181. shadowMatrix.makeTranslation( - lightPositionWorld.x, - lightPositionWorld.y, - lightPositionWorld.z );
  29182. projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  29183. this._frustum.setFromProjectionMatrix( projScreenMatrix );
  29184. }
  29185. } );
  29186. /**
  29187. * @author mrdoob / http://mrdoob.com/
  29188. */
  29189. function PointLight( color, intensity, distance, decay ) {
  29190. Light.call( this, color, intensity );
  29191. this.type = 'PointLight';
  29192. Object.defineProperty( this, 'power', {
  29193. get: function () {
  29194. // intensity = power per solid angle.
  29195. // ref: equation (15) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  29196. return this.intensity * 4 * Math.PI;
  29197. },
  29198. set: function ( power ) {
  29199. // intensity = power per solid angle.
  29200. // ref: equation (15) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  29201. this.intensity = power / ( 4 * Math.PI );
  29202. }
  29203. } );
  29204. this.distance = ( distance !== undefined ) ? distance : 0;
  29205. this.decay = ( decay !== undefined ) ? decay : 1; // for physically correct lights, should be 2.
  29206. this.shadow = new PointLightShadow();
  29207. }
  29208. PointLight.prototype = Object.assign( Object.create( Light.prototype ), {
  29209. constructor: PointLight,
  29210. isPointLight: true,
  29211. copy: function ( source ) {
  29212. Light.prototype.copy.call( this, source );
  29213. this.distance = source.distance;
  29214. this.decay = source.decay;
  29215. this.shadow = source.shadow.clone();
  29216. return this;
  29217. }
  29218. } );
  29219. /**
  29220. * @author alteredq / http://alteredqualia.com/
  29221. * @author arose / http://github.com/arose
  29222. */
  29223. function OrthographicCamera( left, right, top, bottom, near, far ) {
  29224. Camera.call( this );
  29225. this.type = 'OrthographicCamera';
  29226. this.zoom = 1;
  29227. this.view = null;
  29228. this.left = ( left !== undefined ) ? left : - 1;
  29229. this.right = ( right !== undefined ) ? right : 1;
  29230. this.top = ( top !== undefined ) ? top : 1;
  29231. this.bottom = ( bottom !== undefined ) ? bottom : - 1;
  29232. this.near = ( near !== undefined ) ? near : 0.1;
  29233. this.far = ( far !== undefined ) ? far : 2000;
  29234. this.updateProjectionMatrix();
  29235. }
  29236. OrthographicCamera.prototype = Object.assign( Object.create( Camera.prototype ), {
  29237. constructor: OrthographicCamera,
  29238. isOrthographicCamera: true,
  29239. copy: function ( source, recursive ) {
  29240. Camera.prototype.copy.call( this, source, recursive );
  29241. this.left = source.left;
  29242. this.right = source.right;
  29243. this.top = source.top;
  29244. this.bottom = source.bottom;
  29245. this.near = source.near;
  29246. this.far = source.far;
  29247. this.zoom = source.zoom;
  29248. this.view = source.view === null ? null : Object.assign( {}, source.view );
  29249. return this;
  29250. },
  29251. setViewOffset: function ( fullWidth, fullHeight, x, y, width, height ) {
  29252. if ( this.view === null ) {
  29253. this.view = {
  29254. enabled: true,
  29255. fullWidth: 1,
  29256. fullHeight: 1,
  29257. offsetX: 0,
  29258. offsetY: 0,
  29259. width: 1,
  29260. height: 1
  29261. };
  29262. }
  29263. this.view.enabled = true;
  29264. this.view.fullWidth = fullWidth;
  29265. this.view.fullHeight = fullHeight;
  29266. this.view.offsetX = x;
  29267. this.view.offsetY = y;
  29268. this.view.width = width;
  29269. this.view.height = height;
  29270. this.updateProjectionMatrix();
  29271. },
  29272. clearViewOffset: function () {
  29273. if ( this.view !== null ) {
  29274. this.view.enabled = false;
  29275. }
  29276. this.updateProjectionMatrix();
  29277. },
  29278. updateProjectionMatrix: function () {
  29279. var dx = ( this.right - this.left ) / ( 2 * this.zoom );
  29280. var dy = ( this.top - this.bottom ) / ( 2 * this.zoom );
  29281. var cx = ( this.right + this.left ) / 2;
  29282. var cy = ( this.top + this.bottom ) / 2;
  29283. var left = cx - dx;
  29284. var right = cx + dx;
  29285. var top = cy + dy;
  29286. var bottom = cy - dy;
  29287. if ( this.view !== null && this.view.enabled ) {
  29288. var scaleW = ( this.right - this.left ) / this.view.fullWidth / this.zoom;
  29289. var scaleH = ( this.top - this.bottom ) / this.view.fullHeight / this.zoom;
  29290. left += scaleW * this.view.offsetX;
  29291. right = left + scaleW * this.view.width;
  29292. top -= scaleH * this.view.offsetY;
  29293. bottom = top - scaleH * this.view.height;
  29294. }
  29295. this.projectionMatrix.makeOrthographic( left, right, top, bottom, this.near, this.far );
  29296. this.projectionMatrixInverse.getInverse( this.projectionMatrix );
  29297. },
  29298. toJSON: function ( meta ) {
  29299. var data = Object3D.prototype.toJSON.call( this, meta );
  29300. data.object.zoom = this.zoom;
  29301. data.object.left = this.left;
  29302. data.object.right = this.right;
  29303. data.object.top = this.top;
  29304. data.object.bottom = this.bottom;
  29305. data.object.near = this.near;
  29306. data.object.far = this.far;
  29307. if ( this.view !== null ) { data.object.view = Object.assign( {}, this.view ); }
  29308. return data;
  29309. }
  29310. } );
  29311. /**
  29312. * @author mrdoob / http://mrdoob.com/
  29313. */
  29314. function DirectionalLightShadow() {
  29315. LightShadow.call( this, new OrthographicCamera( - 5, 5, 5, - 5, 0.5, 500 ) );
  29316. }
  29317. DirectionalLightShadow.prototype = Object.assign( Object.create( LightShadow.prototype ), {
  29318. constructor: DirectionalLightShadow,
  29319. isDirectionalLightShadow: true,
  29320. updateMatrices: function ( light ) {
  29321. LightShadow.prototype.updateMatrices.call( this, light );
  29322. }
  29323. } );
  29324. /**
  29325. * @author mrdoob / http://mrdoob.com/
  29326. * @author alteredq / http://alteredqualia.com/
  29327. */
  29328. function DirectionalLight( color, intensity ) {
  29329. Light.call( this, color, intensity );
  29330. this.type = 'DirectionalLight';
  29331. this.position.copy( Object3D.DefaultUp );
  29332. this.updateMatrix();
  29333. this.target = new Object3D();
  29334. this.shadow = new DirectionalLightShadow();
  29335. }
  29336. DirectionalLight.prototype = Object.assign( Object.create( Light.prototype ), {
  29337. constructor: DirectionalLight,
  29338. isDirectionalLight: true,
  29339. copy: function ( source ) {
  29340. Light.prototype.copy.call( this, source );
  29341. this.target = source.target.clone();
  29342. this.shadow = source.shadow.clone();
  29343. return this;
  29344. }
  29345. } );
  29346. /**
  29347. * @author mrdoob / http://mrdoob.com/
  29348. */
  29349. function AmbientLight( color, intensity ) {
  29350. Light.call( this, color, intensity );
  29351. this.type = 'AmbientLight';
  29352. this.castShadow = undefined;
  29353. }
  29354. AmbientLight.prototype = Object.assign( Object.create( Light.prototype ), {
  29355. constructor: AmbientLight,
  29356. isAmbientLight: true
  29357. } );
  29358. /**
  29359. * @author abelnation / http://github.com/abelnation
  29360. */
  29361. function RectAreaLight( color, intensity, width, height ) {
  29362. Light.call( this, color, intensity );
  29363. this.type = 'RectAreaLight';
  29364. this.width = ( width !== undefined ) ? width : 10;
  29365. this.height = ( height !== undefined ) ? height : 10;
  29366. }
  29367. RectAreaLight.prototype = Object.assign( Object.create( Light.prototype ), {
  29368. constructor: RectAreaLight,
  29369. isRectAreaLight: true,
  29370. copy: function ( source ) {
  29371. Light.prototype.copy.call( this, source );
  29372. this.width = source.width;
  29373. this.height = source.height;
  29374. return this;
  29375. },
  29376. toJSON: function ( meta ) {
  29377. var data = Light.prototype.toJSON.call( this, meta );
  29378. data.object.width = this.width;
  29379. data.object.height = this.height;
  29380. return data;
  29381. }
  29382. } );
  29383. /**
  29384. * @author mrdoob / http://mrdoob.com/
  29385. */
  29386. function MaterialLoader( manager ) {
  29387. Loader.call( this, manager );
  29388. this.textures = {};
  29389. }
  29390. MaterialLoader.prototype = Object.assign( Object.create( Loader.prototype ), {
  29391. constructor: MaterialLoader,
  29392. load: function ( url, onLoad, onProgress, onError ) {
  29393. var scope = this;
  29394. var loader = new FileLoader( scope.manager );
  29395. loader.setPath( scope.path );
  29396. loader.load( url, function ( text ) {
  29397. onLoad( scope.parse( JSON.parse( text ) ) );
  29398. }, onProgress, onError );
  29399. },
  29400. parse: function ( json ) {
  29401. var textures = this.textures;
  29402. function getTexture( name ) {
  29403. if ( textures[ name ] === undefined ) {
  29404. console.warn( 'THREE.MaterialLoader: Undefined texture', name );
  29405. }
  29406. return textures[ name ];
  29407. }
  29408. var material = new Materials[ json.type ]();
  29409. if ( json.uuid !== undefined ) { material.uuid = json.uuid; }
  29410. if ( json.name !== undefined ) { material.name = json.name; }
  29411. if ( json.color !== undefined ) { material.color.setHex( json.color ); }
  29412. if ( json.roughness !== undefined ) { material.roughness = json.roughness; }
  29413. if ( json.metalness !== undefined ) { material.metalness = json.metalness; }
  29414. if ( json.sheen !== undefined ) { material.sheen = new Color().setHex( json.sheen ); }
  29415. if ( json.emissive !== undefined ) { material.emissive.setHex( json.emissive ); }
  29416. if ( json.specular !== undefined ) { material.specular.setHex( json.specular ); }
  29417. if ( json.shininess !== undefined ) { material.shininess = json.shininess; }
  29418. if ( json.clearcoat !== undefined ) { material.clearcoat = json.clearcoat; }
  29419. if ( json.clearcoatRoughness !== undefined ) { material.clearcoatRoughness = json.clearcoatRoughness; }
  29420. if ( json.fog !== undefined ) { material.fog = json.fog; }
  29421. if ( json.flatShading !== undefined ) { material.flatShading = json.flatShading; }
  29422. if ( json.blending !== undefined ) { material.blending = json.blending; }
  29423. if ( json.combine !== undefined ) { material.combine = json.combine; }
  29424. if ( json.side !== undefined ) { material.side = json.side; }
  29425. if ( json.opacity !== undefined ) { material.opacity = json.opacity; }
  29426. if ( json.transparent !== undefined ) { material.transparent = json.transparent; }
  29427. if ( json.alphaTest !== undefined ) { material.alphaTest = json.alphaTest; }
  29428. if ( json.depthTest !== undefined ) { material.depthTest = json.depthTest; }
  29429. if ( json.depthWrite !== undefined ) { material.depthWrite = json.depthWrite; }
  29430. if ( json.colorWrite !== undefined ) { material.colorWrite = json.colorWrite; }
  29431. if ( json.stencilWrite !== undefined ) { material.stencilWrite = json.stencilWrite; }
  29432. if ( json.stencilWriteMask !== undefined ) { material.stencilWriteMask = json.stencilWriteMask; }
  29433. if ( json.stencilFunc !== undefined ) { material.stencilFunc = json.stencilFunc; }
  29434. if ( json.stencilRef !== undefined ) { material.stencilRef = json.stencilRef; }
  29435. if ( json.stencilFuncMask !== undefined ) { material.stencilFuncMask = json.stencilFuncMask; }
  29436. if ( json.stencilFail !== undefined ) { material.stencilFail = json.stencilFail; }
  29437. if ( json.stencilZFail !== undefined ) { material.stencilZFail = json.stencilZFail; }
  29438. if ( json.stencilZPass !== undefined ) { material.stencilZPass = json.stencilZPass; }
  29439. if ( json.wireframe !== undefined ) { material.wireframe = json.wireframe; }
  29440. if ( json.wireframeLinewidth !== undefined ) { material.wireframeLinewidth = json.wireframeLinewidth; }
  29441. if ( json.wireframeLinecap !== undefined ) { material.wireframeLinecap = json.wireframeLinecap; }
  29442. if ( json.wireframeLinejoin !== undefined ) { material.wireframeLinejoin = json.wireframeLinejoin; }
  29443. if ( json.rotation !== undefined ) { material.rotation = json.rotation; }
  29444. if ( json.linewidth !== 1 ) { material.linewidth = json.linewidth; }
  29445. if ( json.dashSize !== undefined ) { material.dashSize = json.dashSize; }
  29446. if ( json.gapSize !== undefined ) { material.gapSize = json.gapSize; }
  29447. if ( json.scale !== undefined ) { material.scale = json.scale; }
  29448. if ( json.polygonOffset !== undefined ) { material.polygonOffset = json.polygonOffset; }
  29449. if ( json.polygonOffsetFactor !== undefined ) { material.polygonOffsetFactor = json.polygonOffsetFactor; }
  29450. if ( json.polygonOffsetUnits !== undefined ) { material.polygonOffsetUnits = json.polygonOffsetUnits; }
  29451. if ( json.skinning !== undefined ) { material.skinning = json.skinning; }
  29452. if ( json.morphTargets !== undefined ) { material.morphTargets = json.morphTargets; }
  29453. if ( json.morphNormals !== undefined ) { material.morphNormals = json.morphNormals; }
  29454. if ( json.dithering !== undefined ) { material.dithering = json.dithering; }
  29455. if ( json.vertexTangents !== undefined ) { material.vertexTangents = json.vertexTangents; }
  29456. if ( json.visible !== undefined ) { material.visible = json.visible; }
  29457. if ( json.toneMapped !== undefined ) { material.toneMapped = json.toneMapped; }
  29458. if ( json.userData !== undefined ) { material.userData = json.userData; }
  29459. if ( json.vertexColors !== undefined ) {
  29460. if ( typeof json.vertexColors === 'number' ) {
  29461. material.vertexColors = ( json.vertexColors > 0 ) ? true : false;
  29462. } else {
  29463. material.vertexColors = json.vertexColors;
  29464. }
  29465. }
  29466. // Shader Material
  29467. if ( json.uniforms !== undefined ) {
  29468. for ( var name in json.uniforms ) {
  29469. var uniform = json.uniforms[ name ];
  29470. material.uniforms[ name ] = {};
  29471. switch ( uniform.type ) {
  29472. case 't':
  29473. material.uniforms[ name ].value = getTexture( uniform.value );
  29474. break;
  29475. case 'c':
  29476. material.uniforms[ name ].value = new Color().setHex( uniform.value );
  29477. break;
  29478. case 'v2':
  29479. material.uniforms[ name ].value = new Vector2().fromArray( uniform.value );
  29480. break;
  29481. case 'v3':
  29482. material.uniforms[ name ].value = new Vector3().fromArray( uniform.value );
  29483. break;
  29484. case 'v4':
  29485. material.uniforms[ name ].value = new Vector4().fromArray( uniform.value );
  29486. break;
  29487. case 'm3':
  29488. material.uniforms[ name ].value = new Matrix3().fromArray( uniform.value );
  29489. case 'm4':
  29490. material.uniforms[ name ].value = new Matrix4().fromArray( uniform.value );
  29491. break;
  29492. default:
  29493. material.uniforms[ name ].value = uniform.value;
  29494. }
  29495. }
  29496. }
  29497. if ( json.defines !== undefined ) { material.defines = json.defines; }
  29498. if ( json.vertexShader !== undefined ) { material.vertexShader = json.vertexShader; }
  29499. if ( json.fragmentShader !== undefined ) { material.fragmentShader = json.fragmentShader; }
  29500. if ( json.extensions !== undefined ) {
  29501. for ( var key in json.extensions ) {
  29502. material.extensions[ key ] = json.extensions[ key ];
  29503. }
  29504. }
  29505. // Deprecated
  29506. if ( json.shading !== undefined ) { material.flatShading = json.shading === 1; } // THREE.FlatShading
  29507. // for PointsMaterial
  29508. if ( json.size !== undefined ) { material.size = json.size; }
  29509. if ( json.sizeAttenuation !== undefined ) { material.sizeAttenuation = json.sizeAttenuation; }
  29510. // maps
  29511. if ( json.map !== undefined ) { material.map = getTexture( json.map ); }
  29512. if ( json.matcap !== undefined ) { material.matcap = getTexture( json.matcap ); }
  29513. if ( json.alphaMap !== undefined ) { material.alphaMap = getTexture( json.alphaMap ); }
  29514. if ( json.bumpMap !== undefined ) { material.bumpMap = getTexture( json.bumpMap ); }
  29515. if ( json.bumpScale !== undefined ) { material.bumpScale = json.bumpScale; }
  29516. if ( json.normalMap !== undefined ) { material.normalMap = getTexture( json.normalMap ); }
  29517. if ( json.normalMapType !== undefined ) { material.normalMapType = json.normalMapType; }
  29518. if ( json.normalScale !== undefined ) {
  29519. var normalScale = json.normalScale;
  29520. if ( Array.isArray( normalScale ) === false ) {
  29521. // Blender exporter used to export a scalar. See #7459
  29522. normalScale = [ normalScale, normalScale ];
  29523. }
  29524. material.normalScale = new Vector2().fromArray( normalScale );
  29525. }
  29526. if ( json.displacementMap !== undefined ) { material.displacementMap = getTexture( json.displacementMap ); }
  29527. if ( json.displacementScale !== undefined ) { material.displacementScale = json.displacementScale; }
  29528. if ( json.displacementBias !== undefined ) { material.displacementBias = json.displacementBias; }
  29529. if ( json.roughnessMap !== undefined ) { material.roughnessMap = getTexture( json.roughnessMap ); }
  29530. if ( json.metalnessMap !== undefined ) { material.metalnessMap = getTexture( json.metalnessMap ); }
  29531. if ( json.emissiveMap !== undefined ) { material.emissiveMap = getTexture( json.emissiveMap ); }
  29532. if ( json.emissiveIntensity !== undefined ) { material.emissiveIntensity = json.emissiveIntensity; }
  29533. if ( json.specularMap !== undefined ) { material.specularMap = getTexture( json.specularMap ); }
  29534. if ( json.envMap !== undefined ) { material.envMap = getTexture( json.envMap ); }
  29535. if ( json.envMapIntensity !== undefined ) { material.envMapIntensity = json.envMapIntensity; }
  29536. if ( json.reflectivity !== undefined ) { material.reflectivity = json.reflectivity; }
  29537. if ( json.refractionRatio !== undefined ) { material.refractionRatio = json.refractionRatio; }
  29538. if ( json.lightMap !== undefined ) { material.lightMap = getTexture( json.lightMap ); }
  29539. if ( json.lightMapIntensity !== undefined ) { material.lightMapIntensity = json.lightMapIntensity; }
  29540. if ( json.aoMap !== undefined ) { material.aoMap = getTexture( json.aoMap ); }
  29541. if ( json.aoMapIntensity !== undefined ) { material.aoMapIntensity = json.aoMapIntensity; }
  29542. if ( json.gradientMap !== undefined ) { material.gradientMap = getTexture( json.gradientMap ); }
  29543. if ( json.clearcoatMap !== undefined ) { material.clearcoatMap = getTexture( json.clearcoatMap ); }
  29544. if ( json.clearcoatRoughnessMap !== undefined ) { material.clearcoatRoughnessMap = getTexture( json.clearcoatRoughnessMap ); }
  29545. if ( json.clearcoatNormalMap !== undefined ) { material.clearcoatNormalMap = getTexture( json.clearcoatNormalMap ); }
  29546. if ( json.clearcoatNormalScale !== undefined ) { material.clearcoatNormalScale = new Vector2().fromArray( json.clearcoatNormalScale ); }
  29547. return material;
  29548. },
  29549. setTextures: function ( value ) {
  29550. this.textures = value;
  29551. return this;
  29552. }
  29553. } );
  29554. /**
  29555. * @author Don McCurdy / https://www.donmccurdy.com
  29556. */
  29557. var LoaderUtils = {
  29558. decodeText: function ( array ) {
  29559. if ( typeof TextDecoder !== 'undefined' ) {
  29560. return new TextDecoder().decode( array );
  29561. }
  29562. // Avoid the String.fromCharCode.apply(null, array) shortcut, which
  29563. // throws a "maximum call stack size exceeded" error for large arrays.
  29564. var s = '';
  29565. for ( var i = 0, il = array.length; i < il; i ++ ) {
  29566. // Implicitly assumes little-endian.
  29567. s += String.fromCharCode( array[ i ] );
  29568. }
  29569. try {
  29570. // merges multi-byte utf-8 characters.
  29571. return decodeURIComponent( escape( s ) );
  29572. } catch ( e ) { // see #16358
  29573. return s;
  29574. }
  29575. },
  29576. extractUrlBase: function ( url ) {
  29577. var index = url.lastIndexOf( '/' );
  29578. if ( index === - 1 ) { return './'; }
  29579. return url.substr( 0, index + 1 );
  29580. }
  29581. };
  29582. /**
  29583. * @author benaadams / https://twitter.com/ben_a_adams
  29584. */
  29585. function InstancedBufferGeometry() {
  29586. BufferGeometry.call( this );
  29587. this.type = 'InstancedBufferGeometry';
  29588. this.maxInstancedCount = undefined;
  29589. }
  29590. InstancedBufferGeometry.prototype = Object.assign( Object.create( BufferGeometry.prototype ), {
  29591. constructor: InstancedBufferGeometry,
  29592. isInstancedBufferGeometry: true,
  29593. copy: function ( source ) {
  29594. BufferGeometry.prototype.copy.call( this, source );
  29595. this.maxInstancedCount = source.maxInstancedCount;
  29596. return this;
  29597. },
  29598. clone: function () {
  29599. return new this.constructor().copy( this );
  29600. },
  29601. toJSON: function () {
  29602. var data = BufferGeometry.prototype.toJSON.call( this );
  29603. data.maxInstancedCount = this.maxInstancedCount;
  29604. data.isInstancedBufferGeometry = true;
  29605. return data;
  29606. }
  29607. } );
  29608. /**
  29609. * @author benaadams / https://twitter.com/ben_a_adams
  29610. */
  29611. function InstancedBufferAttribute( array, itemSize, normalized, meshPerAttribute ) {
  29612. if ( typeof ( normalized ) === 'number' ) {
  29613. meshPerAttribute = normalized;
  29614. normalized = false;
  29615. console.error( 'THREE.InstancedBufferAttribute: The constructor now expects normalized as the third argument.' );
  29616. }
  29617. BufferAttribute.call( this, array, itemSize, normalized );
  29618. this.meshPerAttribute = meshPerAttribute || 1;
  29619. }
  29620. InstancedBufferAttribute.prototype = Object.assign( Object.create( BufferAttribute.prototype ), {
  29621. constructor: InstancedBufferAttribute,
  29622. isInstancedBufferAttribute: true,
  29623. copy: function ( source ) {
  29624. BufferAttribute.prototype.copy.call( this, source );
  29625. this.meshPerAttribute = source.meshPerAttribute;
  29626. return this;
  29627. },
  29628. toJSON: function () {
  29629. var data = BufferAttribute.prototype.toJSON.call( this );
  29630. data.meshPerAttribute = this.meshPerAttribute;
  29631. data.isInstancedBufferAttribute = true;
  29632. return data;
  29633. }
  29634. } );
  29635. /**
  29636. * @author mrdoob / http://mrdoob.com/
  29637. */
  29638. function BufferGeometryLoader( manager ) {
  29639. Loader.call( this, manager );
  29640. }
  29641. BufferGeometryLoader.prototype = Object.assign( Object.create( Loader.prototype ), {
  29642. constructor: BufferGeometryLoader,
  29643. load: function ( url, onLoad, onProgress, onError ) {
  29644. var scope = this;
  29645. var loader = new FileLoader( scope.manager );
  29646. loader.setPath( scope.path );
  29647. loader.load( url, function ( text ) {
  29648. onLoad( scope.parse( JSON.parse( text ) ) );
  29649. }, onProgress, onError );
  29650. },
  29651. parse: function ( json ) {
  29652. var geometry = json.isInstancedBufferGeometry ? new InstancedBufferGeometry() : new BufferGeometry();
  29653. var index = json.data.index;
  29654. if ( index !== undefined ) {
  29655. var typedArray = new TYPED_ARRAYS[ index.type ]( index.array );
  29656. geometry.setIndex( new BufferAttribute( typedArray, 1 ) );
  29657. }
  29658. var attributes = json.data.attributes;
  29659. for ( var key in attributes ) {
  29660. var attribute = attributes[ key ];
  29661. var typedArray = new TYPED_ARRAYS[ attribute.type ]( attribute.array );
  29662. var bufferAttributeConstr = attribute.isInstancedBufferAttribute ? InstancedBufferAttribute : BufferAttribute;
  29663. var bufferAttribute = new bufferAttributeConstr( typedArray, attribute.itemSize, attribute.normalized );
  29664. if ( attribute.name !== undefined ) { bufferAttribute.name = attribute.name; }
  29665. geometry.setAttribute( key, bufferAttribute );
  29666. }
  29667. var morphAttributes = json.data.morphAttributes;
  29668. if ( morphAttributes ) {
  29669. for ( var key in morphAttributes ) {
  29670. var attributeArray = morphAttributes[ key ];
  29671. var array = [];
  29672. for ( var i = 0, il = attributeArray.length; i < il; i ++ ) {
  29673. var attribute = attributeArray[ i ];
  29674. var typedArray = new TYPED_ARRAYS[ attribute.type ]( attribute.array );
  29675. var bufferAttribute = new BufferAttribute( typedArray, attribute.itemSize, attribute.normalized );
  29676. if ( attribute.name !== undefined ) { bufferAttribute.name = attribute.name; }
  29677. array.push( bufferAttribute );
  29678. }
  29679. geometry.morphAttributes[ key ] = array;
  29680. }
  29681. }
  29682. var morphTargetsRelative = json.data.morphTargetsRelative;
  29683. if ( morphTargetsRelative ) {
  29684. geometry.morphTargetsRelative = true;
  29685. }
  29686. var groups = json.data.groups || json.data.drawcalls || json.data.offsets;
  29687. if ( groups !== undefined ) {
  29688. for ( var i = 0, n = groups.length; i !== n; ++ i ) {
  29689. var group = groups[ i ];
  29690. geometry.addGroup( group.start, group.count, group.materialIndex );
  29691. }
  29692. }
  29693. var boundingSphere = json.data.boundingSphere;
  29694. if ( boundingSphere !== undefined ) {
  29695. var center = new Vector3();
  29696. if ( boundingSphere.center !== undefined ) {
  29697. center.fromArray( boundingSphere.center );
  29698. }
  29699. geometry.boundingSphere = new Sphere( center, boundingSphere.radius );
  29700. }
  29701. if ( json.name ) { geometry.name = json.name; }
  29702. if ( json.userData ) { geometry.userData = json.userData; }
  29703. return geometry;
  29704. }
  29705. } );
  29706. var TYPED_ARRAYS = {
  29707. Int8Array: Int8Array,
  29708. Uint8Array: Uint8Array,
  29709. // Workaround for IE11 pre KB2929437. See #11440
  29710. Uint8ClampedArray: typeof Uint8ClampedArray !== 'undefined' ? Uint8ClampedArray : Uint8Array,
  29711. Int16Array: Int16Array,
  29712. Uint16Array: Uint16Array,
  29713. Int32Array: Int32Array,
  29714. Uint32Array: Uint32Array,
  29715. Float32Array: Float32Array,
  29716. Float64Array: Float64Array
  29717. };
  29718. /**
  29719. * @author mrdoob / http://mrdoob.com/
  29720. */
  29721. function ObjectLoader( manager ) {
  29722. Loader.call( this, manager );
  29723. }
  29724. ObjectLoader.prototype = Object.assign( Object.create( Loader.prototype ), {
  29725. constructor: ObjectLoader,
  29726. load: function ( url, onLoad, onProgress, onError ) {
  29727. var scope = this;
  29728. var path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  29729. this.resourcePath = this.resourcePath || path;
  29730. var loader = new FileLoader( scope.manager );
  29731. loader.setPath( this.path );
  29732. loader.load( url, function ( text ) {
  29733. var json = null;
  29734. try {
  29735. json = JSON.parse( text );
  29736. } catch ( error ) {
  29737. if ( onError !== undefined ) { onError( error ); }
  29738. console.error( 'THREE:ObjectLoader: Can\'t parse ' + url + '.', error.message );
  29739. return;
  29740. }
  29741. var metadata = json.metadata;
  29742. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  29743. console.error( 'THREE.ObjectLoader: Can\'t load ' + url );
  29744. return;
  29745. }
  29746. scope.parse( json, onLoad );
  29747. }, onProgress, onError );
  29748. },
  29749. parse: function ( json, onLoad ) {
  29750. var shapes = this.parseShape( json.shapes );
  29751. var geometries = this.parseGeometries( json.geometries, shapes );
  29752. var images = this.parseImages( json.images, function () {
  29753. if ( onLoad !== undefined ) { onLoad( object ); }
  29754. } );
  29755. var textures = this.parseTextures( json.textures, images );
  29756. var materials = this.parseMaterials( json.materials, textures );
  29757. var object = this.parseObject( json.object, geometries, materials );
  29758. if ( json.animations ) {
  29759. object.animations = this.parseAnimations( json.animations );
  29760. }
  29761. if ( json.images === undefined || json.images.length === 0 ) {
  29762. if ( onLoad !== undefined ) { onLoad( object ); }
  29763. }
  29764. return object;
  29765. },
  29766. parseShape: function ( json ) {
  29767. var shapes = {};
  29768. if ( json !== undefined ) {
  29769. for ( var i = 0, l = json.length; i < l; i ++ ) {
  29770. var shape = new Shape().fromJSON( json[ i ] );
  29771. shapes[ shape.uuid ] = shape;
  29772. }
  29773. }
  29774. return shapes;
  29775. },
  29776. parseGeometries: function ( json, shapes ) {
  29777. var geometries = {};
  29778. if ( json !== undefined ) {
  29779. var bufferGeometryLoader = new BufferGeometryLoader();
  29780. for ( var i = 0, l = json.length; i < l; i ++ ) {
  29781. var geometry;
  29782. var data = json[ i ];
  29783. switch ( data.type ) {
  29784. case 'PlaneGeometry':
  29785. case 'PlaneBufferGeometry':
  29786. geometry = new Geometries[ data.type ](
  29787. data.width,
  29788. data.height,
  29789. data.widthSegments,
  29790. data.heightSegments
  29791. );
  29792. break;
  29793. case 'BoxGeometry':
  29794. case 'BoxBufferGeometry':
  29795. case 'CubeGeometry': // backwards compatible
  29796. geometry = new Geometries[ data.type ](
  29797. data.width,
  29798. data.height,
  29799. data.depth,
  29800. data.widthSegments,
  29801. data.heightSegments,
  29802. data.depthSegments
  29803. );
  29804. break;
  29805. case 'CircleGeometry':
  29806. case 'CircleBufferGeometry':
  29807. geometry = new Geometries[ data.type ](
  29808. data.radius,
  29809. data.segments,
  29810. data.thetaStart,
  29811. data.thetaLength
  29812. );
  29813. break;
  29814. case 'CylinderGeometry':
  29815. case 'CylinderBufferGeometry':
  29816. geometry = new Geometries[ data.type ](
  29817. data.radiusTop,
  29818. data.radiusBottom,
  29819. data.height,
  29820. data.radialSegments,
  29821. data.heightSegments,
  29822. data.openEnded,
  29823. data.thetaStart,
  29824. data.thetaLength
  29825. );
  29826. break;
  29827. case 'ConeGeometry':
  29828. case 'ConeBufferGeometry':
  29829. geometry = new Geometries[ data.type ](
  29830. data.radius,
  29831. data.height,
  29832. data.radialSegments,
  29833. data.heightSegments,
  29834. data.openEnded,
  29835. data.thetaStart,
  29836. data.thetaLength
  29837. );
  29838. break;
  29839. case 'SphereGeometry':
  29840. case 'SphereBufferGeometry':
  29841. geometry = new Geometries[ data.type ](
  29842. data.radius,
  29843. data.widthSegments,
  29844. data.heightSegments,
  29845. data.phiStart,
  29846. data.phiLength,
  29847. data.thetaStart,
  29848. data.thetaLength
  29849. );
  29850. break;
  29851. case 'DodecahedronGeometry':
  29852. case 'DodecahedronBufferGeometry':
  29853. case 'IcosahedronGeometry':
  29854. case 'IcosahedronBufferGeometry':
  29855. case 'OctahedronGeometry':
  29856. case 'OctahedronBufferGeometry':
  29857. case 'TetrahedronGeometry':
  29858. case 'TetrahedronBufferGeometry':
  29859. geometry = new Geometries[ data.type ](
  29860. data.radius,
  29861. data.detail
  29862. );
  29863. break;
  29864. case 'RingGeometry':
  29865. case 'RingBufferGeometry':
  29866. geometry = new Geometries[ data.type ](
  29867. data.innerRadius,
  29868. data.outerRadius,
  29869. data.thetaSegments,
  29870. data.phiSegments,
  29871. data.thetaStart,
  29872. data.thetaLength
  29873. );
  29874. break;
  29875. case 'TorusGeometry':
  29876. case 'TorusBufferGeometry':
  29877. geometry = new Geometries[ data.type ](
  29878. data.radius,
  29879. data.tube,
  29880. data.radialSegments,
  29881. data.tubularSegments,
  29882. data.arc
  29883. );
  29884. break;
  29885. case 'TorusKnotGeometry':
  29886. case 'TorusKnotBufferGeometry':
  29887. geometry = new Geometries[ data.type ](
  29888. data.radius,
  29889. data.tube,
  29890. data.tubularSegments,
  29891. data.radialSegments,
  29892. data.p,
  29893. data.q
  29894. );
  29895. break;
  29896. case 'TubeGeometry':
  29897. case 'TubeBufferGeometry':
  29898. // This only works for built-in curves (e.g. CatmullRomCurve3).
  29899. // User defined curves or instances of CurvePath will not be deserialized.
  29900. geometry = new Geometries[ data.type ](
  29901. new Curves[ data.path.type ]().fromJSON( data.path ),
  29902. data.tubularSegments,
  29903. data.radius,
  29904. data.radialSegments,
  29905. data.closed
  29906. );
  29907. break;
  29908. case 'LatheGeometry':
  29909. case 'LatheBufferGeometry':
  29910. geometry = new Geometries[ data.type ](
  29911. data.points,
  29912. data.segments,
  29913. data.phiStart,
  29914. data.phiLength
  29915. );
  29916. break;
  29917. case 'PolyhedronGeometry':
  29918. case 'PolyhedronBufferGeometry':
  29919. geometry = new Geometries[ data.type ](
  29920. data.vertices,
  29921. data.indices,
  29922. data.radius,
  29923. data.details
  29924. );
  29925. break;
  29926. case 'ShapeGeometry':
  29927. case 'ShapeBufferGeometry':
  29928. var geometryShapes = [];
  29929. for ( var j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  29930. var shape = shapes[ data.shapes[ j ] ];
  29931. geometryShapes.push( shape );
  29932. }
  29933. geometry = new Geometries[ data.type ](
  29934. geometryShapes,
  29935. data.curveSegments
  29936. );
  29937. break;
  29938. case 'ExtrudeGeometry':
  29939. case 'ExtrudeBufferGeometry':
  29940. var geometryShapes = [];
  29941. for ( var j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  29942. var shape = shapes[ data.shapes[ j ] ];
  29943. geometryShapes.push( shape );
  29944. }
  29945. var extrudePath = data.options.extrudePath;
  29946. if ( extrudePath !== undefined ) {
  29947. data.options.extrudePath = new Curves[ extrudePath.type ]().fromJSON( extrudePath );
  29948. }
  29949. geometry = new Geometries[ data.type ](
  29950. geometryShapes,
  29951. data.options
  29952. );
  29953. break;
  29954. case 'BufferGeometry':
  29955. case 'InstancedBufferGeometry':
  29956. geometry = bufferGeometryLoader.parse( data );
  29957. break;
  29958. case 'Geometry':
  29959. console.error( 'THREE.ObjectLoader: Loading "Geometry" is not supported anymore.' );
  29960. break;
  29961. default:
  29962. console.warn( 'THREE.ObjectLoader: Unsupported geometry type "' + data.type + '"' );
  29963. continue;
  29964. }
  29965. geometry.uuid = data.uuid;
  29966. if ( data.name !== undefined ) { geometry.name = data.name; }
  29967. if ( geometry.isBufferGeometry === true && data.userData !== undefined ) { geometry.userData = data.userData; }
  29968. geometries[ data.uuid ] = geometry;
  29969. }
  29970. }
  29971. return geometries;
  29972. },
  29973. parseMaterials: function ( json, textures ) {
  29974. var cache = {}; // MultiMaterial
  29975. var materials = {};
  29976. if ( json !== undefined ) {
  29977. var loader = new MaterialLoader();
  29978. loader.setTextures( textures );
  29979. for ( var i = 0, l = json.length; i < l; i ++ ) {
  29980. var data = json[ i ];
  29981. if ( data.type === 'MultiMaterial' ) {
  29982. // Deprecated
  29983. var array = [];
  29984. for ( var j = 0; j < data.materials.length; j ++ ) {
  29985. var material = data.materials[ j ];
  29986. if ( cache[ material.uuid ] === undefined ) {
  29987. cache[ material.uuid ] = loader.parse( material );
  29988. }
  29989. array.push( cache[ material.uuid ] );
  29990. }
  29991. materials[ data.uuid ] = array;
  29992. } else {
  29993. if ( cache[ data.uuid ] === undefined ) {
  29994. cache[ data.uuid ] = loader.parse( data );
  29995. }
  29996. materials[ data.uuid ] = cache[ data.uuid ];
  29997. }
  29998. }
  29999. }
  30000. return materials;
  30001. },
  30002. parseAnimations: function ( json ) {
  30003. var animations = [];
  30004. for ( var i = 0; i < json.length; i ++ ) {
  30005. var data = json[ i ];
  30006. var clip = AnimationClip.parse( data );
  30007. if ( data.uuid !== undefined ) { clip.uuid = data.uuid; }
  30008. animations.push( clip );
  30009. }
  30010. return animations;
  30011. },
  30012. parseImages: function ( json, onLoad ) {
  30013. var scope = this;
  30014. var images = {};
  30015. function loadImage( url ) {
  30016. scope.manager.itemStart( url );
  30017. return loader.load( url, function () {
  30018. scope.manager.itemEnd( url );
  30019. }, undefined, function () {
  30020. scope.manager.itemError( url );
  30021. scope.manager.itemEnd( url );
  30022. } );
  30023. }
  30024. if ( json !== undefined && json.length > 0 ) {
  30025. var manager = new LoadingManager( onLoad );
  30026. var loader = new ImageLoader( manager );
  30027. loader.setCrossOrigin( this.crossOrigin );
  30028. for ( var i = 0, il = json.length; i < il; i ++ ) {
  30029. var image = json[ i ];
  30030. var url = image.url;
  30031. if ( Array.isArray( url ) ) {
  30032. // load array of images e.g CubeTexture
  30033. images[ image.uuid ] = [];
  30034. for ( var j = 0, jl = url.length; j < jl; j ++ ) {
  30035. var currentUrl = url[ j ];
  30036. var path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( currentUrl ) ? currentUrl : scope.resourcePath + currentUrl;
  30037. images[ image.uuid ].push( loadImage( path ) );
  30038. }
  30039. } else {
  30040. // load single image
  30041. var path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( image.url ) ? image.url : scope.resourcePath + image.url;
  30042. images[ image.uuid ] = loadImage( path );
  30043. }
  30044. }
  30045. }
  30046. return images;
  30047. },
  30048. parseTextures: function ( json, images ) {
  30049. function parseConstant( value, type ) {
  30050. if ( typeof value === 'number' ) { return value; }
  30051. console.warn( 'THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value );
  30052. return type[ value ];
  30053. }
  30054. var textures = {};
  30055. if ( json !== undefined ) {
  30056. for ( var i = 0, l = json.length; i < l; i ++ ) {
  30057. var data = json[ i ];
  30058. if ( data.image === undefined ) {
  30059. console.warn( 'THREE.ObjectLoader: No "image" specified for', data.uuid );
  30060. }
  30061. if ( images[ data.image ] === undefined ) {
  30062. console.warn( 'THREE.ObjectLoader: Undefined image', data.image );
  30063. }
  30064. var texture;
  30065. if ( Array.isArray( images[ data.image ] ) ) {
  30066. texture = new CubeTexture( images[ data.image ] );
  30067. } else {
  30068. texture = new Texture( images[ data.image ] );
  30069. }
  30070. texture.needsUpdate = true;
  30071. texture.uuid = data.uuid;
  30072. if ( data.name !== undefined ) { texture.name = data.name; }
  30073. if ( data.mapping !== undefined ) { texture.mapping = parseConstant( data.mapping, TEXTURE_MAPPING ); }
  30074. if ( data.offset !== undefined ) { texture.offset.fromArray( data.offset ); }
  30075. if ( data.repeat !== undefined ) { texture.repeat.fromArray( data.repeat ); }
  30076. if ( data.center !== undefined ) { texture.center.fromArray( data.center ); }
  30077. if ( data.rotation !== undefined ) { texture.rotation = data.rotation; }
  30078. if ( data.wrap !== undefined ) {
  30079. texture.wrapS = parseConstant( data.wrap[ 0 ], TEXTURE_WRAPPING );
  30080. texture.wrapT = parseConstant( data.wrap[ 1 ], TEXTURE_WRAPPING );
  30081. }
  30082. if ( data.format !== undefined ) { texture.format = data.format; }
  30083. if ( data.type !== undefined ) { texture.type = data.type; }
  30084. if ( data.encoding !== undefined ) { texture.encoding = data.encoding; }
  30085. if ( data.minFilter !== undefined ) { texture.minFilter = parseConstant( data.minFilter, TEXTURE_FILTER ); }
  30086. if ( data.magFilter !== undefined ) { texture.magFilter = parseConstant( data.magFilter, TEXTURE_FILTER ); }
  30087. if ( data.anisotropy !== undefined ) { texture.anisotropy = data.anisotropy; }
  30088. if ( data.flipY !== undefined ) { texture.flipY = data.flipY; }
  30089. if ( data.premultiplyAlpha !== undefined ) { texture.premultiplyAlpha = data.premultiplyAlpha; }
  30090. if ( data.unpackAlignment !== undefined ) { texture.unpackAlignment = data.unpackAlignment; }
  30091. textures[ data.uuid ] = texture;
  30092. }
  30093. }
  30094. return textures;
  30095. },
  30096. parseObject: function ( data, geometries, materials ) {
  30097. var object;
  30098. function getGeometry( name ) {
  30099. if ( geometries[ name ] === undefined ) {
  30100. console.warn( 'THREE.ObjectLoader: Undefined geometry', name );
  30101. }
  30102. return geometries[ name ];
  30103. }
  30104. function getMaterial( name ) {
  30105. if ( name === undefined ) { return undefined; }
  30106. if ( Array.isArray( name ) ) {
  30107. var array = [];
  30108. for ( var i = 0, l = name.length; i < l; i ++ ) {
  30109. var uuid = name[ i ];
  30110. if ( materials[ uuid ] === undefined ) {
  30111. console.warn( 'THREE.ObjectLoader: Undefined material', uuid );
  30112. }
  30113. array.push( materials[ uuid ] );
  30114. }
  30115. return array;
  30116. }
  30117. if ( materials[ name ] === undefined ) {
  30118. console.warn( 'THREE.ObjectLoader: Undefined material', name );
  30119. }
  30120. return materials[ name ];
  30121. }
  30122. switch ( data.type ) {
  30123. case 'Scene':
  30124. object = new Scene();
  30125. if ( data.background !== undefined ) {
  30126. if ( Number.isInteger( data.background ) ) {
  30127. object.background = new Color( data.background );
  30128. }
  30129. }
  30130. if ( data.fog !== undefined ) {
  30131. if ( data.fog.type === 'Fog' ) {
  30132. object.fog = new Fog( data.fog.color, data.fog.near, data.fog.far );
  30133. } else if ( data.fog.type === 'FogExp2' ) {
  30134. object.fog = new FogExp2( data.fog.color, data.fog.density );
  30135. }
  30136. }
  30137. break;
  30138. case 'PerspectiveCamera':
  30139. object = new PerspectiveCamera( data.fov, data.aspect, data.near, data.far );
  30140. if ( data.focus !== undefined ) { object.focus = data.focus; }
  30141. if ( data.zoom !== undefined ) { object.zoom = data.zoom; }
  30142. if ( data.filmGauge !== undefined ) { object.filmGauge = data.filmGauge; }
  30143. if ( data.filmOffset !== undefined ) { object.filmOffset = data.filmOffset; }
  30144. if ( data.view !== undefined ) { object.view = Object.assign( {}, data.view ); }
  30145. break;
  30146. case 'OrthographicCamera':
  30147. object = new OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far );
  30148. if ( data.zoom !== undefined ) { object.zoom = data.zoom; }
  30149. if ( data.view !== undefined ) { object.view = Object.assign( {}, data.view ); }
  30150. break;
  30151. case 'AmbientLight':
  30152. object = new AmbientLight( data.color, data.intensity );
  30153. break;
  30154. case 'DirectionalLight':
  30155. object = new DirectionalLight( data.color, data.intensity );
  30156. break;
  30157. case 'PointLight':
  30158. object = new PointLight( data.color, data.intensity, data.distance, data.decay );
  30159. break;
  30160. case 'RectAreaLight':
  30161. object = new RectAreaLight( data.color, data.intensity, data.width, data.height );
  30162. break;
  30163. case 'SpotLight':
  30164. object = new SpotLight( data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay );
  30165. break;
  30166. case 'HemisphereLight':
  30167. object = new HemisphereLight( data.color, data.groundColor, data.intensity );
  30168. break;
  30169. case 'SkinnedMesh':
  30170. console.warn( 'THREE.ObjectLoader.parseObject() does not support SkinnedMesh yet.' );
  30171. case 'Mesh':
  30172. var geometry = getGeometry( data.geometry );
  30173. var material = getMaterial( data.material );
  30174. object = new Mesh( geometry, material );
  30175. break;
  30176. case 'InstancedMesh':
  30177. var geometry = getGeometry( data.geometry );
  30178. var material = getMaterial( data.material );
  30179. var count = data.count;
  30180. var instanceMatrix = data.instanceMatrix;
  30181. object = new InstancedMesh( geometry, material, count );
  30182. object.instanceMatrix = new BufferAttribute( new Float32Array( instanceMatrix.array ), 16 );
  30183. break;
  30184. case 'LOD':
  30185. object = new LOD();
  30186. break;
  30187. case 'Line':
  30188. object = new Line( getGeometry( data.geometry ), getMaterial( data.material ), data.mode );
  30189. break;
  30190. case 'LineLoop':
  30191. object = new LineLoop( getGeometry( data.geometry ), getMaterial( data.material ) );
  30192. break;
  30193. case 'LineSegments':
  30194. object = new LineSegments( getGeometry( data.geometry ), getMaterial( data.material ) );
  30195. break;
  30196. case 'PointCloud':
  30197. case 'Points':
  30198. object = new Points( getGeometry( data.geometry ), getMaterial( data.material ) );
  30199. break;
  30200. case 'Sprite':
  30201. object = new Sprite( getMaterial( data.material ) );
  30202. break;
  30203. case 'Group':
  30204. object = new Group();
  30205. break;
  30206. default:
  30207. object = new Object3D();
  30208. }
  30209. object.uuid = data.uuid;
  30210. if ( data.name !== undefined ) { object.name = data.name; }
  30211. if ( data.matrix !== undefined ) {
  30212. object.matrix.fromArray( data.matrix );
  30213. if ( data.matrixAutoUpdate !== undefined ) { object.matrixAutoUpdate = data.matrixAutoUpdate; }
  30214. if ( object.matrixAutoUpdate ) { object.matrix.decompose( object.position, object.quaternion, object.scale ); }
  30215. } else {
  30216. if ( data.position !== undefined ) { object.position.fromArray( data.position ); }
  30217. if ( data.rotation !== undefined ) { object.rotation.fromArray( data.rotation ); }
  30218. if ( data.quaternion !== undefined ) { object.quaternion.fromArray( data.quaternion ); }
  30219. if ( data.scale !== undefined ) { object.scale.fromArray( data.scale ); }
  30220. }
  30221. if ( data.castShadow !== undefined ) { object.castShadow = data.castShadow; }
  30222. if ( data.receiveShadow !== undefined ) { object.receiveShadow = data.receiveShadow; }
  30223. if ( data.shadow ) {
  30224. if ( data.shadow.bias !== undefined ) { object.shadow.bias = data.shadow.bias; }
  30225. if ( data.shadow.radius !== undefined ) { object.shadow.radius = data.shadow.radius; }
  30226. if ( data.shadow.mapSize !== undefined ) { object.shadow.mapSize.fromArray( data.shadow.mapSize ); }
  30227. if ( data.shadow.camera !== undefined ) { object.shadow.camera = this.parseObject( data.shadow.camera ); }
  30228. }
  30229. if ( data.visible !== undefined ) { object.visible = data.visible; }
  30230. if ( data.frustumCulled !== undefined ) { object.frustumCulled = data.frustumCulled; }
  30231. if ( data.renderOrder !== undefined ) { object.renderOrder = data.renderOrder; }
  30232. if ( data.userData !== undefined ) { object.userData = data.userData; }
  30233. if ( data.layers !== undefined ) { object.layers.mask = data.layers; }
  30234. if ( data.children !== undefined ) {
  30235. var children = data.children;
  30236. for ( var i = 0; i < children.length; i ++ ) {
  30237. object.add( this.parseObject( children[ i ], geometries, materials ) );
  30238. }
  30239. }
  30240. if ( data.type === 'LOD' ) {
  30241. if ( data.autoUpdate !== undefined ) { object.autoUpdate = data.autoUpdate; }
  30242. var levels = data.levels;
  30243. for ( var l = 0; l < levels.length; l ++ ) {
  30244. var level = levels[ l ];
  30245. var child = object.getObjectByProperty( 'uuid', level.object );
  30246. if ( child !== undefined ) {
  30247. object.addLevel( child, level.distance );
  30248. }
  30249. }
  30250. }
  30251. return object;
  30252. }
  30253. } );
  30254. var TEXTURE_MAPPING = {
  30255. UVMapping: UVMapping,
  30256. CubeReflectionMapping: CubeReflectionMapping,
  30257. CubeRefractionMapping: CubeRefractionMapping,
  30258. EquirectangularReflectionMapping: EquirectangularReflectionMapping,
  30259. EquirectangularRefractionMapping: EquirectangularRefractionMapping,
  30260. SphericalReflectionMapping: SphericalReflectionMapping,
  30261. CubeUVReflectionMapping: CubeUVReflectionMapping,
  30262. CubeUVRefractionMapping: CubeUVRefractionMapping
  30263. };
  30264. var TEXTURE_WRAPPING = {
  30265. RepeatWrapping: RepeatWrapping,
  30266. ClampToEdgeWrapping: ClampToEdgeWrapping,
  30267. MirroredRepeatWrapping: MirroredRepeatWrapping
  30268. };
  30269. var TEXTURE_FILTER = {
  30270. NearestFilter: NearestFilter,
  30271. NearestMipmapNearestFilter: NearestMipmapNearestFilter,
  30272. NearestMipmapLinearFilter: NearestMipmapLinearFilter,
  30273. LinearFilter: LinearFilter,
  30274. LinearMipmapNearestFilter: LinearMipmapNearestFilter,
  30275. LinearMipmapLinearFilter: LinearMipmapLinearFilter
  30276. };
  30277. /**
  30278. * @author thespite / http://clicktorelease.com/
  30279. */
  30280. function ImageBitmapLoader( manager ) {
  30281. if ( typeof createImageBitmap === 'undefined' ) {
  30282. console.warn( 'THREE.ImageBitmapLoader: createImageBitmap() not supported.' );
  30283. }
  30284. if ( typeof fetch === 'undefined' ) {
  30285. console.warn( 'THREE.ImageBitmapLoader: fetch() not supported.' );
  30286. }
  30287. Loader.call( this, manager );
  30288. this.options = undefined;
  30289. }
  30290. ImageBitmapLoader.prototype = Object.assign( Object.create( Loader.prototype ), {
  30291. constructor: ImageBitmapLoader,
  30292. setOptions: function setOptions( options ) {
  30293. this.options = options;
  30294. return this;
  30295. },
  30296. load: function ( url, onLoad, onProgress, onError ) {
  30297. if ( url === undefined ) { url = ''; }
  30298. if ( this.path !== undefined ) { url = this.path + url; }
  30299. url = this.manager.resolveURL( url );
  30300. var scope = this;
  30301. var cached = Cache.get( url );
  30302. if ( cached !== undefined ) {
  30303. scope.manager.itemStart( url );
  30304. setTimeout( function () {
  30305. if ( onLoad ) { onLoad( cached ); }
  30306. scope.manager.itemEnd( url );
  30307. }, 0 );
  30308. return cached;
  30309. }
  30310. fetch( url ).then( function ( res ) {
  30311. return res.blob();
  30312. } ).then( function ( blob ) {
  30313. if ( scope.options === undefined ) {
  30314. // Workaround for FireFox. It causes an error if you pass options.
  30315. return createImageBitmap( blob );
  30316. } else {
  30317. return createImageBitmap( blob, scope.options );
  30318. }
  30319. } ).then( function ( imageBitmap ) {
  30320. Cache.add( url, imageBitmap );
  30321. if ( onLoad ) { onLoad( imageBitmap ); }
  30322. scope.manager.itemEnd( url );
  30323. } ).catch( function ( e ) {
  30324. if ( onError ) { onError( e ); }
  30325. scope.manager.itemError( url );
  30326. scope.manager.itemEnd( url );
  30327. } );
  30328. scope.manager.itemStart( url );
  30329. }
  30330. } );
  30331. /**
  30332. * @author zz85 / http://www.lab4games.net/zz85/blog
  30333. * minimal class for proxing functions to Path. Replaces old "extractSubpaths()"
  30334. **/
  30335. function ShapePath() {
  30336. this.type = 'ShapePath';
  30337. this.color = new Color();
  30338. this.subPaths = [];
  30339. this.currentPath = null;
  30340. }
  30341. Object.assign( ShapePath.prototype, {
  30342. moveTo: function ( x, y ) {
  30343. this.currentPath = new Path();
  30344. this.subPaths.push( this.currentPath );
  30345. this.currentPath.moveTo( x, y );
  30346. return this;
  30347. },
  30348. lineTo: function ( x, y ) {
  30349. this.currentPath.lineTo( x, y );
  30350. return this;
  30351. },
  30352. quadraticCurveTo: function ( aCPx, aCPy, aX, aY ) {
  30353. this.currentPath.quadraticCurveTo( aCPx, aCPy, aX, aY );
  30354. return this;
  30355. },
  30356. bezierCurveTo: function ( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  30357. this.currentPath.bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY );
  30358. return this;
  30359. },
  30360. splineThru: function ( pts ) {
  30361. this.currentPath.splineThru( pts );
  30362. return this;
  30363. },
  30364. toShapes: function ( isCCW, noHoles ) {
  30365. function toShapesNoHoles( inSubpaths ) {
  30366. var shapes = [];
  30367. for ( var i = 0, l = inSubpaths.length; i < l; i ++ ) {
  30368. var tmpPath = inSubpaths[ i ];
  30369. var tmpShape = new Shape();
  30370. tmpShape.curves = tmpPath.curves;
  30371. shapes.push( tmpShape );
  30372. }
  30373. return shapes;
  30374. }
  30375. function isPointInsidePolygon( inPt, inPolygon ) {
  30376. var polyLen = inPolygon.length;
  30377. // inPt on polygon contour => immediate success or
  30378. // toggling of inside/outside at every single! intersection point of an edge
  30379. // with the horizontal line through inPt, left of inPt
  30380. // not counting lowerY endpoints of edges and whole edges on that line
  30381. var inside = false;
  30382. for ( var p = polyLen - 1, q = 0; q < polyLen; p = q ++ ) {
  30383. var edgeLowPt = inPolygon[ p ];
  30384. var edgeHighPt = inPolygon[ q ];
  30385. var edgeDx = edgeHighPt.x - edgeLowPt.x;
  30386. var edgeDy = edgeHighPt.y - edgeLowPt.y;
  30387. if ( Math.abs( edgeDy ) > Number.EPSILON ) {
  30388. // not parallel
  30389. if ( edgeDy < 0 ) {
  30390. edgeLowPt = inPolygon[ q ]; edgeDx = - edgeDx;
  30391. edgeHighPt = inPolygon[ p ]; edgeDy = - edgeDy;
  30392. }
  30393. if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) { continue; }
  30394. if ( inPt.y === edgeLowPt.y ) {
  30395. if ( inPt.x === edgeLowPt.x ) { return true; } // inPt is on contour ?
  30396. // continue; // no intersection or edgeLowPt => doesn't count !!!
  30397. } else {
  30398. var perpEdge = edgeDy * ( inPt.x - edgeLowPt.x ) - edgeDx * ( inPt.y - edgeLowPt.y );
  30399. if ( perpEdge === 0 ) { return true; } // inPt is on contour ?
  30400. if ( perpEdge < 0 ) { continue; }
  30401. inside = ! inside; // true intersection left of inPt
  30402. }
  30403. } else {
  30404. // parallel or collinear
  30405. if ( inPt.y !== edgeLowPt.y ) { continue; } // parallel
  30406. // edge lies on the same horizontal line as inPt
  30407. if ( ( ( edgeHighPt.x <= inPt.x ) && ( inPt.x <= edgeLowPt.x ) ) ||
  30408. ( ( edgeLowPt.x <= inPt.x ) && ( inPt.x <= edgeHighPt.x ) ) ) { return true; } // inPt: Point on contour !
  30409. // continue;
  30410. }
  30411. }
  30412. return inside;
  30413. }
  30414. var isClockWise = ShapeUtils.isClockWise;
  30415. var subPaths = this.subPaths;
  30416. if ( subPaths.length === 0 ) { return []; }
  30417. if ( noHoles === true ) { return toShapesNoHoles( subPaths ); }
  30418. var solid, tmpPath, tmpShape, shapes = [];
  30419. if ( subPaths.length === 1 ) {
  30420. tmpPath = subPaths[ 0 ];
  30421. tmpShape = new Shape();
  30422. tmpShape.curves = tmpPath.curves;
  30423. shapes.push( tmpShape );
  30424. return shapes;
  30425. }
  30426. var holesFirst = ! isClockWise( subPaths[ 0 ].getPoints() );
  30427. holesFirst = isCCW ? ! holesFirst : holesFirst;
  30428. // console.log("Holes first", holesFirst);
  30429. var betterShapeHoles = [];
  30430. var newShapes = [];
  30431. var newShapeHoles = [];
  30432. var mainIdx = 0;
  30433. var tmpPoints;
  30434. newShapes[ mainIdx ] = undefined;
  30435. newShapeHoles[ mainIdx ] = [];
  30436. for ( var i = 0, l = subPaths.length; i < l; i ++ ) {
  30437. tmpPath = subPaths[ i ];
  30438. tmpPoints = tmpPath.getPoints();
  30439. solid = isClockWise( tmpPoints );
  30440. solid = isCCW ? ! solid : solid;
  30441. if ( solid ) {
  30442. if ( ( ! holesFirst ) && ( newShapes[ mainIdx ] ) ) { mainIdx ++; }
  30443. newShapes[ mainIdx ] = { s: new Shape(), p: tmpPoints };
  30444. newShapes[ mainIdx ].s.curves = tmpPath.curves;
  30445. if ( holesFirst ) { mainIdx ++; }
  30446. newShapeHoles[ mainIdx ] = [];
  30447. //console.log('cw', i);
  30448. } else {
  30449. newShapeHoles[ mainIdx ].push( { h: tmpPath, p: tmpPoints[ 0 ] } );
  30450. //console.log('ccw', i);
  30451. }
  30452. }
  30453. // only Holes? -> probably all Shapes with wrong orientation
  30454. if ( ! newShapes[ 0 ] ) { return toShapesNoHoles( subPaths ); }
  30455. if ( newShapes.length > 1 ) {
  30456. var ambiguous = false;
  30457. var toChange = [];
  30458. for ( var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  30459. betterShapeHoles[ sIdx ] = [];
  30460. }
  30461. for ( var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  30462. var sho = newShapeHoles[ sIdx ];
  30463. for ( var hIdx = 0; hIdx < sho.length; hIdx ++ ) {
  30464. var ho = sho[ hIdx ];
  30465. var hole_unassigned = true;
  30466. for ( var s2Idx = 0; s2Idx < newShapes.length; s2Idx ++ ) {
  30467. if ( isPointInsidePolygon( ho.p, newShapes[ s2Idx ].p ) ) {
  30468. if ( sIdx !== s2Idx ) { toChange.push( { froms: sIdx, tos: s2Idx, hole: hIdx } ); }
  30469. if ( hole_unassigned ) {
  30470. hole_unassigned = false;
  30471. betterShapeHoles[ s2Idx ].push( ho );
  30472. } else {
  30473. ambiguous = true;
  30474. }
  30475. }
  30476. }
  30477. if ( hole_unassigned ) {
  30478. betterShapeHoles[ sIdx ].push( ho );
  30479. }
  30480. }
  30481. }
  30482. // console.log("ambiguous: ", ambiguous);
  30483. if ( toChange.length > 0 ) {
  30484. // console.log("to change: ", toChange);
  30485. if ( ! ambiguous ) { newShapeHoles = betterShapeHoles; }
  30486. }
  30487. }
  30488. var tmpHoles;
  30489. for ( var i = 0, il = newShapes.length; i < il; i ++ ) {
  30490. tmpShape = newShapes[ i ].s;
  30491. shapes.push( tmpShape );
  30492. tmpHoles = newShapeHoles[ i ];
  30493. for ( var j = 0, jl = tmpHoles.length; j < jl; j ++ ) {
  30494. tmpShape.holes.push( tmpHoles[ j ].h );
  30495. }
  30496. }
  30497. //console.log("shape", shapes);
  30498. return shapes;
  30499. }
  30500. } );
  30501. /**
  30502. * @author zz85 / http://www.lab4games.net/zz85/blog
  30503. * @author mrdoob / http://mrdoob.com/
  30504. */
  30505. function Font( data ) {
  30506. this.type = 'Font';
  30507. this.data = data;
  30508. }
  30509. Object.assign( Font.prototype, {
  30510. isFont: true,
  30511. generateShapes: function ( text, size ) {
  30512. if ( size === undefined ) { size = 100; }
  30513. var shapes = [];
  30514. var paths = createPaths( text, size, this.data );
  30515. for ( var p = 0, pl = paths.length; p < pl; p ++ ) {
  30516. Array.prototype.push.apply( shapes, paths[ p ].toShapes() );
  30517. }
  30518. return shapes;
  30519. }
  30520. } );
  30521. function createPaths( text, size, data ) {
  30522. var chars = Array.from ? Array.from( text ) : String( text ).split( '' ); // workaround for IE11, see #13988
  30523. var scale = size / data.resolution;
  30524. var line_height = ( data.boundingBox.yMax - data.boundingBox.yMin + data.underlineThickness ) * scale;
  30525. var paths = [];
  30526. var offsetX = 0, offsetY = 0;
  30527. for ( var i = 0; i < chars.length; i ++ ) {
  30528. var char = chars[ i ];
  30529. if ( char === '\n' ) {
  30530. offsetX = 0;
  30531. offsetY -= line_height;
  30532. } else {
  30533. var ret = createPath( char, scale, offsetX, offsetY, data );
  30534. offsetX += ret.offsetX;
  30535. paths.push( ret.path );
  30536. }
  30537. }
  30538. return paths;
  30539. }
  30540. function createPath( char, scale, offsetX, offsetY, data ) {
  30541. var glyph = data.glyphs[ char ] || data.glyphs[ '?' ];
  30542. if ( ! glyph ) {
  30543. console.error( 'THREE.Font: character "' + char + '" does not exists in font family ' + data.familyName + '.' );
  30544. return;
  30545. }
  30546. var path = new ShapePath();
  30547. var x, y, cpx, cpy, cpx1, cpy1, cpx2, cpy2;
  30548. if ( glyph.o ) {
  30549. var outline = glyph._cachedOutline || ( glyph._cachedOutline = glyph.o.split( ' ' ) );
  30550. for ( var i = 0, l = outline.length; i < l; ) {
  30551. var action = outline[ i ++ ];
  30552. switch ( action ) {
  30553. case 'm': // moveTo
  30554. x = outline[ i ++ ] * scale + offsetX;
  30555. y = outline[ i ++ ] * scale + offsetY;
  30556. path.moveTo( x, y );
  30557. break;
  30558. case 'l': // lineTo
  30559. x = outline[ i ++ ] * scale + offsetX;
  30560. y = outline[ i ++ ] * scale + offsetY;
  30561. path.lineTo( x, y );
  30562. break;
  30563. case 'q': // quadraticCurveTo
  30564. cpx = outline[ i ++ ] * scale + offsetX;
  30565. cpy = outline[ i ++ ] * scale + offsetY;
  30566. cpx1 = outline[ i ++ ] * scale + offsetX;
  30567. cpy1 = outline[ i ++ ] * scale + offsetY;
  30568. path.quadraticCurveTo( cpx1, cpy1, cpx, cpy );
  30569. break;
  30570. case 'b': // bezierCurveTo
  30571. cpx = outline[ i ++ ] * scale + offsetX;
  30572. cpy = outline[ i ++ ] * scale + offsetY;
  30573. cpx1 = outline[ i ++ ] * scale + offsetX;
  30574. cpy1 = outline[ i ++ ] * scale + offsetY;
  30575. cpx2 = outline[ i ++ ] * scale + offsetX;
  30576. cpy2 = outline[ i ++ ] * scale + offsetY;
  30577. path.bezierCurveTo( cpx1, cpy1, cpx2, cpy2, cpx, cpy );
  30578. break;
  30579. }
  30580. }
  30581. }
  30582. return { offsetX: glyph.ha * scale, path: path };
  30583. }
  30584. /**
  30585. * @author mrdoob / http://mrdoob.com/
  30586. */
  30587. function FontLoader( manager ) {
  30588. Loader.call( this, manager );
  30589. }
  30590. FontLoader.prototype = Object.assign( Object.create( Loader.prototype ), {
  30591. constructor: FontLoader,
  30592. load: function ( url, onLoad, onProgress, onError ) {
  30593. var scope = this;
  30594. var loader = new FileLoader( this.manager );
  30595. loader.setPath( this.path );
  30596. loader.load( url, function ( text ) {
  30597. var json;
  30598. try {
  30599. json = JSON.parse( text );
  30600. } catch ( e ) {
  30601. console.warn( 'THREE.FontLoader: typeface.js support is being deprecated. Use typeface.json instead.' );
  30602. json = JSON.parse( text.substring( 65, text.length - 2 ) );
  30603. }
  30604. var font = scope.parse( json );
  30605. if ( onLoad ) { onLoad( font ); }
  30606. }, onProgress, onError );
  30607. },
  30608. parse: function ( json ) {
  30609. return new Font( json );
  30610. }
  30611. } );
  30612. /**
  30613. * @author mrdoob / http://mrdoob.com/
  30614. */
  30615. var _context;
  30616. var AudioContext = {
  30617. getContext: function () {
  30618. if ( _context === undefined ) {
  30619. _context = new ( window.AudioContext || window.webkitAudioContext )();
  30620. }
  30621. return _context;
  30622. },
  30623. setContext: function ( value ) {
  30624. _context = value;
  30625. }
  30626. };
  30627. /**
  30628. * @author Reece Aaron Lecrivain / http://reecenotes.com/
  30629. */
  30630. function AudioLoader( manager ) {
  30631. Loader.call( this, manager );
  30632. }
  30633. AudioLoader.prototype = Object.assign( Object.create( Loader.prototype ), {
  30634. constructor: AudioLoader,
  30635. load: function ( url, onLoad, onProgress, onError ) {
  30636. var loader = new FileLoader( this.manager );
  30637. loader.setResponseType( 'arraybuffer' );
  30638. loader.setPath( this.path );
  30639. loader.load( url, function ( buffer ) {
  30640. // Create a copy of the buffer. The `decodeAudioData` method
  30641. // detaches the buffer when complete, preventing reuse.
  30642. var bufferCopy = buffer.slice( 0 );
  30643. var context = AudioContext.getContext();
  30644. context.decodeAudioData( bufferCopy, function ( audioBuffer ) {
  30645. onLoad( audioBuffer );
  30646. } );
  30647. }, onProgress, onError );
  30648. }
  30649. } );
  30650. /**
  30651. * @author bhouston / http://clara.io
  30652. * @author WestLangley / http://github.com/WestLangley
  30653. *
  30654. * Primary reference:
  30655. * https://graphics.stanford.edu/papers/envmap/envmap.pdf
  30656. *
  30657. * Secondary reference:
  30658. * https://www.ppsloan.org/publications/StupidSH36.pdf
  30659. */
  30660. // 3-band SH defined by 9 coefficients
  30661. function SphericalHarmonics3() {
  30662. this.coefficients = [];
  30663. for ( var i = 0; i < 9; i ++ ) {
  30664. this.coefficients.push( new Vector3() );
  30665. }
  30666. }
  30667. Object.assign( SphericalHarmonics3.prototype, {
  30668. isSphericalHarmonics3: true,
  30669. set: function ( coefficients ) {
  30670. for ( var i = 0; i < 9; i ++ ) {
  30671. this.coefficients[ i ].copy( coefficients[ i ] );
  30672. }
  30673. return this;
  30674. },
  30675. zero: function () {
  30676. for ( var i = 0; i < 9; i ++ ) {
  30677. this.coefficients[ i ].set( 0, 0, 0 );
  30678. }
  30679. return this;
  30680. },
  30681. // get the radiance in the direction of the normal
  30682. // target is a Vector3
  30683. getAt: function ( normal, target ) {
  30684. // normal is assumed to be unit length
  30685. var x = normal.x, y = normal.y, z = normal.z;
  30686. var coeff = this.coefficients;
  30687. // band 0
  30688. target.copy( coeff[ 0 ] ).multiplyScalar( 0.282095 );
  30689. // band 1
  30690. target.addScaledVector( coeff[ 1 ], 0.488603 * y );
  30691. target.addScaledVector( coeff[ 2 ], 0.488603 * z );
  30692. target.addScaledVector( coeff[ 3 ], 0.488603 * x );
  30693. // band 2
  30694. target.addScaledVector( coeff[ 4 ], 1.092548 * ( x * y ) );
  30695. target.addScaledVector( coeff[ 5 ], 1.092548 * ( y * z ) );
  30696. target.addScaledVector( coeff[ 6 ], 0.315392 * ( 3.0 * z * z - 1.0 ) );
  30697. target.addScaledVector( coeff[ 7 ], 1.092548 * ( x * z ) );
  30698. target.addScaledVector( coeff[ 8 ], 0.546274 * ( x * x - y * y ) );
  30699. return target;
  30700. },
  30701. // get the irradiance (radiance convolved with cosine lobe) in the direction of the normal
  30702. // target is a Vector3
  30703. // https://graphics.stanford.edu/papers/envmap/envmap.pdf
  30704. getIrradianceAt: function ( normal, target ) {
  30705. // normal is assumed to be unit length
  30706. var x = normal.x, y = normal.y, z = normal.z;
  30707. var coeff = this.coefficients;
  30708. // band 0
  30709. target.copy( coeff[ 0 ] ).multiplyScalar( 0.886227 ); // π * 0.282095
  30710. // band 1
  30711. target.addScaledVector( coeff[ 1 ], 2.0 * 0.511664 * y ); // ( 2 * π / 3 ) * 0.488603
  30712. target.addScaledVector( coeff[ 2 ], 2.0 * 0.511664 * z );
  30713. target.addScaledVector( coeff[ 3 ], 2.0 * 0.511664 * x );
  30714. // band 2
  30715. target.addScaledVector( coeff[ 4 ], 2.0 * 0.429043 * x * y ); // ( π / 4 ) * 1.092548
  30716. target.addScaledVector( coeff[ 5 ], 2.0 * 0.429043 * y * z );
  30717. target.addScaledVector( coeff[ 6 ], 0.743125 * z * z - 0.247708 ); // ( π / 4 ) * 0.315392 * 3
  30718. target.addScaledVector( coeff[ 7 ], 2.0 * 0.429043 * x * z );
  30719. target.addScaledVector( coeff[ 8 ], 0.429043 * ( x * x - y * y ) ); // ( π / 4 ) * 0.546274
  30720. return target;
  30721. },
  30722. add: function ( sh ) {
  30723. for ( var i = 0; i < 9; i ++ ) {
  30724. this.coefficients[ i ].add( sh.coefficients[ i ] );
  30725. }
  30726. return this;
  30727. },
  30728. addScaledSH: function ( sh, s ) {
  30729. for ( var i = 0; i < 9; i ++ ) {
  30730. this.coefficients[ i ].addScaledVector( sh.coefficients[ i ], s );
  30731. }
  30732. return this;
  30733. },
  30734. scale: function ( s ) {
  30735. for ( var i = 0; i < 9; i ++ ) {
  30736. this.coefficients[ i ].multiplyScalar( s );
  30737. }
  30738. return this;
  30739. },
  30740. lerp: function ( sh, alpha ) {
  30741. for ( var i = 0; i < 9; i ++ ) {
  30742. this.coefficients[ i ].lerp( sh.coefficients[ i ], alpha );
  30743. }
  30744. return this;
  30745. },
  30746. equals: function ( sh ) {
  30747. for ( var i = 0; i < 9; i ++ ) {
  30748. if ( ! this.coefficients[ i ].equals( sh.coefficients[ i ] ) ) {
  30749. return false;
  30750. }
  30751. }
  30752. return true;
  30753. },
  30754. copy: function ( sh ) {
  30755. return this.set( sh.coefficients );
  30756. },
  30757. clone: function () {
  30758. return new this.constructor().copy( this );
  30759. },
  30760. fromArray: function ( array, offset ) {
  30761. if ( offset === undefined ) { offset = 0; }
  30762. var coefficients = this.coefficients;
  30763. for ( var i = 0; i < 9; i ++ ) {
  30764. coefficients[ i ].fromArray( array, offset + ( i * 3 ) );
  30765. }
  30766. return this;
  30767. },
  30768. toArray: function ( array, offset ) {
  30769. if ( array === undefined ) { array = []; }
  30770. if ( offset === undefined ) { offset = 0; }
  30771. var coefficients = this.coefficients;
  30772. for ( var i = 0; i < 9; i ++ ) {
  30773. coefficients[ i ].toArray( array, offset + ( i * 3 ) );
  30774. }
  30775. return array;
  30776. }
  30777. } );
  30778. Object.assign( SphericalHarmonics3, {
  30779. // evaluate the basis functions
  30780. // shBasis is an Array[ 9 ]
  30781. getBasisAt: function ( normal, shBasis ) {
  30782. // normal is assumed to be unit length
  30783. var x = normal.x, y = normal.y, z = normal.z;
  30784. // band 0
  30785. shBasis[ 0 ] = 0.282095;
  30786. // band 1
  30787. shBasis[ 1 ] = 0.488603 * y;
  30788. shBasis[ 2 ] = 0.488603 * z;
  30789. shBasis[ 3 ] = 0.488603 * x;
  30790. // band 2
  30791. shBasis[ 4 ] = 1.092548 * x * y;
  30792. shBasis[ 5 ] = 1.092548 * y * z;
  30793. shBasis[ 6 ] = 0.315392 * ( 3 * z * z - 1 );
  30794. shBasis[ 7 ] = 1.092548 * x * z;
  30795. shBasis[ 8 ] = 0.546274 * ( x * x - y * y );
  30796. }
  30797. } );
  30798. /**
  30799. * @author WestLangley / http://github.com/WestLangley
  30800. *
  30801. * A LightProbe is a source of indirect-diffuse light
  30802. */
  30803. function LightProbe( sh, intensity ) {
  30804. Light.call( this, undefined, intensity );
  30805. this.sh = ( sh !== undefined ) ? sh : new SphericalHarmonics3();
  30806. }
  30807. LightProbe.prototype = Object.assign( Object.create( Light.prototype ), {
  30808. constructor: LightProbe,
  30809. isLightProbe: true,
  30810. copy: function ( source ) {
  30811. Light.prototype.copy.call( this, source );
  30812. this.sh.copy( source.sh );
  30813. this.intensity = source.intensity;
  30814. return this;
  30815. },
  30816. toJSON: function ( meta ) {
  30817. var data = Light.prototype.toJSON.call( this, meta );
  30818. // data.sh = this.sh.toArray(); // todo
  30819. return data;
  30820. }
  30821. } );
  30822. /**
  30823. * @author WestLangley / http://github.com/WestLangley
  30824. */
  30825. function HemisphereLightProbe( skyColor, groundColor, intensity ) {
  30826. LightProbe.call( this, undefined, intensity );
  30827. var color1 = new Color().set( skyColor );
  30828. var color2 = new Color().set( groundColor );
  30829. var sky = new Vector3( color1.r, color1.g, color1.b );
  30830. var ground = new Vector3( color2.r, color2.g, color2.b );
  30831. // without extra factor of PI in the shader, should = 1 / Math.sqrt( Math.PI );
  30832. var c0 = Math.sqrt( Math.PI );
  30833. var c1 = c0 * Math.sqrt( 0.75 );
  30834. this.sh.coefficients[ 0 ].copy( sky ).add( ground ).multiplyScalar( c0 );
  30835. this.sh.coefficients[ 1 ].copy( sky ).sub( ground ).multiplyScalar( c1 );
  30836. }
  30837. HemisphereLightProbe.prototype = Object.assign( Object.create( LightProbe.prototype ), {
  30838. constructor: HemisphereLightProbe,
  30839. isHemisphereLightProbe: true,
  30840. copy: function ( source ) { // modifying colors not currently supported
  30841. LightProbe.prototype.copy.call( this, source );
  30842. return this;
  30843. },
  30844. toJSON: function ( meta ) {
  30845. var data = LightProbe.prototype.toJSON.call( this, meta );
  30846. // data.sh = this.sh.toArray(); // todo
  30847. return data;
  30848. }
  30849. } );
  30850. /**
  30851. * @author WestLangley / http://github.com/WestLangley
  30852. */
  30853. function AmbientLightProbe( color, intensity ) {
  30854. LightProbe.call( this, undefined, intensity );
  30855. var color1 = new Color().set( color );
  30856. // without extra factor of PI in the shader, would be 2 / Math.sqrt( Math.PI );
  30857. this.sh.coefficients[ 0 ].set( color1.r, color1.g, color1.b ).multiplyScalar( 2 * Math.sqrt( Math.PI ) );
  30858. }
  30859. AmbientLightProbe.prototype = Object.assign( Object.create( LightProbe.prototype ), {
  30860. constructor: AmbientLightProbe,
  30861. isAmbientLightProbe: true,
  30862. copy: function ( source ) { // modifying color not currently supported
  30863. LightProbe.prototype.copy.call( this, source );
  30864. return this;
  30865. },
  30866. toJSON: function ( meta ) {
  30867. var data = LightProbe.prototype.toJSON.call( this, meta );
  30868. // data.sh = this.sh.toArray(); // todo
  30869. return data;
  30870. }
  30871. } );
  30872. var _eyeRight = new Matrix4();
  30873. var _eyeLeft = new Matrix4();
  30874. /**
  30875. * @author mrdoob / http://mrdoob.com/
  30876. */
  30877. function StereoCamera() {
  30878. this.type = 'StereoCamera';
  30879. this.aspect = 1;
  30880. this.eyeSep = 0.064;
  30881. this.cameraL = new PerspectiveCamera();
  30882. this.cameraL.layers.enable( 1 );
  30883. this.cameraL.matrixAutoUpdate = false;
  30884. this.cameraR = new PerspectiveCamera();
  30885. this.cameraR.layers.enable( 2 );
  30886. this.cameraR.matrixAutoUpdate = false;
  30887. this._cache = {
  30888. focus: null,
  30889. fov: null,
  30890. aspect: null,
  30891. near: null,
  30892. far: null,
  30893. zoom: null,
  30894. eyeSep: null
  30895. };
  30896. }
  30897. Object.assign( StereoCamera.prototype, {
  30898. update: function ( camera ) {
  30899. var cache = this._cache;
  30900. var needsUpdate = cache.focus !== camera.focus || cache.fov !== camera.fov ||
  30901. cache.aspect !== camera.aspect * this.aspect || cache.near !== camera.near ||
  30902. cache.far !== camera.far || cache.zoom !== camera.zoom || cache.eyeSep !== this.eyeSep;
  30903. if ( needsUpdate ) {
  30904. cache.focus = camera.focus;
  30905. cache.fov = camera.fov;
  30906. cache.aspect = camera.aspect * this.aspect;
  30907. cache.near = camera.near;
  30908. cache.far = camera.far;
  30909. cache.zoom = camera.zoom;
  30910. cache.eyeSep = this.eyeSep;
  30911. // Off-axis stereoscopic effect based on
  30912. // http://paulbourke.net/stereographics/stereorender/
  30913. var projectionMatrix = camera.projectionMatrix.clone();
  30914. var eyeSepHalf = cache.eyeSep / 2;
  30915. var eyeSepOnProjection = eyeSepHalf * cache.near / cache.focus;
  30916. var ymax = ( cache.near * Math.tan( MathUtils.DEG2RAD * cache.fov * 0.5 ) ) / cache.zoom;
  30917. var xmin, xmax;
  30918. // translate xOffset
  30919. _eyeLeft.elements[ 12 ] = - eyeSepHalf;
  30920. _eyeRight.elements[ 12 ] = eyeSepHalf;
  30921. // for left eye
  30922. xmin = - ymax * cache.aspect + eyeSepOnProjection;
  30923. xmax = ymax * cache.aspect + eyeSepOnProjection;
  30924. projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  30925. projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  30926. this.cameraL.projectionMatrix.copy( projectionMatrix );
  30927. // for right eye
  30928. xmin = - ymax * cache.aspect - eyeSepOnProjection;
  30929. xmax = ymax * cache.aspect - eyeSepOnProjection;
  30930. projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  30931. projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  30932. this.cameraR.projectionMatrix.copy( projectionMatrix );
  30933. }
  30934. this.cameraL.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeLeft );
  30935. this.cameraR.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeRight );
  30936. }
  30937. } );
  30938. /**
  30939. * @author alteredq / http://alteredqualia.com/
  30940. */
  30941. function Clock( autoStart ) {
  30942. this.autoStart = ( autoStart !== undefined ) ? autoStart : true;
  30943. this.startTime = 0;
  30944. this.oldTime = 0;
  30945. this.elapsedTime = 0;
  30946. this.running = false;
  30947. }
  30948. Object.assign( Clock.prototype, {
  30949. start: function () {
  30950. this.startTime = ( typeof performance === 'undefined' ? Date : performance ).now(); // see #10732
  30951. this.oldTime = this.startTime;
  30952. this.elapsedTime = 0;
  30953. this.running = true;
  30954. },
  30955. stop: function () {
  30956. this.getElapsedTime();
  30957. this.running = false;
  30958. this.autoStart = false;
  30959. },
  30960. getElapsedTime: function () {
  30961. this.getDelta();
  30962. return this.elapsedTime;
  30963. },
  30964. getDelta: function () {
  30965. var diff = 0;
  30966. if ( this.autoStart && ! this.running ) {
  30967. this.start();
  30968. return 0;
  30969. }
  30970. if ( this.running ) {
  30971. var newTime = ( typeof performance === 'undefined' ? Date : performance ).now();
  30972. diff = ( newTime - this.oldTime ) / 1000;
  30973. this.oldTime = newTime;
  30974. this.elapsedTime += diff;
  30975. }
  30976. return diff;
  30977. }
  30978. } );
  30979. /**
  30980. * @author mrdoob / http://mrdoob.com/
  30981. */
  30982. var _position$2 = new Vector3();
  30983. var _quaternion$3 = new Quaternion();
  30984. var _scale$1 = new Vector3();
  30985. var _orientation = new Vector3();
  30986. function AudioListener() {
  30987. Object3D.call( this );
  30988. this.type = 'AudioListener';
  30989. this.context = AudioContext.getContext();
  30990. this.gain = this.context.createGain();
  30991. this.gain.connect( this.context.destination );
  30992. this.filter = null;
  30993. this.timeDelta = 0;
  30994. // private
  30995. this._clock = new Clock();
  30996. }
  30997. AudioListener.prototype = Object.assign( Object.create( Object3D.prototype ), {
  30998. constructor: AudioListener,
  30999. getInput: function () {
  31000. return this.gain;
  31001. },
  31002. removeFilter: function ( ) {
  31003. if ( this.filter !== null ) {
  31004. this.gain.disconnect( this.filter );
  31005. this.filter.disconnect( this.context.destination );
  31006. this.gain.connect( this.context.destination );
  31007. this.filter = null;
  31008. }
  31009. return this;
  31010. },
  31011. getFilter: function () {
  31012. return this.filter;
  31013. },
  31014. setFilter: function ( value ) {
  31015. if ( this.filter !== null ) {
  31016. this.gain.disconnect( this.filter );
  31017. this.filter.disconnect( this.context.destination );
  31018. } else {
  31019. this.gain.disconnect( this.context.destination );
  31020. }
  31021. this.filter = value;
  31022. this.gain.connect( this.filter );
  31023. this.filter.connect( this.context.destination );
  31024. return this;
  31025. },
  31026. getMasterVolume: function () {
  31027. return this.gain.gain.value;
  31028. },
  31029. setMasterVolume: function ( value ) {
  31030. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  31031. return this;
  31032. },
  31033. updateMatrixWorld: function ( force ) {
  31034. Object3D.prototype.updateMatrixWorld.call( this, force );
  31035. var listener = this.context.listener;
  31036. var up = this.up;
  31037. this.timeDelta = this._clock.getDelta();
  31038. this.matrixWorld.decompose( _position$2, _quaternion$3, _scale$1 );
  31039. _orientation.set( 0, 0, - 1 ).applyQuaternion( _quaternion$3 );
  31040. if ( listener.positionX ) {
  31041. // code path for Chrome (see #14393)
  31042. var endTime = this.context.currentTime + this.timeDelta;
  31043. listener.positionX.linearRampToValueAtTime( _position$2.x, endTime );
  31044. listener.positionY.linearRampToValueAtTime( _position$2.y, endTime );
  31045. listener.positionZ.linearRampToValueAtTime( _position$2.z, endTime );
  31046. listener.forwardX.linearRampToValueAtTime( _orientation.x, endTime );
  31047. listener.forwardY.linearRampToValueAtTime( _orientation.y, endTime );
  31048. listener.forwardZ.linearRampToValueAtTime( _orientation.z, endTime );
  31049. listener.upX.linearRampToValueAtTime( up.x, endTime );
  31050. listener.upY.linearRampToValueAtTime( up.y, endTime );
  31051. listener.upZ.linearRampToValueAtTime( up.z, endTime );
  31052. } else {
  31053. listener.setPosition( _position$2.x, _position$2.y, _position$2.z );
  31054. listener.setOrientation( _orientation.x, _orientation.y, _orientation.z, up.x, up.y, up.z );
  31055. }
  31056. }
  31057. } );
  31058. /**
  31059. * @author mrdoob / http://mrdoob.com/
  31060. * @author Reece Aaron Lecrivain / http://reecenotes.com/
  31061. */
  31062. function Audio( listener ) {
  31063. Object3D.call( this );
  31064. this.type = 'Audio';
  31065. this.listener = listener;
  31066. this.context = listener.context;
  31067. this.gain = this.context.createGain();
  31068. this.gain.connect( listener.getInput() );
  31069. this.autoplay = false;
  31070. this.buffer = null;
  31071. this.detune = 0;
  31072. this.loop = false;
  31073. this.loopStart = 0;
  31074. this.loopEnd = 0;
  31075. this.offset = 0;
  31076. this.duration = undefined;
  31077. this.playbackRate = 1;
  31078. this.isPlaying = false;
  31079. this.hasPlaybackControl = true;
  31080. this.sourceType = 'empty';
  31081. this._startedAt = 0;
  31082. this._pausedAt = 0;
  31083. this.filters = [];
  31084. }
  31085. Audio.prototype = Object.assign( Object.create( Object3D.prototype ), {
  31086. constructor: Audio,
  31087. getOutput: function () {
  31088. return this.gain;
  31089. },
  31090. setNodeSource: function ( audioNode ) {
  31091. this.hasPlaybackControl = false;
  31092. this.sourceType = 'audioNode';
  31093. this.source = audioNode;
  31094. this.connect();
  31095. return this;
  31096. },
  31097. setMediaElementSource: function ( mediaElement ) {
  31098. this.hasPlaybackControl = false;
  31099. this.sourceType = 'mediaNode';
  31100. this.source = this.context.createMediaElementSource( mediaElement );
  31101. this.connect();
  31102. return this;
  31103. },
  31104. setMediaStreamSource: function ( mediaStream ) {
  31105. this.hasPlaybackControl = false;
  31106. this.sourceType = 'mediaStreamNode';
  31107. this.source = this.context.createMediaStreamSource( mediaStream );
  31108. this.connect();
  31109. return this;
  31110. },
  31111. setBuffer: function ( audioBuffer ) {
  31112. this.buffer = audioBuffer;
  31113. this.sourceType = 'buffer';
  31114. if ( this.autoplay ) { this.play(); }
  31115. return this;
  31116. },
  31117. play: function ( delay ) {
  31118. if ( delay === undefined ) { delay = 0; }
  31119. if ( this.isPlaying === true ) {
  31120. console.warn( 'THREE.Audio: Audio is already playing.' );
  31121. return;
  31122. }
  31123. if ( this.hasPlaybackControl === false ) {
  31124. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  31125. return;
  31126. }
  31127. this._startedAt = this.context.currentTime + delay;
  31128. var source = this.context.createBufferSource();
  31129. source.buffer = this.buffer;
  31130. source.loop = this.loop;
  31131. source.loopStart = this.loopStart;
  31132. source.loopEnd = this.loopEnd;
  31133. source.onended = this.onEnded.bind( this );
  31134. source.start( this._startedAt, this._pausedAt + this.offset, this.duration );
  31135. this.isPlaying = true;
  31136. this.source = source;
  31137. this.setDetune( this.detune );
  31138. this.setPlaybackRate( this.playbackRate );
  31139. return this.connect();
  31140. },
  31141. pause: function () {
  31142. if ( this.hasPlaybackControl === false ) {
  31143. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  31144. return;
  31145. }
  31146. if ( this.isPlaying === true ) {
  31147. this._pausedAt += Math.max( this.context.currentTime - this._startedAt, 0 ) * this.playbackRate;
  31148. this.source.stop();
  31149. this.source.onended = null;
  31150. this.isPlaying = false;
  31151. }
  31152. return this;
  31153. },
  31154. stop: function () {
  31155. if ( this.hasPlaybackControl === false ) {
  31156. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  31157. return;
  31158. }
  31159. this._pausedAt = 0;
  31160. this.source.stop();
  31161. this.source.onended = null;
  31162. this.isPlaying = false;
  31163. return this;
  31164. },
  31165. connect: function () {
  31166. if ( this.filters.length > 0 ) {
  31167. this.source.connect( this.filters[ 0 ] );
  31168. for ( var i = 1, l = this.filters.length; i < l; i ++ ) {
  31169. this.filters[ i - 1 ].connect( this.filters[ i ] );
  31170. }
  31171. this.filters[ this.filters.length - 1 ].connect( this.getOutput() );
  31172. } else {
  31173. this.source.connect( this.getOutput() );
  31174. }
  31175. return this;
  31176. },
  31177. disconnect: function () {
  31178. if ( this.filters.length > 0 ) {
  31179. this.source.disconnect( this.filters[ 0 ] );
  31180. for ( var i = 1, l = this.filters.length; i < l; i ++ ) {
  31181. this.filters[ i - 1 ].disconnect( this.filters[ i ] );
  31182. }
  31183. this.filters[ this.filters.length - 1 ].disconnect( this.getOutput() );
  31184. } else {
  31185. this.source.disconnect( this.getOutput() );
  31186. }
  31187. return this;
  31188. },
  31189. getFilters: function () {
  31190. return this.filters;
  31191. },
  31192. setFilters: function ( value ) {
  31193. if ( ! value ) { value = []; }
  31194. if ( this.isPlaying === true ) {
  31195. this.disconnect();
  31196. this.filters = value;
  31197. this.connect();
  31198. } else {
  31199. this.filters = value;
  31200. }
  31201. return this;
  31202. },
  31203. setDetune: function ( value ) {
  31204. this.detune = value;
  31205. if ( this.source.detune === undefined ) { return; } // only set detune when available
  31206. if ( this.isPlaying === true ) {
  31207. this.source.detune.setTargetAtTime( this.detune, this.context.currentTime, 0.01 );
  31208. }
  31209. return this;
  31210. },
  31211. getDetune: function () {
  31212. return this.detune;
  31213. },
  31214. getFilter: function () {
  31215. return this.getFilters()[ 0 ];
  31216. },
  31217. setFilter: function ( filter ) {
  31218. return this.setFilters( filter ? [ filter ] : [] );
  31219. },
  31220. setPlaybackRate: function ( value ) {
  31221. if ( this.hasPlaybackControl === false ) {
  31222. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  31223. return;
  31224. }
  31225. this.playbackRate = value;
  31226. if ( this.isPlaying === true ) {
  31227. this.source.playbackRate.setTargetAtTime( this.playbackRate, this.context.currentTime, 0.01 );
  31228. }
  31229. return this;
  31230. },
  31231. getPlaybackRate: function () {
  31232. return this.playbackRate;
  31233. },
  31234. onEnded: function () {
  31235. this.isPlaying = false;
  31236. },
  31237. getLoop: function () {
  31238. if ( this.hasPlaybackControl === false ) {
  31239. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  31240. return false;
  31241. }
  31242. return this.loop;
  31243. },
  31244. setLoop: function ( value ) {
  31245. if ( this.hasPlaybackControl === false ) {
  31246. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  31247. return;
  31248. }
  31249. this.loop = value;
  31250. if ( this.isPlaying === true ) {
  31251. this.source.loop = this.loop;
  31252. }
  31253. return this;
  31254. },
  31255. setLoopStart: function ( value ) {
  31256. this.loopStart = value;
  31257. return this;
  31258. },
  31259. setLoopEnd: function ( value ) {
  31260. this.loopEnd = value;
  31261. return this;
  31262. },
  31263. getVolume: function () {
  31264. return this.gain.gain.value;
  31265. },
  31266. setVolume: function ( value ) {
  31267. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  31268. return this;
  31269. }
  31270. } );
  31271. /**
  31272. * @author mrdoob / http://mrdoob.com/
  31273. */
  31274. var _position$3 = new Vector3();
  31275. var _quaternion$4 = new Quaternion();
  31276. var _scale$2 = new Vector3();
  31277. var _orientation$1 = new Vector3();
  31278. function PositionalAudio( listener ) {
  31279. Audio.call( this, listener );
  31280. this.panner = this.context.createPanner();
  31281. this.panner.panningModel = 'HRTF';
  31282. this.panner.connect( this.gain );
  31283. }
  31284. PositionalAudio.prototype = Object.assign( Object.create( Audio.prototype ), {
  31285. constructor: PositionalAudio,
  31286. getOutput: function () {
  31287. return this.panner;
  31288. },
  31289. getRefDistance: function () {
  31290. return this.panner.refDistance;
  31291. },
  31292. setRefDistance: function ( value ) {
  31293. this.panner.refDistance = value;
  31294. return this;
  31295. },
  31296. getRolloffFactor: function () {
  31297. return this.panner.rolloffFactor;
  31298. },
  31299. setRolloffFactor: function ( value ) {
  31300. this.panner.rolloffFactor = value;
  31301. return this;
  31302. },
  31303. getDistanceModel: function () {
  31304. return this.panner.distanceModel;
  31305. },
  31306. setDistanceModel: function ( value ) {
  31307. this.panner.distanceModel = value;
  31308. return this;
  31309. },
  31310. getMaxDistance: function () {
  31311. return this.panner.maxDistance;
  31312. },
  31313. setMaxDistance: function ( value ) {
  31314. this.panner.maxDistance = value;
  31315. return this;
  31316. },
  31317. setDirectionalCone: function ( coneInnerAngle, coneOuterAngle, coneOuterGain ) {
  31318. this.panner.coneInnerAngle = coneInnerAngle;
  31319. this.panner.coneOuterAngle = coneOuterAngle;
  31320. this.panner.coneOuterGain = coneOuterGain;
  31321. return this;
  31322. },
  31323. updateMatrixWorld: function ( force ) {
  31324. Object3D.prototype.updateMatrixWorld.call( this, force );
  31325. if ( this.hasPlaybackControl === true && this.isPlaying === false ) { return; }
  31326. this.matrixWorld.decompose( _position$3, _quaternion$4, _scale$2 );
  31327. _orientation$1.set( 0, 0, 1 ).applyQuaternion( _quaternion$4 );
  31328. var panner = this.panner;
  31329. if ( panner.positionX ) {
  31330. // code path for Chrome and Firefox (see #14393)
  31331. var endTime = this.context.currentTime + this.listener.timeDelta;
  31332. panner.positionX.linearRampToValueAtTime( _position$3.x, endTime );
  31333. panner.positionY.linearRampToValueAtTime( _position$3.y, endTime );
  31334. panner.positionZ.linearRampToValueAtTime( _position$3.z, endTime );
  31335. panner.orientationX.linearRampToValueAtTime( _orientation$1.x, endTime );
  31336. panner.orientationY.linearRampToValueAtTime( _orientation$1.y, endTime );
  31337. panner.orientationZ.linearRampToValueAtTime( _orientation$1.z, endTime );
  31338. } else {
  31339. panner.setPosition( _position$3.x, _position$3.y, _position$3.z );
  31340. panner.setOrientation( _orientation$1.x, _orientation$1.y, _orientation$1.z );
  31341. }
  31342. }
  31343. } );
  31344. /**
  31345. * @author mrdoob / http://mrdoob.com/
  31346. */
  31347. function AudioAnalyser( audio, fftSize ) {
  31348. this.analyser = audio.context.createAnalyser();
  31349. this.analyser.fftSize = fftSize !== undefined ? fftSize : 2048;
  31350. this.data = new Uint8Array( this.analyser.frequencyBinCount );
  31351. audio.getOutput().connect( this.analyser );
  31352. }
  31353. Object.assign( AudioAnalyser.prototype, {
  31354. getFrequencyData: function () {
  31355. this.analyser.getByteFrequencyData( this.data );
  31356. return this.data;
  31357. },
  31358. getAverageFrequency: function () {
  31359. var value = 0, data = this.getFrequencyData();
  31360. for ( var i = 0; i < data.length; i ++ ) {
  31361. value += data[ i ];
  31362. }
  31363. return value / data.length;
  31364. }
  31365. } );
  31366. /**
  31367. *
  31368. * Buffered scene graph property that allows weighted accumulation.
  31369. *
  31370. *
  31371. * @author Ben Houston / http://clara.io/
  31372. * @author David Sarno / http://lighthaus.us/
  31373. * @author tschw
  31374. */
  31375. function PropertyMixer( binding, typeName, valueSize ) {
  31376. this.binding = binding;
  31377. this.valueSize = valueSize;
  31378. var bufferType = Float64Array,
  31379. mixFunction;
  31380. switch ( typeName ) {
  31381. case 'quaternion':
  31382. mixFunction = this._slerp;
  31383. break;
  31384. case 'string':
  31385. case 'bool':
  31386. bufferType = Array;
  31387. mixFunction = this._select;
  31388. break;
  31389. default:
  31390. mixFunction = this._lerp;
  31391. }
  31392. this.buffer = new bufferType( valueSize * 4 );
  31393. // layout: [ incoming | accu0 | accu1 | orig ]
  31394. //
  31395. // interpolators can use .buffer as their .result
  31396. // the data then goes to 'incoming'
  31397. //
  31398. // 'accu0' and 'accu1' are used frame-interleaved for
  31399. // the cumulative result and are compared to detect
  31400. // changes
  31401. //
  31402. // 'orig' stores the original state of the property
  31403. this._mixBufferRegion = mixFunction;
  31404. this.cumulativeWeight = 0;
  31405. this.useCount = 0;
  31406. this.referenceCount = 0;
  31407. }
  31408. Object.assign( PropertyMixer.prototype, {
  31409. // accumulate data in the 'incoming' region into 'accu<i>'
  31410. accumulate: function ( accuIndex, weight ) {
  31411. // note: happily accumulating nothing when weight = 0, the caller knows
  31412. // the weight and shouldn't have made the call in the first place
  31413. var buffer = this.buffer,
  31414. stride = this.valueSize,
  31415. offset = accuIndex * stride + stride,
  31416. currentWeight = this.cumulativeWeight;
  31417. if ( currentWeight === 0 ) {
  31418. // accuN := incoming * weight
  31419. for ( var i = 0; i !== stride; ++ i ) {
  31420. buffer[ offset + i ] = buffer[ i ];
  31421. }
  31422. currentWeight = weight;
  31423. } else {
  31424. // accuN := accuN + incoming * weight
  31425. currentWeight += weight;
  31426. var mix = weight / currentWeight;
  31427. this._mixBufferRegion( buffer, offset, 0, mix, stride );
  31428. }
  31429. this.cumulativeWeight = currentWeight;
  31430. },
  31431. // apply the state of 'accu<i>' to the binding when accus differ
  31432. apply: function ( accuIndex ) {
  31433. var stride = this.valueSize,
  31434. buffer = this.buffer,
  31435. offset = accuIndex * stride + stride,
  31436. weight = this.cumulativeWeight,
  31437. binding = this.binding;
  31438. this.cumulativeWeight = 0;
  31439. if ( weight < 1 ) {
  31440. // accuN := accuN + original * ( 1 - cumulativeWeight )
  31441. var originalValueOffset = stride * 3;
  31442. this._mixBufferRegion(
  31443. buffer, offset, originalValueOffset, 1 - weight, stride );
  31444. }
  31445. for ( var i = stride, e = stride + stride; i !== e; ++ i ) {
  31446. if ( buffer[ i ] !== buffer[ i + stride ] ) {
  31447. // value has changed -> update scene graph
  31448. binding.setValue( buffer, offset );
  31449. break;
  31450. }
  31451. }
  31452. },
  31453. // remember the state of the bound property and copy it to both accus
  31454. saveOriginalState: function () {
  31455. var binding = this.binding;
  31456. var buffer = this.buffer,
  31457. stride = this.valueSize,
  31458. originalValueOffset = stride * 3;
  31459. binding.getValue( buffer, originalValueOffset );
  31460. // accu[0..1] := orig -- initially detect changes against the original
  31461. for ( var i = stride, e = originalValueOffset; i !== e; ++ i ) {
  31462. buffer[ i ] = buffer[ originalValueOffset + ( i % stride ) ];
  31463. }
  31464. this.cumulativeWeight = 0;
  31465. },
  31466. // apply the state previously taken via 'saveOriginalState' to the binding
  31467. restoreOriginalState: function () {
  31468. var originalValueOffset = this.valueSize * 3;
  31469. this.binding.setValue( this.buffer, originalValueOffset );
  31470. },
  31471. // mix functions
  31472. _select: function ( buffer, dstOffset, srcOffset, t, stride ) {
  31473. if ( t >= 0.5 ) {
  31474. for ( var i = 0; i !== stride; ++ i ) {
  31475. buffer[ dstOffset + i ] = buffer[ srcOffset + i ];
  31476. }
  31477. }
  31478. },
  31479. _slerp: function ( buffer, dstOffset, srcOffset, t ) {
  31480. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t );
  31481. },
  31482. _lerp: function ( buffer, dstOffset, srcOffset, t, stride ) {
  31483. var s = 1 - t;
  31484. for ( var i = 0; i !== stride; ++ i ) {
  31485. var j = dstOffset + i;
  31486. buffer[ j ] = buffer[ j ] * s + buffer[ srcOffset + i ] * t;
  31487. }
  31488. }
  31489. } );
  31490. /**
  31491. *
  31492. * A reference to a real property in the scene graph.
  31493. *
  31494. *
  31495. * @author Ben Houston / http://clara.io/
  31496. * @author David Sarno / http://lighthaus.us/
  31497. * @author tschw
  31498. */
  31499. // Characters [].:/ are reserved for track binding syntax.
  31500. var _RESERVED_CHARS_RE = '\\[\\]\\.:\\/';
  31501. var _reservedRe = new RegExp( '[' + _RESERVED_CHARS_RE + ']', 'g' );
  31502. // Attempts to allow node names from any language. ES5's `\w` regexp matches
  31503. // only latin characters, and the unicode \p{L} is not yet supported. So
  31504. // instead, we exclude reserved characters and match everything else.
  31505. var _wordChar = '[^' + _RESERVED_CHARS_RE + ']';
  31506. var _wordCharOrDot = '[^' + _RESERVED_CHARS_RE.replace( '\\.', '' ) + ']';
  31507. // Parent directories, delimited by '/' or ':'. Currently unused, but must
  31508. // be matched to parse the rest of the track name.
  31509. var _directoryRe = /((?:WC+[\/:])*)/.source.replace( 'WC', _wordChar );
  31510. // Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'.
  31511. var _nodeRe = /(WCOD+)?/.source.replace( 'WCOD', _wordCharOrDot );
  31512. // Object on target node, and accessor. May not contain reserved
  31513. // characters. Accessor may contain any character except closing bracket.
  31514. var _objectRe = /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace( 'WC', _wordChar );
  31515. // Property and accessor. May not contain reserved characters. Accessor may
  31516. // contain any non-bracket characters.
  31517. var _propertyRe = /\.(WC+)(?:\[(.+)\])?/.source.replace( 'WC', _wordChar );
  31518. var _trackRe = new RegExp( ''
  31519. + '^'
  31520. + _directoryRe
  31521. + _nodeRe
  31522. + _objectRe
  31523. + _propertyRe
  31524. + '$'
  31525. );
  31526. var _supportedObjectNames = [ 'material', 'materials', 'bones' ];
  31527. function Composite( targetGroup, path, optionalParsedPath ) {
  31528. var parsedPath = optionalParsedPath || PropertyBinding.parseTrackName( path );
  31529. this._targetGroup = targetGroup;
  31530. this._bindings = targetGroup.subscribe_( path, parsedPath );
  31531. }
  31532. Object.assign( Composite.prototype, {
  31533. getValue: function ( array, offset ) {
  31534. this.bind(); // bind all binding
  31535. var firstValidIndex = this._targetGroup.nCachedObjects_,
  31536. binding = this._bindings[ firstValidIndex ];
  31537. // and only call .getValue on the first
  31538. if ( binding !== undefined ) { binding.getValue( array, offset ); }
  31539. },
  31540. setValue: function ( array, offset ) {
  31541. var bindings = this._bindings;
  31542. for ( var i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  31543. bindings[ i ].setValue( array, offset );
  31544. }
  31545. },
  31546. bind: function () {
  31547. var bindings = this._bindings;
  31548. for ( var i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  31549. bindings[ i ].bind();
  31550. }
  31551. },
  31552. unbind: function () {
  31553. var bindings = this._bindings;
  31554. for ( var i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  31555. bindings[ i ].unbind();
  31556. }
  31557. }
  31558. } );
  31559. function PropertyBinding( rootNode, path, parsedPath ) {
  31560. this.path = path;
  31561. this.parsedPath = parsedPath || PropertyBinding.parseTrackName( path );
  31562. this.node = PropertyBinding.findNode( rootNode, this.parsedPath.nodeName ) || rootNode;
  31563. this.rootNode = rootNode;
  31564. }
  31565. Object.assign( PropertyBinding, {
  31566. Composite: Composite,
  31567. create: function ( root, path, parsedPath ) {
  31568. if ( ! ( root && root.isAnimationObjectGroup ) ) {
  31569. return new PropertyBinding( root, path, parsedPath );
  31570. } else {
  31571. return new PropertyBinding.Composite( root, path, parsedPath );
  31572. }
  31573. },
  31574. /**
  31575. * Replaces spaces with underscores and removes unsupported characters from
  31576. * node names, to ensure compatibility with parseTrackName().
  31577. *
  31578. * @param {string} name Node name to be sanitized.
  31579. * @return {string}
  31580. */
  31581. sanitizeNodeName: function ( name ) {
  31582. return name.replace( /\s/g, '_' ).replace( _reservedRe, '' );
  31583. },
  31584. parseTrackName: function ( trackName ) {
  31585. var matches = _trackRe.exec( trackName );
  31586. if ( ! matches ) {
  31587. throw new Error( 'PropertyBinding: Cannot parse trackName: ' + trackName );
  31588. }
  31589. var results = {
  31590. // directoryName: matches[ 1 ], // (tschw) currently unused
  31591. nodeName: matches[ 2 ],
  31592. objectName: matches[ 3 ],
  31593. objectIndex: matches[ 4 ],
  31594. propertyName: matches[ 5 ], // required
  31595. propertyIndex: matches[ 6 ]
  31596. };
  31597. var lastDot = results.nodeName && results.nodeName.lastIndexOf( '.' );
  31598. if ( lastDot !== undefined && lastDot !== - 1 ) {
  31599. var objectName = results.nodeName.substring( lastDot + 1 );
  31600. // Object names must be checked against a whitelist. Otherwise, there
  31601. // is no way to parse 'foo.bar.baz': 'baz' must be a property, but
  31602. // 'bar' could be the objectName, or part of a nodeName (which can
  31603. // include '.' characters).
  31604. if ( _supportedObjectNames.indexOf( objectName ) !== - 1 ) {
  31605. results.nodeName = results.nodeName.substring( 0, lastDot );
  31606. results.objectName = objectName;
  31607. }
  31608. }
  31609. if ( results.propertyName === null || results.propertyName.length === 0 ) {
  31610. throw new Error( 'PropertyBinding: can not parse propertyName from trackName: ' + trackName );
  31611. }
  31612. return results;
  31613. },
  31614. findNode: function ( root, nodeName ) {
  31615. if ( ! nodeName || nodeName === "" || nodeName === "." || nodeName === - 1 || nodeName === root.name || nodeName === root.uuid ) {
  31616. return root;
  31617. }
  31618. // search into skeleton bones.
  31619. if ( root.skeleton ) {
  31620. var bone = root.skeleton.getBoneByName( nodeName );
  31621. if ( bone !== undefined ) {
  31622. return bone;
  31623. }
  31624. }
  31625. // search into node subtree.
  31626. if ( root.children ) {
  31627. var searchNodeSubtree = function ( children ) {
  31628. for ( var i = 0; i < children.length; i ++ ) {
  31629. var childNode = children[ i ];
  31630. if ( childNode.name === nodeName || childNode.uuid === nodeName ) {
  31631. return childNode;
  31632. }
  31633. var result = searchNodeSubtree( childNode.children );
  31634. if ( result ) { return result; }
  31635. }
  31636. return null;
  31637. };
  31638. var subTreeNode = searchNodeSubtree( root.children );
  31639. if ( subTreeNode ) {
  31640. return subTreeNode;
  31641. }
  31642. }
  31643. return null;
  31644. }
  31645. } );
  31646. Object.assign( PropertyBinding.prototype, { // prototype, continued
  31647. // these are used to "bind" a nonexistent property
  31648. _getValue_unavailable: function () {},
  31649. _setValue_unavailable: function () {},
  31650. BindingType: {
  31651. Direct: 0,
  31652. EntireArray: 1,
  31653. ArrayElement: 2,
  31654. HasFromToArray: 3
  31655. },
  31656. Versioning: {
  31657. None: 0,
  31658. NeedsUpdate: 1,
  31659. MatrixWorldNeedsUpdate: 2
  31660. },
  31661. GetterByBindingType: [
  31662. function getValue_direct( buffer, offset ) {
  31663. buffer[ offset ] = this.node[ this.propertyName ];
  31664. },
  31665. function getValue_array( buffer, offset ) {
  31666. var source = this.resolvedProperty;
  31667. for ( var i = 0, n = source.length; i !== n; ++ i ) {
  31668. buffer[ offset ++ ] = source[ i ];
  31669. }
  31670. },
  31671. function getValue_arrayElement( buffer, offset ) {
  31672. buffer[ offset ] = this.resolvedProperty[ this.propertyIndex ];
  31673. },
  31674. function getValue_toArray( buffer, offset ) {
  31675. this.resolvedProperty.toArray( buffer, offset );
  31676. }
  31677. ],
  31678. SetterByBindingTypeAndVersioning: [
  31679. [
  31680. // Direct
  31681. function setValue_direct( buffer, offset ) {
  31682. this.targetObject[ this.propertyName ] = buffer[ offset ];
  31683. },
  31684. function setValue_direct_setNeedsUpdate( buffer, offset ) {
  31685. this.targetObject[ this.propertyName ] = buffer[ offset ];
  31686. this.targetObject.needsUpdate = true;
  31687. },
  31688. function setValue_direct_setMatrixWorldNeedsUpdate( buffer, offset ) {
  31689. this.targetObject[ this.propertyName ] = buffer[ offset ];
  31690. this.targetObject.matrixWorldNeedsUpdate = true;
  31691. }
  31692. ], [
  31693. // EntireArray
  31694. function setValue_array( buffer, offset ) {
  31695. var dest = this.resolvedProperty;
  31696. for ( var i = 0, n = dest.length; i !== n; ++ i ) {
  31697. dest[ i ] = buffer[ offset ++ ];
  31698. }
  31699. },
  31700. function setValue_array_setNeedsUpdate( buffer, offset ) {
  31701. var dest = this.resolvedProperty;
  31702. for ( var i = 0, n = dest.length; i !== n; ++ i ) {
  31703. dest[ i ] = buffer[ offset ++ ];
  31704. }
  31705. this.targetObject.needsUpdate = true;
  31706. },
  31707. function setValue_array_setMatrixWorldNeedsUpdate( buffer, offset ) {
  31708. var dest = this.resolvedProperty;
  31709. for ( var i = 0, n = dest.length; i !== n; ++ i ) {
  31710. dest[ i ] = buffer[ offset ++ ];
  31711. }
  31712. this.targetObject.matrixWorldNeedsUpdate = true;
  31713. }
  31714. ], [
  31715. // ArrayElement
  31716. function setValue_arrayElement( buffer, offset ) {
  31717. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  31718. },
  31719. function setValue_arrayElement_setNeedsUpdate( buffer, offset ) {
  31720. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  31721. this.targetObject.needsUpdate = true;
  31722. },
  31723. function setValue_arrayElement_setMatrixWorldNeedsUpdate( buffer, offset ) {
  31724. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  31725. this.targetObject.matrixWorldNeedsUpdate = true;
  31726. }
  31727. ], [
  31728. // HasToFromArray
  31729. function setValue_fromArray( buffer, offset ) {
  31730. this.resolvedProperty.fromArray( buffer, offset );
  31731. },
  31732. function setValue_fromArray_setNeedsUpdate( buffer, offset ) {
  31733. this.resolvedProperty.fromArray( buffer, offset );
  31734. this.targetObject.needsUpdate = true;
  31735. },
  31736. function setValue_fromArray_setMatrixWorldNeedsUpdate( buffer, offset ) {
  31737. this.resolvedProperty.fromArray( buffer, offset );
  31738. this.targetObject.matrixWorldNeedsUpdate = true;
  31739. }
  31740. ]
  31741. ],
  31742. getValue: function getValue_unbound( targetArray, offset ) {
  31743. this.bind();
  31744. this.getValue( targetArray, offset );
  31745. // Note: This class uses a State pattern on a per-method basis:
  31746. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  31747. // prototype version of these methods with one that represents
  31748. // the bound state. When the property is not found, the methods
  31749. // become no-ops.
  31750. },
  31751. setValue: function getValue_unbound( sourceArray, offset ) {
  31752. this.bind();
  31753. this.setValue( sourceArray, offset );
  31754. },
  31755. // create getter / setter pair for a property in the scene graph
  31756. bind: function () {
  31757. var targetObject = this.node,
  31758. parsedPath = this.parsedPath,
  31759. objectName = parsedPath.objectName,
  31760. propertyName = parsedPath.propertyName,
  31761. propertyIndex = parsedPath.propertyIndex;
  31762. if ( ! targetObject ) {
  31763. targetObject = PropertyBinding.findNode( this.rootNode, parsedPath.nodeName ) || this.rootNode;
  31764. this.node = targetObject;
  31765. }
  31766. // set fail state so we can just 'return' on error
  31767. this.getValue = this._getValue_unavailable;
  31768. this.setValue = this._setValue_unavailable;
  31769. // ensure there is a value node
  31770. if ( ! targetObject ) {
  31771. console.error( 'THREE.PropertyBinding: Trying to update node for track: ' + this.path + ' but it wasn\'t found.' );
  31772. return;
  31773. }
  31774. if ( objectName ) {
  31775. var objectIndex = parsedPath.objectIndex;
  31776. // special cases were we need to reach deeper into the hierarchy to get the face materials....
  31777. switch ( objectName ) {
  31778. case 'materials':
  31779. if ( ! targetObject.material ) {
  31780. console.error( 'THREE.PropertyBinding: Can not bind to material as node does not have a material.', this );
  31781. return;
  31782. }
  31783. if ( ! targetObject.material.materials ) {
  31784. console.error( 'THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.', this );
  31785. return;
  31786. }
  31787. targetObject = targetObject.material.materials;
  31788. break;
  31789. case 'bones':
  31790. if ( ! targetObject.skeleton ) {
  31791. console.error( 'THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.', this );
  31792. return;
  31793. }
  31794. // potential future optimization: skip this if propertyIndex is already an integer
  31795. // and convert the integer string to a true integer.
  31796. targetObject = targetObject.skeleton.bones;
  31797. // support resolving morphTarget names into indices.
  31798. for ( var i = 0; i < targetObject.length; i ++ ) {
  31799. if ( targetObject[ i ].name === objectIndex ) {
  31800. objectIndex = i;
  31801. break;
  31802. }
  31803. }
  31804. break;
  31805. default:
  31806. if ( targetObject[ objectName ] === undefined ) {
  31807. console.error( 'THREE.PropertyBinding: Can not bind to objectName of node undefined.', this );
  31808. return;
  31809. }
  31810. targetObject = targetObject[ objectName ];
  31811. }
  31812. if ( objectIndex !== undefined ) {
  31813. if ( targetObject[ objectIndex ] === undefined ) {
  31814. console.error( 'THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject );
  31815. return;
  31816. }
  31817. targetObject = targetObject[ objectIndex ];
  31818. }
  31819. }
  31820. // resolve property
  31821. var nodeProperty = targetObject[ propertyName ];
  31822. if ( nodeProperty === undefined ) {
  31823. var nodeName = parsedPath.nodeName;
  31824. console.error( 'THREE.PropertyBinding: Trying to update property for track: ' + nodeName +
  31825. '.' + propertyName + ' but it wasn\'t found.', targetObject );
  31826. return;
  31827. }
  31828. // determine versioning scheme
  31829. var versioning = this.Versioning.None;
  31830. this.targetObject = targetObject;
  31831. if ( targetObject.needsUpdate !== undefined ) { // material
  31832. versioning = this.Versioning.NeedsUpdate;
  31833. } else if ( targetObject.matrixWorldNeedsUpdate !== undefined ) { // node transform
  31834. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  31835. }
  31836. // determine how the property gets bound
  31837. var bindingType = this.BindingType.Direct;
  31838. if ( propertyIndex !== undefined ) {
  31839. // access a sub element of the property array (only primitives are supported right now)
  31840. if ( propertyName === "morphTargetInfluences" ) {
  31841. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  31842. // support resolving morphTarget names into indices.
  31843. if ( ! targetObject.geometry ) {
  31844. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this );
  31845. return;
  31846. }
  31847. if ( targetObject.geometry.isBufferGeometry ) {
  31848. if ( ! targetObject.geometry.morphAttributes ) {
  31849. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this );
  31850. return;
  31851. }
  31852. for ( var i = 0; i < this.node.geometry.morphAttributes.position.length; i ++ ) {
  31853. if ( targetObject.geometry.morphAttributes.position[ i ].name === propertyIndex ) {
  31854. propertyIndex = i;
  31855. break;
  31856. }
  31857. }
  31858. } else {
  31859. if ( ! targetObject.geometry.morphTargets ) {
  31860. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphTargets.', this );
  31861. return;
  31862. }
  31863. for ( var i = 0; i < this.node.geometry.morphTargets.length; i ++ ) {
  31864. if ( targetObject.geometry.morphTargets[ i ].name === propertyIndex ) {
  31865. propertyIndex = i;
  31866. break;
  31867. }
  31868. }
  31869. }
  31870. }
  31871. bindingType = this.BindingType.ArrayElement;
  31872. this.resolvedProperty = nodeProperty;
  31873. this.propertyIndex = propertyIndex;
  31874. } else if ( nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined ) {
  31875. // must use copy for Object3D.Euler/Quaternion
  31876. bindingType = this.BindingType.HasFromToArray;
  31877. this.resolvedProperty = nodeProperty;
  31878. } else if ( Array.isArray( nodeProperty ) ) {
  31879. bindingType = this.BindingType.EntireArray;
  31880. this.resolvedProperty = nodeProperty;
  31881. } else {
  31882. this.propertyName = propertyName;
  31883. }
  31884. // select getter / setter
  31885. this.getValue = this.GetterByBindingType[ bindingType ];
  31886. this.setValue = this.SetterByBindingTypeAndVersioning[ bindingType ][ versioning ];
  31887. },
  31888. unbind: function () {
  31889. this.node = null;
  31890. // back to the prototype version of getValue / setValue
  31891. // note: avoiding to mutate the shape of 'this' via 'delete'
  31892. this.getValue = this._getValue_unbound;
  31893. this.setValue = this._setValue_unbound;
  31894. }
  31895. } );
  31896. // DECLARE ALIAS AFTER assign prototype
  31897. Object.assign( PropertyBinding.prototype, {
  31898. // initial state of these methods that calls 'bind'
  31899. _getValue_unbound: PropertyBinding.prototype.getValue,
  31900. _setValue_unbound: PropertyBinding.prototype.setValue,
  31901. } );
  31902. /**
  31903. *
  31904. * A group of objects that receives a shared animation state.
  31905. *
  31906. * Usage:
  31907. *
  31908. * - Add objects you would otherwise pass as 'root' to the
  31909. * constructor or the .clipAction method of AnimationMixer.
  31910. *
  31911. * - Instead pass this object as 'root'.
  31912. *
  31913. * - You can also add and remove objects later when the mixer
  31914. * is running.
  31915. *
  31916. * Note:
  31917. *
  31918. * Objects of this class appear as one object to the mixer,
  31919. * so cache control of the individual objects must be done
  31920. * on the group.
  31921. *
  31922. * Limitation:
  31923. *
  31924. * - The animated properties must be compatible among the
  31925. * all objects in the group.
  31926. *
  31927. * - A single property can either be controlled through a
  31928. * target group or directly, but not both.
  31929. *
  31930. * @author tschw
  31931. */
  31932. function AnimationObjectGroup() {
  31933. this.uuid = MathUtils.generateUUID();
  31934. // cached objects followed by the active ones
  31935. this._objects = Array.prototype.slice.call( arguments );
  31936. this.nCachedObjects_ = 0; // threshold
  31937. // note: read by PropertyBinding.Composite
  31938. var indices = {};
  31939. this._indicesByUUID = indices; // for bookkeeping
  31940. for ( var i = 0, n = arguments.length; i !== n; ++ i ) {
  31941. indices[ arguments[ i ].uuid ] = i;
  31942. }
  31943. this._paths = []; // inside: string
  31944. this._parsedPaths = []; // inside: { we don't care, here }
  31945. this._bindings = []; // inside: Array< PropertyBinding >
  31946. this._bindingsIndicesByPath = {}; // inside: indices in these arrays
  31947. var scope = this;
  31948. this.stats = {
  31949. objects: {
  31950. get total() {
  31951. return scope._objects.length;
  31952. },
  31953. get inUse() {
  31954. return this.total - scope.nCachedObjects_;
  31955. }
  31956. },
  31957. get bindingsPerObject() {
  31958. return scope._bindings.length;
  31959. }
  31960. };
  31961. }
  31962. Object.assign( AnimationObjectGroup.prototype, {
  31963. isAnimationObjectGroup: true,
  31964. add: function () {
  31965. var objects = this._objects,
  31966. nObjects = objects.length,
  31967. nCachedObjects = this.nCachedObjects_,
  31968. indicesByUUID = this._indicesByUUID,
  31969. paths = this._paths,
  31970. parsedPaths = this._parsedPaths,
  31971. bindings = this._bindings,
  31972. nBindings = bindings.length,
  31973. knownObject = undefined;
  31974. for ( var i = 0, n = arguments.length; i !== n; ++ i ) {
  31975. var object = arguments[ i ],
  31976. uuid = object.uuid,
  31977. index = indicesByUUID[ uuid ];
  31978. if ( index === undefined ) {
  31979. // unknown object -> add it to the ACTIVE region
  31980. index = nObjects ++;
  31981. indicesByUUID[ uuid ] = index;
  31982. objects.push( object );
  31983. // accounting is done, now do the same for all bindings
  31984. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  31985. bindings[ j ].push( new PropertyBinding( object, paths[ j ], parsedPaths[ j ] ) );
  31986. }
  31987. } else if ( index < nCachedObjects ) {
  31988. knownObject = objects[ index ];
  31989. // move existing object to the ACTIVE region
  31990. var firstActiveIndex = -- nCachedObjects,
  31991. lastCachedObject = objects[ firstActiveIndex ];
  31992. indicesByUUID[ lastCachedObject.uuid ] = index;
  31993. objects[ index ] = lastCachedObject;
  31994. indicesByUUID[ uuid ] = firstActiveIndex;
  31995. objects[ firstActiveIndex ] = object;
  31996. // accounting is done, now do the same for all bindings
  31997. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  31998. var bindingsForPath = bindings[ j ],
  31999. lastCached = bindingsForPath[ firstActiveIndex ],
  32000. binding = bindingsForPath[ index ];
  32001. bindingsForPath[ index ] = lastCached;
  32002. if ( binding === undefined ) {
  32003. // since we do not bother to create new bindings
  32004. // for objects that are cached, the binding may
  32005. // or may not exist
  32006. binding = new PropertyBinding( object, paths[ j ], parsedPaths[ j ] );
  32007. }
  32008. bindingsForPath[ firstActiveIndex ] = binding;
  32009. }
  32010. } else if ( objects[ index ] !== knownObject ) {
  32011. console.error( 'THREE.AnimationObjectGroup: Different objects with the same UUID ' +
  32012. 'detected. Clean the caches or recreate your infrastructure when reloading scenes.' );
  32013. } // else the object is already where we want it to be
  32014. } // for arguments
  32015. this.nCachedObjects_ = nCachedObjects;
  32016. },
  32017. remove: function () {
  32018. var objects = this._objects,
  32019. nCachedObjects = this.nCachedObjects_,
  32020. indicesByUUID = this._indicesByUUID,
  32021. bindings = this._bindings,
  32022. nBindings = bindings.length;
  32023. for ( var i = 0, n = arguments.length; i !== n; ++ i ) {
  32024. var object = arguments[ i ],
  32025. uuid = object.uuid,
  32026. index = indicesByUUID[ uuid ];
  32027. if ( index !== undefined && index >= nCachedObjects ) {
  32028. // move existing object into the CACHED region
  32029. var lastCachedIndex = nCachedObjects ++,
  32030. firstActiveObject = objects[ lastCachedIndex ];
  32031. indicesByUUID[ firstActiveObject.uuid ] = index;
  32032. objects[ index ] = firstActiveObject;
  32033. indicesByUUID[ uuid ] = lastCachedIndex;
  32034. objects[ lastCachedIndex ] = object;
  32035. // accounting is done, now do the same for all bindings
  32036. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  32037. var bindingsForPath = bindings[ j ],
  32038. firstActive = bindingsForPath[ lastCachedIndex ],
  32039. binding = bindingsForPath[ index ];
  32040. bindingsForPath[ index ] = firstActive;
  32041. bindingsForPath[ lastCachedIndex ] = binding;
  32042. }
  32043. }
  32044. } // for arguments
  32045. this.nCachedObjects_ = nCachedObjects;
  32046. },
  32047. // remove & forget
  32048. uncache: function () {
  32049. var objects = this._objects,
  32050. nObjects = objects.length,
  32051. nCachedObjects = this.nCachedObjects_,
  32052. indicesByUUID = this._indicesByUUID,
  32053. bindings = this._bindings,
  32054. nBindings = bindings.length;
  32055. for ( var i = 0, n = arguments.length; i !== n; ++ i ) {
  32056. var object = arguments[ i ],
  32057. uuid = object.uuid,
  32058. index = indicesByUUID[ uuid ];
  32059. if ( index !== undefined ) {
  32060. delete indicesByUUID[ uuid ];
  32061. if ( index < nCachedObjects ) {
  32062. // object is cached, shrink the CACHED region
  32063. var firstActiveIndex = -- nCachedObjects,
  32064. lastCachedObject = objects[ firstActiveIndex ],
  32065. lastIndex = -- nObjects,
  32066. lastObject = objects[ lastIndex ];
  32067. // last cached object takes this object's place
  32068. indicesByUUID[ lastCachedObject.uuid ] = index;
  32069. objects[ index ] = lastCachedObject;
  32070. // last object goes to the activated slot and pop
  32071. indicesByUUID[ lastObject.uuid ] = firstActiveIndex;
  32072. objects[ firstActiveIndex ] = lastObject;
  32073. objects.pop();
  32074. // accounting is done, now do the same for all bindings
  32075. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  32076. var bindingsForPath = bindings[ j ],
  32077. lastCached = bindingsForPath[ firstActiveIndex ],
  32078. last = bindingsForPath[ lastIndex ];
  32079. bindingsForPath[ index ] = lastCached;
  32080. bindingsForPath[ firstActiveIndex ] = last;
  32081. bindingsForPath.pop();
  32082. }
  32083. } else {
  32084. // object is active, just swap with the last and pop
  32085. var lastIndex = -- nObjects,
  32086. lastObject = objects[ lastIndex ];
  32087. indicesByUUID[ lastObject.uuid ] = index;
  32088. objects[ index ] = lastObject;
  32089. objects.pop();
  32090. // accounting is done, now do the same for all bindings
  32091. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  32092. var bindingsForPath = bindings[ j ];
  32093. bindingsForPath[ index ] = bindingsForPath[ lastIndex ];
  32094. bindingsForPath.pop();
  32095. }
  32096. } // cached or active
  32097. } // if object is known
  32098. } // for arguments
  32099. this.nCachedObjects_ = nCachedObjects;
  32100. },
  32101. // Internal interface used by befriended PropertyBinding.Composite:
  32102. subscribe_: function ( path, parsedPath ) {
  32103. // returns an array of bindings for the given path that is changed
  32104. // according to the contained objects in the group
  32105. var indicesByPath = this._bindingsIndicesByPath,
  32106. index = indicesByPath[ path ],
  32107. bindings = this._bindings;
  32108. if ( index !== undefined ) { return bindings[ index ]; }
  32109. var paths = this._paths,
  32110. parsedPaths = this._parsedPaths,
  32111. objects = this._objects,
  32112. nObjects = objects.length,
  32113. nCachedObjects = this.nCachedObjects_,
  32114. bindingsForPath = new Array( nObjects );
  32115. index = bindings.length;
  32116. indicesByPath[ path ] = index;
  32117. paths.push( path );
  32118. parsedPaths.push( parsedPath );
  32119. bindings.push( bindingsForPath );
  32120. for ( var i = nCachedObjects, n = objects.length; i !== n; ++ i ) {
  32121. var object = objects[ i ];
  32122. bindingsForPath[ i ] = new PropertyBinding( object, path, parsedPath );
  32123. }
  32124. return bindingsForPath;
  32125. },
  32126. unsubscribe_: function ( path ) {
  32127. // tells the group to forget about a property path and no longer
  32128. // update the array previously obtained with 'subscribe_'
  32129. var indicesByPath = this._bindingsIndicesByPath,
  32130. index = indicesByPath[ path ];
  32131. if ( index !== undefined ) {
  32132. var paths = this._paths,
  32133. parsedPaths = this._parsedPaths,
  32134. bindings = this._bindings,
  32135. lastBindingsIndex = bindings.length - 1,
  32136. lastBindings = bindings[ lastBindingsIndex ],
  32137. lastBindingsPath = path[ lastBindingsIndex ];
  32138. indicesByPath[ lastBindingsPath ] = index;
  32139. bindings[ index ] = lastBindings;
  32140. bindings.pop();
  32141. parsedPaths[ index ] = parsedPaths[ lastBindingsIndex ];
  32142. parsedPaths.pop();
  32143. paths[ index ] = paths[ lastBindingsIndex ];
  32144. paths.pop();
  32145. }
  32146. }
  32147. } );
  32148. /**
  32149. *
  32150. * Action provided by AnimationMixer for scheduling clip playback on specific
  32151. * objects.
  32152. *
  32153. * @author Ben Houston / http://clara.io/
  32154. * @author David Sarno / http://lighthaus.us/
  32155. * @author tschw
  32156. *
  32157. */
  32158. function AnimationAction( mixer, clip, localRoot ) {
  32159. this._mixer = mixer;
  32160. this._clip = clip;
  32161. this._localRoot = localRoot || null;
  32162. var tracks = clip.tracks,
  32163. nTracks = tracks.length,
  32164. interpolants = new Array( nTracks );
  32165. var interpolantSettings = {
  32166. endingStart: ZeroCurvatureEnding,
  32167. endingEnd: ZeroCurvatureEnding
  32168. };
  32169. for ( var i = 0; i !== nTracks; ++ i ) {
  32170. var interpolant = tracks[ i ].createInterpolant( null );
  32171. interpolants[ i ] = interpolant;
  32172. interpolant.settings = interpolantSettings;
  32173. }
  32174. this._interpolantSettings = interpolantSettings;
  32175. this._interpolants = interpolants; // bound by the mixer
  32176. // inside: PropertyMixer (managed by the mixer)
  32177. this._propertyBindings = new Array( nTracks );
  32178. this._cacheIndex = null; // for the memory manager
  32179. this._byClipCacheIndex = null; // for the memory manager
  32180. this._timeScaleInterpolant = null;
  32181. this._weightInterpolant = null;
  32182. this.loop = LoopRepeat;
  32183. this._loopCount = - 1;
  32184. // global mixer time when the action is to be started
  32185. // it's set back to 'null' upon start of the action
  32186. this._startTime = null;
  32187. // scaled local time of the action
  32188. // gets clamped or wrapped to 0..clip.duration according to loop
  32189. this.time = 0;
  32190. this.timeScale = 1;
  32191. this._effectiveTimeScale = 1;
  32192. this.weight = 1;
  32193. this._effectiveWeight = 1;
  32194. this.repetitions = Infinity; // no. of repetitions when looping
  32195. this.paused = false; // true -> zero effective time scale
  32196. this.enabled = true; // false -> zero effective weight
  32197. this.clampWhenFinished = false;// keep feeding the last frame?
  32198. this.zeroSlopeAtStart = true;// for smooth interpolation w/o separate
  32199. this.zeroSlopeAtEnd = true;// clips for start, loop and end
  32200. }
  32201. Object.assign( AnimationAction.prototype, {
  32202. // State & Scheduling
  32203. play: function () {
  32204. this._mixer._activateAction( this );
  32205. return this;
  32206. },
  32207. stop: function () {
  32208. this._mixer._deactivateAction( this );
  32209. return this.reset();
  32210. },
  32211. reset: function () {
  32212. this.paused = false;
  32213. this.enabled = true;
  32214. this.time = 0; // restart clip
  32215. this._loopCount = - 1;// forget previous loops
  32216. this._startTime = null;// forget scheduling
  32217. return this.stopFading().stopWarping();
  32218. },
  32219. isRunning: function () {
  32220. return this.enabled && ! this.paused && this.timeScale !== 0 &&
  32221. this._startTime === null && this._mixer._isActiveAction( this );
  32222. },
  32223. // return true when play has been called
  32224. isScheduled: function () {
  32225. return this._mixer._isActiveAction( this );
  32226. },
  32227. startAt: function ( time ) {
  32228. this._startTime = time;
  32229. return this;
  32230. },
  32231. setLoop: function ( mode, repetitions ) {
  32232. this.loop = mode;
  32233. this.repetitions = repetitions;
  32234. return this;
  32235. },
  32236. // Weight
  32237. // set the weight stopping any scheduled fading
  32238. // although .enabled = false yields an effective weight of zero, this
  32239. // method does *not* change .enabled, because it would be confusing
  32240. setEffectiveWeight: function ( weight ) {
  32241. this.weight = weight;
  32242. // note: same logic as when updated at runtime
  32243. this._effectiveWeight = this.enabled ? weight : 0;
  32244. return this.stopFading();
  32245. },
  32246. // return the weight considering fading and .enabled
  32247. getEffectiveWeight: function () {
  32248. return this._effectiveWeight;
  32249. },
  32250. fadeIn: function ( duration ) {
  32251. return this._scheduleFading( duration, 0, 1 );
  32252. },
  32253. fadeOut: function ( duration ) {
  32254. return this._scheduleFading( duration, 1, 0 );
  32255. },
  32256. crossFadeFrom: function ( fadeOutAction, duration, warp ) {
  32257. fadeOutAction.fadeOut( duration );
  32258. this.fadeIn( duration );
  32259. if ( warp ) {
  32260. var fadeInDuration = this._clip.duration,
  32261. fadeOutDuration = fadeOutAction._clip.duration,
  32262. startEndRatio = fadeOutDuration / fadeInDuration,
  32263. endStartRatio = fadeInDuration / fadeOutDuration;
  32264. fadeOutAction.warp( 1.0, startEndRatio, duration );
  32265. this.warp( endStartRatio, 1.0, duration );
  32266. }
  32267. return this;
  32268. },
  32269. crossFadeTo: function ( fadeInAction, duration, warp ) {
  32270. return fadeInAction.crossFadeFrom( this, duration, warp );
  32271. },
  32272. stopFading: function () {
  32273. var weightInterpolant = this._weightInterpolant;
  32274. if ( weightInterpolant !== null ) {
  32275. this._weightInterpolant = null;
  32276. this._mixer._takeBackControlInterpolant( weightInterpolant );
  32277. }
  32278. return this;
  32279. },
  32280. // Time Scale Control
  32281. // set the time scale stopping any scheduled warping
  32282. // although .paused = true yields an effective time scale of zero, this
  32283. // method does *not* change .paused, because it would be confusing
  32284. setEffectiveTimeScale: function ( timeScale ) {
  32285. this.timeScale = timeScale;
  32286. this._effectiveTimeScale = this.paused ? 0 : timeScale;
  32287. return this.stopWarping();
  32288. },
  32289. // return the time scale considering warping and .paused
  32290. getEffectiveTimeScale: function () {
  32291. return this._effectiveTimeScale;
  32292. },
  32293. setDuration: function ( duration ) {
  32294. this.timeScale = this._clip.duration / duration;
  32295. return this.stopWarping();
  32296. },
  32297. syncWith: function ( action ) {
  32298. this.time = action.time;
  32299. this.timeScale = action.timeScale;
  32300. return this.stopWarping();
  32301. },
  32302. halt: function ( duration ) {
  32303. return this.warp( this._effectiveTimeScale, 0, duration );
  32304. },
  32305. warp: function ( startTimeScale, endTimeScale, duration ) {
  32306. var mixer = this._mixer, now = mixer.time,
  32307. interpolant = this._timeScaleInterpolant,
  32308. timeScale = this.timeScale;
  32309. if ( interpolant === null ) {
  32310. interpolant = mixer._lendControlInterpolant();
  32311. this._timeScaleInterpolant = interpolant;
  32312. }
  32313. var times = interpolant.parameterPositions,
  32314. values = interpolant.sampleValues;
  32315. times[ 0 ] = now;
  32316. times[ 1 ] = now + duration;
  32317. values[ 0 ] = startTimeScale / timeScale;
  32318. values[ 1 ] = endTimeScale / timeScale;
  32319. return this;
  32320. },
  32321. stopWarping: function () {
  32322. var timeScaleInterpolant = this._timeScaleInterpolant;
  32323. if ( timeScaleInterpolant !== null ) {
  32324. this._timeScaleInterpolant = null;
  32325. this._mixer._takeBackControlInterpolant( timeScaleInterpolant );
  32326. }
  32327. return this;
  32328. },
  32329. // Object Accessors
  32330. getMixer: function () {
  32331. return this._mixer;
  32332. },
  32333. getClip: function () {
  32334. return this._clip;
  32335. },
  32336. getRoot: function () {
  32337. return this._localRoot || this._mixer._root;
  32338. },
  32339. // Interna
  32340. _update: function ( time, deltaTime, timeDirection, accuIndex ) {
  32341. // called by the mixer
  32342. if ( ! this.enabled ) {
  32343. // call ._updateWeight() to update ._effectiveWeight
  32344. this._updateWeight( time );
  32345. return;
  32346. }
  32347. var startTime = this._startTime;
  32348. if ( startTime !== null ) {
  32349. // check for scheduled start of action
  32350. var timeRunning = ( time - startTime ) * timeDirection;
  32351. if ( timeRunning < 0 || timeDirection === 0 ) {
  32352. return; // yet to come / don't decide when delta = 0
  32353. }
  32354. // start
  32355. this._startTime = null; // unschedule
  32356. deltaTime = timeDirection * timeRunning;
  32357. }
  32358. // apply time scale and advance time
  32359. deltaTime *= this._updateTimeScale( time );
  32360. var clipTime = this._updateTime( deltaTime );
  32361. // note: _updateTime may disable the action resulting in
  32362. // an effective weight of 0
  32363. var weight = this._updateWeight( time );
  32364. if ( weight > 0 ) {
  32365. var interpolants = this._interpolants;
  32366. var propertyMixers = this._propertyBindings;
  32367. for ( var j = 0, m = interpolants.length; j !== m; ++ j ) {
  32368. interpolants[ j ].evaluate( clipTime );
  32369. propertyMixers[ j ].accumulate( accuIndex, weight );
  32370. }
  32371. }
  32372. },
  32373. _updateWeight: function ( time ) {
  32374. var weight = 0;
  32375. if ( this.enabled ) {
  32376. weight = this.weight;
  32377. var interpolant = this._weightInterpolant;
  32378. if ( interpolant !== null ) {
  32379. var interpolantValue = interpolant.evaluate( time )[ 0 ];
  32380. weight *= interpolantValue;
  32381. if ( time > interpolant.parameterPositions[ 1 ] ) {
  32382. this.stopFading();
  32383. if ( interpolantValue === 0 ) {
  32384. // faded out, disable
  32385. this.enabled = false;
  32386. }
  32387. }
  32388. }
  32389. }
  32390. this._effectiveWeight = weight;
  32391. return weight;
  32392. },
  32393. _updateTimeScale: function ( time ) {
  32394. var timeScale = 0;
  32395. if ( ! this.paused ) {
  32396. timeScale = this.timeScale;
  32397. var interpolant = this._timeScaleInterpolant;
  32398. if ( interpolant !== null ) {
  32399. var interpolantValue = interpolant.evaluate( time )[ 0 ];
  32400. timeScale *= interpolantValue;
  32401. if ( time > interpolant.parameterPositions[ 1 ] ) {
  32402. this.stopWarping();
  32403. if ( timeScale === 0 ) {
  32404. // motion has halted, pause
  32405. this.paused = true;
  32406. } else {
  32407. // warp done - apply final time scale
  32408. this.timeScale = timeScale;
  32409. }
  32410. }
  32411. }
  32412. }
  32413. this._effectiveTimeScale = timeScale;
  32414. return timeScale;
  32415. },
  32416. _updateTime: function ( deltaTime ) {
  32417. var time = this.time + deltaTime;
  32418. var duration = this._clip.duration;
  32419. var loop = this.loop;
  32420. var loopCount = this._loopCount;
  32421. var pingPong = ( loop === LoopPingPong );
  32422. if ( deltaTime === 0 ) {
  32423. if ( loopCount === - 1 ) { return time; }
  32424. return ( pingPong && ( loopCount & 1 ) === 1 ) ? duration - time : time;
  32425. }
  32426. if ( loop === LoopOnce ) {
  32427. if ( loopCount === - 1 ) {
  32428. // just started
  32429. this._loopCount = 0;
  32430. this._setEndings( true, true, false );
  32431. }
  32432. handle_stop: {
  32433. if ( time >= duration ) {
  32434. time = duration;
  32435. } else if ( time < 0 ) {
  32436. time = 0;
  32437. } else {
  32438. this.time = time;
  32439. break handle_stop;
  32440. }
  32441. if ( this.clampWhenFinished ) { this.paused = true; }
  32442. else { this.enabled = false; }
  32443. this.time = time;
  32444. this._mixer.dispatchEvent( {
  32445. type: 'finished', action: this,
  32446. direction: deltaTime < 0 ? - 1 : 1
  32447. } );
  32448. }
  32449. } else { // repetitive Repeat or PingPong
  32450. if ( loopCount === - 1 ) {
  32451. // just started
  32452. if ( deltaTime >= 0 ) {
  32453. loopCount = 0;
  32454. this._setEndings( true, this.repetitions === 0, pingPong );
  32455. } else {
  32456. // when looping in reverse direction, the initial
  32457. // transition through zero counts as a repetition,
  32458. // so leave loopCount at -1
  32459. this._setEndings( this.repetitions === 0, true, pingPong );
  32460. }
  32461. }
  32462. if ( time >= duration || time < 0 ) {
  32463. // wrap around
  32464. var loopDelta = Math.floor( time / duration ); // signed
  32465. time -= duration * loopDelta;
  32466. loopCount += Math.abs( loopDelta );
  32467. var pending = this.repetitions - loopCount;
  32468. if ( pending <= 0 ) {
  32469. // have to stop (switch state, clamp time, fire event)
  32470. if ( this.clampWhenFinished ) { this.paused = true; }
  32471. else { this.enabled = false; }
  32472. time = deltaTime > 0 ? duration : 0;
  32473. this.time = time;
  32474. this._mixer.dispatchEvent( {
  32475. type: 'finished', action: this,
  32476. direction: deltaTime > 0 ? 1 : - 1
  32477. } );
  32478. } else {
  32479. // keep running
  32480. if ( pending === 1 ) {
  32481. // entering the last round
  32482. var atStart = deltaTime < 0;
  32483. this._setEndings( atStart, ! atStart, pingPong );
  32484. } else {
  32485. this._setEndings( false, false, pingPong );
  32486. }
  32487. this._loopCount = loopCount;
  32488. this.time = time;
  32489. this._mixer.dispatchEvent( {
  32490. type: 'loop', action: this, loopDelta: loopDelta
  32491. } );
  32492. }
  32493. } else {
  32494. this.time = time;
  32495. }
  32496. if ( pingPong && ( loopCount & 1 ) === 1 ) {
  32497. // invert time for the "pong round"
  32498. return duration - time;
  32499. }
  32500. }
  32501. return time;
  32502. },
  32503. _setEndings: function ( atStart, atEnd, pingPong ) {
  32504. var settings = this._interpolantSettings;
  32505. if ( pingPong ) {
  32506. settings.endingStart = ZeroSlopeEnding;
  32507. settings.endingEnd = ZeroSlopeEnding;
  32508. } else {
  32509. // assuming for LoopOnce atStart == atEnd == true
  32510. if ( atStart ) {
  32511. settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding;
  32512. } else {
  32513. settings.endingStart = WrapAroundEnding;
  32514. }
  32515. if ( atEnd ) {
  32516. settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding;
  32517. } else {
  32518. settings.endingEnd = WrapAroundEnding;
  32519. }
  32520. }
  32521. },
  32522. _scheduleFading: function ( duration, weightNow, weightThen ) {
  32523. var mixer = this._mixer, now = mixer.time,
  32524. interpolant = this._weightInterpolant;
  32525. if ( interpolant === null ) {
  32526. interpolant = mixer._lendControlInterpolant();
  32527. this._weightInterpolant = interpolant;
  32528. }
  32529. var times = interpolant.parameterPositions,
  32530. values = interpolant.sampleValues;
  32531. times[ 0 ] = now;
  32532. values[ 0 ] = weightNow;
  32533. times[ 1 ] = now + duration;
  32534. values[ 1 ] = weightThen;
  32535. return this;
  32536. }
  32537. } );
  32538. /**
  32539. *
  32540. * Player for AnimationClips.
  32541. *
  32542. *
  32543. * @author Ben Houston / http://clara.io/
  32544. * @author David Sarno / http://lighthaus.us/
  32545. * @author tschw
  32546. */
  32547. function AnimationMixer( root ) {
  32548. this._root = root;
  32549. this._initMemoryManager();
  32550. this._accuIndex = 0;
  32551. this.time = 0;
  32552. this.timeScale = 1.0;
  32553. }
  32554. AnimationMixer.prototype = Object.assign( Object.create( EventDispatcher.prototype ), {
  32555. constructor: AnimationMixer,
  32556. _bindAction: function ( action, prototypeAction ) {
  32557. var root = action._localRoot || this._root,
  32558. tracks = action._clip.tracks,
  32559. nTracks = tracks.length,
  32560. bindings = action._propertyBindings,
  32561. interpolants = action._interpolants,
  32562. rootUuid = root.uuid,
  32563. bindingsByRoot = this._bindingsByRootAndName,
  32564. bindingsByName = bindingsByRoot[ rootUuid ];
  32565. if ( bindingsByName === undefined ) {
  32566. bindingsByName = {};
  32567. bindingsByRoot[ rootUuid ] = bindingsByName;
  32568. }
  32569. for ( var i = 0; i !== nTracks; ++ i ) {
  32570. var track = tracks[ i ],
  32571. trackName = track.name,
  32572. binding = bindingsByName[ trackName ];
  32573. if ( binding !== undefined ) {
  32574. bindings[ i ] = binding;
  32575. } else {
  32576. binding = bindings[ i ];
  32577. if ( binding !== undefined ) {
  32578. // existing binding, make sure the cache knows
  32579. if ( binding._cacheIndex === null ) {
  32580. ++ binding.referenceCount;
  32581. this._addInactiveBinding( binding, rootUuid, trackName );
  32582. }
  32583. continue;
  32584. }
  32585. var path = prototypeAction && prototypeAction.
  32586. _propertyBindings[ i ].binding.parsedPath;
  32587. binding = new PropertyMixer(
  32588. PropertyBinding.create( root, trackName, path ),
  32589. track.ValueTypeName, track.getValueSize() );
  32590. ++ binding.referenceCount;
  32591. this._addInactiveBinding( binding, rootUuid, trackName );
  32592. bindings[ i ] = binding;
  32593. }
  32594. interpolants[ i ].resultBuffer = binding.buffer;
  32595. }
  32596. },
  32597. _activateAction: function ( action ) {
  32598. if ( ! this._isActiveAction( action ) ) {
  32599. if ( action._cacheIndex === null ) {
  32600. // this action has been forgotten by the cache, but the user
  32601. // appears to be still using it -> rebind
  32602. var rootUuid = ( action._localRoot || this._root ).uuid,
  32603. clipUuid = action._clip.uuid,
  32604. actionsForClip = this._actionsByClip[ clipUuid ];
  32605. this._bindAction( action,
  32606. actionsForClip && actionsForClip.knownActions[ 0 ] );
  32607. this._addInactiveAction( action, clipUuid, rootUuid );
  32608. }
  32609. var bindings = action._propertyBindings;
  32610. // increment reference counts / sort out state
  32611. for ( var i = 0, n = bindings.length; i !== n; ++ i ) {
  32612. var binding = bindings[ i ];
  32613. if ( binding.useCount ++ === 0 ) {
  32614. this._lendBinding( binding );
  32615. binding.saveOriginalState();
  32616. }
  32617. }
  32618. this._lendAction( action );
  32619. }
  32620. },
  32621. _deactivateAction: function ( action ) {
  32622. if ( this._isActiveAction( action ) ) {
  32623. var bindings = action._propertyBindings;
  32624. // decrement reference counts / sort out state
  32625. for ( var i = 0, n = bindings.length; i !== n; ++ i ) {
  32626. var binding = bindings[ i ];
  32627. if ( -- binding.useCount === 0 ) {
  32628. binding.restoreOriginalState();
  32629. this._takeBackBinding( binding );
  32630. }
  32631. }
  32632. this._takeBackAction( action );
  32633. }
  32634. },
  32635. // Memory manager
  32636. _initMemoryManager: function () {
  32637. this._actions = []; // 'nActiveActions' followed by inactive ones
  32638. this._nActiveActions = 0;
  32639. this._actionsByClip = {};
  32640. // inside:
  32641. // {
  32642. // knownActions: Array< AnimationAction > - used as prototypes
  32643. // actionByRoot: AnimationAction - lookup
  32644. // }
  32645. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  32646. this._nActiveBindings = 0;
  32647. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  32648. this._controlInterpolants = []; // same game as above
  32649. this._nActiveControlInterpolants = 0;
  32650. var scope = this;
  32651. this.stats = {
  32652. actions: {
  32653. get total() {
  32654. return scope._actions.length;
  32655. },
  32656. get inUse() {
  32657. return scope._nActiveActions;
  32658. }
  32659. },
  32660. bindings: {
  32661. get total() {
  32662. return scope._bindings.length;
  32663. },
  32664. get inUse() {
  32665. return scope._nActiveBindings;
  32666. }
  32667. },
  32668. controlInterpolants: {
  32669. get total() {
  32670. return scope._controlInterpolants.length;
  32671. },
  32672. get inUse() {
  32673. return scope._nActiveControlInterpolants;
  32674. }
  32675. }
  32676. };
  32677. },
  32678. // Memory management for AnimationAction objects
  32679. _isActiveAction: function ( action ) {
  32680. var index = action._cacheIndex;
  32681. return index !== null && index < this._nActiveActions;
  32682. },
  32683. _addInactiveAction: function ( action, clipUuid, rootUuid ) {
  32684. var actions = this._actions,
  32685. actionsByClip = this._actionsByClip,
  32686. actionsForClip = actionsByClip[ clipUuid ];
  32687. if ( actionsForClip === undefined ) {
  32688. actionsForClip = {
  32689. knownActions: [ action ],
  32690. actionByRoot: {}
  32691. };
  32692. action._byClipCacheIndex = 0;
  32693. actionsByClip[ clipUuid ] = actionsForClip;
  32694. } else {
  32695. var knownActions = actionsForClip.knownActions;
  32696. action._byClipCacheIndex = knownActions.length;
  32697. knownActions.push( action );
  32698. }
  32699. action._cacheIndex = actions.length;
  32700. actions.push( action );
  32701. actionsForClip.actionByRoot[ rootUuid ] = action;
  32702. },
  32703. _removeInactiveAction: function ( action ) {
  32704. var actions = this._actions,
  32705. lastInactiveAction = actions[ actions.length - 1 ],
  32706. cacheIndex = action._cacheIndex;
  32707. lastInactiveAction._cacheIndex = cacheIndex;
  32708. actions[ cacheIndex ] = lastInactiveAction;
  32709. actions.pop();
  32710. action._cacheIndex = null;
  32711. var clipUuid = action._clip.uuid,
  32712. actionsByClip = this._actionsByClip,
  32713. actionsForClip = actionsByClip[ clipUuid ],
  32714. knownActionsForClip = actionsForClip.knownActions,
  32715. lastKnownAction =
  32716. knownActionsForClip[ knownActionsForClip.length - 1 ],
  32717. byClipCacheIndex = action._byClipCacheIndex;
  32718. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  32719. knownActionsForClip[ byClipCacheIndex ] = lastKnownAction;
  32720. knownActionsForClip.pop();
  32721. action._byClipCacheIndex = null;
  32722. var actionByRoot = actionsForClip.actionByRoot,
  32723. rootUuid = ( action._localRoot || this._root ).uuid;
  32724. delete actionByRoot[ rootUuid ];
  32725. if ( knownActionsForClip.length === 0 ) {
  32726. delete actionsByClip[ clipUuid ];
  32727. }
  32728. this._removeInactiveBindingsForAction( action );
  32729. },
  32730. _removeInactiveBindingsForAction: function ( action ) {
  32731. var bindings = action._propertyBindings;
  32732. for ( var i = 0, n = bindings.length; i !== n; ++ i ) {
  32733. var binding = bindings[ i ];
  32734. if ( -- binding.referenceCount === 0 ) {
  32735. this._removeInactiveBinding( binding );
  32736. }
  32737. }
  32738. },
  32739. _lendAction: function ( action ) {
  32740. // [ active actions | inactive actions ]
  32741. // [ active actions >| inactive actions ]
  32742. // s a
  32743. // <-swap->
  32744. // a s
  32745. var actions = this._actions,
  32746. prevIndex = action._cacheIndex,
  32747. lastActiveIndex = this._nActiveActions ++,
  32748. firstInactiveAction = actions[ lastActiveIndex ];
  32749. action._cacheIndex = lastActiveIndex;
  32750. actions[ lastActiveIndex ] = action;
  32751. firstInactiveAction._cacheIndex = prevIndex;
  32752. actions[ prevIndex ] = firstInactiveAction;
  32753. },
  32754. _takeBackAction: function ( action ) {
  32755. // [ active actions | inactive actions ]
  32756. // [ active actions |< inactive actions ]
  32757. // a s
  32758. // <-swap->
  32759. // s a
  32760. var actions = this._actions,
  32761. prevIndex = action._cacheIndex,
  32762. firstInactiveIndex = -- this._nActiveActions,
  32763. lastActiveAction = actions[ firstInactiveIndex ];
  32764. action._cacheIndex = firstInactiveIndex;
  32765. actions[ firstInactiveIndex ] = action;
  32766. lastActiveAction._cacheIndex = prevIndex;
  32767. actions[ prevIndex ] = lastActiveAction;
  32768. },
  32769. // Memory management for PropertyMixer objects
  32770. _addInactiveBinding: function ( binding, rootUuid, trackName ) {
  32771. var bindingsByRoot = this._bindingsByRootAndName,
  32772. bindingByName = bindingsByRoot[ rootUuid ],
  32773. bindings = this._bindings;
  32774. if ( bindingByName === undefined ) {
  32775. bindingByName = {};
  32776. bindingsByRoot[ rootUuid ] = bindingByName;
  32777. }
  32778. bindingByName[ trackName ] = binding;
  32779. binding._cacheIndex = bindings.length;
  32780. bindings.push( binding );
  32781. },
  32782. _removeInactiveBinding: function ( binding ) {
  32783. var bindings = this._bindings,
  32784. propBinding = binding.binding,
  32785. rootUuid = propBinding.rootNode.uuid,
  32786. trackName = propBinding.path,
  32787. bindingsByRoot = this._bindingsByRootAndName,
  32788. bindingByName = bindingsByRoot[ rootUuid ],
  32789. lastInactiveBinding = bindings[ bindings.length - 1 ],
  32790. cacheIndex = binding._cacheIndex;
  32791. lastInactiveBinding._cacheIndex = cacheIndex;
  32792. bindings[ cacheIndex ] = lastInactiveBinding;
  32793. bindings.pop();
  32794. delete bindingByName[ trackName ];
  32795. if ( Object.keys( bindingByName ).length === 0 ) {
  32796. delete bindingsByRoot[ rootUuid ];
  32797. }
  32798. },
  32799. _lendBinding: function ( binding ) {
  32800. var bindings = this._bindings,
  32801. prevIndex = binding._cacheIndex,
  32802. lastActiveIndex = this._nActiveBindings ++,
  32803. firstInactiveBinding = bindings[ lastActiveIndex ];
  32804. binding._cacheIndex = lastActiveIndex;
  32805. bindings[ lastActiveIndex ] = binding;
  32806. firstInactiveBinding._cacheIndex = prevIndex;
  32807. bindings[ prevIndex ] = firstInactiveBinding;
  32808. },
  32809. _takeBackBinding: function ( binding ) {
  32810. var bindings = this._bindings,
  32811. prevIndex = binding._cacheIndex,
  32812. firstInactiveIndex = -- this._nActiveBindings,
  32813. lastActiveBinding = bindings[ firstInactiveIndex ];
  32814. binding._cacheIndex = firstInactiveIndex;
  32815. bindings[ firstInactiveIndex ] = binding;
  32816. lastActiveBinding._cacheIndex = prevIndex;
  32817. bindings[ prevIndex ] = lastActiveBinding;
  32818. },
  32819. // Memory management of Interpolants for weight and time scale
  32820. _lendControlInterpolant: function () {
  32821. var interpolants = this._controlInterpolants,
  32822. lastActiveIndex = this._nActiveControlInterpolants ++,
  32823. interpolant = interpolants[ lastActiveIndex ];
  32824. if ( interpolant === undefined ) {
  32825. interpolant = new LinearInterpolant(
  32826. new Float32Array( 2 ), new Float32Array( 2 ),
  32827. 1, this._controlInterpolantsResultBuffer );
  32828. interpolant.__cacheIndex = lastActiveIndex;
  32829. interpolants[ lastActiveIndex ] = interpolant;
  32830. }
  32831. return interpolant;
  32832. },
  32833. _takeBackControlInterpolant: function ( interpolant ) {
  32834. var interpolants = this._controlInterpolants,
  32835. prevIndex = interpolant.__cacheIndex,
  32836. firstInactiveIndex = -- this._nActiveControlInterpolants,
  32837. lastActiveInterpolant = interpolants[ firstInactiveIndex ];
  32838. interpolant.__cacheIndex = firstInactiveIndex;
  32839. interpolants[ firstInactiveIndex ] = interpolant;
  32840. lastActiveInterpolant.__cacheIndex = prevIndex;
  32841. interpolants[ prevIndex ] = lastActiveInterpolant;
  32842. },
  32843. _controlInterpolantsResultBuffer: new Float32Array( 1 ),
  32844. // return an action for a clip optionally using a custom root target
  32845. // object (this method allocates a lot of dynamic memory in case a
  32846. // previously unknown clip/root combination is specified)
  32847. clipAction: function ( clip, optionalRoot ) {
  32848. var root = optionalRoot || this._root,
  32849. rootUuid = root.uuid,
  32850. clipObject = typeof clip === 'string' ?
  32851. AnimationClip.findByName( root, clip ) : clip,
  32852. clipUuid = clipObject !== null ? clipObject.uuid : clip,
  32853. actionsForClip = this._actionsByClip[ clipUuid ],
  32854. prototypeAction = null;
  32855. if ( actionsForClip !== undefined ) {
  32856. var existingAction =
  32857. actionsForClip.actionByRoot[ rootUuid ];
  32858. if ( existingAction !== undefined ) {
  32859. return existingAction;
  32860. }
  32861. // we know the clip, so we don't have to parse all
  32862. // the bindings again but can just copy
  32863. prototypeAction = actionsForClip.knownActions[ 0 ];
  32864. // also, take the clip from the prototype action
  32865. if ( clipObject === null )
  32866. { clipObject = prototypeAction._clip; }
  32867. }
  32868. // clip must be known when specified via string
  32869. if ( clipObject === null ) { return null; }
  32870. // allocate all resources required to run it
  32871. var newAction = new AnimationAction( this, clipObject, optionalRoot );
  32872. this._bindAction( newAction, prototypeAction );
  32873. // and make the action known to the memory manager
  32874. this._addInactiveAction( newAction, clipUuid, rootUuid );
  32875. return newAction;
  32876. },
  32877. // get an existing action
  32878. existingAction: function ( clip, optionalRoot ) {
  32879. var root = optionalRoot || this._root,
  32880. rootUuid = root.uuid,
  32881. clipObject = typeof clip === 'string' ?
  32882. AnimationClip.findByName( root, clip ) : clip,
  32883. clipUuid = clipObject ? clipObject.uuid : clip,
  32884. actionsForClip = this._actionsByClip[ clipUuid ];
  32885. if ( actionsForClip !== undefined ) {
  32886. return actionsForClip.actionByRoot[ rootUuid ] || null;
  32887. }
  32888. return null;
  32889. },
  32890. // deactivates all previously scheduled actions
  32891. stopAllAction: function () {
  32892. var actions = this._actions,
  32893. nActions = this._nActiveActions,
  32894. bindings = this._bindings,
  32895. nBindings = this._nActiveBindings;
  32896. this._nActiveActions = 0;
  32897. this._nActiveBindings = 0;
  32898. for ( var i = 0; i !== nActions; ++ i ) {
  32899. actions[ i ].reset();
  32900. }
  32901. for ( var i = 0; i !== nBindings; ++ i ) {
  32902. bindings[ i ].useCount = 0;
  32903. }
  32904. return this;
  32905. },
  32906. // advance the time and update apply the animation
  32907. update: function ( deltaTime ) {
  32908. deltaTime *= this.timeScale;
  32909. var actions = this._actions,
  32910. nActions = this._nActiveActions,
  32911. time = this.time += deltaTime,
  32912. timeDirection = Math.sign( deltaTime ),
  32913. accuIndex = this._accuIndex ^= 1;
  32914. // run active actions
  32915. for ( var i = 0; i !== nActions; ++ i ) {
  32916. var action = actions[ i ];
  32917. action._update( time, deltaTime, timeDirection, accuIndex );
  32918. }
  32919. // update scene graph
  32920. var bindings = this._bindings,
  32921. nBindings = this._nActiveBindings;
  32922. for ( var i = 0; i !== nBindings; ++ i ) {
  32923. bindings[ i ].apply( accuIndex );
  32924. }
  32925. return this;
  32926. },
  32927. // Allows you to seek to a specific time in an animation.
  32928. setTime: function ( timeInSeconds ) {
  32929. this.time = 0; // Zero out time attribute for AnimationMixer object;
  32930. for ( var i = 0; i < this._actions.length; i ++ ) {
  32931. this._actions[ i ].time = 0; // Zero out time attribute for all associated AnimationAction objects.
  32932. }
  32933. return this.update( timeInSeconds ); // Update used to set exact time. Returns "this" AnimationMixer object.
  32934. },
  32935. // return this mixer's root target object
  32936. getRoot: function () {
  32937. return this._root;
  32938. },
  32939. // free all resources specific to a particular clip
  32940. uncacheClip: function ( clip ) {
  32941. var actions = this._actions,
  32942. clipUuid = clip.uuid,
  32943. actionsByClip = this._actionsByClip,
  32944. actionsForClip = actionsByClip[ clipUuid ];
  32945. if ( actionsForClip !== undefined ) {
  32946. // note: just calling _removeInactiveAction would mess up the
  32947. // iteration state and also require updating the state we can
  32948. // just throw away
  32949. var actionsToRemove = actionsForClip.knownActions;
  32950. for ( var i = 0, n = actionsToRemove.length; i !== n; ++ i ) {
  32951. var action = actionsToRemove[ i ];
  32952. this._deactivateAction( action );
  32953. var cacheIndex = action._cacheIndex,
  32954. lastInactiveAction = actions[ actions.length - 1 ];
  32955. action._cacheIndex = null;
  32956. action._byClipCacheIndex = null;
  32957. lastInactiveAction._cacheIndex = cacheIndex;
  32958. actions[ cacheIndex ] = lastInactiveAction;
  32959. actions.pop();
  32960. this._removeInactiveBindingsForAction( action );
  32961. }
  32962. delete actionsByClip[ clipUuid ];
  32963. }
  32964. },
  32965. // free all resources specific to a particular root target object
  32966. uncacheRoot: function ( root ) {
  32967. var rootUuid = root.uuid,
  32968. actionsByClip = this._actionsByClip;
  32969. for ( var clipUuid in actionsByClip ) {
  32970. var actionByRoot = actionsByClip[ clipUuid ].actionByRoot,
  32971. action = actionByRoot[ rootUuid ];
  32972. if ( action !== undefined ) {
  32973. this._deactivateAction( action );
  32974. this._removeInactiveAction( action );
  32975. }
  32976. }
  32977. var bindingsByRoot = this._bindingsByRootAndName,
  32978. bindingByName = bindingsByRoot[ rootUuid ];
  32979. if ( bindingByName !== undefined ) {
  32980. for ( var trackName in bindingByName ) {
  32981. var binding = bindingByName[ trackName ];
  32982. binding.restoreOriginalState();
  32983. this._removeInactiveBinding( binding );
  32984. }
  32985. }
  32986. },
  32987. // remove a targeted clip from the cache
  32988. uncacheAction: function ( clip, optionalRoot ) {
  32989. var action = this.existingAction( clip, optionalRoot );
  32990. if ( action !== null ) {
  32991. this._deactivateAction( action );
  32992. this._removeInactiveAction( action );
  32993. }
  32994. }
  32995. } );
  32996. /**
  32997. * @author mrdoob / http://mrdoob.com/
  32998. */
  32999. function Uniform( value ) {
  33000. if ( typeof value === 'string' ) {
  33001. console.warn( 'THREE.Uniform: Type parameter is no longer needed.' );
  33002. value = arguments[ 1 ];
  33003. }
  33004. this.value = value;
  33005. }
  33006. Uniform.prototype.clone = function () {
  33007. return new Uniform( this.value.clone === undefined ? this.value : this.value.clone() );
  33008. };
  33009. /**
  33010. * @author benaadams / https://twitter.com/ben_a_adams
  33011. */
  33012. function InstancedInterleavedBuffer( array, stride, meshPerAttribute ) {
  33013. InterleavedBuffer.call( this, array, stride );
  33014. this.meshPerAttribute = meshPerAttribute || 1;
  33015. }
  33016. InstancedInterleavedBuffer.prototype = Object.assign( Object.create( InterleavedBuffer.prototype ), {
  33017. constructor: InstancedInterleavedBuffer,
  33018. isInstancedInterleavedBuffer: true,
  33019. copy: function ( source ) {
  33020. InterleavedBuffer.prototype.copy.call( this, source );
  33021. this.meshPerAttribute = source.meshPerAttribute;
  33022. return this;
  33023. }
  33024. } );
  33025. /**
  33026. * @author mrdoob / http://mrdoob.com/
  33027. * @author bhouston / http://clara.io/
  33028. * @author stephomi / http://stephaneginier.com/
  33029. */
  33030. function Raycaster( origin, direction, near, far ) {
  33031. this.ray = new Ray( origin, direction );
  33032. // direction is assumed to be normalized (for accurate distance calculations)
  33033. this.near = near || 0;
  33034. this.far = far || Infinity;
  33035. this.camera = null;
  33036. this.layers = new Layers();
  33037. this.params = {
  33038. Mesh: {},
  33039. Line: { threshold: 1 },
  33040. LOD: {},
  33041. Points: { threshold: 1 },
  33042. Sprite: {}
  33043. };
  33044. Object.defineProperties( this.params, {
  33045. PointCloud: {
  33046. get: function () {
  33047. console.warn( 'THREE.Raycaster: params.PointCloud has been renamed to params.Points.' );
  33048. return this.Points;
  33049. }
  33050. }
  33051. } );
  33052. }
  33053. function ascSort( a, b ) {
  33054. return a.distance - b.distance;
  33055. }
  33056. function intersectObject( object, raycaster, intersects, recursive ) {
  33057. if ( object.layers.test( raycaster.layers ) ) {
  33058. object.raycast( raycaster, intersects );
  33059. }
  33060. if ( recursive === true ) {
  33061. var children = object.children;
  33062. for ( var i = 0, l = children.length; i < l; i ++ ) {
  33063. intersectObject( children[ i ], raycaster, intersects, true );
  33064. }
  33065. }
  33066. }
  33067. Object.assign( Raycaster.prototype, {
  33068. set: function ( origin, direction ) {
  33069. // direction is assumed to be normalized (for accurate distance calculations)
  33070. this.ray.set( origin, direction );
  33071. },
  33072. setFromCamera: function ( coords, camera ) {
  33073. if ( ( camera && camera.isPerspectiveCamera ) ) {
  33074. this.ray.origin.setFromMatrixPosition( camera.matrixWorld );
  33075. this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( this.ray.origin ).normalize();
  33076. this.camera = camera;
  33077. } else if ( ( camera && camera.isOrthographicCamera ) ) {
  33078. this.ray.origin.set( coords.x, coords.y, ( camera.near + camera.far ) / ( camera.near - camera.far ) ).unproject( camera ); // set origin in plane of camera
  33079. this.ray.direction.set( 0, 0, - 1 ).transformDirection( camera.matrixWorld );
  33080. this.camera = camera;
  33081. } else {
  33082. console.error( 'THREE.Raycaster: Unsupported camera type.' );
  33083. }
  33084. },
  33085. intersectObject: function ( object, recursive, optionalTarget ) {
  33086. var intersects = optionalTarget || [];
  33087. intersectObject( object, this, intersects, recursive );
  33088. intersects.sort( ascSort );
  33089. return intersects;
  33090. },
  33091. intersectObjects: function ( objects, recursive, optionalTarget ) {
  33092. var intersects = optionalTarget || [];
  33093. if ( Array.isArray( objects ) === false ) {
  33094. console.warn( 'THREE.Raycaster.intersectObjects: objects is not an Array.' );
  33095. return intersects;
  33096. }
  33097. for ( var i = 0, l = objects.length; i < l; i ++ ) {
  33098. intersectObject( objects[ i ], this, intersects, recursive );
  33099. }
  33100. intersects.sort( ascSort );
  33101. return intersects;
  33102. }
  33103. } );
  33104. /**
  33105. * @author bhouston / http://clara.io
  33106. * @author WestLangley / http://github.com/WestLangley
  33107. *
  33108. * Ref: https://en.wikipedia.org/wiki/Spherical_coordinate_system
  33109. *
  33110. * The polar angle (phi) is measured from the positive y-axis. The positive y-axis is up.
  33111. * The azimuthal angle (theta) is measured from the positive z-axis.
  33112. */
  33113. function Spherical( radius, phi, theta ) {
  33114. this.radius = ( radius !== undefined ) ? radius : 1.0;
  33115. this.phi = ( phi !== undefined ) ? phi : 0; // polar angle
  33116. this.theta = ( theta !== undefined ) ? theta : 0; // azimuthal angle
  33117. return this;
  33118. }
  33119. Object.assign( Spherical.prototype, {
  33120. set: function ( radius, phi, theta ) {
  33121. this.radius = radius;
  33122. this.phi = phi;
  33123. this.theta = theta;
  33124. return this;
  33125. },
  33126. clone: function () {
  33127. return new this.constructor().copy( this );
  33128. },
  33129. copy: function ( other ) {
  33130. this.radius = other.radius;
  33131. this.phi = other.phi;
  33132. this.theta = other.theta;
  33133. return this;
  33134. },
  33135. // restrict phi to be betwee EPS and PI-EPS
  33136. makeSafe: function () {
  33137. var EPS = 0.000001;
  33138. this.phi = Math.max( EPS, Math.min( Math.PI - EPS, this.phi ) );
  33139. return this;
  33140. },
  33141. setFromVector3: function ( v ) {
  33142. return this.setFromCartesianCoords( v.x, v.y, v.z );
  33143. },
  33144. setFromCartesianCoords: function ( x, y, z ) {
  33145. this.radius = Math.sqrt( x * x + y * y + z * z );
  33146. if ( this.radius === 0 ) {
  33147. this.theta = 0;
  33148. this.phi = 0;
  33149. } else {
  33150. this.theta = Math.atan2( x, z );
  33151. this.phi = Math.acos( MathUtils.clamp( y / this.radius, - 1, 1 ) );
  33152. }
  33153. return this;
  33154. }
  33155. } );
  33156. /**
  33157. * @author Mugen87 / https://github.com/Mugen87
  33158. *
  33159. * Ref: https://en.wikipedia.org/wiki/Cylindrical_coordinate_system
  33160. *
  33161. */
  33162. function Cylindrical( radius, theta, y ) {
  33163. this.radius = ( radius !== undefined ) ? radius : 1.0; // distance from the origin to a point in the x-z plane
  33164. this.theta = ( theta !== undefined ) ? theta : 0; // counterclockwise angle in the x-z plane measured in radians from the positive z-axis
  33165. this.y = ( y !== undefined ) ? y : 0; // height above the x-z plane
  33166. return this;
  33167. }
  33168. Object.assign( Cylindrical.prototype, {
  33169. set: function ( radius, theta, y ) {
  33170. this.radius = radius;
  33171. this.theta = theta;
  33172. this.y = y;
  33173. return this;
  33174. },
  33175. clone: function () {
  33176. return new this.constructor().copy( this );
  33177. },
  33178. copy: function ( other ) {
  33179. this.radius = other.radius;
  33180. this.theta = other.theta;
  33181. this.y = other.y;
  33182. return this;
  33183. },
  33184. setFromVector3: function ( v ) {
  33185. return this.setFromCartesianCoords( v.x, v.y, v.z );
  33186. },
  33187. setFromCartesianCoords: function ( x, y, z ) {
  33188. this.radius = Math.sqrt( x * x + z * z );
  33189. this.theta = Math.atan2( x, z );
  33190. this.y = y;
  33191. return this;
  33192. }
  33193. } );
  33194. /**
  33195. * @author bhouston / http://clara.io
  33196. */
  33197. var _vector$7 = new Vector2();
  33198. function Box2( min, max ) {
  33199. this.min = ( min !== undefined ) ? min : new Vector2( + Infinity, + Infinity );
  33200. this.max = ( max !== undefined ) ? max : new Vector2( - Infinity, - Infinity );
  33201. }
  33202. Object.assign( Box2.prototype, {
  33203. set: function ( min, max ) {
  33204. this.min.copy( min );
  33205. this.max.copy( max );
  33206. return this;
  33207. },
  33208. setFromPoints: function ( points ) {
  33209. this.makeEmpty();
  33210. for ( var i = 0, il = points.length; i < il; i ++ ) {
  33211. this.expandByPoint( points[ i ] );
  33212. }
  33213. return this;
  33214. },
  33215. setFromCenterAndSize: function ( center, size ) {
  33216. var halfSize = _vector$7.copy( size ).multiplyScalar( 0.5 );
  33217. this.min.copy( center ).sub( halfSize );
  33218. this.max.copy( center ).add( halfSize );
  33219. return this;
  33220. },
  33221. clone: function () {
  33222. return new this.constructor().copy( this );
  33223. },
  33224. copy: function ( box ) {
  33225. this.min.copy( box.min );
  33226. this.max.copy( box.max );
  33227. return this;
  33228. },
  33229. makeEmpty: function () {
  33230. this.min.x = this.min.y = + Infinity;
  33231. this.max.x = this.max.y = - Infinity;
  33232. return this;
  33233. },
  33234. isEmpty: function () {
  33235. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  33236. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  33237. },
  33238. getCenter: function ( target ) {
  33239. if ( target === undefined ) {
  33240. console.warn( 'THREE.Box2: .getCenter() target is now required' );
  33241. target = new Vector2();
  33242. }
  33243. return this.isEmpty() ? target.set( 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  33244. },
  33245. getSize: function ( target ) {
  33246. if ( target === undefined ) {
  33247. console.warn( 'THREE.Box2: .getSize() target is now required' );
  33248. target = new Vector2();
  33249. }
  33250. return this.isEmpty() ? target.set( 0, 0 ) : target.subVectors( this.max, this.min );
  33251. },
  33252. expandByPoint: function ( point ) {
  33253. this.min.min( point );
  33254. this.max.max( point );
  33255. return this;
  33256. },
  33257. expandByVector: function ( vector ) {
  33258. this.min.sub( vector );
  33259. this.max.add( vector );
  33260. return this;
  33261. },
  33262. expandByScalar: function ( scalar ) {
  33263. this.min.addScalar( - scalar );
  33264. this.max.addScalar( scalar );
  33265. return this;
  33266. },
  33267. containsPoint: function ( point ) {
  33268. return point.x < this.min.x || point.x > this.max.x ||
  33269. point.y < this.min.y || point.y > this.max.y ? false : true;
  33270. },
  33271. containsBox: function ( box ) {
  33272. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  33273. this.min.y <= box.min.y && box.max.y <= this.max.y;
  33274. },
  33275. getParameter: function ( point, target ) {
  33276. // This can potentially have a divide by zero if the box
  33277. // has a size dimension of 0.
  33278. if ( target === undefined ) {
  33279. console.warn( 'THREE.Box2: .getParameter() target is now required' );
  33280. target = new Vector2();
  33281. }
  33282. return target.set(
  33283. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  33284. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  33285. );
  33286. },
  33287. intersectsBox: function ( box ) {
  33288. // using 4 splitting planes to rule out intersections
  33289. return box.max.x < this.min.x || box.min.x > this.max.x ||
  33290. box.max.y < this.min.y || box.min.y > this.max.y ? false : true;
  33291. },
  33292. clampPoint: function ( point, target ) {
  33293. if ( target === undefined ) {
  33294. console.warn( 'THREE.Box2: .clampPoint() target is now required' );
  33295. target = new Vector2();
  33296. }
  33297. return target.copy( point ).clamp( this.min, this.max );
  33298. },
  33299. distanceToPoint: function ( point ) {
  33300. var clampedPoint = _vector$7.copy( point ).clamp( this.min, this.max );
  33301. return clampedPoint.sub( point ).length();
  33302. },
  33303. intersect: function ( box ) {
  33304. this.min.max( box.min );
  33305. this.max.min( box.max );
  33306. return this;
  33307. },
  33308. union: function ( box ) {
  33309. this.min.min( box.min );
  33310. this.max.max( box.max );
  33311. return this;
  33312. },
  33313. translate: function ( offset ) {
  33314. this.min.add( offset );
  33315. this.max.add( offset );
  33316. return this;
  33317. },
  33318. equals: function ( box ) {
  33319. return box.min.equals( this.min ) && box.max.equals( this.max );
  33320. }
  33321. } );
  33322. /**
  33323. * @author bhouston / http://clara.io
  33324. */
  33325. var _startP = new Vector3();
  33326. var _startEnd = new Vector3();
  33327. function Line3( start, end ) {
  33328. this.start = ( start !== undefined ) ? start : new Vector3();
  33329. this.end = ( end !== undefined ) ? end : new Vector3();
  33330. }
  33331. Object.assign( Line3.prototype, {
  33332. set: function ( start, end ) {
  33333. this.start.copy( start );
  33334. this.end.copy( end );
  33335. return this;
  33336. },
  33337. clone: function () {
  33338. return new this.constructor().copy( this );
  33339. },
  33340. copy: function ( line ) {
  33341. this.start.copy( line.start );
  33342. this.end.copy( line.end );
  33343. return this;
  33344. },
  33345. getCenter: function ( target ) {
  33346. if ( target === undefined ) {
  33347. console.warn( 'THREE.Line3: .getCenter() target is now required' );
  33348. target = new Vector3();
  33349. }
  33350. return target.addVectors( this.start, this.end ).multiplyScalar( 0.5 );
  33351. },
  33352. delta: function ( target ) {
  33353. if ( target === undefined ) {
  33354. console.warn( 'THREE.Line3: .delta() target is now required' );
  33355. target = new Vector3();
  33356. }
  33357. return target.subVectors( this.end, this.start );
  33358. },
  33359. distanceSq: function () {
  33360. return this.start.distanceToSquared( this.end );
  33361. },
  33362. distance: function () {
  33363. return this.start.distanceTo( this.end );
  33364. },
  33365. at: function ( t, target ) {
  33366. if ( target === undefined ) {
  33367. console.warn( 'THREE.Line3: .at() target is now required' );
  33368. target = new Vector3();
  33369. }
  33370. return this.delta( target ).multiplyScalar( t ).add( this.start );
  33371. },
  33372. closestPointToPointParameter: function ( point, clampToLine ) {
  33373. _startP.subVectors( point, this.start );
  33374. _startEnd.subVectors( this.end, this.start );
  33375. var startEnd2 = _startEnd.dot( _startEnd );
  33376. var startEnd_startP = _startEnd.dot( _startP );
  33377. var t = startEnd_startP / startEnd2;
  33378. if ( clampToLine ) {
  33379. t = MathUtils.clamp( t, 0, 1 );
  33380. }
  33381. return t;
  33382. },
  33383. closestPointToPoint: function ( point, clampToLine, target ) {
  33384. var t = this.closestPointToPointParameter( point, clampToLine );
  33385. if ( target === undefined ) {
  33386. console.warn( 'THREE.Line3: .closestPointToPoint() target is now required' );
  33387. target = new Vector3();
  33388. }
  33389. return this.delta( target ).multiplyScalar( t ).add( this.start );
  33390. },
  33391. applyMatrix4: function ( matrix ) {
  33392. this.start.applyMatrix4( matrix );
  33393. this.end.applyMatrix4( matrix );
  33394. return this;
  33395. },
  33396. equals: function ( line ) {
  33397. return line.start.equals( this.start ) && line.end.equals( this.end );
  33398. }
  33399. } );
  33400. /**
  33401. * @author alteredq / http://alteredqualia.com/
  33402. */
  33403. function ImmediateRenderObject( material ) {
  33404. Object3D.call( this );
  33405. this.material = material;
  33406. this.render = function ( /* renderCallback */ ) {};
  33407. }
  33408. ImmediateRenderObject.prototype = Object.create( Object3D.prototype );
  33409. ImmediateRenderObject.prototype.constructor = ImmediateRenderObject;
  33410. ImmediateRenderObject.prototype.isImmediateRenderObject = true;
  33411. /**
  33412. * @author alteredq / http://alteredqualia.com/
  33413. * @author mrdoob / http://mrdoob.com/
  33414. * @author WestLangley / http://github.com/WestLangley
  33415. */
  33416. var _vector$8 = new Vector3();
  33417. function SpotLightHelper( light, color ) {
  33418. Object3D.call( this );
  33419. this.light = light;
  33420. this.light.updateMatrixWorld();
  33421. this.matrix = light.matrixWorld;
  33422. this.matrixAutoUpdate = false;
  33423. this.color = color;
  33424. var geometry = new BufferGeometry();
  33425. var positions = [
  33426. 0, 0, 0, 0, 0, 1,
  33427. 0, 0, 0, 1, 0, 1,
  33428. 0, 0, 0, - 1, 0, 1,
  33429. 0, 0, 0, 0, 1, 1,
  33430. 0, 0, 0, 0, - 1, 1
  33431. ];
  33432. for ( var i = 0, j = 1, l = 32; i < l; i ++, j ++ ) {
  33433. var p1 = ( i / l ) * Math.PI * 2;
  33434. var p2 = ( j / l ) * Math.PI * 2;
  33435. positions.push(
  33436. Math.cos( p1 ), Math.sin( p1 ), 1,
  33437. Math.cos( p2 ), Math.sin( p2 ), 1
  33438. );
  33439. }
  33440. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  33441. var material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  33442. this.cone = new LineSegments( geometry, material );
  33443. this.add( this.cone );
  33444. this.update();
  33445. }
  33446. SpotLightHelper.prototype = Object.create( Object3D.prototype );
  33447. SpotLightHelper.prototype.constructor = SpotLightHelper;
  33448. SpotLightHelper.prototype.dispose = function () {
  33449. this.cone.geometry.dispose();
  33450. this.cone.material.dispose();
  33451. };
  33452. SpotLightHelper.prototype.update = function () {
  33453. this.light.updateMatrixWorld();
  33454. var coneLength = this.light.distance ? this.light.distance : 1000;
  33455. var coneWidth = coneLength * Math.tan( this.light.angle );
  33456. this.cone.scale.set( coneWidth, coneWidth, coneLength );
  33457. _vector$8.setFromMatrixPosition( this.light.target.matrixWorld );
  33458. this.cone.lookAt( _vector$8 );
  33459. if ( this.color !== undefined ) {
  33460. this.cone.material.color.set( this.color );
  33461. } else {
  33462. this.cone.material.color.copy( this.light.color );
  33463. }
  33464. };
  33465. /**
  33466. * @author Sean Griffin / http://twitter.com/sgrif
  33467. * @author Michael Guerrero / http://realitymeltdown.com
  33468. * @author mrdoob / http://mrdoob.com/
  33469. * @author ikerr / http://verold.com
  33470. * @author Mugen87 / https://github.com/Mugen87
  33471. */
  33472. var _vector$9 = new Vector3();
  33473. var _boneMatrix = new Matrix4();
  33474. var _matrixWorldInv = new Matrix4();
  33475. function getBoneList( object ) {
  33476. var boneList = [];
  33477. if ( object && object.isBone ) {
  33478. boneList.push( object );
  33479. }
  33480. for ( var i = 0; i < object.children.length; i ++ ) {
  33481. boneList.push.apply( boneList, getBoneList( object.children[ i ] ) );
  33482. }
  33483. return boneList;
  33484. }
  33485. function SkeletonHelper( object ) {
  33486. var bones = getBoneList( object );
  33487. var geometry = new BufferGeometry();
  33488. var vertices = [];
  33489. var colors = [];
  33490. var color1 = new Color( 0, 0, 1 );
  33491. var color2 = new Color( 0, 1, 0 );
  33492. for ( var i = 0; i < bones.length; i ++ ) {
  33493. var bone = bones[ i ];
  33494. if ( bone.parent && bone.parent.isBone ) {
  33495. vertices.push( 0, 0, 0 );
  33496. vertices.push( 0, 0, 0 );
  33497. colors.push( color1.r, color1.g, color1.b );
  33498. colors.push( color2.r, color2.g, color2.b );
  33499. }
  33500. }
  33501. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  33502. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  33503. var material = new LineBasicMaterial( { vertexColors: true, depthTest: false, depthWrite: false, toneMapped: false, transparent: true } );
  33504. LineSegments.call( this, geometry, material );
  33505. this.root = object;
  33506. this.bones = bones;
  33507. this.matrix = object.matrixWorld;
  33508. this.matrixAutoUpdate = false;
  33509. }
  33510. SkeletonHelper.prototype = Object.create( LineSegments.prototype );
  33511. SkeletonHelper.prototype.constructor = SkeletonHelper;
  33512. SkeletonHelper.prototype.isSkeletonHelper = true;
  33513. SkeletonHelper.prototype.updateMatrixWorld = function ( force ) {
  33514. var bones = this.bones;
  33515. var geometry = this.geometry;
  33516. var position = geometry.getAttribute( 'position' );
  33517. _matrixWorldInv.getInverse( this.root.matrixWorld );
  33518. for ( var i = 0, j = 0; i < bones.length; i ++ ) {
  33519. var bone = bones[ i ];
  33520. if ( bone.parent && bone.parent.isBone ) {
  33521. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.matrixWorld );
  33522. _vector$9.setFromMatrixPosition( _boneMatrix );
  33523. position.setXYZ( j, _vector$9.x, _vector$9.y, _vector$9.z );
  33524. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.parent.matrixWorld );
  33525. _vector$9.setFromMatrixPosition( _boneMatrix );
  33526. position.setXYZ( j + 1, _vector$9.x, _vector$9.y, _vector$9.z );
  33527. j += 2;
  33528. }
  33529. }
  33530. geometry.getAttribute( 'position' ).needsUpdate = true;
  33531. Object3D.prototype.updateMatrixWorld.call( this, force );
  33532. };
  33533. /**
  33534. * @author alteredq / http://alteredqualia.com/
  33535. * @author mrdoob / http://mrdoob.com/
  33536. */
  33537. function PointLightHelper( light, sphereSize, color ) {
  33538. this.light = light;
  33539. this.light.updateMatrixWorld();
  33540. this.color = color;
  33541. var geometry = new SphereBufferGeometry( sphereSize, 4, 2 );
  33542. var material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  33543. Mesh.call( this, geometry, material );
  33544. this.matrix = this.light.matrixWorld;
  33545. this.matrixAutoUpdate = false;
  33546. this.update();
  33547. /*
  33548. var distanceGeometry = new THREE.IcosahedronBufferGeometry( 1, 2 );
  33549. var distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  33550. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  33551. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  33552. var d = light.distance;
  33553. if ( d === 0.0 ) {
  33554. this.lightDistance.visible = false;
  33555. } else {
  33556. this.lightDistance.scale.set( d, d, d );
  33557. }
  33558. this.add( this.lightDistance );
  33559. */
  33560. }
  33561. PointLightHelper.prototype = Object.create( Mesh.prototype );
  33562. PointLightHelper.prototype.constructor = PointLightHelper;
  33563. PointLightHelper.prototype.dispose = function () {
  33564. this.geometry.dispose();
  33565. this.material.dispose();
  33566. };
  33567. PointLightHelper.prototype.update = function () {
  33568. if ( this.color !== undefined ) {
  33569. this.material.color.set( this.color );
  33570. } else {
  33571. this.material.color.copy( this.light.color );
  33572. }
  33573. /*
  33574. var d = this.light.distance;
  33575. if ( d === 0.0 ) {
  33576. this.lightDistance.visible = false;
  33577. } else {
  33578. this.lightDistance.visible = true;
  33579. this.lightDistance.scale.set( d, d, d );
  33580. }
  33581. */
  33582. };
  33583. /**
  33584. * @author alteredq / http://alteredqualia.com/
  33585. * @author mrdoob / http://mrdoob.com/
  33586. * @author Mugen87 / https://github.com/Mugen87
  33587. */
  33588. var _vector$a = new Vector3();
  33589. var _color1 = new Color();
  33590. var _color2 = new Color();
  33591. function HemisphereLightHelper( light, size, color ) {
  33592. Object3D.call( this );
  33593. this.light = light;
  33594. this.light.updateMatrixWorld();
  33595. this.matrix = light.matrixWorld;
  33596. this.matrixAutoUpdate = false;
  33597. this.color = color;
  33598. var geometry = new OctahedronBufferGeometry( size );
  33599. geometry.rotateY( Math.PI * 0.5 );
  33600. this.material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  33601. if ( this.color === undefined ) { this.material.vertexColors = true; }
  33602. var position = geometry.getAttribute( 'position' );
  33603. var colors = new Float32Array( position.count * 3 );
  33604. geometry.setAttribute( 'color', new BufferAttribute( colors, 3 ) );
  33605. this.add( new Mesh( geometry, this.material ) );
  33606. this.update();
  33607. }
  33608. HemisphereLightHelper.prototype = Object.create( Object3D.prototype );
  33609. HemisphereLightHelper.prototype.constructor = HemisphereLightHelper;
  33610. HemisphereLightHelper.prototype.dispose = function () {
  33611. this.children[ 0 ].geometry.dispose();
  33612. this.children[ 0 ].material.dispose();
  33613. };
  33614. HemisphereLightHelper.prototype.update = function () {
  33615. var mesh = this.children[ 0 ];
  33616. if ( this.color !== undefined ) {
  33617. this.material.color.set( this.color );
  33618. } else {
  33619. var colors = mesh.geometry.getAttribute( 'color' );
  33620. _color1.copy( this.light.color );
  33621. _color2.copy( this.light.groundColor );
  33622. for ( var i = 0, l = colors.count; i < l; i ++ ) {
  33623. var color = ( i < ( l / 2 ) ) ? _color1 : _color2;
  33624. colors.setXYZ( i, color.r, color.g, color.b );
  33625. }
  33626. colors.needsUpdate = true;
  33627. }
  33628. mesh.lookAt( _vector$a.setFromMatrixPosition( this.light.matrixWorld ).negate() );
  33629. };
  33630. /**
  33631. * @author mrdoob / http://mrdoob.com/
  33632. */
  33633. function GridHelper( size, divisions, color1, color2 ) {
  33634. size = size || 10;
  33635. divisions = divisions || 10;
  33636. color1 = new Color( color1 !== undefined ? color1 : 0x444444 );
  33637. color2 = new Color( color2 !== undefined ? color2 : 0x888888 );
  33638. var center = divisions / 2;
  33639. var step = size / divisions;
  33640. var halfSize = size / 2;
  33641. var vertices = [], colors = [];
  33642. for ( var i = 0, j = 0, k = - halfSize; i <= divisions; i ++, k += step ) {
  33643. vertices.push( - halfSize, 0, k, halfSize, 0, k );
  33644. vertices.push( k, 0, - halfSize, k, 0, halfSize );
  33645. var color = i === center ? color1 : color2;
  33646. color.toArray( colors, j ); j += 3;
  33647. color.toArray( colors, j ); j += 3;
  33648. color.toArray( colors, j ); j += 3;
  33649. color.toArray( colors, j ); j += 3;
  33650. }
  33651. var geometry = new BufferGeometry();
  33652. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  33653. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  33654. var material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  33655. LineSegments.call( this, geometry, material );
  33656. }
  33657. GridHelper.prototype = Object.assign( Object.create( LineSegments.prototype ), {
  33658. constructor: GridHelper,
  33659. copy: function ( source ) {
  33660. LineSegments.prototype.copy.call( this, source );
  33661. this.geometry.copy( source.geometry );
  33662. this.material.copy( source.material );
  33663. return this;
  33664. },
  33665. clone: function () {
  33666. return new this.constructor().copy( this );
  33667. }
  33668. } );
  33669. /**
  33670. * @author mrdoob / http://mrdoob.com/
  33671. * @author Mugen87 / http://github.com/Mugen87
  33672. * @author Hectate / http://www.github.com/Hectate
  33673. */
  33674. function PolarGridHelper( radius, radials, circles, divisions, color1, color2 ) {
  33675. radius = radius || 10;
  33676. radials = radials || 16;
  33677. circles = circles || 8;
  33678. divisions = divisions || 64;
  33679. color1 = new Color( color1 !== undefined ? color1 : 0x444444 );
  33680. color2 = new Color( color2 !== undefined ? color2 : 0x888888 );
  33681. var vertices = [];
  33682. var colors = [];
  33683. var x, z;
  33684. var v, i, j, r, color;
  33685. // create the radials
  33686. for ( i = 0; i <= radials; i ++ ) {
  33687. v = ( i / radials ) * ( Math.PI * 2 );
  33688. x = Math.sin( v ) * radius;
  33689. z = Math.cos( v ) * radius;
  33690. vertices.push( 0, 0, 0 );
  33691. vertices.push( x, 0, z );
  33692. color = ( i & 1 ) ? color1 : color2;
  33693. colors.push( color.r, color.g, color.b );
  33694. colors.push( color.r, color.g, color.b );
  33695. }
  33696. // create the circles
  33697. for ( i = 0; i <= circles; i ++ ) {
  33698. color = ( i & 1 ) ? color1 : color2;
  33699. r = radius - ( radius / circles * i );
  33700. for ( j = 0; j < divisions; j ++ ) {
  33701. // first vertex
  33702. v = ( j / divisions ) * ( Math.PI * 2 );
  33703. x = Math.sin( v ) * r;
  33704. z = Math.cos( v ) * r;
  33705. vertices.push( x, 0, z );
  33706. colors.push( color.r, color.g, color.b );
  33707. // second vertex
  33708. v = ( ( j + 1 ) / divisions ) * ( Math.PI * 2 );
  33709. x = Math.sin( v ) * r;
  33710. z = Math.cos( v ) * r;
  33711. vertices.push( x, 0, z );
  33712. colors.push( color.r, color.g, color.b );
  33713. }
  33714. }
  33715. var geometry = new BufferGeometry();
  33716. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  33717. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  33718. var material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  33719. LineSegments.call( this, geometry, material );
  33720. }
  33721. PolarGridHelper.prototype = Object.create( LineSegments.prototype );
  33722. PolarGridHelper.prototype.constructor = PolarGridHelper;
  33723. /**
  33724. * @author alteredq / http://alteredqualia.com/
  33725. * @author mrdoob / http://mrdoob.com/
  33726. * @author WestLangley / http://github.com/WestLangley
  33727. */
  33728. var _v1$5 = new Vector3();
  33729. var _v2$3 = new Vector3();
  33730. var _v3$1 = new Vector3();
  33731. function DirectionalLightHelper( light, size, color ) {
  33732. Object3D.call( this );
  33733. this.light = light;
  33734. this.light.updateMatrixWorld();
  33735. this.matrix = light.matrixWorld;
  33736. this.matrixAutoUpdate = false;
  33737. this.color = color;
  33738. if ( size === undefined ) { size = 1; }
  33739. var geometry = new BufferGeometry();
  33740. geometry.setAttribute( 'position', new Float32BufferAttribute( [
  33741. - size, size, 0,
  33742. size, size, 0,
  33743. size, - size, 0,
  33744. - size, - size, 0,
  33745. - size, size, 0
  33746. ], 3 ) );
  33747. var material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  33748. this.lightPlane = new Line( geometry, material );
  33749. this.add( this.lightPlane );
  33750. geometry = new BufferGeometry();
  33751. geometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 0, 1 ], 3 ) );
  33752. this.targetLine = new Line( geometry, material );
  33753. this.add( this.targetLine );
  33754. this.update();
  33755. }
  33756. DirectionalLightHelper.prototype = Object.create( Object3D.prototype );
  33757. DirectionalLightHelper.prototype.constructor = DirectionalLightHelper;
  33758. DirectionalLightHelper.prototype.dispose = function () {
  33759. this.lightPlane.geometry.dispose();
  33760. this.lightPlane.material.dispose();
  33761. this.targetLine.geometry.dispose();
  33762. this.targetLine.material.dispose();
  33763. };
  33764. DirectionalLightHelper.prototype.update = function () {
  33765. _v1$5.setFromMatrixPosition( this.light.matrixWorld );
  33766. _v2$3.setFromMatrixPosition( this.light.target.matrixWorld );
  33767. _v3$1.subVectors( _v2$3, _v1$5 );
  33768. this.lightPlane.lookAt( _v2$3 );
  33769. if ( this.color !== undefined ) {
  33770. this.lightPlane.material.color.set( this.color );
  33771. this.targetLine.material.color.set( this.color );
  33772. } else {
  33773. this.lightPlane.material.color.copy( this.light.color );
  33774. this.targetLine.material.color.copy( this.light.color );
  33775. }
  33776. this.targetLine.lookAt( _v2$3 );
  33777. this.targetLine.scale.z = _v3$1.length();
  33778. };
  33779. /**
  33780. * @author alteredq / http://alteredqualia.com/
  33781. * @author Mugen87 / https://github.com/Mugen87
  33782. *
  33783. * - shows frustum, line of sight and up of the camera
  33784. * - suitable for fast updates
  33785. * - based on frustum visualization in lightgl.js shadowmap example
  33786. * http://evanw.github.com/lightgl.js/tests/shadowmap.html
  33787. */
  33788. var _vector$b = new Vector3();
  33789. var _camera = new Camera();
  33790. function CameraHelper( camera ) {
  33791. var geometry = new BufferGeometry();
  33792. var material = new LineBasicMaterial( { color: 0xffffff, vertexColors: true, toneMapped: false } );
  33793. var vertices = [];
  33794. var colors = [];
  33795. var pointMap = {};
  33796. // colors
  33797. var colorFrustum = new Color( 0xffaa00 );
  33798. var colorCone = new Color( 0xff0000 );
  33799. var colorUp = new Color( 0x00aaff );
  33800. var colorTarget = new Color( 0xffffff );
  33801. var colorCross = new Color( 0x333333 );
  33802. // near
  33803. addLine( 'n1', 'n2', colorFrustum );
  33804. addLine( 'n2', 'n4', colorFrustum );
  33805. addLine( 'n4', 'n3', colorFrustum );
  33806. addLine( 'n3', 'n1', colorFrustum );
  33807. // far
  33808. addLine( 'f1', 'f2', colorFrustum );
  33809. addLine( 'f2', 'f4', colorFrustum );
  33810. addLine( 'f4', 'f3', colorFrustum );
  33811. addLine( 'f3', 'f1', colorFrustum );
  33812. // sides
  33813. addLine( 'n1', 'f1', colorFrustum );
  33814. addLine( 'n2', 'f2', colorFrustum );
  33815. addLine( 'n3', 'f3', colorFrustum );
  33816. addLine( 'n4', 'f4', colorFrustum );
  33817. // cone
  33818. addLine( 'p', 'n1', colorCone );
  33819. addLine( 'p', 'n2', colorCone );
  33820. addLine( 'p', 'n3', colorCone );
  33821. addLine( 'p', 'n4', colorCone );
  33822. // up
  33823. addLine( 'u1', 'u2', colorUp );
  33824. addLine( 'u2', 'u3', colorUp );
  33825. addLine( 'u3', 'u1', colorUp );
  33826. // target
  33827. addLine( 'c', 't', colorTarget );
  33828. addLine( 'p', 'c', colorCross );
  33829. // cross
  33830. addLine( 'cn1', 'cn2', colorCross );
  33831. addLine( 'cn3', 'cn4', colorCross );
  33832. addLine( 'cf1', 'cf2', colorCross );
  33833. addLine( 'cf3', 'cf4', colorCross );
  33834. function addLine( a, b, color ) {
  33835. addPoint( a, color );
  33836. addPoint( b, color );
  33837. }
  33838. function addPoint( id, color ) {
  33839. vertices.push( 0, 0, 0 );
  33840. colors.push( color.r, color.g, color.b );
  33841. if ( pointMap[ id ] === undefined ) {
  33842. pointMap[ id ] = [];
  33843. }
  33844. pointMap[ id ].push( ( vertices.length / 3 ) - 1 );
  33845. }
  33846. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  33847. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  33848. LineSegments.call( this, geometry, material );
  33849. this.camera = camera;
  33850. if ( this.camera.updateProjectionMatrix ) { this.camera.updateProjectionMatrix(); }
  33851. this.matrix = camera.matrixWorld;
  33852. this.matrixAutoUpdate = false;
  33853. this.pointMap = pointMap;
  33854. this.update();
  33855. }
  33856. CameraHelper.prototype = Object.create( LineSegments.prototype );
  33857. CameraHelper.prototype.constructor = CameraHelper;
  33858. CameraHelper.prototype.update = function () {
  33859. var geometry = this.geometry;
  33860. var pointMap = this.pointMap;
  33861. var w = 1, h = 1;
  33862. // we need just camera projection matrix inverse
  33863. // world matrix must be identity
  33864. _camera.projectionMatrixInverse.copy( this.camera.projectionMatrixInverse );
  33865. // center / target
  33866. setPoint( 'c', pointMap, geometry, _camera, 0, 0, - 1 );
  33867. setPoint( 't', pointMap, geometry, _camera, 0, 0, 1 );
  33868. // near
  33869. setPoint( 'n1', pointMap, geometry, _camera, - w, - h, - 1 );
  33870. setPoint( 'n2', pointMap, geometry, _camera, w, - h, - 1 );
  33871. setPoint( 'n3', pointMap, geometry, _camera, - w, h, - 1 );
  33872. setPoint( 'n4', pointMap, geometry, _camera, w, h, - 1 );
  33873. // far
  33874. setPoint( 'f1', pointMap, geometry, _camera, - w, - h, 1 );
  33875. setPoint( 'f2', pointMap, geometry, _camera, w, - h, 1 );
  33876. setPoint( 'f3', pointMap, geometry, _camera, - w, h, 1 );
  33877. setPoint( 'f4', pointMap, geometry, _camera, w, h, 1 );
  33878. // up
  33879. setPoint( 'u1', pointMap, geometry, _camera, w * 0.7, h * 1.1, - 1 );
  33880. setPoint( 'u2', pointMap, geometry, _camera, - w * 0.7, h * 1.1, - 1 );
  33881. setPoint( 'u3', pointMap, geometry, _camera, 0, h * 2, - 1 );
  33882. // cross
  33883. setPoint( 'cf1', pointMap, geometry, _camera, - w, 0, 1 );
  33884. setPoint( 'cf2', pointMap, geometry, _camera, w, 0, 1 );
  33885. setPoint( 'cf3', pointMap, geometry, _camera, 0, - h, 1 );
  33886. setPoint( 'cf4', pointMap, geometry, _camera, 0, h, 1 );
  33887. setPoint( 'cn1', pointMap, geometry, _camera, - w, 0, - 1 );
  33888. setPoint( 'cn2', pointMap, geometry, _camera, w, 0, - 1 );
  33889. setPoint( 'cn3', pointMap, geometry, _camera, 0, - h, - 1 );
  33890. setPoint( 'cn4', pointMap, geometry, _camera, 0, h, - 1 );
  33891. geometry.getAttribute( 'position' ).needsUpdate = true;
  33892. };
  33893. function setPoint( point, pointMap, geometry, camera, x, y, z ) {
  33894. _vector$b.set( x, y, z ).unproject( camera );
  33895. var points = pointMap[ point ];
  33896. if ( points !== undefined ) {
  33897. var position = geometry.getAttribute( 'position' );
  33898. for ( var i = 0, l = points.length; i < l; i ++ ) {
  33899. position.setXYZ( points[ i ], _vector$b.x, _vector$b.y, _vector$b.z );
  33900. }
  33901. }
  33902. }
  33903. /**
  33904. * @author mrdoob / http://mrdoob.com/
  33905. * @author Mugen87 / http://github.com/Mugen87
  33906. */
  33907. var _box$3 = new Box3();
  33908. function BoxHelper( object, color ) {
  33909. this.object = object;
  33910. if ( color === undefined ) { color = 0xffff00; }
  33911. 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 ] );
  33912. var positions = new Float32Array( 8 * 3 );
  33913. var geometry = new BufferGeometry();
  33914. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  33915. geometry.setAttribute( 'position', new BufferAttribute( positions, 3 ) );
  33916. LineSegments.call( this, geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  33917. this.matrixAutoUpdate = false;
  33918. this.update();
  33919. }
  33920. BoxHelper.prototype = Object.create( LineSegments.prototype );
  33921. BoxHelper.prototype.constructor = BoxHelper;
  33922. BoxHelper.prototype.update = function ( object ) {
  33923. if ( object !== undefined ) {
  33924. console.warn( 'THREE.BoxHelper: .update() has no longer arguments.' );
  33925. }
  33926. if ( this.object !== undefined ) {
  33927. _box$3.setFromObject( this.object );
  33928. }
  33929. if ( _box$3.isEmpty() ) { return; }
  33930. var min = _box$3.min;
  33931. var max = _box$3.max;
  33932. /*
  33933. 5____4
  33934. 1/___0/|
  33935. | 6__|_7
  33936. 2/___3/
  33937. 0: max.x, max.y, max.z
  33938. 1: min.x, max.y, max.z
  33939. 2: min.x, min.y, max.z
  33940. 3: max.x, min.y, max.z
  33941. 4: max.x, max.y, min.z
  33942. 5: min.x, max.y, min.z
  33943. 6: min.x, min.y, min.z
  33944. 7: max.x, min.y, min.z
  33945. */
  33946. var position = this.geometry.attributes.position;
  33947. var array = position.array;
  33948. array[ 0 ] = max.x; array[ 1 ] = max.y; array[ 2 ] = max.z;
  33949. array[ 3 ] = min.x; array[ 4 ] = max.y; array[ 5 ] = max.z;
  33950. array[ 6 ] = min.x; array[ 7 ] = min.y; array[ 8 ] = max.z;
  33951. array[ 9 ] = max.x; array[ 10 ] = min.y; array[ 11 ] = max.z;
  33952. array[ 12 ] = max.x; array[ 13 ] = max.y; array[ 14 ] = min.z;
  33953. array[ 15 ] = min.x; array[ 16 ] = max.y; array[ 17 ] = min.z;
  33954. array[ 18 ] = min.x; array[ 19 ] = min.y; array[ 20 ] = min.z;
  33955. array[ 21 ] = max.x; array[ 22 ] = min.y; array[ 23 ] = min.z;
  33956. position.needsUpdate = true;
  33957. this.geometry.computeBoundingSphere();
  33958. };
  33959. BoxHelper.prototype.setFromObject = function ( object ) {
  33960. this.object = object;
  33961. this.update();
  33962. return this;
  33963. };
  33964. BoxHelper.prototype.copy = function ( source ) {
  33965. LineSegments.prototype.copy.call( this, source );
  33966. this.object = source.object;
  33967. return this;
  33968. };
  33969. BoxHelper.prototype.clone = function () {
  33970. return new this.constructor().copy( this );
  33971. };
  33972. /**
  33973. * @author WestLangley / http://github.com/WestLangley
  33974. */
  33975. function Box3Helper( box, color ) {
  33976. this.type = 'Box3Helper';
  33977. this.box = box;
  33978. color = color || 0xffff00;
  33979. 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 ] );
  33980. 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 ];
  33981. var geometry = new BufferGeometry();
  33982. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  33983. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  33984. LineSegments.call( this, geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  33985. this.geometry.computeBoundingSphere();
  33986. }
  33987. Box3Helper.prototype = Object.create( LineSegments.prototype );
  33988. Box3Helper.prototype.constructor = Box3Helper;
  33989. Box3Helper.prototype.updateMatrixWorld = function ( force ) {
  33990. var box = this.box;
  33991. if ( box.isEmpty() ) { return; }
  33992. box.getCenter( this.position );
  33993. box.getSize( this.scale );
  33994. this.scale.multiplyScalar( 0.5 );
  33995. Object3D.prototype.updateMatrixWorld.call( this, force );
  33996. };
  33997. /**
  33998. * @author WestLangley / http://github.com/WestLangley
  33999. */
  34000. function PlaneHelper( plane, size, hex ) {
  34001. this.type = 'PlaneHelper';
  34002. this.plane = plane;
  34003. this.size = ( size === undefined ) ? 1 : size;
  34004. var color = ( hex !== undefined ) ? hex : 0xffff00;
  34005. 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 ];
  34006. var geometry = new BufferGeometry();
  34007. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  34008. geometry.computeBoundingSphere();
  34009. Line.call( this, geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  34010. //
  34011. var positions2 = [ 1, 1, 1, - 1, 1, 1, - 1, - 1, 1, 1, 1, 1, - 1, - 1, 1, 1, - 1, 1 ];
  34012. var geometry2 = new BufferGeometry();
  34013. geometry2.setAttribute( 'position', new Float32BufferAttribute( positions2, 3 ) );
  34014. geometry2.computeBoundingSphere();
  34015. this.add( new Mesh( geometry2, new MeshBasicMaterial( { color: color, opacity: 0.2, transparent: true, depthWrite: false, toneMapped: false } ) ) );
  34016. }
  34017. PlaneHelper.prototype = Object.create( Line.prototype );
  34018. PlaneHelper.prototype.constructor = PlaneHelper;
  34019. PlaneHelper.prototype.updateMatrixWorld = function ( force ) {
  34020. var scale = - this.plane.constant;
  34021. if ( Math.abs( scale ) < 1e-8 ) { scale = 1e-8; } // sign does not matter
  34022. this.scale.set( 0.5 * this.size, 0.5 * this.size, scale );
  34023. this.children[ 0 ].material.side = ( scale < 0 ) ? BackSide : FrontSide; // renderer flips side when determinant < 0; flipping not wanted here
  34024. this.lookAt( this.plane.normal );
  34025. Object3D.prototype.updateMatrixWorld.call( this, force );
  34026. };
  34027. /**
  34028. * @author WestLangley / http://github.com/WestLangley
  34029. * @author zz85 / http://github.com/zz85
  34030. * @author bhouston / http://clara.io
  34031. *
  34032. * Creates an arrow for visualizing directions
  34033. *
  34034. * Parameters:
  34035. * dir - Vector3
  34036. * origin - Vector3
  34037. * length - Number
  34038. * color - color in hex value
  34039. * headLength - Number
  34040. * headWidth - Number
  34041. */
  34042. var _axis = new Vector3();
  34043. var _lineGeometry, _coneGeometry;
  34044. function ArrowHelper( dir, origin, length, color, headLength, headWidth ) {
  34045. // dir is assumed to be normalized
  34046. Object3D.call( this );
  34047. if ( dir === undefined ) { dir = new Vector3( 0, 0, 1 ); }
  34048. if ( origin === undefined ) { origin = new Vector3( 0, 0, 0 ); }
  34049. if ( length === undefined ) { length = 1; }
  34050. if ( color === undefined ) { color = 0xffff00; }
  34051. if ( headLength === undefined ) { headLength = 0.2 * length; }
  34052. if ( headWidth === undefined ) { headWidth = 0.2 * headLength; }
  34053. if ( _lineGeometry === undefined ) {
  34054. _lineGeometry = new BufferGeometry();
  34055. _lineGeometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 1, 0 ], 3 ) );
  34056. _coneGeometry = new CylinderBufferGeometry( 0, 0.5, 1, 5, 1 );
  34057. _coneGeometry.translate( 0, - 0.5, 0 );
  34058. }
  34059. this.position.copy( origin );
  34060. this.line = new Line( _lineGeometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  34061. this.line.matrixAutoUpdate = false;
  34062. this.add( this.line );
  34063. this.cone = new Mesh( _coneGeometry, new MeshBasicMaterial( { color: color, toneMapped: false } ) );
  34064. this.cone.matrixAutoUpdate = false;
  34065. this.add( this.cone );
  34066. this.setDirection( dir );
  34067. this.setLength( length, headLength, headWidth );
  34068. }
  34069. ArrowHelper.prototype = Object.create( Object3D.prototype );
  34070. ArrowHelper.prototype.constructor = ArrowHelper;
  34071. ArrowHelper.prototype.setDirection = function ( dir ) {
  34072. // dir is assumed to be normalized
  34073. if ( dir.y > 0.99999 ) {
  34074. this.quaternion.set( 0, 0, 0, 1 );
  34075. } else if ( dir.y < - 0.99999 ) {
  34076. this.quaternion.set( 1, 0, 0, 0 );
  34077. } else {
  34078. _axis.set( dir.z, 0, - dir.x ).normalize();
  34079. var radians = Math.acos( dir.y );
  34080. this.quaternion.setFromAxisAngle( _axis, radians );
  34081. }
  34082. };
  34083. ArrowHelper.prototype.setLength = function ( length, headLength, headWidth ) {
  34084. if ( headLength === undefined ) { headLength = 0.2 * length; }
  34085. if ( headWidth === undefined ) { headWidth = 0.2 * headLength; }
  34086. this.line.scale.set( 1, Math.max( 0.0001, length - headLength ), 1 ); // see #17458
  34087. this.line.updateMatrix();
  34088. this.cone.scale.set( headWidth, headLength, headWidth );
  34089. this.cone.position.y = length;
  34090. this.cone.updateMatrix();
  34091. };
  34092. ArrowHelper.prototype.setColor = function ( color ) {
  34093. this.line.material.color.set( color );
  34094. this.cone.material.color.set( color );
  34095. };
  34096. ArrowHelper.prototype.copy = function ( source ) {
  34097. Object3D.prototype.copy.call( this, source, false );
  34098. this.line.copy( source.line );
  34099. this.cone.copy( source.cone );
  34100. return this;
  34101. };
  34102. ArrowHelper.prototype.clone = function () {
  34103. return new this.constructor().copy( this );
  34104. };
  34105. /**
  34106. * @author sroucheray / http://sroucheray.org/
  34107. * @author mrdoob / http://mrdoob.com/
  34108. */
  34109. function AxesHelper( size ) {
  34110. size = size || 1;
  34111. var vertices = [
  34112. 0, 0, 0, size, 0, 0,
  34113. 0, 0, 0, 0, size, 0,
  34114. 0, 0, 0, 0, 0, size
  34115. ];
  34116. var colors = [
  34117. 1, 0, 0, 1, 0.6, 0,
  34118. 0, 1, 0, 0.6, 1, 0,
  34119. 0, 0, 1, 0, 0.6, 1
  34120. ];
  34121. var geometry = new BufferGeometry();
  34122. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  34123. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  34124. var material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  34125. LineSegments.call( this, geometry, material );
  34126. }
  34127. AxesHelper.prototype = Object.create( LineSegments.prototype );
  34128. AxesHelper.prototype.constructor = AxesHelper;
  34129. /**
  34130. * @author Emmett Lalish / elalish
  34131. *
  34132. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  34133. * (PMREM) from a cubeMap environment texture. This allows different levels of
  34134. * blur to be quickly accessed based on material roughness. It is packed into a
  34135. * special CubeUV format that allows us to perform custom interpolation so that
  34136. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  34137. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  34138. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  34139. * higher roughness levels. In this way we maintain resolution to smoothly
  34140. * interpolate diffuse lighting while limiting sampling computation.
  34141. */
  34142. var LOD_MIN = 4;
  34143. var LOD_MAX = 8;
  34144. var SIZE_MAX = Math.pow( 2, LOD_MAX );
  34145. // The standard deviations (radians) associated with the extra mips. These are
  34146. // chosen to approximate a Trowbridge-Reitz distribution function times the
  34147. // geometric shadowing function. These sigma values squared must match the
  34148. // variance #defines in cube_uv_reflection_fragment.glsl.js.
  34149. var EXTRA_LOD_SIGMA = [ 0.125, 0.215, 0.35, 0.446, 0.526, 0.582 ];
  34150. var TOTAL_LODS = LOD_MAX - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length;
  34151. // The maximum length of the blur for loop. Smaller sigmas will use fewer
  34152. // samples and exit early, but not recompile the shader.
  34153. var MAX_SAMPLES = 20;
  34154. var ENCODINGS = {};
  34155. ENCODINGS[ LinearEncoding ] = 0;
  34156. ENCODINGS[ sRGBEncoding ] = 1;
  34157. ENCODINGS[ RGBEEncoding ] = 2;
  34158. ENCODINGS[ RGBM7Encoding ] = 3;
  34159. ENCODINGS[ RGBM16Encoding ] = 4;
  34160. ENCODINGS[ RGBDEncoding ] = 5;
  34161. ENCODINGS[ GammaEncoding ] = 6;
  34162. var _flatCamera = new OrthographicCamera();
  34163. var _blurMaterial = _getBlurShader( MAX_SAMPLES );
  34164. var _equirectShader = null;
  34165. var _cubemapShader = null;
  34166. var ref = _createPlanes();
  34167. var _lodPlanes = ref._lodPlanes;
  34168. var _sizeLods = ref._sizeLods;
  34169. var _sigmas = ref._sigmas;
  34170. var _pingPongRenderTarget = null;
  34171. var _renderer = null;
  34172. var _oldTarget = null;
  34173. // Golden Ratio
  34174. var PHI = ( 1 + Math.sqrt( 5 ) ) / 2;
  34175. var INV_PHI = 1 / PHI;
  34176. // Vertices of a dodecahedron (except the opposites, which represent the
  34177. // same axis), used as axis directions evenly spread on a sphere.
  34178. var _axisDirections = [
  34179. new Vector3( 1, 1, 1 ),
  34180. new Vector3( - 1, 1, 1 ),
  34181. new Vector3( 1, 1, - 1 ),
  34182. new Vector3( - 1, 1, - 1 ),
  34183. new Vector3( 0, PHI, INV_PHI ),
  34184. new Vector3( 0, PHI, - INV_PHI ),
  34185. new Vector3( INV_PHI, 0, PHI ),
  34186. new Vector3( - INV_PHI, 0, PHI ),
  34187. new Vector3( PHI, INV_PHI, 0 ),
  34188. new Vector3( - PHI, INV_PHI, 0 ) ];
  34189. function PMREMGenerator( renderer ) {
  34190. _renderer = renderer;
  34191. _compileMaterial( _blurMaterial );
  34192. }
  34193. PMREMGenerator.prototype = {
  34194. constructor: PMREMGenerator,
  34195. /**
  34196. * Generates a PMREM from a supplied Scene, which can be faster than using an
  34197. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  34198. * in radians to be applied to the scene before PMREM generation. Optional near
  34199. * and far planes ensure the scene is rendered in its entirety (the cubeCamera
  34200. * is placed at the origin).
  34201. */
  34202. fromScene: function ( scene, sigma, near, far ) {
  34203. if ( sigma === void 0 ) sigma = 0;
  34204. if ( near === void 0 ) near = 0.1;
  34205. if ( far === void 0 ) far = 100;
  34206. _oldTarget = _renderer.getRenderTarget();
  34207. var cubeUVRenderTarget = _allocateTargets();
  34208. _sceneToCubeUV( scene, near, far, cubeUVRenderTarget );
  34209. if ( sigma > 0 ) {
  34210. _blur( cubeUVRenderTarget, 0, 0, sigma );
  34211. }
  34212. _applyPMREM( cubeUVRenderTarget );
  34213. _cleanup( cubeUVRenderTarget );
  34214. return cubeUVRenderTarget;
  34215. },
  34216. /**
  34217. * Generates a PMREM from an equirectangular texture, which can be either LDR
  34218. * (RGBFormat) or HDR (RGBEFormat). The ideal input image size is 1k (1024 x 512),
  34219. * as this matches best with the 256 x 256 cubemap output.
  34220. */
  34221. fromEquirectangular: function ( equirectangular ) {
  34222. equirectangular.magFilter = NearestFilter;
  34223. equirectangular.minFilter = NearestFilter;
  34224. equirectangular.generateMipmaps = false;
  34225. return this.fromCubemap( equirectangular );
  34226. },
  34227. /**
  34228. * Generates a PMREM from an cubemap texture, which can be either LDR
  34229. * (RGBFormat) or HDR (RGBEFormat). The ideal input cube size is 256 x 256,
  34230. * as this matches best with the 256 x 256 cubemap output.
  34231. */
  34232. fromCubemap: function ( cubemap ) {
  34233. _oldTarget = _renderer.getRenderTarget();
  34234. var cubeUVRenderTarget = _allocateTargets( cubemap );
  34235. _textureToCubeUV( cubemap, cubeUVRenderTarget );
  34236. _applyPMREM( cubeUVRenderTarget );
  34237. _cleanup( cubeUVRenderTarget );
  34238. return cubeUVRenderTarget;
  34239. },
  34240. /**
  34241. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  34242. * your texture's network fetch for increased concurrency.
  34243. */
  34244. compileCubemapShader: function () {
  34245. if ( _cubemapShader == null ) {
  34246. _cubemapShader = _getCubemapShader();
  34247. _compileMaterial( _cubemapShader );
  34248. }
  34249. },
  34250. /**
  34251. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  34252. * your texture's network fetch for increased concurrency.
  34253. */
  34254. compileEquirectangularShader: function () {
  34255. if ( _equirectShader == null ) {
  34256. _equirectShader = _getEquirectShader();
  34257. _compileMaterial( _equirectShader );
  34258. }
  34259. },
  34260. /**
  34261. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  34262. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  34263. * one of them will cause any others to also become unusable.
  34264. */
  34265. dispose: function () {
  34266. _blurMaterial.dispose();
  34267. if ( _cubemapShader != null ) { _cubemapShader.dispose(); }
  34268. if ( _equirectShader != null ) { _equirectShader.dispose(); }
  34269. for ( var i = 0; i < _lodPlanes.length; i ++ ) {
  34270. _lodPlanes[ i ].dispose();
  34271. }
  34272. },
  34273. };
  34274. function _createPlanes() {
  34275. var _lodPlanes = [];
  34276. var _sizeLods = [];
  34277. var _sigmas = [];
  34278. var lod = LOD_MAX;
  34279. for ( var i = 0; i < TOTAL_LODS; i ++ ) {
  34280. var sizeLod = Math.pow( 2, lod );
  34281. _sizeLods.push( sizeLod );
  34282. var sigma = 1.0 / sizeLod;
  34283. if ( i > LOD_MAX - LOD_MIN ) {
  34284. sigma = EXTRA_LOD_SIGMA[ i - LOD_MAX + LOD_MIN - 1 ];
  34285. } else if ( i == 0 ) {
  34286. sigma = 0;
  34287. }
  34288. _sigmas.push( sigma );
  34289. var texelSize = 1.0 / ( sizeLod - 1 );
  34290. var min = - texelSize / 2;
  34291. var max = 1 + texelSize / 2;
  34292. var uv1 = [ min, min, max, min, max, max, min, min, max, max, min, max ];
  34293. var cubeFaces = 6;
  34294. var vertices = 6;
  34295. var positionSize = 3;
  34296. var uvSize = 2;
  34297. var faceIndexSize = 1;
  34298. var position = new Float32Array( positionSize * vertices * cubeFaces );
  34299. var uv = new Float32Array( uvSize * vertices * cubeFaces );
  34300. var faceIndex = new Float32Array( faceIndexSize * vertices * cubeFaces );
  34301. for ( var face = 0; face < cubeFaces; face ++ ) {
  34302. var x = ( face % 3 ) * 2 / 3 - 1;
  34303. var y = face > 2 ? 0 : - 1;
  34304. var coordinates = [
  34305. x, y, 0,
  34306. x + 2 / 3, y, 0,
  34307. x + 2 / 3, y + 1, 0,
  34308. x, y, 0,
  34309. x + 2 / 3, y + 1, 0,
  34310. x, y + 1, 0
  34311. ];
  34312. position.set( coordinates, positionSize * vertices * face );
  34313. uv.set( uv1, uvSize * vertices * face );
  34314. var fill = [ face, face, face, face, face, face ];
  34315. faceIndex.set( fill, faceIndexSize * vertices * face );
  34316. }
  34317. var planes = new BufferGeometry();
  34318. planes.setAttribute( 'position', new BufferAttribute( position, positionSize ) );
  34319. planes.setAttribute( 'uv', new BufferAttribute( uv, uvSize ) );
  34320. planes.setAttribute( 'faceIndex', new BufferAttribute( faceIndex, faceIndexSize ) );
  34321. _lodPlanes.push( planes );
  34322. if ( lod > LOD_MIN ) {
  34323. lod --;
  34324. }
  34325. }
  34326. return { _lodPlanes: _lodPlanes, _sizeLods: _sizeLods, _sigmas: _sigmas };
  34327. }
  34328. function _allocateTargets( equirectangular ) {
  34329. var params = {
  34330. magFilter: NearestFilter,
  34331. minFilter: NearestFilter,
  34332. generateMipmaps: false,
  34333. type: equirectangular ? equirectangular.type : UnsignedByteType,
  34334. format: equirectangular ? equirectangular.format : RGBEFormat,
  34335. encoding: equirectangular ? equirectangular.encoding : RGBEEncoding,
  34336. depthBuffer: false,
  34337. stencilBuffer: false
  34338. };
  34339. var cubeUVRenderTarget = _createRenderTarget( params );
  34340. cubeUVRenderTarget.depthBuffer = equirectangular ? false : true;
  34341. _pingPongRenderTarget = _createRenderTarget( params );
  34342. return cubeUVRenderTarget;
  34343. }
  34344. function _cleanup( outputTarget ) {
  34345. _pingPongRenderTarget.dispose();
  34346. _renderer.setRenderTarget( _oldTarget );
  34347. outputTarget.scissorTest = false;
  34348. // reset viewport and scissor
  34349. outputTarget.setSize( outputTarget.width, outputTarget.height );
  34350. }
  34351. function _sceneToCubeUV( scene, near, far, cubeUVRenderTarget ) {
  34352. var fov = 90;
  34353. var aspect = 1;
  34354. var cubeCamera = new PerspectiveCamera( fov, aspect, near, far );
  34355. var upSign = [ 1, 1, 1, 1, - 1, 1 ];
  34356. var forwardSign = [ 1, 1, - 1, - 1, - 1, 1 ];
  34357. var outputEncoding = _renderer.outputEncoding;
  34358. var toneMapping = _renderer.toneMapping;
  34359. var toneMappingExposure = _renderer.toneMappingExposure;
  34360. var clearColor = _renderer.getClearColor();
  34361. var clearAlpha = _renderer.getClearAlpha();
  34362. _renderer.toneMapping = LinearToneMapping;
  34363. _renderer.toneMappingExposure = 1.0;
  34364. _renderer.outputEncoding = LinearEncoding;
  34365. scene.scale.z *= - 1;
  34366. var background = scene.background;
  34367. if ( background && background.isColor ) {
  34368. background.convertSRGBToLinear();
  34369. // Convert linear to RGBE
  34370. var maxComponent = Math.max( background.r, background.g, background.b );
  34371. var fExp = Math.min( Math.max( Math.ceil( Math.log2( maxComponent ) ), - 128.0 ), 127.0 );
  34372. background = background.multiplyScalar( Math.pow( 2.0, - fExp ) );
  34373. var alpha = ( fExp + 128.0 ) / 255.0;
  34374. _renderer.setClearColor( background, alpha );
  34375. scene.background = null;
  34376. }
  34377. for ( var i = 0; i < 6; i ++ ) {
  34378. var col = i % 3;
  34379. if ( col == 0 ) {
  34380. cubeCamera.up.set( 0, upSign[ i ], 0 );
  34381. cubeCamera.lookAt( forwardSign[ i ], 0, 0 );
  34382. } else if ( col == 1 ) {
  34383. cubeCamera.up.set( 0, 0, upSign[ i ] );
  34384. cubeCamera.lookAt( 0, forwardSign[ i ], 0 );
  34385. } else {
  34386. cubeCamera.up.set( 0, upSign[ i ], 0 );
  34387. cubeCamera.lookAt( 0, 0, forwardSign[ i ] );
  34388. }
  34389. _setViewport( cubeUVRenderTarget,
  34390. col * SIZE_MAX, i > 2 ? SIZE_MAX : 0, SIZE_MAX, SIZE_MAX );
  34391. _renderer.setRenderTarget( cubeUVRenderTarget );
  34392. _renderer.render( scene, cubeCamera );
  34393. }
  34394. _renderer.toneMapping = toneMapping;
  34395. _renderer.toneMappingExposure = toneMappingExposure;
  34396. _renderer.outputEncoding = outputEncoding;
  34397. _renderer.setClearColor( clearColor, clearAlpha );
  34398. scene.scale.z *= - 1;
  34399. }
  34400. function _textureToCubeUV( texture, cubeUVRenderTarget ) {
  34401. var scene = new Scene();
  34402. if ( texture.isCubeTexture ) {
  34403. if ( _cubemapShader == null ) {
  34404. _cubemapShader = _getCubemapShader();
  34405. }
  34406. } else {
  34407. if ( _equirectShader == null ) {
  34408. _equirectShader = _getEquirectShader();
  34409. }
  34410. }
  34411. var material = texture.isCubeTexture ? _cubemapShader : _equirectShader;
  34412. scene.add( new Mesh( _lodPlanes[ 0 ], material ) );
  34413. var uniforms = material.uniforms;
  34414. uniforms[ 'envMap' ].value = texture;
  34415. if ( ! texture.isCubeTexture ) {
  34416. uniforms[ 'texelSize' ].value.set( 1.0 / texture.image.width, 1.0 / texture.image.height );
  34417. }
  34418. uniforms[ 'inputEncoding' ].value = ENCODINGS[ texture.encoding ];
  34419. uniforms[ 'outputEncoding' ].value = ENCODINGS[ texture.encoding ];
  34420. _setViewport( cubeUVRenderTarget, 0, 0, 3 * SIZE_MAX, 2 * SIZE_MAX );
  34421. _renderer.setRenderTarget( cubeUVRenderTarget );
  34422. _renderer.render( scene, _flatCamera );
  34423. }
  34424. function _compileMaterial( material ) {
  34425. var tmpScene = new Scene();
  34426. tmpScene.add( new Mesh( _lodPlanes[ 0 ], material ) );
  34427. _renderer.compile( tmpScene, _flatCamera );
  34428. }
  34429. function _createRenderTarget( params ) {
  34430. var cubeUVRenderTarget = new WebGLRenderTarget( 3 * SIZE_MAX, 3 * SIZE_MAX, params );
  34431. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  34432. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  34433. cubeUVRenderTarget.scissorTest = true;
  34434. return cubeUVRenderTarget;
  34435. }
  34436. function _setViewport( target, x, y, width, height ) {
  34437. target.viewport.set( x, y, width, height );
  34438. target.scissor.set( x, y, width, height );
  34439. }
  34440. function _applyPMREM( cubeUVRenderTarget ) {
  34441. var autoClear = _renderer.autoClear;
  34442. _renderer.autoClear = false;
  34443. for ( var i = 1; i < TOTAL_LODS; i ++ ) {
  34444. var sigma = Math.sqrt(
  34445. _sigmas[ i ] * _sigmas[ i ] -
  34446. _sigmas[ i - 1 ] * _sigmas[ i - 1 ] );
  34447. var poleAxis =
  34448. _axisDirections[ ( i - 1 ) % _axisDirections.length ];
  34449. _blur( cubeUVRenderTarget, i - 1, i, sigma, poleAxis );
  34450. }
  34451. _renderer.autoClear = autoClear;
  34452. }
  34453. /**
  34454. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  34455. * vertically and horizontally, but this breaks down on a cube. Here we apply
  34456. * the blur latitudinally (around the poles), and then longitudinally (towards
  34457. * the poles) to approximate the orthogonally-separable blur. It is least
  34458. * accurate at the poles, but still does a decent job.
  34459. */
  34460. function _blur( cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis ) {
  34461. _halfBlur(
  34462. cubeUVRenderTarget,
  34463. _pingPongRenderTarget,
  34464. lodIn,
  34465. lodOut,
  34466. sigma,
  34467. 'latitudinal',
  34468. poleAxis );
  34469. _halfBlur(
  34470. _pingPongRenderTarget,
  34471. cubeUVRenderTarget,
  34472. lodOut,
  34473. lodOut,
  34474. sigma,
  34475. 'longitudinal',
  34476. poleAxis );
  34477. }
  34478. function _halfBlur( targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis ) {
  34479. if ( direction !== 'latitudinal' && direction !== 'longitudinal' ) {
  34480. console.error(
  34481. 'blur direction must be either latitudinal or longitudinal!' );
  34482. }
  34483. // Number of standard deviations at which to cut off the discrete approximation.
  34484. var STANDARD_DEVIATIONS = 3;
  34485. var blurScene = new Scene();
  34486. blurScene.add( new Mesh( _lodPlanes[ lodOut ], _blurMaterial ) );
  34487. var blurUniforms = _blurMaterial.uniforms;
  34488. var pixels = _sizeLods[ lodIn ] - 1;
  34489. var radiansPerPixel = isFinite( sigmaRadians ) ? Math.PI / ( 2 * pixels ) : 2 * Math.PI / ( 2 * MAX_SAMPLES - 1 );
  34490. var sigmaPixels = sigmaRadians / radiansPerPixel;
  34491. var samples = isFinite( sigmaRadians ) ? 1 + Math.floor( STANDARD_DEVIATIONS * sigmaPixels ) : MAX_SAMPLES;
  34492. if ( samples > MAX_SAMPLES ) {
  34493. console.warn( ("sigmaRadians, " + sigmaRadians + ", is too large and will clip, as it requested " + samples + " samples when the maximum is set to " + MAX_SAMPLES) );
  34494. }
  34495. var weights = [];
  34496. var sum = 0;
  34497. for ( var i = 0; i < MAX_SAMPLES; ++ i ) {
  34498. var x = i / sigmaPixels;
  34499. var weight = Math.exp( - x * x / 2 );
  34500. weights.push( weight );
  34501. if ( i == 0 ) {
  34502. sum += weight;
  34503. } else if ( i < samples ) {
  34504. sum += 2 * weight;
  34505. }
  34506. }
  34507. for ( var i = 0; i < weights.length; i ++ ) {
  34508. weights[ i ] = weights[ i ] / sum;
  34509. }
  34510. blurUniforms[ 'envMap' ].value = targetIn.texture;
  34511. blurUniforms[ 'samples' ].value = samples;
  34512. blurUniforms[ 'weights' ].value = weights;
  34513. blurUniforms[ 'latitudinal' ].value = direction === 'latitudinal';
  34514. if ( poleAxis ) {
  34515. blurUniforms[ 'poleAxis' ].value = poleAxis;
  34516. }
  34517. blurUniforms[ 'dTheta' ].value = radiansPerPixel;
  34518. blurUniforms[ 'mipInt' ].value = LOD_MAX - lodIn;
  34519. blurUniforms[ 'inputEncoding' ].value = ENCODINGS[ targetIn.texture.encoding ];
  34520. blurUniforms[ 'outputEncoding' ].value = ENCODINGS[ targetIn.texture.encoding ];
  34521. var outputSize = _sizeLods[ lodOut ];
  34522. var x = 3 * Math.max( 0, SIZE_MAX - 2 * outputSize );
  34523. var y = ( lodOut === 0 ? 0 : 2 * SIZE_MAX ) +
  34524. 2 * outputSize *
  34525. ( lodOut > LOD_MAX - LOD_MIN ? lodOut - LOD_MAX + LOD_MIN : 0 );
  34526. _setViewport( targetOut, x, y, 3 * outputSize, 2 * outputSize );
  34527. _renderer.setRenderTarget( targetOut );
  34528. _renderer.render( blurScene, _flatCamera );
  34529. }
  34530. function _getBlurShader( maxSamples ) {
  34531. var weights = new Float32Array( maxSamples );
  34532. var poleAxis = new Vector3( 0, 1, 0 );
  34533. var shaderMaterial = new RawShaderMaterial( {
  34534. defines: { 'n': maxSamples },
  34535. uniforms: {
  34536. 'envMap': { value: null },
  34537. 'samples': { value: 1 },
  34538. 'weights': { value: weights },
  34539. 'latitudinal': { value: false },
  34540. 'dTheta': { value: 0 },
  34541. 'mipInt': { value: 0 },
  34542. 'poleAxis': { value: poleAxis },
  34543. 'inputEncoding': { value: ENCODINGS[ LinearEncoding ] },
  34544. 'outputEncoding': { value: ENCODINGS[ LinearEncoding ] }
  34545. },
  34546. vertexShader: _getCommonVertexShader(),
  34547. fragmentShader: ("\nprecision mediump float;\nprecision mediump int;\nvarying vec3 vOutputDirection;\nuniform sampler2D envMap;\nuniform int samples;\nuniform float weights[n];\nuniform bool latitudinal;\nuniform float dTheta;\nuniform float mipInt;\nuniform vec3 poleAxis;\n\n" + (_getEncodings()) + "\n\n#define ENVMAP_TYPE_CUBE_UV\n#include <cube_uv_reflection_fragment>\n\nvec3 getSample(float theta, vec3 axis) {\n\tfloat cosTheta = cos(theta);\n\t// Rodrigues' axis-angle rotation\n\tvec3 sampleDirection = vOutputDirection * cosTheta\n\t\t+ cross(axis, vOutputDirection) * sin(theta)\n\t\t+ axis * dot(axis, vOutputDirection) * (1.0 - cosTheta);\n\treturn bilinearCubeUV(envMap, sampleDirection, mipInt);\n}\n\nvoid main() {\n\tvec3 axis = latitudinal ? poleAxis : cross(poleAxis, vOutputDirection);\n\tif (all(equal(axis, vec3(0.0))))\n\t\taxis = vec3(vOutputDirection.z, 0.0, - vOutputDirection.x);\n\taxis = normalize(axis);\n\tgl_FragColor = vec4(0.0);\n\tgl_FragColor.rgb += weights[0] * getSample(0.0, axis);\n\tfor (int i = 1; i < n; i++) {\n\t\tif (i >= samples)\n\t\t\tbreak;\n\t\tfloat theta = dTheta * float(i);\n\t\tgl_FragColor.rgb += weights[i] * getSample(-1.0 * theta, axis);\n\t\tgl_FragColor.rgb += weights[i] * getSample(theta, axis);\n\t}\n\tgl_FragColor = linearToOutputTexel(gl_FragColor);\n}\n\t\t"),
  34548. blending: NoBlending,
  34549. depthTest: false,
  34550. depthWrite: false
  34551. } );
  34552. shaderMaterial.type = 'SphericalGaussianBlur';
  34553. return shaderMaterial;
  34554. }
  34555. function _getEquirectShader() {
  34556. var texelSize = new Vector2( 1, 1 );
  34557. var shaderMaterial = new RawShaderMaterial( {
  34558. uniforms: {
  34559. 'envMap': { value: null },
  34560. 'texelSize': { value: texelSize },
  34561. 'inputEncoding': { value: ENCODINGS[ LinearEncoding ] },
  34562. 'outputEncoding': { value: ENCODINGS[ LinearEncoding ] }
  34563. },
  34564. vertexShader: _getCommonVertexShader(),
  34565. fragmentShader: ("\nprecision mediump float;\nprecision mediump int;\nvarying vec3 vOutputDirection;\nuniform sampler2D envMap;\nuniform vec2 texelSize;\n\n" + (_getEncodings()) + "\n\n#define RECIPROCAL_PI 0.31830988618\n#define RECIPROCAL_PI2 0.15915494\n\nvoid main() {\n\tgl_FragColor = vec4(0.0);\n\tvec3 outputDirection = normalize(vOutputDirection);\n\tvec2 uv;\n\tuv.y = asin(clamp(outputDirection.y, -1.0, 1.0)) * RECIPROCAL_PI + 0.5;\n\tuv.x = atan(outputDirection.z, outputDirection.x) * RECIPROCAL_PI2 + 0.5;\n\tvec2 f = fract(uv / texelSize - 0.5);\n\tuv -= f * texelSize;\n\tvec3 tl = envMapTexelToLinear(texture2D(envMap, uv)).rgb;\n\tuv.x += texelSize.x;\n\tvec3 tr = envMapTexelToLinear(texture2D(envMap, uv)).rgb;\n\tuv.y += texelSize.y;\n\tvec3 br = envMapTexelToLinear(texture2D(envMap, uv)).rgb;\n\tuv.x -= texelSize.x;\n\tvec3 bl = envMapTexelToLinear(texture2D(envMap, uv)).rgb;\n\tvec3 tm = mix(tl, tr, f.x);\n\tvec3 bm = mix(bl, br, f.x);\n\tgl_FragColor.rgb = mix(tm, bm, f.y);\n\tgl_FragColor = linearToOutputTexel(gl_FragColor);\n}\n\t\t"),
  34566. blending: NoBlending,
  34567. depthTest: false,
  34568. depthWrite: false
  34569. } );
  34570. shaderMaterial.type = 'EquirectangularToCubeUV';
  34571. return shaderMaterial;
  34572. }
  34573. function _getCubemapShader() {
  34574. var shaderMaterial = new RawShaderMaterial( {
  34575. uniforms: {
  34576. 'envMap': { value: null },
  34577. 'inputEncoding': { value: ENCODINGS[ LinearEncoding ] },
  34578. 'outputEncoding': { value: ENCODINGS[ LinearEncoding ] }
  34579. },
  34580. vertexShader: _getCommonVertexShader(),
  34581. fragmentShader: ("\nprecision mediump float;\nprecision mediump int;\nvarying vec3 vOutputDirection;\nuniform samplerCube envMap;\n\n" + (_getEncodings()) + "\n\nvoid main() {\n\tgl_FragColor = vec4(0.0);\n\tgl_FragColor.rgb = envMapTexelToLinear(textureCube(envMap, vec3( - vOutputDirection.x, vOutputDirection.yz ))).rgb;\n\tgl_FragColor = linearToOutputTexel(gl_FragColor);\n}\n\t\t"),
  34582. blending: NoBlending,
  34583. depthTest: false,
  34584. depthWrite: false
  34585. } );
  34586. shaderMaterial.type = 'CubemapToCubeUV';
  34587. return shaderMaterial;
  34588. }
  34589. function _getCommonVertexShader() {
  34590. return "\nprecision mediump float;\nprecision mediump int;\nattribute vec3 position;\nattribute vec2 uv;\nattribute float faceIndex;\nvarying vec3 vOutputDirection;\nvec3 getDirection(vec2 uv, float face) {\n\tuv = 2.0 * uv - 1.0;\n\tvec3 direction = vec3(uv, 1.0);\n\tif (face == 0.0) {\n\t\tdirection = direction.zyx;\n\t\tdirection.z *= -1.0;\n\t} else if (face == 1.0) {\n\t\tdirection = direction.xzy;\n\t\tdirection.z *= -1.0;\n\t} else if (face == 3.0) {\n\t\tdirection = direction.zyx;\n\t\tdirection.x *= -1.0;\n\t} else if (face == 4.0) {\n\t\tdirection = direction.xzy;\n\t\tdirection.y *= -1.0;\n\t} else if (face == 5.0) {\n\t\tdirection.xz *= -1.0;\n\t}\n\treturn direction;\n}\nvoid main() {\n\tvOutputDirection = getDirection(uv, faceIndex);\n\tgl_Position = vec4( position, 1.0 );\n}\n\t";
  34591. }
  34592. function _getEncodings() {
  34593. return "\nuniform int inputEncoding;\nuniform int outputEncoding;\n\n#include <encodings_pars_fragment>\n\nvec4 inputTexelToLinear(vec4 value){\n\tif(inputEncoding == 0){\n\t\treturn value;\n\t}else if(inputEncoding == 1){\n\t\treturn sRGBToLinear(value);\n\t}else if(inputEncoding == 2){\n\t\treturn RGBEToLinear(value);\n\t}else if(inputEncoding == 3){\n\t\treturn RGBMToLinear(value, 7.0);\n\t}else if(inputEncoding == 4){\n\t\treturn RGBMToLinear(value, 16.0);\n\t}else if(inputEncoding == 5){\n\t\treturn RGBDToLinear(value, 256.0);\n\t}else{\n\t\treturn GammaToLinear(value, 2.2);\n\t}\n}\n\nvec4 linearToOutputTexel(vec4 value){\n\tif(outputEncoding == 0){\n\t\treturn value;\n\t}else if(outputEncoding == 1){\n\t\treturn LinearTosRGB(value);\n\t}else if(outputEncoding == 2){\n\t\treturn LinearToRGBE(value);\n\t}else if(outputEncoding == 3){\n\t\treturn LinearToRGBM(value, 7.0);\n\t}else if(outputEncoding == 4){\n\t\treturn LinearToRGBM(value, 16.0);\n\t}else if(outputEncoding == 5){\n\t\treturn LinearToRGBD(value, 256.0);\n\t}else{\n\t\treturn LinearToGamma(value, 2.2);\n\t}\n}\n\nvec4 envMapTexelToLinear(vec4 color) {\n\treturn inputTexelToLinear(color);\n}\n\t";
  34594. }
  34595. /**
  34596. * @author mrdoob / http://mrdoob.com/
  34597. */
  34598. function Face4( a, b, c, d, normal, color, materialIndex ) {
  34599. console.warn( 'THREE.Face4 has been removed. A THREE.Face3 will be created instead.' );
  34600. return new Face3( a, b, c, normal, color, materialIndex );
  34601. }
  34602. var LineStrip = 0;
  34603. var LinePieces = 1;
  34604. var NoColors = 0;
  34605. var FaceColors = 1;
  34606. var VertexColors = 2;
  34607. function MeshFaceMaterial( materials ) {
  34608. console.warn( 'THREE.MeshFaceMaterial has been removed. Use an Array instead.' );
  34609. return materials;
  34610. }
  34611. function MultiMaterial( materials ) {
  34612. if ( materials === undefined ) { materials = []; }
  34613. console.warn( 'THREE.MultiMaterial has been removed. Use an Array instead.' );
  34614. materials.isMultiMaterial = true;
  34615. materials.materials = materials;
  34616. materials.clone = function () {
  34617. return materials.slice();
  34618. };
  34619. return materials;
  34620. }
  34621. function PointCloud( geometry, material ) {
  34622. console.warn( 'THREE.PointCloud has been renamed to THREE.Points.' );
  34623. return new Points( geometry, material );
  34624. }
  34625. function Particle( material ) {
  34626. console.warn( 'THREE.Particle has been renamed to THREE.Sprite.' );
  34627. return new Sprite( material );
  34628. }
  34629. function ParticleSystem( geometry, material ) {
  34630. console.warn( 'THREE.ParticleSystem has been renamed to THREE.Points.' );
  34631. return new Points( geometry, material );
  34632. }
  34633. function PointCloudMaterial( parameters ) {
  34634. console.warn( 'THREE.PointCloudMaterial has been renamed to THREE.PointsMaterial.' );
  34635. return new PointsMaterial( parameters );
  34636. }
  34637. function ParticleBasicMaterial( parameters ) {
  34638. console.warn( 'THREE.ParticleBasicMaterial has been renamed to THREE.PointsMaterial.' );
  34639. return new PointsMaterial( parameters );
  34640. }
  34641. function ParticleSystemMaterial( parameters ) {
  34642. console.warn( 'THREE.ParticleSystemMaterial has been renamed to THREE.PointsMaterial.' );
  34643. return new PointsMaterial( parameters );
  34644. }
  34645. function Vertex( x, y, z ) {
  34646. console.warn( 'THREE.Vertex has been removed. Use THREE.Vector3 instead.' );
  34647. return new Vector3( x, y, z );
  34648. }
  34649. //
  34650. function DynamicBufferAttribute( array, itemSize ) {
  34651. console.warn( 'THREE.DynamicBufferAttribute has been removed. Use new THREE.BufferAttribute().setUsage( THREE.DynamicDrawUsage ) instead.' );
  34652. return new BufferAttribute( array, itemSize ).setUsage( DynamicDrawUsage );
  34653. }
  34654. function Int8Attribute( array, itemSize ) {
  34655. console.warn( 'THREE.Int8Attribute has been removed. Use new THREE.Int8BufferAttribute() instead.' );
  34656. return new Int8BufferAttribute( array, itemSize );
  34657. }
  34658. function Uint8Attribute( array, itemSize ) {
  34659. console.warn( 'THREE.Uint8Attribute has been removed. Use new THREE.Uint8BufferAttribute() instead.' );
  34660. return new Uint8BufferAttribute( array, itemSize );
  34661. }
  34662. function Uint8ClampedAttribute( array, itemSize ) {
  34663. console.warn( 'THREE.Uint8ClampedAttribute has been removed. Use new THREE.Uint8ClampedBufferAttribute() instead.' );
  34664. return new Uint8ClampedBufferAttribute( array, itemSize );
  34665. }
  34666. function Int16Attribute( array, itemSize ) {
  34667. console.warn( 'THREE.Int16Attribute has been removed. Use new THREE.Int16BufferAttribute() instead.' );
  34668. return new Int16BufferAttribute( array, itemSize );
  34669. }
  34670. function Uint16Attribute( array, itemSize ) {
  34671. console.warn( 'THREE.Uint16Attribute has been removed. Use new THREE.Uint16BufferAttribute() instead.' );
  34672. return new Uint16BufferAttribute( array, itemSize );
  34673. }
  34674. function Int32Attribute( array, itemSize ) {
  34675. console.warn( 'THREE.Int32Attribute has been removed. Use new THREE.Int32BufferAttribute() instead.' );
  34676. return new Int32BufferAttribute( array, itemSize );
  34677. }
  34678. function Uint32Attribute( array, itemSize ) {
  34679. console.warn( 'THREE.Uint32Attribute has been removed. Use new THREE.Uint32BufferAttribute() instead.' );
  34680. return new Uint32BufferAttribute( array, itemSize );
  34681. }
  34682. function Float32Attribute( array, itemSize ) {
  34683. console.warn( 'THREE.Float32Attribute has been removed. Use new THREE.Float32BufferAttribute() instead.' );
  34684. return new Float32BufferAttribute( array, itemSize );
  34685. }
  34686. function Float64Attribute( array, itemSize ) {
  34687. console.warn( 'THREE.Float64Attribute has been removed. Use new THREE.Float64BufferAttribute() instead.' );
  34688. return new Float64BufferAttribute( array, itemSize );
  34689. }
  34690. //
  34691. Curve.create = function ( construct, getPoint ) {
  34692. console.log( 'THREE.Curve.create() has been deprecated' );
  34693. construct.prototype = Object.create( Curve.prototype );
  34694. construct.prototype.constructor = construct;
  34695. construct.prototype.getPoint = getPoint;
  34696. return construct;
  34697. };
  34698. //
  34699. Object.assign( CurvePath.prototype, {
  34700. createPointsGeometry: function ( divisions ) {
  34701. console.warn( 'THREE.CurvePath: .createPointsGeometry() has been removed. Use new THREE.Geometry().setFromPoints( points ) instead.' );
  34702. // generate geometry from path points (for Line or Points objects)
  34703. var pts = this.getPoints( divisions );
  34704. return this.createGeometry( pts );
  34705. },
  34706. createSpacedPointsGeometry: function ( divisions ) {
  34707. console.warn( 'THREE.CurvePath: .createSpacedPointsGeometry() has been removed. Use new THREE.Geometry().setFromPoints( points ) instead.' );
  34708. // generate geometry from equidistant sampling along the path
  34709. var pts = this.getSpacedPoints( divisions );
  34710. return this.createGeometry( pts );
  34711. },
  34712. createGeometry: function ( points ) {
  34713. console.warn( 'THREE.CurvePath: .createGeometry() has been removed. Use new THREE.Geometry().setFromPoints( points ) instead.' );
  34714. var geometry = new Geometry();
  34715. for ( var i = 0, l = points.length; i < l; i ++ ) {
  34716. var point = points[ i ];
  34717. geometry.vertices.push( new Vector3( point.x, point.y, point.z || 0 ) );
  34718. }
  34719. return geometry;
  34720. }
  34721. } );
  34722. //
  34723. Object.assign( Path.prototype, {
  34724. fromPoints: function ( points ) {
  34725. console.warn( 'THREE.Path: .fromPoints() has been renamed to .setFromPoints().' );
  34726. return this.setFromPoints( points );
  34727. }
  34728. } );
  34729. //
  34730. function ClosedSplineCurve3( points ) {
  34731. console.warn( 'THREE.ClosedSplineCurve3 has been deprecated. Use THREE.CatmullRomCurve3 instead.' );
  34732. CatmullRomCurve3.call( this, points );
  34733. this.type = 'catmullrom';
  34734. this.closed = true;
  34735. }
  34736. ClosedSplineCurve3.prototype = Object.create( CatmullRomCurve3.prototype );
  34737. //
  34738. function SplineCurve3( points ) {
  34739. console.warn( 'THREE.SplineCurve3 has been deprecated. Use THREE.CatmullRomCurve3 instead.' );
  34740. CatmullRomCurve3.call( this, points );
  34741. this.type = 'catmullrom';
  34742. }
  34743. SplineCurve3.prototype = Object.create( CatmullRomCurve3.prototype );
  34744. //
  34745. function Spline( points ) {
  34746. console.warn( 'THREE.Spline has been removed. Use THREE.CatmullRomCurve3 instead.' );
  34747. CatmullRomCurve3.call( this, points );
  34748. this.type = 'catmullrom';
  34749. }
  34750. Spline.prototype = Object.create( CatmullRomCurve3.prototype );
  34751. Object.assign( Spline.prototype, {
  34752. initFromArray: function ( /* a */ ) {
  34753. console.error( 'THREE.Spline: .initFromArray() has been removed.' );
  34754. },
  34755. getControlPointsArray: function ( /* optionalTarget */ ) {
  34756. console.error( 'THREE.Spline: .getControlPointsArray() has been removed.' );
  34757. },
  34758. reparametrizeByArcLength: function ( /* samplingCoef */ ) {
  34759. console.error( 'THREE.Spline: .reparametrizeByArcLength() has been removed.' );
  34760. }
  34761. } );
  34762. //
  34763. function AxisHelper( size ) {
  34764. console.warn( 'THREE.AxisHelper has been renamed to THREE.AxesHelper.' );
  34765. return new AxesHelper( size );
  34766. }
  34767. function BoundingBoxHelper( object, color ) {
  34768. console.warn( 'THREE.BoundingBoxHelper has been deprecated. Creating a THREE.BoxHelper instead.' );
  34769. return new BoxHelper( object, color );
  34770. }
  34771. function EdgesHelper( object, hex ) {
  34772. console.warn( 'THREE.EdgesHelper has been removed. Use THREE.EdgesGeometry instead.' );
  34773. return new LineSegments( new EdgesGeometry( object.geometry ), new LineBasicMaterial( { color: hex !== undefined ? hex : 0xffffff } ) );
  34774. }
  34775. GridHelper.prototype.setColors = function () {
  34776. console.error( 'THREE.GridHelper: setColors() has been deprecated, pass them in the constructor instead.' );
  34777. };
  34778. SkeletonHelper.prototype.update = function () {
  34779. console.error( 'THREE.SkeletonHelper: update() no longer needs to be called.' );
  34780. };
  34781. function WireframeHelper( object, hex ) {
  34782. console.warn( 'THREE.WireframeHelper has been removed. Use THREE.WireframeGeometry instead.' );
  34783. return new LineSegments( new WireframeGeometry( object.geometry ), new LineBasicMaterial( { color: hex !== undefined ? hex : 0xffffff } ) );
  34784. }
  34785. //
  34786. Object.assign( Loader.prototype, {
  34787. extractUrlBase: function ( url ) {
  34788. console.warn( 'THREE.Loader: .extractUrlBase() has been deprecated. Use THREE.LoaderUtils.extractUrlBase() instead.' );
  34789. return LoaderUtils.extractUrlBase( url );
  34790. }
  34791. } );
  34792. Loader.Handlers = {
  34793. add: function ( /* regex, loader */ ) {
  34794. console.error( 'THREE.Loader: Handlers.add() has been removed. Use LoadingManager.addHandler() instead.' );
  34795. },
  34796. get: function ( /* file */ ) {
  34797. console.error( 'THREE.Loader: Handlers.get() has been removed. Use LoadingManager.getHandler() instead.' );
  34798. }
  34799. };
  34800. function XHRLoader( manager ) {
  34801. console.warn( 'THREE.XHRLoader has been renamed to THREE.FileLoader.' );
  34802. return new FileLoader( manager );
  34803. }
  34804. function BinaryTextureLoader( manager ) {
  34805. console.warn( 'THREE.BinaryTextureLoader has been renamed to THREE.DataTextureLoader.' );
  34806. return new DataTextureLoader( manager );
  34807. }
  34808. Object.assign( ObjectLoader.prototype, {
  34809. setTexturePath: function ( value ) {
  34810. console.warn( 'THREE.ObjectLoader: .setTexturePath() has been renamed to .setResourcePath().' );
  34811. return this.setResourcePath( value );
  34812. }
  34813. } );
  34814. //
  34815. Object.assign( Box2.prototype, {
  34816. center: function ( optionalTarget ) {
  34817. console.warn( 'THREE.Box2: .center() has been renamed to .getCenter().' );
  34818. return this.getCenter( optionalTarget );
  34819. },
  34820. empty: function () {
  34821. console.warn( 'THREE.Box2: .empty() has been renamed to .isEmpty().' );
  34822. return this.isEmpty();
  34823. },
  34824. isIntersectionBox: function ( box ) {
  34825. console.warn( 'THREE.Box2: .isIntersectionBox() has been renamed to .intersectsBox().' );
  34826. return this.intersectsBox( box );
  34827. },
  34828. size: function ( optionalTarget ) {
  34829. console.warn( 'THREE.Box2: .size() has been renamed to .getSize().' );
  34830. return this.getSize( optionalTarget );
  34831. }
  34832. } );
  34833. Object.assign( Box3.prototype, {
  34834. center: function ( optionalTarget ) {
  34835. console.warn( 'THREE.Box3: .center() has been renamed to .getCenter().' );
  34836. return this.getCenter( optionalTarget );
  34837. },
  34838. empty: function () {
  34839. console.warn( 'THREE.Box3: .empty() has been renamed to .isEmpty().' );
  34840. return this.isEmpty();
  34841. },
  34842. isIntersectionBox: function ( box ) {
  34843. console.warn( 'THREE.Box3: .isIntersectionBox() has been renamed to .intersectsBox().' );
  34844. return this.intersectsBox( box );
  34845. },
  34846. isIntersectionSphere: function ( sphere ) {
  34847. console.warn( 'THREE.Box3: .isIntersectionSphere() has been renamed to .intersectsSphere().' );
  34848. return this.intersectsSphere( sphere );
  34849. },
  34850. size: function ( optionalTarget ) {
  34851. console.warn( 'THREE.Box3: .size() has been renamed to .getSize().' );
  34852. return this.getSize( optionalTarget );
  34853. }
  34854. } );
  34855. Frustum.prototype.setFromMatrix = function ( m ) {
  34856. console.warn( 'THREE.Frustum: .setFromMatrix() has been renamed to .setFromProjectionMatrix().' );
  34857. return this.setFromProjectionMatrix( m );
  34858. };
  34859. Line3.prototype.center = function ( optionalTarget ) {
  34860. console.warn( 'THREE.Line3: .center() has been renamed to .getCenter().' );
  34861. return this.getCenter( optionalTarget );
  34862. };
  34863. Object.assign( MathUtils, {
  34864. random16: function () {
  34865. console.warn( 'THREE.Math: .random16() has been deprecated. Use Math.random() instead.' );
  34866. return Math.random();
  34867. },
  34868. nearestPowerOfTwo: function ( value ) {
  34869. console.warn( 'THREE.Math: .nearestPowerOfTwo() has been renamed to .floorPowerOfTwo().' );
  34870. return MathUtils.floorPowerOfTwo( value );
  34871. },
  34872. nextPowerOfTwo: function ( value ) {
  34873. console.warn( 'THREE.Math: .nextPowerOfTwo() has been renamed to .ceilPowerOfTwo().' );
  34874. return MathUtils.ceilPowerOfTwo( value );
  34875. }
  34876. } );
  34877. Object.assign( Matrix3.prototype, {
  34878. flattenToArrayOffset: function ( array, offset ) {
  34879. console.warn( "THREE.Matrix3: .flattenToArrayOffset() has been deprecated. Use .toArray() instead." );
  34880. return this.toArray( array, offset );
  34881. },
  34882. multiplyVector3: function ( vector ) {
  34883. console.warn( 'THREE.Matrix3: .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.' );
  34884. return vector.applyMatrix3( this );
  34885. },
  34886. multiplyVector3Array: function ( /* a */ ) {
  34887. console.error( 'THREE.Matrix3: .multiplyVector3Array() has been removed.' );
  34888. },
  34889. applyToBufferAttribute: function ( attribute ) {
  34890. console.warn( 'THREE.Matrix3: .applyToBufferAttribute() has been removed. Use attribute.applyMatrix3( matrix ) instead.' );
  34891. return attribute.applyMatrix3( this );
  34892. },
  34893. applyToVector3Array: function ( /* array, offset, length */ ) {
  34894. console.error( 'THREE.Matrix3: .applyToVector3Array() has been removed.' );
  34895. }
  34896. } );
  34897. Object.assign( Matrix4.prototype, {
  34898. extractPosition: function ( m ) {
  34899. console.warn( 'THREE.Matrix4: .extractPosition() has been renamed to .copyPosition().' );
  34900. return this.copyPosition( m );
  34901. },
  34902. flattenToArrayOffset: function ( array, offset ) {
  34903. console.warn( "THREE.Matrix4: .flattenToArrayOffset() has been deprecated. Use .toArray() instead." );
  34904. return this.toArray( array, offset );
  34905. },
  34906. getPosition: function () {
  34907. console.warn( 'THREE.Matrix4: .getPosition() has been removed. Use Vector3.setFromMatrixPosition( matrix ) instead.' );
  34908. return new Vector3().setFromMatrixColumn( this, 3 );
  34909. },
  34910. setRotationFromQuaternion: function ( q ) {
  34911. console.warn( 'THREE.Matrix4: .setRotationFromQuaternion() has been renamed to .makeRotationFromQuaternion().' );
  34912. return this.makeRotationFromQuaternion( q );
  34913. },
  34914. multiplyToArray: function () {
  34915. console.warn( 'THREE.Matrix4: .multiplyToArray() has been removed.' );
  34916. },
  34917. multiplyVector3: function ( vector ) {
  34918. console.warn( 'THREE.Matrix4: .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  34919. return vector.applyMatrix4( this );
  34920. },
  34921. multiplyVector4: function ( vector ) {
  34922. console.warn( 'THREE.Matrix4: .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  34923. return vector.applyMatrix4( this );
  34924. },
  34925. multiplyVector3Array: function ( /* a */ ) {
  34926. console.error( 'THREE.Matrix4: .multiplyVector3Array() has been removed.' );
  34927. },
  34928. rotateAxis: function ( v ) {
  34929. console.warn( 'THREE.Matrix4: .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead.' );
  34930. v.transformDirection( this );
  34931. },
  34932. crossVector: function ( vector ) {
  34933. console.warn( 'THREE.Matrix4: .crossVector() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  34934. return vector.applyMatrix4( this );
  34935. },
  34936. translate: function () {
  34937. console.error( 'THREE.Matrix4: .translate() has been removed.' );
  34938. },
  34939. rotateX: function () {
  34940. console.error( 'THREE.Matrix4: .rotateX() has been removed.' );
  34941. },
  34942. rotateY: function () {
  34943. console.error( 'THREE.Matrix4: .rotateY() has been removed.' );
  34944. },
  34945. rotateZ: function () {
  34946. console.error( 'THREE.Matrix4: .rotateZ() has been removed.' );
  34947. },
  34948. rotateByAxis: function () {
  34949. console.error( 'THREE.Matrix4: .rotateByAxis() has been removed.' );
  34950. },
  34951. applyToBufferAttribute: function ( attribute ) {
  34952. console.warn( 'THREE.Matrix4: .applyToBufferAttribute() has been removed. Use attribute.applyMatrix4( matrix ) instead.' );
  34953. return attribute.applyMatrix4( this );
  34954. },
  34955. applyToVector3Array: function ( /* array, offset, length */ ) {
  34956. console.error( 'THREE.Matrix4: .applyToVector3Array() has been removed.' );
  34957. },
  34958. makeFrustum: function ( left, right, bottom, top, near, far ) {
  34959. console.warn( 'THREE.Matrix4: .makeFrustum() has been removed. Use .makePerspective( left, right, top, bottom, near, far ) instead.' );
  34960. return this.makePerspective( left, right, top, bottom, near, far );
  34961. }
  34962. } );
  34963. Plane.prototype.isIntersectionLine = function ( line ) {
  34964. console.warn( 'THREE.Plane: .isIntersectionLine() has been renamed to .intersectsLine().' );
  34965. return this.intersectsLine( line );
  34966. };
  34967. Quaternion.prototype.multiplyVector3 = function ( vector ) {
  34968. console.warn( 'THREE.Quaternion: .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.' );
  34969. return vector.applyQuaternion( this );
  34970. };
  34971. Object.assign( Ray.prototype, {
  34972. isIntersectionBox: function ( box ) {
  34973. console.warn( 'THREE.Ray: .isIntersectionBox() has been renamed to .intersectsBox().' );
  34974. return this.intersectsBox( box );
  34975. },
  34976. isIntersectionPlane: function ( plane ) {
  34977. console.warn( 'THREE.Ray: .isIntersectionPlane() has been renamed to .intersectsPlane().' );
  34978. return this.intersectsPlane( plane );
  34979. },
  34980. isIntersectionSphere: function ( sphere ) {
  34981. console.warn( 'THREE.Ray: .isIntersectionSphere() has been renamed to .intersectsSphere().' );
  34982. return this.intersectsSphere( sphere );
  34983. }
  34984. } );
  34985. Object.assign( Triangle.prototype, {
  34986. area: function () {
  34987. console.warn( 'THREE.Triangle: .area() has been renamed to .getArea().' );
  34988. return this.getArea();
  34989. },
  34990. barycoordFromPoint: function ( point, target ) {
  34991. console.warn( 'THREE.Triangle: .barycoordFromPoint() has been renamed to .getBarycoord().' );
  34992. return this.getBarycoord( point, target );
  34993. },
  34994. midpoint: function ( target ) {
  34995. console.warn( 'THREE.Triangle: .midpoint() has been renamed to .getMidpoint().' );
  34996. return this.getMidpoint( target );
  34997. },
  34998. normal: function ( target ) {
  34999. console.warn( 'THREE.Triangle: .normal() has been renamed to .getNormal().' );
  35000. return this.getNormal( target );
  35001. },
  35002. plane: function ( target ) {
  35003. console.warn( 'THREE.Triangle: .plane() has been renamed to .getPlane().' );
  35004. return this.getPlane( target );
  35005. }
  35006. } );
  35007. Object.assign( Triangle, {
  35008. barycoordFromPoint: function ( point, a, b, c, target ) {
  35009. console.warn( 'THREE.Triangle: .barycoordFromPoint() has been renamed to .getBarycoord().' );
  35010. return Triangle.getBarycoord( point, a, b, c, target );
  35011. },
  35012. normal: function ( a, b, c, target ) {
  35013. console.warn( 'THREE.Triangle: .normal() has been renamed to .getNormal().' );
  35014. return Triangle.getNormal( a, b, c, target );
  35015. }
  35016. } );
  35017. Object.assign( Shape.prototype, {
  35018. extractAllPoints: function ( divisions ) {
  35019. console.warn( 'THREE.Shape: .extractAllPoints() has been removed. Use .extractPoints() instead.' );
  35020. return this.extractPoints( divisions );
  35021. },
  35022. extrude: function ( options ) {
  35023. console.warn( 'THREE.Shape: .extrude() has been removed. Use ExtrudeGeometry() instead.' );
  35024. return new ExtrudeGeometry( this, options );
  35025. },
  35026. makeGeometry: function ( options ) {
  35027. console.warn( 'THREE.Shape: .makeGeometry() has been removed. Use ShapeGeometry() instead.' );
  35028. return new ShapeGeometry( this, options );
  35029. }
  35030. } );
  35031. Object.assign( Vector2.prototype, {
  35032. fromAttribute: function ( attribute, index, offset ) {
  35033. console.warn( 'THREE.Vector2: .fromAttribute() has been renamed to .fromBufferAttribute().' );
  35034. return this.fromBufferAttribute( attribute, index, offset );
  35035. },
  35036. distanceToManhattan: function ( v ) {
  35037. console.warn( 'THREE.Vector2: .distanceToManhattan() has been renamed to .manhattanDistanceTo().' );
  35038. return this.manhattanDistanceTo( v );
  35039. },
  35040. lengthManhattan: function () {
  35041. console.warn( 'THREE.Vector2: .lengthManhattan() has been renamed to .manhattanLength().' );
  35042. return this.manhattanLength();
  35043. }
  35044. } );
  35045. Object.assign( Vector3.prototype, {
  35046. setEulerFromRotationMatrix: function () {
  35047. console.error( 'THREE.Vector3: .setEulerFromRotationMatrix() has been removed. Use Euler.setFromRotationMatrix() instead.' );
  35048. },
  35049. setEulerFromQuaternion: function () {
  35050. console.error( 'THREE.Vector3: .setEulerFromQuaternion() has been removed. Use Euler.setFromQuaternion() instead.' );
  35051. },
  35052. getPositionFromMatrix: function ( m ) {
  35053. console.warn( 'THREE.Vector3: .getPositionFromMatrix() has been renamed to .setFromMatrixPosition().' );
  35054. return this.setFromMatrixPosition( m );
  35055. },
  35056. getScaleFromMatrix: function ( m ) {
  35057. console.warn( 'THREE.Vector3: .getScaleFromMatrix() has been renamed to .setFromMatrixScale().' );
  35058. return this.setFromMatrixScale( m );
  35059. },
  35060. getColumnFromMatrix: function ( index, matrix ) {
  35061. console.warn( 'THREE.Vector3: .getColumnFromMatrix() has been renamed to .setFromMatrixColumn().' );
  35062. return this.setFromMatrixColumn( matrix, index );
  35063. },
  35064. applyProjection: function ( m ) {
  35065. console.warn( 'THREE.Vector3: .applyProjection() has been removed. Use .applyMatrix4( m ) instead.' );
  35066. return this.applyMatrix4( m );
  35067. },
  35068. fromAttribute: function ( attribute, index, offset ) {
  35069. console.warn( 'THREE.Vector3: .fromAttribute() has been renamed to .fromBufferAttribute().' );
  35070. return this.fromBufferAttribute( attribute, index, offset );
  35071. },
  35072. distanceToManhattan: function ( v ) {
  35073. console.warn( 'THREE.Vector3: .distanceToManhattan() has been renamed to .manhattanDistanceTo().' );
  35074. return this.manhattanDistanceTo( v );
  35075. },
  35076. lengthManhattan: function () {
  35077. console.warn( 'THREE.Vector3: .lengthManhattan() has been renamed to .manhattanLength().' );
  35078. return this.manhattanLength();
  35079. }
  35080. } );
  35081. Object.assign( Vector4.prototype, {
  35082. fromAttribute: function ( attribute, index, offset ) {
  35083. console.warn( 'THREE.Vector4: .fromAttribute() has been renamed to .fromBufferAttribute().' );
  35084. return this.fromBufferAttribute( attribute, index, offset );
  35085. },
  35086. lengthManhattan: function () {
  35087. console.warn( 'THREE.Vector4: .lengthManhattan() has been renamed to .manhattanLength().' );
  35088. return this.manhattanLength();
  35089. }
  35090. } );
  35091. //
  35092. Object.assign( Geometry.prototype, {
  35093. computeTangents: function () {
  35094. console.error( 'THREE.Geometry: .computeTangents() has been removed.' );
  35095. },
  35096. computeLineDistances: function () {
  35097. console.error( 'THREE.Geometry: .computeLineDistances() has been removed. Use THREE.Line.computeLineDistances() instead.' );
  35098. },
  35099. applyMatrix: function ( matrix ) {
  35100. console.warn( 'THREE.Geometry: .applyMatrix() has been renamed to .applyMatrix4().' );
  35101. return this.applyMatrix4( matrix );
  35102. }
  35103. } );
  35104. Object.assign( Object3D.prototype, {
  35105. getChildByName: function ( name ) {
  35106. console.warn( 'THREE.Object3D: .getChildByName() has been renamed to .getObjectByName().' );
  35107. return this.getObjectByName( name );
  35108. },
  35109. renderDepth: function () {
  35110. console.warn( 'THREE.Object3D: .renderDepth has been removed. Use .renderOrder, instead.' );
  35111. },
  35112. translate: function ( distance, axis ) {
  35113. console.warn( 'THREE.Object3D: .translate() has been removed. Use .translateOnAxis( axis, distance ) instead.' );
  35114. return this.translateOnAxis( axis, distance );
  35115. },
  35116. getWorldRotation: function () {
  35117. console.error( 'THREE.Object3D: .getWorldRotation() has been removed. Use THREE.Object3D.getWorldQuaternion( target ) instead.' );
  35118. },
  35119. applyMatrix: function ( matrix ) {
  35120. console.warn( 'THREE.Object3D: .applyMatrix() has been renamed to .applyMatrix4().' );
  35121. return this.applyMatrix4( matrix );
  35122. }
  35123. } );
  35124. Object.defineProperties( Object3D.prototype, {
  35125. eulerOrder: {
  35126. get: function () {
  35127. console.warn( 'THREE.Object3D: .eulerOrder is now .rotation.order.' );
  35128. return this.rotation.order;
  35129. },
  35130. set: function ( value ) {
  35131. console.warn( 'THREE.Object3D: .eulerOrder is now .rotation.order.' );
  35132. this.rotation.order = value;
  35133. }
  35134. },
  35135. useQuaternion: {
  35136. get: function () {
  35137. console.warn( 'THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.' );
  35138. },
  35139. set: function () {
  35140. console.warn( 'THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.' );
  35141. }
  35142. }
  35143. } );
  35144. Object.assign( Mesh.prototype, {
  35145. setDrawMode: function () {
  35146. console.error( 'THREE.Mesh: .setDrawMode() has been removed. The renderer now always assumes THREE.TrianglesDrawMode. Transform your geometry via BufferGeometryUtils.toTrianglesDrawMode() if necessary.' );
  35147. },
  35148. } );
  35149. Object.defineProperties( Mesh.prototype, {
  35150. drawMode: {
  35151. get: function () {
  35152. console.error( 'THREE.Mesh: .drawMode has been removed. The renderer now always assumes THREE.TrianglesDrawMode.' );
  35153. return TrianglesDrawMode;
  35154. },
  35155. set: function () {
  35156. console.error( 'THREE.Mesh: .drawMode has been removed. The renderer now always assumes THREE.TrianglesDrawMode. Transform your geometry via BufferGeometryUtils.toTrianglesDrawMode() if necessary.' );
  35157. }
  35158. }
  35159. } );
  35160. Object.defineProperties( LOD.prototype, {
  35161. objects: {
  35162. get: function () {
  35163. console.warn( 'THREE.LOD: .objects has been renamed to .levels.' );
  35164. return this.levels;
  35165. }
  35166. }
  35167. } );
  35168. Object.defineProperty( Skeleton.prototype, 'useVertexTexture', {
  35169. get: function () {
  35170. console.warn( 'THREE.Skeleton: useVertexTexture has been removed.' );
  35171. },
  35172. set: function () {
  35173. console.warn( 'THREE.Skeleton: useVertexTexture has been removed.' );
  35174. }
  35175. } );
  35176. SkinnedMesh.prototype.initBones = function () {
  35177. console.error( 'THREE.SkinnedMesh: initBones() has been removed.' );
  35178. };
  35179. Object.defineProperty( Curve.prototype, '__arcLengthDivisions', {
  35180. get: function () {
  35181. console.warn( 'THREE.Curve: .__arcLengthDivisions is now .arcLengthDivisions.' );
  35182. return this.arcLengthDivisions;
  35183. },
  35184. set: function ( value ) {
  35185. console.warn( 'THREE.Curve: .__arcLengthDivisions is now .arcLengthDivisions.' );
  35186. this.arcLengthDivisions = value;
  35187. }
  35188. } );
  35189. //
  35190. PerspectiveCamera.prototype.setLens = function ( focalLength, filmGauge ) {
  35191. console.warn( "THREE.PerspectiveCamera.setLens is deprecated. " +
  35192. "Use .setFocalLength and .filmGauge for a photographic setup." );
  35193. if ( filmGauge !== undefined ) { this.filmGauge = filmGauge; }
  35194. this.setFocalLength( focalLength );
  35195. };
  35196. //
  35197. Object.defineProperties( Light.prototype, {
  35198. onlyShadow: {
  35199. set: function () {
  35200. console.warn( 'THREE.Light: .onlyShadow has been removed.' );
  35201. }
  35202. },
  35203. shadowCameraFov: {
  35204. set: function ( value ) {
  35205. console.warn( 'THREE.Light: .shadowCameraFov is now .shadow.camera.fov.' );
  35206. this.shadow.camera.fov = value;
  35207. }
  35208. },
  35209. shadowCameraLeft: {
  35210. set: function ( value ) {
  35211. console.warn( 'THREE.Light: .shadowCameraLeft is now .shadow.camera.left.' );
  35212. this.shadow.camera.left = value;
  35213. }
  35214. },
  35215. shadowCameraRight: {
  35216. set: function ( value ) {
  35217. console.warn( 'THREE.Light: .shadowCameraRight is now .shadow.camera.right.' );
  35218. this.shadow.camera.right = value;
  35219. }
  35220. },
  35221. shadowCameraTop: {
  35222. set: function ( value ) {
  35223. console.warn( 'THREE.Light: .shadowCameraTop is now .shadow.camera.top.' );
  35224. this.shadow.camera.top = value;
  35225. }
  35226. },
  35227. shadowCameraBottom: {
  35228. set: function ( value ) {
  35229. console.warn( 'THREE.Light: .shadowCameraBottom is now .shadow.camera.bottom.' );
  35230. this.shadow.camera.bottom = value;
  35231. }
  35232. },
  35233. shadowCameraNear: {
  35234. set: function ( value ) {
  35235. console.warn( 'THREE.Light: .shadowCameraNear is now .shadow.camera.near.' );
  35236. this.shadow.camera.near = value;
  35237. }
  35238. },
  35239. shadowCameraFar: {
  35240. set: function ( value ) {
  35241. console.warn( 'THREE.Light: .shadowCameraFar is now .shadow.camera.far.' );
  35242. this.shadow.camera.far = value;
  35243. }
  35244. },
  35245. shadowCameraVisible: {
  35246. set: function () {
  35247. console.warn( 'THREE.Light: .shadowCameraVisible has been removed. Use new THREE.CameraHelper( light.shadow.camera ) instead.' );
  35248. }
  35249. },
  35250. shadowBias: {
  35251. set: function ( value ) {
  35252. console.warn( 'THREE.Light: .shadowBias is now .shadow.bias.' );
  35253. this.shadow.bias = value;
  35254. }
  35255. },
  35256. shadowDarkness: {
  35257. set: function () {
  35258. console.warn( 'THREE.Light: .shadowDarkness has been removed.' );
  35259. }
  35260. },
  35261. shadowMapWidth: {
  35262. set: function ( value ) {
  35263. console.warn( 'THREE.Light: .shadowMapWidth is now .shadow.mapSize.width.' );
  35264. this.shadow.mapSize.width = value;
  35265. }
  35266. },
  35267. shadowMapHeight: {
  35268. set: function ( value ) {
  35269. console.warn( 'THREE.Light: .shadowMapHeight is now .shadow.mapSize.height.' );
  35270. this.shadow.mapSize.height = value;
  35271. }
  35272. }
  35273. } );
  35274. //
  35275. Object.defineProperties( BufferAttribute.prototype, {
  35276. length: {
  35277. get: function () {
  35278. console.warn( 'THREE.BufferAttribute: .length has been deprecated. Use .count instead.' );
  35279. return this.array.length;
  35280. }
  35281. },
  35282. dynamic: {
  35283. get: function () {
  35284. console.warn( 'THREE.BufferAttribute: .dynamic has been deprecated. Use .usage instead.' );
  35285. return this.usage === DynamicDrawUsage;
  35286. },
  35287. set: function ( /* value */ ) {
  35288. console.warn( 'THREE.BufferAttribute: .dynamic has been deprecated. Use .usage instead.' );
  35289. this.setUsage( DynamicDrawUsage );
  35290. }
  35291. }
  35292. } );
  35293. Object.assign( BufferAttribute.prototype, {
  35294. setDynamic: function ( value ) {
  35295. console.warn( 'THREE.BufferAttribute: .setDynamic() has been deprecated. Use .setUsage() instead.' );
  35296. this.setUsage( value === true ? DynamicDrawUsage : StaticDrawUsage );
  35297. return this;
  35298. },
  35299. copyIndicesArray: function ( /* indices */ ) {
  35300. console.error( 'THREE.BufferAttribute: .copyIndicesArray() has been removed.' );
  35301. },
  35302. setArray: function ( /* array */ ) {
  35303. console.error( 'THREE.BufferAttribute: .setArray has been removed. Use BufferGeometry .setAttribute to replace/resize attribute buffers' );
  35304. }
  35305. } );
  35306. Object.assign( BufferGeometry.prototype, {
  35307. addIndex: function ( index ) {
  35308. console.warn( 'THREE.BufferGeometry: .addIndex() has been renamed to .setIndex().' );
  35309. this.setIndex( index );
  35310. },
  35311. addAttribute: function ( name, attribute ) {
  35312. console.warn( 'THREE.BufferGeometry: .addAttribute() has been renamed to .setAttribute().' );
  35313. if ( ! ( attribute && attribute.isBufferAttribute ) && ! ( attribute && attribute.isInterleavedBufferAttribute ) ) {
  35314. console.warn( 'THREE.BufferGeometry: .addAttribute() now expects ( name, attribute ).' );
  35315. return this.setAttribute( name, new BufferAttribute( arguments[ 1 ], arguments[ 2 ] ) );
  35316. }
  35317. if ( name === 'index' ) {
  35318. console.warn( 'THREE.BufferGeometry.addAttribute: Use .setIndex() for index attribute.' );
  35319. this.setIndex( attribute );
  35320. return this;
  35321. }
  35322. return this.setAttribute( name, attribute );
  35323. },
  35324. addDrawCall: function ( start, count, indexOffset ) {
  35325. if ( indexOffset !== undefined ) {
  35326. console.warn( 'THREE.BufferGeometry: .addDrawCall() no longer supports indexOffset.' );
  35327. }
  35328. console.warn( 'THREE.BufferGeometry: .addDrawCall() is now .addGroup().' );
  35329. this.addGroup( start, count );
  35330. },
  35331. clearDrawCalls: function () {
  35332. console.warn( 'THREE.BufferGeometry: .clearDrawCalls() is now .clearGroups().' );
  35333. this.clearGroups();
  35334. },
  35335. computeTangents: function () {
  35336. console.warn( 'THREE.BufferGeometry: .computeTangents() has been removed.' );
  35337. },
  35338. computeOffsets: function () {
  35339. console.warn( 'THREE.BufferGeometry: .computeOffsets() has been removed.' );
  35340. },
  35341. removeAttribute: function ( name ) {
  35342. console.warn( 'THREE.BufferGeometry: .removeAttribute() has been renamed to .deleteAttribute().' );
  35343. return this.deleteAttribute( name );
  35344. },
  35345. applyMatrix: function ( matrix ) {
  35346. console.warn( 'THREE.BufferGeometry: .applyMatrix() has been renamed to .applyMatrix4().' );
  35347. return this.applyMatrix4( matrix );
  35348. }
  35349. } );
  35350. Object.defineProperties( BufferGeometry.prototype, {
  35351. drawcalls: {
  35352. get: function () {
  35353. console.error( 'THREE.BufferGeometry: .drawcalls has been renamed to .groups.' );
  35354. return this.groups;
  35355. }
  35356. },
  35357. offsets: {
  35358. get: function () {
  35359. console.warn( 'THREE.BufferGeometry: .offsets has been renamed to .groups.' );
  35360. return this.groups;
  35361. }
  35362. }
  35363. } );
  35364. Object.defineProperties( Raycaster.prototype, {
  35365. linePrecision: {
  35366. get: function () {
  35367. console.warn( 'THREE.Raycaster: .linePrecision has been deprecated. Use .params.Line.threshold instead.' );
  35368. return this.params.Line.threshold;
  35369. },
  35370. set: function ( value ) {
  35371. console.warn( 'THREE.Raycaster: .linePrecision has been deprecated. Use .params.Line.threshold instead.' );
  35372. this.params.Line.threshold = value;
  35373. }
  35374. }
  35375. } );
  35376. Object.defineProperties( InterleavedBuffer.prototype, {
  35377. dynamic: {
  35378. get: function () {
  35379. console.warn( 'THREE.InterleavedBuffer: .length has been deprecated. Use .usage instead.' );
  35380. return this.usage === DynamicDrawUsage;
  35381. },
  35382. set: function ( value ) {
  35383. console.warn( 'THREE.InterleavedBuffer: .length has been deprecated. Use .usage instead.' );
  35384. this.setUsage( value );
  35385. }
  35386. }
  35387. } );
  35388. Object.assign( InterleavedBuffer.prototype, {
  35389. setDynamic: function ( value ) {
  35390. console.warn( 'THREE.InterleavedBuffer: .setDynamic() has been deprecated. Use .setUsage() instead.' );
  35391. this.setUsage( value === true ? DynamicDrawUsage : StaticDrawUsage );
  35392. return this;
  35393. },
  35394. setArray: function ( /* array */ ) {
  35395. console.error( 'THREE.InterleavedBuffer: .setArray has been removed. Use BufferGeometry .setAttribute to replace/resize attribute buffers' );
  35396. }
  35397. } );
  35398. //
  35399. Object.assign( ExtrudeBufferGeometry.prototype, {
  35400. getArrays: function () {
  35401. console.error( 'THREE.ExtrudeBufferGeometry: .getArrays() has been removed.' );
  35402. },
  35403. addShapeList: function () {
  35404. console.error( 'THREE.ExtrudeBufferGeometry: .addShapeList() has been removed.' );
  35405. },
  35406. addShape: function () {
  35407. console.error( 'THREE.ExtrudeBufferGeometry: .addShape() has been removed.' );
  35408. }
  35409. } );
  35410. //
  35411. Object.defineProperties( Uniform.prototype, {
  35412. dynamic: {
  35413. set: function () {
  35414. console.warn( 'THREE.Uniform: .dynamic has been removed. Use object.onBeforeRender() instead.' );
  35415. }
  35416. },
  35417. onUpdate: {
  35418. value: function () {
  35419. console.warn( 'THREE.Uniform: .onUpdate() has been removed. Use object.onBeforeRender() instead.' );
  35420. return this;
  35421. }
  35422. }
  35423. } );
  35424. //
  35425. Object.defineProperties( Material.prototype, {
  35426. wrapAround: {
  35427. get: function () {
  35428. console.warn( 'THREE.Material: .wrapAround has been removed.' );
  35429. },
  35430. set: function () {
  35431. console.warn( 'THREE.Material: .wrapAround has been removed.' );
  35432. }
  35433. },
  35434. overdraw: {
  35435. get: function () {
  35436. console.warn( 'THREE.Material: .overdraw has been removed.' );
  35437. },
  35438. set: function () {
  35439. console.warn( 'THREE.Material: .overdraw has been removed.' );
  35440. }
  35441. },
  35442. wrapRGB: {
  35443. get: function () {
  35444. console.warn( 'THREE.Material: .wrapRGB has been removed.' );
  35445. return new Color();
  35446. }
  35447. },
  35448. shading: {
  35449. get: function () {
  35450. console.error( 'THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.' );
  35451. },
  35452. set: function ( value ) {
  35453. console.warn( 'THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.' );
  35454. this.flatShading = ( value === FlatShading );
  35455. }
  35456. },
  35457. stencilMask: {
  35458. get: function () {
  35459. console.warn( 'THREE.' + this.type + ': .stencilMask has been removed. Use .stencilFuncMask instead.' );
  35460. return this.stencilFuncMask;
  35461. },
  35462. set: function ( value ) {
  35463. console.warn( 'THREE.' + this.type + ': .stencilMask has been removed. Use .stencilFuncMask instead.' );
  35464. this.stencilFuncMask = value;
  35465. }
  35466. }
  35467. } );
  35468. Object.defineProperties( MeshPhongMaterial.prototype, {
  35469. metal: {
  35470. get: function () {
  35471. console.warn( 'THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead.' );
  35472. return false;
  35473. },
  35474. set: function () {
  35475. console.warn( 'THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead' );
  35476. }
  35477. }
  35478. } );
  35479. Object.defineProperties( ShaderMaterial.prototype, {
  35480. derivatives: {
  35481. get: function () {
  35482. console.warn( 'THREE.ShaderMaterial: .derivatives has been moved to .extensions.derivatives.' );
  35483. return this.extensions.derivatives;
  35484. },
  35485. set: function ( value ) {
  35486. console.warn( 'THREE. ShaderMaterial: .derivatives has been moved to .extensions.derivatives.' );
  35487. this.extensions.derivatives = value;
  35488. }
  35489. }
  35490. } );
  35491. //
  35492. Object.assign( WebGLRenderer.prototype, {
  35493. clearTarget: function ( renderTarget, color, depth, stencil ) {
  35494. console.warn( 'THREE.WebGLRenderer: .clearTarget() has been deprecated. Use .setRenderTarget() and .clear() instead.' );
  35495. this.setRenderTarget( renderTarget );
  35496. this.clear( color, depth, stencil );
  35497. },
  35498. animate: function ( callback ) {
  35499. console.warn( 'THREE.WebGLRenderer: .animate() is now .setAnimationLoop().' );
  35500. this.setAnimationLoop( callback );
  35501. },
  35502. getCurrentRenderTarget: function () {
  35503. console.warn( 'THREE.WebGLRenderer: .getCurrentRenderTarget() is now .getRenderTarget().' );
  35504. return this.getRenderTarget();
  35505. },
  35506. getMaxAnisotropy: function () {
  35507. console.warn( 'THREE.WebGLRenderer: .getMaxAnisotropy() is now .capabilities.getMaxAnisotropy().' );
  35508. return this.capabilities.getMaxAnisotropy();
  35509. },
  35510. getPrecision: function () {
  35511. console.warn( 'THREE.WebGLRenderer: .getPrecision() is now .capabilities.precision.' );
  35512. return this.capabilities.precision;
  35513. },
  35514. resetGLState: function () {
  35515. console.warn( 'THREE.WebGLRenderer: .resetGLState() is now .state.reset().' );
  35516. return this.state.reset();
  35517. },
  35518. supportsFloatTextures: function () {
  35519. console.warn( 'THREE.WebGLRenderer: .supportsFloatTextures() is now .extensions.get( \'OES_texture_float\' ).' );
  35520. return this.extensions.get( 'OES_texture_float' );
  35521. },
  35522. supportsHalfFloatTextures: function () {
  35523. console.warn( 'THREE.WebGLRenderer: .supportsHalfFloatTextures() is now .extensions.get( \'OES_texture_half_float\' ).' );
  35524. return this.extensions.get( 'OES_texture_half_float' );
  35525. },
  35526. supportsStandardDerivatives: function () {
  35527. console.warn( 'THREE.WebGLRenderer: .supportsStandardDerivatives() is now .extensions.get( \'OES_standard_derivatives\' ).' );
  35528. return this.extensions.get( 'OES_standard_derivatives' );
  35529. },
  35530. supportsCompressedTextureS3TC: function () {
  35531. console.warn( 'THREE.WebGLRenderer: .supportsCompressedTextureS3TC() is now .extensions.get( \'WEBGL_compressed_texture_s3tc\' ).' );
  35532. return this.extensions.get( 'WEBGL_compressed_texture_s3tc' );
  35533. },
  35534. supportsCompressedTexturePVRTC: function () {
  35535. console.warn( 'THREE.WebGLRenderer: .supportsCompressedTexturePVRTC() is now .extensions.get( \'WEBGL_compressed_texture_pvrtc\' ).' );
  35536. return this.extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  35537. },
  35538. supportsBlendMinMax: function () {
  35539. console.warn( 'THREE.WebGLRenderer: .supportsBlendMinMax() is now .extensions.get( \'EXT_blend_minmax\' ).' );
  35540. return this.extensions.get( 'EXT_blend_minmax' );
  35541. },
  35542. supportsVertexTextures: function () {
  35543. console.warn( 'THREE.WebGLRenderer: .supportsVertexTextures() is now .capabilities.vertexTextures.' );
  35544. return this.capabilities.vertexTextures;
  35545. },
  35546. supportsInstancedArrays: function () {
  35547. console.warn( 'THREE.WebGLRenderer: .supportsInstancedArrays() is now .extensions.get( \'ANGLE_instanced_arrays\' ).' );
  35548. return this.extensions.get( 'ANGLE_instanced_arrays' );
  35549. },
  35550. enableScissorTest: function ( boolean ) {
  35551. console.warn( 'THREE.WebGLRenderer: .enableScissorTest() is now .setScissorTest().' );
  35552. this.setScissorTest( boolean );
  35553. },
  35554. initMaterial: function () {
  35555. console.warn( 'THREE.WebGLRenderer: .initMaterial() has been removed.' );
  35556. },
  35557. addPrePlugin: function () {
  35558. console.warn( 'THREE.WebGLRenderer: .addPrePlugin() has been removed.' );
  35559. },
  35560. addPostPlugin: function () {
  35561. console.warn( 'THREE.WebGLRenderer: .addPostPlugin() has been removed.' );
  35562. },
  35563. updateShadowMap: function () {
  35564. console.warn( 'THREE.WebGLRenderer: .updateShadowMap() has been removed.' );
  35565. },
  35566. setFaceCulling: function () {
  35567. console.warn( 'THREE.WebGLRenderer: .setFaceCulling() has been removed.' );
  35568. },
  35569. allocTextureUnit: function () {
  35570. console.warn( 'THREE.WebGLRenderer: .allocTextureUnit() has been removed.' );
  35571. },
  35572. setTexture: function () {
  35573. console.warn( 'THREE.WebGLRenderer: .setTexture() has been removed.' );
  35574. },
  35575. setTextureCube: function () {
  35576. console.warn( 'THREE.WebGLRenderer: .setTextureCube() has been removed.' );
  35577. },
  35578. getActiveMipMapLevel: function () {
  35579. console.warn( 'THREE.WebGLRenderer: .getActiveMipMapLevel() is now .getActiveMipmapLevel().' );
  35580. return this.getActiveMipmapLevel();
  35581. }
  35582. } );
  35583. Object.defineProperties( WebGLRenderer.prototype, {
  35584. shadowMapEnabled: {
  35585. get: function () {
  35586. return this.shadowMap.enabled;
  35587. },
  35588. set: function ( value ) {
  35589. console.warn( 'THREE.WebGLRenderer: .shadowMapEnabled is now .shadowMap.enabled.' );
  35590. this.shadowMap.enabled = value;
  35591. }
  35592. },
  35593. shadowMapType: {
  35594. get: function () {
  35595. return this.shadowMap.type;
  35596. },
  35597. set: function ( value ) {
  35598. console.warn( 'THREE.WebGLRenderer: .shadowMapType is now .shadowMap.type.' );
  35599. this.shadowMap.type = value;
  35600. }
  35601. },
  35602. shadowMapCullFace: {
  35603. get: function () {
  35604. console.warn( 'THREE.WebGLRenderer: .shadowMapCullFace has been removed. Set Material.shadowSide instead.' );
  35605. return undefined;
  35606. },
  35607. set: function ( /* value */ ) {
  35608. console.warn( 'THREE.WebGLRenderer: .shadowMapCullFace has been removed. Set Material.shadowSide instead.' );
  35609. }
  35610. },
  35611. context: {
  35612. get: function () {
  35613. console.warn( 'THREE.WebGLRenderer: .context has been removed. Use .getContext() instead.' );
  35614. return this.getContext();
  35615. }
  35616. },
  35617. vr: {
  35618. get: function () {
  35619. console.warn( 'THREE.WebGLRenderer: .vr has been renamed to .xr' );
  35620. return this.xr;
  35621. }
  35622. },
  35623. gammaInput: {
  35624. get: function () {
  35625. console.warn( 'THREE.WebGLRenderer: .gammaInput has been removed. Set the encoding for textures via Texture.encoding instead.' );
  35626. return false;
  35627. },
  35628. set: function () {
  35629. console.warn( 'THREE.WebGLRenderer: .gammaInput has been removed. Set the encoding for textures via Texture.encoding instead.' );
  35630. }
  35631. },
  35632. gammaOutput: {
  35633. get: function () {
  35634. console.warn( 'THREE.WebGLRenderer: .gammaOutput has been removed. Set WebGLRenderer.outputEncoding instead.' );
  35635. return false;
  35636. },
  35637. set: function ( value ) {
  35638. console.warn( 'THREE.WebGLRenderer: .gammaOutput has been removed. Set WebGLRenderer.outputEncoding instead.' );
  35639. this.outputEncoding = ( value === true ) ? sRGBEncoding : LinearEncoding;
  35640. }
  35641. }
  35642. } );
  35643. Object.defineProperties( WebGLShadowMap.prototype, {
  35644. cullFace: {
  35645. get: function () {
  35646. console.warn( 'THREE.WebGLRenderer: .shadowMap.cullFace has been removed. Set Material.shadowSide instead.' );
  35647. return undefined;
  35648. },
  35649. set: function ( /* cullFace */ ) {
  35650. console.warn( 'THREE.WebGLRenderer: .shadowMap.cullFace has been removed. Set Material.shadowSide instead.' );
  35651. }
  35652. },
  35653. renderReverseSided: {
  35654. get: function () {
  35655. console.warn( 'THREE.WebGLRenderer: .shadowMap.renderReverseSided has been removed. Set Material.shadowSide instead.' );
  35656. return undefined;
  35657. },
  35658. set: function () {
  35659. console.warn( 'THREE.WebGLRenderer: .shadowMap.renderReverseSided has been removed. Set Material.shadowSide instead.' );
  35660. }
  35661. },
  35662. renderSingleSided: {
  35663. get: function () {
  35664. console.warn( 'THREE.WebGLRenderer: .shadowMap.renderSingleSided has been removed. Set Material.shadowSide instead.' );
  35665. return undefined;
  35666. },
  35667. set: function () {
  35668. console.warn( 'THREE.WebGLRenderer: .shadowMap.renderSingleSided has been removed. Set Material.shadowSide instead.' );
  35669. }
  35670. }
  35671. } );
  35672. function WebGLRenderTargetCube( width, height, options ) {
  35673. console.warn( 'THREE.WebGLRenderTargetCube( width, height, options ) is now WebGLCubeRenderTarget( size, options ).' );
  35674. return new WebGLCubeRenderTarget( width, options );
  35675. }
  35676. //
  35677. Object.defineProperties( WebGLRenderTarget.prototype, {
  35678. wrapS: {
  35679. get: function () {
  35680. console.warn( 'THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.' );
  35681. return this.texture.wrapS;
  35682. },
  35683. set: function ( value ) {
  35684. console.warn( 'THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.' );
  35685. this.texture.wrapS = value;
  35686. }
  35687. },
  35688. wrapT: {
  35689. get: function () {
  35690. console.warn( 'THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.' );
  35691. return this.texture.wrapT;
  35692. },
  35693. set: function ( value ) {
  35694. console.warn( 'THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.' );
  35695. this.texture.wrapT = value;
  35696. }
  35697. },
  35698. magFilter: {
  35699. get: function () {
  35700. console.warn( 'THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.' );
  35701. return this.texture.magFilter;
  35702. },
  35703. set: function ( value ) {
  35704. console.warn( 'THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.' );
  35705. this.texture.magFilter = value;
  35706. }
  35707. },
  35708. minFilter: {
  35709. get: function () {
  35710. console.warn( 'THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.' );
  35711. return this.texture.minFilter;
  35712. },
  35713. set: function ( value ) {
  35714. console.warn( 'THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.' );
  35715. this.texture.minFilter = value;
  35716. }
  35717. },
  35718. anisotropy: {
  35719. get: function () {
  35720. console.warn( 'THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.' );
  35721. return this.texture.anisotropy;
  35722. },
  35723. set: function ( value ) {
  35724. console.warn( 'THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.' );
  35725. this.texture.anisotropy = value;
  35726. }
  35727. },
  35728. offset: {
  35729. get: function () {
  35730. console.warn( 'THREE.WebGLRenderTarget: .offset is now .texture.offset.' );
  35731. return this.texture.offset;
  35732. },
  35733. set: function ( value ) {
  35734. console.warn( 'THREE.WebGLRenderTarget: .offset is now .texture.offset.' );
  35735. this.texture.offset = value;
  35736. }
  35737. },
  35738. repeat: {
  35739. get: function () {
  35740. console.warn( 'THREE.WebGLRenderTarget: .repeat is now .texture.repeat.' );
  35741. return this.texture.repeat;
  35742. },
  35743. set: function ( value ) {
  35744. console.warn( 'THREE.WebGLRenderTarget: .repeat is now .texture.repeat.' );
  35745. this.texture.repeat = value;
  35746. }
  35747. },
  35748. format: {
  35749. get: function () {
  35750. console.warn( 'THREE.WebGLRenderTarget: .format is now .texture.format.' );
  35751. return this.texture.format;
  35752. },
  35753. set: function ( value ) {
  35754. console.warn( 'THREE.WebGLRenderTarget: .format is now .texture.format.' );
  35755. this.texture.format = value;
  35756. }
  35757. },
  35758. type: {
  35759. get: function () {
  35760. console.warn( 'THREE.WebGLRenderTarget: .type is now .texture.type.' );
  35761. return this.texture.type;
  35762. },
  35763. set: function ( value ) {
  35764. console.warn( 'THREE.WebGLRenderTarget: .type is now .texture.type.' );
  35765. this.texture.type = value;
  35766. }
  35767. },
  35768. generateMipmaps: {
  35769. get: function () {
  35770. console.warn( 'THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.' );
  35771. return this.texture.generateMipmaps;
  35772. },
  35773. set: function ( value ) {
  35774. console.warn( 'THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.' );
  35775. this.texture.generateMipmaps = value;
  35776. }
  35777. }
  35778. } );
  35779. //
  35780. Object.defineProperties( Audio.prototype, {
  35781. load: {
  35782. value: function ( file ) {
  35783. console.warn( 'THREE.Audio: .load has been deprecated. Use THREE.AudioLoader instead.' );
  35784. var scope = this;
  35785. var audioLoader = new AudioLoader();
  35786. audioLoader.load( file, function ( buffer ) {
  35787. scope.setBuffer( buffer );
  35788. } );
  35789. return this;
  35790. }
  35791. },
  35792. startTime: {
  35793. set: function () {
  35794. console.warn( 'THREE.Audio: .startTime is now .play( delay ).' );
  35795. }
  35796. }
  35797. } );
  35798. AudioAnalyser.prototype.getData = function () {
  35799. console.warn( 'THREE.AudioAnalyser: .getData() is now .getFrequencyData().' );
  35800. return this.getFrequencyData();
  35801. };
  35802. //
  35803. CubeCamera.prototype.updateCubeMap = function ( renderer, scene ) {
  35804. console.warn( 'THREE.CubeCamera: .updateCubeMap() is now .update().' );
  35805. return this.update( renderer, scene );
  35806. };
  35807. //
  35808. var GeometryUtils = {
  35809. merge: function ( geometry1, geometry2, materialIndexOffset ) {
  35810. console.warn( 'THREE.GeometryUtils: .merge() has been moved to Geometry. Use geometry.merge( geometry2, matrix, materialIndexOffset ) instead.' );
  35811. var matrix;
  35812. if ( geometry2.isMesh ) {
  35813. geometry2.matrixAutoUpdate && geometry2.updateMatrix();
  35814. matrix = geometry2.matrix;
  35815. geometry2 = geometry2.geometry;
  35816. }
  35817. geometry1.merge( geometry2, matrix, materialIndexOffset );
  35818. },
  35819. center: function ( geometry ) {
  35820. console.warn( 'THREE.GeometryUtils: .center() has been moved to Geometry. Use geometry.center() instead.' );
  35821. return geometry.center();
  35822. }
  35823. };
  35824. ImageUtils.crossOrigin = undefined;
  35825. ImageUtils.loadTexture = function ( url, mapping, onLoad, onError ) {
  35826. console.warn( 'THREE.ImageUtils.loadTexture has been deprecated. Use THREE.TextureLoader() instead.' );
  35827. var loader = new TextureLoader();
  35828. loader.setCrossOrigin( this.crossOrigin );
  35829. var texture = loader.load( url, onLoad, undefined, onError );
  35830. if ( mapping ) { texture.mapping = mapping; }
  35831. return texture;
  35832. };
  35833. ImageUtils.loadTextureCube = function ( urls, mapping, onLoad, onError ) {
  35834. console.warn( 'THREE.ImageUtils.loadTextureCube has been deprecated. Use THREE.CubeTextureLoader() instead.' );
  35835. var loader = new CubeTextureLoader();
  35836. loader.setCrossOrigin( this.crossOrigin );
  35837. var texture = loader.load( urls, onLoad, undefined, onError );
  35838. if ( mapping ) { texture.mapping = mapping; }
  35839. return texture;
  35840. };
  35841. ImageUtils.loadCompressedTexture = function () {
  35842. console.error( 'THREE.ImageUtils.loadCompressedTexture has been removed. Use THREE.DDSLoader instead.' );
  35843. };
  35844. ImageUtils.loadCompressedTextureCube = function () {
  35845. console.error( 'THREE.ImageUtils.loadCompressedTextureCube has been removed. Use THREE.DDSLoader instead.' );
  35846. };
  35847. //
  35848. function CanvasRenderer() {
  35849. console.error( 'THREE.CanvasRenderer has been removed' );
  35850. }
  35851. //
  35852. function JSONLoader() {
  35853. console.error( 'THREE.JSONLoader has been removed.' );
  35854. }
  35855. //
  35856. var SceneUtils = {
  35857. createMultiMaterialObject: function ( /* geometry, materials */ ) {
  35858. console.error( 'THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js' );
  35859. },
  35860. detach: function ( /* child, parent, scene */ ) {
  35861. console.error( 'THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js' );
  35862. },
  35863. attach: function ( /* child, scene, parent */ ) {
  35864. console.error( 'THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js' );
  35865. }
  35866. };
  35867. //
  35868. function LensFlare() {
  35869. console.error( 'THREE.LensFlare has been moved to /examples/jsm/objects/Lensflare.js' );
  35870. }
  35871. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  35872. /* eslint-disable no-undef */
  35873. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'register', { detail: {
  35874. revision: REVISION,
  35875. } } ) );
  35876. /* eslint-enable no-undef */
  35877. }
  35878. exports.ACESFilmicToneMapping = ACESFilmicToneMapping;
  35879. exports.AddEquation = AddEquation;
  35880. exports.AddOperation = AddOperation;
  35881. exports.AdditiveBlending = AdditiveBlending;
  35882. exports.AlphaFormat = AlphaFormat;
  35883. exports.AlwaysDepth = AlwaysDepth;
  35884. exports.AlwaysStencilFunc = AlwaysStencilFunc;
  35885. exports.AmbientLight = AmbientLight;
  35886. exports.AmbientLightProbe = AmbientLightProbe;
  35887. exports.AnimationClip = AnimationClip;
  35888. exports.AnimationLoader = AnimationLoader;
  35889. exports.AnimationMixer = AnimationMixer;
  35890. exports.AnimationObjectGroup = AnimationObjectGroup;
  35891. exports.AnimationUtils = AnimationUtils;
  35892. exports.ArcCurve = ArcCurve;
  35893. exports.ArrayCamera = ArrayCamera;
  35894. exports.ArrowHelper = ArrowHelper;
  35895. exports.Audio = Audio;
  35896. exports.AudioAnalyser = AudioAnalyser;
  35897. exports.AudioContext = AudioContext;
  35898. exports.AudioListener = AudioListener;
  35899. exports.AudioLoader = AudioLoader;
  35900. exports.AxesHelper = AxesHelper;
  35901. exports.AxisHelper = AxisHelper;
  35902. exports.BackSide = BackSide;
  35903. exports.BasicDepthPacking = BasicDepthPacking;
  35904. exports.BasicShadowMap = BasicShadowMap;
  35905. exports.BinaryTextureLoader = BinaryTextureLoader;
  35906. exports.Bone = Bone;
  35907. exports.BooleanKeyframeTrack = BooleanKeyframeTrack;
  35908. exports.BoundingBoxHelper = BoundingBoxHelper;
  35909. exports.Box2 = Box2;
  35910. exports.Box3 = Box3;
  35911. exports.Box3Helper = Box3Helper;
  35912. exports.BoxBufferGeometry = BoxBufferGeometry;
  35913. exports.BoxGeometry = BoxGeometry;
  35914. exports.BoxHelper = BoxHelper;
  35915. exports.BufferAttribute = BufferAttribute;
  35916. exports.BufferGeometry = BufferGeometry;
  35917. exports.BufferGeometryLoader = BufferGeometryLoader;
  35918. exports.ByteType = ByteType;
  35919. exports.Cache = Cache;
  35920. exports.Camera = Camera;
  35921. exports.CameraHelper = CameraHelper;
  35922. exports.CanvasRenderer = CanvasRenderer;
  35923. exports.CanvasTexture = CanvasTexture;
  35924. exports.CatmullRomCurve3 = CatmullRomCurve3;
  35925. exports.CineonToneMapping = CineonToneMapping;
  35926. exports.CircleBufferGeometry = CircleBufferGeometry;
  35927. exports.CircleGeometry = CircleGeometry;
  35928. exports.ClampToEdgeWrapping = ClampToEdgeWrapping;
  35929. exports.Clock = Clock;
  35930. exports.ClosedSplineCurve3 = ClosedSplineCurve3;
  35931. exports.Color = Color;
  35932. exports.ColorKeyframeTrack = ColorKeyframeTrack;
  35933. exports.CompressedTexture = CompressedTexture;
  35934. exports.CompressedTextureLoader = CompressedTextureLoader;
  35935. exports.ConeBufferGeometry = ConeBufferGeometry;
  35936. exports.ConeGeometry = ConeGeometry;
  35937. exports.CubeCamera = CubeCamera;
  35938. exports.CubeGeometry = BoxGeometry;
  35939. exports.CubeReflectionMapping = CubeReflectionMapping;
  35940. exports.CubeRefractionMapping = CubeRefractionMapping;
  35941. exports.CubeTexture = CubeTexture;
  35942. exports.CubeTextureLoader = CubeTextureLoader;
  35943. exports.CubeUVReflectionMapping = CubeUVReflectionMapping;
  35944. exports.CubeUVRefractionMapping = CubeUVRefractionMapping;
  35945. exports.CubicBezierCurve = CubicBezierCurve;
  35946. exports.CubicBezierCurve3 = CubicBezierCurve3;
  35947. exports.CubicInterpolant = CubicInterpolant;
  35948. exports.CullFaceBack = CullFaceBack;
  35949. exports.CullFaceFront = CullFaceFront;
  35950. exports.CullFaceFrontBack = CullFaceFrontBack;
  35951. exports.CullFaceNone = CullFaceNone;
  35952. exports.Curve = Curve;
  35953. exports.CurvePath = CurvePath;
  35954. exports.CustomBlending = CustomBlending;
  35955. exports.CylinderBufferGeometry = CylinderBufferGeometry;
  35956. exports.CylinderGeometry = CylinderGeometry;
  35957. exports.Cylindrical = Cylindrical;
  35958. exports.DataTexture = DataTexture;
  35959. exports.DataTexture2DArray = DataTexture2DArray;
  35960. exports.DataTexture3D = DataTexture3D;
  35961. exports.DataTextureLoader = DataTextureLoader;
  35962. exports.DecrementStencilOp = DecrementStencilOp;
  35963. exports.DecrementWrapStencilOp = DecrementWrapStencilOp;
  35964. exports.DefaultLoadingManager = DefaultLoadingManager;
  35965. exports.DepthFormat = DepthFormat;
  35966. exports.DepthStencilFormat = DepthStencilFormat;
  35967. exports.DepthTexture = DepthTexture;
  35968. exports.DirectionalLight = DirectionalLight;
  35969. exports.DirectionalLightHelper = DirectionalLightHelper;
  35970. exports.DirectionalLightShadow = DirectionalLightShadow;
  35971. exports.DiscreteInterpolant = DiscreteInterpolant;
  35972. exports.DodecahedronBufferGeometry = DodecahedronBufferGeometry;
  35973. exports.DodecahedronGeometry = DodecahedronGeometry;
  35974. exports.DoubleSide = DoubleSide;
  35975. exports.DstAlphaFactor = DstAlphaFactor;
  35976. exports.DstColorFactor = DstColorFactor;
  35977. exports.DynamicBufferAttribute = DynamicBufferAttribute;
  35978. exports.DynamicCopyUsage = DynamicCopyUsage;
  35979. exports.DynamicDrawUsage = DynamicDrawUsage;
  35980. exports.DynamicReadUsage = DynamicReadUsage;
  35981. exports.EdgesGeometry = EdgesGeometry;
  35982. exports.EdgesHelper = EdgesHelper;
  35983. exports.EllipseCurve = EllipseCurve;
  35984. exports.EqualDepth = EqualDepth;
  35985. exports.EqualStencilFunc = EqualStencilFunc;
  35986. exports.EquirectangularReflectionMapping = EquirectangularReflectionMapping;
  35987. exports.EquirectangularRefractionMapping = EquirectangularRefractionMapping;
  35988. exports.Euler = Euler;
  35989. exports.EventDispatcher = EventDispatcher;
  35990. exports.ExtrudeBufferGeometry = ExtrudeBufferGeometry;
  35991. exports.ExtrudeGeometry = ExtrudeGeometry;
  35992. exports.Face3 = Face3;
  35993. exports.Face4 = Face4;
  35994. exports.FaceColors = FaceColors;
  35995. exports.FileLoader = FileLoader;
  35996. exports.FlatShading = FlatShading;
  35997. exports.Float32Attribute = Float32Attribute;
  35998. exports.Float32BufferAttribute = Float32BufferAttribute;
  35999. exports.Float64Attribute = Float64Attribute;
  36000. exports.Float64BufferAttribute = Float64BufferAttribute;
  36001. exports.FloatType = FloatType;
  36002. exports.Fog = Fog;
  36003. exports.FogExp2 = FogExp2;
  36004. exports.Font = Font;
  36005. exports.FontLoader = FontLoader;
  36006. exports.FrontFaceDirectionCCW = FrontFaceDirectionCCW;
  36007. exports.FrontFaceDirectionCW = FrontFaceDirectionCW;
  36008. exports.FrontSide = FrontSide;
  36009. exports.Frustum = Frustum;
  36010. exports.GammaEncoding = GammaEncoding;
  36011. exports.Geometry = Geometry;
  36012. exports.GeometryUtils = GeometryUtils;
  36013. exports.GreaterDepth = GreaterDepth;
  36014. exports.GreaterEqualDepth = GreaterEqualDepth;
  36015. exports.GreaterEqualStencilFunc = GreaterEqualStencilFunc;
  36016. exports.GreaterStencilFunc = GreaterStencilFunc;
  36017. exports.GridHelper = GridHelper;
  36018. exports.Group = Group;
  36019. exports.HalfFloatType = HalfFloatType;
  36020. exports.HemisphereLight = HemisphereLight;
  36021. exports.HemisphereLightHelper = HemisphereLightHelper;
  36022. exports.HemisphereLightProbe = HemisphereLightProbe;
  36023. exports.IcosahedronBufferGeometry = IcosahedronBufferGeometry;
  36024. exports.IcosahedronGeometry = IcosahedronGeometry;
  36025. exports.ImageBitmapLoader = ImageBitmapLoader;
  36026. exports.ImageLoader = ImageLoader;
  36027. exports.ImageUtils = ImageUtils;
  36028. exports.ImmediateRenderObject = ImmediateRenderObject;
  36029. exports.IncrementStencilOp = IncrementStencilOp;
  36030. exports.IncrementWrapStencilOp = IncrementWrapStencilOp;
  36031. exports.InstancedBufferAttribute = InstancedBufferAttribute;
  36032. exports.InstancedBufferGeometry = InstancedBufferGeometry;
  36033. exports.InstancedInterleavedBuffer = InstancedInterleavedBuffer;
  36034. exports.InstancedMesh = InstancedMesh;
  36035. exports.Int16Attribute = Int16Attribute;
  36036. exports.Int16BufferAttribute = Int16BufferAttribute;
  36037. exports.Int32Attribute = Int32Attribute;
  36038. exports.Int32BufferAttribute = Int32BufferAttribute;
  36039. exports.Int8Attribute = Int8Attribute;
  36040. exports.Int8BufferAttribute = Int8BufferAttribute;
  36041. exports.IntType = IntType;
  36042. exports.InterleavedBuffer = InterleavedBuffer;
  36043. exports.InterleavedBufferAttribute = InterleavedBufferAttribute;
  36044. exports.Interpolant = Interpolant;
  36045. exports.InterpolateDiscrete = InterpolateDiscrete;
  36046. exports.InterpolateLinear = InterpolateLinear;
  36047. exports.InterpolateSmooth = InterpolateSmooth;
  36048. exports.InvertStencilOp = InvertStencilOp;
  36049. exports.JSONLoader = JSONLoader;
  36050. exports.KeepStencilOp = KeepStencilOp;
  36051. exports.KeyframeTrack = KeyframeTrack;
  36052. exports.LOD = LOD;
  36053. exports.LatheBufferGeometry = LatheBufferGeometry;
  36054. exports.LatheGeometry = LatheGeometry;
  36055. exports.Layers = Layers;
  36056. exports.LensFlare = LensFlare;
  36057. exports.LessDepth = LessDepth;
  36058. exports.LessEqualDepth = LessEqualDepth;
  36059. exports.LessEqualStencilFunc = LessEqualStencilFunc;
  36060. exports.LessStencilFunc = LessStencilFunc;
  36061. exports.Light = Light;
  36062. exports.LightProbe = LightProbe;
  36063. exports.LightShadow = LightShadow;
  36064. exports.Line = Line;
  36065. exports.Line3 = Line3;
  36066. exports.LineBasicMaterial = LineBasicMaterial;
  36067. exports.LineCurve = LineCurve;
  36068. exports.LineCurve3 = LineCurve3;
  36069. exports.LineDashedMaterial = LineDashedMaterial;
  36070. exports.LineLoop = LineLoop;
  36071. exports.LinePieces = LinePieces;
  36072. exports.LineSegments = LineSegments;
  36073. exports.LineStrip = LineStrip;
  36074. exports.LinearEncoding = LinearEncoding;
  36075. exports.LinearFilter = LinearFilter;
  36076. exports.LinearInterpolant = LinearInterpolant;
  36077. exports.LinearMipMapLinearFilter = LinearMipMapLinearFilter;
  36078. exports.LinearMipMapNearestFilter = LinearMipMapNearestFilter;
  36079. exports.LinearMipmapLinearFilter = LinearMipmapLinearFilter;
  36080. exports.LinearMipmapNearestFilter = LinearMipmapNearestFilter;
  36081. exports.LinearToneMapping = LinearToneMapping;
  36082. exports.Loader = Loader;
  36083. exports.LoaderUtils = LoaderUtils;
  36084. exports.LoadingManager = LoadingManager;
  36085. exports.LogLuvEncoding = LogLuvEncoding;
  36086. exports.LoopOnce = LoopOnce;
  36087. exports.LoopPingPong = LoopPingPong;
  36088. exports.LoopRepeat = LoopRepeat;
  36089. exports.LuminanceAlphaFormat = LuminanceAlphaFormat;
  36090. exports.LuminanceFormat = LuminanceFormat;
  36091. exports.MOUSE = MOUSE;
  36092. exports.Material = Material;
  36093. exports.MaterialLoader = MaterialLoader;
  36094. exports.Math = MathUtils;
  36095. exports.MathUtils = MathUtils;
  36096. exports.Matrix3 = Matrix3;
  36097. exports.Matrix4 = Matrix4;
  36098. exports.MaxEquation = MaxEquation;
  36099. exports.Mesh = Mesh;
  36100. exports.MeshBasicMaterial = MeshBasicMaterial;
  36101. exports.MeshDepthMaterial = MeshDepthMaterial;
  36102. exports.MeshDistanceMaterial = MeshDistanceMaterial;
  36103. exports.MeshFaceMaterial = MeshFaceMaterial;
  36104. exports.MeshLambertMaterial = MeshLambertMaterial;
  36105. exports.MeshMatcapMaterial = MeshMatcapMaterial;
  36106. exports.MeshNormalMaterial = MeshNormalMaterial;
  36107. exports.MeshPhongMaterial = MeshPhongMaterial;
  36108. exports.MeshPhysicalMaterial = MeshPhysicalMaterial;
  36109. exports.MeshStandardMaterial = MeshStandardMaterial;
  36110. exports.MeshToonMaterial = MeshToonMaterial;
  36111. exports.MinEquation = MinEquation;
  36112. exports.MirroredRepeatWrapping = MirroredRepeatWrapping;
  36113. exports.MixOperation = MixOperation;
  36114. exports.MultiMaterial = MultiMaterial;
  36115. exports.MultiplyBlending = MultiplyBlending;
  36116. exports.MultiplyOperation = MultiplyOperation;
  36117. exports.NearestFilter = NearestFilter;
  36118. exports.NearestMipMapLinearFilter = NearestMipMapLinearFilter;
  36119. exports.NearestMipMapNearestFilter = NearestMipMapNearestFilter;
  36120. exports.NearestMipmapLinearFilter = NearestMipmapLinearFilter;
  36121. exports.NearestMipmapNearestFilter = NearestMipmapNearestFilter;
  36122. exports.NeverDepth = NeverDepth;
  36123. exports.NeverStencilFunc = NeverStencilFunc;
  36124. exports.NoBlending = NoBlending;
  36125. exports.NoColors = NoColors;
  36126. exports.NoToneMapping = NoToneMapping;
  36127. exports.NormalBlending = NormalBlending;
  36128. exports.NotEqualDepth = NotEqualDepth;
  36129. exports.NotEqualStencilFunc = NotEqualStencilFunc;
  36130. exports.NumberKeyframeTrack = NumberKeyframeTrack;
  36131. exports.Object3D = Object3D;
  36132. exports.ObjectLoader = ObjectLoader;
  36133. exports.ObjectSpaceNormalMap = ObjectSpaceNormalMap;
  36134. exports.OctahedronBufferGeometry = OctahedronBufferGeometry;
  36135. exports.OctahedronGeometry = OctahedronGeometry;
  36136. exports.OneFactor = OneFactor;
  36137. exports.OneMinusDstAlphaFactor = OneMinusDstAlphaFactor;
  36138. exports.OneMinusDstColorFactor = OneMinusDstColorFactor;
  36139. exports.OneMinusSrcAlphaFactor = OneMinusSrcAlphaFactor;
  36140. exports.OneMinusSrcColorFactor = OneMinusSrcColorFactor;
  36141. exports.OrthographicCamera = OrthographicCamera;
  36142. exports.PCFShadowMap = PCFShadowMap;
  36143. exports.PCFSoftShadowMap = PCFSoftShadowMap;
  36144. exports.PMREMGenerator = PMREMGenerator;
  36145. exports.ParametricBufferGeometry = ParametricBufferGeometry;
  36146. exports.ParametricGeometry = ParametricGeometry;
  36147. exports.Particle = Particle;
  36148. exports.ParticleBasicMaterial = ParticleBasicMaterial;
  36149. exports.ParticleSystem = ParticleSystem;
  36150. exports.ParticleSystemMaterial = ParticleSystemMaterial;
  36151. exports.Path = Path;
  36152. exports.PerspectiveCamera = PerspectiveCamera;
  36153. exports.Plane = Plane;
  36154. exports.PlaneBufferGeometry = PlaneBufferGeometry;
  36155. exports.PlaneGeometry = PlaneGeometry;
  36156. exports.PlaneHelper = PlaneHelper;
  36157. exports.PointCloud = PointCloud;
  36158. exports.PointCloudMaterial = PointCloudMaterial;
  36159. exports.PointLight = PointLight;
  36160. exports.PointLightHelper = PointLightHelper;
  36161. exports.Points = Points;
  36162. exports.PointsMaterial = PointsMaterial;
  36163. exports.PolarGridHelper = PolarGridHelper;
  36164. exports.PolyhedronBufferGeometry = PolyhedronBufferGeometry;
  36165. exports.PolyhedronGeometry = PolyhedronGeometry;
  36166. exports.PositionalAudio = PositionalAudio;
  36167. exports.PropertyBinding = PropertyBinding;
  36168. exports.PropertyMixer = PropertyMixer;
  36169. exports.QuadraticBezierCurve = QuadraticBezierCurve;
  36170. exports.QuadraticBezierCurve3 = QuadraticBezierCurve3;
  36171. exports.Quaternion = Quaternion;
  36172. exports.QuaternionKeyframeTrack = QuaternionKeyframeTrack;
  36173. exports.QuaternionLinearInterpolant = QuaternionLinearInterpolant;
  36174. exports.REVISION = REVISION;
  36175. exports.RGBADepthPacking = RGBADepthPacking;
  36176. exports.RGBAFormat = RGBAFormat;
  36177. exports.RGBAIntegerFormat = RGBAIntegerFormat;
  36178. exports.RGBA_ASTC_10x10_Format = RGBA_ASTC_10x10_Format;
  36179. exports.RGBA_ASTC_10x5_Format = RGBA_ASTC_10x5_Format;
  36180. exports.RGBA_ASTC_10x6_Format = RGBA_ASTC_10x6_Format;
  36181. exports.RGBA_ASTC_10x8_Format = RGBA_ASTC_10x8_Format;
  36182. exports.RGBA_ASTC_12x10_Format = RGBA_ASTC_12x10_Format;
  36183. exports.RGBA_ASTC_12x12_Format = RGBA_ASTC_12x12_Format;
  36184. exports.RGBA_ASTC_4x4_Format = RGBA_ASTC_4x4_Format;
  36185. exports.RGBA_ASTC_5x4_Format = RGBA_ASTC_5x4_Format;
  36186. exports.RGBA_ASTC_5x5_Format = RGBA_ASTC_5x5_Format;
  36187. exports.RGBA_ASTC_6x5_Format = RGBA_ASTC_6x5_Format;
  36188. exports.RGBA_ASTC_6x6_Format = RGBA_ASTC_6x6_Format;
  36189. exports.RGBA_ASTC_8x5_Format = RGBA_ASTC_8x5_Format;
  36190. exports.RGBA_ASTC_8x6_Format = RGBA_ASTC_8x6_Format;
  36191. exports.RGBA_ASTC_8x8_Format = RGBA_ASTC_8x8_Format;
  36192. exports.RGBA_BPTC_Format = RGBA_BPTC_Format;
  36193. exports.RGBA_ETC2_EAC_Format = RGBA_ETC2_EAC_Format;
  36194. exports.RGBA_PVRTC_2BPPV1_Format = RGBA_PVRTC_2BPPV1_Format;
  36195. exports.RGBA_PVRTC_4BPPV1_Format = RGBA_PVRTC_4BPPV1_Format;
  36196. exports.RGBA_S3TC_DXT1_Format = RGBA_S3TC_DXT1_Format;
  36197. exports.RGBA_S3TC_DXT3_Format = RGBA_S3TC_DXT3_Format;
  36198. exports.RGBA_S3TC_DXT5_Format = RGBA_S3TC_DXT5_Format;
  36199. exports.RGBDEncoding = RGBDEncoding;
  36200. exports.RGBEEncoding = RGBEEncoding;
  36201. exports.RGBEFormat = RGBEFormat;
  36202. exports.RGBFormat = RGBFormat;
  36203. exports.RGBIntegerFormat = RGBIntegerFormat;
  36204. exports.RGBM16Encoding = RGBM16Encoding;
  36205. exports.RGBM7Encoding = RGBM7Encoding;
  36206. exports.RGB_ETC1_Format = RGB_ETC1_Format;
  36207. exports.RGB_ETC2_Format = RGB_ETC2_Format;
  36208. exports.RGB_PVRTC_2BPPV1_Format = RGB_PVRTC_2BPPV1_Format;
  36209. exports.RGB_PVRTC_4BPPV1_Format = RGB_PVRTC_4BPPV1_Format;
  36210. exports.RGB_S3TC_DXT1_Format = RGB_S3TC_DXT1_Format;
  36211. exports.RGFormat = RGFormat;
  36212. exports.RGIntegerFormat = RGIntegerFormat;
  36213. exports.RawShaderMaterial = RawShaderMaterial;
  36214. exports.Ray = Ray;
  36215. exports.Raycaster = Raycaster;
  36216. exports.RectAreaLight = RectAreaLight;
  36217. exports.RedFormat = RedFormat;
  36218. exports.RedIntegerFormat = RedIntegerFormat;
  36219. exports.ReinhardToneMapping = ReinhardToneMapping;
  36220. exports.RepeatWrapping = RepeatWrapping;
  36221. exports.ReplaceStencilOp = ReplaceStencilOp;
  36222. exports.ReverseSubtractEquation = ReverseSubtractEquation;
  36223. exports.RingBufferGeometry = RingBufferGeometry;
  36224. exports.RingGeometry = RingGeometry;
  36225. exports.SRGB8_ALPHA8_ASTC_10x10_Format = SRGB8_ALPHA8_ASTC_10x10_Format;
  36226. exports.SRGB8_ALPHA8_ASTC_10x5_Format = SRGB8_ALPHA8_ASTC_10x5_Format;
  36227. exports.SRGB8_ALPHA8_ASTC_10x6_Format = SRGB8_ALPHA8_ASTC_10x6_Format;
  36228. exports.SRGB8_ALPHA8_ASTC_10x8_Format = SRGB8_ALPHA8_ASTC_10x8_Format;
  36229. exports.SRGB8_ALPHA8_ASTC_12x10_Format = SRGB8_ALPHA8_ASTC_12x10_Format;
  36230. exports.SRGB8_ALPHA8_ASTC_12x12_Format = SRGB8_ALPHA8_ASTC_12x12_Format;
  36231. exports.SRGB8_ALPHA8_ASTC_4x4_Format = SRGB8_ALPHA8_ASTC_4x4_Format;
  36232. exports.SRGB8_ALPHA8_ASTC_5x4_Format = SRGB8_ALPHA8_ASTC_5x4_Format;
  36233. exports.SRGB8_ALPHA8_ASTC_5x5_Format = SRGB8_ALPHA8_ASTC_5x5_Format;
  36234. exports.SRGB8_ALPHA8_ASTC_6x5_Format = SRGB8_ALPHA8_ASTC_6x5_Format;
  36235. exports.SRGB8_ALPHA8_ASTC_6x6_Format = SRGB8_ALPHA8_ASTC_6x6_Format;
  36236. exports.SRGB8_ALPHA8_ASTC_8x5_Format = SRGB8_ALPHA8_ASTC_8x5_Format;
  36237. exports.SRGB8_ALPHA8_ASTC_8x6_Format = SRGB8_ALPHA8_ASTC_8x6_Format;
  36238. exports.SRGB8_ALPHA8_ASTC_8x8_Format = SRGB8_ALPHA8_ASTC_8x8_Format;
  36239. exports.Scene = Scene;
  36240. exports.SceneUtils = SceneUtils;
  36241. exports.ShaderChunk = ShaderChunk;
  36242. exports.ShaderLib = ShaderLib;
  36243. exports.ShaderMaterial = ShaderMaterial;
  36244. exports.ShadowMaterial = ShadowMaterial;
  36245. exports.Shape = Shape;
  36246. exports.ShapeBufferGeometry = ShapeBufferGeometry;
  36247. exports.ShapeGeometry = ShapeGeometry;
  36248. exports.ShapePath = ShapePath;
  36249. exports.ShapeUtils = ShapeUtils;
  36250. exports.ShortType = ShortType;
  36251. exports.Skeleton = Skeleton;
  36252. exports.SkeletonHelper = SkeletonHelper;
  36253. exports.SkinnedMesh = SkinnedMesh;
  36254. exports.SmoothShading = SmoothShading;
  36255. exports.Sphere = Sphere;
  36256. exports.SphereBufferGeometry = SphereBufferGeometry;
  36257. exports.SphereGeometry = SphereGeometry;
  36258. exports.Spherical = Spherical;
  36259. exports.SphericalHarmonics3 = SphericalHarmonics3;
  36260. exports.SphericalReflectionMapping = SphericalReflectionMapping;
  36261. exports.Spline = Spline;
  36262. exports.SplineCurve = SplineCurve;
  36263. exports.SplineCurve3 = SplineCurve3;
  36264. exports.SpotLight = SpotLight;
  36265. exports.SpotLightHelper = SpotLightHelper;
  36266. exports.SpotLightShadow = SpotLightShadow;
  36267. exports.Sprite = Sprite;
  36268. exports.SpriteMaterial = SpriteMaterial;
  36269. exports.SrcAlphaFactor = SrcAlphaFactor;
  36270. exports.SrcAlphaSaturateFactor = SrcAlphaSaturateFactor;
  36271. exports.SrcColorFactor = SrcColorFactor;
  36272. exports.StaticCopyUsage = StaticCopyUsage;
  36273. exports.StaticDrawUsage = StaticDrawUsage;
  36274. exports.StaticReadUsage = StaticReadUsage;
  36275. exports.StereoCamera = StereoCamera;
  36276. exports.StreamCopyUsage = StreamCopyUsage;
  36277. exports.StreamDrawUsage = StreamDrawUsage;
  36278. exports.StreamReadUsage = StreamReadUsage;
  36279. exports.StringKeyframeTrack = StringKeyframeTrack;
  36280. exports.SubtractEquation = SubtractEquation;
  36281. exports.SubtractiveBlending = SubtractiveBlending;
  36282. exports.TOUCH = TOUCH;
  36283. exports.TangentSpaceNormalMap = TangentSpaceNormalMap;
  36284. exports.TetrahedronBufferGeometry = TetrahedronBufferGeometry;
  36285. exports.TetrahedronGeometry = TetrahedronGeometry;
  36286. exports.TextBufferGeometry = TextBufferGeometry;
  36287. exports.TextGeometry = TextGeometry;
  36288. exports.Texture = Texture;
  36289. exports.TextureLoader = TextureLoader;
  36290. exports.TorusBufferGeometry = TorusBufferGeometry;
  36291. exports.TorusGeometry = TorusGeometry;
  36292. exports.TorusKnotBufferGeometry = TorusKnotBufferGeometry;
  36293. exports.TorusKnotGeometry = TorusKnotGeometry;
  36294. exports.Triangle = Triangle;
  36295. exports.TriangleFanDrawMode = TriangleFanDrawMode;
  36296. exports.TriangleStripDrawMode = TriangleStripDrawMode;
  36297. exports.TrianglesDrawMode = TrianglesDrawMode;
  36298. exports.TubeBufferGeometry = TubeBufferGeometry;
  36299. exports.TubeGeometry = TubeGeometry;
  36300. exports.UVMapping = UVMapping;
  36301. exports.Uint16Attribute = Uint16Attribute;
  36302. exports.Uint16BufferAttribute = Uint16BufferAttribute;
  36303. exports.Uint32Attribute = Uint32Attribute;
  36304. exports.Uint32BufferAttribute = Uint32BufferAttribute;
  36305. exports.Uint8Attribute = Uint8Attribute;
  36306. exports.Uint8BufferAttribute = Uint8BufferAttribute;
  36307. exports.Uint8ClampedAttribute = Uint8ClampedAttribute;
  36308. exports.Uint8ClampedBufferAttribute = Uint8ClampedBufferAttribute;
  36309. exports.Uncharted2ToneMapping = Uncharted2ToneMapping;
  36310. exports.Uniform = Uniform;
  36311. exports.UniformsLib = UniformsLib;
  36312. exports.UniformsUtils = UniformsUtils;
  36313. exports.UnsignedByteType = UnsignedByteType;
  36314. exports.UnsignedInt248Type = UnsignedInt248Type;
  36315. exports.UnsignedIntType = UnsignedIntType;
  36316. exports.UnsignedShort4444Type = UnsignedShort4444Type;
  36317. exports.UnsignedShort5551Type = UnsignedShort5551Type;
  36318. exports.UnsignedShort565Type = UnsignedShort565Type;
  36319. exports.UnsignedShortType = UnsignedShortType;
  36320. exports.VSMShadowMap = VSMShadowMap;
  36321. exports.Vector2 = Vector2;
  36322. exports.Vector3 = Vector3;
  36323. exports.Vector4 = Vector4;
  36324. exports.VectorKeyframeTrack = VectorKeyframeTrack;
  36325. exports.Vertex = Vertex;
  36326. exports.VertexColors = VertexColors;
  36327. exports.VideoTexture = VideoTexture;
  36328. exports.WebGLCubeRenderTarget = WebGLCubeRenderTarget;
  36329. exports.WebGLMultisampleRenderTarget = WebGLMultisampleRenderTarget;
  36330. exports.WebGLRenderTarget = WebGLRenderTarget;
  36331. exports.WebGLRenderTargetCube = WebGLRenderTargetCube;
  36332. exports.WebGLRenderer = WebGLRenderer;
  36333. exports.WebGLUtils = WebGLUtils;
  36334. exports.WireframeGeometry = WireframeGeometry;
  36335. exports.WireframeHelper = WireframeHelper;
  36336. exports.WrapAroundEnding = WrapAroundEnding;
  36337. exports.XHRLoader = XHRLoader;
  36338. exports.ZeroCurvatureEnding = ZeroCurvatureEnding;
  36339. exports.ZeroFactor = ZeroFactor;
  36340. exports.ZeroSlopeEnding = ZeroSlopeEnding;
  36341. exports.ZeroStencilOp = ZeroStencilOp;
  36342. exports.sRGBEncoding = sRGBEncoding;
  36343. Object.defineProperty(exports, '__esModule', { value: true });
  36344. })));
  36345. },{}],58:[function(_dereq_,module,exports){
  36346. /**
  36347. * @author Don McCurdy / https://www.donmccurdy.com
  36348. */
  36349. THREE.DRACOLoader = function ( manager ) {
  36350. THREE.Loader.call( this, manager );
  36351. this.decoderPath = '';
  36352. this.decoderConfig = {};
  36353. this.decoderBinary = null;
  36354. this.decoderPending = null;
  36355. this.workerLimit = 4;
  36356. this.workerPool = [];
  36357. this.workerNextTaskID = 1;
  36358. this.workerSourceURL = '';
  36359. this.defaultAttributeIDs = {
  36360. position: 'POSITION',
  36361. normal: 'NORMAL',
  36362. color: 'COLOR',
  36363. uv: 'TEX_COORD'
  36364. };
  36365. this.defaultAttributeTypes = {
  36366. position: 'Float32Array',
  36367. normal: 'Float32Array',
  36368. color: 'Float32Array',
  36369. uv: 'Float32Array'
  36370. };
  36371. };
  36372. THREE.DRACOLoader.prototype = Object.assign( Object.create( THREE.Loader.prototype ), {
  36373. constructor: THREE.DRACOLoader,
  36374. setDecoderPath: function ( path ) {
  36375. this.decoderPath = path;
  36376. return this;
  36377. },
  36378. setDecoderConfig: function ( config ) {
  36379. this.decoderConfig = config;
  36380. return this;
  36381. },
  36382. setWorkerLimit: function ( workerLimit ) {
  36383. this.workerLimit = workerLimit;
  36384. return this;
  36385. },
  36386. /** @deprecated */
  36387. setVerbosity: function () {
  36388. console.warn( 'THREE.DRACOLoader: The .setVerbosity() method has been removed.' );
  36389. },
  36390. /** @deprecated */
  36391. setDrawMode: function () {
  36392. console.warn( 'THREE.DRACOLoader: The .setDrawMode() method has been removed.' );
  36393. },
  36394. /** @deprecated */
  36395. setSkipDequantization: function () {
  36396. console.warn( 'THREE.DRACOLoader: The .setSkipDequantization() method has been removed.' );
  36397. },
  36398. load: function ( url, onLoad, onProgress, onError ) {
  36399. var loader = new THREE.FileLoader( this.manager );
  36400. loader.setPath( this.path );
  36401. loader.setResponseType( 'arraybuffer' );
  36402. if ( this.crossOrigin === 'use-credentials' ) {
  36403. loader.setWithCredentials( true );
  36404. }
  36405. loader.load( url, ( buffer ) => {
  36406. var taskConfig = {
  36407. attributeIDs: this.defaultAttributeIDs,
  36408. attributeTypes: this.defaultAttributeTypes,
  36409. useUniqueIDs: false
  36410. };
  36411. this.decodeGeometry( buffer, taskConfig )
  36412. .then( onLoad )
  36413. .catch( onError );
  36414. }, onProgress, onError );
  36415. },
  36416. /** @deprecated Kept for backward-compatibility with previous DRACOLoader versions. */
  36417. decodeDracoFile: function ( buffer, callback, attributeIDs, attributeTypes ) {
  36418. var taskConfig = {
  36419. attributeIDs: attributeIDs || this.defaultAttributeIDs,
  36420. attributeTypes: attributeTypes || this.defaultAttributeTypes,
  36421. useUniqueIDs: !! attributeIDs
  36422. };
  36423. this.decodeGeometry( buffer, taskConfig ).then( callback );
  36424. },
  36425. decodeGeometry: function ( buffer, taskConfig ) {
  36426. // TODO: For backward-compatibility, support 'attributeTypes' objects containing
  36427. // references (rather than names) to typed array constructors. These must be
  36428. // serialized before sending them to the worker.
  36429. for ( var attribute in taskConfig.attributeTypes ) {
  36430. var type = taskConfig.attributeTypes[ attribute ];
  36431. if ( type.BYTES_PER_ELEMENT !== undefined ) {
  36432. taskConfig.attributeTypes[ attribute ] = type.name;
  36433. }
  36434. }
  36435. //
  36436. var taskKey = JSON.stringify( taskConfig );
  36437. // Check for an existing task using this buffer. A transferred buffer cannot be transferred
  36438. // again from this thread.
  36439. if ( THREE.DRACOLoader.taskCache.has( buffer ) ) {
  36440. var cachedTask = THREE.DRACOLoader.taskCache.get( buffer );
  36441. if ( cachedTask.key === taskKey ) {
  36442. return cachedTask.promise;
  36443. } else if ( buffer.byteLength === 0 ) {
  36444. // Technically, it would be possible to wait for the previous task to complete,
  36445. // transfer the buffer back, and decode again with the second configuration. That
  36446. // is complex, and I don't know of any reason to decode a Draco buffer twice in
  36447. // different ways, so this is left unimplemented.
  36448. throw new Error(
  36449. 'THREE.DRACOLoader: Unable to re-decode a buffer with different ' +
  36450. 'settings. Buffer has already been transferred.'
  36451. );
  36452. }
  36453. }
  36454. //
  36455. var worker;
  36456. var taskID = this.workerNextTaskID ++;
  36457. var taskCost = buffer.byteLength;
  36458. // Obtain a worker and assign a task, and construct a geometry instance
  36459. // when the task completes.
  36460. var geometryPending = this._getWorker( taskID, taskCost )
  36461. .then( ( _worker ) => {
  36462. worker = _worker;
  36463. return new Promise( ( resolve, reject ) => {
  36464. worker._callbacks[ taskID ] = { resolve, reject };
  36465. worker.postMessage( { type: 'decode', id: taskID, taskConfig, buffer }, [ buffer ] );
  36466. // this.debug();
  36467. } );
  36468. } )
  36469. .then( ( message ) => this._createGeometry( message.geometry ) );
  36470. // Remove task from the task list.
  36471. geometryPending
  36472. .finally( () => {
  36473. if ( worker && taskID ) {
  36474. this._releaseTask( worker, taskID );
  36475. // this.debug();
  36476. }
  36477. } );
  36478. // Cache the task result.
  36479. THREE.DRACOLoader.taskCache.set( buffer, {
  36480. key: taskKey,
  36481. promise: geometryPending
  36482. } );
  36483. return geometryPending;
  36484. },
  36485. _createGeometry: function ( geometryData ) {
  36486. var geometry = new THREE.BufferGeometry();
  36487. if ( geometryData.index ) {
  36488. geometry.setIndex( new THREE.BufferAttribute( geometryData.index.array, 1 ) );
  36489. }
  36490. for ( var i = 0; i < geometryData.attributes.length; i ++ ) {
  36491. var attribute = geometryData.attributes[ i ];
  36492. var name = attribute.name;
  36493. var array = attribute.array;
  36494. var itemSize = attribute.itemSize;
  36495. geometry.setAttribute( name, new THREE.BufferAttribute( array, itemSize ) );
  36496. }
  36497. return geometry;
  36498. },
  36499. _loadLibrary: function ( url, responseType ) {
  36500. var loader = new THREE.FileLoader( this.manager );
  36501. loader.setPath( this.decoderPath );
  36502. loader.setResponseType( responseType );
  36503. return new Promise( ( resolve, reject ) => {
  36504. loader.load( url, resolve, undefined, reject );
  36505. } );
  36506. },
  36507. preload: function () {
  36508. this._initDecoder();
  36509. return this;
  36510. },
  36511. _initDecoder: function () {
  36512. if ( this.decoderPending ) return this.decoderPending;
  36513. var useJS = typeof WebAssembly !== 'object' || this.decoderConfig.type === 'js';
  36514. var librariesPending = [];
  36515. if ( useJS ) {
  36516. librariesPending.push( this._loadLibrary( 'draco_decoder.js', 'text' ) );
  36517. } else {
  36518. librariesPending.push( this._loadLibrary( 'draco_wasm_wrapper.js', 'text' ) );
  36519. librariesPending.push( this._loadLibrary( 'draco_decoder.wasm', 'arraybuffer' ) );
  36520. }
  36521. this.decoderPending = Promise.all( librariesPending )
  36522. .then( ( libraries ) => {
  36523. var jsContent = libraries[ 0 ];
  36524. if ( ! useJS ) {
  36525. this.decoderConfig.wasmBinary = libraries[ 1 ];
  36526. }
  36527. var fn = THREE.DRACOLoader.DRACOWorker.toString();
  36528. var body = [
  36529. '/* draco decoder */',
  36530. jsContent,
  36531. '',
  36532. '/* worker */',
  36533. fn.substring( fn.indexOf( '{' ) + 1, fn.lastIndexOf( '}' ) )
  36534. ].join( '\n' );
  36535. this.workerSourceURL = URL.createObjectURL( new Blob( [ body ] ) );
  36536. } );
  36537. return this.decoderPending;
  36538. },
  36539. _getWorker: function ( taskID, taskCost ) {
  36540. return this._initDecoder().then( () => {
  36541. if ( this.workerPool.length < this.workerLimit ) {
  36542. var worker = new Worker( this.workerSourceURL );
  36543. worker._callbacks = {};
  36544. worker._taskCosts = {};
  36545. worker._taskLoad = 0;
  36546. worker.postMessage( { type: 'init', decoderConfig: this.decoderConfig } );
  36547. worker.onmessage = function ( e ) {
  36548. var message = e.data;
  36549. switch ( message.type ) {
  36550. case 'decode':
  36551. worker._callbacks[ message.id ].resolve( message );
  36552. break;
  36553. case 'error':
  36554. worker._callbacks[ message.id ].reject( message );
  36555. break;
  36556. default:
  36557. console.error( 'THREE.DRACOLoader: Unexpected message, "' + message.type + '"' );
  36558. }
  36559. };
  36560. this.workerPool.push( worker );
  36561. } else {
  36562. this.workerPool.sort( function ( a, b ) {
  36563. return a._taskLoad > b._taskLoad ? - 1 : 1;
  36564. } );
  36565. }
  36566. var worker = this.workerPool[ this.workerPool.length - 1 ];
  36567. worker._taskCosts[ taskID ] = taskCost;
  36568. worker._taskLoad += taskCost;
  36569. return worker;
  36570. } );
  36571. },
  36572. _releaseTask: function ( worker, taskID ) {
  36573. worker._taskLoad -= worker._taskCosts[ taskID ];
  36574. delete worker._callbacks[ taskID ];
  36575. delete worker._taskCosts[ taskID ];
  36576. },
  36577. debug: function () {
  36578. console.log( 'Task load: ', this.workerPool.map( ( worker ) => worker._taskLoad ) );
  36579. },
  36580. dispose: function () {
  36581. for ( var i = 0; i < this.workerPool.length; ++ i ) {
  36582. this.workerPool[ i ].terminate();
  36583. }
  36584. this.workerPool.length = 0;
  36585. return this;
  36586. }
  36587. } );
  36588. /* WEB WORKER */
  36589. THREE.DRACOLoader.DRACOWorker = function () {
  36590. var decoderConfig;
  36591. var decoderPending;
  36592. onmessage = function ( e ) {
  36593. var message = e.data;
  36594. switch ( message.type ) {
  36595. case 'init':
  36596. decoderConfig = message.decoderConfig;
  36597. decoderPending = new Promise( function ( resolve/*, reject*/ ) {
  36598. decoderConfig.onModuleLoaded = function ( draco ) {
  36599. // Module is Promise-like. Wrap before resolving to avoid loop.
  36600. resolve( { draco: draco } );
  36601. };
  36602. DracoDecoderModule( decoderConfig );
  36603. } );
  36604. break;
  36605. case 'decode':
  36606. var buffer = message.buffer;
  36607. var taskConfig = message.taskConfig;
  36608. decoderPending.then( ( module ) => {
  36609. var draco = module.draco;
  36610. var decoder = new draco.Decoder();
  36611. var decoderBuffer = new draco.DecoderBuffer();
  36612. decoderBuffer.Init( new Int8Array( buffer ), buffer.byteLength );
  36613. try {
  36614. var geometry = decodeGeometry( draco, decoder, decoderBuffer, taskConfig );
  36615. var buffers = geometry.attributes.map( ( attr ) => attr.array.buffer );
  36616. if ( geometry.index ) buffers.push( geometry.index.array.buffer );
  36617. self.postMessage( { type: 'decode', id: message.id, geometry }, buffers );
  36618. } catch ( error ) {
  36619. console.error( error );
  36620. self.postMessage( { type: 'error', id: message.id, error: error.message } );
  36621. } finally {
  36622. draco.destroy( decoderBuffer );
  36623. draco.destroy( decoder );
  36624. }
  36625. } );
  36626. break;
  36627. }
  36628. };
  36629. function decodeGeometry( draco, decoder, decoderBuffer, taskConfig ) {
  36630. var attributeIDs = taskConfig.attributeIDs;
  36631. var attributeTypes = taskConfig.attributeTypes;
  36632. var dracoGeometry;
  36633. var decodingStatus;
  36634. var geometryType = decoder.GetEncodedGeometryType( decoderBuffer );
  36635. if ( geometryType === draco.TRIANGULAR_MESH ) {
  36636. dracoGeometry = new draco.Mesh();
  36637. decodingStatus = decoder.DecodeBufferToMesh( decoderBuffer, dracoGeometry );
  36638. } else if ( geometryType === draco.POINT_CLOUD ) {
  36639. dracoGeometry = new draco.PointCloud();
  36640. decodingStatus = decoder.DecodeBufferToPointCloud( decoderBuffer, dracoGeometry );
  36641. } else {
  36642. throw new Error( 'THREE.DRACOLoader: Unexpected geometry type.' );
  36643. }
  36644. if ( ! decodingStatus.ok() || dracoGeometry.ptr === 0 ) {
  36645. throw new Error( 'THREE.DRACOLoader: Decoding failed: ' + decodingStatus.error_msg() );
  36646. }
  36647. var geometry = { index: null, attributes: [] };
  36648. // Gather all vertex attributes.
  36649. for ( var attributeName in attributeIDs ) {
  36650. var attributeType = self[ attributeTypes[ attributeName ] ];
  36651. var attribute;
  36652. var attributeID;
  36653. // A Draco file may be created with default vertex attributes, whose attribute IDs
  36654. // are mapped 1:1 from their semantic name (POSITION, NORMAL, ...). Alternatively,
  36655. // a Draco file may contain a custom set of attributes, identified by known unique
  36656. // IDs. glTF files always do the latter, and `.drc` files typically do the former.
  36657. if ( taskConfig.useUniqueIDs ) {
  36658. attributeID = attributeIDs[ attributeName ];
  36659. attribute = decoder.GetAttributeByUniqueId( dracoGeometry, attributeID );
  36660. } else {
  36661. attributeID = decoder.GetAttributeId( dracoGeometry, draco[ attributeIDs[ attributeName ] ] );
  36662. if ( attributeID === - 1 ) continue;
  36663. attribute = decoder.GetAttribute( dracoGeometry, attributeID );
  36664. }
  36665. geometry.attributes.push( decodeAttribute( draco, decoder, dracoGeometry, attributeName, attributeType, attribute ) );
  36666. }
  36667. // Add index.
  36668. if ( geometryType === draco.TRIANGULAR_MESH ) {
  36669. // Generate mesh faces.
  36670. var numFaces = dracoGeometry.num_faces();
  36671. var numIndices = numFaces * 3;
  36672. var index = new Uint32Array( numIndices );
  36673. var indexArray = new draco.DracoInt32Array();
  36674. for ( var i = 0; i < numFaces; ++ i ) {
  36675. decoder.GetFaceFromMesh( dracoGeometry, i, indexArray );
  36676. for ( var j = 0; j < 3; ++ j ) {
  36677. index[ i * 3 + j ] = indexArray.GetValue( j );
  36678. }
  36679. }
  36680. geometry.index = { array: index, itemSize: 1 };
  36681. draco.destroy( indexArray );
  36682. }
  36683. draco.destroy( dracoGeometry );
  36684. return geometry;
  36685. }
  36686. function decodeAttribute( draco, decoder, dracoGeometry, attributeName, attributeType, attribute ) {
  36687. var numComponents = attribute.num_components();
  36688. var numPoints = dracoGeometry.num_points();
  36689. var numValues = numPoints * numComponents;
  36690. var dracoArray;
  36691. var array;
  36692. switch ( attributeType ) {
  36693. case Float32Array:
  36694. dracoArray = new draco.DracoFloat32Array();
  36695. decoder.GetAttributeFloatForAllPoints( dracoGeometry, attribute, dracoArray );
  36696. array = new Float32Array( numValues );
  36697. break;
  36698. case Int8Array:
  36699. dracoArray = new draco.DracoInt8Array();
  36700. decoder.GetAttributeInt8ForAllPoints( dracoGeometry, attribute, dracoArray );
  36701. array = new Int8Array( numValues );
  36702. break;
  36703. case Int16Array:
  36704. dracoArray = new draco.DracoInt16Array();
  36705. decoder.GetAttributeInt16ForAllPoints( dracoGeometry, attribute, dracoArray );
  36706. array = new Int16Array( numValues );
  36707. break;
  36708. case Int32Array:
  36709. dracoArray = new draco.DracoInt32Array();
  36710. decoder.GetAttributeInt32ForAllPoints( dracoGeometry, attribute, dracoArray );
  36711. array = new Int32Array( numValues );
  36712. break;
  36713. case Uint8Array:
  36714. dracoArray = new draco.DracoUInt8Array();
  36715. decoder.GetAttributeUInt8ForAllPoints( dracoGeometry, attribute, dracoArray );
  36716. array = new Uint8Array( numValues );
  36717. break;
  36718. case Uint16Array:
  36719. dracoArray = new draco.DracoUInt16Array();
  36720. decoder.GetAttributeUInt16ForAllPoints( dracoGeometry, attribute, dracoArray );
  36721. array = new Uint16Array( numValues );
  36722. break;
  36723. case Uint32Array:
  36724. dracoArray = new draco.DracoUInt32Array();
  36725. decoder.GetAttributeUInt32ForAllPoints( dracoGeometry, attribute, dracoArray );
  36726. array = new Uint32Array( numValues );
  36727. break;
  36728. default:
  36729. throw new Error( 'THREE.DRACOLoader: Unexpected attribute type.' );
  36730. }
  36731. for ( var i = 0; i < numValues; i ++ ) {
  36732. array[ i ] = dracoArray.GetValue( i );
  36733. }
  36734. draco.destroy( dracoArray );
  36735. return {
  36736. name: attributeName,
  36737. array: array,
  36738. itemSize: numComponents
  36739. };
  36740. }
  36741. };
  36742. THREE.DRACOLoader.taskCache = new WeakMap();
  36743. /** Deprecated static methods */
  36744. /** @deprecated */
  36745. THREE.DRACOLoader.setDecoderPath = function () {
  36746. console.warn( 'THREE.DRACOLoader: The .setDecoderPath() method has been removed. Use instance methods.' );
  36747. };
  36748. /** @deprecated */
  36749. THREE.DRACOLoader.setDecoderConfig = function () {
  36750. console.warn( 'THREE.DRACOLoader: The .setDecoderConfig() method has been removed. Use instance methods.' );
  36751. };
  36752. /** @deprecated */
  36753. THREE.DRACOLoader.releaseDecoderModule = function () {
  36754. console.warn( 'THREE.DRACOLoader: The .releaseDecoderModule() method has been removed. Use instance methods.' );
  36755. };
  36756. /** @deprecated */
  36757. THREE.DRACOLoader.getDecoderModule = function () {
  36758. console.warn( 'THREE.DRACOLoader: The .getDecoderModule() method has been removed. Use instance methods.' );
  36759. };
  36760. },{}],59:[function(_dereq_,module,exports){
  36761. /**
  36762. * @author Rich Tibbett / https://github.com/richtr
  36763. * @author mrdoob / http://mrdoob.com/
  36764. * @author Tony Parisi / http://www.tonyparisi.com/
  36765. * @author Takahiro / https://github.com/takahirox
  36766. * @author Don McCurdy / https://www.donmccurdy.com
  36767. */
  36768. THREE.GLTFLoader = ( function () {
  36769. function GLTFLoader( manager ) {
  36770. THREE.Loader.call( this, manager );
  36771. this.dracoLoader = null;
  36772. this.ddsLoader = null;
  36773. }
  36774. GLTFLoader.prototype = Object.assign( Object.create( THREE.Loader.prototype ), {
  36775. constructor: GLTFLoader,
  36776. load: function ( url, onLoad, onProgress, onError ) {
  36777. var scope = this;
  36778. var resourcePath;
  36779. if ( this.resourcePath !== '' ) {
  36780. resourcePath = this.resourcePath;
  36781. } else if ( this.path !== '' ) {
  36782. resourcePath = this.path;
  36783. } else {
  36784. resourcePath = THREE.LoaderUtils.extractUrlBase( url );
  36785. }
  36786. // Tells the LoadingManager to track an extra item, which resolves after
  36787. // the model is fully loaded. This means the count of items loaded will
  36788. // be incorrect, but ensures manager.onLoad() does not fire early.
  36789. scope.manager.itemStart( url );
  36790. var _onError = function ( e ) {
  36791. if ( onError ) {
  36792. onError( e );
  36793. } else {
  36794. console.error( e );
  36795. }
  36796. scope.manager.itemError( url );
  36797. scope.manager.itemEnd( url );
  36798. };
  36799. var loader = new THREE.FileLoader( scope.manager );
  36800. loader.setPath( this.path );
  36801. loader.setResponseType( 'arraybuffer' );
  36802. if ( scope.crossOrigin === 'use-credentials' ) {
  36803. loader.setWithCredentials( true );
  36804. }
  36805. loader.load( url, function ( data ) {
  36806. try {
  36807. scope.parse( data, resourcePath, function ( gltf ) {
  36808. onLoad( gltf );
  36809. scope.manager.itemEnd( url );
  36810. }, _onError );
  36811. } catch ( e ) {
  36812. _onError( e );
  36813. }
  36814. }, onProgress, _onError );
  36815. },
  36816. setDRACOLoader: function ( dracoLoader ) {
  36817. this.dracoLoader = dracoLoader;
  36818. return this;
  36819. },
  36820. setDDSLoader: function ( ddsLoader ) {
  36821. this.ddsLoader = ddsLoader;
  36822. return this;
  36823. },
  36824. parse: function ( data, path, onLoad, onError ) {
  36825. var content;
  36826. var extensions = {};
  36827. if ( typeof data === 'string' ) {
  36828. content = data;
  36829. } else {
  36830. var magic = THREE.LoaderUtils.decodeText( new Uint8Array( data, 0, 4 ) );
  36831. if ( magic === BINARY_EXTENSION_HEADER_MAGIC ) {
  36832. try {
  36833. extensions[ EXTENSIONS.KHR_BINARY_GLTF ] = new GLTFBinaryExtension( data );
  36834. } catch ( error ) {
  36835. if ( onError ) onError( error );
  36836. return;
  36837. }
  36838. content = extensions[ EXTENSIONS.KHR_BINARY_GLTF ].content;
  36839. } else {
  36840. content = THREE.LoaderUtils.decodeText( new Uint8Array( data ) );
  36841. }
  36842. }
  36843. var json = JSON.parse( content );
  36844. if ( json.asset === undefined || json.asset.version[ 0 ] < 2 ) {
  36845. if ( onError ) onError( new Error( 'THREE.GLTFLoader: Unsupported asset. glTF versions >=2.0 are supported.' ) );
  36846. return;
  36847. }
  36848. if ( json.extensionsUsed ) {
  36849. for ( var i = 0; i < json.extensionsUsed.length; ++ i ) {
  36850. var extensionName = json.extensionsUsed[ i ];
  36851. var extensionsRequired = json.extensionsRequired || [];
  36852. switch ( extensionName ) {
  36853. case EXTENSIONS.KHR_LIGHTS_PUNCTUAL:
  36854. extensions[ extensionName ] = new GLTFLightsExtension( json );
  36855. break;
  36856. case EXTENSIONS.KHR_MATERIALS_CLEARCOAT:
  36857. extensions[ extensionName ] = new GLTFMaterialsClearcoatExtension();
  36858. break;
  36859. case EXTENSIONS.KHR_MATERIALS_UNLIT:
  36860. extensions[ extensionName ] = new GLTFMaterialsUnlitExtension();
  36861. break;
  36862. case EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS:
  36863. extensions[ extensionName ] = new GLTFMaterialsPbrSpecularGlossinessExtension();
  36864. break;
  36865. case EXTENSIONS.KHR_DRACO_MESH_COMPRESSION:
  36866. extensions[ extensionName ] = new GLTFDracoMeshCompressionExtension( json, this.dracoLoader );
  36867. break;
  36868. case EXTENSIONS.MSFT_TEXTURE_DDS:
  36869. extensions[ extensionName ] = new GLTFTextureDDSExtension( this.ddsLoader );
  36870. break;
  36871. case EXTENSIONS.KHR_TEXTURE_TRANSFORM:
  36872. extensions[ extensionName ] = new GLTFTextureTransformExtension();
  36873. break;
  36874. case EXTENSIONS.KHR_MESH_QUANTIZATION:
  36875. extensions[ extensionName ] = new GLTFMeshQuantizationExtension();
  36876. break;
  36877. default:
  36878. if ( extensionsRequired.indexOf( extensionName ) >= 0 ) {
  36879. console.warn( 'THREE.GLTFLoader: Unknown extension "' + extensionName + '".' );
  36880. }
  36881. }
  36882. }
  36883. }
  36884. var parser = new GLTFParser( json, extensions, {
  36885. path: path || this.resourcePath || '',
  36886. crossOrigin: this.crossOrigin,
  36887. manager: this.manager
  36888. } );
  36889. parser.parse( onLoad, onError );
  36890. }
  36891. } );
  36892. /* GLTFREGISTRY */
  36893. function GLTFRegistry() {
  36894. var objects = {};
  36895. return {
  36896. get: function ( key ) {
  36897. return objects[ key ];
  36898. },
  36899. add: function ( key, object ) {
  36900. objects[ key ] = object;
  36901. },
  36902. remove: function ( key ) {
  36903. delete objects[ key ];
  36904. },
  36905. removeAll: function () {
  36906. objects = {};
  36907. }
  36908. };
  36909. }
  36910. /*********************************/
  36911. /********** EXTENSIONS ***********/
  36912. /*********************************/
  36913. var EXTENSIONS = {
  36914. KHR_BINARY_GLTF: 'KHR_binary_glTF',
  36915. KHR_DRACO_MESH_COMPRESSION: 'KHR_draco_mesh_compression',
  36916. KHR_LIGHTS_PUNCTUAL: 'KHR_lights_punctual',
  36917. KHR_MATERIALS_CLEARCOAT: 'KHR_materials_clearcoat',
  36918. KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS: 'KHR_materials_pbrSpecularGlossiness',
  36919. KHR_MATERIALS_UNLIT: 'KHR_materials_unlit',
  36920. KHR_TEXTURE_TRANSFORM: 'KHR_texture_transform',
  36921. KHR_MESH_QUANTIZATION: 'KHR_mesh_quantization',
  36922. MSFT_TEXTURE_DDS: 'MSFT_texture_dds'
  36923. };
  36924. /**
  36925. * DDS Texture Extension
  36926. *
  36927. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/MSFT_texture_dds
  36928. *
  36929. */
  36930. function GLTFTextureDDSExtension( ddsLoader ) {
  36931. if ( ! ddsLoader ) {
  36932. throw new Error( 'THREE.GLTFLoader: Attempting to load .dds texture without importing THREE.DDSLoader' );
  36933. }
  36934. this.name = EXTENSIONS.MSFT_TEXTURE_DDS;
  36935. this.ddsLoader = ddsLoader;
  36936. }
  36937. /**
  36938. * Punctual Lights Extension
  36939. *
  36940. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_lights_punctual
  36941. */
  36942. function GLTFLightsExtension( json ) {
  36943. this.name = EXTENSIONS.KHR_LIGHTS_PUNCTUAL;
  36944. var extension = ( json.extensions && json.extensions[ EXTENSIONS.KHR_LIGHTS_PUNCTUAL ] ) || {};
  36945. this.lightDefs = extension.lights || [];
  36946. }
  36947. GLTFLightsExtension.prototype.loadLight = function ( lightIndex ) {
  36948. var lightDef = this.lightDefs[ lightIndex ];
  36949. var lightNode;
  36950. var color = new THREE.Color( 0xffffff );
  36951. if ( lightDef.color !== undefined ) color.fromArray( lightDef.color );
  36952. var range = lightDef.range !== undefined ? lightDef.range : 0;
  36953. switch ( lightDef.type ) {
  36954. case 'directional':
  36955. lightNode = new THREE.DirectionalLight( color );
  36956. lightNode.target.position.set( 0, 0, - 1 );
  36957. lightNode.add( lightNode.target );
  36958. break;
  36959. case 'point':
  36960. lightNode = new THREE.PointLight( color );
  36961. lightNode.distance = range;
  36962. break;
  36963. case 'spot':
  36964. lightNode = new THREE.SpotLight( color );
  36965. lightNode.distance = range;
  36966. // Handle spotlight properties.
  36967. lightDef.spot = lightDef.spot || {};
  36968. lightDef.spot.innerConeAngle = lightDef.spot.innerConeAngle !== undefined ? lightDef.spot.innerConeAngle : 0;
  36969. lightDef.spot.outerConeAngle = lightDef.spot.outerConeAngle !== undefined ? lightDef.spot.outerConeAngle : Math.PI / 4.0;
  36970. lightNode.angle = lightDef.spot.outerConeAngle;
  36971. lightNode.penumbra = 1.0 - lightDef.spot.innerConeAngle / lightDef.spot.outerConeAngle;
  36972. lightNode.target.position.set( 0, 0, - 1 );
  36973. lightNode.add( lightNode.target );
  36974. break;
  36975. default:
  36976. throw new Error( 'THREE.GLTFLoader: Unexpected light type, "' + lightDef.type + '".' );
  36977. }
  36978. // Some lights (e.g. spot) default to a position other than the origin. Reset the position
  36979. // here, because node-level parsing will only override position if explicitly specified.
  36980. lightNode.position.set( 0, 0, 0 );
  36981. lightNode.decay = 2;
  36982. if ( lightDef.intensity !== undefined ) lightNode.intensity = lightDef.intensity;
  36983. lightNode.name = lightDef.name || ( 'light_' + lightIndex );
  36984. return Promise.resolve( lightNode );
  36985. };
  36986. /**
  36987. * Unlit Materials Extension
  36988. *
  36989. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_unlit
  36990. */
  36991. function GLTFMaterialsUnlitExtension() {
  36992. this.name = EXTENSIONS.KHR_MATERIALS_UNLIT;
  36993. }
  36994. GLTFMaterialsUnlitExtension.prototype.getMaterialType = function () {
  36995. return THREE.MeshBasicMaterial;
  36996. };
  36997. GLTFMaterialsUnlitExtension.prototype.extendParams = function ( materialParams, materialDef, parser ) {
  36998. var pending = [];
  36999. materialParams.color = new THREE.Color( 1.0, 1.0, 1.0 );
  37000. materialParams.opacity = 1.0;
  37001. var metallicRoughness = materialDef.pbrMetallicRoughness;
  37002. if ( metallicRoughness ) {
  37003. if ( Array.isArray( metallicRoughness.baseColorFactor ) ) {
  37004. var array = metallicRoughness.baseColorFactor;
  37005. materialParams.color.fromArray( array );
  37006. materialParams.opacity = array[ 3 ];
  37007. }
  37008. if ( metallicRoughness.baseColorTexture !== undefined ) {
  37009. pending.push( parser.assignTexture( materialParams, 'map', metallicRoughness.baseColorTexture ) );
  37010. }
  37011. }
  37012. return Promise.all( pending );
  37013. };
  37014. /**
  37015. * Clearcoat Materials Extension
  37016. *
  37017. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_clearcoat
  37018. */
  37019. function GLTFMaterialsClearcoatExtension() {
  37020. this.name = EXTENSIONS.KHR_MATERIALS_CLEARCOAT;
  37021. }
  37022. GLTFMaterialsClearcoatExtension.prototype.getMaterialType = function () {
  37023. return THREE.MeshPhysicalMaterial;
  37024. };
  37025. GLTFMaterialsClearcoatExtension.prototype.extendParams = function ( materialParams, materialDef, parser ) {
  37026. var pending = [];
  37027. var extension = materialDef.extensions[ this.name ];
  37028. if ( extension.clearcoatFactor !== undefined ) {
  37029. materialParams.clearcoat = extension.clearcoatFactor;
  37030. }
  37031. if ( extension.clearcoatTexture !== undefined ) {
  37032. pending.push( parser.assignTexture( materialParams, 'clearcoatMap', extension.clearcoatTexture ) );
  37033. }
  37034. if ( extension.clearcoatRoughnessFactor !== undefined ) {
  37035. materialParams.clearcoatRoughness = extension.clearcoatRoughnessFactor;
  37036. }
  37037. if ( extension.clearcoatRoughnessTexture !== undefined ) {
  37038. pending.push( parser.assignTexture( materialParams, 'clearcoatRoughnessMap', extension.clearcoatRoughnessTexture ) );
  37039. }
  37040. if ( extension.clearcoatNormalTexture !== undefined ) {
  37041. pending.push( parser.assignTexture( materialParams, 'clearcoatNormalMap', extension.clearcoatNormalTexture ) );
  37042. if ( extension.clearcoatNormalTexture.scale !== undefined ) {
  37043. var scale = extension.clearcoatNormalTexture.scale;
  37044. materialParams.clearcoatNormalScale = new THREE.Vector2( scale, scale );
  37045. }
  37046. }
  37047. return Promise.all( pending );
  37048. };
  37049. /* BINARY EXTENSION */
  37050. var BINARY_EXTENSION_HEADER_MAGIC = 'glTF';
  37051. var BINARY_EXTENSION_HEADER_LENGTH = 12;
  37052. var BINARY_EXTENSION_CHUNK_TYPES = { JSON: 0x4E4F534A, BIN: 0x004E4942 };
  37053. function GLTFBinaryExtension( data ) {
  37054. this.name = EXTENSIONS.KHR_BINARY_GLTF;
  37055. this.content = null;
  37056. this.body = null;
  37057. var headerView = new DataView( data, 0, BINARY_EXTENSION_HEADER_LENGTH );
  37058. this.header = {
  37059. magic: THREE.LoaderUtils.decodeText( new Uint8Array( data.slice( 0, 4 ) ) ),
  37060. version: headerView.getUint32( 4, true ),
  37061. length: headerView.getUint32( 8, true )
  37062. };
  37063. if ( this.header.magic !== BINARY_EXTENSION_HEADER_MAGIC ) {
  37064. throw new Error( 'THREE.GLTFLoader: Unsupported glTF-Binary header.' );
  37065. } else if ( this.header.version < 2.0 ) {
  37066. throw new Error( 'THREE.GLTFLoader: Legacy binary file detected.' );
  37067. }
  37068. var chunkView = new DataView( data, BINARY_EXTENSION_HEADER_LENGTH );
  37069. var chunkIndex = 0;
  37070. while ( chunkIndex < chunkView.byteLength ) {
  37071. var chunkLength = chunkView.getUint32( chunkIndex, true );
  37072. chunkIndex += 4;
  37073. var chunkType = chunkView.getUint32( chunkIndex, true );
  37074. chunkIndex += 4;
  37075. if ( chunkType === BINARY_EXTENSION_CHUNK_TYPES.JSON ) {
  37076. var contentArray = new Uint8Array( data, BINARY_EXTENSION_HEADER_LENGTH + chunkIndex, chunkLength );
  37077. this.content = THREE.LoaderUtils.decodeText( contentArray );
  37078. } else if ( chunkType === BINARY_EXTENSION_CHUNK_TYPES.BIN ) {
  37079. var byteOffset = BINARY_EXTENSION_HEADER_LENGTH + chunkIndex;
  37080. this.body = data.slice( byteOffset, byteOffset + chunkLength );
  37081. }
  37082. // Clients must ignore chunks with unknown types.
  37083. chunkIndex += chunkLength;
  37084. }
  37085. if ( this.content === null ) {
  37086. throw new Error( 'THREE.GLTFLoader: JSON content not found.' );
  37087. }
  37088. }
  37089. /**
  37090. * DRACO Mesh Compression Extension
  37091. *
  37092. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_draco_mesh_compression
  37093. */
  37094. function GLTFDracoMeshCompressionExtension( json, dracoLoader ) {
  37095. if ( ! dracoLoader ) {
  37096. throw new Error( 'THREE.GLTFLoader: No DRACOLoader instance provided.' );
  37097. }
  37098. this.name = EXTENSIONS.KHR_DRACO_MESH_COMPRESSION;
  37099. this.json = json;
  37100. this.dracoLoader = dracoLoader;
  37101. this.dracoLoader.preload();
  37102. }
  37103. GLTFDracoMeshCompressionExtension.prototype.decodePrimitive = function ( primitive, parser ) {
  37104. var json = this.json;
  37105. var dracoLoader = this.dracoLoader;
  37106. var bufferViewIndex = primitive.extensions[ this.name ].bufferView;
  37107. var gltfAttributeMap = primitive.extensions[ this.name ].attributes;
  37108. var threeAttributeMap = {};
  37109. var attributeNormalizedMap = {};
  37110. var attributeTypeMap = {};
  37111. for ( var attributeName in gltfAttributeMap ) {
  37112. var threeAttributeName = ATTRIBUTES[ attributeName ] || attributeName.toLowerCase();
  37113. threeAttributeMap[ threeAttributeName ] = gltfAttributeMap[ attributeName ];
  37114. }
  37115. for ( attributeName in primitive.attributes ) {
  37116. var threeAttributeName = ATTRIBUTES[ attributeName ] || attributeName.toLowerCase();
  37117. if ( gltfAttributeMap[ attributeName ] !== undefined ) {
  37118. var accessorDef = json.accessors[ primitive.attributes[ attributeName ] ];
  37119. var componentType = WEBGL_COMPONENT_TYPES[ accessorDef.componentType ];
  37120. attributeTypeMap[ threeAttributeName ] = componentType;
  37121. attributeNormalizedMap[ threeAttributeName ] = accessorDef.normalized === true;
  37122. }
  37123. }
  37124. return parser.getDependency( 'bufferView', bufferViewIndex ).then( function ( bufferView ) {
  37125. return new Promise( function ( resolve ) {
  37126. dracoLoader.decodeDracoFile( bufferView, function ( geometry ) {
  37127. for ( var attributeName in geometry.attributes ) {
  37128. var attribute = geometry.attributes[ attributeName ];
  37129. var normalized = attributeNormalizedMap[ attributeName ];
  37130. if ( normalized !== undefined ) attribute.normalized = normalized;
  37131. }
  37132. resolve( geometry );
  37133. }, threeAttributeMap, attributeTypeMap );
  37134. } );
  37135. } );
  37136. };
  37137. /**
  37138. * Texture Transform Extension
  37139. *
  37140. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_texture_transform
  37141. */
  37142. function GLTFTextureTransformExtension() {
  37143. this.name = EXTENSIONS.KHR_TEXTURE_TRANSFORM;
  37144. }
  37145. GLTFTextureTransformExtension.prototype.extendTexture = function ( texture, transform ) {
  37146. texture = texture.clone();
  37147. if ( transform.offset !== undefined ) {
  37148. texture.offset.fromArray( transform.offset );
  37149. }
  37150. if ( transform.rotation !== undefined ) {
  37151. texture.rotation = transform.rotation;
  37152. }
  37153. if ( transform.scale !== undefined ) {
  37154. texture.repeat.fromArray( transform.scale );
  37155. }
  37156. if ( transform.texCoord !== undefined ) {
  37157. console.warn( 'THREE.GLTFLoader: Custom UV sets in "' + this.name + '" extension not yet supported.' );
  37158. }
  37159. texture.needsUpdate = true;
  37160. return texture;
  37161. };
  37162. /**
  37163. * Specular-Glossiness Extension
  37164. *
  37165. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness
  37166. */
  37167. /**
  37168. * A sub class of THREE.StandardMaterial with some of the functionality
  37169. * changed via the `onBeforeCompile` callback
  37170. * @pailhead
  37171. */
  37172. function GLTFMeshStandardSGMaterial( params ) {
  37173. THREE.MeshStandardMaterial.call( this );
  37174. this.isGLTFSpecularGlossinessMaterial = true;
  37175. //various chunks that need replacing
  37176. var specularMapParsFragmentChunk = [
  37177. '#ifdef USE_SPECULARMAP',
  37178. ' uniform sampler2D specularMap;',
  37179. '#endif'
  37180. ].join( '\n' );
  37181. var glossinessMapParsFragmentChunk = [
  37182. '#ifdef USE_GLOSSINESSMAP',
  37183. ' uniform sampler2D glossinessMap;',
  37184. '#endif'
  37185. ].join( '\n' );
  37186. var specularMapFragmentChunk = [
  37187. 'vec3 specularFactor = specular;',
  37188. '#ifdef USE_SPECULARMAP',
  37189. ' vec4 texelSpecular = texture2D( specularMap, vUv );',
  37190. ' texelSpecular = sRGBToLinear( texelSpecular );',
  37191. ' // reads channel RGB, compatible with a glTF Specular-Glossiness (RGBA) texture',
  37192. ' specularFactor *= texelSpecular.rgb;',
  37193. '#endif'
  37194. ].join( '\n' );
  37195. var glossinessMapFragmentChunk = [
  37196. 'float glossinessFactor = glossiness;',
  37197. '#ifdef USE_GLOSSINESSMAP',
  37198. ' vec4 texelGlossiness = texture2D( glossinessMap, vUv );',
  37199. ' // reads channel A, compatible with a glTF Specular-Glossiness (RGBA) texture',
  37200. ' glossinessFactor *= texelGlossiness.a;',
  37201. '#endif'
  37202. ].join( '\n' );
  37203. var lightPhysicalFragmentChunk = [
  37204. 'PhysicalMaterial material;',
  37205. 'material.diffuseColor = diffuseColor.rgb;',
  37206. 'vec3 dxy = max( abs( dFdx( geometryNormal ) ), abs( dFdy( geometryNormal ) ) );',
  37207. 'float geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z );',
  37208. 'material.specularRoughness = max( 1.0 - glossinessFactor, 0.0525 );// 0.0525 corresponds to the base mip of a 256 cubemap.',
  37209. 'material.specularRoughness += geometryRoughness;',
  37210. 'material.specularRoughness = min( material.specularRoughness, 1.0 );',
  37211. 'material.specularColor = specularFactor.rgb;',
  37212. ].join( '\n' );
  37213. var uniforms = {
  37214. specular: { value: new THREE.Color().setHex( 0xffffff ) },
  37215. glossiness: { value: 1 },
  37216. specularMap: { value: null },
  37217. glossinessMap: { value: null }
  37218. };
  37219. this._extraUniforms = uniforms;
  37220. // please see #14031 or #13198 for an alternate approach
  37221. this.onBeforeCompile = function ( shader ) {
  37222. for ( var uniformName in uniforms ) {
  37223. shader.uniforms[ uniformName ] = uniforms[ uniformName ];
  37224. }
  37225. shader.fragmentShader = shader.fragmentShader.replace( 'uniform float roughness;', 'uniform vec3 specular;' );
  37226. shader.fragmentShader = shader.fragmentShader.replace( 'uniform float metalness;', 'uniform float glossiness;' );
  37227. shader.fragmentShader = shader.fragmentShader.replace( '#include <roughnessmap_pars_fragment>', specularMapParsFragmentChunk );
  37228. shader.fragmentShader = shader.fragmentShader.replace( '#include <metalnessmap_pars_fragment>', glossinessMapParsFragmentChunk );
  37229. shader.fragmentShader = shader.fragmentShader.replace( '#include <roughnessmap_fragment>', specularMapFragmentChunk );
  37230. shader.fragmentShader = shader.fragmentShader.replace( '#include <metalnessmap_fragment>', glossinessMapFragmentChunk );
  37231. shader.fragmentShader = shader.fragmentShader.replace( '#include <lights_physical_fragment>', lightPhysicalFragmentChunk );
  37232. };
  37233. /*eslint-disable*/
  37234. Object.defineProperties(
  37235. this,
  37236. {
  37237. specular: {
  37238. get: function () { return uniforms.specular.value; },
  37239. set: function ( v ) { uniforms.specular.value = v; }
  37240. },
  37241. specularMap: {
  37242. get: function () { return uniforms.specularMap.value; },
  37243. set: function ( v ) { uniforms.specularMap.value = v; }
  37244. },
  37245. glossiness: {
  37246. get: function () { return uniforms.glossiness.value; },
  37247. set: function ( v ) { uniforms.glossiness.value = v; }
  37248. },
  37249. glossinessMap: {
  37250. get: function () { return uniforms.glossinessMap.value; },
  37251. set: function ( v ) {
  37252. uniforms.glossinessMap.value = v;
  37253. //how about something like this - @pailhead
  37254. if ( v ) {
  37255. this.defines.USE_GLOSSINESSMAP = '';
  37256. // set USE_ROUGHNESSMAP to enable vUv
  37257. this.defines.USE_ROUGHNESSMAP = '';
  37258. } else {
  37259. delete this.defines.USE_ROUGHNESSMAP;
  37260. delete this.defines.USE_GLOSSINESSMAP;
  37261. }
  37262. }
  37263. }
  37264. }
  37265. );
  37266. /*eslint-enable*/
  37267. delete this.metalness;
  37268. delete this.roughness;
  37269. delete this.metalnessMap;
  37270. delete this.roughnessMap;
  37271. this.setValues( params );
  37272. }
  37273. GLTFMeshStandardSGMaterial.prototype = Object.create( THREE.MeshStandardMaterial.prototype );
  37274. GLTFMeshStandardSGMaterial.prototype.constructor = GLTFMeshStandardSGMaterial;
  37275. GLTFMeshStandardSGMaterial.prototype.copy = function ( source ) {
  37276. THREE.MeshStandardMaterial.prototype.copy.call( this, source );
  37277. this.specularMap = source.specularMap;
  37278. this.specular.copy( source.specular );
  37279. this.glossinessMap = source.glossinessMap;
  37280. this.glossiness = source.glossiness;
  37281. delete this.metalness;
  37282. delete this.roughness;
  37283. delete this.metalnessMap;
  37284. delete this.roughnessMap;
  37285. return this;
  37286. };
  37287. function GLTFMaterialsPbrSpecularGlossinessExtension() {
  37288. return {
  37289. name: EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS,
  37290. specularGlossinessParams: [
  37291. 'color',
  37292. 'map',
  37293. 'lightMap',
  37294. 'lightMapIntensity',
  37295. 'aoMap',
  37296. 'aoMapIntensity',
  37297. 'emissive',
  37298. 'emissiveIntensity',
  37299. 'emissiveMap',
  37300. 'bumpMap',
  37301. 'bumpScale',
  37302. 'normalMap',
  37303. 'normalMapType',
  37304. 'displacementMap',
  37305. 'displacementScale',
  37306. 'displacementBias',
  37307. 'specularMap',
  37308. 'specular',
  37309. 'glossinessMap',
  37310. 'glossiness',
  37311. 'alphaMap',
  37312. 'envMap',
  37313. 'envMapIntensity',
  37314. 'refractionRatio',
  37315. ],
  37316. getMaterialType: function () {
  37317. return GLTFMeshStandardSGMaterial;
  37318. },
  37319. extendParams: function ( materialParams, materialDef, parser ) {
  37320. var pbrSpecularGlossiness = materialDef.extensions[ this.name ];
  37321. materialParams.color = new THREE.Color( 1.0, 1.0, 1.0 );
  37322. materialParams.opacity = 1.0;
  37323. var pending = [];
  37324. if ( Array.isArray( pbrSpecularGlossiness.diffuseFactor ) ) {
  37325. var array = pbrSpecularGlossiness.diffuseFactor;
  37326. materialParams.color.fromArray( array );
  37327. materialParams.opacity = array[ 3 ];
  37328. }
  37329. if ( pbrSpecularGlossiness.diffuseTexture !== undefined ) {
  37330. pending.push( parser.assignTexture( materialParams, 'map', pbrSpecularGlossiness.diffuseTexture ) );
  37331. }
  37332. materialParams.emissive = new THREE.Color( 0.0, 0.0, 0.0 );
  37333. materialParams.glossiness = pbrSpecularGlossiness.glossinessFactor !== undefined ? pbrSpecularGlossiness.glossinessFactor : 1.0;
  37334. materialParams.specular = new THREE.Color( 1.0, 1.0, 1.0 );
  37335. if ( Array.isArray( pbrSpecularGlossiness.specularFactor ) ) {
  37336. materialParams.specular.fromArray( pbrSpecularGlossiness.specularFactor );
  37337. }
  37338. if ( pbrSpecularGlossiness.specularGlossinessTexture !== undefined ) {
  37339. var specGlossMapDef = pbrSpecularGlossiness.specularGlossinessTexture;
  37340. pending.push( parser.assignTexture( materialParams, 'glossinessMap', specGlossMapDef ) );
  37341. pending.push( parser.assignTexture( materialParams, 'specularMap', specGlossMapDef ) );
  37342. }
  37343. return Promise.all( pending );
  37344. },
  37345. createMaterial: function ( materialParams ) {
  37346. var material = new GLTFMeshStandardSGMaterial( materialParams );
  37347. material.fog = true;
  37348. material.color = materialParams.color;
  37349. material.map = materialParams.map === undefined ? null : materialParams.map;
  37350. material.lightMap = null;
  37351. material.lightMapIntensity = 1.0;
  37352. material.aoMap = materialParams.aoMap === undefined ? null : materialParams.aoMap;
  37353. material.aoMapIntensity = 1.0;
  37354. material.emissive = materialParams.emissive;
  37355. material.emissiveIntensity = 1.0;
  37356. material.emissiveMap = materialParams.emissiveMap === undefined ? null : materialParams.emissiveMap;
  37357. material.bumpMap = materialParams.bumpMap === undefined ? null : materialParams.bumpMap;
  37358. material.bumpScale = 1;
  37359. material.normalMap = materialParams.normalMap === undefined ? null : materialParams.normalMap;
  37360. material.normalMapType = THREE.TangentSpaceNormalMap;
  37361. if ( materialParams.normalScale ) material.normalScale = materialParams.normalScale;
  37362. material.displacementMap = null;
  37363. material.displacementScale = 1;
  37364. material.displacementBias = 0;
  37365. material.specularMap = materialParams.specularMap === undefined ? null : materialParams.specularMap;
  37366. material.specular = materialParams.specular;
  37367. material.glossinessMap = materialParams.glossinessMap === undefined ? null : materialParams.glossinessMap;
  37368. material.glossiness = materialParams.glossiness;
  37369. material.alphaMap = null;
  37370. material.envMap = materialParams.envMap === undefined ? null : materialParams.envMap;
  37371. material.envMapIntensity = 1.0;
  37372. material.refractionRatio = 0.98;
  37373. return material;
  37374. },
  37375. };
  37376. }
  37377. /**
  37378. * Mesh Quantization Extension
  37379. *
  37380. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_mesh_quantization
  37381. */
  37382. function GLTFMeshQuantizationExtension() {
  37383. this.name = EXTENSIONS.KHR_MESH_QUANTIZATION;
  37384. }
  37385. /*********************************/
  37386. /********** INTERPOLATION ********/
  37387. /*********************************/
  37388. // Spline Interpolation
  37389. // Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#appendix-c-spline-interpolation
  37390. function GLTFCubicSplineInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  37391. THREE.Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  37392. }
  37393. GLTFCubicSplineInterpolant.prototype = Object.create( THREE.Interpolant.prototype );
  37394. GLTFCubicSplineInterpolant.prototype.constructor = GLTFCubicSplineInterpolant;
  37395. GLTFCubicSplineInterpolant.prototype.copySampleValue_ = function ( index ) {
  37396. // Copies a sample value to the result buffer. See description of glTF
  37397. // CUBICSPLINE values layout in interpolate_() function below.
  37398. var result = this.resultBuffer,
  37399. values = this.sampleValues,
  37400. valueSize = this.valueSize,
  37401. offset = index * valueSize * 3 + valueSize;
  37402. for ( var i = 0; i !== valueSize; i ++ ) {
  37403. result[ i ] = values[ offset + i ];
  37404. }
  37405. return result;
  37406. };
  37407. GLTFCubicSplineInterpolant.prototype.beforeStart_ = GLTFCubicSplineInterpolant.prototype.copySampleValue_;
  37408. GLTFCubicSplineInterpolant.prototype.afterEnd_ = GLTFCubicSplineInterpolant.prototype.copySampleValue_;
  37409. GLTFCubicSplineInterpolant.prototype.interpolate_ = function ( i1, t0, t, t1 ) {
  37410. var result = this.resultBuffer;
  37411. var values = this.sampleValues;
  37412. var stride = this.valueSize;
  37413. var stride2 = stride * 2;
  37414. var stride3 = stride * 3;
  37415. var td = t1 - t0;
  37416. var p = ( t - t0 ) / td;
  37417. var pp = p * p;
  37418. var ppp = pp * p;
  37419. var offset1 = i1 * stride3;
  37420. var offset0 = offset1 - stride3;
  37421. var s2 = - 2 * ppp + 3 * pp;
  37422. var s3 = ppp - pp;
  37423. var s0 = 1 - s2;
  37424. var s1 = s3 - pp + p;
  37425. // Layout of keyframe output values for CUBICSPLINE animations:
  37426. // [ inTangent_1, splineVertex_1, outTangent_1, inTangent_2, splineVertex_2, ... ]
  37427. for ( var i = 0; i !== stride; i ++ ) {
  37428. var p0 = values[ offset0 + i + stride ]; // splineVertex_k
  37429. var m0 = values[ offset0 + i + stride2 ] * td; // outTangent_k * (t_k+1 - t_k)
  37430. var p1 = values[ offset1 + i + stride ]; // splineVertex_k+1
  37431. var m1 = values[ offset1 + i ] * td; // inTangent_k+1 * (t_k+1 - t_k)
  37432. result[ i ] = s0 * p0 + s1 * m0 + s2 * p1 + s3 * m1;
  37433. }
  37434. return result;
  37435. };
  37436. /*********************************/
  37437. /********** INTERNALS ************/
  37438. /*********************************/
  37439. /* CONSTANTS */
  37440. var WEBGL_CONSTANTS = {
  37441. FLOAT: 5126,
  37442. //FLOAT_MAT2: 35674,
  37443. FLOAT_MAT3: 35675,
  37444. FLOAT_MAT4: 35676,
  37445. FLOAT_VEC2: 35664,
  37446. FLOAT_VEC3: 35665,
  37447. FLOAT_VEC4: 35666,
  37448. LINEAR: 9729,
  37449. REPEAT: 10497,
  37450. SAMPLER_2D: 35678,
  37451. POINTS: 0,
  37452. LINES: 1,
  37453. LINE_LOOP: 2,
  37454. LINE_STRIP: 3,
  37455. TRIANGLES: 4,
  37456. TRIANGLE_STRIP: 5,
  37457. TRIANGLE_FAN: 6,
  37458. UNSIGNED_BYTE: 5121,
  37459. UNSIGNED_SHORT: 5123
  37460. };
  37461. var WEBGL_COMPONENT_TYPES = {
  37462. 5120: Int8Array,
  37463. 5121: Uint8Array,
  37464. 5122: Int16Array,
  37465. 5123: Uint16Array,
  37466. 5125: Uint32Array,
  37467. 5126: Float32Array
  37468. };
  37469. var WEBGL_FILTERS = {
  37470. 9728: THREE.NearestFilter,
  37471. 9729: THREE.LinearFilter,
  37472. 9984: THREE.NearestMipmapNearestFilter,
  37473. 9985: THREE.LinearMipmapNearestFilter,
  37474. 9986: THREE.NearestMipmapLinearFilter,
  37475. 9987: THREE.LinearMipmapLinearFilter
  37476. };
  37477. var WEBGL_WRAPPINGS = {
  37478. 33071: THREE.ClampToEdgeWrapping,
  37479. 33648: THREE.MirroredRepeatWrapping,
  37480. 10497: THREE.RepeatWrapping
  37481. };
  37482. var WEBGL_TYPE_SIZES = {
  37483. 'SCALAR': 1,
  37484. 'VEC2': 2,
  37485. 'VEC3': 3,
  37486. 'VEC4': 4,
  37487. 'MAT2': 4,
  37488. 'MAT3': 9,
  37489. 'MAT4': 16
  37490. };
  37491. var ATTRIBUTES = {
  37492. POSITION: 'position',
  37493. NORMAL: 'normal',
  37494. TANGENT: 'tangent',
  37495. TEXCOORD_0: 'uv',
  37496. TEXCOORD_1: 'uv2',
  37497. COLOR_0: 'color',
  37498. WEIGHTS_0: 'skinWeight',
  37499. JOINTS_0: 'skinIndex',
  37500. };
  37501. var PATH_PROPERTIES = {
  37502. scale: 'scale',
  37503. translation: 'position',
  37504. rotation: 'quaternion',
  37505. weights: 'morphTargetInfluences'
  37506. };
  37507. var INTERPOLATION = {
  37508. CUBICSPLINE: undefined, // We use a custom interpolant (GLTFCubicSplineInterpolation) for CUBICSPLINE tracks. Each
  37509. // keyframe track will be initialized with a default interpolation type, then modified.
  37510. LINEAR: THREE.InterpolateLinear,
  37511. STEP: THREE.InterpolateDiscrete
  37512. };
  37513. var ALPHA_MODES = {
  37514. OPAQUE: 'OPAQUE',
  37515. MASK: 'MASK',
  37516. BLEND: 'BLEND'
  37517. };
  37518. var MIME_TYPE_FORMATS = {
  37519. 'image/png': THREE.RGBAFormat,
  37520. 'image/jpeg': THREE.RGBFormat
  37521. };
  37522. /* UTILITY FUNCTIONS */
  37523. function resolveURL( url, path ) {
  37524. // Invalid URL
  37525. if ( typeof url !== 'string' || url === '' ) return '';
  37526. // Host Relative URL
  37527. if ( /^https?:\/\//i.test( path ) && /^\//.test( url ) ) {
  37528. path = path.replace( /(^https?:\/\/[^\/]+).*/i, '$1' );
  37529. }
  37530. // Absolute URL http://,https://,//
  37531. if ( /^(https?:)?\/\//i.test( url ) ) return url;
  37532. // Data URI
  37533. if ( /^data:.*,.*$/i.test( url ) ) return url;
  37534. // Blob URL
  37535. if ( /^blob:.*$/i.test( url ) ) return url;
  37536. // Relative URL
  37537. return path + url;
  37538. }
  37539. /**
  37540. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#default-material
  37541. */
  37542. function createDefaultMaterial( cache ) {
  37543. if ( cache[ 'DefaultMaterial' ] === undefined ) {
  37544. cache[ 'DefaultMaterial' ] = new THREE.MeshStandardMaterial( {
  37545. color: 0xFFFFFF,
  37546. emissive: 0x000000,
  37547. metalness: 1,
  37548. roughness: 1,
  37549. transparent: false,
  37550. depthTest: true,
  37551. side: THREE.FrontSide
  37552. } );
  37553. }
  37554. return cache[ 'DefaultMaterial' ];
  37555. }
  37556. function addUnknownExtensionsToUserData( knownExtensions, object, objectDef ) {
  37557. // Add unknown glTF extensions to an object's userData.
  37558. for ( var name in objectDef.extensions ) {
  37559. if ( knownExtensions[ name ] === undefined ) {
  37560. object.userData.gltfExtensions = object.userData.gltfExtensions || {};
  37561. object.userData.gltfExtensions[ name ] = objectDef.extensions[ name ];
  37562. }
  37563. }
  37564. }
  37565. /**
  37566. * @param {THREE.Object3D|THREE.Material|THREE.BufferGeometry} object
  37567. * @param {GLTF.definition} gltfDef
  37568. */
  37569. function assignExtrasToUserData( object, gltfDef ) {
  37570. if ( gltfDef.extras !== undefined ) {
  37571. if ( typeof gltfDef.extras === 'object' ) {
  37572. Object.assign( object.userData, gltfDef.extras );
  37573. } else {
  37574. console.warn( 'THREE.GLTFLoader: Ignoring primitive type .extras, ' + gltfDef.extras );
  37575. }
  37576. }
  37577. }
  37578. /**
  37579. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#morph-targets
  37580. *
  37581. * @param {THREE.BufferGeometry} geometry
  37582. * @param {Array<GLTF.Target>} targets
  37583. * @param {GLTFParser} parser
  37584. * @return {Promise<THREE.BufferGeometry>}
  37585. */
  37586. function addMorphTargets( geometry, targets, parser ) {
  37587. var hasMorphPosition = false;
  37588. var hasMorphNormal = false;
  37589. for ( var i = 0, il = targets.length; i < il; i ++ ) {
  37590. var target = targets[ i ];
  37591. if ( target.POSITION !== undefined ) hasMorphPosition = true;
  37592. if ( target.NORMAL !== undefined ) hasMorphNormal = true;
  37593. if ( hasMorphPosition && hasMorphNormal ) break;
  37594. }
  37595. if ( ! hasMorphPosition && ! hasMorphNormal ) return Promise.resolve( geometry );
  37596. var pendingPositionAccessors = [];
  37597. var pendingNormalAccessors = [];
  37598. for ( var i = 0, il = targets.length; i < il; i ++ ) {
  37599. var target = targets[ i ];
  37600. if ( hasMorphPosition ) {
  37601. var pendingAccessor = target.POSITION !== undefined
  37602. ? parser.getDependency( 'accessor', target.POSITION )
  37603. : geometry.attributes.position;
  37604. pendingPositionAccessors.push( pendingAccessor );
  37605. }
  37606. if ( hasMorphNormal ) {
  37607. var pendingAccessor = target.NORMAL !== undefined
  37608. ? parser.getDependency( 'accessor', target.NORMAL )
  37609. : geometry.attributes.normal;
  37610. pendingNormalAccessors.push( pendingAccessor );
  37611. }
  37612. }
  37613. return Promise.all( [
  37614. Promise.all( pendingPositionAccessors ),
  37615. Promise.all( pendingNormalAccessors )
  37616. ] ).then( function ( accessors ) {
  37617. var morphPositions = accessors[ 0 ];
  37618. var morphNormals = accessors[ 1 ];
  37619. if ( hasMorphPosition ) geometry.morphAttributes.position = morphPositions;
  37620. if ( hasMorphNormal ) geometry.morphAttributes.normal = morphNormals;
  37621. geometry.morphTargetsRelative = true;
  37622. return geometry;
  37623. } );
  37624. }
  37625. /**
  37626. * @param {THREE.Mesh} mesh
  37627. * @param {GLTF.Mesh} meshDef
  37628. */
  37629. function updateMorphTargets( mesh, meshDef ) {
  37630. mesh.updateMorphTargets();
  37631. if ( meshDef.weights !== undefined ) {
  37632. for ( var i = 0, il = meshDef.weights.length; i < il; i ++ ) {
  37633. mesh.morphTargetInfluences[ i ] = meshDef.weights[ i ];
  37634. }
  37635. }
  37636. // .extras has user-defined data, so check that .extras.targetNames is an array.
  37637. if ( meshDef.extras && Array.isArray( meshDef.extras.targetNames ) ) {
  37638. var targetNames = meshDef.extras.targetNames;
  37639. if ( mesh.morphTargetInfluences.length === targetNames.length ) {
  37640. mesh.morphTargetDictionary = {};
  37641. for ( var i = 0, il = targetNames.length; i < il; i ++ ) {
  37642. mesh.morphTargetDictionary[ targetNames[ i ] ] = i;
  37643. }
  37644. } else {
  37645. console.warn( 'THREE.GLTFLoader: Invalid extras.targetNames length. Ignoring names.' );
  37646. }
  37647. }
  37648. }
  37649. function createPrimitiveKey( primitiveDef ) {
  37650. var dracoExtension = primitiveDef.extensions && primitiveDef.extensions[ EXTENSIONS.KHR_DRACO_MESH_COMPRESSION ];
  37651. var geometryKey;
  37652. if ( dracoExtension ) {
  37653. geometryKey = 'draco:' + dracoExtension.bufferView
  37654. + ':' + dracoExtension.indices
  37655. + ':' + createAttributesKey( dracoExtension.attributes );
  37656. } else {
  37657. geometryKey = primitiveDef.indices + ':' + createAttributesKey( primitiveDef.attributes ) + ':' + primitiveDef.mode;
  37658. }
  37659. return geometryKey;
  37660. }
  37661. function createAttributesKey( attributes ) {
  37662. var attributesKey = '';
  37663. var keys = Object.keys( attributes ).sort();
  37664. for ( var i = 0, il = keys.length; i < il; i ++ ) {
  37665. attributesKey += keys[ i ] + ':' + attributes[ keys[ i ] ] + ';';
  37666. }
  37667. return attributesKey;
  37668. }
  37669. /* GLTF PARSER */
  37670. function GLTFParser( json, extensions, options ) {
  37671. this.json = json || {};
  37672. this.extensions = extensions || {};
  37673. this.options = options || {};
  37674. // loader object cache
  37675. this.cache = new GLTFRegistry();
  37676. // BufferGeometry caching
  37677. this.primitiveCache = {};
  37678. this.textureLoader = new THREE.TextureLoader( this.options.manager );
  37679. this.textureLoader.setCrossOrigin( this.options.crossOrigin );
  37680. this.fileLoader = new THREE.FileLoader( this.options.manager );
  37681. this.fileLoader.setResponseType( 'arraybuffer' );
  37682. if ( this.options.crossOrigin === 'use-credentials' ) {
  37683. this.fileLoader.setWithCredentials( true );
  37684. }
  37685. }
  37686. GLTFParser.prototype.parse = function ( onLoad, onError ) {
  37687. var parser = this;
  37688. var json = this.json;
  37689. var extensions = this.extensions;
  37690. // Clear the loader cache
  37691. this.cache.removeAll();
  37692. // Mark the special nodes/meshes in json for efficient parse
  37693. this.markDefs();
  37694. Promise.all( [
  37695. this.getDependencies( 'scene' ),
  37696. this.getDependencies( 'animation' ),
  37697. this.getDependencies( 'camera' ),
  37698. ] ).then( function ( dependencies ) {
  37699. var result = {
  37700. scene: dependencies[ 0 ][ json.scene || 0 ],
  37701. scenes: dependencies[ 0 ],
  37702. animations: dependencies[ 1 ],
  37703. cameras: dependencies[ 2 ],
  37704. asset: json.asset,
  37705. parser: parser,
  37706. userData: {}
  37707. };
  37708. addUnknownExtensionsToUserData( extensions, result, json );
  37709. assignExtrasToUserData( result, json );
  37710. onLoad( result );
  37711. } ).catch( onError );
  37712. };
  37713. /**
  37714. * Marks the special nodes/meshes in json for efficient parse.
  37715. */
  37716. GLTFParser.prototype.markDefs = function () {
  37717. var nodeDefs = this.json.nodes || [];
  37718. var skinDefs = this.json.skins || [];
  37719. var meshDefs = this.json.meshes || [];
  37720. var meshReferences = {};
  37721. var meshUses = {};
  37722. // Nothing in the node definition indicates whether it is a Bone or an
  37723. // Object3D. Use the skins' joint references to mark bones.
  37724. for ( var skinIndex = 0, skinLength = skinDefs.length; skinIndex < skinLength; skinIndex ++ ) {
  37725. var joints = skinDefs[ skinIndex ].joints;
  37726. for ( var i = 0, il = joints.length; i < il; i ++ ) {
  37727. nodeDefs[ joints[ i ] ].isBone = true;
  37728. }
  37729. }
  37730. // Meshes can (and should) be reused by multiple nodes in a glTF asset. To
  37731. // avoid having more than one THREE.Mesh with the same name, count
  37732. // references and rename instances below.
  37733. //
  37734. // Example: CesiumMilkTruck sample model reuses "Wheel" meshes.
  37735. for ( var nodeIndex = 0, nodeLength = nodeDefs.length; nodeIndex < nodeLength; nodeIndex ++ ) {
  37736. var nodeDef = nodeDefs[ nodeIndex ];
  37737. if ( nodeDef.mesh !== undefined ) {
  37738. if ( meshReferences[ nodeDef.mesh ] === undefined ) {
  37739. meshReferences[ nodeDef.mesh ] = meshUses[ nodeDef.mesh ] = 0;
  37740. }
  37741. meshReferences[ nodeDef.mesh ] ++;
  37742. // Nothing in the mesh definition indicates whether it is
  37743. // a SkinnedMesh or Mesh. Use the node's mesh reference
  37744. // to mark SkinnedMesh if node has skin.
  37745. if ( nodeDef.skin !== undefined ) {
  37746. meshDefs[ nodeDef.mesh ].isSkinnedMesh = true;
  37747. }
  37748. }
  37749. }
  37750. this.json.meshReferences = meshReferences;
  37751. this.json.meshUses = meshUses;
  37752. };
  37753. /**
  37754. * Requests the specified dependency asynchronously, with caching.
  37755. * @param {string} type
  37756. * @param {number} index
  37757. * @return {Promise<THREE.Object3D|THREE.Material|THREE.Texture|THREE.AnimationClip|ArrayBuffer|Object>}
  37758. */
  37759. GLTFParser.prototype.getDependency = function ( type, index ) {
  37760. var cacheKey = type + ':' + index;
  37761. var dependency = this.cache.get( cacheKey );
  37762. if ( ! dependency ) {
  37763. switch ( type ) {
  37764. case 'scene':
  37765. dependency = this.loadScene( index );
  37766. break;
  37767. case 'node':
  37768. dependency = this.loadNode( index );
  37769. break;
  37770. case 'mesh':
  37771. dependency = this.loadMesh( index );
  37772. break;
  37773. case 'accessor':
  37774. dependency = this.loadAccessor( index );
  37775. break;
  37776. case 'bufferView':
  37777. dependency = this.loadBufferView( index );
  37778. break;
  37779. case 'buffer':
  37780. dependency = this.loadBuffer( index );
  37781. break;
  37782. case 'material':
  37783. dependency = this.loadMaterial( index );
  37784. break;
  37785. case 'texture':
  37786. dependency = this.loadTexture( index );
  37787. break;
  37788. case 'skin':
  37789. dependency = this.loadSkin( index );
  37790. break;
  37791. case 'animation':
  37792. dependency = this.loadAnimation( index );
  37793. break;
  37794. case 'camera':
  37795. dependency = this.loadCamera( index );
  37796. break;
  37797. case 'light':
  37798. dependency = this.extensions[ EXTENSIONS.KHR_LIGHTS_PUNCTUAL ].loadLight( index );
  37799. break;
  37800. default:
  37801. throw new Error( 'Unknown type: ' + type );
  37802. }
  37803. this.cache.add( cacheKey, dependency );
  37804. }
  37805. return dependency;
  37806. };
  37807. /**
  37808. * Requests all dependencies of the specified type asynchronously, with caching.
  37809. * @param {string} type
  37810. * @return {Promise<Array<Object>>}
  37811. */
  37812. GLTFParser.prototype.getDependencies = function ( type ) {
  37813. var dependencies = this.cache.get( type );
  37814. if ( ! dependencies ) {
  37815. var parser = this;
  37816. var defs = this.json[ type + ( type === 'mesh' ? 'es' : 's' ) ] || [];
  37817. dependencies = Promise.all( defs.map( function ( def, index ) {
  37818. return parser.getDependency( type, index );
  37819. } ) );
  37820. this.cache.add( type, dependencies );
  37821. }
  37822. return dependencies;
  37823. };
  37824. /**
  37825. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#buffers-and-buffer-views
  37826. * @param {number} bufferIndex
  37827. * @return {Promise<ArrayBuffer>}
  37828. */
  37829. GLTFParser.prototype.loadBuffer = function ( bufferIndex ) {
  37830. var bufferDef = this.json.buffers[ bufferIndex ];
  37831. var loader = this.fileLoader;
  37832. if ( bufferDef.type && bufferDef.type !== 'arraybuffer' ) {
  37833. throw new Error( 'THREE.GLTFLoader: ' + bufferDef.type + ' buffer type is not supported.' );
  37834. }
  37835. // If present, GLB container is required to be the first buffer.
  37836. if ( bufferDef.uri === undefined && bufferIndex === 0 ) {
  37837. return Promise.resolve( this.extensions[ EXTENSIONS.KHR_BINARY_GLTF ].body );
  37838. }
  37839. var options = this.options;
  37840. return new Promise( function ( resolve, reject ) {
  37841. loader.load( resolveURL( bufferDef.uri, options.path ), resolve, undefined, function () {
  37842. reject( new Error( 'THREE.GLTFLoader: Failed to load buffer "' + bufferDef.uri + '".' ) );
  37843. } );
  37844. } );
  37845. };
  37846. /**
  37847. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#buffers-and-buffer-views
  37848. * @param {number} bufferViewIndex
  37849. * @return {Promise<ArrayBuffer>}
  37850. */
  37851. GLTFParser.prototype.loadBufferView = function ( bufferViewIndex ) {
  37852. var bufferViewDef = this.json.bufferViews[ bufferViewIndex ];
  37853. return this.getDependency( 'buffer', bufferViewDef.buffer ).then( function ( buffer ) {
  37854. var byteLength = bufferViewDef.byteLength || 0;
  37855. var byteOffset = bufferViewDef.byteOffset || 0;
  37856. return buffer.slice( byteOffset, byteOffset + byteLength );
  37857. } );
  37858. };
  37859. /**
  37860. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#accessors
  37861. * @param {number} accessorIndex
  37862. * @return {Promise<THREE.BufferAttribute|THREE.InterleavedBufferAttribute>}
  37863. */
  37864. GLTFParser.prototype.loadAccessor = function ( accessorIndex ) {
  37865. var parser = this;
  37866. var json = this.json;
  37867. var accessorDef = this.json.accessors[ accessorIndex ];
  37868. if ( accessorDef.bufferView === undefined && accessorDef.sparse === undefined ) {
  37869. // Ignore empty accessors, which may be used to declare runtime
  37870. // information about attributes coming from another source (e.g. Draco
  37871. // compression extension).
  37872. return Promise.resolve( null );
  37873. }
  37874. var pendingBufferViews = [];
  37875. if ( accessorDef.bufferView !== undefined ) {
  37876. pendingBufferViews.push( this.getDependency( 'bufferView', accessorDef.bufferView ) );
  37877. } else {
  37878. pendingBufferViews.push( null );
  37879. }
  37880. if ( accessorDef.sparse !== undefined ) {
  37881. pendingBufferViews.push( this.getDependency( 'bufferView', accessorDef.sparse.indices.bufferView ) );
  37882. pendingBufferViews.push( this.getDependency( 'bufferView', accessorDef.sparse.values.bufferView ) );
  37883. }
  37884. return Promise.all( pendingBufferViews ).then( function ( bufferViews ) {
  37885. var bufferView = bufferViews[ 0 ];
  37886. var itemSize = WEBGL_TYPE_SIZES[ accessorDef.type ];
  37887. var TypedArray = WEBGL_COMPONENT_TYPES[ accessorDef.componentType ];
  37888. // For VEC3: itemSize is 3, elementBytes is 4, itemBytes is 12.
  37889. var elementBytes = TypedArray.BYTES_PER_ELEMENT;
  37890. var itemBytes = elementBytes * itemSize;
  37891. var byteOffset = accessorDef.byteOffset || 0;
  37892. var byteStride = accessorDef.bufferView !== undefined ? json.bufferViews[ accessorDef.bufferView ].byteStride : undefined;
  37893. var normalized = accessorDef.normalized === true;
  37894. var array, bufferAttribute;
  37895. // The buffer is not interleaved if the stride is the item size in bytes.
  37896. if ( byteStride && byteStride !== itemBytes ) {
  37897. // Each "slice" of the buffer, as defined by 'count' elements of 'byteStride' bytes, gets its own InterleavedBuffer
  37898. // This makes sure that IBA.count reflects accessor.count properly
  37899. var ibSlice = Math.floor( byteOffset / byteStride );
  37900. var ibCacheKey = 'InterleavedBuffer:' + accessorDef.bufferView + ':' + accessorDef.componentType + ':' + ibSlice + ':' + accessorDef.count;
  37901. var ib = parser.cache.get( ibCacheKey );
  37902. if ( ! ib ) {
  37903. array = new TypedArray( bufferView, ibSlice * byteStride, accessorDef.count * byteStride / elementBytes );
  37904. // Integer parameters to IB/IBA are in array elements, not bytes.
  37905. ib = new THREE.InterleavedBuffer( array, byteStride / elementBytes );
  37906. parser.cache.add( ibCacheKey, ib );
  37907. }
  37908. bufferAttribute = new THREE.InterleavedBufferAttribute( ib, itemSize, ( byteOffset % byteStride ) / elementBytes, normalized );
  37909. } else {
  37910. if ( bufferView === null ) {
  37911. array = new TypedArray( accessorDef.count * itemSize );
  37912. } else {
  37913. array = new TypedArray( bufferView, byteOffset, accessorDef.count * itemSize );
  37914. }
  37915. bufferAttribute = new THREE.BufferAttribute( array, itemSize, normalized );
  37916. }
  37917. // https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#sparse-accessors
  37918. if ( accessorDef.sparse !== undefined ) {
  37919. var itemSizeIndices = WEBGL_TYPE_SIZES.SCALAR;
  37920. var TypedArrayIndices = WEBGL_COMPONENT_TYPES[ accessorDef.sparse.indices.componentType ];
  37921. var byteOffsetIndices = accessorDef.sparse.indices.byteOffset || 0;
  37922. var byteOffsetValues = accessorDef.sparse.values.byteOffset || 0;
  37923. var sparseIndices = new TypedArrayIndices( bufferViews[ 1 ], byteOffsetIndices, accessorDef.sparse.count * itemSizeIndices );
  37924. var sparseValues = new TypedArray( bufferViews[ 2 ], byteOffsetValues, accessorDef.sparse.count * itemSize );
  37925. if ( bufferView !== null ) {
  37926. // Avoid modifying the original ArrayBuffer, if the bufferView wasn't initialized with zeroes.
  37927. bufferAttribute = new THREE.BufferAttribute( bufferAttribute.array.slice(), bufferAttribute.itemSize, bufferAttribute.normalized );
  37928. }
  37929. for ( var i = 0, il = sparseIndices.length; i < il; i ++ ) {
  37930. var index = sparseIndices[ i ];
  37931. bufferAttribute.setX( index, sparseValues[ i * itemSize ] );
  37932. if ( itemSize >= 2 ) bufferAttribute.setY( index, sparseValues[ i * itemSize + 1 ] );
  37933. if ( itemSize >= 3 ) bufferAttribute.setZ( index, sparseValues[ i * itemSize + 2 ] );
  37934. if ( itemSize >= 4 ) bufferAttribute.setW( index, sparseValues[ i * itemSize + 3 ] );
  37935. if ( itemSize >= 5 ) throw new Error( 'THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute.' );
  37936. }
  37937. }
  37938. return bufferAttribute;
  37939. } );
  37940. };
  37941. /**
  37942. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#textures
  37943. * @param {number} textureIndex
  37944. * @return {Promise<THREE.Texture>}
  37945. */
  37946. GLTFParser.prototype.loadTexture = function ( textureIndex ) {
  37947. var parser = this;
  37948. var json = this.json;
  37949. var options = this.options;
  37950. var textureLoader = this.textureLoader;
  37951. var URL = self.URL || self.webkitURL;
  37952. var textureDef = json.textures[ textureIndex ];
  37953. var textureExtensions = textureDef.extensions || {};
  37954. var source;
  37955. if ( textureExtensions[ EXTENSIONS.MSFT_TEXTURE_DDS ] ) {
  37956. source = json.images[ textureExtensions[ EXTENSIONS.MSFT_TEXTURE_DDS ].source ];
  37957. } else {
  37958. source = json.images[ textureDef.source ];
  37959. }
  37960. var sourceURI = source.uri;
  37961. var isObjectURL = false;
  37962. if ( source.bufferView !== undefined ) {
  37963. // Load binary image data from bufferView, if provided.
  37964. sourceURI = parser.getDependency( 'bufferView', source.bufferView ).then( function ( bufferView ) {
  37965. isObjectURL = true;
  37966. var blob = new Blob( [ bufferView ], { type: source.mimeType } );
  37967. sourceURI = URL.createObjectURL( blob );
  37968. return sourceURI;
  37969. } );
  37970. }
  37971. return Promise.resolve( sourceURI ).then( function ( sourceURI ) {
  37972. // Load Texture resource.
  37973. var loader = options.manager.getHandler( sourceURI );
  37974. if ( ! loader ) {
  37975. loader = textureExtensions[ EXTENSIONS.MSFT_TEXTURE_DDS ]
  37976. ? parser.extensions[ EXTENSIONS.MSFT_TEXTURE_DDS ].ddsLoader
  37977. : textureLoader;
  37978. }
  37979. return new Promise( function ( resolve, reject ) {
  37980. loader.load( resolveURL( sourceURI, options.path ), resolve, undefined, reject );
  37981. } );
  37982. } ).then( function ( texture ) {
  37983. // Clean up resources and configure Texture.
  37984. if ( isObjectURL === true ) {
  37985. URL.revokeObjectURL( sourceURI );
  37986. }
  37987. texture.flipY = false;
  37988. if ( textureDef.name ) texture.name = textureDef.name;
  37989. // Ignore unknown mime types, like DDS files.
  37990. if ( source.mimeType in MIME_TYPE_FORMATS ) {
  37991. texture.format = MIME_TYPE_FORMATS[ source.mimeType ];
  37992. }
  37993. var samplers = json.samplers || {};
  37994. var sampler = samplers[ textureDef.sampler ] || {};
  37995. texture.magFilter = WEBGL_FILTERS[ sampler.magFilter ] || THREE.LinearFilter;
  37996. texture.minFilter = WEBGL_FILTERS[ sampler.minFilter ] || THREE.LinearMipmapLinearFilter;
  37997. texture.wrapS = WEBGL_WRAPPINGS[ sampler.wrapS ] || THREE.RepeatWrapping;
  37998. texture.wrapT = WEBGL_WRAPPINGS[ sampler.wrapT ] || THREE.RepeatWrapping;
  37999. return texture;
  38000. } );
  38001. };
  38002. /**
  38003. * Asynchronously assigns a texture to the given material parameters.
  38004. * @param {Object} materialParams
  38005. * @param {string} mapName
  38006. * @param {Object} mapDef
  38007. * @return {Promise}
  38008. */
  38009. GLTFParser.prototype.assignTexture = function ( materialParams, mapName, mapDef ) {
  38010. var parser = this;
  38011. return this.getDependency( 'texture', mapDef.index ).then( function ( texture ) {
  38012. if ( ! texture.isCompressedTexture ) {
  38013. switch ( mapName ) {
  38014. case 'aoMap':
  38015. case 'emissiveMap':
  38016. case 'metalnessMap':
  38017. case 'normalMap':
  38018. case 'roughnessMap':
  38019. texture.format = THREE.RGBFormat;
  38020. break;
  38021. }
  38022. }
  38023. // Materials sample aoMap from UV set 1 and other maps from UV set 0 - this can't be configured
  38024. // However, we will copy UV set 0 to UV set 1 on demand for aoMap
  38025. if ( mapDef.texCoord !== undefined && mapDef.texCoord != 0 && ! ( mapName === 'aoMap' && mapDef.texCoord == 1 ) ) {
  38026. console.warn( 'THREE.GLTFLoader: Custom UV set ' + mapDef.texCoord + ' for texture ' + mapName + ' not yet supported.' );
  38027. }
  38028. if ( parser.extensions[ EXTENSIONS.KHR_TEXTURE_TRANSFORM ] ) {
  38029. var transform = mapDef.extensions !== undefined ? mapDef.extensions[ EXTENSIONS.KHR_TEXTURE_TRANSFORM ] : undefined;
  38030. if ( transform ) {
  38031. texture = parser.extensions[ EXTENSIONS.KHR_TEXTURE_TRANSFORM ].extendTexture( texture, transform );
  38032. }
  38033. }
  38034. materialParams[ mapName ] = texture;
  38035. } );
  38036. };
  38037. /**
  38038. * Assigns final material to a Mesh, Line, or Points instance. The instance
  38039. * already has a material (generated from the glTF material options alone)
  38040. * but reuse of the same glTF material may require multiple threejs materials
  38041. * to accomodate different primitive types, defines, etc. New materials will
  38042. * be created if necessary, and reused from a cache.
  38043. * @param {THREE.Object3D} mesh Mesh, Line, or Points instance.
  38044. */
  38045. GLTFParser.prototype.assignFinalMaterial = function ( mesh ) {
  38046. var geometry = mesh.geometry;
  38047. var material = mesh.material;
  38048. var useVertexTangents = geometry.attributes.tangent !== undefined;
  38049. var useVertexColors = geometry.attributes.color !== undefined;
  38050. var useFlatShading = geometry.attributes.normal === undefined;
  38051. var useSkinning = mesh.isSkinnedMesh === true;
  38052. var useMorphTargets = Object.keys( geometry.morphAttributes ).length > 0;
  38053. var useMorphNormals = useMorphTargets && geometry.morphAttributes.normal !== undefined;
  38054. if ( mesh.isPoints ) {
  38055. var cacheKey = 'PointsMaterial:' + material.uuid;
  38056. var pointsMaterial = this.cache.get( cacheKey );
  38057. if ( ! pointsMaterial ) {
  38058. pointsMaterial = new THREE.PointsMaterial();
  38059. THREE.Material.prototype.copy.call( pointsMaterial, material );
  38060. pointsMaterial.color.copy( material.color );
  38061. pointsMaterial.map = material.map;
  38062. pointsMaterial.sizeAttenuation = false; // glTF spec says points should be 1px
  38063. this.cache.add( cacheKey, pointsMaterial );
  38064. }
  38065. material = pointsMaterial;
  38066. } else if ( mesh.isLine ) {
  38067. var cacheKey = 'LineBasicMaterial:' + material.uuid;
  38068. var lineMaterial = this.cache.get( cacheKey );
  38069. if ( ! lineMaterial ) {
  38070. lineMaterial = new THREE.LineBasicMaterial();
  38071. THREE.Material.prototype.copy.call( lineMaterial, material );
  38072. lineMaterial.color.copy( material.color );
  38073. this.cache.add( cacheKey, lineMaterial );
  38074. }
  38075. material = lineMaterial;
  38076. }
  38077. // Clone the material if it will be modified
  38078. if ( useVertexTangents || useVertexColors || useFlatShading || useSkinning || useMorphTargets ) {
  38079. var cacheKey = 'ClonedMaterial:' + material.uuid + ':';
  38080. if ( material.isGLTFSpecularGlossinessMaterial ) cacheKey += 'specular-glossiness:';
  38081. if ( useSkinning ) cacheKey += 'skinning:';
  38082. if ( useVertexTangents ) cacheKey += 'vertex-tangents:';
  38083. if ( useVertexColors ) cacheKey += 'vertex-colors:';
  38084. if ( useFlatShading ) cacheKey += 'flat-shading:';
  38085. if ( useMorphTargets ) cacheKey += 'morph-targets:';
  38086. if ( useMorphNormals ) cacheKey += 'morph-normals:';
  38087. var cachedMaterial = this.cache.get( cacheKey );
  38088. if ( ! cachedMaterial ) {
  38089. cachedMaterial = material.clone();
  38090. if ( useSkinning ) cachedMaterial.skinning = true;
  38091. if ( useVertexTangents ) cachedMaterial.vertexTangents = true;
  38092. if ( useVertexColors ) cachedMaterial.vertexColors = true;
  38093. if ( useFlatShading ) cachedMaterial.flatShading = true;
  38094. if ( useMorphTargets ) cachedMaterial.morphTargets = true;
  38095. if ( useMorphNormals ) cachedMaterial.morphNormals = true;
  38096. this.cache.add( cacheKey, cachedMaterial );
  38097. }
  38098. material = cachedMaterial;
  38099. }
  38100. // workarounds for mesh and geometry
  38101. if ( material.aoMap && geometry.attributes.uv2 === undefined && geometry.attributes.uv !== undefined ) {
  38102. geometry.setAttribute( 'uv2', new THREE.BufferAttribute( geometry.attributes.uv.array, 2 ) );
  38103. }
  38104. // https://github.com/mrdoob/three.js/issues/11438#issuecomment-507003995
  38105. if ( material.normalScale && ! useVertexTangents ) {
  38106. material.normalScale.y = - material.normalScale.y;
  38107. }
  38108. if ( material.clearcoatNormalScale && ! useVertexTangents ) {
  38109. material.clearcoatNormalScale.y = - material.clearcoatNormalScale.y;
  38110. }
  38111. mesh.material = material;
  38112. };
  38113. /**
  38114. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#materials
  38115. * @param {number} materialIndex
  38116. * @return {Promise<THREE.Material>}
  38117. */
  38118. GLTFParser.prototype.loadMaterial = function ( materialIndex ) {
  38119. var parser = this;
  38120. var json = this.json;
  38121. var extensions = this.extensions;
  38122. var materialDef = json.materials[ materialIndex ];
  38123. var materialType;
  38124. var materialParams = {};
  38125. var materialExtensions = materialDef.extensions || {};
  38126. var pending = [];
  38127. if ( materialExtensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ] ) {
  38128. var sgExtension = extensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ];
  38129. materialType = sgExtension.getMaterialType();
  38130. pending.push( sgExtension.extendParams( materialParams, materialDef, parser ) );
  38131. } else if ( materialExtensions[ EXTENSIONS.KHR_MATERIALS_UNLIT ] ) {
  38132. var kmuExtension = extensions[ EXTENSIONS.KHR_MATERIALS_UNLIT ];
  38133. materialType = kmuExtension.getMaterialType();
  38134. pending.push( kmuExtension.extendParams( materialParams, materialDef, parser ) );
  38135. } else {
  38136. // Specification:
  38137. // https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#metallic-roughness-material
  38138. materialType = THREE.MeshStandardMaterial;
  38139. var metallicRoughness = materialDef.pbrMetallicRoughness || {};
  38140. materialParams.color = new THREE.Color( 1.0, 1.0, 1.0 );
  38141. materialParams.opacity = 1.0;
  38142. if ( Array.isArray( metallicRoughness.baseColorFactor ) ) {
  38143. var array = metallicRoughness.baseColorFactor;
  38144. materialParams.color.fromArray( array );
  38145. materialParams.opacity = array[ 3 ];
  38146. }
  38147. if ( metallicRoughness.baseColorTexture !== undefined ) {
  38148. pending.push( parser.assignTexture( materialParams, 'map', metallicRoughness.baseColorTexture ) );
  38149. }
  38150. materialParams.metalness = metallicRoughness.metallicFactor !== undefined ? metallicRoughness.metallicFactor : 1.0;
  38151. materialParams.roughness = metallicRoughness.roughnessFactor !== undefined ? metallicRoughness.roughnessFactor : 1.0;
  38152. if ( metallicRoughness.metallicRoughnessTexture !== undefined ) {
  38153. pending.push( parser.assignTexture( materialParams, 'metalnessMap', metallicRoughness.metallicRoughnessTexture ) );
  38154. pending.push( parser.assignTexture( materialParams, 'roughnessMap', metallicRoughness.metallicRoughnessTexture ) );
  38155. }
  38156. }
  38157. if ( materialDef.doubleSided === true ) {
  38158. materialParams.side = THREE.DoubleSide;
  38159. }
  38160. var alphaMode = materialDef.alphaMode || ALPHA_MODES.OPAQUE;
  38161. if ( alphaMode === ALPHA_MODES.BLEND ) {
  38162. materialParams.transparent = true;
  38163. // See: https://github.com/mrdoob/three.js/issues/17706
  38164. materialParams.depthWrite = false;
  38165. } else {
  38166. materialParams.transparent = false;
  38167. if ( alphaMode === ALPHA_MODES.MASK ) {
  38168. materialParams.alphaTest = materialDef.alphaCutoff !== undefined ? materialDef.alphaCutoff : 0.5;
  38169. }
  38170. }
  38171. if ( materialDef.normalTexture !== undefined && materialType !== THREE.MeshBasicMaterial ) {
  38172. pending.push( parser.assignTexture( materialParams, 'normalMap', materialDef.normalTexture ) );
  38173. materialParams.normalScale = new THREE.Vector2( 1, 1 );
  38174. if ( materialDef.normalTexture.scale !== undefined ) {
  38175. materialParams.normalScale.set( materialDef.normalTexture.scale, materialDef.normalTexture.scale );
  38176. }
  38177. }
  38178. if ( materialDef.occlusionTexture !== undefined && materialType !== THREE.MeshBasicMaterial ) {
  38179. pending.push( parser.assignTexture( materialParams, 'aoMap', materialDef.occlusionTexture ) );
  38180. if ( materialDef.occlusionTexture.strength !== undefined ) {
  38181. materialParams.aoMapIntensity = materialDef.occlusionTexture.strength;
  38182. }
  38183. }
  38184. if ( materialDef.emissiveFactor !== undefined && materialType !== THREE.MeshBasicMaterial ) {
  38185. materialParams.emissive = new THREE.Color().fromArray( materialDef.emissiveFactor );
  38186. }
  38187. if ( materialDef.emissiveTexture !== undefined && materialType !== THREE.MeshBasicMaterial ) {
  38188. pending.push( parser.assignTexture( materialParams, 'emissiveMap', materialDef.emissiveTexture ) );
  38189. }
  38190. if ( materialExtensions[ EXTENSIONS.KHR_MATERIALS_CLEARCOAT ] ) {
  38191. var clearcoatExtension = extensions[ EXTENSIONS.KHR_MATERIALS_CLEARCOAT ];
  38192. materialType = clearcoatExtension.getMaterialType();
  38193. pending.push( clearcoatExtension.extendParams( materialParams, { extensions: materialExtensions }, parser ) );
  38194. }
  38195. return Promise.all( pending ).then( function () {
  38196. var material;
  38197. if ( materialType === GLTFMeshStandardSGMaterial ) {
  38198. material = extensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ].createMaterial( materialParams );
  38199. } else {
  38200. material = new materialType( materialParams );
  38201. }
  38202. if ( materialDef.name ) material.name = materialDef.name;
  38203. // baseColorTexture, emissiveTexture, and specularGlossinessTexture use sRGB encoding.
  38204. if ( material.map ) material.map.encoding = THREE.sRGBEncoding;
  38205. if ( material.emissiveMap ) material.emissiveMap.encoding = THREE.sRGBEncoding;
  38206. assignExtrasToUserData( material, materialDef );
  38207. if ( materialDef.extensions ) addUnknownExtensionsToUserData( extensions, material, materialDef );
  38208. return material;
  38209. } );
  38210. };
  38211. /**
  38212. * @param {THREE.BufferGeometry} geometry
  38213. * @param {GLTF.Primitive} primitiveDef
  38214. * @param {GLTFParser} parser
  38215. */
  38216. function computeBounds( geometry, primitiveDef, parser ) {
  38217. var attributes = primitiveDef.attributes;
  38218. var box = new THREE.Box3();
  38219. if ( attributes.POSITION !== undefined ) {
  38220. var accessor = parser.json.accessors[ attributes.POSITION ];
  38221. var min = accessor.min;
  38222. var max = accessor.max;
  38223. // glTF requires 'min' and 'max', but VRM (which extends glTF) currently ignores that requirement.
  38224. if ( min !== undefined && max !== undefined ) {
  38225. box.set(
  38226. new THREE.Vector3( min[ 0 ], min[ 1 ], min[ 2 ] ),
  38227. new THREE.Vector3( max[ 0 ], max[ 1 ], max[ 2 ] ) );
  38228. } else {
  38229. console.warn( 'THREE.GLTFLoader: Missing min/max properties for accessor POSITION.' );
  38230. return;
  38231. }
  38232. } else {
  38233. return;
  38234. }
  38235. var targets = primitiveDef.targets;
  38236. if ( targets !== undefined ) {
  38237. var maxDisplacement = new THREE.Vector3();
  38238. var vector = new THREE.Vector3();
  38239. for ( var i = 0, il = targets.length; i < il; i ++ ) {
  38240. var target = targets[ i ];
  38241. if ( target.POSITION !== undefined ) {
  38242. var accessor = parser.json.accessors[ target.POSITION ];
  38243. var min = accessor.min;
  38244. var max = accessor.max;
  38245. // glTF requires 'min' and 'max', but VRM (which extends glTF) currently ignores that requirement.
  38246. if ( min !== undefined && max !== undefined ) {
  38247. // we need to get max of absolute components because target weight is [-1,1]
  38248. vector.setX( Math.max( Math.abs( min[ 0 ] ), Math.abs( max[ 0 ] ) ) );
  38249. vector.setY( Math.max( Math.abs( min[ 1 ] ), Math.abs( max[ 1 ] ) ) );
  38250. vector.setZ( Math.max( Math.abs( min[ 2 ] ), Math.abs( max[ 2 ] ) ) );
  38251. // Note: this assumes that the sum of all weights is at most 1. This isn't quite correct - it's more conservative
  38252. // to assume that each target can have a max weight of 1. However, for some use cases - notably, when morph targets
  38253. // are used to implement key-frame animations and as such only two are active at a time - this results in very large
  38254. // boxes. So for now we make a box that's sometimes a touch too small but is hopefully mostly of reasonable size.
  38255. maxDisplacement.max( vector );
  38256. } else {
  38257. console.warn( 'THREE.GLTFLoader: Missing min/max properties for accessor POSITION.' );
  38258. }
  38259. }
  38260. }
  38261. // As per comment above this box isn't conservative, but has a reasonable size for a very large number of morph targets.
  38262. box.expandByVector( maxDisplacement );
  38263. }
  38264. geometry.boundingBox = box;
  38265. var sphere = new THREE.Sphere();
  38266. box.getCenter( sphere.center );
  38267. sphere.radius = box.min.distanceTo( box.max ) / 2;
  38268. geometry.boundingSphere = sphere;
  38269. }
  38270. /**
  38271. * @param {THREE.BufferGeometry} geometry
  38272. * @param {GLTF.Primitive} primitiveDef
  38273. * @param {GLTFParser} parser
  38274. * @return {Promise<THREE.BufferGeometry>}
  38275. */
  38276. function addPrimitiveAttributes( geometry, primitiveDef, parser ) {
  38277. var attributes = primitiveDef.attributes;
  38278. var pending = [];
  38279. function assignAttributeAccessor( accessorIndex, attributeName ) {
  38280. return parser.getDependency( 'accessor', accessorIndex )
  38281. .then( function ( accessor ) {
  38282. geometry.setAttribute( attributeName, accessor );
  38283. } );
  38284. }
  38285. for ( var gltfAttributeName in attributes ) {
  38286. var threeAttributeName = ATTRIBUTES[ gltfAttributeName ] || gltfAttributeName.toLowerCase();
  38287. // Skip attributes already provided by e.g. Draco extension.
  38288. if ( threeAttributeName in geometry.attributes ) continue;
  38289. pending.push( assignAttributeAccessor( attributes[ gltfAttributeName ], threeAttributeName ) );
  38290. }
  38291. if ( primitiveDef.indices !== undefined && ! geometry.index ) {
  38292. var accessor = parser.getDependency( 'accessor', primitiveDef.indices ).then( function ( accessor ) {
  38293. geometry.setIndex( accessor );
  38294. } );
  38295. pending.push( accessor );
  38296. }
  38297. assignExtrasToUserData( geometry, primitiveDef );
  38298. computeBounds( geometry, primitiveDef, parser );
  38299. return Promise.all( pending ).then( function () {
  38300. return primitiveDef.targets !== undefined
  38301. ? addMorphTargets( geometry, primitiveDef.targets, parser )
  38302. : geometry;
  38303. } );
  38304. }
  38305. /**
  38306. * @param {THREE.BufferGeometry} geometry
  38307. * @param {Number} drawMode
  38308. * @return {THREE.BufferGeometry}
  38309. */
  38310. function toTrianglesDrawMode( geometry, drawMode ) {
  38311. var index = geometry.getIndex();
  38312. // generate index if not present
  38313. if ( index === null ) {
  38314. var indices = [];
  38315. var position = geometry.getAttribute( 'position' );
  38316. if ( position !== undefined ) {
  38317. for ( var i = 0; i < position.count; i ++ ) {
  38318. indices.push( i );
  38319. }
  38320. geometry.setIndex( indices );
  38321. index = geometry.getIndex();
  38322. } else {
  38323. console.error( 'THREE.GLTFLoader.toTrianglesDrawMode(): Undefined position attribute. Processing not possible.' );
  38324. return geometry;
  38325. }
  38326. }
  38327. //
  38328. var numberOfTriangles = index.count - 2;
  38329. var newIndices = [];
  38330. if ( drawMode === THREE.TriangleFanDrawMode ) {
  38331. // gl.TRIANGLE_FAN
  38332. for ( var i = 1; i <= numberOfTriangles; i ++ ) {
  38333. newIndices.push( index.getX( 0 ) );
  38334. newIndices.push( index.getX( i ) );
  38335. newIndices.push( index.getX( i + 1 ) );
  38336. }
  38337. } else {
  38338. // gl.TRIANGLE_STRIP
  38339. for ( var i = 0; i < numberOfTriangles; i ++ ) {
  38340. if ( i % 2 === 0 ) {
  38341. newIndices.push( index.getX( i ) );
  38342. newIndices.push( index.getX( i + 1 ) );
  38343. newIndices.push( index.getX( i + 2 ) );
  38344. } else {
  38345. newIndices.push( index.getX( i + 2 ) );
  38346. newIndices.push( index.getX( i + 1 ) );
  38347. newIndices.push( index.getX( i ) );
  38348. }
  38349. }
  38350. }
  38351. if ( ( newIndices.length / 3 ) !== numberOfTriangles ) {
  38352. console.error( 'THREE.GLTFLoader.toTrianglesDrawMode(): Unable to generate correct amount of triangles.' );
  38353. }
  38354. // build final geometry
  38355. var newGeometry = geometry.clone();
  38356. newGeometry.setIndex( newIndices );
  38357. return newGeometry;
  38358. }
  38359. /**
  38360. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#geometry
  38361. *
  38362. * Creates BufferGeometries from primitives.
  38363. *
  38364. * @param {Array<GLTF.Primitive>} primitives
  38365. * @return {Promise<Array<THREE.BufferGeometry>>}
  38366. */
  38367. GLTFParser.prototype.loadGeometries = function ( primitives ) {
  38368. var parser = this;
  38369. var extensions = this.extensions;
  38370. var cache = this.primitiveCache;
  38371. function createDracoPrimitive( primitive ) {
  38372. return extensions[ EXTENSIONS.KHR_DRACO_MESH_COMPRESSION ]
  38373. .decodePrimitive( primitive, parser )
  38374. .then( function ( geometry ) {
  38375. return addPrimitiveAttributes( geometry, primitive, parser );
  38376. } );
  38377. }
  38378. var pending = [];
  38379. for ( var i = 0, il = primitives.length; i < il; i ++ ) {
  38380. var primitive = primitives[ i ];
  38381. var cacheKey = createPrimitiveKey( primitive );
  38382. // See if we've already created this geometry
  38383. var cached = cache[ cacheKey ];
  38384. if ( cached ) {
  38385. // Use the cached geometry if it exists
  38386. pending.push( cached.promise );
  38387. } else {
  38388. var geometryPromise;
  38389. if ( primitive.extensions && primitive.extensions[ EXTENSIONS.KHR_DRACO_MESH_COMPRESSION ] ) {
  38390. // Use DRACO geometry if available
  38391. geometryPromise = createDracoPrimitive( primitive );
  38392. } else {
  38393. // Otherwise create a new geometry
  38394. geometryPromise = addPrimitiveAttributes( new THREE.BufferGeometry(), primitive, parser );
  38395. }
  38396. // Cache this geometry
  38397. cache[ cacheKey ] = { primitive: primitive, promise: geometryPromise };
  38398. pending.push( geometryPromise );
  38399. }
  38400. }
  38401. return Promise.all( pending );
  38402. };
  38403. /**
  38404. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#meshes
  38405. * @param {number} meshIndex
  38406. * @return {Promise<THREE.Group|THREE.Mesh|THREE.SkinnedMesh>}
  38407. */
  38408. GLTFParser.prototype.loadMesh = function ( meshIndex ) {
  38409. var parser = this;
  38410. var json = this.json;
  38411. var meshDef = json.meshes[ meshIndex ];
  38412. var primitives = meshDef.primitives;
  38413. var pending = [];
  38414. for ( var i = 0, il = primitives.length; i < il; i ++ ) {
  38415. var material = primitives[ i ].material === undefined
  38416. ? createDefaultMaterial( this.cache )
  38417. : this.getDependency( 'material', primitives[ i ].material );
  38418. pending.push( material );
  38419. }
  38420. pending.push( parser.loadGeometries( primitives ) );
  38421. return Promise.all( pending ).then( function ( results ) {
  38422. var materials = results.slice( 0, results.length - 1 );
  38423. var geometries = results[ results.length - 1 ];
  38424. var meshes = [];
  38425. for ( var i = 0, il = geometries.length; i < il; i ++ ) {
  38426. var geometry = geometries[ i ];
  38427. var primitive = primitives[ i ];
  38428. // 1. create Mesh
  38429. var mesh;
  38430. var material = materials[ i ];
  38431. if ( primitive.mode === WEBGL_CONSTANTS.TRIANGLES ||
  38432. primitive.mode === WEBGL_CONSTANTS.TRIANGLE_STRIP ||
  38433. primitive.mode === WEBGL_CONSTANTS.TRIANGLE_FAN ||
  38434. primitive.mode === undefined ) {
  38435. // .isSkinnedMesh isn't in glTF spec. See .markDefs()
  38436. mesh = meshDef.isSkinnedMesh === true
  38437. ? new THREE.SkinnedMesh( geometry, material )
  38438. : new THREE.Mesh( geometry, material );
  38439. if ( mesh.isSkinnedMesh === true && ! mesh.geometry.attributes.skinWeight.normalized ) {
  38440. // we normalize floating point skin weight array to fix malformed assets (see #15319)
  38441. // it's important to skip this for non-float32 data since normalizeSkinWeights assumes non-normalized inputs
  38442. mesh.normalizeSkinWeights();
  38443. }
  38444. if ( primitive.mode === WEBGL_CONSTANTS.TRIANGLE_STRIP ) {
  38445. mesh.geometry = toTrianglesDrawMode( mesh.geometry, THREE.TriangleStripDrawMode );
  38446. } else if ( primitive.mode === WEBGL_CONSTANTS.TRIANGLE_FAN ) {
  38447. mesh.geometry = toTrianglesDrawMode( mesh.geometry, THREE.TriangleFanDrawMode );
  38448. }
  38449. } else if ( primitive.mode === WEBGL_CONSTANTS.LINES ) {
  38450. mesh = new THREE.LineSegments( geometry, material );
  38451. } else if ( primitive.mode === WEBGL_CONSTANTS.LINE_STRIP ) {
  38452. mesh = new THREE.Line( geometry, material );
  38453. } else if ( primitive.mode === WEBGL_CONSTANTS.LINE_LOOP ) {
  38454. mesh = new THREE.LineLoop( geometry, material );
  38455. } else if ( primitive.mode === WEBGL_CONSTANTS.POINTS ) {
  38456. mesh = new THREE.Points( geometry, material );
  38457. } else {
  38458. throw new Error( 'THREE.GLTFLoader: Primitive mode unsupported: ' + primitive.mode );
  38459. }
  38460. if ( Object.keys( mesh.geometry.morphAttributes ).length > 0 ) {
  38461. updateMorphTargets( mesh, meshDef );
  38462. }
  38463. mesh.name = meshDef.name || ( 'mesh_' + meshIndex );
  38464. if ( geometries.length > 1 ) mesh.name += '_' + i;
  38465. assignExtrasToUserData( mesh, meshDef );
  38466. parser.assignFinalMaterial( mesh );
  38467. meshes.push( mesh );
  38468. }
  38469. if ( meshes.length === 1 ) {
  38470. return meshes[ 0 ];
  38471. }
  38472. var group = new THREE.Group();
  38473. for ( var i = 0, il = meshes.length; i < il; i ++ ) {
  38474. group.add( meshes[ i ] );
  38475. }
  38476. return group;
  38477. } );
  38478. };
  38479. /**
  38480. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#cameras
  38481. * @param {number} cameraIndex
  38482. * @return {Promise<THREE.Camera>}
  38483. */
  38484. GLTFParser.prototype.loadCamera = function ( cameraIndex ) {
  38485. var camera;
  38486. var cameraDef = this.json.cameras[ cameraIndex ];
  38487. var params = cameraDef[ cameraDef.type ];
  38488. if ( ! params ) {
  38489. console.warn( 'THREE.GLTFLoader: Missing camera parameters.' );
  38490. return;
  38491. }
  38492. if ( cameraDef.type === 'perspective' ) {
  38493. camera = new THREE.PerspectiveCamera( THREE.MathUtils.radToDeg( params.yfov ), params.aspectRatio || 1, params.znear || 1, params.zfar || 2e6 );
  38494. } else if ( cameraDef.type === 'orthographic' ) {
  38495. camera = new THREE.OrthographicCamera( params.xmag / - 2, params.xmag / 2, params.ymag / 2, params.ymag / - 2, params.znear, params.zfar );
  38496. }
  38497. if ( cameraDef.name ) camera.name = cameraDef.name;
  38498. assignExtrasToUserData( camera, cameraDef );
  38499. return Promise.resolve( camera );
  38500. };
  38501. /**
  38502. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins
  38503. * @param {number} skinIndex
  38504. * @return {Promise<Object>}
  38505. */
  38506. GLTFParser.prototype.loadSkin = function ( skinIndex ) {
  38507. var skinDef = this.json.skins[ skinIndex ];
  38508. var skinEntry = { joints: skinDef.joints };
  38509. if ( skinDef.inverseBindMatrices === undefined ) {
  38510. return Promise.resolve( skinEntry );
  38511. }
  38512. return this.getDependency( 'accessor', skinDef.inverseBindMatrices ).then( function ( accessor ) {
  38513. skinEntry.inverseBindMatrices = accessor;
  38514. return skinEntry;
  38515. } );
  38516. };
  38517. /**
  38518. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#animations
  38519. * @param {number} animationIndex
  38520. * @return {Promise<THREE.AnimationClip>}
  38521. */
  38522. GLTFParser.prototype.loadAnimation = function ( animationIndex ) {
  38523. var json = this.json;
  38524. var animationDef = json.animations[ animationIndex ];
  38525. var pendingNodes = [];
  38526. var pendingInputAccessors = [];
  38527. var pendingOutputAccessors = [];
  38528. var pendingSamplers = [];
  38529. var pendingTargets = [];
  38530. for ( var i = 0, il = animationDef.channels.length; i < il; i ++ ) {
  38531. var channel = animationDef.channels[ i ];
  38532. var sampler = animationDef.samplers[ channel.sampler ];
  38533. var target = channel.target;
  38534. var name = target.node !== undefined ? target.node : target.id; // NOTE: target.id is deprecated.
  38535. var input = animationDef.parameters !== undefined ? animationDef.parameters[ sampler.input ] : sampler.input;
  38536. var output = animationDef.parameters !== undefined ? animationDef.parameters[ sampler.output ] : sampler.output;
  38537. pendingNodes.push( this.getDependency( 'node', name ) );
  38538. pendingInputAccessors.push( this.getDependency( 'accessor', input ) );
  38539. pendingOutputAccessors.push( this.getDependency( 'accessor', output ) );
  38540. pendingSamplers.push( sampler );
  38541. pendingTargets.push( target );
  38542. }
  38543. return Promise.all( [
  38544. Promise.all( pendingNodes ),
  38545. Promise.all( pendingInputAccessors ),
  38546. Promise.all( pendingOutputAccessors ),
  38547. Promise.all( pendingSamplers ),
  38548. Promise.all( pendingTargets )
  38549. ] ).then( function ( dependencies ) {
  38550. var nodes = dependencies[ 0 ];
  38551. var inputAccessors = dependencies[ 1 ];
  38552. var outputAccessors = dependencies[ 2 ];
  38553. var samplers = dependencies[ 3 ];
  38554. var targets = dependencies[ 4 ];
  38555. var tracks = [];
  38556. for ( var i = 0, il = nodes.length; i < il; i ++ ) {
  38557. var node = nodes[ i ];
  38558. var inputAccessor = inputAccessors[ i ];
  38559. var outputAccessor = outputAccessors[ i ];
  38560. var sampler = samplers[ i ];
  38561. var target = targets[ i ];
  38562. if ( node === undefined ) continue;
  38563. node.updateMatrix();
  38564. node.matrixAutoUpdate = true;
  38565. var TypedKeyframeTrack;
  38566. switch ( PATH_PROPERTIES[ target.path ] ) {
  38567. case PATH_PROPERTIES.weights:
  38568. TypedKeyframeTrack = THREE.NumberKeyframeTrack;
  38569. break;
  38570. case PATH_PROPERTIES.rotation:
  38571. TypedKeyframeTrack = THREE.QuaternionKeyframeTrack;
  38572. break;
  38573. case PATH_PROPERTIES.position:
  38574. case PATH_PROPERTIES.scale:
  38575. default:
  38576. TypedKeyframeTrack = THREE.VectorKeyframeTrack;
  38577. break;
  38578. }
  38579. var targetName = node.name ? node.name : node.uuid;
  38580. var interpolation = sampler.interpolation !== undefined ? INTERPOLATION[ sampler.interpolation ] : THREE.InterpolateLinear;
  38581. var targetNames = [];
  38582. if ( PATH_PROPERTIES[ target.path ] === PATH_PROPERTIES.weights ) {
  38583. // Node may be a THREE.Group (glTF mesh with several primitives) or a THREE.Mesh.
  38584. node.traverse( function ( object ) {
  38585. if ( object.isMesh === true && object.morphTargetInfluences ) {
  38586. targetNames.push( object.name ? object.name : object.uuid );
  38587. }
  38588. } );
  38589. } else {
  38590. targetNames.push( targetName );
  38591. }
  38592. var outputArray = outputAccessor.array;
  38593. if ( outputAccessor.normalized ) {
  38594. var scale;
  38595. if ( outputArray.constructor === Int8Array ) {
  38596. scale = 1 / 127;
  38597. } else if ( outputArray.constructor === Uint8Array ) {
  38598. scale = 1 / 255;
  38599. } else if ( outputArray.constructor == Int16Array ) {
  38600. scale = 1 / 32767;
  38601. } else if ( outputArray.constructor === Uint16Array ) {
  38602. scale = 1 / 65535;
  38603. } else {
  38604. throw new Error( 'THREE.GLTFLoader: Unsupported output accessor component type.' );
  38605. }
  38606. var scaled = new Float32Array( outputArray.length );
  38607. for ( var j = 0, jl = outputArray.length; j < jl; j ++ ) {
  38608. scaled[ j ] = outputArray[ j ] * scale;
  38609. }
  38610. outputArray = scaled;
  38611. }
  38612. for ( var j = 0, jl = targetNames.length; j < jl; j ++ ) {
  38613. var track = new TypedKeyframeTrack(
  38614. targetNames[ j ] + '.' + PATH_PROPERTIES[ target.path ],
  38615. inputAccessor.array,
  38616. outputArray,
  38617. interpolation
  38618. );
  38619. // Override interpolation with custom factory method.
  38620. if ( sampler.interpolation === 'CUBICSPLINE' ) {
  38621. track.createInterpolant = function InterpolantFactoryMethodGLTFCubicSpline( result ) {
  38622. // A CUBICSPLINE keyframe in glTF has three output values for each input value,
  38623. // representing inTangent, splineVertex, and outTangent. As a result, track.getValueSize()
  38624. // must be divided by three to get the interpolant's sampleSize argument.
  38625. return new GLTFCubicSplineInterpolant( this.times, this.values, this.getValueSize() / 3, result );
  38626. };
  38627. // Mark as CUBICSPLINE. `track.getInterpolation()` doesn't support custom interpolants.
  38628. track.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline = true;
  38629. }
  38630. tracks.push( track );
  38631. }
  38632. }
  38633. var name = animationDef.name ? animationDef.name : 'animation_' + animationIndex;
  38634. return new THREE.AnimationClip( name, undefined, tracks );
  38635. } );
  38636. };
  38637. /**
  38638. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#nodes-and-hierarchy
  38639. * @param {number} nodeIndex
  38640. * @return {Promise<THREE.Object3D>}
  38641. */
  38642. GLTFParser.prototype.loadNode = function ( nodeIndex ) {
  38643. var json = this.json;
  38644. var extensions = this.extensions;
  38645. var parser = this;
  38646. var meshReferences = json.meshReferences;
  38647. var meshUses = json.meshUses;
  38648. var nodeDef = json.nodes[ nodeIndex ];
  38649. return ( function () {
  38650. var pending = [];
  38651. if ( nodeDef.mesh !== undefined ) {
  38652. pending.push( parser.getDependency( 'mesh', nodeDef.mesh ).then( function ( mesh ) {
  38653. var node;
  38654. if ( meshReferences[ nodeDef.mesh ] > 1 ) {
  38655. var instanceNum = meshUses[ nodeDef.mesh ] ++;
  38656. node = mesh.clone();
  38657. node.name += '_instance_' + instanceNum;
  38658. } else {
  38659. node = mesh;
  38660. }
  38661. // if weights are provided on the node, override weights on the mesh.
  38662. if ( nodeDef.weights !== undefined ) {
  38663. node.traverse( function ( o ) {
  38664. if ( ! o.isMesh ) return;
  38665. for ( var i = 0, il = nodeDef.weights.length; i < il; i ++ ) {
  38666. o.morphTargetInfluences[ i ] = nodeDef.weights[ i ];
  38667. }
  38668. } );
  38669. }
  38670. return node;
  38671. } ) );
  38672. }
  38673. if ( nodeDef.camera !== undefined ) {
  38674. pending.push( parser.getDependency( 'camera', nodeDef.camera ) );
  38675. }
  38676. if ( nodeDef.extensions
  38677. && nodeDef.extensions[ EXTENSIONS.KHR_LIGHTS_PUNCTUAL ]
  38678. && nodeDef.extensions[ EXTENSIONS.KHR_LIGHTS_PUNCTUAL ].light !== undefined ) {
  38679. pending.push( parser.getDependency( 'light', nodeDef.extensions[ EXTENSIONS.KHR_LIGHTS_PUNCTUAL ].light ) );
  38680. }
  38681. return Promise.all( pending );
  38682. }() ).then( function ( objects ) {
  38683. var node;
  38684. // .isBone isn't in glTF spec. See .markDefs
  38685. if ( nodeDef.isBone === true ) {
  38686. node = new THREE.Bone();
  38687. } else if ( objects.length > 1 ) {
  38688. node = new THREE.Group();
  38689. } else if ( objects.length === 1 ) {
  38690. node = objects[ 0 ];
  38691. } else {
  38692. node = new THREE.Object3D();
  38693. }
  38694. if ( node !== objects[ 0 ] ) {
  38695. for ( var i = 0, il = objects.length; i < il; i ++ ) {
  38696. node.add( objects[ i ] );
  38697. }
  38698. }
  38699. if ( nodeDef.name ) {
  38700. node.userData.name = nodeDef.name;
  38701. node.name = THREE.PropertyBinding.sanitizeNodeName( nodeDef.name );
  38702. }
  38703. assignExtrasToUserData( node, nodeDef );
  38704. if ( nodeDef.extensions ) addUnknownExtensionsToUserData( extensions, node, nodeDef );
  38705. if ( nodeDef.matrix !== undefined ) {
  38706. var matrix = new THREE.Matrix4();
  38707. matrix.fromArray( nodeDef.matrix );
  38708. node.applyMatrix4( matrix );
  38709. } else {
  38710. if ( nodeDef.translation !== undefined ) {
  38711. node.position.fromArray( nodeDef.translation );
  38712. }
  38713. if ( nodeDef.rotation !== undefined ) {
  38714. node.quaternion.fromArray( nodeDef.rotation );
  38715. }
  38716. if ( nodeDef.scale !== undefined ) {
  38717. node.scale.fromArray( nodeDef.scale );
  38718. }
  38719. }
  38720. return node;
  38721. } );
  38722. };
  38723. /**
  38724. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#scenes
  38725. * @param {number} sceneIndex
  38726. * @return {Promise<THREE.Group>}
  38727. */
  38728. GLTFParser.prototype.loadScene = function () {
  38729. // scene node hierachy builder
  38730. function buildNodeHierachy( nodeId, parentObject, json, parser ) {
  38731. var nodeDef = json.nodes[ nodeId ];
  38732. return parser.getDependency( 'node', nodeId ).then( function ( node ) {
  38733. if ( nodeDef.skin === undefined ) return node;
  38734. // build skeleton here as well
  38735. var skinEntry;
  38736. return parser.getDependency( 'skin', nodeDef.skin ).then( function ( skin ) {
  38737. skinEntry = skin;
  38738. var pendingJoints = [];
  38739. for ( var i = 0, il = skinEntry.joints.length; i < il; i ++ ) {
  38740. pendingJoints.push( parser.getDependency( 'node', skinEntry.joints[ i ] ) );
  38741. }
  38742. return Promise.all( pendingJoints );
  38743. } ).then( function ( jointNodes ) {
  38744. node.traverse( function ( mesh ) {
  38745. if ( ! mesh.isMesh ) return;
  38746. var bones = [];
  38747. var boneInverses = [];
  38748. for ( var j = 0, jl = jointNodes.length; j < jl; j ++ ) {
  38749. var jointNode = jointNodes[ j ];
  38750. if ( jointNode ) {
  38751. bones.push( jointNode );
  38752. var mat = new THREE.Matrix4();
  38753. if ( skinEntry.inverseBindMatrices !== undefined ) {
  38754. mat.fromArray( skinEntry.inverseBindMatrices.array, j * 16 );
  38755. }
  38756. boneInverses.push( mat );
  38757. } else {
  38758. console.warn( 'THREE.GLTFLoader: Joint "%s" could not be found.', skinEntry.joints[ j ] );
  38759. }
  38760. }
  38761. mesh.bind( new THREE.Skeleton( bones, boneInverses ), mesh.matrixWorld );
  38762. } );
  38763. return node;
  38764. } );
  38765. } ).then( function ( node ) {
  38766. // build node hierachy
  38767. parentObject.add( node );
  38768. var pending = [];
  38769. if ( nodeDef.children ) {
  38770. var children = nodeDef.children;
  38771. for ( var i = 0, il = children.length; i < il; i ++ ) {
  38772. var child = children[ i ];
  38773. pending.push( buildNodeHierachy( child, node, json, parser ) );
  38774. }
  38775. }
  38776. return Promise.all( pending );
  38777. } );
  38778. }
  38779. return function loadScene( sceneIndex ) {
  38780. var json = this.json;
  38781. var extensions = this.extensions;
  38782. var sceneDef = this.json.scenes[ sceneIndex ];
  38783. var parser = this;
  38784. // Loader returns Group, not Scene.
  38785. // See: https://github.com/mrdoob/three.js/issues/18342#issuecomment-578981172
  38786. var scene = new THREE.Group();
  38787. if ( sceneDef.name ) scene.name = sceneDef.name;
  38788. assignExtrasToUserData( scene, sceneDef );
  38789. if ( sceneDef.extensions ) addUnknownExtensionsToUserData( extensions, scene, sceneDef );
  38790. var nodeIds = sceneDef.nodes || [];
  38791. var pending = [];
  38792. for ( var i = 0, il = nodeIds.length; i < il; i ++ ) {
  38793. pending.push( buildNodeHierachy( nodeIds[ i ], scene, json, parser ) );
  38794. }
  38795. return Promise.all( pending ).then( function () {
  38796. return scene;
  38797. } );
  38798. };
  38799. }();
  38800. return GLTFLoader;
  38801. } )();
  38802. },{}],60:[function(_dereq_,module,exports){
  38803. /**
  38804. * Loads a Wavefront .mtl file specifying materials
  38805. *
  38806. * @author angelxuanchang
  38807. */
  38808. THREE.MTLLoader = function ( manager ) {
  38809. THREE.Loader.call( this, manager );
  38810. };
  38811. THREE.MTLLoader.prototype = Object.assign( Object.create( THREE.Loader.prototype ), {
  38812. constructor: THREE.MTLLoader,
  38813. /**
  38814. * Loads and parses a MTL asset from a URL.
  38815. *
  38816. * @param {String} url - URL to the MTL file.
  38817. * @param {Function} [onLoad] - Callback invoked with the loaded object.
  38818. * @param {Function} [onProgress] - Callback for download progress.
  38819. * @param {Function} [onError] - Callback for download errors.
  38820. *
  38821. * @see setPath setResourcePath
  38822. *
  38823. * @note In order for relative texture references to resolve correctly
  38824. * you must call setResourcePath() explicitly prior to load.
  38825. */
  38826. load: function ( url, onLoad, onProgress, onError ) {
  38827. var scope = this;
  38828. var path = ( this.path === '' ) ? THREE.LoaderUtils.extractUrlBase( url ) : this.path;
  38829. var loader = new THREE.FileLoader( this.manager );
  38830. loader.setPath( this.path );
  38831. loader.load( url, function ( text ) {
  38832. onLoad( scope.parse( text, path ) );
  38833. }, onProgress, onError );
  38834. },
  38835. setMaterialOptions: function ( value ) {
  38836. this.materialOptions = value;
  38837. return this;
  38838. },
  38839. /**
  38840. * Parses a MTL file.
  38841. *
  38842. * @param {String} text - Content of MTL file
  38843. * @return {THREE.MTLLoader.MaterialCreator}
  38844. *
  38845. * @see setPath setResourcePath
  38846. *
  38847. * @note In order for relative texture references to resolve correctly
  38848. * you must call setResourcePath() explicitly prior to parse.
  38849. */
  38850. parse: function ( text, path ) {
  38851. var lines = text.split( '\n' );
  38852. var info = {};
  38853. var delimiter_pattern = /\s+/;
  38854. var materialsInfo = {};
  38855. for ( var i = 0; i < lines.length; i ++ ) {
  38856. var line = lines[ i ];
  38857. line = line.trim();
  38858. if ( line.length === 0 || line.charAt( 0 ) === '#' ) {
  38859. // Blank line or comment ignore
  38860. continue;
  38861. }
  38862. var pos = line.indexOf( ' ' );
  38863. var key = ( pos >= 0 ) ? line.substring( 0, pos ) : line;
  38864. key = key.toLowerCase();
  38865. var value = ( pos >= 0 ) ? line.substring( pos + 1 ) : '';
  38866. value = value.trim();
  38867. if ( key === 'newmtl' ) {
  38868. // New material
  38869. info = { name: value };
  38870. materialsInfo[ value ] = info;
  38871. } else {
  38872. if ( key === 'ka' || key === 'kd' || key === 'ks' || key === 'ke' ) {
  38873. var ss = value.split( delimiter_pattern, 3 );
  38874. info[ key ] = [ parseFloat( ss[ 0 ] ), parseFloat( ss[ 1 ] ), parseFloat( ss[ 2 ] ) ];
  38875. } else {
  38876. info[ key ] = value;
  38877. }
  38878. }
  38879. }
  38880. var materialCreator = new THREE.MTLLoader.MaterialCreator( this.resourcePath || path, this.materialOptions );
  38881. materialCreator.setCrossOrigin( this.crossOrigin );
  38882. materialCreator.setManager( this.manager );
  38883. materialCreator.setMaterials( materialsInfo );
  38884. return materialCreator;
  38885. }
  38886. } );
  38887. /**
  38888. * Create a new THREE.MTLLoader.MaterialCreator
  38889. * @param baseUrl - Url relative to which textures are loaded
  38890. * @param options - Set of options on how to construct the materials
  38891. * side: Which side to apply the material
  38892. * THREE.FrontSide (default), THREE.BackSide, THREE.DoubleSide
  38893. * wrap: What type of wrapping to apply for textures
  38894. * THREE.RepeatWrapping (default), THREE.ClampToEdgeWrapping, THREE.MirroredRepeatWrapping
  38895. * normalizeRGB: RGBs need to be normalized to 0-1 from 0-255
  38896. * Default: false, assumed to be already normalized
  38897. * ignoreZeroRGBs: Ignore values of RGBs (Ka,Kd,Ks) that are all 0's
  38898. * Default: false
  38899. * @constructor
  38900. */
  38901. THREE.MTLLoader.MaterialCreator = function ( baseUrl, options ) {
  38902. this.baseUrl = baseUrl || '';
  38903. this.options = options;
  38904. this.materialsInfo = {};
  38905. this.materials = {};
  38906. this.materialsArray = [];
  38907. this.nameLookup = {};
  38908. this.side = ( this.options && this.options.side ) ? this.options.side : THREE.FrontSide;
  38909. this.wrap = ( this.options && this.options.wrap ) ? this.options.wrap : THREE.RepeatWrapping;
  38910. };
  38911. THREE.MTLLoader.MaterialCreator.prototype = {
  38912. constructor: THREE.MTLLoader.MaterialCreator,
  38913. crossOrigin: 'anonymous',
  38914. setCrossOrigin: function ( value ) {
  38915. this.crossOrigin = value;
  38916. return this;
  38917. },
  38918. setManager: function ( value ) {
  38919. this.manager = value;
  38920. },
  38921. setMaterials: function ( materialsInfo ) {
  38922. this.materialsInfo = this.convert( materialsInfo );
  38923. this.materials = {};
  38924. this.materialsArray = [];
  38925. this.nameLookup = {};
  38926. },
  38927. convert: function ( materialsInfo ) {
  38928. if ( ! this.options ) return materialsInfo;
  38929. var converted = {};
  38930. for ( var mn in materialsInfo ) {
  38931. // Convert materials info into normalized form based on options
  38932. var mat = materialsInfo[ mn ];
  38933. var covmat = {};
  38934. converted[ mn ] = covmat;
  38935. for ( var prop in mat ) {
  38936. var save = true;
  38937. var value = mat[ prop ];
  38938. var lprop = prop.toLowerCase();
  38939. switch ( lprop ) {
  38940. case 'kd':
  38941. case 'ka':
  38942. case 'ks':
  38943. // Diffuse color (color under white light) using RGB values
  38944. if ( this.options && this.options.normalizeRGB ) {
  38945. value = [ value[ 0 ] / 255, value[ 1 ] / 255, value[ 2 ] / 255 ];
  38946. }
  38947. if ( this.options && this.options.ignoreZeroRGBs ) {
  38948. if ( value[ 0 ] === 0 && value[ 1 ] === 0 && value[ 2 ] === 0 ) {
  38949. // ignore
  38950. save = false;
  38951. }
  38952. }
  38953. break;
  38954. default:
  38955. break;
  38956. }
  38957. if ( save ) {
  38958. covmat[ lprop ] = value;
  38959. }
  38960. }
  38961. }
  38962. return converted;
  38963. },
  38964. preload: function () {
  38965. for ( var mn in this.materialsInfo ) {
  38966. this.create( mn );
  38967. }
  38968. },
  38969. getIndex: function ( materialName ) {
  38970. return this.nameLookup[ materialName ];
  38971. },
  38972. getAsArray: function () {
  38973. var index = 0;
  38974. for ( var mn in this.materialsInfo ) {
  38975. this.materialsArray[ index ] = this.create( mn );
  38976. this.nameLookup[ mn ] = index;
  38977. index ++;
  38978. }
  38979. return this.materialsArray;
  38980. },
  38981. create: function ( materialName ) {
  38982. if ( this.materials[ materialName ] === undefined ) {
  38983. this.createMaterial_( materialName );
  38984. }
  38985. return this.materials[ materialName ];
  38986. },
  38987. createMaterial_: function ( materialName ) {
  38988. // Create material
  38989. var scope = this;
  38990. var mat = this.materialsInfo[ materialName ];
  38991. var params = {
  38992. name: materialName,
  38993. side: this.side
  38994. };
  38995. function resolveURL( baseUrl, url ) {
  38996. if ( typeof url !== 'string' || url === '' )
  38997. return '';
  38998. // Absolute URL
  38999. if ( /^https?:\/\//i.test( url ) ) return url;
  39000. return baseUrl + url;
  39001. }
  39002. function setMapForType( mapType, value ) {
  39003. if ( params[ mapType ] ) return; // Keep the first encountered texture
  39004. var texParams = scope.getTextureParams( value, params );
  39005. var map = scope.loadTexture( resolveURL( scope.baseUrl, texParams.url ) );
  39006. map.repeat.copy( texParams.scale );
  39007. map.offset.copy( texParams.offset );
  39008. map.wrapS = scope.wrap;
  39009. map.wrapT = scope.wrap;
  39010. params[ mapType ] = map;
  39011. }
  39012. for ( var prop in mat ) {
  39013. var value = mat[ prop ];
  39014. var n;
  39015. if ( value === '' ) continue;
  39016. switch ( prop.toLowerCase() ) {
  39017. // Ns is material specular exponent
  39018. case 'kd':
  39019. // Diffuse color (color under white light) using RGB values
  39020. params.color = new THREE.Color().fromArray( value );
  39021. break;
  39022. case 'ks':
  39023. // Specular color (color when light is reflected from shiny surface) using RGB values
  39024. params.specular = new THREE.Color().fromArray( value );
  39025. break;
  39026. case 'ke':
  39027. // Emissive using RGB values
  39028. params.emissive = new THREE.Color().fromArray( value );
  39029. break;
  39030. case 'map_kd':
  39031. // Diffuse texture map
  39032. setMapForType( "map", value );
  39033. break;
  39034. case 'map_ks':
  39035. // Specular map
  39036. setMapForType( "specularMap", value );
  39037. break;
  39038. case 'map_ke':
  39039. // Emissive map
  39040. setMapForType( "emissiveMap", value );
  39041. break;
  39042. case 'norm':
  39043. setMapForType( "normalMap", value );
  39044. break;
  39045. case 'map_bump':
  39046. case 'bump':
  39047. // Bump texture map
  39048. setMapForType( "bumpMap", value );
  39049. break;
  39050. case 'map_d':
  39051. // Alpha map
  39052. setMapForType( "alphaMap", value );
  39053. params.transparent = true;
  39054. break;
  39055. case 'ns':
  39056. // The specular exponent (defines the focus of the specular highlight)
  39057. // A high exponent results in a tight, concentrated highlight. Ns values normally range from 0 to 1000.
  39058. params.shininess = parseFloat( value );
  39059. break;
  39060. case 'd':
  39061. n = parseFloat( value );
  39062. if ( n < 1 ) {
  39063. params.opacity = n;
  39064. params.transparent = true;
  39065. }
  39066. break;
  39067. case 'tr':
  39068. n = parseFloat( value );
  39069. if ( this.options && this.options.invertTrProperty ) n = 1 - n;
  39070. if ( n > 0 ) {
  39071. params.opacity = 1 - n;
  39072. params.transparent = true;
  39073. }
  39074. break;
  39075. default:
  39076. break;
  39077. }
  39078. }
  39079. this.materials[ materialName ] = new THREE.MeshPhongMaterial( params );
  39080. return this.materials[ materialName ];
  39081. },
  39082. getTextureParams: function ( value, matParams ) {
  39083. var texParams = {
  39084. scale: new THREE.Vector2( 1, 1 ),
  39085. offset: new THREE.Vector2( 0, 0 )
  39086. };
  39087. var items = value.split( /\s+/ );
  39088. var pos;
  39089. pos = items.indexOf( '-bm' );
  39090. if ( pos >= 0 ) {
  39091. matParams.bumpScale = parseFloat( items[ pos + 1 ] );
  39092. items.splice( pos, 2 );
  39093. }
  39094. pos = items.indexOf( '-s' );
  39095. if ( pos >= 0 ) {
  39096. texParams.scale.set( parseFloat( items[ pos + 1 ] ), parseFloat( items[ pos + 2 ] ) );
  39097. items.splice( pos, 4 ); // we expect 3 parameters here!
  39098. }
  39099. pos = items.indexOf( '-o' );
  39100. if ( pos >= 0 ) {
  39101. texParams.offset.set( parseFloat( items[ pos + 1 ] ), parseFloat( items[ pos + 2 ] ) );
  39102. items.splice( pos, 4 ); // we expect 3 parameters here!
  39103. }
  39104. texParams.url = items.join( ' ' ).trim();
  39105. return texParams;
  39106. },
  39107. loadTexture: function ( url, mapping, onLoad, onProgress, onError ) {
  39108. var texture;
  39109. var manager = ( this.manager !== undefined ) ? this.manager : THREE.DefaultLoadingManager;
  39110. var loader = manager.getHandler( url );
  39111. if ( loader === null ) {
  39112. loader = new THREE.TextureLoader( manager );
  39113. }
  39114. if ( loader.setCrossOrigin ) loader.setCrossOrigin( this.crossOrigin );
  39115. texture = loader.load( url, onLoad, onProgress, onError );
  39116. if ( mapping !== undefined ) texture.mapping = mapping;
  39117. return texture;
  39118. }
  39119. };
  39120. },{}],61:[function(_dereq_,module,exports){
  39121. /**
  39122. * @author mrdoob / http://mrdoob.com/
  39123. */
  39124. THREE.OBJLoader = ( function () {
  39125. // o object_name | g group_name
  39126. var object_pattern = /^[og]\s*(.+)?/;
  39127. // mtllib file_reference
  39128. var material_library_pattern = /^mtllib /;
  39129. // usemtl material_name
  39130. var material_use_pattern = /^usemtl /;
  39131. // usemap map_name
  39132. var map_use_pattern = /^usemap /;
  39133. function ParserState() {
  39134. var state = {
  39135. objects: [],
  39136. object: {},
  39137. vertices: [],
  39138. normals: [],
  39139. colors: [],
  39140. uvs: [],
  39141. materials: {},
  39142. materialLibraries: [],
  39143. startObject: function ( name, fromDeclaration ) {
  39144. // If the current object (initial from reset) is not from a g/o declaration in the parsed
  39145. // file. We need to use it for the first parsed g/o to keep things in sync.
  39146. if ( this.object && this.object.fromDeclaration === false ) {
  39147. this.object.name = name;
  39148. this.object.fromDeclaration = ( fromDeclaration !== false );
  39149. return;
  39150. }
  39151. var previousMaterial = ( this.object && typeof this.object.currentMaterial === 'function' ? this.object.currentMaterial() : undefined );
  39152. if ( this.object && typeof this.object._finalize === 'function' ) {
  39153. this.object._finalize( true );
  39154. }
  39155. this.object = {
  39156. name: name || '',
  39157. fromDeclaration: ( fromDeclaration !== false ),
  39158. geometry: {
  39159. vertices: [],
  39160. normals: [],
  39161. colors: [],
  39162. uvs: []
  39163. },
  39164. materials: [],
  39165. smooth: true,
  39166. startMaterial: function ( name, libraries ) {
  39167. var previous = this._finalize( false );
  39168. // New usemtl declaration overwrites an inherited material, except if faces were declared
  39169. // after the material, then it must be preserved for proper MultiMaterial continuation.
  39170. if ( previous && ( previous.inherited || previous.groupCount <= 0 ) ) {
  39171. this.materials.splice( previous.index, 1 );
  39172. }
  39173. var material = {
  39174. index: this.materials.length,
  39175. name: name || '',
  39176. mtllib: ( Array.isArray( libraries ) && libraries.length > 0 ? libraries[ libraries.length - 1 ] : '' ),
  39177. smooth: ( previous !== undefined ? previous.smooth : this.smooth ),
  39178. groupStart: ( previous !== undefined ? previous.groupEnd : 0 ),
  39179. groupEnd: - 1,
  39180. groupCount: - 1,
  39181. inherited: false,
  39182. clone: function ( index ) {
  39183. var cloned = {
  39184. index: ( typeof index === 'number' ? index : this.index ),
  39185. name: this.name,
  39186. mtllib: this.mtllib,
  39187. smooth: this.smooth,
  39188. groupStart: 0,
  39189. groupEnd: - 1,
  39190. groupCount: - 1,
  39191. inherited: false
  39192. };
  39193. cloned.clone = this.clone.bind( cloned );
  39194. return cloned;
  39195. }
  39196. };
  39197. this.materials.push( material );
  39198. return material;
  39199. },
  39200. currentMaterial: function () {
  39201. if ( this.materials.length > 0 ) {
  39202. return this.materials[ this.materials.length - 1 ];
  39203. }
  39204. return undefined;
  39205. },
  39206. _finalize: function ( end ) {
  39207. var lastMultiMaterial = this.currentMaterial();
  39208. if ( lastMultiMaterial && lastMultiMaterial.groupEnd === - 1 ) {
  39209. lastMultiMaterial.groupEnd = this.geometry.vertices.length / 3;
  39210. lastMultiMaterial.groupCount = lastMultiMaterial.groupEnd - lastMultiMaterial.groupStart;
  39211. lastMultiMaterial.inherited = false;
  39212. }
  39213. // Ignore objects tail materials if no face declarations followed them before a new o/g started.
  39214. if ( end && this.materials.length > 1 ) {
  39215. for ( var mi = this.materials.length - 1; mi >= 0; mi -- ) {
  39216. if ( this.materials[ mi ].groupCount <= 0 ) {
  39217. this.materials.splice( mi, 1 );
  39218. }
  39219. }
  39220. }
  39221. // Guarantee at least one empty material, this makes the creation later more straight forward.
  39222. if ( end && this.materials.length === 0 ) {
  39223. this.materials.push( {
  39224. name: '',
  39225. smooth: this.smooth
  39226. } );
  39227. }
  39228. return lastMultiMaterial;
  39229. }
  39230. };
  39231. // Inherit previous objects material.
  39232. // Spec tells us that a declared material must be set to all objects until a new material is declared.
  39233. // If a usemtl declaration is encountered while this new object is being parsed, it will
  39234. // overwrite the inherited material. Exception being that there was already face declarations
  39235. // to the inherited material, then it will be preserved for proper MultiMaterial continuation.
  39236. if ( previousMaterial && previousMaterial.name && typeof previousMaterial.clone === 'function' ) {
  39237. var declared = previousMaterial.clone( 0 );
  39238. declared.inherited = true;
  39239. this.object.materials.push( declared );
  39240. }
  39241. this.objects.push( this.object );
  39242. },
  39243. finalize: function () {
  39244. if ( this.object && typeof this.object._finalize === 'function' ) {
  39245. this.object._finalize( true );
  39246. }
  39247. },
  39248. parseVertexIndex: function ( value, len ) {
  39249. var index = parseInt( value, 10 );
  39250. return ( index >= 0 ? index - 1 : index + len / 3 ) * 3;
  39251. },
  39252. parseNormalIndex: function ( value, len ) {
  39253. var index = parseInt( value, 10 );
  39254. return ( index >= 0 ? index - 1 : index + len / 3 ) * 3;
  39255. },
  39256. parseUVIndex: function ( value, len ) {
  39257. var index = parseInt( value, 10 );
  39258. return ( index >= 0 ? index - 1 : index + len / 2 ) * 2;
  39259. },
  39260. addVertex: function ( a, b, c ) {
  39261. var src = this.vertices;
  39262. var dst = this.object.geometry.vertices;
  39263. dst.push( src[ a + 0 ], src[ a + 1 ], src[ a + 2 ] );
  39264. dst.push( src[ b + 0 ], src[ b + 1 ], src[ b + 2 ] );
  39265. dst.push( src[ c + 0 ], src[ c + 1 ], src[ c + 2 ] );
  39266. },
  39267. addVertexPoint: function ( a ) {
  39268. var src = this.vertices;
  39269. var dst = this.object.geometry.vertices;
  39270. dst.push( src[ a + 0 ], src[ a + 1 ], src[ a + 2 ] );
  39271. },
  39272. addVertexLine: function ( a ) {
  39273. var src = this.vertices;
  39274. var dst = this.object.geometry.vertices;
  39275. dst.push( src[ a + 0 ], src[ a + 1 ], src[ a + 2 ] );
  39276. },
  39277. addNormal: function ( a, b, c ) {
  39278. var src = this.normals;
  39279. var dst = this.object.geometry.normals;
  39280. dst.push( src[ a + 0 ], src[ a + 1 ], src[ a + 2 ] );
  39281. dst.push( src[ b + 0 ], src[ b + 1 ], src[ b + 2 ] );
  39282. dst.push( src[ c + 0 ], src[ c + 1 ], src[ c + 2 ] );
  39283. },
  39284. addColor: function ( a, b, c ) {
  39285. var src = this.colors;
  39286. var dst = this.object.geometry.colors;
  39287. dst.push( src[ a + 0 ], src[ a + 1 ], src[ a + 2 ] );
  39288. dst.push( src[ b + 0 ], src[ b + 1 ], src[ b + 2 ] );
  39289. dst.push( src[ c + 0 ], src[ c + 1 ], src[ c + 2 ] );
  39290. },
  39291. addUV: function ( a, b, c ) {
  39292. var src = this.uvs;
  39293. var dst = this.object.geometry.uvs;
  39294. dst.push( src[ a + 0 ], src[ a + 1 ] );
  39295. dst.push( src[ b + 0 ], src[ b + 1 ] );
  39296. dst.push( src[ c + 0 ], src[ c + 1 ] );
  39297. },
  39298. addUVLine: function ( a ) {
  39299. var src = this.uvs;
  39300. var dst = this.object.geometry.uvs;
  39301. dst.push( src[ a + 0 ], src[ a + 1 ] );
  39302. },
  39303. addFace: function ( a, b, c, ua, ub, uc, na, nb, nc ) {
  39304. var vLen = this.vertices.length;
  39305. var ia = this.parseVertexIndex( a, vLen );
  39306. var ib = this.parseVertexIndex( b, vLen );
  39307. var ic = this.parseVertexIndex( c, vLen );
  39308. this.addVertex( ia, ib, ic );
  39309. if ( this.colors.length > 0 ) {
  39310. this.addColor( ia, ib, ic );
  39311. }
  39312. if ( ua !== undefined && ua !== '' ) {
  39313. var uvLen = this.uvs.length;
  39314. ia = this.parseUVIndex( ua, uvLen );
  39315. ib = this.parseUVIndex( ub, uvLen );
  39316. ic = this.parseUVIndex( uc, uvLen );
  39317. this.addUV( ia, ib, ic );
  39318. }
  39319. if ( na !== undefined && na !== '' ) {
  39320. // Normals are many times the same. If so, skip function call and parseInt.
  39321. var nLen = this.normals.length;
  39322. ia = this.parseNormalIndex( na, nLen );
  39323. ib = na === nb ? ia : this.parseNormalIndex( nb, nLen );
  39324. ic = na === nc ? ia : this.parseNormalIndex( nc, nLen );
  39325. this.addNormal( ia, ib, ic );
  39326. }
  39327. },
  39328. addPointGeometry: function ( vertices ) {
  39329. this.object.geometry.type = 'Points';
  39330. var vLen = this.vertices.length;
  39331. for ( var vi = 0, l = vertices.length; vi < l; vi ++ ) {
  39332. this.addVertexPoint( this.parseVertexIndex( vertices[ vi ], vLen ) );
  39333. }
  39334. },
  39335. addLineGeometry: function ( vertices, uvs ) {
  39336. this.object.geometry.type = 'Line';
  39337. var vLen = this.vertices.length;
  39338. var uvLen = this.uvs.length;
  39339. for ( var vi = 0, l = vertices.length; vi < l; vi ++ ) {
  39340. this.addVertexLine( this.parseVertexIndex( vertices[ vi ], vLen ) );
  39341. }
  39342. for ( var uvi = 0, l = uvs.length; uvi < l; uvi ++ ) {
  39343. this.addUVLine( this.parseUVIndex( uvs[ uvi ], uvLen ) );
  39344. }
  39345. }
  39346. };
  39347. state.startObject( '', false );
  39348. return state;
  39349. }
  39350. //
  39351. function OBJLoader( manager ) {
  39352. THREE.Loader.call( this, manager );
  39353. this.materials = null;
  39354. }
  39355. OBJLoader.prototype = Object.assign( Object.create( THREE.Loader.prototype ), {
  39356. constructor: OBJLoader,
  39357. load: function ( url, onLoad, onProgress, onError ) {
  39358. var scope = this;
  39359. var loader = new THREE.FileLoader( scope.manager );
  39360. loader.setPath( this.path );
  39361. loader.load( url, function ( text ) {
  39362. onLoad( scope.parse( text ) );
  39363. }, onProgress, onError );
  39364. },
  39365. setMaterials: function ( materials ) {
  39366. this.materials = materials;
  39367. return this;
  39368. },
  39369. parse: function ( text ) {
  39370. var state = new ParserState();
  39371. if ( text.indexOf( '\r\n' ) !== - 1 ) {
  39372. // This is faster than String.split with regex that splits on both
  39373. text = text.replace( /\r\n/g, '\n' );
  39374. }
  39375. if ( text.indexOf( '\\\n' ) !== - 1 ) {
  39376. // join lines separated by a line continuation character (\)
  39377. text = text.replace( /\\\n/g, '' );
  39378. }
  39379. var lines = text.split( '\n' );
  39380. var line = '', lineFirstChar = '';
  39381. var lineLength = 0;
  39382. var result = [];
  39383. // Faster to just trim left side of the line. Use if available.
  39384. var trimLeft = ( typeof ''.trimLeft === 'function' );
  39385. for ( var i = 0, l = lines.length; i < l; i ++ ) {
  39386. line = lines[ i ];
  39387. line = trimLeft ? line.trimLeft() : line.trim();
  39388. lineLength = line.length;
  39389. if ( lineLength === 0 ) continue;
  39390. lineFirstChar = line.charAt( 0 );
  39391. // @todo invoke passed in handler if any
  39392. if ( lineFirstChar === '#' ) continue;
  39393. if ( lineFirstChar === 'v' ) {
  39394. var data = line.split( /\s+/ );
  39395. switch ( data[ 0 ] ) {
  39396. case 'v':
  39397. state.vertices.push(
  39398. parseFloat( data[ 1 ] ),
  39399. parseFloat( data[ 2 ] ),
  39400. parseFloat( data[ 3 ] )
  39401. );
  39402. if ( data.length >= 7 ) {
  39403. state.colors.push(
  39404. parseFloat( data[ 4 ] ),
  39405. parseFloat( data[ 5 ] ),
  39406. parseFloat( data[ 6 ] )
  39407. );
  39408. }
  39409. break;
  39410. case 'vn':
  39411. state.normals.push(
  39412. parseFloat( data[ 1 ] ),
  39413. parseFloat( data[ 2 ] ),
  39414. parseFloat( data[ 3 ] )
  39415. );
  39416. break;
  39417. case 'vt':
  39418. state.uvs.push(
  39419. parseFloat( data[ 1 ] ),
  39420. parseFloat( data[ 2 ] )
  39421. );
  39422. break;
  39423. }
  39424. } else if ( lineFirstChar === 'f' ) {
  39425. var lineData = line.substr( 1 ).trim();
  39426. var vertexData = lineData.split( /\s+/ );
  39427. var faceVertices = [];
  39428. // Parse the face vertex data into an easy to work with format
  39429. for ( var j = 0, jl = vertexData.length; j < jl; j ++ ) {
  39430. var vertex = vertexData[ j ];
  39431. if ( vertex.length > 0 ) {
  39432. var vertexParts = vertex.split( '/' );
  39433. faceVertices.push( vertexParts );
  39434. }
  39435. }
  39436. // Draw an edge between the first vertex and all subsequent vertices to form an n-gon
  39437. var v1 = faceVertices[ 0 ];
  39438. for ( var j = 1, jl = faceVertices.length - 1; j < jl; j ++ ) {
  39439. var v2 = faceVertices[ j ];
  39440. var v3 = faceVertices[ j + 1 ];
  39441. state.addFace(
  39442. v1[ 0 ], v2[ 0 ], v3[ 0 ],
  39443. v1[ 1 ], v2[ 1 ], v3[ 1 ],
  39444. v1[ 2 ], v2[ 2 ], v3[ 2 ]
  39445. );
  39446. }
  39447. } else if ( lineFirstChar === 'l' ) {
  39448. var lineParts = line.substring( 1 ).trim().split( " " );
  39449. var lineVertices = [], lineUVs = [];
  39450. if ( line.indexOf( "/" ) === - 1 ) {
  39451. lineVertices = lineParts;
  39452. } else {
  39453. for ( var li = 0, llen = lineParts.length; li < llen; li ++ ) {
  39454. var parts = lineParts[ li ].split( "/" );
  39455. if ( parts[ 0 ] !== "" ) lineVertices.push( parts[ 0 ] );
  39456. if ( parts[ 1 ] !== "" ) lineUVs.push( parts[ 1 ] );
  39457. }
  39458. }
  39459. state.addLineGeometry( lineVertices, lineUVs );
  39460. } else if ( lineFirstChar === 'p' ) {
  39461. var lineData = line.substr( 1 ).trim();
  39462. var pointData = lineData.split( " " );
  39463. state.addPointGeometry( pointData );
  39464. } else if ( ( result = object_pattern.exec( line ) ) !== null ) {
  39465. // o object_name
  39466. // or
  39467. // g group_name
  39468. // WORKAROUND: https://bugs.chromium.org/p/v8/issues/detail?id=2869
  39469. // var name = result[ 0 ].substr( 1 ).trim();
  39470. var name = ( " " + result[ 0 ].substr( 1 ).trim() ).substr( 1 );
  39471. state.startObject( name );
  39472. } else if ( material_use_pattern.test( line ) ) {
  39473. // material
  39474. state.object.startMaterial( line.substring( 7 ).trim(), state.materialLibraries );
  39475. } else if ( material_library_pattern.test( line ) ) {
  39476. // mtl file
  39477. state.materialLibraries.push( line.substring( 7 ).trim() );
  39478. } else if ( map_use_pattern.test( line ) ) {
  39479. // the line is parsed but ignored since the loader assumes textures are defined MTL files
  39480. // (according to https://www.okino.com/conv/imp_wave.htm, 'usemap' is the old-style Wavefront texture reference method)
  39481. console.warn( 'THREE.OBJLoader: Rendering identifier "usemap" not supported. Textures must be defined in MTL files.' );
  39482. } else if ( lineFirstChar === 's' ) {
  39483. result = line.split( ' ' );
  39484. // smooth shading
  39485. // @todo Handle files that have varying smooth values for a set of faces inside one geometry,
  39486. // but does not define a usemtl for each face set.
  39487. // This should be detected and a dummy material created (later MultiMaterial and geometry groups).
  39488. // This requires some care to not create extra material on each smooth value for "normal" obj files.
  39489. // where explicit usemtl defines geometry groups.
  39490. // Example asset: examples/models/obj/cerberus/Cerberus.obj
  39491. /*
  39492. * http://paulbourke.net/dataformats/obj/
  39493. * or
  39494. * http://www.cs.utah.edu/~boulos/cs3505/obj_spec.pdf
  39495. *
  39496. * From chapter "Grouping" Syntax explanation "s group_number":
  39497. * "group_number is the smoothing group number. To turn off smoothing groups, use a value of 0 or off.
  39498. * Polygonal elements use group numbers to put elements in different smoothing groups. For free-form
  39499. * surfaces, smoothing groups are either turned on or off; there is no difference between values greater
  39500. * than 0."
  39501. */
  39502. if ( result.length > 1 ) {
  39503. var value = result[ 1 ].trim().toLowerCase();
  39504. state.object.smooth = ( value !== '0' && value !== 'off' );
  39505. } else {
  39506. // ZBrush can produce "s" lines #11707
  39507. state.object.smooth = true;
  39508. }
  39509. var material = state.object.currentMaterial();
  39510. if ( material ) material.smooth = state.object.smooth;
  39511. } else {
  39512. // Handle null terminated files without exception
  39513. if ( line === '\0' ) continue;
  39514. console.warn( 'THREE.OBJLoader: Unexpected line: "' + line + '"' );
  39515. }
  39516. }
  39517. state.finalize();
  39518. var container = new THREE.Group();
  39519. container.materialLibraries = [].concat( state.materialLibraries );
  39520. for ( var i = 0, l = state.objects.length; i < l; i ++ ) {
  39521. var object = state.objects[ i ];
  39522. var geometry = object.geometry;
  39523. var materials = object.materials;
  39524. var isLine = ( geometry.type === 'Line' );
  39525. var isPoints = ( geometry.type === 'Points' );
  39526. var hasVertexColors = false;
  39527. // Skip o/g line declarations that did not follow with any faces
  39528. if ( geometry.vertices.length === 0 ) continue;
  39529. var buffergeometry = new THREE.BufferGeometry();
  39530. buffergeometry.setAttribute( 'position', new THREE.Float32BufferAttribute( geometry.vertices, 3 ) );
  39531. if ( geometry.normals.length > 0 ) {
  39532. buffergeometry.setAttribute( 'normal', new THREE.Float32BufferAttribute( geometry.normals, 3 ) );
  39533. } else {
  39534. buffergeometry.computeVertexNormals();
  39535. }
  39536. if ( geometry.colors.length > 0 ) {
  39537. hasVertexColors = true;
  39538. buffergeometry.setAttribute( 'color', new THREE.Float32BufferAttribute( geometry.colors, 3 ) );
  39539. }
  39540. if ( geometry.uvs.length > 0 ) {
  39541. buffergeometry.setAttribute( 'uv', new THREE.Float32BufferAttribute( geometry.uvs, 2 ) );
  39542. }
  39543. // Create materials
  39544. var createdMaterials = [];
  39545. for ( var mi = 0, miLen = materials.length; mi < miLen; mi ++ ) {
  39546. var sourceMaterial = materials[ mi ];
  39547. var materialHash = sourceMaterial.name + '_' + sourceMaterial.smooth + '_' + hasVertexColors;
  39548. var material = state.materials[ materialHash ];
  39549. if ( this.materials !== null ) {
  39550. material = this.materials.create( sourceMaterial.name );
  39551. // mtl etc. loaders probably can't create line materials correctly, copy properties to a line material.
  39552. if ( isLine && material && ! ( material instanceof THREE.LineBasicMaterial ) ) {
  39553. var materialLine = new THREE.LineBasicMaterial();
  39554. THREE.Material.prototype.copy.call( materialLine, material );
  39555. materialLine.color.copy( material.color );
  39556. material = materialLine;
  39557. } else if ( isPoints && material && ! ( material instanceof THREE.PointsMaterial ) ) {
  39558. var materialPoints = new THREE.PointsMaterial( { size: 10, sizeAttenuation: false } );
  39559. THREE.Material.prototype.copy.call( materialPoints, material );
  39560. materialPoints.color.copy( material.color );
  39561. materialPoints.map = material.map;
  39562. material = materialPoints;
  39563. }
  39564. }
  39565. if ( material === undefined ) {
  39566. if ( isLine ) {
  39567. material = new THREE.LineBasicMaterial();
  39568. } else if ( isPoints ) {
  39569. material = new THREE.PointsMaterial( { size: 1, sizeAttenuation: false } );
  39570. } else {
  39571. material = new THREE.MeshPhongMaterial();
  39572. }
  39573. material.name = sourceMaterial.name;
  39574. material.flatShading = sourceMaterial.smooth ? false : true;
  39575. material.vertexColors = hasVertexColors;
  39576. state.materials[ materialHash ] = material;
  39577. }
  39578. createdMaterials.push( material );
  39579. }
  39580. // Create mesh
  39581. var mesh;
  39582. if ( createdMaterials.length > 1 ) {
  39583. for ( var mi = 0, miLen = materials.length; mi < miLen; mi ++ ) {
  39584. var sourceMaterial = materials[ mi ];
  39585. buffergeometry.addGroup( sourceMaterial.groupStart, sourceMaterial.groupCount, mi );
  39586. }
  39587. if ( isLine ) {
  39588. mesh = new THREE.LineSegments( buffergeometry, createdMaterials );
  39589. } else if ( isPoints ) {
  39590. mesh = new THREE.Points( buffergeometry, createdMaterials );
  39591. } else {
  39592. mesh = new THREE.Mesh( buffergeometry, createdMaterials );
  39593. }
  39594. } else {
  39595. if ( isLine ) {
  39596. mesh = new THREE.LineSegments( buffergeometry, createdMaterials[ 0 ] );
  39597. } else if ( isPoints ) {
  39598. mesh = new THREE.Points( buffergeometry, createdMaterials[ 0 ] );
  39599. } else {
  39600. mesh = new THREE.Mesh( buffergeometry, createdMaterials[ 0 ] );
  39601. }
  39602. }
  39603. mesh.name = object.name;
  39604. container.add( mesh );
  39605. }
  39606. return container;
  39607. }
  39608. } );
  39609. return OBJLoader;
  39610. } )();
  39611. },{}],62:[function(_dereq_,module,exports){
  39612. var createLayout = _dereq_('layout-bmfont-text')
  39613. var inherits = _dereq_('inherits')
  39614. var createIndices = _dereq_('quad-indices')
  39615. var buffer = _dereq_('three-buffer-vertex-data')
  39616. var assign = _dereq_('object-assign')
  39617. var vertices = _dereq_('./lib/vertices')
  39618. var utils = _dereq_('./lib/utils')
  39619. var Base = THREE.BufferGeometry
  39620. module.exports = function createTextGeometry (opt) {
  39621. return new TextGeometry(opt)
  39622. }
  39623. function TextGeometry (opt) {
  39624. Base.call(this)
  39625. if (typeof opt === 'string') {
  39626. opt = { text: opt }
  39627. }
  39628. // use these as default values for any subsequent
  39629. // calls to update()
  39630. this._opt = assign({}, opt)
  39631. // also do an initial setup...
  39632. if (opt) this.update(opt)
  39633. }
  39634. inherits(TextGeometry, Base)
  39635. TextGeometry.prototype.update = function (opt) {
  39636. if (typeof opt === 'string') {
  39637. opt = { text: opt }
  39638. }
  39639. // use constructor defaults
  39640. opt = assign({}, this._opt, opt)
  39641. if (!opt.font) {
  39642. throw new TypeError('must specify a { font } in options')
  39643. }
  39644. this.layout = createLayout(opt)
  39645. // get vec2 texcoords
  39646. var flipY = opt.flipY !== false
  39647. // the desired BMFont data
  39648. var font = opt.font
  39649. // determine texture size from font file
  39650. var texWidth = font.common.scaleW
  39651. var texHeight = font.common.scaleH
  39652. // get visible glyphs
  39653. var glyphs = this.layout.glyphs.filter(function (glyph) {
  39654. var bitmap = glyph.data
  39655. return bitmap.width * bitmap.height > 0
  39656. })
  39657. // provide visible glyphs for convenience
  39658. this.visibleGlyphs = glyphs
  39659. // get common vertex data
  39660. var positions = vertices.positions(glyphs)
  39661. var uvs = vertices.uvs(glyphs, texWidth, texHeight, flipY)
  39662. var indices = createIndices({
  39663. clockwise: true,
  39664. type: 'uint16',
  39665. count: glyphs.length
  39666. })
  39667. // update vertex data
  39668. buffer.index(this, indices, 1, 'uint16')
  39669. buffer.attr(this, 'position', positions, 2)
  39670. buffer.attr(this, 'uv', uvs, 2)
  39671. // update multipage data
  39672. if (!opt.multipage && 'page' in this.attributes) {
  39673. // disable multipage rendering
  39674. this.removeAttribute('page')
  39675. } else if (opt.multipage) {
  39676. var pages = vertices.pages(glyphs)
  39677. // enable multipage rendering
  39678. buffer.attr(this, 'page', pages, 1)
  39679. }
  39680. }
  39681. TextGeometry.prototype.computeBoundingSphere = function () {
  39682. if (this.boundingSphere === null) {
  39683. this.boundingSphere = new THREE.Sphere()
  39684. }
  39685. var positions = this.attributes.position.array
  39686. var itemSize = this.attributes.position.itemSize
  39687. if (!positions || !itemSize || positions.length < 2) {
  39688. this.boundingSphere.radius = 0
  39689. this.boundingSphere.center.set(0, 0, 0)
  39690. return
  39691. }
  39692. utils.computeSphere(positions, this.boundingSphere)
  39693. if (isNaN(this.boundingSphere.radius)) {
  39694. console.error('THREE.BufferGeometry.computeBoundingSphere(): ' +
  39695. 'Computed radius is NaN. The ' +
  39696. '"position" attribute is likely to have NaN values.')
  39697. }
  39698. }
  39699. TextGeometry.prototype.computeBoundingBox = function () {
  39700. if (this.boundingBox === null) {
  39701. this.boundingBox = new THREE.Box3()
  39702. }
  39703. var bbox = this.boundingBox
  39704. var positions = this.attributes.position.array
  39705. var itemSize = this.attributes.position.itemSize
  39706. if (!positions || !itemSize || positions.length < 2) {
  39707. bbox.makeEmpty()
  39708. return
  39709. }
  39710. utils.computeBox(positions, bbox)
  39711. }
  39712. },{"./lib/utils":63,"./lib/vertices":64,"inherits":30,"layout-bmfont-text":36,"object-assign":39,"quad-indices":51,"three-buffer-vertex-data":65}],63:[function(_dereq_,module,exports){
  39713. var itemSize = 2
  39714. var box = { min: [0, 0], max: [0, 0] }
  39715. function bounds (positions) {
  39716. var count = positions.length / itemSize
  39717. box.min[0] = positions[0]
  39718. box.min[1] = positions[1]
  39719. box.max[0] = positions[0]
  39720. box.max[1] = positions[1]
  39721. for (var i = 0; i < count; i++) {
  39722. var x = positions[i * itemSize + 0]
  39723. var y = positions[i * itemSize + 1]
  39724. box.min[0] = Math.min(x, box.min[0])
  39725. box.min[1] = Math.min(y, box.min[1])
  39726. box.max[0] = Math.max(x, box.max[0])
  39727. box.max[1] = Math.max(y, box.max[1])
  39728. }
  39729. }
  39730. module.exports.computeBox = function (positions, output) {
  39731. bounds(positions)
  39732. output.min.set(box.min[0], box.min[1], 0)
  39733. output.max.set(box.max[0], box.max[1], 0)
  39734. }
  39735. module.exports.computeSphere = function (positions, output) {
  39736. bounds(positions)
  39737. var minX = box.min[0]
  39738. var minY = box.min[1]
  39739. var maxX = box.max[0]
  39740. var maxY = box.max[1]
  39741. var width = maxX - minX
  39742. var height = maxY - minY
  39743. var length = Math.sqrt(width * width + height * height)
  39744. output.center.set(minX + width / 2, minY + height / 2, 0)
  39745. output.radius = length / 2
  39746. }
  39747. },{}],64:[function(_dereq_,module,exports){
  39748. module.exports.pages = function pages (glyphs) {
  39749. var pages = new Float32Array(glyphs.length * 4 * 1)
  39750. var i = 0
  39751. glyphs.forEach(function (glyph) {
  39752. var id = glyph.data.page || 0
  39753. pages[i++] = id
  39754. pages[i++] = id
  39755. pages[i++] = id
  39756. pages[i++] = id
  39757. })
  39758. return pages
  39759. }
  39760. module.exports.uvs = function uvs (glyphs, texWidth, texHeight, flipY) {
  39761. var uvs = new Float32Array(glyphs.length * 4 * 2)
  39762. var i = 0
  39763. glyphs.forEach(function (glyph) {
  39764. var bitmap = glyph.data
  39765. var bw = (bitmap.x + bitmap.width)
  39766. var bh = (bitmap.y + bitmap.height)
  39767. // top left position
  39768. var u0 = bitmap.x / texWidth
  39769. var v1 = bitmap.y / texHeight
  39770. var u1 = bw / texWidth
  39771. var v0 = bh / texHeight
  39772. if (flipY) {
  39773. v1 = (texHeight - bitmap.y) / texHeight
  39774. v0 = (texHeight - bh) / texHeight
  39775. }
  39776. // BL
  39777. uvs[i++] = u0
  39778. uvs[i++] = v1
  39779. // TL
  39780. uvs[i++] = u0
  39781. uvs[i++] = v0
  39782. // TR
  39783. uvs[i++] = u1
  39784. uvs[i++] = v0
  39785. // BR
  39786. uvs[i++] = u1
  39787. uvs[i++] = v1
  39788. })
  39789. return uvs
  39790. }
  39791. module.exports.positions = function positions (glyphs) {
  39792. var positions = new Float32Array(glyphs.length * 4 * 2)
  39793. var i = 0
  39794. glyphs.forEach(function (glyph) {
  39795. var bitmap = glyph.data
  39796. // bottom left position
  39797. var x = glyph.position[0] + bitmap.xoffset
  39798. var y = glyph.position[1] + bitmap.yoffset
  39799. // quad size
  39800. var w = bitmap.width
  39801. var h = bitmap.height
  39802. // BL
  39803. positions[i++] = x
  39804. positions[i++] = y
  39805. // TL
  39806. positions[i++] = x
  39807. positions[i++] = y + h
  39808. // TR
  39809. positions[i++] = x + w
  39810. positions[i++] = y + h
  39811. // BR
  39812. positions[i++] = x + w
  39813. positions[i++] = y
  39814. })
  39815. return positions
  39816. }
  39817. },{}],65:[function(_dereq_,module,exports){
  39818. var flatten = _dereq_('flatten-vertex-data')
  39819. var warned = false;
  39820. module.exports.attr = setAttribute
  39821. module.exports.index = setIndex
  39822. function setIndex (geometry, data, itemSize, dtype) {
  39823. if (typeof itemSize !== 'number') itemSize = 1
  39824. if (typeof dtype !== 'string') dtype = 'uint16'
  39825. var isR69 = !geometry.index && typeof geometry.setIndex !== 'function'
  39826. var attrib = isR69 ? geometry.getAttribute('index') : geometry.index
  39827. var newAttrib = updateAttribute(attrib, data, itemSize, dtype)
  39828. if (newAttrib) {
  39829. if (isR69) geometry.addAttribute('index', newAttrib)
  39830. else geometry.index = newAttrib
  39831. }
  39832. }
  39833. function setAttribute (geometry, key, data, itemSize, dtype) {
  39834. if (typeof itemSize !== 'number') itemSize = 3
  39835. if (typeof dtype !== 'string') dtype = 'float32'
  39836. if (Array.isArray(data) &&
  39837. Array.isArray(data[0]) &&
  39838. data[0].length !== itemSize) {
  39839. throw new Error('Nested vertex array has unexpected size; expected ' +
  39840. itemSize + ' but found ' + data[0].length)
  39841. }
  39842. var attrib = geometry.getAttribute(key)
  39843. var newAttrib = updateAttribute(attrib, data, itemSize, dtype)
  39844. geometry.setAttribute(key, newAttrib)
  39845. }
  39846. function updateAttribute (attrib, data, itemSize, dtype) {
  39847. data = data || []
  39848. // create a new array with desired type
  39849. data = flatten(data, dtype)
  39850. attrib = new THREE.BufferAttribute(data, itemSize);
  39851. attrib.itemSize = itemSize;
  39852. attrib.needsUpdate = true;
  39853. return attrib
  39854. }
  39855. // Test whether the attribute needs to be re-created,
  39856. // returns false if we can re-use it as-is.
  39857. function rebuildAttribute (attrib, data, itemSize) {
  39858. if (attrib.itemSize !== itemSize) return true
  39859. if (!attrib.array) return true
  39860. var attribLength = attrib.array.length
  39861. if (Array.isArray(data) && Array.isArray(data[0])) {
  39862. // [ [ x, y, z ] ]
  39863. return attribLength !== data.length * itemSize
  39864. } else {
  39865. // [ x, y, z ]
  39866. return attribLength !== data.length
  39867. }
  39868. return false
  39869. }
  39870. },{"flatten-vertex-data":23}],66:[function(_dereq_,module,exports){
  39871. (function (setImmediate,clearImmediate){
  39872. var nextTick = _dereq_('process/browser.js').nextTick;
  39873. var apply = Function.prototype.apply;
  39874. var slice = Array.prototype.slice;
  39875. var immediateIds = {};
  39876. var nextImmediateId = 0;
  39877. // DOM APIs, for completeness
  39878. exports.setTimeout = function() {
  39879. return new Timeout(apply.call(setTimeout, window, arguments), clearTimeout);
  39880. };
  39881. exports.setInterval = function() {
  39882. return new Timeout(apply.call(setInterval, window, arguments), clearInterval);
  39883. };
  39884. exports.clearTimeout =
  39885. exports.clearInterval = function(timeout) { timeout.close(); };
  39886. function Timeout(id, clearFn) {
  39887. this._id = id;
  39888. this._clearFn = clearFn;
  39889. }
  39890. Timeout.prototype.unref = Timeout.prototype.ref = function() {};
  39891. Timeout.prototype.close = function() {
  39892. this._clearFn.call(window, this._id);
  39893. };
  39894. // Does not start the time, just sets up the members needed.
  39895. exports.enroll = function(item, msecs) {
  39896. clearTimeout(item._idleTimeoutId);
  39897. item._idleTimeout = msecs;
  39898. };
  39899. exports.unenroll = function(item) {
  39900. clearTimeout(item._idleTimeoutId);
  39901. item._idleTimeout = -1;
  39902. };
  39903. exports._unrefActive = exports.active = function(item) {
  39904. clearTimeout(item._idleTimeoutId);
  39905. var msecs = item._idleTimeout;
  39906. if (msecs >= 0) {
  39907. item._idleTimeoutId = setTimeout(function onTimeout() {
  39908. if (item._onTimeout)
  39909. item._onTimeout();
  39910. }, msecs);
  39911. }
  39912. };
  39913. // That's not how node.js implements it but the exposed api is the same.
  39914. exports.setImmediate = typeof setImmediate === "function" ? setImmediate : function(fn) {
  39915. var id = nextImmediateId++;
  39916. var args = arguments.length < 2 ? false : slice.call(arguments, 1);
  39917. immediateIds[id] = true;
  39918. nextTick(function onNextTick() {
  39919. if (immediateIds[id]) {
  39920. // fn.call() is faster so we optimize for the common use-case
  39921. // @see http://jsperf.com/call-apply-segu
  39922. if (args) {
  39923. fn.apply(null, args);
  39924. } else {
  39925. fn.call(null);
  39926. }
  39927. // Prevent ids from leaking
  39928. exports.clearImmediate(id);
  39929. }
  39930. });
  39931. return id;
  39932. };
  39933. exports.clearImmediate = typeof clearImmediate === "function" ? clearImmediate : function(id) {
  39934. delete immediateIds[id];
  39935. };
  39936. }).call(this,_dereq_("timers").setImmediate,_dereq_("timers").clearImmediate)
  39937. },{"process/browser.js":49,"timers":66}],67:[function(_dereq_,module,exports){
  39938. (function (global){
  39939. /**
  39940. * @license
  39941. * webvr-polyfill
  39942. * Copyright (c) 2015-2017 Google
  39943. * Licensed under the Apache License, Version 2.0 (the "License");
  39944. * you may not use this file except in compliance with the License.
  39945. * You may obtain a copy of the License at
  39946. *
  39947. * http://www.apache.org/licenses/LICENSE-2.0
  39948. *
  39949. * Unless required by applicable law or agreed to in writing, software
  39950. * distributed under the License is distributed on an "AS IS" BASIS,
  39951. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  39952. * See the License for the specific language governing permissions and
  39953. * limitations under the License.
  39954. */
  39955. /**
  39956. * @license
  39957. * cardboard-vr-display
  39958. * Copyright (c) 2015-2017 Google
  39959. * Licensed under the Apache License, Version 2.0 (the "License");
  39960. * you may not use this file except in compliance with the License.
  39961. * You may obtain a copy of the License at
  39962. *
  39963. * http://www.apache.org/licenses/LICENSE-2.0
  39964. *
  39965. * Unless required by applicable law or agreed to in writing, software
  39966. * distributed under the License is distributed on an "AS IS" BASIS,
  39967. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  39968. * See the License for the specific language governing permissions and
  39969. * limitations under the License.
  39970. */
  39971. /**
  39972. * @license
  39973. * webvr-polyfill-dpdb
  39974. * Copyright (c) 2017 Google
  39975. * Licensed under the Apache License, Version 2.0 (the "License");
  39976. * you may not use this file except in compliance with the License.
  39977. * You may obtain a copy of the License at
  39978. *
  39979. * http://www.apache.org/licenses/LICENSE-2.0
  39980. *
  39981. * Unless required by applicable law or agreed to in writing, software
  39982. * distributed under the License is distributed on an "AS IS" BASIS,
  39983. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  39984. * See the License for the specific language governing permissions and
  39985. * limitations under the License.
  39986. */
  39987. /**
  39988. * @license
  39989. * wglu-preserve-state
  39990. * Copyright (c) 2016, Brandon Jones.
  39991. *
  39992. * Permission is hereby granted, free of charge, to any person obtaining a copy
  39993. * of this software and associated documentation files (the "Software"), to deal
  39994. * in the Software without restriction, including without limitation the rights
  39995. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  39996. * copies of the Software, and to permit persons to whom the Software is
  39997. * furnished to do so, subject to the following conditions:
  39998. *
  39999. * The above copyright notice and this permission notice shall be included in
  40000. * all copies or substantial portions of the Software.
  40001. *
  40002. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  40003. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  40004. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  40005. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  40006. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  40007. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  40008. * THE SOFTWARE.
  40009. */
  40010. /**
  40011. * @license
  40012. * nosleep.js
  40013. * Copyright (c) 2017, Rich Tibbett
  40014. *
  40015. * Permission is hereby granted, free of charge, to any person obtaining a copy
  40016. * of this software and associated documentation files (the "Software"), to deal
  40017. * in the Software without restriction, including without limitation the rights
  40018. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  40019. * copies of the Software, and to permit persons to whom the Software is
  40020. * furnished to do so, subject to the following conditions:
  40021. *
  40022. * The above copyright notice and this permission notice shall be included in
  40023. * all copies or substantial portions of the Software.
  40024. *
  40025. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  40026. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  40027. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  40028. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  40029. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  40030. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  40031. * THE SOFTWARE.
  40032. */
  40033. (function (global, factory) {
  40034. typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
  40035. typeof define === 'function' && define.amd ? define(factory) :
  40036. (global.WebVRPolyfill = factory());
  40037. }(this, (function () { 'use strict';
  40038. var commonjsGlobal = typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
  40039. function unwrapExports (x) {
  40040. return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
  40041. }
  40042. function createCommonjsModule(fn, module) {
  40043. return module = { exports: {} }, fn(module, module.exports), module.exports;
  40044. }
  40045. var isMobile = function isMobile() {
  40046. return (/Android/i.test(navigator.userAgent) || /iPhone|iPad|iPod/i.test(navigator.userAgent)
  40047. );
  40048. };
  40049. var copyArray = function copyArray(source, dest) {
  40050. for (var i = 0, n = source.length; i < n; i++) {
  40051. dest[i] = source[i];
  40052. }
  40053. };
  40054. var extend = function extend(dest, src) {
  40055. for (var key in src) {
  40056. if (src.hasOwnProperty(key)) {
  40057. dest[key] = src[key];
  40058. }
  40059. }
  40060. return dest;
  40061. };
  40062. var cardboardVrDisplay = createCommonjsModule(function (module, exports) {
  40063. /**
  40064. * @license
  40065. * cardboard-vr-display
  40066. * Copyright (c) 2015-2017 Google
  40067. * Licensed under the Apache License, Version 2.0 (the "License");
  40068. * you may not use this file except in compliance with the License.
  40069. * You may obtain a copy of the License at
  40070. *
  40071. * http://www.apache.org/licenses/LICENSE-2.0
  40072. *
  40073. * Unless required by applicable law or agreed to in writing, software
  40074. * distributed under the License is distributed on an "AS IS" BASIS,
  40075. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  40076. * See the License for the specific language governing permissions and
  40077. * limitations under the License.
  40078. */
  40079. /**
  40080. * @license
  40081. * gl-preserve-state
  40082. * Copyright (c) 2016, Brandon Jones.
  40083. *
  40084. * Permission is hereby granted, free of charge, to any person obtaining a copy
  40085. * of this software and associated documentation files (the "Software"), to deal
  40086. * in the Software without restriction, including without limitation the rights
  40087. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  40088. * copies of the Software, and to permit persons to whom the Software is
  40089. * furnished to do so, subject to the following conditions:
  40090. *
  40091. * The above copyright notice and this permission notice shall be included in
  40092. * all copies or substantial portions of the Software.
  40093. *
  40094. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  40095. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  40096. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  40097. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  40098. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  40099. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  40100. * THE SOFTWARE.
  40101. */
  40102. /**
  40103. * @license
  40104. * webvr-polyfill-dpdb
  40105. * Copyright (c) 2015-2017 Google
  40106. * Licensed under the Apache License, Version 2.0 (the "License");
  40107. * you may not use this file except in compliance with the License.
  40108. * You may obtain a copy of the License at
  40109. *
  40110. * http://www.apache.org/licenses/LICENSE-2.0
  40111. *
  40112. * Unless required by applicable law or agreed to in writing, software
  40113. * distributed under the License is distributed on an "AS IS" BASIS,
  40114. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  40115. * See the License for the specific language governing permissions and
  40116. * limitations under the License.
  40117. */
  40118. /**
  40119. * @license
  40120. * nosleep.js
  40121. * Copyright (c) 2017, Rich Tibbett
  40122. *
  40123. * Permission is hereby granted, free of charge, to any person obtaining a copy
  40124. * of this software and associated documentation files (the "Software"), to deal
  40125. * in the Software without restriction, including without limitation the rights
  40126. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  40127. * copies of the Software, and to permit persons to whom the Software is
  40128. * furnished to do so, subject to the following conditions:
  40129. *
  40130. * The above copyright notice and this permission notice shall be included in
  40131. * all copies or substantial portions of the Software.
  40132. *
  40133. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  40134. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  40135. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  40136. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  40137. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  40138. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  40139. * THE SOFTWARE.
  40140. */
  40141. (function (global, factory) {
  40142. module.exports = factory();
  40143. }(commonjsGlobal, (function () { var classCallCheck = function (instance, Constructor) {
  40144. if (!(instance instanceof Constructor)) {
  40145. throw new TypeError("Cannot call a class as a function");
  40146. }
  40147. };
  40148. var createClass = function () {
  40149. function defineProperties(target, props) {
  40150. for (var i = 0; i < props.length; i++) {
  40151. var descriptor = props[i];
  40152. descriptor.enumerable = descriptor.enumerable || false;
  40153. descriptor.configurable = true;
  40154. if ("value" in descriptor) descriptor.writable = true;
  40155. Object.defineProperty(target, descriptor.key, descriptor);
  40156. }
  40157. }
  40158. return function (Constructor, protoProps, staticProps) {
  40159. if (protoProps) defineProperties(Constructor.prototype, protoProps);
  40160. if (staticProps) defineProperties(Constructor, staticProps);
  40161. return Constructor;
  40162. };
  40163. }();
  40164. var slicedToArray = function () {
  40165. function sliceIterator(arr, i) {
  40166. var _arr = [];
  40167. var _n = true;
  40168. var _d = false;
  40169. var _e = undefined;
  40170. try {
  40171. for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {
  40172. _arr.push(_s.value);
  40173. if (i && _arr.length === i) break;
  40174. }
  40175. } catch (err) {
  40176. _d = true;
  40177. _e = err;
  40178. } finally {
  40179. try {
  40180. if (!_n && _i["return"]) _i["return"]();
  40181. } finally {
  40182. if (_d) throw _e;
  40183. }
  40184. }
  40185. return _arr;
  40186. }
  40187. return function (arr, i) {
  40188. if (Array.isArray(arr)) {
  40189. return arr;
  40190. } else if (Symbol.iterator in Object(arr)) {
  40191. return sliceIterator(arr, i);
  40192. } else {
  40193. throw new TypeError("Invalid attempt to destructure non-iterable instance");
  40194. }
  40195. };
  40196. }();
  40197. var MIN_TIMESTEP = 0.001;
  40198. var MAX_TIMESTEP = 1;
  40199. var dataUri = function dataUri(mimeType, svg) {
  40200. return 'data:' + mimeType + ',' + encodeURIComponent(svg);
  40201. };
  40202. var lerp = function lerp(a, b, t) {
  40203. return a + (b - a) * t;
  40204. };
  40205. var isIOS = function () {
  40206. var isIOS = /iPad|iPhone|iPod/.test(navigator.platform);
  40207. return function () {
  40208. return isIOS;
  40209. };
  40210. }();
  40211. var isWebViewAndroid = function () {
  40212. var isWebViewAndroid = navigator.userAgent.indexOf('Version') !== -1 && navigator.userAgent.indexOf('Android') !== -1 && navigator.userAgent.indexOf('Chrome') !== -1;
  40213. return function () {
  40214. return isWebViewAndroid;
  40215. };
  40216. }();
  40217. var isSafari = function () {
  40218. var isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  40219. return function () {
  40220. return isSafari;
  40221. };
  40222. }();
  40223. var isFirefoxAndroid = function () {
  40224. var isFirefoxAndroid = navigator.userAgent.indexOf('Firefox') !== -1 && navigator.userAgent.indexOf('Android') !== -1;
  40225. return function () {
  40226. return isFirefoxAndroid;
  40227. };
  40228. }();
  40229. var getChromeVersion = function () {
  40230. var match = navigator.userAgent.match(/.*Chrome\/([0-9]+)/);
  40231. var value = match ? parseInt(match[1], 10) : null;
  40232. return function () {
  40233. return value;
  40234. };
  40235. }();
  40236. var isChromeWithoutDeviceMotion = function () {
  40237. var value = false;
  40238. if (getChromeVersion() === 65) {
  40239. var match = navigator.userAgent.match(/.*Chrome\/([0-9\.]*)/);
  40240. if (match) {
  40241. var _match$1$split = match[1].split('.'),
  40242. _match$1$split2 = slicedToArray(_match$1$split, 4),
  40243. major = _match$1$split2[0],
  40244. minor = _match$1$split2[1],
  40245. branch = _match$1$split2[2],
  40246. build = _match$1$split2[3];
  40247. value = parseInt(branch, 10) === 3325 && parseInt(build, 10) < 148;
  40248. }
  40249. }
  40250. return function () {
  40251. return value;
  40252. };
  40253. }();
  40254. var isR7 = function () {
  40255. var isR7 = navigator.userAgent.indexOf('R7 Build') !== -1;
  40256. return function () {
  40257. return isR7;
  40258. };
  40259. }();
  40260. var isLandscapeMode = function isLandscapeMode() {
  40261. var rtn = window.orientation == 90 || window.orientation == -90;
  40262. return isR7() ? !rtn : rtn;
  40263. };
  40264. var isTimestampDeltaValid = function isTimestampDeltaValid(timestampDeltaS) {
  40265. if (isNaN(timestampDeltaS)) {
  40266. return false;
  40267. }
  40268. if (timestampDeltaS <= MIN_TIMESTEP) {
  40269. return false;
  40270. }
  40271. if (timestampDeltaS > MAX_TIMESTEP) {
  40272. return false;
  40273. }
  40274. return true;
  40275. };
  40276. var getScreenWidth = function getScreenWidth() {
  40277. return Math.max(window.screen.width, window.screen.height) * window.devicePixelRatio;
  40278. };
  40279. var getScreenHeight = function getScreenHeight() {
  40280. return Math.min(window.screen.width, window.screen.height) * window.devicePixelRatio;
  40281. };
  40282. var requestFullscreen = function requestFullscreen(element) {
  40283. if (isWebViewAndroid()) {
  40284. return false;
  40285. }
  40286. if (element.requestFullscreen) {
  40287. element.requestFullscreen();
  40288. } else if (element.webkitRequestFullscreen) {
  40289. element.webkitRequestFullscreen();
  40290. } else if (element.mozRequestFullScreen) {
  40291. element.mozRequestFullScreen();
  40292. } else if (element.msRequestFullscreen) {
  40293. element.msRequestFullscreen();
  40294. } else {
  40295. return false;
  40296. }
  40297. return true;
  40298. };
  40299. var exitFullscreen = function exitFullscreen() {
  40300. if (document.exitFullscreen) {
  40301. document.exitFullscreen();
  40302. } else if (document.webkitExitFullscreen) {
  40303. document.webkitExitFullscreen();
  40304. } else if (document.mozCancelFullScreen) {
  40305. document.mozCancelFullScreen();
  40306. } else if (document.msExitFullscreen) {
  40307. document.msExitFullscreen();
  40308. } else {
  40309. return false;
  40310. }
  40311. return true;
  40312. };
  40313. var getFullscreenElement = function getFullscreenElement() {
  40314. return document.fullscreenElement || document.webkitFullscreenElement || document.mozFullScreenElement || document.msFullscreenElement;
  40315. };
  40316. var linkProgram = function linkProgram(gl, vertexSource, fragmentSource, attribLocationMap) {
  40317. var vertexShader = gl.createShader(gl.VERTEX_SHADER);
  40318. gl.shaderSource(vertexShader, vertexSource);
  40319. gl.compileShader(vertexShader);
  40320. var fragmentShader = gl.createShader(gl.FRAGMENT_SHADER);
  40321. gl.shaderSource(fragmentShader, fragmentSource);
  40322. gl.compileShader(fragmentShader);
  40323. var program = gl.createProgram();
  40324. gl.attachShader(program, vertexShader);
  40325. gl.attachShader(program, fragmentShader);
  40326. for (var attribName in attribLocationMap) {
  40327. gl.bindAttribLocation(program, attribLocationMap[attribName], attribName);
  40328. }gl.linkProgram(program);
  40329. gl.deleteShader(vertexShader);
  40330. gl.deleteShader(fragmentShader);
  40331. return program;
  40332. };
  40333. var getProgramUniforms = function getProgramUniforms(gl, program) {
  40334. var uniforms = {};
  40335. var uniformCount = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS);
  40336. var uniformName = '';
  40337. for (var i = 0; i < uniformCount; i++) {
  40338. var uniformInfo = gl.getActiveUniform(program, i);
  40339. uniformName = uniformInfo.name.replace('[0]', '');
  40340. uniforms[uniformName] = gl.getUniformLocation(program, uniformName);
  40341. }
  40342. return uniforms;
  40343. };
  40344. var orthoMatrix = function orthoMatrix(out, left, right, bottom, top, near, far) {
  40345. var lr = 1 / (left - right),
  40346. bt = 1 / (bottom - top),
  40347. nf = 1 / (near - far);
  40348. out[0] = -2 * lr;
  40349. out[1] = 0;
  40350. out[2] = 0;
  40351. out[3] = 0;
  40352. out[4] = 0;
  40353. out[5] = -2 * bt;
  40354. out[6] = 0;
  40355. out[7] = 0;
  40356. out[8] = 0;
  40357. out[9] = 0;
  40358. out[10] = 2 * nf;
  40359. out[11] = 0;
  40360. out[12] = (left + right) * lr;
  40361. out[13] = (top + bottom) * bt;
  40362. out[14] = (far + near) * nf;
  40363. out[15] = 1;
  40364. return out;
  40365. };
  40366. var isMobile = function isMobile() {
  40367. var check = false;
  40368. (function (a) {
  40369. 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;
  40370. })(navigator.userAgent || navigator.vendor || window.opera);
  40371. return check;
  40372. };
  40373. var extend = function extend(dest, src) {
  40374. for (var key in src) {
  40375. if (src.hasOwnProperty(key)) {
  40376. dest[key] = src[key];
  40377. }
  40378. }
  40379. return dest;
  40380. };
  40381. var safariCssSizeWorkaround = function safariCssSizeWorkaround(canvas) {
  40382. if (isIOS()) {
  40383. var width = canvas.style.width;
  40384. var height = canvas.style.height;
  40385. canvas.style.width = parseInt(width) + 1 + 'px';
  40386. canvas.style.height = parseInt(height) + 'px';
  40387. setTimeout(function () {
  40388. canvas.style.width = width;
  40389. canvas.style.height = height;
  40390. }, 100);
  40391. }
  40392. window.canvas = canvas;
  40393. };
  40394. var frameDataFromPose = function () {
  40395. var piOver180 = Math.PI / 180.0;
  40396. var rad45 = Math.PI * 0.25;
  40397. function mat4_perspectiveFromFieldOfView(out, fov, near, far) {
  40398. var upTan = Math.tan(fov ? fov.upDegrees * piOver180 : rad45),
  40399. downTan = Math.tan(fov ? fov.downDegrees * piOver180 : rad45),
  40400. leftTan = Math.tan(fov ? fov.leftDegrees * piOver180 : rad45),
  40401. rightTan = Math.tan(fov ? fov.rightDegrees * piOver180 : rad45),
  40402. xScale = 2.0 / (leftTan + rightTan),
  40403. yScale = 2.0 / (upTan + downTan);
  40404. out[0] = xScale;
  40405. out[1] = 0.0;
  40406. out[2] = 0.0;
  40407. out[3] = 0.0;
  40408. out[4] = 0.0;
  40409. out[5] = yScale;
  40410. out[6] = 0.0;
  40411. out[7] = 0.0;
  40412. out[8] = -((leftTan - rightTan) * xScale * 0.5);
  40413. out[9] = (upTan - downTan) * yScale * 0.5;
  40414. out[10] = far / (near - far);
  40415. out[11] = -1.0;
  40416. out[12] = 0.0;
  40417. out[13] = 0.0;
  40418. out[14] = far * near / (near - far);
  40419. out[15] = 0.0;
  40420. return out;
  40421. }
  40422. function mat4_fromRotationTranslation(out, q, v) {
  40423. var x = q[0],
  40424. y = q[1],
  40425. z = q[2],
  40426. w = q[3],
  40427. x2 = x + x,
  40428. y2 = y + y,
  40429. z2 = z + z,
  40430. xx = x * x2,
  40431. xy = x * y2,
  40432. xz = x * z2,
  40433. yy = y * y2,
  40434. yz = y * z2,
  40435. zz = z * z2,
  40436. wx = w * x2,
  40437. wy = w * y2,
  40438. wz = w * z2;
  40439. out[0] = 1 - (yy + zz);
  40440. out[1] = xy + wz;
  40441. out[2] = xz - wy;
  40442. out[3] = 0;
  40443. out[4] = xy - wz;
  40444. out[5] = 1 - (xx + zz);
  40445. out[6] = yz + wx;
  40446. out[7] = 0;
  40447. out[8] = xz + wy;
  40448. out[9] = yz - wx;
  40449. out[10] = 1 - (xx + yy);
  40450. out[11] = 0;
  40451. out[12] = v[0];
  40452. out[13] = v[1];
  40453. out[14] = v[2];
  40454. out[15] = 1;
  40455. return out;
  40456. }
  40457. function mat4_translate(out, a, v) {
  40458. var x = v[0],
  40459. y = v[1],
  40460. z = v[2],
  40461. a00,
  40462. a01,
  40463. a02,
  40464. a03,
  40465. a10,
  40466. a11,
  40467. a12,
  40468. a13,
  40469. a20,
  40470. a21,
  40471. a22,
  40472. a23;
  40473. if (a === out) {
  40474. out[12] = a[0] * x + a[4] * y + a[8] * z + a[12];
  40475. out[13] = a[1] * x + a[5] * y + a[9] * z + a[13];
  40476. out[14] = a[2] * x + a[6] * y + a[10] * z + a[14];
  40477. out[15] = a[3] * x + a[7] * y + a[11] * z + a[15];
  40478. } else {
  40479. a00 = a[0];a01 = a[1];a02 = a[2];a03 = a[3];
  40480. a10 = a[4];a11 = a[5];a12 = a[6];a13 = a[7];
  40481. a20 = a[8];a21 = a[9];a22 = a[10];a23 = a[11];
  40482. out[0] = a00;out[1] = a01;out[2] = a02;out[3] = a03;
  40483. out[4] = a10;out[5] = a11;out[6] = a12;out[7] = a13;
  40484. out[8] = a20;out[9] = a21;out[10] = a22;out[11] = a23;
  40485. out[12] = a00 * x + a10 * y + a20 * z + a[12];
  40486. out[13] = a01 * x + a11 * y + a21 * z + a[13];
  40487. out[14] = a02 * x + a12 * y + a22 * z + a[14];
  40488. out[15] = a03 * x + a13 * y + a23 * z + a[15];
  40489. }
  40490. return out;
  40491. }
  40492. function mat4_invert(out, a) {
  40493. var a00 = a[0],
  40494. a01 = a[1],
  40495. a02 = a[2],
  40496. a03 = a[3],
  40497. a10 = a[4],
  40498. a11 = a[5],
  40499. a12 = a[6],
  40500. a13 = a[7],
  40501. a20 = a[8],
  40502. a21 = a[9],
  40503. a22 = a[10],
  40504. a23 = a[11],
  40505. a30 = a[12],
  40506. a31 = a[13],
  40507. a32 = a[14],
  40508. a33 = a[15],
  40509. b00 = a00 * a11 - a01 * a10,
  40510. b01 = a00 * a12 - a02 * a10,
  40511. b02 = a00 * a13 - a03 * a10,
  40512. b03 = a01 * a12 - a02 * a11,
  40513. b04 = a01 * a13 - a03 * a11,
  40514. b05 = a02 * a13 - a03 * a12,
  40515. b06 = a20 * a31 - a21 * a30,
  40516. b07 = a20 * a32 - a22 * a30,
  40517. b08 = a20 * a33 - a23 * a30,
  40518. b09 = a21 * a32 - a22 * a31,
  40519. b10 = a21 * a33 - a23 * a31,
  40520. b11 = a22 * a33 - a23 * a32,
  40521. det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;
  40522. if (!det) {
  40523. return null;
  40524. }
  40525. det = 1.0 / det;
  40526. out[0] = (a11 * b11 - a12 * b10 + a13 * b09) * det;
  40527. out[1] = (a02 * b10 - a01 * b11 - a03 * b09) * det;
  40528. out[2] = (a31 * b05 - a32 * b04 + a33 * b03) * det;
  40529. out[3] = (a22 * b04 - a21 * b05 - a23 * b03) * det;
  40530. out[4] = (a12 * b08 - a10 * b11 - a13 * b07) * det;
  40531. out[5] = (a00 * b11 - a02 * b08 + a03 * b07) * det;
  40532. out[6] = (a32 * b02 - a30 * b05 - a33 * b01) * det;
  40533. out[7] = (a20 * b05 - a22 * b02 + a23 * b01) * det;
  40534. out[8] = (a10 * b10 - a11 * b08 + a13 * b06) * det;
  40535. out[9] = (a01 * b08 - a00 * b10 - a03 * b06) * det;
  40536. out[10] = (a30 * b04 - a31 * b02 + a33 * b00) * det;
  40537. out[11] = (a21 * b02 - a20 * b04 - a23 * b00) * det;
  40538. out[12] = (a11 * b07 - a10 * b09 - a12 * b06) * det;
  40539. out[13] = (a00 * b09 - a01 * b07 + a02 * b06) * det;
  40540. out[14] = (a31 * b01 - a30 * b03 - a32 * b00) * det;
  40541. out[15] = (a20 * b03 - a21 * b01 + a22 * b00) * det;
  40542. return out;
  40543. }
  40544. var defaultOrientation = new Float32Array([0, 0, 0, 1]);
  40545. var defaultPosition = new Float32Array([0, 0, 0]);
  40546. function updateEyeMatrices(projection, view, pose, fov, offset, vrDisplay) {
  40547. mat4_perspectiveFromFieldOfView(projection, fov || null, vrDisplay.depthNear, vrDisplay.depthFar);
  40548. var orientation = pose.orientation || defaultOrientation;
  40549. var position = pose.position || defaultPosition;
  40550. mat4_fromRotationTranslation(view, orientation, position);
  40551. if (offset) mat4_translate(view, view, offset);
  40552. mat4_invert(view, view);
  40553. }
  40554. return function (frameData, pose, vrDisplay) {
  40555. if (!frameData || !pose) return false;
  40556. frameData.pose = pose;
  40557. frameData.timestamp = pose.timestamp;
  40558. updateEyeMatrices(frameData.leftProjectionMatrix, frameData.leftViewMatrix, pose, vrDisplay._getFieldOfView("left"), vrDisplay._getEyeOffset("left"), vrDisplay);
  40559. updateEyeMatrices(frameData.rightProjectionMatrix, frameData.rightViewMatrix, pose, vrDisplay._getFieldOfView("right"), vrDisplay._getEyeOffset("right"), vrDisplay);
  40560. return true;
  40561. };
  40562. }();
  40563. var isInsideCrossOriginIFrame = function isInsideCrossOriginIFrame() {
  40564. var isFramed = window.self !== window.top;
  40565. var refOrigin = getOriginFromUrl(document.referrer);
  40566. var thisOrigin = getOriginFromUrl(window.location.href);
  40567. return isFramed && refOrigin !== thisOrigin;
  40568. };
  40569. var getOriginFromUrl = function getOriginFromUrl(url) {
  40570. var domainIdx;
  40571. var protoSepIdx = url.indexOf("://");
  40572. if (protoSepIdx !== -1) {
  40573. domainIdx = protoSepIdx + 3;
  40574. } else {
  40575. domainIdx = 0;
  40576. }
  40577. var domainEndIdx = url.indexOf('/', domainIdx);
  40578. if (domainEndIdx === -1) {
  40579. domainEndIdx = url.length;
  40580. }
  40581. return url.substring(0, domainEndIdx);
  40582. };
  40583. var getQuaternionAngle = function getQuaternionAngle(quat) {
  40584. if (quat.w > 1) {
  40585. console.warn('getQuaternionAngle: w > 1');
  40586. return 0;
  40587. }
  40588. var angle = 2 * Math.acos(quat.w);
  40589. return angle;
  40590. };
  40591. var warnOnce = function () {
  40592. var observedWarnings = {};
  40593. return function (key, message) {
  40594. if (observedWarnings[key] === undefined) {
  40595. console.warn('webvr-polyfill: ' + message);
  40596. observedWarnings[key] = true;
  40597. }
  40598. };
  40599. }();
  40600. var deprecateWarning = function deprecateWarning(deprecated, suggested) {
  40601. var alternative = suggested ? 'Please use ' + suggested + ' instead.' : '';
  40602. warnOnce(deprecated, deprecated + ' has been deprecated. ' + 'This may not work on native WebVR displays. ' + alternative);
  40603. };
  40604. function WGLUPreserveGLState(gl, bindings, callback) {
  40605. if (!bindings) {
  40606. callback(gl);
  40607. return;
  40608. }
  40609. var boundValues = [];
  40610. var activeTexture = null;
  40611. for (var i = 0; i < bindings.length; ++i) {
  40612. var binding = bindings[i];
  40613. switch (binding) {
  40614. case gl.TEXTURE_BINDING_2D:
  40615. case gl.TEXTURE_BINDING_CUBE_MAP:
  40616. var textureUnit = bindings[++i];
  40617. if (textureUnit < gl.TEXTURE0 || textureUnit > gl.TEXTURE31) {
  40618. console.error("TEXTURE_BINDING_2D or TEXTURE_BINDING_CUBE_MAP must be followed by a valid texture unit");
  40619. boundValues.push(null, null);
  40620. break;
  40621. }
  40622. if (!activeTexture) {
  40623. activeTexture = gl.getParameter(gl.ACTIVE_TEXTURE);
  40624. }
  40625. gl.activeTexture(textureUnit);
  40626. boundValues.push(gl.getParameter(binding), null);
  40627. break;
  40628. case gl.ACTIVE_TEXTURE:
  40629. activeTexture = gl.getParameter(gl.ACTIVE_TEXTURE);
  40630. boundValues.push(null);
  40631. break;
  40632. default:
  40633. boundValues.push(gl.getParameter(binding));
  40634. break;
  40635. }
  40636. }
  40637. callback(gl);
  40638. for (var i = 0; i < bindings.length; ++i) {
  40639. var binding = bindings[i];
  40640. var boundValue = boundValues[i];
  40641. switch (binding) {
  40642. case gl.ACTIVE_TEXTURE:
  40643. break;
  40644. case gl.ARRAY_BUFFER_BINDING:
  40645. gl.bindBuffer(gl.ARRAY_BUFFER, boundValue);
  40646. break;
  40647. case gl.COLOR_CLEAR_VALUE:
  40648. gl.clearColor(boundValue[0], boundValue[1], boundValue[2], boundValue[3]);
  40649. break;
  40650. case gl.COLOR_WRITEMASK:
  40651. gl.colorMask(boundValue[0], boundValue[1], boundValue[2], boundValue[3]);
  40652. break;
  40653. case gl.CURRENT_PROGRAM:
  40654. gl.useProgram(boundValue);
  40655. break;
  40656. case gl.ELEMENT_ARRAY_BUFFER_BINDING:
  40657. gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, boundValue);
  40658. break;
  40659. case gl.FRAMEBUFFER_BINDING:
  40660. gl.bindFramebuffer(gl.FRAMEBUFFER, boundValue);
  40661. break;
  40662. case gl.RENDERBUFFER_BINDING:
  40663. gl.bindRenderbuffer(gl.RENDERBUFFER, boundValue);
  40664. break;
  40665. case gl.TEXTURE_BINDING_2D:
  40666. var textureUnit = bindings[++i];
  40667. if (textureUnit < gl.TEXTURE0 || textureUnit > gl.TEXTURE31)
  40668. break;
  40669. gl.activeTexture(textureUnit);
  40670. gl.bindTexture(gl.TEXTURE_2D, boundValue);
  40671. break;
  40672. case gl.TEXTURE_BINDING_CUBE_MAP:
  40673. var textureUnit = bindings[++i];
  40674. if (textureUnit < gl.TEXTURE0 || textureUnit > gl.TEXTURE31)
  40675. break;
  40676. gl.activeTexture(textureUnit);
  40677. gl.bindTexture(gl.TEXTURE_CUBE_MAP, boundValue);
  40678. break;
  40679. case gl.VIEWPORT:
  40680. gl.viewport(boundValue[0], boundValue[1], boundValue[2], boundValue[3]);
  40681. break;
  40682. case gl.BLEND:
  40683. case gl.CULL_FACE:
  40684. case gl.DEPTH_TEST:
  40685. case gl.SCISSOR_TEST:
  40686. case gl.STENCIL_TEST:
  40687. if (boundValue) {
  40688. gl.enable(binding);
  40689. } else {
  40690. gl.disable(binding);
  40691. }
  40692. break;
  40693. default:
  40694. console.log("No GL restore behavior for 0x" + binding.toString(16));
  40695. break;
  40696. }
  40697. if (activeTexture) {
  40698. gl.activeTexture(activeTexture);
  40699. }
  40700. }
  40701. }
  40702. var glPreserveState = WGLUPreserveGLState;
  40703. 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');
  40704. var distortionFS = ['precision mediump float;', 'uniform sampler2D diffuse;', 'varying vec2 vTexCoord;', 'void main() {', ' gl_FragColor = texture2D(diffuse, vTexCoord);', '}'].join('\n');
  40705. function CardboardDistorter(gl, cardboardUI, bufferScale, dirtySubmitFrameBindings) {
  40706. this.gl = gl;
  40707. this.cardboardUI = cardboardUI;
  40708. this.bufferScale = bufferScale;
  40709. this.dirtySubmitFrameBindings = dirtySubmitFrameBindings;
  40710. this.ctxAttribs = gl.getContextAttributes();
  40711. this.meshWidth = 20;
  40712. this.meshHeight = 20;
  40713. this.bufferWidth = gl.drawingBufferWidth;
  40714. this.bufferHeight = gl.drawingBufferHeight;
  40715. this.realBindFramebuffer = gl.bindFramebuffer;
  40716. this.realEnable = gl.enable;
  40717. this.realDisable = gl.disable;
  40718. this.realColorMask = gl.colorMask;
  40719. this.realClearColor = gl.clearColor;
  40720. this.realViewport = gl.viewport;
  40721. if (!isIOS()) {
  40722. this.realCanvasWidth = Object.getOwnPropertyDescriptor(gl.canvas.__proto__, 'width');
  40723. this.realCanvasHeight = Object.getOwnPropertyDescriptor(gl.canvas.__proto__, 'height');
  40724. }
  40725. this.isPatched = false;
  40726. this.lastBoundFramebuffer = null;
  40727. this.cullFace = false;
  40728. this.depthTest = false;
  40729. this.blend = false;
  40730. this.scissorTest = false;
  40731. this.stencilTest = false;
  40732. this.viewport = [0, 0, 0, 0];
  40733. this.colorMask = [true, true, true, true];
  40734. this.clearColor = [0, 0, 0, 0];
  40735. this.attribs = {
  40736. position: 0,
  40737. texCoord: 1
  40738. };
  40739. this.program = linkProgram(gl, distortionVS, distortionFS, this.attribs);
  40740. this.uniforms = getProgramUniforms(gl, this.program);
  40741. this.viewportOffsetScale = new Float32Array(8);
  40742. this.setTextureBounds();
  40743. this.vertexBuffer = gl.createBuffer();
  40744. this.indexBuffer = gl.createBuffer();
  40745. this.indexCount = 0;
  40746. this.renderTarget = gl.createTexture();
  40747. this.framebuffer = gl.createFramebuffer();
  40748. this.depthStencilBuffer = null;
  40749. this.depthBuffer = null;
  40750. this.stencilBuffer = null;
  40751. if (this.ctxAttribs.depth && this.ctxAttribs.stencil) {
  40752. this.depthStencilBuffer = gl.createRenderbuffer();
  40753. } else if (this.ctxAttribs.depth) {
  40754. this.depthBuffer = gl.createRenderbuffer();
  40755. } else if (this.ctxAttribs.stencil) {
  40756. this.stencilBuffer = gl.createRenderbuffer();
  40757. }
  40758. this.patch();
  40759. this.onResize();
  40760. }
  40761. CardboardDistorter.prototype.destroy = function () {
  40762. var gl = this.gl;
  40763. this.unpatch();
  40764. gl.deleteProgram(this.program);
  40765. gl.deleteBuffer(this.vertexBuffer);
  40766. gl.deleteBuffer(this.indexBuffer);
  40767. gl.deleteTexture(this.renderTarget);
  40768. gl.deleteFramebuffer(this.framebuffer);
  40769. if (this.depthStencilBuffer) {
  40770. gl.deleteRenderbuffer(this.depthStencilBuffer);
  40771. }
  40772. if (this.depthBuffer) {
  40773. gl.deleteRenderbuffer(this.depthBuffer);
  40774. }
  40775. if (this.stencilBuffer) {
  40776. gl.deleteRenderbuffer(this.stencilBuffer);
  40777. }
  40778. if (this.cardboardUI) {
  40779. this.cardboardUI.destroy();
  40780. }
  40781. };
  40782. CardboardDistorter.prototype.onResize = function () {
  40783. var gl = this.gl;
  40784. var self = this;
  40785. var glState = [gl.RENDERBUFFER_BINDING, gl.TEXTURE_BINDING_2D, gl.TEXTURE0];
  40786. glPreserveState(gl, glState, function (gl) {
  40787. self.realBindFramebuffer.call(gl, gl.FRAMEBUFFER, null);
  40788. if (self.scissorTest) {
  40789. self.realDisable.call(gl, gl.SCISSOR_TEST);
  40790. }
  40791. self.realColorMask.call(gl, true, true, true, true);
  40792. self.realViewport.call(gl, 0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
  40793. self.realClearColor.call(gl, 0, 0, 0, 1);
  40794. gl.clear(gl.COLOR_BUFFER_BIT);
  40795. self.realBindFramebuffer.call(gl, gl.FRAMEBUFFER, self.framebuffer);
  40796. gl.bindTexture(gl.TEXTURE_2D, self.renderTarget);
  40797. 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);
  40798. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  40799. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  40800. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  40801. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  40802. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, self.renderTarget, 0);
  40803. if (self.ctxAttribs.depth && self.ctxAttribs.stencil) {
  40804. gl.bindRenderbuffer(gl.RENDERBUFFER, self.depthStencilBuffer);
  40805. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, self.bufferWidth, self.bufferHeight);
  40806. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, self.depthStencilBuffer);
  40807. } else if (self.ctxAttribs.depth) {
  40808. gl.bindRenderbuffer(gl.RENDERBUFFER, self.depthBuffer);
  40809. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, self.bufferWidth, self.bufferHeight);
  40810. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, self.depthBuffer);
  40811. } else if (self.ctxAttribs.stencil) {
  40812. gl.bindRenderbuffer(gl.RENDERBUFFER, self.stencilBuffer);
  40813. gl.renderbufferStorage(gl.RENDERBUFFER, gl.STENCIL_INDEX8, self.bufferWidth, self.bufferHeight);
  40814. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.STENCIL_ATTACHMENT, gl.RENDERBUFFER, self.stencilBuffer);
  40815. }
  40816. if (!gl.checkFramebufferStatus(gl.FRAMEBUFFER) === gl.FRAMEBUFFER_COMPLETE) {
  40817. console.error('Framebuffer incomplete!');
  40818. }
  40819. self.realBindFramebuffer.call(gl, gl.FRAMEBUFFER, self.lastBoundFramebuffer);
  40820. if (self.scissorTest) {
  40821. self.realEnable.call(gl, gl.SCISSOR_TEST);
  40822. }
  40823. self.realColorMask.apply(gl, self.colorMask);
  40824. self.realViewport.apply(gl, self.viewport);
  40825. self.realClearColor.apply(gl, self.clearColor);
  40826. });
  40827. if (this.cardboardUI) {
  40828. this.cardboardUI.onResize();
  40829. }
  40830. };
  40831. CardboardDistorter.prototype.patch = function () {
  40832. if (this.isPatched) {
  40833. return;
  40834. }
  40835. var self = this;
  40836. var canvas = this.gl.canvas;
  40837. var gl = this.gl;
  40838. if (!isIOS()) {
  40839. canvas.width = getScreenWidth() * this.bufferScale;
  40840. canvas.height = getScreenHeight() * this.bufferScale;
  40841. Object.defineProperty(canvas, 'width', {
  40842. configurable: true,
  40843. enumerable: true,
  40844. get: function get() {
  40845. return self.bufferWidth;
  40846. },
  40847. set: function set(value) {
  40848. self.bufferWidth = value;
  40849. self.realCanvasWidth.set.call(canvas, value);
  40850. self.onResize();
  40851. }
  40852. });
  40853. Object.defineProperty(canvas, 'height', {
  40854. configurable: true,
  40855. enumerable: true,
  40856. get: function get() {
  40857. return self.bufferHeight;
  40858. },
  40859. set: function set(value) {
  40860. self.bufferHeight = value;
  40861. self.realCanvasHeight.set.call(canvas, value);
  40862. self.onResize();
  40863. }
  40864. });
  40865. }
  40866. this.lastBoundFramebuffer = gl.getParameter(gl.FRAMEBUFFER_BINDING);
  40867. if (this.lastBoundFramebuffer == null) {
  40868. this.lastBoundFramebuffer = this.framebuffer;
  40869. this.gl.bindFramebuffer(gl.FRAMEBUFFER, this.framebuffer);
  40870. }
  40871. this.gl.bindFramebuffer = function (target, framebuffer) {
  40872. self.lastBoundFramebuffer = framebuffer ? framebuffer : self.framebuffer;
  40873. self.realBindFramebuffer.call(gl, target, self.lastBoundFramebuffer);
  40874. };
  40875. this.cullFace = gl.getParameter(gl.CULL_FACE);
  40876. this.depthTest = gl.getParameter(gl.DEPTH_TEST);
  40877. this.blend = gl.getParameter(gl.BLEND);
  40878. this.scissorTest = gl.getParameter(gl.SCISSOR_TEST);
  40879. this.stencilTest = gl.getParameter(gl.STENCIL_TEST);
  40880. gl.enable = function (pname) {
  40881. switch (pname) {
  40882. case gl.CULL_FACE:
  40883. self.cullFace = true;break;
  40884. case gl.DEPTH_TEST:
  40885. self.depthTest = true;break;
  40886. case gl.BLEND:
  40887. self.blend = true;break;
  40888. case gl.SCISSOR_TEST:
  40889. self.scissorTest = true;break;
  40890. case gl.STENCIL_TEST:
  40891. self.stencilTest = true;break;
  40892. }
  40893. self.realEnable.call(gl, pname);
  40894. };
  40895. gl.disable = function (pname) {
  40896. switch (pname) {
  40897. case gl.CULL_FACE:
  40898. self.cullFace = false;break;
  40899. case gl.DEPTH_TEST:
  40900. self.depthTest = false;break;
  40901. case gl.BLEND:
  40902. self.blend = false;break;
  40903. case gl.SCISSOR_TEST:
  40904. self.scissorTest = false;break;
  40905. case gl.STENCIL_TEST:
  40906. self.stencilTest = false;break;
  40907. }
  40908. self.realDisable.call(gl, pname);
  40909. };
  40910. this.colorMask = gl.getParameter(gl.COLOR_WRITEMASK);
  40911. gl.colorMask = function (r, g, b, a) {
  40912. self.colorMask[0] = r;
  40913. self.colorMask[1] = g;
  40914. self.colorMask[2] = b;
  40915. self.colorMask[3] = a;
  40916. self.realColorMask.call(gl, r, g, b, a);
  40917. };
  40918. this.clearColor = gl.getParameter(gl.COLOR_CLEAR_VALUE);
  40919. gl.clearColor = function (r, g, b, a) {
  40920. self.clearColor[0] = r;
  40921. self.clearColor[1] = g;
  40922. self.clearColor[2] = b;
  40923. self.clearColor[3] = a;
  40924. self.realClearColor.call(gl, r, g, b, a);
  40925. };
  40926. this.viewport = gl.getParameter(gl.VIEWPORT);
  40927. gl.viewport = function (x, y, w, h) {
  40928. self.viewport[0] = x;
  40929. self.viewport[1] = y;
  40930. self.viewport[2] = w;
  40931. self.viewport[3] = h;
  40932. self.realViewport.call(gl, x, y, w, h);
  40933. };
  40934. this.isPatched = true;
  40935. safariCssSizeWorkaround(canvas);
  40936. };
  40937. CardboardDistorter.prototype.unpatch = function () {
  40938. if (!this.isPatched) {
  40939. return;
  40940. }
  40941. var gl = this.gl;
  40942. var canvas = this.gl.canvas;
  40943. if (!isIOS()) {
  40944. Object.defineProperty(canvas, 'width', this.realCanvasWidth);
  40945. Object.defineProperty(canvas, 'height', this.realCanvasHeight);
  40946. }
  40947. canvas.width = this.bufferWidth;
  40948. canvas.height = this.bufferHeight;
  40949. gl.bindFramebuffer = this.realBindFramebuffer;
  40950. gl.enable = this.realEnable;
  40951. gl.disable = this.realDisable;
  40952. gl.colorMask = this.realColorMask;
  40953. gl.clearColor = this.realClearColor;
  40954. gl.viewport = this.realViewport;
  40955. if (this.lastBoundFramebuffer == this.framebuffer) {
  40956. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  40957. }
  40958. this.isPatched = false;
  40959. setTimeout(function () {
  40960. safariCssSizeWorkaround(canvas);
  40961. }, 1);
  40962. };
  40963. CardboardDistorter.prototype.setTextureBounds = function (leftBounds, rightBounds) {
  40964. if (!leftBounds) {
  40965. leftBounds = [0, 0, 0.5, 1];
  40966. }
  40967. if (!rightBounds) {
  40968. rightBounds = [0.5, 0, 0.5, 1];
  40969. }
  40970. this.viewportOffsetScale[0] = leftBounds[0];
  40971. this.viewportOffsetScale[1] = leftBounds[1];
  40972. this.viewportOffsetScale[2] = leftBounds[2];
  40973. this.viewportOffsetScale[3] = leftBounds[3];
  40974. this.viewportOffsetScale[4] = rightBounds[0];
  40975. this.viewportOffsetScale[5] = rightBounds[1];
  40976. this.viewportOffsetScale[6] = rightBounds[2];
  40977. this.viewportOffsetScale[7] = rightBounds[3];
  40978. };
  40979. CardboardDistorter.prototype.submitFrame = function () {
  40980. var gl = this.gl;
  40981. var self = this;
  40982. var glState = [];
  40983. if (!this.dirtySubmitFrameBindings) {
  40984. glState.push(gl.CURRENT_PROGRAM, gl.ARRAY_BUFFER_BINDING, gl.ELEMENT_ARRAY_BUFFER_BINDING, gl.TEXTURE_BINDING_2D, gl.TEXTURE0);
  40985. }
  40986. glPreserveState(gl, glState, function (gl) {
  40987. self.realBindFramebuffer.call(gl, gl.FRAMEBUFFER, null);
  40988. if (self.cullFace) {
  40989. self.realDisable.call(gl, gl.CULL_FACE);
  40990. }
  40991. if (self.depthTest) {
  40992. self.realDisable.call(gl, gl.DEPTH_TEST);
  40993. }
  40994. if (self.blend) {
  40995. self.realDisable.call(gl, gl.BLEND);
  40996. }
  40997. if (self.scissorTest) {
  40998. self.realDisable.call(gl, gl.SCISSOR_TEST);
  40999. }
  41000. if (self.stencilTest) {
  41001. self.realDisable.call(gl, gl.STENCIL_TEST);
  41002. }
  41003. self.realColorMask.call(gl, true, true, true, true);
  41004. self.realViewport.call(gl, 0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
  41005. if (self.ctxAttribs.alpha || isIOS()) {
  41006. self.realClearColor.call(gl, 0, 0, 0, 1);
  41007. gl.clear(gl.COLOR_BUFFER_BIT);
  41008. }
  41009. gl.useProgram(self.program);
  41010. gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, self.indexBuffer);
  41011. gl.bindBuffer(gl.ARRAY_BUFFER, self.vertexBuffer);
  41012. gl.enableVertexAttribArray(self.attribs.position);
  41013. gl.enableVertexAttribArray(self.attribs.texCoord);
  41014. gl.vertexAttribPointer(self.attribs.position, 2, gl.FLOAT, false, 20, 0);
  41015. gl.vertexAttribPointer(self.attribs.texCoord, 3, gl.FLOAT, false, 20, 8);
  41016. gl.activeTexture(gl.TEXTURE0);
  41017. gl.uniform1i(self.uniforms.diffuse, 0);
  41018. gl.bindTexture(gl.TEXTURE_2D, self.renderTarget);
  41019. gl.uniform4fv(self.uniforms.viewportOffsetScale, self.viewportOffsetScale);
  41020. gl.drawElements(gl.TRIANGLES, self.indexCount, gl.UNSIGNED_SHORT, 0);
  41021. if (self.cardboardUI) {
  41022. self.cardboardUI.renderNoState();
  41023. }
  41024. self.realBindFramebuffer.call(self.gl, gl.FRAMEBUFFER, self.framebuffer);
  41025. if (!self.ctxAttribs.preserveDrawingBuffer) {
  41026. self.realClearColor.call(gl, 0, 0, 0, 0);
  41027. gl.clear(gl.COLOR_BUFFER_BIT);
  41028. }
  41029. if (!self.dirtySubmitFrameBindings) {
  41030. self.realBindFramebuffer.call(gl, gl.FRAMEBUFFER, self.lastBoundFramebuffer);
  41031. }
  41032. if (self.cullFace) {
  41033. self.realEnable.call(gl, gl.CULL_FACE);
  41034. }
  41035. if (self.depthTest) {
  41036. self.realEnable.call(gl, gl.DEPTH_TEST);
  41037. }
  41038. if (self.blend) {
  41039. self.realEnable.call(gl, gl.BLEND);
  41040. }
  41041. if (self.scissorTest) {
  41042. self.realEnable.call(gl, gl.SCISSOR_TEST);
  41043. }
  41044. if (self.stencilTest) {
  41045. self.realEnable.call(gl, gl.STENCIL_TEST);
  41046. }
  41047. self.realColorMask.apply(gl, self.colorMask);
  41048. self.realViewport.apply(gl, self.viewport);
  41049. if (self.ctxAttribs.alpha || !self.ctxAttribs.preserveDrawingBuffer) {
  41050. self.realClearColor.apply(gl, self.clearColor);
  41051. }
  41052. });
  41053. if (isIOS()) {
  41054. var canvas = gl.canvas;
  41055. if (canvas.width != self.bufferWidth || canvas.height != self.bufferHeight) {
  41056. self.bufferWidth = canvas.width;
  41057. self.bufferHeight = canvas.height;
  41058. self.onResize();
  41059. }
  41060. }
  41061. };
  41062. CardboardDistorter.prototype.updateDeviceInfo = function (deviceInfo) {
  41063. var gl = this.gl;
  41064. var self = this;
  41065. var glState = [gl.ARRAY_BUFFER_BINDING, gl.ELEMENT_ARRAY_BUFFER_BINDING];
  41066. glPreserveState(gl, glState, function (gl) {
  41067. var vertices = self.computeMeshVertices_(self.meshWidth, self.meshHeight, deviceInfo);
  41068. gl.bindBuffer(gl.ARRAY_BUFFER, self.vertexBuffer);
  41069. gl.bufferData(gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW);
  41070. if (!self.indexCount) {
  41071. var indices = self.computeMeshIndices_(self.meshWidth, self.meshHeight);
  41072. gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, self.indexBuffer);
  41073. gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, indices, gl.STATIC_DRAW);
  41074. self.indexCount = indices.length;
  41075. }
  41076. });
  41077. };
  41078. CardboardDistorter.prototype.computeMeshVertices_ = function (width, height, deviceInfo) {
  41079. var vertices = new Float32Array(2 * width * height * 5);
  41080. var lensFrustum = deviceInfo.getLeftEyeVisibleTanAngles();
  41081. var noLensFrustum = deviceInfo.getLeftEyeNoLensTanAngles();
  41082. var viewport = deviceInfo.getLeftEyeVisibleScreenRect(noLensFrustum);
  41083. var vidx = 0;
  41084. for (var e = 0; e < 2; e++) {
  41085. for (var j = 0; j < height; j++) {
  41086. for (var i = 0; i < width; i++, vidx++) {
  41087. var u = i / (width - 1);
  41088. var v = j / (height - 1);
  41089. var s = u;
  41090. var t = v;
  41091. var x = lerp(lensFrustum[0], lensFrustum[2], u);
  41092. var y = lerp(lensFrustum[3], lensFrustum[1], v);
  41093. var d = Math.sqrt(x * x + y * y);
  41094. var r = deviceInfo.distortion.distortInverse(d);
  41095. var p = x * r / d;
  41096. var q = y * r / d;
  41097. u = (p - noLensFrustum[0]) / (noLensFrustum[2] - noLensFrustum[0]);
  41098. v = (q - noLensFrustum[3]) / (noLensFrustum[1] - noLensFrustum[3]);
  41099. u = (viewport.x + u * viewport.width - 0.5) * 2.0;
  41100. v = (viewport.y + v * viewport.height - 0.5) * 2.0;
  41101. vertices[vidx * 5 + 0] = u;
  41102. vertices[vidx * 5 + 1] = v;
  41103. vertices[vidx * 5 + 2] = s;
  41104. vertices[vidx * 5 + 3] = t;
  41105. vertices[vidx * 5 + 4] = e;
  41106. }
  41107. }
  41108. var w = lensFrustum[2] - lensFrustum[0];
  41109. lensFrustum[0] = -(w + lensFrustum[0]);
  41110. lensFrustum[2] = w - lensFrustum[2];
  41111. w = noLensFrustum[2] - noLensFrustum[0];
  41112. noLensFrustum[0] = -(w + noLensFrustum[0]);
  41113. noLensFrustum[2] = w - noLensFrustum[2];
  41114. viewport.x = 1 - (viewport.x + viewport.width);
  41115. }
  41116. return vertices;
  41117. };
  41118. CardboardDistorter.prototype.computeMeshIndices_ = function (width, height) {
  41119. var indices = new Uint16Array(2 * (width - 1) * (height - 1) * 6);
  41120. var halfwidth = width / 2;
  41121. var halfheight = height / 2;
  41122. var vidx = 0;
  41123. var iidx = 0;
  41124. for (var e = 0; e < 2; e++) {
  41125. for (var j = 0; j < height; j++) {
  41126. for (var i = 0; i < width; i++, vidx++) {
  41127. if (i == 0 || j == 0) continue;
  41128. if (i <= halfwidth == j <= halfheight) {
  41129. indices[iidx++] = vidx;
  41130. indices[iidx++] = vidx - width - 1;
  41131. indices[iidx++] = vidx - width;
  41132. indices[iidx++] = vidx - width - 1;
  41133. indices[iidx++] = vidx;
  41134. indices[iidx++] = vidx - 1;
  41135. } else {
  41136. indices[iidx++] = vidx - 1;
  41137. indices[iidx++] = vidx - width;
  41138. indices[iidx++] = vidx;
  41139. indices[iidx++] = vidx - width;
  41140. indices[iidx++] = vidx - 1;
  41141. indices[iidx++] = vidx - width - 1;
  41142. }
  41143. }
  41144. }
  41145. }
  41146. return indices;
  41147. };
  41148. CardboardDistorter.prototype.getOwnPropertyDescriptor_ = function (proto, attrName) {
  41149. var descriptor = Object.getOwnPropertyDescriptor(proto, attrName);
  41150. if (descriptor.get === undefined || descriptor.set === undefined) {
  41151. descriptor.configurable = true;
  41152. descriptor.enumerable = true;
  41153. descriptor.get = function () {
  41154. return this.getAttribute(attrName);
  41155. };
  41156. descriptor.set = function (val) {
  41157. this.setAttribute(attrName, val);
  41158. };
  41159. }
  41160. return descriptor;
  41161. };
  41162. var uiVS = ['attribute vec2 position;', 'uniform mat4 projectionMat;', 'void main() {', ' gl_Position = projectionMat * vec4( position, -1.0, 1.0 );', '}'].join('\n');
  41163. var uiFS = ['precision mediump float;', 'uniform vec4 color;', 'void main() {', ' gl_FragColor = color;', '}'].join('\n');
  41164. var DEG2RAD = Math.PI / 180.0;
  41165. var kAnglePerGearSection = 60;
  41166. var kOuterRimEndAngle = 12;
  41167. var kInnerRimBeginAngle = 20;
  41168. var kOuterRadius = 1;
  41169. var kMiddleRadius = 0.75;
  41170. var kInnerRadius = 0.3125;
  41171. var kCenterLineThicknessDp = 4;
  41172. var kButtonWidthDp = 28;
  41173. var kTouchSlopFactor = 1.5;
  41174. function CardboardUI(gl) {
  41175. this.gl = gl;
  41176. this.attribs = {
  41177. position: 0
  41178. };
  41179. this.program = linkProgram(gl, uiVS, uiFS, this.attribs);
  41180. this.uniforms = getProgramUniforms(gl, this.program);
  41181. this.vertexBuffer = gl.createBuffer();
  41182. this.gearOffset = 0;
  41183. this.gearVertexCount = 0;
  41184. this.arrowOffset = 0;
  41185. this.arrowVertexCount = 0;
  41186. this.projMat = new Float32Array(16);
  41187. this.listener = null;
  41188. this.onResize();
  41189. }
  41190. CardboardUI.prototype.destroy = function () {
  41191. var gl = this.gl;
  41192. if (this.listener) {
  41193. gl.canvas.removeEventListener('click', this.listener, false);
  41194. }
  41195. gl.deleteProgram(this.program);
  41196. gl.deleteBuffer(this.vertexBuffer);
  41197. };
  41198. CardboardUI.prototype.listen = function (optionsCallback, backCallback) {
  41199. var canvas = this.gl.canvas;
  41200. this.listener = function (event) {
  41201. var midline = canvas.clientWidth / 2;
  41202. var buttonSize = kButtonWidthDp * kTouchSlopFactor;
  41203. if (event.clientX > midline - buttonSize && event.clientX < midline + buttonSize && event.clientY > canvas.clientHeight - buttonSize) {
  41204. optionsCallback(event);
  41205. }
  41206. else if (event.clientX < buttonSize && event.clientY < buttonSize) {
  41207. backCallback(event);
  41208. }
  41209. };
  41210. canvas.addEventListener('click', this.listener, false);
  41211. };
  41212. CardboardUI.prototype.onResize = function () {
  41213. var gl = this.gl;
  41214. var self = this;
  41215. var glState = [gl.ARRAY_BUFFER_BINDING];
  41216. glPreserveState(gl, glState, function (gl) {
  41217. var vertices = [];
  41218. var midline = gl.drawingBufferWidth / 2;
  41219. var physicalPixels = Math.max(screen.width, screen.height) * window.devicePixelRatio;
  41220. var scalingRatio = gl.drawingBufferWidth / physicalPixels;
  41221. var dps = scalingRatio * window.devicePixelRatio;
  41222. var lineWidth = kCenterLineThicknessDp * dps / 2;
  41223. var buttonSize = kButtonWidthDp * kTouchSlopFactor * dps;
  41224. var buttonScale = kButtonWidthDp * dps / 2;
  41225. var buttonBorder = (kButtonWidthDp * kTouchSlopFactor - kButtonWidthDp) * dps;
  41226. vertices.push(midline - lineWidth, buttonSize);
  41227. vertices.push(midline - lineWidth, gl.drawingBufferHeight);
  41228. vertices.push(midline + lineWidth, buttonSize);
  41229. vertices.push(midline + lineWidth, gl.drawingBufferHeight);
  41230. self.gearOffset = vertices.length / 2;
  41231. function addGearSegment(theta, r) {
  41232. var angle = (90 - theta) * DEG2RAD;
  41233. var x = Math.cos(angle);
  41234. var y = Math.sin(angle);
  41235. vertices.push(kInnerRadius * x * buttonScale + midline, kInnerRadius * y * buttonScale + buttonScale);
  41236. vertices.push(r * x * buttonScale + midline, r * y * buttonScale + buttonScale);
  41237. }
  41238. for (var i = 0; i <= 6; i++) {
  41239. var segmentTheta = i * kAnglePerGearSection;
  41240. addGearSegment(segmentTheta, kOuterRadius);
  41241. addGearSegment(segmentTheta + kOuterRimEndAngle, kOuterRadius);
  41242. addGearSegment(segmentTheta + kInnerRimBeginAngle, kMiddleRadius);
  41243. addGearSegment(segmentTheta + (kAnglePerGearSection - kInnerRimBeginAngle), kMiddleRadius);
  41244. addGearSegment(segmentTheta + (kAnglePerGearSection - kOuterRimEndAngle), kOuterRadius);
  41245. }
  41246. self.gearVertexCount = vertices.length / 2 - self.gearOffset;
  41247. self.arrowOffset = vertices.length / 2;
  41248. function addArrowVertex(x, y) {
  41249. vertices.push(buttonBorder + x, gl.drawingBufferHeight - buttonBorder - y);
  41250. }
  41251. var angledLineWidth = lineWidth / Math.sin(45 * DEG2RAD);
  41252. addArrowVertex(0, buttonScale);
  41253. addArrowVertex(buttonScale, 0);
  41254. addArrowVertex(buttonScale + angledLineWidth, angledLineWidth);
  41255. addArrowVertex(angledLineWidth, buttonScale + angledLineWidth);
  41256. addArrowVertex(angledLineWidth, buttonScale - angledLineWidth);
  41257. addArrowVertex(0, buttonScale);
  41258. addArrowVertex(buttonScale, buttonScale * 2);
  41259. addArrowVertex(buttonScale + angledLineWidth, buttonScale * 2 - angledLineWidth);
  41260. addArrowVertex(angledLineWidth, buttonScale - angledLineWidth);
  41261. addArrowVertex(0, buttonScale);
  41262. addArrowVertex(angledLineWidth, buttonScale - lineWidth);
  41263. addArrowVertex(kButtonWidthDp * dps, buttonScale - lineWidth);
  41264. addArrowVertex(angledLineWidth, buttonScale + lineWidth);
  41265. addArrowVertex(kButtonWidthDp * dps, buttonScale + lineWidth);
  41266. self.arrowVertexCount = vertices.length / 2 - self.arrowOffset;
  41267. gl.bindBuffer(gl.ARRAY_BUFFER, self.vertexBuffer);
  41268. gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW);
  41269. });
  41270. };
  41271. CardboardUI.prototype.render = function () {
  41272. var gl = this.gl;
  41273. var self = this;
  41274. 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];
  41275. glPreserveState(gl, glState, function (gl) {
  41276. gl.disable(gl.CULL_FACE);
  41277. gl.disable(gl.DEPTH_TEST);
  41278. gl.disable(gl.BLEND);
  41279. gl.disable(gl.SCISSOR_TEST);
  41280. gl.disable(gl.STENCIL_TEST);
  41281. gl.colorMask(true, true, true, true);
  41282. gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
  41283. self.renderNoState();
  41284. });
  41285. };
  41286. CardboardUI.prototype.renderNoState = function () {
  41287. var gl = this.gl;
  41288. gl.useProgram(this.program);
  41289. gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer);
  41290. gl.enableVertexAttribArray(this.attribs.position);
  41291. gl.vertexAttribPointer(this.attribs.position, 2, gl.FLOAT, false, 8, 0);
  41292. gl.uniform4f(this.uniforms.color, 1.0, 1.0, 1.0, 1.0);
  41293. orthoMatrix(this.projMat, 0, gl.drawingBufferWidth, 0, gl.drawingBufferHeight, 0.1, 1024.0);
  41294. gl.uniformMatrix4fv(this.uniforms.projectionMat, false, this.projMat);
  41295. gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
  41296. gl.drawArrays(gl.TRIANGLE_STRIP, this.gearOffset, this.gearVertexCount);
  41297. gl.drawArrays(gl.TRIANGLE_STRIP, this.arrowOffset, this.arrowVertexCount);
  41298. };
  41299. function Distortion(coefficients) {
  41300. this.coefficients = coefficients;
  41301. }
  41302. Distortion.prototype.distortInverse = function (radius) {
  41303. var r0 = 0;
  41304. var r1 = 1;
  41305. var dr0 = radius - this.distort(r0);
  41306. while (Math.abs(r1 - r0) > 0.0001 ) {
  41307. var dr1 = radius - this.distort(r1);
  41308. var r2 = r1 - dr1 * ((r1 - r0) / (dr1 - dr0));
  41309. r0 = r1;
  41310. r1 = r2;
  41311. dr0 = dr1;
  41312. }
  41313. return r1;
  41314. };
  41315. Distortion.prototype.distort = function (radius) {
  41316. var r2 = radius * radius;
  41317. var ret = 0;
  41318. for (var i = 0; i < this.coefficients.length; i++) {
  41319. ret = r2 * (ret + this.coefficients[i]);
  41320. }
  41321. return (ret + 1) * radius;
  41322. };
  41323. var degToRad = Math.PI / 180;
  41324. var radToDeg = 180 / Math.PI;
  41325. var Vector3 = function Vector3(x, y, z) {
  41326. this.x = x || 0;
  41327. this.y = y || 0;
  41328. this.z = z || 0;
  41329. };
  41330. Vector3.prototype = {
  41331. constructor: Vector3,
  41332. set: function set(x, y, z) {
  41333. this.x = x;
  41334. this.y = y;
  41335. this.z = z;
  41336. return this;
  41337. },
  41338. copy: function copy(v) {
  41339. this.x = v.x;
  41340. this.y = v.y;
  41341. this.z = v.z;
  41342. return this;
  41343. },
  41344. length: function length() {
  41345. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  41346. },
  41347. normalize: function normalize() {
  41348. var scalar = this.length();
  41349. if (scalar !== 0) {
  41350. var invScalar = 1 / scalar;
  41351. this.multiplyScalar(invScalar);
  41352. } else {
  41353. this.x = 0;
  41354. this.y = 0;
  41355. this.z = 0;
  41356. }
  41357. return this;
  41358. },
  41359. multiplyScalar: function multiplyScalar(scalar) {
  41360. this.x *= scalar;
  41361. this.y *= scalar;
  41362. this.z *= scalar;
  41363. },
  41364. applyQuaternion: function applyQuaternion(q) {
  41365. var x = this.x;
  41366. var y = this.y;
  41367. var z = this.z;
  41368. var qx = q.x;
  41369. var qy = q.y;
  41370. var qz = q.z;
  41371. var qw = q.w;
  41372. var ix = qw * x + qy * z - qz * y;
  41373. var iy = qw * y + qz * x - qx * z;
  41374. var iz = qw * z + qx * y - qy * x;
  41375. var iw = -qx * x - qy * y - qz * z;
  41376. this.x = ix * qw + iw * -qx + iy * -qz - iz * -qy;
  41377. this.y = iy * qw + iw * -qy + iz * -qx - ix * -qz;
  41378. this.z = iz * qw + iw * -qz + ix * -qy - iy * -qx;
  41379. return this;
  41380. },
  41381. dot: function dot(v) {
  41382. return this.x * v.x + this.y * v.y + this.z * v.z;
  41383. },
  41384. crossVectors: function crossVectors(a, b) {
  41385. var ax = a.x,
  41386. ay = a.y,
  41387. az = a.z;
  41388. var bx = b.x,
  41389. by = b.y,
  41390. bz = b.z;
  41391. this.x = ay * bz - az * by;
  41392. this.y = az * bx - ax * bz;
  41393. this.z = ax * by - ay * bx;
  41394. return this;
  41395. }
  41396. };
  41397. var Quaternion = function Quaternion(x, y, z, w) {
  41398. this.x = x || 0;
  41399. this.y = y || 0;
  41400. this.z = z || 0;
  41401. this.w = w !== undefined ? w : 1;
  41402. };
  41403. Quaternion.prototype = {
  41404. constructor: Quaternion,
  41405. set: function set(x, y, z, w) {
  41406. this.x = x;
  41407. this.y = y;
  41408. this.z = z;
  41409. this.w = w;
  41410. return this;
  41411. },
  41412. copy: function copy(quaternion) {
  41413. this.x = quaternion.x;
  41414. this.y = quaternion.y;
  41415. this.z = quaternion.z;
  41416. this.w = quaternion.w;
  41417. return this;
  41418. },
  41419. setFromEulerXYZ: function setFromEulerXYZ(x, y, z) {
  41420. var c1 = Math.cos(x / 2);
  41421. var c2 = Math.cos(y / 2);
  41422. var c3 = Math.cos(z / 2);
  41423. var s1 = Math.sin(x / 2);
  41424. var s2 = Math.sin(y / 2);
  41425. var s3 = Math.sin(z / 2);
  41426. this.x = s1 * c2 * c3 + c1 * s2 * s3;
  41427. this.y = c1 * s2 * c3 - s1 * c2 * s3;
  41428. this.z = c1 * c2 * s3 + s1 * s2 * c3;
  41429. this.w = c1 * c2 * c3 - s1 * s2 * s3;
  41430. return this;
  41431. },
  41432. setFromEulerYXZ: function setFromEulerYXZ(x, y, z) {
  41433. var c1 = Math.cos(x / 2);
  41434. var c2 = Math.cos(y / 2);
  41435. var c3 = Math.cos(z / 2);
  41436. var s1 = Math.sin(x / 2);
  41437. var s2 = Math.sin(y / 2);
  41438. var s3 = Math.sin(z / 2);
  41439. this.x = s1 * c2 * c3 + c1 * s2 * s3;
  41440. this.y = c1 * s2 * c3 - s1 * c2 * s3;
  41441. this.z = c1 * c2 * s3 - s1 * s2 * c3;
  41442. this.w = c1 * c2 * c3 + s1 * s2 * s3;
  41443. return this;
  41444. },
  41445. setFromAxisAngle: function setFromAxisAngle(axis, angle) {
  41446. var halfAngle = angle / 2,
  41447. s = Math.sin(halfAngle);
  41448. this.x = axis.x * s;
  41449. this.y = axis.y * s;
  41450. this.z = axis.z * s;
  41451. this.w = Math.cos(halfAngle);
  41452. return this;
  41453. },
  41454. multiply: function multiply(q) {
  41455. return this.multiplyQuaternions(this, q);
  41456. },
  41457. multiplyQuaternions: function multiplyQuaternions(a, b) {
  41458. var qax = a.x,
  41459. qay = a.y,
  41460. qaz = a.z,
  41461. qaw = a.w;
  41462. var qbx = b.x,
  41463. qby = b.y,
  41464. qbz = b.z,
  41465. qbw = b.w;
  41466. this.x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  41467. this.y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  41468. this.z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  41469. this.w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  41470. return this;
  41471. },
  41472. inverse: function inverse() {
  41473. this.x *= -1;
  41474. this.y *= -1;
  41475. this.z *= -1;
  41476. this.normalize();
  41477. return this;
  41478. },
  41479. normalize: function normalize() {
  41480. var l = Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  41481. if (l === 0) {
  41482. this.x = 0;
  41483. this.y = 0;
  41484. this.z = 0;
  41485. this.w = 1;
  41486. } else {
  41487. l = 1 / l;
  41488. this.x = this.x * l;
  41489. this.y = this.y * l;
  41490. this.z = this.z * l;
  41491. this.w = this.w * l;
  41492. }
  41493. return this;
  41494. },
  41495. slerp: function slerp(qb, t) {
  41496. if (t === 0) return this;
  41497. if (t === 1) return this.copy(qb);
  41498. var x = this.x,
  41499. y = this.y,
  41500. z = this.z,
  41501. w = this.w;
  41502. var cosHalfTheta = w * qb.w + x * qb.x + y * qb.y + z * qb.z;
  41503. if (cosHalfTheta < 0) {
  41504. this.w = -qb.w;
  41505. this.x = -qb.x;
  41506. this.y = -qb.y;
  41507. this.z = -qb.z;
  41508. cosHalfTheta = -cosHalfTheta;
  41509. } else {
  41510. this.copy(qb);
  41511. }
  41512. if (cosHalfTheta >= 1.0) {
  41513. this.w = w;
  41514. this.x = x;
  41515. this.y = y;
  41516. this.z = z;
  41517. return this;
  41518. }
  41519. var halfTheta = Math.acos(cosHalfTheta);
  41520. var sinHalfTheta = Math.sqrt(1.0 - cosHalfTheta * cosHalfTheta);
  41521. if (Math.abs(sinHalfTheta) < 0.001) {
  41522. this.w = 0.5 * (w + this.w);
  41523. this.x = 0.5 * (x + this.x);
  41524. this.y = 0.5 * (y + this.y);
  41525. this.z = 0.5 * (z + this.z);
  41526. return this;
  41527. }
  41528. var ratioA = Math.sin((1 - t) * halfTheta) / sinHalfTheta,
  41529. ratioB = Math.sin(t * halfTheta) / sinHalfTheta;
  41530. this.w = w * ratioA + this.w * ratioB;
  41531. this.x = x * ratioA + this.x * ratioB;
  41532. this.y = y * ratioA + this.y * ratioB;
  41533. this.z = z * ratioA + this.z * ratioB;
  41534. return this;
  41535. },
  41536. setFromUnitVectors: function () {
  41537. var v1, r;
  41538. var EPS = 0.000001;
  41539. return function (vFrom, vTo) {
  41540. if (v1 === undefined) v1 = new Vector3();
  41541. r = vFrom.dot(vTo) + 1;
  41542. if (r < EPS) {
  41543. r = 0;
  41544. if (Math.abs(vFrom.x) > Math.abs(vFrom.z)) {
  41545. v1.set(-vFrom.y, vFrom.x, 0);
  41546. } else {
  41547. v1.set(0, -vFrom.z, vFrom.y);
  41548. }
  41549. } else {
  41550. v1.crossVectors(vFrom, vTo);
  41551. }
  41552. this.x = v1.x;
  41553. this.y = v1.y;
  41554. this.z = v1.z;
  41555. this.w = r;
  41556. this.normalize();
  41557. return this;
  41558. };
  41559. }()
  41560. };
  41561. function Device(params) {
  41562. this.width = params.width || getScreenWidth();
  41563. this.height = params.height || getScreenHeight();
  41564. this.widthMeters = params.widthMeters;
  41565. this.heightMeters = params.heightMeters;
  41566. this.bevelMeters = params.bevelMeters;
  41567. }
  41568. var DEFAULT_ANDROID = new Device({
  41569. widthMeters: 0.110,
  41570. heightMeters: 0.062,
  41571. bevelMeters: 0.004
  41572. });
  41573. var DEFAULT_IOS = new Device({
  41574. widthMeters: 0.1038,
  41575. heightMeters: 0.0584,
  41576. bevelMeters: 0.004
  41577. });
  41578. var Viewers = {
  41579. CardboardV1: new CardboardViewer({
  41580. id: 'CardboardV1',
  41581. label: 'Cardboard I/O 2014',
  41582. fov: 40,
  41583. interLensDistance: 0.060,
  41584. baselineLensDistance: 0.035,
  41585. screenLensDistance: 0.042,
  41586. distortionCoefficients: [0.441, 0.156],
  41587. 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]
  41588. }),
  41589. CardboardV2: new CardboardViewer({
  41590. id: 'CardboardV2',
  41591. label: 'Cardboard I/O 2015',
  41592. fov: 60,
  41593. interLensDistance: 0.064,
  41594. baselineLensDistance: 0.035,
  41595. screenLensDistance: 0.039,
  41596. distortionCoefficients: [0.34, 0.55],
  41597. 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]
  41598. })
  41599. };
  41600. function DeviceInfo(deviceParams, additionalViewers) {
  41601. this.viewer = Viewers.CardboardV2;
  41602. this.updateDeviceParams(deviceParams);
  41603. this.distortion = new Distortion(this.viewer.distortionCoefficients);
  41604. for (var i = 0; i < additionalViewers.length; i++) {
  41605. var viewer = additionalViewers[i];
  41606. Viewers[viewer.id] = new CardboardViewer(viewer);
  41607. }
  41608. }
  41609. DeviceInfo.prototype.updateDeviceParams = function (deviceParams) {
  41610. this.device = this.determineDevice_(deviceParams) || this.device;
  41611. };
  41612. DeviceInfo.prototype.getDevice = function () {
  41613. return this.device;
  41614. };
  41615. DeviceInfo.prototype.setViewer = function (viewer) {
  41616. this.viewer = viewer;
  41617. this.distortion = new Distortion(this.viewer.distortionCoefficients);
  41618. };
  41619. DeviceInfo.prototype.determineDevice_ = function (deviceParams) {
  41620. if (!deviceParams) {
  41621. if (isIOS()) {
  41622. console.warn('Using fallback iOS device measurements.');
  41623. return DEFAULT_IOS;
  41624. } else {
  41625. console.warn('Using fallback Android device measurements.');
  41626. return DEFAULT_ANDROID;
  41627. }
  41628. }
  41629. var METERS_PER_INCH = 0.0254;
  41630. var metersPerPixelX = METERS_PER_INCH / deviceParams.xdpi;
  41631. var metersPerPixelY = METERS_PER_INCH / deviceParams.ydpi;
  41632. var width = getScreenWidth();
  41633. var height = getScreenHeight();
  41634. return new Device({
  41635. widthMeters: metersPerPixelX * width,
  41636. heightMeters: metersPerPixelY * height,
  41637. bevelMeters: deviceParams.bevelMm * 0.001
  41638. });
  41639. };
  41640. DeviceInfo.prototype.getDistortedFieldOfViewLeftEye = function () {
  41641. var viewer = this.viewer;
  41642. var device = this.device;
  41643. var distortion = this.distortion;
  41644. var eyeToScreenDistance = viewer.screenLensDistance;
  41645. var outerDist = (device.widthMeters - viewer.interLensDistance) / 2;
  41646. var innerDist = viewer.interLensDistance / 2;
  41647. var bottomDist = viewer.baselineLensDistance - device.bevelMeters;
  41648. var topDist = device.heightMeters - bottomDist;
  41649. var outerAngle = radToDeg * Math.atan(distortion.distort(outerDist / eyeToScreenDistance));
  41650. var innerAngle = radToDeg * Math.atan(distortion.distort(innerDist / eyeToScreenDistance));
  41651. var bottomAngle = radToDeg * Math.atan(distortion.distort(bottomDist / eyeToScreenDistance));
  41652. var topAngle = radToDeg * Math.atan(distortion.distort(topDist / eyeToScreenDistance));
  41653. return {
  41654. leftDegrees: Math.min(outerAngle, viewer.fov),
  41655. rightDegrees: Math.min(innerAngle, viewer.fov),
  41656. downDegrees: Math.min(bottomAngle, viewer.fov),
  41657. upDegrees: Math.min(topAngle, viewer.fov)
  41658. };
  41659. };
  41660. DeviceInfo.prototype.getLeftEyeVisibleTanAngles = function () {
  41661. var viewer = this.viewer;
  41662. var device = this.device;
  41663. var distortion = this.distortion;
  41664. var fovLeft = Math.tan(-degToRad * viewer.fov);
  41665. var fovTop = Math.tan(degToRad * viewer.fov);
  41666. var fovRight = Math.tan(degToRad * viewer.fov);
  41667. var fovBottom = Math.tan(-degToRad * viewer.fov);
  41668. var halfWidth = device.widthMeters / 4;
  41669. var halfHeight = device.heightMeters / 2;
  41670. var verticalLensOffset = viewer.baselineLensDistance - device.bevelMeters - halfHeight;
  41671. var centerX = viewer.interLensDistance / 2 - halfWidth;
  41672. var centerY = -verticalLensOffset;
  41673. var centerZ = viewer.screenLensDistance;
  41674. var screenLeft = distortion.distort((centerX - halfWidth) / centerZ);
  41675. var screenTop = distortion.distort((centerY + halfHeight) / centerZ);
  41676. var screenRight = distortion.distort((centerX + halfWidth) / centerZ);
  41677. var screenBottom = distortion.distort((centerY - halfHeight) / centerZ);
  41678. var result = new Float32Array(4);
  41679. result[0] = Math.max(fovLeft, screenLeft);
  41680. result[1] = Math.min(fovTop, screenTop);
  41681. result[2] = Math.min(fovRight, screenRight);
  41682. result[3] = Math.max(fovBottom, screenBottom);
  41683. return result;
  41684. };
  41685. DeviceInfo.prototype.getLeftEyeNoLensTanAngles = function () {
  41686. var viewer = this.viewer;
  41687. var device = this.device;
  41688. var distortion = this.distortion;
  41689. var result = new Float32Array(4);
  41690. var fovLeft = distortion.distortInverse(Math.tan(-degToRad * viewer.fov));
  41691. var fovTop = distortion.distortInverse(Math.tan(degToRad * viewer.fov));
  41692. var fovRight = distortion.distortInverse(Math.tan(degToRad * viewer.fov));
  41693. var fovBottom = distortion.distortInverse(Math.tan(-degToRad * viewer.fov));
  41694. var halfWidth = device.widthMeters / 4;
  41695. var halfHeight = device.heightMeters / 2;
  41696. var verticalLensOffset = viewer.baselineLensDistance - device.bevelMeters - halfHeight;
  41697. var centerX = viewer.interLensDistance / 2 - halfWidth;
  41698. var centerY = -verticalLensOffset;
  41699. var centerZ = viewer.screenLensDistance;
  41700. var screenLeft = (centerX - halfWidth) / centerZ;
  41701. var screenTop = (centerY + halfHeight) / centerZ;
  41702. var screenRight = (centerX + halfWidth) / centerZ;
  41703. var screenBottom = (centerY - halfHeight) / centerZ;
  41704. result[0] = Math.max(fovLeft, screenLeft);
  41705. result[1] = Math.min(fovTop, screenTop);
  41706. result[2] = Math.min(fovRight, screenRight);
  41707. result[3] = Math.max(fovBottom, screenBottom);
  41708. return result;
  41709. };
  41710. DeviceInfo.prototype.getLeftEyeVisibleScreenRect = function (undistortedFrustum) {
  41711. var viewer = this.viewer;
  41712. var device = this.device;
  41713. var dist = viewer.screenLensDistance;
  41714. var eyeX = (device.widthMeters - viewer.interLensDistance) / 2;
  41715. var eyeY = viewer.baselineLensDistance - device.bevelMeters;
  41716. var left = (undistortedFrustum[0] * dist + eyeX) / device.widthMeters;
  41717. var top = (undistortedFrustum[1] * dist + eyeY) / device.heightMeters;
  41718. var right = (undistortedFrustum[2] * dist + eyeX) / device.widthMeters;
  41719. var bottom = (undistortedFrustum[3] * dist + eyeY) / device.heightMeters;
  41720. return {
  41721. x: left,
  41722. y: bottom,
  41723. width: right - left,
  41724. height: top - bottom
  41725. };
  41726. };
  41727. DeviceInfo.prototype.getFieldOfViewLeftEye = function (opt_isUndistorted) {
  41728. return opt_isUndistorted ? this.getUndistortedFieldOfViewLeftEye() : this.getDistortedFieldOfViewLeftEye();
  41729. };
  41730. DeviceInfo.prototype.getFieldOfViewRightEye = function (opt_isUndistorted) {
  41731. var fov = this.getFieldOfViewLeftEye(opt_isUndistorted);
  41732. return {
  41733. leftDegrees: fov.rightDegrees,
  41734. rightDegrees: fov.leftDegrees,
  41735. upDegrees: fov.upDegrees,
  41736. downDegrees: fov.downDegrees
  41737. };
  41738. };
  41739. DeviceInfo.prototype.getUndistortedFieldOfViewLeftEye = function () {
  41740. var p = this.getUndistortedParams_();
  41741. return {
  41742. leftDegrees: radToDeg * Math.atan(p.outerDist),
  41743. rightDegrees: radToDeg * Math.atan(p.innerDist),
  41744. downDegrees: radToDeg * Math.atan(p.bottomDist),
  41745. upDegrees: radToDeg * Math.atan(p.topDist)
  41746. };
  41747. };
  41748. DeviceInfo.prototype.getUndistortedViewportLeftEye = function () {
  41749. var p = this.getUndistortedParams_();
  41750. var viewer = this.viewer;
  41751. var device = this.device;
  41752. var eyeToScreenDistance = viewer.screenLensDistance;
  41753. var screenWidth = device.widthMeters / eyeToScreenDistance;
  41754. var screenHeight = device.heightMeters / eyeToScreenDistance;
  41755. var xPxPerTanAngle = device.width / screenWidth;
  41756. var yPxPerTanAngle = device.height / screenHeight;
  41757. var x = Math.round((p.eyePosX - p.outerDist) * xPxPerTanAngle);
  41758. var y = Math.round((p.eyePosY - p.bottomDist) * yPxPerTanAngle);
  41759. return {
  41760. x: x,
  41761. y: y,
  41762. width: Math.round((p.eyePosX + p.innerDist) * xPxPerTanAngle) - x,
  41763. height: Math.round((p.eyePosY + p.topDist) * yPxPerTanAngle) - y
  41764. };
  41765. };
  41766. DeviceInfo.prototype.getUndistortedParams_ = function () {
  41767. var viewer = this.viewer;
  41768. var device = this.device;
  41769. var distortion = this.distortion;
  41770. var eyeToScreenDistance = viewer.screenLensDistance;
  41771. var halfLensDistance = viewer.interLensDistance / 2 / eyeToScreenDistance;
  41772. var screenWidth = device.widthMeters / eyeToScreenDistance;
  41773. var screenHeight = device.heightMeters / eyeToScreenDistance;
  41774. var eyePosX = screenWidth / 2 - halfLensDistance;
  41775. var eyePosY = (viewer.baselineLensDistance - device.bevelMeters) / eyeToScreenDistance;
  41776. var maxFov = viewer.fov;
  41777. var viewerMax = distortion.distortInverse(Math.tan(degToRad * maxFov));
  41778. var outerDist = Math.min(eyePosX, viewerMax);
  41779. var innerDist = Math.min(halfLensDistance, viewerMax);
  41780. var bottomDist = Math.min(eyePosY, viewerMax);
  41781. var topDist = Math.min(screenHeight - eyePosY, viewerMax);
  41782. return {
  41783. outerDist: outerDist,
  41784. innerDist: innerDist,
  41785. topDist: topDist,
  41786. bottomDist: bottomDist,
  41787. eyePosX: eyePosX,
  41788. eyePosY: eyePosY
  41789. };
  41790. };
  41791. function CardboardViewer(params) {
  41792. this.id = params.id;
  41793. this.label = params.label;
  41794. this.fov = params.fov;
  41795. this.interLensDistance = params.interLensDistance;
  41796. this.baselineLensDistance = params.baselineLensDistance;
  41797. this.screenLensDistance = params.screenLensDistance;
  41798. this.distortionCoefficients = params.distortionCoefficients;
  41799. this.inverseCoefficients = params.inverseCoefficients;
  41800. }
  41801. DeviceInfo.Viewers = Viewers;
  41802. var format = 1;
  41803. var last_updated = "2018-12-10T17:01:42Z";
  41804. 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_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 E1005/*"},{"ua":"ONE E1005"}],"dpi":[442.4,441.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 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":"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":"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}];
  41805. var DPDB_CACHE = {
  41806. format: format,
  41807. last_updated: last_updated,
  41808. devices: devices
  41809. };
  41810. function Dpdb(url, onDeviceParamsUpdated) {
  41811. this.dpdb = DPDB_CACHE;
  41812. this.recalculateDeviceParams_();
  41813. if (url) {
  41814. this.onDeviceParamsUpdated = onDeviceParamsUpdated;
  41815. var xhr = new XMLHttpRequest();
  41816. var obj = this;
  41817. xhr.open('GET', url, true);
  41818. xhr.addEventListener('load', function () {
  41819. obj.loading = false;
  41820. if (xhr.status >= 200 && xhr.status <= 299) {
  41821. obj.dpdb = JSON.parse(xhr.response);
  41822. obj.recalculateDeviceParams_();
  41823. } else {
  41824. console.error('Error loading online DPDB!');
  41825. }
  41826. });
  41827. xhr.send();
  41828. }
  41829. }
  41830. Dpdb.prototype.getDeviceParams = function () {
  41831. return this.deviceParams;
  41832. };
  41833. Dpdb.prototype.recalculateDeviceParams_ = function () {
  41834. var newDeviceParams = this.calcDeviceParams_();
  41835. if (newDeviceParams) {
  41836. this.deviceParams = newDeviceParams;
  41837. if (this.onDeviceParamsUpdated) {
  41838. this.onDeviceParamsUpdated(this.deviceParams);
  41839. }
  41840. } else {
  41841. console.error('Failed to recalculate device parameters.');
  41842. }
  41843. };
  41844. Dpdb.prototype.calcDeviceParams_ = function () {
  41845. var db = this.dpdb;
  41846. if (!db) {
  41847. console.error('DPDB not available.');
  41848. return null;
  41849. }
  41850. if (db.format != 1) {
  41851. console.error('DPDB has unexpected format version.');
  41852. return null;
  41853. }
  41854. if (!db.devices || !db.devices.length) {
  41855. console.error('DPDB does not have a devices section.');
  41856. return null;
  41857. }
  41858. var userAgent = navigator.userAgent || navigator.vendor || window.opera;
  41859. var width = getScreenWidth();
  41860. var height = getScreenHeight();
  41861. if (!db.devices) {
  41862. console.error('DPDB has no devices section.');
  41863. return null;
  41864. }
  41865. for (var i = 0; i < db.devices.length; i++) {
  41866. var device = db.devices[i];
  41867. if (!device.rules) {
  41868. console.warn('Device[' + i + '] has no rules section.');
  41869. continue;
  41870. }
  41871. if (device.type != 'ios' && device.type != 'android') {
  41872. console.warn('Device[' + i + '] has invalid type.');
  41873. continue;
  41874. }
  41875. if (isIOS() != (device.type == 'ios')) continue;
  41876. var matched = false;
  41877. for (var j = 0; j < device.rules.length; j++) {
  41878. var rule = device.rules[j];
  41879. if (this.ruleMatches_(rule, userAgent, width, height)) {
  41880. matched = true;
  41881. break;
  41882. }
  41883. }
  41884. if (!matched) continue;
  41885. var xdpi = device.dpi[0] || device.dpi;
  41886. var ydpi = device.dpi[1] || device.dpi;
  41887. return new DeviceParams({ xdpi: xdpi, ydpi: ydpi, bevelMm: device.bw });
  41888. }
  41889. console.warn('No DPDB device match.');
  41890. return null;
  41891. };
  41892. Dpdb.prototype.ruleMatches_ = function (rule, ua, screenWidth, screenHeight) {
  41893. if (!rule.ua && !rule.res) return false;
  41894. if (rule.ua && rule.ua.substring(0, 2) === 'SM') rule.ua = rule.ua.substring(0, 7);
  41895. if (rule.ua && ua.indexOf(rule.ua) < 0) return false;
  41896. if (rule.res) {
  41897. if (!rule.res[0] || !rule.res[1]) return false;
  41898. var resX = rule.res[0];
  41899. var resY = rule.res[1];
  41900. if (Math.min(screenWidth, screenHeight) != Math.min(resX, resY) || Math.max(screenWidth, screenHeight) != Math.max(resX, resY)) {
  41901. return false;
  41902. }
  41903. }
  41904. return true;
  41905. };
  41906. function DeviceParams(params) {
  41907. this.xdpi = params.xdpi;
  41908. this.ydpi = params.ydpi;
  41909. this.bevelMm = params.bevelMm;
  41910. }
  41911. function SensorSample(sample, timestampS) {
  41912. this.set(sample, timestampS);
  41913. }
  41914. SensorSample.prototype.set = function (sample, timestampS) {
  41915. this.sample = sample;
  41916. this.timestampS = timestampS;
  41917. };
  41918. SensorSample.prototype.copy = function (sensorSample) {
  41919. this.set(sensorSample.sample, sensorSample.timestampS);
  41920. };
  41921. function ComplementaryFilter(kFilter, isDebug) {
  41922. this.kFilter = kFilter;
  41923. this.isDebug = isDebug;
  41924. this.currentAccelMeasurement = new SensorSample();
  41925. this.currentGyroMeasurement = new SensorSample();
  41926. this.previousGyroMeasurement = new SensorSample();
  41927. if (isIOS()) {
  41928. this.filterQ = new Quaternion(-1, 0, 0, 1);
  41929. } else {
  41930. this.filterQ = new Quaternion(1, 0, 0, 1);
  41931. }
  41932. this.previousFilterQ = new Quaternion();
  41933. this.previousFilterQ.copy(this.filterQ);
  41934. this.accelQ = new Quaternion();
  41935. this.isOrientationInitialized = false;
  41936. this.estimatedGravity = new Vector3();
  41937. this.measuredGravity = new Vector3();
  41938. this.gyroIntegralQ = new Quaternion();
  41939. }
  41940. ComplementaryFilter.prototype.addAccelMeasurement = function (vector, timestampS) {
  41941. this.currentAccelMeasurement.set(vector, timestampS);
  41942. };
  41943. ComplementaryFilter.prototype.addGyroMeasurement = function (vector, timestampS) {
  41944. this.currentGyroMeasurement.set(vector, timestampS);
  41945. var deltaT = timestampS - this.previousGyroMeasurement.timestampS;
  41946. if (isTimestampDeltaValid(deltaT)) {
  41947. this.run_();
  41948. }
  41949. this.previousGyroMeasurement.copy(this.currentGyroMeasurement);
  41950. };
  41951. ComplementaryFilter.prototype.run_ = function () {
  41952. if (!this.isOrientationInitialized) {
  41953. this.accelQ = this.accelToQuaternion_(this.currentAccelMeasurement.sample);
  41954. this.previousFilterQ.copy(this.accelQ);
  41955. this.isOrientationInitialized = true;
  41956. return;
  41957. }
  41958. var deltaT = this.currentGyroMeasurement.timestampS - this.previousGyroMeasurement.timestampS;
  41959. var gyroDeltaQ = this.gyroToQuaternionDelta_(this.currentGyroMeasurement.sample, deltaT);
  41960. this.gyroIntegralQ.multiply(gyroDeltaQ);
  41961. this.filterQ.copy(this.previousFilterQ);
  41962. this.filterQ.multiply(gyroDeltaQ);
  41963. var invFilterQ = new Quaternion();
  41964. invFilterQ.copy(this.filterQ);
  41965. invFilterQ.inverse();
  41966. this.estimatedGravity.set(0, 0, -1);
  41967. this.estimatedGravity.applyQuaternion(invFilterQ);
  41968. this.estimatedGravity.normalize();
  41969. this.measuredGravity.copy(this.currentAccelMeasurement.sample);
  41970. this.measuredGravity.normalize();
  41971. var deltaQ = new Quaternion();
  41972. deltaQ.setFromUnitVectors(this.estimatedGravity, this.measuredGravity);
  41973. deltaQ.inverse();
  41974. if (this.isDebug) {
  41975. 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));
  41976. }
  41977. var targetQ = new Quaternion();
  41978. targetQ.copy(this.filterQ);
  41979. targetQ.multiply(deltaQ);
  41980. this.filterQ.slerp(targetQ, 1 - this.kFilter);
  41981. this.previousFilterQ.copy(this.filterQ);
  41982. };
  41983. ComplementaryFilter.prototype.getOrientation = function () {
  41984. return this.filterQ;
  41985. };
  41986. ComplementaryFilter.prototype.accelToQuaternion_ = function (accel) {
  41987. var normAccel = new Vector3();
  41988. normAccel.copy(accel);
  41989. normAccel.normalize();
  41990. var quat = new Quaternion();
  41991. quat.setFromUnitVectors(new Vector3(0, 0, -1), normAccel);
  41992. quat.inverse();
  41993. return quat;
  41994. };
  41995. ComplementaryFilter.prototype.gyroToQuaternionDelta_ = function (gyro, dt) {
  41996. var quat = new Quaternion();
  41997. var axis = new Vector3();
  41998. axis.copy(gyro);
  41999. axis.normalize();
  42000. quat.setFromAxisAngle(axis, gyro.length() * dt);
  42001. return quat;
  42002. };
  42003. function PosePredictor(predictionTimeS, isDebug) {
  42004. this.predictionTimeS = predictionTimeS;
  42005. this.isDebug = isDebug;
  42006. this.previousQ = new Quaternion();
  42007. this.previousTimestampS = null;
  42008. this.deltaQ = new Quaternion();
  42009. this.outQ = new Quaternion();
  42010. }
  42011. PosePredictor.prototype.getPrediction = function (currentQ, gyro, timestampS) {
  42012. if (!this.previousTimestampS) {
  42013. this.previousQ.copy(currentQ);
  42014. this.previousTimestampS = timestampS;
  42015. return currentQ;
  42016. }
  42017. var axis = new Vector3();
  42018. axis.copy(gyro);
  42019. axis.normalize();
  42020. var angularSpeed = gyro.length();
  42021. if (angularSpeed < degToRad * 20) {
  42022. if (this.isDebug) {
  42023. console.log('Moving slowly, at %s deg/s: no prediction', (radToDeg * angularSpeed).toFixed(1));
  42024. }
  42025. this.outQ.copy(currentQ);
  42026. this.previousQ.copy(currentQ);
  42027. return this.outQ;
  42028. }
  42029. var predictAngle = angularSpeed * this.predictionTimeS;
  42030. this.deltaQ.setFromAxisAngle(axis, predictAngle);
  42031. this.outQ.copy(this.previousQ);
  42032. this.outQ.multiply(this.deltaQ);
  42033. this.previousQ.copy(currentQ);
  42034. this.previousTimestampS = timestampS;
  42035. return this.outQ;
  42036. };
  42037. function FusionPoseSensor(kFilter, predictionTime, yawOnly, isDebug) {
  42038. this.yawOnly = yawOnly;
  42039. this.accelerometer = new Vector3();
  42040. this.gyroscope = new Vector3();
  42041. this.filter = new ComplementaryFilter(kFilter, isDebug);
  42042. this.posePredictor = new PosePredictor(predictionTime, isDebug);
  42043. this.isFirefoxAndroid = isFirefoxAndroid();
  42044. this.isIOS = isIOS();
  42045. var chromeVersion = getChromeVersion();
  42046. this.isDeviceMotionInRadians = !this.isIOS && chromeVersion && chromeVersion < 66;
  42047. this.isWithoutDeviceMotion = isChromeWithoutDeviceMotion();
  42048. this.filterToWorldQ = new Quaternion();
  42049. if (isIOS()) {
  42050. this.filterToWorldQ.setFromAxisAngle(new Vector3(1, 0, 0), Math.PI / 2);
  42051. } else {
  42052. this.filterToWorldQ.setFromAxisAngle(new Vector3(1, 0, 0), -Math.PI / 2);
  42053. }
  42054. this.inverseWorldToScreenQ = new Quaternion();
  42055. this.worldToScreenQ = new Quaternion();
  42056. this.originalPoseAdjustQ = new Quaternion();
  42057. this.originalPoseAdjustQ.setFromAxisAngle(new Vector3(0, 0, 1), -window.orientation * Math.PI / 180);
  42058. this.setScreenTransform_();
  42059. if (isLandscapeMode()) {
  42060. this.filterToWorldQ.multiply(this.inverseWorldToScreenQ);
  42061. }
  42062. this.resetQ = new Quaternion();
  42063. this.orientationOut_ = new Float32Array(4);
  42064. this.start();
  42065. }
  42066. FusionPoseSensor.prototype.getPosition = function () {
  42067. return null;
  42068. };
  42069. FusionPoseSensor.prototype.getOrientation = function () {
  42070. var orientation = void 0;
  42071. if (this.isWithoutDeviceMotion && this._deviceOrientationQ) {
  42072. this.deviceOrientationFixQ = this.deviceOrientationFixQ || function () {
  42073. var z = new Quaternion().setFromAxisAngle(new Vector3(0, 0, -1), 0);
  42074. var y = new Quaternion();
  42075. if (window.orientation === -90) {
  42076. y.setFromAxisAngle(new Vector3(0, 1, 0), Math.PI / -2);
  42077. } else {
  42078. y.setFromAxisAngle(new Vector3(0, 1, 0), Math.PI / 2);
  42079. }
  42080. return z.multiply(y);
  42081. }();
  42082. this.deviceOrientationFilterToWorldQ = this.deviceOrientationFilterToWorldQ || function () {
  42083. var q = new Quaternion();
  42084. q.setFromAxisAngle(new Vector3(1, 0, 0), -Math.PI / 2);
  42085. return q;
  42086. }();
  42087. orientation = this._deviceOrientationQ;
  42088. var out = new Quaternion();
  42089. out.copy(orientation);
  42090. out.multiply(this.deviceOrientationFilterToWorldQ);
  42091. out.multiply(this.resetQ);
  42092. out.multiply(this.worldToScreenQ);
  42093. out.multiplyQuaternions(this.deviceOrientationFixQ, out);
  42094. if (this.yawOnly) {
  42095. out.x = 0;
  42096. out.z = 0;
  42097. out.normalize();
  42098. }
  42099. this.orientationOut_[0] = out.x;
  42100. this.orientationOut_[1] = out.y;
  42101. this.orientationOut_[2] = out.z;
  42102. this.orientationOut_[3] = out.w;
  42103. return this.orientationOut_;
  42104. } else {
  42105. var filterOrientation = this.filter.getOrientation();
  42106. orientation = this.posePredictor.getPrediction(filterOrientation, this.gyroscope, this.previousTimestampS);
  42107. }
  42108. var out = new Quaternion();
  42109. out.copy(this.filterToWorldQ);
  42110. out.multiply(this.resetQ);
  42111. out.multiply(orientation);
  42112. out.multiply(this.worldToScreenQ);
  42113. if (this.yawOnly) {
  42114. out.x = 0;
  42115. out.z = 0;
  42116. out.normalize();
  42117. }
  42118. this.orientationOut_[0] = out.x;
  42119. this.orientationOut_[1] = out.y;
  42120. this.orientationOut_[2] = out.z;
  42121. this.orientationOut_[3] = out.w;
  42122. return this.orientationOut_;
  42123. };
  42124. FusionPoseSensor.prototype.resetPose = function () {
  42125. this.resetQ.copy(this.filter.getOrientation());
  42126. this.resetQ.x = 0;
  42127. this.resetQ.y = 0;
  42128. this.resetQ.z *= -1;
  42129. this.resetQ.normalize();
  42130. if (isLandscapeMode()) {
  42131. this.resetQ.multiply(this.inverseWorldToScreenQ);
  42132. }
  42133. this.resetQ.multiply(this.originalPoseAdjustQ);
  42134. };
  42135. FusionPoseSensor.prototype.onDeviceOrientation_ = function (e) {
  42136. this._deviceOrientationQ = this._deviceOrientationQ || new Quaternion();
  42137. var alpha = e.alpha,
  42138. beta = e.beta,
  42139. gamma = e.gamma;
  42140. alpha = (alpha || 0) * Math.PI / 180;
  42141. beta = (beta || 0) * Math.PI / 180;
  42142. gamma = (gamma || 0) * Math.PI / 180;
  42143. this._deviceOrientationQ.setFromEulerYXZ(beta, alpha, -gamma);
  42144. };
  42145. FusionPoseSensor.prototype.onDeviceMotion_ = function (deviceMotion) {
  42146. this.updateDeviceMotion_(deviceMotion);
  42147. };
  42148. FusionPoseSensor.prototype.updateDeviceMotion_ = function (deviceMotion) {
  42149. var accGravity = deviceMotion.accelerationIncludingGravity;
  42150. var rotRate = deviceMotion.rotationRate;
  42151. var timestampS = deviceMotion.timeStamp / 1000;
  42152. var deltaS = timestampS - this.previousTimestampS;
  42153. if (deltaS < 0) {
  42154. warnOnce('fusion-pose-sensor:invalid:non-monotonic', 'Invalid timestamps detected: non-monotonic timestamp from devicemotion');
  42155. this.previousTimestampS = timestampS;
  42156. return;
  42157. } else if (deltaS <= MIN_TIMESTEP || deltaS > MAX_TIMESTEP) {
  42158. warnOnce('fusion-pose-sensor:invalid:outside-threshold', 'Invalid timestamps detected: Timestamp from devicemotion outside expected range.');
  42159. this.previousTimestampS = timestampS;
  42160. return;
  42161. }
  42162. this.accelerometer.set(-accGravity.x, -accGravity.y, -accGravity.z);
  42163. if (isR7()) {
  42164. this.gyroscope.set(-rotRate.beta, rotRate.alpha, rotRate.gamma);
  42165. } else {
  42166. this.gyroscope.set(rotRate.alpha, rotRate.beta, rotRate.gamma);
  42167. }
  42168. if (!this.isDeviceMotionInRadians) {
  42169. this.gyroscope.multiplyScalar(Math.PI / 180);
  42170. }
  42171. this.filter.addAccelMeasurement(this.accelerometer, timestampS);
  42172. this.filter.addGyroMeasurement(this.gyroscope, timestampS);
  42173. this.previousTimestampS = timestampS;
  42174. };
  42175. FusionPoseSensor.prototype.onOrientationChange_ = function (screenOrientation) {
  42176. this.setScreenTransform_();
  42177. };
  42178. FusionPoseSensor.prototype.onMessage_ = function (event) {
  42179. var message = event.data;
  42180. if (!message || !message.type) {
  42181. return;
  42182. }
  42183. var type = message.type.toLowerCase();
  42184. if (type !== 'devicemotion') {
  42185. return;
  42186. }
  42187. this.updateDeviceMotion_(message.deviceMotionEvent);
  42188. };
  42189. FusionPoseSensor.prototype.setScreenTransform_ = function () {
  42190. this.worldToScreenQ.set(0, 0, 0, 1);
  42191. switch (window.orientation) {
  42192. case 0:
  42193. break;
  42194. case 90:
  42195. this.worldToScreenQ.setFromAxisAngle(new Vector3(0, 0, 1), -Math.PI / 2);
  42196. break;
  42197. case -90:
  42198. this.worldToScreenQ.setFromAxisAngle(new Vector3(0, 0, 1), Math.PI / 2);
  42199. break;
  42200. case 180:
  42201. break;
  42202. }
  42203. this.inverseWorldToScreenQ.copy(this.worldToScreenQ);
  42204. this.inverseWorldToScreenQ.inverse();
  42205. };
  42206. FusionPoseSensor.prototype.start = function () {
  42207. this.onDeviceMotionCallback_ = this.onDeviceMotion_.bind(this);
  42208. this.onOrientationChangeCallback_ = this.onOrientationChange_.bind(this);
  42209. this.onMessageCallback_ = this.onMessage_.bind(this);
  42210. this.onDeviceOrientationCallback_ = this.onDeviceOrientation_.bind(this);
  42211. if (isIOS() && isInsideCrossOriginIFrame()) {
  42212. window.addEventListener('message', this.onMessageCallback_);
  42213. }
  42214. window.addEventListener('orientationchange', this.onOrientationChangeCallback_);
  42215. if (this.isWithoutDeviceMotion) {
  42216. window.addEventListener('deviceorientation', this.onDeviceOrientationCallback_);
  42217. } else {
  42218. window.addEventListener('devicemotion', this.onDeviceMotionCallback_);
  42219. }
  42220. };
  42221. FusionPoseSensor.prototype.stop = function () {
  42222. window.removeEventListener('devicemotion', this.onDeviceMotionCallback_);
  42223. window.removeEventListener('deviceorientation', this.onDeviceOrientationCallback_);
  42224. window.removeEventListener('orientationchange', this.onOrientationChangeCallback_);
  42225. window.removeEventListener('message', this.onMessageCallback_);
  42226. };
  42227. var SENSOR_FREQUENCY = 60;
  42228. var X_AXIS = new Vector3(1, 0, 0);
  42229. var Z_AXIS = new Vector3(0, 0, 1);
  42230. var SENSOR_TO_VR = new Quaternion();
  42231. SENSOR_TO_VR.setFromAxisAngle(X_AXIS, -Math.PI / 2);
  42232. SENSOR_TO_VR.multiply(new Quaternion().setFromAxisAngle(Z_AXIS, Math.PI / 2));
  42233. var PoseSensor = function () {
  42234. function PoseSensor(config) {
  42235. classCallCheck(this, PoseSensor);
  42236. this.config = config;
  42237. this.sensor = null;
  42238. this.fusionSensor = null;
  42239. this._out = new Float32Array(4);
  42240. this.api = null;
  42241. this.errors = [];
  42242. this._sensorQ = new Quaternion();
  42243. this._outQ = new Quaternion();
  42244. this._onSensorRead = this._onSensorRead.bind(this);
  42245. this._onSensorError = this._onSensorError.bind(this);
  42246. this.init();
  42247. }
  42248. createClass(PoseSensor, [{
  42249. key: 'init',
  42250. value: function init() {
  42251. var sensor = null;
  42252. try {
  42253. sensor = new RelativeOrientationSensor({
  42254. frequency: SENSOR_FREQUENCY,
  42255. referenceFrame: 'screen'
  42256. });
  42257. sensor.addEventListener('error', this._onSensorError);
  42258. } catch (error) {
  42259. this.errors.push(error);
  42260. if (error.name === 'SecurityError') {
  42261. console.error('Cannot construct sensors due to the Feature Policy');
  42262. console.warn('Attempting to fall back using "devicemotion"; however this will ' + 'fail in the future without correct permissions.');
  42263. this.useDeviceMotion();
  42264. } else if (error.name === 'ReferenceError') {
  42265. this.useDeviceMotion();
  42266. } else {
  42267. console.error(error);
  42268. }
  42269. }
  42270. if (sensor) {
  42271. this.api = 'sensor';
  42272. this.sensor = sensor;
  42273. this.sensor.addEventListener('reading', this._onSensorRead);
  42274. this.sensor.start();
  42275. }
  42276. }
  42277. }, {
  42278. key: 'useDeviceMotion',
  42279. value: function useDeviceMotion() {
  42280. this.api = 'devicemotion';
  42281. this.fusionSensor = new FusionPoseSensor(this.config.K_FILTER, this.config.PREDICTION_TIME_S, this.config.YAW_ONLY, this.config.DEBUG);
  42282. if (this.sensor) {
  42283. this.sensor.removeEventListener('reading', this._onSensorRead);
  42284. this.sensor.removeEventListener('error', this._onSensorError);
  42285. this.sensor = null;
  42286. }
  42287. }
  42288. }, {
  42289. key: 'getOrientation',
  42290. value: function getOrientation() {
  42291. if (this.fusionSensor) {
  42292. return this.fusionSensor.getOrientation();
  42293. }
  42294. if (!this.sensor || !this.sensor.quaternion) {
  42295. this._out[0] = this._out[1] = this._out[2] = 0;
  42296. this._out[3] = 1;
  42297. return this._out;
  42298. }
  42299. var q = this.sensor.quaternion;
  42300. this._sensorQ.set(q[0], q[1], q[2], q[3]);
  42301. var out = this._outQ;
  42302. out.copy(SENSOR_TO_VR);
  42303. out.multiply(this._sensorQ);
  42304. if (this.config.YAW_ONLY) {
  42305. out.x = out.z = 0;
  42306. out.normalize();
  42307. }
  42308. this._out[0] = out.x;
  42309. this._out[1] = out.y;
  42310. this._out[2] = out.z;
  42311. this._out[3] = out.w;
  42312. return this._out;
  42313. }
  42314. }, {
  42315. key: '_onSensorError',
  42316. value: function _onSensorError(event) {
  42317. this.errors.push(event.error);
  42318. if (event.error.name === 'NotAllowedError') {
  42319. console.error('Permission to access sensor was denied');
  42320. } else if (event.error.name === 'NotReadableError') {
  42321. console.error('Sensor could not be read');
  42322. } else {
  42323. console.error(event.error);
  42324. }
  42325. this.useDeviceMotion();
  42326. }
  42327. }, {
  42328. key: '_onSensorRead',
  42329. value: function _onSensorRead() {}
  42330. }]);
  42331. return PoseSensor;
  42332. }();
  42333. 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>";
  42334. function RotateInstructions() {
  42335. this.loadIcon_();
  42336. var overlay = document.createElement('div');
  42337. var s = overlay.style;
  42338. s.position = 'fixed';
  42339. s.top = 0;
  42340. s.right = 0;
  42341. s.bottom = 0;
  42342. s.left = 0;
  42343. s.backgroundColor = 'gray';
  42344. s.fontFamily = 'sans-serif';
  42345. s.zIndex = 1000000;
  42346. var img = document.createElement('img');
  42347. img.src = this.icon;
  42348. var s = img.style;
  42349. s.marginLeft = '25%';
  42350. s.marginTop = '25%';
  42351. s.width = '50%';
  42352. overlay.appendChild(img);
  42353. var text = document.createElement('div');
  42354. var s = text.style;
  42355. s.textAlign = 'center';
  42356. s.fontSize = '16px';
  42357. s.lineHeight = '24px';
  42358. s.margin = '24px 25%';
  42359. s.width = '50%';
  42360. text.innerHTML = 'Place your phone into your Cardboard viewer.';
  42361. overlay.appendChild(text);
  42362. var snackbar = document.createElement('div');
  42363. var s = snackbar.style;
  42364. s.backgroundColor = '#CFD8DC';
  42365. s.position = 'fixed';
  42366. s.bottom = 0;
  42367. s.width = '100%';
  42368. s.height = '48px';
  42369. s.padding = '14px 24px';
  42370. s.boxSizing = 'border-box';
  42371. s.color = '#656A6B';
  42372. overlay.appendChild(snackbar);
  42373. var snackbarText = document.createElement('div');
  42374. snackbarText.style.float = 'left';
  42375. snackbarText.innerHTML = 'No Cardboard viewer?';
  42376. var snackbarButton = document.createElement('a');
  42377. snackbarButton.href = 'https://www.google.com/get/cardboard/get-cardboard/';
  42378. snackbarButton.innerHTML = 'get one';
  42379. snackbarButton.target = '_blank';
  42380. var s = snackbarButton.style;
  42381. s.float = 'right';
  42382. s.fontWeight = 600;
  42383. s.textTransform = 'uppercase';
  42384. s.borderLeft = '1px solid gray';
  42385. s.paddingLeft = '24px';
  42386. s.textDecoration = 'none';
  42387. s.color = '#656A6B';
  42388. snackbar.appendChild(snackbarText);
  42389. snackbar.appendChild(snackbarButton);
  42390. this.overlay = overlay;
  42391. this.text = text;
  42392. this.hide();
  42393. }
  42394. RotateInstructions.prototype.show = function (parent) {
  42395. if (!parent && !this.overlay.parentElement) {
  42396. document.body.appendChild(this.overlay);
  42397. } else if (parent) {
  42398. if (this.overlay.parentElement && this.overlay.parentElement != parent) this.overlay.parentElement.removeChild(this.overlay);
  42399. parent.appendChild(this.overlay);
  42400. }
  42401. this.overlay.style.display = 'block';
  42402. var img = this.overlay.querySelector('img');
  42403. var s = img.style;
  42404. if (isLandscapeMode()) {
  42405. s.width = '20%';
  42406. s.marginLeft = '40%';
  42407. s.marginTop = '3%';
  42408. } else {
  42409. s.width = '50%';
  42410. s.marginLeft = '25%';
  42411. s.marginTop = '25%';
  42412. }
  42413. };
  42414. RotateInstructions.prototype.hide = function () {
  42415. this.overlay.style.display = 'none';
  42416. };
  42417. RotateInstructions.prototype.showTemporarily = function (ms, parent) {
  42418. this.show(parent);
  42419. this.timer = setTimeout(this.hide.bind(this), ms);
  42420. };
  42421. RotateInstructions.prototype.disableShowTemporarily = function () {
  42422. clearTimeout(this.timer);
  42423. };
  42424. RotateInstructions.prototype.update = function () {
  42425. this.disableShowTemporarily();
  42426. if (!isLandscapeMode() && isMobile()) {
  42427. this.show();
  42428. } else {
  42429. this.hide();
  42430. }
  42431. };
  42432. RotateInstructions.prototype.loadIcon_ = function () {
  42433. this.icon = dataUri('image/svg+xml', rotateInstructionsAsset);
  42434. };
  42435. var DEFAULT_VIEWER = 'CardboardV1';
  42436. var VIEWER_KEY = 'WEBVR_CARDBOARD_VIEWER';
  42437. var CLASS_NAME = 'webvr-polyfill-viewer-selector';
  42438. function ViewerSelector(defaultViewer) {
  42439. try {
  42440. this.selectedKey = localStorage.getItem(VIEWER_KEY);
  42441. } catch (error) {
  42442. console.error('Failed to load viewer profile: %s', error);
  42443. }
  42444. if (!this.selectedKey) {
  42445. this.selectedKey = defaultViewer || DEFAULT_VIEWER;
  42446. }
  42447. this.dialog = this.createDialog_(DeviceInfo.Viewers);
  42448. this.root = null;
  42449. this.onChangeCallbacks_ = [];
  42450. }
  42451. ViewerSelector.prototype.show = function (root) {
  42452. this.root = root;
  42453. root.appendChild(this.dialog);
  42454. var selected = this.dialog.querySelector('#' + this.selectedKey);
  42455. selected.checked = true;
  42456. this.dialog.style.display = 'block';
  42457. };
  42458. ViewerSelector.prototype.hide = function () {
  42459. if (this.root && this.root.contains(this.dialog)) {
  42460. this.root.removeChild(this.dialog);
  42461. }
  42462. this.dialog.style.display = 'none';
  42463. };
  42464. ViewerSelector.prototype.getCurrentViewer = function () {
  42465. return DeviceInfo.Viewers[this.selectedKey];
  42466. };
  42467. ViewerSelector.prototype.getSelectedKey_ = function () {
  42468. var input = this.dialog.querySelector('input[name=field]:checked');
  42469. if (input) {
  42470. return input.id;
  42471. }
  42472. return null;
  42473. };
  42474. ViewerSelector.prototype.onChange = function (cb) {
  42475. this.onChangeCallbacks_.push(cb);
  42476. };
  42477. ViewerSelector.prototype.fireOnChange_ = function (viewer) {
  42478. for (var i = 0; i < this.onChangeCallbacks_.length; i++) {
  42479. this.onChangeCallbacks_[i](viewer);
  42480. }
  42481. };
  42482. ViewerSelector.prototype.onSave_ = function () {
  42483. this.selectedKey = this.getSelectedKey_();
  42484. if (!this.selectedKey || !DeviceInfo.Viewers[this.selectedKey]) {
  42485. console.error('ViewerSelector.onSave_: this should never happen!');
  42486. return;
  42487. }
  42488. this.fireOnChange_(DeviceInfo.Viewers[this.selectedKey]);
  42489. try {
  42490. localStorage.setItem(VIEWER_KEY, this.selectedKey);
  42491. } catch (error) {
  42492. console.error('Failed to save viewer profile: %s', error);
  42493. }
  42494. this.hide();
  42495. };
  42496. ViewerSelector.prototype.createDialog_ = function (options) {
  42497. var container = document.createElement('div');
  42498. container.classList.add(CLASS_NAME);
  42499. container.style.display = 'none';
  42500. var overlay = document.createElement('div');
  42501. var s = overlay.style;
  42502. s.position = 'fixed';
  42503. s.left = 0;
  42504. s.top = 0;
  42505. s.width = '100%';
  42506. s.height = '100%';
  42507. s.background = 'rgba(0, 0, 0, 0.3)';
  42508. overlay.addEventListener('click', this.hide.bind(this));
  42509. var width = 280;
  42510. var dialog = document.createElement('div');
  42511. var s = dialog.style;
  42512. s.boxSizing = 'border-box';
  42513. s.position = 'fixed';
  42514. s.top = '24px';
  42515. s.left = '50%';
  42516. s.marginLeft = -width / 2 + 'px';
  42517. s.width = width + 'px';
  42518. s.padding = '24px';
  42519. s.overflow = 'hidden';
  42520. s.background = '#fafafa';
  42521. s.fontFamily = "'Roboto', sans-serif";
  42522. s.boxShadow = '0px 5px 20px #666';
  42523. dialog.appendChild(this.createH1_('Select your viewer'));
  42524. for (var id in options) {
  42525. dialog.appendChild(this.createChoice_(id, options[id].label));
  42526. }
  42527. dialog.appendChild(this.createButton_('Save', this.onSave_.bind(this)));
  42528. container.appendChild(overlay);
  42529. container.appendChild(dialog);
  42530. return container;
  42531. };
  42532. ViewerSelector.prototype.createH1_ = function (name) {
  42533. var h1 = document.createElement('h1');
  42534. var s = h1.style;
  42535. s.color = 'black';
  42536. s.fontSize = '20px';
  42537. s.fontWeight = 'bold';
  42538. s.marginTop = 0;
  42539. s.marginBottom = '24px';
  42540. h1.innerHTML = name;
  42541. return h1;
  42542. };
  42543. ViewerSelector.prototype.createChoice_ = function (id, name) {
  42544. var div = document.createElement('div');
  42545. div.style.marginTop = '8px';
  42546. div.style.color = 'black';
  42547. var input = document.createElement('input');
  42548. input.style.fontSize = '30px';
  42549. input.setAttribute('id', id);
  42550. input.setAttribute('type', 'radio');
  42551. input.setAttribute('value', id);
  42552. input.setAttribute('name', 'field');
  42553. var label = document.createElement('label');
  42554. label.style.marginLeft = '4px';
  42555. label.setAttribute('for', id);
  42556. label.innerHTML = name;
  42557. div.appendChild(input);
  42558. div.appendChild(label);
  42559. return div;
  42560. };
  42561. ViewerSelector.prototype.createButton_ = function (label, onclick) {
  42562. var button = document.createElement('button');
  42563. button.innerHTML = label;
  42564. var s = button.style;
  42565. s.float = 'right';
  42566. s.textTransform = 'uppercase';
  42567. s.color = '#1094f7';
  42568. s.fontSize = '14px';
  42569. s.letterSpacing = 0;
  42570. s.border = 0;
  42571. s.background = 'none';
  42572. s.marginTop = '16px';
  42573. button.addEventListener('click', onclick);
  42574. return button;
  42575. };
  42576. var commonjsGlobal$$1 = typeof window !== 'undefined' ? window : typeof commonjsGlobal !== 'undefined' ? commonjsGlobal : typeof self !== 'undefined' ? self : {};
  42577. function unwrapExports$$1 (x) {
  42578. return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
  42579. }
  42580. function createCommonjsModule$$1(fn, module) {
  42581. return module = { exports: {} }, fn(module, module.exports), module.exports;
  42582. }
  42583. var NoSleep = createCommonjsModule$$1(function (module, exports) {
  42584. (function webpackUniversalModuleDefinition(root, factory) {
  42585. module.exports = factory();
  42586. })(commonjsGlobal$$1, function() {
  42587. return (function(modules) {
  42588. var installedModules = {};
  42589. function __webpack_require__(moduleId) {
  42590. if(installedModules[moduleId]) {
  42591. return installedModules[moduleId].exports;
  42592. }
  42593. var module = installedModules[moduleId] = {
  42594. i: moduleId,
  42595. l: false,
  42596. exports: {}
  42597. };
  42598. modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
  42599. module.l = true;
  42600. return module.exports;
  42601. }
  42602. __webpack_require__.m = modules;
  42603. __webpack_require__.c = installedModules;
  42604. __webpack_require__.d = function(exports, name, getter) {
  42605. if(!__webpack_require__.o(exports, name)) {
  42606. Object.defineProperty(exports, name, {
  42607. configurable: false,
  42608. enumerable: true,
  42609. get: getter
  42610. });
  42611. }
  42612. };
  42613. __webpack_require__.n = function(module) {
  42614. var getter = module && module.__esModule ?
  42615. function getDefault() { return module['default']; } :
  42616. function getModuleExports() { return module; };
  42617. __webpack_require__.d(getter, 'a', getter);
  42618. return getter;
  42619. };
  42620. __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
  42621. __webpack_require__.p = "";
  42622. return __webpack_require__(__webpack_require__.s = 0);
  42623. })
  42624. ([
  42625. (function(module, exports, __webpack_require__) {
  42626. 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; }; }();
  42627. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  42628. var mediaFile = __webpack_require__(1);
  42629. 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;
  42630. var NoSleep = function () {
  42631. function NoSleep() {
  42632. _classCallCheck(this, NoSleep);
  42633. if (oldIOS) {
  42634. this.noSleepTimer = null;
  42635. } else {
  42636. this.noSleepVideo = document.createElement('video');
  42637. this.noSleepVideo.setAttribute('playsinline', '');
  42638. this.noSleepVideo.setAttribute('src', mediaFile);
  42639. this.noSleepVideo.addEventListener('timeupdate', function (e) {
  42640. if (this.noSleepVideo.currentTime > 0.5) {
  42641. this.noSleepVideo.currentTime = Math.random();
  42642. }
  42643. }.bind(this));
  42644. }
  42645. }
  42646. _createClass(NoSleep, [{
  42647. key: 'enable',
  42648. value: function enable() {
  42649. if (oldIOS) {
  42650. this.disable();
  42651. this.noSleepTimer = window.setInterval(function () {
  42652. window.location.href = '/';
  42653. window.setTimeout(window.stop, 0);
  42654. }, 15000);
  42655. } else {
  42656. this.noSleepVideo.play();
  42657. }
  42658. }
  42659. }, {
  42660. key: 'disable',
  42661. value: function disable() {
  42662. if (oldIOS) {
  42663. if (this.noSleepTimer) {
  42664. window.clearInterval(this.noSleepTimer);
  42665. this.noSleepTimer = null;
  42666. }
  42667. } else {
  42668. this.noSleepVideo.pause();
  42669. }
  42670. }
  42671. }]);
  42672. return NoSleep;
  42673. }();
  42674. module.exports = NoSleep;
  42675. }),
  42676. (function(module, exports, __webpack_require__) {
  42677. 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=';
  42678. })
  42679. ]);
  42680. });
  42681. });
  42682. var NoSleep$1 = unwrapExports$$1(NoSleep);
  42683. var nextDisplayId = 1000;
  42684. var defaultLeftBounds = [0, 0, 0.5, 1];
  42685. var defaultRightBounds = [0.5, 0, 0.5, 1];
  42686. var raf = window.requestAnimationFrame;
  42687. var caf = window.cancelAnimationFrame;
  42688. function VRFrameData() {
  42689. this.leftProjectionMatrix = new Float32Array(16);
  42690. this.leftViewMatrix = new Float32Array(16);
  42691. this.rightProjectionMatrix = new Float32Array(16);
  42692. this.rightViewMatrix = new Float32Array(16);
  42693. this.pose = null;
  42694. }
  42695. function VRDisplayCapabilities(config) {
  42696. Object.defineProperties(this, {
  42697. hasPosition: {
  42698. writable: false, enumerable: true, value: config.hasPosition
  42699. },
  42700. hasExternalDisplay: {
  42701. writable: false, enumerable: true, value: config.hasExternalDisplay
  42702. },
  42703. canPresent: {
  42704. writable: false, enumerable: true, value: config.canPresent
  42705. },
  42706. maxLayers: {
  42707. writable: false, enumerable: true, value: config.maxLayers
  42708. },
  42709. hasOrientation: {
  42710. enumerable: true, get: function get() {
  42711. deprecateWarning('VRDisplayCapabilities.prototype.hasOrientation', 'VRDisplay.prototype.getFrameData');
  42712. return config.hasOrientation;
  42713. }
  42714. }
  42715. });
  42716. }
  42717. function VRDisplay(config) {
  42718. config = config || {};
  42719. var USE_WAKELOCK = 'wakelock' in config ? config.wakelock : true;
  42720. this.isPolyfilled = true;
  42721. this.displayId = nextDisplayId++;
  42722. this.displayName = '';
  42723. this.depthNear = 0.01;
  42724. this.depthFar = 10000.0;
  42725. this.isPresenting = false;
  42726. Object.defineProperty(this, 'isConnected', {
  42727. get: function get() {
  42728. deprecateWarning('VRDisplay.prototype.isConnected', 'VRDisplayCapabilities.prototype.hasExternalDisplay');
  42729. return false;
  42730. }
  42731. });
  42732. this.capabilities = new VRDisplayCapabilities({
  42733. hasPosition: false,
  42734. hasOrientation: false,
  42735. hasExternalDisplay: false,
  42736. canPresent: false,
  42737. maxLayers: 1
  42738. });
  42739. this.stageParameters = null;
  42740. this.waitingForPresent_ = false;
  42741. this.layer_ = null;
  42742. this.originalParent_ = null;
  42743. this.fullscreenElement_ = null;
  42744. this.fullscreenWrapper_ = null;
  42745. this.fullscreenElementCachedStyle_ = null;
  42746. this.fullscreenEventTarget_ = null;
  42747. this.fullscreenChangeHandler_ = null;
  42748. this.fullscreenErrorHandler_ = null;
  42749. if (USE_WAKELOCK && isMobile()) {
  42750. this.wakelock_ = new NoSleep$1();
  42751. }
  42752. }
  42753. VRDisplay.prototype.getFrameData = function (frameData) {
  42754. return frameDataFromPose(frameData, this._getPose(), this);
  42755. };
  42756. VRDisplay.prototype.getPose = function () {
  42757. deprecateWarning('VRDisplay.prototype.getPose', 'VRDisplay.prototype.getFrameData');
  42758. return this._getPose();
  42759. };
  42760. VRDisplay.prototype.resetPose = function () {
  42761. deprecateWarning('VRDisplay.prototype.resetPose');
  42762. return this._resetPose();
  42763. };
  42764. VRDisplay.prototype.getImmediatePose = function () {
  42765. deprecateWarning('VRDisplay.prototype.getImmediatePose', 'VRDisplay.prototype.getFrameData');
  42766. return this._getPose();
  42767. };
  42768. VRDisplay.prototype.requestAnimationFrame = function (callback) {
  42769. return raf(callback);
  42770. };
  42771. VRDisplay.prototype.cancelAnimationFrame = function (id) {
  42772. return caf(id);
  42773. };
  42774. VRDisplay.prototype.wrapForFullscreen = function (element) {
  42775. if (isIOS()) {
  42776. return element;
  42777. }
  42778. if (!this.fullscreenWrapper_) {
  42779. this.fullscreenWrapper_ = document.createElement('div');
  42780. 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'];
  42781. this.fullscreenWrapper_.setAttribute('style', cssProperties.join('; ') + ';');
  42782. this.fullscreenWrapper_.classList.add('webvr-polyfill-fullscreen-wrapper');
  42783. }
  42784. if (this.fullscreenElement_ == element) {
  42785. return this.fullscreenWrapper_;
  42786. }
  42787. if (this.fullscreenElement_) {
  42788. if (this.originalParent_) {
  42789. this.originalParent_.appendChild(this.fullscreenElement_);
  42790. } else {
  42791. this.fullscreenElement_.parentElement.removeChild(this.fullscreenElement_);
  42792. }
  42793. }
  42794. this.fullscreenElement_ = element;
  42795. this.originalParent_ = element.parentElement;
  42796. if (!this.originalParent_) {
  42797. document.body.appendChild(element);
  42798. }
  42799. if (!this.fullscreenWrapper_.parentElement) {
  42800. var parent = this.fullscreenElement_.parentElement;
  42801. parent.insertBefore(this.fullscreenWrapper_, this.fullscreenElement_);
  42802. parent.removeChild(this.fullscreenElement_);
  42803. }
  42804. this.fullscreenWrapper_.insertBefore(this.fullscreenElement_, this.fullscreenWrapper_.firstChild);
  42805. this.fullscreenElementCachedStyle_ = this.fullscreenElement_.getAttribute('style');
  42806. var self = this;
  42807. function applyFullscreenElementStyle() {
  42808. if (!self.fullscreenElement_) {
  42809. return;
  42810. }
  42811. 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'];
  42812. self.fullscreenElement_.setAttribute('style', cssProperties.join('; ') + ';');
  42813. }
  42814. applyFullscreenElementStyle();
  42815. return this.fullscreenWrapper_;
  42816. };
  42817. VRDisplay.prototype.removeFullscreenWrapper = function () {
  42818. if (!this.fullscreenElement_) {
  42819. return;
  42820. }
  42821. var element = this.fullscreenElement_;
  42822. if (this.fullscreenElementCachedStyle_) {
  42823. element.setAttribute('style', this.fullscreenElementCachedStyle_);
  42824. } else {
  42825. element.removeAttribute('style');
  42826. }
  42827. this.fullscreenElement_ = null;
  42828. this.fullscreenElementCachedStyle_ = null;
  42829. var parent = this.fullscreenWrapper_.parentElement;
  42830. this.fullscreenWrapper_.removeChild(element);
  42831. if (this.originalParent_ === parent) {
  42832. parent.insertBefore(element, this.fullscreenWrapper_);
  42833. }
  42834. else if (this.originalParent_) {
  42835. this.originalParent_.appendChild(element);
  42836. }
  42837. parent.removeChild(this.fullscreenWrapper_);
  42838. return element;
  42839. };
  42840. VRDisplay.prototype.requestPresent = function (layers) {
  42841. var wasPresenting = this.isPresenting;
  42842. var self = this;
  42843. if (!(layers instanceof Array)) {
  42844. deprecateWarning('VRDisplay.prototype.requestPresent with non-array argument', 'an array of VRLayers as the first argument');
  42845. layers = [layers];
  42846. }
  42847. return new Promise(function (resolve, reject) {
  42848. if (!self.capabilities.canPresent) {
  42849. reject(new Error('VRDisplay is not capable of presenting.'));
  42850. return;
  42851. }
  42852. if (layers.length == 0 || layers.length > self.capabilities.maxLayers) {
  42853. reject(new Error('Invalid number of layers.'));
  42854. return;
  42855. }
  42856. var incomingLayer = layers[0];
  42857. if (!incomingLayer.source) {
  42858. resolve();
  42859. return;
  42860. }
  42861. var leftBounds = incomingLayer.leftBounds || defaultLeftBounds;
  42862. var rightBounds = incomingLayer.rightBounds || defaultRightBounds;
  42863. if (wasPresenting) {
  42864. var layer = self.layer_;
  42865. if (layer.source !== incomingLayer.source) {
  42866. layer.source = incomingLayer.source;
  42867. }
  42868. for (var i = 0; i < 4; i++) {
  42869. layer.leftBounds[i] = leftBounds[i];
  42870. layer.rightBounds[i] = rightBounds[i];
  42871. }
  42872. self.wrapForFullscreen(self.layer_.source);
  42873. self.updatePresent_();
  42874. resolve();
  42875. return;
  42876. }
  42877. self.layer_ = {
  42878. predistorted: incomingLayer.predistorted,
  42879. source: incomingLayer.source,
  42880. leftBounds: leftBounds.slice(0),
  42881. rightBounds: rightBounds.slice(0)
  42882. };
  42883. self.waitingForPresent_ = false;
  42884. if (self.layer_ && self.layer_.source) {
  42885. var fullscreenElement = self.wrapForFullscreen(self.layer_.source);
  42886. var onFullscreenChange = function onFullscreenChange() {
  42887. var actualFullscreenElement = getFullscreenElement();
  42888. self.isPresenting = fullscreenElement === actualFullscreenElement;
  42889. if (self.isPresenting) {
  42890. if (screen.orientation && screen.orientation.lock) {
  42891. screen.orientation.lock('landscape-primary').catch(function (error) {
  42892. console.error('screen.orientation.lock() failed due to', error.message);
  42893. });
  42894. }
  42895. self.waitingForPresent_ = false;
  42896. self.beginPresent_();
  42897. resolve();
  42898. } else {
  42899. if (screen.orientation && screen.orientation.unlock) {
  42900. screen.orientation.unlock();
  42901. }
  42902. self.removeFullscreenWrapper();
  42903. self.disableWakeLock();
  42904. self.endPresent_();
  42905. self.removeFullscreenListeners_();
  42906. }
  42907. self.fireVRDisplayPresentChange_();
  42908. };
  42909. var onFullscreenError = function onFullscreenError() {
  42910. if (!self.waitingForPresent_) {
  42911. return;
  42912. }
  42913. self.removeFullscreenWrapper();
  42914. self.removeFullscreenListeners_();
  42915. self.disableWakeLock();
  42916. self.waitingForPresent_ = false;
  42917. self.isPresenting = false;
  42918. reject(new Error('Unable to present.'));
  42919. };
  42920. self.addFullscreenListeners_(fullscreenElement, onFullscreenChange, onFullscreenError);
  42921. if (requestFullscreen(fullscreenElement)) {
  42922. self.enableWakeLock();
  42923. self.waitingForPresent_ = true;
  42924. } else if (isIOS() || isWebViewAndroid()) {
  42925. self.enableWakeLock();
  42926. self.isPresenting = true;
  42927. self.beginPresent_();
  42928. self.fireVRDisplayPresentChange_();
  42929. resolve();
  42930. }
  42931. }
  42932. if (!self.waitingForPresent_ && !isIOS()) {
  42933. exitFullscreen();
  42934. reject(new Error('Unable to present.'));
  42935. }
  42936. });
  42937. };
  42938. VRDisplay.prototype.exitPresent = function () {
  42939. var wasPresenting = this.isPresenting;
  42940. var self = this;
  42941. this.isPresenting = false;
  42942. this.layer_ = null;
  42943. this.disableWakeLock();
  42944. return new Promise(function (resolve, reject) {
  42945. if (wasPresenting) {
  42946. if (!exitFullscreen() && isIOS()) {
  42947. self.endPresent_();
  42948. self.fireVRDisplayPresentChange_();
  42949. }
  42950. if (isWebViewAndroid()) {
  42951. self.removeFullscreenWrapper();
  42952. self.removeFullscreenListeners_();
  42953. self.endPresent_();
  42954. self.fireVRDisplayPresentChange_();
  42955. }
  42956. resolve();
  42957. } else {
  42958. reject(new Error('Was not presenting to VRDisplay.'));
  42959. }
  42960. });
  42961. };
  42962. VRDisplay.prototype.getLayers = function () {
  42963. if (this.layer_) {
  42964. return [this.layer_];
  42965. }
  42966. return [];
  42967. };
  42968. VRDisplay.prototype.fireVRDisplayPresentChange_ = function () {
  42969. var event = new CustomEvent('vrdisplaypresentchange', { detail: { display: this } });
  42970. window.dispatchEvent(event);
  42971. };
  42972. VRDisplay.prototype.fireVRDisplayConnect_ = function () {
  42973. var event = new CustomEvent('vrdisplayconnect', { detail: { display: this } });
  42974. window.dispatchEvent(event);
  42975. };
  42976. VRDisplay.prototype.addFullscreenListeners_ = function (element, changeHandler, errorHandler) {
  42977. this.removeFullscreenListeners_();
  42978. this.fullscreenEventTarget_ = element;
  42979. this.fullscreenChangeHandler_ = changeHandler;
  42980. this.fullscreenErrorHandler_ = errorHandler;
  42981. if (changeHandler) {
  42982. if (document.fullscreenEnabled) {
  42983. element.addEventListener('fullscreenchange', changeHandler, false);
  42984. } else if (document.webkitFullscreenEnabled) {
  42985. element.addEventListener('webkitfullscreenchange', changeHandler, false);
  42986. } else if (document.mozFullScreenEnabled) {
  42987. document.addEventListener('mozfullscreenchange', changeHandler, false);
  42988. } else if (document.msFullscreenEnabled) {
  42989. element.addEventListener('msfullscreenchange', changeHandler, false);
  42990. }
  42991. }
  42992. if (errorHandler) {
  42993. if (document.fullscreenEnabled) {
  42994. element.addEventListener('fullscreenerror', errorHandler, false);
  42995. } else if (document.webkitFullscreenEnabled) {
  42996. element.addEventListener('webkitfullscreenerror', errorHandler, false);
  42997. } else if (document.mozFullScreenEnabled) {
  42998. document.addEventListener('mozfullscreenerror', errorHandler, false);
  42999. } else if (document.msFullscreenEnabled) {
  43000. element.addEventListener('msfullscreenerror', errorHandler, false);
  43001. }
  43002. }
  43003. };
  43004. VRDisplay.prototype.removeFullscreenListeners_ = function () {
  43005. if (!this.fullscreenEventTarget_) return;
  43006. var element = this.fullscreenEventTarget_;
  43007. if (this.fullscreenChangeHandler_) {
  43008. var changeHandler = this.fullscreenChangeHandler_;
  43009. element.removeEventListener('fullscreenchange', changeHandler, false);
  43010. element.removeEventListener('webkitfullscreenchange', changeHandler, false);
  43011. document.removeEventListener('mozfullscreenchange', changeHandler, false);
  43012. element.removeEventListener('msfullscreenchange', changeHandler, false);
  43013. }
  43014. if (this.fullscreenErrorHandler_) {
  43015. var errorHandler = this.fullscreenErrorHandler_;
  43016. element.removeEventListener('fullscreenerror', errorHandler, false);
  43017. element.removeEventListener('webkitfullscreenerror', errorHandler, false);
  43018. document.removeEventListener('mozfullscreenerror', errorHandler, false);
  43019. element.removeEventListener('msfullscreenerror', errorHandler, false);
  43020. }
  43021. this.fullscreenEventTarget_ = null;
  43022. this.fullscreenChangeHandler_ = null;
  43023. this.fullscreenErrorHandler_ = null;
  43024. };
  43025. VRDisplay.prototype.enableWakeLock = function () {
  43026. if (this.wakelock_) {
  43027. this.wakelock_.enable();
  43028. }
  43029. };
  43030. VRDisplay.prototype.disableWakeLock = function () {
  43031. if (this.wakelock_) {
  43032. this.wakelock_.disable();
  43033. }
  43034. };
  43035. VRDisplay.prototype.beginPresent_ = function () {
  43036. };
  43037. VRDisplay.prototype.endPresent_ = function () {
  43038. };
  43039. VRDisplay.prototype.submitFrame = function (pose) {
  43040. };
  43041. VRDisplay.prototype.getEyeParameters = function (whichEye) {
  43042. return null;
  43043. };
  43044. var config = {
  43045. ADDITIONAL_VIEWERS: [],
  43046. DEFAULT_VIEWER: '',
  43047. MOBILE_WAKE_LOCK: true,
  43048. DEBUG: false,
  43049. DPDB_URL: 'https://dpdb.webvr.rocks/dpdb.json',
  43050. K_FILTER: 0.98,
  43051. PREDICTION_TIME_S: 0.040,
  43052. CARDBOARD_UI_DISABLED: false,
  43053. ROTATE_INSTRUCTIONS_DISABLED: false,
  43054. YAW_ONLY: false,
  43055. BUFFER_SCALE: 0.5,
  43056. DIRTY_SUBMIT_FRAME_BINDINGS: false
  43057. };
  43058. var Eye = {
  43059. LEFT: 'left',
  43060. RIGHT: 'right'
  43061. };
  43062. function CardboardVRDisplay(config$$1) {
  43063. var defaults = extend({}, config);
  43064. config$$1 = extend(defaults, config$$1 || {});
  43065. VRDisplay.call(this, {
  43066. wakelock: config$$1.MOBILE_WAKE_LOCK
  43067. });
  43068. this.config = config$$1;
  43069. this.displayName = 'Cardboard VRDisplay';
  43070. this.capabilities = new VRDisplayCapabilities({
  43071. hasPosition: false,
  43072. hasOrientation: true,
  43073. hasExternalDisplay: false,
  43074. canPresent: true,
  43075. maxLayers: 1
  43076. });
  43077. this.stageParameters = null;
  43078. this.bufferScale_ = this.config.BUFFER_SCALE;
  43079. this.poseSensor_ = new PoseSensor(this.config);
  43080. this.distorter_ = null;
  43081. this.cardboardUI_ = null;
  43082. this.dpdb_ = new Dpdb(this.config.DPDB_URL, this.onDeviceParamsUpdated_.bind(this));
  43083. this.deviceInfo_ = new DeviceInfo(this.dpdb_.getDeviceParams(), config$$1.ADDITIONAL_VIEWERS);
  43084. this.viewerSelector_ = new ViewerSelector(config$$1.DEFAULT_VIEWER);
  43085. this.viewerSelector_.onChange(this.onViewerChanged_.bind(this));
  43086. this.deviceInfo_.setViewer(this.viewerSelector_.getCurrentViewer());
  43087. if (!this.config.ROTATE_INSTRUCTIONS_DISABLED) {
  43088. this.rotateInstructions_ = new RotateInstructions();
  43089. }
  43090. if (isIOS()) {
  43091. window.addEventListener('resize', this.onResize_.bind(this));
  43092. }
  43093. }
  43094. CardboardVRDisplay.prototype = Object.create(VRDisplay.prototype);
  43095. CardboardVRDisplay.prototype._getPose = function () {
  43096. return {
  43097. position: null,
  43098. orientation: this.poseSensor_.getOrientation(),
  43099. linearVelocity: null,
  43100. linearAcceleration: null,
  43101. angularVelocity: null,
  43102. angularAcceleration: null
  43103. };
  43104. };
  43105. CardboardVRDisplay.prototype._resetPose = function () {
  43106. if (this.poseSensor_.resetPose) {
  43107. this.poseSensor_.resetPose();
  43108. }
  43109. };
  43110. CardboardVRDisplay.prototype._getFieldOfView = function (whichEye) {
  43111. var fieldOfView;
  43112. if (whichEye == Eye.LEFT) {
  43113. fieldOfView = this.deviceInfo_.getFieldOfViewLeftEye();
  43114. } else if (whichEye == Eye.RIGHT) {
  43115. fieldOfView = this.deviceInfo_.getFieldOfViewRightEye();
  43116. } else {
  43117. console.error('Invalid eye provided: %s', whichEye);
  43118. return null;
  43119. }
  43120. return fieldOfView;
  43121. };
  43122. CardboardVRDisplay.prototype._getEyeOffset = function (whichEye) {
  43123. var offset;
  43124. if (whichEye == Eye.LEFT) {
  43125. offset = [-this.deviceInfo_.viewer.interLensDistance * 0.5, 0.0, 0.0];
  43126. } else if (whichEye == Eye.RIGHT) {
  43127. offset = [this.deviceInfo_.viewer.interLensDistance * 0.5, 0.0, 0.0];
  43128. } else {
  43129. console.error('Invalid eye provided: %s', whichEye);
  43130. return null;
  43131. }
  43132. return offset;
  43133. };
  43134. CardboardVRDisplay.prototype.getEyeParameters = function (whichEye) {
  43135. var offset = this._getEyeOffset(whichEye);
  43136. var fieldOfView = this._getFieldOfView(whichEye);
  43137. var eyeParams = {
  43138. offset: offset,
  43139. renderWidth: this.deviceInfo_.device.width * 0.5 * this.bufferScale_,
  43140. renderHeight: this.deviceInfo_.device.height * this.bufferScale_
  43141. };
  43142. Object.defineProperty(eyeParams, 'fieldOfView', {
  43143. enumerable: true,
  43144. get: function get() {
  43145. deprecateWarning('VRFieldOfView', 'VRFrameData\'s projection matrices');
  43146. return fieldOfView;
  43147. }
  43148. });
  43149. return eyeParams;
  43150. };
  43151. CardboardVRDisplay.prototype.onDeviceParamsUpdated_ = function (newParams) {
  43152. if (this.config.DEBUG) {
  43153. console.log('DPDB reported that device params were updated.');
  43154. }
  43155. this.deviceInfo_.updateDeviceParams(newParams);
  43156. if (this.distorter_) {
  43157. this.distorter_.updateDeviceInfo(this.deviceInfo_);
  43158. }
  43159. };
  43160. CardboardVRDisplay.prototype.updateBounds_ = function () {
  43161. if (this.layer_ && this.distorter_ && (this.layer_.leftBounds || this.layer_.rightBounds)) {
  43162. this.distorter_.setTextureBounds(this.layer_.leftBounds, this.layer_.rightBounds);
  43163. }
  43164. };
  43165. CardboardVRDisplay.prototype.beginPresent_ = function () {
  43166. var gl = this.layer_.source.getContext('webgl');
  43167. if (!gl) gl = this.layer_.source.getContext('experimental-webgl');
  43168. if (!gl) gl = this.layer_.source.getContext('webgl2');
  43169. if (!gl) return;
  43170. if (this.layer_.predistorted) {
  43171. if (!this.config.CARDBOARD_UI_DISABLED) {
  43172. gl.canvas.width = getScreenWidth() * this.bufferScale_;
  43173. gl.canvas.height = getScreenHeight() * this.bufferScale_;
  43174. this.cardboardUI_ = new CardboardUI(gl);
  43175. }
  43176. } else {
  43177. if (!this.config.CARDBOARD_UI_DISABLED) {
  43178. this.cardboardUI_ = new CardboardUI(gl);
  43179. }
  43180. this.distorter_ = new CardboardDistorter(gl, this.cardboardUI_, this.config.BUFFER_SCALE, this.config.DIRTY_SUBMIT_FRAME_BINDINGS);
  43181. this.distorter_.updateDeviceInfo(this.deviceInfo_);
  43182. }
  43183. if (this.cardboardUI_) {
  43184. this.cardboardUI_.listen(function (e) {
  43185. this.viewerSelector_.show(this.layer_.source.parentElement);
  43186. e.stopPropagation();
  43187. e.preventDefault();
  43188. }.bind(this), function (e) {
  43189. this.exitPresent();
  43190. e.stopPropagation();
  43191. e.preventDefault();
  43192. }.bind(this));
  43193. }
  43194. if (this.rotateInstructions_) {
  43195. if (isLandscapeMode() && isMobile()) {
  43196. this.rotateInstructions_.showTemporarily(3000, this.layer_.source.parentElement);
  43197. } else {
  43198. this.rotateInstructions_.update();
  43199. }
  43200. }
  43201. this.orientationHandler = this.onOrientationChange_.bind(this);
  43202. window.addEventListener('orientationchange', this.orientationHandler);
  43203. this.vrdisplaypresentchangeHandler = this.updateBounds_.bind(this);
  43204. window.addEventListener('vrdisplaypresentchange', this.vrdisplaypresentchangeHandler);
  43205. this.fireVRDisplayDeviceParamsChange_();
  43206. };
  43207. CardboardVRDisplay.prototype.endPresent_ = function () {
  43208. if (this.distorter_) {
  43209. this.distorter_.destroy();
  43210. this.distorter_ = null;
  43211. }
  43212. if (this.cardboardUI_) {
  43213. this.cardboardUI_.destroy();
  43214. this.cardboardUI_ = null;
  43215. }
  43216. if (this.rotateInstructions_) {
  43217. this.rotateInstructions_.hide();
  43218. }
  43219. this.viewerSelector_.hide();
  43220. window.removeEventListener('orientationchange', this.orientationHandler);
  43221. window.removeEventListener('vrdisplaypresentchange', this.vrdisplaypresentchangeHandler);
  43222. };
  43223. CardboardVRDisplay.prototype.updatePresent_ = function () {
  43224. this.endPresent_();
  43225. this.beginPresent_();
  43226. };
  43227. CardboardVRDisplay.prototype.submitFrame = function (pose) {
  43228. if (this.distorter_) {
  43229. this.updateBounds_();
  43230. this.distorter_.submitFrame();
  43231. } else if (this.cardboardUI_ && this.layer_) {
  43232. var canvas = this.layer_.source.getContext('webgl').canvas;
  43233. if (canvas.width != this.lastWidth || canvas.height != this.lastHeight) {
  43234. this.cardboardUI_.onResize();
  43235. }
  43236. this.lastWidth = canvas.width;
  43237. this.lastHeight = canvas.height;
  43238. this.cardboardUI_.render();
  43239. }
  43240. };
  43241. CardboardVRDisplay.prototype.onOrientationChange_ = function (e) {
  43242. this.viewerSelector_.hide();
  43243. if (this.rotateInstructions_) {
  43244. this.rotateInstructions_.update();
  43245. }
  43246. this.onResize_();
  43247. };
  43248. CardboardVRDisplay.prototype.onResize_ = function (e) {
  43249. if (this.layer_) {
  43250. var gl = this.layer_.source.getContext('webgl');
  43251. var cssProperties = ['position: absolute', 'top: 0', 'left: 0',
  43252. 'width: 100vw', 'height: 100vh', 'border: 0', 'margin: 0',
  43253. 'padding: 0px', 'box-sizing: content-box'];
  43254. gl.canvas.setAttribute('style', cssProperties.join('; ') + ';');
  43255. safariCssSizeWorkaround(gl.canvas);
  43256. }
  43257. };
  43258. CardboardVRDisplay.prototype.onViewerChanged_ = function (viewer) {
  43259. this.deviceInfo_.setViewer(viewer);
  43260. if (this.distorter_) {
  43261. this.distorter_.updateDeviceInfo(this.deviceInfo_);
  43262. }
  43263. this.fireVRDisplayDeviceParamsChange_();
  43264. };
  43265. CardboardVRDisplay.prototype.fireVRDisplayDeviceParamsChange_ = function () {
  43266. var event = new CustomEvent('vrdisplaydeviceparamschange', {
  43267. detail: {
  43268. vrdisplay: this,
  43269. deviceInfo: this.deviceInfo_
  43270. }
  43271. });
  43272. window.dispatchEvent(event);
  43273. };
  43274. CardboardVRDisplay.VRFrameData = VRFrameData;
  43275. CardboardVRDisplay.VRDisplay = VRDisplay;
  43276. return CardboardVRDisplay;
  43277. })));
  43278. });
  43279. var CardboardVRDisplay = unwrapExports(cardboardVrDisplay);
  43280. var version = "0.10.10";
  43281. var DefaultConfig = {
  43282. ADDITIONAL_VIEWERS: [],
  43283. DEFAULT_VIEWER: '',
  43284. PROVIDE_MOBILE_VRDISPLAY: true,
  43285. MOBILE_WAKE_LOCK: true,
  43286. DEBUG: false,
  43287. DPDB_URL: 'https://dpdb.webvr.rocks/dpdb.json',
  43288. K_FILTER: 0.98,
  43289. PREDICTION_TIME_S: 0.040,
  43290. CARDBOARD_UI_DISABLED: false,
  43291. ROTATE_INSTRUCTIONS_DISABLED: false,
  43292. YAW_ONLY: false,
  43293. BUFFER_SCALE: 0.5,
  43294. DIRTY_SUBMIT_FRAME_BINDINGS: false
  43295. };
  43296. function WebVRPolyfill(config) {
  43297. this.config = extend(extend({}, DefaultConfig), config);
  43298. this.polyfillDisplays = [];
  43299. this.enabled = false;
  43300. this.hasNative = 'getVRDisplays' in navigator;
  43301. this.native = {};
  43302. this.native.getVRDisplays = navigator.getVRDisplays;
  43303. this.native.VRFrameData = window.VRFrameData;
  43304. this.native.VRDisplay = window.VRDisplay;
  43305. if (!this.hasNative || this.config.PROVIDE_MOBILE_VRDISPLAY && isMobile()) {
  43306. this.enable();
  43307. this.getVRDisplays().then(function (displays) {
  43308. if (displays && displays[0] && displays[0].fireVRDisplayConnect_) {
  43309. displays[0].fireVRDisplayConnect_();
  43310. }
  43311. });
  43312. }
  43313. }
  43314. WebVRPolyfill.prototype.getPolyfillDisplays = function () {
  43315. if (this._polyfillDisplaysPopulated) {
  43316. return this.polyfillDisplays;
  43317. }
  43318. if (isMobile()) {
  43319. var vrDisplay = new CardboardVRDisplay({
  43320. ADDITIONAL_VIEWERS: this.config.ADDITIONAL_VIEWERS,
  43321. DEFAULT_VIEWER: this.config.DEFAULT_VIEWER,
  43322. MOBILE_WAKE_LOCK: this.config.MOBILE_WAKE_LOCK,
  43323. DEBUG: this.config.DEBUG,
  43324. DPDB_URL: this.config.DPDB_URL,
  43325. CARDBOARD_UI_DISABLED: this.config.CARDBOARD_UI_DISABLED,
  43326. K_FILTER: this.config.K_FILTER,
  43327. PREDICTION_TIME_S: this.config.PREDICTION_TIME_S,
  43328. ROTATE_INSTRUCTIONS_DISABLED: this.config.ROTATE_INSTRUCTIONS_DISABLED,
  43329. YAW_ONLY: this.config.YAW_ONLY,
  43330. BUFFER_SCALE: this.config.BUFFER_SCALE,
  43331. DIRTY_SUBMIT_FRAME_BINDINGS: this.config.DIRTY_SUBMIT_FRAME_BINDINGS
  43332. });
  43333. this.polyfillDisplays.push(vrDisplay);
  43334. }
  43335. this._polyfillDisplaysPopulated = true;
  43336. return this.polyfillDisplays;
  43337. };
  43338. WebVRPolyfill.prototype.enable = function () {
  43339. this.enabled = true;
  43340. if (this.hasNative && this.native.VRFrameData) {
  43341. var NativeVRFrameData = this.native.VRFrameData;
  43342. var nativeFrameData = new this.native.VRFrameData();
  43343. var nativeGetFrameData = this.native.VRDisplay.prototype.getFrameData;
  43344. window.VRDisplay.prototype.getFrameData = function (frameData) {
  43345. if (frameData instanceof NativeVRFrameData) {
  43346. nativeGetFrameData.call(this, frameData);
  43347. return;
  43348. }
  43349. nativeGetFrameData.call(this, nativeFrameData);
  43350. frameData.pose = nativeFrameData.pose;
  43351. copyArray(nativeFrameData.leftProjectionMatrix, frameData.leftProjectionMatrix);
  43352. copyArray(nativeFrameData.rightProjectionMatrix, frameData.rightProjectionMatrix);
  43353. copyArray(nativeFrameData.leftViewMatrix, frameData.leftViewMatrix);
  43354. copyArray(nativeFrameData.rightViewMatrix, frameData.rightViewMatrix);
  43355. };
  43356. }
  43357. navigator.getVRDisplays = this.getVRDisplays.bind(this);
  43358. window.VRDisplay = CardboardVRDisplay.VRDisplay;
  43359. window.VRFrameData = CardboardVRDisplay.VRFrameData;
  43360. };
  43361. WebVRPolyfill.prototype.getVRDisplays = function () {
  43362. var _this = this;
  43363. var config = this.config;
  43364. if (!this.hasNative) {
  43365. return Promise.resolve(this.getPolyfillDisplays());
  43366. }
  43367. return this.native.getVRDisplays.call(navigator).then(function (nativeDisplays) {
  43368. return nativeDisplays.length > 0 ? nativeDisplays : _this.getPolyfillDisplays();
  43369. });
  43370. };
  43371. WebVRPolyfill.version = version;
  43372. WebVRPolyfill.VRFrameData = CardboardVRDisplay.VRFrameData;
  43373. WebVRPolyfill.VRDisplay = CardboardVRDisplay.VRDisplay;
  43374. var webvrPolyfill = Object.freeze({
  43375. default: WebVRPolyfill
  43376. });
  43377. var require$$0 = ( webvrPolyfill && WebVRPolyfill ) || webvrPolyfill;
  43378. if (typeof commonjsGlobal !== 'undefined' && commonjsGlobal.window) {
  43379. if (!commonjsGlobal.document) {
  43380. commonjsGlobal.document = commonjsGlobal.window.document;
  43381. }
  43382. if (!commonjsGlobal.navigator) {
  43383. commonjsGlobal.navigator = commonjsGlobal.window.navigator;
  43384. }
  43385. }
  43386. var src = require$$0;
  43387. return src;
  43388. })));
  43389. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  43390. },{}],68:[function(_dereq_,module,exports){
  43391. var newline = /\n/
  43392. var newlineChar = '\n'
  43393. var whitespace = /\s/
  43394. module.exports = function(text, opt) {
  43395. var lines = module.exports.lines(text, opt)
  43396. return lines.map(function(line) {
  43397. return text.substring(line.start, line.end)
  43398. }).join('\n')
  43399. }
  43400. module.exports.lines = function wordwrap(text, opt) {
  43401. opt = opt||{}
  43402. //zero width results in nothing visible
  43403. if (opt.width === 0 && opt.mode !== 'nowrap')
  43404. return []
  43405. text = text||''
  43406. var width = typeof opt.width === 'number' ? opt.width : Number.MAX_VALUE
  43407. var start = Math.max(0, opt.start||0)
  43408. var end = typeof opt.end === 'number' ? opt.end : text.length
  43409. var mode = opt.mode
  43410. var measure = opt.measure || monospace
  43411. if (mode === 'pre')
  43412. return pre(measure, text, start, end, width)
  43413. else
  43414. return greedy(measure, text, start, end, width, mode)
  43415. }
  43416. function idxOf(text, chr, start, end) {
  43417. var idx = text.indexOf(chr, start)
  43418. if (idx === -1 || idx > end)
  43419. return end
  43420. return idx
  43421. }
  43422. function isWhitespace(chr) {
  43423. return whitespace.test(chr)
  43424. }
  43425. function pre(measure, text, start, end, width) {
  43426. var lines = []
  43427. var lineStart = start
  43428. for (var i=start; i<end && i<text.length; i++) {
  43429. var chr = text.charAt(i)
  43430. var isNewline = newline.test(chr)
  43431. //If we've reached a newline, then step down a line
  43432. //Or if we've reached the EOF
  43433. if (isNewline || i===end-1) {
  43434. var lineEnd = isNewline ? i : i+1
  43435. var measured = measure(text, lineStart, lineEnd, width)
  43436. lines.push(measured)
  43437. lineStart = i+1
  43438. }
  43439. }
  43440. return lines
  43441. }
  43442. function greedy(measure, text, start, end, width, mode) {
  43443. //A greedy word wrapper based on LibGDX algorithm
  43444. //https://github.com/libgdx/libgdx/blob/master/gdx/src/com/badlogic/gdx/graphics/g2d/BitmapFontCache.java
  43445. var lines = []
  43446. var testWidth = width
  43447. //if 'nowrap' is specified, we only wrap on newline chars
  43448. if (mode === 'nowrap')
  43449. testWidth = Number.MAX_VALUE
  43450. while (start < end && start < text.length) {
  43451. //get next newline position
  43452. var newLine = idxOf(text, newlineChar, start, end)
  43453. //eat whitespace at start of line
  43454. while (start < newLine) {
  43455. if (!isWhitespace( text.charAt(start) ))
  43456. break
  43457. start++
  43458. }
  43459. //determine visible # of glyphs for the available width
  43460. var measured = measure(text, start, newLine, testWidth)
  43461. var lineEnd = start + (measured.end-measured.start)
  43462. var nextStart = lineEnd + newlineChar.length
  43463. //if we had to cut the line before the next newline...
  43464. if (lineEnd < newLine) {
  43465. //find char to break on
  43466. while (lineEnd > start) {
  43467. if (isWhitespace(text.charAt(lineEnd)))
  43468. break
  43469. lineEnd--
  43470. }
  43471. if (lineEnd === start) {
  43472. if (nextStart > start + newlineChar.length) nextStart--
  43473. lineEnd = nextStart // If no characters to break, show all.
  43474. } else {
  43475. nextStart = lineEnd
  43476. //eat whitespace at end of line
  43477. while (lineEnd > start) {
  43478. if (!isWhitespace(text.charAt(lineEnd - newlineChar.length)))
  43479. break
  43480. lineEnd--
  43481. }
  43482. }
  43483. }
  43484. if (lineEnd >= start) {
  43485. var result = measure(text, start, lineEnd, testWidth)
  43486. lines.push(result)
  43487. }
  43488. start = nextStart
  43489. }
  43490. return lines
  43491. }
  43492. //determines the visible number of glyphs within a given width
  43493. function monospace(text, start, end, width) {
  43494. var glyphs = Math.min(width, end-start)
  43495. return {
  43496. start: start,
  43497. end: start+glyphs
  43498. }
  43499. }
  43500. },{}],69:[function(_dereq_,module,exports){
  43501. "use strict";
  43502. var window = _dereq_("global/window")
  43503. var isFunction = _dereq_("is-function")
  43504. var parseHeaders = _dereq_("parse-headers")
  43505. var xtend = _dereq_("xtend")
  43506. module.exports = createXHR
  43507. // Allow use of default import syntax in TypeScript
  43508. module.exports.default = createXHR;
  43509. createXHR.XMLHttpRequest = window.XMLHttpRequest || noop
  43510. createXHR.XDomainRequest = "withCredentials" in (new createXHR.XMLHttpRequest()) ? createXHR.XMLHttpRequest : window.XDomainRequest
  43511. forEachArray(["get", "put", "post", "patch", "head", "delete"], function(method) {
  43512. createXHR[method === "delete" ? "del" : method] = function(uri, options, callback) {
  43513. options = initParams(uri, options, callback)
  43514. options.method = method.toUpperCase()
  43515. return _createXHR(options)
  43516. }
  43517. })
  43518. function forEachArray(array, iterator) {
  43519. for (var i = 0; i < array.length; i++) {
  43520. iterator(array[i])
  43521. }
  43522. }
  43523. function isEmpty(obj){
  43524. for(var i in obj){
  43525. if(obj.hasOwnProperty(i)) return false
  43526. }
  43527. return true
  43528. }
  43529. function initParams(uri, options, callback) {
  43530. var params = uri
  43531. if (isFunction(options)) {
  43532. callback = options
  43533. if (typeof uri === "string") {
  43534. params = {uri:uri}
  43535. }
  43536. } else {
  43537. params = xtend(options, {uri: uri})
  43538. }
  43539. params.callback = callback
  43540. return params
  43541. }
  43542. function createXHR(uri, options, callback) {
  43543. options = initParams(uri, options, callback)
  43544. return _createXHR(options)
  43545. }
  43546. function _createXHR(options) {
  43547. if(typeof options.callback === "undefined"){
  43548. throw new Error("callback argument missing")
  43549. }
  43550. var called = false
  43551. var callback = function cbOnce(err, response, body){
  43552. if(!called){
  43553. called = true
  43554. options.callback(err, response, body)
  43555. }
  43556. }
  43557. function readystatechange() {
  43558. if (xhr.readyState === 4) {
  43559. setTimeout(loadFunc, 0)
  43560. }
  43561. }
  43562. function getBody() {
  43563. // Chrome with requestType=blob throws errors arround when even testing access to responseText
  43564. var body = undefined
  43565. if (xhr.response) {
  43566. body = xhr.response
  43567. } else {
  43568. body = xhr.responseText || getXml(xhr)
  43569. }
  43570. if (isJson) {
  43571. try {
  43572. body = JSON.parse(body)
  43573. } catch (e) {}
  43574. }
  43575. return body
  43576. }
  43577. function errorFunc(evt) {
  43578. clearTimeout(timeoutTimer)
  43579. if(!(evt instanceof Error)){
  43580. evt = new Error("" + (evt || "Unknown XMLHttpRequest Error") )
  43581. }
  43582. evt.statusCode = 0
  43583. return callback(evt, failureResponse)
  43584. }
  43585. // will load the data & process the response in a special response object
  43586. function loadFunc() {
  43587. if (aborted) return
  43588. var status
  43589. clearTimeout(timeoutTimer)
  43590. if(options.useXDR && xhr.status===undefined) {
  43591. //IE8 CORS GET successful response doesn't have a status field, but body is fine
  43592. status = 200
  43593. } else {
  43594. status = (xhr.status === 1223 ? 204 : xhr.status)
  43595. }
  43596. var response = failureResponse
  43597. var err = null
  43598. if (status !== 0){
  43599. response = {
  43600. body: getBody(),
  43601. statusCode: status,
  43602. method: method,
  43603. headers: {},
  43604. url: uri,
  43605. rawRequest: xhr
  43606. }
  43607. if(xhr.getAllResponseHeaders){ //remember xhr can in fact be XDR for CORS in IE
  43608. response.headers = parseHeaders(xhr.getAllResponseHeaders())
  43609. }
  43610. } else {
  43611. err = new Error("Internal XMLHttpRequest Error")
  43612. }
  43613. return callback(err, response, response.body)
  43614. }
  43615. var xhr = options.xhr || null
  43616. if (!xhr) {
  43617. if (options.cors || options.useXDR) {
  43618. xhr = new createXHR.XDomainRequest()
  43619. }else{
  43620. xhr = new createXHR.XMLHttpRequest()
  43621. }
  43622. }
  43623. var key
  43624. var aborted
  43625. var uri = xhr.url = options.uri || options.url
  43626. var method = xhr.method = options.method || "GET"
  43627. var body = options.body || options.data
  43628. var headers = xhr.headers = options.headers || {}
  43629. var sync = !!options.sync
  43630. var isJson = false
  43631. var timeoutTimer
  43632. var failureResponse = {
  43633. body: undefined,
  43634. headers: {},
  43635. statusCode: 0,
  43636. method: method,
  43637. url: uri,
  43638. rawRequest: xhr
  43639. }
  43640. if ("json" in options && options.json !== false) {
  43641. isJson = true
  43642. headers["accept"] || headers["Accept"] || (headers["Accept"] = "application/json") //Don't override existing accept header declared by user
  43643. if (method !== "GET" && method !== "HEAD") {
  43644. headers["content-type"] || headers["Content-Type"] || (headers["Content-Type"] = "application/json") //Don't override existing accept header declared by user
  43645. body = JSON.stringify(options.json === true ? body : options.json)
  43646. }
  43647. }
  43648. xhr.onreadystatechange = readystatechange
  43649. xhr.onload = loadFunc
  43650. xhr.onerror = errorFunc
  43651. // IE9 must have onprogress be set to a unique function.
  43652. xhr.onprogress = function () {
  43653. // IE must die
  43654. }
  43655. xhr.onabort = function(){
  43656. aborted = true;
  43657. }
  43658. xhr.ontimeout = errorFunc
  43659. xhr.open(method, uri, !sync, options.username, options.password)
  43660. //has to be after open
  43661. if(!sync) {
  43662. xhr.withCredentials = !!options.withCredentials
  43663. }
  43664. // Cannot set timeout with sync request
  43665. // not setting timeout on the xhr object, because of old webkits etc. not handling that correctly
  43666. // both npm's request and jquery 1.x use this kind of timeout, so this is being consistent
  43667. if (!sync && options.timeout > 0 ) {
  43668. timeoutTimer = setTimeout(function(){
  43669. if (aborted) return
  43670. aborted = true//IE9 may still call readystatechange
  43671. xhr.abort("timeout")
  43672. var e = new Error("XMLHttpRequest timeout")
  43673. e.code = "ETIMEDOUT"
  43674. errorFunc(e)
  43675. }, options.timeout )
  43676. }
  43677. if (xhr.setRequestHeader) {
  43678. for(key in headers){
  43679. if(headers.hasOwnProperty(key)){
  43680. xhr.setRequestHeader(key, headers[key])
  43681. }
  43682. }
  43683. } else if (options.headers && !isEmpty(options.headers)) {
  43684. throw new Error("Headers cannot be set on an XDomainRequest object")
  43685. }
  43686. if ("responseType" in options) {
  43687. xhr.responseType = options.responseType
  43688. }
  43689. if ("beforeSend" in options &&
  43690. typeof options.beforeSend === "function"
  43691. ) {
  43692. options.beforeSend(xhr)
  43693. }
  43694. // Microsoft Edge browser sends "undefined" when send is called with undefined value.
  43695. // XMLHttpRequest spec says to pass null as body to indicate no body
  43696. // See https://github.com/naugtur/xhr/issues/100.
  43697. xhr.send(body || null)
  43698. return xhr
  43699. }
  43700. function getXml(xhr) {
  43701. // xhr.responseXML will throw Exception "InvalidStateError" or "DOMException"
  43702. // See https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/responseXML.
  43703. try {
  43704. if (xhr.responseType === "document") {
  43705. return xhr.responseXML
  43706. }
  43707. var firefoxBugTakenEffect = xhr.responseXML && xhr.responseXML.documentElement.nodeName === "parsererror"
  43708. if (xhr.responseType === "" && !firefoxBugTakenEffect) {
  43709. return xhr.responseXML
  43710. }
  43711. } catch (e) {}
  43712. return null
  43713. }
  43714. function noop() {}
  43715. },{"global/window":27,"is-function":33,"parse-headers":47,"xtend":71}],70:[function(_dereq_,module,exports){
  43716. module.exports = (function xmlparser() {
  43717. //common browsers
  43718. if (typeof self.DOMParser !== 'undefined') {
  43719. return function(str) {
  43720. var parser = new self.DOMParser()
  43721. return parser.parseFromString(str, 'application/xml')
  43722. }
  43723. }
  43724. //IE8 fallback
  43725. if (typeof self.ActiveXObject !== 'undefined'
  43726. && new self.ActiveXObject('Microsoft.XMLDOM')) {
  43727. return function(str) {
  43728. var xmlDoc = new self.ActiveXObject("Microsoft.XMLDOM")
  43729. xmlDoc.async = "false"
  43730. xmlDoc.loadXML(str)
  43731. return xmlDoc
  43732. }
  43733. }
  43734. //last resort fallback
  43735. return function(str) {
  43736. var div = document.createElement('div')
  43737. div.innerHTML = str
  43738. return div
  43739. }
  43740. })()
  43741. },{}],71:[function(_dereq_,module,exports){
  43742. module.exports = extend
  43743. var hasOwnProperty = Object.prototype.hasOwnProperty;
  43744. function extend() {
  43745. var target = {}
  43746. for (var i = 0; i < arguments.length; i++) {
  43747. var source = arguments[i]
  43748. for (var key in source) {
  43749. if (hasOwnProperty.call(source, key)) {
  43750. target[key] = source[key]
  43751. }
  43752. }
  43753. }
  43754. return target
  43755. }
  43756. },{}],72:[function(_dereq_,module,exports){
  43757. module.exports={
  43758. "name": "aframe",
  43759. "version": "1.0.4",
  43760. "description": "A web framework for building virtual reality experiences.",
  43761. "homepage": "https://aframe.io/",
  43762. "main": "dist/aframe-master.js",
  43763. "scripts": {
  43764. "browserify": "browserify src/index.js -s 'AFRAME' -p browserify-derequire",
  43765. "build": "shx mkdir -p build/ && npm run browserify -- --debug -t [ envify --INSPECTOR_VERSION dev ] -o build/aframe.js",
  43766. "codecov": "codecov",
  43767. "dev": "npm run build && cross-env INSPECTOR_VERSION=dev node ./scripts/budo -t envify",
  43768. "dist": "node scripts/updateVersionLog.js && npm run dist:min && npm run dist:max",
  43769. "dist:max": "npm run browserify -s -- --debug | exorcist dist/aframe-master.js.map > dist/aframe-master.js",
  43770. "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",
  43771. "docs": "markserv --dir docs --port 9001",
  43772. "preghpages": "node ./scripts/preghpages.js",
  43773. "ghpages": "ghpages -p gh-pages/",
  43774. "lint": "semistandard -v | snazzy",
  43775. "lint:fix": "semistandard --fix",
  43776. "precommit": "npm run lint",
  43777. "prepush": "node scripts/testOnlyCheck.js",
  43778. "prerelease": "node scripts/release.js 1.0.3 1.0.4",
  43779. "start": "npm run dev",
  43780. "start:https": "cross-env SSL=true npm run dev",
  43781. "test": "karma start ./tests/karma.conf.js",
  43782. "test:docs": "node scripts/docsLint.js",
  43783. "test:firefox": "npm test -- --browsers Firefox",
  43784. "test:chrome": "npm test -- --browsers Chrome",
  43785. "test:nobrowser": "NO_BROWSER=true npm test",
  43786. "test:node": "mocha --ui tdd tests/node"
  43787. },
  43788. "repository": "aframevr/aframe",
  43789. "license": "MIT",
  43790. "files": [
  43791. "dist/*",
  43792. "docs/**/*",
  43793. "src/**/*",
  43794. "vendor/**/*"
  43795. ],
  43796. "dependencies": {
  43797. "custom-event-polyfill": "^1.0.6",
  43798. "debug": "ngokevin/debug#noTimestamp",
  43799. "deep-assign": "^2.0.0",
  43800. "document-register-element": "dmarcos/document-register-element#8ccc532b7f3744be954574caf3072a5fd260ca90",
  43801. "load-bmfont": "^1.2.3",
  43802. "object-assign": "^4.0.1",
  43803. "present": "0.0.6",
  43804. "promise-polyfill": "^3.1.0",
  43805. "super-animejs": "^3.1.0",
  43806. "super-three": "^0.115.1",
  43807. "three-bmfont-text": "dmarcos/three-bmfont-text#1babdf8507c731a18f8af3b807292e2b9740955e",
  43808. "webvr-polyfill": "^0.10.10"
  43809. },
  43810. "devDependencies": {
  43811. "browserify": "^13.1.0",
  43812. "browserify-css": "^0.8.4",
  43813. "browserify-derequire": "^0.9.4",
  43814. "browserify-istanbul": "^2.0.0",
  43815. "budo": "^9.2.0",
  43816. "chai": "^3.5.0",
  43817. "chai-shallow-deep-equal": "^1.4.0",
  43818. "chalk": "^1.1.3",
  43819. "codecov": "^1.0.1",
  43820. "cross-env": "^5.0.1",
  43821. "envify": "^3.4.1",
  43822. "exorcist": "^0.4.0",
  43823. "ghpages": "0.0.8",
  43824. "git-rev": "^0.2.1",
  43825. "glob": "^7.1.1",
  43826. "husky": "^0.11.7",
  43827. "istanbul": "^0.4.5",
  43828. "jsdom": "^9.11.0",
  43829. "karma": "1.4.1",
  43830. "karma-browserify": "^5.1.0",
  43831. "karma-chai-shallow-deep-equal": "0.0.4",
  43832. "karma-chrome-launcher": "^2.0.0",
  43833. "karma-coverage": "^1.1.1",
  43834. "karma-env-preprocessor": "^0.1.1",
  43835. "karma-firefox-launcher": "^1.2.0",
  43836. "karma-mocha": "^1.1.1",
  43837. "karma-mocha-reporter": "^2.1.0",
  43838. "karma-sinon-chai": "1.2.4",
  43839. "lolex": "^1.5.1",
  43840. "markserv": "github:sukima/markserv#feature/fix-broken-websoketio-link",
  43841. "minifyify": "^7.3.3",
  43842. "mocha": "^3.0.2",
  43843. "mozilla-download": "^1.1.1",
  43844. "replace-in-file": "^2.5.3",
  43845. "semistandard": "^9.0.0",
  43846. "shelljs": "^0.7.7",
  43847. "shx": "^0.2.2",
  43848. "sinon": "^1.17.5",
  43849. "sinon-chai": "2.8.0",
  43850. "snazzy": "^5.0.0",
  43851. "too-wordy": "ngokevin/too-wordy",
  43852. "uglifyjs": "^2.4.10",
  43853. "write-good": "^0.9.1"
  43854. },
  43855. "link": true,
  43856. "browserify": {
  43857. "transform": [
  43858. "browserify-css",
  43859. "envify"
  43860. ]
  43861. },
  43862. "semistandard": {
  43863. "ignore": [
  43864. "build/**",
  43865. "dist/**",
  43866. "examples/**/shaders/*.js",
  43867. "**/vendor/**"
  43868. ]
  43869. },
  43870. "keywords": [
  43871. "3d",
  43872. "aframe",
  43873. "cardboard",
  43874. "components",
  43875. "oculus",
  43876. "three",
  43877. "three.js",
  43878. "rift",
  43879. "vive",
  43880. "vr",
  43881. "web-components",
  43882. "webvr"
  43883. ],
  43884. "browserify-css": {
  43885. "minify": true
  43886. },
  43887. "engines": {
  43888. "node": ">= 4.6.0",
  43889. "npm": "^2.15.9"
  43890. }
  43891. }
  43892. },{}],73:[function(_dereq_,module,exports){
  43893. var anime = _dereq_('super-animejs');
  43894. var components = _dereq_('../core/component').components;
  43895. var registerComponent = _dereq_('../core/component').registerComponent;
  43896. var THREE = _dereq_('../lib/three');
  43897. var utils = _dereq_('../utils');
  43898. var colorHelperFrom = new THREE.Color();
  43899. var colorHelperTo = new THREE.Color();
  43900. var getComponentProperty = utils.entity.getComponentProperty;
  43901. var setComponentProperty = utils.entity.setComponentProperty;
  43902. var splitCache = {};
  43903. var TYPE_COLOR = 'color';
  43904. var PROP_POSITION = 'position';
  43905. var PROP_ROTATION = 'rotation';
  43906. var PROP_SCALE = 'scale';
  43907. var STRING_COMPONENTS = 'components';
  43908. var STRING_OBJECT3D = 'object3D';
  43909. /**
  43910. * Animation component for A-Frame using anime.js.
  43911. *
  43912. * The component manually controls the tick by setting `autoplay: false` on anime.js and
  43913. * manually * calling `animation.tick()` in the tick handler. To pause or resume, we toggle a
  43914. * boolean * flag * `isAnimationPlaying`.
  43915. *
  43916. * anime.js animation config for tweenining Javascript objects and values works as:
  43917. *
  43918. * config = {
  43919. * targets: {foo: 0.0, bar: '#000'},
  43920. * foo: 1.0,
  43921. * bar: '#FFF'
  43922. * }
  43923. *
  43924. * The above will tween each property in `targets`. The `to` values are set in the root of
  43925. * the config.
  43926. *
  43927. * @member {object} animation - anime.js instance.
  43928. * @member {boolean} animationIsPlaying - Control if animation is playing.
  43929. */
  43930. module.exports.Component = registerComponent('animation', {
  43931. schema: {
  43932. autoplay: {default: true},
  43933. delay: {default: 0},
  43934. dir: {default: ''},
  43935. dur: {default: 1000},
  43936. easing: {default: 'easeInQuad'},
  43937. elasticity: {default: 400},
  43938. enabled: {default: true},
  43939. from: {default: ''},
  43940. loop: {
  43941. default: 0,
  43942. parse: function (value) {
  43943. // Boolean or integer.
  43944. if (value === true || value === 'true') { return true; }
  43945. if (value === false || value === 'false') { return false; }
  43946. return parseInt(value, 10);
  43947. }
  43948. },
  43949. property: {default: ''},
  43950. startEvents: {type: 'array'},
  43951. pauseEvents: {type: 'array'},
  43952. resumeEvents: {type: 'array'},
  43953. round: {default: false},
  43954. to: {default: ''},
  43955. type: {default: ''},
  43956. isRawProperty: {default: false}
  43957. },
  43958. multiple: true,
  43959. init: function () {
  43960. var self = this;
  43961. this.eventDetail = {name: this.attrName};
  43962. this.time = 0;
  43963. this.animation = null;
  43964. this.animationIsPlaying = false;
  43965. this.onStartEvent = this.onStartEvent.bind(this);
  43966. this.beginAnimation = this.beginAnimation.bind(this);
  43967. this.pauseAnimation = this.pauseAnimation.bind(this);
  43968. this.resumeAnimation = this.resumeAnimation.bind(this);
  43969. this.fromColor = {};
  43970. this.toColor = {};
  43971. this.targets = {};
  43972. this.targetsArray = [];
  43973. this.updateConfigForDefault = this.updateConfigForDefault.bind(this);
  43974. this.updateConfigForRawColor = this.updateConfigForRawColor.bind(this);
  43975. this.config = {
  43976. complete: function () {
  43977. self.animationIsPlaying = false;
  43978. self.el.emit('animationcomplete', self.eventDetail, false);
  43979. if (self.id) {
  43980. self.el.emit('animationcomplete__' + self.id, self.eventDetail, false);
  43981. }
  43982. }
  43983. };
  43984. },
  43985. update: function (oldData) {
  43986. var config = this.config;
  43987. var data = this.data;
  43988. this.animationIsPlaying = false;
  43989. if (!this.data.enabled) { return; }
  43990. if (!data.property) { return; }
  43991. // Base config.
  43992. config.autoplay = false;
  43993. config.direction = data.dir;
  43994. config.duration = data.dur;
  43995. config.easing = data.easing;
  43996. config.elasticity = data.elasticity;
  43997. config.loop = data.loop;
  43998. config.round = data.round;
  43999. // Start new animation.
  44000. this.createAndStartAnimation();
  44001. },
  44002. tick: function (t, dt) {
  44003. if (!this.animationIsPlaying) { return; }
  44004. this.time += dt;
  44005. this.animation.tick(this.time);
  44006. },
  44007. remove: function () {
  44008. this.pauseAnimation();
  44009. this.removeEventListeners();
  44010. },
  44011. pause: function () {
  44012. this.paused = true;
  44013. this.pausedWasPlaying = this.animationIsPlaying;
  44014. this.pauseAnimation();
  44015. this.removeEventListeners();
  44016. },
  44017. /**
  44018. * `play` handler only for resuming scene.
  44019. */
  44020. play: function () {
  44021. if (!this.paused) { return; }
  44022. this.paused = false;
  44023. this.addEventListeners();
  44024. if (this.pausedWasPlaying) {
  44025. this.resumeAnimation();
  44026. this.pausedWasPlaying = false;
  44027. }
  44028. },
  44029. /**
  44030. * Start animation from scratch.
  44031. */
  44032. createAndStartAnimation: function () {
  44033. var data = this.data;
  44034. this.updateConfig();
  44035. this.animationIsPlaying = false;
  44036. this.animation = anime(this.config);
  44037. this.animation.began = true;
  44038. this.removeEventListeners();
  44039. this.addEventListeners();
  44040. // Wait for start events for animation.
  44041. if (!data.autoplay || data.startEvents && data.startEvents.length) { return; }
  44042. // Delay animation.
  44043. if (data.delay) {
  44044. setTimeout(this.beginAnimation, data.delay);
  44045. return;
  44046. }
  44047. // Play animation.
  44048. this.beginAnimation();
  44049. },
  44050. /**
  44051. * This is before animation start (including from startEvents).
  44052. * Set to initial state (config.from, time = 0, seekTime = 0).
  44053. */
  44054. beginAnimation: function () {
  44055. this.updateConfig();
  44056. this.animation.began = true;
  44057. this.time = 0;
  44058. this.animationIsPlaying = true;
  44059. this.stopRelatedAnimations();
  44060. this.el.emit('animationbegin', this.eventDetail, false);
  44061. },
  44062. pauseAnimation: function () {
  44063. this.animationIsPlaying = false;
  44064. },
  44065. resumeAnimation: function () {
  44066. this.animationIsPlaying = true;
  44067. },
  44068. /**
  44069. * startEvents callback.
  44070. */
  44071. onStartEvent: function () {
  44072. if (!this.data.enabled) { return; }
  44073. this.updateConfig();
  44074. if (this.animation) {
  44075. this.animation.pause();
  44076. }
  44077. this.animation = anime(this.config);
  44078. // Include the delay before each start event.
  44079. if (this.data.delay) {
  44080. setTimeout(this.beginAnimation, this.data.delay);
  44081. return;
  44082. }
  44083. this.beginAnimation();
  44084. },
  44085. /**
  44086. * rawProperty: true and type: color;
  44087. */
  44088. updateConfigForRawColor: function () {
  44089. var config = this.config;
  44090. var data = this.data;
  44091. var el = this.el;
  44092. var from;
  44093. var key;
  44094. var to;
  44095. if (this.waitComponentInitRawProperty(this.updateConfigForRawColor)) {
  44096. return;
  44097. }
  44098. from = data.from === '' ? getRawProperty(el, data.property) : data.from;
  44099. to = data.to;
  44100. // Use r/g/b vector for color type.
  44101. this.setColorConfig(from, to);
  44102. from = this.fromColor;
  44103. to = this.toColor;
  44104. this.targetsArray.length = 0;
  44105. this.targetsArray.push(from);
  44106. config.targets = this.targetsArray;
  44107. for (key in to) { config[key] = to[key]; }
  44108. config.update = (function () {
  44109. var lastValue = {};
  44110. return function (anim) {
  44111. var value;
  44112. value = anim.animatables[0].target;
  44113. // For animation timeline.
  44114. if (value.r === lastValue.r &&
  44115. value.g === lastValue.g &&
  44116. value.b === lastValue.b) { return; }
  44117. setRawProperty(el, data.property, value, data.type);
  44118. };
  44119. })();
  44120. },
  44121. /**
  44122. * Stuff property into generic `property` key.
  44123. */
  44124. updateConfigForDefault: function () {
  44125. var config = this.config;
  44126. var data = this.data;
  44127. var el = this.el;
  44128. var from;
  44129. var isBoolean;
  44130. var isNumber;
  44131. var to;
  44132. if (this.waitComponentInitRawProperty(this.updateConfigForDefault)) {
  44133. return;
  44134. }
  44135. if (data.from === '') {
  44136. // Infer from.
  44137. from = isRawProperty(data)
  44138. ? getRawProperty(el, data.property)
  44139. : getComponentProperty(el, data.property);
  44140. } else {
  44141. // Explicit from.
  44142. from = data.from;
  44143. }
  44144. to = data.to;
  44145. isNumber = !isNaN(from || to);
  44146. if (isNumber) {
  44147. from = parseFloat(from);
  44148. to = parseFloat(to);
  44149. } else {
  44150. from = from ? from.toString() : from;
  44151. to = to ? to.toString() : to;
  44152. }
  44153. // Convert booleans to integer to allow boolean flipping.
  44154. isBoolean = data.to === 'true' || data.to === 'false' ||
  44155. data.to === true || data.to === false;
  44156. if (isBoolean) {
  44157. from = data.from === 'true' || data.from === true ? 1 : 0;
  44158. to = data.to === 'true' || data.to === true ? 1 : 0;
  44159. }
  44160. this.targets.aframeProperty = from;
  44161. config.targets = this.targets;
  44162. config.aframeProperty = to;
  44163. config.update = (function () {
  44164. var lastValue;
  44165. return function (anim) {
  44166. var value;
  44167. value = anim.animatables[0].target.aframeProperty;
  44168. // Need to do a last value check for animation timeline since all the tweening
  44169. // begins simultaenously even if the value has not changed. Also better for perf
  44170. // anyways.
  44171. if (value === lastValue) { return; }
  44172. lastValue = value;
  44173. if (isBoolean) { value = value >= 1; }
  44174. if (isRawProperty(data)) {
  44175. setRawProperty(el, data.property, value, data.type);
  44176. } else {
  44177. setComponentProperty(el, data.property, value);
  44178. }
  44179. };
  44180. })();
  44181. },
  44182. /**
  44183. * Extend x/y/z/w onto the config.
  44184. * Update vector by modifying object3D.
  44185. */
  44186. updateConfigForVector: function () {
  44187. var config = this.config;
  44188. var data = this.data;
  44189. var el = this.el;
  44190. var key;
  44191. var from;
  44192. var to;
  44193. // Parse coordinates.
  44194. from = data.from !== ''
  44195. ? utils.coordinates.parse(data.from) // If data.from defined, use that.
  44196. : getComponentProperty(el, data.property); // If data.from not defined, get on the fly.
  44197. to = utils.coordinates.parse(data.to);
  44198. if (data.property === PROP_ROTATION) {
  44199. toRadians(from);
  44200. toRadians(to);
  44201. }
  44202. // Set to and from.
  44203. this.targetsArray.length = 0;
  44204. this.targetsArray.push(from);
  44205. config.targets = this.targetsArray;
  44206. for (key in to) { config[key] = to[key]; }
  44207. // If animating object3D transformation, run more optimized updater.
  44208. if (data.property === PROP_POSITION || data.property === PROP_ROTATION ||
  44209. data.property === PROP_SCALE) {
  44210. config.update = (function () {
  44211. var lastValue = {};
  44212. return function (anim) {
  44213. var value = anim.animatables[0].target;
  44214. if (data.property === PROP_SCALE) {
  44215. value.x = Math.max(0.0001, value.x);
  44216. value.y = Math.max(0.0001, value.y);
  44217. value.z = Math.max(0.0001, value.z);
  44218. }
  44219. // For animation timeline.
  44220. if (value.x === lastValue.x &&
  44221. value.y === lastValue.y &&
  44222. value.z === lastValue.z) { return; }
  44223. lastValue.x = value.x;
  44224. lastValue.y = value.y;
  44225. lastValue.z = value.z;
  44226. el.object3D[data.property].set(value.x, value.y, value.z);
  44227. };
  44228. })();
  44229. return;
  44230. }
  44231. // Animating some vector.
  44232. config.update = (function () {
  44233. var lastValue = {};
  44234. return function (anim) {
  44235. var value = anim.animatables[0].target;
  44236. // Animate rotation through radians.
  44237. // For animation timeline.
  44238. if (value.x === lastValue.x &&
  44239. value.y === lastValue.y &&
  44240. value.z === lastValue.z) { return; }
  44241. lastValue.x = value.x;
  44242. lastValue.y = value.y;
  44243. lastValue.z = value.z;
  44244. setComponentProperty(el, data.property, value);
  44245. };
  44246. })();
  44247. },
  44248. /**
  44249. * Update the config before each run.
  44250. */
  44251. updateConfig: function () {
  44252. var propType;
  44253. // Route config type.
  44254. propType = getPropertyType(this.el, this.data.property);
  44255. if (isRawProperty(this.data) && this.data.type === TYPE_COLOR) {
  44256. this.updateConfigForRawColor();
  44257. } else if (propType === 'vec2' || propType === 'vec3' || propType === 'vec4') {
  44258. this.updateConfigForVector();
  44259. } else {
  44260. this.updateConfigForDefault();
  44261. }
  44262. },
  44263. /**
  44264. * Wait for component to initialize.
  44265. */
  44266. waitComponentInitRawProperty: function (cb) {
  44267. var componentName;
  44268. var data = this.data;
  44269. var el = this.el;
  44270. var self = this;
  44271. if (data.from !== '') { return false; }
  44272. if (!data.property.startsWith(STRING_COMPONENTS)) { return false; }
  44273. componentName = splitDot(data.property)[1];
  44274. if (el.components[componentName]) { return false; }
  44275. el.addEventListener('componentinitialized', function wait (evt) {
  44276. if (evt.detail.name !== componentName) { return; }
  44277. cb();
  44278. // Since the config was created async, create the animation now since we missed it
  44279. // earlier.
  44280. self.animation = anime(self.config);
  44281. el.removeEventListener('componentinitialized', wait);
  44282. });
  44283. return true;
  44284. },
  44285. /**
  44286. * Make sure two animations on the same property don't fight each other.
  44287. * e.g., animation__mouseenter="property: material.opacity"
  44288. * animation__mouseleave="property: material.opacity"
  44289. */
  44290. stopRelatedAnimations: function () {
  44291. var component;
  44292. var componentName;
  44293. for (componentName in this.el.components) {
  44294. component = this.el.components[componentName];
  44295. if (componentName === this.attrName) { continue; }
  44296. if (component.name !== 'animation') { continue; }
  44297. if (!component.animationIsPlaying) { continue; }
  44298. if (component.data.property !== this.data.property) { continue; }
  44299. component.animationIsPlaying = false;
  44300. }
  44301. },
  44302. addEventListeners: function () {
  44303. var data = this.data;
  44304. var el = this.el;
  44305. addEventListeners(el, data.startEvents, this.onStartEvent);
  44306. addEventListeners(el, data.pauseEvents, this.pauseAnimation);
  44307. addEventListeners(el, data.resumeEvents, this.resumeAnimation);
  44308. },
  44309. removeEventListeners: function () {
  44310. var data = this.data;
  44311. var el = this.el;
  44312. removeEventListeners(el, data.startEvents, this.onStartEvent);
  44313. removeEventListeners(el, data.pauseEvents, this.pauseAnimation);
  44314. removeEventListeners(el, data.resumeEvents, this.resumeAnimation);
  44315. },
  44316. setColorConfig: function (from, to) {
  44317. colorHelperFrom.set(from);
  44318. colorHelperTo.set(to);
  44319. from = this.fromColor;
  44320. to = this.toColor;
  44321. from.r = colorHelperFrom.r;
  44322. from.g = colorHelperFrom.g;
  44323. from.b = colorHelperFrom.b;
  44324. to.r = colorHelperTo.r;
  44325. to.g = colorHelperTo.g;
  44326. to.b = colorHelperTo.b;
  44327. }
  44328. });
  44329. /**
  44330. * Given property name, check schema to see what type we are animating.
  44331. * We just care whether the property is a vector.
  44332. */
  44333. function getPropertyType (el, property) {
  44334. var component;
  44335. var componentName;
  44336. var split;
  44337. var propertyName;
  44338. split = property.split('.');
  44339. componentName = split[0];
  44340. propertyName = split[1];
  44341. component = el.components[componentName] || components[componentName];
  44342. // Primitives.
  44343. if (!component) { return null; }
  44344. // Dynamic schema. We only care about vectors anyways.
  44345. if (propertyName && !component.schema[propertyName]) { return null; }
  44346. // Multi-prop.
  44347. if (propertyName) { return component.schema[propertyName].type; }
  44348. // Single-prop.
  44349. return component.schema.type;
  44350. }
  44351. /**
  44352. * Convert object to radians.
  44353. */
  44354. function toRadians (obj) {
  44355. obj.x = THREE.Math.degToRad(obj.x);
  44356. obj.y = THREE.Math.degToRad(obj.y);
  44357. obj.z = THREE.Math.degToRad(obj.z);
  44358. }
  44359. function addEventListeners (el, eventNames, handler) {
  44360. var i;
  44361. for (i = 0; i < eventNames.length; i++) {
  44362. el.addEventListener(eventNames[i], handler);
  44363. }
  44364. }
  44365. function removeEventListeners (el, eventNames, handler) {
  44366. var i;
  44367. for (i = 0; i < eventNames.length; i++) {
  44368. el.removeEventListener(eventNames[i], handler);
  44369. }
  44370. }
  44371. function getRawProperty (el, path) {
  44372. var i;
  44373. var split;
  44374. var value;
  44375. split = splitDot(path);
  44376. value = el;
  44377. for (i = 0; i < split.length; i++) {
  44378. value = value[split[i]];
  44379. }
  44380. if (value === undefined) {
  44381. console.log(el);
  44382. throw new Error('[animation] property (' + path + ') could not be found');
  44383. }
  44384. return value;
  44385. }
  44386. function setRawProperty (el, path, value, type) {
  44387. var i;
  44388. var split;
  44389. var propertyName;
  44390. var targetValue;
  44391. if (path.startsWith('object3D.rotation')) {
  44392. value = THREE.Math.degToRad(value);
  44393. }
  44394. // Walk.
  44395. split = splitDot(path);
  44396. targetValue = el;
  44397. for (i = 0; i < split.length - 1; i++) { targetValue = targetValue[split[i]]; }
  44398. propertyName = split[split.length - 1];
  44399. // Raw color.
  44400. if (type === TYPE_COLOR) {
  44401. if ('r' in targetValue[propertyName]) {
  44402. targetValue[propertyName].r = value.r;
  44403. targetValue[propertyName].g = value.g;
  44404. targetValue[propertyName].b = value.b;
  44405. } else {
  44406. targetValue[propertyName].x = value.r;
  44407. targetValue[propertyName].y = value.g;
  44408. targetValue[propertyName].z = value.b;
  44409. }
  44410. return;
  44411. }
  44412. targetValue[propertyName] = value;
  44413. }
  44414. function splitDot (path) {
  44415. if (path in splitCache) { return splitCache[path]; }
  44416. splitCache[path] = path.split('.');
  44417. return splitCache[path];
  44418. }
  44419. function isRawProperty (data) {
  44420. return data.isRawProperty || data.property.startsWith(STRING_COMPONENTS) ||
  44421. data.property.startsWith(STRING_OBJECT3D);
  44422. }
  44423. },{"../core/component":128,"../lib/three":176,"../utils":202,"super-animejs":56}],74:[function(_dereq_,module,exports){
  44424. var registerComponent = _dereq_('../core/component').registerComponent;
  44425. var THREE = _dereq_('../lib/three');
  44426. /**
  44427. * Camera component.
  44428. * Pairs along with camera system to handle tracking the active camera.
  44429. */
  44430. module.exports.Component = registerComponent('camera', {
  44431. schema: {
  44432. active: {default: true},
  44433. far: {default: 10000},
  44434. fov: {default: 80, min: 0},
  44435. near: {default: 0.005, min: 0},
  44436. spectator: {default: false},
  44437. zoom: {default: 1, min: 0}
  44438. },
  44439. /**
  44440. * Initialize three.js camera and add it to the entity.
  44441. * Add reference from scene to this entity as the camera.
  44442. */
  44443. init: function () {
  44444. var camera;
  44445. var el = this.el;
  44446. // Create camera.
  44447. camera = this.camera = new THREE.PerspectiveCamera();
  44448. el.setObject3D('camera', camera);
  44449. },
  44450. /**
  44451. * Update three.js camera.
  44452. */
  44453. update: function (oldData) {
  44454. var data = this.data;
  44455. var camera = this.camera;
  44456. // Update properties.
  44457. camera.aspect = data.aspect || (window.innerWidth / window.innerHeight);
  44458. camera.far = data.far;
  44459. camera.fov = data.fov;
  44460. camera.near = data.near;
  44461. camera.zoom = data.zoom;
  44462. camera.updateProjectionMatrix();
  44463. this.updateActiveCamera(oldData);
  44464. this.updateSpectatorCamera(oldData);
  44465. },
  44466. updateActiveCamera: function (oldData) {
  44467. var data = this.data;
  44468. var el = this.el;
  44469. var system = this.system;
  44470. // Active property did not change.
  44471. if (oldData && oldData.active === data.active || data.spectator) { return; }
  44472. // If `active` property changes, or first update, handle active camera with system.
  44473. if (data.active && system.activeCameraEl !== el) {
  44474. // Camera enabled. Set camera to this camera.
  44475. system.setActiveCamera(el);
  44476. } else if (!data.active && system.activeCameraEl === el) {
  44477. // Camera disabled. Set camera to another camera.
  44478. system.disableActiveCamera();
  44479. }
  44480. },
  44481. updateSpectatorCamera: function (oldData) {
  44482. var data = this.data;
  44483. var el = this.el;
  44484. var system = this.system;
  44485. // spectator property did not change.
  44486. if (oldData && oldData.spectator === data.spectator) { return; }
  44487. // If `spectator` property changes, or first update, handle spectator camera with system.
  44488. if (data.spectator && system.spectatorCameraEl !== el) {
  44489. // Camera enabled. Set camera to this camera.
  44490. system.setSpectatorCamera(el);
  44491. } else if (!data.spectator && system.spectatorCameraEl === el) {
  44492. // Camera disabled. Set camera to another camera.
  44493. system.disableSpectatorCamera();
  44494. }
  44495. },
  44496. /**
  44497. * Remove camera on remove (callback).
  44498. */
  44499. remove: function () {
  44500. this.el.removeObject3D('camera');
  44501. }
  44502. });
  44503. },{"../core/component":128,"../lib/three":176}],75:[function(_dereq_,module,exports){
  44504. /* global THREE */
  44505. var registerComponent = _dereq_('../core/component').registerComponent;
  44506. var utils = _dereq_('../utils/');
  44507. var bind = utils.bind;
  44508. var EVENTS = {
  44509. CLICK: 'click',
  44510. FUSING: 'fusing',
  44511. MOUSEENTER: 'mouseenter',
  44512. MOUSEDOWN: 'mousedown',
  44513. MOUSELEAVE: 'mouseleave',
  44514. MOUSEUP: 'mouseup'
  44515. };
  44516. var STATES = {
  44517. FUSING: 'cursor-fusing',
  44518. HOVERING: 'cursor-hovering',
  44519. HOVERED: 'cursor-hovered'
  44520. };
  44521. var CANVAS_EVENTS = {
  44522. DOWN: ['mousedown', 'touchstart'],
  44523. UP: ['mouseup', 'touchend']
  44524. };
  44525. var WEBXR_EVENTS = {
  44526. DOWN: ['selectstart'],
  44527. UP: ['selectend']
  44528. };
  44529. var CANVAS_HOVER_CLASS = 'a-mouse-cursor-hover';
  44530. /**
  44531. * Cursor component. Applies the raycaster component specifically for starting the raycaster
  44532. * from the camera and pointing from camera's facing direction, and then only returning the
  44533. * closest intersection. Cursor can be fine-tuned by setting raycaster properties.
  44534. *
  44535. * @member {object} fuseTimeout - Timeout to trigger fuse-click.
  44536. * @member {Element} cursorDownEl - Entity that was last mousedowned during current click.
  44537. * @member {object} intersection - Attributes of the current intersection event, including
  44538. * 3D- and 2D-space coordinates. See: http://threejs.org/docs/api/core/Raycaster.html
  44539. * @member {Element} intersectedEl - Currently-intersected entity. Used to keep track to
  44540. * emit events when unintersecting.
  44541. */
  44542. module.exports.Component = registerComponent('cursor', {
  44543. dependencies: ['raycaster'],
  44544. schema: {
  44545. downEvents: {default: []},
  44546. fuse: {default: utils.device.isMobile()},
  44547. fuseTimeout: {default: 1500, min: 0},
  44548. mouseCursorStylesEnabled: {default: true},
  44549. upEvents: {default: []},
  44550. rayOrigin: {default: 'entity', oneOf: ['mouse', 'entity']}
  44551. },
  44552. init: function () {
  44553. var self = this;
  44554. this.fuseTimeout = undefined;
  44555. this.cursorDownEl = null;
  44556. this.intersectedEl = null;
  44557. this.canvasBounds = document.body.getBoundingClientRect();
  44558. this.isCursorDown = false;
  44559. // Debounce.
  44560. this.updateCanvasBounds = utils.debounce(function updateCanvasBounds () {
  44561. self.canvasBounds = self.el.sceneEl.canvas.getBoundingClientRect();
  44562. }, 500);
  44563. this.eventDetail = {};
  44564. this.intersectedEventDetail = {cursorEl: this.el};
  44565. // Bind methods.
  44566. this.onCursorDown = bind(this.onCursorDown, this);
  44567. this.onCursorUp = bind(this.onCursorUp, this);
  44568. this.onIntersection = bind(this.onIntersection, this);
  44569. this.onIntersectionCleared = bind(this.onIntersectionCleared, this);
  44570. this.onMouseMove = bind(this.onMouseMove, this);
  44571. this.onEnterVR = bind(this.onEnterVR, this);
  44572. },
  44573. update: function (oldData) {
  44574. if (this.data.rayOrigin === oldData.rayOrigin) { return; }
  44575. this.updateMouseEventListeners();
  44576. },
  44577. play: function () {
  44578. this.addEventListeners();
  44579. },
  44580. pause: function () {
  44581. this.removeEventListeners();
  44582. },
  44583. remove: function () {
  44584. var el = this.el;
  44585. el.removeState(STATES.HOVERING);
  44586. el.removeState(STATES.FUSING);
  44587. clearTimeout(this.fuseTimeout);
  44588. if (this.intersectedEl) { this.intersectedEl.removeState(STATES.HOVERED); }
  44589. this.removeEventListeners();
  44590. },
  44591. addEventListeners: function () {
  44592. var canvas;
  44593. var data = this.data;
  44594. var el = this.el;
  44595. var self = this;
  44596. function addCanvasListeners () {
  44597. canvas = el.sceneEl.canvas;
  44598. if (data.downEvents.length || data.upEvents.length) { return; }
  44599. CANVAS_EVENTS.DOWN.forEach(function (downEvent) {
  44600. canvas.addEventListener(downEvent, self.onCursorDown);
  44601. });
  44602. CANVAS_EVENTS.UP.forEach(function (upEvent) {
  44603. canvas.addEventListener(upEvent, self.onCursorUp);
  44604. });
  44605. }
  44606. canvas = el.sceneEl.canvas;
  44607. if (canvas) {
  44608. addCanvasListeners();
  44609. } else {
  44610. el.sceneEl.addEventListener('render-target-loaded', addCanvasListeners);
  44611. }
  44612. data.downEvents.forEach(function (downEvent) {
  44613. el.addEventListener(downEvent, self.onCursorDown);
  44614. });
  44615. data.upEvents.forEach(function (upEvent) {
  44616. el.addEventListener(upEvent, self.onCursorUp);
  44617. });
  44618. el.addEventListener('raycaster-intersection', this.onIntersection);
  44619. el.addEventListener('raycaster-intersection-cleared', this.onIntersectionCleared);
  44620. el.sceneEl.addEventListener('rendererresize', this.updateCanvasBounds);
  44621. el.sceneEl.addEventListener('enter-vr', this.onEnterVR);
  44622. window.addEventListener('resize', this.updateCanvasBounds);
  44623. window.addEventListener('scroll', this.updateCanvasBounds);
  44624. this.updateMouseEventListeners();
  44625. },
  44626. removeEventListeners: function () {
  44627. var canvas;
  44628. var data = this.data;
  44629. var el = this.el;
  44630. var self = this;
  44631. canvas = el.sceneEl.canvas;
  44632. if (canvas && !data.downEvents.length && !data.upEvents.length) {
  44633. CANVAS_EVENTS.DOWN.forEach(function (downEvent) {
  44634. canvas.removeEventListener(downEvent, self.onCursorDown);
  44635. });
  44636. CANVAS_EVENTS.UP.forEach(function (upEvent) {
  44637. canvas.removeEventListener(upEvent, self.onCursorUp);
  44638. });
  44639. }
  44640. data.downEvents.forEach(function (downEvent) {
  44641. el.removeEventListener(downEvent, self.onCursorDown);
  44642. });
  44643. data.upEvents.forEach(function (upEvent) {
  44644. el.removeEventListener(upEvent, self.onCursorUp);
  44645. });
  44646. el.removeEventListener('raycaster-intersection', this.onIntersection);
  44647. el.removeEventListener('raycaster-intersection-cleared', this.onIntersectionCleared);
  44648. canvas.removeEventListener('mousemove', this.onMouseMove);
  44649. canvas.removeEventListener('touchstart', this.onMouseMove);
  44650. canvas.removeEventListener('touchmove', this.onMouseMove);
  44651. el.sceneEl.removeEventListener('rendererresize', this.updateCanvasBounds);
  44652. el.sceneEl.removeEventListener('enter-vr', this.onEnterVR);
  44653. window.removeEventListener('resize', this.updateCanvasBounds);
  44654. window.removeEventListener('scroll', this.updateCanvasBounds);
  44655. },
  44656. updateMouseEventListeners: function () {
  44657. var canvas;
  44658. var el = this.el;
  44659. canvas = el.sceneEl.canvas;
  44660. canvas.removeEventListener('mousemove', this.onMouseMove);
  44661. canvas.removeEventListener('touchmove', this.onMouseMove);
  44662. el.setAttribute('raycaster', 'useWorldCoordinates', false);
  44663. if (this.data.rayOrigin !== 'mouse') { return; }
  44664. canvas.addEventListener('mousemove', this.onMouseMove, false);
  44665. canvas.addEventListener('touchmove', this.onMouseMove, false);
  44666. el.setAttribute('raycaster', 'useWorldCoordinates', true);
  44667. this.updateCanvasBounds();
  44668. },
  44669. onMouseMove: (function () {
  44670. var direction = new THREE.Vector3();
  44671. var mouse = new THREE.Vector2();
  44672. var origin = new THREE.Vector3();
  44673. var rayCasterConfig = {origin: origin, direction: direction};
  44674. return function (evt) {
  44675. var bounds = this.canvasBounds;
  44676. var camera = this.el.sceneEl.camera;
  44677. var left;
  44678. var point;
  44679. var top;
  44680. camera.parent.updateMatrixWorld();
  44681. // Calculate mouse position based on the canvas element
  44682. if (evt.type === 'touchmove' || evt.type === 'touchstart') {
  44683. // Track the first touch for simplicity.
  44684. point = evt.touches.item(0);
  44685. } else {
  44686. point = evt;
  44687. }
  44688. left = point.clientX - bounds.left;
  44689. top = point.clientY - bounds.top;
  44690. mouse.x = (left / bounds.width) * 2 - 1;
  44691. mouse.y = -(top / bounds.height) * 2 + 1;
  44692. origin.setFromMatrixPosition(camera.matrixWorld);
  44693. direction.set(mouse.x, mouse.y, 0.5).unproject(camera).sub(origin).normalize();
  44694. this.el.setAttribute('raycaster', rayCasterConfig);
  44695. if (evt.type === 'touchmove') { evt.preventDefault(); }
  44696. };
  44697. })(),
  44698. /**
  44699. * Trigger mousedown and keep track of the mousedowned entity.
  44700. */
  44701. onCursorDown: function (evt) {
  44702. this.isCursorDown = true;
  44703. // Raycast again for touch.
  44704. if (this.data.rayOrigin === 'mouse' && evt.type === 'touchstart') {
  44705. this.onMouseMove(evt);
  44706. this.el.components.raycaster.checkIntersections();
  44707. evt.preventDefault();
  44708. }
  44709. this.twoWayEmit(EVENTS.MOUSEDOWN);
  44710. this.cursorDownEl = this.intersectedEl;
  44711. },
  44712. /**
  44713. * Trigger mouseup if:
  44714. * - Not fusing (mobile has no mouse).
  44715. * - Currently intersecting an entity.
  44716. * - Currently-intersected entity is the same as the one when mousedown was triggered,
  44717. * in case user mousedowned one entity, dragged to another, and mouseupped.
  44718. */
  44719. onCursorUp: function (evt) {
  44720. if (!this.isCursorDown) { return; }
  44721. this.isCursorDown = false;
  44722. var data = this.data;
  44723. this.twoWayEmit(EVENTS.MOUSEUP);
  44724. // If intersected entity has changed since the cursorDown, still emit mouseUp on the
  44725. // previously cursorUp entity.
  44726. if (this.cursorDownEl && this.cursorDownEl !== this.intersectedEl) {
  44727. this.intersectedEventDetail.intersection = null;
  44728. this.cursorDownEl.emit(EVENTS.MOUSEUP, this.intersectedEventDetail);
  44729. }
  44730. if ((!data.fuse || data.rayOrigin === 'mouse') &&
  44731. this.intersectedEl && this.cursorDownEl === this.intersectedEl) {
  44732. this.twoWayEmit(EVENTS.CLICK);
  44733. }
  44734. this.cursorDownEl = null;
  44735. if (evt.type === 'touchend') { evt.preventDefault(); }
  44736. },
  44737. /**
  44738. * Handle intersection.
  44739. */
  44740. onIntersection: function (evt) {
  44741. var currentIntersection;
  44742. var cursorEl = this.el;
  44743. var index;
  44744. var intersectedEl;
  44745. var intersection;
  44746. // Select closest object, excluding the cursor.
  44747. index = evt.detail.els[0] === cursorEl ? 1 : 0;
  44748. intersection = evt.detail.intersections[index];
  44749. intersectedEl = evt.detail.els[index];
  44750. // If cursor is the only intersected object, ignore the event.
  44751. if (!intersectedEl) { return; }
  44752. // Already intersecting this entity.
  44753. if (this.intersectedEl === intersectedEl) { return; }
  44754. // Ignore events further away than active intersection.
  44755. if (this.intersectedEl) {
  44756. currentIntersection = this.el.components.raycaster.getIntersection(this.intersectedEl);
  44757. if (currentIntersection && currentIntersection.distance <= intersection.distance) { return; }
  44758. }
  44759. // Unset current intersection.
  44760. this.clearCurrentIntersection(true);
  44761. this.setIntersection(intersectedEl, intersection);
  44762. },
  44763. /**
  44764. * Handle intersection cleared.
  44765. */
  44766. onIntersectionCleared: function (evt) {
  44767. var clearedEls = evt.detail.clearedEls;
  44768. // Check if the current intersection has ended
  44769. if (clearedEls.indexOf(this.intersectedEl) === -1) { return; }
  44770. this.clearCurrentIntersection();
  44771. },
  44772. onEnterVR: function () {
  44773. this.clearCurrentIntersection(true);
  44774. var xrSession = this.el.sceneEl.xrSession;
  44775. var self = this;
  44776. if (!xrSession) { return; }
  44777. WEBXR_EVENTS.DOWN.forEach(function (downEvent) {
  44778. xrSession.addEventListener(downEvent, self.onCursorDown);
  44779. });
  44780. WEBXR_EVENTS.UP.forEach(function (upEvent) {
  44781. xrSession.addEventListener(upEvent, self.onCursorUp);
  44782. });
  44783. },
  44784. setIntersection: function (intersectedEl, intersection) {
  44785. var cursorEl = this.el;
  44786. var data = this.data;
  44787. var self = this;
  44788. // Already intersecting.
  44789. if (this.intersectedEl === intersectedEl) { return; }
  44790. // Set new intersection.
  44791. this.intersectedEl = intersectedEl;
  44792. // Hovering.
  44793. cursorEl.addState(STATES.HOVERING);
  44794. intersectedEl.addState(STATES.HOVERED);
  44795. this.twoWayEmit(EVENTS.MOUSEENTER);
  44796. if (this.data.mouseCursorStylesEnabled && this.data.rayOrigin === 'mouse') {
  44797. this.el.sceneEl.canvas.classList.add(CANVAS_HOVER_CLASS);
  44798. }
  44799. // Begin fuse if necessary.
  44800. if (data.fuseTimeout === 0 || !data.fuse) { return; }
  44801. cursorEl.addState(STATES.FUSING);
  44802. this.twoWayEmit(EVENTS.FUSING);
  44803. this.fuseTimeout = setTimeout(function fuse () {
  44804. cursorEl.removeState(STATES.FUSING);
  44805. self.twoWayEmit(EVENTS.CLICK);
  44806. }, data.fuseTimeout);
  44807. },
  44808. clearCurrentIntersection: function (ignoreRemaining) {
  44809. var index;
  44810. var intersection;
  44811. var intersections;
  44812. var cursorEl = this.el;
  44813. // Nothing to be cleared.
  44814. if (!this.intersectedEl) { return; }
  44815. // No longer hovering (or fusing).
  44816. this.intersectedEl.removeState(STATES.HOVERED);
  44817. cursorEl.removeState(STATES.HOVERING);
  44818. cursorEl.removeState(STATES.FUSING);
  44819. this.twoWayEmit(EVENTS.MOUSELEAVE);
  44820. if (this.data.mouseCursorStylesEnabled && this.data.rayOrigin === 'mouse') {
  44821. this.el.sceneEl.canvas.classList.remove(CANVAS_HOVER_CLASS);
  44822. }
  44823. // Unset intersected entity (after emitting the event).
  44824. this.intersectedEl = null;
  44825. // Clear fuseTimeout.
  44826. clearTimeout(this.fuseTimeout);
  44827. // Set intersection to another raycasted element if any.
  44828. if (ignoreRemaining === true) { return; }
  44829. intersections = this.el.components.raycaster.intersections;
  44830. if (intersections.length === 0) { return; }
  44831. // Exclude the cursor.
  44832. index = intersections[0].object.el === cursorEl ? 1 : 0;
  44833. intersection = intersections[index];
  44834. if (!intersection) { return; }
  44835. this.setIntersection(intersection.object.el, intersection);
  44836. },
  44837. /**
  44838. * Helper to emit on both the cursor and the intersected entity (if exists).
  44839. */
  44840. twoWayEmit: function (evtName) {
  44841. var el = this.el;
  44842. var intersectedEl = this.intersectedEl;
  44843. var intersection;
  44844. intersection = this.el.components.raycaster.getIntersection(intersectedEl);
  44845. this.eventDetail.intersectedEl = intersectedEl;
  44846. this.eventDetail.intersection = intersection;
  44847. el.emit(evtName, this.eventDetail);
  44848. if (!intersectedEl) { return; }
  44849. this.intersectedEventDetail.intersection = intersection;
  44850. intersectedEl.emit(evtName, this.intersectedEventDetail);
  44851. }
  44852. });
  44853. },{"../core/component":128,"../utils/":202}],76:[function(_dereq_,module,exports){
  44854. var registerComponent = _dereq_('../core/component').registerComponent;
  44855. var bind = _dereq_('../utils/bind');
  44856. var trackedControlsUtils = _dereq_('../utils/tracked-controls');
  44857. var checkControllerPresentAndSetup = trackedControlsUtils.checkControllerPresentAndSetup;
  44858. var emitIfAxesChanged = trackedControlsUtils.emitIfAxesChanged;
  44859. var onButtonEvent = trackedControlsUtils.onButtonEvent;
  44860. var DAYDREAM_CONTROLLER_MODEL_BASE_URL = 'https://cdn.aframe.io/controllers/google/';
  44861. var DAYDREAM_CONTROLLER_MODEL_OBJ_URL = DAYDREAM_CONTROLLER_MODEL_BASE_URL + 'vr_controller_daydream.obj';
  44862. var DAYDREAM_CONTROLLER_MODEL_OBJ_MTL = DAYDREAM_CONTROLLER_MODEL_BASE_URL + 'vr_controller_daydream.mtl';
  44863. var isWebXRAvailable = _dereq_('../utils/').device.isWebXRAvailable;
  44864. var GAMEPAD_ID_WEBXR = 'google-daydream';
  44865. var GAMEPAD_ID_WEBVR = 'Daydream Controller';
  44866. var GAMEPAD_ID_PREFIX = isWebXRAvailable ? GAMEPAD_ID_WEBXR : GAMEPAD_ID_WEBVR;
  44867. /**
  44868. * Daydream controls.
  44869. * Interface with Daydream controller and map Gamepad events to
  44870. * controller buttons: trackpad, menu, system
  44871. * Load a controller model and highlight the pressed buttons.
  44872. */
  44873. module.exports.Component = registerComponent('daydream-controls', {
  44874. schema: {
  44875. hand: {default: ''}, // This informs the degenerate arm model.
  44876. buttonColor: {type: 'color', default: '#000000'},
  44877. buttonTouchedColor: {type: 'color', default: '#777777'},
  44878. buttonHighlightColor: {type: 'color', default: '#FFFFFF'},
  44879. model: {default: true},
  44880. orientationOffset: {type: 'vec3'},
  44881. armModel: {default: true}
  44882. },
  44883. /**
  44884. * Button IDs:
  44885. * 0 - trackpad
  44886. * 1 - menu (never dispatched on this layer)
  44887. * 2 - system (never dispatched on this layer)
  44888. */
  44889. mapping: {
  44890. axes: {trackpad: [0, 1]},
  44891. buttons: ['trackpad', 'menu', 'system']
  44892. },
  44893. bindMethods: function () {
  44894. this.onModelLoaded = bind(this.onModelLoaded, this);
  44895. this.onControllersUpdate = bind(this.onControllersUpdate, this);
  44896. this.checkIfControllerPresent = bind(this.checkIfControllerPresent, this);
  44897. this.removeControllersUpdateListener = bind(this.removeControllersUpdateListener, this);
  44898. this.onAxisMoved = bind(this.onAxisMoved, this);
  44899. },
  44900. init: function () {
  44901. var self = this;
  44902. this.onButtonChanged = bind(this.onButtonChanged, this);
  44903. this.onButtonDown = function (evt) { onButtonEvent(evt.detail.id, 'down', self); };
  44904. this.onButtonUp = function (evt) { onButtonEvent(evt.detail.id, 'up', self); };
  44905. this.onButtonTouchStart = function (evt) { onButtonEvent(evt.detail.id, 'touchstart', self); };
  44906. this.onButtonTouchEnd = function (evt) { onButtonEvent(evt.detail.id, 'touchend', self); };
  44907. this.controllerPresent = false;
  44908. this.lastControllerCheck = 0;
  44909. this.bindMethods();
  44910. },
  44911. addEventListeners: function () {
  44912. var el = this.el;
  44913. el.addEventListener('buttonchanged', this.onButtonChanged);
  44914. el.addEventListener('buttondown', this.onButtonDown);
  44915. el.addEventListener('buttonup', this.onButtonUp);
  44916. el.addEventListener('touchstart', this.onButtonTouchStart);
  44917. el.addEventListener('touchend', this.onButtonTouchEnd);
  44918. el.addEventListener('model-loaded', this.onModelLoaded);
  44919. el.addEventListener('axismove', this.onAxisMoved);
  44920. this.controllerEventsActive = true;
  44921. },
  44922. removeEventListeners: function () {
  44923. var el = this.el;
  44924. el.removeEventListener('buttonchanged', this.onButtonChanged);
  44925. el.removeEventListener('buttondown', this.onButtonDown);
  44926. el.removeEventListener('buttonup', this.onButtonUp);
  44927. el.removeEventListener('touchstart', this.onButtonTouchStart);
  44928. el.removeEventListener('touchend', this.onButtonTouchEnd);
  44929. el.removeEventListener('model-loaded', this.onModelLoaded);
  44930. el.removeEventListener('axismove', this.onAxisMoved);
  44931. this.controllerEventsActive = false;
  44932. },
  44933. checkIfControllerPresent: function () {
  44934. checkControllerPresentAndSetup(this, GAMEPAD_ID_PREFIX, {hand: this.data.hand});
  44935. },
  44936. play: function () {
  44937. this.checkIfControllerPresent();
  44938. this.addControllersUpdateListener();
  44939. },
  44940. pause: function () {
  44941. this.removeEventListeners();
  44942. this.removeControllersUpdateListener();
  44943. },
  44944. injectTrackedControls: function () {
  44945. var el = this.el;
  44946. var data = this.data;
  44947. el.setAttribute('tracked-controls', {
  44948. armModel: data.armModel,
  44949. hand: data.hand,
  44950. idPrefix: GAMEPAD_ID_PREFIX,
  44951. orientationOffset: data.orientationOffset
  44952. });
  44953. if (!this.data.model) { return; }
  44954. this.el.setAttribute('obj-model', {
  44955. obj: DAYDREAM_CONTROLLER_MODEL_OBJ_URL,
  44956. mtl: DAYDREAM_CONTROLLER_MODEL_OBJ_MTL
  44957. });
  44958. },
  44959. addControllersUpdateListener: function () {
  44960. this.el.sceneEl.addEventListener('controllersupdated', this.onControllersUpdate, false);
  44961. },
  44962. removeControllersUpdateListener: function () {
  44963. this.el.sceneEl.removeEventListener('controllersupdated', this.onControllersUpdate, false);
  44964. },
  44965. onControllersUpdate: function () {
  44966. this.checkIfControllerPresent();
  44967. },
  44968. onModelLoaded: function (evt) {
  44969. var controllerObject3D = evt.detail.model;
  44970. var buttonMeshes;
  44971. if (!this.data.model) { return; }
  44972. buttonMeshes = this.buttonMeshes = {};
  44973. buttonMeshes.menu = controllerObject3D.getObjectByName('AppButton_AppButton_Cylinder.004');
  44974. buttonMeshes.system = controllerObject3D.getObjectByName('HomeButton_HomeButton_Cylinder.005');
  44975. buttonMeshes.trackpad = controllerObject3D.getObjectByName('TouchPad_TouchPad_Cylinder.003');
  44976. // Offset pivot point.
  44977. controllerObject3D.position.set(0, 0, -0.04);
  44978. },
  44979. onAxisMoved: function (evt) {
  44980. emitIfAxesChanged(this, this.mapping.axes, evt);
  44981. },
  44982. onButtonChanged: function (evt) {
  44983. var button = this.mapping.buttons[evt.detail.id];
  44984. if (!button) return;
  44985. // Pass along changed event with button state, using button mapping for convenience.
  44986. this.el.emit(button + 'changed', evt.detail.state);
  44987. },
  44988. updateModel: function (buttonName, evtName) {
  44989. if (!this.data.model) { return; }
  44990. this.updateButtonModel(buttonName, evtName);
  44991. },
  44992. updateButtonModel: function (buttonName, state) {
  44993. var buttonMeshes = this.buttonMeshes;
  44994. if (!buttonMeshes || !buttonMeshes[buttonName]) { return; }
  44995. var color;
  44996. switch (state) {
  44997. case 'down':
  44998. color = this.data.buttonHighlightColor;
  44999. break;
  45000. case 'touchstart':
  45001. color = this.data.buttonTouchedColor;
  45002. break;
  45003. default:
  45004. color = this.data.buttonColor;
  45005. }
  45006. buttonMeshes[buttonName].material.color.set(color);
  45007. }
  45008. });
  45009. },{"../core/component":128,"../utils/":202,"../utils/bind":196,"../utils/tracked-controls":210}],77:[function(_dereq_,module,exports){
  45010. var registerComponent = _dereq_('../core/component').registerComponent;
  45011. var bind = _dereq_('../utils/bind');
  45012. var trackedControlsUtils = _dereq_('../utils/tracked-controls');
  45013. var checkControllerPresentAndSetup = trackedControlsUtils.checkControllerPresentAndSetup;
  45014. var emitIfAxesChanged = trackedControlsUtils.emitIfAxesChanged;
  45015. var onButtonEvent = trackedControlsUtils.onButtonEvent;
  45016. var isWebXRAvailable = _dereq_('../utils/').device.isWebXRAvailable;
  45017. var GEARVR_CONTROLLER_MODEL_BASE_URL = 'https://cdn.aframe.io/controllers/samsung/';
  45018. var GEARVR_CONTROLLER_MODEL_OBJ_URL = GEARVR_CONTROLLER_MODEL_BASE_URL + 'gear_vr_controller.obj';
  45019. var GEARVR_CONTROLLER_MODEL_OBJ_MTL = GEARVR_CONTROLLER_MODEL_BASE_URL + 'gear_vr_controller.mtl';
  45020. var GAMEPAD_ID_WEBXR = 'samsung-gearvr';
  45021. var GAMEPAD_ID_WEBVR = 'Gear VR';
  45022. // Prefix for Gen1 and Gen2 Oculus Touch Controllers.
  45023. var GAMEPAD_ID_PREFIX = isWebXRAvailable ? GAMEPAD_ID_WEBXR : GAMEPAD_ID_WEBVR;
  45024. /**
  45025. * Button indices:
  45026. * 0 - trackpad
  45027. * 1 - trigger
  45028. *
  45029. * Axis:
  45030. * 0 - trackpad x
  45031. * 1 - trackpad y
  45032. */
  45033. var INPUT_MAPPING_WEBVR = {
  45034. axes: {trackpad: [0, 1]},
  45035. buttons: ['trackpad', 'trigger']
  45036. };
  45037. /**
  45038. * Button indices:
  45039. * 0 - trigger
  45040. * 1 - none
  45041. * 2 - touchpad
  45042. * 3 - menu
  45043. *
  45044. * Axis:
  45045. * 0 - touchpad x
  45046. * 1 - touchpad y
  45047. * Reference: https://github.com/immersive-web/webxr-input-profiles/blob/master/packages/registry/profiles/oculus/oculus-go.json
  45048. */
  45049. var INPUT_MAPPING_WEBXR = {
  45050. left: {
  45051. axes: {touchpad: [0, 1]},
  45052. buttons: ['trigger', 'none', 'touchpad', 'menu']
  45053. },
  45054. right: {
  45055. axes: {touchpad: [0, 1]},
  45056. buttons: ['trigger', 'none', 'touchpad', 'menu']
  45057. }
  45058. };
  45059. var INPUT_MAPPING = isWebXRAvailable ? INPUT_MAPPING_WEBXR : INPUT_MAPPING_WEBVR;
  45060. /**
  45061. * Gear VR controls.
  45062. * Interface with Gear VR controller and map Gamepad events to
  45063. * controller buttons: trackpad, trigger
  45064. * Load a controller model and highlight the pressed buttons.
  45065. */
  45066. module.exports.Component = registerComponent('gearvr-controls', {
  45067. schema: {
  45068. hand: {default: ''}, // This informs the degenerate arm model.
  45069. buttonColor: {type: 'color', default: '#000000'},
  45070. buttonTouchedColor: {type: 'color', default: '#777777'},
  45071. buttonHighlightColor: {type: 'color', default: '#FFFFFF'},
  45072. model: {default: true},
  45073. orientationOffset: {type: 'vec3'},
  45074. armModel: {default: true}
  45075. },
  45076. /**
  45077. * Button IDs:
  45078. * 0 - trackpad
  45079. * 1 - trigger
  45080. */
  45081. mapping: INPUT_MAPPING,
  45082. bindMethods: function () {
  45083. this.onModelLoaded = bind(this.onModelLoaded, this);
  45084. this.onControllersUpdate = bind(this.onControllersUpdate, this);
  45085. this.checkIfControllerPresent = bind(this.checkIfControllerPresent, this);
  45086. this.removeControllersUpdateListener = bind(this.removeControllersUpdateListener, this);
  45087. this.onAxisMoved = bind(this.onAxisMoved, this);
  45088. },
  45089. init: function () {
  45090. var self = this;
  45091. this.onButtonChanged = bind(this.onButtonChanged, this);
  45092. this.onButtonDown = function (evt) { onButtonEvent(evt.detail.id, 'down', self); };
  45093. this.onButtonUp = function (evt) { onButtonEvent(evt.detail.id, 'up', self); };
  45094. this.onButtonTouchStart = function (evt) { onButtonEvent(evt.detail.id, 'touchstart', self); };
  45095. this.onButtonTouchEnd = function (evt) { onButtonEvent(evt.detail.id, 'touchend', self); };
  45096. this.controllerPresent = false;
  45097. this.lastControllerCheck = 0;
  45098. this.bindMethods();
  45099. },
  45100. addEventListeners: function () {
  45101. var el = this.el;
  45102. el.addEventListener('buttonchanged', this.onButtonChanged);
  45103. el.addEventListener('buttondown', this.onButtonDown);
  45104. el.addEventListener('buttonup', this.onButtonUp);
  45105. el.addEventListener('touchstart', this.onButtonTouchStart);
  45106. el.addEventListener('touchend', this.onButtonTouchEnd);
  45107. el.addEventListener('model-loaded', this.onModelLoaded);
  45108. el.addEventListener('axismove', this.onAxisMoved);
  45109. this.controllerEventsActive = true;
  45110. },
  45111. removeEventListeners: function () {
  45112. var el = this.el;
  45113. el.removeEventListener('buttonchanged', this.onButtonChanged);
  45114. el.removeEventListener('buttondown', this.onButtonDown);
  45115. el.removeEventListener('buttonup', this.onButtonUp);
  45116. el.removeEventListener('touchstart', this.onButtonTouchStart);
  45117. el.removeEventListener('touchend', this.onButtonTouchEnd);
  45118. el.removeEventListener('model-loaded', this.onModelLoaded);
  45119. el.removeEventListener('axismove', this.onAxisMoved);
  45120. this.controllerEventsActive = false;
  45121. },
  45122. checkIfControllerPresent: function () {
  45123. checkControllerPresentAndSetup(this, GAMEPAD_ID_PREFIX,
  45124. this.data.hand ? {hand: this.data.hand} : {});
  45125. },
  45126. play: function () {
  45127. this.checkIfControllerPresent();
  45128. this.addControllersUpdateListener();
  45129. },
  45130. pause: function () {
  45131. this.removeEventListeners();
  45132. this.removeControllersUpdateListener();
  45133. },
  45134. injectTrackedControls: function () {
  45135. var el = this.el;
  45136. var data = this.data;
  45137. el.setAttribute('tracked-controls', {
  45138. armModel: data.armModel,
  45139. hand: data.hand,
  45140. idPrefix: GAMEPAD_ID_PREFIX,
  45141. id: GAMEPAD_ID_PREFIX,
  45142. orientationOffset: data.orientationOffset
  45143. });
  45144. if (!this.data.model) { return; }
  45145. this.el.setAttribute('obj-model', {
  45146. obj: GEARVR_CONTROLLER_MODEL_OBJ_URL,
  45147. mtl: GEARVR_CONTROLLER_MODEL_OBJ_MTL
  45148. });
  45149. },
  45150. addControllersUpdateListener: function () {
  45151. this.el.sceneEl.addEventListener('controllersupdated', this.onControllersUpdate, false);
  45152. },
  45153. removeControllersUpdateListener: function () {
  45154. this.el.sceneEl.removeEventListener('controllersupdated', this.onControllersUpdate, false);
  45155. },
  45156. onControllersUpdate: function () {
  45157. this.checkIfControllerPresent();
  45158. },
  45159. // No need for onButtonChanged, since Gear VR controller has no analog buttons.
  45160. onModelLoaded: function (evt) {
  45161. var controllerObject3D = evt.detail.model;
  45162. var buttonMeshes;
  45163. if (!this.data.model) { return; }
  45164. buttonMeshes = this.buttonMeshes = {};
  45165. buttonMeshes.trigger = controllerObject3D.children[2];
  45166. buttonMeshes.trackpad = controllerObject3D.children[1];
  45167. },
  45168. onButtonChanged: function (evt) {
  45169. var button = this.mapping.buttons[evt.detail.id];
  45170. if (!button) return;
  45171. // Pass along changed event with button state, using button mapping for convenience.
  45172. this.el.emit(button + 'changed', evt.detail.state);
  45173. },
  45174. onAxisMoved: function (evt) {
  45175. emitIfAxesChanged(this, this.mapping.axes, evt);
  45176. },
  45177. updateModel: function (buttonName, evtName) {
  45178. if (!this.data.model) { return; }
  45179. this.updateButtonModel(buttonName, evtName);
  45180. },
  45181. updateButtonModel: function (buttonName, state) {
  45182. var buttonMeshes = this.buttonMeshes;
  45183. if (!buttonMeshes || !buttonMeshes[buttonName]) { return; }
  45184. var color;
  45185. switch (state) {
  45186. case 'down':
  45187. color = this.data.buttonHighlightColor;
  45188. break;
  45189. case 'touchstart':
  45190. color = this.data.buttonTouchedColor;
  45191. break;
  45192. default:
  45193. color = this.data.buttonColor;
  45194. }
  45195. buttonMeshes[buttonName].material.color.set(color);
  45196. }
  45197. });
  45198. },{"../core/component":128,"../utils/":202,"../utils/bind":196,"../utils/tracked-controls":210}],78:[function(_dereq_,module,exports){
  45199. var registerComponent = _dereq_('../core/component').registerComponent;
  45200. var bind = _dereq_('../utils/bind');
  45201. var trackedControlsUtils = _dereq_('../utils/tracked-controls');
  45202. var checkControllerPresentAndSetup = trackedControlsUtils.checkControllerPresentAndSetup;
  45203. var emitIfAxesChanged = trackedControlsUtils.emitIfAxesChanged;
  45204. var onButtonEvent = trackedControlsUtils.onButtonEvent;
  45205. var GAMEPAD_ID_PREFIX = 'generic';
  45206. /**
  45207. * Button indices:
  45208. * 0 - trigger
  45209. * 1 - squeeze
  45210. * 2 - touchpad
  45211. * 3 - thumbstick
  45212. *
  45213. * Axis:
  45214. * 0 - touchpad
  45215. * 1 - thumbstick
  45216. *
  45217. */
  45218. var INPUT_MAPPING = {
  45219. axes: {
  45220. touchpad: [0, 1],
  45221. thumbstick: [2, 3]
  45222. },
  45223. buttons: ['trigger', 'squeeze', 'touchpad', 'thumbstick']
  45224. };
  45225. /**
  45226. * Oculus Go controls.
  45227. * Interface with Oculus Go controller and map Gamepad events to
  45228. * controller buttons: trackpad, trigger
  45229. * Load a controller model and highlight the pressed buttons.
  45230. */
  45231. module.exports.Component = registerComponent('generic-tracked-controller-controls', {
  45232. schema: {
  45233. hand: {default: ''}, // This informs the degenerate arm model.
  45234. defaultModel: {default: true},
  45235. defaultModelColor: {default: 'gray'},
  45236. orientationOffset: {type: 'vec3'}
  45237. },
  45238. /**
  45239. * Button IDs:
  45240. * 0 - trackpad
  45241. * 1 - trigger
  45242. */
  45243. mapping: INPUT_MAPPING,
  45244. bindMethods: function () {
  45245. this.onControllersUpdate = bind(this.onControllersUpdate, this);
  45246. this.checkIfControllerPresent = bind(this.checkIfControllerPresent, this);
  45247. this.removeControllersUpdateListener = bind(this.removeControllersUpdateListener, this);
  45248. this.onAxisMoved = bind(this.onAxisMoved, this);
  45249. },
  45250. init: function () {
  45251. var self = this;
  45252. this.onButtonChanged = bind(this.onButtonChanged, this);
  45253. this.onButtonDown = function (evt) { onButtonEvent(evt.detail.id, 'down', self); };
  45254. this.onButtonUp = function (evt) { onButtonEvent(evt.detail.id, 'up', self); };
  45255. this.onButtonTouchStart = function (evt) { onButtonEvent(evt.detail.id, 'touchstart', self); };
  45256. this.onButtonTouchEnd = function (evt) { onButtonEvent(evt.detail.id, 'touchend', self); };
  45257. this.controllerPresent = false;
  45258. this.lastControllerCheck = 0;
  45259. this.rendererSystem = this.el.sceneEl.systems.renderer;
  45260. this.bindMethods();
  45261. },
  45262. addEventListeners: function () {
  45263. var el = this.el;
  45264. el.addEventListener('buttonchanged', this.onButtonChanged);
  45265. el.addEventListener('buttondown', this.onButtonDown);
  45266. el.addEventListener('buttonup', this.onButtonUp);
  45267. el.addEventListener('touchstart', this.onButtonTouchStart);
  45268. el.addEventListener('touchend', this.onButtonTouchEnd);
  45269. el.addEventListener('axismove', this.onAxisMoved);
  45270. this.controllerEventsActive = true;
  45271. },
  45272. removeEventListeners: function () {
  45273. var el = this.el;
  45274. el.removeEventListener('buttonchanged', this.onButtonChanged);
  45275. el.removeEventListener('buttondown', this.onButtonDown);
  45276. el.removeEventListener('buttonup', this.onButtonUp);
  45277. el.removeEventListener('touchstart', this.onButtonTouchStart);
  45278. el.removeEventListener('touchend', this.onButtonTouchEnd);
  45279. el.removeEventListener('axismove', this.onAxisMoved);
  45280. this.controllerEventsActive = false;
  45281. },
  45282. checkIfControllerPresent: function () {
  45283. var data = this.data;
  45284. var hand = data.hand ? data.hand : undefined;
  45285. checkControllerPresentAndSetup(
  45286. this, GAMEPAD_ID_PREFIX,
  45287. {hand: hand, iterateControllerProfiles: true});
  45288. },
  45289. play: function () {
  45290. this.checkIfControllerPresent();
  45291. this.addControllersUpdateListener();
  45292. },
  45293. pause: function () {
  45294. this.removeEventListeners();
  45295. this.removeControllersUpdateListener();
  45296. },
  45297. injectTrackedControls: function () {
  45298. var el = this.el;
  45299. var data = this.data;
  45300. // Do nothing if tracked-controls already set.
  45301. // Generic controls have the lowest precedence.
  45302. if (this.el.components['tracked-controls']) { return; }
  45303. el.setAttribute('tracked-controls', {
  45304. hand: data.hand,
  45305. idPrefix: GAMEPAD_ID_PREFIX,
  45306. orientationOffset: data.orientationOffset,
  45307. iterateControllerProfiles: true
  45308. });
  45309. if (!this.data.defaultModel) { return; }
  45310. this.initDefaultModel();
  45311. },
  45312. addControllersUpdateListener: function () {
  45313. this.el.sceneEl.addEventListener('controllersupdated', this.onControllersUpdate, false);
  45314. },
  45315. removeControllersUpdateListener: function () {
  45316. this.el.sceneEl.removeEventListener('controllersupdated', this.onControllersUpdate, false);
  45317. },
  45318. onControllersUpdate: function () {
  45319. this.checkIfControllerPresent();
  45320. },
  45321. onButtonChanged: function (evt) {
  45322. var button = this.mapping.buttons[evt.detail.id];
  45323. if (!button) return;
  45324. // Pass along changed event with button state, using button mapping for convenience.
  45325. this.el.emit(button + 'changed', evt.detail.state);
  45326. },
  45327. onAxisMoved: function (evt) {
  45328. emitIfAxesChanged(this, this.mapping.axes, evt);
  45329. },
  45330. initDefaultModel: function () {
  45331. var modelEl = this.modelEl = document.createElement('a-entity');
  45332. modelEl.setAttribute('geometry', {
  45333. primitive: 'sphere',
  45334. radius: 0.03
  45335. });
  45336. modelEl.setAttribute('material', {color: this.data.color});
  45337. this.el.appendChild(modelEl);
  45338. }
  45339. });
  45340. },{"../core/component":128,"../utils/bind":196,"../utils/tracked-controls":210}],79:[function(_dereq_,module,exports){
  45341. var geometries = _dereq_('../core/geometry').geometries;
  45342. var geometryNames = _dereq_('../core/geometry').geometryNames;
  45343. var registerComponent = _dereq_('../core/component').registerComponent;
  45344. var THREE = _dereq_('../lib/three');
  45345. var dummyGeometry = new THREE.Geometry();
  45346. /**
  45347. * Geometry component. Combined with material component to make a mesh in 3D object.
  45348. * Extended with registered geometries.
  45349. */
  45350. module.exports.Component = registerComponent('geometry', {
  45351. schema: {
  45352. buffer: {default: true},
  45353. primitive: {default: 'box', oneOf: geometryNames, schemaChange: true},
  45354. skipCache: {default: false}
  45355. },
  45356. init: function () {
  45357. this.geometry = null;
  45358. },
  45359. /**
  45360. * Talk to geometry system to get or create geometry.
  45361. */
  45362. update: function (previousData) {
  45363. var data = this.data;
  45364. var el = this.el;
  45365. var mesh;
  45366. var system = this.system;
  45367. // Dispose old geometry if we created one.
  45368. if (this.geometry) {
  45369. system.unuseGeometry(previousData);
  45370. this.geometry = null;
  45371. }
  45372. // Create new geometry.
  45373. this.geometry = system.getOrCreateGeometry(data);
  45374. // Set on mesh. If mesh does not exist, create it.
  45375. mesh = el.getObject3D('mesh');
  45376. if (mesh) {
  45377. mesh.geometry = this.geometry;
  45378. } else {
  45379. mesh = new THREE.Mesh();
  45380. mesh.geometry = this.geometry;
  45381. el.setObject3D('mesh', mesh);
  45382. }
  45383. },
  45384. /**
  45385. * Tell geometry system that entity is no longer using the geometry.
  45386. * Unset the geometry on the mesh
  45387. */
  45388. remove: function () {
  45389. this.system.unuseGeometry(this.data);
  45390. this.el.getObject3D('mesh').geometry = dummyGeometry;
  45391. this.geometry = null;
  45392. },
  45393. /**
  45394. * Update geometry component schema based on geometry type.
  45395. */
  45396. updateSchema: function (data) {
  45397. var currentGeometryType = this.oldData && this.oldData.primitive;
  45398. var newGeometryType = data.primitive;
  45399. var schema = geometries[newGeometryType] && geometries[newGeometryType].schema;
  45400. // Geometry has no schema.
  45401. if (!schema) { throw new Error('Unknown geometry schema `' + newGeometryType + '`'); }
  45402. // Nothing has changed.
  45403. if (currentGeometryType && currentGeometryType === newGeometryType) { return; }
  45404. this.extendSchema(schema);
  45405. }
  45406. });
  45407. },{"../core/component":128,"../core/geometry":129,"../lib/three":176}],80:[function(_dereq_,module,exports){
  45408. var registerComponent = _dereq_('../core/component').registerComponent;
  45409. var THREE = _dereq_('../lib/three');
  45410. var utils = _dereq_('../utils/');
  45411. var warn = utils.debug('components:gltf-model:warn');
  45412. /**
  45413. * glTF model loader.
  45414. */
  45415. module.exports.Component = registerComponent('gltf-model', {
  45416. schema: {type: 'model'},
  45417. init: function () {
  45418. var dracoLoader = this.system.getDRACOLoader();
  45419. this.model = null;
  45420. this.loader = new THREE.GLTFLoader();
  45421. if (dracoLoader) {
  45422. this.loader.setDRACOLoader(dracoLoader);
  45423. }
  45424. },
  45425. update: function () {
  45426. var self = this;
  45427. var el = this.el;
  45428. var src = this.data;
  45429. if (!src) { return; }
  45430. this.remove();
  45431. this.loader.load(src, function gltfLoaded (gltfModel) {
  45432. self.model = gltfModel.scene || gltfModel.scenes[0];
  45433. self.model.animations = gltfModel.animations;
  45434. el.setObject3D('mesh', self.model);
  45435. el.emit('model-loaded', {format: 'gltf', model: self.model});
  45436. }, undefined /* onProgress */, function gltfFailed (error) {
  45437. var message = (error && error.message) ? error.message : 'Failed to load glTF model';
  45438. warn(message);
  45439. el.emit('model-error', {format: 'gltf', src: src});
  45440. });
  45441. },
  45442. remove: function () {
  45443. if (!this.model) { return; }
  45444. this.el.removeObject3D('mesh');
  45445. }
  45446. });
  45447. },{"../core/component":128,"../lib/three":176,"../utils/":202}],81:[function(_dereq_,module,exports){
  45448. /* global THREE */
  45449. var registerComponent = _dereq_('../core/component').registerComponent;
  45450. // Found at https://github.com/aframevr/assets.
  45451. var MODEL_URLS = {
  45452. toonLeft: 'https://cdn.aframe.io/controllers/hands/leftHand.glb',
  45453. toonRight: 'https://cdn.aframe.io/controllers/hands/rightHand.glb',
  45454. lowPolyLeft: 'https://cdn.aframe.io/controllers/hands/leftHandLow.glb',
  45455. lowPolyRight: 'https://cdn.aframe.io/controllers/hands/rightHandLow.glb',
  45456. highPolyLeft: 'https://cdn.aframe.io/controllers/hands/leftHandHigh.glb',
  45457. highPolyRight: 'https://cdn.aframe.io/controllers/hands/rightHandHigh.glb'
  45458. };
  45459. // Poses.
  45460. var ANIMATIONS = {
  45461. open: 'Open',
  45462. // point: grip active, trackpad surface active, trigger inactive.
  45463. point: 'Point',
  45464. // pointThumb: grip active, trigger inactive, trackpad surface inactive.
  45465. pointThumb: 'Point + Thumb',
  45466. // fist: grip active, trigger active, trackpad surface active.
  45467. fist: 'Fist',
  45468. // hold: trigger active, grip inactive.
  45469. hold: 'Hold',
  45470. // thumbUp: grip active, trigger active, trackpad surface inactive.
  45471. thumbUp: 'Thumb Up'
  45472. };
  45473. // Map animation to public events for the API.
  45474. var EVENTS = {};
  45475. EVENTS[ANIMATIONS.fist] = 'grip';
  45476. EVENTS[ANIMATIONS.thumbUp] = 'pistol';
  45477. EVENTS[ANIMATIONS.point] = 'pointing';
  45478. /**
  45479. * Hand controls component that abstracts 6DoF controls:
  45480. * oculus-touch-controls, vive-controls, windows-motion-controls.
  45481. *
  45482. * Originally meant to be a sample implementation of applications-specific controls that
  45483. * abstracts multiple types of controllers.
  45484. *
  45485. * Auto-detect appropriate controller.
  45486. * Handle common events coming from the detected vendor-specific controls.
  45487. * Translate button events to semantic hand-related event names:
  45488. * (gripclose, gripopen, thumbup, thumbdown, pointup, pointdown)
  45489. * Load hand model with gestures that are applied based on the button pressed.
  45490. *
  45491. * @property {string} Hand mapping (`left`, `right`).
  45492. */
  45493. module.exports.Component = registerComponent('hand-controls', {
  45494. schema: {
  45495. color: {default: 'white', type: 'color'},
  45496. hand: { default: 'left' },
  45497. handModelStyle: {default: 'lowPoly', oneOf: ['lowPoly', 'highPoly', 'toon']}
  45498. },
  45499. init: function () {
  45500. var self = this;
  45501. var el = this.el;
  45502. // Current pose.
  45503. this.gesture = ANIMATIONS.open;
  45504. // Active buttons populated by events provided by the attached controls.
  45505. this.pressedButtons = {};
  45506. this.touchedButtons = {};
  45507. this.loader = new THREE.GLTFLoader();
  45508. this.loader.setCrossOrigin('anonymous');
  45509. this.onGripDown = function () { self.handleButton('grip', 'down'); };
  45510. this.onGripUp = function () { self.handleButton('grip', 'up'); };
  45511. this.onTrackpadDown = function () { self.handleButton('trackpad', 'down'); };
  45512. this.onTrackpadUp = function () { self.handleButton('trackpad', 'up'); };
  45513. this.onTrackpadTouchStart = function () { self.handleButton('trackpad', 'touchstart'); };
  45514. this.onTrackpadTouchEnd = function () { self.handleButton('trackpad', 'touchend'); };
  45515. this.onTriggerDown = function () { self.handleButton('trigger', 'down'); };
  45516. this.onTriggerUp = function () { self.handleButton('trigger', 'up'); };
  45517. this.onTriggerTouchStart = function () { self.handleButton('trigger', 'touchstart'); };
  45518. this.onTriggerTouchEnd = function () { self.handleButton('trigger', 'touchend'); };
  45519. this.onGripTouchStart = function () { self.handleButton('grip', 'touchstart'); };
  45520. this.onGripTouchEnd = function () { self.handleButton('grip', 'touchend'); };
  45521. this.onThumbstickDown = function () { self.handleButton('thumbstick', 'down'); };
  45522. this.onThumbstickUp = function () { self.handleButton('thumbstick', 'up'); };
  45523. this.onAorXTouchStart = function () { self.handleButton('AorX', 'touchstart'); };
  45524. this.onAorXTouchEnd = function () { self.handleButton('AorX', 'touchend'); };
  45525. this.onBorYTouchStart = function () { self.handleButton('BorY', 'touchstart'); };
  45526. this.onBorYTouchEnd = function () { self.handleButton('BorY', 'touchend'); };
  45527. this.onSurfaceTouchStart = function () { self.handleButton('surface', 'touchstart'); };
  45528. this.onSurfaceTouchEnd = function () { self.handleButton('surface', 'touchend'); };
  45529. this.onControllerConnected = this.onControllerConnected.bind(this);
  45530. this.onControllerDisconnected = this.onControllerDisconnected.bind(this);
  45531. el.addEventListener('controllerconnected', this.onControllerConnected);
  45532. el.addEventListener('controllerdisconnected', this.onControllerDisconnected);
  45533. // Hidden by default.
  45534. el.object3D.visible = false;
  45535. },
  45536. play: function () {
  45537. this.addEventListeners();
  45538. },
  45539. pause: function () {
  45540. this.removeEventListeners();
  45541. },
  45542. tick: function (time, delta) {
  45543. var mesh = this.el.getObject3D('mesh');
  45544. if (!mesh || !mesh.mixer) { return; }
  45545. mesh.mixer.update(delta / 1000);
  45546. },
  45547. onControllerConnected: function () {
  45548. this.el.object3D.visible = true;
  45549. },
  45550. onControllerDisconnected: function () {
  45551. this.el.object3D.visible = false;
  45552. },
  45553. addEventListeners: function () {
  45554. var el = this.el;
  45555. el.addEventListener('gripdown', this.onGripDown);
  45556. el.addEventListener('gripup', this.onGripUp);
  45557. el.addEventListener('trackpaddown', this.onTrackpadDown);
  45558. el.addEventListener('trackpadup', this.onTrackpadUp);
  45559. el.addEventListener('trackpadtouchstart', this.onTrackpadTouchStart);
  45560. el.addEventListener('trackpadtouchend', this.onTrackpadTouchEnd);
  45561. el.addEventListener('triggerdown', this.onTriggerDown);
  45562. el.addEventListener('triggerup', this.onTriggerUp);
  45563. el.addEventListener('triggertouchstart', this.onTriggerTouchStart);
  45564. el.addEventListener('triggertouchend', this.onTriggerTouchEnd);
  45565. el.addEventListener('griptouchstart', this.onGripTouchStart);
  45566. el.addEventListener('griptouchend', this.onGripTouchEnd);
  45567. el.addEventListener('thumbstickdown', this.onThumbstickDown);
  45568. el.addEventListener('thumbstickup', this.onThumbstickUp);
  45569. el.addEventListener('abuttontouchstart', this.onAorXTouchStart);
  45570. el.addEventListener('abuttontouchend', this.onAorXTouchEnd);
  45571. el.addEventListener('bbuttontouchstart', this.onBorYTouchStart);
  45572. el.addEventListener('bbuttontouchend', this.onBorYTouchEnd);
  45573. el.addEventListener('xbuttontouchstart', this.onAorXTouchStart);
  45574. el.addEventListener('xbuttontouchend', this.onAorXTouchEnd);
  45575. el.addEventListener('ybuttontouchstart', this.onBorYTouchStart);
  45576. el.addEventListener('ybuttontouchend', this.onBorYTouchEnd);
  45577. el.addEventListener('surfacetouchstart', this.onSurfaceTouchStart);
  45578. el.addEventListener('surfacetouchend', this.onSurfaceTouchEnd);
  45579. },
  45580. removeEventListeners: function () {
  45581. var el = this.el;
  45582. el.removeEventListener('gripdown', this.onGripDown);
  45583. el.removeEventListener('gripup', this.onGripUp);
  45584. el.removeEventListener('trackpaddown', this.onTrackpadDown);
  45585. el.removeEventListener('trackpadup', this.onTrackpadUp);
  45586. el.removeEventListener('trackpadtouchstart', this.onTrackpadTouchStart);
  45587. el.removeEventListener('trackpadtouchend', this.onTrackpadTouchEnd);
  45588. el.removeEventListener('triggerdown', this.onTriggerDown);
  45589. el.removeEventListener('triggerup', this.onTriggerUp);
  45590. el.removeEventListener('triggertouchstart', this.onTriggerTouchStart);
  45591. el.removeEventListener('triggertouchend', this.onTriggerTouchEnd);
  45592. el.removeEventListener('griptouchstart', this.onGripTouchStart);
  45593. el.removeEventListener('griptouchend', this.onGripTouchEnd);
  45594. el.removeEventListener('thumbstickdown', this.onThumbstickDown);
  45595. el.removeEventListener('thumbstickup', this.onThumbstickUp);
  45596. el.removeEventListener('abuttontouchstart', this.onAorXTouchStart);
  45597. el.removeEventListener('abuttontouchend', this.onAorXTouchEnd);
  45598. el.removeEventListener('bbuttontouchstart', this.onBorYTouchStart);
  45599. el.removeEventListener('bbuttontouchend', this.onBorYTouchEnd);
  45600. el.removeEventListener('xbuttontouchstart', this.onAorXTouchStart);
  45601. el.removeEventListener('xbuttontouchend', this.onAorXTouchEnd);
  45602. el.removeEventListener('ybuttontouchstart', this.onBorYTouchStart);
  45603. el.removeEventListener('ybuttontouchend', this.onBorYTouchEnd);
  45604. el.removeEventListener('surfacetouchstart', this.onSurfaceTouchStart);
  45605. el.removeEventListener('surfacetouchend', this.onSurfaceTouchEnd);
  45606. },
  45607. /**
  45608. * Update handler. More like the `init` handler since the only property is the hand, and
  45609. * that won't be changing much.
  45610. */
  45611. update: function (previousHand) {
  45612. var controlConfiguration;
  45613. var el = this.el;
  45614. var hand = this.data.hand;
  45615. var handModelStyle = this.data.handModelStyle;
  45616. var handColor = this.data.color;
  45617. var self = this;
  45618. // Get common configuration to abstract different vendor controls.
  45619. controlConfiguration = {
  45620. hand: hand,
  45621. model: false
  45622. };
  45623. // Set model.
  45624. if (hand !== previousHand) {
  45625. var handmodelUrl = MODEL_URLS[handModelStyle + hand.charAt(0).toUpperCase() + hand.slice(1)];
  45626. this.loader.load(handmodelUrl, function (gltf) {
  45627. var mesh = gltf.scene.children[0];
  45628. var handModelOrientation = hand === 'left' ? Math.PI / 2 : -Math.PI / 2;
  45629. mesh.mixer = new THREE.AnimationMixer(mesh);
  45630. self.clips = gltf.animations;
  45631. el.setObject3D('mesh', mesh);
  45632. var handMaterial = mesh.children[1].material;
  45633. handMaterial.color = new THREE.Color(handColor);
  45634. mesh.position.set(0, 0, 0);
  45635. mesh.rotation.set(0, 0, handModelOrientation);
  45636. el.setAttribute('magicleap-controls', controlConfiguration);
  45637. el.setAttribute('vive-controls', controlConfiguration);
  45638. el.setAttribute('oculus-touch-controls', controlConfiguration);
  45639. el.setAttribute('windows-motion-controls', controlConfiguration);
  45640. });
  45641. }
  45642. },
  45643. remove: function () {
  45644. this.el.removeObject3D('mesh');
  45645. },
  45646. /**
  45647. * Play model animation, based on which button was pressed and which kind of event.
  45648. *
  45649. * 1. Process buttons.
  45650. * 2. Determine gesture (this.determineGesture()).
  45651. * 3. Animation gesture (this.animationGesture()).
  45652. * 4. Emit gesture events (this.emitGestureEvents()).
  45653. *
  45654. * @param {string} button - Name of the button.
  45655. * @param {string} evt - Type of event for the button (i.e., down/up/touchstart/touchend).
  45656. */
  45657. handleButton: function (button, evt) {
  45658. var lastGesture;
  45659. var isPressed = evt === 'down';
  45660. var isTouched = evt === 'touchstart';
  45661. // Update objects.
  45662. if (evt.indexOf('touch') === 0) {
  45663. // Update touch object.
  45664. if (isTouched === this.touchedButtons[button]) { return; }
  45665. this.touchedButtons[button] = isTouched;
  45666. } else {
  45667. // Update button object.
  45668. if (isPressed === this.pressedButtons[button]) { return; }
  45669. this.pressedButtons[button] = isPressed;
  45670. }
  45671. // Determine the gesture.
  45672. lastGesture = this.gesture;
  45673. this.gesture = this.determineGesture();
  45674. // Same gesture.
  45675. if (this.gesture === lastGesture) { return; }
  45676. // Animate gesture.
  45677. this.animateGesture(this.gesture, lastGesture);
  45678. // Emit events.
  45679. this.emitGestureEvents(this.gesture, lastGesture);
  45680. },
  45681. /**
  45682. * Determine which pose hand should be in considering active and touched buttons.
  45683. */
  45684. determineGesture: function () {
  45685. var gesture;
  45686. var isGripActive = this.pressedButtons.grip;
  45687. var isSurfaceActive = this.pressedButtons.surface || this.touchedButtons.surface;
  45688. var isTrackpadActive = this.pressedButtons.trackpad || this.touchedButtons.trackpad;
  45689. var isTriggerActive = this.pressedButtons.trigger || this.touchedButtons.trigger;
  45690. var isABXYActive = this.touchedButtons.AorX || this.touchedButtons.BorY;
  45691. var isVive = isViveController(this.el.components['tracked-controls']);
  45692. // Works well with Oculus Touch and Windows Motion Controls, but Vive needs tweaks.
  45693. if (isVive) {
  45694. if (isGripActive || isTriggerActive) {
  45695. gesture = ANIMATIONS.fist;
  45696. } else if (isTrackpadActive) {
  45697. gesture = ANIMATIONS.point;
  45698. }
  45699. } else {
  45700. if (isGripActive) {
  45701. if (isSurfaceActive || isABXYActive || isTrackpadActive) {
  45702. gesture = isTriggerActive ? ANIMATIONS.fist : ANIMATIONS.point;
  45703. } else {
  45704. gesture = isTriggerActive ? ANIMATIONS.thumbUp : ANIMATIONS.pointThumb;
  45705. }
  45706. } else if (isTriggerActive) {
  45707. gesture = ANIMATIONS.hold;
  45708. }
  45709. }
  45710. return gesture;
  45711. },
  45712. /**
  45713. * Play corresponding clip to a gesture
  45714. */
  45715. getClip: function (gesture) {
  45716. var clip;
  45717. var i;
  45718. for (i = 0; i < this.clips.length; i++) {
  45719. clip = this.clips[i];
  45720. if (clip.name !== gesture) { continue; }
  45721. return clip;
  45722. }
  45723. },
  45724. /**
  45725. * Play gesture animation.
  45726. *
  45727. * @param {string} gesture - Which pose to animate to. If absent, then animate to open.
  45728. * @param {string} lastGesture - Previous gesture, to reverse back to open if needed.
  45729. */
  45730. animateGesture: function (gesture, lastGesture) {
  45731. if (gesture) {
  45732. this.playAnimation(gesture || ANIMATIONS.open, lastGesture, false);
  45733. return;
  45734. }
  45735. // If no gesture, then reverse the current gesture back to open pose.
  45736. this.playAnimation(lastGesture, lastGesture, true);
  45737. },
  45738. /**
  45739. * Emit `hand-controls`-specific events.
  45740. */
  45741. emitGestureEvents: function (gesture, lastGesture) {
  45742. var el = this.el;
  45743. var eventName;
  45744. if (lastGesture === gesture) { return; }
  45745. // Emit event for lastGesture not inactive.
  45746. eventName = getGestureEventName(lastGesture, false);
  45747. if (eventName) { el.emit(eventName); }
  45748. // Emit event for current gesture now active.
  45749. eventName = getGestureEventName(gesture, true);
  45750. if (eventName) { el.emit(eventName); }
  45751. },
  45752. /**
  45753. * Play hand animation based on button state.
  45754. *
  45755. * @param {string} gesture - Name of the animation as specified by the model.
  45756. * @param {string} lastGesture - Previous pose.
  45757. * @param {boolean} reverse - Whether animation should play in reverse.
  45758. */
  45759. playAnimation: function (gesture, lastGesture, reverse) {
  45760. var clip;
  45761. var fromAction;
  45762. var mesh = this.el.getObject3D('mesh');
  45763. var toAction;
  45764. if (!mesh) { return; }
  45765. // Stop all current animations.
  45766. mesh.mixer.stopAllAction();
  45767. // Grab clip action.
  45768. clip = this.getClip(gesture);
  45769. toAction = mesh.mixer.clipAction(clip);
  45770. toAction.clampWhenFinished = true;
  45771. toAction.loop = THREE.LoopRepeat;
  45772. toAction.repetitions = 0;
  45773. toAction.timeScale = reverse ? -1 : 1;
  45774. toAction.time = reverse ? clip.duration : 0;
  45775. toAction.weight = 1;
  45776. // No gesture to gesture or gesture to no gesture.
  45777. if (!lastGesture || gesture === lastGesture) {
  45778. // Stop all current animations.
  45779. mesh.mixer.stopAllAction();
  45780. // Play animation.
  45781. toAction.play();
  45782. return;
  45783. }
  45784. // Animate or crossfade from gesture to gesture.
  45785. clip = this.getClip(lastGesture);
  45786. fromAction = mesh.mixer.clipAction(clip);
  45787. fromAction.weight = 0.15;
  45788. fromAction.play();
  45789. toAction.play();
  45790. fromAction.crossFadeTo(toAction, 0.15, true);
  45791. }
  45792. });
  45793. /**
  45794. * Suffix gestures based on toggle state (e.g., open/close, up/down, start/end).
  45795. *
  45796. * @param {string} gesture
  45797. * @param {boolean} active
  45798. */
  45799. function getGestureEventName (gesture, active) {
  45800. var eventName;
  45801. if (!gesture) { return; }
  45802. eventName = EVENTS[gesture];
  45803. if (eventName === 'grip') {
  45804. return eventName + (active ? 'close' : 'open');
  45805. }
  45806. if (eventName === 'point') {
  45807. return eventName + (active ? 'up' : 'down');
  45808. }
  45809. if (eventName === 'pointing' || eventName === 'pistol') {
  45810. return eventName + (active ? 'start' : 'end');
  45811. }
  45812. }
  45813. function isViveController (trackedControls) {
  45814. var controller = trackedControls && trackedControls.controller;
  45815. var isVive = controller && (controller.id && controller.id.indexOf('OpenVR ') === 0 ||
  45816. (controller.profiles &&
  45817. controller.profiles[0] &&
  45818. controller.profiles[0] === 'htc-vive-controller-mv'));
  45819. return isVive;
  45820. }
  45821. },{"../core/component":128}],82:[function(_dereq_,module,exports){
  45822. _dereq_('./animation');
  45823. _dereq_('./camera');
  45824. _dereq_('./cursor');
  45825. _dereq_('./daydream-controls');
  45826. _dereq_('./gearvr-controls');
  45827. _dereq_('./geometry');
  45828. _dereq_('./generic-tracked-controller-controls');
  45829. _dereq_('./gltf-model');
  45830. _dereq_('./hand-controls');
  45831. _dereq_('./laser-controls');
  45832. _dereq_('./light');
  45833. _dereq_('./line');
  45834. _dereq_('./link');
  45835. _dereq_('./look-controls');
  45836. _dereq_('./magicleap-controls');
  45837. _dereq_('./material');
  45838. _dereq_('./obj-model');
  45839. _dereq_('./oculus-go-controls');
  45840. _dereq_('./oculus-touch-controls');
  45841. _dereq_('./position');
  45842. _dereq_('./raycaster');
  45843. _dereq_('./rotation');
  45844. _dereq_('./scale');
  45845. _dereq_('./shadow');
  45846. _dereq_('./sound');
  45847. _dereq_('./text');
  45848. _dereq_('./tracked-controls');
  45849. _dereq_('./tracked-controls-webvr');
  45850. _dereq_('./tracked-controls-webxr');
  45851. _dereq_('./visible');
  45852. _dereq_('./valve-index-controls');
  45853. _dereq_('./vive-controls');
  45854. _dereq_('./vive-focus-controls');
  45855. _dereq_('./wasd-controls');
  45856. _dereq_('./windows-motion-controls');
  45857. _dereq_('./scene/background');
  45858. _dereq_('./scene/debug');
  45859. _dereq_('./scene/device-orientation-permission-ui');
  45860. _dereq_('./scene/embedded');
  45861. _dereq_('./scene/inspector');
  45862. _dereq_('./scene/fog');
  45863. _dereq_('./scene/keyboard-shortcuts');
  45864. _dereq_('./scene/pool');
  45865. _dereq_('./scene/screenshot');
  45866. _dereq_('./scene/stats');
  45867. _dereq_('./scene/vr-mode-ui');
  45868. },{"./animation":73,"./camera":74,"./cursor":75,"./daydream-controls":76,"./gearvr-controls":77,"./generic-tracked-controller-controls":78,"./geometry":79,"./gltf-model":80,"./hand-controls":81,"./laser-controls":83,"./light":84,"./line":85,"./link":86,"./look-controls":87,"./magicleap-controls":88,"./material":89,"./obj-model":90,"./oculus-go-controls":91,"./oculus-touch-controls":92,"./position":93,"./raycaster":94,"./rotation":95,"./scale":96,"./scene/background":97,"./scene/debug":98,"./scene/device-orientation-permission-ui":99,"./scene/embedded":100,"./scene/fog":101,"./scene/inspector":102,"./scene/keyboard-shortcuts":103,"./scene/pool":104,"./scene/screenshot":105,"./scene/stats":106,"./scene/vr-mode-ui":107,"./shadow":108,"./sound":109,"./text":110,"./tracked-controls":113,"./tracked-controls-webvr":111,"./tracked-controls-webxr":112,"./valve-index-controls":114,"./visible":115,"./vive-controls":116,"./vive-focus-controls":117,"./wasd-controls":118,"./windows-motion-controls":119}],83:[function(_dereq_,module,exports){
  45869. var registerComponent = _dereq_('../core/component').registerComponent;
  45870. var utils = _dereq_('../utils/');
  45871. registerComponent('laser-controls', {
  45872. schema: {
  45873. hand: {default: 'right'},
  45874. model: {default: true},
  45875. defaultModelColor: {type: 'color', default: 'grey'}
  45876. },
  45877. init: function () {
  45878. var config = this.config;
  45879. var data = this.data;
  45880. var el = this.el;
  45881. var self = this;
  45882. var controlsConfiguration = {hand: data.hand, model: data.model};
  45883. // Set all controller models.
  45884. el.setAttribute('daydream-controls', controlsConfiguration);
  45885. el.setAttribute('gearvr-controls', controlsConfiguration);
  45886. el.setAttribute('magicleap-controls', controlsConfiguration);
  45887. el.setAttribute('oculus-go-controls', controlsConfiguration);
  45888. el.setAttribute('oculus-touch-controls', controlsConfiguration);
  45889. el.setAttribute('valve-index-controls', controlsConfiguration);
  45890. el.setAttribute('vive-controls', controlsConfiguration);
  45891. el.setAttribute('vive-focus-controls', controlsConfiguration);
  45892. el.setAttribute('windows-motion-controls', controlsConfiguration);
  45893. el.setAttribute('generic-tracked-controller-controls', controlsConfiguration);
  45894. // Wait for controller to connect, or have a valid pointing pose, before creating ray
  45895. el.addEventListener('controllerconnected', createRay);
  45896. el.addEventListener('controllerdisconnected', hideRay);
  45897. el.addEventListener('controllermodelready', function (evt) {
  45898. createRay(evt);
  45899. self.modelReady = true;
  45900. });
  45901. function createRay (evt) {
  45902. var controllerConfig = config[evt.detail.name];
  45903. if (!controllerConfig) { return; }
  45904. // Show the line unless a particular config opts to hide it, until a controllermodelready
  45905. // event comes through.
  45906. var raycasterConfig = utils.extend({
  45907. showLine: true
  45908. }, controllerConfig.raycaster || {});
  45909. // The controllermodelready event contains a rayOrigin that takes into account
  45910. // offsets specific to the loaded model.
  45911. if (evt.detail.rayOrigin) {
  45912. raycasterConfig.origin = evt.detail.rayOrigin.origin;
  45913. raycasterConfig.direction = evt.detail.rayOrigin.direction;
  45914. raycasterConfig.showLine = true;
  45915. }
  45916. // Only apply a default raycaster if it does not yet exist. This prevents it overwriting
  45917. // config applied from a controllermodelready event.
  45918. if (evt.detail.rayOrigin || !self.modelReady) {
  45919. el.setAttribute('raycaster', raycasterConfig);
  45920. } else {
  45921. el.setAttribute('raycaster', 'showLine', true);
  45922. }
  45923. el.setAttribute('cursor', utils.extend({
  45924. fuse: false
  45925. }, controllerConfig.cursor));
  45926. }
  45927. function hideRay () {
  45928. el.setAttribute('raycaster', 'showLine', false);
  45929. }
  45930. },
  45931. config: {
  45932. 'daydream-controls': {
  45933. cursor: {downEvents: ['trackpaddown', 'triggerdown'], upEvents: ['trackpadup', 'triggerup']}
  45934. },
  45935. 'gearvr-controls': {
  45936. cursor: {downEvents: ['triggerdown'], upEvents: ['triggerup']},
  45937. raycaster: {origin: {x: 0, y: 0.0010, z: 0}}
  45938. },
  45939. 'generic-tracked-controller-controls': {
  45940. cursor: {downEvents: ['triggerdown'], upEvents: ['triggerup']}
  45941. },
  45942. 'magicleap-controls': {
  45943. cursor: {downEvents: ['trackpaddown', 'triggerdown'], upEvents: ['trackpadup', 'triggerup']}
  45944. },
  45945. 'oculus-go-controls': {
  45946. cursor: {downEvents: ['triggerdown'], upEvents: ['triggerup']},
  45947. raycaster: {origin: {x: 0, y: 0.0005, z: 0}}
  45948. },
  45949. 'oculus-touch-controls': {
  45950. cursor: {downEvents: ['triggerdown'], upEvents: ['triggerup']},
  45951. raycaster: {origin: {x: 0, y: 0, z: 0}}
  45952. },
  45953. 'valve-index-controls': {
  45954. cursor: {downEvents: ['triggerdown'], upEvents: ['triggerup']}
  45955. },
  45956. 'vive-controls': {
  45957. cursor: {downEvents: ['triggerdown'], upEvents: ['triggerup']}
  45958. },
  45959. 'vive-focus-controls': {
  45960. cursor: {downEvents: ['trackpaddown', 'triggerdown'], upEvents: ['trackpadup', 'triggerup']}
  45961. },
  45962. 'windows-motion-controls': {
  45963. cursor: {downEvents: ['triggerdown'], upEvents: ['triggerup']},
  45964. raycaster: {showLine: false}
  45965. }
  45966. }
  45967. });
  45968. },{"../core/component":128,"../utils/":202}],84:[function(_dereq_,module,exports){
  45969. var bind = _dereq_('../utils/bind');
  45970. var diff = _dereq_('../utils').diff;
  45971. var debug = _dereq_('../utils/debug');
  45972. var registerComponent = _dereq_('../core/component').registerComponent;
  45973. var THREE = _dereq_('../lib/three');
  45974. var degToRad = THREE.Math.degToRad;
  45975. var warn = debug('components:light:warn');
  45976. /**
  45977. * Light component.
  45978. */
  45979. module.exports.Component = registerComponent('light', {
  45980. schema: {
  45981. angle: {default: 60, if: {type: ['spot']}},
  45982. color: {type: 'color'},
  45983. groundColor: {type: 'color', if: {type: ['hemisphere']}},
  45984. decay: {default: 1, if: {type: ['point', 'spot']}},
  45985. distance: {default: 0.0, min: 0, if: {type: ['point', 'spot']}},
  45986. intensity: {default: 1.0, min: 0, if: {type: ['ambient', 'directional', 'hemisphere', 'point', 'spot']}},
  45987. penumbra: {default: 0, min: 0, max: 1, if: {type: ['spot']}},
  45988. type: {
  45989. default: 'directional',
  45990. oneOf: ['ambient', 'directional', 'hemisphere', 'point', 'spot'],
  45991. schemaChange: true
  45992. },
  45993. target: {type: 'selector', if: {type: ['spot', 'directional']}},
  45994. // Shadows.
  45995. castShadow: {default: false, if: {type: ['point', 'spot', 'directional']}},
  45996. shadowBias: {default: 0, if: {castShadow: true}},
  45997. shadowCameraFar: {default: 500, if: {castShadow: true}},
  45998. shadowCameraFov: {default: 90, if: {castShadow: true}},
  45999. shadowCameraNear: {default: 0.5, if: {castShadow: true}},
  46000. shadowCameraTop: {default: 5, if: {castShadow: true}},
  46001. shadowCameraRight: {default: 5, if: {castShadow: true}},
  46002. shadowCameraBottom: {default: -5, if: {castShadow: true}},
  46003. shadowCameraLeft: {default: -5, if: {castShadow: true}},
  46004. shadowCameraVisible: {default: false, if: {castShadow: true}},
  46005. shadowMapHeight: {default: 512, if: {castShadow: true}},
  46006. shadowMapWidth: {default: 512, if: {castShadow: true}},
  46007. shadowRadius: {default: 1, if: {castShadow: true}}
  46008. },
  46009. /**
  46010. * Notifies scene a light has been added to remove default lighting.
  46011. */
  46012. init: function () {
  46013. var el = this.el;
  46014. this.light = null;
  46015. this.defaultTarget = null;
  46016. this.rendererSystem = this.el.sceneEl.systems.renderer;
  46017. this.system.registerLight(el);
  46018. },
  46019. /**
  46020. * (Re)create or update light.
  46021. */
  46022. update: function (oldData) {
  46023. var data = this.data;
  46024. var diffData = diff(data, oldData);
  46025. var light = this.light;
  46026. var rendererSystem = this.rendererSystem;
  46027. var self = this;
  46028. // Existing light.
  46029. if (light && !('type' in diffData)) {
  46030. var shadowsLoaded = false;
  46031. // Light type has not changed. Update light.
  46032. Object.keys(diffData).forEach(function (key) {
  46033. var value = data[key];
  46034. switch (key) {
  46035. case 'color': {
  46036. light.color.set(value);
  46037. rendererSystem.applyColorCorrection(light.color);
  46038. break;
  46039. }
  46040. case 'groundColor': {
  46041. light.groundColor.set(value);
  46042. rendererSystem.applyColorCorrection(light.groundColor);
  46043. break;
  46044. }
  46045. case 'angle': {
  46046. light.angle = degToRad(value);
  46047. break;
  46048. }
  46049. case 'target': {
  46050. // Reset target if selector is null.
  46051. if (value === null) {
  46052. if (data.type === 'spot' || data.type === 'directional') {
  46053. light.target = self.defaultTarget;
  46054. }
  46055. } else {
  46056. // Target specified, set target to entity's `object3D` when it is loaded.
  46057. if (value.hasLoaded) {
  46058. self.onSetTarget(value, light);
  46059. } else {
  46060. value.addEventListener('loaded', bind(self.onSetTarget, self, value, light));
  46061. }
  46062. }
  46063. break;
  46064. }
  46065. case 'castShadow':
  46066. case 'shadowBias':
  46067. case 'shadowCameraFar':
  46068. case 'shadowCameraFov':
  46069. case 'shadowCameraNear':
  46070. case 'shadowCameraTop':
  46071. case 'shadowCameraRight':
  46072. case 'shadowCameraBottom':
  46073. case 'shadowCameraLeft':
  46074. case 'shadowCameraVisible':
  46075. case 'shadowMapHeight':
  46076. case 'shadowMapWidth':
  46077. case 'shadowRadius':
  46078. if (!shadowsLoaded) {
  46079. self.updateShadow();
  46080. shadowsLoaded = true;
  46081. }
  46082. break;
  46083. default: {
  46084. light[key] = value;
  46085. }
  46086. }
  46087. });
  46088. return;
  46089. }
  46090. // No light yet or light type has changed. Create and add light.
  46091. this.setLight(this.data);
  46092. this.updateShadow();
  46093. },
  46094. setLight: function (data) {
  46095. var el = this.el;
  46096. var newLight = this.getLight(data);
  46097. if (newLight) {
  46098. if (this.light) {
  46099. el.removeObject3D('light');
  46100. }
  46101. this.light = newLight;
  46102. this.light.el = el;
  46103. el.setObject3D('light', this.light);
  46104. // HACK solution for issue #1624
  46105. if (data.type === 'spot' || data.type === 'directional' || data.type === 'hemisphere') {
  46106. el.getObject3D('light').translateY(-1);
  46107. }
  46108. // set and position default lighttarget as a child to enable spotlight orientation
  46109. if (data.type === 'spot') {
  46110. el.setObject3D('light-target', this.defaultTarget);
  46111. el.getObject3D('light-target').position.set(0, 0, -1);
  46112. }
  46113. }
  46114. },
  46115. /**
  46116. * Updates shadow-related properties on the current light.
  46117. */
  46118. updateShadow: function () {
  46119. var el = this.el;
  46120. var data = this.data;
  46121. var light = this.light;
  46122. light.castShadow = data.castShadow;
  46123. // Shadow camera helper.
  46124. var cameraHelper = el.getObject3D('cameraHelper');
  46125. if (data.shadowCameraVisible && !cameraHelper) {
  46126. el.setObject3D('cameraHelper', new THREE.CameraHelper(light.shadow.camera));
  46127. } else if (!data.shadowCameraVisible && cameraHelper) {
  46128. el.removeObject3D('cameraHelper');
  46129. }
  46130. if (!data.castShadow) { return light; }
  46131. // Shadow appearance.
  46132. light.shadow.bias = data.shadowBias;
  46133. light.shadow.radius = data.shadowRadius;
  46134. light.shadow.mapSize.height = data.shadowMapHeight;
  46135. light.shadow.mapSize.width = data.shadowMapWidth;
  46136. // Shadow camera.
  46137. light.shadow.camera.near = data.shadowCameraNear;
  46138. light.shadow.camera.far = data.shadowCameraFar;
  46139. if (light.shadow.camera instanceof THREE.OrthographicCamera) {
  46140. light.shadow.camera.top = data.shadowCameraTop;
  46141. light.shadow.camera.right = data.shadowCameraRight;
  46142. light.shadow.camera.bottom = data.shadowCameraBottom;
  46143. light.shadow.camera.left = data.shadowCameraLeft;
  46144. } else {
  46145. light.shadow.camera.fov = data.shadowCameraFov;
  46146. }
  46147. light.shadow.camera.updateProjectionMatrix();
  46148. if (cameraHelper) { cameraHelper.update(); }
  46149. },
  46150. /**
  46151. * Creates a new three.js light object given data object defining the light.
  46152. *
  46153. * @param {object} data
  46154. */
  46155. getLight: function (data) {
  46156. var angle = data.angle;
  46157. var color = new THREE.Color(data.color);
  46158. this.rendererSystem.applyColorCorrection(color);
  46159. color = color.getHex();
  46160. var decay = data.decay;
  46161. var distance = data.distance;
  46162. var groundColor = new THREE.Color(data.groundColor);
  46163. this.rendererSystem.applyColorCorrection(groundColor);
  46164. groundColor = groundColor.getHex();
  46165. var intensity = data.intensity;
  46166. var type = data.type;
  46167. var target = data.target;
  46168. var light = null;
  46169. switch (type.toLowerCase()) {
  46170. case 'ambient': {
  46171. return new THREE.AmbientLight(color, intensity);
  46172. }
  46173. case 'directional': {
  46174. light = new THREE.DirectionalLight(color, intensity);
  46175. this.defaultTarget = light.target;
  46176. if (target) {
  46177. if (target.hasLoaded) {
  46178. this.onSetTarget(target, light);
  46179. } else {
  46180. target.addEventListener('loaded', bind(this.onSetTarget, this, target, light));
  46181. }
  46182. }
  46183. return light;
  46184. }
  46185. case 'hemisphere': {
  46186. return new THREE.HemisphereLight(color, groundColor, intensity);
  46187. }
  46188. case 'point': {
  46189. return new THREE.PointLight(color, intensity, distance, decay);
  46190. }
  46191. case 'spot': {
  46192. light = new THREE.SpotLight(color, intensity, distance, degToRad(angle), data.penumbra, decay);
  46193. this.defaultTarget = light.target;
  46194. if (target) {
  46195. if (target.hasLoaded) {
  46196. this.onSetTarget(target, light);
  46197. } else {
  46198. target.addEventListener('loaded', bind(this.onSetTarget, this, target, light));
  46199. }
  46200. }
  46201. return light;
  46202. }
  46203. default: {
  46204. warn('%s is not a valid light type. ' +
  46205. 'Choose from ambient, directional, hemisphere, point, spot.', type);
  46206. }
  46207. }
  46208. },
  46209. onSetTarget: function (targetEl, light) {
  46210. light.target = targetEl.object3D;
  46211. },
  46212. /**
  46213. * Remove light on remove (callback).
  46214. */
  46215. remove: function () {
  46216. var el = this.el;
  46217. el.removeObject3D('light');
  46218. if (el.getObject3D('cameraHelper')) {
  46219. el.removeObject3D('cameraHelper');
  46220. }
  46221. }
  46222. });
  46223. },{"../core/component":128,"../lib/three":176,"../utils":202,"../utils/bind":196,"../utils/debug":198}],85:[function(_dereq_,module,exports){
  46224. /* global THREE */
  46225. var registerComponent = _dereq_('../core/component').registerComponent;
  46226. module.exports.Component = registerComponent('line', {
  46227. schema: {
  46228. start: {type: 'vec3', default: {x: 0, y: 0, z: 0}},
  46229. end: {type: 'vec3', default: {x: 0, y: 0, z: 0}},
  46230. color: {type: 'color', default: '#74BEC1'},
  46231. opacity: {type: 'number', default: 1},
  46232. visible: {default: true}
  46233. },
  46234. multiple: true,
  46235. init: function () {
  46236. var data = this.data;
  46237. var geometry;
  46238. var material;
  46239. this.rendererSystem = this.el.sceneEl.systems.renderer;
  46240. material = this.material = new THREE.LineBasicMaterial({
  46241. color: data.color,
  46242. opacity: data.opacity,
  46243. transparent: data.opacity < 1,
  46244. visible: data.visible
  46245. });
  46246. geometry = this.geometry = new THREE.BufferGeometry();
  46247. geometry.setAttribute('position', new THREE.BufferAttribute(new Float32Array(2 * 3), 3));
  46248. this.rendererSystem.applyColorCorrection(material.color);
  46249. this.line = new THREE.Line(geometry, material);
  46250. this.el.setObject3D(this.attrName, this.line);
  46251. },
  46252. update: function (oldData) {
  46253. var data = this.data;
  46254. var geometry = this.geometry;
  46255. var geoNeedsUpdate = false;
  46256. var material = this.material;
  46257. var positionArray = geometry.attributes.position.array;
  46258. // Update geometry.
  46259. if (!isEqualVec3(data.start, oldData.start)) {
  46260. positionArray[0] = data.start.x;
  46261. positionArray[1] = data.start.y;
  46262. positionArray[2] = data.start.z;
  46263. geoNeedsUpdate = true;
  46264. }
  46265. if (!isEqualVec3(data.end, oldData.end)) {
  46266. positionArray[3] = data.end.x;
  46267. positionArray[4] = data.end.y;
  46268. positionArray[5] = data.end.z;
  46269. geoNeedsUpdate = true;
  46270. }
  46271. if (geoNeedsUpdate) {
  46272. geometry.attributes.position.needsUpdate = true;
  46273. geometry.computeBoundingSphere();
  46274. }
  46275. material.color.setStyle(data.color);
  46276. this.rendererSystem.applyColorCorrection(material.color);
  46277. material.opacity = data.opacity;
  46278. material.transparent = data.opacity < 1;
  46279. material.visible = data.visible;
  46280. },
  46281. remove: function () {
  46282. this.el.removeObject3D('line', this.line);
  46283. }
  46284. });
  46285. function isEqualVec3 (a, b) {
  46286. if (!a || !b) { return false; }
  46287. return (a.x === b.x && a.y === b.y && a.z === b.z);
  46288. }
  46289. },{"../core/component":128}],86:[function(_dereq_,module,exports){
  46290. var registerComponent = _dereq_('../core/component').registerComponent;
  46291. var registerShader = _dereq_('../core/shader').registerShader;
  46292. var THREE = _dereq_('../lib/three');
  46293. /**
  46294. * Link component. Connect experiences and traverse between them in VR
  46295. *
  46296. * @member {object} hiddenEls - Store the hidden elements during peek mode.
  46297. */
  46298. module.exports.Component = registerComponent('link', {
  46299. schema: {
  46300. backgroundColor: {default: 'red', type: 'color'},
  46301. borderColor: {default: 'white', type: 'color'},
  46302. highlighted: {default: false},
  46303. highlightedColor: {default: '#24CAFF', type: 'color'},
  46304. href: {default: ''},
  46305. image: {type: 'asset'},
  46306. on: {default: 'click'},
  46307. peekMode: {default: false},
  46308. title: {default: ''},
  46309. titleColor: {default: 'white', type: 'color'},
  46310. visualAspectEnabled: {default: false}
  46311. },
  46312. init: function () {
  46313. this.navigate = this.navigate.bind(this);
  46314. this.previousQuaternion = undefined;
  46315. this.quaternionClone = new THREE.Quaternion();
  46316. // Store hidden elements during peek mode so we can show them again later.
  46317. this.hiddenEls = [];
  46318. },
  46319. update: function (oldData) {
  46320. var data = this.data;
  46321. var el = this.el;
  46322. var backgroundColor;
  46323. var strokeColor;
  46324. if (!data.visualAspectEnabled) { return; }
  46325. this.initVisualAspect();
  46326. backgroundColor = data.highlighted ? data.highlightedColor : data.backgroundColor;
  46327. strokeColor = data.highlighted ? data.highlightedColor : data.borderColor;
  46328. el.setAttribute('material', 'backgroundColor', backgroundColor);
  46329. el.setAttribute('material', 'strokeColor', strokeColor);
  46330. if (data.on !== oldData.on) { this.updateEventListener(); }
  46331. if (oldData.peekMode !== undefined &&
  46332. data.peekMode !== oldData.peekMode) { this.updatePeekMode(); }
  46333. if (!data.image || oldData.image === data.image) { return; }
  46334. el.setAttribute('material', 'pano',
  46335. typeof data.image === 'string' ? data.image : data.image.src);
  46336. },
  46337. /*
  46338. * Toggle all elements and full 360 preview of the linked page.
  46339. */
  46340. updatePeekMode: function () {
  46341. var el = this.el;
  46342. var sphereEl = this.sphereEl;
  46343. if (this.data.peekMode) {
  46344. this.hideAll();
  46345. el.getObject3D('mesh').visible = false;
  46346. sphereEl.setAttribute('visible', true);
  46347. } else {
  46348. this.showAll();
  46349. el.getObject3D('mesh').visible = true;
  46350. sphereEl.setAttribute('visible', false);
  46351. }
  46352. },
  46353. play: function () {
  46354. this.updateEventListener();
  46355. },
  46356. pause: function () {
  46357. this.removeEventListener();
  46358. },
  46359. updateEventListener: function () {
  46360. var el = this.el;
  46361. if (!el.isPlaying) { return; }
  46362. this.removeEventListener();
  46363. el.addEventListener(this.data.on, this.navigate);
  46364. },
  46365. removeEventListener: function () {
  46366. var on = this.data.on;
  46367. if (!on) { return; }
  46368. this.el.removeEventListener(on, this.navigate);
  46369. },
  46370. initVisualAspect: function () {
  46371. var el = this.el;
  46372. var semiSphereEl;
  46373. var sphereEl;
  46374. var textEl;
  46375. if (!this.data.visualAspectEnabled || this.visualAspectInitialized) { return; }
  46376. textEl = this.textEl = this.textEl || document.createElement('a-entity');
  46377. sphereEl = this.sphereEl = this.sphereEl || document.createElement('a-entity');
  46378. semiSphereEl = this.semiSphereEl = this.semiSphereEl || document.createElement('a-entity');
  46379. // Set portal.
  46380. el.setAttribute('geometry', {primitive: 'circle', radius: 1.0, segments: 64});
  46381. el.setAttribute('material', {shader: 'portal', pano: this.data.image, side: 'double'});
  46382. // Set text that displays the link title and URL.
  46383. textEl.setAttribute('text', {
  46384. color: this.data.titleColor,
  46385. align: 'center',
  46386. font: 'kelsonsans',
  46387. value: this.data.title || this.data.href,
  46388. width: 4
  46389. });
  46390. textEl.setAttribute('position', '0 1.5 0');
  46391. el.appendChild(textEl);
  46392. // Set sphere rendered when camera is close to portal to allow user to peek inside.
  46393. semiSphereEl.setAttribute('geometry', {
  46394. primitive: 'sphere',
  46395. radius: 1.0,
  46396. phiStart: 0,
  46397. segmentsWidth: 64,
  46398. segmentsHeight: 64,
  46399. phiLength: 180,
  46400. thetaStart: 0,
  46401. thetaLength: 360
  46402. });
  46403. semiSphereEl.setAttribute('material', {
  46404. shader: 'portal',
  46405. borderEnabled: 0.0,
  46406. pano: this.data.image,
  46407. side: 'back'
  46408. });
  46409. semiSphereEl.setAttribute('rotation', '0 180 0');
  46410. semiSphereEl.setAttribute('position', '0 0 0');
  46411. semiSphereEl.setAttribute('visible', false);
  46412. el.appendChild(semiSphereEl);
  46413. // Set sphere rendered when camera is close to portal to allow user to peek inside.
  46414. sphereEl.setAttribute('geometry', {
  46415. primitive: 'sphere',
  46416. radius: 10,
  46417. segmentsWidth: 64,
  46418. segmentsHeight: 64
  46419. });
  46420. sphereEl.setAttribute('material', {
  46421. shader: 'portal',
  46422. borderEnabled: 0.0,
  46423. pano: this.data.image,
  46424. side: 'back'
  46425. });
  46426. sphereEl.setAttribute('visible', false);
  46427. el.appendChild(sphereEl);
  46428. this.visualAspectInitialized = true;
  46429. },
  46430. navigate: function () {
  46431. window.location = this.data.href;
  46432. },
  46433. /**
  46434. * 1. Swap plane that represents portal with sphere with a hole when the camera is close
  46435. * so user can peek inside portal. Sphere is rendered on oposite side of portal
  46436. * from where user enters.
  46437. * 2. Place the url/title above or inside portal depending on distance to camera.
  46438. * 3. Face portal to camera when far away from user.
  46439. */
  46440. tick: (function () {
  46441. var cameraWorldPosition = new THREE.Vector3();
  46442. var elWorldPosition = new THREE.Vector3();
  46443. var quaternion = new THREE.Quaternion();
  46444. var scale = new THREE.Vector3();
  46445. return function () {
  46446. var el = this.el;
  46447. var object3D = el.object3D;
  46448. var camera = el.sceneEl.camera;
  46449. var cameraPortalOrientation;
  46450. var distance;
  46451. var textEl = this.textEl;
  46452. if (!this.data.visualAspectEnabled) { return; }
  46453. // Update matrices
  46454. object3D.updateMatrixWorld();
  46455. camera.parent.updateMatrixWorld();
  46456. camera.updateMatrixWorld();
  46457. object3D.matrix.decompose(elWorldPosition, quaternion, scale);
  46458. elWorldPosition.setFromMatrixPosition(object3D.matrixWorld);
  46459. cameraWorldPosition.setFromMatrixPosition(camera.matrixWorld);
  46460. distance = elWorldPosition.distanceTo(cameraWorldPosition);
  46461. if (distance > 20) {
  46462. // Store original orientation to be restored when the portal stops facing the camera.
  46463. if (!this.previousQuaternion) {
  46464. this.quaternionClone.copy(quaternion);
  46465. this.previousQuaternion = this.quaternionClone;
  46466. }
  46467. // If the portal is far away from the user, face portal to camera.
  46468. object3D.lookAt(cameraWorldPosition);
  46469. } else {
  46470. // When portal is close to the user/camera.
  46471. cameraPortalOrientation = this.calculateCameraPortalOrientation();
  46472. // If user gets very close to portal, replace with holed sphere they can peek in.
  46473. if (distance < 0.5) {
  46474. // Configure text size and sphere orientation depending side user approaches portal.
  46475. if (this.semiSphereEl.getAttribute('visible') === true) { return; }
  46476. textEl.setAttribute('text', 'width', 1.5);
  46477. if (cameraPortalOrientation <= 0.0) {
  46478. textEl.setAttribute('position', '0 0 0.75');
  46479. textEl.setAttribute('rotation', '0 180 0');
  46480. this.semiSphereEl.setAttribute('rotation', '0 0 0');
  46481. } else {
  46482. textEl.setAttribute('position', '0 0 -0.75');
  46483. textEl.setAttribute('rotation', '0 0 0');
  46484. this.semiSphereEl.setAttribute('rotation', '0 180 0');
  46485. }
  46486. el.getObject3D('mesh').visible = false;
  46487. this.semiSphereEl.setAttribute('visible', true);
  46488. this.peekCameraPortalOrientation = cameraPortalOrientation;
  46489. } else {
  46490. // Calculate wich side the camera is approaching the camera (back / front).
  46491. // Adjust text orientation based on camera position.
  46492. if (cameraPortalOrientation <= 0.0) {
  46493. textEl.setAttribute('rotation', '0 180 0');
  46494. } else {
  46495. textEl.setAttribute('rotation', '0 0 0');
  46496. }
  46497. textEl.setAttribute('text', 'width', 5);
  46498. textEl.setAttribute('position', '0 1.5 0');
  46499. el.getObject3D('mesh').visible = true;
  46500. this.semiSphereEl.setAttribute('visible', false);
  46501. this.peekCameraPortalOrientation = undefined;
  46502. }
  46503. if (this.previousQuaternion) {
  46504. object3D.quaternion.copy(this.previousQuaternion);
  46505. this.previousQuaternion = undefined;
  46506. }
  46507. }
  46508. };
  46509. })(),
  46510. hideAll: function () {
  46511. var el = this.el;
  46512. var hiddenEls = this.hiddenEls;
  46513. var self = this;
  46514. if (hiddenEls.length > 0) { return; }
  46515. el.sceneEl.object3D.traverse(function (object) {
  46516. if (object && object.el && object.el.hasAttribute('link-controls')) { return; }
  46517. if (!object.el || object === el.sceneEl.object3D || object.el === el ||
  46518. object.el === self.sphereEl || object.el === el.sceneEl.cameraEl ||
  46519. object.el.getAttribute('visible') === false || object.el === self.textEl ||
  46520. object.el === self.semiSphereEl) {
  46521. return;
  46522. }
  46523. object.el.setAttribute('visible', false);
  46524. hiddenEls.push(object.el);
  46525. });
  46526. },
  46527. showAll: function () {
  46528. this.hiddenEls.forEach(function (el) { el.setAttribute('visible', true); });
  46529. this.hiddenEls = [];
  46530. },
  46531. /**
  46532. * Calculate whether the camera faces the front or back face of the portal.
  46533. * @returns {number} > 0 if camera faces front of portal, < 0 if it faces back of portal.
  46534. */
  46535. calculateCameraPortalOrientation: (function () {
  46536. var mat4 = new THREE.Matrix4();
  46537. var cameraPosition = new THREE.Vector3();
  46538. var portalNormal = new THREE.Vector3(0, 0, 1);
  46539. var portalPosition = new THREE.Vector3(0, 0, 0);
  46540. return function () {
  46541. var el = this.el;
  46542. var camera = el.sceneEl.camera;
  46543. // Reset tmp variables.
  46544. cameraPosition.set(0, 0, 0);
  46545. portalNormal.set(0, 0, 1);
  46546. portalPosition.set(0, 0, 0);
  46547. // Apply portal orientation to the normal.
  46548. el.object3D.matrixWorld.extractRotation(mat4);
  46549. portalNormal.applyMatrix4(mat4);
  46550. // Calculate portal world position.
  46551. el.object3D.updateMatrixWorld();
  46552. el.object3D.localToWorld(portalPosition);
  46553. // Calculate camera world position.
  46554. camera.parent.parent.updateMatrixWorld();
  46555. camera.parent.updateMatrixWorld();
  46556. camera.updateMatrixWorld();
  46557. camera.localToWorld(cameraPosition);
  46558. // Calculate vector from portal to camera.
  46559. // (portal) -------> (camera)
  46560. cameraPosition.sub(portalPosition).normalize();
  46561. portalNormal.normalize();
  46562. // Side where camera approaches portal is given by sign of dot product of portal normal
  46563. // and portal to camera vectors.
  46564. return Math.sign(portalNormal.dot(cameraPosition));
  46565. };
  46566. })(),
  46567. remove: function () {
  46568. this.removeEventListener();
  46569. }
  46570. });
  46571. /* eslint-disable */
  46572. registerShader('portal', {
  46573. schema: {
  46574. borderEnabled: {default: 1.0, type: 'int', is: 'uniform'},
  46575. backgroundColor: {default: 'red', type: 'color', is: 'uniform'},
  46576. pano: {type: 'map', is: 'uniform'},
  46577. strokeColor: {default: 'white', type: 'color', is: 'uniform'}
  46578. },
  46579. vertexShader: [
  46580. 'vec3 portalPosition;',
  46581. 'varying vec3 vWorldPosition;',
  46582. 'varying float vDistanceToCenter;',
  46583. 'varying float vDistance;',
  46584. 'void main() {',
  46585. 'vDistanceToCenter = clamp(length(position - vec3(0.0, 0.0, 0.0)), 0.0, 1.0);',
  46586. 'portalPosition = (modelMatrix * vec4(0.0, 0.0, 0.0, 1.0)).xyz;',
  46587. 'vDistance = length(portalPosition - cameraPosition);',
  46588. 'vWorldPosition = (modelMatrix * vec4(position, 1.0)).xyz;',
  46589. 'gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);',
  46590. '}'
  46591. ].join('\n'),
  46592. fragmentShader: [
  46593. '#define RECIPROCAL_PI2 0.15915494',
  46594. 'uniform sampler2D pano;',
  46595. 'uniform vec3 strokeColor;',
  46596. 'uniform vec3 backgroundColor;',
  46597. 'uniform float borderEnabled;',
  46598. 'varying float vDistanceToCenter;',
  46599. 'varying float vDistance;',
  46600. 'varying vec3 vWorldPosition;',
  46601. 'void main() {',
  46602. 'vec3 direction = normalize(vWorldPosition - cameraPosition);',
  46603. 'vec2 sampleUV;',
  46604. 'float borderThickness = clamp(exp(-vDistance / 50.0), 0.6, 0.95);',
  46605. 'sampleUV.y = saturate(direction.y * 0.5 + 0.5);',
  46606. 'sampleUV.x = atan(direction.z, -direction.x) * -RECIPROCAL_PI2 + 0.5;',
  46607. 'if (vDistanceToCenter > borderThickness && borderEnabled == 1.0) {',
  46608. 'gl_FragColor = vec4(strokeColor, 1.0);',
  46609. '} else {',
  46610. 'gl_FragColor = mix(texture2D(pano, sampleUV), vec4(backgroundColor, 1.0), clamp(pow((vDistance / 15.0), 2.0), 0.0, 1.0));',
  46611. '}',
  46612. '}'
  46613. ].join('\n')
  46614. });
  46615. /* eslint-enable */
  46616. },{"../core/component":128,"../core/shader":138,"../lib/three":176}],87:[function(_dereq_,module,exports){
  46617. /* global DeviceOrientationEvent */
  46618. var registerComponent = _dereq_('../core/component').registerComponent;
  46619. var THREE = _dereq_('../lib/three');
  46620. var utils = _dereq_('../utils/');
  46621. var bind = utils.bind;
  46622. // To avoid recalculation at every mouse movement tick
  46623. var PI_2 = Math.PI / 2;
  46624. /**
  46625. * look-controls. Update entity pose, factoring mouse, touch, and WebVR API data.
  46626. */
  46627. module.exports.Component = registerComponent('look-controls', {
  46628. dependencies: ['position', 'rotation'],
  46629. schema: {
  46630. enabled: {default: true},
  46631. hmdEnabled: {default: true},
  46632. pointerLockEnabled: {default: false},
  46633. reverseMouseDrag: {default: false},
  46634. reverseTouchDrag: {default: false},
  46635. touchEnabled: {default: true}
  46636. },
  46637. init: function () {
  46638. this.deltaYaw = 0;
  46639. this.previousHMDPosition = new THREE.Vector3();
  46640. this.hmdQuaternion = new THREE.Quaternion();
  46641. this.magicWindowAbsoluteEuler = new THREE.Euler();
  46642. this.magicWindowDeltaEuler = new THREE.Euler();
  46643. this.position = new THREE.Vector3();
  46644. this.magicWindowObject = new THREE.Object3D();
  46645. this.rotation = {};
  46646. this.deltaRotation = {};
  46647. this.savedPose = null;
  46648. this.pointerLocked = false;
  46649. this.setupMouseControls();
  46650. this.bindMethods();
  46651. this.setupMagicWindowControls();
  46652. // To save / restore camera pose
  46653. this.savedPose = {
  46654. position: new THREE.Vector3(),
  46655. rotation: new THREE.Euler()
  46656. };
  46657. // Call enter VR handler if the scene has entered VR before the event listeners attached.
  46658. if (this.el.sceneEl.is('vr-mode')) { this.onEnterVR(); }
  46659. },
  46660. setupMagicWindowControls: function () {
  46661. var magicWindowControls;
  46662. // Only on mobile devices and only enabled if DeviceOrientation permission has been granted.
  46663. if (utils.device.isMobile()) {
  46664. magicWindowControls = this.magicWindowControls = new THREE.DeviceOrientationControls(this.magicWindowObject);
  46665. if (typeof DeviceOrientationEvent !== 'undefined' && DeviceOrientationEvent.requestPermission) {
  46666. magicWindowControls.enabled = false;
  46667. if (this.el.sceneEl.components['device-orientation-permission-ui'].permissionGranted) {
  46668. magicWindowControls.enabled = true;
  46669. } else {
  46670. this.el.sceneEl.addEventListener('deviceorientationpermissiongranted', function () {
  46671. magicWindowControls.enabled = true;
  46672. });
  46673. }
  46674. }
  46675. }
  46676. },
  46677. update: function (oldData) {
  46678. var data = this.data;
  46679. // Disable grab cursor classes if no longer enabled.
  46680. if (data.enabled !== oldData.enabled) {
  46681. this.updateGrabCursor(data.enabled);
  46682. }
  46683. // Reset pitch and yaw if disabling HMD.
  46684. if (oldData && !data.hmdEnabled && !oldData.hmdEnabled) {
  46685. this.pitchObject.rotation.set(0, 0, 0);
  46686. this.yawObject.rotation.set(0, 0, 0);
  46687. }
  46688. if (oldData && !data.pointerLockEnabled !== oldData.pointerLockEnabled) {
  46689. this.removeEventListeners();
  46690. this.addEventListeners();
  46691. if (this.pointerLocked) { this.exitPointerLock(); }
  46692. }
  46693. },
  46694. tick: function (t) {
  46695. var data = this.data;
  46696. if (!data.enabled) { return; }
  46697. this.updateOrientation();
  46698. },
  46699. play: function () {
  46700. this.addEventListeners();
  46701. },
  46702. pause: function () {
  46703. this.removeEventListeners();
  46704. if (this.pointerLocked) { this.exitPointerLock(); }
  46705. },
  46706. remove: function () {
  46707. this.removeEventListeners();
  46708. if (this.pointerLocked) { this.exitPointerLock(); }
  46709. },
  46710. bindMethods: function () {
  46711. this.onMouseDown = bind(this.onMouseDown, this);
  46712. this.onMouseMove = bind(this.onMouseMove, this);
  46713. this.onMouseUp = bind(this.onMouseUp, this);
  46714. this.onTouchStart = bind(this.onTouchStart, this);
  46715. this.onTouchMove = bind(this.onTouchMove, this);
  46716. this.onTouchEnd = bind(this.onTouchEnd, this);
  46717. this.onEnterVR = bind(this.onEnterVR, this);
  46718. this.onExitVR = bind(this.onExitVR, this);
  46719. this.onPointerLockChange = bind(this.onPointerLockChange, this);
  46720. this.onPointerLockError = bind(this.onPointerLockError, this);
  46721. },
  46722. /**
  46723. * Set up states and Object3Ds needed to store rotation data.
  46724. */
  46725. setupMouseControls: function () {
  46726. this.mouseDown = false;
  46727. this.pitchObject = new THREE.Object3D();
  46728. this.yawObject = new THREE.Object3D();
  46729. this.yawObject.position.y = 10;
  46730. this.yawObject.add(this.pitchObject);
  46731. },
  46732. /**
  46733. * Add mouse and touch event listeners to canvas.
  46734. */
  46735. addEventListeners: function () {
  46736. var sceneEl = this.el.sceneEl;
  46737. var canvasEl = sceneEl.canvas;
  46738. // Wait for canvas to load.
  46739. if (!canvasEl) {
  46740. sceneEl.addEventListener('render-target-loaded', bind(this.addEventListeners, this));
  46741. return;
  46742. }
  46743. // Mouse events.
  46744. canvasEl.addEventListener('mousedown', this.onMouseDown, false);
  46745. window.addEventListener('mousemove', this.onMouseMove, false);
  46746. window.addEventListener('mouseup', this.onMouseUp, false);
  46747. // Touch events.
  46748. canvasEl.addEventListener('touchstart', this.onTouchStart);
  46749. window.addEventListener('touchmove', this.onTouchMove);
  46750. window.addEventListener('touchend', this.onTouchEnd);
  46751. // sceneEl events.
  46752. sceneEl.addEventListener('enter-vr', this.onEnterVR);
  46753. sceneEl.addEventListener('exit-vr', this.onExitVR);
  46754. // Pointer Lock events.
  46755. if (this.data.pointerLockEnabled) {
  46756. document.addEventListener('pointerlockchange', this.onPointerLockChange, false);
  46757. document.addEventListener('mozpointerlockchange', this.onPointerLockChange, false);
  46758. document.addEventListener('pointerlockerror', this.onPointerLockError, false);
  46759. }
  46760. },
  46761. /**
  46762. * Remove mouse and touch event listeners from canvas.
  46763. */
  46764. removeEventListeners: function () {
  46765. var sceneEl = this.el.sceneEl;
  46766. var canvasEl = sceneEl && sceneEl.canvas;
  46767. if (!canvasEl) { return; }
  46768. // Mouse events.
  46769. canvasEl.removeEventListener('mousedown', this.onMouseDown);
  46770. window.removeEventListener('mousemove', this.onMouseMove);
  46771. window.removeEventListener('mouseup', this.onMouseUp);
  46772. // Touch events.
  46773. canvasEl.removeEventListener('touchstart', this.onTouchStart);
  46774. window.removeEventListener('touchmove', this.onTouchMove);
  46775. window.removeEventListener('touchend', this.onTouchEnd);
  46776. // sceneEl events.
  46777. sceneEl.removeEventListener('enter-vr', this.onEnterVR);
  46778. sceneEl.removeEventListener('exit-vr', this.onExitVR);
  46779. // Pointer Lock events.
  46780. document.removeEventListener('pointerlockchange', this.onPointerLockChange, false);
  46781. document.removeEventListener('mozpointerlockchange', this.onPointerLockChange, false);
  46782. document.removeEventListener('pointerlockerror', this.onPointerLockError, false);
  46783. },
  46784. /**
  46785. * Update orientation for mobile, mouse drag, and headset.
  46786. * Mouse-drag only enabled if HMD is not active.
  46787. */
  46788. updateOrientation: (function () {
  46789. var poseMatrix = new THREE.Matrix4();
  46790. return function () {
  46791. var object3D = this.el.object3D;
  46792. var pitchObject = this.pitchObject;
  46793. var yawObject = this.yawObject;
  46794. var pose;
  46795. var sceneEl = this.el.sceneEl;
  46796. // In VR mode, THREE is in charge of updating the camera pose.
  46797. if (sceneEl.is('vr-mode') && sceneEl.checkHeadsetConnected()) {
  46798. // With WebXR THREE applies headset pose to the object3D matrixWorld internally.
  46799. // Reflect values back on position, rotation, scale for getAttribute to return the expected values.
  46800. if (sceneEl.hasWebXR) {
  46801. pose = sceneEl.renderer.xr.getCameraPose();
  46802. if (pose) {
  46803. poseMatrix.elements = pose.transform.matrix;
  46804. poseMatrix.decompose(object3D.position, object3D.rotation, object3D.scale);
  46805. }
  46806. }
  46807. return;
  46808. }
  46809. this.updateMagicWindowOrientation();
  46810. // On mobile, do camera rotation with touch events and sensors.
  46811. object3D.rotation.x = this.magicWindowDeltaEuler.x + pitchObject.rotation.x;
  46812. object3D.rotation.y = this.magicWindowDeltaEuler.y + yawObject.rotation.y;
  46813. object3D.rotation.z = this.magicWindowDeltaEuler.z;
  46814. };
  46815. })(),
  46816. updateMagicWindowOrientation: function () {
  46817. var magicWindowAbsoluteEuler = this.magicWindowAbsoluteEuler;
  46818. var magicWindowDeltaEuler = this.magicWindowDeltaEuler;
  46819. // Calculate magic window HMD quaternion.
  46820. if (this.magicWindowControls && this.magicWindowControls.enabled) {
  46821. this.magicWindowControls.update();
  46822. magicWindowAbsoluteEuler.setFromQuaternion(this.magicWindowObject.quaternion, 'YXZ');
  46823. if (!this.previousMagicWindowYaw && magicWindowAbsoluteEuler.y !== 0) {
  46824. this.previousMagicWindowYaw = magicWindowAbsoluteEuler.y;
  46825. }
  46826. if (this.previousMagicWindowYaw) {
  46827. magicWindowDeltaEuler.x = magicWindowAbsoluteEuler.x;
  46828. magicWindowDeltaEuler.y += magicWindowAbsoluteEuler.y - this.previousMagicWindowYaw;
  46829. magicWindowDeltaEuler.z = magicWindowAbsoluteEuler.z;
  46830. this.previousMagicWindowYaw = magicWindowAbsoluteEuler.y;
  46831. }
  46832. }
  46833. },
  46834. /**
  46835. * Translate mouse drag into rotation.
  46836. *
  46837. * Dragging up and down rotates the camera around the X-axis (yaw).
  46838. * Dragging left and right rotates the camera around the Y-axis (pitch).
  46839. */
  46840. onMouseMove: function (event) {
  46841. var direction;
  46842. var movementX;
  46843. var movementY;
  46844. var pitchObject = this.pitchObject;
  46845. var previousMouseEvent = this.previousMouseEvent;
  46846. var yawObject = this.yawObject;
  46847. // Not dragging or not enabled.
  46848. if (!this.data.enabled || (!this.mouseDown && !this.pointerLocked)) { return; }
  46849. // Calculate delta.
  46850. if (this.pointerLocked) {
  46851. movementX = event.movementX || event.mozMovementX || 0;
  46852. movementY = event.movementY || event.mozMovementY || 0;
  46853. } else {
  46854. movementX = event.screenX - previousMouseEvent.screenX;
  46855. movementY = event.screenY - previousMouseEvent.screenY;
  46856. }
  46857. this.previousMouseEvent = event;
  46858. // Calculate rotation.
  46859. direction = this.data.reverseMouseDrag ? 1 : -1;
  46860. yawObject.rotation.y += movementX * 0.002 * direction;
  46861. pitchObject.rotation.x += movementY * 0.002 * direction;
  46862. pitchObject.rotation.x = Math.max(-PI_2, Math.min(PI_2, pitchObject.rotation.x));
  46863. },
  46864. /**
  46865. * Register mouse down to detect mouse drag.
  46866. */
  46867. onMouseDown: function (evt) {
  46868. var sceneEl = this.el.sceneEl;
  46869. if (!this.data.enabled || (sceneEl.is('vr-mode') && sceneEl.checkHeadsetConnected())) { return; }
  46870. // Handle only primary button.
  46871. if (evt.button !== 0) { return; }
  46872. var canvasEl = sceneEl && sceneEl.canvas;
  46873. this.mouseDown = true;
  46874. this.previousMouseEvent = evt;
  46875. this.showGrabbingCursor();
  46876. if (this.data.pointerLockEnabled && !this.pointerLocked) {
  46877. if (canvasEl.requestPointerLock) {
  46878. canvasEl.requestPointerLock();
  46879. } else if (canvasEl.mozRequestPointerLock) {
  46880. canvasEl.mozRequestPointerLock();
  46881. }
  46882. }
  46883. },
  46884. /**
  46885. * Shows grabbing cursor on scene
  46886. */
  46887. showGrabbingCursor: function () {
  46888. this.el.sceneEl.canvas.style.cursor = 'grabbing';
  46889. },
  46890. /**
  46891. * Hides grabbing cursor on scene
  46892. */
  46893. hideGrabbingCursor: function () {
  46894. this.el.sceneEl.canvas.style.cursor = '';
  46895. },
  46896. /**
  46897. * Register mouse up to detect release of mouse drag.
  46898. */
  46899. onMouseUp: function () {
  46900. this.mouseDown = false;
  46901. this.hideGrabbingCursor();
  46902. },
  46903. /**
  46904. * Register touch down to detect touch drag.
  46905. */
  46906. onTouchStart: function (evt) {
  46907. if (evt.touches.length !== 1 ||
  46908. !this.data.touchEnabled ||
  46909. this.el.sceneEl.is('vr-mode')) { return; }
  46910. this.touchStart = {
  46911. x: evt.touches[0].pageX,
  46912. y: evt.touches[0].pageY
  46913. };
  46914. this.touchStarted = true;
  46915. },
  46916. /**
  46917. * Translate touch move to Y-axis rotation.
  46918. */
  46919. onTouchMove: function (evt) {
  46920. var direction;
  46921. var canvas = this.el.sceneEl.canvas;
  46922. var deltaY;
  46923. var yawObject = this.yawObject;
  46924. if (!this.touchStarted || !this.data.touchEnabled) { return; }
  46925. deltaY = 2 * Math.PI * (evt.touches[0].pageX - this.touchStart.x) / canvas.clientWidth;
  46926. direction = this.data.reverseTouchDrag ? 1 : -1;
  46927. // Limit touch orientaion to to yaw (y axis).
  46928. yawObject.rotation.y -= deltaY * 0.5 * direction;
  46929. this.touchStart = {
  46930. x: evt.touches[0].pageX,
  46931. y: evt.touches[0].pageY
  46932. };
  46933. },
  46934. /**
  46935. * Register touch end to detect release of touch drag.
  46936. */
  46937. onTouchEnd: function () {
  46938. this.touchStarted = false;
  46939. },
  46940. /**
  46941. * Save pose.
  46942. */
  46943. onEnterVR: function () {
  46944. var sceneEl = this.el.sceneEl;
  46945. if (!sceneEl.checkHeadsetConnected()) { return; }
  46946. this.saveCameraPose();
  46947. this.el.object3D.position.set(0, 0, 0);
  46948. this.el.object3D.rotation.set(0, 0, 0);
  46949. if (sceneEl.hasWebXR) {
  46950. this.el.object3D.matrixAutoUpdate = false;
  46951. this.el.object3D.updateMatrix();
  46952. }
  46953. },
  46954. /**
  46955. * Restore the pose.
  46956. */
  46957. onExitVR: function () {
  46958. if (!this.el.sceneEl.checkHeadsetConnected()) { return; }
  46959. this.restoreCameraPose();
  46960. this.previousHMDPosition.set(0, 0, 0);
  46961. this.el.object3D.matrixAutoUpdate = true;
  46962. },
  46963. /**
  46964. * Update Pointer Lock state.
  46965. */
  46966. onPointerLockChange: function () {
  46967. this.pointerLocked = !!(document.pointerLockElement || document.mozPointerLockElement);
  46968. },
  46969. /**
  46970. * Recover from Pointer Lock error.
  46971. */
  46972. onPointerLockError: function () {
  46973. this.pointerLocked = false;
  46974. },
  46975. // Exits pointer-locked mode.
  46976. exitPointerLock: function () {
  46977. document.exitPointerLock();
  46978. this.pointerLocked = false;
  46979. },
  46980. /**
  46981. * Toggle the feature of showing/hiding the grab cursor.
  46982. */
  46983. updateGrabCursor: function (enabled) {
  46984. var sceneEl = this.el.sceneEl;
  46985. function enableGrabCursor () { sceneEl.canvas.classList.add('a-grab-cursor'); }
  46986. function disableGrabCursor () { sceneEl.canvas.classList.remove('a-grab-cursor'); }
  46987. if (!sceneEl.canvas) {
  46988. if (enabled) {
  46989. sceneEl.addEventListener('render-target-loaded', enableGrabCursor);
  46990. } else {
  46991. sceneEl.addEventListener('render-target-loaded', disableGrabCursor);
  46992. }
  46993. return;
  46994. }
  46995. if (enabled) {
  46996. enableGrabCursor();
  46997. return;
  46998. }
  46999. disableGrabCursor();
  47000. },
  47001. /**
  47002. * Save camera pose before entering VR to restore later if exiting.
  47003. */
  47004. saveCameraPose: function () {
  47005. var el = this.el;
  47006. this.savedPose.position.copy(el.object3D.position);
  47007. this.savedPose.rotation.copy(el.object3D.rotation);
  47008. this.hasSavedPose = true;
  47009. },
  47010. /**
  47011. * Reset camera pose to before entering VR.
  47012. */
  47013. restoreCameraPose: function () {
  47014. var el = this.el;
  47015. var savedPose = this.savedPose;
  47016. if (!this.hasSavedPose) { return; }
  47017. // Reset camera orientation.
  47018. el.object3D.position.copy(savedPose.position);
  47019. el.object3D.rotation.copy(savedPose.rotation);
  47020. this.hasSavedPose = false;
  47021. }
  47022. });
  47023. },{"../core/component":128,"../lib/three":176,"../utils/":202}],88:[function(_dereq_,module,exports){
  47024. var bind = _dereq_('../utils/bind');
  47025. var registerComponent = _dereq_('../core/component').registerComponent;
  47026. var trackedControlsUtils = _dereq_('../utils/tracked-controls');
  47027. var checkControllerPresentAndSetup = trackedControlsUtils.checkControllerPresentAndSetup;
  47028. var emitIfAxesChanged = trackedControlsUtils.emitIfAxesChanged;
  47029. var onButtonEvent = trackedControlsUtils.onButtonEvent;
  47030. // See Profiles Registry:
  47031. // https://github.com/immersive-web/webxr-input-profiles/tree/master/packages/registry
  47032. // TODO: Add a more robust system for deriving gamepad name.
  47033. var GAMEPAD_ID_PREFIX = 'magicleap';
  47034. var GAMEPAD_ID_SUFFIX = '-one';
  47035. var GAMEPAD_ID_COMPOSITE = GAMEPAD_ID_PREFIX + GAMEPAD_ID_SUFFIX;
  47036. var MAGICLEAP_CONTROLLER_MODEL_GLB_URL = 'https://cdn.aframe.io/controllers/magicleap/magicleap-one-controller.glb';
  47037. /**
  47038. * Button IDs:
  47039. * 0 - trigger
  47040. * 1 - grip
  47041. * 2 - touchpad
  47042. * 3 - menu (never dispatched on this layer)
  47043. *
  47044. * Axis:
  47045. * 0 - touchpad x axis
  47046. * 1 - touchpad y axis
  47047. */
  47048. var INPUT_MAPPING_WEBXR = {
  47049. axes: {touchpad: [0, 1]},
  47050. buttons: ['trigger', 'grip', 'touchpad', 'menu']
  47051. };
  47052. /**
  47053. * Magic Leap Controls
  47054. * Interface with Magic Leap control and map Gamepad events to controller
  47055. * buttons: trigger, grip, touchpad, and menu.
  47056. * Load a controller model.
  47057. */
  47058. module.exports.Component = registerComponent('magicleap-controls', {
  47059. schema: {
  47060. hand: {default: 'none'},
  47061. model: {default: true},
  47062. orientationOffset: {type: 'vec3'}
  47063. },
  47064. mapping: INPUT_MAPPING_WEBXR,
  47065. init: function () {
  47066. var self = this;
  47067. this.controllerPresent = false;
  47068. this.lastControllerCheck = 0;
  47069. this.onButtonChanged = bind(this.onButtonChanged, this);
  47070. this.onButtonDown = function (evt) { onButtonEvent(evt.detail.id, 'down', self); };
  47071. this.onButtonUp = function (evt) { onButtonEvent(evt.detail.id, 'up', self); };
  47072. this.onButtonTouchEnd = function (evt) { onButtonEvent(evt.detail.id, 'touchend', self); };
  47073. this.onButtonTouchStart = function (evt) { onButtonEvent(evt.detail.id, 'touchstart', self); };
  47074. this.previousButtonValues = {};
  47075. this.rendererSystem = this.el.sceneEl.systems.renderer;
  47076. this.bindMethods();
  47077. },
  47078. update: function () {
  47079. var data = this.data;
  47080. this.controllerIndex = data.hand === 'right' ? 0 : data.hand === 'left' ? 1 : 2;
  47081. },
  47082. play: function () {
  47083. this.checkIfControllerPresent();
  47084. this.addControllersUpdateListener();
  47085. },
  47086. pause: function () {
  47087. this.removeEventListeners();
  47088. this.removeControllersUpdateListener();
  47089. },
  47090. bindMethods: function () {
  47091. this.onModelLoaded = bind(this.onModelLoaded, this);
  47092. this.onControllersUpdate = bind(this.onControllersUpdate, this);
  47093. this.checkIfControllerPresent = bind(this.checkIfControllerPresent, this);
  47094. this.removeControllersUpdateListener = bind(this.removeControllersUpdateListener, this);
  47095. this.onAxisMoved = bind(this.onAxisMoved, this);
  47096. },
  47097. addEventListeners: function () {
  47098. var el = this.el;
  47099. el.addEventListener('buttonchanged', this.onButtonChanged);
  47100. el.addEventListener('buttondown', this.onButtonDown);
  47101. el.addEventListener('buttonup', this.onButtonUp);
  47102. el.addEventListener('touchstart', this.onButtonTouchStart);
  47103. el.addEventListener('touchend', this.onButtonTouchEnd);
  47104. el.addEventListener('axismove', this.onAxisMoved);
  47105. el.addEventListener('model-loaded', this.onModelLoaded);
  47106. this.controllerEventsActive = true;
  47107. },
  47108. removeEventListeners: function () {
  47109. var el = this.el;
  47110. el.removeEventListener('buttonchanged', this.onButtonChanged);
  47111. el.removeEventListener('buttondown', this.onButtonDown);
  47112. el.removeEventListener('buttonup', this.onButtonUp);
  47113. el.removeEventListener('touchstart', this.onButtonTouchStart);
  47114. el.removeEventListener('touchend', this.onButtonTouchEnd);
  47115. el.removeEventListener('axismove', this.onAxisMoved);
  47116. el.removeEventListener('model-loaded', this.onModelLoaded);
  47117. this.controllerEventsActive = false;
  47118. },
  47119. checkIfControllerPresent: function () {
  47120. var data = this.data;
  47121. checkControllerPresentAndSetup(this, GAMEPAD_ID_COMPOSITE,
  47122. {index: this.controllerIndex, hand: data.hand});
  47123. },
  47124. injectTrackedControls: function () {
  47125. var el = this.el;
  47126. var data = this.data;
  47127. el.setAttribute('tracked-controls', {
  47128. // TODO: verify expected behavior between reserved prefixes.
  47129. idPrefix: GAMEPAD_ID_COMPOSITE,
  47130. hand: data.hand,
  47131. controller: this.controllerIndex,
  47132. orientationOffset: data.orientationOffset
  47133. });
  47134. // Load model.
  47135. if (!this.data.model) { return; }
  47136. this.el.setAttribute('gltf-model', MAGICLEAP_CONTROLLER_MODEL_GLB_URL);
  47137. },
  47138. addControllersUpdateListener: function () {
  47139. this.el.sceneEl.addEventListener('controllersupdated', this.onControllersUpdate, false);
  47140. },
  47141. removeControllersUpdateListener: function () {
  47142. this.el.sceneEl.removeEventListener('controllersupdated', this.onControllersUpdate, false);
  47143. },
  47144. onControllersUpdate: function () {
  47145. // Note that due to gamepadconnected event propagation issues, we don't rely on events.
  47146. this.checkIfControllerPresent();
  47147. },
  47148. /**
  47149. * Rotate the trigger button based on how hard the trigger is pressed.
  47150. */
  47151. onButtonChanged: function (evt) {
  47152. var button = this.mapping.buttons[evt.detail.id];
  47153. var analogValue;
  47154. if (!button) { return; }
  47155. if (button === 'trigger') {
  47156. analogValue = evt.detail.state.value;
  47157. console.log('analog value of trigger press: ' + analogValue);
  47158. }
  47159. // Pass along changed event with button state, using button mapping for convenience.
  47160. this.el.emit(button + 'changed', evt.detail.state);
  47161. },
  47162. onModelLoaded: function (evt) {
  47163. var controllerObject3D = evt.detail.model;
  47164. // our glb scale is too large.
  47165. controllerObject3D.scale.set(0.01, 0.01, 0.01);
  47166. },
  47167. onAxisMoved: function (evt) {
  47168. emitIfAxesChanged(this, this.mapping.axes, evt);
  47169. },
  47170. updateModel: function (buttonName, evtName) {},
  47171. setButtonColor: function (buttonName, color) {}
  47172. });
  47173. },{"../core/component":128,"../utils/bind":196,"../utils/tracked-controls":210}],89:[function(_dereq_,module,exports){
  47174. /* global Promise */
  47175. var utils = _dereq_('../utils/');
  47176. var component = _dereq_('../core/component');
  47177. var THREE = _dereq_('../lib/three');
  47178. var shader = _dereq_('../core/shader');
  47179. var error = utils.debug('components:material:error');
  47180. var registerComponent = component.registerComponent;
  47181. var shaders = shader.shaders;
  47182. var shaderNames = shader.shaderNames;
  47183. /**
  47184. * Material component.
  47185. *
  47186. * @member {object} shader - Determines how material is shaded. Defaults to `standard`,
  47187. * three.js's implementation of PBR. Another standard shading model is `flat` which
  47188. * uses MeshBasicMaterial.
  47189. */
  47190. module.exports.Component = registerComponent('material', {
  47191. schema: {
  47192. alphaTest: {default: 0.0, min: 0.0, max: 1.0},
  47193. depthTest: {default: true},
  47194. depthWrite: {default: true},
  47195. flatShading: {default: false},
  47196. npot: {default: false},
  47197. offset: {type: 'vec2', default: {x: 0, y: 0}},
  47198. opacity: {default: 1.0, min: 0.0, max: 1.0},
  47199. repeat: {type: 'vec2', default: {x: 1, y: 1}},
  47200. shader: {default: 'standard', oneOf: shaderNames, schemaChange: true},
  47201. side: {default: 'front', oneOf: ['front', 'back', 'double']},
  47202. transparent: {default: false},
  47203. vertexColors: {type: 'string', default: 'none', oneOf: ['face', 'vertex']},
  47204. visible: {default: true},
  47205. blending: {default: 'normal', oneOf: ['none', 'normal', 'additive', 'subtractive', 'multiply']},
  47206. dithering: {default: true}
  47207. },
  47208. init: function () {
  47209. this.material = null;
  47210. },
  47211. /**
  47212. * Update or create material.
  47213. *
  47214. * @param {object|null} oldData
  47215. */
  47216. update: function (oldData) {
  47217. var data = this.data;
  47218. if (!this.shader || data.shader !== oldData.shader) {
  47219. this.updateShader(data.shader);
  47220. }
  47221. this.shader.update(this.data);
  47222. this.updateMaterial(oldData);
  47223. },
  47224. updateSchema: function (data) {
  47225. var currentShader;
  47226. var newShader;
  47227. var schema;
  47228. var shader;
  47229. newShader = data && data.shader;
  47230. currentShader = this.oldData && this.oldData.shader;
  47231. shader = newShader || currentShader;
  47232. schema = shaders[shader] && shaders[shader].schema;
  47233. if (!schema) { error('Unknown shader schema ' + shader); }
  47234. if (currentShader && newShader === currentShader) { return; }
  47235. this.extendSchema(schema);
  47236. this.updateBehavior();
  47237. },
  47238. updateBehavior: function () {
  47239. var key;
  47240. var sceneEl = this.el.sceneEl;
  47241. var schema = this.schema;
  47242. var self = this;
  47243. var tickProperties;
  47244. function tickTime (time, delta) {
  47245. var key;
  47246. for (key in tickProperties) {
  47247. tickProperties[key] = time;
  47248. }
  47249. self.shader.update(tickProperties);
  47250. }
  47251. this.tick = undefined;
  47252. tickProperties = {};
  47253. for (key in schema) {
  47254. if (schema[key].type === 'time') {
  47255. this.tick = tickTime;
  47256. tickProperties[key] = true;
  47257. }
  47258. }
  47259. if (!sceneEl) { return; }
  47260. if (this.tick) {
  47261. sceneEl.addBehavior(this);
  47262. } else {
  47263. sceneEl.removeBehavior(this);
  47264. }
  47265. },
  47266. updateShader: function (shaderName) {
  47267. var data = this.data;
  47268. var Shader = shaders[shaderName] && shaders[shaderName].Shader;
  47269. var shaderInstance;
  47270. if (!Shader) { throw new Error('Unknown shader ' + shaderName); }
  47271. // Get material from A-Frame shader.
  47272. shaderInstance = this.shader = new Shader();
  47273. shaderInstance.el = this.el;
  47274. shaderInstance.init(data);
  47275. this.setMaterial(shaderInstance.material);
  47276. this.updateSchema(data);
  47277. },
  47278. /**
  47279. * Set and update base material properties.
  47280. * Set `needsUpdate` when needed.
  47281. */
  47282. updateMaterial: function (oldData) {
  47283. var data = this.data;
  47284. var material = this.material;
  47285. var oldDataHasKeys;
  47286. // Base material properties.
  47287. material.alphaTest = data.alphaTest;
  47288. material.depthTest = data.depthTest !== false;
  47289. material.depthWrite = data.depthWrite !== false;
  47290. material.opacity = data.opacity;
  47291. material.flatShading = data.flatShading;
  47292. material.side = parseSide(data.side);
  47293. material.transparent = data.transparent !== false || data.opacity < 1.0;
  47294. material.vertexColors = parseVertexColors(data.vertexColors);
  47295. material.visible = data.visible;
  47296. material.blending = parseBlending(data.blending);
  47297. material.dithering = data.dithering;
  47298. // Check if material needs update.
  47299. for (oldDataHasKeys in oldData) { break; }
  47300. if (oldDataHasKeys &&
  47301. (oldData.alphaTest !== data.alphaTest ||
  47302. oldData.side !== data.side ||
  47303. oldData.vertexColors !== data.vertexColors)) {
  47304. material.needsUpdate = true;
  47305. }
  47306. },
  47307. /**
  47308. * Remove material on remove (callback).
  47309. * Dispose of it from memory and unsubscribe from scene updates.
  47310. */
  47311. remove: function () {
  47312. var defaultMaterial = new THREE.MeshBasicMaterial();
  47313. var material = this.material;
  47314. var object3D = this.el.getObject3D('mesh');
  47315. if (object3D) { object3D.material = defaultMaterial; }
  47316. disposeMaterial(material, this.system);
  47317. },
  47318. /**
  47319. * (Re)create new material. Has side-effects of setting `this.material` and updating
  47320. * material registration in scene.
  47321. *
  47322. * @param {object} data - Material component data.
  47323. * @param {object} type - Material type to create.
  47324. * @returns {object} Material.
  47325. */
  47326. setMaterial: function (material) {
  47327. var el = this.el;
  47328. var mesh;
  47329. var system = this.system;
  47330. if (this.material) { disposeMaterial(this.material, system); }
  47331. this.material = material;
  47332. system.registerMaterial(material);
  47333. // Set on mesh. If mesh does not exist, wait for it.
  47334. mesh = el.getObject3D('mesh');
  47335. if (mesh) {
  47336. mesh.material = material;
  47337. } else {
  47338. el.addEventListener('object3dset', function waitForMesh (evt) {
  47339. if (evt.detail.type !== 'mesh' || evt.target !== el) { return; }
  47340. el.getObject3D('mesh').material = material;
  47341. el.removeEventListener('object3dset', waitForMesh);
  47342. });
  47343. }
  47344. }
  47345. });
  47346. /**
  47347. * Return a three.js constant determining which material face sides to render
  47348. * based on the side parameter (passed as a component property).
  47349. *
  47350. * @param {string} [side=front] - `front`, `back`, or `double`.
  47351. * @returns {number} THREE.FrontSide, THREE.BackSide, or THREE.DoubleSide.
  47352. */
  47353. function parseSide (side) {
  47354. switch (side) {
  47355. case 'back': {
  47356. return THREE.BackSide;
  47357. }
  47358. case 'double': {
  47359. return THREE.DoubleSide;
  47360. }
  47361. default: {
  47362. // Including case `front`.
  47363. return THREE.FrontSide;
  47364. }
  47365. }
  47366. }
  47367. /**
  47368. * Return a three.js constant determining vertex coloring.
  47369. */
  47370. function parseVertexColors (coloring) {
  47371. switch (coloring) {
  47372. case 'face': {
  47373. return THREE.FaceColors;
  47374. }
  47375. case 'vertex': {
  47376. return THREE.VertexColors;
  47377. }
  47378. default: {
  47379. return THREE.NoColors;
  47380. }
  47381. }
  47382. }
  47383. /**
  47384. * Return a three.js constant determining blending
  47385. *
  47386. * @param {string} [blending=normal]
  47387. * - `none`, additive`, `subtractive`,`multiply` or `normal`.
  47388. * @returns {number}
  47389. */
  47390. function parseBlending (blending) {
  47391. switch (blending) {
  47392. case 'none': {
  47393. return THREE.NoBlending;
  47394. }
  47395. case 'additive': {
  47396. return THREE.AdditiveBlending;
  47397. }
  47398. case 'subtractive': {
  47399. return THREE.SubtractiveBlending;
  47400. }
  47401. case 'multiply': {
  47402. return THREE.MultiplyBlending;
  47403. }
  47404. default: {
  47405. return THREE.NormalBlending;
  47406. }
  47407. }
  47408. }
  47409. /**
  47410. * Dispose of material from memory and unsubscribe material from scene updates like fog.
  47411. */
  47412. function disposeMaterial (material, system) {
  47413. material.dispose();
  47414. system.unregisterMaterial(material);
  47415. }
  47416. },{"../core/component":128,"../core/shader":138,"../lib/three":176,"../utils/":202}],90:[function(_dereq_,module,exports){
  47417. var debug = _dereq_('../utils/debug');
  47418. var registerComponent = _dereq_('../core/component').registerComponent;
  47419. var THREE = _dereq_('../lib/three');
  47420. var warn = debug('components:obj-model:warn');
  47421. module.exports.Component = registerComponent('obj-model', {
  47422. schema: {
  47423. mtl: {type: 'model'},
  47424. obj: {type: 'model'}
  47425. },
  47426. init: function () {
  47427. var self = this;
  47428. this.model = null;
  47429. this.objLoader = new THREE.OBJLoader();
  47430. this.mtlLoader = new THREE.MTLLoader(this.objLoader.manager);
  47431. // Allow cross-origin images to be loaded.
  47432. this.mtlLoader.crossOrigin = '';
  47433. this.el.addEventListener('componentinitialized', function (evt) {
  47434. if (!self.model) { return; }
  47435. if (evt.detail.name !== 'material') { return; }
  47436. self.applyMaterial();
  47437. });
  47438. },
  47439. update: function () {
  47440. var data = this.data;
  47441. if (!data.obj) { return; }
  47442. this.resetMesh();
  47443. this.loadObj(data.obj, data.mtl);
  47444. },
  47445. remove: function () {
  47446. if (!this.model) { return; }
  47447. this.resetMesh();
  47448. },
  47449. resetMesh: function () {
  47450. this.el.removeObject3D('mesh');
  47451. },
  47452. loadObj: function (objUrl, mtlUrl) {
  47453. var self = this;
  47454. var el = this.el;
  47455. var mtlLoader = this.mtlLoader;
  47456. var objLoader = this.objLoader;
  47457. var rendererSystem = this.el.sceneEl.systems.renderer;
  47458. var BASE_PATH = mtlUrl.substr(0, mtlUrl.lastIndexOf('/') + 1);
  47459. if (mtlUrl) {
  47460. // .OBJ with an .MTL.
  47461. if (el.hasAttribute('material')) {
  47462. warn('Material component properties are ignored when a .MTL is provided');
  47463. }
  47464. mtlLoader.setResourcePath(BASE_PATH);
  47465. mtlLoader.load(mtlUrl, function (materials) {
  47466. materials.preload();
  47467. objLoader.setMaterials(materials);
  47468. objLoader.load(objUrl, function (objModel) {
  47469. self.model = objModel;
  47470. self.model.traverse(function (object) {
  47471. if (object.isMesh) {
  47472. var material = object.material;
  47473. if (material.color) rendererSystem.applyColorCorrection(material.color);
  47474. if (material.map) rendererSystem.applyColorCorrection(material.map);
  47475. if (material.emissive) rendererSystem.applyColorCorrection(material.emissive);
  47476. if (material.emissiveMap) rendererSystem.applyColorCorrection(material.emissiveMap);
  47477. }
  47478. });
  47479. el.setObject3D('mesh', objModel);
  47480. el.emit('model-loaded', {format: 'obj', model: objModel});
  47481. });
  47482. });
  47483. return;
  47484. }
  47485. // .OBJ only.
  47486. objLoader.load(objUrl, function loadObjOnly (objModel) {
  47487. self.model = objModel;
  47488. self.applyMaterial();
  47489. el.setObject3D('mesh', objModel);
  47490. el.emit('model-loaded', {format: 'obj', model: objModel});
  47491. });
  47492. },
  47493. /**
  47494. * Apply material from material component recursively.
  47495. */
  47496. applyMaterial: function () {
  47497. var material = this.el.components.material;
  47498. if (!material) { return; }
  47499. this.model.traverse(function (child) {
  47500. if (child instanceof THREE.Mesh) {
  47501. child.material = material.material;
  47502. }
  47503. });
  47504. }
  47505. });
  47506. },{"../core/component":128,"../lib/three":176,"../utils/debug":198}],91:[function(_dereq_,module,exports){
  47507. var registerComponent = _dereq_('../core/component').registerComponent;
  47508. var bind = _dereq_('../utils/bind');
  47509. var trackedControlsUtils = _dereq_('../utils/tracked-controls');
  47510. var checkControllerPresentAndSetup = trackedControlsUtils.checkControllerPresentAndSetup;
  47511. var emitIfAxesChanged = trackedControlsUtils.emitIfAxesChanged;
  47512. var onButtonEvent = trackedControlsUtils.onButtonEvent;
  47513. var isWebXRAvailable = _dereq_('../utils/').device.isWebXRAvailable;
  47514. var GAMEPAD_ID_WEBXR = 'oculus-go';
  47515. var GAMEPAD_ID_WEBVR = 'Oculus Go';
  47516. var OCULUS_GO_CONTROLLER_MODEL_URL = 'https://cdn.aframe.io/controllers/oculus/go/oculus-go-controller.gltf';
  47517. // Prefix for Gen1 and Gen2 Oculus Touch Controllers.
  47518. var GAMEPAD_ID_PREFIX = isWebXRAvailable ? GAMEPAD_ID_WEBXR : GAMEPAD_ID_WEBVR;
  47519. /**
  47520. * Button indices:
  47521. * 0 - trackpad
  47522. * 1 - trigger
  47523. *
  47524. * Axis:
  47525. * 0 - trackpad x
  47526. * 1 - trackpad y
  47527. */
  47528. var INPUT_MAPPING_WEBVR = {
  47529. axes: {trackpad: [0, 1]},
  47530. buttons: ['trackpad', 'trigger']
  47531. };
  47532. /**
  47533. * Button indices:
  47534. * 0 - trigger
  47535. * 1 - none
  47536. * 2 - touchpad
  47537. *
  47538. * Axis:
  47539. * 0 - touchpad x
  47540. * 1 - touchpad y
  47541. * Reference: https://github.com/immersive-web/webxr-input-profiles/blob/master/packages/registry/profiles/oculus/oculus-go.json
  47542. */
  47543. var INPUT_MAPPING_WEBXR = {
  47544. axes: {touchpad: [0, 1]},
  47545. buttons: ['trigger', 'none', 'touchpad']
  47546. };
  47547. var INPUT_MAPPING = isWebXRAvailable ? INPUT_MAPPING_WEBXR : INPUT_MAPPING_WEBVR;
  47548. /**
  47549. * Oculus Go controls.
  47550. * Interface with Oculus Go controller and map Gamepad events to
  47551. * controller buttons: trackpad, trigger
  47552. * Load a controller model and highlight the pressed buttons.
  47553. */
  47554. module.exports.Component = registerComponent('oculus-go-controls', {
  47555. schema: {
  47556. hand: {default: ''}, // This informs the degenerate arm model.
  47557. buttonColor: {type: 'color', default: '#FFFFFF'},
  47558. buttonTouchedColor: {type: 'color', default: '#BBBBBB'},
  47559. buttonHighlightColor: {type: 'color', default: '#7A7A7A'},
  47560. model: {default: true},
  47561. orientationOffset: {type: 'vec3'},
  47562. armModel: {default: true}
  47563. },
  47564. /**
  47565. * Button IDs:
  47566. * 0 - trackpad
  47567. * 1 - trigger
  47568. */
  47569. mapping: INPUT_MAPPING,
  47570. bindMethods: function () {
  47571. this.onModelLoaded = bind(this.onModelLoaded, this);
  47572. this.onControllersUpdate = bind(this.onControllersUpdate, this);
  47573. this.checkIfControllerPresent = bind(this.checkIfControllerPresent, this);
  47574. this.removeControllersUpdateListener = bind(this.removeControllersUpdateListener, this);
  47575. this.onAxisMoved = bind(this.onAxisMoved, this);
  47576. },
  47577. init: function () {
  47578. var self = this;
  47579. this.onButtonChanged = bind(this.onButtonChanged, this);
  47580. this.onButtonDown = function (evt) { onButtonEvent(evt.detail.id, 'down', self); };
  47581. this.onButtonUp = function (evt) { onButtonEvent(evt.detail.id, 'up', self); };
  47582. this.onButtonTouchStart = function (evt) { onButtonEvent(evt.detail.id, 'touchstart', self); };
  47583. this.onButtonTouchEnd = function (evt) { onButtonEvent(evt.detail.id, 'touchend', self); };
  47584. this.controllerPresent = false;
  47585. this.lastControllerCheck = 0;
  47586. this.rendererSystem = this.el.sceneEl.systems.renderer;
  47587. this.bindMethods();
  47588. },
  47589. addEventListeners: function () {
  47590. var el = this.el;
  47591. el.addEventListener('buttonchanged', this.onButtonChanged);
  47592. el.addEventListener('buttondown', this.onButtonDown);
  47593. el.addEventListener('buttonup', this.onButtonUp);
  47594. el.addEventListener('touchstart', this.onButtonTouchStart);
  47595. el.addEventListener('touchend', this.onButtonTouchEnd);
  47596. el.addEventListener('model-loaded', this.onModelLoaded);
  47597. el.addEventListener('axismove', this.onAxisMoved);
  47598. this.controllerEventsActive = true;
  47599. },
  47600. removeEventListeners: function () {
  47601. var el = this.el;
  47602. el.removeEventListener('buttonchanged', this.onButtonChanged);
  47603. el.removeEventListener('buttondown', this.onButtonDown);
  47604. el.removeEventListener('buttonup', this.onButtonUp);
  47605. el.removeEventListener('touchstart', this.onButtonTouchStart);
  47606. el.removeEventListener('touchend', this.onButtonTouchEnd);
  47607. el.removeEventListener('model-loaded', this.onModelLoaded);
  47608. el.removeEventListener('axismove', this.onAxisMoved);
  47609. this.controllerEventsActive = false;
  47610. },
  47611. checkIfControllerPresent: function () {
  47612. checkControllerPresentAndSetup(this, GAMEPAD_ID_PREFIX,
  47613. this.data.hand ? {hand: this.data.hand} : {});
  47614. },
  47615. play: function () {
  47616. this.checkIfControllerPresent();
  47617. this.addControllersUpdateListener();
  47618. },
  47619. pause: function () {
  47620. this.removeEventListeners();
  47621. this.removeControllersUpdateListener();
  47622. },
  47623. injectTrackedControls: function () {
  47624. var el = this.el;
  47625. var data = this.data;
  47626. el.setAttribute('tracked-controls', {
  47627. armModel: data.armModel,
  47628. hand: data.hand,
  47629. idPrefix: GAMEPAD_ID_PREFIX,
  47630. orientationOffset: data.orientationOffset
  47631. });
  47632. if (!this.data.model) { return; }
  47633. this.el.setAttribute('gltf-model', OCULUS_GO_CONTROLLER_MODEL_URL);
  47634. },
  47635. addControllersUpdateListener: function () {
  47636. this.el.sceneEl.addEventListener('controllersupdated', this.onControllersUpdate, false);
  47637. },
  47638. removeControllersUpdateListener: function () {
  47639. this.el.sceneEl.removeEventListener('controllersupdated', this.onControllersUpdate, false);
  47640. },
  47641. onControllersUpdate: function () {
  47642. this.checkIfControllerPresent();
  47643. },
  47644. // No need for onButtonChanged, since Oculus Go controller has no analog buttons.
  47645. onModelLoaded: function (evt) {
  47646. var controllerObject3D = evt.detail.model;
  47647. var buttonMeshes;
  47648. if (!this.data.model) { return; }
  47649. buttonMeshes = this.buttonMeshes = {};
  47650. buttonMeshes.trigger = controllerObject3D.getObjectByName('oculus_go_button_trigger');
  47651. buttonMeshes.trackpad = controllerObject3D.getObjectByName('oculus_go_touchpad');
  47652. },
  47653. onButtonChanged: function (evt) {
  47654. var button = this.mapping.buttons[evt.detail.id];
  47655. if (!button) return;
  47656. // Pass along changed event with button state, using button mapping for convenience.
  47657. this.el.emit(button + 'changed', evt.detail.state);
  47658. },
  47659. onAxisMoved: function (evt) {
  47660. emitIfAxesChanged(this, this.mapping.axes, evt);
  47661. },
  47662. updateModel: function (buttonName, evtName) {
  47663. if (!this.data.model) { return; }
  47664. this.updateButtonModel(buttonName, evtName);
  47665. },
  47666. updateButtonModel: function (buttonName, state) {
  47667. var buttonMeshes = this.buttonMeshes;
  47668. if (!buttonMeshes || !buttonMeshes[buttonName]) { return; }
  47669. var color;
  47670. var button;
  47671. switch (state) {
  47672. case 'down':
  47673. color = this.data.buttonHighlightColor;
  47674. break;
  47675. case 'touchstart':
  47676. color = this.data.buttonTouchedColor;
  47677. break;
  47678. default:
  47679. color = this.data.buttonColor;
  47680. }
  47681. button = buttonMeshes[buttonName];
  47682. button.material.color.set(color);
  47683. this.rendererSystem.applyColorCorrection(button.material.color);
  47684. }
  47685. });
  47686. },{"../core/component":128,"../utils/":202,"../utils/bind":196,"../utils/tracked-controls":210}],92:[function(_dereq_,module,exports){
  47687. var bind = _dereq_('../utils/bind');
  47688. var registerComponent = _dereq_('../core/component').registerComponent;
  47689. var THREE = _dereq_('../lib/three');
  47690. var trackedControlsUtils = _dereq_('../utils/tracked-controls');
  47691. var checkControllerPresentAndSetup = trackedControlsUtils.checkControllerPresentAndSetup;
  47692. var emitIfAxesChanged = trackedControlsUtils.emitIfAxesChanged;
  47693. var onButtonEvent = trackedControlsUtils.onButtonEvent;
  47694. var isOculusBrowser = _dereq_('../utils/').device.isOculusBrowser();
  47695. var isWebXRAvailable = _dereq_('../utils/').device.isWebXRAvailable;
  47696. var GAMEPAD_ID_WEBXR = 'oculus-touch';
  47697. var GAMEPAD_ID_WEBVR = 'Oculus Touch';
  47698. // Prefix for Gen1 and Gen2 Oculus Touch Controllers.
  47699. var GAMEPAD_ID_PREFIX = isWebXRAvailable ? GAMEPAD_ID_WEBXR : GAMEPAD_ID_WEBVR;
  47700. // First generation model URL.
  47701. var TOUCH_CONTROLLER_MODEL_BASE_URL = 'https://cdn.aframe.io/controllers/oculus/oculus-touch-controller-';
  47702. // For now the generation 2 model is the same as the original until a new one is prepared for upload.
  47703. var TOUCH_GEN2_CONTROLLER_MODEL_BASE_URL = TOUCH_CONTROLLER_MODEL_BASE_URL;
  47704. var OCULUS_TOUCH_WEBVR = {
  47705. left: {
  47706. modelUrl: TOUCH_CONTROLLER_MODEL_BASE_URL + 'left.gltf',
  47707. rayOrigin: {origin: {x: 0.008, y: -0.01, z: 0}, direction: {x: 0, y: -0.8, z: -1}},
  47708. modelPivotOffset: new THREE.Vector3(-0.005, 0.003, -0.055),
  47709. modelPivotRotation: new THREE.Euler(0, 0, 0)
  47710. },
  47711. right: {
  47712. modelUrl: TOUCH_CONTROLLER_MODEL_BASE_URL + 'right.gltf',
  47713. rayOrigin: {origin: {x: -0.008, y: -0.01, z: 0}, direction: {x: 0, y: -0.8, z: -1}},
  47714. modelPivotOffset: new THREE.Vector3(0.005, 0.003, -0.055),
  47715. modelPivotRotation: new THREE.Euler(0, 0, 0)
  47716. }
  47717. };
  47718. var OCULUS_TOUCH_WEBXR = {
  47719. left: {
  47720. modelUrl: TOUCH_CONTROLLER_MODEL_BASE_URL + 'left.gltf',
  47721. rayOrigin: {origin: {x: 0.002, y: -0.005, z: -0.03}, direction: {x: 0, y: -0.8, z: -1}},
  47722. modelPivotOffset: new THREE.Vector3(-0.005, 0.036, -0.037),
  47723. modelPivotRotation: new THREE.Euler(Math.PI / 4.5, 0, 0)
  47724. },
  47725. right: {
  47726. modelUrl: TOUCH_CONTROLLER_MODEL_BASE_URL + 'right.gltf',
  47727. rayOrigin: {origin: {x: -0.002, y: -0.005, z: -0.03}, direction: {x: 0, y: -0.8, z: -1}},
  47728. modelPivotOffset: new THREE.Vector3(0.005, 0.036, -0.037),
  47729. modelPivotRotation: new THREE.Euler(Math.PI / 4.5, 0, 0)
  47730. }
  47731. };
  47732. var OCULUS_TOUCH_CONFIG = isWebXRAvailable ? OCULUS_TOUCH_WEBXR : OCULUS_TOUCH_WEBVR;
  47733. var CONTROLLER_DEFAULT = 'oculus-touch';
  47734. var CONTROLLER_PROPERTIES = {
  47735. 'oculus-touch': OCULUS_TOUCH_CONFIG,
  47736. 'oculus-touch-v2': {
  47737. left: {
  47738. modelUrl: TOUCH_GEN2_CONTROLLER_MODEL_BASE_URL + 'gen2-left.gltf',
  47739. rayOrigin: {origin: {x: -0.01, y: 0, z: -0.02}, direction: {x: 0, y: -0.5, z: -1}},
  47740. modelPivotOffset: new THREE.Vector3(0, 0, 0),
  47741. modelPivotRotation: new THREE.Euler(0, 0, 0)
  47742. },
  47743. right: {
  47744. modelUrl: TOUCH_GEN2_CONTROLLER_MODEL_BASE_URL + 'gen2-right.gltf',
  47745. rayOrigin: {origin: {x: 0.01, y: 0, z: -0.02}, direction: {x: 0, y: -0.5, z: -1}},
  47746. modelPivotOffset: new THREE.Vector3(0, 0, 0),
  47747. modelPivotRotation: new THREE.Euler(0, 0, 0)
  47748. }
  47749. }
  47750. };
  47751. /**
  47752. * Button indices:
  47753. * 0 - thumbstick (which has separate axismove / thumbstickmoved events)
  47754. * 1 - trigger (with analog value, which goes up to 1)
  47755. * 2 - grip (with analog value, which goes up to 1)
  47756. * 3 - X (left) or A (right)
  47757. * 4 - Y (left) or B (right)
  47758. * 5 - surface (touch only)
  47759. */
  47760. var INPUT_MAPPING_WEBVR = {
  47761. left: {
  47762. axes: {thumbstick: [0, 1]},
  47763. buttons: ['thumbstick', 'trigger', 'grip', 'xbutton', 'ybutton', 'surface']
  47764. },
  47765. right: {
  47766. axes: {thumbstick: [0, 1]},
  47767. buttons: ['thumbstick', 'trigger', 'grip', 'abutton', 'bbutton', 'surface']
  47768. }
  47769. };
  47770. /**
  47771. * Button indices:
  47772. * 0 - trigger
  47773. * 1 - grip
  47774. * 2 - none
  47775. * 3 - thumbstick
  47776. * 4 - X or A button
  47777. * 5 - Y or B button
  47778. * 6 - surface
  47779. *
  47780. * Axis:
  47781. * 0 - none
  47782. * 1 - none
  47783. * 2 - thumbstick
  47784. * 3 - thumbstick
  47785. * Reference: https://github.com/immersive-web/webxr-input-profiles/blob/master/packages/registry/profiles/oculus/oculus-touch.json
  47786. */
  47787. var INPUT_MAPPING_WEBXR = {
  47788. left: {
  47789. axes: {thumbstick: [2, 3]},
  47790. buttons: ['trigger', 'grip', 'none', 'thumbstick', 'xbutton', 'ybutton', 'surface']
  47791. },
  47792. right: {
  47793. axes: {thumbstick: [2, 3]},
  47794. buttons: ['trigger', 'grip', 'none', 'thumbstick', 'abutton', 'bbutton', 'surface']
  47795. }
  47796. };
  47797. var INPUT_MAPPING = isWebXRAvailable ? INPUT_MAPPING_WEBXR : INPUT_MAPPING_WEBVR;
  47798. /**
  47799. * Oculus Touch controls.
  47800. * Interface with Oculus Touch controllers and map Gamepad events to
  47801. * controller buttons: thumbstick, trigger, grip, xbutton, ybutton, surface
  47802. * Load a controller model and highlight the pressed buttons.
  47803. */
  47804. module.exports.Component = registerComponent('oculus-touch-controls', {
  47805. schema: {
  47806. hand: {default: 'left'},
  47807. buttonColor: {type: 'color', default: '#999'}, // Off-white.
  47808. buttonTouchColor: {type: 'color', default: '#8AB'},
  47809. buttonHighlightColor: {type: 'color', default: '#2DF'}, // Light blue.
  47810. model: {default: true},
  47811. controllerType: {default: 'auto', oneOf: ['auto', 'oculus-touch', 'oculus-touch-v2']},
  47812. orientationOffset: {type: 'vec3', default: {x: 43, y: 0, z: 0}}
  47813. },
  47814. mapping: INPUT_MAPPING,
  47815. bindMethods: function () {
  47816. this.onModelLoaded = bind(this.onModelLoaded, this);
  47817. this.onControllersUpdate = bind(this.onControllersUpdate, this);
  47818. this.checkIfControllerPresent = bind(this.checkIfControllerPresent, this);
  47819. this.onAxisMoved = bind(this.onAxisMoved, this);
  47820. },
  47821. init: function () {
  47822. var self = this;
  47823. this.onButtonChanged = bind(this.onButtonChanged, this);
  47824. this.onButtonDown = function (evt) { onButtonEvent(evt.detail.id, 'down', self, self.data.hand); };
  47825. this.onButtonUp = function (evt) { onButtonEvent(evt.detail.id, 'up', self, self.data.hand); };
  47826. this.onButtonTouchStart = function (evt) { onButtonEvent(evt.detail.id, 'touchstart', self, self.data.hand); };
  47827. this.onButtonTouchEnd = function (evt) { onButtonEvent(evt.detail.id, 'touchend', self, self.data.hand); };
  47828. this.controllerPresent = false;
  47829. this.lastControllerCheck = 0;
  47830. this.previousButtonValues = {};
  47831. this.rendererSystem = this.el.sceneEl.systems.renderer;
  47832. this.bindMethods();
  47833. },
  47834. addEventListeners: function () {
  47835. var el = this.el;
  47836. el.addEventListener('buttonchanged', this.onButtonChanged);
  47837. el.addEventListener('buttondown', this.onButtonDown);
  47838. el.addEventListener('buttonup', this.onButtonUp);
  47839. el.addEventListener('touchstart', this.onButtonTouchStart);
  47840. el.addEventListener('touchend', this.onButtonTouchEnd);
  47841. el.addEventListener('axismove', this.onAxisMoved);
  47842. el.addEventListener('model-loaded', this.onModelLoaded);
  47843. this.controllerEventsActive = true;
  47844. },
  47845. removeEventListeners: function () {
  47846. var el = this.el;
  47847. el.removeEventListener('buttonchanged', this.onButtonChanged);
  47848. el.removeEventListener('buttondown', this.onButtonDown);
  47849. el.removeEventListener('buttonup', this.onButtonUp);
  47850. el.removeEventListener('touchstart', this.onButtonTouchStart);
  47851. el.removeEventListener('touchend', this.onButtonTouchEnd);
  47852. el.removeEventListener('axismove', this.onAxisMoved);
  47853. el.removeEventListener('model-loaded', this.onModelLoaded);
  47854. this.controllerEventsActive = false;
  47855. },
  47856. checkIfControllerPresent: function () {
  47857. checkControllerPresentAndSetup(this, GAMEPAD_ID_PREFIX, {
  47858. hand: this.data.hand
  47859. });
  47860. },
  47861. play: function () {
  47862. this.checkIfControllerPresent();
  47863. this.addControllersUpdateListener();
  47864. },
  47865. pause: function () {
  47866. this.removeEventListeners();
  47867. this.removeControllersUpdateListener();
  47868. },
  47869. loadModel: function () {
  47870. var data = this.data;
  47871. if (!data.model) { return; }
  47872. // Set the controller display model based on the data passed in.
  47873. this.displayModel = CONTROLLER_PROPERTIES[data.controllerType] || CONTROLLER_PROPERTIES[CONTROLLER_DEFAULT];
  47874. // If the developer is asking for auto-detection, see if the displayName can be retrieved to identify the specific unit.
  47875. // This only works for WebVR currently.
  47876. if (data.controllerType === 'auto') {
  47877. var trackedControlsSystem = this.el.sceneEl.systems['tracked-controls-webvr'];
  47878. if (trackedControlsSystem && trackedControlsSystem.vrDisplay) {
  47879. var displayName = trackedControlsSystem.vrDisplay.displayName;
  47880. // The Oculus Quest uses the updated generation 2 inside-out tracked controllers so update the displayModel.
  47881. if (/^Oculus Quest$/.test(displayName)) {
  47882. this.displayModel = CONTROLLER_PROPERTIES['oculus-touch-v2'];
  47883. }
  47884. }
  47885. if (isOculusBrowser) { this.displayModel = CONTROLLER_PROPERTIES['oculus-touch-v2']; }
  47886. }
  47887. var modelUrl = this.displayModel[data.hand].modelUrl;
  47888. this.el.setAttribute('gltf-model', modelUrl);
  47889. },
  47890. injectTrackedControls: function () {
  47891. var data = this.data;
  47892. var webXRId = GAMEPAD_ID_WEBXR;
  47893. var webVRId = data.hand === 'right' ? 'Oculus Touch (Right)' : 'Oculus Touch (Left)';
  47894. var id = isWebXRAvailable ? webXRId : webVRId;
  47895. this.el.setAttribute('tracked-controls', {
  47896. id: id,
  47897. hand: data.hand,
  47898. orientationOffset: data.orientationOffset
  47899. });
  47900. this.loadModel();
  47901. },
  47902. addControllersUpdateListener: function () {
  47903. this.el.sceneEl.addEventListener('controllersupdated', this.onControllersUpdate, false);
  47904. },
  47905. removeControllersUpdateListener: function () {
  47906. this.el.sceneEl.removeEventListener('controllersupdated', this.onControllersUpdate, false);
  47907. },
  47908. onControllersUpdate: function () {
  47909. // Note that due to gamepadconnected event propagation issues, we don't rely on events.
  47910. this.checkIfControllerPresent();
  47911. },
  47912. onButtonChanged: function (evt) {
  47913. var button = this.mapping[this.data.hand].buttons[evt.detail.id];
  47914. var buttonMeshes = this.buttonMeshes;
  47915. var analogValue;
  47916. if (!button) { return; }
  47917. if (button === 'trigger' || button === 'grip') { analogValue = evt.detail.state.value; }
  47918. // Update trigger and/or grip meshes, if any.
  47919. if (buttonMeshes) {
  47920. if (button === 'trigger' && buttonMeshes.trigger) {
  47921. buttonMeshes.trigger.rotation.x = this.originalXRotationTrigger - analogValue * (Math.PI / 26);
  47922. }
  47923. if (button === 'grip' && buttonMeshes.grip) {
  47924. buttonMeshes.grip.position.x = this.originalXPositionGrip + (this.data.hand === 'left' ? -1 : 1) * analogValue * 0.004;
  47925. }
  47926. }
  47927. // Pass along changed event with button state, using the buttom mapping for convenience.
  47928. this.el.emit(button + 'changed', evt.detail.state);
  47929. },
  47930. onModelLoaded: function (evt) {
  47931. var controllerObject3D = evt.detail.model;
  47932. var buttonMeshes;
  47933. if (!this.data.model) { return; }
  47934. buttonMeshes = this.buttonMeshes = {};
  47935. buttonMeshes.grip = controllerObject3D.getObjectByName('buttonHand');
  47936. this.originalXPositionGrip = buttonMeshes.grip.position.x;
  47937. buttonMeshes.thumbstick = controllerObject3D.getObjectByName('stick');
  47938. buttonMeshes.trigger = controllerObject3D.getObjectByName('buttonTrigger');
  47939. this.originalXRotationTrigger = buttonMeshes.trigger.rotation.x;
  47940. buttonMeshes.xbutton = controllerObject3D.getObjectByName('buttonX');
  47941. buttonMeshes.abutton = controllerObject3D.getObjectByName('buttonA');
  47942. buttonMeshes.ybutton = controllerObject3D.getObjectByName('buttonY');
  47943. buttonMeshes.bbutton = controllerObject3D.getObjectByName('buttonB');
  47944. // Offset pivot point
  47945. controllerObject3D.position.copy(this.displayModel[this.data.hand].modelPivotOffset);
  47946. controllerObject3D.rotation.copy(this.displayModel[this.data.hand].modelPivotRotation);
  47947. this.el.emit('controllermodelready', {
  47948. name: 'oculus-touch-controls',
  47949. model: this.data.model,
  47950. rayOrigin: this.displayModel[this.data.hand].rayOrigin
  47951. });
  47952. },
  47953. onAxisMoved: function (evt) {
  47954. emitIfAxesChanged(this, this.mapping[this.data.hand].axes, evt);
  47955. },
  47956. updateModel: function (buttonName, evtName) {
  47957. if (!this.data.model) { return; }
  47958. this.updateButtonModel(buttonName, evtName);
  47959. },
  47960. updateButtonModel: function (buttonName, state) {
  47961. var button;
  47962. var color = (state === 'up' || state === 'touchend') ? this.data.buttonColor : state === 'touchstart' ? this.data.buttonTouchColor : this.data.buttonHighlightColor;
  47963. var buttonMeshes = this.buttonMeshes;
  47964. if (!this.data.model) { return; }
  47965. if (buttonMeshes && buttonMeshes[buttonName]) {
  47966. button = buttonMeshes[buttonName];
  47967. button.material.color.set(color);
  47968. this.rendererSystem.applyColorCorrection(button.material.color);
  47969. }
  47970. }
  47971. });
  47972. },{"../core/component":128,"../lib/three":176,"../utils/":202,"../utils/bind":196,"../utils/tracked-controls":210}],93:[function(_dereq_,module,exports){
  47973. var registerComponent = _dereq_('../core/component').registerComponent;
  47974. module.exports.Component = registerComponent('position', {
  47975. schema: {type: 'vec3'},
  47976. update: function () {
  47977. var object3D = this.el.object3D;
  47978. var data = this.data;
  47979. object3D.position.set(data.x, data.y, data.z);
  47980. },
  47981. remove: function () {
  47982. // Pretty much for mixins.
  47983. this.el.object3D.position.set(0, 0, 0);
  47984. }
  47985. });
  47986. },{"../core/component":128}],94:[function(_dereq_,module,exports){
  47987. /* global MutationObserver */
  47988. var registerComponent = _dereq_('../core/component').registerComponent;
  47989. var THREE = _dereq_('../lib/three');
  47990. var utils = _dereq_('../utils/');
  47991. var warn = utils.debug('components:raycaster:warn');
  47992. // Defines selectors that should be 'safe' for the MutationObserver used to
  47993. // refresh the whitelist. Matches classnames, IDs, and presence of attributes.
  47994. // Selectors for the value of an attribute, like [position=0 2 0], cannot be
  47995. // reliably detected and are therefore disallowed.
  47996. var OBSERVER_SELECTOR_RE = /^[\w\s-.,[\]#]*$/;
  47997. // Configuration for the MutationObserver used to refresh the whitelist.
  47998. // Listens for addition/removal of elements and attributes within the scene.
  47999. var OBSERVER_CONFIG = {
  48000. childList: true,
  48001. attributes: true,
  48002. subtree: true
  48003. };
  48004. var EVENTS = {
  48005. INTERSECT: 'raycaster-intersected',
  48006. INTERSECTION: 'raycaster-intersection',
  48007. INTERSECT_CLEAR: 'raycaster-intersected-cleared',
  48008. INTERSECTION_CLEAR: 'raycaster-intersection-cleared'
  48009. };
  48010. /**
  48011. * Raycaster component.
  48012. *
  48013. * Pass options to three.js Raycaster including which objects to test.
  48014. * Poll for intersections.
  48015. * Emit event on origin entity and on target entity on intersect.
  48016. *
  48017. * @member {array} intersectedEls - List of currently intersected entities.
  48018. * @member {array} objects - Cached list of meshes to intersect.
  48019. * @member {number} prevCheckTime - Previous time intersection was checked. To help interval.
  48020. * @member {object} raycaster - three.js Raycaster.
  48021. */
  48022. module.exports.Component = registerComponent('raycaster', {
  48023. schema: {
  48024. autoRefresh: {default: true},
  48025. direction: {type: 'vec3', default: {x: 0, y: 0, z: -1}},
  48026. enabled: {default: true},
  48027. far: {default: 1000},
  48028. interval: {default: 0},
  48029. near: {default: 0},
  48030. objects: {default: ''},
  48031. origin: {type: 'vec3'},
  48032. showLine: {default: false},
  48033. useWorldCoordinates: {default: false}
  48034. },
  48035. multiple: true,
  48036. init: function () {
  48037. this.clearedIntersectedEls = [];
  48038. this.unitLineEndVec3 = new THREE.Vector3();
  48039. this.intersectedEls = [];
  48040. this.intersections = [];
  48041. this.newIntersectedEls = [];
  48042. this.newIntersections = [];
  48043. this.objects = [];
  48044. this.prevCheckTime = undefined;
  48045. this.prevIntersectedEls = [];
  48046. this.rawIntersections = [];
  48047. this.raycaster = new THREE.Raycaster();
  48048. this.updateOriginDirection();
  48049. this.setDirty = this.setDirty.bind(this);
  48050. this.updateLine = this.updateLine.bind(this);
  48051. this.observer = new MutationObserver(this.setDirty);
  48052. this.dirty = true;
  48053. this.lineEndVec3 = new THREE.Vector3();
  48054. this.otherLineEndVec3 = new THREE.Vector3();
  48055. this.lineData = {end: this.lineEndVec3};
  48056. this.getIntersection = this.getIntersection.bind(this);
  48057. this.intersectedDetail = {el: this.el, getIntersection: this.getIntersection};
  48058. this.intersectedClearedDetail = {el: this.el};
  48059. this.intersectionClearedDetail = {clearedEls: this.clearedIntersectedEls};
  48060. this.intersectionDetail = {};
  48061. },
  48062. /**
  48063. * Create or update raycaster object.
  48064. */
  48065. update: function (oldData) {
  48066. var data = this.data;
  48067. var el = this.el;
  48068. var raycaster = this.raycaster;
  48069. // Set raycaster properties.
  48070. raycaster.far = data.far;
  48071. raycaster.near = data.near;
  48072. // Draw line.
  48073. if (data.showLine &&
  48074. (data.far !== oldData.far || data.origin !== oldData.origin ||
  48075. data.direction !== oldData.direction || !oldData.showLine)) {
  48076. // Calculate unit vector for line direction. Can be multiplied via scalar to performantly
  48077. // adjust line length.
  48078. this.unitLineEndVec3.copy(data.origin).add(data.direction).normalize();
  48079. this.drawLine();
  48080. }
  48081. if (!data.showLine && oldData.showLine) {
  48082. el.removeAttribute('line');
  48083. }
  48084. if (data.objects !== oldData.objects && !OBSERVER_SELECTOR_RE.test(data.objects)) {
  48085. warn('[raycaster] Selector "' + data.objects +
  48086. '" may not update automatically with DOM changes.');
  48087. }
  48088. if (!data.objects) {
  48089. warn('[raycaster] For performance, please define raycaster.objects when using ' +
  48090. 'raycaster or cursor components to whitelist which entities to intersect with. ' +
  48091. 'e.g., raycaster="objects: [data-raycastable]".');
  48092. }
  48093. if (data.autoRefresh !== oldData.autoRefresh && el.isPlaying) {
  48094. data.autoRefresh
  48095. ? this.addEventListeners()
  48096. : this.removeEventListeners();
  48097. }
  48098. if (oldData.enabled && !data.enabled) { this.clearAllIntersections(); }
  48099. this.setDirty();
  48100. },
  48101. play: function () {
  48102. this.addEventListeners();
  48103. },
  48104. pause: function () {
  48105. this.removeEventListeners();
  48106. },
  48107. remove: function () {
  48108. if (this.data.showLine) {
  48109. this.el.removeAttribute('line');
  48110. }
  48111. this.clearAllIntersections();
  48112. },
  48113. addEventListeners: function () {
  48114. if (!this.data.autoRefresh) { return; }
  48115. this.observer.observe(this.el.sceneEl, OBSERVER_CONFIG);
  48116. this.el.sceneEl.addEventListener('object3dset', this.setDirty);
  48117. this.el.sceneEl.addEventListener('object3dremove', this.setDirty);
  48118. },
  48119. removeEventListeners: function () {
  48120. this.observer.disconnect();
  48121. this.el.sceneEl.removeEventListener('object3dset', this.setDirty);
  48122. this.el.sceneEl.removeEventListener('object3dremove', this.setDirty);
  48123. },
  48124. /**
  48125. * Mark the object list as dirty, to be refreshed before next raycast.
  48126. */
  48127. setDirty: function () {
  48128. this.dirty = true;
  48129. },
  48130. /**
  48131. * Update list of objects to test for intersection.
  48132. */
  48133. refreshObjects: function () {
  48134. var data = this.data;
  48135. var els;
  48136. // If objects not defined, intersect with everything.
  48137. els = data.objects
  48138. ? this.el.sceneEl.querySelectorAll(data.objects)
  48139. : this.el.sceneEl.querySelectorAll('*');
  48140. this.objects = this.flattenObject3DMaps(els);
  48141. this.dirty = false;
  48142. },
  48143. /**
  48144. * Check for intersections and cleared intersections on an interval.
  48145. */
  48146. tick: function (time) {
  48147. var data = this.data;
  48148. var prevCheckTime = this.prevCheckTime;
  48149. if (!data.enabled) { return; }
  48150. // Only check for intersection if interval time has passed.
  48151. if (prevCheckTime && (time - prevCheckTime < data.interval)) { return; }
  48152. // Update check time.
  48153. this.prevCheckTime = time;
  48154. this.checkIntersections();
  48155. },
  48156. /**
  48157. * Raycast for intersections and emit events for current and cleared inersections.
  48158. */
  48159. checkIntersections: function () {
  48160. var clearedIntersectedEls = this.clearedIntersectedEls;
  48161. var el = this.el;
  48162. var data = this.data;
  48163. var i;
  48164. var intersectedEls = this.intersectedEls;
  48165. var intersection;
  48166. var intersections = this.intersections;
  48167. var newIntersectedEls = this.newIntersectedEls;
  48168. var newIntersections = this.newIntersections;
  48169. var prevIntersectedEls = this.prevIntersectedEls;
  48170. var rawIntersections = this.rawIntersections;
  48171. // Refresh the object whitelist if needed.
  48172. if (this.dirty) { this.refreshObjects(); }
  48173. // Store old previously intersected entities.
  48174. copyArray(this.prevIntersectedEls, this.intersectedEls);
  48175. // Raycast.
  48176. this.updateOriginDirection();
  48177. rawIntersections.length = 0;
  48178. this.raycaster.intersectObjects(this.objects, true, rawIntersections);
  48179. // Only keep intersections against objects that have a reference to an entity.
  48180. intersections.length = 0;
  48181. intersectedEls.length = 0;
  48182. for (i = 0; i < rawIntersections.length; i++) {
  48183. intersection = rawIntersections[i];
  48184. // Don't intersect with own line.
  48185. if (data.showLine && intersection.object === el.getObject3D('line')) {
  48186. continue;
  48187. }
  48188. if (intersection.object.el) {
  48189. intersections.push(intersection);
  48190. intersectedEls.push(intersection.object.el);
  48191. }
  48192. }
  48193. // Get newly intersected entities.
  48194. newIntersections.length = 0;
  48195. newIntersectedEls.length = 0;
  48196. for (i = 0; i < intersections.length; i++) {
  48197. if (prevIntersectedEls.indexOf(intersections[i].object.el) === -1) {
  48198. newIntersections.push(intersections[i]);
  48199. newIntersectedEls.push(intersections[i].object.el);
  48200. }
  48201. }
  48202. // Emit intersection cleared on both entities per formerly intersected entity.
  48203. clearedIntersectedEls.length = 0;
  48204. for (i = 0; i < prevIntersectedEls.length; i++) {
  48205. if (intersectedEls.indexOf(prevIntersectedEls[i]) !== -1) { continue; }
  48206. prevIntersectedEls[i].emit(EVENTS.INTERSECT_CLEAR,
  48207. this.intersectedClearedDetail);
  48208. clearedIntersectedEls.push(prevIntersectedEls[i]);
  48209. }
  48210. if (clearedIntersectedEls.length) {
  48211. el.emit(EVENTS.INTERSECTION_CLEAR, this.intersectionClearedDetail);
  48212. }
  48213. // Emit intersected on intersected entity per intersected entity.
  48214. for (i = 0; i < newIntersectedEls.length; i++) {
  48215. newIntersectedEls[i].emit(EVENTS.INTERSECT, this.intersectedDetail);
  48216. }
  48217. // Emit all intersections at once on raycasting entity.
  48218. if (newIntersections.length) {
  48219. this.intersectionDetail.els = newIntersectedEls;
  48220. this.intersectionDetail.intersections = newIntersections;
  48221. el.emit(EVENTS.INTERSECTION, this.intersectionDetail);
  48222. }
  48223. // Update line length.
  48224. if (data.showLine) { setTimeout(this.updateLine); }
  48225. },
  48226. updateLine: function () {
  48227. var el = this.el;
  48228. var intersections = this.intersections;
  48229. var lineLength;
  48230. if (intersections.length) {
  48231. if (intersections[0].object.el === el && intersections[1]) {
  48232. lineLength = intersections[1].distance;
  48233. } else {
  48234. lineLength = intersections[0].distance;
  48235. }
  48236. }
  48237. this.drawLine(lineLength);
  48238. },
  48239. /**
  48240. * Return the most recent intersection details for a given entity, if any.
  48241. * @param {AEntity} el
  48242. * @return {Object}
  48243. */
  48244. getIntersection: function (el) {
  48245. var i;
  48246. var intersection;
  48247. for (i = 0; i < this.intersections.length; i++) {
  48248. intersection = this.intersections[i];
  48249. if (intersection.object.el === el) { return intersection; }
  48250. }
  48251. return null;
  48252. },
  48253. /**
  48254. * Update origin and direction of raycaster using entity transforms and supplied origin or
  48255. * direction offsets.
  48256. */
  48257. updateOriginDirection: (function () {
  48258. var direction = new THREE.Vector3();
  48259. var originVec3 = new THREE.Vector3();
  48260. // Closure to make quaternion/vector3 objects private.
  48261. return function updateOriginDirection () {
  48262. var el = this.el;
  48263. var data = this.data;
  48264. if (data.useWorldCoordinates) {
  48265. this.raycaster.set(data.origin, data.direction);
  48266. return;
  48267. }
  48268. el.object3D.updateMatrixWorld();
  48269. originVec3.setFromMatrixPosition(el.object3D.matrixWorld);
  48270. // If non-zero origin, translate the origin into world space.
  48271. if (data.origin.x !== 0 || data.origin.y !== 0 || data.origin.z !== 0) {
  48272. originVec3 = el.object3D.localToWorld(originVec3.copy(data.origin));
  48273. }
  48274. // three.js raycaster direction is relative to 0, 0, 0 NOT the origin / offset we
  48275. // provide. Apply the offset to the direction, then rotation from the object,
  48276. // and normalize.
  48277. direction.copy(data.direction).transformDirection(el.object3D.matrixWorld).normalize();
  48278. // Apply offset and direction, in world coordinates.
  48279. this.raycaster.set(originVec3, direction);
  48280. };
  48281. })(),
  48282. /**
  48283. * Create or update line to give raycaster visual representation.
  48284. * Customize the line through through line component.
  48285. * We draw the line in the raycaster component to customize the line to the
  48286. * raycaster's origin, direction, and far.
  48287. *
  48288. * Unlike the raycaster, we create the line as a child of the object. The line will
  48289. * be affected by the transforms of the objects, so we don't have to calculate transforms
  48290. * like we do with the raycaster.
  48291. *
  48292. * @param {number} length - Length of line. Pass in to shorten the line to the intersection
  48293. * point. If not provided, length will default to the max length, `raycaster.far`.
  48294. */
  48295. drawLine: function (length) {
  48296. var data = this.data;
  48297. var el = this.el;
  48298. var endVec3;
  48299. // Switch each time vector so line update triggered and to avoid unnecessary vector clone.
  48300. endVec3 = this.lineData.end === this.lineEndVec3
  48301. ? this.otherLineEndVec3
  48302. : this.lineEndVec3;
  48303. // Treat Infinity as 1000m for the line.
  48304. if (length === undefined) {
  48305. length = data.far === Infinity ? 1000 : data.far;
  48306. }
  48307. // Update the length of the line if given. `unitLineEndVec3` is the direction
  48308. // given by data.direction, then we apply a scalar to give it a length.
  48309. this.lineData.start = data.origin;
  48310. this.lineData.end = endVec3.copy(this.unitLineEndVec3).multiplyScalar(length);
  48311. el.setAttribute('line', this.lineData);
  48312. },
  48313. /**
  48314. * Return A-Frame attachments of each element's object3D group (e.g., mesh).
  48315. * Children are flattened by one level, removing the THREE.Group wrapper,
  48316. * so that non-recursive raycasting remains useful.
  48317. *
  48318. * Only push children defined as component attachemnts (e.g., setObject3D),
  48319. * NOT actual children in the scene graph hierarchy.
  48320. *
  48321. * @param {Array<Element>} els
  48322. * @return {Array<THREE.Object3D>}
  48323. */
  48324. flattenObject3DMaps: function (els) {
  48325. var key;
  48326. var i;
  48327. var objects = this.objects;
  48328. // Push meshes and other attachments onto list of objects to intersect.
  48329. objects.length = 0;
  48330. for (i = 0; i < els.length; i++) {
  48331. if (els[i].isEntity && els[i].object3D) {
  48332. for (key in els[i].object3DMap) {
  48333. objects.push(els[i].getObject3D(key));
  48334. }
  48335. }
  48336. }
  48337. return objects;
  48338. },
  48339. clearAllIntersections: function () {
  48340. var i;
  48341. for (i = 0; i < this.intersectedEls.length; i++) {
  48342. this.intersectedEls[i].emit(EVENTS.INTERSECT_CLEAR,
  48343. this.intersectedClearedDetail);
  48344. }
  48345. copyArray(this.clearedIntersectedEls, this.intersectedEls);
  48346. this.intersectedEls.length = 0;
  48347. this.intersections.length = 0;
  48348. this.el.emit(EVENTS.INTERSECTION_CLEAR, this.intersectionClearedDetail);
  48349. }
  48350. });
  48351. /**
  48352. * Copy contents of one array to another without allocating new array.
  48353. */
  48354. function copyArray (a, b) {
  48355. var i;
  48356. a.length = b.length;
  48357. for (i = 0; i < b.length; i++) {
  48358. a[i] = b[i];
  48359. }
  48360. }
  48361. },{"../core/component":128,"../lib/three":176,"../utils/":202}],95:[function(_dereq_,module,exports){
  48362. var degToRad = _dereq_('../lib/three').Math.degToRad;
  48363. var registerComponent = _dereq_('../core/component').registerComponent;
  48364. module.exports.Component = registerComponent('rotation', {
  48365. schema: {type: 'vec3'},
  48366. /**
  48367. * Updates object3D rotation.
  48368. */
  48369. update: function () {
  48370. var data = this.data;
  48371. var object3D = this.el.object3D;
  48372. object3D.rotation.set(degToRad(data.x), degToRad(data.y), degToRad(data.z));
  48373. object3D.rotation.order = 'YXZ';
  48374. },
  48375. remove: function () {
  48376. // Pretty much for mixins.
  48377. this.el.object3D.rotation.set(0, 0, 0);
  48378. }
  48379. });
  48380. },{"../core/component":128,"../lib/three":176}],96:[function(_dereq_,module,exports){
  48381. var registerComponent = _dereq_('../core/component').registerComponent;
  48382. // Avoids triggering a zero-determinant which makes object3D matrix non-invertible.
  48383. var zeroScale = 0.00001;
  48384. module.exports.Component = registerComponent('scale', {
  48385. schema: {
  48386. type: 'vec3',
  48387. default: {x: 1, y: 1, z: 1}
  48388. },
  48389. update: function () {
  48390. var data = this.data;
  48391. var object3D = this.el.object3D;
  48392. var x = data.x === 0 ? zeroScale : data.x;
  48393. var y = data.y === 0 ? zeroScale : data.y;
  48394. var z = data.z === 0 ? zeroScale : data.z;
  48395. object3D.scale.set(x, y, z);
  48396. },
  48397. remove: function () {
  48398. // Pretty much for mixins.
  48399. this.el.object3D.scale.set(1, 1, 1);
  48400. }
  48401. });
  48402. },{"../core/component":128}],97:[function(_dereq_,module,exports){
  48403. /* global THREE */
  48404. var register = _dereq_('../../core/component').registerComponent;
  48405. module.exports.Component = register('background', {
  48406. schema: {
  48407. color: {type: 'color', default: 'black'},
  48408. transparent: {default: false}
  48409. },
  48410. update: function () {
  48411. var data = this.data;
  48412. var object3D = this.el.object3D;
  48413. if (data.transparent) {
  48414. object3D.background = null;
  48415. return;
  48416. }
  48417. object3D.background = new THREE.Color(data.color);
  48418. }
  48419. });
  48420. },{"../../core/component":128}],98:[function(_dereq_,module,exports){
  48421. var register = _dereq_('../../core/component').registerComponent;
  48422. module.exports.Component = register('debug', {
  48423. schema: {default: true}
  48424. });
  48425. },{"../../core/component":128}],99:[function(_dereq_,module,exports){
  48426. /* global DeviceOrientationEvent, location */
  48427. var registerComponent = _dereq_('../../core/component').registerComponent;
  48428. var utils = _dereq_('../../utils/');
  48429. var bind = utils.bind;
  48430. var constants = _dereq_('../../constants/');
  48431. var MODAL_CLASS = 'a-modal';
  48432. var DIALOG_CLASS = 'a-dialog';
  48433. var DIALOG_TEXT_CLASS = 'a-dialog-text';
  48434. var DIALOG_TEXT_CONTAINER_CLASS = 'a-dialog-text-container';
  48435. var DIALOG_BUTTONS_CONTAINER_CLASS = 'a-dialog-buttons-container';
  48436. var DIALOG_BUTTON_CLASS = 'a-dialog-button';
  48437. var DIALOG_ALLOW_BUTTON_CLASS = 'a-dialog-allow-button';
  48438. var DIALOG_DENY_BUTTON_CLASS = 'a-dialog-deny-button';
  48439. var DIALOG_OK_BUTTON_CLASS = 'a-dialog-ok-button';
  48440. /**
  48441. * UI for enabling device motion permission
  48442. */
  48443. module.exports.Component = registerComponent('device-orientation-permission-ui', {
  48444. schema: {enabled: {default: true}},
  48445. init: function () {
  48446. var self = this;
  48447. if (!this.data.enabled) { return; }
  48448. if (location.hostname !== 'localhost' &&
  48449. location.hostname !== '127.0.0.1' &&
  48450. location.protocol === 'http:') {
  48451. this.showHTTPAlert();
  48452. }
  48453. // Show alert on iPad if Safari is on desktop mode.
  48454. if (utils.device.isMobileDeviceRequestingDesktopSite()) {
  48455. this.showMobileDesktopModeAlert();
  48456. return;
  48457. }
  48458. // Browser doesn't support or doesn't require permission to DeviceOrientationEvent API.
  48459. if (typeof DeviceOrientationEvent === 'undefined' || !DeviceOrientationEvent.requestPermission) {
  48460. this.permissionGranted = true;
  48461. return;
  48462. }
  48463. this.onDeviceMotionDialogAllowClicked = bind(this.onDeviceMotionDialogAllowClicked, this);
  48464. this.onDeviceMotionDialogDenyClicked = bind(this.onDeviceMotionDialogDenyClicked, this);
  48465. // Show dialog only if permission has not yet been granted.
  48466. DeviceOrientationEvent.requestPermission().catch(function () {
  48467. self.devicePermissionDialogEl = createPermissionDialog(
  48468. 'This immersive website requires access to your device motion sensors.',
  48469. self.onDeviceMotionDialogAllowClicked,
  48470. self.onDeviceMotionDialogDenyClicked);
  48471. self.el.appendChild(self.devicePermissionDialogEl);
  48472. }).then(function () {
  48473. self.el.emit('deviceorientationpermissiongranted');
  48474. self.permissionGranted = true;
  48475. });
  48476. },
  48477. remove: function () {
  48478. // This removes the modal screen
  48479. if (this.devicePermissionDialogEl) { this.el.removeChild(this.devicePermissionDialogEl); }
  48480. },
  48481. onDeviceMotionDialogDenyClicked: function () {
  48482. this.remove();
  48483. },
  48484. showMobileDesktopModeAlert: function () {
  48485. var self = this;
  48486. var safariIpadAlertEl = createAlertDialog(
  48487. 'Set your browser to request the mobile version of the site and reload the page to enjoy immersive mode.',
  48488. function () { self.el.removeChild(safariIpadAlertEl); });
  48489. this.el.appendChild(safariIpadAlertEl);
  48490. },
  48491. showHTTPAlert: function () {
  48492. var self = this;
  48493. var httpAlertEl = createAlertDialog(
  48494. 'Access this site over HTTPS to enter VR mode and grant access to the device sensors.',
  48495. function () { self.el.removeChild(httpAlertEl); });
  48496. this.el.appendChild(httpAlertEl);
  48497. },
  48498. /**
  48499. * Enable device motion permission when clicked.
  48500. */
  48501. onDeviceMotionDialogAllowClicked: function () {
  48502. var self = this;
  48503. this.el.emit('deviceorientationpermissionrequested');
  48504. DeviceOrientationEvent.requestPermission().then(function (response) {
  48505. if (response === 'granted') {
  48506. self.el.emit('deviceorientationpermissiongranted');
  48507. self.permissionGranted = true;
  48508. } else {
  48509. self.el.emit('deviceorientationpermissionrejected');
  48510. }
  48511. self.remove();
  48512. }).catch(console.error);
  48513. }
  48514. });
  48515. /**
  48516. * Create a modal dialog that request users permission to access the Device Motion API.
  48517. *
  48518. * @param {function} onAllowClicked - click event handler
  48519. * @returns {Element} Wrapper <div>.
  48520. */
  48521. function createPermissionDialog (text, onAllowClicked, onDenyClicked) {
  48522. var buttonsContainer;
  48523. var denyButton;
  48524. var acceptButton;
  48525. buttonsContainer = document.createElement('div');
  48526. buttonsContainer.classList.add(DIALOG_BUTTONS_CONTAINER_CLASS);
  48527. // Buttons
  48528. denyButton = document.createElement('button');
  48529. denyButton.classList.add(DIALOG_BUTTON_CLASS, DIALOG_DENY_BUTTON_CLASS);
  48530. denyButton.setAttribute(constants.AFRAME_INJECTED, '');
  48531. denyButton.innerHTML = 'Deny';
  48532. buttonsContainer.appendChild(denyButton);
  48533. acceptButton = document.createElement('button');
  48534. acceptButton.classList.add(DIALOG_BUTTON_CLASS, DIALOG_ALLOW_BUTTON_CLASS);
  48535. acceptButton.setAttribute(constants.AFRAME_INJECTED, '');
  48536. acceptButton.innerHTML = 'Allow';
  48537. buttonsContainer.appendChild(acceptButton);
  48538. // Ask for sensor events to be used
  48539. acceptButton.addEventListener('click', function (evt) {
  48540. evt.stopPropagation();
  48541. onAllowClicked();
  48542. });
  48543. denyButton.addEventListener('click', function (evt) {
  48544. evt.stopPropagation();
  48545. onDenyClicked();
  48546. });
  48547. return createDialog(text, buttonsContainer);
  48548. }
  48549. function createAlertDialog (text, onOkClicked) {
  48550. var buttonsContainer;
  48551. var okButton;
  48552. buttonsContainer = document.createElement('div');
  48553. buttonsContainer.classList.add(DIALOG_BUTTONS_CONTAINER_CLASS);
  48554. // Buttons
  48555. okButton = document.createElement('button');
  48556. okButton.classList.add(DIALOG_BUTTON_CLASS, DIALOG_OK_BUTTON_CLASS);
  48557. okButton.setAttribute(constants.AFRAME_INJECTED, '');
  48558. okButton.innerHTML = 'Close';
  48559. buttonsContainer.appendChild(okButton);
  48560. // Ask for sensor events to be used
  48561. okButton.addEventListener('click', function (evt) {
  48562. evt.stopPropagation();
  48563. onOkClicked();
  48564. });
  48565. return createDialog(text, buttonsContainer);
  48566. }
  48567. function createDialog (text, buttonsContainerEl) {
  48568. var modalContainer;
  48569. var dialog;
  48570. var dialogTextContainer;
  48571. var dialogText;
  48572. modalContainer = document.createElement('div');
  48573. modalContainer.classList.add(MODAL_CLASS);
  48574. modalContainer.setAttribute(constants.AFRAME_INJECTED, '');
  48575. dialog = document.createElement('div');
  48576. dialog.className = DIALOG_CLASS;
  48577. dialog.setAttribute(constants.AFRAME_INJECTED, '');
  48578. modalContainer.appendChild(dialog);
  48579. dialogTextContainer = document.createElement('div');
  48580. dialogTextContainer.classList.add(DIALOG_TEXT_CONTAINER_CLASS);
  48581. dialog.appendChild(dialogTextContainer);
  48582. dialogText = document.createElement('div');
  48583. dialogText.classList.add(DIALOG_TEXT_CLASS);
  48584. dialogText.innerHTML = text;
  48585. dialogTextContainer.appendChild(dialogText);
  48586. dialog.appendChild(buttonsContainerEl);
  48587. return modalContainer;
  48588. }
  48589. },{"../../constants/":120,"../../core/component":128,"../../utils/":202}],100:[function(_dereq_,module,exports){
  48590. var registerComponent = _dereq_('../../core/component').registerComponent;
  48591. /**
  48592. * Component to embed an a-frame scene within the layout of a 2D page.
  48593. */
  48594. module.exports.Component = registerComponent('embedded', {
  48595. dependencies: ['vr-mode-ui'],
  48596. schema: {default: true},
  48597. update: function () {
  48598. var sceneEl = this.el;
  48599. var enterVREl = sceneEl.querySelector('.a-enter-vr');
  48600. if (this.data === true) {
  48601. if (enterVREl) { enterVREl.classList.add('embedded'); }
  48602. sceneEl.removeFullScreenStyles();
  48603. } else {
  48604. if (enterVREl) { enterVREl.classList.remove('embedded'); }
  48605. sceneEl.addFullScreenStyles();
  48606. }
  48607. }
  48608. });
  48609. },{"../../core/component":128}],101:[function(_dereq_,module,exports){
  48610. var register = _dereq_('../../core/component').registerComponent;
  48611. var THREE = _dereq_('../../lib/three');
  48612. var debug = _dereq_('../../utils/debug');
  48613. var warn = debug('components:fog:warn');
  48614. /**
  48615. * Fog component.
  48616. * Applies only to the scene entity.
  48617. */
  48618. module.exports.Component = register('fog', {
  48619. schema: {
  48620. color: {type: 'color', default: '#000'},
  48621. density: {default: 0.00025},
  48622. far: {default: 1000, min: 0},
  48623. near: {default: 1, min: 0},
  48624. type: {default: 'linear', oneOf: ['linear', 'exponential']}
  48625. },
  48626. update: function () {
  48627. var data = this.data;
  48628. var el = this.el;
  48629. var fog = this.el.object3D.fog;
  48630. if (!el.isScene) {
  48631. warn('Fog component can only be applied to <a-scene>');
  48632. return;
  48633. }
  48634. // (Re)create fog if fog doesn't exist or fog type changed.
  48635. if (!fog || data.type !== fog.name) {
  48636. el.object3D.fog = getFog(data);
  48637. el.systems.material.updateMaterials();
  48638. return;
  48639. }
  48640. // Fog data changed. Update fog.
  48641. Object.keys(this.schema).forEach(function (key) {
  48642. var value = data[key];
  48643. if (key === 'color') { value = new THREE.Color(value); }
  48644. fog[key] = value;
  48645. });
  48646. },
  48647. /**
  48648. * Remove fog on remove (callback).
  48649. */
  48650. remove: function () {
  48651. var fog = this.el.object3D.fog;
  48652. if (!fog) { return; }
  48653. fog.far = 0;
  48654. fog.near = 0.1;
  48655. }
  48656. });
  48657. /**
  48658. * Creates a fog object. Sets fog.name to be able to detect fog type changes.
  48659. *
  48660. * @param {object} data - Fog data.
  48661. * @returns {object} fog
  48662. */
  48663. function getFog (data) {
  48664. var fog;
  48665. if (data.type === 'exponential') {
  48666. fog = new THREE.FogExp2(data.color, data.density);
  48667. } else {
  48668. fog = new THREE.Fog(data.color, data.near, data.far);
  48669. }
  48670. fog.name = data.type;
  48671. return fog;
  48672. }
  48673. },{"../../core/component":128,"../../lib/three":176,"../../utils/debug":198}],102:[function(_dereq_,module,exports){
  48674. (function (process){
  48675. /* global AFRAME */
  48676. var AFRAME_INJECTED = _dereq_('../../constants').AFRAME_INJECTED;
  48677. var pkg = _dereq_('../../../package');
  48678. var registerComponent = _dereq_('../../core/component').registerComponent;
  48679. var utils = _dereq_('../../utils/');
  48680. /**
  48681. * 0.4.2 to 0.4.x
  48682. * Will need to update this when A-Frame goes to 1.x.x.
  48683. */
  48684. function getFuzzyPatchVersion (version) {
  48685. var split = version.split('.');
  48686. split[2] = 'x';
  48687. return split.join('.');
  48688. }
  48689. var INSPECTOR_DEV_URL = 'https://aframe.io/aframe-inspector/dist/aframe-inspector.js';
  48690. var INSPECTOR_RELEASE_URL = 'https://unpkg.com/aframe-inspector@' + getFuzzyPatchVersion(pkg.version) + '/dist/aframe-inspector.min.js';
  48691. var INSPECTOR_URL = process.env.INSPECTOR_VERSION === 'dev' ? INSPECTOR_DEV_URL : INSPECTOR_RELEASE_URL;
  48692. var LOADING_MESSAGE = 'Loading Inspector';
  48693. var LOADING_ERROR_MESSAGE = 'Error loading Inspector';
  48694. module.exports.Component = registerComponent('inspector', {
  48695. schema: {
  48696. url: {default: INSPECTOR_URL}
  48697. },
  48698. init: function () {
  48699. this.firstPlay = true;
  48700. this.onKeydown = this.onKeydown.bind(this);
  48701. this.onMessage = this.onMessage.bind(this);
  48702. this.initOverlay();
  48703. window.addEventListener('keydown', this.onKeydown);
  48704. window.addEventListener('message', this.onMessage);
  48705. },
  48706. play: function () {
  48707. var urlParam;
  48708. if (!this.firstPlay) { return; }
  48709. urlParam = utils.getUrlParameter('inspector');
  48710. if (urlParam !== 'false' && !!urlParam) {
  48711. this.openInspector();
  48712. this.firstPlay = false;
  48713. }
  48714. },
  48715. initOverlay: function () {
  48716. var dotsHTML = '<span class="dots"><span>.</span><span>.</span><span>.</span></span>';
  48717. this.loadingMessageEl = document.createElement('div');
  48718. this.loadingMessageEl.classList.add('a-inspector-loader');
  48719. this.loadingMessageEl.innerHTML = LOADING_MESSAGE + dotsHTML;
  48720. },
  48721. remove: function () {
  48722. this.removeEventListeners();
  48723. },
  48724. /**
  48725. * <ctrl> + <alt> + i keyboard shortcut.
  48726. */
  48727. onKeydown: function (evt) {
  48728. var shortcutPressed = evt.keyCode === 73 && evt.ctrlKey && evt.altKey;
  48729. if (!shortcutPressed) { return; }
  48730. this.openInspector();
  48731. },
  48732. showLoader: function () {
  48733. document.body.appendChild(this.loadingMessageEl);
  48734. },
  48735. hideLoader: function () {
  48736. document.body.removeChild(this.loadingMessageEl);
  48737. },
  48738. /**
  48739. * postMessage. aframe.io uses this to create a button on examples to open Inspector.
  48740. */
  48741. onMessage: function (evt) {
  48742. if (evt.data === 'INJECT_AFRAME_INSPECTOR') { this.openInspector(); }
  48743. },
  48744. openInspector: function (focusEl) {
  48745. var self = this;
  48746. var script;
  48747. // Already injected. Open.
  48748. if (AFRAME.INSPECTOR || AFRAME.inspectorInjected) {
  48749. AFRAME.INSPECTOR.open(focusEl);
  48750. return;
  48751. }
  48752. this.showLoader();
  48753. // Inject.
  48754. script = document.createElement('script');
  48755. script.src = this.data.url;
  48756. script.setAttribute('data-name', 'aframe-inspector');
  48757. script.setAttribute(AFRAME_INJECTED, '');
  48758. script.onload = function () {
  48759. AFRAME.INSPECTOR.open(focusEl);
  48760. self.hideLoader();
  48761. self.removeEventListeners();
  48762. };
  48763. script.onerror = function () {
  48764. self.loadingMessageEl.innerHTML = LOADING_ERROR_MESSAGE;
  48765. };
  48766. document.head.appendChild(script);
  48767. AFRAME.inspectorInjected = true;
  48768. },
  48769. removeEventListeners: function () {
  48770. window.removeEventListener('keydown', this.onKeydown);
  48771. window.removeEventListener('message', this.onMessage);
  48772. }
  48773. });
  48774. }).call(this,_dereq_('_process'))
  48775. },{"../../../package":72,"../../constants":120,"../../core/component":128,"../../utils/":202,"_process":49}],103:[function(_dereq_,module,exports){
  48776. var registerComponent = _dereq_('../../core/component').registerComponent;
  48777. var shouldCaptureKeyEvent = _dereq_('../../utils/').shouldCaptureKeyEvent;
  48778. module.exports.Component = registerComponent('keyboard-shortcuts', {
  48779. schema: {
  48780. enterVR: {default: true},
  48781. exitVR: {default: true}
  48782. },
  48783. init: function () {
  48784. this.onKeyup = this.onKeyup.bind(this);
  48785. },
  48786. update: function (oldData) {
  48787. var data = this.data;
  48788. this.enterVREnabled = data.enterVR;
  48789. },
  48790. play: function () {
  48791. window.addEventListener('keyup', this.onKeyup, false);
  48792. },
  48793. pause: function () {
  48794. window.removeEventListener('keyup', this.onKeyup);
  48795. },
  48796. onKeyup: function (evt) {
  48797. var scene = this.el;
  48798. if (!shouldCaptureKeyEvent(evt)) { return; }
  48799. if (this.enterVREnabled && evt.keyCode === 70) { // f.
  48800. scene.enterVR();
  48801. }
  48802. if (this.enterVREnabled && evt.keyCode === 27) { // escape.
  48803. scene.exitVR();
  48804. }
  48805. }
  48806. });
  48807. },{"../../core/component":128,"../../utils/":202}],104:[function(_dereq_,module,exports){
  48808. var debug = _dereq_('../../utils/debug');
  48809. var registerComponent = _dereq_('../../core/component').registerComponent;
  48810. var warn = debug('components:pool:warn');
  48811. /**
  48812. * Pool component to reuse entities.
  48813. * Avoids creating and destroying the same kind of entities.
  48814. * Helps reduce GC pauses. For example in a game to reuse enemies entities.
  48815. *
  48816. * @member {array} availableEls - Available entities in the pool.
  48817. * @member {array} usedEls - Entities of the pool in use.
  48818. */
  48819. module.exports.Component = registerComponent('pool', {
  48820. schema: {
  48821. container: {default: ''},
  48822. mixin: {default: ''},
  48823. size: {default: 0},
  48824. dynamic: {default: false}
  48825. },
  48826. multiple: true,
  48827. initPool: function () {
  48828. var i;
  48829. this.availableEls = [];
  48830. this.usedEls = [];
  48831. if (!this.data.mixin) {
  48832. warn('No mixin provided for pool component.');
  48833. }
  48834. if (this.data.container) {
  48835. this.container = document.querySelector(this.data.container);
  48836. if (!this.container) {
  48837. warn('Container ' + this.data.container + ' not found.');
  48838. }
  48839. }
  48840. this.container = this.container || this.el;
  48841. for (i = 0; i < this.data.size; ++i) {
  48842. this.createEntity();
  48843. }
  48844. },
  48845. update: function (oldData) {
  48846. var data = this.data;
  48847. if (oldData.mixin !== data.mixin || oldData.size !== data.size) {
  48848. this.initPool();
  48849. }
  48850. },
  48851. /**
  48852. * Add a new entity to the list of available entities.
  48853. */
  48854. createEntity: function () {
  48855. var el;
  48856. el = document.createElement('a-entity');
  48857. el.play = this.wrapPlay(el.play);
  48858. el.setAttribute('mixin', this.data.mixin);
  48859. el.object3D.visible = false;
  48860. el.pause();
  48861. this.container.appendChild(el);
  48862. this.availableEls.push(el);
  48863. },
  48864. /**
  48865. * Play wrapper for pooled entities. When pausing and playing a scene, don't want to play
  48866. * entities that are not in use.
  48867. */
  48868. wrapPlay: function (playMethod) {
  48869. var usedEls = this.usedEls;
  48870. return function () {
  48871. if (usedEls.indexOf(this) === -1) { return; }
  48872. playMethod.call(this);
  48873. };
  48874. },
  48875. /**
  48876. * Used to request one of the available entities of the pool.
  48877. */
  48878. requestEntity: function () {
  48879. var el;
  48880. if (this.availableEls.length === 0) {
  48881. if (this.data.dynamic === false) {
  48882. warn('Requested entity from empty pool: ' + this.attrName);
  48883. return;
  48884. } else {
  48885. warn('Requested entity from empty pool. This pool is dynamic and will resize ' +
  48886. 'automatically. You might want to increase its initial size: ' + this.attrName);
  48887. }
  48888. this.createEntity();
  48889. }
  48890. el = this.availableEls.shift();
  48891. this.usedEls.push(el);
  48892. el.object3D.visible = true;
  48893. return el;
  48894. },
  48895. /**
  48896. * Used to return a used entity to the pool.
  48897. */
  48898. returnEntity: function (el) {
  48899. var index = this.usedEls.indexOf(el);
  48900. if (index === -1) {
  48901. warn('The returned entity was not previously pooled from ' + this.attrName);
  48902. return;
  48903. }
  48904. this.usedEls.splice(index, 1);
  48905. this.availableEls.push(el);
  48906. el.object3D.visible = false;
  48907. el.pause();
  48908. return el;
  48909. }
  48910. });
  48911. },{"../../core/component":128,"../../utils/debug":198}],105:[function(_dereq_,module,exports){
  48912. /* global ImageData, URL */
  48913. var registerComponent = _dereq_('../../core/component').registerComponent;
  48914. var THREE = _dereq_('../../lib/three');
  48915. var VERTEX_SHADER = [
  48916. 'attribute vec3 position;',
  48917. 'attribute vec2 uv;',
  48918. 'uniform mat4 projectionMatrix;',
  48919. 'uniform mat4 modelViewMatrix;',
  48920. 'varying vec2 vUv;',
  48921. 'void main() {',
  48922. ' vUv = vec2( 1.- uv.x, uv.y );',
  48923. ' gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );',
  48924. '}'
  48925. ].join('\n');
  48926. var FRAGMENT_SHADER = [
  48927. 'precision mediump float;',
  48928. 'uniform samplerCube map;',
  48929. 'varying vec2 vUv;',
  48930. '#define M_PI 3.141592653589793238462643383279',
  48931. 'void main() {',
  48932. ' vec2 uv = vUv;',
  48933. ' float longitude = uv.x * 2. * M_PI - M_PI + M_PI / 2.;',
  48934. ' float latitude = uv.y * M_PI;',
  48935. ' vec3 dir = vec3(',
  48936. ' - sin( longitude ) * sin( latitude ),',
  48937. ' cos( latitude ),',
  48938. ' - cos( longitude ) * sin( latitude )',
  48939. ' );',
  48940. ' normalize( dir );',
  48941. ' gl_FragColor = vec4( textureCube( map, dir ).rgb, 1.0 );',
  48942. '}'
  48943. ].join('\n');
  48944. /**
  48945. * Component to take screenshots of the scene using a keboard shortcut (alt+s).
  48946. * It can be configured to either take 360&deg; captures (`equirectangular`)
  48947. * or regular screenshots (`projection`)
  48948. *
  48949. * This is based on https://github.com/spite/THREE.CubemapToEquirectangular
  48950. * To capture an equirectangular projection of the scene a THREE.CubeCamera is used
  48951. * The cube map produced by the CubeCamera is projected on a quad and then rendered to
  48952. * WebGLRenderTarget with an ortographic camera.
  48953. */
  48954. module.exports.Component = registerComponent('screenshot', {
  48955. schema: {
  48956. width: {default: 4096},
  48957. height: {default: 2048},
  48958. camera: {type: 'selector'}
  48959. },
  48960. init: function () {
  48961. var el = this.el;
  48962. var self = this;
  48963. if (el.renderer) {
  48964. setup();
  48965. } else {
  48966. el.addEventListener('render-target-loaded', setup);
  48967. }
  48968. function setup () {
  48969. var gl = el.renderer.getContext();
  48970. if (!gl) { return; }
  48971. self.cubeMapSize = gl.getParameter(gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  48972. self.material = new THREE.RawShaderMaterial({
  48973. uniforms: {map: {type: 't', value: null}},
  48974. vertexShader: VERTEX_SHADER,
  48975. fragmentShader: FRAGMENT_SHADER,
  48976. side: THREE.DoubleSide
  48977. });
  48978. self.quad = new THREE.Mesh(
  48979. new THREE.PlaneBufferGeometry(1, 1),
  48980. self.material
  48981. );
  48982. self.quad.visible = false;
  48983. self.camera = new THREE.OrthographicCamera(-1 / 2, 1 / 2, 1 / 2, -1 / 2, -10000, 10000);
  48984. self.canvas = document.createElement('canvas');
  48985. self.ctx = self.canvas.getContext('2d');
  48986. el.object3D.add(self.quad);
  48987. self.onKeyDown = self.onKeyDown.bind(self);
  48988. }
  48989. },
  48990. getRenderTarget: function (width, height) {
  48991. return new THREE.WebGLRenderTarget(width, height, {
  48992. minFilter: THREE.LinearFilter,
  48993. magFilter: THREE.LinearFilter,
  48994. wrapS: THREE.ClampToEdgeWrapping,
  48995. wrapT: THREE.ClampToEdgeWrapping,
  48996. format: THREE.RGBAFormat,
  48997. type: THREE.UnsignedByteType
  48998. });
  48999. },
  49000. resize: function (width, height) {
  49001. // Resize quad.
  49002. this.quad.scale.set(width, height, 1);
  49003. // Resize camera.
  49004. this.camera.left = -1 * width / 2;
  49005. this.camera.right = width / 2;
  49006. this.camera.top = height / 2;
  49007. this.camera.bottom = -1 * height / 2;
  49008. this.camera.updateProjectionMatrix();
  49009. // Resize canvas.
  49010. this.canvas.width = width;
  49011. this.canvas.height = height;
  49012. },
  49013. play: function () {
  49014. window.addEventListener('keydown', this.onKeyDown);
  49015. },
  49016. /**
  49017. * <ctrl> + <alt> + s = Regular screenshot.
  49018. * <ctrl> + <alt> + <shift> + s = Equirectangular screenshot.
  49019. */
  49020. onKeyDown: function (evt) {
  49021. var shortcutPressed = evt.keyCode === 83 && evt.ctrlKey && evt.altKey;
  49022. if (!this.data || !shortcutPressed) { return; }
  49023. var projection = evt.shiftKey ? 'equirectangular' : 'perspective';
  49024. this.capture(projection);
  49025. },
  49026. /**
  49027. * Capture a screenshot of the scene.
  49028. *
  49029. * @param {string} projection - Screenshot projection (equirectangular or perspective).
  49030. */
  49031. setCapture: function (projection) {
  49032. var el = this.el;
  49033. var size;
  49034. var camera;
  49035. var cubeCamera;
  49036. // Configure camera.
  49037. if (projection === 'perspective') {
  49038. // Quad is only used in equirectangular mode. Hide it in this case.
  49039. this.quad.visible = false;
  49040. // Use scene camera.
  49041. camera = (this.data.camera && this.data.camera.components.camera.camera) || el.camera;
  49042. size = {width: this.data.width, height: this.data.height};
  49043. } else {
  49044. // Use ortho camera.
  49045. camera = this.camera;
  49046. // Create cube camera and copy position from scene camera.
  49047. cubeCamera = new THREE.CubeCamera(el.camera.near, el.camera.far,
  49048. Math.min(this.cubeMapSize, 2048));
  49049. // Copy camera position into cube camera;
  49050. el.camera.getWorldPosition(cubeCamera.position);
  49051. el.camera.getWorldQuaternion(cubeCamera.quaternion);
  49052. // Render scene with cube camera.
  49053. cubeCamera.update(el.renderer, el.object3D);
  49054. this.quad.material.uniforms.map.value = cubeCamera.renderTarget.texture;
  49055. size = {width: this.data.width, height: this.data.height};
  49056. // Use quad to project image taken by the cube camera.
  49057. this.quad.visible = true;
  49058. }
  49059. return {
  49060. camera: camera,
  49061. size: size,
  49062. projection: projection
  49063. };
  49064. },
  49065. /**
  49066. * Maintained for backwards compatibility.
  49067. */
  49068. capture: function (projection) {
  49069. var isVREnabled = this.el.renderer.xr.enabled;
  49070. var renderer = this.el.renderer;
  49071. var params;
  49072. // Disable VR.
  49073. renderer.xr.enabled = false;
  49074. params = this.setCapture(projection);
  49075. this.renderCapture(params.camera, params.size, params.projection);
  49076. // Trigger file download.
  49077. this.saveCapture();
  49078. // Restore VR.
  49079. renderer.xr.enabled = isVREnabled;
  49080. },
  49081. /**
  49082. * Return canvas instead of triggering download (e.g., for uploading blob to server).
  49083. */
  49084. getCanvas: function (projection) {
  49085. var isVREnabled = this.el.renderer.xr.enabled;
  49086. var renderer = this.el.renderer;
  49087. // Disable VR.
  49088. var params = this.setCapture(projection);
  49089. renderer.xr.enabled = false;
  49090. this.renderCapture(params.camera, params.size, params.projection);
  49091. // Restore VR.
  49092. renderer.xr.enabled = isVREnabled;
  49093. return this.canvas;
  49094. },
  49095. renderCapture: function (camera, size, projection) {
  49096. var autoClear = this.el.renderer.autoClear;
  49097. var el = this.el;
  49098. var imageData;
  49099. var output;
  49100. var pixels;
  49101. var renderer = el.renderer;
  49102. // Create rendering target and buffer to store the read pixels.
  49103. output = this.getRenderTarget(size.width, size.height);
  49104. pixels = new Uint8Array(4 * size.width * size.height);
  49105. // Resize quad, camera, and canvas.
  49106. this.resize(size.width, size.height);
  49107. // Render scene to render target.
  49108. renderer.autoClear = true;
  49109. renderer.clear();
  49110. renderer.setRenderTarget(output);
  49111. renderer.render(el.object3D, camera);
  49112. renderer.autoClear = autoClear;
  49113. // Read image pizels back.
  49114. renderer.readRenderTargetPixels(output, 0, 0, size.width, size.height, pixels);
  49115. renderer.setRenderTarget(null);
  49116. if (projection === 'perspective') {
  49117. pixels = this.flipPixelsVertically(pixels, size.width, size.height);
  49118. }
  49119. imageData = new ImageData(new Uint8ClampedArray(pixels), size.width, size.height);
  49120. // Hide quad after projecting the image.
  49121. this.quad.visible = false;
  49122. // Copy pixels into canvas.
  49123. this.ctx.putImageData(imageData, 0, 0);
  49124. },
  49125. flipPixelsVertically: function (pixels, width, height) {
  49126. var flippedPixels = pixels.slice(0);
  49127. for (var x = 0; x < width; ++x) {
  49128. for (var y = 0; y < height; ++y) {
  49129. flippedPixels[x * 4 + y * width * 4] = pixels[x * 4 + (height - y) * width * 4];
  49130. flippedPixels[x * 4 + 1 + y * width * 4] = pixels[x * 4 + 1 + (height - y) * width * 4];
  49131. flippedPixels[x * 4 + 2 + y * width * 4] = pixels[x * 4 + 2 + (height - y) * width * 4];
  49132. flippedPixels[x * 4 + 3 + y * width * 4] = pixels[x * 4 + 3 + (height - y) * width * 4];
  49133. }
  49134. }
  49135. return flippedPixels;
  49136. },
  49137. /**
  49138. * Download capture to file.
  49139. */
  49140. saveCapture: function () {
  49141. this.canvas.toBlob(function (blob) {
  49142. var fileName = 'screenshot-' + document.title.toLowerCase() + '-' + Date.now() + '.png';
  49143. var linkEl = document.createElement('a');
  49144. var url = URL.createObjectURL(blob);
  49145. linkEl.href = url;
  49146. linkEl.setAttribute('download', fileName);
  49147. linkEl.innerHTML = 'downloading...';
  49148. linkEl.style.display = 'none';
  49149. document.body.appendChild(linkEl);
  49150. setTimeout(function () {
  49151. linkEl.click();
  49152. document.body.removeChild(linkEl);
  49153. }, 1);
  49154. }, 'image/png');
  49155. }
  49156. });
  49157. },{"../../core/component":128,"../../lib/three":176}],106:[function(_dereq_,module,exports){
  49158. var registerComponent = _dereq_('../../core/component').registerComponent;
  49159. var RStats = _dereq_('../../../vendor/rStats');
  49160. var utils = _dereq_('../../utils');
  49161. _dereq_('../../../vendor/rStats.extras');
  49162. _dereq_('../../lib/rStatsAframe');
  49163. var AFrameStats = window.aframeStats;
  49164. var bind = utils.bind;
  49165. var HIDDEN_CLASS = 'a-hidden';
  49166. var ThreeStats = window.threeStats;
  49167. /**
  49168. * Stats appended to document.body by RStats.
  49169. */
  49170. module.exports.Component = registerComponent('stats', {
  49171. schema: {default: true},
  49172. init: function () {
  49173. var scene = this.el;
  49174. if (utils.getUrlParameter('stats') === 'false') { return; }
  49175. this.stats = createStats(scene);
  49176. this.statsEl = document.querySelector('.rs-base');
  49177. this.hideBound = bind(this.hide, this);
  49178. this.showBound = bind(this.show, this);
  49179. scene.addEventListener('enter-vr', this.hideBound);
  49180. scene.addEventListener('exit-vr', this.showBound);
  49181. },
  49182. update: function () {
  49183. if (!this.stats) { return; }
  49184. return (!this.data) ? this.hide() : this.show();
  49185. },
  49186. remove: function () {
  49187. this.el.removeEventListener('enter-vr', this.hideBound);
  49188. this.el.removeEventListener('exit-vr', this.showBound);
  49189. if (!this.statsEl) { return; } // Scene detached.
  49190. this.statsEl.parentNode.removeChild(this.statsEl);
  49191. },
  49192. tick: function () {
  49193. var stats = this.stats;
  49194. if (!stats) { return; }
  49195. stats('rAF').tick();
  49196. stats('FPS').frame();
  49197. stats().update();
  49198. },
  49199. hide: function () {
  49200. this.statsEl.classList.add(HIDDEN_CLASS);
  49201. },
  49202. show: function () {
  49203. this.statsEl.classList.remove(HIDDEN_CLASS);
  49204. }
  49205. });
  49206. function createStats (scene) {
  49207. var threeStats = new ThreeStats(scene.renderer);
  49208. var aframeStats = new AFrameStats(scene);
  49209. var plugins = scene.isMobile ? [] : [threeStats, aframeStats];
  49210. return new RStats({
  49211. css: [], // Our stylesheet is injected from `src/index.js`.
  49212. values: {
  49213. fps: {caption: 'fps', below: 30}
  49214. },
  49215. groups: [
  49216. {caption: 'Framerate', values: ['fps', 'raf']}
  49217. ],
  49218. plugins: plugins
  49219. });
  49220. }
  49221. },{"../../../vendor/rStats":213,"../../../vendor/rStats.extras":212,"../../core/component":128,"../../lib/rStatsAframe":175,"../../utils":202}],107:[function(_dereq_,module,exports){
  49222. var registerComponent = _dereq_('../../core/component').registerComponent;
  49223. var constants = _dereq_('../../constants/');
  49224. var utils = _dereq_('../../utils/');
  49225. var bind = utils.bind;
  49226. var ENTER_VR_CLASS = 'a-enter-vr';
  49227. var ENTER_AR_CLASS = 'a-enter-ar';
  49228. var ENTER_VR_BTN_CLASS = 'a-enter-vr-button';
  49229. var ENTER_AR_BTN_CLASS = 'a-enter-ar-button';
  49230. var HIDDEN_CLASS = 'a-hidden';
  49231. var ORIENTATION_MODAL_CLASS = 'a-orientation-modal';
  49232. /**
  49233. * UI for entering VR mode.
  49234. */
  49235. module.exports.Component = registerComponent('vr-mode-ui', {
  49236. dependencies: ['canvas'],
  49237. schema: {
  49238. enabled: {default: true},
  49239. enterVRButton: {default: ''},
  49240. enterARButton: {default: ''}
  49241. },
  49242. init: function () {
  49243. var self = this;
  49244. var sceneEl = this.el;
  49245. if (utils.getUrlParameter('ui') === 'false') { return; }
  49246. this.insideLoader = false;
  49247. this.enterVREl = null;
  49248. this.enterAREl = null;
  49249. this.orientationModalEl = null;
  49250. this.bindMethods();
  49251. // Hide/show VR UI when entering/exiting VR mode.
  49252. sceneEl.addEventListener('enter-vr', this.updateEnterInterfaces);
  49253. sceneEl.addEventListener('exit-vr', this.updateEnterInterfaces);
  49254. sceneEl.addEventListener('update-vr-devices', this.updateEnterInterfaces);
  49255. window.addEventListener('message', function (event) {
  49256. if (event.data.type === 'loaderReady') {
  49257. self.insideLoader = true;
  49258. self.remove();
  49259. }
  49260. });
  49261. // Modal that tells the user to change orientation if in portrait.
  49262. window.addEventListener('orientationchange', this.toggleOrientationModalIfNeeded);
  49263. },
  49264. bindMethods: function () {
  49265. this.onEnterVRButtonClick = bind(this.onEnterVRButtonClick, this);
  49266. this.onEnterARButtonClick = bind(this.onEnterARButtonClick, this);
  49267. this.onModalClick = bind(this.onModalClick, this);
  49268. this.toggleOrientationModalIfNeeded = bind(this.toggleOrientationModalIfNeeded, this);
  49269. this.updateEnterInterfaces = bind(this.updateEnterInterfaces, this);
  49270. },
  49271. /**
  49272. * Exit VR when modal clicked.
  49273. */
  49274. onModalClick: function () {
  49275. this.el.exitVR();
  49276. },
  49277. /**
  49278. * Enter VR when clicked.
  49279. */
  49280. onEnterVRButtonClick: function () {
  49281. this.el.enterVR();
  49282. },
  49283. /**
  49284. * Enter AR when clicked.
  49285. */
  49286. onEnterARButtonClick: function () {
  49287. this.el.enterAR();
  49288. },
  49289. update: function () {
  49290. var data = this.data;
  49291. var sceneEl = this.el;
  49292. if (!data.enabled || this.insideLoader || utils.getUrlParameter('ui') === 'false') {
  49293. return this.remove();
  49294. }
  49295. if (this.enterVREl || this.enterAREl || this.orientationModalEl) { return; }
  49296. // Add UI if enabled and not already present.
  49297. if (data.enterVRButton) {
  49298. // Custom button.
  49299. this.enterVREl = document.querySelector(data.enterVRButton);
  49300. this.enterVREl.addEventListener('click', this.onEnterVRButtonClick);
  49301. } else {
  49302. this.enterVREl = createEnterVRButton(this.onEnterVRButtonClick);
  49303. sceneEl.appendChild(this.enterVREl);
  49304. }
  49305. if (data.enterARButton) {
  49306. // Custom button.
  49307. this.enterAREl = document.querySelector(data.enterARButton);
  49308. this.enterAREl.addEventListener('click', this.onEnterARButtonClick);
  49309. } else {
  49310. this.enterAREl = createEnterARButton(this.onEnterARButtonClick);
  49311. sceneEl.appendChild(this.enterAREl);
  49312. }
  49313. this.orientationModalEl = createOrientationModal(this.onModalClick);
  49314. sceneEl.appendChild(this.orientationModalEl);
  49315. this.updateEnterInterfaces();
  49316. },
  49317. remove: function () {
  49318. [this.enterVREl, this.enterAREl, this.orientationModalEl].forEach(function (uiElement) {
  49319. if (uiElement && uiElement.parentNode) {
  49320. uiElement.parentNode.removeChild(uiElement);
  49321. }
  49322. });
  49323. },
  49324. updateEnterInterfaces: function () {
  49325. this.toggleEnterVRButtonIfNeeded();
  49326. this.toggleEnterARButtonIfNeeded();
  49327. this.toggleOrientationModalIfNeeded();
  49328. },
  49329. toggleEnterVRButtonIfNeeded: function () {
  49330. var sceneEl = this.el;
  49331. if (!this.enterVREl) { return; }
  49332. if (sceneEl.is('vr-mode')) {
  49333. this.enterVREl.classList.add(HIDDEN_CLASS);
  49334. } else {
  49335. this.enterVREl.classList.remove(HIDDEN_CLASS);
  49336. }
  49337. },
  49338. toggleEnterARButtonIfNeeded: function () {
  49339. var sceneEl = this.el;
  49340. if (!this.enterAREl) { return; }
  49341. // Hide the button while in a session, or if AR is not supported.
  49342. if (sceneEl.is('vr-mode') || !utils.device.checkARSupport()) {
  49343. this.enterAREl.classList.add(HIDDEN_CLASS);
  49344. } else {
  49345. this.enterAREl.classList.remove(HIDDEN_CLASS);
  49346. }
  49347. },
  49348. toggleOrientationModalIfNeeded: function () {
  49349. var sceneEl = this.el;
  49350. var orientationModalEl = this.orientationModalEl;
  49351. if (!orientationModalEl || !sceneEl.isMobile) { return; }
  49352. if (!utils.device.isLandscape() && sceneEl.is('vr-mode')) {
  49353. // Show if in VR mode on portrait.
  49354. orientationModalEl.classList.remove(HIDDEN_CLASS);
  49355. } else {
  49356. orientationModalEl.classList.add(HIDDEN_CLASS);
  49357. }
  49358. }
  49359. });
  49360. /**
  49361. * Create a button that when clicked will enter into stereo-rendering mode for VR.
  49362. *
  49363. * Structure: <div><button></div>
  49364. *
  49365. * @param {function} onClick - click event handler
  49366. * @returns {Element} Wrapper <div>.
  49367. */
  49368. function createEnterVRButton (onClick) {
  49369. var vrButton;
  49370. var wrapper;
  49371. // Create elements.
  49372. wrapper = document.createElement('div');
  49373. wrapper.classList.add(ENTER_VR_CLASS);
  49374. wrapper.setAttribute(constants.AFRAME_INJECTED, '');
  49375. vrButton = document.createElement('button');
  49376. vrButton.className = ENTER_VR_BTN_CLASS;
  49377. vrButton.setAttribute('title',
  49378. 'Enter VR mode with a headset or fullscreen mode on a desktop. ' +
  49379. 'Visit https://webvr.rocks or https://webvr.info for more information.');
  49380. vrButton.setAttribute(constants.AFRAME_INJECTED, '');
  49381. if (utils.device.isMobile()) { applyStickyHoverFix(vrButton); }
  49382. // Insert elements.
  49383. wrapper.appendChild(vrButton);
  49384. vrButton.addEventListener('click', function (evt) {
  49385. onClick();
  49386. evt.stopPropagation();
  49387. });
  49388. return wrapper;
  49389. }
  49390. /**
  49391. * Create a button that when clicked will enter into AR mode
  49392. *
  49393. * Structure: <div><button></div>
  49394. *
  49395. * @param {function} onClick - click event handler
  49396. * @returns {Element} Wrapper <div>.
  49397. */
  49398. function createEnterARButton (onClick) {
  49399. var arButton;
  49400. var wrapper;
  49401. // Create elements.
  49402. wrapper = document.createElement('div');
  49403. wrapper.classList.add(ENTER_AR_CLASS);
  49404. wrapper.setAttribute(constants.AFRAME_INJECTED, '');
  49405. arButton = document.createElement('button');
  49406. arButton.className = ENTER_AR_BTN_CLASS;
  49407. arButton.setAttribute('title',
  49408. 'Enter AR mode with a headset or handheld device. ' +
  49409. 'Visit https://webvr.rocks or https://webvr.info for more information.');
  49410. arButton.setAttribute(constants.AFRAME_INJECTED, '');
  49411. if (utils.device.isMobile()) { applyStickyHoverFix(arButton); }
  49412. // Insert elements.
  49413. wrapper.appendChild(arButton);
  49414. arButton.addEventListener('click', function (evt) {
  49415. onClick();
  49416. evt.stopPropagation();
  49417. });
  49418. return wrapper;
  49419. }
  49420. /**
  49421. * Creates a modal dialog to request the user to switch to landscape orientation.
  49422. *
  49423. * @param {function} onClick - click event handler
  49424. * @returns {Element} Wrapper <div>.
  49425. */
  49426. function createOrientationModal (onClick) {
  49427. var modal = document.createElement('div');
  49428. modal.className = ORIENTATION_MODAL_CLASS;
  49429. modal.classList.add(HIDDEN_CLASS);
  49430. modal.setAttribute(constants.AFRAME_INJECTED, '');
  49431. var exit = document.createElement('button');
  49432. exit.setAttribute(constants.AFRAME_INJECTED, '');
  49433. exit.innerHTML = 'Exit VR';
  49434. // Exit VR on close.
  49435. exit.addEventListener('click', onClick);
  49436. modal.appendChild(exit);
  49437. return modal;
  49438. }
  49439. /**
  49440. * CSS hover state is sticky in iOS (as in 12/18/2019)
  49441. * They are not removed on mouseleave and this function applies a class
  49442. * to resets the style.
  49443. *
  49444. * @param {function} buttonEl - Button element
  49445. */
  49446. function applyStickyHoverFix (buttonEl) {
  49447. buttonEl.addEventListener('touchstart', function () {
  49448. buttonEl.classList.remove('resethover');
  49449. });
  49450. buttonEl.addEventListener('touchend', function () {
  49451. buttonEl.classList.add('resethover');
  49452. });
  49453. }
  49454. },{"../../constants/":120,"../../core/component":128,"../../utils/":202}],108:[function(_dereq_,module,exports){
  49455. var component = _dereq_('../core/component');
  49456. var THREE = _dereq_('../lib/three');
  49457. var bind = _dereq_('../utils/bind');
  49458. var registerComponent = component.registerComponent;
  49459. /**
  49460. * Shadow component.
  49461. *
  49462. * When applied to an entity, that entity's geometry and any descendants will cast or receive
  49463. * shadows as specified by the `cast` and `receive` properties.
  49464. */
  49465. module.exports.Component = registerComponent('shadow', {
  49466. schema: {
  49467. cast: {default: true},
  49468. receive: {default: true}
  49469. },
  49470. init: function () {
  49471. this.onMeshChanged = bind(this.update, this);
  49472. this.el.addEventListener('object3dset', this.onMeshChanged);
  49473. this.system.setShadowMapEnabled(true);
  49474. },
  49475. update: function () {
  49476. var data = this.data;
  49477. this.updateDescendants(data.cast, data.receive);
  49478. },
  49479. remove: function () {
  49480. var el = this.el;
  49481. el.removeEventListener('object3dset', this.onMeshChanged);
  49482. this.updateDescendants(false, false);
  49483. },
  49484. updateDescendants: function (cast, receive) {
  49485. var sceneEl = this.el.sceneEl;
  49486. this.el.object3D.traverse(function (node) {
  49487. if (!(node instanceof THREE.Mesh)) { return; }
  49488. node.castShadow = cast;
  49489. node.receiveShadow = receive;
  49490. // If scene has already rendered, materials must be updated.
  49491. if (sceneEl.hasLoaded && node.material) {
  49492. var materials = Array.isArray(node.material) ? node.material : [node.material];
  49493. for (var i = 0; i < materials.length; i++) {
  49494. materials[i].needsUpdate = true;
  49495. }
  49496. }
  49497. });
  49498. }
  49499. });
  49500. },{"../core/component":128,"../lib/three":176,"../utils/bind":196}],109:[function(_dereq_,module,exports){
  49501. var registerComponent = _dereq_('../core/component').registerComponent;
  49502. var debug = _dereq_('../utils/debug');
  49503. var THREE = _dereq_('../lib/three');
  49504. var warn = debug('components:sound:warn');
  49505. /**
  49506. * Sound component.
  49507. */
  49508. module.exports.Component = registerComponent('sound', {
  49509. schema: {
  49510. autoplay: {default: false},
  49511. distanceModel: {default: 'inverse', oneOf: ['linear', 'inverse', 'exponential']},
  49512. loop: {default: false},
  49513. maxDistance: {default: 10000},
  49514. on: {default: ''},
  49515. poolSize: {default: 1},
  49516. positional: {default: true},
  49517. refDistance: {default: 1},
  49518. rolloffFactor: {default: 1},
  49519. src: {type: 'audio'},
  49520. volume: {default: 1}
  49521. },
  49522. multiple: true,
  49523. init: function () {
  49524. var self = this;
  49525. this.listener = null;
  49526. this.audioLoader = new THREE.AudioLoader();
  49527. this.pool = new THREE.Group();
  49528. this.loaded = false;
  49529. this.mustPlay = false;
  49530. // Don't pass evt because playSound takes a function as parameter.
  49531. this.playSoundBound = function () { self.playSound(); };
  49532. },
  49533. update: function (oldData) {
  49534. var data = this.data;
  49535. var i;
  49536. var sound;
  49537. var srcChanged = data.src !== oldData.src;
  49538. // Create new sound if not yet created or changing `src`.
  49539. if (srcChanged) {
  49540. if (!data.src) { return; }
  49541. this.setupSound();
  49542. }
  49543. for (i = 0; i < this.pool.children.length; i++) {
  49544. sound = this.pool.children[i];
  49545. if (data.positional) {
  49546. sound.setDistanceModel(data.distanceModel);
  49547. sound.setMaxDistance(data.maxDistance);
  49548. sound.setRefDistance(data.refDistance);
  49549. sound.setRolloffFactor(data.rolloffFactor);
  49550. }
  49551. sound.setLoop(data.loop);
  49552. sound.setVolume(data.volume);
  49553. sound.isPaused = false;
  49554. }
  49555. if (data.on !== oldData.on) {
  49556. this.updateEventListener(oldData.on);
  49557. }
  49558. // All sound values set. Load in `src`.
  49559. if (srcChanged) {
  49560. var self = this;
  49561. this.loaded = false;
  49562. this.audioLoader.load(data.src, function (buffer) {
  49563. for (i = 0; i < self.pool.children.length; i++) {
  49564. sound = self.pool.children[i];
  49565. sound.setBuffer(buffer);
  49566. }
  49567. self.loaded = true;
  49568. // Remove this key from cache, otherwise we can't play it again
  49569. THREE.Cache.remove(data.src);
  49570. if (self.data.autoplay || self.mustPlay) { self.playSound(); }
  49571. self.el.emit('sound-loaded', self.evtDetail, false);
  49572. });
  49573. }
  49574. },
  49575. pause: function () {
  49576. this.stopSound();
  49577. this.removeEventListener();
  49578. },
  49579. play: function () {
  49580. if (this.data.autoplay) { this.playSound(); }
  49581. this.updateEventListener();
  49582. },
  49583. remove: function () {
  49584. var i;
  49585. var sound;
  49586. this.removeEventListener();
  49587. if (this.el.getObject3D(this.attrName)) {
  49588. this.el.removeObject3D(this.attrName);
  49589. }
  49590. try {
  49591. for (i = 0; i < this.pool.children.length; i++) {
  49592. sound = this.pool.children[i];
  49593. sound.disconnect();
  49594. }
  49595. } catch (e) {
  49596. // disconnect() will throw if it was never connected initially.
  49597. warn('Audio source not properly disconnected');
  49598. }
  49599. },
  49600. /**
  49601. * Update listener attached to the user defined on event.
  49602. */
  49603. updateEventListener: function (oldEvt) {
  49604. var el = this.el;
  49605. if (oldEvt) { el.removeEventListener(oldEvt, this.playSoundBound); }
  49606. el.addEventListener(this.data.on, this.playSoundBound);
  49607. },
  49608. removeEventListener: function () {
  49609. this.el.removeEventListener(this.data.on, this.playSoundBound);
  49610. },
  49611. /**
  49612. * Removes current sound object, creates new sound object, adds to entity.
  49613. *
  49614. * @returns {object} sound
  49615. */
  49616. setupSound: function () {
  49617. var el = this.el;
  49618. var i;
  49619. var sceneEl = el.sceneEl;
  49620. var self = this;
  49621. var sound;
  49622. if (this.pool.children.length > 0) {
  49623. this.stopSound();
  49624. el.removeObject3D('sound');
  49625. }
  49626. // Only want one AudioListener. Cache it on the scene.
  49627. var listener = this.listener = sceneEl.audioListener || new THREE.AudioListener();
  49628. sceneEl.audioListener = listener;
  49629. if (sceneEl.camera) {
  49630. sceneEl.camera.add(listener);
  49631. }
  49632. // Wait for camera if necessary.
  49633. sceneEl.addEventListener('camera-set-active', function (evt) {
  49634. evt.detail.cameraEl.getObject3D('camera').add(listener);
  49635. });
  49636. // Create [poolSize] audio instances and attach them to pool
  49637. this.pool = new THREE.Group();
  49638. for (i = 0; i < this.data.poolSize; i++) {
  49639. sound = this.data.positional
  49640. ? new THREE.PositionalAudio(listener)
  49641. : new THREE.Audio(listener);
  49642. this.pool.add(sound);
  49643. }
  49644. el.setObject3D(this.attrName, this.pool);
  49645. for (i = 0; i < this.pool.children.length; i++) {
  49646. sound = this.pool.children[i];
  49647. sound.onEnded = function () {
  49648. this.isPlaying = false;
  49649. self.el.emit('sound-ended', self.evtDetail, false);
  49650. };
  49651. }
  49652. },
  49653. /**
  49654. * Pause all the sounds in the pool.
  49655. */
  49656. pauseSound: function () {
  49657. var i;
  49658. var sound;
  49659. this.isPlaying = false;
  49660. for (i = 0; i < this.pool.children.length; i++) {
  49661. sound = this.pool.children[i];
  49662. if (!sound.source || !sound.source.buffer || !sound.isPlaying || sound.isPaused) {
  49663. continue;
  49664. }
  49665. sound.isPaused = true;
  49666. sound.pause();
  49667. }
  49668. },
  49669. /**
  49670. * Look for an unused sound in the pool and play it if found.
  49671. */
  49672. playSound: function (processSound) {
  49673. var found;
  49674. var i;
  49675. var sound;
  49676. if (!this.loaded) {
  49677. warn('Sound not loaded yet. It will be played once it finished loading');
  49678. this.mustPlay = true;
  49679. return;
  49680. }
  49681. found = false;
  49682. this.isPlaying = true;
  49683. for (i = 0; i < this.pool.children.length; i++) {
  49684. sound = this.pool.children[i];
  49685. if (!sound.isPlaying && sound.buffer && !found) {
  49686. if (processSound) { processSound(sound); }
  49687. sound.play();
  49688. sound.isPaused = false;
  49689. found = true;
  49690. continue;
  49691. }
  49692. }
  49693. if (!found) {
  49694. warn('All the sounds are playing. If you need to play more sounds simultaneously ' +
  49695. 'consider increasing the size of pool with the `poolSize` attribute.', this.el);
  49696. return;
  49697. }
  49698. this.mustPlay = false;
  49699. },
  49700. /**
  49701. * Stop all the sounds in the pool.
  49702. */
  49703. stopSound: function () {
  49704. var i;
  49705. var sound;
  49706. this.isPlaying = false;
  49707. for (i = 0; i < this.pool.children.length; i++) {
  49708. sound = this.pool.children[i];
  49709. if (!sound.source || !sound.source.buffer) { return; }
  49710. sound.stop();
  49711. }
  49712. }
  49713. });
  49714. },{"../core/component":128,"../lib/three":176,"../utils/debug":198}],110:[function(_dereq_,module,exports){
  49715. var createTextGeometry = _dereq_('three-bmfont-text');
  49716. var loadBMFont = _dereq_('load-bmfont');
  49717. var registerComponent = _dereq_('../core/component').registerComponent;
  49718. var coreShader = _dereq_('../core/shader');
  49719. var THREE = _dereq_('../lib/three');
  49720. var utils = _dereq_('../utils/');
  49721. var error = utils.debug('components:text:error');
  49722. var shaders = coreShader.shaders;
  49723. var warn = utils.debug('components:text:warn');
  49724. // 1 to match other A-Frame default widths.
  49725. var DEFAULT_WIDTH = 1;
  49726. // @bryik set anisotropy to 16. Improves look of large amounts of text when viewed from angle.
  49727. var MAX_ANISOTROPY = 16;
  49728. var FONT_BASE_URL = 'https://cdn.aframe.io/fonts/';
  49729. var FONTS = {
  49730. aileronsemibold: FONT_BASE_URL + 'Aileron-Semibold.fnt',
  49731. dejavu: FONT_BASE_URL + 'DejaVu-sdf.fnt',
  49732. exo2bold: FONT_BASE_URL + 'Exo2Bold.fnt',
  49733. exo2semibold: FONT_BASE_URL + 'Exo2SemiBold.fnt',
  49734. kelsonsans: FONT_BASE_URL + 'KelsonSans.fnt',
  49735. monoid: FONT_BASE_URL + 'Monoid.fnt',
  49736. mozillavr: FONT_BASE_URL + 'mozillavr.fnt',
  49737. roboto: FONT_BASE_URL + 'Roboto-msdf.json',
  49738. sourcecodepro: FONT_BASE_URL + 'SourceCodePro.fnt'
  49739. };
  49740. var MSDF_FONTS = ['roboto'];
  49741. var DEFAULT_FONT = 'roboto';
  49742. module.exports.FONTS = FONTS;
  49743. var cache = new PromiseCache();
  49744. var fontWidthFactors = {};
  49745. var textures = {};
  49746. // Regular expression for detecting a URLs with a protocol prefix.
  49747. var protocolRe = /^\w+:/;
  49748. /**
  49749. * SDF-based text component.
  49750. * Based on https://github.com/Jam3/three-bmfont-text.
  49751. *
  49752. * All the stock fonts are for the `sdf` registered shader, an improved version of jam3's
  49753. * original `sdf` shader.
  49754. */
  49755. module.exports.Component = registerComponent('text', {
  49756. multiple: true,
  49757. schema: {
  49758. align: {type: 'string', default: 'left', oneOf: ['left', 'right', 'center']},
  49759. alphaTest: {default: 0.5},
  49760. // `anchor` defaults to center to match geometries.
  49761. anchor: {default: 'center', oneOf: ['left', 'right', 'center', 'align']},
  49762. baseline: {default: 'center', oneOf: ['top', 'center', 'bottom']},
  49763. color: {type: 'color', default: '#FFF'},
  49764. font: {type: 'string', default: DEFAULT_FONT},
  49765. // `fontImage` defaults to the font name as a .png (e.g., mozillavr.fnt -> mozillavr.png).
  49766. fontImage: {type: 'string'},
  49767. // `height` has no default, will be populated at layout.
  49768. height: {type: 'number'},
  49769. letterSpacing: {type: 'number', default: 0},
  49770. // `lineHeight` defaults to font's `lineHeight` value.
  49771. lineHeight: {type: 'number'},
  49772. // `negate` must be true for fonts generated with older versions of msdfgen (white background).
  49773. negate: {type: 'boolean', default: true},
  49774. opacity: {type: 'number', default: 1.0},
  49775. shader: {default: 'sdf', oneOf: shaders},
  49776. side: {default: 'front', oneOf: ['front', 'back', 'double']},
  49777. tabSize: {default: 4},
  49778. transparent: {default: true},
  49779. value: {type: 'string'},
  49780. whiteSpace: {default: 'normal', oneOf: ['normal', 'pre', 'nowrap']},
  49781. // `width` defaults to geometry width if present, else `DEFAULT_WIDTH`.
  49782. width: {type: 'number'},
  49783. // `wrapCount` units are about one default font character. Wrap roughly at this number.
  49784. wrapCount: {type: 'number', default: 40},
  49785. // `wrapPixels` will wrap using bmfont pixel units (e.g., dejavu's is 32 pixels).
  49786. wrapPixels: {type: 'number'},
  49787. // `xOffset` to add padding.
  49788. xOffset: {type: 'number', default: 0},
  49789. // `yOffset` to adjust generated fonts from tools that may have incorrect metrics.
  49790. yOffset: {type: 'number', default: 0},
  49791. // `zOffset` will provide a small z offset to avoid z-fighting.
  49792. zOffset: {type: 'number', default: 0.001}
  49793. },
  49794. init: function () {
  49795. this.shaderData = {};
  49796. this.geometry = createTextGeometry();
  49797. this.createOrUpdateMaterial();
  49798. this.mesh = new THREE.Mesh(this.geometry, this.material);
  49799. this.el.setObject3D(this.attrName, this.mesh);
  49800. },
  49801. update: function (oldData) {
  49802. var data = this.data;
  49803. var font = this.currentFont;
  49804. if (textures[data.font]) {
  49805. this.texture = textures[data.font];
  49806. } else {
  49807. // Create texture per font.
  49808. this.texture = textures[data.font] = new THREE.Texture();
  49809. this.texture.anisotropy = MAX_ANISOTROPY;
  49810. }
  49811. // Update material.
  49812. this.createOrUpdateMaterial();
  49813. // New font. `updateFont` will later change data and layout.
  49814. if (oldData.font !== data.font) {
  49815. this.updateFont();
  49816. return;
  49817. }
  49818. // Update geometry and layout.
  49819. if (font) {
  49820. this.updateGeometry(this.geometry, font);
  49821. this.updateLayout();
  49822. }
  49823. },
  49824. /**
  49825. * Clean up geometry, material, texture, mesh, objects.
  49826. */
  49827. remove: function () {
  49828. this.geometry.dispose();
  49829. this.geometry = null;
  49830. this.el.removeObject3D(this.attrName);
  49831. this.material.dispose();
  49832. this.material = null;
  49833. this.texture.dispose();
  49834. this.texture = null;
  49835. if (this.shaderObject) {
  49836. delete this.shaderObject;
  49837. }
  49838. },
  49839. /**
  49840. * Update the shader of the material.
  49841. */
  49842. createOrUpdateMaterial: function () {
  49843. var data = this.data;
  49844. var hasChangedShader;
  49845. var material = this.material;
  49846. var NewShader;
  49847. var shaderData = this.shaderData;
  49848. var shaderName;
  49849. // Infer shader if using a stock font (or from `-msdf` filename convention).
  49850. shaderName = data.shader;
  49851. if (MSDF_FONTS.indexOf(data.font) !== -1 || data.font.indexOf('-msdf.') >= 0) {
  49852. shaderName = 'msdf';
  49853. } else if (data.font in FONTS && MSDF_FONTS.indexOf(data.font) === -1) {
  49854. shaderName = 'sdf';
  49855. }
  49856. hasChangedShader = (this.shaderObject && this.shaderObject.name) !== shaderName;
  49857. shaderData.alphaTest = data.alphaTest;
  49858. shaderData.color = data.color;
  49859. shaderData.map = this.texture;
  49860. shaderData.opacity = data.opacity;
  49861. shaderData.side = parseSide(data.side);
  49862. shaderData.transparent = data.transparent;
  49863. shaderData.negate = data.negate;
  49864. // Shader has not changed, do an update.
  49865. if (!hasChangedShader) {
  49866. // Update shader material.
  49867. this.shaderObject.update(shaderData);
  49868. // Apparently, was not set on `init` nor `update`.
  49869. material.transparent = shaderData.transparent;
  49870. material.side = shaderData.side;
  49871. return;
  49872. }
  49873. // Shader has changed. Create a shader material.
  49874. NewShader = createShader(this.el, shaderName, shaderData);
  49875. this.material = NewShader.material;
  49876. this.shaderObject = NewShader.shader;
  49877. // Set new shader material.
  49878. this.material.side = shaderData.side;
  49879. if (this.mesh) { this.mesh.material = this.material; }
  49880. },
  49881. /**
  49882. * Load font for geometry, load font image for material, and apply.
  49883. */
  49884. updateFont: function () {
  49885. var data = this.data;
  49886. var el = this.el;
  49887. var fontSrc;
  49888. var geometry = this.geometry;
  49889. var self = this;
  49890. if (!data.font) { warn('No font specified. Using the default font.'); }
  49891. // Make invisible during font swap.
  49892. this.mesh.visible = false;
  49893. // Look up font URL to use, and perform cached load.
  49894. fontSrc = this.lookupFont(data.font || DEFAULT_FONT) || data.font;
  49895. cache.get(fontSrc, function doLoadFont () {
  49896. return loadFont(fontSrc, data.yOffset);
  49897. }).then(function setFont (font) {
  49898. var fontImgSrc;
  49899. if (font.pages.length !== 1) {
  49900. throw new Error('Currently only single-page bitmap fonts are supported.');
  49901. }
  49902. if (!fontWidthFactors[fontSrc]) {
  49903. font.widthFactor = fontWidthFactors[font] = computeFontWidthFactor(font);
  49904. }
  49905. // Update geometry given font metrics.
  49906. self.updateGeometry(geometry, font);
  49907. // Set font and update layout.
  49908. self.currentFont = font;
  49909. self.updateLayout();
  49910. // Look up font image URL to use, and perform cached load.
  49911. fontImgSrc = self.getFontImageSrc();
  49912. cache.get(fontImgSrc, function () {
  49913. return loadTexture(fontImgSrc);
  49914. }).then(function (image) {
  49915. // Make mesh visible and apply font image as texture.
  49916. var texture = self.texture;
  49917. texture.image = image;
  49918. texture.needsUpdate = true;
  49919. textures[data.font] = texture;
  49920. self.texture = texture;
  49921. self.mesh.visible = true;
  49922. el.emit('textfontset', {font: data.font, fontObj: font});
  49923. }).catch(function (err) {
  49924. error(err.message);
  49925. error(err.stack);
  49926. });
  49927. }).catch(function (err) {
  49928. error(err.message);
  49929. error(err.stack);
  49930. });
  49931. },
  49932. getFontImageSrc: function () {
  49933. if (this.data.fontImage) { return this.data.fontImage; }
  49934. var fontSrc = this.lookupFont(this.data.font || DEFAULT_FONT) || this.data.font;
  49935. var imageSrc = this.currentFont.pages[0];
  49936. // If the image URL contains a non-HTTP(S) protocol, assume it's an absolute
  49937. // path on disk and try to infer the path from the font source instead.
  49938. if (imageSrc.match(protocolRe) && imageSrc.indexOf('http') !== 0) {
  49939. return fontSrc.replace(/(\.fnt)|(\.json)/, '.png');
  49940. }
  49941. return THREE.LoaderUtils.extractUrlBase(fontSrc) + imageSrc;
  49942. },
  49943. /**
  49944. * Update layout with anchor, alignment, baseline, and considering any meshes.
  49945. */
  49946. updateLayout: function () {
  49947. var anchor;
  49948. var baseline;
  49949. var el = this.el;
  49950. var data = this.data;
  49951. var geometry = this.geometry;
  49952. var geometryComponent;
  49953. var height;
  49954. var layout;
  49955. var mesh = this.mesh;
  49956. var textRenderWidth;
  49957. var textScale;
  49958. var width;
  49959. var x;
  49960. var y;
  49961. if (!geometry.layout) { return; }
  49962. // Determine width to use (defined width, geometry's width, or default width).
  49963. geometryComponent = el.getAttribute('geometry');
  49964. width = data.width || (geometryComponent && geometryComponent.width) || DEFAULT_WIDTH;
  49965. // Determine wrap pixel count. Either specified or by experimental fudge factor.
  49966. // Note that experimental factor will never be correct for variable width fonts.
  49967. textRenderWidth = computeWidth(data.wrapPixels, data.wrapCount,
  49968. this.currentFont.widthFactor);
  49969. textScale = width / textRenderWidth;
  49970. // Determine height to use.
  49971. layout = geometry.layout;
  49972. height = textScale * (layout.height + layout.descender);
  49973. // Update geometry dimensions to match text layout if width and height are set to 0.
  49974. // For example, scales a plane to fit text.
  49975. if (geometryComponent && geometryComponent.primitive === 'plane') {
  49976. if (!geometryComponent.width) { el.setAttribute('geometry', 'width', width); }
  49977. if (!geometryComponent.height) { el.setAttribute('geometry', 'height', height); }
  49978. }
  49979. // Calculate X position to anchor text left, center, or right.
  49980. anchor = data.anchor === 'align' ? data.align : data.anchor;
  49981. if (anchor === 'left') {
  49982. x = 0;
  49983. } else if (anchor === 'right') {
  49984. x = -1 * layout.width;
  49985. } else if (anchor === 'center') {
  49986. x = -1 * layout.width / 2;
  49987. } else {
  49988. throw new TypeError('Invalid text.anchor property value', anchor);
  49989. }
  49990. // Calculate Y position to anchor text top, center, or bottom.
  49991. baseline = data.baseline;
  49992. if (baseline === 'bottom') {
  49993. y = 0;
  49994. } else if (baseline === 'top') {
  49995. y = -1 * layout.height + layout.ascender;
  49996. } else if (baseline === 'center') {
  49997. y = -1 * layout.height / 2;
  49998. } else {
  49999. throw new TypeError('Invalid text.baseline property value', baseline);
  50000. }
  50001. // Position and scale mesh to apply layout.
  50002. mesh.position.x = x * textScale + data.xOffset;
  50003. mesh.position.y = y * textScale;
  50004. // Place text slightly in front to avoid Z-fighting.
  50005. mesh.position.z = data.zOffset;
  50006. mesh.scale.set(textScale, -1 * textScale, textScale);
  50007. },
  50008. /**
  50009. * Grab font from the constant.
  50010. * Set as a method for test stubbing purposes.
  50011. */
  50012. lookupFont: function (key) {
  50013. return FONTS[key];
  50014. },
  50015. /**
  50016. * Update the text geometry using `three-bmfont-text.update`.
  50017. */
  50018. updateGeometry: (function () {
  50019. var geometryUpdateBase = {};
  50020. var geometryUpdateData = {};
  50021. var newLineRegex = /\\n/g;
  50022. var tabRegex = /\\t/g;
  50023. return function (geometry, font) {
  50024. var data = this.data;
  50025. geometryUpdateData.font = font;
  50026. geometryUpdateData.lineHeight = data.lineHeight && isFinite(data.lineHeight)
  50027. ? data.lineHeight
  50028. : font.common.lineHeight;
  50029. geometryUpdateData.text = data.value.toString().replace(newLineRegex, '\n')
  50030. .replace(tabRegex, '\t');
  50031. geometryUpdateData.width = computeWidth(data.wrapPixels, data.wrapCount,
  50032. font.widthFactor);
  50033. geometry.update(utils.extend(geometryUpdateBase, data, geometryUpdateData));
  50034. };
  50035. })()
  50036. });
  50037. /**
  50038. * Due to using negative scale, we return the opposite side specified.
  50039. * https://github.com/mrdoob/three.js/pull/12787/
  50040. */
  50041. function parseSide (side) {
  50042. switch (side) {
  50043. case 'back': {
  50044. return THREE.FrontSide;
  50045. }
  50046. case 'double': {
  50047. return THREE.DoubleSide;
  50048. }
  50049. default: {
  50050. return THREE.BackSide;
  50051. }
  50052. }
  50053. }
  50054. /**
  50055. * @returns {Promise}
  50056. */
  50057. function loadFont (src, yOffset) {
  50058. return new Promise(function (resolve, reject) {
  50059. loadBMFont(src, function (err, font) {
  50060. if (err) {
  50061. error('Error loading font', src);
  50062. reject(err);
  50063. return;
  50064. }
  50065. // Fix negative Y offsets for Roboto MSDF font from tool. Experimentally determined.
  50066. if (src.indexOf('/Roboto-msdf.json') >= 0) { yOffset = 30; }
  50067. if (yOffset) { font.chars.map(function doOffset (ch) { ch.yoffset += yOffset; }); }
  50068. resolve(font);
  50069. });
  50070. });
  50071. }
  50072. /**
  50073. * @returns {Promise}
  50074. */
  50075. function loadTexture (src) {
  50076. return new Promise(function (resolve, reject) {
  50077. new THREE.ImageLoader().load(src, function (image) {
  50078. resolve(image);
  50079. }, undefined, function () {
  50080. error('Error loading font image', src);
  50081. reject(null);
  50082. });
  50083. });
  50084. }
  50085. function createShader (el, shaderName, data) {
  50086. var shader;
  50087. var shaderObject;
  50088. // Set up Shader.
  50089. shaderObject = new shaders[shaderName].Shader();
  50090. shaderObject.el = el;
  50091. shaderObject.init(data);
  50092. shaderObject.update(data);
  50093. // Get material.
  50094. shader = shaderObject.material;
  50095. // Apparently, was not set on `init` nor `update`.
  50096. shader.transparent = data.transparent;
  50097. return {
  50098. material: shader,
  50099. shader: shaderObject
  50100. };
  50101. }
  50102. /**
  50103. * Determine wrap pixel count. Either specified or by experimental fudge factor.
  50104. * Note that experimental factor will never be correct for variable width fonts.
  50105. */
  50106. function computeWidth (wrapPixels, wrapCount, widthFactor) {
  50107. return wrapPixels || ((0.5 + wrapCount) * widthFactor);
  50108. }
  50109. /**
  50110. * Compute default font width factor to use.
  50111. */
  50112. function computeFontWidthFactor (font) {
  50113. var sum = 0;
  50114. var digitsum = 0;
  50115. var digits = 0;
  50116. font.chars.map(function (ch) {
  50117. sum += ch.xadvance;
  50118. if (ch.id >= 48 && ch.id <= 57) {
  50119. digits++;
  50120. digitsum += ch.xadvance;
  50121. }
  50122. });
  50123. return digits ? digitsum / digits : sum / font.chars.length;
  50124. }
  50125. /**
  50126. * Get or create a promise given a key and promise generator.
  50127. * @todo Move to a utility and use in other parts of A-Frame.
  50128. */
  50129. function PromiseCache () {
  50130. var cache = this.cache = {};
  50131. this.get = function (key, promiseGenerator) {
  50132. if (key in cache) {
  50133. return cache[key];
  50134. }
  50135. cache[key] = promiseGenerator();
  50136. return cache[key];
  50137. };
  50138. }
  50139. },{"../core/component":128,"../core/shader":138,"../lib/three":176,"../utils/":202,"load-bmfont":37,"three-bmfont-text":62}],111:[function(_dereq_,module,exports){
  50140. var registerComponent = _dereq_('../core/component').registerComponent;
  50141. var controllerUtils = _dereq_('../utils/tracked-controls');
  50142. var DEFAULT_CAMERA_HEIGHT = _dereq_('../constants').DEFAULT_CAMERA_HEIGHT;
  50143. var THREE = _dereq_('../lib/three');
  50144. var DEFAULT_HANDEDNESS = _dereq_('../constants').DEFAULT_HANDEDNESS;
  50145. // Vector from eyes to elbow (divided by user height).
  50146. var EYES_TO_ELBOW = {x: 0.175, y: -0.3, z: -0.03};
  50147. // Vector from eyes to elbow (divided by user height).
  50148. var FOREARM = {x: 0, y: 0, z: -0.175};
  50149. // Due to unfortunate name collision, add empty touches array to avoid Daydream error.
  50150. var EMPTY_DAYDREAM_TOUCHES = {touches: []};
  50151. var EVENTS = {
  50152. AXISMOVE: 'axismove',
  50153. BUTTONCHANGED: 'buttonchanged',
  50154. BUTTONDOWN: 'buttondown',
  50155. BUTTONUP: 'buttonup',
  50156. TOUCHSTART: 'touchstart',
  50157. TOUCHEND: 'touchend'
  50158. };
  50159. /**
  50160. * Tracked controls component.
  50161. * Wrap the gamepad API for pose and button states.
  50162. * Select the appropriate controller and apply pose to the entity.
  50163. * Observe button states and emit appropriate events.
  50164. *
  50165. * @property {number} controller - Index of controller in array returned by Gamepad API.
  50166. * Only used if hand property is not set.
  50167. * @property {string} id - Selected controller among those returned by Gamepad API.
  50168. * @property {number} hand - If multiple controllers found with id, choose the one with the
  50169. * given value for hand. If set, we ignore 'controller' property
  50170. */
  50171. module.exports.Component = registerComponent('tracked-controls-webvr', {
  50172. schema: {
  50173. autoHide: {default: true},
  50174. controller: {default: 0},
  50175. id: {type: 'string', default: ''},
  50176. hand: {type: 'string', default: ''},
  50177. idPrefix: {type: 'string', default: ''},
  50178. orientationOffset: {type: 'vec3'},
  50179. // Arm model parameters when not 6DoF.
  50180. armModel: {default: false},
  50181. headElement: {type: 'selector'}
  50182. },
  50183. init: function () {
  50184. // Copy variables back to tracked-controls for backwards compatibility.
  50185. // Some 3rd components rely on them.
  50186. this.axis = this.el.components['tracked-controls'].axis = [0, 0, 0];
  50187. this.buttonStates = this.el.components['tracked-controls'].buttonStates = {};
  50188. this.changedAxes = [];
  50189. this.targetControllerNumber = this.data.controller;
  50190. this.axisMoveEventDetail = {axis: this.axis, changed: this.changedAxes};
  50191. this.deltaControllerPosition = new THREE.Vector3();
  50192. this.controllerQuaternion = new THREE.Quaternion();
  50193. this.controllerEuler = new THREE.Euler();
  50194. this.updateGamepad();
  50195. this.buttonEventDetails = {};
  50196. },
  50197. tick: function (time, delta) {
  50198. var mesh = this.el.getObject3D('mesh');
  50199. // Update mesh animations.
  50200. if (mesh && mesh.update) { mesh.update(delta / 1000); }
  50201. this.updateGamepad();
  50202. this.updatePose();
  50203. this.updateButtons();
  50204. },
  50205. /**
  50206. * Return default user height to use for non-6DOF arm model.
  50207. */
  50208. defaultUserHeight: function () {
  50209. return DEFAULT_CAMERA_HEIGHT;
  50210. },
  50211. /**
  50212. * Return head element to use for non-6DOF arm model.
  50213. */
  50214. getHeadElement: function () {
  50215. return this.data.headElement || this.el.sceneEl.camera.el;
  50216. },
  50217. /**
  50218. * Handle update controller match criteria (such as `id`, `idPrefix`, `hand`, `controller`)
  50219. */
  50220. updateGamepad: function () {
  50221. var data = this.data;
  50222. var controller = controllerUtils.findMatchingControllerWebVR(
  50223. this.system.controllers,
  50224. data.id,
  50225. data.idPrefix,
  50226. data.hand,
  50227. data.controller
  50228. );
  50229. this.controller = controller;
  50230. // Legacy handle to the controller for old components.
  50231. this.el.components['tracked-controls'].controller = controller;
  50232. if (this.data.autoHide) { this.el.object3D.visible = !!this.controller; }
  50233. },
  50234. /**
  50235. * Applies an artificial arm model to simulate elbow to wrist positioning
  50236. * based on the orientation of the controller.
  50237. *
  50238. * @param {object} controllerPosition - Existing vector to update with controller position.
  50239. */
  50240. applyArmModel: function (controllerPosition) {
  50241. // Use controllerPosition and deltaControllerPosition to avoid creating variables.
  50242. var controller = this.controller;
  50243. var controllerEuler = this.controllerEuler;
  50244. var controllerQuaternion = this.controllerQuaternion;
  50245. var deltaControllerPosition = this.deltaControllerPosition;
  50246. var hand;
  50247. var headEl;
  50248. var headObject3D;
  50249. var pose;
  50250. var userHeight;
  50251. headEl = this.getHeadElement();
  50252. headObject3D = headEl.object3D;
  50253. userHeight = this.defaultUserHeight();
  50254. pose = controller.pose;
  50255. hand = (controller ? controller.hand : undefined) || DEFAULT_HANDEDNESS;
  50256. // Use camera position as head position.
  50257. controllerPosition.copy(headObject3D.position);
  50258. // Set offset for degenerate "arm model" to elbow.
  50259. deltaControllerPosition.set(
  50260. EYES_TO_ELBOW.x * (hand === 'left' ? -1 : hand === 'right' ? 1 : 0),
  50261. EYES_TO_ELBOW.y, // Lower than our eyes.
  50262. EYES_TO_ELBOW.z); // Slightly out in front.
  50263. // Scale offset by user height.
  50264. deltaControllerPosition.multiplyScalar(userHeight);
  50265. // Apply camera Y rotation (not X or Z, so you can look down at your hand).
  50266. deltaControllerPosition.applyAxisAngle(headObject3D.up, headObject3D.rotation.y);
  50267. // Apply rotated offset to position.
  50268. controllerPosition.add(deltaControllerPosition);
  50269. // Set offset for degenerate "arm model" forearm. Forearm sticking out from elbow.
  50270. deltaControllerPosition.set(FOREARM.x, FOREARM.y, FOREARM.z);
  50271. // Scale offset by user height.
  50272. deltaControllerPosition.multiplyScalar(userHeight);
  50273. // Apply controller X/Y rotation (tilting up/down/left/right is usually moving the arm).
  50274. if (pose.orientation) {
  50275. controllerQuaternion.fromArray(pose.orientation);
  50276. } else {
  50277. controllerQuaternion.copy(headObject3D.quaternion);
  50278. }
  50279. controllerEuler.setFromQuaternion(controllerQuaternion);
  50280. controllerEuler.set(controllerEuler.x, controllerEuler.y, 0);
  50281. deltaControllerPosition.applyEuler(controllerEuler);
  50282. // Apply rotated offset to position.
  50283. controllerPosition.add(deltaControllerPosition);
  50284. },
  50285. /**
  50286. * Read pose from controller (from Gamepad API), apply transforms, apply to entity.
  50287. */
  50288. updatePose: function () {
  50289. var controller = this.controller;
  50290. var data = this.data;
  50291. var object3D = this.el.object3D;
  50292. var pose;
  50293. var vrDisplay = this.system.vrDisplay;
  50294. var standingMatrix;
  50295. if (!controller) { return; }
  50296. // Compose pose from Gamepad.
  50297. pose = controller.pose;
  50298. if (pose.position) {
  50299. object3D.position.fromArray(pose.position);
  50300. } else {
  50301. // Controller not 6DOF, apply arm model.
  50302. if (data.armModel) { this.applyArmModel(object3D.position); }
  50303. }
  50304. if (pose.orientation) {
  50305. object3D.quaternion.fromArray(pose.orientation);
  50306. }
  50307. // Apply transforms, if 6DOF and in VR.
  50308. if (vrDisplay && pose.position) {
  50309. standingMatrix = this.el.sceneEl.renderer.xr.getStandingMatrix();
  50310. object3D.matrix.compose(object3D.position, object3D.quaternion, object3D.scale);
  50311. object3D.matrix.multiplyMatrices(standingMatrix, object3D.matrix);
  50312. object3D.matrix.decompose(object3D.position, object3D.quaternion, object3D.scale);
  50313. }
  50314. object3D.rotateX(this.data.orientationOffset.x * THREE.Math.DEG2RAD);
  50315. object3D.rotateY(this.data.orientationOffset.y * THREE.Math.DEG2RAD);
  50316. object3D.rotateZ(this.data.orientationOffset.z * THREE.Math.DEG2RAD);
  50317. },
  50318. /**
  50319. * Handle button changes including axes, presses, touches, values.
  50320. */
  50321. updateButtons: function () {
  50322. var buttonState;
  50323. var controller = this.controller;
  50324. var id;
  50325. if (!controller) { return; }
  50326. // Check every button.
  50327. for (id = 0; id < controller.buttons.length; ++id) {
  50328. // Initialize button state.
  50329. if (!this.buttonStates[id]) {
  50330. this.buttonStates[id] = {pressed: false, touched: false, value: 0};
  50331. }
  50332. if (!this.buttonEventDetails[id]) {
  50333. this.buttonEventDetails[id] = {id: id, state: this.buttonStates[id]};
  50334. }
  50335. buttonState = controller.buttons[id];
  50336. this.handleButton(id, buttonState);
  50337. }
  50338. // Check axes.
  50339. this.handleAxes();
  50340. },
  50341. /**
  50342. * Handle presses and touches for a single button.
  50343. *
  50344. * @param {number} id - Index of button in Gamepad button array.
  50345. * @param {number} buttonState - Value of button state from 0 to 1.
  50346. * @returns {boolean} Whether button has changed in any way.
  50347. */
  50348. handleButton: function (id, buttonState) {
  50349. var changed;
  50350. changed = this.handlePress(id, buttonState) |
  50351. this.handleTouch(id, buttonState) |
  50352. this.handleValue(id, buttonState);
  50353. if (!changed) { return false; }
  50354. this.el.emit(EVENTS.BUTTONCHANGED, this.buttonEventDetails[id], false);
  50355. return true;
  50356. },
  50357. /**
  50358. * An axis is an array of values from -1 (up, left) to 1 (down, right).
  50359. * Compare each component of the axis to the previous value to determine change.
  50360. *
  50361. * @returns {boolean} Whether axes changed.
  50362. */
  50363. handleAxes: function () {
  50364. var changed = false;
  50365. var controllerAxes = this.controller.axes;
  50366. var i;
  50367. var previousAxis = this.axis;
  50368. var changedAxes = this.changedAxes;
  50369. // Check if axis changed.
  50370. this.changedAxes.splice(0, this.changedAxes.length);
  50371. for (i = 0; i < controllerAxes.length; ++i) {
  50372. changedAxes.push(previousAxis[i] !== controllerAxes[i]);
  50373. if (changedAxes[i]) { changed = true; }
  50374. }
  50375. if (!changed) { return false; }
  50376. this.axis.splice(0, this.axis.length);
  50377. for (i = 0; i < controllerAxes.length; i++) {
  50378. this.axis.push(controllerAxes[i]);
  50379. }
  50380. this.el.emit(EVENTS.AXISMOVE, this.axisMoveEventDetail, false);
  50381. return true;
  50382. },
  50383. /**
  50384. * Determine whether a button press has occured and emit events as appropriate.
  50385. *
  50386. * @param {string} id - ID of the button to check.
  50387. * @param {object} buttonState - State of the button to check.
  50388. * @returns {boolean} Whether button press state changed.
  50389. */
  50390. handlePress: function (id, buttonState) {
  50391. var evtName;
  50392. var previousButtonState = this.buttonStates[id];
  50393. // Not changed.
  50394. if (buttonState.pressed === previousButtonState.pressed) { return false; }
  50395. evtName = buttonState.pressed ? EVENTS.BUTTONDOWN : EVENTS.BUTTONUP;
  50396. this.el.emit(evtName, this.buttonEventDetails[id], false);
  50397. previousButtonState.pressed = buttonState.pressed;
  50398. return true;
  50399. },
  50400. /**
  50401. * Determine whether a button touch has occured and emit events as appropriate.
  50402. *
  50403. * @param {string} id - ID of the button to check.
  50404. * @param {object} buttonState - State of the button to check.
  50405. * @returns {boolean} Whether button touch state changed.
  50406. */
  50407. handleTouch: function (id, buttonState) {
  50408. var evtName;
  50409. var previousButtonState = this.buttonStates[id];
  50410. // Not changed.
  50411. if (buttonState.touched === previousButtonState.touched) { return false; }
  50412. evtName = buttonState.touched ? EVENTS.TOUCHSTART : EVENTS.TOUCHEND;
  50413. this.el.emit(evtName, this.buttonEventDetails[id], false, EMPTY_DAYDREAM_TOUCHES);
  50414. previousButtonState.touched = buttonState.touched;
  50415. return true;
  50416. },
  50417. /**
  50418. * Determine whether a button value has changed.
  50419. *
  50420. * @param {string} id - Id of the button to check.
  50421. * @param {object} buttonState - State of the button to check.
  50422. * @returns {boolean} Whether button value changed.
  50423. */
  50424. handleValue: function (id, buttonState) {
  50425. var previousButtonState = this.buttonStates[id];
  50426. // Not changed.
  50427. if (buttonState.value === previousButtonState.value) { return false; }
  50428. previousButtonState.value = buttonState.value;
  50429. return true;
  50430. }
  50431. });
  50432. },{"../constants":120,"../core/component":128,"../lib/three":176,"../utils/tracked-controls":210}],112:[function(_dereq_,module,exports){
  50433. var controllerUtils = _dereq_('../utils/tracked-controls');
  50434. var registerComponent = _dereq_('../core/component').registerComponent;
  50435. var EVENTS = {
  50436. AXISMOVE: 'axismove',
  50437. BUTTONCHANGED: 'buttonchanged',
  50438. BUTTONDOWN: 'buttondown',
  50439. BUTTONUP: 'buttonup',
  50440. TOUCHSTART: 'touchstart',
  50441. TOUCHEND: 'touchend'
  50442. };
  50443. module.exports.Component = registerComponent('tracked-controls-webxr', {
  50444. schema: {
  50445. id: {type: 'string', default: ''},
  50446. hand: {type: 'string', default: ''},
  50447. index: {type: 'int', default: -1},
  50448. iterateControllerProfiles: {default: false}
  50449. },
  50450. init: function () {
  50451. this.addSessionEventListeners = this.addSessionEventListeners.bind(this);
  50452. this.updateController = this.updateController.bind(this);
  50453. this.emitButtonUpEvent = this.emitButtonUpEvent.bind(this);
  50454. this.emitButtonDownEvent = this.emitButtonDownEvent.bind(this);
  50455. this.selectEventDetails = {id: 'trigger', state: {pressed: false}};
  50456. this.buttonEventDetails = {};
  50457. this.buttonStates = this.el.components['tracked-controls'].buttonStates = {};
  50458. this.axis = this.el.components['tracked-controls'].axis = [0, 0, 0];
  50459. this.changedAxes = [];
  50460. this.axisMoveEventDetail = {axis: this.axis, changed: this.changedAxes};
  50461. },
  50462. update: function () {
  50463. this.updateController();
  50464. },
  50465. play: function () {
  50466. var sceneEl = this.el.sceneEl;
  50467. this.updateController();
  50468. this.addSessionEventListeners();
  50469. sceneEl.addEventListener('enter-vr', this.addSessionEventListeners);
  50470. sceneEl.addEventListener('controllersupdated', this.updateController);
  50471. },
  50472. pause: function () {
  50473. var sceneEl = this.el.sceneEl;
  50474. this.removeSessionEventListeners();
  50475. sceneEl.removeEventListener('enter-vr', this.addSessionEventListeners);
  50476. sceneEl.removeEventListener('controllersupdated', this.updateController);
  50477. },
  50478. addSessionEventListeners: function () {
  50479. var sceneEl = this.el.sceneEl;
  50480. if (!sceneEl.xrSession) { return; }
  50481. sceneEl.xrSession.addEventListener('selectstart', this.emitButtonDownEvent);
  50482. sceneEl.xrSession.addEventListener('selectend', this.emitButtonUpEvent);
  50483. },
  50484. removeSessionEventListeners: function () {
  50485. var sceneEl = this.el.sceneEl;
  50486. if (!sceneEl.xrSession) { return; }
  50487. sceneEl.xrSession.removeEventListener('selectstart', this.emitButtonDownEvent);
  50488. sceneEl.xrSession.removeEventListener('selectend', this.emitButtonUpEvent);
  50489. },
  50490. isControllerPresent: function (evt) {
  50491. if (!this.controller || this.controller.gamepad) { return false; }
  50492. if (evt.inputSource.handedness !== 'none' &&
  50493. evt.inputSource.handedness !== this.data.hand) {
  50494. return false;
  50495. }
  50496. return true;
  50497. },
  50498. emitButtonDownEvent: function (evt) {
  50499. if (!this.isControllerPresent(evt)) { return; }
  50500. this.selectEventDetails.state.pressed = true;
  50501. this.el.emit('buttondown', this.selectEventDetails);
  50502. this.el.emit('buttonchanged', this.selectEventDetails);
  50503. this.el.emit('triggerdown');
  50504. },
  50505. emitButtonUpEvent: function (evt) {
  50506. if (!this.isControllerPresent(evt)) { return; }
  50507. this.selectEventDetails.state.pressed = false;
  50508. this.el.emit('buttonup', this.selectEventDetails);
  50509. this.el.emit('buttonchanged', this.selectEventDetails);
  50510. this.el.emit('triggerup');
  50511. },
  50512. /**
  50513. * Handle update controller match criteria (such as `id`, `idPrefix`, `hand`, `controller`)
  50514. */
  50515. updateController: function () {
  50516. this.controller = controllerUtils.findMatchingControllerWebXR(
  50517. this.system.controllers,
  50518. this.data.id,
  50519. this.data.hand,
  50520. this.data.index,
  50521. this.data.iterateControllerProfiles
  50522. );
  50523. // Legacy handle to the controller for old components.
  50524. this.el.components['tracked-controls'].controller = this.controller;
  50525. if (this.data.autoHide) { this.el.object3D.visible = !!this.controller; }
  50526. },
  50527. tick: function () {
  50528. var sceneEl = this.el.sceneEl;
  50529. if (!this.controller || !sceneEl.frame || !this.system.referenceSpace) { return; }
  50530. this.pose = sceneEl.frame.getPose(this.controller.targetRaySpace, this.system.referenceSpace);
  50531. this.updatePose();
  50532. this.updateButtons();
  50533. },
  50534. updatePose: function () {
  50535. var object3D = this.el.object3D;
  50536. var pose = this.pose;
  50537. if (!pose) { return; }
  50538. object3D.matrix.elements = pose.transform.matrix;
  50539. object3D.matrix.decompose(object3D.position, object3D.rotation, object3D.scale);
  50540. },
  50541. /**
  50542. * Handle button changes including axes, presses, touches, values.
  50543. */
  50544. updateButtons: function () {
  50545. var buttonState;
  50546. var id;
  50547. var controller = this.controller;
  50548. var gamepad;
  50549. if (!controller || !controller.gamepad) { return; }
  50550. gamepad = controller.gamepad;
  50551. // Check every button.
  50552. for (id = 0; id < gamepad.buttons.length; ++id) {
  50553. // Initialize button state.
  50554. if (!this.buttonStates[id]) {
  50555. this.buttonStates[id] = {pressed: false, touched: false, value: 0};
  50556. }
  50557. if (!this.buttonEventDetails[id]) {
  50558. this.buttonEventDetails[id] = {id: id, state: this.buttonStates[id]};
  50559. }
  50560. buttonState = gamepad.buttons[id];
  50561. this.handleButton(id, buttonState);
  50562. }
  50563. // Check axes.
  50564. this.handleAxes();
  50565. },
  50566. /**
  50567. * Handle presses and touches for a single button.
  50568. *
  50569. * @param {number} id - Index of button in Gamepad button array.
  50570. * @param {number} buttonState - Value of button state from 0 to 1.
  50571. * @returns {boolean} Whether button has changed in any way.
  50572. */
  50573. handleButton: function (id, buttonState) {
  50574. var changed;
  50575. changed = this.handlePress(id, buttonState) |
  50576. this.handleTouch(id, buttonState) |
  50577. this.handleValue(id, buttonState);
  50578. if (!changed) { return false; }
  50579. this.el.emit(EVENTS.BUTTONCHANGED, this.buttonEventDetails[id], false);
  50580. return true;
  50581. },
  50582. /**
  50583. * An axis is an array of values from -1 (up, left) to 1 (down, right).
  50584. * Compare each component of the axis to the previous value to determine change.
  50585. *
  50586. * @returns {boolean} Whether axes changed.
  50587. */
  50588. handleAxes: function () {
  50589. var changed = false;
  50590. var controllerAxes = this.controller.gamepad.axes;
  50591. var i;
  50592. var previousAxis = this.axis;
  50593. var changedAxes = this.changedAxes;
  50594. // Check if axis changed.
  50595. this.changedAxes.splice(0, this.changedAxes.length);
  50596. for (i = 0; i < controllerAxes.length; ++i) {
  50597. changedAxes.push(previousAxis[i] !== controllerAxes[i]);
  50598. if (changedAxes[i]) { changed = true; }
  50599. }
  50600. if (!changed) { return false; }
  50601. this.axis.splice(0, this.axis.length);
  50602. for (i = 0; i < controllerAxes.length; i++) {
  50603. this.axis.push(controllerAxes[i]);
  50604. }
  50605. this.el.emit(EVENTS.AXISMOVE, this.axisMoveEventDetail, false);
  50606. return true;
  50607. },
  50608. /**
  50609. * Determine whether a button press has occured and emit events as appropriate.
  50610. *
  50611. * @param {string} id - ID of the button to check.
  50612. * @param {object} buttonState - State of the button to check.
  50613. * @returns {boolean} Whether button press state changed.
  50614. */
  50615. handlePress: function (id, buttonState) {
  50616. var evtName;
  50617. var previousButtonState = this.buttonStates[id];
  50618. // Not changed.
  50619. if (buttonState.pressed === previousButtonState.pressed) { return false; }
  50620. evtName = buttonState.pressed ? EVENTS.BUTTONDOWN : EVENTS.BUTTONUP;
  50621. this.el.emit(evtName, this.buttonEventDetails[id], false);
  50622. previousButtonState.pressed = buttonState.pressed;
  50623. return true;
  50624. },
  50625. /**
  50626. * Determine whether a button touch has occured and emit events as appropriate.
  50627. *
  50628. * @param {string} id - ID of the button to check.
  50629. * @param {object} buttonState - State of the button to check.
  50630. * @returns {boolean} Whether button touch state changed.
  50631. */
  50632. handleTouch: function (id, buttonState) {
  50633. var evtName;
  50634. var previousButtonState = this.buttonStates[id];
  50635. // Not changed.
  50636. if (buttonState.touched === previousButtonState.touched) { return false; }
  50637. evtName = buttonState.touched ? EVENTS.TOUCHSTART : EVENTS.TOUCHEND;
  50638. this.el.emit(evtName, this.buttonEventDetails[id], false);
  50639. previousButtonState.touched = buttonState.touched;
  50640. return true;
  50641. },
  50642. /**
  50643. * Determine whether a button value has changed.
  50644. *
  50645. * @param {string} id - Id of the button to check.
  50646. * @param {object} buttonState - State of the button to check.
  50647. * @returns {boolean} Whether button value changed.
  50648. */
  50649. handleValue: function (id, buttonState) {
  50650. var previousButtonState = this.buttonStates[id];
  50651. // Not changed.
  50652. if (buttonState.value === previousButtonState.value) { return false; }
  50653. previousButtonState.value = buttonState.value;
  50654. return true;
  50655. }
  50656. });
  50657. },{"../core/component":128,"../utils/tracked-controls":210}],113:[function(_dereq_,module,exports){
  50658. var registerComponent = _dereq_('../core/component').registerComponent;
  50659. /**
  50660. * Tracked controls.
  50661. * Abstract controls that decide if the WebVR or WebXR version is going to be applied.
  50662. *
  50663. * @property {number} controller - Index of controller in array returned by Gamepad API.
  50664. * Only used if hand property is not set.
  50665. * @property {string} id - Selected controller among those returned by Gamepad API.
  50666. * @property {number} hand - If multiple controllers found with id, choose the one with the
  50667. * given value for hand. If set, we ignore 'controller' property
  50668. */
  50669. module.exports.Component = registerComponent('tracked-controls', {
  50670. schema: {
  50671. autoHide: {default: true},
  50672. controller: {default: -1},
  50673. id: {type: 'string', default: ''},
  50674. hand: {type: 'string', default: ''},
  50675. idPrefix: {type: 'string', default: ''},
  50676. orientationOffset: {type: 'vec3'},
  50677. // Arm model parameters when not 6DoF.
  50678. armModel: {default: false},
  50679. headElement: {type: 'selector'},
  50680. iterateControllerProfiles: {default: false}
  50681. },
  50682. update: function () {
  50683. var data = this.data;
  50684. var el = this.el;
  50685. if (el.sceneEl.hasWebXR) {
  50686. el.setAttribute('tracked-controls-webxr', {
  50687. id: data.id,
  50688. hand: data.hand,
  50689. index: data.controller,
  50690. iterateControllerProfiles: data.iterateControllerProfiles
  50691. });
  50692. } else {
  50693. el.setAttribute('tracked-controls-webvr', data);
  50694. }
  50695. }
  50696. });
  50697. },{"../core/component":128}],114:[function(_dereq_,module,exports){
  50698. var registerComponent = _dereq_('../core/component').registerComponent;
  50699. var bind = _dereq_('../utils/bind');
  50700. var THREE = _dereq_('../lib/three');
  50701. var trackedControlsUtils = _dereq_('../utils/tracked-controls');
  50702. var checkControllerPresentAndSetup = trackedControlsUtils.checkControllerPresentAndSetup;
  50703. var emitIfAxesChanged = trackedControlsUtils.emitIfAxesChanged;
  50704. var onButtonEvent = trackedControlsUtils.onButtonEvent;
  50705. var INDEX_CONTROLLER_MODEL_BASE_URL = 'https://cdn.aframe.io/controllers/valve/index/valve_index_';
  50706. var INDEX_CONTROLLER_MODEL_URL = {
  50707. left: INDEX_CONTROLLER_MODEL_BASE_URL + 'left.gltf',
  50708. right: INDEX_CONTROLLER_MODEL_BASE_URL + 'right.gltf'
  50709. };
  50710. var GAMEPAD_ID_PREFIX = 'valve';
  50711. var INDEX_CONTROLLER_POSITION_OFFSET = {
  50712. left: {x: -0.00023692678902063457, y: 0.04724540367838371, z: -0.061959880395271096},
  50713. right: {x: 0.002471558599671131, y: 0.055765208987076195, z: -0.061068168708348844}
  50714. };
  50715. var INDEX_CONTROLLER_ROTATION_OFFSET = {
  50716. left: {_x: 0.692295102620542, _y: -0.0627618864318427, _z: -0.06265893149611756, _order: 'XYZ'},
  50717. right: {_x: 0.6484021229942998, _y: -0.032563619881892894, _z: -0.1327973171917482, _order: 'XYZ'}
  50718. };
  50719. /**
  50720. * Vive controls.
  50721. * Interface with Vive controllers and map Gamepad events to controller buttons:
  50722. * trackpad, trigger, grip, menu, system
  50723. * Load a controller model and highlight the pressed buttons.
  50724. */
  50725. module.exports.Component = registerComponent('valve-index-controls', {
  50726. schema: {
  50727. hand: {default: 'left'},
  50728. buttonColor: {type: 'color', default: '#FAFAFA'}, // Off-white.
  50729. buttonHighlightColor: {type: 'color', default: '#22D1EE'}, // Light blue.
  50730. model: {default: true},
  50731. orientationOffset: {type: 'vec3'}
  50732. },
  50733. mapping: {
  50734. axes: {trackpad: [0, 1]},
  50735. buttons: [
  50736. 'trigger', 'grip', 'joystick', 'abutton', 'abutton',
  50737. 'system', 'finger1', 'finger2', 'finger3',
  50738. 'finger4', 'finger5']
  50739. },
  50740. init: function () {
  50741. var self = this;
  50742. this.controllerPresent = false;
  50743. this.lastControllerCheck = 0;
  50744. this.onButtonChanged = bind(this.onButtonChanged, this);
  50745. this.onButtonDown = function (evt) { onButtonEvent(evt.detail.id, 'down', self); };
  50746. this.onButtonUp = function (evt) { onButtonEvent(evt.detail.id, 'up', self); };
  50747. this.onButtonTouchEnd = function (evt) { onButtonEvent(evt.detail.id, 'touchend', self); };
  50748. this.onButtonTouchStart = function (evt) { onButtonEvent(evt.detail.id, 'touchstart', self); };
  50749. this.previousButtonValues = {};
  50750. this.rendererSystem = this.el.sceneEl.systems.renderer;
  50751. this.bindMethods();
  50752. },
  50753. play: function () {
  50754. this.checkIfControllerPresent();
  50755. this.addControllersUpdateListener();
  50756. },
  50757. pause: function () {
  50758. this.removeEventListeners();
  50759. this.removeControllersUpdateListener();
  50760. },
  50761. bindMethods: function () {
  50762. this.onModelLoaded = bind(this.onModelLoaded, this);
  50763. this.onControllersUpdate = bind(this.onControllersUpdate, this);
  50764. this.checkIfControllerPresent = bind(this.checkIfControllerPresent, this);
  50765. this.removeControllersUpdateListener = bind(this.removeControllersUpdateListener, this);
  50766. this.onAxisMoved = bind(this.onAxisMoved, this);
  50767. },
  50768. addEventListeners: function () {
  50769. var el = this.el;
  50770. el.addEventListener('buttonchanged', this.onButtonChanged);
  50771. el.addEventListener('buttondown', this.onButtonDown);
  50772. el.addEventListener('buttonup', this.onButtonUp);
  50773. el.addEventListener('touchend', this.onButtonTouchEnd);
  50774. el.addEventListener('touchstart', this.onButtonTouchStart);
  50775. el.addEventListener('model-loaded', this.onModelLoaded);
  50776. el.addEventListener('axismove', this.onAxisMoved);
  50777. this.controllerEventsActive = true;
  50778. },
  50779. removeEventListeners: function () {
  50780. var el = this.el;
  50781. el.removeEventListener('buttonchanged', this.onButtonChanged);
  50782. el.removeEventListener('buttondown', this.onButtonDown);
  50783. el.removeEventListener('buttonup', this.onButtonUp);
  50784. el.removeEventListener('touchend', this.onButtonTouchEnd);
  50785. el.removeEventListener('touchstart', this.onButtonTouchStart);
  50786. el.removeEventListener('model-loaded', this.onModelLoaded);
  50787. el.removeEventListener('axismove', this.onAxisMoved);
  50788. this.controllerEventsActive = false;
  50789. },
  50790. /**
  50791. * Once OpenVR returns correct hand data in supporting browsers, we can use hand property.
  50792. * var isPresent = checkControllerPresentAndSetup(this.el.sceneEl, GAMEPAD_ID_PREFIX,
  50793. { hand: data.hand });
  50794. * Until then, use hardcoded index.
  50795. */
  50796. checkIfControllerPresent: function () {
  50797. var data = this.data;
  50798. var controllerIndex = data.hand === 'right' ? 0 : data.hand === 'left' ? 1 : 2;
  50799. checkControllerPresentAndSetup(this, GAMEPAD_ID_PREFIX, {index: controllerIndex, iterateControllerProfiles: true, hand: data.hand});
  50800. },
  50801. injectTrackedControls: function () {
  50802. var el = this.el;
  50803. var data = this.data;
  50804. // If we have an OpenVR Gamepad, use the fixed mapping.
  50805. el.setAttribute('tracked-controls', {
  50806. idPrefix: GAMEPAD_ID_PREFIX,
  50807. // Hand IDs: 1 = right, 0 = left, 2 = anything else.
  50808. controller: data.hand === 'right' ? 1 : data.hand === 'left' ? 0 : 2,
  50809. hand: data.hand,
  50810. orientationOffset: data.orientationOffset
  50811. });
  50812. this.loadModel();
  50813. },
  50814. loadModel: function () {
  50815. var data = this.data;
  50816. if (!data.model) { return; }
  50817. this.el.setAttribute('gltf-model', '' + INDEX_CONTROLLER_MODEL_URL[data.hand] + '');
  50818. },
  50819. addControllersUpdateListener: function () {
  50820. this.el.sceneEl.addEventListener('controllersupdated', this.onControllersUpdate, false);
  50821. },
  50822. removeControllersUpdateListener: function () {
  50823. this.el.sceneEl.removeEventListener('controllersupdated', this.onControllersUpdate, false);
  50824. },
  50825. onControllersUpdate: function () {
  50826. this.checkIfControllerPresent();
  50827. },
  50828. /**
  50829. * Rotate the trigger button based on how hard the trigger is pressed.
  50830. */
  50831. onButtonChanged: function (evt) {
  50832. var button = this.mapping.buttons[evt.detail.id];
  50833. var buttonMeshes = this.buttonMeshes;
  50834. var analogValue;
  50835. if (!button) { return; }
  50836. if (button === 'trigger') {
  50837. analogValue = evt.detail.state.value;
  50838. // Update trigger rotation depending on button value.
  50839. if (buttonMeshes && buttonMeshes.trigger) {
  50840. buttonMeshes.trigger.rotation.x = -analogValue * (Math.PI / 12);
  50841. }
  50842. }
  50843. // Pass along changed event with button state, using button mapping for convenience.
  50844. this.el.emit(button + 'changed', evt.detail.state);
  50845. },
  50846. onModelLoaded: function (evt) {
  50847. var buttonMeshes;
  50848. var controllerObject3D = evt.detail.model;
  50849. var self = this;
  50850. if (!this.data.model) { return; }
  50851. // Store button meshes object to be able to change their colors.
  50852. buttonMeshes = this.buttonMeshes = {};
  50853. buttonMeshes.grip = {
  50854. left: controllerObject3D.getObjectByName('leftgrip'),
  50855. right: controllerObject3D.getObjectByName('rightgrip')
  50856. };
  50857. buttonMeshes.menu = controllerObject3D.getObjectByName('menubutton');
  50858. buttonMeshes.system = controllerObject3D.getObjectByName('systembutton');
  50859. buttonMeshes.trackpad = controllerObject3D.getObjectByName('touchpad');
  50860. buttonMeshes.trigger = controllerObject3D.getObjectByName('trigger');
  50861. // Set default colors.
  50862. Object.keys(buttonMeshes).forEach(function (buttonName) {
  50863. self.setButtonColor(buttonName, self.data.buttonColor);
  50864. });
  50865. // Offset pivot point.
  50866. controllerObject3D.position.copy(INDEX_CONTROLLER_POSITION_OFFSET[this.data.hand]);
  50867. controllerObject3D.rotation.copy(INDEX_CONTROLLER_ROTATION_OFFSET[this.data.hand]);
  50868. this.el.emit('controllermodelready', {
  50869. name: 'valve-index-controlls',
  50870. model: this.data.model,
  50871. rayOrigin: new THREE.Vector3(0, 0, 0)
  50872. });
  50873. },
  50874. onAxisMoved: function (evt) {
  50875. emitIfAxesChanged(this, this.mapping.axes, evt);
  50876. },
  50877. updateModel: function (buttonName, evtName) {
  50878. var color;
  50879. var isTouch;
  50880. if (!this.data.model) { return; }
  50881. isTouch = evtName.indexOf('touch') !== -1;
  50882. // Don't change color for trackpad touch.
  50883. if (isTouch) { return; }
  50884. // Update colors.
  50885. color = evtName === 'up' ? this.data.buttonColor : this.data.buttonHighlightColor;
  50886. this.setButtonColor(buttonName, color);
  50887. },
  50888. setButtonColor: function (buttonName, color) {
  50889. // TODO: The meshes aren't set up correctly now, skipping for the moment
  50890. return;
  50891. }
  50892. });
  50893. },{"../core/component":128,"../lib/three":176,"../utils/bind":196,"../utils/tracked-controls":210}],115:[function(_dereq_,module,exports){
  50894. var registerComponent = _dereq_('../core/component').registerComponent;
  50895. /**
  50896. * Visibility component.
  50897. */
  50898. module.exports.Component = registerComponent('visible', {
  50899. schema: {default: true},
  50900. update: function () {
  50901. this.el.object3D.visible = this.data;
  50902. }
  50903. });
  50904. },{"../core/component":128}],116:[function(_dereq_,module,exports){
  50905. var registerComponent = _dereq_('../core/component').registerComponent;
  50906. var bind = _dereq_('../utils/bind');
  50907. var trackedControlsUtils = _dereq_('../utils/tracked-controls');
  50908. var checkControllerPresentAndSetup = trackedControlsUtils.checkControllerPresentAndSetup;
  50909. var emitIfAxesChanged = trackedControlsUtils.emitIfAxesChanged;
  50910. var onButtonEvent = trackedControlsUtils.onButtonEvent;
  50911. var VIVE_CONTROLLER_MODEL_OBJ_URL = 'https://cdn.aframe.io/controllers/vive/vr_controller_vive.obj';
  50912. var VIVE_CONTROLLER_MODEL_OBJ_MTL = 'https://cdn.aframe.io/controllers/vive/vr_controller_vive.mtl';
  50913. var isWebXRAvailable = _dereq_('../utils/').device.isWebXRAvailable;
  50914. var GAMEPAD_ID_WEBXR = 'htc-vive-controller-mv';
  50915. var GAMEPAD_ID_WEBVR = 'OpenVR ';
  50916. // Prefix for Gen1 and Gen2 Oculus Touch Controllers.
  50917. var GAMEPAD_ID_PREFIX = isWebXRAvailable ? GAMEPAD_ID_WEBXR : GAMEPAD_ID_WEBVR;
  50918. /**
  50919. * Button IDs:
  50920. * 0 - trackpad
  50921. * 1 - trigger (intensity value from 0.5 to 1)
  50922. * 2 - grip
  50923. * 3 - menu (dispatch but better for menu options)
  50924. * 4 - system (never dispatched on this layer)
  50925. */
  50926. var INPUT_MAPPING_WEBVR = {
  50927. axes: {trackpad: [0, 1]},
  50928. buttons: ['trackpad', 'trigger', 'grip', 'menu', 'system']
  50929. };
  50930. /**
  50931. * Button IDs:
  50932. * 0 - trigger
  50933. * 1 - squeeze
  50934. * 2 - touchpad
  50935. * 3 - none (dispatch but better for menu options)
  50936. * 4 - menu (never dispatched on this layer)
  50937. *
  50938. * Axis:
  50939. * 0 - touchpad x axis
  50940. * 1 - touchpad y axis
  50941. * Reference: https://github.com/immersive-web/webxr-input-profiles/blob/master/packages/registry/profiles/htc/htc-vive.json
  50942. */
  50943. var INPUT_MAPPING_WEBXR = {
  50944. axes: {thumbstick: [0, 1]},
  50945. buttons: ['trigger', 'grip', 'trackpad', 'none', 'menu']
  50946. };
  50947. var INPUT_MAPPING = isWebXRAvailable ? INPUT_MAPPING_WEBXR : INPUT_MAPPING_WEBVR;
  50948. /**
  50949. * Vive controls.
  50950. * Interface with Vive controllers and map Gamepad events to controller buttons:
  50951. * trackpad, trigger, grip, menu, system
  50952. * Load a controller model and highlight the pressed buttons.
  50953. */
  50954. module.exports.Component = registerComponent('vive-controls', {
  50955. schema: {
  50956. hand: {default: 'left'},
  50957. buttonColor: {type: 'color', default: '#FAFAFA'}, // Off-white.
  50958. buttonHighlightColor: {type: 'color', default: '#22D1EE'}, // Light blue.
  50959. model: {default: true},
  50960. orientationOffset: {type: 'vec3'}
  50961. },
  50962. mapping: INPUT_MAPPING,
  50963. init: function () {
  50964. var self = this;
  50965. this.controllerPresent = false;
  50966. this.lastControllerCheck = 0;
  50967. this.onButtonChanged = bind(this.onButtonChanged, this);
  50968. this.onButtonDown = function (evt) { onButtonEvent(evt.detail.id, 'down', self); };
  50969. this.onButtonUp = function (evt) { onButtonEvent(evt.detail.id, 'up', self); };
  50970. this.onButtonTouchEnd = function (evt) { onButtonEvent(evt.detail.id, 'touchend', self); };
  50971. this.onButtonTouchStart = function (evt) { onButtonEvent(evt.detail.id, 'touchstart', self); };
  50972. this.previousButtonValues = {};
  50973. this.rendererSystem = this.el.sceneEl.systems.renderer;
  50974. this.bindMethods();
  50975. },
  50976. update: function () {
  50977. var data = this.data;
  50978. this.controllerIndex = data.hand === 'right' ? 0 : data.hand === 'left' ? 1 : 2;
  50979. },
  50980. play: function () {
  50981. this.checkIfControllerPresent();
  50982. this.addControllersUpdateListener();
  50983. },
  50984. pause: function () {
  50985. this.removeEventListeners();
  50986. this.removeControllersUpdateListener();
  50987. },
  50988. bindMethods: function () {
  50989. this.onModelLoaded = bind(this.onModelLoaded, this);
  50990. this.onControllersUpdate = bind(this.onControllersUpdate, this);
  50991. this.checkIfControllerPresent = bind(this.checkIfControllerPresent, this);
  50992. this.removeControllersUpdateListener = bind(this.removeControllersUpdateListener, this);
  50993. this.onAxisMoved = bind(this.onAxisMoved, this);
  50994. },
  50995. addEventListeners: function () {
  50996. var el = this.el;
  50997. el.addEventListener('buttonchanged', this.onButtonChanged);
  50998. el.addEventListener('buttondown', this.onButtonDown);
  50999. el.addEventListener('buttonup', this.onButtonUp);
  51000. el.addEventListener('touchend', this.onButtonTouchEnd);
  51001. el.addEventListener('touchstart', this.onButtonTouchStart);
  51002. el.addEventListener('model-loaded', this.onModelLoaded);
  51003. el.addEventListener('axismove', this.onAxisMoved);
  51004. this.controllerEventsActive = true;
  51005. },
  51006. removeEventListeners: function () {
  51007. var el = this.el;
  51008. el.removeEventListener('buttonchanged', this.onButtonChanged);
  51009. el.removeEventListener('buttondown', this.onButtonDown);
  51010. el.removeEventListener('buttonup', this.onButtonUp);
  51011. el.removeEventListener('touchend', this.onButtonTouchEnd);
  51012. el.removeEventListener('touchstart', this.onButtonTouchStart);
  51013. el.removeEventListener('model-loaded', this.onModelLoaded);
  51014. el.removeEventListener('axismove', this.onAxisMoved);
  51015. this.controllerEventsActive = false;
  51016. },
  51017. /**
  51018. * Once OpenVR returns correct hand data in supporting browsers, we can use hand property.
  51019. * var isPresent = checkControllerPresentAndSetup(this.el.sceneEl, GAMEPAD_ID_PREFIX,
  51020. { hand: data.hand });
  51021. * Until then, use hardcoded index.
  51022. */
  51023. checkIfControllerPresent: function () {
  51024. var data = this.data;
  51025. checkControllerPresentAndSetup(this, GAMEPAD_ID_PREFIX, {index: this.controllerIndex, hand: data.hand});
  51026. },
  51027. injectTrackedControls: function () {
  51028. var el = this.el;
  51029. var data = this.data;
  51030. // If we have an OpenVR Gamepad, use the fixed mapping.
  51031. el.setAttribute('tracked-controls', {
  51032. idPrefix: GAMEPAD_ID_PREFIX,
  51033. hand: data.hand,
  51034. controller: this.controllerIndex,
  51035. orientationOffset: data.orientationOffset
  51036. });
  51037. // Load model.
  51038. if (!this.data.model) { return; }
  51039. this.el.setAttribute('obj-model', {
  51040. obj: VIVE_CONTROLLER_MODEL_OBJ_URL,
  51041. mtl: VIVE_CONTROLLER_MODEL_OBJ_MTL
  51042. });
  51043. },
  51044. addControllersUpdateListener: function () {
  51045. this.el.sceneEl.addEventListener('controllersupdated', this.onControllersUpdate, false);
  51046. },
  51047. removeControllersUpdateListener: function () {
  51048. this.el.sceneEl.removeEventListener('controllersupdated', this.onControllersUpdate, false);
  51049. },
  51050. onControllersUpdate: function () {
  51051. this.checkIfControllerPresent();
  51052. },
  51053. /**
  51054. * Rotate the trigger button based on how hard the trigger is pressed.
  51055. */
  51056. onButtonChanged: function (evt) {
  51057. var button = this.mapping.buttons[evt.detail.id];
  51058. var buttonMeshes = this.buttonMeshes;
  51059. var analogValue;
  51060. if (!button) { return; }
  51061. if (button === 'trigger') {
  51062. analogValue = evt.detail.state.value;
  51063. // Update trigger rotation depending on button value.
  51064. if (buttonMeshes && buttonMeshes.trigger) {
  51065. buttonMeshes.trigger.rotation.x = -analogValue * (Math.PI / 12);
  51066. }
  51067. }
  51068. // Pass along changed event with button state, using button mapping for convenience.
  51069. this.el.emit(button + 'changed', evt.detail.state);
  51070. },
  51071. onModelLoaded: function (evt) {
  51072. var buttonMeshes;
  51073. var controllerObject3D = evt.detail.model;
  51074. var self = this;
  51075. if (!this.data.model) { return; }
  51076. // Store button meshes object to be able to change their colors.
  51077. buttonMeshes = this.buttonMeshes = {};
  51078. buttonMeshes.grip = {
  51079. left: controllerObject3D.getObjectByName('leftgrip'),
  51080. right: controllerObject3D.getObjectByName('rightgrip')
  51081. };
  51082. buttonMeshes.menu = controllerObject3D.getObjectByName('menubutton');
  51083. buttonMeshes.system = controllerObject3D.getObjectByName('systembutton');
  51084. buttonMeshes.trackpad = controllerObject3D.getObjectByName('touchpad');
  51085. buttonMeshes.trigger = controllerObject3D.getObjectByName('trigger');
  51086. // Set default colors.
  51087. Object.keys(buttonMeshes).forEach(function (buttonName) {
  51088. self.setButtonColor(buttonName, self.data.buttonColor);
  51089. });
  51090. // Offset pivot point.
  51091. controllerObject3D.position.set(0, -0.015, 0.04);
  51092. },
  51093. onAxisMoved: function (evt) {
  51094. emitIfAxesChanged(this, this.mapping.axes, evt);
  51095. },
  51096. updateModel: function (buttonName, evtName) {
  51097. var color;
  51098. var isTouch;
  51099. if (!this.data.model) { return; }
  51100. isTouch = evtName.indexOf('touch') !== -1;
  51101. // Don't change color for trackpad touch.
  51102. if (isTouch) { return; }
  51103. // Update colors.
  51104. color = evtName === 'up' ? this.data.buttonColor : this.data.buttonHighlightColor;
  51105. this.setButtonColor(buttonName, color);
  51106. },
  51107. setButtonColor: function (buttonName, color) {
  51108. var buttonMeshes = this.buttonMeshes;
  51109. var rendererSystem = this.rendererSystem;
  51110. if (!buttonMeshes) { return; }
  51111. // Need to do both left and right sides for grip.
  51112. if (buttonName === 'grip') {
  51113. buttonMeshes.grip.left.material.color.set(color);
  51114. buttonMeshes.grip.right.material.color.set(color);
  51115. rendererSystem.applyColorCorrection(buttonMeshes.grip.left.material.color);
  51116. rendererSystem.applyColorCorrection(buttonMeshes.grip.right.material.color);
  51117. return;
  51118. }
  51119. buttonMeshes[buttonName].material.color.set(color);
  51120. rendererSystem.applyColorCorrection(buttonMeshes[buttonName].material.color);
  51121. }
  51122. });
  51123. },{"../core/component":128,"../utils/":202,"../utils/bind":196,"../utils/tracked-controls":210}],117:[function(_dereq_,module,exports){
  51124. var registerComponent = _dereq_('../core/component').registerComponent;
  51125. var bind = _dereq_('../utils/bind');
  51126. var trackedControlsUtils = _dereq_('../utils/tracked-controls');
  51127. var checkControllerPresentAndSetup = trackedControlsUtils.checkControllerPresentAndSetup;
  51128. var emitIfAxesChanged = trackedControlsUtils.emitIfAxesChanged;
  51129. var onButtonEvent = trackedControlsUtils.onButtonEvent;
  51130. var GAMEPAD_ID_PREFIX = 'HTC Vive Focus';
  51131. var VIVE_FOCUS_CONTROLLER_MODEL_URL = 'https://cdn.aframe.io/controllers/vive/focus-controller/focus-controller.gltf';
  51132. /**
  51133. * Vive Focus controls.
  51134. * Interface with Vive Focus controller and map Gamepad events to
  51135. * controller buttons: trackpad, trigger
  51136. * Load a controller model and highlight the pressed buttons.
  51137. */
  51138. module.exports.Component = registerComponent('vive-focus-controls', {
  51139. schema: {
  51140. hand: {default: ''}, // This informs the degenerate arm model.
  51141. buttonTouchedColor: {type: 'color', default: '#BBBBBB'},
  51142. buttonHighlightColor: {type: 'color', default: '#7A7A7A'},
  51143. model: {default: true},
  51144. orientationOffset: {type: 'vec3'},
  51145. armModel: {default: true}
  51146. },
  51147. /**
  51148. * Button IDs:
  51149. * 0 - trackpad
  51150. * 1 - trigger
  51151. */
  51152. mapping: {
  51153. axes: {trackpad: [0, 1]},
  51154. buttons: ['trackpad', 'trigger']
  51155. },
  51156. bindMethods: function () {
  51157. this.onModelLoaded = bind(this.onModelLoaded, this);
  51158. this.onControllersUpdate = bind(this.onControllersUpdate, this);
  51159. this.checkIfControllerPresent = bind(this.checkIfControllerPresent, this);
  51160. this.removeControllersUpdateListener = bind(this.removeControllersUpdateListener, this);
  51161. this.onAxisMoved = bind(this.onAxisMoved, this);
  51162. },
  51163. init: function () {
  51164. var self = this;
  51165. this.onButtonChanged = bind(this.onButtonChanged, this);
  51166. this.onButtonDown = function (evt) { onButtonEvent(evt.detail.id, 'down', self); };
  51167. this.onButtonUp = function (evt) { onButtonEvent(evt.detail.id, 'up', self); };
  51168. this.onButtonTouchStart = function (evt) { onButtonEvent(evt.detail.id, 'touchstart', self); };
  51169. this.onButtonTouchEnd = function (evt) { onButtonEvent(evt.detail.id, 'touchend', self); };
  51170. this.controllerPresent = false;
  51171. this.lastControllerCheck = 0;
  51172. this.bindMethods();
  51173. },
  51174. addEventListeners: function () {
  51175. var el = this.el;
  51176. el.addEventListener('buttonchanged', this.onButtonChanged);
  51177. el.addEventListener('buttondown', this.onButtonDown);
  51178. el.addEventListener('buttonup', this.onButtonUp);
  51179. el.addEventListener('touchstart', this.onButtonTouchStart);
  51180. el.addEventListener('touchend', this.onButtonTouchEnd);
  51181. el.addEventListener('model-loaded', this.onModelLoaded);
  51182. el.addEventListener('axismove', this.onAxisMoved);
  51183. this.controllerEventsActive = true;
  51184. this.addControllersUpdateListener();
  51185. },
  51186. removeEventListeners: function () {
  51187. var el = this.el;
  51188. el.removeEventListener('buttonchanged', this.onButtonChanged);
  51189. el.removeEventListener('buttondown', this.onButtonDown);
  51190. el.removeEventListener('buttonup', this.onButtonUp);
  51191. el.removeEventListener('touchstart', this.onButtonTouchStart);
  51192. el.removeEventListener('touchend', this.onButtonTouchEnd);
  51193. el.removeEventListener('model-loaded', this.onModelLoaded);
  51194. el.removeEventListener('axismove', this.onAxisMoved);
  51195. this.controllerEventsActive = false;
  51196. this.removeControllersUpdateListener();
  51197. },
  51198. checkIfControllerPresent: function () {
  51199. checkControllerPresentAndSetup(this, GAMEPAD_ID_PREFIX,
  51200. this.data.hand ? {hand: this.data.hand} : {});
  51201. },
  51202. play: function () {
  51203. this.checkIfControllerPresent();
  51204. this.addControllersUpdateListener();
  51205. },
  51206. pause: function () {
  51207. this.removeEventListeners();
  51208. this.removeControllersUpdateListener();
  51209. },
  51210. injectTrackedControls: function () {
  51211. var el = this.el;
  51212. var data = this.data;
  51213. el.setAttribute('tracked-controls', {
  51214. armModel: data.armModel,
  51215. idPrefix: GAMEPAD_ID_PREFIX,
  51216. orientationOffset: data.orientationOffset
  51217. });
  51218. if (!this.data.model) { return; }
  51219. this.el.setAttribute('gltf-model', VIVE_FOCUS_CONTROLLER_MODEL_URL);
  51220. },
  51221. addControllersUpdateListener: function () {
  51222. this.el.sceneEl.addEventListener('controllersupdated', this.onControllersUpdate, false);
  51223. },
  51224. removeControllersUpdateListener: function () {
  51225. this.el.sceneEl.removeEventListener('controllersupdated', this.onControllersUpdate, false);
  51226. },
  51227. onControllersUpdate: function () {
  51228. this.checkIfControllerPresent();
  51229. },
  51230. onModelLoaded: function (evt) {
  51231. var controllerObject3D = evt.detail.model;
  51232. var buttonMeshes;
  51233. if (!this.data.model) { return; }
  51234. buttonMeshes = this.buttonMeshes = {};
  51235. buttonMeshes.trigger = controllerObject3D.getObjectByName('BumperKey');
  51236. buttonMeshes.triggerPressed = controllerObject3D.getObjectByName('BumperKey_Press');
  51237. if (buttonMeshes.triggerPressed) {
  51238. buttonMeshes.triggerPressed.visible = false;
  51239. }
  51240. buttonMeshes.trackpad = controllerObject3D.getObjectByName('TouchPad');
  51241. buttonMeshes.trackpadPressed = controllerObject3D.getObjectByName('TouchPad_Press');
  51242. if (buttonMeshes.trackpadPressed) {
  51243. buttonMeshes.trackpadPressed.visible = false;
  51244. }
  51245. },
  51246. // No analog buttons, only emits 0/1 values
  51247. onButtonChanged: function (evt) {
  51248. var button = this.mapping.buttons[evt.detail.id];
  51249. if (!button) return;
  51250. // Pass along changed event with button state, using button mapping for convenience.
  51251. this.el.emit(button + 'changed', evt.detail.state);
  51252. },
  51253. onAxisMoved: function (evt) {
  51254. emitIfAxesChanged(this, this.mapping.axes, evt);
  51255. },
  51256. updateModel: function (buttonName, evtName) {
  51257. if (!this.data.model) { return; }
  51258. this.updateButtonModel(buttonName, evtName);
  51259. },
  51260. updateButtonModel: function (buttonName, state) {
  51261. var buttonMeshes = this.buttonMeshes;
  51262. var pressedName = buttonName + 'Pressed';
  51263. if (!buttonMeshes || !buttonMeshes[buttonName] || !buttonMeshes[pressedName]) {
  51264. return;
  51265. }
  51266. var color;
  51267. switch (state) {
  51268. case 'down':
  51269. color = this.data.buttonHighlightColor;
  51270. break;
  51271. case 'touchstart':
  51272. color = this.data.buttonTouchedColor;
  51273. break;
  51274. }
  51275. if (color) {
  51276. buttonMeshes[pressedName].material.color.set(color);
  51277. }
  51278. buttonMeshes[pressedName].visible = !!color;
  51279. buttonMeshes[buttonName].visible = !color;
  51280. }
  51281. });
  51282. },{"../core/component":128,"../utils/bind":196,"../utils/tracked-controls":210}],118:[function(_dereq_,module,exports){
  51283. var KEYCODE_TO_CODE = _dereq_('../constants').keyboardevent.KEYCODE_TO_CODE;
  51284. var registerComponent = _dereq_('../core/component').registerComponent;
  51285. var THREE = _dereq_('../lib/three');
  51286. var utils = _dereq_('../utils/');
  51287. var bind = utils.bind;
  51288. var shouldCaptureKeyEvent = utils.shouldCaptureKeyEvent;
  51289. var CLAMP_VELOCITY = 0.00001;
  51290. var MAX_DELTA = 0.2;
  51291. var KEYS = [
  51292. 'KeyW', 'KeyA', 'KeyS', 'KeyD',
  51293. 'ArrowUp', 'ArrowLeft', 'ArrowRight', 'ArrowDown'
  51294. ];
  51295. /**
  51296. * WASD component to control entities using WASD keys.
  51297. */
  51298. module.exports.Component = registerComponent('wasd-controls', {
  51299. schema: {
  51300. acceleration: {default: 65},
  51301. adAxis: {default: 'x', oneOf: ['x', 'y', 'z']},
  51302. adEnabled: {default: true},
  51303. adInverted: {default: false},
  51304. enabled: {default: true},
  51305. fly: {default: false},
  51306. wsAxis: {default: 'z', oneOf: ['x', 'y', 'z']},
  51307. wsEnabled: {default: true},
  51308. wsInverted: {default: false}
  51309. },
  51310. init: function () {
  51311. // To keep track of the pressed keys.
  51312. this.keys = {};
  51313. this.easing = 1.1;
  51314. this.velocity = new THREE.Vector3();
  51315. // Bind methods and add event listeners.
  51316. this.onBlur = bind(this.onBlur, this);
  51317. this.onFocus = bind(this.onFocus, this);
  51318. this.onKeyDown = bind(this.onKeyDown, this);
  51319. this.onKeyUp = bind(this.onKeyUp, this);
  51320. this.onVisibilityChange = bind(this.onVisibilityChange, this);
  51321. this.attachVisibilityEventListeners();
  51322. },
  51323. tick: function (time, delta) {
  51324. var data = this.data;
  51325. var el = this.el;
  51326. var velocity = this.velocity;
  51327. if (!velocity[data.adAxis] && !velocity[data.wsAxis] &&
  51328. isEmptyObject(this.keys)) { return; }
  51329. // Update velocity.
  51330. delta = delta / 1000;
  51331. this.updateVelocity(delta);
  51332. if (!velocity[data.adAxis] && !velocity[data.wsAxis]) { return; }
  51333. // Get movement vector and translate position.
  51334. el.object3D.position.add(this.getMovementVector(delta));
  51335. },
  51336. remove: function () {
  51337. this.removeKeyEventListeners();
  51338. this.removeVisibilityEventListeners();
  51339. },
  51340. play: function () {
  51341. this.attachKeyEventListeners();
  51342. },
  51343. pause: function () {
  51344. this.keys = {};
  51345. this.removeKeyEventListeners();
  51346. },
  51347. updateVelocity: function (delta) {
  51348. var acceleration;
  51349. var adAxis;
  51350. var adSign;
  51351. var data = this.data;
  51352. var keys = this.keys;
  51353. var velocity = this.velocity;
  51354. var wsAxis;
  51355. var wsSign;
  51356. adAxis = data.adAxis;
  51357. wsAxis = data.wsAxis;
  51358. // If FPS too low, reset velocity.
  51359. if (delta > MAX_DELTA) {
  51360. velocity[adAxis] = 0;
  51361. velocity[wsAxis] = 0;
  51362. return;
  51363. }
  51364. // https://gamedev.stackexchange.com/questions/151383/frame-rate-independant-movement-with-acceleration
  51365. var scaledEasing = Math.pow(1 / this.easing, delta * 60);
  51366. // Velocity Easing.
  51367. if (velocity[adAxis] !== 0) {
  51368. velocity[adAxis] = velocity[adAxis] * scaledEasing;
  51369. }
  51370. if (velocity[wsAxis] !== 0) {
  51371. velocity[wsAxis] = velocity[wsAxis] * scaledEasing;
  51372. }
  51373. // Clamp velocity easing.
  51374. if (Math.abs(velocity[adAxis]) < CLAMP_VELOCITY) { velocity[adAxis] = 0; }
  51375. if (Math.abs(velocity[wsAxis]) < CLAMP_VELOCITY) { velocity[wsAxis] = 0; }
  51376. if (!data.enabled) { return; }
  51377. // Update velocity using keys pressed.
  51378. acceleration = data.acceleration;
  51379. if (data.adEnabled) {
  51380. adSign = data.adInverted ? -1 : 1;
  51381. if (keys.KeyA || keys.ArrowLeft) { velocity[adAxis] -= adSign * acceleration * delta; }
  51382. if (keys.KeyD || keys.ArrowRight) { velocity[adAxis] += adSign * acceleration * delta; }
  51383. }
  51384. if (data.wsEnabled) {
  51385. wsSign = data.wsInverted ? -1 : 1;
  51386. if (keys.KeyW || keys.ArrowUp) { velocity[wsAxis] -= wsSign * acceleration * delta; }
  51387. if (keys.KeyS || keys.ArrowDown) { velocity[wsAxis] += wsSign * acceleration * delta; }
  51388. }
  51389. },
  51390. getMovementVector: (function () {
  51391. var directionVector = new THREE.Vector3(0, 0, 0);
  51392. var rotationEuler = new THREE.Euler(0, 0, 0, 'YXZ');
  51393. return function (delta) {
  51394. var rotation = this.el.getAttribute('rotation');
  51395. var velocity = this.velocity;
  51396. var xRotation;
  51397. directionVector.copy(velocity);
  51398. directionVector.multiplyScalar(delta);
  51399. // Absolute.
  51400. if (!rotation) { return directionVector; }
  51401. xRotation = this.data.fly ? rotation.x : 0;
  51402. // Transform direction relative to heading.
  51403. rotationEuler.set(THREE.Math.degToRad(xRotation), THREE.Math.degToRad(rotation.y), 0);
  51404. directionVector.applyEuler(rotationEuler);
  51405. return directionVector;
  51406. };
  51407. })(),
  51408. attachVisibilityEventListeners: function () {
  51409. window.addEventListener('blur', this.onBlur);
  51410. window.addEventListener('focus', this.onFocus);
  51411. document.addEventListener('visibilitychange', this.onVisibilityChange);
  51412. },
  51413. removeVisibilityEventListeners: function () {
  51414. window.removeEventListener('blur', this.onBlur);
  51415. window.removeEventListener('focus', this.onFocus);
  51416. document.removeEventListener('visibilitychange', this.onVisibilityChange);
  51417. },
  51418. attachKeyEventListeners: function () {
  51419. window.addEventListener('keydown', this.onKeyDown);
  51420. window.addEventListener('keyup', this.onKeyUp);
  51421. },
  51422. removeKeyEventListeners: function () {
  51423. window.removeEventListener('keydown', this.onKeyDown);
  51424. window.removeEventListener('keyup', this.onKeyUp);
  51425. },
  51426. onBlur: function () {
  51427. this.pause();
  51428. },
  51429. onFocus: function () {
  51430. this.play();
  51431. },
  51432. onVisibilityChange: function () {
  51433. if (document.hidden) {
  51434. this.onBlur();
  51435. } else {
  51436. this.onFocus();
  51437. }
  51438. },
  51439. onKeyDown: function (event) {
  51440. var code;
  51441. if (!shouldCaptureKeyEvent(event)) { return; }
  51442. code = event.code || KEYCODE_TO_CODE[event.keyCode];
  51443. if (KEYS.indexOf(code) !== -1) { this.keys[code] = true; }
  51444. },
  51445. onKeyUp: function (event) {
  51446. var code;
  51447. code = event.code || KEYCODE_TO_CODE[event.keyCode];
  51448. delete this.keys[code];
  51449. }
  51450. });
  51451. function isEmptyObject (keys) {
  51452. var key;
  51453. for (key in keys) { return false; }
  51454. return true;
  51455. }
  51456. },{"../constants":120,"../core/component":128,"../lib/three":176,"../utils/":202}],119:[function(_dereq_,module,exports){
  51457. /* global THREE */
  51458. var registerComponent = _dereq_('../core/component').registerComponent;
  51459. var bind = _dereq_('../utils/bind');
  51460. var trackedControlsUtils = _dereq_('../utils/tracked-controls');
  51461. var checkControllerPresentAndSetup = trackedControlsUtils.checkControllerPresentAndSetup;
  51462. var emitIfAxesChanged = trackedControlsUtils.emitIfAxesChanged;
  51463. var onButtonEvent = trackedControlsUtils.onButtonEvent;
  51464. var utils = _dereq_('../utils/');
  51465. var debug = utils.debug('components:windows-motion-controls:debug');
  51466. var warn = utils.debug('components:windows-motion-controls:warn');
  51467. var DEFAULT_HANDEDNESS = _dereq_('../constants').DEFAULT_HANDEDNESS;
  51468. var MODEL_BASE_URL = 'https://cdn.aframe.io/controllers/microsoft/';
  51469. var MODEL_FILENAMES = { left: 'left.glb', right: 'right.glb', default: 'universal.glb' };
  51470. var isWebXRAvailable = _dereq_('../utils/').device.isWebXRAvailable;
  51471. var GAMEPAD_ID_WEBXR = 'windows-mixed-reality';
  51472. var GAMEPAD_ID_WEBVR = 'Spatial Controller (Spatial Interaction Source) ';
  51473. var GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  51474. var GAMEPAD_ID_PREFIX = isWebXRAvailable ? GAMEPAD_ID_WEBXR : GAMEPAD_ID_WEBVR;
  51475. var INPUT_MAPPING_WEBVR = {
  51476. // A-Frame specific semantic axis names
  51477. axes: {'thumbstick': [0, 1], 'trackpad': [2, 3]},
  51478. // A-Frame specific semantic button names
  51479. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  51480. // A mapping of the semantic name to node name in the glTF model file,
  51481. // that should be transformed by axis value.
  51482. // This array mirrors the browser Gamepad.axes array, such that
  51483. // the mesh corresponding to axis 0 is in this array index 0.
  51484. axisMeshNames: [
  51485. 'THUMBSTICK_X',
  51486. 'THUMBSTICK_Y',
  51487. 'TOUCHPAD_TOUCH_X',
  51488. 'TOUCHPAD_TOUCH_Y'
  51489. ],
  51490. // A mapping of the semantic name to button node name in the glTF model file,
  51491. // that should be transformed by button value.
  51492. buttonMeshNames: {
  51493. 'trigger': 'SELECT',
  51494. 'menu': 'MENU',
  51495. 'grip': 'GRASP',
  51496. 'thumbstick': 'THUMBSTICK_PRESS',
  51497. 'trackpad': 'TOUCHPAD_PRESS'
  51498. },
  51499. pointingPoseMeshName: 'POINTING_POSE'
  51500. };
  51501. var INPUT_MAPPING_WEBXR = {
  51502. // A-Frame specific semantic axis names
  51503. axes: {'touchpad': [0, 1], 'thumbstick': [2, 3]},
  51504. // A-Frame specific semantic button names
  51505. buttons: ['trigger', 'squeeze', 'touchpad', 'thumbstick', 'menu'],
  51506. // A mapping of the semantic name to node name in the glTF model file,
  51507. // that should be transformed by axis value.
  51508. // This array mirrors the browser Gamepad.axes array, such that
  51509. // the mesh corresponding to axis 0 is in this array index 0.
  51510. axisMeshNames: [
  51511. 'TOUCHPAD_TOUCH_X',
  51512. 'TOUCHPAD_TOUCH_X',
  51513. 'THUMBSTICK_X',
  51514. 'THUMBSTICK_Y'
  51515. ],
  51516. // A mapping of the semantic name to button node name in the glTF model file,
  51517. // that should be transformed by button value.
  51518. buttonMeshNames: {
  51519. 'trigger': 'SELECT',
  51520. 'menu': 'MENU',
  51521. 'squeeze': 'GRASP',
  51522. 'thumbstick': 'THUMBSTICK_PRESS',
  51523. 'touchpad': 'TOUCHPAD_PRESS'
  51524. },
  51525. pointingPoseMeshName: 'POINTING_POSE'
  51526. };
  51527. var INPUT_MAPPING = isWebXRAvailable ? INPUT_MAPPING_WEBXR : INPUT_MAPPING_WEBVR;
  51528. /**
  51529. * Windows Motion Controller controls.
  51530. * Interface with Windows Motion Controller controllers and map Gamepad events to
  51531. * controller buttons: trackpad, trigger, grip, menu, thumbstick
  51532. * Load a controller model and transform the pressed buttons.
  51533. */
  51534. module.exports.Component = registerComponent('windows-motion-controls', {
  51535. schema: {
  51536. hand: {default: DEFAULT_HANDEDNESS},
  51537. // It is possible to have multiple pairs of controllers attached (a pair has both left and right).
  51538. // Set this to 1 to use a controller from the second pair, 2 from the third pair, etc.
  51539. pair: {default: 0},
  51540. // If true, loads the controller glTF asset.
  51541. model: {default: true},
  51542. // If true, will hide the model from the scene if no matching gamepad (based on ID & hand) is connected.
  51543. hideDisconnected: {default: true}
  51544. },
  51545. mapping: INPUT_MAPPING,
  51546. bindMethods: function () {
  51547. this.onModelError = bind(this.onModelError, this);
  51548. this.onModelLoaded = bind(this.onModelLoaded, this);
  51549. this.onControllersUpdate = bind(this.onControllersUpdate, this);
  51550. this.checkIfControllerPresent = bind(this.checkIfControllerPresent, this);
  51551. this.onAxisMoved = bind(this.onAxisMoved, this);
  51552. },
  51553. init: function () {
  51554. var self = this;
  51555. var el = this.el;
  51556. this.onButtonChanged = bind(this.onButtonChanged, this);
  51557. this.onButtonDown = function (evt) { onButtonEvent(evt.detail.id, 'down', self); };
  51558. this.onButtonUp = function (evt) { onButtonEvent(evt.detail.id, 'up', self); };
  51559. this.onButtonTouchStart = function (evt) { onButtonEvent(evt.detail.id, 'touchstart', self); };
  51560. this.onButtonTouchEnd = function (evt) { onButtonEvent(evt.detail.id, 'touchend', self); };
  51561. this.onControllerConnected = function () { self.setModelVisibility(true); };
  51562. this.onControllerDisconnected = function () { self.setModelVisibility(false); };
  51563. this.controllerPresent = false;
  51564. this.lastControllerCheck = 0;
  51565. this.previousButtonValues = {};
  51566. this.bindMethods();
  51567. // Cache for submeshes that we have looked up by name.
  51568. this.loadedMeshInfo = {
  51569. buttonMeshes: null,
  51570. axisMeshes: null
  51571. };
  51572. // Pointing poses
  51573. this.rayOrigin = {
  51574. origin: new THREE.Vector3(),
  51575. direction: new THREE.Vector3(0, 0, -1),
  51576. createdFromMesh: false
  51577. };
  51578. el.addEventListener('controllerconnected', this.onControllerConnected);
  51579. el.addEventListener('controllerdisconnected', this.onControllerDisconnected);
  51580. },
  51581. addEventListeners: function () {
  51582. var el = this.el;
  51583. el.addEventListener('buttonchanged', this.onButtonChanged);
  51584. el.addEventListener('buttondown', this.onButtonDown);
  51585. el.addEventListener('buttonup', this.onButtonUp);
  51586. el.addEventListener('touchstart', this.onButtonTouchStart);
  51587. el.addEventListener('touchend', this.onButtonTouchEnd);
  51588. el.addEventListener('axismove', this.onAxisMoved);
  51589. el.addEventListener('model-error', this.onModelError);
  51590. el.addEventListener('model-loaded', this.onModelLoaded);
  51591. this.controllerEventsActive = true;
  51592. },
  51593. removeEventListeners: function () {
  51594. var el = this.el;
  51595. el.removeEventListener('buttonchanged', this.onButtonChanged);
  51596. el.removeEventListener('buttondown', this.onButtonDown);
  51597. el.removeEventListener('buttonup', this.onButtonUp);
  51598. el.removeEventListener('touchstart', this.onButtonTouchStart);
  51599. el.removeEventListener('touchend', this.onButtonTouchEnd);
  51600. el.removeEventListener('axismove', this.onAxisMoved);
  51601. el.removeEventListener('model-error', this.onModelError);
  51602. el.removeEventListener('model-loaded', this.onModelLoaded);
  51603. this.controllerEventsActive = false;
  51604. },
  51605. checkIfControllerPresent: function () {
  51606. checkControllerPresentAndSetup(this, GAMEPAD_ID_PREFIX, {
  51607. hand: this.data.hand,
  51608. index: this.data.pair,
  51609. iterateControllerProfiles: true
  51610. });
  51611. },
  51612. play: function () {
  51613. this.checkIfControllerPresent();
  51614. this.addControllersUpdateListener();
  51615. },
  51616. pause: function () {
  51617. this.removeEventListeners();
  51618. this.removeControllersUpdateListener();
  51619. },
  51620. updateControllerModel: function () {
  51621. // If we do not want to load a model, or, have already loaded the model, emit the controllermodelready event.
  51622. if (!this.data.model || this.rayOrigin.createdFromMesh) {
  51623. this.modelReady();
  51624. return;
  51625. }
  51626. var sourceUrl = this.createControllerModelUrl();
  51627. this.loadModel(sourceUrl);
  51628. },
  51629. /**
  51630. * Helper function that constructs a URL from the controller ID suffix, for future proofed
  51631. * art assets.
  51632. */
  51633. createControllerModelUrl: function (forceDefault) {
  51634. // Determine the device specific folder based on the ID suffix
  51635. var trackedControlsComponent = this.el.components['tracked-controls'];
  51636. var controller = trackedControlsComponent ? trackedControlsComponent.controller : null;
  51637. var device = 'default';
  51638. var hand = this.data.hand;
  51639. var filename;
  51640. if (controller && !window.hasNativeWebXRImplementation) {
  51641. // Read hand directly from the controller, rather than this.data, as in the case that the controller
  51642. // is unhanded this.data will still have 'left' or 'right' (depending on what the user inserted in to the scene).
  51643. // In this case, we want to load the universal model, so need to get the '' from the controller.
  51644. hand = controller.hand;
  51645. if (!forceDefault) {
  51646. var match = controller.id.match(GAMEPAD_ID_PATTERN);
  51647. device = ((match && match[0]) || device);
  51648. }
  51649. }
  51650. // Hand
  51651. filename = MODEL_FILENAMES[hand] || MODEL_FILENAMES.default;
  51652. // Final url
  51653. return MODEL_BASE_URL + device + '/' + filename;
  51654. },
  51655. injectTrackedControls: function () {
  51656. var data = this.data;
  51657. this.el.setAttribute('tracked-controls', {
  51658. idPrefix: GAMEPAD_ID_PREFIX,
  51659. controller: data.pair,
  51660. hand: data.hand,
  51661. armModel: false
  51662. });
  51663. this.updateControllerModel();
  51664. },
  51665. addControllersUpdateListener: function () {
  51666. this.el.sceneEl.addEventListener('controllersupdated', this.onControllersUpdate, false);
  51667. },
  51668. removeControllersUpdateListener: function () {
  51669. this.el.sceneEl.removeEventListener('controllersupdated', this.onControllersUpdate, false);
  51670. },
  51671. onControllersUpdate: function () {
  51672. this.checkIfControllerPresent();
  51673. },
  51674. onModelError: function (evt) {
  51675. var defaultUrl = this.createControllerModelUrl(true);
  51676. if (evt.detail.src !== defaultUrl) {
  51677. warn('Failed to load controller model for device, attempting to load default.');
  51678. this.loadModel(defaultUrl);
  51679. } else {
  51680. warn('Failed to load default controller model.');
  51681. }
  51682. },
  51683. loadModel: function (url) {
  51684. // The model is loaded by the gltf-model compoent when this attribute is initially set,
  51685. // removed and re-loaded if the given url changes.
  51686. this.el.setAttribute('gltf-model', 'url(' + url + ')');
  51687. },
  51688. onModelLoaded: function (evt) {
  51689. var rootNode = this.controllerModel = evt.detail.model;
  51690. var loadedMeshInfo = this.loadedMeshInfo;
  51691. var i;
  51692. var meshName;
  51693. var mesh;
  51694. var meshInfo;
  51695. debug('Processing model');
  51696. // Reset the caches
  51697. loadedMeshInfo.buttonMeshes = {};
  51698. loadedMeshInfo.axisMeshes = {};
  51699. // Cache our meshes so we aren't traversing the hierarchy per frame
  51700. if (rootNode) {
  51701. // Button Meshes
  51702. for (i = 0; i < this.mapping.buttons.length; i++) {
  51703. meshName = this.mapping.buttonMeshNames[this.mapping.buttons[i]];
  51704. if (!meshName) {
  51705. debug('Skipping unknown button at index: ' + i + ' with mapped name: ' + this.mapping.buttons[i]);
  51706. continue;
  51707. }
  51708. mesh = rootNode.getObjectByName(meshName);
  51709. if (!mesh) {
  51710. warn('Missing button mesh with name: ' + meshName);
  51711. continue;
  51712. }
  51713. meshInfo = {
  51714. index: i,
  51715. value: getImmediateChildByName(mesh, 'VALUE'),
  51716. pressed: getImmediateChildByName(mesh, 'PRESSED'),
  51717. unpressed: getImmediateChildByName(mesh, 'UNPRESSED')
  51718. };
  51719. if (meshInfo.value && meshInfo.pressed && meshInfo.unpressed) {
  51720. loadedMeshInfo.buttonMeshes[this.mapping.buttons[i]] = meshInfo;
  51721. } else {
  51722. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  51723. warn('Missing button submesh under mesh with name: ' + meshName +
  51724. '(VALUE: ' + !!meshInfo.value +
  51725. ', PRESSED: ' + !!meshInfo.pressed +
  51726. ', UNPRESSED:' + !!meshInfo.unpressed +
  51727. ')');
  51728. }
  51729. }
  51730. // Axis Meshes
  51731. for (i = 0; i < this.mapping.axisMeshNames.length; i++) {
  51732. meshName = this.mapping.axisMeshNames[i];
  51733. if (!meshName) {
  51734. debug('Skipping unknown axis at index: ' + i);
  51735. continue;
  51736. }
  51737. mesh = rootNode.getObjectByName(meshName);
  51738. if (!mesh) {
  51739. warn('Missing axis mesh with name: ' + meshName);
  51740. continue;
  51741. }
  51742. meshInfo = {
  51743. index: i,
  51744. value: getImmediateChildByName(mesh, 'VALUE'),
  51745. min: getImmediateChildByName(mesh, 'MIN'),
  51746. max: getImmediateChildByName(mesh, 'MAX')
  51747. };
  51748. if (meshInfo.value && meshInfo.min && meshInfo.max) {
  51749. loadedMeshInfo.axisMeshes[i] = meshInfo;
  51750. } else {
  51751. // If we didn't find the mesh, it simply means this axis won't have transforms applied as mapped axis values change.
  51752. warn('Missing axis submesh under mesh with name: ' + meshName +
  51753. '(VALUE: ' + !!meshInfo.value +
  51754. ', MIN: ' + !!meshInfo.min +
  51755. ', MAX:' + !!meshInfo.max +
  51756. ')');
  51757. }
  51758. }
  51759. this.calculateRayOriginFromMesh(rootNode);
  51760. // Determine if the model has to be visible or not.
  51761. this.setModelVisibility();
  51762. }
  51763. debug('Model load complete.');
  51764. // Look through only immediate children. This will return null if no mesh exists with the given name.
  51765. function getImmediateChildByName (object3d, value) {
  51766. for (var i = 0, l = object3d.children.length; i < l; i++) {
  51767. var obj = object3d.children[i];
  51768. if (obj && obj['name'] === value) {
  51769. return obj;
  51770. }
  51771. }
  51772. return undefined;
  51773. }
  51774. },
  51775. calculateRayOriginFromMesh: (function () {
  51776. var quaternion = new THREE.Quaternion();
  51777. return function (rootNode) {
  51778. var mesh;
  51779. // Calculate the pointer pose (used for rays), by applying the world transform of th POINTER_POSE node
  51780. // in the glTF (assumes that root node is at world origin)
  51781. this.rayOrigin.origin.set(0, 0, 0);
  51782. this.rayOrigin.direction.set(0, 0, -1);
  51783. this.rayOrigin.createdFromMesh = true;
  51784. // Try to read Pointing pose from the source model
  51785. mesh = rootNode.getObjectByName(this.mapping.pointingPoseMeshName);
  51786. if (mesh) {
  51787. var parent = rootNode.parent;
  51788. // We need to read pose transforms accumulated from the root of the glTF, not the scene.
  51789. if (parent) {
  51790. rootNode.parent = null;
  51791. rootNode.updateMatrixWorld(true);
  51792. rootNode.parent = parent;
  51793. }
  51794. mesh.getWorldPosition(this.rayOrigin.origin);
  51795. mesh.getWorldQuaternion(quaternion);
  51796. this.rayOrigin.direction.applyQuaternion(quaternion);
  51797. // Recalculate the world matrices now that the rootNode is re-attached to the parent.
  51798. if (parent) {
  51799. rootNode.updateMatrixWorld(true);
  51800. }
  51801. } else {
  51802. debug('Mesh does not contain pointing origin data, defaulting to none.');
  51803. }
  51804. // Emit event stating that our pointing ray is now accurate.
  51805. this.modelReady();
  51806. };
  51807. })(),
  51808. lerpAxisTransform: (function () {
  51809. var quaternion = new THREE.Quaternion();
  51810. return function (axis, axisValue) {
  51811. var axisMeshInfo = this.loadedMeshInfo.axisMeshes[axis];
  51812. if (!axisMeshInfo) return;
  51813. var min = axisMeshInfo.min;
  51814. var max = axisMeshInfo.max;
  51815. var target = axisMeshInfo.value;
  51816. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  51817. var lerpValue = axisValue * 0.5 + 0.5;
  51818. target.setRotationFromQuaternion(quaternion.copy(min.quaternion).slerp(max.quaternion, lerpValue));
  51819. target.position.lerpVectors(min.position, max.position, lerpValue);
  51820. };
  51821. })(),
  51822. lerpButtonTransform: (function () {
  51823. var quaternion = new THREE.Quaternion();
  51824. return function (buttonName, buttonValue) {
  51825. var buttonMeshInfo = this.loadedMeshInfo.buttonMeshes[buttonName];
  51826. if (!buttonMeshInfo) return;
  51827. var min = buttonMeshInfo.unpressed;
  51828. var max = buttonMeshInfo.pressed;
  51829. var target = buttonMeshInfo.value;
  51830. target.setRotationFromQuaternion(quaternion.copy(min.quaternion).slerp(max.quaternion, buttonValue));
  51831. target.position.lerpVectors(min.position, max.position, buttonValue);
  51832. };
  51833. })(),
  51834. modelReady: function () {
  51835. this.el.emit('controllermodelready', {
  51836. name: 'windows-motion-controls',
  51837. model: this.data.model,
  51838. rayOrigin: this.rayOrigin
  51839. });
  51840. },
  51841. onButtonChanged: function (evt) {
  51842. var buttonName = this.mapping.buttons[evt.detail.id];
  51843. if (buttonName) {
  51844. // Update the button mesh transform
  51845. if (this.loadedMeshInfo && this.loadedMeshInfo.buttonMeshes) {
  51846. this.lerpButtonTransform(buttonName, evt.detail.state.value);
  51847. }
  51848. // Only emit events for buttons that we know how to map from index to name
  51849. this.el.emit(buttonName + 'changed', evt.detail.state);
  51850. }
  51851. },
  51852. onAxisMoved: function (evt) {
  51853. var numAxes = this.mapping.axisMeshNames.length;
  51854. // Only attempt to update meshes if we have valid data.
  51855. if (this.loadedMeshInfo && this.loadedMeshInfo.axisMeshes) {
  51856. for (var axis = 0; axis < numAxes; axis++) {
  51857. // Update the button mesh transform
  51858. this.lerpAxisTransform(axis, evt.detail.axis[axis] || 0.0);
  51859. }
  51860. }
  51861. emitIfAxesChanged(this, this.mapping.axes, evt);
  51862. },
  51863. setModelVisibility: function (visible) {
  51864. var model = this.el.getObject3D('mesh');
  51865. visible = visible !== undefined ? visible : this.modelVisible;
  51866. this.modelVisible = visible;
  51867. if (!model) { return; }
  51868. model.visible = visible;
  51869. }
  51870. });
  51871. },{"../constants":120,"../core/component":128,"../utils/":202,"../utils/bind":196,"../utils/tracked-controls":210}],120:[function(_dereq_,module,exports){
  51872. module.exports = {
  51873. AFRAME_INJECTED: 'aframe-injected',
  51874. DEFAULT_CAMERA_HEIGHT: 1.6,
  51875. DEFAULT_HANDEDNESS: 'right',
  51876. keyboardevent: _dereq_('./keyboardevent')
  51877. };
  51878. },{"./keyboardevent":121}],121:[function(_dereq_,module,exports){
  51879. module.exports = {
  51880. // Tiny KeyboardEvent.code polyfill.
  51881. KEYCODE_TO_CODE: {
  51882. '38': 'ArrowUp',
  51883. '37': 'ArrowLeft',
  51884. '40': 'ArrowDown',
  51885. '39': 'ArrowRight',
  51886. '87': 'KeyW',
  51887. '65': 'KeyA',
  51888. '83': 'KeyS',
  51889. '68': 'KeyD'
  51890. }
  51891. };
  51892. },{}],122:[function(_dereq_,module,exports){
  51893. var ANode = _dereq_('./a-node');
  51894. var bind = _dereq_('../utils/bind');
  51895. var debug = _dereq_('../utils/debug');
  51896. var registerElement = _dereq_('./a-register-element').registerElement;
  51897. var THREE = _dereq_('../lib/three');
  51898. var fileLoader = new THREE.FileLoader();
  51899. var warn = debug('core:a-assets:warn');
  51900. /**
  51901. * Asset management system. Handles blocking on asset loading.
  51902. */
  51903. module.exports = registerElement('a-assets', {
  51904. prototype: Object.create(ANode.prototype, {
  51905. createdCallback: {
  51906. value: function () {
  51907. this.isAssets = true;
  51908. this.fileLoader = fileLoader;
  51909. this.timeout = null;
  51910. }
  51911. },
  51912. attachedCallback: {
  51913. value: function () {
  51914. var self = this;
  51915. var i;
  51916. var loaded = [];
  51917. var mediaEl;
  51918. var mediaEls;
  51919. var imgEl;
  51920. var imgEls;
  51921. var timeout;
  51922. if (!this.parentNode.isScene) {
  51923. throw new Error('<a-assets> must be a child of a <a-scene>.');
  51924. }
  51925. // Wait for <img>s.
  51926. imgEls = this.querySelectorAll('img');
  51927. for (i = 0; i < imgEls.length; i++) {
  51928. imgEl = fixUpMediaElement(imgEls[i]);
  51929. loaded.push(new Promise(function (resolve, reject) {
  51930. // Set in cache because we won't be needing to call three.js loader if we have.
  51931. // a loaded media element.
  51932. THREE.Cache.files[imgEls[i].getAttribute('src')] = imgEl;
  51933. imgEl.onload = resolve;
  51934. imgEl.onerror = reject;
  51935. }));
  51936. }
  51937. // Wait for <audio>s and <video>s.
  51938. mediaEls = this.querySelectorAll('audio, video');
  51939. for (i = 0; i < mediaEls.length; i++) {
  51940. mediaEl = fixUpMediaElement(mediaEls[i]);
  51941. if (!mediaEl.src && !mediaEl.srcObject) {
  51942. warn('Audio/video asset has neither `src` nor `srcObject` attributes.');
  51943. }
  51944. loaded.push(mediaElementLoaded(mediaEl));
  51945. }
  51946. // Trigger loaded for scene to start rendering.
  51947. Promise.all(loaded).then(bind(this.load, this));
  51948. // Timeout to start loading anyways.
  51949. timeout = parseInt(this.getAttribute('timeout'), 10) || 3000;
  51950. this.timeout = setTimeout(function () {
  51951. if (self.hasLoaded) { return; }
  51952. warn('Asset loading timed out in ', timeout, 'ms');
  51953. self.emit('timeout');
  51954. self.load();
  51955. }, timeout);
  51956. }
  51957. },
  51958. detachedCallback: {
  51959. value: function () {
  51960. if (this.timeout) { clearTimeout(this.timeout); }
  51961. }
  51962. },
  51963. load: {
  51964. value: function () {
  51965. ANode.prototype.load.call(this, null, function waitOnFilter (el) {
  51966. return el.isAssetItem && el.hasAttribute('src');
  51967. });
  51968. }
  51969. }
  51970. })
  51971. });
  51972. /**
  51973. * Preload using XHRLoader for any type of asset.
  51974. */
  51975. registerElement('a-asset-item', {
  51976. prototype: Object.create(ANode.prototype, {
  51977. createdCallback: {
  51978. value: function () {
  51979. this.data = null;
  51980. this.isAssetItem = true;
  51981. }
  51982. },
  51983. attachedCallback: {
  51984. value: function () {
  51985. var self = this;
  51986. var src = this.getAttribute('src');
  51987. fileLoader.setResponseType(
  51988. this.getAttribute('response-type') || inferResponseType(src));
  51989. fileLoader.load(src, function handleOnLoad (response) {
  51990. self.data = response;
  51991. /*
  51992. Workaround for a Chrome bug. If another XHR is sent to the same url before the
  51993. previous one closes, the second request never finishes.
  51994. setTimeout finishes the first request and lets the logic triggered by load open
  51995. subsequent requests.
  51996. setTimeout can be removed once the fix for the bug below ships:
  51997. 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
  51998. */
  51999. setTimeout(function load () { ANode.prototype.load.call(self); });
  52000. }, function handleOnProgress (xhr) {
  52001. self.emit('progress', {
  52002. loadedBytes: xhr.loaded,
  52003. totalBytes: xhr.total,
  52004. xhr: xhr
  52005. });
  52006. }, function handleOnError (xhr) {
  52007. self.emit('error', {xhr: xhr});
  52008. });
  52009. }
  52010. }
  52011. })
  52012. });
  52013. /**
  52014. * Create a Promise that resolves once the media element has finished buffering.
  52015. *
  52016. * @param {Element} el - HTMLMediaElement.
  52017. * @returns {Promise}
  52018. */
  52019. function mediaElementLoaded (el) {
  52020. if (!el.hasAttribute('autoplay') && el.getAttribute('preload') !== 'auto') {
  52021. return;
  52022. }
  52023. // If media specifies autoplay or preload, wait until media is completely buffered.
  52024. return new Promise(function (resolve, reject) {
  52025. if (el.readyState === 4) { return resolve(); } // Already loaded.
  52026. if (el.error) { return reject(); } // Error.
  52027. el.addEventListener('loadeddata', checkProgress, false);
  52028. el.addEventListener('progress', checkProgress, false);
  52029. el.addEventListener('error', reject, false);
  52030. function checkProgress () {
  52031. // Add up the seconds buffered.
  52032. var secondsBuffered = 0;
  52033. for (var i = 0; i < el.buffered.length; i++) {
  52034. secondsBuffered += el.buffered.end(i) - el.buffered.start(i);
  52035. }
  52036. // Compare seconds buffered to media duration.
  52037. if (secondsBuffered >= el.duration) {
  52038. // Set in cache because we won't be needing to call three.js loader if we have.
  52039. // a loaded media element.
  52040. // Store video elements only. three.js loader is used for audio elements.
  52041. // See assetParse too.
  52042. if (el.tagName === 'VIDEO') {
  52043. THREE.Cache.files[el.getAttribute('src')] = el;
  52044. }
  52045. resolve();
  52046. }
  52047. }
  52048. });
  52049. }
  52050. /**
  52051. * Automatically add attributes to media elements where convenient.
  52052. * crossorigin, playsinline.
  52053. */
  52054. function fixUpMediaElement (mediaEl) {
  52055. // Cross-origin.
  52056. var newMediaEl = setCrossOrigin(mediaEl);
  52057. // Plays inline for mobile.
  52058. if (newMediaEl.tagName && newMediaEl.tagName.toLowerCase() === 'video') {
  52059. newMediaEl.setAttribute('playsinline', '');
  52060. newMediaEl.setAttribute('webkit-playsinline', '');
  52061. }
  52062. if (newMediaEl !== mediaEl) {
  52063. mediaEl.parentNode.appendChild(newMediaEl);
  52064. mediaEl.parentNode.removeChild(mediaEl);
  52065. }
  52066. return newMediaEl;
  52067. }
  52068. /**
  52069. * Automatically set `crossorigin` if not defined on the media element.
  52070. * If it is not defined, we must create and re-append a new media element <img> and
  52071. * have the browser re-request it with `crossorigin` set.
  52072. *
  52073. * @param {Element} Media element (e.g., <img>, <audio>, <video>).
  52074. * @returns {Element} Media element to be used to listen to for loaded events.
  52075. */
  52076. function setCrossOrigin (mediaEl) {
  52077. var newMediaEl;
  52078. var src;
  52079. // Already has crossorigin set.
  52080. if (mediaEl.hasAttribute('crossorigin')) { return mediaEl; }
  52081. src = mediaEl.getAttribute('src');
  52082. if (src !== null) {
  52083. // Does not have protocol.
  52084. if (src.indexOf('://') === -1) { return mediaEl; }
  52085. // Determine if cross origin is actually needed.
  52086. if (extractDomain(src) === window.location.host) { return mediaEl; }
  52087. }
  52088. warn('Cross-origin element (e.g., <img>) was requested without `crossorigin` set. ' +
  52089. 'A-Frame will re-request the asset with `crossorigin` attribute set. ' +
  52090. 'Please set `crossorigin` on the element (e.g., <img crossorigin="anonymous">)', src);
  52091. mediaEl.crossOrigin = 'anonymous';
  52092. newMediaEl = mediaEl.cloneNode(true);
  52093. return newMediaEl;
  52094. }
  52095. /**
  52096. * Extract domain out of URL.
  52097. *
  52098. * @param {string} url
  52099. * @returns {string}
  52100. */
  52101. function extractDomain (url) {
  52102. // Find and remove protocol (e.g., http, ftp, etc.) to get domain.
  52103. var domain = url.indexOf('://') > -1 ? url.split('/')[2] : url.split('/')[0];
  52104. // Find and remove port number.
  52105. return domain.substring(0, domain.indexOf(':'));
  52106. }
  52107. /**
  52108. * Infer response-type attribute from src.
  52109. * Default is text (default XMLHttpRequest.responseType)
  52110. * and arraybuffer for .glb files.
  52111. *
  52112. * @param {string} src
  52113. * @returns {string}
  52114. */
  52115. function inferResponseType (src) {
  52116. var fileName = getFileNameFromURL(src);
  52117. var dotLastIndex = fileName.lastIndexOf('.');
  52118. if (dotLastIndex >= 0) {
  52119. var extension = fileName.slice(dotLastIndex, src.search(/\?|#|$/));
  52120. if (extension === '.glb') {
  52121. return 'arraybuffer';
  52122. }
  52123. }
  52124. return 'text';
  52125. }
  52126. module.exports.inferResponseType = inferResponseType;
  52127. /**
  52128. * Extract filename from URL
  52129. *
  52130. * @param {string} url
  52131. * @returns {string}
  52132. */
  52133. function getFileNameFromURL (url) {
  52134. var parser = document.createElement('a');
  52135. parser.href = url;
  52136. var query = parser.search.replace(/^\?/, '');
  52137. var filePath = url.replace(query, '').replace('?', '');
  52138. return filePath.substring(filePath.lastIndexOf('/') + 1);
  52139. }
  52140. module.exports.getFileNameFromURL = getFileNameFromURL;
  52141. },{"../lib/three":176,"../utils/bind":196,"../utils/debug":198,"./a-node":126,"./a-register-element":127}],123:[function(_dereq_,module,exports){
  52142. var debug = _dereq_('../utils/debug');
  52143. var registerElement = _dereq_('./a-register-element').registerElement;
  52144. var warn = debug('core:cubemap:warn');
  52145. /**
  52146. * Cubemap element that handles validation and exposes list of URLs.
  52147. * Does not listen to updates.
  52148. */
  52149. module.exports = registerElement('a-cubemap', {
  52150. prototype: Object.create(window.HTMLElement.prototype, {
  52151. /**
  52152. * Calculates this.srcs.
  52153. */
  52154. attachedCallback: {
  52155. value: function () {
  52156. this.srcs = this.validate();
  52157. },
  52158. writable: window.debug
  52159. },
  52160. /**
  52161. * Checks for exactly six elements with [src].
  52162. * Does not check explicitly for <img>s in case user does not want
  52163. * prefetching.
  52164. *
  52165. * @returns {Array|null} - six URLs if valid, else null.
  52166. */
  52167. validate: {
  52168. value: function () {
  52169. var elements = this.querySelectorAll('[src]');
  52170. var i;
  52171. var srcs = [];
  52172. if (elements.length === 6) {
  52173. for (i = 0; i < elements.length; i++) {
  52174. srcs.push(elements[i].getAttribute('src'));
  52175. }
  52176. return srcs;
  52177. }
  52178. // Else if there are not six elements, throw a warning.
  52179. warn(
  52180. '<a-cubemap> did not contain exactly six elements each with a ' +
  52181. '`src` attribute.');
  52182. },
  52183. writable: window.debug
  52184. }
  52185. })
  52186. });
  52187. },{"../utils/debug":198,"./a-register-element":127}],124:[function(_dereq_,module,exports){
  52188. var ANode = _dereq_('./a-node');
  52189. var COMPONENTS = _dereq_('./component').components;
  52190. var registerElement = _dereq_('./a-register-element').registerElement;
  52191. var THREE = _dereq_('../lib/three');
  52192. var utils = _dereq_('../utils/');
  52193. var AEntity;
  52194. var debug = utils.debug('core:a-entity:debug');
  52195. var warn = utils.debug('core:a-entity:warn');
  52196. var MULTIPLE_COMPONENT_DELIMITER = '__';
  52197. var OBJECT3D_COMPONENTS = ['position', 'rotation', 'scale', 'visible'];
  52198. var ONCE = {once: true};
  52199. /**
  52200. * Entity is a container object that components are plugged into to comprise everything in
  52201. * the scene. In A-Frame, they inherently have position, rotation, and scale.
  52202. *
  52203. * To be able to take components, the scene element inherits from the entity definition.
  52204. *
  52205. * @member {object} components - entity's currently initialized components.
  52206. * @member {object} object3D - three.js object.
  52207. * @member {array} states
  52208. * @member {boolean} isPlaying - false if dynamic behavior of the entity is paused.
  52209. */
  52210. var proto = Object.create(ANode.prototype, {
  52211. createdCallback: {
  52212. value: function () {
  52213. this.components = {};
  52214. // To avoid double initializations and infinite loops.
  52215. this.initializingComponents = {};
  52216. this.componentsToUpdate = {};
  52217. this.isEntity = true;
  52218. this.isPlaying = false;
  52219. this.object3D = new THREE.Group();
  52220. this.object3D.el = this;
  52221. this.object3DMap = {};
  52222. this.parentEl = null;
  52223. this.rotationObj = {};
  52224. this.states = [];
  52225. }
  52226. },
  52227. /**
  52228. * Handle changes coming from the browser DOM inspector.
  52229. */
  52230. attributeChangedCallback: {
  52231. value: function (attr, oldVal, newVal) {
  52232. var component = this.components[attr];
  52233. // If the empty string is passed by the component initialization
  52234. // logic we ignore the component update.
  52235. if (component && component.justInitialized && newVal === '') {
  52236. delete component.justInitialized;
  52237. return;
  52238. }
  52239. // When a component is removed after calling el.removeAttribute('material')
  52240. if (!component && newVal === null) { return; }
  52241. this.setEntityAttribute(attr, oldVal, newVal);
  52242. }
  52243. },
  52244. /**
  52245. * Add to parent, load, play.
  52246. */
  52247. attachedCallback: {
  52248. value: function () {
  52249. var assetsEl; // Asset management system element.
  52250. var sceneEl = this.sceneEl;
  52251. var self = this; // Component.
  52252. this.addToParent();
  52253. // Don't .load() scene on attachedCallback.
  52254. if (this.isScene) { return; }
  52255. // Gracefully not error when outside of <a-scene> (e.g., tests).
  52256. if (!sceneEl) {
  52257. this.load();
  52258. return;
  52259. }
  52260. // Wait for asset management system to finish before loading.
  52261. assetsEl = sceneEl.querySelector('a-assets');
  52262. if (assetsEl && !assetsEl.hasLoaded) {
  52263. assetsEl.addEventListener('loaded', function () { self.load(); });
  52264. return;
  52265. }
  52266. this.load();
  52267. }
  52268. },
  52269. /**
  52270. * Tell parent to remove this element's object3D from its object3D.
  52271. * Do not call on scene element because that will cause a call to document.body.remove().
  52272. */
  52273. detachedCallback: {
  52274. value: function () {
  52275. var componentName;
  52276. if (!this.parentEl) { return; }
  52277. // Remove components.
  52278. for (componentName in this.components) {
  52279. this.removeComponent(componentName, false);
  52280. }
  52281. if (this.isScene) { return; }
  52282. this.removeFromParent();
  52283. ANode.prototype.detachedCallback.call(this);
  52284. // Remove cyclic reference.
  52285. this.object3D.el = null;
  52286. }
  52287. },
  52288. getObject3D: {
  52289. value: function (type) {
  52290. return this.object3DMap[type];
  52291. }
  52292. },
  52293. /**
  52294. * Set a THREE.Object3D into the map.
  52295. *
  52296. * @param {string} type - Developer-set name of the type of object, will be unique per type.
  52297. * @param {object} obj - A THREE.Object3D.
  52298. */
  52299. setObject3D: {
  52300. value: function (type, obj) {
  52301. var oldObj;
  52302. var self = this;
  52303. if (!(obj instanceof THREE.Object3D)) {
  52304. throw new Error(
  52305. '`Entity.setObject3D` was called with an object that was not an instance of ' +
  52306. 'THREE.Object3D.'
  52307. );
  52308. }
  52309. // Remove existing object of the type.
  52310. oldObj = this.getObject3D(type);
  52311. if (oldObj) { this.object3D.remove(oldObj); }
  52312. // Set references to A-Frame entity.
  52313. obj.el = this;
  52314. if (obj.children.length) {
  52315. obj.traverse(function bindEl (child) {
  52316. child.el = self;
  52317. });
  52318. }
  52319. // Add.
  52320. this.object3D.add(obj);
  52321. this.object3DMap[type] = obj;
  52322. this.emit('object3dset', {object: obj, type: type});
  52323. }
  52324. },
  52325. /**
  52326. * Remove object from scene and entity object3D map.
  52327. */
  52328. removeObject3D: {
  52329. value: function (type) {
  52330. var obj = this.getObject3D(type);
  52331. if (!obj) {
  52332. warn('Tried to remove `Object3D` of type:', type, 'which was not defined.');
  52333. return;
  52334. }
  52335. this.object3D.remove(obj);
  52336. delete this.object3DMap[type];
  52337. this.emit('object3dremove', {type: type});
  52338. }
  52339. },
  52340. /**
  52341. * Gets or creates an object3D of a given type.
  52342. *
  52343. * @param {string} type - Type of the object3D.
  52344. * @param {string} Constructor - Constructor to use to create the object3D if needed.
  52345. * @returns {object}
  52346. */
  52347. getOrCreateObject3D: {
  52348. value: function (type, Constructor) {
  52349. var object3D = this.getObject3D(type);
  52350. if (!object3D && Constructor) {
  52351. object3D = new Constructor();
  52352. this.setObject3D(type, object3D);
  52353. }
  52354. warn('`getOrCreateObject3D` has been deprecated. Use `setObject3D()` ' +
  52355. 'and `object3dset` event instead.');
  52356. return object3D;
  52357. }
  52358. },
  52359. /**
  52360. * Add child entity.
  52361. *
  52362. * @param {Element} el - Child entity.
  52363. */
  52364. add: {
  52365. value: function (el) {
  52366. if (!el.object3D) {
  52367. throw new Error("Trying to add an element that doesn't have an `object3D`");
  52368. }
  52369. this.object3D.add(el.object3D);
  52370. this.emit('child-attached', {el: el});
  52371. }
  52372. },
  52373. /**
  52374. * Tell parentNode to add this entity to itself.
  52375. */
  52376. addToParent: {
  52377. value: function () {
  52378. var parentNode = this.parentEl = this.parentNode;
  52379. // `!parentNode` check primarily for unit tests.
  52380. if (!parentNode || !parentNode.add || this.attachedToParent) { return; }
  52381. parentNode.add(this);
  52382. this.attachedToParent = true; // To prevent multiple attachments to same parent.
  52383. }
  52384. },
  52385. /**
  52386. * Tell parentNode to remove this entity from itself.
  52387. */
  52388. removeFromParent: {
  52389. value: function () {
  52390. var parentEl = this.parentEl;
  52391. this.parentEl.remove(this);
  52392. this.attachedToParent = false;
  52393. this.parentEl = null;
  52394. parentEl.emit('child-detached', {el: this});
  52395. }
  52396. },
  52397. load: {
  52398. value: function () {
  52399. var self = this;
  52400. if (this.hasLoaded || !this.parentEl) { return; }
  52401. ANode.prototype.load.call(this, function entityLoadCallback () {
  52402. // Check if entity was detached while it was waiting to load.
  52403. if (!self.parentEl) { return; }
  52404. self.updateComponents();
  52405. if (self.isScene || self.parentEl.isPlaying) { self.play(); }
  52406. });
  52407. },
  52408. writable: window.debug
  52409. },
  52410. /**
  52411. * Remove child entity.
  52412. *
  52413. * @param {Element} el - Child entity.
  52414. */
  52415. remove: {
  52416. value: function (el) {
  52417. if (el) {
  52418. this.object3D.remove(el.object3D);
  52419. } else {
  52420. this.parentNode.removeChild(this);
  52421. }
  52422. }
  52423. },
  52424. /**
  52425. * @returns {array} Direct children that are entities.
  52426. */
  52427. getChildEntities: {
  52428. value: function () {
  52429. var children = this.children;
  52430. var childEntities = [];
  52431. for (var i = 0; i < children.length; i++) {
  52432. var child = children[i];
  52433. if (child instanceof AEntity) {
  52434. childEntities.push(child);
  52435. }
  52436. }
  52437. return childEntities;
  52438. }
  52439. },
  52440. /**
  52441. * Initialize component.
  52442. *
  52443. * @param {string} attrName - Attribute name asociated to the component.
  52444. * @param {object} data - Component data
  52445. * @param {boolean} isDependency - True if the component is a dependency.
  52446. */
  52447. initComponent: {
  52448. value: function (attrName, data, isDependency) {
  52449. var component;
  52450. var componentId;
  52451. var componentInfo;
  52452. var componentName;
  52453. var isComponentDefined;
  52454. componentInfo = utils.split(attrName, MULTIPLE_COMPONENT_DELIMITER);
  52455. componentName = componentInfo[0];
  52456. componentId = componentInfo.length > 2
  52457. ? componentInfo.slice(1).join('__')
  52458. : componentInfo[1];
  52459. // Not a registered component.
  52460. if (!COMPONENTS[componentName]) { return; }
  52461. // Component is not a dependency and is undefined.
  52462. // If a component is a dependency, then it is okay to have no data.
  52463. isComponentDefined = checkComponentDefined(this, attrName) ||
  52464. data !== undefined;
  52465. if (!isComponentDefined && !isDependency) { return; }
  52466. // Component already initialized.
  52467. if (attrName in this.components) { return; }
  52468. // Initialize dependencies first
  52469. this.initComponentDependencies(componentName);
  52470. // If component name has an id we check component type multiplic
  52471. if (componentId && !COMPONENTS[componentName].multiple) {
  52472. throw new Error('Trying to initialize multiple ' +
  52473. 'components of type `' + componentName +
  52474. '`. There can only be one component of this type per entity.');
  52475. }
  52476. component = new COMPONENTS[componentName].Component(this, data, componentId);
  52477. if (this.isPlaying) { component.play(); }
  52478. // Components are reflected in the DOM as attributes but the state is not shown
  52479. // hence we set the attribute to empty string.
  52480. // The flag justInitialized is for attributeChangedCallback to not overwrite
  52481. // the component with the empty string.
  52482. if (!this.hasAttribute(attrName)) {
  52483. component.justInitialized = true;
  52484. window.HTMLElement.prototype.setAttribute.call(this, attrName, '');
  52485. }
  52486. debug('Component initialized: %s', attrName);
  52487. },
  52488. writable: window.debug
  52489. },
  52490. /**
  52491. * Initialize dependencies of a component.
  52492. *
  52493. * @param {string} name - Root component name.
  52494. */
  52495. initComponentDependencies: {
  52496. value: function (name) {
  52497. var self = this;
  52498. var component = COMPONENTS[name];
  52499. var dependencies;
  52500. var i;
  52501. // Not a component.
  52502. if (!component) { return; }
  52503. // No dependencies.
  52504. dependencies = COMPONENTS[name].dependencies;
  52505. if (!dependencies) { return; }
  52506. // Initialize dependencies.
  52507. for (i = 0; i < dependencies.length; i++) {
  52508. // Call getAttribute to initialize the data from the DOM.
  52509. self.initComponent(
  52510. dependencies[i],
  52511. window.HTMLElement.prototype.getAttribute.call(self, dependencies[i]) || undefined,
  52512. true
  52513. );
  52514. }
  52515. }
  52516. },
  52517. removeComponent: {
  52518. value: function (name, destroy) {
  52519. var component;
  52520. component = this.components[name];
  52521. if (!component) { return; }
  52522. // Wait for component to initialize.
  52523. if (!component.initialized) {
  52524. this.addEventListener('componentinitialized', function tryRemoveLater (evt) {
  52525. if (evt.detail.name !== name) { return; }
  52526. this.removeComponent(name, destroy);
  52527. this.removeEventListener('componentinitialized', tryRemoveLater);
  52528. });
  52529. return;
  52530. }
  52531. component.pause();
  52532. component.remove();
  52533. // Keep component attached to entity in case of just full entity detach.
  52534. if (destroy) {
  52535. component.destroy();
  52536. delete this.components[name];
  52537. }
  52538. this.emit('componentremoved', component.evtDetail, false);
  52539. },
  52540. writable: window.debug
  52541. },
  52542. /**
  52543. * Initialize or update all components.
  52544. * Build data using initial components, defined attributes, mixins, and defaults.
  52545. * Update default components before the rest.
  52546. *
  52547. * @member {function} getExtraComponents - Can be implemented to include component data
  52548. * from other sources (e.g., implemented by primitives).
  52549. */
  52550. updateComponents: {
  52551. value: function () {
  52552. var data;
  52553. var extraComponents;
  52554. var i;
  52555. var name;
  52556. var componentsToUpdate = this.componentsToUpdate;
  52557. if (!this.hasLoaded) { return; }
  52558. // Gather mixin-defined components.
  52559. for (i = 0; i < this.mixinEls.length; i++) {
  52560. for (name in this.mixinEls[i].componentCache) {
  52561. if (isComponent(name)) { componentsToUpdate[name] = true; }
  52562. }
  52563. }
  52564. // Gather from extra initial component data if defined (e.g., primitives).
  52565. if (this.getExtraComponents) {
  52566. extraComponents = this.getExtraComponents();
  52567. for (name in extraComponents) {
  52568. if (isComponent(name)) { componentsToUpdate[name] = true; }
  52569. }
  52570. }
  52571. // Gather entity-defined components.
  52572. for (i = 0; i < this.attributes.length; ++i) {
  52573. name = this.attributes[i].name;
  52574. if (OBJECT3D_COMPONENTS.indexOf(name) !== -1) { continue; }
  52575. if (isComponent(name)) { componentsToUpdate[name] = true; }
  52576. }
  52577. // object3D components first (position, rotation, scale, visible).
  52578. for (i = 0; i < OBJECT3D_COMPONENTS.length; i++) {
  52579. name = OBJECT3D_COMPONENTS[i];
  52580. if (!this.hasAttribute(name)) { continue; }
  52581. this.updateComponent(name, this.getDOMAttribute(name));
  52582. }
  52583. // Initialize or update rest of components.
  52584. for (name in componentsToUpdate) {
  52585. data = mergeComponentData(this.getDOMAttribute(name),
  52586. extraComponents && extraComponents[name]);
  52587. this.updateComponent(name, data);
  52588. delete componentsToUpdate[name];
  52589. }
  52590. },
  52591. writable: window.debug
  52592. },
  52593. /**
  52594. * Initialize, update, or remove a single component.
  52595. *
  52596. * When initializing, we set the component on `this.components`.
  52597. *
  52598. * @param {string} attr - Component name.
  52599. * @param {object} attrValue - Value of the DOM attribute.
  52600. * @param {boolean} clobber - If new attrValue completely replaces previous properties.
  52601. */
  52602. updateComponent: {
  52603. value: function (attr, attrValue, clobber) {
  52604. var component = this.components[attr];
  52605. if (component) {
  52606. // Remove component.
  52607. if (attrValue === null && !checkComponentDefined(this, attr)) {
  52608. this.removeComponent(attr, true);
  52609. return;
  52610. }
  52611. // Component already initialized. Update component.
  52612. component.updateProperties(attrValue, clobber);
  52613. return;
  52614. }
  52615. // Component not yet initialized. Initialize component.
  52616. this.initComponent(attr, attrValue, false);
  52617. }
  52618. },
  52619. /**
  52620. * If `attr` is a component name, detach the component from the entity.
  52621. *
  52622. * If `propertyName` is given, reset the component property value to its default.
  52623. *
  52624. * @param {string} attr - Attribute name, which could also be a component name.
  52625. * @param {string} propertyName - Component prop name, if resetting an individual prop.
  52626. */
  52627. removeAttribute: {
  52628. value: function (attr, propertyName) {
  52629. var component = this.components[attr];
  52630. // Remove component.
  52631. if (component && propertyName === undefined) {
  52632. this.removeComponent(attr, true);
  52633. }
  52634. // Reset component property value.
  52635. if (component && propertyName !== undefined) {
  52636. component.resetProperty(propertyName);
  52637. return;
  52638. }
  52639. // Remove mixins.
  52640. if (attr === 'mixin') {
  52641. this.mixinUpdate('');
  52642. }
  52643. window.HTMLElement.prototype.removeAttribute.call(this, attr);
  52644. }
  52645. },
  52646. /**
  52647. * Start dynamic behavior associated with entity such as dynamic components and animations.
  52648. * Tell all children entities to also play.
  52649. */
  52650. play: {
  52651. value: function () {
  52652. var entities;
  52653. var i;
  52654. var key;
  52655. // Already playing.
  52656. if (this.isPlaying || !this.hasLoaded) { return; }
  52657. this.isPlaying = true;
  52658. // Wake up all components.
  52659. for (key in this.components) { this.components[key].play(); }
  52660. // Tell all child entities to play.
  52661. entities = this.getChildEntities();
  52662. for (i = 0; i < entities.length; i++) { entities[i].play(); }
  52663. this.emit('play');
  52664. },
  52665. writable: true
  52666. },
  52667. /**
  52668. * Pause dynamic behavior associated with entity such as dynamic components and animations.
  52669. * Tell all children entities to also pause.
  52670. */
  52671. pause: {
  52672. value: function () {
  52673. var entities;
  52674. var i;
  52675. var key;
  52676. if (!this.isPlaying) { return; }
  52677. this.isPlaying = false;
  52678. // Sleep all components.
  52679. for (key in this.components) { this.components[key].pause(); }
  52680. // Tell all child entities to pause.
  52681. entities = this.getChildEntities();
  52682. for (i = 0; i < entities.length; i++) { entities[i].pause(); }
  52683. this.emit('pause');
  52684. },
  52685. writable: true
  52686. },
  52687. /**
  52688. * Deals with updates on entity-specific attributes (i.e., components and mixins).
  52689. *
  52690. * @param {string} attr
  52691. * @param {string} oldVal
  52692. * @param {string|object} newVal
  52693. */
  52694. setEntityAttribute: {
  52695. value: function (attr, oldVal, newVal) {
  52696. if (COMPONENTS[attr] || this.components[attr]) {
  52697. this.updateComponent(attr, newVal);
  52698. return;
  52699. }
  52700. if (attr === 'mixin') {
  52701. // Ignore if `<a-node>` code is just updating computed mixin in the DOM.
  52702. if (newVal === this.computedMixinStr) { return; }
  52703. this.mixinUpdate(newVal, oldVal);
  52704. }
  52705. }
  52706. },
  52707. /**
  52708. * When mixins updated, trigger init or optimized-update of relevant components.
  52709. */
  52710. mixinUpdate: {
  52711. value: (function () {
  52712. var componentsUpdated = [];
  52713. return function (newMixins, oldMixins) {
  52714. var component;
  52715. var mixinEl;
  52716. var mixinIds;
  52717. var i;
  52718. var self = this;
  52719. if (!this.hasLoaded) {
  52720. this.addEventListener('loaded', function () {
  52721. self.mixinUpdate(newMixins, oldMixins);
  52722. }, ONCE);
  52723. return;
  52724. }
  52725. oldMixins = oldMixins || this.getAttribute('mixin');
  52726. mixinIds = this.updateMixins(newMixins, oldMixins);
  52727. // Loop over current mixins.
  52728. componentsUpdated.length = 0;
  52729. for (i = 0; i < this.mixinEls.length; i++) {
  52730. for (component in this.mixinEls[i].componentCache) {
  52731. if (componentsUpdated.indexOf(component) === -1) {
  52732. if (this.components[component]) {
  52733. // Update. Just rebuild data.
  52734. this.components[component].handleMixinUpdate();
  52735. } else {
  52736. // Init. buildData will gather mixin values.
  52737. this.initComponent(component, null);
  52738. }
  52739. componentsUpdated.push(component);
  52740. }
  52741. }
  52742. }
  52743. // Loop over old mixins to call for data rebuild.
  52744. for (i = 0; i < mixinIds.oldMixinIds.length; i++) {
  52745. mixinEl = document.getElementById(mixinIds.oldMixinIds[i]);
  52746. if (!mixinEl) { continue; }
  52747. for (component in mixinEl.componentCache) {
  52748. if (componentsUpdated.indexOf(component) === -1) {
  52749. if (this.components[component]) {
  52750. if (this.getDOMAttribute(component)) {
  52751. // Update component if explicitly defined.
  52752. this.components[component].handleMixinUpdate();
  52753. } else {
  52754. // Remove component if not explicitly defined.
  52755. this.removeComponent(component, true);
  52756. }
  52757. }
  52758. }
  52759. }
  52760. }
  52761. };
  52762. })()
  52763. },
  52764. /**
  52765. * setAttribute can:
  52766. *
  52767. * 1. Set a single property of a multi-property component.
  52768. * 2. Set multiple properties of a multi-property component.
  52769. * 3. Replace properties of a multi-property component.
  52770. * 4. Set a value for a single-property component, mixin, or normal HTML attribute.
  52771. *
  52772. * @param {string} attrName - Component or attribute name.
  52773. * @param {*} arg1 - Can be a value, property name, CSS-style property string, or
  52774. * object of properties.
  52775. * @param {*|bool} arg2 - If arg1 is a property name, this should be a value. Otherwise,
  52776. * it is a boolean indicating whether to clobber previous values (defaults to false).
  52777. */
  52778. setAttribute: {
  52779. value: (function () {
  52780. var singlePropUpdate = {};
  52781. return function (attrName, arg1, arg2) {
  52782. var newAttrValue;
  52783. var clobber;
  52784. var componentName;
  52785. var delimiterIndex;
  52786. var isDebugMode;
  52787. var key;
  52788. delimiterIndex = attrName.indexOf(MULTIPLE_COMPONENT_DELIMITER);
  52789. componentName = delimiterIndex > 0 ? attrName.substring(0, delimiterIndex) : attrName;
  52790. // Not a component. Normal set attribute.
  52791. if (!COMPONENTS[componentName]) {
  52792. if (attrName === 'mixin') { this.mixinUpdate(arg1); }
  52793. ANode.prototype.setAttribute.call(this, attrName, arg1);
  52794. return;
  52795. }
  52796. // Initialize component first if not yet initialized.
  52797. if (!this.components[attrName] && this.hasAttribute(attrName)) {
  52798. this.updateComponent(
  52799. attrName,
  52800. window.HTMLElement.prototype.getAttribute.call(this, attrName));
  52801. }
  52802. // Determine new attributes from the arguments
  52803. if (typeof arg2 !== 'undefined' &&
  52804. typeof arg1 === 'string' &&
  52805. arg1.length > 0 &&
  52806. typeof utils.styleParser.parse(arg1) === 'string') {
  52807. // Update a single property of a multi-property component
  52808. for (key in singlePropUpdate) { delete singlePropUpdate[key]; }
  52809. newAttrValue = singlePropUpdate;
  52810. newAttrValue[arg1] = arg2;
  52811. clobber = false;
  52812. } else {
  52813. // Update with a value, object, or CSS-style property string, with the possiblity
  52814. // of clobbering previous values.
  52815. newAttrValue = arg1;
  52816. clobber = (arg2 === true);
  52817. }
  52818. // Update component
  52819. this.updateComponent(attrName, newAttrValue, clobber);
  52820. // In debug mode, write component data up to the DOM.
  52821. isDebugMode = this.sceneEl && this.sceneEl.getAttribute('debug');
  52822. if (isDebugMode) { this.components[attrName].flushToDOM(); }
  52823. };
  52824. })(),
  52825. writable: window.debug
  52826. },
  52827. /**
  52828. * Reflect component data in the DOM (as seen from the browser DOM Inspector).
  52829. *
  52830. * @param {bool} recursive - Also flushToDOM on the children.
  52831. **/
  52832. flushToDOM: {
  52833. value: function (recursive) {
  52834. var components = this.components;
  52835. var child;
  52836. var children = this.children;
  52837. var i;
  52838. var key;
  52839. // Flush entity's components to DOM.
  52840. for (key in components) {
  52841. components[key].flushToDOM();
  52842. }
  52843. // Recurse.
  52844. if (!recursive) { return; }
  52845. for (i = 0; i < children.length; ++i) {
  52846. child = children[i];
  52847. if (!child.flushToDOM) { continue; }
  52848. child.flushToDOM(recursive);
  52849. }
  52850. }
  52851. },
  52852. /**
  52853. * If `attr` is a component, returns ALL component data including applied mixins and
  52854. * defaults.
  52855. *
  52856. * If `attr` is not a component, fall back to HTML getAttribute.
  52857. *
  52858. * @param {string} attr
  52859. * @returns {object|string} Object if component, else string.
  52860. */
  52861. getAttribute: {
  52862. value: function (attr) {
  52863. // If component, return component data.
  52864. var component;
  52865. if (attr === 'position') { return this.object3D.position; }
  52866. if (attr === 'rotation') { return getRotation(this); }
  52867. if (attr === 'scale') { return this.object3D.scale; }
  52868. if (attr === 'visible') { return this.object3D.visible; }
  52869. component = this.components[attr];
  52870. if (component) { return component.data; }
  52871. return window.HTMLElement.prototype.getAttribute.call(this, attr);
  52872. },
  52873. writable: window.debug
  52874. },
  52875. /**
  52876. * If `attr` is a component, returns JUST the component data defined on the entity.
  52877. * Like a partial version of `getComputedAttribute` as returned component data
  52878. * does not include applied mixins or defaults.
  52879. *
  52880. * If `attr` is not a component, fall back to HTML getAttribute.
  52881. *
  52882. * @param {string} attr
  52883. * @returns {object|string} Object if component, else string.
  52884. */
  52885. getDOMAttribute: {
  52886. value: function (attr) {
  52887. // If cached value exists, return partial component data.
  52888. var component = this.components[attr];
  52889. if (component) { return component.attrValue; }
  52890. return window.HTMLElement.prototype.getAttribute.call(this, attr);
  52891. },
  52892. writable: window.debug
  52893. },
  52894. addState: {
  52895. value: function (state) {
  52896. if (this.is(state)) { return; }
  52897. this.states.push(state);
  52898. this.emit('stateadded', state);
  52899. }
  52900. },
  52901. removeState: {
  52902. value: function (state) {
  52903. var stateIndex = this.states.indexOf(state);
  52904. if (stateIndex === -1) { return; }
  52905. this.states.splice(stateIndex, 1);
  52906. this.emit('stateremoved', state);
  52907. }
  52908. },
  52909. /**
  52910. * Checks if the element is in a given state. e.g. el.is('alive');
  52911. * @type {string} state - Name of the state we want to check
  52912. */
  52913. is: {
  52914. value: function (state) {
  52915. return this.states.indexOf(state) !== -1;
  52916. }
  52917. },
  52918. /**
  52919. * Open Inspector to this entity.
  52920. */
  52921. inspect: {
  52922. value: function () {
  52923. this.sceneEl.components.inspector.openInspector(this);
  52924. }
  52925. },
  52926. /**
  52927. * Clean up memory and return memory to object pools.
  52928. */
  52929. destroy: {
  52930. value: function () {
  52931. var key;
  52932. if (this.parentNode) {
  52933. warn('Entity can only be destroyed if detached from scenegraph.');
  52934. return;
  52935. }
  52936. for (key in this.components) {
  52937. this.components[key].destroy();
  52938. }
  52939. }
  52940. }
  52941. });
  52942. /**
  52943. * Check if a component is *defined* for an entity, including defaults and mixins.
  52944. * Does not check whether the component has been *initialized* for an entity.
  52945. *
  52946. * @param {string} el - Entity.
  52947. * @param {string} name - Component name.
  52948. * @returns {boolean}
  52949. */
  52950. function checkComponentDefined (el, name) {
  52951. // Check if element contains the component.
  52952. if (el.components[name] && el.components[name].attrValue) { return true; }
  52953. return isComponentMixedIn(name, el.mixinEls);
  52954. }
  52955. /**
  52956. * Check if any mixins contains a component.
  52957. *
  52958. * @param {string} name - Component name.
  52959. * @param {array} mixinEls - Array of <a-mixin>s.
  52960. */
  52961. function isComponentMixedIn (name, mixinEls) {
  52962. var i;
  52963. var inMixin = false;
  52964. for (i = 0; i < mixinEls.length; ++i) {
  52965. inMixin = mixinEls[i].hasAttribute(name);
  52966. if (inMixin) { break; }
  52967. }
  52968. return inMixin;
  52969. }
  52970. /**
  52971. * Given entity defined value, merge in extra data if necessary.
  52972. * Handle both single and multi-property components.
  52973. *
  52974. * @param {string} attrValue - Entity data.
  52975. * @param extraData - Entity data from another source to merge in.
  52976. */
  52977. function mergeComponentData (attrValue, extraData) {
  52978. // Extra data not defined, just return attrValue.
  52979. if (!extraData) { return attrValue; }
  52980. // Merge multi-property data.
  52981. if (extraData.constructor === Object) {
  52982. return utils.extend(extraData, utils.styleParser.parse(attrValue || {}));
  52983. }
  52984. // Return data, precendence to the defined value.
  52985. return attrValue || extraData;
  52986. }
  52987. function isComponent (componentName) {
  52988. if (componentName.indexOf(MULTIPLE_COMPONENT_DELIMITER) !== -1) {
  52989. componentName = utils.split(componentName, MULTIPLE_COMPONENT_DELIMITER)[0];
  52990. }
  52991. if (!COMPONENTS[componentName]) { return false; }
  52992. return true;
  52993. }
  52994. function getRotation (entityEl) {
  52995. var radToDeg = THREE.Math.radToDeg;
  52996. var rotation = entityEl.object3D.rotation;
  52997. var rotationObj = entityEl.rotationObj;
  52998. rotationObj.x = radToDeg(rotation.x);
  52999. rotationObj.y = radToDeg(rotation.y);
  53000. rotationObj.z = radToDeg(rotation.z);
  53001. return rotationObj;
  53002. }
  53003. AEntity = registerElement('a-entity', {prototype: proto});
  53004. module.exports = AEntity;
  53005. },{"../lib/three":176,"../utils/":202,"./a-node":126,"./a-register-element":127,"./component":128}],125:[function(_dereq_,module,exports){
  53006. var ANode = _dereq_('./a-node');
  53007. var registerElement = _dereq_('./a-register-element').registerElement;
  53008. var components = _dereq_('./component').components;
  53009. var utils = _dereq_('../utils');
  53010. var MULTIPLE_COMPONENT_DELIMITER = '__';
  53011. /**
  53012. * @member {object} componentCache - Cache of pre-parsed values. An object where the keys
  53013. * are component names and the values are already parsed by the component.
  53014. */
  53015. module.exports = registerElement('a-mixin', {
  53016. prototype: Object.create(ANode.prototype, {
  53017. createdCallback: {
  53018. value: function () {
  53019. this.componentCache = {};
  53020. this.id = this.getAttribute('id');
  53021. this.isMixin = true;
  53022. }
  53023. },
  53024. attributeChangedCallback: {
  53025. value: function (attr, oldVal, newVal) {
  53026. this.cacheAttribute(attr, newVal);
  53027. this.updateEntities();
  53028. }
  53029. },
  53030. attachedCallback: {
  53031. value: function () {
  53032. this.sceneEl = this.closestScene();
  53033. this.cacheAttributes();
  53034. this.updateEntities();
  53035. this.load();
  53036. }
  53037. },
  53038. /**
  53039. * setAttribute that parses and caches component values.
  53040. */
  53041. setAttribute: {
  53042. value: function (attr, value) {
  53043. window.HTMLElement.prototype.setAttribute.call(this, attr, value);
  53044. this.cacheAttribute(attr, value);
  53045. }
  53046. },
  53047. /**
  53048. * If `attr` is a component, then parse the value using the schema and store it.
  53049. */
  53050. cacheAttribute: {
  53051. value: function (attr, value) {
  53052. var component;
  53053. var componentName;
  53054. // Get component data.
  53055. componentName = utils.split(attr, MULTIPLE_COMPONENT_DELIMITER)[0];
  53056. component = components[componentName];
  53057. if (!component) { return; }
  53058. if (value === undefined) {
  53059. value = window.HTMLElement.prototype.getAttribute.call(this, attr);
  53060. }
  53061. this.componentCache[attr] = component.parseAttrValueForCache(value);
  53062. }
  53063. },
  53064. /**
  53065. * If `attr` is a component, then grab pre-parsed value from the cache.
  53066. * Else do a normal getAttribute.
  53067. */
  53068. getAttribute: {
  53069. value: function (attr) {
  53070. return this.componentCache[attr] ||
  53071. window.HTMLElement.prototype.getAttribute.call(this, attr);
  53072. }
  53073. },
  53074. /**
  53075. * Parse and cache every component defined on the mixin.
  53076. */
  53077. cacheAttributes: {
  53078. value: function () {
  53079. var attributes = this.attributes;
  53080. var attrName;
  53081. var i;
  53082. for (i = 0; i < attributes.length; i++) {
  53083. attrName = attributes[i].name;
  53084. this.cacheAttribute(attrName);
  53085. }
  53086. }
  53087. },
  53088. /**
  53089. * For entities that already have been loaded by the time the mixin was attached, tell
  53090. * those entities to register the mixin and refresh their component data.
  53091. */
  53092. updateEntities: {
  53093. value: function () {
  53094. var entity;
  53095. var entities;
  53096. var i;
  53097. if (!this.sceneEl) { return; }
  53098. entities = this.sceneEl.querySelectorAll('[mixin~=' + this.id + ']');
  53099. for (i = 0; i < entities.length; i++) {
  53100. entity = entities[i];
  53101. if (!entity.hasLoaded || entity.isMixin) { continue; }
  53102. entity.mixinUpdate(this.id);
  53103. }
  53104. }
  53105. }
  53106. })
  53107. });
  53108. },{"../utils":202,"./a-node":126,"./a-register-element":127,"./component":128}],126:[function(_dereq_,module,exports){
  53109. /* global CustomEvent */
  53110. var registerElement = _dereq_('./a-register-element').registerElement;
  53111. var isNode = _dereq_('./a-register-element').isNode;
  53112. var utils = _dereq_('../utils/');
  53113. var warn = utils.debug('core:a-node:warn');
  53114. var error = utils.debug('core:a-node:error');
  53115. /**
  53116. * Base class for A-Frame that manages loading of objects.
  53117. *
  53118. * Nodes can be modified using mixins.
  53119. * Nodes emit a `loaded` event when they and their children have initialized.
  53120. */
  53121. module.exports = registerElement('a-node', {
  53122. prototype: Object.create(window.HTMLElement.prototype, {
  53123. createdCallback: {
  53124. value: function () {
  53125. this.computedMixinStr = '';
  53126. this.hasLoaded = false;
  53127. this.isNode = true;
  53128. this.mixinEls = [];
  53129. },
  53130. writable: window.debug
  53131. },
  53132. attachedCallback: {
  53133. value: function () {
  53134. var mixins;
  53135. this.sceneEl = this.closestScene();
  53136. if (!this.sceneEl) {
  53137. warn('You are attempting to attach <' + this.tagName + '> outside of an A-Frame ' +
  53138. 'scene. Append this element to `<a-scene>` instead.');
  53139. }
  53140. this.hasLoaded = false;
  53141. this.emit('nodeready', undefined, false);
  53142. if (!this.isMixin) {
  53143. mixins = this.getAttribute('mixin');
  53144. if (mixins) { this.updateMixins(mixins); }
  53145. }
  53146. },
  53147. writable: window.debug
  53148. },
  53149. /**
  53150. * Handle mixin.
  53151. */
  53152. attributeChangedCallback: {
  53153. value: function (attr, oldVal, newVal) {
  53154. // Ignore if `<a-node>` code is just updating computed mixin in the DOM.
  53155. if (newVal === this.computedMixinStr) { return; }
  53156. if (attr === 'mixin' && !this.isMixin) {
  53157. this.updateMixins(newVal, oldVal);
  53158. }
  53159. }
  53160. },
  53161. /**
  53162. * Returns the first scene by traversing up the tree starting from and
  53163. * including receiver element.
  53164. */
  53165. closestScene: {
  53166. value: function closest () {
  53167. var element = this;
  53168. while (element) {
  53169. if (element.isScene) { break; }
  53170. element = element.parentElement;
  53171. }
  53172. return element;
  53173. }
  53174. },
  53175. /**
  53176. * Returns first element matching a selector by traversing up the tree starting
  53177. * from and including receiver element.
  53178. *
  53179. * @param {string} selector - Selector of element to find.
  53180. */
  53181. closest: {
  53182. value: function closest (selector) {
  53183. var matches = this.matches || this.mozMatchesSelector ||
  53184. this.msMatchesSelector || this.oMatchesSelector || this.webkitMatchesSelector;
  53185. var element = this;
  53186. while (element) {
  53187. if (matches.call(element, selector)) { break; }
  53188. element = element.parentElement;
  53189. }
  53190. return element;
  53191. }
  53192. },
  53193. detachedCallback: {
  53194. value: function () {
  53195. this.hasLoaded = false;
  53196. }
  53197. },
  53198. /**
  53199. * Wait for children to load, if any.
  53200. * Then emit `loaded` event and set `hasLoaded`.
  53201. */
  53202. load: {
  53203. value: function (cb, childFilter) {
  53204. var children;
  53205. var childrenLoaded;
  53206. var self = this;
  53207. if (this.hasLoaded) { return; }
  53208. // Default to waiting for all nodes.
  53209. childFilter = childFilter || isNode;
  53210. // Wait for children to load (if any), then load.
  53211. children = this.getChildren();
  53212. childrenLoaded = children.filter(childFilter).map(function (child) {
  53213. return new Promise(function waitForLoaded (resolve) {
  53214. if (child.hasLoaded) { return resolve(); }
  53215. child.addEventListener('loaded', resolve);
  53216. });
  53217. });
  53218. Promise.all(childrenLoaded).then(function emitLoaded () {
  53219. self.hasLoaded = true;
  53220. if (cb) { cb(); }
  53221. self.emit('loaded', undefined, false);
  53222. }).catch(function (err) {
  53223. error('Failure loading node: ', err);
  53224. });
  53225. },
  53226. writable: true
  53227. },
  53228. getChildren: {
  53229. value: function () {
  53230. return Array.prototype.slice.call(this.children, 0);
  53231. }
  53232. },
  53233. /**
  53234. * Unregister old mixins and listeners.
  53235. * Register new mixins and listeners.
  53236. * Registering means to update `this.mixinEls` with listeners.
  53237. */
  53238. updateMixins: {
  53239. value: (function () {
  53240. var newMixinIdArray = [];
  53241. var oldMixinIdArray = [];
  53242. var mixinIds = {};
  53243. return function (newMixins, oldMixins) {
  53244. var i;
  53245. var newMixinIds;
  53246. var oldMixinIds;
  53247. newMixinIdArray.length = 0;
  53248. oldMixinIdArray.length = 0;
  53249. newMixinIds = newMixins ? utils.split(newMixins.trim(), /\s+/) : newMixinIdArray;
  53250. oldMixinIds = oldMixins ? utils.split(oldMixins.trim(), /\s+/) : oldMixinIdArray;
  53251. mixinIds.newMixinIds = newMixinIds;
  53252. mixinIds.oldMixinIds = oldMixinIds;
  53253. // Unregister old mixins.
  53254. for (i = 0; i < oldMixinIds.length; i++) {
  53255. if (newMixinIds.indexOf(oldMixinIds[i]) === -1) {
  53256. this.unregisterMixin(oldMixinIds[i]);
  53257. }
  53258. }
  53259. // Register new mixins.
  53260. this.computedMixinStr = '';
  53261. this.mixinEls.length = 0;
  53262. for (i = 0; i < newMixinIds.length; i++) {
  53263. this.registerMixin(document.getElementById(newMixinIds[i]));
  53264. }
  53265. // Update DOM. Keep track of `computedMixinStr` to not recurse back here after
  53266. // update.
  53267. if (this.computedMixinStr) {
  53268. this.computedMixinStr = this.computedMixinStr.trim();
  53269. window.HTMLElement.prototype.setAttribute.call(this, 'mixin',
  53270. this.computedMixinStr);
  53271. }
  53272. return mixinIds;
  53273. };
  53274. })()
  53275. },
  53276. /**
  53277. * From mixin ID, add mixin element to `mixinEls`.
  53278. *
  53279. * @param {Element} mixinEl
  53280. */
  53281. registerMixin: {
  53282. value: function (mixinEl) {
  53283. var compositedMixinIds;
  53284. var i;
  53285. var mixin;
  53286. if (!mixinEl) { return; }
  53287. // Register composited mixins (if mixin has mixins).
  53288. mixin = mixinEl.getAttribute('mixin');
  53289. if (mixin) {
  53290. compositedMixinIds = utils.split(mixin.trim(), /\s+/);
  53291. for (i = 0; i < compositedMixinIds.length; i++) {
  53292. this.registerMixin(document.getElementById(compositedMixinIds[i]));
  53293. }
  53294. }
  53295. // Register mixin.
  53296. this.computedMixinStr = this.computedMixinStr + ' ' + mixinEl.id;
  53297. this.mixinEls.push(mixinEl);
  53298. }
  53299. },
  53300. setAttribute: {
  53301. value: function (attr, newValue) {
  53302. if (attr === 'mixin') { this.updateMixins(newValue); }
  53303. window.HTMLElement.prototype.setAttribute.call(this, attr, newValue);
  53304. }
  53305. },
  53306. unregisterMixin: {
  53307. value: function (mixinId) {
  53308. var i;
  53309. var mixinEls = this.mixinEls;
  53310. var mixinEl;
  53311. for (i = 0; i < mixinEls.length; ++i) {
  53312. mixinEl = mixinEls[i];
  53313. if (mixinId === mixinEl.id) {
  53314. mixinEls.splice(i, 1);
  53315. break;
  53316. }
  53317. }
  53318. }
  53319. },
  53320. /**
  53321. * Emit a DOM event.
  53322. *
  53323. * @param {string} name - Name of event.
  53324. * @param {object} [detail={}] - Custom data to pass as `detail` to the event.
  53325. * @param {boolean} [bubbles=true] - Whether the event should bubble.
  53326. * @param {object} [extraData] - Extra data to pass to the event, if any.
  53327. */
  53328. emit: {
  53329. value: (function () {
  53330. var data = {};
  53331. return function (name, detail, bubbles, extraData) {
  53332. if (bubbles === undefined) { bubbles = true; }
  53333. data.bubbles = !!bubbles;
  53334. data.detail = detail;
  53335. // If extra data is present, we need to create a new object.
  53336. if (extraData) { data = utils.extend({}, extraData, data); }
  53337. this.dispatchEvent(new CustomEvent(name, data));
  53338. };
  53339. })(),
  53340. writable: window.debug
  53341. }
  53342. })
  53343. });
  53344. },{"../utils/":202,"./a-register-element":127}],127:[function(_dereq_,module,exports){
  53345. /*
  53346. ------------------------------------------------------------
  53347. ------------- WARNING WARNING WARNING WARNING --------------
  53348. ------------------------------------------------------------
  53349. This module wraps registerElement to deal with components that inherit from
  53350. `ANode` and `AEntity`. It's a pass through in any other case.
  53351. It wraps some of the prototype methods of the created element to make sure
  53352. that the corresponding functions in the base prototypes (`AEntity` and `ANode`)
  53353. are also invoked. The method in the base prototype is always called before the one
  53354. in the derived prototype.
  53355. */
  53356. // Polyfill `document.registerElement`.
  53357. _dereq_('document-register-element');
  53358. var ANode; // Must declare before AEntity. Initialized at the bottom.
  53359. var AEntity;
  53360. var knownTags = module.exports.knownTags = {};
  53361. function addTagName (tagName) {
  53362. knownTags[tagName.toLowerCase()] = true;
  53363. }
  53364. /**
  53365. * Return whether the element type is one of our known registered ones.
  53366. *
  53367. * @param {string} node - The name of the tag to register.
  53368. * @returns {boolean} Whether the tag name matches that of our registered custom elements.
  53369. */
  53370. module.exports.isNode = function (node) {
  53371. return node.tagName.toLowerCase() in knownTags || node.isNode;
  53372. };
  53373. /**
  53374. * @param {string} tagName - The name of the tag to register.
  53375. * @param {object} obj - The prototype of the new element.
  53376. * @returns {object} The prototype of the new element.
  53377. */
  53378. module.exports.registerElement = function (tagName, obj) {
  53379. var proto = Object.getPrototypeOf(obj.prototype);
  53380. var newObj = obj;
  53381. var isANode = ANode && proto === ANode.prototype;
  53382. var isAEntity = AEntity && proto === AEntity.prototype;
  53383. if (isANode || isAEntity) { addTagName(tagName); }
  53384. // Wrap if element inherits from `ANode`.
  53385. if (isANode) {
  53386. newObj = wrapANodeMethods(obj.prototype);
  53387. newObj = {prototype: Object.create(proto, newObj)};
  53388. }
  53389. // Wrap if element inherits from `AEntity`.
  53390. if (isAEntity) {
  53391. newObj = wrapAEntityMethods(obj.prototype);
  53392. newObj = {prototype: Object.create(proto, newObj)};
  53393. }
  53394. // Give all functions their proper name.
  53395. Object.getOwnPropertyNames(newObj.prototype).forEach(function (propName) {
  53396. var propVal = newObj.prototype[propName];
  53397. if (typeof propVal === 'function') {
  53398. propVal.displayName = propName;
  53399. }
  53400. });
  53401. return document.registerElement(tagName, newObj);
  53402. };
  53403. /**
  53404. * Wrap some obj methods to call those on `ANode` base prototype.
  53405. *
  53406. * @param {object} obj - Object that contains the methods that will be wrapped.
  53407. * @return {object} An object with the same properties as the input parameter but
  53408. * with some of methods wrapped.
  53409. */
  53410. function wrapANodeMethods (obj) {
  53411. var newObj = {};
  53412. var ANodeMethods = [
  53413. 'attachedCallback',
  53414. 'attributeChangedCallback',
  53415. 'createdCallback',
  53416. 'detachedCallback'
  53417. ];
  53418. wrapMethods(newObj, ANodeMethods, obj, ANode.prototype);
  53419. copyProperties(obj, newObj);
  53420. return newObj;
  53421. }
  53422. /**
  53423. * This wraps some of the obj methods to call those on `AEntity` base prototype.
  53424. *
  53425. * @param {object} obj - The objects that contains the methods that will be wrapped.
  53426. * @return {object} - An object with the same properties as the input parameter but
  53427. * with some of methods wrapped.
  53428. */
  53429. function wrapAEntityMethods (obj) {
  53430. var newObj = {};
  53431. var ANodeMethods = [
  53432. 'attachedCallback',
  53433. 'attributeChangedCallback',
  53434. 'createdCallback',
  53435. 'detachedCallback'
  53436. ];
  53437. var AEntityMethods = [
  53438. 'attachedCallback',
  53439. 'attributeChangedCallback',
  53440. 'createdCallback',
  53441. 'detachedCallback'
  53442. ];
  53443. wrapMethods(newObj, ANodeMethods, obj, ANode.prototype);
  53444. wrapMethods(newObj, AEntityMethods, obj, AEntity.prototype);
  53445. // Copies the remaining properties into the new object.
  53446. copyProperties(obj, newObj);
  53447. return newObj;
  53448. }
  53449. /**
  53450. * Wrap a list a methods to ensure that those in the base prototype are called
  53451. * before the derived one.
  53452. *
  53453. * @param {object} targetObj - Object that will contain the wrapped methods.
  53454. * @param {array} methodList - List of methods from the derivedObj that will be wrapped.
  53455. * @param {object} derivedObject - Object that inherits from the baseObj.
  53456. * @param {object} baseObj - Object that derivedObj inherits from.
  53457. */
  53458. function wrapMethods (targetObj, methodList, derivedObj, baseObj) {
  53459. methodList.forEach(function (methodName) {
  53460. wrapMethod(targetObj, methodName, derivedObj, baseObj);
  53461. });
  53462. }
  53463. module.exports.wrapMethods = wrapMethods;
  53464. /**
  53465. * Wrap one method to ensure that the one in the base prototype is called before
  53466. * the one in the derived one.
  53467. *
  53468. * @param {object} obj - Object that will contain the wrapped method.
  53469. * @param {string} methodName - The name of the method that will be wrapped.
  53470. * @param {object} derivedObject - Object that inherits from the baseObj.
  53471. * @param {object} baseObj - Object that derivedObj inherits from.
  53472. */
  53473. function wrapMethod (obj, methodName, derivedObj, baseObj) {
  53474. var derivedMethod = derivedObj[methodName];
  53475. var baseMethod = baseObj[methodName];
  53476. // Derived prototype does not define method, no need to wrap.
  53477. if (!derivedMethod || !baseMethod) { return; }
  53478. // Derived prototype doesn't override the one in the base one, no need to wrap.
  53479. if (derivedMethod === baseMethod) { return; }
  53480. // Wrap to ensure the base method is called before the one in the derived prototype.
  53481. obj[methodName] = {
  53482. value: function wrappedMethod () {
  53483. baseMethod.apply(this, arguments);
  53484. return derivedMethod.apply(this, arguments);
  53485. },
  53486. writable: window.debug
  53487. };
  53488. }
  53489. /**
  53490. * It copies the properties from source to destination object if they don't
  53491. * exist already.
  53492. *
  53493. * @param {object} source - The object where properties are copied from.
  53494. * @param {type} destination - The object where properties are copied to.
  53495. */
  53496. function copyProperties (source, destination) {
  53497. var props = Object.getOwnPropertyNames(source);
  53498. props.forEach(function (prop) {
  53499. var desc;
  53500. if (!destination[prop]) {
  53501. desc = Object.getOwnPropertyDescriptor(source, prop);
  53502. destination[prop] = {value: source[prop], writable: desc.writable};
  53503. }
  53504. });
  53505. }
  53506. ANode = _dereq_('./a-node');
  53507. AEntity = _dereq_('./a-entity');
  53508. },{"./a-entity":124,"./a-node":126,"document-register-element":12}],128:[function(_dereq_,module,exports){
  53509. /* global Node */
  53510. var schema = _dereq_('./schema');
  53511. var scenes = _dereq_('./scene/scenes');
  53512. var systems = _dereq_('./system');
  53513. var utils = _dereq_('../utils/');
  53514. var components = module.exports.components = {}; // Keep track of registered components.
  53515. var parseProperties = schema.parseProperties;
  53516. var parseProperty = schema.parseProperty;
  53517. var processSchema = schema.process;
  53518. var isSingleProp = schema.isSingleProperty;
  53519. var stringifyProperties = schema.stringifyProperties;
  53520. var stringifyProperty = schema.stringifyProperty;
  53521. var styleParser = utils.styleParser;
  53522. var warn = utils.debug('core:component:warn');
  53523. var aframeScript = document.currentScript;
  53524. var upperCaseRegExp = new RegExp('[A-Z]+');
  53525. // Object pools by component, created upon registration.
  53526. var objectPools = {};
  53527. /**
  53528. * Component class definition.
  53529. *
  53530. * Components configure appearance, modify behavior, or add functionality to
  53531. * entities. The behavior and appearance of an entity can be changed at runtime
  53532. * by adding, removing, or updating components. Entities do not share instances
  53533. * of components.
  53534. *
  53535. * @member {object} el - Reference to the entity element.
  53536. * @member {string} attrValue - Value of the corresponding HTML attribute.
  53537. * @member {object} data - Component data populated by parsing the
  53538. * mapped attribute of the component plus applying defaults and mixins.
  53539. */
  53540. var Component = module.exports.Component = function (el, attrValue, id) {
  53541. var self = this;
  53542. this.el = el;
  53543. this.id = id;
  53544. this.attrName = this.name + (id ? '__' + id : '');
  53545. this.evtDetail = {id: this.id, name: this.name};
  53546. this.initialized = false;
  53547. this.isSingleProperty = isSingleProp(this.schema);
  53548. this.isSinglePropertyObject = this.isSingleProperty &&
  53549. isObject(parseProperty(undefined, this.schema)) &&
  53550. !(this.schema.default instanceof window.HTMLElement);
  53551. this.isObjectBased = !this.isSingleProperty || this.isSinglePropertyObject;
  53552. this.el.components[this.attrName] = this;
  53553. this.objectPool = objectPools[this.name];
  53554. const events = this.events;
  53555. this.events = {};
  53556. eventsBind(this, events);
  53557. // Store component data from previous update call.
  53558. this.attrValue = undefined;
  53559. if (this.isObjectBased) {
  53560. this.nextData = this.objectPool.use();
  53561. // Drop any properties added by dynamic schemas in previous use
  53562. utils.objectPool.removeUnusedKeys(this.nextData, this.schema);
  53563. this.oldData = this.objectPool.use();
  53564. utils.objectPool.removeUnusedKeys(this.oldData, this.schema);
  53565. this.previousOldData = this.objectPool.use();
  53566. utils.objectPool.removeUnusedKeys(this.previousOldData, this.schema);
  53567. this.parsingAttrValue = this.objectPool.use();
  53568. utils.objectPool.removeUnusedKeys(this.parsingAttrValue, this.schema);
  53569. } else {
  53570. this.nextData = undefined;
  53571. this.oldData = undefined;
  53572. this.previousOldData = undefined;
  53573. this.parsingAttrValue = undefined;
  53574. }
  53575. // Last value passed to updateProperties.
  53576. this.throttledEmitComponentChanged = utils.throttle(function emitChange () {
  53577. el.emit('componentchanged', self.evtDetail, false);
  53578. }, 200);
  53579. this.updateProperties(attrValue);
  53580. };
  53581. Component.prototype = {
  53582. /**
  53583. * Contains the type schema and defaults for the data values.
  53584. * Data is coerced into the types of the values of the defaults.
  53585. */
  53586. schema: {},
  53587. /**
  53588. * Init handler. Similar to attachedCallback.
  53589. * Called during component initialization and is only run once.
  53590. * Components can use this to set initial state.
  53591. */
  53592. init: function () { /* no-op */ },
  53593. /**
  53594. * Map of event names to binded event handlers that will be lifecycle-handled.
  53595. * Will be detached on pause / remove.
  53596. * Will be attached on play.
  53597. */
  53598. events: {},
  53599. /**
  53600. * Update handler. Similar to attributeChangedCallback.
  53601. * Called whenever component's data changes.
  53602. * Also called on component initialization when the component receives initial data.
  53603. *
  53604. * @param {object} prevData - Previous attributes of the component.
  53605. */
  53606. update: function (prevData) { /* no-op */ },
  53607. updateSchema: undefined,
  53608. /**
  53609. * Tick handler.
  53610. * Called on each tick of the scene render loop.
  53611. * Affected by play and pause.
  53612. *
  53613. * @param {number} time - Scene tick time.
  53614. * @param {number} timeDelta - Difference in current render time and previous render time.
  53615. */
  53616. tick: undefined,
  53617. /**
  53618. * Tock handler.
  53619. * Called on each tock of the scene render loop.
  53620. * Affected by play and pause.
  53621. *
  53622. * @param {number} time - Scene tick time.
  53623. * @param {number} timeDelta - Difference in current render time and previous render time.
  53624. * @param {object} camera - Camera used to render the last frame.
  53625. */
  53626. tock: undefined,
  53627. /**
  53628. * Called to start any dynamic behavior (e.g., animation, AI, events, physics).
  53629. */
  53630. play: function () { /* no-op */ },
  53631. /**
  53632. * Called to stop any dynamic behavior (e.g., animation, AI, events, physics).
  53633. */
  53634. pause: function () { /* no-op */ },
  53635. /**
  53636. * Remove handler. Similar to detachedCallback.
  53637. * Called whenever component is removed from the entity (i.e., removeAttribute).
  53638. * Components can use this to reset behavior on the entity.
  53639. */
  53640. remove: function () { /* no-op */ },
  53641. /**
  53642. * Parses each property based on property type.
  53643. * If component is single-property, then parses the single property value.
  53644. *
  53645. * @param {string} value - HTML attribute value.
  53646. * @param {boolean} silent - Suppress warning messages.
  53647. * @returns {object} Component data.
  53648. */
  53649. parse: function (value, silent) {
  53650. var schema = this.schema;
  53651. if (this.isSingleProperty) { return parseProperty(value, schema); }
  53652. return parseProperties(styleParser.parse(value), schema, true, this.name, silent);
  53653. },
  53654. /**
  53655. * Stringify properties if necessary.
  53656. *
  53657. * Only called from `Entity.setAttribute` for properties whose parsers accept a non-string
  53658. * value (e.g., selector, vec3 property types).
  53659. *
  53660. * @param {object} data - Complete component data.
  53661. * @returns {string}
  53662. */
  53663. stringify: function (data) {
  53664. var schema = this.schema;
  53665. if (typeof data === 'string') { return data; }
  53666. if (this.isSingleProperty) { return stringifyProperty(data, schema); }
  53667. data = stringifyProperties(data, schema);
  53668. return styleParser.stringify(data);
  53669. },
  53670. /**
  53671. * Update the cache of the pre-parsed attribute value.
  53672. *
  53673. * @param {string} value - New data.
  53674. * @param {boolean } clobber - Whether to wipe out and replace previous data.
  53675. */
  53676. updateCachedAttrValue: function (value, clobber) {
  53677. var newAttrValue;
  53678. var tempObject;
  53679. var property;
  53680. if (value === undefined) { return; }
  53681. // If null value is the new attribute value, make the attribute value falsy.
  53682. if (value === null) {
  53683. if (this.isObjectBased && this.attrValue) {
  53684. this.objectPool.recycle(this.attrValue);
  53685. }
  53686. this.attrValue = undefined;
  53687. return;
  53688. }
  53689. if (value instanceof Object && !(value instanceof window.HTMLElement)) {
  53690. // If value is an object, copy it to our pooled newAttrValue object to use to update
  53691. // the attrValue.
  53692. tempObject = this.objectPool.use();
  53693. newAttrValue = utils.extend(tempObject, value);
  53694. } else {
  53695. newAttrValue = this.parseAttrValueForCache(value);
  53696. }
  53697. // Merge new data with previous `attrValue` if updating and not clobbering.
  53698. if (this.isObjectBased && !clobber && this.attrValue) {
  53699. for (property in this.attrValue) {
  53700. if (newAttrValue[property] === undefined) {
  53701. newAttrValue[property] = this.attrValue[property];
  53702. }
  53703. }
  53704. }
  53705. // Update attrValue.
  53706. if (this.isObjectBased && !this.attrValue) {
  53707. this.attrValue = this.objectPool.use();
  53708. }
  53709. utils.objectPool.clearObject(this.attrValue);
  53710. this.attrValue = extendProperties(this.attrValue, newAttrValue, this.isObjectBased);
  53711. utils.objectPool.clearObject(tempObject);
  53712. },
  53713. /**
  53714. * Given an HTML attribute value parses the string based on the component schema.
  53715. * To avoid double parsings of strings into strings we store the original instead
  53716. * of the parsed one
  53717. *
  53718. * @param {string} value - HTML attribute value
  53719. */
  53720. parseAttrValueForCache: function (value) {
  53721. var parsedValue;
  53722. if (typeof value !== 'string') { return value; }
  53723. if (this.isSingleProperty) {
  53724. parsedValue = this.schema.parse(value);
  53725. /**
  53726. * To avoid bogus double parsings. Cached values will be parsed when building
  53727. * component data. For instance when parsing a src id to its url, we want to cache
  53728. * original string and not the parsed one (#monster -> models/monster.dae)
  53729. * so when building data we parse the expected value.
  53730. */
  53731. if (typeof parsedValue === 'string') { parsedValue = value; }
  53732. } else {
  53733. // Parse using the style parser to avoid double parsing of individual properties.
  53734. utils.objectPool.clearObject(this.parsingAttrValue);
  53735. parsedValue = styleParser.parse(value, this.parsingAttrValue);
  53736. }
  53737. return parsedValue;
  53738. },
  53739. /**
  53740. * Write cached attribute data to the entity DOM element.
  53741. *
  53742. * @param {boolean} isDefault - Whether component is a default component. Always flush for
  53743. * default components.
  53744. */
  53745. flushToDOM: function (isDefault) {
  53746. var attrValue = isDefault ? this.data : this.attrValue;
  53747. if (attrValue === null || attrValue === undefined) { return; }
  53748. window.HTMLElement.prototype.setAttribute.call(this.el, this.attrName,
  53749. this.stringify(attrValue));
  53750. },
  53751. /**
  53752. * Apply new component data if data has changed (from setAttribute).
  53753. *
  53754. * @param {string} attrValue - HTML attribute value.
  53755. * If undefined, use the cached attribute value and continue updating properties.
  53756. * @param {boolean} clobber - The previous component data is overwritten by the atrrValue
  53757. */
  53758. updateProperties: function (attrValue, clobber) {
  53759. var el = this.el;
  53760. // Just cache the attribute if the entity has not loaded
  53761. // Components are not initialized until the entity has loaded
  53762. if (!el.hasLoaded) {
  53763. this.updateCachedAttrValue(attrValue);
  53764. return;
  53765. }
  53766. // Parse the attribute value.
  53767. // Cache current attrValue for future updates. Updates `this.attrValue`.
  53768. // `null` means no value on purpose, do not set a default value, let mixins take over.
  53769. if (attrValue !== null) {
  53770. attrValue = this.parseAttrValueForCache(attrValue);
  53771. }
  53772. // Cache current attrValue for future updates.
  53773. this.updateCachedAttrValue(attrValue, clobber);
  53774. if (this.initialized) {
  53775. this.updateComponent(attrValue, clobber);
  53776. this.callUpdateHandler();
  53777. } else {
  53778. this.initComponent();
  53779. }
  53780. },
  53781. initComponent: function () {
  53782. var el = this.el;
  53783. var initialOldData;
  53784. // Build data.
  53785. if (this.updateSchema) { this.updateSchema(this.buildData(this.attrValue, false, true)); }
  53786. this.data = this.buildData(this.attrValue);
  53787. // Component is being already initialized.
  53788. if (el.initializingComponents[this.name]) { return; }
  53789. // Prevent infinite loop in case of init method setting same component on the entity.
  53790. el.initializingComponents[this.name] = true;
  53791. // Initialize component.
  53792. this.init();
  53793. this.initialized = true;
  53794. delete el.initializingComponents[this.name];
  53795. // Store current data as previous data for future updates.
  53796. this.oldData = extendProperties(this.oldData, this.data, this.isObjectBased);
  53797. // For oldData, pass empty object to multiple-prop schemas or object single-prop schema.
  53798. // Pass undefined to rest of types.
  53799. initialOldData = this.isObjectBased ? this.objectPool.use() : undefined;
  53800. this.update(initialOldData);
  53801. if (this.isObjectBased) { this.objectPool.recycle(initialOldData); }
  53802. // Play the component if the entity is playing.
  53803. if (el.isPlaying) { this.play(); }
  53804. el.emit('componentinitialized', this.evtDetail, false);
  53805. },
  53806. /**
  53807. * @param attrValue - Passed argument from setAttribute.
  53808. */
  53809. updateComponent: function (attrValue, clobber) {
  53810. var key;
  53811. var mayNeedSchemaUpdate;
  53812. if (clobber) {
  53813. // Clobber. Rebuild.
  53814. if (this.updateSchema) {
  53815. this.updateSchema(this.buildData(this.attrValue, true, true));
  53816. }
  53817. this.data = this.buildData(this.attrValue, true, false);
  53818. return;
  53819. }
  53820. // Apply new value to this.data in place since direct update.
  53821. if (this.isSingleProperty) {
  53822. if (this.isObjectBased) {
  53823. parseProperty(attrValue, this.schema);
  53824. }
  53825. // Single-property (already parsed).
  53826. this.data = attrValue;
  53827. return;
  53828. }
  53829. parseProperties(attrValue, this.schema, true, this.name);
  53830. // Check if we need to update schema.
  53831. if (this.schemaChangeKeys.length) {
  53832. for (key in attrValue) {
  53833. if (this.schema[key].schemaChange) {
  53834. mayNeedSchemaUpdate = true;
  53835. break;
  53836. }
  53837. }
  53838. }
  53839. if (mayNeedSchemaUpdate) {
  53840. // Rebuild data if need schema update.
  53841. if (this.updateSchema) {
  53842. this.updateSchema(this.buildData(this.attrValue, true, true));
  53843. }
  53844. this.data = this.buildData(this.attrValue, true, false);
  53845. return;
  53846. }
  53847. // Normal update.
  53848. for (key in attrValue) {
  53849. if (attrValue[key] === undefined) { continue; }
  53850. this.data[key] = attrValue[key];
  53851. }
  53852. },
  53853. /**
  53854. * Check if component should fire update and fire update lifecycle handler.
  53855. */
  53856. callUpdateHandler: function () {
  53857. var hasComponentChanged;
  53858. // Store the previous old data before we calculate the new oldData.
  53859. if (this.previousOldData instanceof Object) {
  53860. utils.objectPool.clearObject(this.previousOldData);
  53861. }
  53862. if (this.isObjectBased) {
  53863. copyData(this.previousOldData, this.oldData);
  53864. } else {
  53865. this.previousOldData = this.oldData;
  53866. }
  53867. hasComponentChanged = !utils.deepEqual(this.oldData, this.data);
  53868. // Don't update if properties haven't changed.
  53869. // Always update rotation, position, scale.
  53870. if (!this.isPositionRotationScale && !hasComponentChanged) { return; }
  53871. // Store current data as previous data for future updates.
  53872. // Reuse `this.oldData` object to try not to allocate another one.
  53873. if (this.oldData instanceof Object) { utils.objectPool.clearObject(this.oldData); }
  53874. this.oldData = extendProperties(this.oldData, this.data, this.isObjectBased);
  53875. // Update component with the previous old data.
  53876. this.update(this.previousOldData);
  53877. this.throttledEmitComponentChanged();
  53878. },
  53879. handleMixinUpdate: function () {
  53880. this.data = this.buildData(this.attrValue);
  53881. this.callUpdateHandler();
  53882. },
  53883. /**
  53884. * Reset value of a property to the property's default value.
  53885. * If single-prop component, reset value to component's default value.
  53886. *
  53887. * @param {string} propertyName - Name of property to reset.
  53888. */
  53889. resetProperty: function (propertyName) {
  53890. if (this.isObjectBased) {
  53891. if (!(propertyName in this.attrValue)) { return; }
  53892. delete this.attrValue[propertyName];
  53893. this.data[propertyName] = this.schema[propertyName].default;
  53894. } else {
  53895. this.attrValue = this.schema.default;
  53896. this.data = this.schema.default;
  53897. }
  53898. this.updateProperties(this.attrValue);
  53899. },
  53900. /**
  53901. * Extend schema of component given a partial schema.
  53902. *
  53903. * Some components might want to mutate their schema based on certain properties.
  53904. * e.g., Material component changes its schema based on `shader` to account for different
  53905. * uniforms
  53906. *
  53907. * @param {object} schemaAddon - Schema chunk that extend base schema.
  53908. */
  53909. extendSchema: function (schemaAddon) {
  53910. var extendedSchema;
  53911. // Clone base schema.
  53912. extendedSchema = utils.extend({}, components[this.name].schema);
  53913. // Extend base schema with new schema chunk.
  53914. utils.extend(extendedSchema, schemaAddon);
  53915. this.schema = processSchema(extendedSchema);
  53916. this.el.emit('schemachanged', this.evtDetail);
  53917. },
  53918. /**
  53919. * Build component data from the current state of the entity.data.
  53920. *
  53921. * Precedence:
  53922. * 1. Defaults data
  53923. * 2. Mixin data.
  53924. * 3. Attribute data.
  53925. *
  53926. * Finally coerce the data to the types of the defaults.
  53927. *
  53928. * @param {object} newData - Element new data.
  53929. * @param {boolean} clobber - The previous data is completely replaced by the new one.
  53930. * @param {boolean} silent - Suppress warning messages.
  53931. * @return {object} The component data
  53932. */
  53933. buildData: function (newData, clobber, silent) {
  53934. var componentDefined;
  53935. var data;
  53936. var defaultValue;
  53937. var key;
  53938. var mixinData;
  53939. var nextData = this.nextData;
  53940. var schema = this.schema;
  53941. var i;
  53942. var mixinEls = this.el.mixinEls;
  53943. var previousData;
  53944. // Whether component has a defined value. For arrays, treat empty as not defined.
  53945. componentDefined = newData && newData.constructor === Array
  53946. ? newData.length
  53947. : newData !== undefined && newData !== null;
  53948. if (this.isObjectBased) { utils.objectPool.clearObject(nextData); }
  53949. // 1. Gather default values (lowest precendence).
  53950. if (this.isSingleProperty) {
  53951. if (this.isObjectBased) {
  53952. // If object-based single-prop, then copy over the data to our pooled object.
  53953. data = copyData(nextData, schema.default);
  53954. } else {
  53955. // If is plain single-prop, copy by value the default.
  53956. data = isObjectOrArray(schema.default)
  53957. ? utils.clone(schema.default)
  53958. : schema.default;
  53959. }
  53960. } else {
  53961. // Preserve previously set properties if clobber not enabled.
  53962. previousData = !clobber && this.attrValue;
  53963. // Clone default value if object so components don't share object
  53964. data = previousData instanceof Object
  53965. ? copyData(nextData, previousData)
  53966. : nextData;
  53967. // Apply defaults.
  53968. for (key in schema) {
  53969. defaultValue = schema[key].default;
  53970. if (data[key] !== undefined) { continue; }
  53971. // Clone default value if object so components don't share object
  53972. data[key] = isObjectOrArray(defaultValue)
  53973. ? utils.clone(defaultValue)
  53974. : defaultValue;
  53975. }
  53976. }
  53977. // 2. Gather mixin values.
  53978. for (i = 0; i < mixinEls.length; i++) {
  53979. mixinData = mixinEls[i].getAttribute(this.attrName);
  53980. if (!mixinData) { continue; }
  53981. data = extendProperties(data, mixinData, this.isObjectBased);
  53982. }
  53983. // 3. Gather attribute values (highest precendence).
  53984. if (componentDefined) {
  53985. if (this.isSingleProperty) {
  53986. // If object-based, copy the value to not modify the original.
  53987. if (isObject(newData)) {
  53988. copyData(this.parsingAttrValue, newData);
  53989. return parseProperty(this.parsingAttrValue, schema);
  53990. }
  53991. return parseProperty(newData, schema);
  53992. }
  53993. data = extendProperties(data, newData, this.isObjectBased);
  53994. } else {
  53995. // Parse and coerce using the schema.
  53996. if (this.isSingleProperty) { return parseProperty(data, schema); }
  53997. }
  53998. return parseProperties(data, schema, undefined, this.name, silent);
  53999. },
  54000. /**
  54001. * Attach events from component-defined events map.
  54002. */
  54003. eventsAttach: function () {
  54004. var eventName;
  54005. // Safety detach to prevent double-registration.
  54006. this.eventsDetach();
  54007. for (eventName in this.events) {
  54008. this.el.addEventListener(eventName, this.events[eventName]);
  54009. }
  54010. },
  54011. /**
  54012. * Detach events from component-defined events map.
  54013. */
  54014. eventsDetach: function () {
  54015. var eventName;
  54016. for (eventName in this.events) {
  54017. this.el.removeEventListener(eventName, this.events[eventName]);
  54018. }
  54019. },
  54020. /**
  54021. * Release and free memory.
  54022. */
  54023. destroy: function () {
  54024. this.objectPool.recycle(this.attrValue);
  54025. this.objectPool.recycle(this.oldData);
  54026. this.objectPool.recycle(this.parsingAttrValue);
  54027. this.attrValue = this.oldData = this.parsingAttrValue = undefined;
  54028. }
  54029. };
  54030. function eventsBind (component, events) {
  54031. var eventName;
  54032. for (eventName in events) {
  54033. component.events[eventName] = events[eventName].bind(component);
  54034. }
  54035. }
  54036. // For testing.
  54037. if (window.debug) {
  54038. var registrationOrderWarnings = module.exports.registrationOrderWarnings = {};
  54039. }
  54040. /**
  54041. * Register a component to A-Frame.
  54042. *
  54043. * @param {string} name - Component name.
  54044. * @param {object} definition - Component schema and lifecycle method handlers.
  54045. * @returns {object} Component.
  54046. */
  54047. module.exports.registerComponent = function (name, definition) {
  54048. var NewComponent;
  54049. var propertyName;
  54050. var proto = {};
  54051. var schema;
  54052. var schemaIsSingleProp;
  54053. // Warning if component is statically registered after the scene.
  54054. if (document.currentScript && document.currentScript !== aframeScript) {
  54055. scenes.forEach(function checkPosition (sceneEl) {
  54056. // Okay to register component after the scene at runtime.
  54057. if (sceneEl.hasLoaded) { return; }
  54058. // Check that component is declared before the scene.
  54059. if (document.currentScript.compareDocumentPosition(sceneEl) ===
  54060. Node.DOCUMENT_POSITION_FOLLOWING) { return; }
  54061. warn('The component `' + name + '` was registered in a <script> tag after the scene. ' +
  54062. 'Component <script> tags in an HTML file should be declared *before* the scene ' +
  54063. 'such that the component is available to entities during scene initialization.');
  54064. // For testing.
  54065. if (window.debug) { registrationOrderWarnings[name] = true; }
  54066. });
  54067. }
  54068. if (upperCaseRegExp.test(name) === true) {
  54069. warn('The component name `' + name + '` contains uppercase characters, but ' +
  54070. 'HTML will ignore the capitalization of attribute names. ' +
  54071. 'Change the name to be lowercase: `' + name.toLowerCase() + '`');
  54072. }
  54073. if (name.indexOf('__') !== -1) {
  54074. throw new Error('The component name `' + name + '` is not allowed. ' +
  54075. 'The sequence __ (double underscore) is reserved to specify an id' +
  54076. ' for multiple components of the same type');
  54077. }
  54078. // Format definition object to prototype object.
  54079. Object.keys(definition).forEach(function (key) {
  54080. proto[key] = {
  54081. value: definition[key],
  54082. writable: true
  54083. };
  54084. });
  54085. if (components[name]) {
  54086. throw new Error('The component `' + name + '` has been already registered. ' +
  54087. 'Check that you are not loading two versions of the same component ' +
  54088. 'or two different components of the same name.');
  54089. }
  54090. NewComponent = function (el, attr, id) {
  54091. Component.call(this, el, attr, id);
  54092. };
  54093. NewComponent.prototype = Object.create(Component.prototype, proto);
  54094. NewComponent.prototype.name = name;
  54095. NewComponent.prototype.isPositionRotationScale =
  54096. name === 'position' || name === 'rotation' || name === 'scale';
  54097. NewComponent.prototype.constructor = NewComponent;
  54098. NewComponent.prototype.system = systems && systems.systems[name];
  54099. NewComponent.prototype.play = wrapPlay(NewComponent.prototype.play);
  54100. NewComponent.prototype.pause = wrapPause(NewComponent.prototype.pause);
  54101. schema = utils.extend(processSchema(NewComponent.prototype.schema,
  54102. NewComponent.prototype.name));
  54103. schemaIsSingleProp = isSingleProp(NewComponent.prototype.schema);
  54104. // Keep track of keys that may potentially change the schema.
  54105. if (!schemaIsSingleProp) {
  54106. NewComponent.prototype.schemaChangeKeys = [];
  54107. for (propertyName in schema) {
  54108. if (schema[propertyName].schemaChange) {
  54109. NewComponent.prototype.schemaChangeKeys.push(propertyName);
  54110. }
  54111. }
  54112. }
  54113. // Create object pool for class of components.
  54114. objectPools[name] = utils.objectPool.createPool();
  54115. components[name] = {
  54116. Component: NewComponent,
  54117. dependencies: NewComponent.prototype.dependencies,
  54118. isSingleProp: schemaIsSingleProp,
  54119. multiple: NewComponent.prototype.multiple,
  54120. name: name,
  54121. parse: NewComponent.prototype.parse,
  54122. parseAttrValueForCache: NewComponent.prototype.parseAttrValueForCache,
  54123. schema: schema,
  54124. stringify: NewComponent.prototype.stringify,
  54125. type: NewComponent.prototype.type
  54126. };
  54127. return NewComponent;
  54128. };
  54129. /**
  54130. * Clone component data.
  54131. * Clone only the properties that are plain objects while keeping a reference for the rest.
  54132. *
  54133. * @param data - Component data to clone.
  54134. * @returns Cloned data.
  54135. */
  54136. function copyData (dest, sourceData) {
  54137. var parsedProperty;
  54138. var key;
  54139. for (key in sourceData) {
  54140. if (sourceData[key] === undefined) { continue; }
  54141. parsedProperty = sourceData[key];
  54142. dest[key] = isObjectOrArray(parsedProperty)
  54143. ? utils.clone(parsedProperty)
  54144. : parsedProperty;
  54145. }
  54146. return dest;
  54147. }
  54148. /**
  54149. * Object extending with checking for single-property schema.
  54150. *
  54151. * @param dest - Destination object or value.
  54152. * @param source - Source object or value
  54153. * @param {boolean} isObjectBased - Whether values are objects.
  54154. * @returns Overridden object or value.
  54155. */
  54156. function extendProperties (dest, source, isObjectBased) {
  54157. var key;
  54158. if (isObjectBased && source.constructor === Object) {
  54159. for (key in source) {
  54160. if (source[key] === undefined) { continue; }
  54161. if (source[key] && source[key].constructor === Object) {
  54162. dest[key] = utils.clone(source[key]);
  54163. } else {
  54164. dest[key] = source[key];
  54165. }
  54166. }
  54167. return dest;
  54168. }
  54169. return source;
  54170. }
  54171. /**
  54172. * Checks if a component has defined a method that needs to run every frame.
  54173. */
  54174. function hasBehavior (component) {
  54175. return component.tick || component.tock;
  54176. }
  54177. /**
  54178. * Wrapper for defined pause method.
  54179. * Pause component by removing tick behavior and calling user's pause method.
  54180. *
  54181. * @param pauseMethod {function}
  54182. */
  54183. function wrapPause (pauseMethod) {
  54184. return function pause () {
  54185. var sceneEl = this.el.sceneEl;
  54186. if (!this.isPlaying) { return; }
  54187. pauseMethod.call(this);
  54188. this.isPlaying = false;
  54189. this.eventsDetach();
  54190. // Remove tick behavior.
  54191. if (!hasBehavior(this)) { return; }
  54192. sceneEl.removeBehavior(this);
  54193. };
  54194. }
  54195. /**
  54196. * Wrapper for defined play method.
  54197. * Play component by adding tick behavior and calling user's play method.
  54198. *
  54199. * @param playMethod {function}
  54200. */
  54201. function wrapPlay (playMethod) {
  54202. return function play () {
  54203. var sceneEl = this.el.sceneEl;
  54204. var shouldPlay = this.el.isPlaying && !this.isPlaying;
  54205. if (!this.initialized || !shouldPlay) { return; }
  54206. playMethod.call(this);
  54207. this.isPlaying = true;
  54208. this.eventsAttach();
  54209. // Add tick behavior.
  54210. if (!hasBehavior(this)) { return; }
  54211. sceneEl.addBehavior(this);
  54212. };
  54213. }
  54214. function isObject (value) {
  54215. return value && value.constructor === Object && !(value instanceof window.HTMLElement);
  54216. }
  54217. function isObjectOrArray (value) {
  54218. return value && (value.constructor === Object || value.constructor === Array) &&
  54219. !(value instanceof window.HTMLElement);
  54220. }
  54221. },{"../utils/":202,"./scene/scenes":135,"./schema":137,"./system":139}],129:[function(_dereq_,module,exports){
  54222. var schema = _dereq_('./schema');
  54223. var processSchema = schema.process;
  54224. var geometries = module.exports.geometries = {}; // Registered geometries.
  54225. var geometryNames = module.exports.geometryNames = []; // Names of registered geometries.
  54226. var THREE = _dereq_('../lib/three');
  54227. /**
  54228. * Geometry class definition.
  54229. *
  54230. * Geometries extend the geometry component API to create and register geometry types.
  54231. */
  54232. var Geometry = module.exports.Geometry = function () {};
  54233. Geometry.prototype = {
  54234. /**
  54235. * Contains the type schema and defaults for the data values.
  54236. * Data is coerced into the types of the values of the defaults.
  54237. */
  54238. schema: {},
  54239. /**
  54240. * Init handler. Similar to attachedCallback.
  54241. * Called during shader initialization and is only run once.
  54242. */
  54243. init: function (data) {
  54244. this.geometry = new THREE.Geometry();
  54245. return this.geometry;
  54246. },
  54247. /**
  54248. * Update handler. Similar to attributeChangedCallback.
  54249. * Called whenever the associated geometry data changes.
  54250. *
  54251. * @param {object} data - New geometry data.
  54252. */
  54253. update: function (data) { /* no-op */ }
  54254. };
  54255. /**
  54256. * Registers a geometry to A-Frame.
  54257. *
  54258. * @param {string} name - Geometry name.
  54259. * @param {object} definition - Geometry property and methods.
  54260. * @returns {object} Geometry.
  54261. */
  54262. module.exports.registerGeometry = function (name, definition) {
  54263. var NewGeometry;
  54264. var proto = {};
  54265. // Format definition object to prototype object.
  54266. Object.keys(definition).forEach(function expandDefinition (key) {
  54267. proto[key] = {
  54268. value: definition[key],
  54269. writable: true
  54270. };
  54271. });
  54272. if (geometries[name]) {
  54273. throw new Error('The geometry `' + name + '` has been already registered');
  54274. }
  54275. NewGeometry = function () { Geometry.call(this); };
  54276. NewGeometry.prototype = Object.create(Geometry.prototype, proto);
  54277. NewGeometry.prototype.name = name;
  54278. NewGeometry.prototype.constructor = NewGeometry;
  54279. geometries[name] = {
  54280. Geometry: NewGeometry,
  54281. schema: processSchema(NewGeometry.prototype.schema)
  54282. };
  54283. geometryNames.push(name);
  54284. return NewGeometry;
  54285. };
  54286. },{"../lib/three":176,"./schema":137}],130:[function(_dereq_,module,exports){
  54287. var coordinates = _dereq_('../utils/coordinates');
  54288. var debug = _dereq_('debug');
  54289. var error = debug('core:propertyTypes:warn');
  54290. var warn = debug('core:propertyTypes:warn');
  54291. var propertyTypes = module.exports.propertyTypes = {};
  54292. var nonCharRegex = /[,> .[\]:]/;
  54293. var urlRegex = /\url\((.+)\)/;
  54294. // Built-in property types.
  54295. registerPropertyType('audio', '', assetParse);
  54296. registerPropertyType('array', [], arrayParse, arrayStringify);
  54297. registerPropertyType('asset', '', assetParse);
  54298. registerPropertyType('boolean', false, boolParse);
  54299. registerPropertyType('color', '#FFF', defaultParse, defaultStringify);
  54300. registerPropertyType('int', 0, intParse);
  54301. registerPropertyType('number', 0, numberParse);
  54302. registerPropertyType('map', '', assetParse);
  54303. registerPropertyType('model', '', assetParse);
  54304. registerPropertyType('selector', null, selectorParse, selectorStringify);
  54305. registerPropertyType('selectorAll', null, selectorAllParse, selectorAllStringify);
  54306. registerPropertyType('src', '', srcParse);
  54307. registerPropertyType('string', '', defaultParse, defaultStringify);
  54308. registerPropertyType('time', 0, intParse);
  54309. registerPropertyType('vec2', {x: 0, y: 0}, vecParse, coordinates.stringify);
  54310. registerPropertyType('vec3', {x: 0, y: 0, z: 0}, vecParse, coordinates.stringify);
  54311. registerPropertyType('vec4', {x: 0, y: 0, z: 0, w: 1}, vecParse, coordinates.stringify);
  54312. /**
  54313. * Register a parser for re-use such that when someone uses `type` in the schema,
  54314. * `schema.process` will set the property `parse` and `stringify`.
  54315. *
  54316. * @param {string} type - Type name.
  54317. * @param [defaultValue=null] -
  54318. * Default value to use if component does not define default value.
  54319. * @param {function} [parse=defaultParse] - Parse string function.
  54320. * @param {function} [stringify=defaultStringify] - Stringify to DOM function.
  54321. */
  54322. function registerPropertyType (type, defaultValue, parse, stringify) {
  54323. if ('type' in propertyTypes) {
  54324. error('Property type ' + type + ' is already registered.');
  54325. return;
  54326. }
  54327. propertyTypes[type] = {
  54328. default: defaultValue,
  54329. parse: parse || defaultParse,
  54330. stringify: stringify || defaultStringify
  54331. };
  54332. }
  54333. module.exports.registerPropertyType = registerPropertyType;
  54334. function arrayParse (value) {
  54335. if (Array.isArray(value)) { return value; }
  54336. if (!value || typeof value !== 'string') { return []; }
  54337. return value.split(',').map(trim);
  54338. function trim (str) { return str.trim(); }
  54339. }
  54340. function arrayStringify (value) {
  54341. return value.join(', ');
  54342. }
  54343. /**
  54344. * For general assets.
  54345. *
  54346. * @param {string} value - Can either be `url(<value>)`, an ID selector to an asset, or
  54347. * just string.
  54348. * @returns {string} Parsed value from `url(<value>)`, src from `<someasset src>`, or
  54349. * just string.
  54350. */
  54351. function assetParse (value) {
  54352. var el;
  54353. var parsedUrl;
  54354. // If an element was provided (e.g. canvas or video), just return it.
  54355. if (typeof value !== 'string') { return value; }
  54356. // Wrapped `url()` in case of data URI.
  54357. parsedUrl = value.match(urlRegex);
  54358. if (parsedUrl) { return parsedUrl[1]; }
  54359. // ID.
  54360. if (value.charAt(0) === '#') {
  54361. el = document.getElementById(value.substring(1));
  54362. if (el) {
  54363. // Pass through media elements. If we have the elements, we don't have to call
  54364. // three.js loaders which would re-request the assets.
  54365. if (el.tagName === 'CANVAS' || el.tagName === 'VIDEO' || el.tagName === 'IMG') {
  54366. return el;
  54367. }
  54368. return el.getAttribute('src');
  54369. }
  54370. warn('"' + value + '" asset not found.');
  54371. return;
  54372. }
  54373. // Non-wrapped url().
  54374. return value;
  54375. }
  54376. function defaultParse (value) {
  54377. return value;
  54378. }
  54379. function defaultStringify (value) {
  54380. if (value === null) { return 'null'; }
  54381. return value.toString();
  54382. }
  54383. function boolParse (value) {
  54384. return value !== 'false' && value !== false;
  54385. }
  54386. function intParse (value) {
  54387. return parseInt(value, 10);
  54388. }
  54389. function numberParse (value) {
  54390. return parseFloat(value, 10);
  54391. }
  54392. function selectorParse (value) {
  54393. if (!value) { return null; }
  54394. if (typeof value !== 'string') { return value; }
  54395. if (value[0] === '#' && !nonCharRegex.test(value)) {
  54396. // When selecting element by ID only, use getElementById for better performance.
  54397. // Don't match like #myId .child.
  54398. return document.getElementById(value.substring(1));
  54399. }
  54400. return document.querySelector(value);
  54401. }
  54402. function selectorAllParse (value) {
  54403. if (!value) { return null; }
  54404. if (typeof value !== 'string') { return value; }
  54405. return Array.prototype.slice.call(document.querySelectorAll(value), 0);
  54406. }
  54407. function selectorStringify (value) {
  54408. if (value.getAttribute) {
  54409. return '#' + value.getAttribute('id');
  54410. }
  54411. return defaultStringify(value);
  54412. }
  54413. function selectorAllStringify (value) {
  54414. if (value instanceof Array) {
  54415. return value.map(function (element) {
  54416. return '#' + element.getAttribute('id');
  54417. }).join(', ');
  54418. }
  54419. return defaultStringify(value);
  54420. }
  54421. function srcParse (value) {
  54422. warn('`src` property type is deprecated. Use `asset` instead.');
  54423. return assetParse(value);
  54424. }
  54425. function vecParse (value) {
  54426. return coordinates.parse(value, this.default);
  54427. }
  54428. /**
  54429. * Validate the default values in a schema to match their type.
  54430. *
  54431. * @param {string} type - Property type name.
  54432. * @param defaultVal - Property type default value.
  54433. * @returns {boolean} Whether default value is accurate given the type.
  54434. */
  54435. function isValidDefaultValue (type, defaultVal) {
  54436. if (type === 'audio' && typeof defaultVal !== 'string') { return false; }
  54437. if (type === 'array' && !Array.isArray(defaultVal)) { return false; }
  54438. if (type === 'asset' && typeof defaultVal !== 'string') { return false; }
  54439. if (type === 'boolean' && typeof defaultVal !== 'boolean') { return false; }
  54440. if (type === 'color' && typeof defaultVal !== 'string') { return false; }
  54441. if (type === 'int' && typeof defaultVal !== 'number') { return false; }
  54442. if (type === 'number' && typeof defaultVal !== 'number') { return false; }
  54443. if (type === 'map' && typeof defaultVal !== 'string') { return false; }
  54444. if (type === 'model' && typeof defaultVal !== 'string') { return false; }
  54445. if (type === 'selector' && typeof defaultVal !== 'string' &&
  54446. defaultVal !== null) { return false; }
  54447. if (type === 'selectorAll' && typeof defaultVal !== 'string' &&
  54448. defaultVal !== null) { return false; }
  54449. if (type === 'src' && typeof defaultVal !== 'string') { return false; }
  54450. if (type === 'string' && typeof defaultVal !== 'string') { return false; }
  54451. if (type === 'time' && typeof defaultVal !== 'number') { return false; }
  54452. if (type === 'vec2') { return isValidDefaultCoordinate(defaultVal, 2); }
  54453. if (type === 'vec3') { return isValidDefaultCoordinate(defaultVal, 3); }
  54454. if (type === 'vec4') { return isValidDefaultCoordinate(defaultVal, 4); }
  54455. return true;
  54456. }
  54457. module.exports.isValidDefaultValue = isValidDefaultValue;
  54458. /**
  54459. * Checks if default coordinates are valid.
  54460. *
  54461. * @param possibleCoordinates
  54462. * @param {number} dimensions - 2 for 2D Vector, 3 for 3D vector.
  54463. * @returns {boolean} Whether coordinates are parsed correctly.
  54464. */
  54465. function isValidDefaultCoordinate (possibleCoordinates, dimensions) {
  54466. if (possibleCoordinates === null) { return true; }
  54467. if (typeof possibleCoordinates !== 'object') { return false; }
  54468. if (Object.keys(possibleCoordinates).length !== dimensions) {
  54469. return false;
  54470. } else {
  54471. var x = possibleCoordinates.x;
  54472. var y = possibleCoordinates.y;
  54473. var z = possibleCoordinates.z;
  54474. var w = possibleCoordinates.w;
  54475. if (typeof x !== 'number' || typeof y !== 'number') { return false; }
  54476. if (dimensions > 2 && typeof z !== 'number') { return false; }
  54477. if (dimensions > 3 && typeof w !== 'number') { return false; }
  54478. }
  54479. return true;
  54480. }
  54481. module.exports.isValidDefaultCoordinate = isValidDefaultCoordinate;
  54482. },{"../utils/coordinates":197,"debug":8}],131:[function(_dereq_,module,exports){
  54483. /* global Promise, screen, CustomEvent */
  54484. var initMetaTags = _dereq_('./metaTags').inject;
  54485. var initWakelock = _dereq_('./wakelock');
  54486. var loadingScreen = _dereq_('./loadingScreen');
  54487. var re = _dereq_('../a-register-element');
  54488. var scenes = _dereq_('./scenes');
  54489. var systems = _dereq_('../system').systems;
  54490. var THREE = _dereq_('../../lib/three');
  54491. var utils = _dereq_('../../utils/');
  54492. // Require after.
  54493. var AEntity = _dereq_('../a-entity');
  54494. var ANode = _dereq_('../a-node');
  54495. var initPostMessageAPI = _dereq_('./postMessage');
  54496. var bind = utils.bind;
  54497. var isIOS = utils.device.isIOS();
  54498. var isMobile = utils.device.isMobile();
  54499. var isWebXRAvailable = utils.device.isWebXRAvailable;
  54500. var registerElement = re.registerElement;
  54501. var warn = utils.debug('core:a-scene:warn');
  54502. /**
  54503. * Scene element, holds all entities.
  54504. *
  54505. * @member {array} behaviors - Component instances that have registered themselves to be
  54506. updated on every tick.
  54507. * @member {object} camera - three.js Camera object.
  54508. * @member {object} canvas
  54509. * @member {bool} isScene - Differentiates as scene entity as opposed to other entites.
  54510. * @member {bool} isMobile - Whether browser is mobile (via UA detection).
  54511. * @member {object} object3D - Root three.js Scene object.
  54512. * @member {object} renderer
  54513. * @member {bool} renderStarted
  54514. * @member {object} systems - Registered instantiated systems.
  54515. * @member {number} time
  54516. */
  54517. module.exports.AScene = registerElement('a-scene', {
  54518. prototype: Object.create(AEntity.prototype, {
  54519. createdCallback: {
  54520. value: function () {
  54521. this.clock = new THREE.Clock();
  54522. this.isIOS = isIOS;
  54523. this.isMobile = isMobile;
  54524. this.hasWebXR = isWebXRAvailable;
  54525. this.isAR = false;
  54526. this.isScene = true;
  54527. this.object3D = new THREE.Scene();
  54528. var self = this;
  54529. this.object3D.onAfterRender = function (renderer, scene, camera) {
  54530. // THREE may swap the camera used for the rendering if in VR, so we pass it to tock
  54531. if (self.isPlaying) { self.tock(self.time, self.delta, camera); }
  54532. };
  54533. this.resize = bind(this.resize, this);
  54534. this.render = bind(this.render, this);
  54535. this.systems = {};
  54536. this.systemNames = [];
  54537. this.time = this.delta = 0;
  54538. this.behaviors = {tick: [], tock: []};
  54539. this.hasLoaded = false;
  54540. this.isPlaying = false;
  54541. this.originalHTML = this.innerHTML;
  54542. // Default components.
  54543. this.setAttribute('inspector', '');
  54544. this.setAttribute('keyboard-shortcuts', '');
  54545. this.setAttribute('screenshot', '');
  54546. this.setAttribute('vr-mode-ui', '');
  54547. this.setAttribute('device-orientation-permission-ui', '');
  54548. }
  54549. },
  54550. addFullScreenStyles: {
  54551. value: function () {
  54552. document.documentElement.classList.add('a-fullscreen');
  54553. }
  54554. },
  54555. removeFullScreenStyles: {
  54556. value: function () {
  54557. document.documentElement.classList.remove('a-fullscreen');
  54558. }
  54559. },
  54560. attachedCallback: {
  54561. value: function () {
  54562. var self = this;
  54563. var embedded = this.hasAttribute('embedded');
  54564. // Renderer initialization
  54565. setupCanvas(this);
  54566. this.setupRenderer();
  54567. this.resize();
  54568. if (!embedded) { this.addFullScreenStyles(); }
  54569. initPostMessageAPI(this);
  54570. initMetaTags(this);
  54571. initWakelock(this);
  54572. // Handler to exit VR (e.g., Oculus Browser back button).
  54573. this.onVRPresentChangeBound = bind(this.onVRPresentChange, this);
  54574. window.addEventListener('vrdisplaypresentchange', this.onVRPresentChangeBound);
  54575. // Bind functions.
  54576. this.enterVRBound = function () { self.enterVR(); };
  54577. this.exitVRBound = function () { self.exitVR(); };
  54578. this.exitVRTrueBound = function () { self.exitVR(true); };
  54579. this.pointerRestrictedBound = function () { self.pointerRestricted(); };
  54580. this.pointerUnrestrictedBound = function () { self.pointerUnrestricted(); };
  54581. if (!isWebXRAvailable) {
  54582. // Exit VR on `vrdisplaydeactivate` (e.g. taking off Rift headset).
  54583. window.addEventListener('vrdisplaydeactivate', this.exitVRBound);
  54584. // Exit VR on `vrdisplaydisconnect` (e.g. unplugging Rift headset).
  54585. window.addEventListener('vrdisplaydisconnect', this.exitVRTrueBound);
  54586. // Register for mouse restricted events while in VR
  54587. // (e.g. mouse no longer available on desktop 2D view)
  54588. window.addEventListener('vrdisplaypointerrestricted', this.pointerRestrictedBound);
  54589. // Register for mouse unrestricted events while in VR
  54590. // (e.g. mouse once again available on desktop 2D view)
  54591. window.addEventListener('vrdisplaypointerunrestricted',
  54592. this.pointerUnrestrictedBound);
  54593. }
  54594. window.addEventListener('sessionend', this.resize);
  54595. // Camera set up by camera system.
  54596. this.addEventListener('cameraready', function () {
  54597. self.attachedCallbackPostCamera();
  54598. });
  54599. this.initSystems();
  54600. }
  54601. },
  54602. attachedCallbackPostCamera: {
  54603. value: function () {
  54604. var resize;
  54605. var self = this;
  54606. window.addEventListener('load', resize);
  54607. window.addEventListener('resize', function () {
  54608. // Workaround for a Webkit bug (https://bugs.webkit.org/show_bug.cgi?id=170595)
  54609. // where the window does not contain the correct viewport size
  54610. // after an orientation change. The window size is correct if the operation
  54611. // is postponed a few milliseconds.
  54612. // self.resize can be called directly once the bug above is fixed.
  54613. if (self.isIOS) {
  54614. setTimeout(self.resize, 100);
  54615. } else {
  54616. self.resize();
  54617. }
  54618. });
  54619. this.play();
  54620. // Add to scene index.
  54621. scenes.push(this);
  54622. },
  54623. writable: window.debug
  54624. },
  54625. /**
  54626. * Initialize all systems.
  54627. */
  54628. initSystems: {
  54629. value: function () {
  54630. var name;
  54631. // Initialize camera system first.
  54632. this.initSystem('camera');
  54633. for (name in systems) {
  54634. if (name === 'camera') { continue; }
  54635. this.initSystem(name);
  54636. }
  54637. }
  54638. },
  54639. /**
  54640. * Initialize a system.
  54641. */
  54642. initSystem: {
  54643. value: function (name) {
  54644. if (this.systems[name]) { return; }
  54645. this.systems[name] = new systems[name](this);
  54646. this.systemNames.push(name);
  54647. }
  54648. },
  54649. /**
  54650. * Shut down scene on detach.
  54651. */
  54652. detachedCallback: {
  54653. value: function () {
  54654. // Remove from scene index.
  54655. var sceneIndex = scenes.indexOf(this);
  54656. scenes.splice(sceneIndex, 1);
  54657. window.removeEventListener('vrdisplaypresentchange', this.onVRPresentChangeBound);
  54658. window.removeEventListener('vrdisplayactivate', this.enterVRBound);
  54659. window.removeEventListener('vrdisplaydeactivate', this.exitVRBound);
  54660. window.removeEventListener('vrdisplayconnect', this.enterVRBound);
  54661. window.removeEventListener('vrdisplaydisconnect', this.exitVRTrueBound);
  54662. window.removeEventListener('vrdisplaypointerrestricted', this.pointerRestrictedBound);
  54663. window.removeEventListener('vrdisplaypointerunrestricted', this.pointerUnrestrictedBound);
  54664. window.removeEventListener('sessionend', this.resize);
  54665. }
  54666. },
  54667. /**
  54668. * Add ticks and tocks.
  54669. *
  54670. * @param {object} behavior - A component.
  54671. */
  54672. addBehavior: {
  54673. value: function (behavior) {
  54674. var behaviorArr;
  54675. var behaviors = this.behaviors;
  54676. var behaviorType;
  54677. // Check if behavior has tick and/or tock and add the behavior to the appropriate list.
  54678. for (behaviorType in behaviors) {
  54679. if (!behavior[behaviorType]) { continue; }
  54680. behaviorArr = this.behaviors[behaviorType];
  54681. if (behaviorArr.indexOf(behavior) === -1) {
  54682. behaviorArr.push(behavior);
  54683. }
  54684. }
  54685. }
  54686. },
  54687. /**
  54688. * For tests.
  54689. */
  54690. getPointerLockElement: {
  54691. value: function () {
  54692. return document.pointerLockElement;
  54693. },
  54694. writable: window.debug
  54695. },
  54696. /**
  54697. * For tests.
  54698. */
  54699. checkHeadsetConnected: {
  54700. value: utils.device.checkHeadsetConnected,
  54701. writable: window.debug
  54702. },
  54703. enterAR: {
  54704. value: function () {
  54705. if (!this.hasWebXR) {
  54706. throw new Error('Failed to enter AR mode, WebXR not supported.');
  54707. }
  54708. this.enterVR(true);
  54709. }
  54710. },
  54711. /**
  54712. * Call `requestPresent` if WebVR or WebVR polyfill.
  54713. * Call `requestFullscreen` on desktop.
  54714. * Handle events, states, fullscreen styles.
  54715. *
  54716. * @param {bool?} useAR - if true, try immersive-ar mode
  54717. * @returns {Promise}
  54718. */
  54719. enterVR: {
  54720. value: function (useAR) {
  54721. var self = this;
  54722. var vrDisplay;
  54723. var vrManager = self.renderer.xr;
  54724. // Don't enter VR if already in VR.
  54725. if (this.is('vr-mode')) { return Promise.resolve('Already in VR.'); }
  54726. // Has VR.
  54727. if (this.checkHeadsetConnected() || this.isMobile) {
  54728. vrManager.enabled = true;
  54729. if (this.hasWebXR) {
  54730. // XR API.
  54731. if (this.xrSession) {
  54732. this.xrSession.removeEventListener('end', this.exitVRBound);
  54733. }
  54734. var refspace = this.sceneEl.systems.webxr.sessionReferenceSpaceType;
  54735. vrManager.setReferenceSpaceType(refspace);
  54736. var xrMode = useAR ? 'immersive-ar' : 'immersive-vr';
  54737. var xrInit = this.sceneEl.systems.webxr.sessionConfiguration;
  54738. navigator.xr.requestSession(xrMode, xrInit).then(
  54739. function requestSuccess (xrSession) {
  54740. self.xrSession = xrSession;
  54741. vrManager.setSession(xrSession);
  54742. xrSession.addEventListener('end', self.exitVRBound);
  54743. if (useAR) {
  54744. self.addState('ar-mode');
  54745. }
  54746. enterVRSuccess();
  54747. });
  54748. } else {
  54749. vrDisplay = utils.device.getVRDisplay();
  54750. vrManager.setDevice(vrDisplay);
  54751. if (vrDisplay.isPresenting &&
  54752. !window.hasNativeWebVRImplementation) {
  54753. enterVRSuccess();
  54754. return Promise.resolve();
  54755. }
  54756. var rendererSystem = this.getAttribute('renderer');
  54757. var presentationAttributes = {
  54758. highRefreshRate: rendererSystem.highRefreshRate,
  54759. foveationLevel: rendererSystem.foveationLevel
  54760. };
  54761. return vrDisplay.requestPresent([{
  54762. source: this.canvas,
  54763. attributes: presentationAttributes
  54764. }]).then(enterVRSuccess, enterVRFailure);
  54765. }
  54766. return Promise.resolve();
  54767. }
  54768. // No VR.
  54769. enterVRSuccess();
  54770. return Promise.resolve();
  54771. // Callback that happens on enter VR success or enter fullscreen (any API).
  54772. function enterVRSuccess () {
  54773. // vrdisplaypresentchange fires only once when the first requestPresent is completed;
  54774. // the first requestPresent could be called from ondisplayactivate and there is no way
  54775. // to setup everything from there. Thus, we need to emulate another vrdisplaypresentchange
  54776. // for the actual requestPresent. Need to make sure there are no issues with firing the
  54777. // vrdisplaypresentchange multiple times.
  54778. var event;
  54779. if (window.hasNativeWebVRImplementation && !window.hasNativeWebXRImplementation) {
  54780. event = new CustomEvent('vrdisplaypresentchange', {detail: {display: utils.device.getVRDisplay()}});
  54781. window.dispatchEvent(event);
  54782. }
  54783. self.addState('vr-mode');
  54784. self.emit('enter-vr', {target: self});
  54785. // Lock to landscape orientation on mobile.
  54786. if (!isWebXRAvailable && self.isMobile && screen.orientation && screen.orientation.lock) {
  54787. screen.orientation.lock('landscape');
  54788. }
  54789. self.addFullScreenStyles();
  54790. // On mobile, the polyfill handles fullscreen.
  54791. // TODO: 07/16 Chromium builds break when `requestFullscreen`ing on a canvas
  54792. // that we are also `requestPresent`ing. Until then, don't fullscreen if headset
  54793. // connected.
  54794. if (!self.isMobile && !self.checkHeadsetConnected()) {
  54795. requestFullscreen(self.canvas);
  54796. }
  54797. self.renderer.setAnimationLoop(self.render);
  54798. self.resize();
  54799. }
  54800. function enterVRFailure (err) {
  54801. if (err && err.message) {
  54802. throw new Error('Failed to enter VR mode (`requestPresent`): ' + err.message);
  54803. } else {
  54804. throw new Error('Failed to enter VR mode (`requestPresent`).');
  54805. }
  54806. }
  54807. },
  54808. writable: true
  54809. },
  54810. /**
  54811. * Call `exitPresent` if WebVR / WebXR or WebVR polyfill.
  54812. * Handle events, states, fullscreen styles.
  54813. *
  54814. * @returns {Promise}
  54815. */
  54816. exitVR: {
  54817. value: function () {
  54818. var self = this;
  54819. var vrDisplay;
  54820. var vrManager = this.renderer.xr;
  54821. // Don't exit VR if not in VR.
  54822. if (!this.is('vr-mode')) { return Promise.resolve('Not in VR.'); }
  54823. // Handle exiting VR if not yet already and in a headset or polyfill.
  54824. if (this.checkHeadsetConnected() || this.isMobile) {
  54825. vrManager.enabled = false;
  54826. vrDisplay = utils.device.getVRDisplay();
  54827. if (this.hasWebXR) {
  54828. this.xrSession.removeEventListener('end', this.exitVRBound);
  54829. // Capture promise to avoid errors.
  54830. this.xrSession.end().then(function () {}, function () {});
  54831. this.xrSession = undefined;
  54832. vrManager.setSession(null);
  54833. } else {
  54834. if (vrDisplay.isPresenting) {
  54835. return vrDisplay.exitPresent().then(exitVRSuccess, exitVRFailure);
  54836. }
  54837. }
  54838. } else {
  54839. exitFullscreen();
  54840. }
  54841. // Handle exiting VR in all other cases (2D fullscreen, external exit VR event).
  54842. exitVRSuccess();
  54843. return Promise.resolve();
  54844. function exitVRSuccess () {
  54845. self.removeState('vr-mode');
  54846. self.removeState('ar-mode');
  54847. // Lock to landscape orientation on mobile.
  54848. if (self.isMobile && screen.orientation && screen.orientation.unlock) {
  54849. screen.orientation.unlock();
  54850. }
  54851. // Exiting VR in embedded mode, no longer need fullscreen styles.
  54852. if (self.hasAttribute('embedded')) { self.removeFullScreenStyles(); }
  54853. self.resize();
  54854. if (self.isIOS) { utils.forceCanvasResizeSafariMobile(self.canvas); }
  54855. self.renderer.setPixelRatio(window.devicePixelRatio);
  54856. self.emit('exit-vr', {target: self});
  54857. }
  54858. function exitVRFailure (err) {
  54859. if (err && err.message) {
  54860. throw new Error('Failed to exit VR mode (`exitPresent`): ' + err.message);
  54861. } else {
  54862. throw new Error('Failed to exit VR mode (`exitPresent`).');
  54863. }
  54864. }
  54865. },
  54866. writable: true
  54867. },
  54868. pointerRestricted: {
  54869. value: function () {
  54870. if (this.canvas) {
  54871. var pointerLockElement = this.getPointerLockElement();
  54872. if (pointerLockElement && pointerLockElement !== this.canvas && document.exitPointerLock) {
  54873. // Recreate pointer lock on the canvas, if taken on another element.
  54874. document.exitPointerLock();
  54875. }
  54876. if (this.canvas.requestPointerLock) {
  54877. this.canvas.requestPointerLock();
  54878. }
  54879. }
  54880. }
  54881. },
  54882. pointerUnrestricted: {
  54883. value: function () {
  54884. var pointerLockElement = this.getPointerLockElement();
  54885. if (pointerLockElement && pointerLockElement === this.canvas && document.exitPointerLock) {
  54886. document.exitPointerLock();
  54887. }
  54888. }
  54889. },
  54890. /**
  54891. * Handle `vrdisplaypresentchange` event for exiting VR through other means than
  54892. * `<ESC>` key. For example, GearVR back button on Oculus Browser.
  54893. */
  54894. onVRPresentChange: {
  54895. value: function (evt) {
  54896. // Polyfill places display inside the detail property
  54897. var display = evt.display || evt.detail.display;
  54898. // Entering VR.
  54899. if (display && display.isPresenting) {
  54900. this.enterVR();
  54901. return;
  54902. }
  54903. // Exiting VR.
  54904. this.exitVR();
  54905. }
  54906. },
  54907. /**
  54908. * Wraps Entity.getAttribute to take into account for systems.
  54909. * If system exists, then return system data rather than possible component data.
  54910. */
  54911. getAttribute: {
  54912. value: function (attr) {
  54913. var system = this.systems[attr];
  54914. if (system) { return system.data; }
  54915. return AEntity.prototype.getAttribute.call(this, attr);
  54916. }
  54917. },
  54918. /**
  54919. * `getAttribute` used to be `getDOMAttribute` and `getComputedAttribute` used to be
  54920. * what `getAttribute` is now. Now legacy code.
  54921. */
  54922. getComputedAttribute: {
  54923. value: function (attr) {
  54924. warn('`getComputedAttribute` is deprecated. Use `getAttribute` instead.');
  54925. this.getAttribute(attr);
  54926. }
  54927. },
  54928. /**
  54929. * Wraps Entity.getDOMAttribute to take into account for systems.
  54930. * If system exists, then return system data rather than possible component data.
  54931. */
  54932. getDOMAttribute: {
  54933. value: function (attr) {
  54934. var system = this.systems[attr];
  54935. if (system) { return system.data; }
  54936. return AEntity.prototype.getDOMAttribute.call(this, attr);
  54937. }
  54938. },
  54939. /**
  54940. * Wrap Entity.setAttribute to take into account for systems.
  54941. * If system exists, then skip component initialization checks and do a normal
  54942. * setAttribute.
  54943. */
  54944. setAttribute: {
  54945. value: function (attr, value, componentPropValue) {
  54946. var system = this.systems[attr];
  54947. if (system) {
  54948. ANode.prototype.setAttribute.call(this, attr, value);
  54949. system.updateProperties(value);
  54950. return;
  54951. }
  54952. AEntity.prototype.setAttribute.call(this, attr, value, componentPropValue);
  54953. }
  54954. },
  54955. /**
  54956. * @param {object} behavior - A component.
  54957. */
  54958. removeBehavior: {
  54959. value: function (behavior) {
  54960. var behaviorArr;
  54961. var behaviorType;
  54962. var behaviors = this.behaviors;
  54963. var index;
  54964. // Check if behavior has tick and/or tock and remove the behavior from the appropriate
  54965. // array.
  54966. for (behaviorType in behaviors) {
  54967. if (!behavior[behaviorType]) { continue; }
  54968. behaviorArr = this.behaviors[behaviorType];
  54969. index = behaviorArr.indexOf(behavior);
  54970. if (index !== -1) { behaviorArr.splice(index, 1); }
  54971. }
  54972. }
  54973. },
  54974. resize: {
  54975. value: function () {
  54976. var camera = this.camera;
  54977. var canvas = this.canvas;
  54978. var embedded;
  54979. var isVRPresenting;
  54980. var size;
  54981. var isPresenting = this.renderer.xr.isPresenting;
  54982. isVRPresenting = this.renderer.xr.enabled && isPresenting;
  54983. // Do not update renderer, if a camera or a canvas have not been injected.
  54984. // In VR mode, three handles canvas resize based on the dimensions returned by
  54985. // the getEyeParameters function of the WebVR API. These dimensions are independent of
  54986. // the window size, therefore should not be overwritten with the window's width and
  54987. // height, // except when in fullscreen mode.
  54988. if (!camera || !canvas || (this.is('vr-mode') && (this.isMobile || isVRPresenting))) {
  54989. return;
  54990. }
  54991. // Update camera.
  54992. embedded = this.getAttribute('embedded') && !this.is('vr-mode');
  54993. size = getCanvasSize(canvas, embedded, this.maxCanvasSize, this.is('vr-mode'));
  54994. camera.aspect = size.width / size.height;
  54995. camera.updateProjectionMatrix();
  54996. // Notify renderer of size change.
  54997. this.renderer.setSize(size.width, size.height, false);
  54998. this.emit('rendererresize', null, false);
  54999. },
  55000. writable: true
  55001. },
  55002. setupRenderer: {
  55003. value: function () {
  55004. var self = this;
  55005. var renderer;
  55006. var rendererAttr;
  55007. var rendererAttrString;
  55008. var rendererConfig;
  55009. rendererConfig = {
  55010. alpha: true,
  55011. antialias: !isMobile,
  55012. canvas: this.canvas,
  55013. logarithmicDepthBuffer: false,
  55014. powerPreference: 'high-performance'
  55015. };
  55016. this.maxCanvasSize = {height: 1920, width: 1920};
  55017. if (this.hasAttribute('renderer')) {
  55018. rendererAttrString = this.getAttribute('renderer');
  55019. rendererAttr = utils.styleParser.parse(rendererAttrString);
  55020. if (rendererAttr.precision) {
  55021. rendererConfig.precision = rendererAttr.precision + 'p';
  55022. }
  55023. if (rendererAttr.antialias && rendererAttr.antialias !== 'auto') {
  55024. rendererConfig.antialias = rendererAttr.antialias === 'true';
  55025. }
  55026. if (rendererAttr.logarithmicDepthBuffer && rendererAttr.logarithmicDepthBuffer !== 'auto') {
  55027. rendererConfig.logarithmicDepthBuffer = rendererAttr.logarithmicDepthBuffer === 'true';
  55028. }
  55029. if (rendererAttr.alpha) {
  55030. rendererConfig.alpha = rendererAttr.alpha === 'true';
  55031. }
  55032. this.maxCanvasSize = {
  55033. width: rendererAttr.maxCanvasWidth
  55034. ? parseInt(rendererAttr.maxCanvasWidth)
  55035. : this.maxCanvasSize.width,
  55036. height: rendererAttr.maxCanvasHeight
  55037. ? parseInt(rendererAttr.maxCanvasHeight)
  55038. : this.maxCanvasSize.height
  55039. };
  55040. }
  55041. renderer = this.renderer = new THREE.WebGLRenderer(rendererConfig);
  55042. renderer.setPixelRatio(window.devicePixelRatio);
  55043. renderer.sortObjects = false;
  55044. if (this.camera) { renderer.xr.setPoseTarget(this.camera.el.object3D); }
  55045. this.addEventListener('camera-set-active', function () {
  55046. renderer.xr.setPoseTarget(self.camera.el.object3D);
  55047. });
  55048. loadingScreen.setup(this, getCanvasSize);
  55049. },
  55050. writable: window.debug
  55051. },
  55052. /**
  55053. * Handler attached to elements to help scene know when to kick off.
  55054. * Scene waits for all entities to load.
  55055. */
  55056. play: {
  55057. value: function () {
  55058. var self = this;
  55059. var sceneEl = this;
  55060. if (this.renderStarted) {
  55061. AEntity.prototype.play.call(this);
  55062. return;
  55063. }
  55064. this.addEventListener('loaded', function () {
  55065. var renderer = this.renderer;
  55066. var vrDisplay;
  55067. var vrManager = this.renderer.xr;
  55068. AEntity.prototype.play.call(this); // .play() *before* render.
  55069. // WebXR Immersive navigation handler.
  55070. if (this.hasWebXR && navigator.xr.addEventListener) {
  55071. navigator.xr.addEventListener('sessiongranted', function () { sceneEl.enterVR(); });
  55072. }
  55073. if (sceneEl.renderStarted) { return; }
  55074. sceneEl.resize();
  55075. // Kick off render loop.
  55076. if (sceneEl.renderer) {
  55077. if (window.performance) { window.performance.mark('render-started'); }
  55078. loadingScreen.remove();
  55079. vrDisplay = utils.device.getVRDisplay();
  55080. if (vrDisplay && vrDisplay.isPresenting) {
  55081. vrManager.setDevice(vrDisplay);
  55082. vrManager.enabled = true;
  55083. sceneEl.enterVR();
  55084. }
  55085. renderer.setAnimationLoop(this.render);
  55086. sceneEl.renderStarted = true;
  55087. sceneEl.emit('renderstart');
  55088. }
  55089. });
  55090. // setTimeout to wait for all nodes to attach and run their callbacks.
  55091. setTimeout(function () {
  55092. AEntity.prototype.load.call(self);
  55093. });
  55094. }
  55095. },
  55096. /**
  55097. * Wrap `updateComponent` to not initialize the component if the component has a system
  55098. * (aframevr/aframe#2365).
  55099. */
  55100. updateComponent: {
  55101. value: function (componentName) {
  55102. if (componentName in systems) { return; }
  55103. AEntity.prototype.updateComponent.apply(this, arguments);
  55104. }
  55105. },
  55106. /**
  55107. * Behavior-updater meant to be called from scene render.
  55108. * Abstracted to a different function to facilitate unit testing (`scene.tick()`) without
  55109. * needing to render.
  55110. */
  55111. tick: {
  55112. value: function (time, timeDelta) {
  55113. var i;
  55114. var systems = this.systems;
  55115. // Components.
  55116. for (i = 0; i < this.behaviors.tick.length; i++) {
  55117. if (!this.behaviors.tick[i].el.isPlaying) { continue; }
  55118. this.behaviors.tick[i].tick(time, timeDelta);
  55119. }
  55120. // Systems.
  55121. for (i = 0; i < this.systemNames.length; i++) {
  55122. if (!systems[this.systemNames[i]].tick) { continue; }
  55123. systems[this.systemNames[i]].tick(time, timeDelta);
  55124. }
  55125. }
  55126. },
  55127. /**
  55128. * Behavior-updater meant to be called after scene render for post processing purposes.
  55129. * Abstracted to a different function to facilitate unit testing (`scene.tock()`) without
  55130. * needing to render.
  55131. */
  55132. tock: {
  55133. value: function (time, timeDelta, camera) {
  55134. var i;
  55135. var systems = this.systems;
  55136. // Components.
  55137. for (i = 0; i < this.behaviors.tock.length; i++) {
  55138. if (!this.behaviors.tock[i].el.isPlaying) { continue; }
  55139. this.behaviors.tock[i].tock(time, timeDelta, camera);
  55140. }
  55141. // Systems.
  55142. for (i = 0; i < this.systemNames.length; i++) {
  55143. if (!systems[this.systemNames[i]].tock) { continue; }
  55144. systems[this.systemNames[i]].tock(time, timeDelta, camera);
  55145. }
  55146. }
  55147. },
  55148. /**
  55149. * The render loop.
  55150. *
  55151. * Updates animations.
  55152. * Updates behaviors.
  55153. * Renders with request animation frame.
  55154. */
  55155. render: {
  55156. value: function (time, frame) {
  55157. var renderer = this.renderer;
  55158. this.frame = frame;
  55159. this.delta = this.clock.getDelta() * 1000;
  55160. this.time = this.clock.elapsedTime * 1000;
  55161. if (this.isPlaying) { this.tick(this.time, this.delta); }
  55162. var savedBackground = null;
  55163. if (this.is('ar-mode')) {
  55164. // In AR mode, don't render the default background. Hide it, then
  55165. // restore it again after rendering.
  55166. savedBackground = this.object3D.background;
  55167. this.object3D.background = null;
  55168. }
  55169. renderer.render(this.object3D, this.camera);
  55170. if (savedBackground) {
  55171. this.object3D.background = savedBackground;
  55172. }
  55173. },
  55174. writable: true
  55175. }
  55176. })
  55177. });
  55178. /**
  55179. * Return the canvas size where the scene will be rendered.
  55180. * Will be always the window size except when the scene is embedded.
  55181. * The parent size (less than max size) will be returned in that case.
  55182. *
  55183. * @param {object} canvasEl - the canvas element
  55184. * @param {boolean} embedded - Is the scene embedded?
  55185. * @param {object} max - Max size parameters
  55186. * @param {boolean} isVR - If in VR
  55187. */
  55188. function getCanvasSize (canvasEl, embedded, maxSize, isVR) {
  55189. if (embedded) {
  55190. return {
  55191. height: canvasEl.parentElement.offsetHeight,
  55192. width: canvasEl.parentElement.offsetWidth
  55193. };
  55194. }
  55195. return getMaxSize(maxSize, isVR);
  55196. }
  55197. /**
  55198. * Return the canvas size. Will be the window size unless that size is greater than the
  55199. * maximum size (1920x1920 by default). The constrained size will be returned in that case,
  55200. * maintaining aspect ratio
  55201. *
  55202. * @param {object} maxSize - Max size parameters (width and height).
  55203. * @param {boolean} isVR - If in VR.
  55204. * @returns {object} Width and height.
  55205. */
  55206. function getMaxSize (maxSize, isVR) {
  55207. var aspectRatio;
  55208. var size;
  55209. var pixelRatio = window.devicePixelRatio;
  55210. size = {height: document.body.offsetHeight, width: document.body.offsetWidth};
  55211. if (!maxSize || isVR || (maxSize.width === -1 && maxSize.height === -1)) {
  55212. return size;
  55213. }
  55214. if (size.width * pixelRatio < maxSize.width &&
  55215. size.height * pixelRatio < maxSize.height) {
  55216. return size;
  55217. }
  55218. aspectRatio = size.width / size.height;
  55219. if ((size.width * pixelRatio) > maxSize.width && maxSize.width !== -1) {
  55220. size.width = Math.round(maxSize.width / pixelRatio);
  55221. size.height = Math.round(maxSize.width / aspectRatio / pixelRatio);
  55222. }
  55223. if ((size.height * pixelRatio) > maxSize.height && maxSize.height !== -1) {
  55224. size.height = Math.round(maxSize.height / pixelRatio);
  55225. size.width = Math.round(maxSize.height * aspectRatio / pixelRatio);
  55226. }
  55227. return size;
  55228. }
  55229. function requestFullscreen (canvas) {
  55230. var requestFullscreen =
  55231. canvas.requestFullscreen ||
  55232. canvas.webkitRequestFullscreen ||
  55233. canvas.mozRequestFullScreen || // The capitalized `S` is not a typo.
  55234. canvas.msRequestFullscreen;
  55235. // Hide navigation buttons on Android.
  55236. requestFullscreen.apply(canvas, [{navigationUI: 'hide'}]);
  55237. }
  55238. function exitFullscreen () {
  55239. var fullscreenEl =
  55240. document.fullscreenElement ||
  55241. document.webkitFullscreenElement ||
  55242. document.mozFullScreenElement;
  55243. if (!fullscreenEl) { return; }
  55244. if (document.exitFullscreen) {
  55245. document.exitFullscreen();
  55246. } else if (document.mozCancelFullScreen) {
  55247. document.mozCancelFullScreen();
  55248. } else if (document.webkitExitFullscreen) {
  55249. document.webkitExitFullscreen();
  55250. }
  55251. }
  55252. function setupCanvas (sceneEl) {
  55253. var canvasEl;
  55254. canvasEl = document.createElement('canvas');
  55255. canvasEl.classList.add('a-canvas');
  55256. // Mark canvas as provided/injected by A-Frame.
  55257. canvasEl.dataset.aframeCanvas = true;
  55258. sceneEl.appendChild(canvasEl);
  55259. document.addEventListener('fullscreenchange', onFullScreenChange);
  55260. document.addEventListener('mozfullscreenchange', onFullScreenChange);
  55261. document.addEventListener('webkitfullscreenchange', onFullScreenChange);
  55262. document.addEventListener('MSFullscreenChange', onFullScreenChange);
  55263. // Prevent overscroll on mobile.
  55264. canvasEl.addEventListener('touchmove', function (event) { event.preventDefault(); });
  55265. // Set canvas on scene.
  55266. sceneEl.canvas = canvasEl;
  55267. sceneEl.emit('render-target-loaded', {target: canvasEl});
  55268. // For unknown reasons a synchronous resize does not work on desktop when
  55269. // entering/exiting fullscreen.
  55270. setTimeout(bind(sceneEl.resize, sceneEl), 0);
  55271. function onFullScreenChange () {
  55272. var fullscreenEl =
  55273. document.fullscreenElement ||
  55274. document.mozFullScreenElement ||
  55275. document.webkitFullscreenElement;
  55276. // No fullscren element === exit fullscreen
  55277. if (!fullscreenEl) { sceneEl.exitVR(); }
  55278. document.activeElement.blur();
  55279. document.body.focus();
  55280. }
  55281. }
  55282. module.exports.setupCanvas = setupCanvas; // For testing.
  55283. },{"../../lib/three":176,"../../utils/":202,"../a-entity":124,"../a-node":126,"../a-register-element":127,"../system":139,"./loadingScreen":132,"./metaTags":133,"./postMessage":134,"./scenes":135,"./wakelock":136}],132:[function(_dereq_,module,exports){
  55284. /* global THREE */
  55285. var utils = _dereq_('../../utils/');
  55286. var styleParser = utils.styleParser;
  55287. var sceneEl;
  55288. var titleEl;
  55289. var getSceneCanvasSize;
  55290. var ATTR_NAME = 'loading-screen';
  55291. var LOADER_TITLE_CLASS = 'a-loader-title';
  55292. module.exports.setup = function setup (el, getCanvasSize) {
  55293. sceneEl = el;
  55294. getSceneCanvasSize = getCanvasSize;
  55295. var loaderAttribute = sceneEl.hasAttribute(ATTR_NAME) ? styleParser.parse(sceneEl.getAttribute(ATTR_NAME)) : undefined;
  55296. var dotsColor = loaderAttribute && loaderAttribute.dotsColor || 'white';
  55297. var backgroundColor = loaderAttribute && loaderAttribute.backgroundColor || '#24CAFF';
  55298. var loaderEnabled = loaderAttribute === undefined || loaderAttribute.enabled === 'true' || loaderAttribute.enabled === undefined; // true default
  55299. var loaderScene;
  55300. var sphereGeometry;
  55301. var sphereMaterial;
  55302. var sphereMesh1;
  55303. var sphereMesh2;
  55304. var sphereMesh3;
  55305. var camera;
  55306. var clock;
  55307. var time;
  55308. var render;
  55309. if (!loaderEnabled) { return; }
  55310. // Setup Scene.
  55311. loaderScene = new THREE.Scene();
  55312. sphereGeometry = new THREE.SphereGeometry(0.20, 36, 18, 0, 2 * Math.PI, 0, Math.PI);
  55313. sphereMaterial = new THREE.MeshBasicMaterial({color: dotsColor});
  55314. sphereMesh1 = new THREE.Mesh(sphereGeometry, sphereMaterial);
  55315. sphereMesh2 = sphereMesh1.clone();
  55316. sphereMesh3 = sphereMesh1.clone();
  55317. camera = new THREE.PerspectiveCamera(80, window.innerWidth / window.innerHeight, 0.0005, 10000);
  55318. clock = new THREE.Clock();
  55319. time = 0;
  55320. render = function () {
  55321. sceneEl.renderer.render(loaderScene, camera);
  55322. time = clock.getElapsedTime() % 4;
  55323. sphereMesh1.visible = time >= 1;
  55324. sphereMesh2.visible = time >= 2;
  55325. sphereMesh3.visible = time >= 3;
  55326. };
  55327. loaderScene.background = new THREE.Color(backgroundColor);
  55328. loaderScene.add(camera);
  55329. sphereMesh1.position.set(-1, 0, -15);
  55330. sphereMesh2.position.set(0, 0, -15);
  55331. sphereMesh3.position.set(1, 0, -15);
  55332. camera.add(sphereMesh1);
  55333. camera.add(sphereMesh2);
  55334. camera.add(sphereMesh3);
  55335. setupTitle();
  55336. // Delay 200ms to avoid loader flashes.
  55337. setTimeout(function () {
  55338. if (sceneEl.hasLoaded) { return; }
  55339. resize(camera);
  55340. titleEl.style.display = 'block';
  55341. window.addEventListener('resize', function () { resize(camera); });
  55342. sceneEl.renderer.setAnimationLoop(render);
  55343. }, 200);
  55344. };
  55345. module.exports.remove = function remove () {
  55346. window.removeEventListener('resize', resize);
  55347. if (!titleEl) { return; }
  55348. // Hide title.
  55349. titleEl.style.display = 'none';
  55350. };
  55351. function resize (camera) {
  55352. var embedded = sceneEl.hasAttribute('embedded');
  55353. var size = getSceneCanvasSize(sceneEl.canvas, embedded, sceneEl.maxCanvasSize, sceneEl.is('vr-mode'));
  55354. camera.aspect = size.width / size.height;
  55355. camera.updateProjectionMatrix();
  55356. // Notify renderer of size change.
  55357. sceneEl.renderer.setSize(size.width, size.height, false);
  55358. }
  55359. function setupTitle () {
  55360. titleEl = document.createElement('div');
  55361. titleEl.className = LOADER_TITLE_CLASS;
  55362. titleEl.innerHTML = document.title;
  55363. titleEl.style.display = 'none';
  55364. sceneEl.appendChild(titleEl);
  55365. }
  55366. },{"../../utils/":202}],133:[function(_dereq_,module,exports){
  55367. var constants = _dereq_('../../constants/');
  55368. var extend = _dereq_('../../utils').extend;
  55369. var MOBILE_HEAD_TAGS = module.exports.MOBILE_HEAD_TAGS = [
  55370. 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'}),
  55371. // W3C-standardised meta tags.
  55372. Meta({name: 'mobile-web-app-capable', content: 'yes'}),
  55373. Meta({name: 'theme-color', content: 'black'})
  55374. ];
  55375. var MOBILE_IOS_HEAD_TAGS = [
  55376. // iOS-specific meta tags for fullscreen when pinning to homescreen.
  55377. Meta({name: 'apple-mobile-web-app-capable', content: 'yes'}),
  55378. Meta({name: 'apple-mobile-web-app-status-bar-style', content: 'black'}),
  55379. Link({rel: 'apple-touch-icon', href: 'https://aframe.io/images/aframe-logo-152.png'})
  55380. ];
  55381. function Meta (attrs) {
  55382. return {
  55383. tagName: 'meta',
  55384. attributes: attrs,
  55385. exists: function () { return document.querySelector('meta[name="' + attrs.name + '"]'); }
  55386. };
  55387. }
  55388. function Link (attrs) {
  55389. return {
  55390. tagName: 'link',
  55391. attributes: attrs,
  55392. exists: function () { return document.querySelector('link[rel="' + attrs.rel + '"]'); }
  55393. };
  55394. }
  55395. /**
  55396. * Injects the necessary metatags in the document for mobile support:
  55397. * 1. Prevent the user to zoom in the document.
  55398. * 2. Ensure that window.innerWidth and window.innerHeight have the correct
  55399. * values and the canvas is properly scaled.
  55400. * 3. To allow fullscreen mode when pinning a web app on the home screen on
  55401. * iOS.
  55402. * Adapted from https://www.reddit.com/r/web_design/comments/3la04p/
  55403. *
  55404. * @param {object} scene - Scene element
  55405. * @returns {Array}
  55406. */
  55407. module.exports.inject = function injectHeadTags (scene) {
  55408. var headEl = document.head;
  55409. var headScriptEl = headEl.querySelector('script');
  55410. var tag;
  55411. var headTags = [];
  55412. MOBILE_HEAD_TAGS.forEach(createAndInjectTag);
  55413. if (scene.isIOS) {
  55414. MOBILE_IOS_HEAD_TAGS.forEach(createAndInjectTag);
  55415. }
  55416. return headTags;
  55417. function createAndInjectTag (tagObj) {
  55418. if (!tagObj || tagObj.exists()) { return; }
  55419. tag = createTag(tagObj);
  55420. if (!tag) { return; }
  55421. if (headScriptEl) {
  55422. headScriptEl.parentNode.insertBefore(tag, headScriptEl);
  55423. } else {
  55424. headEl.appendChild(tag);
  55425. }
  55426. headTags.push(tag);
  55427. }
  55428. };
  55429. function createTag (tagObj) {
  55430. if (!tagObj || !tagObj.tagName) { return; }
  55431. var meta = document.createElement(tagObj.tagName);
  55432. meta.setAttribute(constants.AFRAME_INJECTED, '');
  55433. return extend(meta, tagObj.attributes);
  55434. }
  55435. },{"../../constants/":120,"../../utils":202}],134:[function(_dereq_,module,exports){
  55436. var bind = _dereq_('../../utils/bind');
  55437. var isIframed = _dereq_('../../utils/').isIframed;
  55438. /**
  55439. * Provides a post message API for scenes contained
  55440. * in an iframe.
  55441. */
  55442. module.exports = function initPostMessageAPI (scene) {
  55443. // Handles fullscreen behavior when inside an iframe.
  55444. if (!isIframed()) { return; }
  55445. // postMessage API handler
  55446. window.addEventListener('message', bind(postMessageAPIHandler, scene));
  55447. };
  55448. function postMessageAPIHandler (event) {
  55449. var scene = this;
  55450. if (!event.data) { return; }
  55451. switch (event.data.type) {
  55452. case 'vr': {
  55453. switch (event.data.data) {
  55454. case 'enter':
  55455. scene.enterVR();
  55456. break;
  55457. case 'exit':
  55458. scene.exitVR();
  55459. break;
  55460. }
  55461. }
  55462. }
  55463. }
  55464. },{"../../utils/":202,"../../utils/bind":196}],135:[function(_dereq_,module,exports){
  55465. /*
  55466. Scene index for keeping track of created scenes.
  55467. */
  55468. module.exports = [];
  55469. },{}],136:[function(_dereq_,module,exports){
  55470. var Wakelock = _dereq_('../../../vendor/wakelock/wakelock');
  55471. module.exports = function initWakelock (scene) {
  55472. if (!scene.isMobile) { return; }
  55473. var wakelock = scene.wakelock = new Wakelock();
  55474. scene.addEventListener('enter-vr', function () { wakelock.request(); });
  55475. scene.addEventListener('exit-vr', function () { wakelock.release(); });
  55476. };
  55477. },{"../../../vendor/wakelock/wakelock":216}],137:[function(_dereq_,module,exports){
  55478. var utils = _dereq_('../utils/');
  55479. var PropertyTypes = _dereq_('./propertyTypes');
  55480. var debug = utils.debug;
  55481. var isValidDefaultValue = PropertyTypes.isValidDefaultValue;
  55482. var propertyTypes = PropertyTypes.propertyTypes;
  55483. var warn = debug('core:schema:warn');
  55484. /**
  55485. * A schema is classified as a schema for a single property if:
  55486. * - `type` is defined on the schema as a string.
  55487. * - OR `default` is defined on the schema, as a reserved keyword.
  55488. * - OR schema is empty.
  55489. */
  55490. function isSingleProperty (schema) {
  55491. if ('type' in schema) {
  55492. return typeof schema.type === 'string';
  55493. }
  55494. return 'default' in schema;
  55495. }
  55496. module.exports.isSingleProperty = isSingleProperty;
  55497. /**
  55498. * Build step to schema to use `type` to inject default value, parser, and stringifier.
  55499. *
  55500. * @param {object} schema
  55501. * @param {string} componentName
  55502. * @returns {object} Schema.
  55503. */
  55504. module.exports.process = function (schema, componentName) {
  55505. var propName;
  55506. // For single property schema, run processPropDefinition over the whole schema.
  55507. if (isSingleProperty(schema)) {
  55508. return processPropertyDefinition(schema, componentName);
  55509. }
  55510. // For multi-property schema, run processPropDefinition over each property definition.
  55511. for (propName in schema) {
  55512. schema[propName] = processPropertyDefinition(schema[propName], componentName);
  55513. }
  55514. return schema;
  55515. };
  55516. /**
  55517. * Inject default value, parser, stringifier for single property.
  55518. *
  55519. * @param {object} propDefinition
  55520. * @param {string} componentName
  55521. */
  55522. function processPropertyDefinition (propDefinition, componentName) {
  55523. var defaultVal = propDefinition.default;
  55524. var isCustomType;
  55525. var propType;
  55526. var typeName = propDefinition.type;
  55527. // Type inference.
  55528. if (!propDefinition.type) {
  55529. if (defaultVal !== undefined &&
  55530. (typeof defaultVal === 'boolean' || typeof defaultVal === 'number')) {
  55531. // Type inference.
  55532. typeName = typeof defaultVal;
  55533. } else if (Array.isArray(defaultVal)) {
  55534. typeName = 'array';
  55535. } else {
  55536. // Fall back to string.
  55537. typeName = 'string';
  55538. }
  55539. } else if (propDefinition.type === 'bool') {
  55540. typeName = 'boolean';
  55541. } else if (propDefinition.type === 'float') {
  55542. typeName = 'number';
  55543. }
  55544. propType = propertyTypes[typeName];
  55545. if (!propType) {
  55546. warn('Unknown property type for component `' + componentName + '`: ' + typeName);
  55547. }
  55548. // Fill in parse and stringify using property types.
  55549. isCustomType = !!propDefinition.parse;
  55550. propDefinition.parse = propDefinition.parse || propType.parse;
  55551. propDefinition.stringify = propDefinition.stringify || propType.stringify;
  55552. // Fill in type name.
  55553. propDefinition.type = typeName;
  55554. // Check that default value exists.
  55555. if ('default' in propDefinition) {
  55556. // Check that default values are valid.
  55557. if (!isCustomType && !isValidDefaultValue(typeName, defaultVal)) {
  55558. warn('Default value `' + defaultVal + '` does not match type `' + typeName +
  55559. '` in component `' + componentName + '`');
  55560. }
  55561. } else {
  55562. // Fill in default value.
  55563. propDefinition.default = propType.default;
  55564. }
  55565. return propDefinition;
  55566. }
  55567. module.exports.processPropertyDefinition = processPropertyDefinition;
  55568. /**
  55569. * Parse propData using schema. Use default values if not existing in propData.
  55570. *
  55571. * @param {object} propData - Unparsed properties.
  55572. * @param {object} schema - Property types definition.
  55573. * @param {boolean} getPartialData - Whether to return full component data or just the data
  55574. * with keys in `propData`.
  55575. * @param {string } componentName - Name of the component, used for the property warning.
  55576. * @param {boolean} silent - Suppress warning messages.
  55577. */
  55578. module.exports.parseProperties = (function () {
  55579. var propNames = [];
  55580. return function (propData, schema, getPartialData, componentName, silent) {
  55581. var i;
  55582. var propName;
  55583. var propDefinition;
  55584. var propValue;
  55585. propNames.length = 0;
  55586. for (propName in (getPartialData ? propData : schema)) {
  55587. if (getPartialData && propData[propName] === undefined) { continue; }
  55588. propNames.push(propName);
  55589. }
  55590. if (propData === null || typeof propData !== 'object') { return propData; }
  55591. // Validation errors.
  55592. for (propName in propData) {
  55593. if (propData[propName] !== undefined && !schema[propName] && !silent) {
  55594. warn('Unknown property `' + propName +
  55595. '` for component/system `' + componentName + '`.');
  55596. }
  55597. }
  55598. for (i = 0; i < propNames.length; i++) {
  55599. propName = propNames[i];
  55600. propDefinition = schema[propName];
  55601. propValue = propData[propName];
  55602. if (!(schema[propName])) { return; }
  55603. propData[propName] = parseProperty(propValue, propDefinition);
  55604. }
  55605. return propData;
  55606. };
  55607. })();
  55608. /**
  55609. * Deserialize a single property.
  55610. */
  55611. function parseProperty (value, propDefinition) {
  55612. // Use default value if value is falsy.
  55613. if (value === undefined || value === null || value === '') {
  55614. value = propDefinition.default;
  55615. if (Array.isArray(value)) { value = value.slice(); }
  55616. }
  55617. // Invoke property type parser.
  55618. return propDefinition.parse(value, propDefinition.default);
  55619. }
  55620. module.exports.parseProperty = parseProperty;
  55621. /**
  55622. * Serialize a group of properties.
  55623. */
  55624. module.exports.stringifyProperties = function (propData, schema) {
  55625. var propName;
  55626. var propDefinition;
  55627. var propValue;
  55628. var stringifiedData = {};
  55629. var value;
  55630. for (propName in propData) {
  55631. propDefinition = schema[propName];
  55632. propValue = propData[propName];
  55633. value = propValue;
  55634. if (typeof value === 'object') {
  55635. value = stringifyProperty(propValue, propDefinition);
  55636. if (!propDefinition) { warn('Unknown component property: ' + propName); }
  55637. }
  55638. stringifiedData[propName] = value;
  55639. }
  55640. return stringifiedData;
  55641. };
  55642. /**
  55643. * Serialize a single property.
  55644. */
  55645. function stringifyProperty (value, propDefinition) {
  55646. // This function stringifies but it's used in a context where
  55647. // there's always second stringification pass. By returning the original
  55648. // value when it's not an object we save one unnecessary call
  55649. // to JSON.stringify.
  55650. if (typeof value !== 'object') { return value; }
  55651. // if there's no schema for the property we use standar JSON stringify
  55652. if (!propDefinition || value === null) { return JSON.stringify(value); }
  55653. return propDefinition.stringify(value);
  55654. }
  55655. module.exports.stringifyProperty = stringifyProperty;
  55656. },{"../utils/":202,"./propertyTypes":130}],138:[function(_dereq_,module,exports){
  55657. var schema = _dereq_('./schema');
  55658. var processSchema = schema.process;
  55659. var shaders = module.exports.shaders = {}; // Keep track of registered shaders.
  55660. var shaderNames = module.exports.shaderNames = []; // Keep track of the names of registered shaders.
  55661. var THREE = _dereq_('../lib/three');
  55662. var utils = _dereq_('../utils');
  55663. // A-Frame properties to three.js uniform types.
  55664. var propertyToThreeMapping = {
  55665. array: 'v3',
  55666. color: 'v3',
  55667. int: 'i',
  55668. number: 'f',
  55669. map: 't',
  55670. time: 'f',
  55671. vec2: 'v2',
  55672. vec3: 'v3',
  55673. vec4: 'v4'
  55674. };
  55675. /**
  55676. * Shader class definition.
  55677. *
  55678. * Shaders extend the material component API so you can create your own library
  55679. * of customized materials
  55680. *
  55681. */
  55682. var Shader = module.exports.Shader = function () {};
  55683. Shader.prototype = {
  55684. /**
  55685. * Contains the type schema and defaults for the data values.
  55686. * Data is coerced into the types of the values of the defaults.
  55687. */
  55688. schema: {},
  55689. vertexShader:
  55690. 'void main() {' +
  55691. 'gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);' +
  55692. '}',
  55693. fragmentShader:
  55694. 'void main() {' +
  55695. 'gl_FragColor = vec4(1.0, 0.0, 1.0, 1.0);' +
  55696. '}',
  55697. /**
  55698. * Init handler. Similar to attachedCallback.
  55699. * Called during shader initialization and is only run once.
  55700. */
  55701. init: function (data) {
  55702. this.attributes = this.initVariables(data, 'attribute');
  55703. this.uniforms = this.initVariables(data, 'uniform');
  55704. this.material = new (this.raw ? THREE.RawShaderMaterial : THREE.ShaderMaterial)({
  55705. // attributes: this.attributes,
  55706. uniforms: this.uniforms,
  55707. vertexShader: this.vertexShader,
  55708. fragmentShader: this.fragmentShader
  55709. });
  55710. return this.material;
  55711. },
  55712. initVariables: function (data, type) {
  55713. var key;
  55714. var schema = this.schema;
  55715. var variables = {};
  55716. var varType;
  55717. for (key in schema) {
  55718. if (schema[key].is !== type) { continue; }
  55719. varType = propertyToThreeMapping[schema[key].type];
  55720. variables[key] = {
  55721. type: varType,
  55722. value: undefined // Let updateVariables handle setting these.
  55723. };
  55724. }
  55725. return variables;
  55726. },
  55727. /**
  55728. * Update handler. Similar to attributeChangedCallback.
  55729. * Called whenever the associated material data changes.
  55730. *
  55731. * @param {object} data - New material data.
  55732. */
  55733. update: function (data) {
  55734. this.updateVariables(data, 'attribute');
  55735. this.updateVariables(data, 'uniform');
  55736. },
  55737. updateVariables: function (data, type) {
  55738. var key;
  55739. var materialKey;
  55740. var schema = this.schema;
  55741. var variables;
  55742. variables = type === 'uniform' ? this.uniforms : this.attributes;
  55743. for (key in data) {
  55744. if (!schema[key] || schema[key].is !== type) { continue; }
  55745. if (schema[key].type === 'map') {
  55746. // If data unchanged, get out early.
  55747. if (!variables[key] || variables[key].value === data[key]) { continue; }
  55748. // Special handling is needed for textures.
  55749. materialKey = '_texture_' + key;
  55750. // We can't actually set the variable correctly until we've loaded the texture.
  55751. this.setMapOnTextureLoad(variables, key, materialKey);
  55752. // Kick off the texture update now that handler is added.
  55753. utils.material.updateMapMaterialFromData(materialKey, key, this, data);
  55754. continue;
  55755. }
  55756. variables[key].value = this.parseValue(schema[key].type, data[key]);
  55757. variables[key].needsUpdate = true;
  55758. }
  55759. },
  55760. parseValue: function (type, value) {
  55761. var color;
  55762. switch (type) {
  55763. case 'vec2': {
  55764. return new THREE.Vector2(value.x, value.y);
  55765. }
  55766. case 'vec3': {
  55767. return new THREE.Vector3(value.x, value.y, value.z);
  55768. }
  55769. case 'vec4': {
  55770. return new THREE.Vector4(value.x, value.y, value.z, value.w);
  55771. }
  55772. case 'color': {
  55773. color = new THREE.Color(value);
  55774. return new THREE.Vector3(color.r, color.g, color.b);
  55775. }
  55776. case 'map': {
  55777. return THREE.ImageUtils.loadTexture(value);
  55778. }
  55779. default: {
  55780. return value;
  55781. }
  55782. }
  55783. },
  55784. setMapOnTextureLoad: function (variables, key, materialKey) {
  55785. var self = this;
  55786. this.el.addEventListener('materialtextureloaded', function () {
  55787. variables[key].value = self.material[materialKey];
  55788. variables[key].needsUpdate = true;
  55789. });
  55790. }
  55791. };
  55792. /**
  55793. * Registers a shader to A-Frame.
  55794. *
  55795. * @param {string} name - shader name.
  55796. * @param {object} definition - shader property and methods.
  55797. * @returns {object} Shader.
  55798. */
  55799. module.exports.registerShader = function (name, definition) {
  55800. var NewShader;
  55801. var proto = {};
  55802. // Format definition object to prototype object.
  55803. Object.keys(definition).forEach(function (key) {
  55804. proto[key] = {
  55805. value: definition[key],
  55806. writable: true
  55807. };
  55808. });
  55809. if (shaders[name]) {
  55810. throw new Error('The shader ' + name + ' has been already registered');
  55811. }
  55812. NewShader = function () { Shader.call(this); };
  55813. NewShader.prototype = Object.create(Shader.prototype, proto);
  55814. NewShader.prototype.name = name;
  55815. NewShader.prototype.constructor = NewShader;
  55816. shaders[name] = {
  55817. Shader: NewShader,
  55818. schema: processSchema(NewShader.prototype.schema)
  55819. };
  55820. shaderNames.push(name);
  55821. return NewShader;
  55822. };
  55823. },{"../lib/three":176,"../utils":202,"./schema":137}],139:[function(_dereq_,module,exports){
  55824. var components = _dereq_('./component');
  55825. var schema = _dereq_('./schema');
  55826. var utils = _dereq_('../utils/');
  55827. var parseProperties = schema.parseProperties;
  55828. var parseProperty = schema.parseProperty;
  55829. var processSchema = schema.process;
  55830. var isSingleProp = schema.isSingleProperty;
  55831. var styleParser = utils.styleParser;
  55832. var systems = module.exports.systems = {}; // Keep track of registered systems.
  55833. /**
  55834. * System class definition.
  55835. *
  55836. * Systems provide global scope and services to a group of instantiated components of the
  55837. * same class. They can also help abstract logic away from components such that components
  55838. * only have to worry about data.
  55839. *
  55840. * For example, a physics component that creates a physics world that oversees
  55841. * all entities with a physics or rigid body component.
  55842. *
  55843. * TODO: Have the System prototype reuse the Component prototype. Most code is copied
  55844. * and some pieces are missing from the Component facilities (e.g., attribute caching,
  55845. * setAttribute behavior).
  55846. *
  55847. * @member {string} name - Name that system is registered under.
  55848. * @member {Element} sceneEl - Handle to the scene element where system applies to.
  55849. */
  55850. var System = module.exports.System = function (sceneEl) {
  55851. var component = components && components.components[this.name];
  55852. // Set reference to scene.
  55853. this.el = sceneEl;
  55854. this.sceneEl = sceneEl;
  55855. // Set reference to matching component (if exists).
  55856. if (component) { component.Component.prototype.system = this; }
  55857. // Process system configuration.
  55858. this.buildData();
  55859. this.init();
  55860. this.update({});
  55861. };
  55862. System.prototype = {
  55863. /**
  55864. * Schema to configure system.
  55865. */
  55866. schema: {},
  55867. /**
  55868. * Init handler. Called during scene initialization and is only run once.
  55869. * Systems can use this to set initial state.
  55870. */
  55871. init: function () { /* no-op */ },
  55872. /**
  55873. * Update handler. Called during scene attribute updates.
  55874. * Systems can use this to dynamically update their state.
  55875. */
  55876. update: function (oldData) { /* no-op */ },
  55877. /**
  55878. * Build data and call update handler.
  55879. *
  55880. * @private
  55881. */
  55882. updateProperties: function (rawData) {
  55883. var oldData = this.data;
  55884. if (!Object.keys(schema).length) { return; }
  55885. this.buildData(rawData);
  55886. this.update(oldData);
  55887. },
  55888. /**
  55889. * Parse data.
  55890. */
  55891. buildData: function (rawData) {
  55892. var schema = this.schema;
  55893. if (!Object.keys(schema).length) { return; }
  55894. rawData = rawData || window.HTMLElement.prototype.getAttribute.call(this.sceneEl, this.name);
  55895. if (isSingleProp(schema)) {
  55896. this.data = parseProperty(rawData, schema);
  55897. } else {
  55898. this.data = parseProperties(styleParser.parse(rawData) || {}, schema);
  55899. }
  55900. },
  55901. /**
  55902. * Tick handler.
  55903. * Called on each tick of the scene render loop.
  55904. * Affected by play and pause.
  55905. *
  55906. * @param {number} time - Scene tick time.
  55907. * @param {number} timeDelta - Difference in current render time and previous render time.
  55908. */
  55909. tick: undefined,
  55910. /**
  55911. * Tock handler.
  55912. * Called on each tock of the scene render loop.
  55913. * Affected by play and pause.
  55914. *
  55915. * @param {number} time - Scene tick time.
  55916. * @param {number} timeDelta - Difference in current render time and previous render time.
  55917. */
  55918. tock: undefined,
  55919. /**
  55920. * Called to start any dynamic behavior (e.g., animation, AI, events, physics).
  55921. */
  55922. play: function () { /* no-op */ },
  55923. /**
  55924. * Called to stop any dynamic behavior (e.g., animation, AI, events, physics).
  55925. */
  55926. pause: function () { /* no-op */ }
  55927. };
  55928. /**
  55929. * Registers a system to A-Frame.
  55930. *
  55931. * @param {string} name - Component name.
  55932. * @param {object} definition - Component property and methods.
  55933. * @returns {object} Component.
  55934. */
  55935. module.exports.registerSystem = function (name, definition) {
  55936. var i;
  55937. var NewSystem;
  55938. var proto = {};
  55939. var scenes = utils.findAllScenes(document);
  55940. // Format definition object to prototype object.
  55941. Object.keys(definition).forEach(function (key) {
  55942. proto[key] = {
  55943. value: definition[key],
  55944. writable: true
  55945. };
  55946. });
  55947. if (systems[name]) {
  55948. throw new Error('The system `' + name + '` has been already registered. ' +
  55949. 'Check that you are not loading two versions of the same system ' +
  55950. 'or two different systems of the same name.');
  55951. }
  55952. NewSystem = function (sceneEl) { System.call(this, sceneEl); };
  55953. NewSystem.prototype = Object.create(System.prototype, proto);
  55954. NewSystem.prototype.name = name;
  55955. NewSystem.prototype.constructor = NewSystem;
  55956. NewSystem.prototype.schema = utils.extend(processSchema(NewSystem.prototype.schema));
  55957. systems[name] = NewSystem;
  55958. // Initialize systems for existing scenes
  55959. for (i = 0; i < scenes.length; i++) { scenes[i].initSystem(name); }
  55960. };
  55961. },{"../utils/":202,"./component":128,"./schema":137}],140:[function(_dereq_,module,exports){
  55962. _dereq_('./pivot');
  55963. },{"./pivot":141}],141:[function(_dereq_,module,exports){
  55964. var registerComponent = _dereq_('../../core/component').registerComponent;
  55965. var THREE = _dereq_('../../lib/three');
  55966. var originalPosition = new THREE.Vector3();
  55967. var originalRotation = new THREE.Vector3();
  55968. /**
  55969. * Wrap el.object3D within an outer group. Apply pivot to el.object3D as position.
  55970. */
  55971. registerComponent('pivot', {
  55972. dependencies: ['position'],
  55973. schema: {type: 'vec3'},
  55974. init: function () {
  55975. var data = this.data;
  55976. var el = this.el;
  55977. var originalParent = el.object3D.parent;
  55978. var originalGroup = el.object3D;
  55979. var outerGroup = new THREE.Group();
  55980. originalPosition.copy(originalGroup.position);
  55981. originalRotation.copy(originalGroup.rotation);
  55982. // Detach current group from parent.
  55983. originalParent.remove(originalGroup);
  55984. outerGroup.add(originalGroup);
  55985. // Set new group as the outer group.
  55986. originalParent.add(outerGroup);
  55987. // Set outer group as new object3D.
  55988. el.object3D = outerGroup;
  55989. // Apply pivot to original group.
  55990. originalGroup.position.set(-1 * data.x, -1 * data.y, -1 * data.z);
  55991. // Offset the pivot so that world position not affected.
  55992. // And restore position onto outer group.
  55993. outerGroup.position.set(data.x + originalPosition.x, data.y + originalPosition.y,
  55994. data.z + originalPosition.z);
  55995. // Transfer rotation to outer group.
  55996. outerGroup.rotation.copy(originalGroup.rotation);
  55997. originalGroup.rotation.set(0, 0, 0);
  55998. }
  55999. });
  56000. },{"../../core/component":128,"../../lib/three":176}],142:[function(_dereq_,module,exports){
  56001. /**
  56002. * Common mesh defaults, mappings, and transforms.
  56003. */
  56004. var components = _dereq_('../../core/component').components;
  56005. var shaders = _dereq_('../../core/shader').shaders;
  56006. var utils = _dereq_('../../utils/');
  56007. var materialMappings = {};
  56008. Object.keys(components.material.schema).forEach(addMapping);
  56009. Object.keys(shaders.standard.schema).forEach(addMapping);
  56010. function addMapping (prop) {
  56011. // To hyphenated.
  56012. var htmlAttrName = prop.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();
  56013. if (prop === 'fog') { htmlAttrName = 'material-fog'; }
  56014. if (prop === 'visible') { htmlAttrName = 'material-visible'; }
  56015. materialMappings[htmlAttrName] = 'material.' + prop;
  56016. }
  56017. module.exports = function getMeshMixin () {
  56018. return {
  56019. defaultComponents: {material: {}},
  56020. mappings: utils.extend({}, materialMappings)
  56021. };
  56022. };
  56023. },{"../../core/component":128,"../../core/shader":138,"../../utils/":202}],143:[function(_dereq_,module,exports){
  56024. _dereq_('./primitives/a-camera');
  56025. _dereq_('./primitives/a-cursor');
  56026. _dereq_('./primitives/a-curvedimage');
  56027. _dereq_('./primitives/a-gltf-model');
  56028. _dereq_('./primitives/a-image');
  56029. _dereq_('./primitives/a-light');
  56030. _dereq_('./primitives/a-link');
  56031. _dereq_('./primitives/a-obj-model');
  56032. _dereq_('./primitives/a-sky');
  56033. _dereq_('./primitives/a-sound');
  56034. _dereq_('./primitives/a-text');
  56035. _dereq_('./primitives/a-video');
  56036. _dereq_('./primitives/a-videosphere');
  56037. _dereq_('./primitives/meshPrimitives');
  56038. },{"./primitives/a-camera":145,"./primitives/a-cursor":146,"./primitives/a-curvedimage":147,"./primitives/a-gltf-model":148,"./primitives/a-image":149,"./primitives/a-light":150,"./primitives/a-link":151,"./primitives/a-obj-model":152,"./primitives/a-sky":153,"./primitives/a-sound":154,"./primitives/a-text":155,"./primitives/a-video":156,"./primitives/a-videosphere":157,"./primitives/meshPrimitives":158}],144:[function(_dereq_,module,exports){
  56039. var AEntity = _dereq_('../../core/a-entity');
  56040. var components = _dereq_('../../core/component').components;
  56041. var registerElement = _dereq_('../../core/a-register-element').registerElement;
  56042. var utils = _dereq_('../../utils/');
  56043. var debug = utils.debug;
  56044. var setComponentProperty = utils.entity.setComponentProperty;
  56045. var log = debug('extras:primitives:debug');
  56046. var warn = debug('extras:primitives:warn');
  56047. var primitives = module.exports.primitives = {};
  56048. module.exports.registerPrimitive = function registerPrimitive (name, definition) {
  56049. name = name.toLowerCase();
  56050. log('Registering <%s>', name);
  56051. // Deprecation warning for defaultAttributes usage.
  56052. if (definition.defaultAttributes) {
  56053. warn("The 'defaultAttributes' object is deprecated. Use 'defaultComponents' instead.");
  56054. }
  56055. var primitive = registerElement(name, {
  56056. prototype: Object.create(AEntity.prototype, {
  56057. defaultComponentsFromPrimitive: {
  56058. value: definition.defaultComponents || definition.defaultAttributes || {}
  56059. },
  56060. deprecated: {value: definition.deprecated || null},
  56061. deprecatedMappings: {value: definition.deprecatedMappings || {}},
  56062. mappings: {value: definition.mappings || {}},
  56063. createdCallback: {
  56064. value: function () {
  56065. if (definition.deprecated) { console.warn(definition.deprecated); }
  56066. this.resolveMappingCollisions();
  56067. }
  56068. },
  56069. /**
  56070. * If a mapping collides with a registered component name
  56071. * it renames the mapping to componentname-property
  56072. */
  56073. resolveMappingCollisions: {
  56074. value: function () {
  56075. var mappings = this.mappings;
  56076. var self = this;
  56077. Object.keys(mappings).forEach(function resolveCollision (key) {
  56078. var newAttribute;
  56079. if (key !== key.toLowerCase()) { warn('Mapping keys should be specified in lower case. The mapping key ' + key + ' may not be recognized'); }
  56080. if (components[key]) {
  56081. newAttribute = mappings[key].replace('.', '-');
  56082. mappings[newAttribute] = mappings[key];
  56083. delete mappings[key];
  56084. console.warn('The primitive ' + self.tagName.toLowerCase() + ' has a mapping collision. ' +
  56085. 'The attribute ' + key + ' has the same name as a registered component and' +
  56086. ' has been renamed to ' + newAttribute);
  56087. }
  56088. });
  56089. }
  56090. },
  56091. getExtraComponents: {
  56092. value: function () {
  56093. var attr;
  56094. var data;
  56095. var i;
  56096. var mapping;
  56097. var mixins;
  56098. var path;
  56099. var self = this;
  56100. // Gather component data from default components.
  56101. data = utils.clone(this.defaultComponentsFromPrimitive);
  56102. // Factor in mixins to overwrite default components.
  56103. mixins = this.getAttribute('mixin');
  56104. if (mixins) {
  56105. mixins = mixins.trim().split(' ');
  56106. mixins.forEach(function applyMixin (mixinId) {
  56107. var mixinComponents = self.sceneEl.querySelector('#' + mixinId).componentCache;
  56108. Object.keys(mixinComponents).forEach(function setComponent (name) {
  56109. data[name] = extend(data[name], mixinComponents[name]);
  56110. });
  56111. });
  56112. }
  56113. // Gather component data from mappings.
  56114. for (i = 0; i < this.attributes.length; i++) {
  56115. attr = this.attributes[i];
  56116. mapping = this.mappings[attr.name];
  56117. if (mapping) {
  56118. path = utils.entity.getComponentPropertyPath(mapping);
  56119. if (path.constructor === Array) {
  56120. data[path[0]] = data[path[0]] || {};
  56121. data[path[0]][path[1]] = attr.value.trim();
  56122. } else {
  56123. data[path] = attr.value.trim();
  56124. }
  56125. continue;
  56126. }
  56127. }
  56128. return data;
  56129. /**
  56130. * For the base to be extensible, both objects must be pure JavaScript objects.
  56131. * The function assumes that base is undefined, or null or a pure object.
  56132. */
  56133. function extend (base, extension) {
  56134. if (isUndefined(base)) {
  56135. return copy(extension);
  56136. }
  56137. if (isUndefined(extension)) {
  56138. return copy(base);
  56139. }
  56140. if (isPureObject(base) && isPureObject(extension)) {
  56141. return utils.extendDeep(base, extension);
  56142. }
  56143. return copy(extension);
  56144. }
  56145. function isUndefined (value) {
  56146. return typeof value === 'undefined';
  56147. }
  56148. function copy (value) {
  56149. if (isPureObject(value)) {
  56150. return utils.extendDeep({}, value);
  56151. }
  56152. return value;
  56153. }
  56154. function isPureObject (value) {
  56155. return value !== null && value.constructor === Object;
  56156. }
  56157. }
  56158. },
  56159. /**
  56160. * Sync to attribute to component property whenever mapped attribute changes.
  56161. * If attribute is mapped to a component property, set the component property using
  56162. * the attribute value.
  56163. */
  56164. attributeChangedCallback: {
  56165. value: function (attr, oldVal, value) {
  56166. var componentName = this.mappings[attr];
  56167. if (attr in this.deprecatedMappings) {
  56168. console.warn(this.deprecatedMappings[attr]);
  56169. }
  56170. if (!attr || !componentName) { return; }
  56171. // Set value.
  56172. setComponentProperty(this, componentName, value);
  56173. }
  56174. }
  56175. })
  56176. });
  56177. // Store.
  56178. primitives[name] = primitive;
  56179. return primitive;
  56180. };
  56181. /**
  56182. * Add component mappings using schema.
  56183. */
  56184. function addComponentMapping (componentName, mappings) {
  56185. var schema = components[componentName].schema;
  56186. Object.keys(schema).map(function (prop) {
  56187. // Hyphenate where there is camelCase.
  56188. var attrName = prop.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();
  56189. // If there is a mapping collision, prefix with component name and hyphen.
  56190. if (mappings[attrName] !== undefined) { attrName = componentName + '-' + prop; }
  56191. mappings[attrName] = componentName + '.' + prop;
  56192. });
  56193. }
  56194. /**
  56195. * Helper to define a primitive, building mappings using a component schema.
  56196. */
  56197. function definePrimitive (tagName, defaultComponents, mappings) {
  56198. // If no initial mappings provided, start from empty map.
  56199. mappings = mappings || {};
  56200. // From the default components, add mapping automagically.
  56201. Object.keys(defaultComponents).map(function buildMappings (componentName) {
  56202. addComponentMapping(componentName, mappings);
  56203. });
  56204. // Register the primitive.
  56205. module.exports.registerPrimitive(tagName, utils.extendDeep({}, null, {
  56206. defaultComponents: defaultComponents,
  56207. mappings: mappings
  56208. }));
  56209. }
  56210. module.exports.definePrimitive = definePrimitive;
  56211. },{"../../core/a-entity":124,"../../core/a-register-element":127,"../../core/component":128,"../../utils/":202}],145:[function(_dereq_,module,exports){
  56212. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  56213. registerPrimitive('a-camera', {
  56214. defaultComponents: {
  56215. 'camera': {},
  56216. 'look-controls': {},
  56217. 'wasd-controls': {},
  56218. 'position': {x: 0, y: 1.6, z: 0}
  56219. },
  56220. mappings: {
  56221. active: 'camera.active',
  56222. far: 'camera.far',
  56223. fov: 'camera.fov',
  56224. 'look-controls-enabled': 'look-controls.enabled',
  56225. near: 'camera.near',
  56226. 'pointer-lock-enabled': 'look-controls.pointerLockEnabled',
  56227. 'wasd-controls-enabled': 'wasd-controls.enabled',
  56228. 'reverse-mouse-drag': 'look-controls.reverseMouseDrag',
  56229. zoom: 'camera.zoom'
  56230. }
  56231. });
  56232. },{"../primitives":144}],146:[function(_dereq_,module,exports){
  56233. var getMeshMixin = _dereq_('../getMeshMixin');
  56234. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  56235. var utils = _dereq_('../../../utils/');
  56236. registerPrimitive('a-cursor', utils.extendDeep({}, getMeshMixin(), {
  56237. defaultComponents: {
  56238. cursor: {},
  56239. geometry: {
  56240. primitive: 'ring',
  56241. radiusOuter: 0.016,
  56242. radiusInner: 0.01,
  56243. segmentsTheta: 32
  56244. },
  56245. material: {
  56246. color: '#000',
  56247. shader: 'flat',
  56248. opacity: 0.8
  56249. },
  56250. position: {
  56251. x: 0,
  56252. y: 0,
  56253. z: -1
  56254. }
  56255. },
  56256. mappings: {
  56257. far: 'raycaster.far',
  56258. fuse: 'cursor.fuse',
  56259. 'fuse-timeout': 'cursor.fuseTimeout',
  56260. interval: 'raycaster.interval',
  56261. objects: 'raycaster.objects'
  56262. }
  56263. }));
  56264. },{"../../../utils/":202,"../getMeshMixin":142,"../primitives":144}],147:[function(_dereq_,module,exports){
  56265. var getMeshMixin = _dereq_('../getMeshMixin');
  56266. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  56267. var utils = _dereq_('../../../utils/');
  56268. registerPrimitive('a-curvedimage', utils.extendDeep({}, getMeshMixin(), {
  56269. defaultComponents: {
  56270. geometry: {
  56271. height: 1,
  56272. primitive: 'cylinder',
  56273. radius: 2,
  56274. segmentsRadial: 48,
  56275. thetaLength: 270,
  56276. openEnded: true,
  56277. thetaStart: 0
  56278. },
  56279. material: {
  56280. color: '#FFF',
  56281. shader: 'flat',
  56282. side: 'double',
  56283. transparent: true,
  56284. repeat: '-1 1'
  56285. }
  56286. },
  56287. mappings: {
  56288. height: 'geometry.height',
  56289. 'open-ended': 'geometry.openEnded',
  56290. radius: 'geometry.radius',
  56291. segments: 'geometry.segmentsRadial',
  56292. start: 'geometry.thetaStart',
  56293. 'theta-length': 'geometry.thetaLength',
  56294. 'theta-start': 'geometry.thetaStart',
  56295. 'width': 'geometry.thetaLength'
  56296. }
  56297. }));
  56298. },{"../../../utils/":202,"../getMeshMixin":142,"../primitives":144}],148:[function(_dereq_,module,exports){
  56299. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  56300. registerPrimitive('a-gltf-model', {
  56301. mappings: {
  56302. src: 'gltf-model'
  56303. }
  56304. });
  56305. },{"../primitives":144}],149:[function(_dereq_,module,exports){
  56306. var getMeshMixin = _dereq_('../getMeshMixin');
  56307. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  56308. var utils = _dereq_('../../../utils/');
  56309. registerPrimitive('a-image', utils.extendDeep({}, getMeshMixin(), {
  56310. defaultComponents: {
  56311. geometry: {
  56312. primitive: 'plane'
  56313. },
  56314. material: {
  56315. color: '#FFF',
  56316. shader: 'flat',
  56317. side: 'double',
  56318. transparent: true
  56319. }
  56320. },
  56321. mappings: {
  56322. height: 'geometry.height',
  56323. width: 'geometry.width'
  56324. }
  56325. }));
  56326. },{"../../../utils/":202,"../getMeshMixin":142,"../primitives":144}],150:[function(_dereq_,module,exports){
  56327. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  56328. registerPrimitive('a-light', {
  56329. defaultComponents: {
  56330. light: {}
  56331. },
  56332. mappings: {
  56333. angle: 'light.angle',
  56334. color: 'light.color',
  56335. 'ground-color': 'light.groundColor',
  56336. decay: 'light.decay',
  56337. distance: 'light.distance',
  56338. intensity: 'light.intensity',
  56339. penumbra: 'light.penumbra',
  56340. type: 'light.type',
  56341. target: 'light.target'
  56342. }
  56343. });
  56344. },{"../primitives":144}],151:[function(_dereq_,module,exports){
  56345. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  56346. registerPrimitive('a-link', {
  56347. defaultComponents: {
  56348. link: {
  56349. visualAspectEnabled: true
  56350. }
  56351. },
  56352. mappings: {
  56353. href: 'link.href',
  56354. image: 'link.image',
  56355. title: 'link.title'
  56356. }
  56357. });
  56358. },{"../primitives":144}],152:[function(_dereq_,module,exports){
  56359. var meshMixin = _dereq_('../getMeshMixin')();
  56360. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  56361. var utils = _dereq_('../../../utils/');
  56362. registerPrimitive('a-obj-model', utils.extendDeep({}, meshMixin, {
  56363. defaultComponents: {
  56364. 'obj-model': {}
  56365. },
  56366. mappings: {
  56367. src: 'obj-model.obj',
  56368. mtl: 'obj-model.mtl'
  56369. }
  56370. }));
  56371. },{"../../../utils/":202,"../getMeshMixin":142,"../primitives":144}],153:[function(_dereq_,module,exports){
  56372. var getMeshMixin = _dereq_('../getMeshMixin');
  56373. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  56374. var utils = _dereq_('../../../utils/');
  56375. var meshPrimitives = _dereq_('./meshPrimitives');
  56376. registerPrimitive('a-sky', utils.extendDeep({}, getMeshMixin(), {
  56377. defaultComponents: {
  56378. geometry: {
  56379. primitive: 'sphere',
  56380. radius: 500,
  56381. segmentsWidth: 64,
  56382. segmentsHeight: 32
  56383. },
  56384. material: {
  56385. color: '#FFF',
  56386. side: 'back',
  56387. shader: 'flat',
  56388. npot: true
  56389. },
  56390. scale: '-1 1 1'
  56391. },
  56392. mappings: utils.extendDeep({}, meshPrimitives['a-sphere'].prototype.mappings)
  56393. }));
  56394. },{"../../../utils/":202,"../getMeshMixin":142,"../primitives":144,"./meshPrimitives":158}],154:[function(_dereq_,module,exports){
  56395. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  56396. registerPrimitive('a-sound', {
  56397. defaultComponents: {
  56398. sound: {}
  56399. },
  56400. mappings: {
  56401. src: 'sound.src',
  56402. on: 'sound.on',
  56403. autoplay: 'sound.autoplay',
  56404. loop: 'sound.loop',
  56405. volume: 'sound.volume'
  56406. }
  56407. });
  56408. },{"../primitives":144}],155:[function(_dereq_,module,exports){
  56409. // <a-text> using `definePrimitive` helper.
  56410. var definePrimitive = _dereq_('../primitives').definePrimitive;
  56411. definePrimitive('a-text', {text: {anchor: 'align', width: 5}});
  56412. },{"../primitives":144}],156:[function(_dereq_,module,exports){
  56413. var getMeshMixin = _dereq_('../getMeshMixin');
  56414. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  56415. var utils = _dereq_('../../../utils/');
  56416. registerPrimitive('a-video', utils.extendDeep({}, getMeshMixin(), {
  56417. defaultComponents: {
  56418. geometry: {
  56419. primitive: 'plane'
  56420. },
  56421. material: {
  56422. color: '#FFF',
  56423. shader: 'flat',
  56424. side: 'double',
  56425. transparent: true
  56426. }
  56427. },
  56428. mappings: {
  56429. height: 'geometry.height',
  56430. width: 'geometry.width'
  56431. }
  56432. }));
  56433. },{"../../../utils/":202,"../getMeshMixin":142,"../primitives":144}],157:[function(_dereq_,module,exports){
  56434. var getMeshMixin = _dereq_('../getMeshMixin');
  56435. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  56436. var utils = _dereq_('../../../utils/');
  56437. registerPrimitive('a-videosphere', utils.extendDeep({}, getMeshMixin(), {
  56438. defaultComponents: {
  56439. geometry: {
  56440. primitive: 'sphere',
  56441. radius: 500,
  56442. segmentsWidth: 64,
  56443. segmentsHeight: 32
  56444. },
  56445. material: {
  56446. color: '#FFF',
  56447. shader: 'flat',
  56448. side: 'back',
  56449. npot: true
  56450. },
  56451. scale: '-1 1 1'
  56452. },
  56453. mappings: {
  56454. radius: 'geometry.radius',
  56455. 'segments-height': 'geometry.segmentsHeight',
  56456. 'segments-width': 'geometry.segmentsWidth'
  56457. }
  56458. }));
  56459. },{"../../../utils/":202,"../getMeshMixin":142,"../primitives":144}],158:[function(_dereq_,module,exports){
  56460. /**
  56461. * Automated mesh primitive registration.
  56462. */
  56463. var getMeshMixin = _dereq_('../getMeshMixin');
  56464. var geometries = _dereq_('../../../core/geometry').geometries;
  56465. var geometryNames = _dereq_('../../../core/geometry').geometryNames;
  56466. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  56467. var utils = _dereq_('../../../utils/');
  56468. // For testing.
  56469. var meshPrimitives = module.exports = {};
  56470. // Generate primitive for each geometry type.
  56471. geometryNames.forEach(function registerMeshPrimitive (geometryName) {
  56472. var geometry = geometries[geometryName];
  56473. var geometryHyphened = unCamelCase(geometryName);
  56474. // Generate mappings.
  56475. var mappings = {};
  56476. Object.keys(geometry.schema).forEach(function createMapping (property) {
  56477. mappings[unCamelCase(property)] = 'geometry.' + property;
  56478. });
  56479. // Register.
  56480. var tagName = 'a-' + geometryHyphened;
  56481. var primitive = registerPrimitive(tagName, utils.extendDeep({}, getMeshMixin(), {
  56482. defaultComponents: {geometry: {primitive: geometryName}},
  56483. mappings: mappings
  56484. }));
  56485. meshPrimitives[tagName] = primitive;
  56486. });
  56487. /**
  56488. * camelCase to hyphened-string.
  56489. */
  56490. function unCamelCase (str) {
  56491. return str.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();
  56492. }
  56493. },{"../../../core/geometry":129,"../../../utils/":202,"../getMeshMixin":142,"../primitives":144}],159:[function(_dereq_,module,exports){
  56494. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  56495. var THREE = _dereq_('../lib/three');
  56496. registerGeometry('box', {
  56497. schema: {
  56498. depth: {default: 1, min: 0},
  56499. height: {default: 1, min: 0},
  56500. width: {default: 1, min: 0},
  56501. segmentsHeight: {default: 1, min: 1, max: 20, type: 'int'},
  56502. segmentsWidth: {default: 1, min: 1, max: 20, type: 'int'},
  56503. segmentsDepth: {default: 1, min: 1, max: 20, type: 'int'}
  56504. },
  56505. init: function (data) {
  56506. this.geometry = new THREE.BoxGeometry(
  56507. data.width, data.height, data.depth,
  56508. data.segmentsWidth, data.segmentsHeight, data.segmentsDepth);
  56509. }
  56510. });
  56511. },{"../core/geometry":129,"../lib/three":176}],160:[function(_dereq_,module,exports){
  56512. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  56513. var THREE = _dereq_('../lib/three');
  56514. var degToRad = THREE.Math.degToRad;
  56515. registerGeometry('circle', {
  56516. schema: {
  56517. radius: {default: 1, min: 0},
  56518. segments: {default: 32, min: 3, type: 'int'},
  56519. thetaLength: {default: 360, min: 0},
  56520. thetaStart: {default: 0}
  56521. },
  56522. init: function (data) {
  56523. this.geometry = new THREE.CircleGeometry(
  56524. data.radius, data.segments, degToRad(data.thetaStart), degToRad(data.thetaLength));
  56525. }
  56526. });
  56527. },{"../core/geometry":129,"../lib/three":176}],161:[function(_dereq_,module,exports){
  56528. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  56529. var THREE = _dereq_('../lib/three');
  56530. var degToRad = THREE.Math.degToRad;
  56531. registerGeometry('cone', {
  56532. schema: {
  56533. height: {default: 1, min: 0},
  56534. openEnded: {default: false},
  56535. radiusBottom: {default: 1, min: 0},
  56536. radiusTop: {default: 0.01, min: 0},
  56537. segmentsHeight: {default: 18, min: 1, type: 'int'},
  56538. segmentsRadial: {default: 36, min: 3, type: 'int'},
  56539. thetaLength: {default: 360, min: 0},
  56540. thetaStart: {default: 0}
  56541. },
  56542. init: function (data) {
  56543. this.geometry = new THREE.CylinderGeometry(
  56544. data.radiusTop, data.radiusBottom, data.height, data.segmentsRadial,
  56545. data.segmentsHeight, data.openEnded, degToRad(data.thetaStart),
  56546. degToRad(data.thetaLength));
  56547. }
  56548. });
  56549. },{"../core/geometry":129,"../lib/three":176}],162:[function(_dereq_,module,exports){
  56550. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  56551. var THREE = _dereq_('../lib/three');
  56552. var degToRad = THREE.Math.degToRad;
  56553. registerGeometry('cylinder', {
  56554. schema: {
  56555. height: {default: 1, min: 0},
  56556. openEnded: {default: false},
  56557. radius: {default: 1, min: 0},
  56558. segmentsHeight: {default: 18, min: 1, type: 'int'},
  56559. segmentsRadial: {default: 36, min: 3, type: 'int'},
  56560. thetaLength: {default: 360, min: 0},
  56561. thetaStart: {default: 0}
  56562. },
  56563. init: function (data) {
  56564. this.geometry = new THREE.CylinderGeometry(
  56565. data.radius, data.radius, data.height, data.segmentsRadial, data.segmentsHeight,
  56566. data.openEnded, degToRad(data.thetaStart), degToRad(data.thetaLength));
  56567. }
  56568. });
  56569. },{"../core/geometry":129,"../lib/three":176}],163:[function(_dereq_,module,exports){
  56570. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  56571. var THREE = _dereq_('../lib/three');
  56572. registerGeometry('dodecahedron', {
  56573. schema: {
  56574. detail: {default: 0, min: 0, max: 5, type: 'int'},
  56575. radius: {default: 1, min: 0}
  56576. },
  56577. init: function (data) {
  56578. this.geometry = new THREE.DodecahedronGeometry(data.radius, data.detail);
  56579. }
  56580. });
  56581. },{"../core/geometry":129,"../lib/three":176}],164:[function(_dereq_,module,exports){
  56582. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  56583. var THREE = _dereq_('../lib/three');
  56584. registerGeometry('icosahedron', {
  56585. schema: {
  56586. detail: {default: 0, min: 0, max: 5, type: 'int'},
  56587. radius: {default: 1, min: 0}
  56588. },
  56589. init: function (data) {
  56590. this.geometry = new THREE.IcosahedronGeometry(data.radius, data.detail);
  56591. }
  56592. });
  56593. },{"../core/geometry":129,"../lib/three":176}],165:[function(_dereq_,module,exports){
  56594. _dereq_('./box.js');
  56595. _dereq_('./circle.js');
  56596. _dereq_('./cone.js');
  56597. _dereq_('./cylinder.js');
  56598. _dereq_('./dodecahedron.js');
  56599. _dereq_('./icosahedron.js');
  56600. _dereq_('./octahedron.js');
  56601. _dereq_('./plane.js');
  56602. _dereq_('./ring.js');
  56603. _dereq_('./sphere.js');
  56604. _dereq_('./tetrahedron.js');
  56605. _dereq_('./torus.js');
  56606. _dereq_('./torusKnot.js');
  56607. _dereq_('./triangle.js');
  56608. },{"./box.js":159,"./circle.js":160,"./cone.js":161,"./cylinder.js":162,"./dodecahedron.js":163,"./icosahedron.js":164,"./octahedron.js":166,"./plane.js":167,"./ring.js":168,"./sphere.js":169,"./tetrahedron.js":170,"./torus.js":171,"./torusKnot.js":172,"./triangle.js":173}],166:[function(_dereq_,module,exports){
  56609. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  56610. var THREE = _dereq_('../lib/three');
  56611. registerGeometry('octahedron', {
  56612. schema: {
  56613. detail: {default: 0, min: 0, max: 5, type: 'int'},
  56614. radius: {default: 1, min: 0}
  56615. },
  56616. init: function (data) {
  56617. this.geometry = new THREE.OctahedronGeometry(data.radius, data.detail);
  56618. }
  56619. });
  56620. },{"../core/geometry":129,"../lib/three":176}],167:[function(_dereq_,module,exports){
  56621. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  56622. var THREE = _dereq_('../lib/three');
  56623. registerGeometry('plane', {
  56624. schema: {
  56625. height: {default: 1, min: 0},
  56626. width: {default: 1, min: 0},
  56627. segmentsHeight: {default: 1, min: 1, max: 20, type: 'int'},
  56628. segmentsWidth: {default: 1, min: 1, max: 20, type: 'int'}
  56629. },
  56630. init: function (data) {
  56631. this.geometry = new THREE.PlaneGeometry(data.width, data.height, data.segmentsWidth, data.segmentsHeight);
  56632. }
  56633. });
  56634. },{"../core/geometry":129,"../lib/three":176}],168:[function(_dereq_,module,exports){
  56635. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  56636. var THREE = _dereq_('../lib/three');
  56637. var degToRad = THREE.Math.degToRad;
  56638. registerGeometry('ring', {
  56639. schema: {
  56640. radiusInner: {default: 0.8, min: 0},
  56641. radiusOuter: {default: 1.2, min: 0},
  56642. segmentsPhi: {default: 10, min: 1, type: 'int'},
  56643. segmentsTheta: {default: 32, min: 3, type: 'int'},
  56644. thetaLength: {default: 360, min: 0},
  56645. thetaStart: {default: 0}
  56646. },
  56647. init: function (data) {
  56648. this.geometry = new THREE.RingGeometry(
  56649. data.radiusInner, data.radiusOuter, data.segmentsTheta, data.segmentsPhi,
  56650. degToRad(data.thetaStart), degToRad(data.thetaLength));
  56651. }
  56652. });
  56653. },{"../core/geometry":129,"../lib/three":176}],169:[function(_dereq_,module,exports){
  56654. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  56655. var THREE = _dereq_('../lib/three');
  56656. var degToRad = THREE.Math.degToRad;
  56657. registerGeometry('sphere', {
  56658. schema: {
  56659. radius: {default: 1, min: 0},
  56660. phiLength: {default: 360},
  56661. phiStart: {default: 0, min: 0},
  56662. thetaLength: {default: 180, min: 0},
  56663. thetaStart: {default: 0},
  56664. segmentsHeight: {default: 18, min: 2, type: 'int'},
  56665. segmentsWidth: {default: 36, min: 3, type: 'int'}
  56666. },
  56667. init: function (data) {
  56668. this.geometry = new THREE.SphereGeometry(
  56669. data.radius, data.segmentsWidth, data.segmentsHeight, degToRad(data.phiStart),
  56670. degToRad(data.phiLength), degToRad(data.thetaStart), degToRad(data.thetaLength));
  56671. }
  56672. });
  56673. },{"../core/geometry":129,"../lib/three":176}],170:[function(_dereq_,module,exports){
  56674. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  56675. var THREE = _dereq_('../lib/three');
  56676. registerGeometry('tetrahedron', {
  56677. schema: {
  56678. detail: {default: 0, min: 0, max: 5, type: 'int'},
  56679. radius: {default: 1, min: 0}
  56680. },
  56681. init: function (data) {
  56682. this.geometry = new THREE.TetrahedronGeometry(data.radius, data.detail);
  56683. }
  56684. });
  56685. },{"../core/geometry":129,"../lib/three":176}],171:[function(_dereq_,module,exports){
  56686. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  56687. var THREE = _dereq_('../lib/three');
  56688. var degToRad = THREE.Math.degToRad;
  56689. registerGeometry('torus', {
  56690. schema: {
  56691. arc: {default: 360},
  56692. radius: {default: 1, min: 0},
  56693. radiusTubular: {default: 0.2, min: 0},
  56694. segmentsRadial: {default: 36, min: 2, type: 'int'},
  56695. segmentsTubular: {default: 32, min: 3, type: 'int'}
  56696. },
  56697. init: function (data) {
  56698. this.geometry = new THREE.TorusGeometry(
  56699. data.radius, data.radiusTubular * 2, data.segmentsRadial, data.segmentsTubular,
  56700. degToRad(data.arc));
  56701. }
  56702. });
  56703. },{"../core/geometry":129,"../lib/three":176}],172:[function(_dereq_,module,exports){
  56704. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  56705. var THREE = _dereq_('../lib/three');
  56706. registerGeometry('torusKnot', {
  56707. schema: {
  56708. p: {default: 2, min: 1},
  56709. q: {default: 3, min: 1},
  56710. radius: {default: 1, min: 0},
  56711. radiusTubular: {default: 0.2, min: 0},
  56712. segmentsRadial: {default: 8, min: 3, type: 'int'},
  56713. segmentsTubular: {default: 100, min: 3, type: 'int'}
  56714. },
  56715. init: function (data) {
  56716. this.geometry = new THREE.TorusKnotGeometry(
  56717. data.radius, data.radiusTubular * 2, data.segmentsTubular, data.segmentsRadial,
  56718. data.p, data.q);
  56719. }
  56720. });
  56721. },{"../core/geometry":129,"../lib/three":176}],173:[function(_dereq_,module,exports){
  56722. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  56723. var THREE = _dereq_('../lib/three');
  56724. var quaternion = new THREE.Quaternion();
  56725. var rotateVector = new THREE.Vector3(0, 0, 1);
  56726. var uvMinVector = new THREE.Vector2();
  56727. var uvMaxVector = new THREE.Vector2();
  56728. var uvScaleVector = new THREE.Vector2();
  56729. registerGeometry('triangle', {
  56730. schema: {
  56731. vertexA: {type: 'vec3', default: {x: 0, y: 0.5, z: 0}},
  56732. vertexB: {type: 'vec3', default: {x: -0.5, y: -0.5, z: 0}},
  56733. vertexC: {type: 'vec3', default: {x: 0.5, y: -0.5, z: 0}}
  56734. },
  56735. init: function (data) {
  56736. var geometry;
  56737. var normal;
  56738. var triangle;
  56739. var uvA;
  56740. var uvB;
  56741. var uvC;
  56742. triangle = new THREE.Triangle();
  56743. triangle.a.set(data.vertexA.x, data.vertexA.y, data.vertexA.z);
  56744. triangle.b.set(data.vertexB.x, data.vertexB.y, data.vertexB.z);
  56745. triangle.c.set(data.vertexC.x, data.vertexC.y, data.vertexC.z);
  56746. normal = triangle.getNormal(new THREE.Vector3());
  56747. // Rotate the 3D triangle to be parallel to XY plane.
  56748. quaternion.setFromUnitVectors(normal, rotateVector);
  56749. uvA = triangle.a.clone().applyQuaternion(quaternion);
  56750. uvB = triangle.b.clone().applyQuaternion(quaternion);
  56751. uvC = triangle.c.clone().applyQuaternion(quaternion);
  56752. // Compute UVs.
  56753. // Normalize x/y values of UV so they are within 0 to 1.
  56754. uvMinVector.set(Math.min(uvA.x, uvB.x, uvC.x), Math.min(uvA.y, uvB.y, uvC.y));
  56755. uvMaxVector.set(Math.max(uvA.x, uvB.x, uvC.x), Math.max(uvA.y, uvB.y, uvC.y));
  56756. uvScaleVector.set(0, 0).subVectors(uvMaxVector, uvMinVector);
  56757. uvA = new THREE.Vector2().subVectors(uvA, uvMinVector).divide(uvScaleVector);
  56758. uvB = new THREE.Vector2().subVectors(uvB, uvMinVector).divide(uvScaleVector);
  56759. uvC = new THREE.Vector2().subVectors(uvC, uvMinVector).divide(uvScaleVector);
  56760. geometry = this.geometry = new THREE.Geometry();
  56761. geometry.vertices.push(triangle.a);
  56762. geometry.vertices.push(triangle.b);
  56763. geometry.vertices.push(triangle.c);
  56764. geometry.faces.push(new THREE.Face3(0, 1, 2, normal));
  56765. geometry.faceVertexUvs[0] = [[uvA, uvB, uvC]];
  56766. }
  56767. });
  56768. },{"../core/geometry":129,"../lib/three":176}],174:[function(_dereq_,module,exports){
  56769. // Polyfill `Promise`.
  56770. window.Promise = window.Promise || _dereq_('promise-polyfill');
  56771. // WebVR polyfill
  56772. // Check before the polyfill runs.
  56773. window.hasNativeWebVRImplementation = !!window.navigator.getVRDisplays ||
  56774. !!window.navigator.getVRDevices;
  56775. window.hasNativeWebXRImplementation = navigator.xr !== undefined;
  56776. // If native WebXR or WebVR are defined WebVRPolyfill does not initialize.
  56777. if (!window.hasNativeWebXRImplementation && !window.hasNativeWebVRImplementation) {
  56778. var isIOSOlderThan10 = _dereq_('./utils/isIOSOlderThan10');
  56779. // Workaround for iOS Safari canvas sizing issues in stereo (webvr-polyfill/issues/102).
  56780. // Only for iOS on versions older than 10.
  56781. var bufferScale = isIOSOlderThan10(window.navigator.userAgent) ? 1 / window.devicePixelRatio : 1;
  56782. var WebVRPolyfill = _dereq_('webvr-polyfill');
  56783. var polyfillConfig = {
  56784. BUFFER_SCALE: bufferScale,
  56785. CARDBOARD_UI_DISABLED: true,
  56786. ROTATE_INSTRUCTIONS_DISABLED: true,
  56787. MOBILE_WAKE_LOCK: !!window.cordova
  56788. };
  56789. window.webvrpolyfill = new WebVRPolyfill(polyfillConfig);
  56790. }
  56791. var utils = _dereq_('./utils/');
  56792. var debug = utils.debug;
  56793. if (utils.isIE11) {
  56794. // Polyfill `CustomEvent`.
  56795. _dereq_('custom-event-polyfill');
  56796. // Polyfill String.startsWith.
  56797. _dereq_('../vendor/starts-with-polyfill');
  56798. }
  56799. var error = debug('A-Frame:error');
  56800. var warn = debug('A-Frame:warn');
  56801. if (window.document.currentScript && window.document.currentScript.parentNode !==
  56802. window.document.head && !window.debug) {
  56803. warn('Put the A-Frame <script> tag in the <head> of the HTML *before* the scene to ' +
  56804. 'ensure everything for A-Frame is properly registered before they are used from ' +
  56805. 'HTML.');
  56806. }
  56807. // Error if not using a server.
  56808. if (!window.cordova && window.location.protocol === 'file:') {
  56809. error(
  56810. 'This HTML file is currently being served via the file:// protocol. ' +
  56811. 'Assets, textures, and models WILL NOT WORK due to cross-origin policy! ' +
  56812. 'Please use a local or hosted server: ' +
  56813. 'https://aframe.io/docs/0.5.0/introduction/getting-started.html#using-a-local-server.');
  56814. }
  56815. _dereq_('present'); // Polyfill `performance.now()`.
  56816. // CSS.
  56817. if (utils.device.isBrowserEnvironment) {
  56818. _dereq_('./style/aframe.css');
  56819. _dereq_('./style/rStats.css');
  56820. }
  56821. // Required before `AEntity` so that all components are registered.
  56822. var AScene = _dereq_('./core/scene/a-scene').AScene;
  56823. var components = _dereq_('./core/component').components;
  56824. var registerComponent = _dereq_('./core/component').registerComponent;
  56825. var registerGeometry = _dereq_('./core/geometry').registerGeometry;
  56826. var registerPrimitive = _dereq_('./extras/primitives/primitives').registerPrimitive;
  56827. var registerShader = _dereq_('./core/shader').registerShader;
  56828. var registerSystem = _dereq_('./core/system').registerSystem;
  56829. var shaders = _dereq_('./core/shader').shaders;
  56830. var systems = _dereq_('./core/system').systems;
  56831. // Exports THREE to window so three.js can be used without alteration.
  56832. var THREE = window.THREE = _dereq_('./lib/three');
  56833. var pkg = _dereq_('../package');
  56834. _dereq_('./components/index'); // Register standard components.
  56835. _dereq_('./geometries/index'); // Register standard geometries.
  56836. _dereq_('./shaders/index'); // Register standard shaders.
  56837. _dereq_('./systems/index'); // Register standard systems.
  56838. var ANode = _dereq_('./core/a-node');
  56839. var AEntity = _dereq_('./core/a-entity'); // Depends on ANode and core components.
  56840. _dereq_('./core/a-assets');
  56841. _dereq_('./core/a-cubemap');
  56842. _dereq_('./core/a-mixin');
  56843. // Extras.
  56844. _dereq_('./extras/components/');
  56845. _dereq_('./extras/primitives/');
  56846. console.log('A-Frame Version: 1.0.4 (Date 2020-05-07, Commit #9022b97e)');
  56847. console.log('THREE Version (https://github.com/supermedium/three.js):',
  56848. pkg.dependencies['super-three']);
  56849. console.log('WebVR Polyfill Version:', pkg.dependencies['webvr-polyfill']);
  56850. module.exports = window.AFRAME = {
  56851. AComponent: _dereq_('./core/component').Component,
  56852. AEntity: AEntity,
  56853. ANode: ANode,
  56854. ANIME: _dereq_('super-animejs'),
  56855. AScene: AScene,
  56856. components: components,
  56857. coreComponents: Object.keys(components),
  56858. geometries: _dereq_('./core/geometry').geometries,
  56859. registerComponent: registerComponent,
  56860. registerElement: _dereq_('./core/a-register-element').registerElement,
  56861. registerGeometry: registerGeometry,
  56862. registerPrimitive: registerPrimitive,
  56863. registerShader: registerShader,
  56864. registerSystem: registerSystem,
  56865. primitives: {
  56866. getMeshMixin: _dereq_('./extras/primitives/getMeshMixin'),
  56867. primitives: _dereq_('./extras/primitives/primitives').primitives
  56868. },
  56869. scenes: _dereq_('./core/scene/scenes'),
  56870. schema: _dereq_('./core/schema'),
  56871. shaders: shaders,
  56872. systems: systems,
  56873. THREE: THREE,
  56874. utils: utils,
  56875. version: pkg.version
  56876. };
  56877. },{"../package":72,"../vendor/starts-with-polyfill":214,"./components/index":82,"./core/a-assets":122,"./core/a-cubemap":123,"./core/a-entity":124,"./core/a-mixin":125,"./core/a-node":126,"./core/a-register-element":127,"./core/component":128,"./core/geometry":129,"./core/scene/a-scene":131,"./core/scene/scenes":135,"./core/schema":137,"./core/shader":138,"./core/system":139,"./extras/components/":140,"./extras/primitives/":143,"./extras/primitives/getMeshMixin":142,"./extras/primitives/primitives":144,"./geometries/index":165,"./lib/three":176,"./shaders/index":178,"./style/aframe.css":183,"./style/rStats.css":184,"./systems/index":188,"./utils/":202,"./utils/isIOSOlderThan10":204,"custom-event-polyfill":7,"present":48,"promise-polyfill":50,"super-animejs":56,"webvr-polyfill":67}],175:[function(_dereq_,module,exports){
  56878. window.aframeStats = function (scene) {
  56879. var _rS = null;
  56880. var _scene = scene;
  56881. var _values = {
  56882. te: {
  56883. caption: 'Entities'
  56884. },
  56885. lt: {
  56886. caption: 'Load Time'
  56887. }
  56888. };
  56889. var _groups = [ {
  56890. caption: 'A-Frame',
  56891. values: [ 'te', 'lt' ]
  56892. } ];
  56893. function _update () {
  56894. _rS('te').set(getEntityCount());
  56895. if (window.performance.getEntriesByName) {
  56896. _rS('lt').set(window.performance.getEntriesByName('render-started')[0].startTime.toFixed(0));
  56897. }
  56898. }
  56899. function getEntityCount () {
  56900. var elements = _scene.querySelectorAll('*');
  56901. Array.prototype.slice.call(elements).filter(function (el) {
  56902. return el.isEntity;
  56903. });
  56904. return elements.length;
  56905. }
  56906. function _start () {}
  56907. function _end () {}
  56908. function _attach (r) {
  56909. _rS = r;
  56910. }
  56911. return {
  56912. update: _update,
  56913. start: _start,
  56914. end: _end,
  56915. attach: _attach,
  56916. values: _values,
  56917. groups: _groups,
  56918. fractions: []
  56919. };
  56920. };
  56921. if (typeof module === 'object') {
  56922. module.exports = {
  56923. aframeStats: window.aframeStats
  56924. };
  56925. }
  56926. },{}],176:[function(_dereq_,module,exports){
  56927. (function (global){
  56928. var THREE = global.THREE = _dereq_('super-three');
  56929. // Allow cross-origin images to be loaded.
  56930. // This should not be on `THREE.Loader` nor `THREE.ImageUtils`.
  56931. // Must be on `THREE.TextureLoader`.
  56932. if (THREE.TextureLoader) {
  56933. THREE.TextureLoader.prototype.crossOrigin = 'anonymous';
  56934. }
  56935. // This is for images loaded from the model loaders.
  56936. if (THREE.ImageLoader) {
  56937. THREE.ImageLoader.prototype.crossOrigin = 'anonymous';
  56938. }
  56939. // In-memory caching for XHRs (for images, audio files, textures, etc.).
  56940. if (THREE.Cache) {
  56941. THREE.Cache.enabled = true;
  56942. }
  56943. // TODO: Eventually include these only if they are needed by a component.
  56944. _dereq_('../../vendor/DeviceOrientationControls'); // THREE.DeviceOrientationControls
  56945. _dereq_('super-three/examples/js/loaders/DRACOLoader'); // THREE.DRACOLoader
  56946. _dereq_('super-three/examples/js/loaders/GLTFLoader'); // THREE.GLTFLoader
  56947. _dereq_('super-three/examples/js/loaders/OBJLoader'); // THREE.OBJLoader
  56948. _dereq_('super-three/examples/js/loaders/MTLLoader'); // THREE.MTLLoader
  56949. THREE.DRACOLoader.prototype.crossOrigin = 'anonymous';
  56950. THREE.GLTFLoader.prototype.crossOrigin = 'anonymous';
  56951. THREE.MTLLoader.prototype.crossOrigin = 'anonymous';
  56952. THREE.OBJLoader.prototype.crossOrigin = 'anonymous';
  56953. module.exports = THREE;
  56954. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  56955. },{"../../vendor/DeviceOrientationControls":211,"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}],177:[function(_dereq_,module,exports){
  56956. var registerShader = _dereq_('../core/shader').registerShader;
  56957. var THREE = _dereq_('../lib/three');
  56958. var utils = _dereq_('../utils/');
  56959. /**
  56960. * Flat shader using THREE.MeshBasicMaterial.
  56961. */
  56962. module.exports.Shader = registerShader('flat', {
  56963. schema: {
  56964. color: {type: 'color'},
  56965. fog: {default: true},
  56966. height: {default: 256},
  56967. offset: {type: 'vec2', default: {x: 0, y: 0}},
  56968. repeat: {type: 'vec2', default: {x: 1, y: 1}},
  56969. src: {type: 'map'},
  56970. width: {default: 512},
  56971. wireframe: {default: false},
  56972. wireframeLinewidth: {default: 2}
  56973. },
  56974. /**
  56975. * Initializes the shader.
  56976. * Adds a reference from the scene to this entity as the camera.
  56977. */
  56978. init: function (data) {
  56979. this.rendererSystem = this.el.sceneEl.systems.renderer;
  56980. this.materialData = {color: new THREE.Color()};
  56981. this.textureSrc = null;
  56982. getMaterialData(data, this.materialData);
  56983. this.rendererSystem.applyColorCorrection(this.materialData.color);
  56984. this.material = new THREE.MeshBasicMaterial(this.materialData);
  56985. utils.material.updateMap(this, data);
  56986. },
  56987. update: function (data) {
  56988. this.updateMaterial(data);
  56989. utils.material.updateMap(this, data);
  56990. },
  56991. /**
  56992. * Updating existing material.
  56993. *
  56994. * @param {object} data - Material component data.
  56995. */
  56996. updateMaterial: function (data) {
  56997. var key;
  56998. getMaterialData(data, this.materialData);
  56999. this.rendererSystem.applyColorCorrection(this.materialData.color);
  57000. for (key in this.materialData) {
  57001. this.material[key] = this.materialData[key];
  57002. }
  57003. }
  57004. });
  57005. /**
  57006. * Builds and normalize material data, normalizing stuff along the way.
  57007. *
  57008. * @param {object} data - Material data.
  57009. * @param {object} materialData - Object to reuse.
  57010. * @returns {object} Updated material data.
  57011. */
  57012. function getMaterialData (data, materialData) {
  57013. materialData.color.set(data.color);
  57014. materialData.fog = data.fog;
  57015. materialData.wireframe = data.wireframe;
  57016. materialData.wireframeLinewidth = data.wireframeLinewidth;
  57017. return materialData;
  57018. }
  57019. },{"../core/shader":138,"../lib/three":176,"../utils/":202}],178:[function(_dereq_,module,exports){
  57020. _dereq_('./flat');
  57021. _dereq_('./standard');
  57022. _dereq_('./sdf');
  57023. _dereq_('./msdf');
  57024. _dereq_('./ios10hls');
  57025. },{"./flat":177,"./ios10hls":179,"./msdf":180,"./sdf":181,"./standard":182}],179:[function(_dereq_,module,exports){
  57026. var registerShader = _dereq_('../core/shader').registerShader;
  57027. /**
  57028. * Custom shader for iOS 10 HTTP Live Streaming (HLS).
  57029. * For more information on HLS, see https://datatracker.ietf.org/doc/draft-pantos-http-live-streaming/
  57030. */
  57031. module.exports.Shader = registerShader('ios10hls', {
  57032. schema: {
  57033. src: {type: 'map', is: 'uniform'},
  57034. opacity: {type: 'number', is: 'uniform', default: 1}
  57035. },
  57036. vertexShader: [
  57037. 'varying vec2 vUV;',
  57038. 'void main(void) {',
  57039. ' gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);',
  57040. ' vUV = uv;',
  57041. '}'
  57042. ].join('\n'),
  57043. fragmentShader: [
  57044. 'uniform sampler2D src;',
  57045. 'uniform float opacity;',
  57046. 'varying vec2 vUV;',
  57047. 'void main() {',
  57048. ' vec2 offset = vec2(0, 0);',
  57049. ' vec2 repeat = vec2(1, 1);',
  57050. ' vec4 color = texture2D(src, vec2(vUV.x / repeat.x + offset.x, (1.0 - vUV.y) / repeat.y + offset.y)).bgra;',
  57051. ' gl_FragColor = vec4(color.rgb, opacity);',
  57052. '}'
  57053. ].join('\n')
  57054. });
  57055. },{"../core/shader":138}],180:[function(_dereq_,module,exports){
  57056. var registerShader = _dereq_('../core/shader').registerShader;
  57057. /**
  57058. * Multi-channel signed distance field.
  57059. * Used by text component.
  57060. */
  57061. module.exports.Shader = registerShader('msdf', {
  57062. schema: {
  57063. alphaTest: {type: 'number', is: 'uniform', default: 0.5},
  57064. color: {type: 'color', is: 'uniform', default: 'white'},
  57065. map: {type: 'map', is: 'uniform'},
  57066. negate: {type: 'boolean', is: 'uniform', default: true},
  57067. opacity: {type: 'number', is: 'uniform', default: 1.0}
  57068. },
  57069. raw: true,
  57070. vertexShader: [
  57071. 'attribute vec2 uv;',
  57072. 'attribute vec3 position;',
  57073. 'uniform mat4 projectionMatrix;',
  57074. 'uniform mat4 modelViewMatrix;',
  57075. 'varying vec2 vUV;',
  57076. 'void main(void) {',
  57077. ' gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);',
  57078. ' vUV = uv;',
  57079. '}'
  57080. ].join('\n'),
  57081. fragmentShader: [
  57082. '#ifdef GL_OES_standard_derivatives',
  57083. '#extension GL_OES_standard_derivatives: enable',
  57084. '#endif',
  57085. 'precision highp float;',
  57086. 'uniform bool negate;',
  57087. 'uniform float alphaTest;',
  57088. 'uniform float opacity;',
  57089. 'uniform sampler2D map;',
  57090. 'uniform vec3 color;',
  57091. 'varying vec2 vUV;',
  57092. 'float median(float r, float g, float b) {',
  57093. ' return max(min(r, g), min(max(r, g), b));',
  57094. '}',
  57095. // FIXME: Experimentally determined constants.
  57096. '#define BIG_ENOUGH 0.001',
  57097. '#define MODIFIED_ALPHATEST (0.02 * isBigEnough / BIG_ENOUGH)',
  57098. 'void main() {',
  57099. ' vec3 sampleColor = texture2D(map, vUV).rgb;',
  57100. ' if (negate) { sampleColor = 1.0 - sampleColor; }',
  57101. ' float sigDist = median(sampleColor.r, sampleColor.g, sampleColor.b) - 0.5;',
  57102. ' float alpha = clamp(sigDist / fwidth(sigDist) + 0.5, 0.0, 1.0);',
  57103. ' float dscale = 0.353505;',
  57104. ' vec2 duv = dscale * (dFdx(vUV) + dFdy(vUV));',
  57105. ' float isBigEnough = max(abs(duv.x), abs(duv.y));',
  57106. // When texel is too small, blend raw alpha value rather than supersampling.
  57107. // FIXME: Experimentally determined constant.
  57108. ' // Do modified alpha test.',
  57109. ' if (isBigEnough > BIG_ENOUGH) {',
  57110. ' float ratio = BIG_ENOUGH / isBigEnough;',
  57111. ' alpha = ratio * alpha + (1.0 - ratio) * (sigDist + 0.5);',
  57112. ' }',
  57113. ' // Do modified alpha test.',
  57114. ' if (alpha < alphaTest * MODIFIED_ALPHATEST) { discard; return; }',
  57115. ' gl_FragColor = vec4(color.xyz, alpha * opacity);',
  57116. '}'
  57117. ].join('\n')
  57118. });
  57119. },{"../core/shader":138}],181:[function(_dereq_,module,exports){
  57120. var registerShader = _dereq_('../core/shader').registerShader;
  57121. /**
  57122. * Signed distance field.
  57123. * Used by text component.
  57124. */
  57125. module.exports.Shader = registerShader('sdf', {
  57126. schema: {
  57127. alphaTest: {type: 'number', is: 'uniform', default: 0.5},
  57128. color: {type: 'color', is: 'uniform', default: 'white'},
  57129. map: {type: 'map', is: 'uniform'},
  57130. opacity: {type: 'number', is: 'uniform', default: 1.0}
  57131. },
  57132. raw: true,
  57133. vertexShader: [
  57134. 'attribute vec2 uv;',
  57135. 'attribute vec3 position;',
  57136. 'uniform mat4 projectionMatrix;',
  57137. 'uniform mat4 modelViewMatrix;',
  57138. 'varying vec2 vUV;',
  57139. 'void main(void) {',
  57140. ' gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);',
  57141. ' vUV = uv;',
  57142. '}'
  57143. ].join('\n'),
  57144. fragmentShader: [
  57145. '#ifdef GL_OES_standard_derivatives',
  57146. '#extension GL_OES_standard_derivatives: enable',
  57147. '#endif',
  57148. 'precision highp float;',
  57149. 'uniform float alphaTest;',
  57150. 'uniform float opacity;',
  57151. 'uniform sampler2D map;',
  57152. 'uniform vec3 color;',
  57153. 'varying vec2 vUV;',
  57154. '#ifdef GL_OES_standard_derivatives',
  57155. ' float contour(float width, float value) {',
  57156. ' return smoothstep(0.5 - value, 0.5 + value, width);',
  57157. ' }',
  57158. '#else',
  57159. ' float aastep(float value, float afwidth) {',
  57160. ' return smoothstep(0.5 - afwidth, 0.5 + afwidth, value);',
  57161. ' }',
  57162. '#endif',
  57163. // FIXME: Experimentally determined constants.
  57164. '#define BIG_ENOUGH 0.001',
  57165. '#define MODIFIED_ALPHATEST (0.02 * isBigEnough / BIG_ENOUGH)',
  57166. '#define ALL_SMOOTH 0.4',
  57167. '#define ALL_ROUGH 0.02',
  57168. '#define DISCARD_ALPHA (alphaTest / (2.2 - 1.2 * ratio))',
  57169. 'void main() {',
  57170. // When we have derivatives and can get texel size for supersampling.
  57171. ' #ifdef GL_OES_standard_derivatives',
  57172. ' vec2 uv = vUV;',
  57173. ' vec4 texColor = texture2D(map, uv);',
  57174. ' float dist = texColor.a;',
  57175. ' float width = fwidth(dist);',
  57176. ' float alpha = contour(dist, width);',
  57177. ' float dscale = 0.353505;',
  57178. ' vec2 duv = dscale * (dFdx(uv) + dFdy(uv));',
  57179. ' float isBigEnough = max(abs(duv.x), abs(duv.y));',
  57180. // When texel is too small, blend raw alpha value rather than supersampling.
  57181. // FIXME: experimentally determined constant
  57182. ' if (isBigEnough > BIG_ENOUGH) {',
  57183. ' float ratio = BIG_ENOUGH / isBigEnough;',
  57184. ' alpha = ratio * alpha + (1.0 - ratio) * dist;',
  57185. ' }',
  57186. // Otherwise do weighted supersampling.
  57187. // FIXME: why this weighting?
  57188. ' if (isBigEnough <= BIG_ENOUGH) {',
  57189. ' vec4 box = vec4 (uv - duv, uv + duv);',
  57190. ' alpha = (alpha + 0.5 * (',
  57191. ' contour(texture2D(map, box.xy).a, width)',
  57192. ' + contour(texture2D(map, box.zw).a, width)',
  57193. ' + contour(texture2D(map, box.xw).a, width)',
  57194. ' + contour(texture2D(map, box.zy).a, width)',
  57195. ' )) / 3.0;',
  57196. ' }',
  57197. // Do modified alpha test.
  57198. ' if (alpha < alphaTest * MODIFIED_ALPHATEST) { discard; return; }',
  57199. ' #else',
  57200. // When we don't have derivatives, use approximations.
  57201. ' vec4 texColor = texture2D(map, vUV);',
  57202. ' float value = texColor.a;',
  57203. // FIXME: if we understood font pixel dimensions, this could probably be improved
  57204. ' float afwidth = (1.0 / 32.0) * (1.4142135623730951 / (2.0 * gl_FragCoord.w));',
  57205. ' float alpha = aastep(value, afwidth);',
  57206. // Use gl_FragCoord.w to guess when we should blend.
  57207. // FIXME: If we understood font pixel dimensions, this could probably be improved.
  57208. ' 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);',
  57209. ' if (alpha < alphaTest) { if (ratio >= 1.0) { discard; return; } alpha = 0.0; }',
  57210. ' alpha = alpha * ratio + (1.0 - ratio) * value;',
  57211. ' if (ratio < 1.0 && alpha <= DISCARD_ALPHA) { discard; return; }',
  57212. ' #endif',
  57213. ' gl_FragColor = vec4(color, opacity * alpha);',
  57214. '}'
  57215. ].join('\n')
  57216. });
  57217. },{"../core/shader":138}],182:[function(_dereq_,module,exports){
  57218. var registerShader = _dereq_('../core/shader').registerShader;
  57219. var THREE = _dereq_('../lib/three');
  57220. var utils = _dereq_('../utils/');
  57221. var CubeLoader = new THREE.CubeTextureLoader();
  57222. var texturePromises = {};
  57223. /**
  57224. * Standard (physically-based) shader using THREE.MeshStandardMaterial.
  57225. */
  57226. module.exports.Shader = registerShader('standard', {
  57227. schema: {
  57228. ambientOcclusionMap: {type: 'map'},
  57229. ambientOcclusionMapIntensity: {default: 1},
  57230. ambientOcclusionTextureOffset: {type: 'vec2'},
  57231. ambientOcclusionTextureRepeat: {type: 'vec2', default: {x: 1, y: 1}},
  57232. color: {type: 'color'},
  57233. displacementMap: {type: 'map'},
  57234. displacementScale: {default: 1},
  57235. displacementBias: {default: 0.5},
  57236. displacementTextureOffset: {type: 'vec2'},
  57237. displacementTextureRepeat: {type: 'vec2', default: {x: 1, y: 1}},
  57238. emissive: {type: 'color', default: '#000'},
  57239. emissiveIntensity: {default: 1},
  57240. envMap: {default: ''},
  57241. fog: {default: true},
  57242. height: {default: 256},
  57243. metalness: {default: 0.0, min: 0.0, max: 1.0},
  57244. metalnessMap: {type: 'map'},
  57245. metalnessTextureOffset: {type: 'vec2'},
  57246. metalnessTextureRepeat: {type: 'vec2', default: {x: 1, y: 1}},
  57247. normalMap: {type: 'map'},
  57248. normalScale: {type: 'vec2', default: {x: 1, y: 1}},
  57249. normalTextureOffset: {type: 'vec2'},
  57250. normalTextureRepeat: {type: 'vec2', default: {x: 1, y: 1}},
  57251. offset: {type: 'vec2', default: {x: 0, y: 0}},
  57252. repeat: {type: 'vec2', default: {x: 1, y: 1}},
  57253. roughness: {default: 0.5, min: 0.0, max: 1.0},
  57254. roughnessMap: {type: 'map'},
  57255. roughnessTextureOffset: {type: 'vec2'},
  57256. roughnessTextureRepeat: {type: 'vec2', default: {x: 1, y: 1}},
  57257. sphericalEnvMap: {type: 'map'},
  57258. src: {type: 'map'},
  57259. width: {default: 512},
  57260. wireframe: {default: false},
  57261. wireframeLinewidth: {default: 2}
  57262. },
  57263. /**
  57264. * Initializes the shader.
  57265. * Adds a reference from the scene to this entity as the camera.
  57266. */
  57267. init: function (data) {
  57268. this.rendererSystem = this.el.sceneEl.systems.renderer;
  57269. this.materialData = {color: new THREE.Color(), emissive: new THREE.Color()};
  57270. getMaterialData(data, this.materialData);
  57271. this.rendererSystem.applyColorCorrection(this.materialData.color);
  57272. this.rendererSystem.applyColorCorrection(this.materialData.emissive);
  57273. this.material = new THREE.MeshStandardMaterial(this.materialData);
  57274. utils.material.updateMap(this, data);
  57275. if (data.normalMap) { utils.material.updateDistortionMap('normal', this, data); }
  57276. if (data.displacementMap) { utils.material.updateDistortionMap('displacement', this, data); }
  57277. if (data.ambientOcclusionMap) { utils.material.updateDistortionMap('ambientOcclusion', this, data); }
  57278. if (data.metalnessMap) { utils.material.updateDistortionMap('metalness', this, data); }
  57279. if (data.roughnessMap) { utils.material.updateDistortionMap('roughness', this, data); }
  57280. this.updateEnvMap(data);
  57281. },
  57282. update: function (data) {
  57283. this.updateMaterial(data);
  57284. utils.material.updateMap(this, data);
  57285. if (data.normalMap) { utils.material.updateDistortionMap('normal', this, data); }
  57286. if (data.displacementMap) { utils.material.updateDistortionMap('displacement', this, data); }
  57287. if (data.ambientOcclusionMap) { utils.material.updateDistortionMap('ambientOcclusion', this, data); }
  57288. if (data.metalnessMap) { utils.material.updateDistortionMap('metalness', this, data); }
  57289. if (data.roughnessMap) { utils.material.updateDistortionMap('roughness', this, data); }
  57290. this.updateEnvMap(data);
  57291. },
  57292. /**
  57293. * Updating existing material.
  57294. *
  57295. * @param {object} data - Material component data.
  57296. * @returns {object} Material.
  57297. */
  57298. updateMaterial: function (data) {
  57299. var key;
  57300. var material = this.material;
  57301. getMaterialData(data, this.materialData);
  57302. this.rendererSystem.applyColorCorrection(this.materialData.color);
  57303. this.rendererSystem.applyColorCorrection(this.materialData.emissive);
  57304. for (key in this.materialData) {
  57305. material[key] = this.materialData[key];
  57306. }
  57307. },
  57308. /**
  57309. * Handle environment cubemap. Textures are cached in texturePromises.
  57310. */
  57311. updateEnvMap: function (data) {
  57312. var self = this;
  57313. var material = this.material;
  57314. var envMap = data.envMap;
  57315. var sphericalEnvMap = data.sphericalEnvMap;
  57316. // No envMap defined or already loading.
  57317. if ((!envMap && !sphericalEnvMap) || this.isLoadingEnvMap) {
  57318. material.envMap = null;
  57319. material.needsUpdate = true;
  57320. return;
  57321. }
  57322. this.isLoadingEnvMap = true;
  57323. // if a spherical env map is defined then use it.
  57324. if (sphericalEnvMap) {
  57325. this.el.sceneEl.systems.material.loadTexture(sphericalEnvMap, {src: sphericalEnvMap}, function textureLoaded (texture) {
  57326. self.isLoadingEnvMap = false;
  57327. texture.mapping = THREE.SphericalReflectionMapping;
  57328. material.envMap = texture;
  57329. utils.material.handleTextureEvents(self.el, texture);
  57330. material.needsUpdate = true;
  57331. });
  57332. return;
  57333. }
  57334. // Another material is already loading this texture. Wait on promise.
  57335. if (texturePromises[envMap]) {
  57336. texturePromises[envMap].then(function (cube) {
  57337. self.isLoadingEnvMap = false;
  57338. material.envMap = cube;
  57339. utils.material.handleTextureEvents(self.el, cube);
  57340. material.needsUpdate = true;
  57341. });
  57342. return;
  57343. }
  57344. // Material is first to load this texture. Load and resolve texture.
  57345. texturePromises[envMap] = new Promise(function (resolve) {
  57346. utils.srcLoader.validateCubemapSrc(envMap, function loadEnvMap (urls) {
  57347. CubeLoader.load(urls, function (cube) {
  57348. // Texture loaded.
  57349. self.isLoadingEnvMap = false;
  57350. material.envMap = cube;
  57351. utils.material.handleTextureEvents(self.el, cube);
  57352. resolve(cube);
  57353. });
  57354. });
  57355. });
  57356. }
  57357. });
  57358. /**
  57359. * Builds and normalize material data, normalizing stuff along the way.
  57360. *
  57361. * @param {object} data - Material data.
  57362. * @param {object} materialData - Object to use.
  57363. * @returns {object} Updated materialData.
  57364. */
  57365. function getMaterialData (data, materialData) {
  57366. materialData.color.set(data.color);
  57367. materialData.emissive.set(data.emissive);
  57368. materialData.emissiveIntensity = data.emissiveIntensity;
  57369. materialData.fog = data.fog;
  57370. materialData.metalness = data.metalness;
  57371. materialData.roughness = data.roughness;
  57372. materialData.wireframe = data.wireframe;
  57373. materialData.wireframeLinewidth = data.wireframeLinewidth;
  57374. if (data.normalMap) { materialData.normalScale = data.normalScale; }
  57375. if (data.ambientOcclusionMap) {
  57376. materialData.aoMapIntensity = data.ambientOcclusionMapIntensity;
  57377. }
  57378. if (data.displacementMap) {
  57379. materialData.displacementScale = data.displacementScale;
  57380. materialData.displacementBias = data.displacementBias;
  57381. }
  57382. return materialData;
  57383. }
  57384. },{"../core/shader":138,"../lib/three":176,"../utils/":202}],183:[function(_dereq_,module,exports){
  57385. 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;
  57386. },{"browserify-css":4}],184:[function(_dereq_,module,exports){
  57387. 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;
  57388. },{"browserify-css":4}],185:[function(_dereq_,module,exports){
  57389. var constants = _dereq_('../constants/');
  57390. var registerSystem = _dereq_('../core/system').registerSystem;
  57391. var DEFAULT_CAMERA_ATTR = 'data-aframe-default-camera';
  57392. /**
  57393. * Camera system. Manages which camera is active among multiple cameras in scene.
  57394. *
  57395. * @member {object} activeCameraEl - Active camera entity.
  57396. */
  57397. module.exports.System = registerSystem('camera', {
  57398. init: function () {
  57399. this.activeCameraEl = null;
  57400. this.render = this.render.bind(this);
  57401. this.unwrapRender = this.unwrapRender.bind(this);
  57402. this.wrapRender = this.wrapRender.bind(this);
  57403. this.initialCameraFound = false;
  57404. this.numUserCameras = 0;
  57405. this.numUserCamerasChecked = 0;
  57406. this.setupInitialCamera();
  57407. },
  57408. /**
  57409. * Setup initial camera, either searching for camera or
  57410. * creating a default camera if user has not added one during the initial scene traversal.
  57411. * We want sceneEl.camera to be ready, set, and initialized before the rest of the scene
  57412. * loads.
  57413. *
  57414. * Default camera offset height is at average eye level (~1.6m).
  57415. */
  57416. setupInitialCamera: function () {
  57417. var cameraEls;
  57418. var i;
  57419. var sceneEl = this.sceneEl;
  57420. var self = this;
  57421. // Camera already defined or the one defined it is an spectator one.
  57422. if (sceneEl.camera && !sceneEl.camera.el.getAttribute('camera').spectator) {
  57423. sceneEl.emit('cameraready', {cameraEl: sceneEl.camera.el});
  57424. return;
  57425. }
  57426. // Search for initial user-defined camera.
  57427. cameraEls = sceneEl.querySelectorAll('a-camera, [camera]');
  57428. // No user cameras, create default one.
  57429. if (!cameraEls.length) {
  57430. this.createDefaultCamera();
  57431. return;
  57432. }
  57433. this.numUserCameras = cameraEls.length;
  57434. for (i = 0; i < cameraEls.length; i++) {
  57435. cameraEls[i].addEventListener('object3dset', function (evt) {
  57436. if (evt.detail.type !== 'camera') { return; }
  57437. self.checkUserCamera(this);
  57438. });
  57439. // Load camera and wait for camera to initialize.
  57440. if (cameraEls[i].isNode) {
  57441. cameraEls[i].load();
  57442. } else {
  57443. cameraEls[i].addEventListener('nodeready', function () {
  57444. this.load();
  57445. });
  57446. }
  57447. }
  57448. },
  57449. /**
  57450. * Check if a user-defined camera entity is appropriate to be initial camera.
  57451. * (active + non-spectator).
  57452. *
  57453. * Keep track of the number of cameras we checked and whether we found one.
  57454. */
  57455. checkUserCamera: function (cameraEl) {
  57456. var cameraData;
  57457. var sceneEl = this.el.sceneEl;
  57458. this.numUserCamerasChecked++;
  57459. // Already found one.
  57460. if (this.initialCameraFound) { return; }
  57461. // Check if camera is appropriate for being the initial camera.
  57462. cameraData = cameraEl.getAttribute('camera');
  57463. if (!cameraData.active || cameraData.spectator) {
  57464. // No user cameras eligible, create default camera.
  57465. if (this.numUserCamerasChecked === this.numUserCameras) {
  57466. this.createDefaultCamera();
  57467. }
  57468. return;
  57469. }
  57470. this.initialCameraFound = true;
  57471. sceneEl.camera = cameraEl.getObject3D('camera');
  57472. sceneEl.emit('cameraready', {cameraEl: cameraEl});
  57473. },
  57474. createDefaultCamera: function () {
  57475. var defaultCameraEl;
  57476. var sceneEl = this.sceneEl;
  57477. // Set up default camera.
  57478. defaultCameraEl = document.createElement('a-entity');
  57479. defaultCameraEl.setAttribute('camera', {active: true});
  57480. defaultCameraEl.setAttribute('position', {
  57481. x: 0,
  57482. y: constants.DEFAULT_CAMERA_HEIGHT,
  57483. z: 0
  57484. });
  57485. defaultCameraEl.setAttribute('wasd-controls', '');
  57486. defaultCameraEl.setAttribute('look-controls', '');
  57487. defaultCameraEl.setAttribute(constants.AFRAME_INJECTED, '');
  57488. defaultCameraEl.addEventListener('object3dset', function (evt) {
  57489. if (evt.detail.type !== 'camera') { return; }
  57490. sceneEl.camera = evt.detail.object;
  57491. sceneEl.emit('cameraready', {cameraEl: defaultCameraEl});
  57492. });
  57493. sceneEl.appendChild(defaultCameraEl);
  57494. },
  57495. /**
  57496. * Set a different active camera.
  57497. * When we choose a (sort of) random scene camera as the replacement, set its `active` to
  57498. * true. The camera component will call `setActiveCamera` and handle passing the torch to
  57499. * the new camera.
  57500. */
  57501. disableActiveCamera: function () {
  57502. var cameraEls;
  57503. var newActiveCameraEl;
  57504. cameraEls = this.sceneEl.querySelectorAll('[camera]');
  57505. newActiveCameraEl = cameraEls[cameraEls.length - 1];
  57506. newActiveCameraEl.setAttribute('camera', 'active', true);
  57507. },
  57508. /**
  57509. * Set active camera to be used by renderer.
  57510. * Removes the default camera (if present).
  57511. * Disables all other cameras in the scene.
  57512. *
  57513. * @param {Element} newCameraEl - Entity with camera component.
  57514. */
  57515. setActiveCamera: function (newCameraEl) {
  57516. var cameraEl;
  57517. var cameraEls;
  57518. var i;
  57519. var newCamera;
  57520. var previousCamera = this.activeCameraEl;
  57521. var sceneEl = this.sceneEl;
  57522. // Same camera.
  57523. newCamera = newCameraEl.getObject3D('camera');
  57524. if (!newCamera || newCameraEl === this.activeCameraEl) { return; }
  57525. // Grab the default camera.
  57526. var defaultCameraWrapper = sceneEl.querySelector('[' + DEFAULT_CAMERA_ATTR + ']');
  57527. var defaultCameraEl = defaultCameraWrapper &&
  57528. defaultCameraWrapper.querySelector('[camera]');
  57529. // Remove default camera if new camera is not the default camera.
  57530. if (newCameraEl !== defaultCameraEl) { removeDefaultCamera(sceneEl); }
  57531. // Make new camera active.
  57532. this.activeCameraEl = newCameraEl;
  57533. this.activeCameraEl.play();
  57534. sceneEl.camera = newCamera;
  57535. // Disable current camera
  57536. if (previousCamera) {
  57537. previousCamera.setAttribute('camera', 'active', false);
  57538. }
  57539. // Disable other cameras in the scene
  57540. cameraEls = sceneEl.querySelectorAll('[camera]');
  57541. for (i = 0; i < cameraEls.length; i++) {
  57542. cameraEl = cameraEls[i];
  57543. if (!cameraEl.isEntity || newCameraEl === cameraEl) { continue; }
  57544. cameraEl.setAttribute('camera', 'active', false);
  57545. cameraEl.pause();
  57546. }
  57547. sceneEl.emit('camera-set-active', {cameraEl: newCameraEl});
  57548. },
  57549. /**
  57550. * Set spectator camera to render the scene on a 2D display.
  57551. *
  57552. * @param {Element} newCameraEl - Entity with camera component.
  57553. */
  57554. setSpectatorCamera: function (newCameraEl) {
  57555. var newCamera;
  57556. var previousCamera = this.spectatorCameraEl;
  57557. var sceneEl = this.sceneEl;
  57558. var spectatorCameraEl;
  57559. // Same camera.
  57560. newCamera = newCameraEl.getObject3D('camera');
  57561. if (!newCamera || newCameraEl === this.spectatorCameraEl) { return; }
  57562. // Disable current camera
  57563. if (previousCamera) {
  57564. previousCamera.setAttribute('camera', 'spectator', false);
  57565. }
  57566. spectatorCameraEl = this.spectatorCameraEl = newCameraEl;
  57567. sceneEl.addEventListener('enter-vr', this.wrapRender);
  57568. sceneEl.addEventListener('exit-vr', this.unwrapRender);
  57569. spectatorCameraEl.setAttribute('camera', 'active', false);
  57570. spectatorCameraEl.play();
  57571. sceneEl.emit('camera-set-spectator', {cameraEl: newCameraEl});
  57572. },
  57573. /**
  57574. * Disables current spectator camera.
  57575. */
  57576. disableSpectatorCamera: function () {
  57577. this.spectatorCameraEl = undefined;
  57578. },
  57579. /**
  57580. * Wrap the render method of the renderer to render
  57581. * the spectator camera after vrDisplay.submitFrame.
  57582. */
  57583. wrapRender: function () {
  57584. if (!this.spectatorCameraEl) { return; }
  57585. this.originalRender = this.sceneEl.renderer.render;
  57586. this.sceneEl.renderer.render = this.render;
  57587. },
  57588. unwrapRender: function () {
  57589. if (!this.originalRender) { return; }
  57590. this.sceneEl.renderer.render = this.originalRender;
  57591. this.originalRender = undefined;
  57592. },
  57593. render: function (scene, camera) {
  57594. var isVREnabled;
  57595. var sceneEl = this.sceneEl;
  57596. var spectatorCamera;
  57597. isVREnabled = sceneEl.renderer.xr.enabled;
  57598. this.originalRender.call(sceneEl.renderer, scene, camera);
  57599. if (!this.spectatorCameraEl || sceneEl.isMobile || !isVREnabled) { return; }
  57600. spectatorCamera = this.spectatorCameraEl.components.camera.camera;
  57601. sceneEl.renderer.xr.enabled = false;
  57602. this.originalRender.call(sceneEl.renderer, scene, spectatorCamera);
  57603. sceneEl.renderer.xr.enabled = isVREnabled;
  57604. }
  57605. });
  57606. /**
  57607. * Remove injected default camera from scene, if present.
  57608. *
  57609. * @param {Element} sceneEl
  57610. */
  57611. function removeDefaultCamera (sceneEl) {
  57612. var defaultCamera;
  57613. var camera = sceneEl.camera;
  57614. if (!camera) { return; }
  57615. // Remove default camera if present.
  57616. defaultCamera = sceneEl.querySelector('[' + DEFAULT_CAMERA_ATTR + ']');
  57617. if (!defaultCamera) { return; }
  57618. sceneEl.removeChild(defaultCamera);
  57619. }
  57620. },{"../constants/":120,"../core/system":139}],186:[function(_dereq_,module,exports){
  57621. var geometries = _dereq_('../core/geometry').geometries;
  57622. var registerSystem = _dereq_('../core/system').registerSystem;
  57623. var THREE = _dereq_('../lib/three');
  57624. /**
  57625. * System for geometry component.
  57626. * Handle geometry caching.
  57627. *
  57628. * @member {object} cache - Mapping of stringified component data to THREE.Geometry objects.
  57629. * @member {object} cacheCount - Keep track of number of entities using a geometry to
  57630. * know whether to dispose on removal.
  57631. */
  57632. module.exports.System = registerSystem('geometry', {
  57633. init: function () {
  57634. this.cache = {};
  57635. this.cacheCount = {};
  57636. },
  57637. /**
  57638. * Reset cache. Mainly for testing.
  57639. */
  57640. clearCache: function () {
  57641. this.cache = {};
  57642. this.cacheCount = {};
  57643. },
  57644. /**
  57645. * Attempt to retrieve from cache.
  57646. *
  57647. * @returns {Object|null} A geometry if it exists, else null.
  57648. */
  57649. getOrCreateGeometry: function (data) {
  57650. var cache = this.cache;
  57651. var cachedGeometry;
  57652. var hash;
  57653. // Skip all caching logic.
  57654. if (data.skipCache) { return createGeometry(data); }
  57655. // Try to retrieve from cache first.
  57656. hash = this.hash(data);
  57657. cachedGeometry = cache[hash];
  57658. incrementCacheCount(this.cacheCount, hash);
  57659. if (cachedGeometry) { return cachedGeometry; }
  57660. // Create geometry.
  57661. cachedGeometry = createGeometry(data);
  57662. // Cache and return geometry.
  57663. cache[hash] = cachedGeometry;
  57664. return cachedGeometry;
  57665. },
  57666. /**
  57667. * Let system know that an entity is no longer using a geometry.
  57668. */
  57669. unuseGeometry: function (data) {
  57670. var cache = this.cache;
  57671. var cacheCount = this.cacheCount;
  57672. var geometry;
  57673. var hash;
  57674. if (data.skipCache) { return; }
  57675. hash = this.hash(data);
  57676. if (!cache[hash]) { return; }
  57677. decrementCacheCount(cacheCount, hash);
  57678. // Another entity is still using this geometry. No need to do anything.
  57679. if (cacheCount[hash] > 0) { return; }
  57680. // No more entities are using this geometry. Dispose.
  57681. geometry = cache[hash];
  57682. geometry.dispose();
  57683. delete cache[hash];
  57684. delete cacheCount[hash];
  57685. },
  57686. /**
  57687. * Use JSON.stringify to turn component data into hash.
  57688. * Should be deterministic within a single browser engine.
  57689. * If not, then look into json-stable-stringify.
  57690. */
  57691. hash: function (data) {
  57692. return JSON.stringify(data);
  57693. }
  57694. });
  57695. /**
  57696. * Create geometry using component data.
  57697. *
  57698. * @param {object} data - Component data.
  57699. * @returns {object} Geometry.
  57700. */
  57701. function createGeometry (data) {
  57702. var geometryType = data.primitive;
  57703. var GeometryClass = geometries[geometryType] && geometries[geometryType].Geometry;
  57704. var geometryInstance = new GeometryClass();
  57705. if (!GeometryClass) { throw new Error('Unknown geometry `' + geometryType + '`'); }
  57706. geometryInstance.init(data);
  57707. return toBufferGeometry(geometryInstance.geometry, data.buffer);
  57708. }
  57709. /**
  57710. * Decreate count of entity using a geometry.
  57711. */
  57712. function decrementCacheCount (cacheCount, hash) {
  57713. cacheCount[hash]--;
  57714. }
  57715. /**
  57716. * Increase count of entity using a geometry.
  57717. */
  57718. function incrementCacheCount (cacheCount, hash) {
  57719. cacheCount[hash] = cacheCount[hash] === undefined ? 1 : cacheCount[hash] + 1;
  57720. }
  57721. /**
  57722. * Transform geometry to BufferGeometry if `doBuffer`.
  57723. *
  57724. * @param {object} geometry
  57725. * @param {boolean} doBuffer
  57726. * @returns {object} Geometry.
  57727. */
  57728. function toBufferGeometry (geometry, doBuffer) {
  57729. var bufferGeometry;
  57730. if (!doBuffer) { return geometry; }
  57731. bufferGeometry = new THREE.BufferGeometry().fromGeometry(geometry);
  57732. bufferGeometry.metadata = {type: geometry.type, parameters: geometry.parameters || {}};
  57733. geometry.dispose(); // Dispose no longer needed non-buffer geometry.
  57734. return bufferGeometry;
  57735. }
  57736. },{"../core/geometry":129,"../core/system":139,"../lib/three":176}],187:[function(_dereq_,module,exports){
  57737. var registerSystem = _dereq_('../core/system').registerSystem;
  57738. var THREE = _dereq_('../lib/three');
  57739. /**
  57740. * glTF model system.
  57741. *
  57742. * Configures glTF loading options. Models using glTF compression require that a Draco decoder be
  57743. * provided externally.
  57744. *
  57745. * @param {string} dracoDecoderPath - Base path from which to load Draco decoder library.
  57746. */
  57747. module.exports.System = registerSystem('gltf-model', {
  57748. schema: {
  57749. dracoDecoderPath: {default: ''}
  57750. },
  57751. init: function () {
  57752. var path = this.data.dracoDecoderPath;
  57753. this.dracoLoader = new THREE.DRACOLoader();
  57754. this.dracoLoader.setDecoderPath(path);
  57755. },
  57756. update: function () {
  57757. var path;
  57758. if (this.dracoLoader) { return; }
  57759. path = this.data.dracoDecoderPath;
  57760. this.dracoLoader = new THREE.DRACOLoader();
  57761. this.dracoLoader.setDecoderPath(path);
  57762. },
  57763. getDRACOLoader: function () {
  57764. return this.dracoLoader;
  57765. }
  57766. });
  57767. },{"../core/system":139,"../lib/three":176}],188:[function(_dereq_,module,exports){
  57768. _dereq_('./camera');
  57769. _dereq_('./geometry');
  57770. _dereq_('./gltf-model');
  57771. _dereq_('./light');
  57772. _dereq_('./material');
  57773. _dereq_('./renderer');
  57774. _dereq_('./shadow');
  57775. _dereq_('./tracked-controls-webvr');
  57776. _dereq_('./tracked-controls-webxr');
  57777. _dereq_('./webxr');
  57778. },{"./camera":185,"./geometry":186,"./gltf-model":187,"./light":189,"./material":190,"./renderer":191,"./shadow":192,"./tracked-controls-webvr":193,"./tracked-controls-webxr":194,"./webxr":195}],189:[function(_dereq_,module,exports){
  57779. var registerSystem = _dereq_('../core/system').registerSystem;
  57780. var bind = _dereq_('../utils/bind');
  57781. var constants = _dereq_('../constants/');
  57782. var DEFAULT_LIGHT_ATTR = 'data-aframe-default-light';
  57783. /**
  57784. * Light system.
  57785. *
  57786. * Prescribes default lighting if not specified (one ambient, one directional).
  57787. * Removes default lighting from the scene when a new light is added.
  57788. *
  57789. * @param {bool} defaultLights - Whether default lighting are defined.
  57790. * @param {bool} userDefinedLights - Whether user lighting is defined.
  57791. */
  57792. module.exports.System = registerSystem('light', {
  57793. schema: {
  57794. defaultLightsEnabled: {default: true}
  57795. },
  57796. init: function () {
  57797. this.defaultLights = false;
  57798. this.userDefinedLights = false;
  57799. // Wait for all entities to fully load before checking for existence of lights.
  57800. // Since entities wait for <a-assets> to load, any lights attaching to the scene
  57801. // will do so asynchronously.
  57802. this.sceneEl.addEventListener('loaded', bind(this.setupDefaultLights, this));
  57803. },
  57804. /**
  57805. * Notify scene that light has been added and to remove the default.
  57806. *
  57807. * @param {object} el - element holding the light component.
  57808. */
  57809. registerLight: function (el) {
  57810. if (!el.hasAttribute(DEFAULT_LIGHT_ATTR)) {
  57811. // User added a light, remove default lights through DOM.
  57812. this.removeDefaultLights();
  57813. this.userDefinedLights = true;
  57814. }
  57815. },
  57816. removeDefaultLights: function () {
  57817. var defaultLights;
  57818. var sceneEl = this.sceneEl;
  57819. if (!this.defaultLights) { return; }
  57820. defaultLights = document.querySelectorAll('[' + DEFAULT_LIGHT_ATTR + ']');
  57821. for (var i = 0; i < defaultLights.length; i++) {
  57822. sceneEl.removeChild(defaultLights[i]);
  57823. }
  57824. this.defaultLights = false;
  57825. },
  57826. /**
  57827. * Prescibe default lights to the scene.
  57828. * Does so by injecting markup such that this state is not invisible.
  57829. * These lights are removed if the user adds any lights.
  57830. */
  57831. setupDefaultLights: function () {
  57832. var sceneEl = this.sceneEl;
  57833. var ambientLight;
  57834. var directionalLight;
  57835. if (this.userDefinedLights || this.defaultLights || !this.data.defaultLightsEnabled) {
  57836. return;
  57837. }
  57838. ambientLight = document.createElement('a-entity');
  57839. ambientLight.setAttribute('light', {color: '#BBB', type: 'ambient'});
  57840. ambientLight.setAttribute(DEFAULT_LIGHT_ATTR, '');
  57841. ambientLight.setAttribute(constants.AFRAME_INJECTED, '');
  57842. sceneEl.appendChild(ambientLight);
  57843. directionalLight = document.createElement('a-entity');
  57844. directionalLight.setAttribute('light', {color: '#FFF', intensity: 0.6, castShadow: true});
  57845. directionalLight.setAttribute('position', {x: -0.5, y: 1, z: 1});
  57846. directionalLight.setAttribute(DEFAULT_LIGHT_ATTR, '');
  57847. directionalLight.setAttribute(constants.AFRAME_INJECTED, '');
  57848. sceneEl.appendChild(directionalLight);
  57849. this.defaultLights = true;
  57850. }
  57851. });
  57852. },{"../constants/":120,"../core/system":139,"../utils/bind":196}],190:[function(_dereq_,module,exports){
  57853. var registerSystem = _dereq_('../core/system').registerSystem;
  57854. var THREE = _dereq_('../lib/three');
  57855. var utils = _dereq_('../utils/');
  57856. var isHLS = _dereq_('../utils/material').isHLS;
  57857. var bind = utils.bind;
  57858. var debug = utils.debug;
  57859. var error = debug('components:texture:error');
  57860. var TextureLoader = new THREE.TextureLoader();
  57861. var warn = debug('components:texture:warn');
  57862. TextureLoader.setCrossOrigin('anonymous');
  57863. /**
  57864. * System for material component.
  57865. * Handle material registration, updates (for fog), and texture caching.
  57866. *
  57867. * @member {object} materials - Registered materials.
  57868. * @member {object} textureCounts - Number of times each texture is used. Tracked
  57869. * separately from textureCache, because the cache (1) is populated in
  57870. * multiple places, and (2) may be cleared at any time.
  57871. * @member {object} textureCache - Texture cache for:
  57872. * - Images: textureCache has mapping of src -> repeat -> cached three.js texture.
  57873. * - Videos: textureCache has mapping of videoElement -> cached three.js texture.
  57874. */
  57875. module.exports.System = registerSystem('material', {
  57876. init: function () {
  57877. this.materials = {};
  57878. this.textureCounts = {};
  57879. this.textureCache = {};
  57880. this.sceneEl.addEventListener(
  57881. 'materialtextureloaded',
  57882. bind(this.onMaterialTextureLoaded, this)
  57883. );
  57884. },
  57885. clearTextureCache: function () {
  57886. this.textureCache = {};
  57887. },
  57888. /**
  57889. * Determine whether `src` is a image or video. Then try to load the asset, then call back.
  57890. *
  57891. * @param {string, or element} src - Texture URL or element.
  57892. * @param {string} data - Relevant texture data used for caching.
  57893. * @param {function} cb - Callback to pass texture to.
  57894. */
  57895. loadTexture: function (src, data, cb) {
  57896. var self = this;
  57897. // Canvas.
  57898. if (src.tagName === 'CANVAS') {
  57899. this.loadCanvas(src, data, cb);
  57900. return;
  57901. }
  57902. // Video element.
  57903. if (src.tagName === 'VIDEO') {
  57904. if (!src.src && !src.srcObject && !src.childElementCount) {
  57905. warn('Video element was defined with neither `source` elements nor `src` / `srcObject` attributes.');
  57906. }
  57907. this.loadVideo(src, data, cb);
  57908. return;
  57909. }
  57910. utils.srcLoader.validateSrc(src, loadImageCb, loadVideoCb);
  57911. function loadImageCb (src) { self.loadImage(src, data, cb); }
  57912. function loadVideoCb (src) { self.loadVideo(src, data, cb); }
  57913. },
  57914. /**
  57915. * High-level function for loading image textures (THREE.Texture).
  57916. *
  57917. * @param {Element|string} src - Texture source.
  57918. * @param {object} data - Texture data.
  57919. * @param {function} cb - Callback to pass texture to.
  57920. */
  57921. loadImage: function (src, data, handleImageTextureLoaded) {
  57922. var hash = this.hash(data);
  57923. var textureCache = this.textureCache;
  57924. // Texture already being loaded or already loaded. Wait on promise.
  57925. if (textureCache[hash]) {
  57926. textureCache[hash].then(handleImageTextureLoaded);
  57927. return;
  57928. }
  57929. // Texture not yet being loaded. Start loading it.
  57930. textureCache[hash] = loadImageTexture(src, data);
  57931. textureCache[hash].then(handleImageTextureLoaded);
  57932. },
  57933. /**
  57934. * High-level function for loading canvas textures (THREE.Texture).
  57935. *
  57936. * @param {Element|string} src - Texture source.
  57937. * @param {object} data - Texture data.
  57938. * @param {function} cb - Callback to pass texture to.
  57939. */
  57940. loadCanvas: function (src, data, cb) {
  57941. var texture;
  57942. texture = new THREE.CanvasTexture(src);
  57943. setTextureProperties(texture, data);
  57944. cb(texture);
  57945. },
  57946. /**
  57947. * Load video texture (THREE.VideoTexture).
  57948. * Which is just an image texture that RAFs + needsUpdate.
  57949. * Note that creating a video texture is synchronous unlike loading an image texture.
  57950. * Made asynchronous to be consistent with image textures.
  57951. *
  57952. * @param {Element|string} src - Texture source.
  57953. * @param {object} data - Texture data.
  57954. * @param {function} cb - Callback to pass texture to.
  57955. */
  57956. loadVideo: function (src, data, cb) {
  57957. var hash;
  57958. var texture;
  57959. var textureCache = this.textureCache;
  57960. var videoEl;
  57961. var videoTextureResult;
  57962. function handleVideoTextureLoaded (result) {
  57963. result.texture.needsUpdate = true;
  57964. cb(result.texture, result.videoEl);
  57965. }
  57966. // Video element provided.
  57967. if (typeof src !== 'string') {
  57968. // Check cache before creating texture.
  57969. videoEl = src;
  57970. hash = this.hashVideo(data, videoEl);
  57971. if (textureCache[hash]) {
  57972. textureCache[hash].then(handleVideoTextureLoaded);
  57973. return;
  57974. }
  57975. // If not in cache, fix up the attributes then start to create the texture.
  57976. fixVideoAttributes(videoEl);
  57977. }
  57978. // Only URL provided. Use video element to create texture.
  57979. videoEl = videoEl || createVideoEl(src, data.width, data.height);
  57980. // Generated video element already cached. Use that.
  57981. hash = this.hashVideo(data, videoEl);
  57982. if (textureCache[hash]) {
  57983. textureCache[hash].then(handleVideoTextureLoaded);
  57984. return;
  57985. }
  57986. // Create new video texture.
  57987. texture = new THREE.VideoTexture(videoEl);
  57988. texture.minFilter = THREE.LinearFilter;
  57989. setTextureProperties(texture, data);
  57990. // If iOS and video is HLS, do some hacks.
  57991. if (this.sceneEl.isIOS &&
  57992. isHLS(videoEl.src || videoEl.getAttribute('src'),
  57993. videoEl.type || videoEl.getAttribute('type'))) {
  57994. // Actually BGRA. Tell shader to correct later.
  57995. texture.format = THREE.RGBAFormat;
  57996. texture.needsCorrectionBGRA = true;
  57997. // Apparently needed for HLS. Tell shader to correct later.
  57998. texture.flipY = false;
  57999. texture.needsCorrectionFlipY = true;
  58000. }
  58001. // Cache as promise to be consistent with image texture caching.
  58002. videoTextureResult = {texture: texture, videoEl: videoEl};
  58003. textureCache[hash] = Promise.resolve(videoTextureResult);
  58004. handleVideoTextureLoaded(videoTextureResult);
  58005. },
  58006. /**
  58007. * Create a hash of the material properties for texture cache key.
  58008. */
  58009. hash: function (data) {
  58010. if (data.src.tagName) {
  58011. // Since `data.src` can be an element, parse out the string if necessary for the hash.
  58012. data = utils.extendDeep({}, data);
  58013. data.src = data.src.src;
  58014. }
  58015. return JSON.stringify(data);
  58016. },
  58017. hashVideo: function (data, videoEl) {
  58018. return calculateVideoCacheHash(data, videoEl);
  58019. },
  58020. /**
  58021. * Keep track of material in case an update trigger is needed (e.g., fog).
  58022. *
  58023. * @param {object} material
  58024. */
  58025. registerMaterial: function (material) {
  58026. this.materials[material.uuid] = material;
  58027. },
  58028. /**
  58029. * Stop tracking material, and dispose of any textures not being used by
  58030. * another material component.
  58031. *
  58032. * @param {object} material
  58033. */
  58034. unregisterMaterial: function (material) {
  58035. delete this.materials[material.uuid];
  58036. // If any textures on this material are no longer in use, dispose of them.
  58037. var textureCounts = this.textureCounts;
  58038. Object.keys(material)
  58039. .filter(function (propName) {
  58040. return material[propName] && material[propName].isTexture;
  58041. })
  58042. .forEach(function (mapName) {
  58043. textureCounts[material[mapName].uuid]--;
  58044. if (textureCounts[material[mapName].uuid] <= 0) {
  58045. material[mapName].dispose();
  58046. }
  58047. });
  58048. },
  58049. /**
  58050. * Trigger update to all registered materials.
  58051. */
  58052. updateMaterials: function (material) {
  58053. var materials = this.materials;
  58054. Object.keys(materials).forEach(function (uuid) {
  58055. materials[uuid].needsUpdate = true;
  58056. });
  58057. },
  58058. /**
  58059. * Track textures used by material components, so that they can be safely
  58060. * disposed when no longer in use. Textures must be registered here, and not
  58061. * through registerMaterial(), because textures may not be attached at the
  58062. * time the material is registered.
  58063. *
  58064. * @param {Event} e
  58065. */
  58066. onMaterialTextureLoaded: function (e) {
  58067. if (!this.textureCounts[e.detail.texture.uuid]) {
  58068. this.textureCounts[e.detail.texture.uuid] = 0;
  58069. }
  58070. this.textureCounts[e.detail.texture.uuid]++;
  58071. }
  58072. });
  58073. /**
  58074. * Calculates consistent hash from a video element using its attributes.
  58075. * If the video element has an ID, use that.
  58076. * Else build a hash that looks like `src:myvideo.mp4;height:200;width:400;`.
  58077. *
  58078. * @param data {object} - Texture data such as repeat.
  58079. * @param videoEl {Element} - Video element.
  58080. * @returns {string}
  58081. */
  58082. function calculateVideoCacheHash (data, videoEl) {
  58083. var i;
  58084. var id = videoEl.getAttribute('id');
  58085. var hash;
  58086. var videoAttributes;
  58087. if (id) { return id; }
  58088. // Calculate hash using sorted video attributes.
  58089. hash = '';
  58090. videoAttributes = data || {};
  58091. for (i = 0; i < videoEl.attributes.length; i++) {
  58092. videoAttributes[videoEl.attributes[i].name] = videoEl.attributes[i].value;
  58093. }
  58094. Object.keys(videoAttributes).sort().forEach(function (name) {
  58095. hash += name + ':' + videoAttributes[name] + ';';
  58096. });
  58097. return hash;
  58098. }
  58099. /**
  58100. * Load image texture.
  58101. *
  58102. * @private
  58103. * @param {string|object} src - An <img> element or url to an image file.
  58104. * @param {object} data - Data to set texture properties like `repeat`.
  58105. * @returns {Promise} Resolves once texture is loaded.
  58106. */
  58107. function loadImageTexture (src, data) {
  58108. return new Promise(doLoadImageTexture);
  58109. function doLoadImageTexture (resolve, reject) {
  58110. var isEl = typeof src !== 'string';
  58111. function resolveTexture (texture) {
  58112. setTextureProperties(texture, data);
  58113. texture.needsUpdate = true;
  58114. resolve(texture);
  58115. }
  58116. // Create texture from an element.
  58117. if (isEl) {
  58118. resolveTexture(new THREE.Texture(src));
  58119. return;
  58120. }
  58121. // Request and load texture from src string. THREE will create underlying element.
  58122. // Use THREE.TextureLoader (src, onLoad, onProgress, onError) to load texture.
  58123. TextureLoader.load(
  58124. src,
  58125. resolveTexture,
  58126. function () { /* no-op */ },
  58127. function (xhr) {
  58128. error('`$s` could not be fetched (Error code: %s; Response: %s)', xhr.status,
  58129. xhr.statusText);
  58130. }
  58131. );
  58132. }
  58133. }
  58134. /**
  58135. * Set texture properties such as repeat and offset.
  58136. *
  58137. * @param {object} data - With keys like `repeat`.
  58138. */
  58139. function setTextureProperties (texture, data) {
  58140. var offset = data.offset || {x: 0, y: 0};
  58141. var repeat = data.repeat || {x: 1, y: 1};
  58142. var npot = data.npot || false;
  58143. // To support NPOT textures, wrap must be ClampToEdge (not Repeat),
  58144. // and filters must not use mipmaps (i.e. Nearest or Linear).
  58145. if (npot) {
  58146. texture.wrapS = THREE.ClampToEdgeWrapping;
  58147. texture.wrapT = THREE.ClampToEdgeWrapping;
  58148. texture.magFilter = THREE.LinearFilter;
  58149. texture.minFilter = THREE.LinearFilter;
  58150. }
  58151. // Don't bother setting repeat if it is 1/1. Power-of-two is required to repeat.
  58152. if (repeat.x !== 1 || repeat.y !== 1) {
  58153. texture.wrapS = THREE.RepeatWrapping;
  58154. texture.wrapT = THREE.RepeatWrapping;
  58155. texture.repeat.set(repeat.x, repeat.y);
  58156. }
  58157. // Don't bother setting offset if it is 0/0.
  58158. if (offset.x !== 0 || offset.y !== 0) {
  58159. texture.offset.set(offset.x, offset.y);
  58160. }
  58161. }
  58162. /**
  58163. * Create video element to be used as a texture.
  58164. *
  58165. * @param {string} src - Url to a video file.
  58166. * @param {number} width - Width of the video.
  58167. * @param {number} height - Height of the video.
  58168. * @returns {Element} Video element.
  58169. */
  58170. function createVideoEl (src, width, height) {
  58171. var videoEl = document.createElement('video');
  58172. videoEl.width = width;
  58173. videoEl.height = height;
  58174. // Support inline videos for iOS webviews.
  58175. videoEl.setAttribute('playsinline', '');
  58176. videoEl.setAttribute('webkit-playsinline', '');
  58177. videoEl.autoplay = true;
  58178. videoEl.loop = true;
  58179. videoEl.crossOrigin = 'anonymous';
  58180. videoEl.addEventListener('error', function () {
  58181. warn('`$s` is not a valid video', src);
  58182. }, true);
  58183. videoEl.src = src;
  58184. return videoEl;
  58185. }
  58186. /**
  58187. * Fixes a video element's attributes to prevent developers from accidentally passing the
  58188. * wrong attribute values to commonly misused video attributes.
  58189. *
  58190. * <video> does not treat `autoplay`, `controls`, `crossorigin`, `loop`, and `preload` as
  58191. * as booleans. Existence of those attributes will mean truthy.
  58192. *
  58193. * For example, translates <video loop="false"> to <video>.
  58194. *
  58195. * @see https://developer.mozilla.org/docs/Web/HTML/Element/video#Attributes
  58196. * @param {Element} videoEl - Video element.
  58197. * @returns {Element} Video element with the correct properties updated.
  58198. */
  58199. function fixVideoAttributes (videoEl) {
  58200. videoEl.autoplay = videoEl.hasAttribute('autoplay') && videoEl.getAttribute('autoplay') !== 'false';
  58201. videoEl.controls = videoEl.hasAttribute('controls') && videoEl.getAttribute('controls') !== 'false';
  58202. if (videoEl.getAttribute('loop') === 'false') {
  58203. videoEl.removeAttribute('loop');
  58204. }
  58205. if (videoEl.getAttribute('preload') === 'false') {
  58206. videoEl.preload = 'none';
  58207. }
  58208. videoEl.crossOrigin = videoEl.crossOrigin || 'anonymous';
  58209. // To support inline videos in iOS webviews.
  58210. videoEl.setAttribute('playsinline', '');
  58211. videoEl.setAttribute('webkit-playsinline', '');
  58212. return videoEl;
  58213. }
  58214. },{"../core/system":139,"../lib/three":176,"../utils/":202,"../utils/material":205}],191:[function(_dereq_,module,exports){
  58215. var registerSystem = _dereq_('../core/system').registerSystem;
  58216. var utils = _dereq_('../utils/');
  58217. var THREE = _dereq_('../lib/three');
  58218. var debug = utils.debug;
  58219. var warn = debug('components:renderer:warn');
  58220. /**
  58221. * Determines state of various renderer properties.
  58222. */
  58223. module.exports.System = registerSystem('renderer', {
  58224. schema: {
  58225. antialias: {default: 'auto', oneOf: ['true', 'false', 'auto']},
  58226. highRefreshRate: {default: utils.device.isOculusBrowser()},
  58227. logarithmicDepthBuffer: {default: 'auto', oneOf: ['true', 'false', 'auto']},
  58228. maxCanvasWidth: {default: 1920},
  58229. maxCanvasHeight: {default: 1920},
  58230. physicallyCorrectLights: {default: false},
  58231. precision: {default: 'high', oneOf: ['high', 'medium', 'low']},
  58232. sortObjects: {default: false},
  58233. colorManagement: {default: false},
  58234. gammaOutput: {default: false},
  58235. alpha: {default: true},
  58236. foveationLevel: {default: 0}
  58237. },
  58238. init: function () {
  58239. var data = this.data;
  58240. var sceneEl = this.el;
  58241. // This is the rendering engine, such as THREE.js so copy over any persistent properties from the rendering system.
  58242. var renderer = sceneEl.renderer;
  58243. renderer.sortObjects = data.sortObjects;
  58244. renderer.physicallyCorrectLights = data.physicallyCorrectLights;
  58245. if (data.colorManagement || data.gammaOutput) {
  58246. renderer.outputEncoding = THREE.sRGBEncoding;
  58247. if (data.gammaOutput) {
  58248. warn('Property `gammaOutput` is deprecated. Use `renderer="colorManagement: true;"` instead.');
  58249. }
  58250. }
  58251. if (sceneEl.hasAttribute('antialias')) {
  58252. warn('Component `antialias` is deprecated. Use `renderer="antialias: true"` instead.');
  58253. }
  58254. if (sceneEl.hasAttribute('logarithmicDepthBuffer')) {
  58255. warn('Component `logarithmicDepthBuffer` is deprecated. Use `renderer="logarithmicDepthBuffer: true"` instead.');
  58256. }
  58257. },
  58258. applyColorCorrection: function (colorOrTexture) {
  58259. if (!this.data.colorManagement || !colorOrTexture) {
  58260. return;
  58261. } else if (colorOrTexture.isColor) {
  58262. colorOrTexture.convertSRGBToLinear();
  58263. } else if (colorOrTexture.isTexture) {
  58264. colorOrTexture.encoding = THREE.sRGBEncoding;
  58265. }
  58266. }
  58267. });
  58268. },{"../core/system":139,"../lib/three":176,"../utils/":202}],192:[function(_dereq_,module,exports){
  58269. var registerSystem = _dereq_('../core/system').registerSystem;
  58270. var THREE = _dereq_('../lib/three');
  58271. var SHADOW_MAP_TYPE_MAP = {
  58272. basic: THREE.BasicShadowMap,
  58273. pcf: THREE.PCFShadowMap,
  58274. pcfsoft: THREE.PCFSoftShadowMap
  58275. };
  58276. /**
  58277. * Shadow system.
  58278. *
  58279. * Enabled automatically when one or more shadow components are added to the scene, the system sets
  58280. * options on the WebGLRenderer for configuring shadow appearance.
  58281. */
  58282. module.exports.System = registerSystem('shadow', {
  58283. schema: {
  58284. enabled: {default: true},
  58285. autoUpdate: {default: true},
  58286. type: {default: 'pcf', oneOf: ['basic', 'pcf', 'pcfsoft']}
  58287. },
  58288. init: function () {
  58289. var sceneEl = this.sceneEl;
  58290. var data = this.data;
  58291. this.shadowMapEnabled = false;
  58292. if (!sceneEl.renderer) { return; } // For tests.
  58293. sceneEl.renderer.shadowMap.type = SHADOW_MAP_TYPE_MAP[data.type];
  58294. sceneEl.renderer.shadowMap.autoUpdate = data.autoUpdate;
  58295. this.setShadowMapEnabled(this.shadowMapEnabled);
  58296. },
  58297. update: function (prevData) {
  58298. if (prevData.enabled !== this.data.enabled) {
  58299. this.setShadowMapEnabled(this.data.enabled);
  58300. }
  58301. },
  58302. /**
  58303. * Enables/disables the renderer shadow map.
  58304. * @param {boolean} enabled
  58305. */
  58306. setShadowMapEnabled: function (enabled) {
  58307. var renderer = this.sceneEl.renderer;
  58308. this.shadowMapEnabled = this.data.enabled && enabled;
  58309. if (renderer) {
  58310. renderer.shadowMap.enabled = this.shadowMapEnabled;
  58311. }
  58312. }
  58313. });
  58314. },{"../core/system":139,"../lib/three":176}],193:[function(_dereq_,module,exports){
  58315. var registerSystem = _dereq_('../core/system').registerSystem;
  58316. var utils = _dereq_('../utils');
  58317. var isWebXRAvailable = utils.device.isWebXRAvailable;
  58318. /**
  58319. * Tracked controls system.
  58320. * Maintain list with available tracked controllers.
  58321. */
  58322. module.exports.System = registerSystem('tracked-controls-webvr', {
  58323. init: function () {
  58324. var self = this;
  58325. this.controllers = [];
  58326. this.isChrome = navigator.userAgent.indexOf('Chrome') !== -1;
  58327. this.updateControllerList();
  58328. this.throttledUpdateControllerList = utils.throttle(this.updateControllerList, 500, this);
  58329. // Don't use WebVR if WebXR is available?
  58330. if (isWebXRAvailable) { return; }
  58331. if (!navigator.getVRDisplays) { return; }
  58332. this.sceneEl.addEventListener('enter-vr', function () {
  58333. navigator.getVRDisplays().then(function (displays) {
  58334. if (displays.length) { self.vrDisplay = displays[0]; }
  58335. });
  58336. });
  58337. },
  58338. tick: function () {
  58339. if (this.isChrome) {
  58340. // Retrieve new controller handlers with updated state (pose, buttons...)
  58341. this.updateControllerList();
  58342. } else {
  58343. this.throttledUpdateControllerList();
  58344. }
  58345. },
  58346. /**
  58347. * Update controller list.
  58348. */
  58349. updateControllerList: function () {
  58350. var controllers = this.controllers;
  58351. var gamepad;
  58352. var gamepads;
  58353. var i;
  58354. var prevCount;
  58355. gamepads = navigator.getGamepads && navigator.getGamepads();
  58356. if (!gamepads) { return; }
  58357. prevCount = controllers.length;
  58358. controllers.length = 0;
  58359. for (i = 0; i < gamepads.length; ++i) {
  58360. gamepad = gamepads[i];
  58361. if (gamepad && gamepad.pose) {
  58362. controllers.push(gamepad);
  58363. }
  58364. }
  58365. if (controllers.length !== prevCount) {
  58366. this.el.emit('controllersupdated', undefined, false);
  58367. }
  58368. }
  58369. });
  58370. },{"../core/system":139,"../utils":202}],194:[function(_dereq_,module,exports){
  58371. var registerSystem = _dereq_('../core/system').registerSystem;
  58372. var utils = _dereq_('../utils');
  58373. /**
  58374. * Tracked controls system.
  58375. * Maintain list with available tracked controllers.
  58376. */
  58377. module.exports.System = registerSystem('tracked-controls-webxr', {
  58378. init: function () {
  58379. this.controllers = [];
  58380. this.oldControllersLength = 0;
  58381. this.throttledUpdateControllerList = utils.throttle(this.updateControllerList, 500, this);
  58382. this.updateReferenceSpace = this.updateReferenceSpace.bind(this);
  58383. this.el.addEventListener('enter-vr', this.updateReferenceSpace);
  58384. this.el.addEventListener('exit-vr', this.updateReferenceSpace);
  58385. },
  58386. tick: function () {
  58387. this.throttledUpdateControllerList();
  58388. },
  58389. updateReferenceSpace: function () {
  58390. var self = this;
  58391. var xrSession = this.el.xrSession;
  58392. if (!xrSession) {
  58393. this.referenceSpace = undefined;
  58394. this.controllers = [];
  58395. if (this.oldControllersLength > 0) {
  58396. this.oldControllersLength = 0;
  58397. this.el.emit('controllersupdated', undefined, false);
  58398. }
  58399. return;
  58400. }
  58401. var refspace = self.el.sceneEl.systems.webxr.sessionReferenceSpaceType;
  58402. xrSession.requestReferenceSpace(refspace).then(function (referenceSpace) {
  58403. self.referenceSpace = referenceSpace;
  58404. }).catch(function (err) {
  58405. self.el.sceneEl.systems.webxr.warnIfFeatureNotRequested(
  58406. refspace,
  58407. 'tracked-controls-webxr uses reference space "' + refspace + '".');
  58408. throw err;
  58409. });
  58410. },
  58411. updateControllerList: function () {
  58412. var xrSession = this.el.xrSession;
  58413. if (!xrSession) {
  58414. if (this.oldControllersLength === 0) { return; }
  58415. // Broadcast that we now have zero controllers connected if there is
  58416. // no session
  58417. this.oldControllersLength = 0;
  58418. this.controllers = [];
  58419. this.el.emit('controllersupdated', undefined, false);
  58420. return;
  58421. }
  58422. this.controllers = xrSession.inputSources;
  58423. if (this.oldControllersLength === this.controllers.length) { return; }
  58424. this.oldControllersLength = this.controllers.length;
  58425. this.el.emit('controllersupdated', undefined, false);
  58426. }
  58427. });
  58428. },{"../core/system":139,"../utils":202}],195:[function(_dereq_,module,exports){
  58429. var registerSystem = _dereq_('../core/system').registerSystem;
  58430. var utils = _dereq_('../utils/');
  58431. var warn = utils.debug('systems:webxr:warn');
  58432. /**
  58433. * WebXR session initialization and XR module support.
  58434. */
  58435. module.exports.System = registerSystem('webxr', {
  58436. schema: {
  58437. referenceSpaceType: {type: 'string', default: 'local-floor'},
  58438. requiredFeatures: {type: 'array', default: ['local-floor']},
  58439. optionalFeatures: {type: 'array', default: ['bounded-floor']},
  58440. overlayElement: {type: 'selector'}
  58441. },
  58442. update: function () {
  58443. var data = this.data;
  58444. this.sessionConfiguration = {
  58445. requiredFeatures: data.requiredFeatures,
  58446. optionalFeatures: data.optionalFeatures
  58447. };
  58448. this.sessionReferenceSpaceType = data.referenceSpaceType;
  58449. if (data.overlayElement) {
  58450. this.warnIfFeatureNotRequested('dom-overlay');
  58451. this.sessionConfiguration.domOverlay = {root: data.overlayElement};
  58452. }
  58453. },
  58454. wasFeatureRequested: function (feature) {
  58455. // Features available by default for immersive sessions don't need to
  58456. // be requested explicitly.
  58457. if (feature === 'viewer' || feature === 'local') return true;
  58458. if (this.sessionConfiguration.requiredFeatures.includes(feature) ||
  58459. this.sessionConfiguration.optionalFeatures.includes(feature)) {
  58460. return true;
  58461. }
  58462. return false;
  58463. },
  58464. warnIfFeatureNotRequested: function (feature, optIntro) {
  58465. if (!this.wasFeatureRequested(feature)) {
  58466. var msg = 'Please add the feature "' + feature + '" to a-scene\'s ' +
  58467. 'webxr system options in requiredFeatures/optionalFeatures.';
  58468. warn((optIntro ? optIntro + ' ' : '') + msg);
  58469. }
  58470. }
  58471. });
  58472. },{"../core/system":139,"../utils/":202}],196:[function(_dereq_,module,exports){
  58473. /**
  58474. * Faster version of Function.prototype.bind
  58475. * @param {Function} fn - Function to wrap.
  58476. * @param {Object} ctx - What to bind as context.
  58477. * @param {...*} arguments - Arguments to pass through.
  58478. */
  58479. module.exports = function bind (fn, ctx/* , arg1, arg2 */) {
  58480. return (function (prependedArgs) {
  58481. return function bound () {
  58482. // Concat the bound function arguments with those passed to original bind
  58483. var args = prependedArgs.concat(Array.prototype.slice.call(arguments, 0));
  58484. return fn.apply(ctx, args);
  58485. };
  58486. })(Array.prototype.slice.call(arguments, 2));
  58487. };
  58488. },{}],197:[function(_dereq_,module,exports){
  58489. /* global THREE */
  58490. var debug = _dereq_('./debug');
  58491. var extend = _dereq_('object-assign');
  58492. var warn = debug('utils:coordinates:warn');
  58493. // Order of coordinates parsed by coordinates.parse.
  58494. var COORDINATE_KEYS = ['x', 'y', 'z', 'w'];
  58495. // Coordinate string regex. Handles negative, positive, and decimals.
  58496. var regex = /^\s*((-?\d*\.{0,1}\d+(e-?\d+)?)\s+){2,3}(-?\d*\.{0,1}\d+(e-?\d+)?)\s*$/;
  58497. module.exports.regex = regex;
  58498. var OBJECT = 'object';
  58499. var whitespaceRegex = /\s+/g;
  58500. /**
  58501. * Parses coordinates from an "x y z" string.
  58502. * Example: "3 10 -5" to {x: 3, y: 10, z: -5}.
  58503. *
  58504. * @param {string} val - An "x y z" string.
  58505. * @param {string} defaults - fallback value.
  58506. * @returns {object} An object with keys [x, y, z].
  58507. */
  58508. function parse (value, defaultVec) {
  58509. var coordinate;
  58510. var defaultVal;
  58511. var key;
  58512. var i;
  58513. var vec;
  58514. var x;
  58515. var y;
  58516. var z;
  58517. var w;
  58518. if (value && value instanceof Object) {
  58519. x = value.x === undefined ? defaultVec && defaultVec.x : value.x;
  58520. y = value.y === undefined ? defaultVec && defaultVec.y : value.y;
  58521. z = value.z === undefined ? defaultVec && defaultVec.z : value.z;
  58522. w = value.w === undefined ? defaultVec && defaultVec.w : value.w;
  58523. if (x !== undefined && x !== null) { value.x = parseIfString(x); }
  58524. if (y !== undefined && y !== null) { value.y = parseIfString(y); }
  58525. if (z !== undefined && z !== null) { value.z = parseIfString(z); }
  58526. if (w !== undefined && w !== null) { value.w = parseIfString(w); }
  58527. return value;
  58528. }
  58529. if (value === null || value === undefined) {
  58530. return typeof defaultVec === OBJECT ? extend({}, defaultVec) : defaultVec;
  58531. }
  58532. coordinate = value.trim().split(whitespaceRegex);
  58533. vec = {};
  58534. for (i = 0; i < COORDINATE_KEYS.length; i++) {
  58535. key = COORDINATE_KEYS[i];
  58536. if (coordinate[i]) {
  58537. vec[key] = parseFloat(coordinate[i], 10);
  58538. } else {
  58539. defaultVal = defaultVec && defaultVec[key];
  58540. if (defaultVal === undefined) { continue; }
  58541. vec[key] = parseIfString(defaultVal);
  58542. }
  58543. }
  58544. return vec;
  58545. }
  58546. module.exports.parse = parse;
  58547. /**
  58548. * Stringify coordinates from an object with keys [x y z].
  58549. * Example: {x: 3, y: 10, z: -5} to "3 10 -5".
  58550. *
  58551. * @param {object|string} data - An object with keys [x y z].
  58552. * @returns {string} An "x y z" string.
  58553. */
  58554. function stringify (data) {
  58555. var str;
  58556. if (typeof data !== OBJECT) { return data; }
  58557. str = data.x + ' ' + data.y;
  58558. if (data.z != null) { str += ' ' + data.z; }
  58559. if (data.w != null) { str += ' ' + data.w; }
  58560. return str;
  58561. }
  58562. module.exports.stringify = stringify;
  58563. /**
  58564. * @returns {bool}
  58565. */
  58566. function isCoordinates (value) {
  58567. return regex.test(value);
  58568. }
  58569. module.exports.isCoordinates = isCoordinates;
  58570. module.exports.isCoordinate = function (value) {
  58571. warn('`AFRAME.utils.isCoordinate` has been renamed to `AFRAME.utils.isCoordinates`');
  58572. return isCoordinates(value);
  58573. };
  58574. function parseIfString (val) {
  58575. if (val !== null && val !== undefined && val.constructor === String) {
  58576. return parseFloat(val, 10);
  58577. }
  58578. return val;
  58579. }
  58580. /**
  58581. * Convert {x, y, z} object to three.js Vector3.
  58582. */
  58583. module.exports.toVector3 = function (vec3) {
  58584. return new THREE.Vector3(vec3.x, vec3.y, vec3.z);
  58585. };
  58586. },{"./debug":198,"object-assign":39}],198:[function(_dereq_,module,exports){
  58587. (function (process){
  58588. var debugLib = _dereq_('debug');
  58589. var extend = _dereq_('object-assign');
  58590. var settings = {
  58591. colors: {
  58592. debug: 'gray',
  58593. error: 'red',
  58594. info: 'gray',
  58595. warn: 'orange'
  58596. }
  58597. };
  58598. /**
  58599. * Monkeypatches `debug` so we can colorize error/warning messages.
  58600. *
  58601. * (See issue: https://github.com/visionmedia/debug/issues/137)
  58602. */
  58603. var debug = function (namespace) {
  58604. var d = debugLib(namespace);
  58605. d.color = getDebugNamespaceColor(namespace);
  58606. return d;
  58607. };
  58608. extend(debug, debugLib);
  58609. /**
  58610. * Returns the type of the namespace (e.g., `error`, `warn`).
  58611. *
  58612. * @param {String} namespace
  58613. * The debug logger's namespace (e.g., `components:geometry:warn`).
  58614. * @returns {String} The type of the namespace (e.g., `warn`).
  58615. * @api private
  58616. */
  58617. function getDebugNamespaceType (namespace) {
  58618. var chunks = namespace.split(':');
  58619. return chunks[chunks.length - 1]; // Return the last one
  58620. }
  58621. /**
  58622. * Returns the color of the namespace (e.g., `orange`).
  58623. *
  58624. * @param {String} namespace
  58625. * The debug logger's namespace (e.g., `components:geometry:warn`).
  58626. * @returns {String} The color of the namespace (e.g., `orange`).
  58627. * @api private
  58628. */
  58629. function getDebugNamespaceColor (namespace) {
  58630. var type = getDebugNamespaceType(namespace);
  58631. var color = settings.colors && settings.colors[type];
  58632. return color || null;
  58633. }
  58634. /**
  58635. * Returns `localStorage` if possible.
  58636. *
  58637. * This is necessary because Safari throws when a user disables
  58638. * cookies or `localStorage` and you attempt to access it.
  58639. *
  58640. * @returns {localStorage}
  58641. * @api private
  58642. */
  58643. function storage () {
  58644. try {
  58645. return window.localStorage;
  58646. } catch (e) {
  58647. }
  58648. }
  58649. /**
  58650. * To enable console logging, type this in the Console of your Dev Tools:
  58651. *
  58652. * localStorage.logs = 1
  58653. *
  58654. * To disable console logging:
  58655. *
  58656. * localStorage.logs = 0
  58657. *
  58658. */
  58659. var ls = storage();
  58660. if (ls && (parseInt(ls.logs, 10) || ls.logs === 'true')) {
  58661. debug.enable('*');
  58662. } else {
  58663. debug.enable('*:error,*:info,*:warn');
  58664. }
  58665. if (process.browser) { window.logs = debug; }
  58666. module.exports = debug;
  58667. }).call(this,_dereq_('_process'))
  58668. },{"_process":49,"debug":8,"object-assign":39}],199:[function(_dereq_,module,exports){
  58669. (function (process){
  58670. var error = _dereq_('debug')('device:error');
  58671. var vrDisplay;
  58672. var supportsVRSession = false;
  58673. var supportsARSession = false;
  58674. /**
  58675. * Oculus Browser 7 doesn't support the WebXR gamepads module.
  58676. * We fallback to WebVR API and will hotfix when implementation is complete.
  58677. */
  58678. var isWebXRAvailable = module.exports.isWebXRAvailable = !window.debug && navigator.xr !== undefined;
  58679. // Catch vrdisplayactivate early to ensure we can enter VR mode after the scene loads.
  58680. window.addEventListener('vrdisplayactivate', function (evt) {
  58681. var canvasEl;
  58682. // WebXR takes priority if available.
  58683. if (isWebXRAvailable) { return; }
  58684. canvasEl = document.createElement('canvas');
  58685. vrDisplay = evt.display;
  58686. // We need to make sure the canvas has a WebGL context associated with it.
  58687. // Otherwise, the requestPresent could be denied.
  58688. canvasEl.getContext('webgl', {});
  58689. // Request present immediately. a-scene will be allowed to enter VR without user gesture.
  58690. vrDisplay.requestPresent([{source: canvasEl}]).then(function () {}, function () {});
  58691. });
  58692. // Support both WebVR and WebXR APIs.
  58693. if (isWebXRAvailable) {
  58694. var updateEnterInterfaces = function () {
  58695. var sceneEl = document.querySelector('a-scene');
  58696. if (!sceneEl) {
  58697. window.addEventListener('DOMContentLoaded', updateEnterInterfaces);
  58698. return;
  58699. }
  58700. if (sceneEl.hasLoaded) {
  58701. sceneEl.components['vr-mode-ui'].updateEnterInterfaces();
  58702. } else {
  58703. sceneEl.addEventListener('loaded', updateEnterInterfaces);
  58704. }
  58705. };
  58706. var errorHandler = function (err) {
  58707. error('WebXR session support error: ' + err.message);
  58708. };
  58709. if (navigator.xr.isSessionSupported) {
  58710. // Current WebXR spec uses a boolean-returning isSessionSupported promise
  58711. navigator.xr.isSessionSupported('immersive-vr').then(function (supported) {
  58712. supportsVRSession = supported;
  58713. updateEnterInterfaces();
  58714. }).catch(errorHandler);
  58715. navigator.xr.isSessionSupported('immersive-ar').then(function (supported) {
  58716. supportsARSession = supported;
  58717. updateEnterInterfaces();
  58718. }).catch(function () {});
  58719. } else if (navigator.xr.supportsSession) {
  58720. // Fallback for implementations that haven't updated to the new spec yet,
  58721. // the old version used supportsSession which is rejected for missing
  58722. // support.
  58723. navigator.xr.supportsSession('immersive-vr').then(function () {
  58724. supportsVRSession = true;
  58725. updateEnterInterfaces();
  58726. }).catch(errorHandler);
  58727. navigator.xr.supportsSession('immersive-ar').then(function () {
  58728. supportsARSession = true;
  58729. updateEnterInterfaces();
  58730. }).catch(function () {});
  58731. } else {
  58732. error('WebXR has neither isSessionSupported or supportsSession?!');
  58733. }
  58734. } else {
  58735. if (navigator.getVRDisplays) {
  58736. navigator.getVRDisplays().then(function (displays) {
  58737. var sceneEl = document.querySelector('a-scene');
  58738. vrDisplay = displays.length && displays[0];
  58739. if (sceneEl) { sceneEl.emit('displayconnected', {vrDisplay: vrDisplay}); }
  58740. });
  58741. }
  58742. }
  58743. function getVRDisplay () { return vrDisplay; }
  58744. module.exports.getVRDisplay = getVRDisplay;
  58745. /**
  58746. * Determine if a headset is connected by checking if a vrDisplay is available.
  58747. */
  58748. function checkHeadsetConnected () {
  58749. return supportsVRSession || supportsARSession || !!getVRDisplay();
  58750. }
  58751. module.exports.checkHeadsetConnected = checkHeadsetConnected;
  58752. function checkARSupport () { return supportsARSession; }
  58753. module.exports.checkARSupport = checkARSupport;
  58754. /**
  58755. * Checks if browser is mobile and not stand-alone dedicated vr device.
  58756. * @return {Boolean} True if mobile browser detected.
  58757. */
  58758. var isMobile = (function () {
  58759. var _isMobile = false;
  58760. (function (a) {
  58761. // eslint-disable-next-line no-useless-escape
  58762. 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))) {
  58763. _isMobile = true;
  58764. }
  58765. if (isIOS() || isTablet() || isR7()) {
  58766. _isMobile = true;
  58767. }
  58768. if (isMobileVR()) {
  58769. _isMobile = false;
  58770. }
  58771. })(window.navigator.userAgent || window.navigator.vendor || window.opera);
  58772. return function () { return _isMobile; };
  58773. })();
  58774. module.exports.isMobile = isMobile;
  58775. /**
  58776. * Detect tablet devices.
  58777. * @param {string} mockUserAgent - Allow passing a mock user agent for testing.
  58778. */
  58779. function isTablet (mockUserAgent) {
  58780. var userAgent = mockUserAgent || window.navigator.userAgent;
  58781. return /ipad|Nexus (7|9)|xoom|sch-i800|playbook|tablet|kindle/i.test(userAgent);
  58782. }
  58783. module.exports.isTablet = isTablet;
  58784. function isIOS () {
  58785. return /iPad|iPhone|iPod/.test(window.navigator.platform);
  58786. }
  58787. module.exports.isIOS = isIOS;
  58788. function isMobileDeviceRequestingDesktopSite () {
  58789. return !isMobile() && !isMobileVR() && window.orientation !== undefined;
  58790. }
  58791. module.exports.isMobileDeviceRequestingDesktopSite = isMobileDeviceRequestingDesktopSite;
  58792. /**
  58793. * Detect Oculus Browser (standalone headset)
  58794. */
  58795. function isOculusBrowser () {
  58796. return /(OculusBrowser)/i.test(window.navigator.userAgent);
  58797. }
  58798. module.exports.isOculusBrowser = isOculusBrowser;
  58799. /**
  58800. * Detect Firefox Reality (standalone headset)
  58801. */
  58802. function isFirefoxReality () {
  58803. return /(Mobile VR)/i.test(window.navigator.userAgent);
  58804. }
  58805. module.exports.isFirefoxReality = isFirefoxReality;
  58806. /**
  58807. * Detect browsers in Stand-Alone headsets
  58808. */
  58809. function isMobileVR () {
  58810. return isOculusBrowser() || isFirefoxReality();
  58811. }
  58812. module.exports.isMobileVR = isMobileVR;
  58813. function isR7 () {
  58814. return /R7 Build/.test(window.navigator.userAgent);
  58815. }
  58816. module.exports.isR7 = isR7;
  58817. /**
  58818. * Checks mobile device orientation.
  58819. * @return {Boolean} True if landscape orientation.
  58820. */
  58821. module.exports.isLandscape = function () {
  58822. var orientation = window.orientation;
  58823. if (isR7()) { orientation += 90; }
  58824. return orientation === 90 || orientation === -90;
  58825. };
  58826. /**
  58827. * Check if running in a browser or spoofed browser (bundler).
  58828. * We need to check a node api that isn't mocked on either side.
  58829. * `require` and `module.exports` are mocked in browser by bundlers.
  58830. * `window` is mocked in node.
  58831. * `process` is also mocked by browserify, but has custom properties.
  58832. */
  58833. module.exports.isBrowserEnvironment = !!(!process || process.browser);
  58834. /**
  58835. * Check if running in node on the server.
  58836. */
  58837. module.exports.isNodeEnvironment = !module.exports.isBrowserEnvironment;
  58838. }).call(this,_dereq_('_process'))
  58839. },{"_process":49,"debug":8}],200:[function(_dereq_,module,exports){
  58840. /**
  58841. * Split a delimited component property string (e.g., `material.color`) to an object
  58842. * containing `component` name and `property` name. If there is no delimiter, just return the
  58843. * string back.
  58844. *
  58845. * Cache arrays from splitting strings via delimiter to save on memory.
  58846. *
  58847. * @param {string} str - e.g., `material.opacity`.
  58848. * @param {string} delimiter - e.g., `.`.
  58849. * @returns {array} e.g., `['material', 'opacity']`.
  58850. */
  58851. var propertyPathCache = {};
  58852. function getComponentPropertyPath (str, delimiter) {
  58853. delimiter = delimiter || '.';
  58854. if (!propertyPathCache[delimiter]) { propertyPathCache[delimiter] = {}; }
  58855. if (str.indexOf(delimiter) !== -1) {
  58856. propertyPathCache[delimiter][str] = str.split(delimiter);
  58857. } else {
  58858. propertyPathCache[delimiter][str] = str;
  58859. }
  58860. return propertyPathCache[delimiter][str];
  58861. }
  58862. module.exports.getComponentPropertyPath = getComponentPropertyPath;
  58863. module.exports.propertyPathCache = propertyPathCache;
  58864. /**
  58865. * Get component property using encoded component name + component property name with a
  58866. * delimiter.
  58867. */
  58868. module.exports.getComponentProperty = function (el, name, delimiter) {
  58869. var splitName;
  58870. delimiter = delimiter || '.';
  58871. if (name.indexOf(delimiter) !== -1) {
  58872. splitName = getComponentPropertyPath(name, delimiter);
  58873. if (splitName.constructor === String) {
  58874. return el.getAttribute(splitName);
  58875. }
  58876. return el.getAttribute(splitName[0])[splitName[1]];
  58877. }
  58878. return el.getAttribute(name);
  58879. };
  58880. /**
  58881. * Set component property using encoded component name + component property name with a
  58882. * delimiter.
  58883. */
  58884. module.exports.setComponentProperty = function (el, name, value, delimiter) {
  58885. var splitName;
  58886. delimiter = delimiter || '.';
  58887. if (name.indexOf(delimiter) !== -1) {
  58888. splitName = getComponentPropertyPath(name, delimiter);
  58889. if (splitName.constructor === String) {
  58890. el.setAttribute(splitName, value);
  58891. } else {
  58892. el.setAttribute(splitName[0], splitName[1], value);
  58893. }
  58894. return;
  58895. }
  58896. el.setAttribute(name, value);
  58897. };
  58898. },{}],201:[function(_dereq_,module,exports){
  58899. module.exports = function forceCanvasResizeSafariMobile (canvasEl) {
  58900. var width = canvasEl.style.width;
  58901. var height = canvasEl.style.height;
  58902. // Taken from webvr-polyfill (https://github.com/borismus/webvr-polyfill/blob/85f657cd502ec9417bf26b87c3cb2afa6a70e079/src/util.js#L200)
  58903. // iOS only workaround for https://bugs.webkit.org/show_bug.cgi?id=152556
  58904. // By changing the size 1 pixel and restoring the previous value
  58905. // we trigger a size recalculation cycle.
  58906. canvasEl.style.width = (parseInt(width, 10) + 1) + 'px';
  58907. canvasEl.style.height = (parseInt(height, 10) + 1) + 'px';
  58908. setTimeout(function () {
  58909. canvasEl.style.width = width;
  58910. canvasEl.style.height = height;
  58911. }, 200);
  58912. };
  58913. },{}],202:[function(_dereq_,module,exports){
  58914. /* global location */
  58915. /* Centralized place to reference utilities since utils is exposed to the user. */
  58916. var debug = _dereq_('./debug');
  58917. var deepAssign = _dereq_('deep-assign');
  58918. var device = _dereq_('./device');
  58919. var objectAssign = _dereq_('object-assign');
  58920. var objectPool = _dereq_('./object-pool');
  58921. var warn = debug('utils:warn');
  58922. module.exports.bind = _dereq_('./bind');
  58923. module.exports.coordinates = _dereq_('./coordinates');
  58924. module.exports.debug = debug;
  58925. module.exports.device = device;
  58926. module.exports.entity = _dereq_('./entity');
  58927. module.exports.forceCanvasResizeSafariMobile = _dereq_('./forceCanvasResizeSafariMobile');
  58928. module.exports.isIE11 = _dereq_('./is-ie11');
  58929. module.exports.material = _dereq_('./material');
  58930. module.exports.objectPool = objectPool;
  58931. module.exports.split = _dereq_('./split').split;
  58932. module.exports.styleParser = _dereq_('./styleParser');
  58933. module.exports.trackedControls = _dereq_('./tracked-controls');
  58934. module.exports.checkHeadsetConnected = function () {
  58935. warn('`utils.checkHeadsetConnected` has moved to `utils.device.checkHeadsetConnected`');
  58936. return device.checkHeadsetConnected(arguments);
  58937. };
  58938. module.exports.isGearVR = module.exports.device.isGearVR = function () {
  58939. warn('`utils.isGearVR` has been deprecated, use `utils.device.isMobileVR`');
  58940. };
  58941. module.exports.isIOS = function () {
  58942. warn('`utils.isIOS` has moved to `utils.device.isIOS`');
  58943. return device.isIOS(arguments);
  58944. };
  58945. module.exports.isOculusGo = module.exports.device.isOculusGo = function () {
  58946. warn('`utils.isOculusGo` has been deprecated, use `utils.device.isMobileVR`');
  58947. };
  58948. module.exports.isMobile = function () {
  58949. warn('`utils.isMobile has moved to `utils.device.isMobile`');
  58950. return device.isMobile(arguments);
  58951. };
  58952. /**
  58953. * Returns throttle function that gets called at most once every interval.
  58954. *
  58955. * @param {function} functionToThrottle
  58956. * @param {number} minimumInterval - Minimal interval between calls (milliseconds).
  58957. * @param {object} optionalContext - If given, bind function to throttle to this context.
  58958. * @returns {function} Throttled function.
  58959. */
  58960. module.exports.throttle = function (functionToThrottle, minimumInterval, optionalContext) {
  58961. var lastTime;
  58962. if (optionalContext) {
  58963. functionToThrottle = module.exports.bind(functionToThrottle, optionalContext);
  58964. }
  58965. return function () {
  58966. var time = Date.now();
  58967. var sinceLastTime = typeof lastTime === 'undefined' ? minimumInterval : time - lastTime;
  58968. if (typeof lastTime === 'undefined' || (sinceLastTime >= minimumInterval)) {
  58969. lastTime = time;
  58970. functionToThrottle.apply(null, arguments);
  58971. }
  58972. };
  58973. };
  58974. /**
  58975. * Returns throttle function that gets called at most once every interval.
  58976. * Uses the time/timeDelta timestamps provided by the global render loop for better perf.
  58977. *
  58978. * @param {function} functionToThrottle
  58979. * @param {number} minimumInterval - Minimal interval between calls (milliseconds).
  58980. * @param {object} optionalContext - If given, bind function to throttle to this context.
  58981. * @returns {function} Throttled function.
  58982. */
  58983. module.exports.throttleTick = function (functionToThrottle, minimumInterval, optionalContext) {
  58984. var lastTime;
  58985. if (optionalContext) {
  58986. functionToThrottle = module.exports.bind(functionToThrottle, optionalContext);
  58987. }
  58988. return function (time, delta) {
  58989. var sinceLastTime = typeof lastTime === 'undefined' ? delta : time - lastTime;
  58990. if (typeof lastTime === 'undefined' || (sinceLastTime >= minimumInterval)) {
  58991. lastTime = time;
  58992. functionToThrottle(time, sinceLastTime);
  58993. }
  58994. };
  58995. };
  58996. /**
  58997. * Returns debounce function that gets called only once after a set of repeated calls.
  58998. *
  58999. * @param {function} functionToDebounce
  59000. * @param {number} wait - Time to wait for repeated function calls (milliseconds).
  59001. * @param {boolean} immediate - Calls the function immediately regardless of if it should be waiting.
  59002. * @returns {function} Debounced function.
  59003. */
  59004. module.exports.debounce = function (func, wait, immediate) {
  59005. var timeout;
  59006. return function () {
  59007. var context = this;
  59008. var args = arguments;
  59009. var later = function () {
  59010. timeout = null;
  59011. if (!immediate) func.apply(context, args);
  59012. };
  59013. var callNow = immediate && !timeout;
  59014. clearTimeout(timeout);
  59015. timeout = setTimeout(later, wait);
  59016. if (callNow) func.apply(context, args);
  59017. };
  59018. };
  59019. /**
  59020. * Mix the properties of source object(s) into a destination object.
  59021. *
  59022. * @param {object} dest - The object to which properties will be copied.
  59023. * @param {...object} source - The object(s) from which properties will be copied.
  59024. */
  59025. module.exports.extend = objectAssign;
  59026. module.exports.extendDeep = deepAssign;
  59027. module.exports.clone = function (obj) {
  59028. return JSON.parse(JSON.stringify(obj));
  59029. };
  59030. /**
  59031. * Checks if two values are equal.
  59032. * Includes objects and arrays and nested objects and arrays.
  59033. * Try to keep this function performant as it will be called often to see if a component
  59034. * should be updated.
  59035. *
  59036. * @param {object} a - First object.
  59037. * @param {object} b - Second object.
  59038. * @returns {boolean} Whether two objects are deeply equal.
  59039. */
  59040. var deepEqual = (function () {
  59041. var arrayPool = objectPool.createPool(function () { return []; });
  59042. return function (a, b) {
  59043. var key;
  59044. var keysA;
  59045. var keysB;
  59046. var i;
  59047. var valA;
  59048. var valB;
  59049. // If not objects or arrays, compare as values.
  59050. if (a === undefined || b === undefined || a === null || b === null ||
  59051. !(a && b && (a.constructor === Object && b.constructor === Object) ||
  59052. (a.constructor === Array && b.constructor === Array))) {
  59053. return a === b;
  59054. }
  59055. // Different number of keys, not equal.
  59056. keysA = arrayPool.use();
  59057. keysB = arrayPool.use();
  59058. keysA.length = 0;
  59059. keysB.length = 0;
  59060. for (key in a) { keysA.push(key); }
  59061. for (key in b) { keysB.push(key); }
  59062. if (keysA.length !== keysB.length) {
  59063. arrayPool.recycle(keysA);
  59064. arrayPool.recycle(keysB);
  59065. return false;
  59066. }
  59067. // Return `false` at the first sign of inequality.
  59068. for (i = 0; i < keysA.length; ++i) {
  59069. valA = a[keysA[i]];
  59070. valB = b[keysA[i]];
  59071. // Check nested array and object.
  59072. if ((typeof valA === 'object' || typeof valB === 'object') ||
  59073. (Array.isArray(valA) && Array.isArray(valB))) {
  59074. if (valA === valB) { continue; }
  59075. if (!deepEqual(valA, valB)) {
  59076. arrayPool.recycle(keysA);
  59077. arrayPool.recycle(keysB);
  59078. return false;
  59079. }
  59080. } else if (valA !== valB) {
  59081. arrayPool.recycle(keysA);
  59082. arrayPool.recycle(keysB);
  59083. return false;
  59084. }
  59085. }
  59086. arrayPool.recycle(keysA);
  59087. arrayPool.recycle(keysB);
  59088. return true;
  59089. };
  59090. })();
  59091. module.exports.deepEqual = deepEqual;
  59092. /**
  59093. * Computes the difference between two objects.
  59094. *
  59095. * @param {object} a - First object to compare (e.g., oldData).
  59096. * @param {object} b - Second object to compare (e.g., newData).
  59097. * @returns {object}
  59098. * Difference object where set of keys note which values were not equal, and values are
  59099. * `b`'s values.
  59100. */
  59101. module.exports.diff = (function () {
  59102. var keys = [];
  59103. return function (a, b, targetObject) {
  59104. var aVal;
  59105. var bVal;
  59106. var bKey;
  59107. var diff;
  59108. var key;
  59109. var i;
  59110. var isComparingObjects;
  59111. diff = targetObject || {};
  59112. // Collect A keys.
  59113. keys.length = 0;
  59114. for (key in a) { keys.push(key); }
  59115. if (!b) { return diff; }
  59116. // Collect B keys.
  59117. for (bKey in b) {
  59118. if (keys.indexOf(bKey) === -1) {
  59119. keys.push(bKey);
  59120. }
  59121. }
  59122. for (i = 0; i < keys.length; i++) {
  59123. key = keys[i];
  59124. aVal = a[key];
  59125. bVal = b[key];
  59126. isComparingObjects = aVal && bVal &&
  59127. aVal.constructor === Object && bVal.constructor === Object;
  59128. if ((isComparingObjects && !deepEqual(aVal, bVal)) ||
  59129. (!isComparingObjects && aVal !== bVal)) {
  59130. diff[key] = bVal;
  59131. }
  59132. }
  59133. return diff;
  59134. };
  59135. })();
  59136. /**
  59137. * Returns whether we should capture this keyboard event for keyboard shortcuts.
  59138. * @param {Event} event Event object.
  59139. * @returns {Boolean} Whether the key event should be captured.
  59140. */
  59141. module.exports.shouldCaptureKeyEvent = function (event) {
  59142. if (event.metaKey) { return false; }
  59143. return document.activeElement === document.body;
  59144. };
  59145. /**
  59146. * Splits a string into an array based on a delimiter.
  59147. *
  59148. * @param {string=} [str=''] Source string
  59149. * @param {string=} [delimiter=' '] Delimiter to use
  59150. * @returns {array} Array of delimited strings
  59151. */
  59152. module.exports.splitString = function (str, delimiter) {
  59153. if (typeof delimiter === 'undefined') { delimiter = ' '; }
  59154. // First collapse the whitespace (or whatever the delimiter is).
  59155. var regex = new RegExp(delimiter, 'g');
  59156. str = (str || '').replace(regex, delimiter);
  59157. // Then split.
  59158. return str.split(delimiter);
  59159. };
  59160. /**
  59161. * Extracts data from the element given an object that contains expected keys.
  59162. *
  59163. * @param {Element} Source element.
  59164. * @param {Object} [defaults={}] Object of default key-value pairs.
  59165. * @returns {Object}
  59166. */
  59167. module.exports.getElData = function (el, defaults) {
  59168. defaults = defaults || {};
  59169. var data = {};
  59170. Object.keys(defaults).forEach(copyAttribute);
  59171. function copyAttribute (key) {
  59172. if (el.hasAttribute(key)) {
  59173. data[key] = el.getAttribute(key);
  59174. }
  59175. }
  59176. return data;
  59177. };
  59178. /**
  59179. * Retrieves querystring value.
  59180. * @param {String} name Name of querystring key.
  59181. * @return {String} Value
  59182. */
  59183. module.exports.getUrlParameter = function (name) {
  59184. // eslint-disable-next-line no-useless-escape
  59185. name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
  59186. var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
  59187. var results = regex.exec(location.search);
  59188. return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
  59189. };
  59190. /**
  59191. * Detects whether context is within iframe.
  59192. */
  59193. module.exports.isIframed = function () {
  59194. return window.top !== window.self;
  59195. };
  59196. /**
  59197. * Finds all elements under the element that have the isScene
  59198. * property set to true
  59199. */
  59200. module.exports.findAllScenes = function (el) {
  59201. var matchingElements = [];
  59202. var allElements = el.getElementsByTagName('*');
  59203. for (var i = 0, n = allElements.length; i < n; i++) {
  59204. if (allElements[i].isScene) {
  59205. // Element exists with isScene set.
  59206. matchingElements.push(allElements[i]);
  59207. }
  59208. }
  59209. return matchingElements;
  59210. };
  59211. // Must be at bottom to avoid circular dependency.
  59212. module.exports.srcLoader = _dereq_('./src-loader');
  59213. },{"./bind":196,"./coordinates":197,"./debug":198,"./device":199,"./entity":200,"./forceCanvasResizeSafariMobile":201,"./is-ie11":203,"./material":205,"./object-pool":206,"./split":207,"./src-loader":208,"./styleParser":209,"./tracked-controls":210,"deep-assign":10,"object-assign":39}],203:[function(_dereq_,module,exports){
  59214. // https://stackoverflow.com/a/17907562
  59215. function getInternetExplorerVersion () {
  59216. var version = -1;
  59217. var userAgent = navigator.userAgent;
  59218. var re;
  59219. if (navigator.appName === 'Microsoft Internet Explorer') {
  59220. re = new RegExp('MSIE ([0-9]{1,}[\\.0-9]{0,})');
  59221. if (re.exec(userAgent) != null) { version = parseFloat(RegExp.$1); }
  59222. } else if (navigator.appName === 'Netscape') {
  59223. re = new RegExp('Trident/.*rv:([0-9]{1,}[\\.0-9]{0,})');
  59224. if (re.exec(userAgent) != null) { version = parseFloat(RegExp.$1); }
  59225. }
  59226. return version;
  59227. }
  59228. module.exports = getInternetExplorerVersion() === 11;
  59229. },{}],204:[function(_dereq_,module,exports){
  59230. /**
  59231. * Check if device is iOS and older than version 10.
  59232. */
  59233. module.exports = function isIOSOlderThan10 (userAgent) {
  59234. return /(iphone|ipod|ipad).*os.(7_|8_|9_)/i.test(userAgent);
  59235. };
  59236. },{}],205:[function(_dereq_,module,exports){
  59237. var THREE = _dereq_('../lib/three');
  59238. var HLS_MIMETYPES = ['application/x-mpegurl', 'application/vnd.apple.mpegurl'];
  59239. var COLOR_MAPS = new Set([
  59240. 'emissiveMap',
  59241. 'envMap',
  59242. 'map',
  59243. 'specularMap'
  59244. ]);
  59245. /**
  59246. * Update `material` texture property (usually but not always `map`)
  59247. * from `data` property (usually but not always `src`)
  59248. *
  59249. * @param {object} shader - A-Frame shader instance.
  59250. * @param {object} data
  59251. */
  59252. module.exports.updateMapMaterialFromData = function (materialName, dataName, shader, data) {
  59253. var el = shader.el;
  59254. var material = shader.material;
  59255. var rendererSystem = el.sceneEl.systems.renderer;
  59256. var src = data[dataName];
  59257. // Because a single material / shader may have multiple textures,
  59258. // we need to remember the source value for this data property
  59259. // to avoid redundant operations which can be expensive otherwise
  59260. // (e.g. video texture loads).
  59261. if (!shader.materialSrcs) { shader.materialSrcs = {}; }
  59262. if (!src) {
  59263. // Forget the prior material src.
  59264. delete shader.materialSrcs[materialName];
  59265. // Remove the texture.
  59266. setMap(null);
  59267. return;
  59268. }
  59269. // Don't process if material src hasn't changed.
  59270. if (src === shader.materialSrcs[materialName]) { return; }
  59271. // Remember the new src for this texture (there may be multiple).
  59272. shader.materialSrcs[materialName] = src;
  59273. // If the new material src is already a texture, just use it.
  59274. if (src instanceof THREE.Texture) { setMap(src); } else {
  59275. // Load texture for the new material src.
  59276. // (And check if we should still use it once available in callback.)
  59277. el.sceneEl.systems.material.loadTexture(src,
  59278. {src: src, repeat: data.repeat, offset: data.offset, npot: data.npot},
  59279. checkSetMap);
  59280. }
  59281. function checkSetMap (texture) {
  59282. // If the source has been changed, don't use loaded texture.
  59283. if (shader.materialSrcs[materialName] !== src) { return; }
  59284. setMap(texture);
  59285. }
  59286. function setMap (texture) {
  59287. material[materialName] = texture;
  59288. if (texture && COLOR_MAPS.has(materialName)) {
  59289. rendererSystem.applyColorCorrection(texture);
  59290. }
  59291. material.needsUpdate = true;
  59292. handleTextureEvents(el, texture);
  59293. }
  59294. };
  59295. /**
  59296. * Update `material.map` given `data.src`. For standard and flat shaders.
  59297. *
  59298. * @param {object} shader - A-Frame shader instance.
  59299. * @param {object} data
  59300. */
  59301. module.exports.updateMap = function (shader, data) {
  59302. return module.exports.updateMapMaterialFromData('map', 'src', shader, data);
  59303. };
  59304. /**
  59305. * Updates the material's maps which give the illusion of extra geometry.
  59306. *
  59307. * @param {string} longType - The friendly name of the map from the component e.g. ambientOcclusionMap becomes aoMap in THREE.js
  59308. * @param {object} shader - A-Frame shader instance
  59309. * @param {object} data
  59310. */
  59311. module.exports.updateDistortionMap = function (longType, shader, data) {
  59312. var shortType = longType;
  59313. if (longType === 'ambientOcclusion') { shortType = 'ao'; }
  59314. var el = shader.el;
  59315. var material = shader.material;
  59316. var rendererSystem = el.sceneEl.systems.renderer;
  59317. var src = data[longType + 'Map'];
  59318. var info = {};
  59319. info.src = src;
  59320. // Pass through the repeat and offset to be handled by the material loader.
  59321. info.offset = data[longType + 'TextureOffset'];
  59322. info.repeat = data[longType + 'TextureRepeat'];
  59323. info.wrap = data[longType + 'TextureWrap'];
  59324. if (src) {
  59325. if (src === shader[longType + 'TextureSrc']) { return; }
  59326. // Texture added or changed.
  59327. shader[longType + 'TextureSrc'] = src;
  59328. el.sceneEl.systems.material.loadTexture(src, info, setMap);
  59329. return;
  59330. }
  59331. // Texture removed.
  59332. if (!material.map) { return; }
  59333. setMap(null);
  59334. function setMap (texture) {
  59335. var slot = shortType + 'Map';
  59336. material[slot] = texture;
  59337. if (texture && COLOR_MAPS.has(slot)) {
  59338. rendererSystem.applyColorCorrection(texture);
  59339. }
  59340. material.needsUpdate = true;
  59341. handleTextureEvents(el, texture);
  59342. }
  59343. };
  59344. /**
  59345. * Emit event on entities on texture-related events.
  59346. *
  59347. * @param {Element} el - Entity.
  59348. * @param {object} texture - three.js Texture.
  59349. */
  59350. function handleTextureEvents (el, texture) {
  59351. if (!texture) { return; }
  59352. el.emit('materialtextureloaded', {src: texture.image, texture: texture});
  59353. // Video events.
  59354. if (!texture.image || texture.image.tagName !== 'VIDEO') { return; }
  59355. texture.image.addEventListener('loadeddata', function emitVideoTextureLoadedDataAll () {
  59356. // Check to see if we need to use iOS 10 HLS shader.
  59357. // Only override the shader if it is stock shader that we know doesn't correct.
  59358. if (!el.components || !el.components.material) { return; }
  59359. if (texture.needsCorrectionBGRA && texture.needsCorrectionFlipY &&
  59360. ['standard', 'flat'].indexOf(el.components.material.data.shader) !== -1) {
  59361. el.setAttribute('material', 'shader', 'ios10hls');
  59362. }
  59363. el.emit('materialvideoloadeddata', {src: texture.image, texture: texture});
  59364. });
  59365. texture.image.addEventListener('ended', function emitVideoTextureEndedAll () {
  59366. // Works for non-looping videos only.
  59367. el.emit('materialvideoended', {src: texture.image, texture: texture});
  59368. });
  59369. }
  59370. module.exports.handleTextureEvents = handleTextureEvents;
  59371. /**
  59372. * Given video element src and type, guess whether stream is HLS.
  59373. *
  59374. * @param {string} src - src from video element (generally URL to content).
  59375. * @param {string} type - type from video element (generally MIME type if present).
  59376. */
  59377. module.exports.isHLS = function (src, type) {
  59378. if (type && HLS_MIMETYPES.includes(type.toLowerCase())) { return true; }
  59379. if (src && src.toLowerCase().indexOf('.m3u8') > 0) { return true; }
  59380. return false;
  59381. };
  59382. },{"../lib/three":176}],206:[function(_dereq_,module,exports){
  59383. /*
  59384. Adapted deePool by Kyle Simpson.
  59385. MIT License: http://getify.mit-license.org
  59386. */
  59387. var EMPTY_SLOT = Object.freeze(Object.create(null));
  59388. // Default object factory.
  59389. function defaultObjectFactory () { return {}; }
  59390. /**
  59391. * Create a new pool.
  59392. */
  59393. module.exports.createPool = function createPool (objectFactory) {
  59394. var objPool = [];
  59395. var nextFreeSlot = null; // Pool location to look for a free object to use.
  59396. objectFactory = objectFactory || defaultObjectFactory;
  59397. function use () {
  59398. var objToUse;
  59399. if (nextFreeSlot === null || nextFreeSlot === objPool.length) {
  59400. grow(objPool.length || 5);
  59401. }
  59402. objToUse = objPool[nextFreeSlot];
  59403. objPool[nextFreeSlot++] = EMPTY_SLOT;
  59404. clearObject(objToUse);
  59405. return objToUse;
  59406. }
  59407. function recycle (obj) {
  59408. if (!(obj instanceof Object)) { return; }
  59409. if (nextFreeSlot === null || nextFreeSlot === -1) {
  59410. objPool[objPool.length] = obj;
  59411. return;
  59412. }
  59413. objPool[--nextFreeSlot] = obj;
  59414. }
  59415. function grow (count) {
  59416. var currentLength;
  59417. var i;
  59418. count = count === undefined ? objPool.length : count;
  59419. if (count > 0 && nextFreeSlot == null) {
  59420. nextFreeSlot = 0;
  59421. }
  59422. if (count > 0) {
  59423. currentLength = objPool.length;
  59424. objPool.length += Number(count);
  59425. for (i = currentLength; i < objPool.length; i++) {
  59426. // Add new obj to pool.
  59427. objPool[i] = objectFactory();
  59428. }
  59429. }
  59430. return objPool.length;
  59431. }
  59432. function size () {
  59433. return objPool.length;
  59434. }
  59435. return {
  59436. grow: grow,
  59437. pool: objPool,
  59438. recycle: recycle,
  59439. size: size,
  59440. use: use
  59441. };
  59442. };
  59443. function clearObject (obj) {
  59444. var key;
  59445. if (!obj || obj.constructor !== Object) { return; }
  59446. for (key in obj) { obj[key] = undefined; }
  59447. }
  59448. module.exports.clearObject = clearObject;
  59449. function removeUnusedKeys (obj, schema) {
  59450. var key;
  59451. if (!obj || obj.constructor !== Object) { return; }
  59452. for (key in obj) {
  59453. if (!(key in schema)) {
  59454. delete obj[key];
  59455. }
  59456. }
  59457. }
  59458. module.exports.removeUnusedKeys = removeUnusedKeys;
  59459. },{}],207:[function(_dereq_,module,exports){
  59460. /**
  59461. * String split with cached result.
  59462. */
  59463. module.exports.split = (function () {
  59464. var splitCache = {};
  59465. return function (str, delimiter) {
  59466. if (!(delimiter in splitCache)) { splitCache[delimiter] = {}; }
  59467. if (str in splitCache[delimiter]) { return splitCache[delimiter][str]; }
  59468. splitCache[delimiter][str] = str.split(delimiter);
  59469. return splitCache[delimiter][str];
  59470. };
  59471. })();
  59472. },{}],208:[function(_dereq_,module,exports){
  59473. /* global Image, XMLHttpRequest */
  59474. var debug = _dereq_('./debug');
  59475. var warn = debug('utils:src-loader:warn');
  59476. /**
  59477. * Validate a texture, either as a selector or as a URL.
  59478. * Detects whether `src` is pointing to an image or video and invokes the appropriate
  59479. * callback.
  59480. *
  59481. * `src` will be passed into the callback
  59482. *
  59483. * @params {string|Element} src - URL or media element.
  59484. * @params {function} isImageCb - callback if texture is an image.
  59485. * @params {function} isVideoCb - callback if texture is a video.
  59486. */
  59487. function validateSrc (src, isImageCb, isVideoCb) {
  59488. checkIsImage(src, function isAnImageUrl (isImage) {
  59489. if (isImage) {
  59490. isImageCb(src);
  59491. return;
  59492. }
  59493. isVideoCb(src);
  59494. });
  59495. }
  59496. /**
  59497. * Validates six images as a cubemap, either as selector or comma-separated
  59498. * URLs.
  59499. *
  59500. * @param {string} src - A selector or comma-separated image URLs. Image URLs
  59501. must be wrapped by `url()`.
  59502. * @param {string} src - A selector or comma-separated image URLs. Image URLs
  59503. must be wrapped by `url()`.
  59504. */
  59505. function validateCubemapSrc (src, cb) {
  59506. var aCubemap;
  59507. var cubemapSrcRegex = '';
  59508. var i;
  59509. var urls;
  59510. var validatedUrls = [];
  59511. for (i = 0; i < 5; i++) {
  59512. cubemapSrcRegex += '(url\\((?:[^\\)]+)\\),\\s*)';
  59513. }
  59514. cubemapSrcRegex += '(url\\((?:[^\\)]+)\\)\\s*)';
  59515. urls = src.match(new RegExp(cubemapSrcRegex));
  59516. // `src` is a comma-separated list of URLs.
  59517. // In this case, re-use validateSrc for each side of the cube.
  59518. function isImageCb (url) {
  59519. validatedUrls.push(url);
  59520. if (validatedUrls.length === 6) {
  59521. cb(validatedUrls);
  59522. }
  59523. }
  59524. if (urls) {
  59525. for (i = 1; i < 7; i++) {
  59526. validateSrc(parseUrl(urls[i]), isImageCb);
  59527. }
  59528. return;
  59529. }
  59530. // `src` is a query selector to <a-cubemap> containing six $([src])s.
  59531. aCubemap = validateAndGetQuerySelector(src);
  59532. if (!aCubemap) { return; }
  59533. if (aCubemap.tagName === 'A-CUBEMAP' && aCubemap.srcs) {
  59534. return cb(aCubemap.srcs);
  59535. }
  59536. // Else if aCubeMap is not a <a-cubemap>.
  59537. warn('Selector "%s" does not point to <a-cubemap>', src);
  59538. }
  59539. /**
  59540. * Parses src from `url(src)`.
  59541. * @param {string} src - String to parse.
  59542. * @return {string} The parsed src, if parseable.
  59543. */
  59544. function parseUrl (src) {
  59545. var parsedSrc = src.match(/\url\((.+)\)/);
  59546. if (!parsedSrc) { return; }
  59547. return parsedSrc[1];
  59548. }
  59549. /**
  59550. * Call back whether `src` is an image.
  59551. *
  59552. * @param {string|Element} src - URL or element that will be tested.
  59553. * @param {function} onResult - Callback with whether `src` is an image.
  59554. */
  59555. function checkIsImage (src, onResult) {
  59556. var request;
  59557. if (src.tagName) {
  59558. onResult(src.tagName === 'IMG');
  59559. return;
  59560. }
  59561. request = new XMLHttpRequest();
  59562. // Try to send HEAD request to check if image first.
  59563. request.open('HEAD', src);
  59564. request.addEventListener('load', function (event) {
  59565. var contentType;
  59566. if (request.status >= 200 && request.status < 300) {
  59567. contentType = request.getResponseHeader('Content-Type');
  59568. if (contentType == null) {
  59569. checkIsImageFallback(src, onResult);
  59570. } else {
  59571. if (contentType.startsWith('image')) {
  59572. onResult(true);
  59573. } else {
  59574. onResult(false);
  59575. }
  59576. }
  59577. } else {
  59578. checkIsImageFallback(src, onResult);
  59579. }
  59580. request.abort();
  59581. });
  59582. request.send();
  59583. }
  59584. function checkIsImageFallback (src, onResult) {
  59585. var tester = new Image();
  59586. tester.addEventListener('load', onLoad);
  59587. function onLoad () { onResult(true); }
  59588. tester.addEventListener('error', onError);
  59589. function onError () { onResult(false); }
  59590. tester.src = src;
  59591. }
  59592. /**
  59593. * Query and validate a query selector,
  59594. *
  59595. * @param {string} selector - DOM selector.
  59596. * @return {object|null|undefined} Selected DOM element if exists.
  59597. null if query yields no results.
  59598. undefined if `selector` is not a valid selector.
  59599. */
  59600. function validateAndGetQuerySelector (selector) {
  59601. try {
  59602. var el = document.querySelector(selector);
  59603. if (!el) {
  59604. warn('No element was found matching the selector: "%s"', selector);
  59605. }
  59606. return el;
  59607. } catch (e) { // Capture exception if it's not a valid selector.
  59608. warn('"%s" is not a valid selector', selector);
  59609. return undefined;
  59610. }
  59611. }
  59612. module.exports = {
  59613. parseUrl: parseUrl,
  59614. validateSrc: validateSrc,
  59615. validateCubemapSrc: validateCubemapSrc
  59616. };
  59617. },{"./debug":198}],209:[function(_dereq_,module,exports){
  59618. /**
  59619. * Utils for parsing style-like strings (e.g., "primitive: box; width: 5; height: 4.5").
  59620. * Some code adapted from `style-attr` (https://github.com/joshwnj/style-attr)
  59621. * by Josh Johnston (MIT License).
  59622. */
  59623. var DASH_REGEX = /-([a-z])/g;
  59624. /**
  59625. * Deserialize style-like string into an object of properties.
  59626. *
  59627. * @param {string} value - HTML attribute value.
  59628. * @param {object} obj - Reused object for object pooling.
  59629. * @returns {object} Property data.
  59630. */
  59631. module.exports.parse = function (value, obj) {
  59632. var parsedData;
  59633. if (typeof value !== 'string') { return value; }
  59634. parsedData = styleParse(value, obj);
  59635. // The style parser returns an object { "" : "test"} when fed a string
  59636. if (parsedData['']) { return value; }
  59637. return transformKeysToCamelCase(parsedData);
  59638. };
  59639. /**
  59640. * Serialize an object of properties into a style-like string.
  59641. *
  59642. * @param {object} data - Property data.
  59643. * @returns {string}
  59644. */
  59645. module.exports.stringify = function (data) {
  59646. if (typeof data === 'string') { return data; }
  59647. return styleStringify(data);
  59648. };
  59649. /**
  59650. * Converts string from hyphen to camelCase.
  59651. *
  59652. * @param {string} str - String to camelCase.
  59653. * @return {string} CamelCased string.
  59654. */
  59655. function toCamelCase (str) {
  59656. return str.replace(DASH_REGEX, upperCase);
  59657. }
  59658. module.exports.toCamelCase = toCamelCase;
  59659. /**
  59660. * Converts object's keys from hyphens to camelCase (e.g., `max-value` to
  59661. * `maxValue`).
  59662. *
  59663. * @param {object} obj - The object to camelCase keys.
  59664. * @return {object} The object with keys camelCased.
  59665. */
  59666. function transformKeysToCamelCase (obj) {
  59667. var camelKey;
  59668. var key;
  59669. for (key in obj) {
  59670. camelKey = toCamelCase(key);
  59671. if (key === camelKey) { continue; }
  59672. obj[camelKey] = obj[key];
  59673. delete obj[key];
  59674. }
  59675. return obj;
  59676. }
  59677. module.exports.transformKeysToCamelCase = transformKeysToCamelCase;
  59678. /**
  59679. * Split a string into chunks matching `<key>: <value>`
  59680. */
  59681. var getKeyValueChunks = (function () {
  59682. var chunks = [];
  59683. var hasUnclosedUrl = /url\([^)]+$/;
  59684. return function getKeyValueChunks (raw) {
  59685. var chunk = '';
  59686. var nextSplit;
  59687. var offset = 0;
  59688. var sep = ';';
  59689. chunks.length = 0;
  59690. while (offset < raw.length) {
  59691. nextSplit = raw.indexOf(sep, offset);
  59692. if (nextSplit === -1) { nextSplit = raw.length; }
  59693. chunk += raw.substring(offset, nextSplit);
  59694. // data URIs can contain semicolons, so make sure we get the whole thing
  59695. if (hasUnclosedUrl.test(chunk)) {
  59696. chunk += ';';
  59697. offset = nextSplit + 1;
  59698. continue;
  59699. }
  59700. chunks.push(chunk.trim());
  59701. chunk = '';
  59702. offset = nextSplit + 1;
  59703. }
  59704. return chunks;
  59705. };
  59706. })();
  59707. /**
  59708. * Convert a style attribute string to an object.
  59709. *
  59710. * @param {object} str - Attribute string.
  59711. * @param {object} obj - Object to reuse as a base, else a new one will be allocated.
  59712. */
  59713. function styleParse (str, obj) {
  59714. var chunks;
  59715. var i;
  59716. var item;
  59717. var pos;
  59718. var key;
  59719. var val;
  59720. obj = obj || {};
  59721. chunks = getKeyValueChunks(str);
  59722. for (i = 0; i < chunks.length; i++) {
  59723. item = chunks[i];
  59724. if (!item) { continue; }
  59725. // Split with `.indexOf` rather than `.split` because the value may also contain colons.
  59726. pos = item.indexOf(':');
  59727. key = item.substr(0, pos).trim();
  59728. val = item.substr(pos + 1).trim();
  59729. obj[key] = val;
  59730. }
  59731. return obj;
  59732. }
  59733. /**
  59734. * Convert an object into an attribute string
  59735. **/
  59736. function styleStringify (obj) {
  59737. var key;
  59738. var keyCount = 0;
  59739. var i = 0;
  59740. var str = '';
  59741. for (key in obj) { keyCount++; }
  59742. for (key in obj) {
  59743. str += (key + ': ' + obj[key]);
  59744. if (i < keyCount - 1) { str += '; '; }
  59745. i++;
  59746. }
  59747. return str;
  59748. }
  59749. function upperCase (str) { return str[1].toUpperCase(); }
  59750. },{}],210:[function(_dereq_,module,exports){
  59751. var DEFAULT_HANDEDNESS = _dereq_('../constants').DEFAULT_HANDEDNESS;
  59752. var AXIS_LABELS = ['x', 'y', 'z', 'w'];
  59753. var NUM_HANDS = 2; // Number of hands in a pair. Should always be 2.
  59754. /**
  59755. * Called on controller component `.play` handlers.
  59756. * Check if controller matches parameters and inject tracked-controls component.
  59757. * Handle event listeners.
  59758. * Generate controllerconnected or controllerdisconnected events.
  59759. *
  59760. * @param {object} component - Tracked controls component.
  59761. * @param {object} idPrefix - Prefix to match in gamepad id if any.
  59762. * @param {object} queryObject - Map of values to match.
  59763. */
  59764. module.exports.checkControllerPresentAndSetup = function (component, idPrefix, queryObject) {
  59765. var el = component.el;
  59766. var controller;
  59767. var hasWebXR = el.sceneEl.hasWebXR;
  59768. var isControllerPresent = hasWebXR ? isControllerPresentWebXR : isControllerPresentWebVR;
  59769. var isPresent;
  59770. controller = isControllerPresent(component, idPrefix, queryObject);
  59771. isPresent = !!controller;
  59772. // If component was previously paused and now playing, re-add event listeners.
  59773. // Handle the event listeners here since this helper method is control of calling
  59774. // `.addEventListeners` and `.removeEventListeners`.
  59775. if (component.controllerPresent && !component.controllerEventsActive && !hasWebXR) {
  59776. component.addEventListeners();
  59777. }
  59778. // Nothing changed, no need to do anything.
  59779. if (isPresent === component.controllerPresent) { return isPresent; }
  59780. component.controllerPresent = isPresent;
  59781. // Update controller presence.
  59782. if (isPresent) {
  59783. component.injectTrackedControls();
  59784. component.addEventListeners();
  59785. el.emit('controllerconnected', {name: component.name, component: component});
  59786. } else {
  59787. component.removeEventListeners();
  59788. el.emit('controllerdisconnected', {name: component.name, component: component});
  59789. }
  59790. };
  59791. /**
  59792. * Enumerate controller (that have pose) and check if they match parameters for WebVR
  59793. *
  59794. * @param {object} component - Tracked controls component.
  59795. * @param {object} idPrefix - Prefix to match in gamepad id if any.
  59796. * @param {object} queryObject - Map of values to match.
  59797. */
  59798. function isControllerPresentWebVR (component, idPrefix, queryObject) {
  59799. var gamepads;
  59800. var sceneEl = component.el.sceneEl;
  59801. var trackedControlsSystem;
  59802. var filterControllerIndex = queryObject.index || 0;
  59803. if (!idPrefix) { return false; }
  59804. trackedControlsSystem = sceneEl && sceneEl.systems['tracked-controls-webvr'];
  59805. if (!trackedControlsSystem) { return false; }
  59806. gamepads = trackedControlsSystem.controllers;
  59807. if (!gamepads.length) { return false; }
  59808. return !!findMatchingControllerWebVR(gamepads, null, idPrefix, queryObject.hand,
  59809. filterControllerIndex);
  59810. }
  59811. /**
  59812. *
  59813. * @param {object} component - Tracked controls component.
  59814. */
  59815. function isControllerPresentWebXR (component, id, queryObject) {
  59816. var controllers;
  59817. var sceneEl = component.el.sceneEl;
  59818. var trackedControlsSystem = sceneEl && sceneEl.systems['tracked-controls-webxr'];
  59819. if (!trackedControlsSystem) { return false; }
  59820. controllers = trackedControlsSystem.controllers;
  59821. if (!controllers || !controllers.length) { return false; }
  59822. return findMatchingControllerWebXR(
  59823. controllers, id,
  59824. queryObject.hand, queryObject.index, queryObject.iterateControllerProfiles);
  59825. }
  59826. module.exports.isControllerPresentWebVR = isControllerPresentWebVR;
  59827. module.exports.isControllerPresentWebXR = isControllerPresentWebXR;
  59828. /**
  59829. * Walk through the given controllers to find any where the device ID equals
  59830. * filterIdExact, or startsWith filterIdPrefix.
  59831. * A controller where this considered true is considered a 'match'.
  59832. *
  59833. * For each matching controller:
  59834. * If filterHand is set, and the controller:
  59835. * is handed, we further verify that controller.hand equals filterHand.
  59836. * is unhanded (controller.hand is ''), we skip until we have found a
  59837. * number of matching controllers that equals filterControllerIndex
  59838. * If filterHand is not set, we skip until we have found the nth matching
  59839. * controller, where n equals filterControllerIndex
  59840. *
  59841. * The method should be called with one of: [filterIdExact, filterIdPrefix] AND
  59842. * one or both of: [filterHand, filterControllerIndex]
  59843. *
  59844. * @param {object} controllers - Array of gamepads to search
  59845. * @param {string} filterIdExact - If set, used to find controllers with id === this value
  59846. * @param {string} filterIdPrefix - If set, used to find controllers with id startsWith this value
  59847. * @param {object} filterHand - If set, further filters controllers with matching 'hand' property
  59848. * @param {object} filterControllerIndex - Find the nth matching controller,
  59849. * where n equals filterControllerIndex. defaults to 0.
  59850. */
  59851. function findMatchingControllerWebVR (controllers, filterIdExact, filterIdPrefix, filterHand,
  59852. filterControllerIndex) {
  59853. var controller;
  59854. var i;
  59855. var matchingControllerOccurence = 0;
  59856. var targetControllerMatch = filterControllerIndex >= 0 ? filterControllerIndex : 0;
  59857. for (i = 0; i < controllers.length; i++) {
  59858. controller = controllers[i];
  59859. // Determine if the controller ID matches our criteria.
  59860. if (filterIdPrefix && !controller.id.startsWith(filterIdPrefix)) {
  59861. continue;
  59862. }
  59863. if (!filterIdPrefix && controller.id !== filterIdExact) { continue; }
  59864. // If the hand filter and controller handedness are defined we compare them.
  59865. if (filterHand && controller.hand && filterHand !== controller.hand) { continue; }
  59866. // If we have detected an unhanded controller and the component was asking
  59867. // for a particular hand, we need to treat the controllers in the array as
  59868. // pairs of controllers. This effectively means that we need to skip
  59869. // NUM_HANDS matches for each controller number, instead of 1.
  59870. if (filterHand && !controller.hand) {
  59871. targetControllerMatch = NUM_HANDS * filterControllerIndex + ((filterHand === DEFAULT_HANDEDNESS) ? 0 : 1);
  59872. } else {
  59873. return controller;
  59874. }
  59875. // We are looking for the nth occurence of a matching controller
  59876. // (n equals targetControllerMatch).
  59877. if (matchingControllerOccurence === targetControllerMatch) { return controller; }
  59878. ++matchingControllerOccurence;
  59879. }
  59880. return undefined;
  59881. }
  59882. function findMatchingControllerWebXR (controllers, idPrefix, handedness, index, iterateProfiles) {
  59883. var i;
  59884. var j;
  59885. var controller;
  59886. var controllerMatch = false;
  59887. var controllerHasHandedness;
  59888. var profiles;
  59889. for (i = 0; i < controllers.length; i++) {
  59890. controller = controllers[i];
  59891. profiles = controller.profiles;
  59892. if (profiles.length === 0) { return; }
  59893. if (iterateProfiles) {
  59894. for (j = 0; j < profiles.length; j++) {
  59895. controllerMatch = profiles[j].startsWith(idPrefix);
  59896. if (controllerMatch) { break; }
  59897. }
  59898. } else {
  59899. controllerMatch = profiles[0].startsWith(idPrefix);
  59900. }
  59901. if (!controllerMatch) { continue; }
  59902. // Vive controllers are assigned handedness at runtime and it might not be always available.
  59903. controllerHasHandedness = controller.handedness === 'right' || controller.handedness === 'left';
  59904. if (controllerHasHandedness) {
  59905. if (controller.handedness === handedness) { return controllers[i]; }
  59906. } else { // Fallback to index if controller has no handedness.
  59907. if ((i === index)) { return controllers[i]; }
  59908. }
  59909. }
  59910. return undefined;
  59911. }
  59912. module.exports.findMatchingControllerWebVR = findMatchingControllerWebVR;
  59913. module.exports.findMatchingControllerWebXR = findMatchingControllerWebXR;
  59914. /**
  59915. * Emit specific `moved` event(s) if axes changed based on original axismoved event.
  59916. *
  59917. * @param {object} component - Controller component in use.
  59918. * @param {array} axesMapping - For example `{thumbstick: [0, 1]}`.
  59919. * @param {object} evt - Event to process.
  59920. */
  59921. module.exports.emitIfAxesChanged = function (component, axesMapping, evt) {
  59922. var axes;
  59923. var buttonType;
  59924. var changed;
  59925. var detail;
  59926. var j;
  59927. for (buttonType in axesMapping) {
  59928. axes = axesMapping[buttonType];
  59929. changed = false;
  59930. for (j = 0; j < axes.length; j++) {
  59931. if (evt.detail.changed[axes[j]]) { changed = true; }
  59932. }
  59933. if (!changed) { continue; }
  59934. // Axis has changed. Emit the specific moved event with axis values in detail.
  59935. detail = {};
  59936. for (j = 0; j < axes.length; j++) {
  59937. detail[AXIS_LABELS[j]] = evt.detail.axis[axes[j]];
  59938. }
  59939. component.el.emit(buttonType + 'moved', detail);
  59940. }
  59941. };
  59942. /**
  59943. * Handle a button event and reemits the events.
  59944. *
  59945. * @param {string} id - id of the button.
  59946. * @param {string} evtName - name of the reemitted event
  59947. * @param {object} component - reference to the component
  59948. * @param {string} hand - handedness of the controller: left or right.
  59949. */
  59950. module.exports.onButtonEvent = function (id, evtName, component, hand) {
  59951. var mapping = hand ? component.mapping[hand] : component.mapping;
  59952. var buttonName = mapping.buttons[id];
  59953. component.el.emit(buttonName + evtName);
  59954. if (component.updateModel) {
  59955. component.updateModel(buttonName, evtName);
  59956. }
  59957. };
  59958. },{"../constants":120}],211:[function(_dereq_,module,exports){
  59959. /**
  59960. * @author richt / http://richt.me
  59961. * @author WestLangley / http://github.com/WestLangley
  59962. *
  59963. * W3C Device Orientation control (http://w3c.github.io/deviceorientation/spec-source-orientation.html)
  59964. */
  59965. THREE.DeviceOrientationControls = function ( object ) {
  59966. var scope = this;
  59967. this.object = object;
  59968. this.object.rotation.reorder( 'YXZ' );
  59969. this.enabled = true;
  59970. this.deviceOrientation = {};
  59971. this.screenOrientation = 0;
  59972. this.alphaOffset = 0; // radians
  59973. var onDeviceOrientationChangeEvent = function ( event ) {
  59974. scope.deviceOrientation = event;
  59975. };
  59976. var onScreenOrientationChangeEvent = function () {
  59977. scope.screenOrientation = window.orientation || 0;
  59978. };
  59979. // The angles alpha, beta and gamma form a set of intrinsic Tait-Bryan angles of type Z-X'-Y''
  59980. var setObjectQuaternion = function () {
  59981. var zee = new THREE.Vector3( 0, 0, 1 );
  59982. var euler = new THREE.Euler();
  59983. var q0 = new THREE.Quaternion();
  59984. var q1 = new THREE.Quaternion( - Math.sqrt( 0.5 ), 0, 0, Math.sqrt( 0.5 ) ); // - PI/2 around the x-axis
  59985. return function ( quaternion, alpha, beta, gamma, orient ) {
  59986. euler.set( beta, alpha, - gamma, 'YXZ' ); // 'ZXY' for the device, but 'YXZ' for us
  59987. quaternion.setFromEuler( euler ); // orient the device
  59988. quaternion.multiply( q1 ); // camera looks out the back of the device, not the top
  59989. quaternion.multiply( q0.setFromAxisAngle( zee, - orient ) ); // adjust for screen orientation
  59990. };
  59991. }();
  59992. this.connect = function () {
  59993. onScreenOrientationChangeEvent();
  59994. window.addEventListener( 'orientationchange', onScreenOrientationChangeEvent, false );
  59995. window.addEventListener( 'deviceorientation', onDeviceOrientationChangeEvent, false );
  59996. scope.enabled = true;
  59997. };
  59998. this.disconnect = function () {
  59999. window.removeEventListener( 'orientationchange', onScreenOrientationChangeEvent, false );
  60000. window.removeEventListener( 'deviceorientation', onDeviceOrientationChangeEvent, false );
  60001. scope.enabled = false;
  60002. };
  60003. this.update = function () {
  60004. if ( scope.enabled === false ) return;
  60005. var device = scope.deviceOrientation;
  60006. if ( device ) {
  60007. var alpha = device.alpha ? THREE.Math.degToRad( device.alpha ) + scope.alphaOffset : 0; // Z
  60008. var beta = device.beta ? THREE.Math.degToRad( device.beta ) : 0; // X'
  60009. var gamma = device.gamma ? THREE.Math.degToRad( device.gamma ) : 0; // Y''
  60010. var orient = scope.screenOrientation ? THREE.Math.degToRad( scope.screenOrientation ) : 0; // O
  60011. setObjectQuaternion( scope.object.quaternion, alpha, beta, gamma, orient );
  60012. }
  60013. };
  60014. this.dispose = function () {
  60015. scope.disconnect();
  60016. };
  60017. this.connect();
  60018. };
  60019. },{}],212:[function(_dereq_,module,exports){
  60020. window.glStats = function () {
  60021. var _rS = null;
  60022. var _totalDrawArraysCalls = 0,
  60023. _totalDrawElementsCalls = 0,
  60024. _totalUseProgramCalls = 0,
  60025. _totalFaces = 0,
  60026. _totalVertices = 0,
  60027. _totalPoints = 0,
  60028. _totalBindTexures = 0;
  60029. function _h ( f, c ) {
  60030. return function () {
  60031. c.apply( this, arguments );
  60032. f.apply( this, arguments );
  60033. };
  60034. }
  60035. WebGLRenderingContext.prototype.drawArrays = _h( WebGLRenderingContext.prototype.drawArrays, function () {
  60036. _totalDrawArraysCalls++;
  60037. if ( arguments[ 0 ] == this.POINTS ) _totalPoints += arguments[ 2 ];
  60038. else _totalVertices += arguments[ 2 ];
  60039. } );
  60040. WebGLRenderingContext.prototype.drawElements = _h( WebGLRenderingContext.prototype.drawElements, function () {
  60041. _totalDrawElementsCalls++;
  60042. _totalFaces += arguments[ 1 ] / 3;
  60043. _totalVertices += arguments[ 1 ];
  60044. } );
  60045. WebGLRenderingContext.prototype.useProgram = _h( WebGLRenderingContext.prototype.useProgram, function () {
  60046. _totalUseProgramCalls++;
  60047. } );
  60048. WebGLRenderingContext.prototype.bindTexture = _h( WebGLRenderingContext.prototype.bindTexture, function () {
  60049. _totalBindTexures++;
  60050. } );
  60051. var _values = {
  60052. allcalls: {
  60053. over: 3000,
  60054. caption: 'Calls (hook)'
  60055. },
  60056. drawelements: {
  60057. caption: 'drawElements (hook)'
  60058. },
  60059. drawarrays: {
  60060. caption: 'drawArrays (hook)'
  60061. }
  60062. };
  60063. var _groups = [ {
  60064. caption: 'WebGL',
  60065. values: [ 'allcalls', 'drawelements', 'drawarrays', 'useprogram', 'bindtexture', 'glfaces', 'glvertices', 'glpoints' ]
  60066. } ];
  60067. var _fractions = [ {
  60068. base: 'allcalls',
  60069. steps: [ 'drawelements', 'drawarrays' ]
  60070. } ];
  60071. function _update () {
  60072. _rS( 'allcalls' ).set( _totalDrawArraysCalls + _totalDrawElementsCalls );
  60073. _rS( 'drawElements' ).set( _totalDrawElementsCalls );
  60074. _rS( 'drawArrays' ).set( _totalDrawArraysCalls );
  60075. _rS( 'bindTexture' ).set( _totalBindTexures );
  60076. _rS( 'useProgram' ).set( _totalUseProgramCalls );
  60077. _rS( 'glfaces' ).set( _totalFaces );
  60078. _rS( 'glvertices' ).set( _totalVertices );
  60079. _rS( 'glpoints' ).set( _totalPoints );
  60080. }
  60081. function _start () {
  60082. _totalDrawArraysCalls = 0;
  60083. _totalDrawElementsCalls = 0;
  60084. _totalUseProgramCalls = 0;
  60085. _totalFaces = 0;
  60086. _totalVertices = 0;
  60087. _totalPoints = 0;
  60088. _totalBindTexures = 0;
  60089. }
  60090. function _end () {}
  60091. function _attach ( r ) {
  60092. _rS = r;
  60093. }
  60094. return {
  60095. update: _update,
  60096. start: _start,
  60097. end: _end,
  60098. attach: _attach,
  60099. values: _values,
  60100. groups: _groups,
  60101. fractions: _fractions
  60102. };
  60103. };
  60104. window.threeStats = function ( renderer ) {
  60105. var _rS = null;
  60106. var _values = {
  60107. 'renderer.info.memory.geometries': {
  60108. caption: 'Geometries'
  60109. },
  60110. 'renderer.info.memory.textures': {
  60111. caption: 'Textures'
  60112. },
  60113. 'renderer.info.programs': {
  60114. caption: 'Programs'
  60115. },
  60116. 'renderer.info.render.calls': {
  60117. caption: 'Calls'
  60118. },
  60119. 'renderer.info.render.triangles': {
  60120. caption: 'Triangles',
  60121. over: 1000
  60122. },
  60123. 'renderer.info.render.points': {
  60124. caption: 'Points'
  60125. }
  60126. };
  60127. var _groups = [ {
  60128. caption: 'Three.js - Memory',
  60129. values: [ 'renderer.info.memory.geometries', 'renderer.info.programs', 'renderer.info.memory.textures' ]
  60130. }, {
  60131. caption: 'Three.js - Render',
  60132. values: [ 'renderer.info.render.calls', 'renderer.info.render.triangles', 'renderer.info.render.points' ]
  60133. } ];
  60134. var _fractions = [];
  60135. function _update () {
  60136. _rS( 'renderer.info.memory.geometries' ).set( renderer.info.memory.geometries );
  60137. _rS( 'renderer.info.programs' ).set( renderer.info.programs.length );
  60138. _rS( 'renderer.info.memory.textures' ).set( renderer.info.memory.textures );
  60139. _rS( 'renderer.info.render.calls' ).set( renderer.info.render.calls );
  60140. _rS( 'renderer.info.render.triangles' ).set( renderer.info.render.triangles );
  60141. _rS( 'renderer.info.render.points' ).set( renderer.info.render.points );
  60142. }
  60143. function _start () {}
  60144. function _end () {}
  60145. function _attach ( r ) {
  60146. _rS = r;
  60147. }
  60148. return {
  60149. update: _update,
  60150. start: _start,
  60151. end: _end,
  60152. attach: _attach,
  60153. values: _values,
  60154. groups: _groups,
  60155. fractions: _fractions
  60156. };
  60157. };
  60158. /*
  60159. * From https://github.com/paulirish/memory-stats.js
  60160. */
  60161. window.BrowserStats = function () {
  60162. var _rS = null;
  60163. var _usedJSHeapSize = 0,
  60164. _totalJSHeapSize = 0;
  60165. if ( window.performance && !performance.memory ) {
  60166. performance.memory = {
  60167. usedJSHeapSize: 0,
  60168. totalJSHeapSize: 0
  60169. };
  60170. }
  60171. if ( performance.memory.totalJSHeapSize === 0 ) {
  60172. console.warn( 'totalJSHeapSize === 0... performance.memory is only available in Chrome .' );
  60173. }
  60174. var _values = {
  60175. memory: {
  60176. caption: 'Used Memory',
  60177. average: true,
  60178. avgMs: 1000,
  60179. over: 22
  60180. },
  60181. total: {
  60182. caption: 'Total Memory'
  60183. }
  60184. };
  60185. var _groups = [ {
  60186. caption: 'Browser',
  60187. values: [ 'memory', 'total' ]
  60188. } ];
  60189. var _fractions = [ {
  60190. base: 'total',
  60191. steps: [ 'memory' ]
  60192. } ];
  60193. var log1024 = Math.log( 1024 );
  60194. function _size ( v ) {
  60195. var precision = 100; //Math.pow(10, 2);
  60196. var i = Math.floor( Math.log( v ) / log1024 );
  60197. return Math.round( v * precision / Math.pow( 1024, i ) ) / precision; // + ' ' + sizes[i];
  60198. }
  60199. function _update () {
  60200. _usedJSHeapSize = _size( performance.memory.usedJSHeapSize );
  60201. _totalJSHeapSize = _size( performance.memory.totalJSHeapSize );
  60202. _rS( 'memory' ).set( _usedJSHeapSize );
  60203. _rS( 'total' ).set( _totalJSHeapSize );
  60204. }
  60205. function _start () {
  60206. _usedJSHeapSize = 0;
  60207. }
  60208. function _end () {}
  60209. function _attach ( r ) {
  60210. _rS = r;
  60211. }
  60212. return {
  60213. update: _update,
  60214. start: _start,
  60215. end: _end,
  60216. attach: _attach,
  60217. values: _values,
  60218. groups: _groups,
  60219. fractions: _fractions
  60220. };
  60221. };
  60222. if (typeof module === 'object') {
  60223. module.exports = {
  60224. glStats: window.glStats,
  60225. threeStats: window.threeStats,
  60226. BrowserStats: window.BrowserStats
  60227. };
  60228. }
  60229. },{}],213:[function(_dereq_,module,exports){
  60230. // performance.now() polyfill from https://gist.github.com/paulirish/5438650
  60231. 'use strict';
  60232. ( function () {
  60233. if ( 'performance' in window == false ) {
  60234. window.performance = {};
  60235. }
  60236. var performance = window.performance;
  60237. if ( 'now' in performance == false ) {
  60238. var nowOffset = Date.now();
  60239. if ( performance.timing && performance.timing.navigationStart ) {
  60240. nowOffset = performance.timing.navigationStart;
  60241. }
  60242. performance.now = function now () {
  60243. return Date.now() - nowOffset;
  60244. };
  60245. }
  60246. if( !performance.mark ) {
  60247. performance.mark = function(){}
  60248. }
  60249. if( !performance.measure ) {
  60250. performance.measure = function(){}
  60251. }
  60252. } )();
  60253. window.rStats = function rStats ( settings ) {
  60254. function iterateKeys ( array, callback ) {
  60255. var keys = Object.keys( array );
  60256. for ( var j = 0, l = keys.length; j < l; j++ ) {
  60257. callback( keys[ j ] );
  60258. }
  60259. }
  60260. function importCSS ( url ) {
  60261. var element = document.createElement( 'link' );
  60262. element.href = url;
  60263. element.rel = 'stylesheet';
  60264. element.type = 'text/css';
  60265. document.getElementsByTagName( 'head' )[ 0 ].appendChild( element );
  60266. }
  60267. var _settings = settings || {};
  60268. var _colours = _settings.colours || [ '#850700', '#c74900', '#fcb300', '#284280', '#4c7c0c' ];
  60269. var _cssFont = 'https://fonts.googleapis.com/css?family=Roboto+Condensed:400,700,300';
  60270. var _cssRStats = ( _settings.CSSPath ? _settings.CSSPath : '' ) + 'rStats.css';
  60271. var _css = _settings.css || [ _cssFont, _cssRStats ];
  60272. _css.forEach(function (uri) {
  60273. importCSS( uri );
  60274. });
  60275. if ( !_settings.values ) _settings.values = {};
  60276. var _base, _div, _elHeight = 10, _elWidth = 200;
  60277. var _perfCounters = {};
  60278. function Graph ( _dom, _id, _defArg ) {
  60279. var _def = _defArg || {};
  60280. var _canvas = document.createElement( 'canvas' ),
  60281. _ctx = _canvas.getContext( '2d' ),
  60282. _max = 0,
  60283. _current = 0;
  60284. var c = _def.color ? _def.color : '#666666';
  60285. var _dotCanvas = document.createElement( 'canvas' ),
  60286. _dotCtx = _dotCanvas.getContext( '2d' );
  60287. _dotCanvas.width = 1;
  60288. _dotCanvas.height = 2 * _elHeight;
  60289. _dotCtx.fillStyle = '#444444';
  60290. _dotCtx.fillRect( 0, 0, 1, 2 * _elHeight );
  60291. _dotCtx.fillStyle = c;
  60292. _dotCtx.fillRect( 0, _elHeight, 1, _elHeight );
  60293. _dotCtx.fillStyle = '#ffffff';
  60294. _dotCtx.globalAlpha = 0.5;
  60295. _dotCtx.fillRect( 0, _elHeight, 1, 1 );
  60296. _dotCtx.globalAlpha = 1;
  60297. var _alarmCanvas = document.createElement( 'canvas' ),
  60298. _alarmCtx = _alarmCanvas.getContext( '2d' );
  60299. _alarmCanvas.width = 1;
  60300. _alarmCanvas.height = 2 * _elHeight;
  60301. _alarmCtx.fillStyle = '#444444';
  60302. _alarmCtx.fillRect( 0, 0, 1, 2 * _elHeight );
  60303. _alarmCtx.fillStyle = '#b70000';
  60304. _alarmCtx.fillRect( 0, _elHeight, 1, _elHeight );
  60305. _alarmCtx.globalAlpha = 0.5;
  60306. _alarmCtx.fillStyle = '#ffffff';
  60307. _alarmCtx.fillRect( 0, _elHeight, 1, 1 );
  60308. _alarmCtx.globalAlpha = 1;
  60309. function _init () {
  60310. _canvas.width = _elWidth;
  60311. _canvas.height = _elHeight;
  60312. _canvas.style.width = _canvas.width + 'px';
  60313. _canvas.style.height = _canvas.height + 'px';
  60314. _canvas.className = 'rs-canvas';
  60315. _dom.appendChild( _canvas );
  60316. _ctx.fillStyle = '#444444';
  60317. _ctx.fillRect( 0, 0, _canvas.width, _canvas.height );
  60318. }
  60319. function _draw ( v, alarm ) {
  60320. _current += ( v - _current ) * 0.1;
  60321. _max *= 0.99;
  60322. if ( _current > _max ) _max = _current;
  60323. _ctx.drawImage( _canvas, 1, 0, _canvas.width - 1, _canvas.height, 0, 0, _canvas.width - 1, _canvas.height );
  60324. if ( alarm ) {
  60325. _ctx.drawImage( _alarmCanvas, _canvas.width - 1, _canvas.height - _current * _canvas.height / _max - _elHeight );
  60326. } else {
  60327. _ctx.drawImage( _dotCanvas, _canvas.width - 1, _canvas.height - _current * _canvas.height / _max - _elHeight );
  60328. }
  60329. }
  60330. _init();
  60331. return {
  60332. draw: _draw
  60333. };
  60334. }
  60335. function StackGraph ( _dom, _num ) {
  60336. var _canvas = document.createElement( 'canvas' ),
  60337. _ctx = _canvas.getContext( '2d' );
  60338. function _init () {
  60339. _canvas.width = _elWidth;
  60340. _canvas.height = _elHeight * _num;
  60341. _canvas.style.width = _canvas.width + 'px';
  60342. _canvas.style.height = _canvas.height + 'px';
  60343. _canvas.className = 'rs-canvas';
  60344. _dom.appendChild( _canvas );
  60345. _ctx.fillStyle = '#444444';
  60346. _ctx.fillRect( 0, 0, _canvas.width, _canvas.height );
  60347. }
  60348. function _draw ( v ) {
  60349. _ctx.drawImage( _canvas, 1, 0, _canvas.width - 1, _canvas.height, 0, 0, _canvas.width - 1, _canvas.height );
  60350. var th = 0;
  60351. iterateKeys( v, function ( j ) {
  60352. var h = v[ j ] * _canvas.height;
  60353. _ctx.fillStyle = _colours[ j ];
  60354. _ctx.fillRect( _canvas.width - 1, th, 1, h );
  60355. th += h;
  60356. } );
  60357. }
  60358. _init();
  60359. return {
  60360. draw: _draw
  60361. };
  60362. }
  60363. function PerfCounter ( id, group ) {
  60364. var _id = id,
  60365. _time,
  60366. _value = 0,
  60367. _total = 0,
  60368. _averageValue = 0,
  60369. _accumValue = 0,
  60370. _accumStart = performance.now(),
  60371. _accumSamples = 0,
  60372. _dom = document.createElement( 'div' ),
  60373. _spanId = document.createElement( 'span' ),
  60374. _spanValue = document.createElement( 'div' ),
  60375. _spanValueText = document.createTextNode( '' ),
  60376. _def = _settings ? _settings.values[ _id.toLowerCase() ] : null,
  60377. _graph = new Graph( _dom, _id, _def ),
  60378. _started = false;
  60379. _spanId.className = 'rs-counter-id';
  60380. _spanId.textContent = ( _def && _def.caption ) ? _def.caption : _id;
  60381. _spanValue.className = 'rs-counter-value';
  60382. _spanValue.appendChild( _spanValueText );
  60383. _dom.appendChild( _spanId );
  60384. _dom.appendChild( _spanValue );
  60385. if ( group ) group.div.appendChild( _dom );
  60386. else _div.appendChild( _dom );
  60387. _time = performance.now();
  60388. function _average ( v ) {
  60389. if ( _def && _def.average ) {
  60390. _accumValue += v;
  60391. _accumSamples++;
  60392. var t = performance.now();
  60393. if ( t - _accumStart >= ( _def.avgMs || 1000 ) ) {
  60394. _averageValue = _accumValue / _accumSamples;
  60395. _accumValue = 0;
  60396. _accumStart = t;
  60397. _accumSamples = 0;
  60398. }
  60399. }
  60400. }
  60401. function _start () {
  60402. _time = performance.now();
  60403. if( _settings.userTimingAPI ) performance.mark( _id + '-start' );
  60404. _started = true;
  60405. }
  60406. function _end () {
  60407. _value = performance.now() - _time;
  60408. if( _settings.userTimingAPI ) {
  60409. performance.mark( _id + '-end' );
  60410. if( _started ) {
  60411. performance.measure( _id, _id + '-start', _id + '-end' );
  60412. }
  60413. }
  60414. _average( _value );
  60415. }
  60416. function _tick () {
  60417. _end();
  60418. _start();
  60419. }
  60420. function _draw () {
  60421. var v = ( _def && _def.average ) ? _averageValue : _value;
  60422. _spanValueText.nodeValue = Math.round( v * 100 ) / 100;
  60423. var a = ( _def && ( ( _def.below && _value < _def.below ) || ( _def.over && _value > _def.over ) ) );
  60424. _graph.draw( _value, a );
  60425. _dom.className = a ? 'rs-counter-base alarm' : 'rs-counter-base';
  60426. }
  60427. function _frame () {
  60428. var t = performance.now();
  60429. var e = t - _time;
  60430. _total++;
  60431. if ( e > 1000 ) {
  60432. if ( _def && _def.interpolate === false ) {
  60433. _value = _total;
  60434. } else {
  60435. _value = _total * 1000 / e;
  60436. }
  60437. _total = 0;
  60438. _time = t;
  60439. _average( _value );
  60440. }
  60441. }
  60442. function _set ( v ) {
  60443. _value = v;
  60444. _average( _value );
  60445. }
  60446. return {
  60447. set: _set,
  60448. start: _start,
  60449. tick: _tick,
  60450. end: _end,
  60451. frame: _frame,
  60452. value: function () {
  60453. return _value;
  60454. },
  60455. draw: _draw
  60456. };
  60457. }
  60458. function sample () {
  60459. var _value = 0;
  60460. function _set ( v ) {
  60461. _value = v;
  60462. }
  60463. return {
  60464. set: _set,
  60465. value: function () {
  60466. return _value;
  60467. }
  60468. };
  60469. }
  60470. function _perf ( idArg ) {
  60471. var id = idArg.toLowerCase();
  60472. if ( id === undefined ) id = 'default';
  60473. if ( _perfCounters[ id ] ) return _perfCounters[ id ];
  60474. var group = null;
  60475. if ( _settings && _settings.groups ) {
  60476. iterateKeys( _settings.groups, function ( j ) {
  60477. var g = _settings.groups[ parseInt( j, 10 ) ];
  60478. if ( !group && g.values.indexOf( id.toLowerCase() ) !== -1 ) {
  60479. group = g;
  60480. }
  60481. } );
  60482. }
  60483. var p = new PerfCounter( id, group );
  60484. _perfCounters[ id ] = p;
  60485. return p;
  60486. }
  60487. function _init () {
  60488. if ( _settings.plugins ) {
  60489. if ( !_settings.values ) _settings.values = {};
  60490. if ( !_settings.groups ) _settings.groups = [];
  60491. if ( !_settings.fractions ) _settings.fractions = [];
  60492. for ( var j = 0; j < _settings.plugins.length; j++ ) {
  60493. _settings.plugins[ j ].attach( _perf );
  60494. iterateKeys( _settings.plugins[ j ].values, function ( k ) {
  60495. _settings.values[ k ] = _settings.plugins[ j ].values[ k ];
  60496. } );
  60497. _settings.groups = _settings.groups.concat( _settings.plugins[ j ].groups );
  60498. _settings.fractions = _settings.fractions.concat( _settings.plugins[ j ].fractions );
  60499. }
  60500. } else {
  60501. _settings.plugins = {};
  60502. }
  60503. _base = document.createElement( 'div' );
  60504. _base.className = 'rs-base';
  60505. _div = document.createElement( 'div' );
  60506. _div.className = 'rs-container';
  60507. _div.style.height = 'auto';
  60508. _base.appendChild( _div );
  60509. document.body.appendChild( _base );
  60510. if ( !_settings ) return;
  60511. if ( _settings.groups ) {
  60512. iterateKeys( _settings.groups, function ( j ) {
  60513. var g = _settings.groups[ parseInt( j, 10 ) ];
  60514. var div = document.createElement( 'div' );
  60515. div.className = 'rs-group';
  60516. g.div = div;
  60517. var h1 = document.createElement( 'h1' );
  60518. h1.textContent = g.caption;
  60519. h1.addEventListener( 'click', function ( e ) {
  60520. this.classList.toggle( 'hidden' );
  60521. e.preventDefault();
  60522. }.bind( div ) );
  60523. _div.appendChild( h1 );
  60524. _div.appendChild( div );
  60525. } );
  60526. }
  60527. if ( _settings.fractions ) {
  60528. iterateKeys( _settings.fractions, function ( j ) {
  60529. var f = _settings.fractions[ parseInt( j, 10 ) ];
  60530. var div = document.createElement( 'div' );
  60531. div.className = 'rs-fraction';
  60532. var legend = document.createElement( 'div' );
  60533. legend.className = 'rs-legend';
  60534. var h = 0;
  60535. iterateKeys( _settings.fractions[ j ].steps, function ( k ) {
  60536. var p = document.createElement( 'p' );
  60537. p.textContent = _settings.fractions[ j ].steps[ k ];
  60538. p.style.color = _colours[ h ];
  60539. legend.appendChild( p );
  60540. h++;
  60541. } );
  60542. div.appendChild( legend );
  60543. div.style.height = h * _elHeight + 'px';
  60544. f.div = div;
  60545. var graph = new StackGraph( div, h );
  60546. f.graph = graph;
  60547. _div.appendChild( div );
  60548. } );
  60549. }
  60550. }
  60551. function _update () {
  60552. iterateKeys( _settings.plugins, function ( j ) {
  60553. _settings.plugins[ j ].update();
  60554. } );
  60555. iterateKeys( _perfCounters, function ( j ) {
  60556. _perfCounters[ j ].draw();
  60557. } );
  60558. if ( _settings && _settings.fractions ) {
  60559. iterateKeys( _settings.fractions, function ( j ) {
  60560. var f = _settings.fractions[ parseInt( j, 10 ) ];
  60561. var v = [];
  60562. var base = _perfCounters[ f.base.toLowerCase() ];
  60563. if ( base ) {
  60564. base = base.value();
  60565. iterateKeys( _settings.fractions[ j ].steps, function ( k ) {
  60566. var s = _settings.fractions[ j ].steps[ parseInt( k, 10 ) ].toLowerCase();
  60567. var val = _perfCounters[ s ];
  60568. if ( val ) {
  60569. v.push( val.value() / base );
  60570. }
  60571. } );
  60572. }
  60573. f.graph.draw( v );
  60574. } );
  60575. }
  60576. /*if( _height != _div.clientHeight ) {
  60577. _height = _div.clientHeight;
  60578. _base.style.height = _height + 2 * _elHeight + 'px';
  60579. console.log( _base.clientHeight );
  60580. }*/
  60581. }
  60582. _init();
  60583. return function ( id ) {
  60584. if ( id ) return _perf( id );
  60585. return {
  60586. element: _base,
  60587. update: _update
  60588. };
  60589. };
  60590. }
  60591. if (typeof module === 'object') {
  60592. module.exports = window.rStats;
  60593. }
  60594. },{}],214:[function(_dereq_,module,exports){
  60595. // https://stackoverflow.com/a/36213464
  60596. if (!String.prototype.startsWith) {
  60597. String.prototype.startsWith = function(searchString, position){
  60598. position = position || 0;
  60599. return this.substr(position, searchString.length) === searchString;
  60600. };
  60601. }
  60602. },{}],215:[function(_dereq_,module,exports){
  60603. /*
  60604. * Copyright 2015 Google Inc. All Rights Reserved.
  60605. * Licensed under the Apache License, Version 2.0 (the "License");
  60606. * you may not use this file except in compliance with the License.
  60607. * You may obtain a copy of the License at
  60608. *
  60609. * http://www.apache.org/licenses/LICENSE-2.0
  60610. *
  60611. * Unless required by applicable law or agreed to in writing, software
  60612. * distributed under the License is distributed on an "AS IS" BASIS,
  60613. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  60614. * See the License for the specific language governing permissions and
  60615. * limitations under the License.
  60616. */
  60617. var Util = {};
  60618. Util.base64 = function(mimeType, base64) {
  60619. return 'data:' + mimeType + ';base64,' + base64;
  60620. };
  60621. Util.isMobile = function() {
  60622. var check = false;
  60623. (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);
  60624. return check;
  60625. };
  60626. Util.isIOS = function() {
  60627. return /(iPad|iPhone|iPod)/g.test(navigator.userAgent);
  60628. };
  60629. Util.isIFrame = function() {
  60630. try {
  60631. return window.self !== window.top;
  60632. } catch (e) {
  60633. return true;
  60634. }
  60635. };
  60636. Util.appendQueryParameter = function(url, key, value) {
  60637. // Determine delimiter based on if the URL already GET parameters in it.
  60638. var delimiter = (url.indexOf('?') < 0 ? '?' : '&');
  60639. url += delimiter + key + '=' + value;
  60640. return url;
  60641. };
  60642. // From http://goo.gl/4WX3tg
  60643. Util.getQueryParameter = function(name) {
  60644. name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
  60645. var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
  60646. results = regex.exec(location.search);
  60647. return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
  60648. };
  60649. Util.isLandscapeMode = function() {
  60650. return (window.orientation == 90 || window.orientation == -90);
  60651. };
  60652. module.exports = Util;
  60653. },{}],216:[function(_dereq_,module,exports){
  60654. /*
  60655. * Copyright 2015 Google Inc. All Rights Reserved.
  60656. * Licensed under the Apache License, Version 2.0 (the "License");
  60657. * you may not use this file except in compliance with the License.
  60658. * You may obtain a copy of the License at
  60659. *
  60660. * http://www.apache.org/licenses/LICENSE-2.0
  60661. *
  60662. * Unless required by applicable law or agreed to in writing, software
  60663. * distributed under the License is distributed on an "AS IS" BASIS,
  60664. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  60665. * See the License for the specific language governing permissions and
  60666. * limitations under the License.
  60667. */
  60668. var Util = _dereq_('./util.js');
  60669. /**
  60670. * Android and iOS compatible wakelock implementation.
  60671. *
  60672. * Refactored thanks to dkovalev@.
  60673. */
  60674. function AndroidWakeLock() {
  60675. var video = document.createElement('video');
  60676. video.addEventListener('ended', function() {
  60677. video.play();
  60678. });
  60679. this.request = function() {
  60680. if (video.paused) {
  60681. // Base64 version of videos_src/no-sleep-60s.webm.
  60682. video.src = Util.base64('video/webm', 'GkXfowEAAAAAAAAfQoaBAUL3gQFC8oEEQvOBCEKChHdlYm1Ch4ECQoWBAhhTgGcBAAAAAAAH4xFNm3RALE27i1OrhBVJqWZTrIHfTbuMU6uEFlSua1OsggEwTbuMU6uEHFO7a1OsggfG7AEAAAAAAACkAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAVSalmAQAAAAAAAEUq17GDD0JATYCNTGF2ZjU2LjQwLjEwMVdBjUxhdmY1Ni40MC4xMDFzpJAGSJTMbsLpDt/ySkipgX1fRImIQO1MAAAAAAAWVK5rAQAAAAAAADuuAQAAAAAAADLXgQFzxYEBnIEAIrWcg3VuZIaFVl9WUDmDgQEj44OEO5rKAOABAAAAAAAABrCBsLqBkB9DtnUBAAAAAAAAo+eBAKOmgQAAgKJJg0IAAV4BHsAHBIODCoAACmH2MAAAZxgz4dPSTFi5JACjloED6ACmAECSnABMQAADYAAAWi0quoCjloEH0ACmAECSnABNwAADYAAAWi0quoCjloELuACmAECSnABNgAADYAAAWi0quoCjloEPoACmAECSnABNYAADYAAAWi0quoCjloETiACmAECSnABNIAADYAAAWi0quoAfQ7Z1AQAAAAAAAJTnghdwo5aBAAAApgBAkpwATOAAA2AAAFotKrqAo5aBA+gApgBAkpwATMAAA2AAAFotKrqAo5aBB9AApgBAkpwATIAAA2AAAFotKrqAo5aBC7gApgBAkpwATEAAA2AAAFotKrqAo5aBD6AApgDAkpwAQ2AAA2AAAFotKrqAo5aBE4gApgBAkpwATCAAA2AAAFotKrqAH0O2dQEAAAAAAACU54Iu4KOWgQAAAKYAQJKcAEvAAANgAABaLSq6gKOWgQPoAKYAQJKcAEtgAANgAABaLSq6gKOWgQfQAKYAQJKcAEsAAANgAABaLSq6gKOWgQu4AKYAQJKcAEqAAANgAABaLSq6gKOWgQ+gAKYAQJKcAEogAANgAABaLSq6gKOWgROIAKYAQJKcAEnAAANgAABaLSq6gB9DtnUBAAAAAAAAlOeCRlCjloEAAACmAECSnABJgAADYAAAWi0quoCjloED6ACmAECSnABJIAADYAAAWi0quoCjloEH0ACmAMCSnABDYAADYAAAWi0quoCjloELuACmAECSnABI4AADYAAAWi0quoCjloEPoACmAECSnABIoAADYAAAWi0quoCjloETiACmAECSnABIYAADYAAAWi0quoAfQ7Z1AQAAAAAAAJTngl3Ao5aBAAAApgBAkpwASCAAA2AAAFotKrqAo5aBA+gApgBAkpwASAAAA2AAAFotKrqAo5aBB9AApgBAkpwAR8AAA2AAAFotKrqAo5aBC7gApgBAkpwAR4AAA2AAAFotKrqAo5aBD6AApgBAkpwAR2AAA2AAAFotKrqAo5aBE4gApgBAkpwARyAAA2AAAFotKrqAH0O2dQEAAAAAAACU54J1MKOWgQAAAKYAwJKcAENgAANgAABaLSq6gKOWgQPoAKYAQJKcAEbgAANgAABaLSq6gKOWgQfQAKYAQJKcAEagAANgAABaLSq6gKOWgQu4AKYAQJKcAEaAAANgAABaLSq6gKOWgQ+gAKYAQJKcAEZAAANgAABaLSq6gKOWgROIAKYAQJKcAEYAAANgAABaLSq6gB9DtnUBAAAAAAAAlOeCjKCjloEAAACmAECSnABF4AADYAAAWi0quoCjloED6ACmAECSnABFwAADYAAAWi0quoCjloEH0ACmAECSnABFoAADYAAAWi0quoCjloELuACmAECSnABFgAADYAAAWi0quoCjloEPoACmAMCSnABDYAADYAAAWi0quoCjloETiACmAECSnABFYAADYAAAWi0quoAfQ7Z1AQAAAAAAAJTngqQQo5aBAAAApgBAkpwARUAAA2AAAFotKrqAo5aBA+gApgBAkpwARSAAA2AAAFotKrqAo5aBB9AApgBAkpwARQAAA2AAAFotKrqAo5aBC7gApgBAkpwARQAAA2AAAFotKrqAo5aBD6AApgBAkpwAROAAA2AAAFotKrqAo5aBE4gApgBAkpwARMAAA2AAAFotKrqAH0O2dQEAAAAAAACU54K7gKOWgQAAAKYAQJKcAESgAANgAABaLSq6gKOWgQPoAKYAQJKcAESAAANgAABaLSq6gKOWgQfQAKYAwJKcAENgAANgAABaLSq6gKOWgQu4AKYAQJKcAERgAANgAABaLSq6gKOWgQ+gAKYAQJKcAERAAANgAABaLSq6gKOWgROIAKYAQJKcAEQgAANgAABaLSq6gB9DtnUBAAAAAAAAlOeC0vCjloEAAACmAECSnABEIAADYAAAWi0quoCjloED6ACmAECSnABEAAADYAAAWi0quoCjloEH0ACmAECSnABD4AADYAAAWi0quoCjloELuACmAECSnABDwAADYAAAWi0quoCjloEPoACmAECSnABDoAADYAAAWi0quoCjloETiACmAECSnABDgAADYAAAWi0quoAcU7trAQAAAAAAABG7j7OBALeK94EB8YIBd/CBAw==');
  60683. video.play();
  60684. }
  60685. };
  60686. this.release = function() {
  60687. video.pause();
  60688. video.src = '';
  60689. };
  60690. }
  60691. function iOSWakeLock() {
  60692. var timer = null;
  60693. this.request = function() {
  60694. if (!timer) {
  60695. timer = setInterval(function() {
  60696. window.location.href = '/';
  60697. setTimeout(window.stop, 0);
  60698. }, 15000);
  60699. }
  60700. }
  60701. this.release = function() {
  60702. if (timer) {
  60703. clearInterval(timer);
  60704. timer = null;
  60705. }
  60706. }
  60707. }
  60708. function getWakeLock() {
  60709. var userAgent = navigator.userAgent || navigator.vendor || window.opera;
  60710. if (userAgent.match(/iPhone/i) || userAgent.match(/iPod/i)) {
  60711. return iOSWakeLock;
  60712. } else {
  60713. return AndroidWakeLock;
  60714. }
  60715. }
  60716. module.exports = getWakeLock();
  60717. },{"./util.js":215}]},{},[174])(174)
  60718. });
  60719. //# sourceMappingURL=aframe-master.js.map