Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

bundle.js 2.2MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613
  1. (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(require,module,exports){
  2. },{}],2:[function(require,module,exports){
  3. require('aframe');
  4. require('./components/index.js');
  5. require('./systems/index.js');
  6. document.addEventListener("DOMContentLoaded",(event) => {
  7. let body = document.querySelector('body');
  8. let scene = document.createElement('a-scene');
  9. scene.setAttribute('stats','');
  10. let sky = document.createElement('a-sky');
  11. sky.setAttribute('segments-height','5');
  12. sky.setAttribute('segments-width','100');
  13. sky.setAttribute('radius','1000')
  14. scene.appendChild(sky);
  15. body.appendChild(scene);
  16. });
  17. },{"./components/index.js":1,"./systems/index.js":3,"aframe":4}],3:[function(require,module,exports){
  18. arguments[4][1][0].apply(exports,arguments)
  19. },{"dup":1}],4:[function(require,module,exports){
  20. (function (global,Buffer,setImmediate){
  21. (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 e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s}return e})()({1:[function(_dereq_,module,exports){
  22. var str = Object.prototype.toString
  23. module.exports = anArray
  24. function anArray(arr) {
  25. return (
  26. arr.BYTES_PER_ELEMENT
  27. && str.call(arr.buffer) === '[object ArrayBuffer]'
  28. || Array.isArray(arr)
  29. )
  30. }
  31. },{}],2:[function(_dereq_,module,exports){
  32. module.exports = function numtype(num, def) {
  33. return typeof num === 'number'
  34. ? num
  35. : (typeof def === 'number' ? def : 0)
  36. }
  37. },{}],3:[function(_dereq_,module,exports){
  38. 'use strict'
  39. exports.byteLength = byteLength
  40. exports.toByteArray = toByteArray
  41. exports.fromByteArray = fromByteArray
  42. var lookup = []
  43. var revLookup = []
  44. var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array
  45. var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
  46. for (var i = 0, len = code.length; i < len; ++i) {
  47. lookup[i] = code[i]
  48. revLookup[code.charCodeAt(i)] = i
  49. }
  50. // Support decoding URL-safe base64 strings, as Node.js does.
  51. // See: https://en.wikipedia.org/wiki/Base64#URL_applications
  52. revLookup['-'.charCodeAt(0)] = 62
  53. revLookup['_'.charCodeAt(0)] = 63
  54. function placeHoldersCount (b64) {
  55. var len = b64.length
  56. if (len % 4 > 0) {
  57. throw new Error('Invalid string. Length must be a multiple of 4')
  58. }
  59. // the number of equal signs (place holders)
  60. // if there are two placeholders, than the two characters before it
  61. // represent one byte
  62. // if there is only one, then the three characters before it represent 2 bytes
  63. // this is just a cheap hack to not do indexOf twice
  64. return b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0
  65. }
  66. function byteLength (b64) {
  67. // base64 is 4/3 + up to two characters of the original data
  68. return (b64.length * 3 / 4) - placeHoldersCount(b64)
  69. }
  70. function toByteArray (b64) {
  71. var i, l, tmp, placeHolders, arr
  72. var len = b64.length
  73. placeHolders = placeHoldersCount(b64)
  74. arr = new Arr((len * 3 / 4) - placeHolders)
  75. // if there are placeholders, only get up to the last complete 4 chars
  76. l = placeHolders > 0 ? len - 4 : len
  77. var L = 0
  78. for (i = 0; i < l; i += 4) {
  79. tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)]
  80. arr[L++] = (tmp >> 16) & 0xFF
  81. arr[L++] = (tmp >> 8) & 0xFF
  82. arr[L++] = tmp & 0xFF
  83. }
  84. if (placeHolders === 2) {
  85. tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4)
  86. arr[L++] = tmp & 0xFF
  87. } else if (placeHolders === 1) {
  88. tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2)
  89. arr[L++] = (tmp >> 8) & 0xFF
  90. arr[L++] = tmp & 0xFF
  91. }
  92. return arr
  93. }
  94. function tripletToBase64 (num) {
  95. return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F]
  96. }
  97. function encodeChunk (uint8, start, end) {
  98. var tmp
  99. var output = []
  100. for (var i = start; i < end; i += 3) {
  101. tmp = ((uint8[i] << 16) & 0xFF0000) + ((uint8[i + 1] << 8) & 0xFF00) + (uint8[i + 2] & 0xFF)
  102. output.push(tripletToBase64(tmp))
  103. }
  104. return output.join('')
  105. }
  106. function fromByteArray (uint8) {
  107. var tmp
  108. var len = uint8.length
  109. var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes
  110. var output = ''
  111. var parts = []
  112. var maxChunkLength = 16383 // must be multiple of 3
  113. // go through the array every three bytes, we'll deal with trailing stuff later
  114. for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
  115. parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)))
  116. }
  117. // pad the end with zeros, but make sure to not forget the extra bytes
  118. if (extraBytes === 1) {
  119. tmp = uint8[len - 1]
  120. output += lookup[tmp >> 2]
  121. output += lookup[(tmp << 4) & 0x3F]
  122. output += '=='
  123. } else if (extraBytes === 2) {
  124. tmp = (uint8[len - 2] << 8) + (uint8[len - 1])
  125. output += lookup[tmp >> 10]
  126. output += lookup[(tmp >> 4) & 0x3F]
  127. output += lookup[(tmp << 2) & 0x3F]
  128. output += '='
  129. }
  130. parts.push(output)
  131. return parts.join('')
  132. }
  133. },{}],4:[function(_dereq_,module,exports){
  134. 'use strict';
  135. // For more information about browser field, check out the browser field at https://github.com/substack/browserify-handbook#browser-field.
  136. module.exports = {
  137. // Create a <link> tag with optional data attributes
  138. createLink: function(href, attributes) {
  139. var head = document.head || document.getElementsByTagName('head')[0];
  140. var link = document.createElement('link');
  141. link.href = href;
  142. link.rel = 'stylesheet';
  143. for (var key in attributes) {
  144. if ( ! attributes.hasOwnProperty(key)) {
  145. continue;
  146. }
  147. var value = attributes[key];
  148. link.setAttribute('data-' + key, value);
  149. }
  150. head.appendChild(link);
  151. },
  152. // Create a <style> tag with optional data attributes
  153. createStyle: function(cssText, attributes) {
  154. var head = document.head || document.getElementsByTagName('head')[0],
  155. style = document.createElement('style');
  156. style.type = 'text/css';
  157. for (var key in attributes) {
  158. if ( ! attributes.hasOwnProperty(key)) {
  159. continue;
  160. }
  161. var value = attributes[key];
  162. style.setAttribute('data-' + key, value);
  163. }
  164. if (style.sheet) { // for jsdom and IE9+
  165. style.innerHTML = cssText;
  166. style.sheet.cssText = cssText;
  167. head.appendChild(style);
  168. } else if (style.styleSheet) { // for IE8 and below
  169. head.appendChild(style);
  170. style.styleSheet.cssText = cssText;
  171. } else { // for Chrome, Firefox, and Safari
  172. style.appendChild(document.createTextNode(cssText));
  173. head.appendChild(style);
  174. }
  175. }
  176. };
  177. },{}],5:[function(_dereq_,module,exports){
  178. var Buffer = _dereq_('buffer').Buffer; // for use with browserify
  179. module.exports = function (a, b) {
  180. if (!Buffer.isBuffer(a)) return undefined;
  181. if (!Buffer.isBuffer(b)) return undefined;
  182. if (typeof a.equals === 'function') return a.equals(b);
  183. if (a.length !== b.length) return false;
  184. for (var i = 0; i < a.length; i++) {
  185. if (a[i] !== b[i]) return false;
  186. }
  187. return true;
  188. };
  189. },{"buffer":6}],6:[function(_dereq_,module,exports){
  190. (function (global){
  191. /*!
  192. * The buffer module from node.js, for the browser.
  193. *
  194. * @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
  195. * @license MIT
  196. */
  197. /* eslint-disable no-proto */
  198. 'use strict'
  199. var base64 = _dereq_('base64-js')
  200. var ieee754 = _dereq_('ieee754')
  201. var isArray = _dereq_('isarray')
  202. exports.Buffer = Buffer
  203. exports.SlowBuffer = SlowBuffer
  204. exports.INSPECT_MAX_BYTES = 50
  205. /**
  206. * If `Buffer.TYPED_ARRAY_SUPPORT`:
  207. * === true Use Uint8Array implementation (fastest)
  208. * === false Use Object implementation (most compatible, even IE6)
  209. *
  210. * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
  211. * Opera 11.6+, iOS 4.2+.
  212. *
  213. * Due to various browser bugs, sometimes the Object implementation will be used even
  214. * when the browser supports typed arrays.
  215. *
  216. * Note:
  217. *
  218. * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances,
  219. * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438.
  220. *
  221. * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function.
  222. *
  223. * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of
  224. * incorrect length in some situations.
  225. * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they
  226. * get the Object implementation, which is slower but behaves correctly.
  227. */
  228. Buffer.TYPED_ARRAY_SUPPORT = global.TYPED_ARRAY_SUPPORT !== undefined
  229. ? global.TYPED_ARRAY_SUPPORT
  230. : typedArraySupport()
  231. /*
  232. * Export kMaxLength after typed array support is determined.
  233. */
  234. exports.kMaxLength = kMaxLength()
  235. function typedArraySupport () {
  236. try {
  237. var arr = new Uint8Array(1)
  238. arr.__proto__ = {__proto__: Uint8Array.prototype, foo: function () { return 42 }}
  239. return arr.foo() === 42 && // typed array instances can be augmented
  240. typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray`
  241. arr.subarray(1, 1).byteLength === 0 // ie10 has broken `subarray`
  242. } catch (e) {
  243. return false
  244. }
  245. }
  246. function kMaxLength () {
  247. return Buffer.TYPED_ARRAY_SUPPORT
  248. ? 0x7fffffff
  249. : 0x3fffffff
  250. }
  251. function createBuffer (that, length) {
  252. if (kMaxLength() < length) {
  253. throw new RangeError('Invalid typed array length')
  254. }
  255. if (Buffer.TYPED_ARRAY_SUPPORT) {
  256. // Return an augmented `Uint8Array` instance, for best performance
  257. that = new Uint8Array(length)
  258. that.__proto__ = Buffer.prototype
  259. } else {
  260. // Fallback: Return an object instance of the Buffer class
  261. if (that === null) {
  262. that = new Buffer(length)
  263. }
  264. that.length = length
  265. }
  266. return that
  267. }
  268. /**
  269. * The Buffer constructor returns instances of `Uint8Array` that have their
  270. * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
  271. * `Uint8Array`, so the returned instances will have all the node `Buffer` methods
  272. * and the `Uint8Array` methods. Square bracket notation works as expected -- it
  273. * returns a single octet.
  274. *
  275. * The `Uint8Array` prototype remains unmodified.
  276. */
  277. function Buffer (arg, encodingOrOffset, length) {
  278. if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) {
  279. return new Buffer(arg, encodingOrOffset, length)
  280. }
  281. // Common case.
  282. if (typeof arg === 'number') {
  283. if (typeof encodingOrOffset === 'string') {
  284. throw new Error(
  285. 'If encoding is specified then the first argument must be a string'
  286. )
  287. }
  288. return allocUnsafe(this, arg)
  289. }
  290. return from(this, arg, encodingOrOffset, length)
  291. }
  292. Buffer.poolSize = 8192 // not used by this implementation
  293. // TODO: Legacy, not needed anymore. Remove in next major version.
  294. Buffer._augment = function (arr) {
  295. arr.__proto__ = Buffer.prototype
  296. return arr
  297. }
  298. function from (that, value, encodingOrOffset, length) {
  299. if (typeof value === 'number') {
  300. throw new TypeError('"value" argument must not be a number')
  301. }
  302. if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) {
  303. return fromArrayBuffer(that, value, encodingOrOffset, length)
  304. }
  305. if (typeof value === 'string') {
  306. return fromString(that, value, encodingOrOffset)
  307. }
  308. return fromObject(that, value)
  309. }
  310. /**
  311. * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
  312. * if value is a number.
  313. * Buffer.from(str[, encoding])
  314. * Buffer.from(array)
  315. * Buffer.from(buffer)
  316. * Buffer.from(arrayBuffer[, byteOffset[, length]])
  317. **/
  318. Buffer.from = function (value, encodingOrOffset, length) {
  319. return from(null, value, encodingOrOffset, length)
  320. }
  321. if (Buffer.TYPED_ARRAY_SUPPORT) {
  322. Buffer.prototype.__proto__ = Uint8Array.prototype
  323. Buffer.__proto__ = Uint8Array
  324. if (typeof Symbol !== 'undefined' && Symbol.species &&
  325. Buffer[Symbol.species] === Buffer) {
  326. // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97
  327. Object.defineProperty(Buffer, Symbol.species, {
  328. value: null,
  329. configurable: true
  330. })
  331. }
  332. }
  333. function assertSize (size) {
  334. if (typeof size !== 'number') {
  335. throw new TypeError('"size" argument must be a number')
  336. } else if (size < 0) {
  337. throw new RangeError('"size" argument must not be negative')
  338. }
  339. }
  340. function alloc (that, size, fill, encoding) {
  341. assertSize(size)
  342. if (size <= 0) {
  343. return createBuffer(that, size)
  344. }
  345. if (fill !== undefined) {
  346. // Only pay attention to encoding if it's a string. This
  347. // prevents accidentally sending in a number that would
  348. // be interpretted as a start offset.
  349. return typeof encoding === 'string'
  350. ? createBuffer(that, size).fill(fill, encoding)
  351. : createBuffer(that, size).fill(fill)
  352. }
  353. return createBuffer(that, size)
  354. }
  355. /**
  356. * Creates a new filled Buffer instance.
  357. * alloc(size[, fill[, encoding]])
  358. **/
  359. Buffer.alloc = function (size, fill, encoding) {
  360. return alloc(null, size, fill, encoding)
  361. }
  362. function allocUnsafe (that, size) {
  363. assertSize(size)
  364. that = createBuffer(that, size < 0 ? 0 : checked(size) | 0)
  365. if (!Buffer.TYPED_ARRAY_SUPPORT) {
  366. for (var i = 0; i < size; ++i) {
  367. that[i] = 0
  368. }
  369. }
  370. return that
  371. }
  372. /**
  373. * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
  374. * */
  375. Buffer.allocUnsafe = function (size) {
  376. return allocUnsafe(null, size)
  377. }
  378. /**
  379. * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
  380. */
  381. Buffer.allocUnsafeSlow = function (size) {
  382. return allocUnsafe(null, size)
  383. }
  384. function fromString (that, string, encoding) {
  385. if (typeof encoding !== 'string' || encoding === '') {
  386. encoding = 'utf8'
  387. }
  388. if (!Buffer.isEncoding(encoding)) {
  389. throw new TypeError('"encoding" must be a valid string encoding')
  390. }
  391. var length = byteLength(string, encoding) | 0
  392. that = createBuffer(that, length)
  393. var actual = that.write(string, encoding)
  394. if (actual !== length) {
  395. // Writing a hex string, for example, that contains invalid characters will
  396. // cause everything after the first invalid character to be ignored. (e.g.
  397. // 'abxxcd' will be treated as 'ab')
  398. that = that.slice(0, actual)
  399. }
  400. return that
  401. }
  402. function fromArrayLike (that, array) {
  403. var length = array.length < 0 ? 0 : checked(array.length) | 0
  404. that = createBuffer(that, length)
  405. for (var i = 0; i < length; i += 1) {
  406. that[i] = array[i] & 255
  407. }
  408. return that
  409. }
  410. function fromArrayBuffer (that, array, byteOffset, length) {
  411. array.byteLength // this throws if `array` is not a valid ArrayBuffer
  412. if (byteOffset < 0 || array.byteLength < byteOffset) {
  413. throw new RangeError('\'offset\' is out of bounds')
  414. }
  415. if (array.byteLength < byteOffset + (length || 0)) {
  416. throw new RangeError('\'length\' is out of bounds')
  417. }
  418. if (byteOffset === undefined && length === undefined) {
  419. array = new Uint8Array(array)
  420. } else if (length === undefined) {
  421. array = new Uint8Array(array, byteOffset)
  422. } else {
  423. array = new Uint8Array(array, byteOffset, length)
  424. }
  425. if (Buffer.TYPED_ARRAY_SUPPORT) {
  426. // Return an augmented `Uint8Array` instance, for best performance
  427. that = array
  428. that.__proto__ = Buffer.prototype
  429. } else {
  430. // Fallback: Return an object instance of the Buffer class
  431. that = fromArrayLike(that, array)
  432. }
  433. return that
  434. }
  435. function fromObject (that, obj) {
  436. if (Buffer.isBuffer(obj)) {
  437. var len = checked(obj.length) | 0
  438. that = createBuffer(that, len)
  439. if (that.length === 0) {
  440. return that
  441. }
  442. obj.copy(that, 0, 0, len)
  443. return that
  444. }
  445. if (obj) {
  446. if ((typeof ArrayBuffer !== 'undefined' &&
  447. obj.buffer instanceof ArrayBuffer) || 'length' in obj) {
  448. if (typeof obj.length !== 'number' || isnan(obj.length)) {
  449. return createBuffer(that, 0)
  450. }
  451. return fromArrayLike(that, obj)
  452. }
  453. if (obj.type === 'Buffer' && isArray(obj.data)) {
  454. return fromArrayLike(that, obj.data)
  455. }
  456. }
  457. throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.')
  458. }
  459. function checked (length) {
  460. // Note: cannot use `length < kMaxLength()` here because that fails when
  461. // length is NaN (which is otherwise coerced to zero.)
  462. if (length >= kMaxLength()) {
  463. throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
  464. 'size: 0x' + kMaxLength().toString(16) + ' bytes')
  465. }
  466. return length | 0
  467. }
  468. function SlowBuffer (length) {
  469. if (+length != length) { // eslint-disable-line eqeqeq
  470. length = 0
  471. }
  472. return Buffer.alloc(+length)
  473. }
  474. Buffer.isBuffer = function isBuffer (b) {
  475. return !!(b != null && b._isBuffer)
  476. }
  477. Buffer.compare = function compare (a, b) {
  478. if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
  479. throw new TypeError('Arguments must be Buffers')
  480. }
  481. if (a === b) return 0
  482. var x = a.length
  483. var y = b.length
  484. for (var i = 0, len = Math.min(x, y); i < len; ++i) {
  485. if (a[i] !== b[i]) {
  486. x = a[i]
  487. y = b[i]
  488. break
  489. }
  490. }
  491. if (x < y) return -1
  492. if (y < x) return 1
  493. return 0
  494. }
  495. Buffer.isEncoding = function isEncoding (encoding) {
  496. switch (String(encoding).toLowerCase()) {
  497. case 'hex':
  498. case 'utf8':
  499. case 'utf-8':
  500. case 'ascii':
  501. case 'latin1':
  502. case 'binary':
  503. case 'base64':
  504. case 'ucs2':
  505. case 'ucs-2':
  506. case 'utf16le':
  507. case 'utf-16le':
  508. return true
  509. default:
  510. return false
  511. }
  512. }
  513. Buffer.concat = function concat (list, length) {
  514. if (!isArray(list)) {
  515. throw new TypeError('"list" argument must be an Array of Buffers')
  516. }
  517. if (list.length === 0) {
  518. return Buffer.alloc(0)
  519. }
  520. var i
  521. if (length === undefined) {
  522. length = 0
  523. for (i = 0; i < list.length; ++i) {
  524. length += list[i].length
  525. }
  526. }
  527. var buffer = Buffer.allocUnsafe(length)
  528. var pos = 0
  529. for (i = 0; i < list.length; ++i) {
  530. var buf = list[i]
  531. if (!Buffer.isBuffer(buf)) {
  532. throw new TypeError('"list" argument must be an Array of Buffers')
  533. }
  534. buf.copy(buffer, pos)
  535. pos += buf.length
  536. }
  537. return buffer
  538. }
  539. function byteLength (string, encoding) {
  540. if (Buffer.isBuffer(string)) {
  541. return string.length
  542. }
  543. if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' &&
  544. (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) {
  545. return string.byteLength
  546. }
  547. if (typeof string !== 'string') {
  548. string = '' + string
  549. }
  550. var len = string.length
  551. if (len === 0) return 0
  552. // Use a for loop to avoid recursion
  553. var loweredCase = false
  554. for (;;) {
  555. switch (encoding) {
  556. case 'ascii':
  557. case 'latin1':
  558. case 'binary':
  559. return len
  560. case 'utf8':
  561. case 'utf-8':
  562. case undefined:
  563. return utf8ToBytes(string).length
  564. case 'ucs2':
  565. case 'ucs-2':
  566. case 'utf16le':
  567. case 'utf-16le':
  568. return len * 2
  569. case 'hex':
  570. return len >>> 1
  571. case 'base64':
  572. return base64ToBytes(string).length
  573. default:
  574. if (loweredCase) return utf8ToBytes(string).length // assume utf8
  575. encoding = ('' + encoding).toLowerCase()
  576. loweredCase = true
  577. }
  578. }
  579. }
  580. Buffer.byteLength = byteLength
  581. function slowToString (encoding, start, end) {
  582. var loweredCase = false
  583. // No need to verify that "this.length <= MAX_UINT32" since it's a read-only
  584. // property of a typed array.
  585. // This behaves neither like String nor Uint8Array in that we set start/end
  586. // to their upper/lower bounds if the value passed is out of range.
  587. // undefined is handled specially as per ECMA-262 6th Edition,
  588. // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
  589. if (start === undefined || start < 0) {
  590. start = 0
  591. }
  592. // Return early if start > this.length. Done here to prevent potential uint32
  593. // coercion fail below.
  594. if (start > this.length) {
  595. return ''
  596. }
  597. if (end === undefined || end > this.length) {
  598. end = this.length
  599. }
  600. if (end <= 0) {
  601. return ''
  602. }
  603. // Force coersion to uint32. This will also coerce falsey/NaN values to 0.
  604. end >>>= 0
  605. start >>>= 0
  606. if (end <= start) {
  607. return ''
  608. }
  609. if (!encoding) encoding = 'utf8'
  610. while (true) {
  611. switch (encoding) {
  612. case 'hex':
  613. return hexSlice(this, start, end)
  614. case 'utf8':
  615. case 'utf-8':
  616. return utf8Slice(this, start, end)
  617. case 'ascii':
  618. return asciiSlice(this, start, end)
  619. case 'latin1':
  620. case 'binary':
  621. return latin1Slice(this, start, end)
  622. case 'base64':
  623. return base64Slice(this, start, end)
  624. case 'ucs2':
  625. case 'ucs-2':
  626. case 'utf16le':
  627. case 'utf-16le':
  628. return utf16leSlice(this, start, end)
  629. default:
  630. if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
  631. encoding = (encoding + '').toLowerCase()
  632. loweredCase = true
  633. }
  634. }
  635. }
  636. // The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect
  637. // Buffer instances.
  638. Buffer.prototype._isBuffer = true
  639. function swap (b, n, m) {
  640. var i = b[n]
  641. b[n] = b[m]
  642. b[m] = i
  643. }
  644. Buffer.prototype.swap16 = function swap16 () {
  645. var len = this.length
  646. if (len % 2 !== 0) {
  647. throw new RangeError('Buffer size must be a multiple of 16-bits')
  648. }
  649. for (var i = 0; i < len; i += 2) {
  650. swap(this, i, i + 1)
  651. }
  652. return this
  653. }
  654. Buffer.prototype.swap32 = function swap32 () {
  655. var len = this.length
  656. if (len % 4 !== 0) {
  657. throw new RangeError('Buffer size must be a multiple of 32-bits')
  658. }
  659. for (var i = 0; i < len; i += 4) {
  660. swap(this, i, i + 3)
  661. swap(this, i + 1, i + 2)
  662. }
  663. return this
  664. }
  665. Buffer.prototype.swap64 = function swap64 () {
  666. var len = this.length
  667. if (len % 8 !== 0) {
  668. throw new RangeError('Buffer size must be a multiple of 64-bits')
  669. }
  670. for (var i = 0; i < len; i += 8) {
  671. swap(this, i, i + 7)
  672. swap(this, i + 1, i + 6)
  673. swap(this, i + 2, i + 5)
  674. swap(this, i + 3, i + 4)
  675. }
  676. return this
  677. }
  678. Buffer.prototype.toString = function toString () {
  679. var length = this.length | 0
  680. if (length === 0) return ''
  681. if (arguments.length === 0) return utf8Slice(this, 0, length)
  682. return slowToString.apply(this, arguments)
  683. }
  684. Buffer.prototype.equals = function equals (b) {
  685. if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
  686. if (this === b) return true
  687. return Buffer.compare(this, b) === 0
  688. }
  689. Buffer.prototype.inspect = function inspect () {
  690. var str = ''
  691. var max = exports.INSPECT_MAX_BYTES
  692. if (this.length > 0) {
  693. str = this.toString('hex', 0, max).match(/.{2}/g).join(' ')
  694. if (this.length > max) str += ' ... '
  695. }
  696. return '<Buffer ' + str + '>'
  697. }
  698. Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
  699. if (!Buffer.isBuffer(target)) {
  700. throw new TypeError('Argument must be a Buffer')
  701. }
  702. if (start === undefined) {
  703. start = 0
  704. }
  705. if (end === undefined) {
  706. end = target ? target.length : 0
  707. }
  708. if (thisStart === undefined) {
  709. thisStart = 0
  710. }
  711. if (thisEnd === undefined) {
  712. thisEnd = this.length
  713. }
  714. if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
  715. throw new RangeError('out of range index')
  716. }
  717. if (thisStart >= thisEnd && start >= end) {
  718. return 0
  719. }
  720. if (thisStart >= thisEnd) {
  721. return -1
  722. }
  723. if (start >= end) {
  724. return 1
  725. }
  726. start >>>= 0
  727. end >>>= 0
  728. thisStart >>>= 0
  729. thisEnd >>>= 0
  730. if (this === target) return 0
  731. var x = thisEnd - thisStart
  732. var y = end - start
  733. var len = Math.min(x, y)
  734. var thisCopy = this.slice(thisStart, thisEnd)
  735. var targetCopy = target.slice(start, end)
  736. for (var i = 0; i < len; ++i) {
  737. if (thisCopy[i] !== targetCopy[i]) {
  738. x = thisCopy[i]
  739. y = targetCopy[i]
  740. break
  741. }
  742. }
  743. if (x < y) return -1
  744. if (y < x) return 1
  745. return 0
  746. }
  747. // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
  748. // OR the last index of `val` in `buffer` at offset <= `byteOffset`.
  749. //
  750. // Arguments:
  751. // - buffer - a Buffer to search
  752. // - val - a string, Buffer, or number
  753. // - byteOffset - an index into `buffer`; will be clamped to an int32
  754. // - encoding - an optional encoding, relevant is val is a string
  755. // - dir - true for indexOf, false for lastIndexOf
  756. function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {
  757. // Empty buffer means no match
  758. if (buffer.length === 0) return -1
  759. // Normalize byteOffset
  760. if (typeof byteOffset === 'string') {
  761. encoding = byteOffset
  762. byteOffset = 0
  763. } else if (byteOffset > 0x7fffffff) {
  764. byteOffset = 0x7fffffff
  765. } else if (byteOffset < -0x80000000) {
  766. byteOffset = -0x80000000
  767. }
  768. byteOffset = +byteOffset // Coerce to Number.
  769. if (isNaN(byteOffset)) {
  770. // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
  771. byteOffset = dir ? 0 : (buffer.length - 1)
  772. }
  773. // Normalize byteOffset: negative offsets start from the end of the buffer
  774. if (byteOffset < 0) byteOffset = buffer.length + byteOffset
  775. if (byteOffset >= buffer.length) {
  776. if (dir) return -1
  777. else byteOffset = buffer.length - 1
  778. } else if (byteOffset < 0) {
  779. if (dir) byteOffset = 0
  780. else return -1
  781. }
  782. // Normalize val
  783. if (typeof val === 'string') {
  784. val = Buffer.from(val, encoding)
  785. }
  786. // Finally, search either indexOf (if dir is true) or lastIndexOf
  787. if (Buffer.isBuffer(val)) {
  788. // Special case: looking for empty string/buffer always fails
  789. if (val.length === 0) {
  790. return -1
  791. }
  792. return arrayIndexOf(buffer, val, byteOffset, encoding, dir)
  793. } else if (typeof val === 'number') {
  794. val = val & 0xFF // Search for a byte value [0-255]
  795. if (Buffer.TYPED_ARRAY_SUPPORT &&
  796. typeof Uint8Array.prototype.indexOf === 'function') {
  797. if (dir) {
  798. return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)
  799. } else {
  800. return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)
  801. }
  802. }
  803. return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)
  804. }
  805. throw new TypeError('val must be string, number or Buffer')
  806. }
  807. function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
  808. var indexSize = 1
  809. var arrLength = arr.length
  810. var valLength = val.length
  811. if (encoding !== undefined) {
  812. encoding = String(encoding).toLowerCase()
  813. if (encoding === 'ucs2' || encoding === 'ucs-2' ||
  814. encoding === 'utf16le' || encoding === 'utf-16le') {
  815. if (arr.length < 2 || val.length < 2) {
  816. return -1
  817. }
  818. indexSize = 2
  819. arrLength /= 2
  820. valLength /= 2
  821. byteOffset /= 2
  822. }
  823. }
  824. function read (buf, i) {
  825. if (indexSize === 1) {
  826. return buf[i]
  827. } else {
  828. return buf.readUInt16BE(i * indexSize)
  829. }
  830. }
  831. var i
  832. if (dir) {
  833. var foundIndex = -1
  834. for (i = byteOffset; i < arrLength; i++) {
  835. if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
  836. if (foundIndex === -1) foundIndex = i
  837. if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
  838. } else {
  839. if (foundIndex !== -1) i -= i - foundIndex
  840. foundIndex = -1
  841. }
  842. }
  843. } else {
  844. if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength
  845. for (i = byteOffset; i >= 0; i--) {
  846. var found = true
  847. for (var j = 0; j < valLength; j++) {
  848. if (read(arr, i + j) !== read(val, j)) {
  849. found = false
  850. break
  851. }
  852. }
  853. if (found) return i
  854. }
  855. }
  856. return -1
  857. }
  858. Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
  859. return this.indexOf(val, byteOffset, encoding) !== -1
  860. }
  861. Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
  862. return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
  863. }
  864. Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
  865. return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
  866. }
  867. function hexWrite (buf, string, offset, length) {
  868. offset = Number(offset) || 0
  869. var remaining = buf.length - offset
  870. if (!length) {
  871. length = remaining
  872. } else {
  873. length = Number(length)
  874. if (length > remaining) {
  875. length = remaining
  876. }
  877. }
  878. // must be an even number of digits
  879. var strLen = string.length
  880. if (strLen % 2 !== 0) throw new TypeError('Invalid hex string')
  881. if (length > strLen / 2) {
  882. length = strLen / 2
  883. }
  884. for (var i = 0; i < length; ++i) {
  885. var parsed = parseInt(string.substr(i * 2, 2), 16)
  886. if (isNaN(parsed)) return i
  887. buf[offset + i] = parsed
  888. }
  889. return i
  890. }
  891. function utf8Write (buf, string, offset, length) {
  892. return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
  893. }
  894. function asciiWrite (buf, string, offset, length) {
  895. return blitBuffer(asciiToBytes(string), buf, offset, length)
  896. }
  897. function latin1Write (buf, string, offset, length) {
  898. return asciiWrite(buf, string, offset, length)
  899. }
  900. function base64Write (buf, string, offset, length) {
  901. return blitBuffer(base64ToBytes(string), buf, offset, length)
  902. }
  903. function ucs2Write (buf, string, offset, length) {
  904. return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
  905. }
  906. Buffer.prototype.write = function write (string, offset, length, encoding) {
  907. // Buffer#write(string)
  908. if (offset === undefined) {
  909. encoding = 'utf8'
  910. length = this.length
  911. offset = 0
  912. // Buffer#write(string, encoding)
  913. } else if (length === undefined && typeof offset === 'string') {
  914. encoding = offset
  915. length = this.length
  916. offset = 0
  917. // Buffer#write(string, offset[, length][, encoding])
  918. } else if (isFinite(offset)) {
  919. offset = offset | 0
  920. if (isFinite(length)) {
  921. length = length | 0
  922. if (encoding === undefined) encoding = 'utf8'
  923. } else {
  924. encoding = length
  925. length = undefined
  926. }
  927. // legacy write(string, encoding, offset, length) - remove in v0.13
  928. } else {
  929. throw new Error(
  930. 'Buffer.write(string, encoding, offset[, length]) is no longer supported'
  931. )
  932. }
  933. var remaining = this.length - offset
  934. if (length === undefined || length > remaining) length = remaining
  935. if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
  936. throw new RangeError('Attempt to write outside buffer bounds')
  937. }
  938. if (!encoding) encoding = 'utf8'
  939. var loweredCase = false
  940. for (;;) {
  941. switch (encoding) {
  942. case 'hex':
  943. return hexWrite(this, string, offset, length)
  944. case 'utf8':
  945. case 'utf-8':
  946. return utf8Write(this, string, offset, length)
  947. case 'ascii':
  948. return asciiWrite(this, string, offset, length)
  949. case 'latin1':
  950. case 'binary':
  951. return latin1Write(this, string, offset, length)
  952. case 'base64':
  953. // Warning: maxLength not taken into account in base64Write
  954. return base64Write(this, string, offset, length)
  955. case 'ucs2':
  956. case 'ucs-2':
  957. case 'utf16le':
  958. case 'utf-16le':
  959. return ucs2Write(this, string, offset, length)
  960. default:
  961. if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
  962. encoding = ('' + encoding).toLowerCase()
  963. loweredCase = true
  964. }
  965. }
  966. }
  967. Buffer.prototype.toJSON = function toJSON () {
  968. return {
  969. type: 'Buffer',
  970. data: Array.prototype.slice.call(this._arr || this, 0)
  971. }
  972. }
  973. function base64Slice (buf, start, end) {
  974. if (start === 0 && end === buf.length) {
  975. return base64.fromByteArray(buf)
  976. } else {
  977. return base64.fromByteArray(buf.slice(start, end))
  978. }
  979. }
  980. function utf8Slice (buf, start, end) {
  981. end = Math.min(buf.length, end)
  982. var res = []
  983. var i = start
  984. while (i < end) {
  985. var firstByte = buf[i]
  986. var codePoint = null
  987. var bytesPerSequence = (firstByte > 0xEF) ? 4
  988. : (firstByte > 0xDF) ? 3
  989. : (firstByte > 0xBF) ? 2
  990. : 1
  991. if (i + bytesPerSequence <= end) {
  992. var secondByte, thirdByte, fourthByte, tempCodePoint
  993. switch (bytesPerSequence) {
  994. case 1:
  995. if (firstByte < 0x80) {
  996. codePoint = firstByte
  997. }
  998. break
  999. case 2:
  1000. secondByte = buf[i + 1]
  1001. if ((secondByte & 0xC0) === 0x80) {
  1002. tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)
  1003. if (tempCodePoint > 0x7F) {
  1004. codePoint = tempCodePoint
  1005. }
  1006. }
  1007. break
  1008. case 3:
  1009. secondByte = buf[i + 1]
  1010. thirdByte = buf[i + 2]
  1011. if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
  1012. tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)
  1013. if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
  1014. codePoint = tempCodePoint
  1015. }
  1016. }
  1017. break
  1018. case 4:
  1019. secondByte = buf[i + 1]
  1020. thirdByte = buf[i + 2]
  1021. fourthByte = buf[i + 3]
  1022. if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
  1023. tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)
  1024. if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
  1025. codePoint = tempCodePoint
  1026. }
  1027. }
  1028. }
  1029. }
  1030. if (codePoint === null) {
  1031. // we did not generate a valid codePoint so insert a
  1032. // replacement char (U+FFFD) and advance only 1 byte
  1033. codePoint = 0xFFFD
  1034. bytesPerSequence = 1
  1035. } else if (codePoint > 0xFFFF) {
  1036. // encode to utf16 (surrogate pair dance)
  1037. codePoint -= 0x10000
  1038. res.push(codePoint >>> 10 & 0x3FF | 0xD800)
  1039. codePoint = 0xDC00 | codePoint & 0x3FF
  1040. }
  1041. res.push(codePoint)
  1042. i += bytesPerSequence
  1043. }
  1044. return decodeCodePointsArray(res)
  1045. }
  1046. // Based on http://stackoverflow.com/a/22747272/680742, the browser with
  1047. // the lowest limit is Chrome, with 0x10000 args.
  1048. // We go 1 magnitude less, for safety
  1049. var MAX_ARGUMENTS_LENGTH = 0x1000
  1050. function decodeCodePointsArray (codePoints) {
  1051. var len = codePoints.length
  1052. if (len <= MAX_ARGUMENTS_LENGTH) {
  1053. return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
  1054. }
  1055. // Decode in chunks to avoid "call stack size exceeded".
  1056. var res = ''
  1057. var i = 0
  1058. while (i < len) {
  1059. res += String.fromCharCode.apply(
  1060. String,
  1061. codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
  1062. )
  1063. }
  1064. return res
  1065. }
  1066. function asciiSlice (buf, start, end) {
  1067. var ret = ''
  1068. end = Math.min(buf.length, end)
  1069. for (var i = start; i < end; ++i) {
  1070. ret += String.fromCharCode(buf[i] & 0x7F)
  1071. }
  1072. return ret
  1073. }
  1074. function latin1Slice (buf, start, end) {
  1075. var ret = ''
  1076. end = Math.min(buf.length, end)
  1077. for (var i = start; i < end; ++i) {
  1078. ret += String.fromCharCode(buf[i])
  1079. }
  1080. return ret
  1081. }
  1082. function hexSlice (buf, start, end) {
  1083. var len = buf.length
  1084. if (!start || start < 0) start = 0
  1085. if (!end || end < 0 || end > len) end = len
  1086. var out = ''
  1087. for (var i = start; i < end; ++i) {
  1088. out += toHex(buf[i])
  1089. }
  1090. return out
  1091. }
  1092. function utf16leSlice (buf, start, end) {
  1093. var bytes = buf.slice(start, end)
  1094. var res = ''
  1095. for (var i = 0; i < bytes.length; i += 2) {
  1096. res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256)
  1097. }
  1098. return res
  1099. }
  1100. Buffer.prototype.slice = function slice (start, end) {
  1101. var len = this.length
  1102. start = ~~start
  1103. end = end === undefined ? len : ~~end
  1104. if (start < 0) {
  1105. start += len
  1106. if (start < 0) start = 0
  1107. } else if (start > len) {
  1108. start = len
  1109. }
  1110. if (end < 0) {
  1111. end += len
  1112. if (end < 0) end = 0
  1113. } else if (end > len) {
  1114. end = len
  1115. }
  1116. if (end < start) end = start
  1117. var newBuf
  1118. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1119. newBuf = this.subarray(start, end)
  1120. newBuf.__proto__ = Buffer.prototype
  1121. } else {
  1122. var sliceLen = end - start
  1123. newBuf = new Buffer(sliceLen, undefined)
  1124. for (var i = 0; i < sliceLen; ++i) {
  1125. newBuf[i] = this[i + start]
  1126. }
  1127. }
  1128. return newBuf
  1129. }
  1130. /*
  1131. * Need to make sure that buffer isn't trying to write out of bounds.
  1132. */
  1133. function checkOffset (offset, ext, length) {
  1134. if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
  1135. if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
  1136. }
  1137. Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
  1138. offset = offset | 0
  1139. byteLength = byteLength | 0
  1140. if (!noAssert) checkOffset(offset, byteLength, this.length)
  1141. var val = this[offset]
  1142. var mul = 1
  1143. var i = 0
  1144. while (++i < byteLength && (mul *= 0x100)) {
  1145. val += this[offset + i] * mul
  1146. }
  1147. return val
  1148. }
  1149. Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
  1150. offset = offset | 0
  1151. byteLength = byteLength | 0
  1152. if (!noAssert) {
  1153. checkOffset(offset, byteLength, this.length)
  1154. }
  1155. var val = this[offset + --byteLength]
  1156. var mul = 1
  1157. while (byteLength > 0 && (mul *= 0x100)) {
  1158. val += this[offset + --byteLength] * mul
  1159. }
  1160. return val
  1161. }
  1162. Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
  1163. if (!noAssert) checkOffset(offset, 1, this.length)
  1164. return this[offset]
  1165. }
  1166. Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
  1167. if (!noAssert) checkOffset(offset, 2, this.length)
  1168. return this[offset] | (this[offset + 1] << 8)
  1169. }
  1170. Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
  1171. if (!noAssert) checkOffset(offset, 2, this.length)
  1172. return (this[offset] << 8) | this[offset + 1]
  1173. }
  1174. Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
  1175. if (!noAssert) checkOffset(offset, 4, this.length)
  1176. return ((this[offset]) |
  1177. (this[offset + 1] << 8) |
  1178. (this[offset + 2] << 16)) +
  1179. (this[offset + 3] * 0x1000000)
  1180. }
  1181. Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
  1182. if (!noAssert) checkOffset(offset, 4, this.length)
  1183. return (this[offset] * 0x1000000) +
  1184. ((this[offset + 1] << 16) |
  1185. (this[offset + 2] << 8) |
  1186. this[offset + 3])
  1187. }
  1188. Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
  1189. offset = offset | 0
  1190. byteLength = byteLength | 0
  1191. if (!noAssert) checkOffset(offset, byteLength, this.length)
  1192. var val = this[offset]
  1193. var mul = 1
  1194. var i = 0
  1195. while (++i < byteLength && (mul *= 0x100)) {
  1196. val += this[offset + i] * mul
  1197. }
  1198. mul *= 0x80
  1199. if (val >= mul) val -= Math.pow(2, 8 * byteLength)
  1200. return val
  1201. }
  1202. Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
  1203. offset = offset | 0
  1204. byteLength = byteLength | 0
  1205. if (!noAssert) checkOffset(offset, byteLength, this.length)
  1206. var i = byteLength
  1207. var mul = 1
  1208. var val = this[offset + --i]
  1209. while (i > 0 && (mul *= 0x100)) {
  1210. val += this[offset + --i] * mul
  1211. }
  1212. mul *= 0x80
  1213. if (val >= mul) val -= Math.pow(2, 8 * byteLength)
  1214. return val
  1215. }
  1216. Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
  1217. if (!noAssert) checkOffset(offset, 1, this.length)
  1218. if (!(this[offset] & 0x80)) return (this[offset])
  1219. return ((0xff - this[offset] + 1) * -1)
  1220. }
  1221. Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
  1222. if (!noAssert) checkOffset(offset, 2, this.length)
  1223. var val = this[offset] | (this[offset + 1] << 8)
  1224. return (val & 0x8000) ? val | 0xFFFF0000 : val
  1225. }
  1226. Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
  1227. if (!noAssert) checkOffset(offset, 2, this.length)
  1228. var val = this[offset + 1] | (this[offset] << 8)
  1229. return (val & 0x8000) ? val | 0xFFFF0000 : val
  1230. }
  1231. Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
  1232. if (!noAssert) checkOffset(offset, 4, this.length)
  1233. return (this[offset]) |
  1234. (this[offset + 1] << 8) |
  1235. (this[offset + 2] << 16) |
  1236. (this[offset + 3] << 24)
  1237. }
  1238. Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
  1239. if (!noAssert) checkOffset(offset, 4, this.length)
  1240. return (this[offset] << 24) |
  1241. (this[offset + 1] << 16) |
  1242. (this[offset + 2] << 8) |
  1243. (this[offset + 3])
  1244. }
  1245. Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
  1246. if (!noAssert) checkOffset(offset, 4, this.length)
  1247. return ieee754.read(this, offset, true, 23, 4)
  1248. }
  1249. Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
  1250. if (!noAssert) checkOffset(offset, 4, this.length)
  1251. return ieee754.read(this, offset, false, 23, 4)
  1252. }
  1253. Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
  1254. if (!noAssert) checkOffset(offset, 8, this.length)
  1255. return ieee754.read(this, offset, true, 52, 8)
  1256. }
  1257. Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
  1258. if (!noAssert) checkOffset(offset, 8, this.length)
  1259. return ieee754.read(this, offset, false, 52, 8)
  1260. }
  1261. function checkInt (buf, value, offset, ext, max, min) {
  1262. if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance')
  1263. if (value > max || value < min) throw new RangeError('"value" argument is out of bounds')
  1264. if (offset + ext > buf.length) throw new RangeError('Index out of range')
  1265. }
  1266. Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
  1267. value = +value
  1268. offset = offset | 0
  1269. byteLength = byteLength | 0
  1270. if (!noAssert) {
  1271. var maxBytes = Math.pow(2, 8 * byteLength) - 1
  1272. checkInt(this, value, offset, byteLength, maxBytes, 0)
  1273. }
  1274. var mul = 1
  1275. var i = 0
  1276. this[offset] = value & 0xFF
  1277. while (++i < byteLength && (mul *= 0x100)) {
  1278. this[offset + i] = (value / mul) & 0xFF
  1279. }
  1280. return offset + byteLength
  1281. }
  1282. Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
  1283. value = +value
  1284. offset = offset | 0
  1285. byteLength = byteLength | 0
  1286. if (!noAssert) {
  1287. var maxBytes = Math.pow(2, 8 * byteLength) - 1
  1288. checkInt(this, value, offset, byteLength, maxBytes, 0)
  1289. }
  1290. var i = byteLength - 1
  1291. var mul = 1
  1292. this[offset + i] = value & 0xFF
  1293. while (--i >= 0 && (mul *= 0x100)) {
  1294. this[offset + i] = (value / mul) & 0xFF
  1295. }
  1296. return offset + byteLength
  1297. }
  1298. Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
  1299. value = +value
  1300. offset = offset | 0
  1301. if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)
  1302. if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
  1303. this[offset] = (value & 0xff)
  1304. return offset + 1
  1305. }
  1306. function objectWriteUInt16 (buf, value, offset, littleEndian) {
  1307. if (value < 0) value = 0xffff + value + 1
  1308. for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) {
  1309. buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>>
  1310. (littleEndian ? i : 1 - i) * 8
  1311. }
  1312. }
  1313. Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
  1314. value = +value
  1315. offset = offset | 0
  1316. if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
  1317. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1318. this[offset] = (value & 0xff)
  1319. this[offset + 1] = (value >>> 8)
  1320. } else {
  1321. objectWriteUInt16(this, value, offset, true)
  1322. }
  1323. return offset + 2
  1324. }
  1325. Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
  1326. value = +value
  1327. offset = offset | 0
  1328. if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
  1329. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1330. this[offset] = (value >>> 8)
  1331. this[offset + 1] = (value & 0xff)
  1332. } else {
  1333. objectWriteUInt16(this, value, offset, false)
  1334. }
  1335. return offset + 2
  1336. }
  1337. function objectWriteUInt32 (buf, value, offset, littleEndian) {
  1338. if (value < 0) value = 0xffffffff + value + 1
  1339. for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) {
  1340. buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff
  1341. }
  1342. }
  1343. Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
  1344. value = +value
  1345. offset = offset | 0
  1346. if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
  1347. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1348. this[offset + 3] = (value >>> 24)
  1349. this[offset + 2] = (value >>> 16)
  1350. this[offset + 1] = (value >>> 8)
  1351. this[offset] = (value & 0xff)
  1352. } else {
  1353. objectWriteUInt32(this, value, offset, true)
  1354. }
  1355. return offset + 4
  1356. }
  1357. Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
  1358. value = +value
  1359. offset = offset | 0
  1360. if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
  1361. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1362. this[offset] = (value >>> 24)
  1363. this[offset + 1] = (value >>> 16)
  1364. this[offset + 2] = (value >>> 8)
  1365. this[offset + 3] = (value & 0xff)
  1366. } else {
  1367. objectWriteUInt32(this, value, offset, false)
  1368. }
  1369. return offset + 4
  1370. }
  1371. Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
  1372. value = +value
  1373. offset = offset | 0
  1374. if (!noAssert) {
  1375. var limit = Math.pow(2, 8 * byteLength - 1)
  1376. checkInt(this, value, offset, byteLength, limit - 1, -limit)
  1377. }
  1378. var i = 0
  1379. var mul = 1
  1380. var sub = 0
  1381. this[offset] = value & 0xFF
  1382. while (++i < byteLength && (mul *= 0x100)) {
  1383. if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
  1384. sub = 1
  1385. }
  1386. this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
  1387. }
  1388. return offset + byteLength
  1389. }
  1390. Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
  1391. value = +value
  1392. offset = offset | 0
  1393. if (!noAssert) {
  1394. var limit = Math.pow(2, 8 * byteLength - 1)
  1395. checkInt(this, value, offset, byteLength, limit - 1, -limit)
  1396. }
  1397. var i = byteLength - 1
  1398. var mul = 1
  1399. var sub = 0
  1400. this[offset + i] = value & 0xFF
  1401. while (--i >= 0 && (mul *= 0x100)) {
  1402. if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
  1403. sub = 1
  1404. }
  1405. this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
  1406. }
  1407. return offset + byteLength
  1408. }
  1409. Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
  1410. value = +value
  1411. offset = offset | 0
  1412. if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)
  1413. if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
  1414. if (value < 0) value = 0xff + value + 1
  1415. this[offset] = (value & 0xff)
  1416. return offset + 1
  1417. }
  1418. Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
  1419. value = +value
  1420. offset = offset | 0
  1421. if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
  1422. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1423. this[offset] = (value & 0xff)
  1424. this[offset + 1] = (value >>> 8)
  1425. } else {
  1426. objectWriteUInt16(this, value, offset, true)
  1427. }
  1428. return offset + 2
  1429. }
  1430. Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
  1431. value = +value
  1432. offset = offset | 0
  1433. if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
  1434. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1435. this[offset] = (value >>> 8)
  1436. this[offset + 1] = (value & 0xff)
  1437. } else {
  1438. objectWriteUInt16(this, value, offset, false)
  1439. }
  1440. return offset + 2
  1441. }
  1442. Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
  1443. value = +value
  1444. offset = offset | 0
  1445. if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
  1446. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1447. this[offset] = (value & 0xff)
  1448. this[offset + 1] = (value >>> 8)
  1449. this[offset + 2] = (value >>> 16)
  1450. this[offset + 3] = (value >>> 24)
  1451. } else {
  1452. objectWriteUInt32(this, value, offset, true)
  1453. }
  1454. return offset + 4
  1455. }
  1456. Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
  1457. value = +value
  1458. offset = offset | 0
  1459. if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
  1460. if (value < 0) value = 0xffffffff + value + 1
  1461. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1462. this[offset] = (value >>> 24)
  1463. this[offset + 1] = (value >>> 16)
  1464. this[offset + 2] = (value >>> 8)
  1465. this[offset + 3] = (value & 0xff)
  1466. } else {
  1467. objectWriteUInt32(this, value, offset, false)
  1468. }
  1469. return offset + 4
  1470. }
  1471. function checkIEEE754 (buf, value, offset, ext, max, min) {
  1472. if (offset + ext > buf.length) throw new RangeError('Index out of range')
  1473. if (offset < 0) throw new RangeError('Index out of range')
  1474. }
  1475. function writeFloat (buf, value, offset, littleEndian, noAssert) {
  1476. if (!noAssert) {
  1477. checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
  1478. }
  1479. ieee754.write(buf, value, offset, littleEndian, 23, 4)
  1480. return offset + 4
  1481. }
  1482. Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
  1483. return writeFloat(this, value, offset, true, noAssert)
  1484. }
  1485. Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
  1486. return writeFloat(this, value, offset, false, noAssert)
  1487. }
  1488. function writeDouble (buf, value, offset, littleEndian, noAssert) {
  1489. if (!noAssert) {
  1490. checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
  1491. }
  1492. ieee754.write(buf, value, offset, littleEndian, 52, 8)
  1493. return offset + 8
  1494. }
  1495. Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
  1496. return writeDouble(this, value, offset, true, noAssert)
  1497. }
  1498. Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
  1499. return writeDouble(this, value, offset, false, noAssert)
  1500. }
  1501. // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
  1502. Buffer.prototype.copy = function copy (target, targetStart, start, end) {
  1503. if (!start) start = 0
  1504. if (!end && end !== 0) end = this.length
  1505. if (targetStart >= target.length) targetStart = target.length
  1506. if (!targetStart) targetStart = 0
  1507. if (end > 0 && end < start) end = start
  1508. // Copy 0 bytes; we're done
  1509. if (end === start) return 0
  1510. if (target.length === 0 || this.length === 0) return 0
  1511. // Fatal error conditions
  1512. if (targetStart < 0) {
  1513. throw new RangeError('targetStart out of bounds')
  1514. }
  1515. if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds')
  1516. if (end < 0) throw new RangeError('sourceEnd out of bounds')
  1517. // Are we oob?
  1518. if (end > this.length) end = this.length
  1519. if (target.length - targetStart < end - start) {
  1520. end = target.length - targetStart + start
  1521. }
  1522. var len = end - start
  1523. var i
  1524. if (this === target && start < targetStart && targetStart < end) {
  1525. // descending copy from end
  1526. for (i = len - 1; i >= 0; --i) {
  1527. target[i + targetStart] = this[i + start]
  1528. }
  1529. } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) {
  1530. // ascending copy from start
  1531. for (i = 0; i < len; ++i) {
  1532. target[i + targetStart] = this[i + start]
  1533. }
  1534. } else {
  1535. Uint8Array.prototype.set.call(
  1536. target,
  1537. this.subarray(start, start + len),
  1538. targetStart
  1539. )
  1540. }
  1541. return len
  1542. }
  1543. // Usage:
  1544. // buffer.fill(number[, offset[, end]])
  1545. // buffer.fill(buffer[, offset[, end]])
  1546. // buffer.fill(string[, offset[, end]][, encoding])
  1547. Buffer.prototype.fill = function fill (val, start, end, encoding) {
  1548. // Handle string cases:
  1549. if (typeof val === 'string') {
  1550. if (typeof start === 'string') {
  1551. encoding = start
  1552. start = 0
  1553. end = this.length
  1554. } else if (typeof end === 'string') {
  1555. encoding = end
  1556. end = this.length
  1557. }
  1558. if (val.length === 1) {
  1559. var code = val.charCodeAt(0)
  1560. if (code < 256) {
  1561. val = code
  1562. }
  1563. }
  1564. if (encoding !== undefined && typeof encoding !== 'string') {
  1565. throw new TypeError('encoding must be a string')
  1566. }
  1567. if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
  1568. throw new TypeError('Unknown encoding: ' + encoding)
  1569. }
  1570. } else if (typeof val === 'number') {
  1571. val = val & 255
  1572. }
  1573. // Invalid ranges are not set to a default, so can range check early.
  1574. if (start < 0 || this.length < start || this.length < end) {
  1575. throw new RangeError('Out of range index')
  1576. }
  1577. if (end <= start) {
  1578. return this
  1579. }
  1580. start = start >>> 0
  1581. end = end === undefined ? this.length : end >>> 0
  1582. if (!val) val = 0
  1583. var i
  1584. if (typeof val === 'number') {
  1585. for (i = start; i < end; ++i) {
  1586. this[i] = val
  1587. }
  1588. } else {
  1589. var bytes = Buffer.isBuffer(val)
  1590. ? val
  1591. : utf8ToBytes(new Buffer(val, encoding).toString())
  1592. var len = bytes.length
  1593. for (i = 0; i < end - start; ++i) {
  1594. this[i + start] = bytes[i % len]
  1595. }
  1596. }
  1597. return this
  1598. }
  1599. // HELPER FUNCTIONS
  1600. // ================
  1601. var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g
  1602. function base64clean (str) {
  1603. // Node strips out invalid characters like \n and \t from the string, base64-js does not
  1604. str = stringtrim(str).replace(INVALID_BASE64_RE, '')
  1605. // Node converts strings with length < 2 to ''
  1606. if (str.length < 2) return ''
  1607. // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
  1608. while (str.length % 4 !== 0) {
  1609. str = str + '='
  1610. }
  1611. return str
  1612. }
  1613. function stringtrim (str) {
  1614. if (str.trim) return str.trim()
  1615. return str.replace(/^\s+|\s+$/g, '')
  1616. }
  1617. function toHex (n) {
  1618. if (n < 16) return '0' + n.toString(16)
  1619. return n.toString(16)
  1620. }
  1621. function utf8ToBytes (string, units) {
  1622. units = units || Infinity
  1623. var codePoint
  1624. var length = string.length
  1625. var leadSurrogate = null
  1626. var bytes = []
  1627. for (var i = 0; i < length; ++i) {
  1628. codePoint = string.charCodeAt(i)
  1629. // is surrogate component
  1630. if (codePoint > 0xD7FF && codePoint < 0xE000) {
  1631. // last char was a lead
  1632. if (!leadSurrogate) {
  1633. // no lead yet
  1634. if (codePoint > 0xDBFF) {
  1635. // unexpected trail
  1636. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  1637. continue
  1638. } else if (i + 1 === length) {
  1639. // unpaired lead
  1640. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  1641. continue
  1642. }
  1643. // valid lead
  1644. leadSurrogate = codePoint
  1645. continue
  1646. }
  1647. // 2 leads in a row
  1648. if (codePoint < 0xDC00) {
  1649. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  1650. leadSurrogate = codePoint
  1651. continue
  1652. }
  1653. // valid surrogate pair
  1654. codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000
  1655. } else if (leadSurrogate) {
  1656. // valid bmp char, but last char was a lead
  1657. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  1658. }
  1659. leadSurrogate = null
  1660. // encode utf8
  1661. if (codePoint < 0x80) {
  1662. if ((units -= 1) < 0) break
  1663. bytes.push(codePoint)
  1664. } else if (codePoint < 0x800) {
  1665. if ((units -= 2) < 0) break
  1666. bytes.push(
  1667. codePoint >> 0x6 | 0xC0,
  1668. codePoint & 0x3F | 0x80
  1669. )
  1670. } else if (codePoint < 0x10000) {
  1671. if ((units -= 3) < 0) break
  1672. bytes.push(
  1673. codePoint >> 0xC | 0xE0,
  1674. codePoint >> 0x6 & 0x3F | 0x80,
  1675. codePoint & 0x3F | 0x80
  1676. )
  1677. } else if (codePoint < 0x110000) {
  1678. if ((units -= 4) < 0) break
  1679. bytes.push(
  1680. codePoint >> 0x12 | 0xF0,
  1681. codePoint >> 0xC & 0x3F | 0x80,
  1682. codePoint >> 0x6 & 0x3F | 0x80,
  1683. codePoint & 0x3F | 0x80
  1684. )
  1685. } else {
  1686. throw new Error('Invalid code point')
  1687. }
  1688. }
  1689. return bytes
  1690. }
  1691. function asciiToBytes (str) {
  1692. var byteArray = []
  1693. for (var i = 0; i < str.length; ++i) {
  1694. // Node's code seems to be doing this and not & 0x7F..
  1695. byteArray.push(str.charCodeAt(i) & 0xFF)
  1696. }
  1697. return byteArray
  1698. }
  1699. function utf16leToBytes (str, units) {
  1700. var c, hi, lo
  1701. var byteArray = []
  1702. for (var i = 0; i < str.length; ++i) {
  1703. if ((units -= 2) < 0) break
  1704. c = str.charCodeAt(i)
  1705. hi = c >> 8
  1706. lo = c % 256
  1707. byteArray.push(lo)
  1708. byteArray.push(hi)
  1709. }
  1710. return byteArray
  1711. }
  1712. function base64ToBytes (str) {
  1713. return base64.toByteArray(base64clean(str))
  1714. }
  1715. function blitBuffer (src, dst, offset, length) {
  1716. for (var i = 0; i < length; ++i) {
  1717. if ((i + offset >= dst.length) || (i >= src.length)) break
  1718. dst[i + offset] = src[i]
  1719. }
  1720. return i
  1721. }
  1722. function isnan (val) {
  1723. return val !== val // eslint-disable-line no-self-compare
  1724. }
  1725. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  1726. },{"base64-js":3,"ieee754":16,"isarray":21}],7:[function(_dereq_,module,exports){
  1727. // Polyfill for creating CustomEvents on IE9/10/11
  1728. // code pulled from:
  1729. // https://github.com/d4tocchini/customevent-polyfill
  1730. // https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent#Polyfill
  1731. (function() {
  1732. if (typeof window === 'undefined') {
  1733. return;
  1734. }
  1735. try {
  1736. var ce = new window.CustomEvent('test', { cancelable: true });
  1737. ce.preventDefault();
  1738. if (ce.defaultPrevented !== true) {
  1739. // IE has problems with .preventDefault() on custom events
  1740. // http://stackoverflow.com/questions/23349191
  1741. throw new Error('Could not prevent default');
  1742. }
  1743. } catch (e) {
  1744. var CustomEvent = function(event, params) {
  1745. var evt, origPrevent;
  1746. params = params || {
  1747. bubbles: false,
  1748. cancelable: false,
  1749. detail: undefined
  1750. };
  1751. evt = document.createEvent('CustomEvent');
  1752. evt.initCustomEvent(
  1753. event,
  1754. params.bubbles,
  1755. params.cancelable,
  1756. params.detail
  1757. );
  1758. origPrevent = evt.preventDefault;
  1759. evt.preventDefault = function() {
  1760. origPrevent.call(this);
  1761. try {
  1762. Object.defineProperty(this, 'defaultPrevented', {
  1763. get: function() {
  1764. return true;
  1765. }
  1766. });
  1767. } catch (e) {
  1768. this.defaultPrevented = true;
  1769. }
  1770. };
  1771. return evt;
  1772. };
  1773. CustomEvent.prototype = window.Event.prototype;
  1774. window.CustomEvent = CustomEvent; // expose definition to window
  1775. }
  1776. })();
  1777. },{}],8:[function(_dereq_,module,exports){
  1778. /**
  1779. * This is the web browser implementation of `debug()`.
  1780. *
  1781. * Expose `debug()` as the module.
  1782. */
  1783. exports = module.exports = _dereq_('./debug');
  1784. exports.log = log;
  1785. exports.formatArgs = formatArgs;
  1786. exports.save = save;
  1787. exports.load = load;
  1788. exports.useColors = useColors;
  1789. exports.storage = 'undefined' != typeof chrome
  1790. && 'undefined' != typeof chrome.storage
  1791. ? chrome.storage.local
  1792. : localstorage();
  1793. /**
  1794. * Colors.
  1795. */
  1796. exports.colors = [
  1797. 'lightseagreen',
  1798. 'forestgreen',
  1799. 'goldenrod',
  1800. 'dodgerblue',
  1801. 'darkorchid',
  1802. 'crimson'
  1803. ];
  1804. /**
  1805. * Currently only WebKit-based Web Inspectors, Firefox >= v31,
  1806. * and the Firebug extension (any Firefox version) are known
  1807. * to support "%c" CSS customizations.
  1808. *
  1809. * TODO: add a `localStorage` variable to explicitly enable/disable colors
  1810. */
  1811. function useColors() {
  1812. // is webkit? http://stackoverflow.com/a/16459606/376773
  1813. return ('WebkitAppearance' in document.documentElement.style) ||
  1814. // is firebug? http://stackoverflow.com/a/398120/376773
  1815. (window.console && (console.firebug || (console.exception && console.table))) ||
  1816. // is firefox >= v31?
  1817. // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
  1818. (navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31);
  1819. }
  1820. /**
  1821. * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
  1822. */
  1823. exports.formatters.j = function(v) {
  1824. return JSON.stringify(v);
  1825. };
  1826. /**
  1827. * Colorize log arguments if enabled.
  1828. *
  1829. * @api public
  1830. */
  1831. function formatArgs() {
  1832. var args = arguments;
  1833. var useColors = this.useColors;
  1834. args[0] = (useColors ? '%c' : '')
  1835. + this.namespace
  1836. + (useColors ? ' %c' : ' ')
  1837. + args[0]
  1838. + (useColors ? '%c ' : ' ');
  1839. if (!useColors) return args;
  1840. var c = 'color: ' + this.color;
  1841. args = [args[0], c, 'color: inherit'].concat(Array.prototype.slice.call(args, 1));
  1842. // the final "%c" is somewhat tricky, because there could be other
  1843. // arguments passed either before or after the %c, so we need to
  1844. // figure out the correct index to insert the CSS into
  1845. var index = 0;
  1846. var lastC = 0;
  1847. args[0].replace(/%[a-z%]/g, function(match) {
  1848. if ('%%' === match) return;
  1849. index++;
  1850. if ('%c' === match) {
  1851. // we only are interested in the *last* %c
  1852. // (the user may have provided their own)
  1853. lastC = index;
  1854. }
  1855. });
  1856. args.splice(lastC, 0, c);
  1857. return args;
  1858. }
  1859. /**
  1860. * Invokes `console.log()` when available.
  1861. * No-op when `console.log` is not a "function".
  1862. *
  1863. * @api public
  1864. */
  1865. function log() {
  1866. // this hackery is required for IE8/9, where
  1867. // the `console.log` function doesn't have 'apply'
  1868. return 'object' === typeof console
  1869. && console.log
  1870. && Function.prototype.apply.call(console.log, console, arguments);
  1871. }
  1872. /**
  1873. * Save `namespaces`.
  1874. *
  1875. * @param {String} namespaces
  1876. * @api private
  1877. */
  1878. function save(namespaces) {
  1879. try {
  1880. if (null == namespaces) {
  1881. exports.storage.removeItem('debug');
  1882. } else {
  1883. exports.storage.debug = namespaces;
  1884. }
  1885. } catch(e) {}
  1886. }
  1887. /**
  1888. * Load `namespaces`.
  1889. *
  1890. * @return {String} returns the previously persisted debug modes
  1891. * @api private
  1892. */
  1893. function load() {
  1894. var r;
  1895. try {
  1896. r = exports.storage.debug;
  1897. } catch(e) {}
  1898. return r;
  1899. }
  1900. /**
  1901. * Enable namespaces listed in `localStorage.debug` initially.
  1902. */
  1903. exports.enable(load());
  1904. /**
  1905. * Localstorage attempts to return the localstorage.
  1906. *
  1907. * This is necessary because safari throws
  1908. * when a user disables cookies/localstorage
  1909. * and you attempt to access it.
  1910. *
  1911. * @return {LocalStorage}
  1912. * @api private
  1913. */
  1914. function localstorage(){
  1915. try {
  1916. return window.localStorage;
  1917. } catch (e) {}
  1918. }
  1919. },{"./debug":9}],9:[function(_dereq_,module,exports){
  1920. /**
  1921. * This is the common logic for both the Node.js and web browser
  1922. * implementations of `debug()`.
  1923. *
  1924. * Expose `debug()` as the module.
  1925. */
  1926. exports = module.exports = debug;
  1927. exports.coerce = coerce;
  1928. exports.disable = disable;
  1929. exports.enable = enable;
  1930. exports.enabled = enabled;
  1931. /**
  1932. * The currently active debug mode names, and names to skip.
  1933. */
  1934. exports.names = [];
  1935. exports.skips = [];
  1936. /**
  1937. * Map of special "%n" handling functions, for the debug "format" argument.
  1938. *
  1939. * Valid key names are a single, lowercased letter, i.e. "n".
  1940. */
  1941. exports.formatters = {};
  1942. /**
  1943. * Previously assigned color.
  1944. */
  1945. var prevColor = 0;
  1946. /**
  1947. * Select a color.
  1948. *
  1949. * @return {Number}
  1950. * @api private
  1951. */
  1952. function selectColor() {
  1953. return exports.colors[prevColor++ % exports.colors.length];
  1954. }
  1955. /**
  1956. * Create a debugger with the given `namespace`.
  1957. *
  1958. * @param {String} namespace
  1959. * @return {Function}
  1960. * @api public
  1961. */
  1962. function debug(namespace) {
  1963. // define the `disabled` version
  1964. function disabled() {
  1965. }
  1966. disabled.enabled = false;
  1967. // define the `enabled` version
  1968. function enabled() {
  1969. var self = enabled;
  1970. // add the `color` if not set
  1971. if (null == self.useColors) self.useColors = exports.useColors();
  1972. if (null == self.color && self.useColors) self.color = selectColor();
  1973. var args = Array.prototype.slice.call(arguments);
  1974. args[0] = exports.coerce(args[0]);
  1975. if ('string' !== typeof args[0]) {
  1976. // anything else let's inspect with %o
  1977. args = ['%o'].concat(args);
  1978. }
  1979. // apply any `formatters` transformations
  1980. var index = 0;
  1981. args[0] = args[0].replace(/%([a-z%])/g, function(match, format) {
  1982. // if we encounter an escaped % then don't increase the array index
  1983. if (match === '%%') return match;
  1984. index++;
  1985. var formatter = exports.formatters[format];
  1986. if ('function' === typeof formatter) {
  1987. var val = args[index];
  1988. match = formatter.call(self, val);
  1989. // now we need to remove `args[index]` since it's inlined in the `format`
  1990. args.splice(index, 1);
  1991. index--;
  1992. }
  1993. return match;
  1994. });
  1995. if ('function' === typeof exports.formatArgs) {
  1996. args = exports.formatArgs.apply(self, args);
  1997. }
  1998. var logFn = enabled.log || exports.log || console.log.bind(console);
  1999. logFn.apply(self, args);
  2000. }
  2001. enabled.enabled = true;
  2002. var fn = exports.enabled(namespace) ? enabled : disabled;
  2003. fn.namespace = namespace;
  2004. return fn;
  2005. }
  2006. /**
  2007. * Enables a debug mode by namespaces. This can include modes
  2008. * separated by a colon and wildcards.
  2009. *
  2010. * @param {String} namespaces
  2011. * @api public
  2012. */
  2013. function enable(namespaces) {
  2014. exports.save(namespaces);
  2015. var split = (namespaces || '').split(/[\s,]+/);
  2016. var len = split.length;
  2017. for (var i = 0; i < len; i++) {
  2018. if (!split[i]) continue; // ignore empty strings
  2019. namespaces = split[i].replace(/\*/g, '.*?');
  2020. if (namespaces[0] === '-') {
  2021. exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));
  2022. } else {
  2023. exports.names.push(new RegExp('^' + namespaces + '$'));
  2024. }
  2025. }
  2026. }
  2027. /**
  2028. * Disable debug output.
  2029. *
  2030. * @api public
  2031. */
  2032. function disable() {
  2033. exports.enable('');
  2034. }
  2035. /**
  2036. * Returns true if the given mode name is enabled, false otherwise.
  2037. *
  2038. * @param {String} name
  2039. * @return {Boolean}
  2040. * @api public
  2041. */
  2042. function enabled(name) {
  2043. var i, len;
  2044. for (i = 0, len = exports.skips.length; i < len; i++) {
  2045. if (exports.skips[i].test(name)) {
  2046. return false;
  2047. }
  2048. }
  2049. for (i = 0, len = exports.names.length; i < len; i++) {
  2050. if (exports.names[i].test(name)) {
  2051. return true;
  2052. }
  2053. }
  2054. return false;
  2055. }
  2056. /**
  2057. * Coerce `val`.
  2058. *
  2059. * @param {Mixed} val
  2060. * @return {Mixed}
  2061. * @api private
  2062. */
  2063. function coerce(val) {
  2064. if (val instanceof Error) return val.stack || val.message;
  2065. return val;
  2066. }
  2067. },{}],10:[function(_dereq_,module,exports){
  2068. 'use strict';
  2069. var isObj = _dereq_('is-obj');
  2070. var hasOwnProperty = Object.prototype.hasOwnProperty;
  2071. var propIsEnumerable = Object.prototype.propertyIsEnumerable;
  2072. function toObject(val) {
  2073. if (val === null || val === undefined) {
  2074. throw new TypeError('Sources cannot be null or undefined');
  2075. }
  2076. return Object(val);
  2077. }
  2078. function assignKey(to, from, key) {
  2079. var val = from[key];
  2080. if (val === undefined || val === null) {
  2081. return;
  2082. }
  2083. if (hasOwnProperty.call(to, key)) {
  2084. if (to[key] === undefined || to[key] === null) {
  2085. throw new TypeError('Cannot convert undefined or null to object (' + key + ')');
  2086. }
  2087. }
  2088. if (!hasOwnProperty.call(to, key) || !isObj(val)) {
  2089. to[key] = val;
  2090. } else {
  2091. to[key] = assign(Object(to[key]), from[key]);
  2092. }
  2093. }
  2094. function assign(to, from) {
  2095. if (to === from) {
  2096. return to;
  2097. }
  2098. from = Object(from);
  2099. for (var key in from) {
  2100. if (hasOwnProperty.call(from, key)) {
  2101. assignKey(to, from, key);
  2102. }
  2103. }
  2104. if (Object.getOwnPropertySymbols) {
  2105. var symbols = Object.getOwnPropertySymbols(from);
  2106. for (var i = 0; i < symbols.length; i++) {
  2107. if (propIsEnumerable.call(from, symbols[i])) {
  2108. assignKey(to, from, symbols[i]);
  2109. }
  2110. }
  2111. }
  2112. return to;
  2113. }
  2114. module.exports = function deepAssign(target) {
  2115. target = toObject(target);
  2116. for (var s = 1; s < arguments.length; s++) {
  2117. assign(target, arguments[s]);
  2118. }
  2119. return target;
  2120. };
  2121. },{"is-obj":20}],11:[function(_dereq_,module,exports){
  2122. /*! (C) WebReflection Mit Style License */
  2123. (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");
  2124. },{}],12:[function(_dereq_,module,exports){
  2125. module.exports = function(dtype) {
  2126. switch (dtype) {
  2127. case 'int8':
  2128. return Int8Array
  2129. case 'int16':
  2130. return Int16Array
  2131. case 'int32':
  2132. return Int32Array
  2133. case 'uint8':
  2134. return Uint8Array
  2135. case 'uint16':
  2136. return Uint16Array
  2137. case 'uint32':
  2138. return Uint32Array
  2139. case 'float32':
  2140. return Float32Array
  2141. case 'float64':
  2142. return Float64Array
  2143. case 'array':
  2144. return Array
  2145. case 'uint8_clamped':
  2146. return Uint8ClampedArray
  2147. }
  2148. }
  2149. },{}],13:[function(_dereq_,module,exports){
  2150. /*eslint new-cap:0*/
  2151. var dtype = _dereq_('dtype')
  2152. module.exports = flattenVertexData
  2153. function flattenVertexData (data, output, offset) {
  2154. if (!data) throw new TypeError('must specify data as first parameter')
  2155. offset = +(offset || 0) | 0
  2156. if (Array.isArray(data) && Array.isArray(data[0])) {
  2157. var dim = data[0].length
  2158. var length = data.length * dim
  2159. // no output specified, create a new typed array
  2160. if (!output || typeof output === 'string') {
  2161. output = new (dtype(output || 'float32'))(length + offset)
  2162. }
  2163. var dstLength = output.length - offset
  2164. if (length !== dstLength) {
  2165. throw new Error('source length ' + length + ' (' + dim + 'x' + data.length + ')' +
  2166. ' does not match destination length ' + dstLength)
  2167. }
  2168. for (var i = 0, k = offset; i < data.length; i++) {
  2169. for (var j = 0; j < dim; j++) {
  2170. output[k++] = data[i][j]
  2171. }
  2172. }
  2173. } else {
  2174. if (!output || typeof output === 'string') {
  2175. // no output, create a new one
  2176. var Ctor = dtype(output || 'float32')
  2177. if (offset === 0) {
  2178. output = new Ctor(data)
  2179. } else {
  2180. output = new Ctor(data.length + offset)
  2181. output.set(data, offset)
  2182. }
  2183. } else {
  2184. // store output in existing array
  2185. output.set(data, offset)
  2186. }
  2187. }
  2188. return output
  2189. }
  2190. },{"dtype":12}],14:[function(_dereq_,module,exports){
  2191. var isFunction = _dereq_('is-function')
  2192. module.exports = forEach
  2193. var toString = Object.prototype.toString
  2194. var hasOwnProperty = Object.prototype.hasOwnProperty
  2195. function forEach(list, iterator, context) {
  2196. if (!isFunction(iterator)) {
  2197. throw new TypeError('iterator must be a function')
  2198. }
  2199. if (arguments.length < 3) {
  2200. context = this
  2201. }
  2202. if (toString.call(list) === '[object Array]')
  2203. forEachArray(list, iterator, context)
  2204. else if (typeof list === 'string')
  2205. forEachString(list, iterator, context)
  2206. else
  2207. forEachObject(list, iterator, context)
  2208. }
  2209. function forEachArray(array, iterator, context) {
  2210. for (var i = 0, len = array.length; i < len; i++) {
  2211. if (hasOwnProperty.call(array, i)) {
  2212. iterator.call(context, array[i], i, array)
  2213. }
  2214. }
  2215. }
  2216. function forEachString(string, iterator, context) {
  2217. for (var i = 0, len = string.length; i < len; i++) {
  2218. // no such thing as a sparse string.
  2219. iterator.call(context, string.charAt(i), i, string)
  2220. }
  2221. }
  2222. function forEachObject(object, iterator, context) {
  2223. for (var k in object) {
  2224. if (hasOwnProperty.call(object, k)) {
  2225. iterator.call(context, object[k], k, object)
  2226. }
  2227. }
  2228. }
  2229. },{"is-function":19}],15:[function(_dereq_,module,exports){
  2230. (function (global){
  2231. var win;
  2232. if (typeof window !== "undefined") {
  2233. win = window;
  2234. } else if (typeof global !== "undefined") {
  2235. win = global;
  2236. } else if (typeof self !== "undefined"){
  2237. win = self;
  2238. } else {
  2239. win = {};
  2240. }
  2241. module.exports = win;
  2242. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  2243. },{}],16:[function(_dereq_,module,exports){
  2244. exports.read = function (buffer, offset, isLE, mLen, nBytes) {
  2245. var e, m
  2246. var eLen = nBytes * 8 - mLen - 1
  2247. var eMax = (1 << eLen) - 1
  2248. var eBias = eMax >> 1
  2249. var nBits = -7
  2250. var i = isLE ? (nBytes - 1) : 0
  2251. var d = isLE ? -1 : 1
  2252. var s = buffer[offset + i]
  2253. i += d
  2254. e = s & ((1 << (-nBits)) - 1)
  2255. s >>= (-nBits)
  2256. nBits += eLen
  2257. for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {}
  2258. m = e & ((1 << (-nBits)) - 1)
  2259. e >>= (-nBits)
  2260. nBits += mLen
  2261. for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {}
  2262. if (e === 0) {
  2263. e = 1 - eBias
  2264. } else if (e === eMax) {
  2265. return m ? NaN : ((s ? -1 : 1) * Infinity)
  2266. } else {
  2267. m = m + Math.pow(2, mLen)
  2268. e = e - eBias
  2269. }
  2270. return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
  2271. }
  2272. exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
  2273. var e, m, c
  2274. var eLen = nBytes * 8 - mLen - 1
  2275. var eMax = (1 << eLen) - 1
  2276. var eBias = eMax >> 1
  2277. var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)
  2278. var i = isLE ? 0 : (nBytes - 1)
  2279. var d = isLE ? 1 : -1
  2280. var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0
  2281. value = Math.abs(value)
  2282. if (isNaN(value) || value === Infinity) {
  2283. m = isNaN(value) ? 1 : 0
  2284. e = eMax
  2285. } else {
  2286. e = Math.floor(Math.log(value) / Math.LN2)
  2287. if (value * (c = Math.pow(2, -e)) < 1) {
  2288. e--
  2289. c *= 2
  2290. }
  2291. if (e + eBias >= 1) {
  2292. value += rt / c
  2293. } else {
  2294. value += rt * Math.pow(2, 1 - eBias)
  2295. }
  2296. if (value * c >= 2) {
  2297. e++
  2298. c /= 2
  2299. }
  2300. if (e + eBias >= eMax) {
  2301. m = 0
  2302. e = eMax
  2303. } else if (e + eBias >= 1) {
  2304. m = (value * c - 1) * Math.pow(2, mLen)
  2305. e = e + eBias
  2306. } else {
  2307. m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
  2308. e = 0
  2309. }
  2310. }
  2311. for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
  2312. e = (e << mLen) | m
  2313. eLen += mLen
  2314. for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
  2315. buffer[offset + i - d] |= s * 128
  2316. }
  2317. },{}],17:[function(_dereq_,module,exports){
  2318. if (typeof Object.create === 'function') {
  2319. // implementation from standard node.js 'util' module
  2320. module.exports = function inherits(ctor, superCtor) {
  2321. ctor.super_ = superCtor
  2322. ctor.prototype = Object.create(superCtor.prototype, {
  2323. constructor: {
  2324. value: ctor,
  2325. enumerable: false,
  2326. writable: true,
  2327. configurable: true
  2328. }
  2329. });
  2330. };
  2331. } else {
  2332. // old school shim for old browsers
  2333. module.exports = function inherits(ctor, superCtor) {
  2334. ctor.super_ = superCtor
  2335. var TempCtor = function () {}
  2336. TempCtor.prototype = superCtor.prototype
  2337. ctor.prototype = new TempCtor()
  2338. ctor.prototype.constructor = ctor
  2339. }
  2340. }
  2341. },{}],18:[function(_dereq_,module,exports){
  2342. /*!
  2343. * Determine if an object is a Buffer
  2344. *
  2345. * @author Feross Aboukhadijeh <https://feross.org>
  2346. * @license MIT
  2347. */
  2348. // The _isBuffer check is for Safari 5-7 support, because it's missing
  2349. // Object.prototype.constructor. Remove this eventually
  2350. module.exports = function (obj) {
  2351. return obj != null && (isBuffer(obj) || isSlowBuffer(obj) || !!obj._isBuffer)
  2352. }
  2353. function isBuffer (obj) {
  2354. return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj)
  2355. }
  2356. // For Node v0.10 support. Remove this eventually.
  2357. function isSlowBuffer (obj) {
  2358. return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isBuffer(obj.slice(0, 0))
  2359. }
  2360. },{}],19:[function(_dereq_,module,exports){
  2361. module.exports = isFunction
  2362. var toString = Object.prototype.toString
  2363. function isFunction (fn) {
  2364. var string = toString.call(fn)
  2365. return string === '[object Function]' ||
  2366. (typeof fn === 'function' && string !== '[object RegExp]') ||
  2367. (typeof window !== 'undefined' &&
  2368. // IE8 and below
  2369. (fn === window.setTimeout ||
  2370. fn === window.alert ||
  2371. fn === window.confirm ||
  2372. fn === window.prompt))
  2373. };
  2374. },{}],20:[function(_dereq_,module,exports){
  2375. 'use strict';
  2376. module.exports = function (x) {
  2377. var type = typeof x;
  2378. return x !== null && (type === 'object' || type === 'function');
  2379. };
  2380. },{}],21:[function(_dereq_,module,exports){
  2381. var toString = {}.toString;
  2382. module.exports = Array.isArray || function (arr) {
  2383. return toString.call(arr) == '[object Array]';
  2384. };
  2385. },{}],22:[function(_dereq_,module,exports){
  2386. var wordWrap = _dereq_('word-wrapper')
  2387. var xtend = _dereq_('xtend')
  2388. var number = _dereq_('as-number')
  2389. var X_HEIGHTS = ['x', 'e', 'a', 'o', 'n', 's', 'r', 'c', 'u', 'm', 'v', 'w', 'z']
  2390. var M_WIDTHS = ['m', 'w']
  2391. var CAP_HEIGHTS = ['H', 'I', 'N', 'E', 'F', 'K', 'L', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
  2392. var TAB_ID = '\t'.charCodeAt(0)
  2393. var SPACE_ID = ' '.charCodeAt(0)
  2394. var ALIGN_LEFT = 0,
  2395. ALIGN_CENTER = 1,
  2396. ALIGN_RIGHT = 2
  2397. module.exports = function createLayout(opt) {
  2398. return new TextLayout(opt)
  2399. }
  2400. function TextLayout(opt) {
  2401. this.glyphs = []
  2402. this._measure = this.computeMetrics.bind(this)
  2403. this.update(opt)
  2404. }
  2405. TextLayout.prototype.update = function(opt) {
  2406. opt = xtend({
  2407. measure: this._measure
  2408. }, opt)
  2409. this._opt = opt
  2410. this._opt.tabSize = number(this._opt.tabSize, 4)
  2411. if (!opt.font)
  2412. throw new Error('must provide a valid bitmap font')
  2413. var glyphs = this.glyphs
  2414. var text = opt.text||''
  2415. var font = opt.font
  2416. this._setupSpaceGlyphs(font)
  2417. var lines = wordWrap.lines(text, opt)
  2418. var minWidth = opt.width || 0
  2419. //clear glyphs
  2420. glyphs.length = 0
  2421. //get max line width
  2422. var maxLineWidth = lines.reduce(function(prev, line) {
  2423. return Math.max(prev, line.width, minWidth)
  2424. }, 0)
  2425. //the pen position
  2426. var x = 0
  2427. var y = 0
  2428. var lineHeight = number(opt.lineHeight, font.common.lineHeight)
  2429. var baseline = font.common.base
  2430. var descender = lineHeight-baseline
  2431. var letterSpacing = opt.letterSpacing || 0
  2432. var height = lineHeight * lines.length - descender
  2433. var align = getAlignType(this._opt.align)
  2434. //draw text along baseline
  2435. y -= height
  2436. //the metrics for this text layout
  2437. this._width = maxLineWidth
  2438. this._height = height
  2439. this._descender = lineHeight - baseline
  2440. this._baseline = baseline
  2441. this._xHeight = getXHeight(font)
  2442. this._capHeight = getCapHeight(font)
  2443. this._lineHeight = lineHeight
  2444. this._ascender = lineHeight - descender - this._xHeight
  2445. //layout each glyph
  2446. var self = this
  2447. lines.forEach(function(line, lineIndex) {
  2448. var start = line.start
  2449. var end = line.end
  2450. var lineWidth = line.width
  2451. var lastGlyph
  2452. //for each glyph in that line...
  2453. for (var i=start; i<end; i++) {
  2454. var id = text.charCodeAt(i)
  2455. var glyph = self.getGlyph(font, id)
  2456. if (glyph) {
  2457. if (lastGlyph)
  2458. x += getKerning(font, lastGlyph.id, glyph.id)
  2459. var tx = x
  2460. if (align === ALIGN_CENTER)
  2461. tx += (maxLineWidth-lineWidth)/2
  2462. else if (align === ALIGN_RIGHT)
  2463. tx += (maxLineWidth-lineWidth)
  2464. glyphs.push({
  2465. position: [tx, y],
  2466. data: glyph,
  2467. index: i,
  2468. line: lineIndex
  2469. })
  2470. //move pen forward
  2471. x += glyph.xadvance + letterSpacing
  2472. lastGlyph = glyph
  2473. }
  2474. }
  2475. //next line down
  2476. y += lineHeight
  2477. x = 0
  2478. })
  2479. this._linesTotal = lines.length;
  2480. }
  2481. TextLayout.prototype._setupSpaceGlyphs = function(font) {
  2482. //These are fallbacks, when the font doesn't include
  2483. //' ' or '\t' glyphs
  2484. this._fallbackSpaceGlyph = null
  2485. this._fallbackTabGlyph = null
  2486. if (!font.chars || font.chars.length === 0)
  2487. return
  2488. //try to get space glyph
  2489. //then fall back to the 'm' or 'w' glyphs
  2490. //then fall back to the first glyph available
  2491. var space = getGlyphById(font, SPACE_ID)
  2492. || getMGlyph(font)
  2493. || font.chars[0]
  2494. //and create a fallback for tab
  2495. var tabWidth = this._opt.tabSize * space.xadvance
  2496. this._fallbackSpaceGlyph = space
  2497. this._fallbackTabGlyph = xtend(space, {
  2498. x: 0, y: 0, xadvance: tabWidth, id: TAB_ID,
  2499. xoffset: 0, yoffset: 0, width: 0, height: 0
  2500. })
  2501. }
  2502. TextLayout.prototype.getGlyph = function(font, id) {
  2503. var glyph = getGlyphById(font, id)
  2504. if (glyph)
  2505. return glyph
  2506. else if (id === TAB_ID)
  2507. return this._fallbackTabGlyph
  2508. else if (id === SPACE_ID)
  2509. return this._fallbackSpaceGlyph
  2510. return null
  2511. }
  2512. TextLayout.prototype.computeMetrics = function(text, start, end, width) {
  2513. var letterSpacing = this._opt.letterSpacing || 0
  2514. var font = this._opt.font
  2515. var curPen = 0
  2516. var curWidth = 0
  2517. var count = 0
  2518. var glyph
  2519. var lastGlyph
  2520. if (!font.chars || font.chars.length === 0) {
  2521. return {
  2522. start: start,
  2523. end: start,
  2524. width: 0
  2525. }
  2526. }
  2527. end = Math.min(text.length, end)
  2528. for (var i=start; i < end; i++) {
  2529. var id = text.charCodeAt(i)
  2530. var glyph = this.getGlyph(font, id)
  2531. if (glyph) {
  2532. //move pen forward
  2533. var xoff = glyph.xoffset
  2534. var kern = lastGlyph ? getKerning(font, lastGlyph.id, glyph.id) : 0
  2535. curPen += kern
  2536. var nextPen = curPen + glyph.xadvance + letterSpacing
  2537. var nextWidth = curPen + glyph.width
  2538. //we've hit our limit; we can't move onto the next glyph
  2539. if (nextWidth >= width || nextPen >= width)
  2540. break
  2541. //otherwise continue along our line
  2542. curPen = nextPen
  2543. curWidth = nextWidth
  2544. lastGlyph = glyph
  2545. }
  2546. count++
  2547. }
  2548. //make sure rightmost edge lines up with rendered glyphs
  2549. if (lastGlyph)
  2550. curWidth += lastGlyph.xoffset
  2551. return {
  2552. start: start,
  2553. end: start + count,
  2554. width: curWidth
  2555. }
  2556. }
  2557. //getters for the private vars
  2558. ;['width', 'height',
  2559. 'descender', 'ascender',
  2560. 'xHeight', 'baseline',
  2561. 'capHeight',
  2562. 'lineHeight' ].forEach(addGetter)
  2563. function addGetter(name) {
  2564. Object.defineProperty(TextLayout.prototype, name, {
  2565. get: wrapper(name),
  2566. configurable: true
  2567. })
  2568. }
  2569. //create lookups for private vars
  2570. function wrapper(name) {
  2571. return (new Function([
  2572. 'return function '+name+'() {',
  2573. ' return this._'+name,
  2574. '}'
  2575. ].join('\n')))()
  2576. }
  2577. function getGlyphById(font, id) {
  2578. if (!font.chars || font.chars.length === 0)
  2579. return null
  2580. var glyphIdx = findChar(font.chars, id)
  2581. if (glyphIdx >= 0)
  2582. return font.chars[glyphIdx]
  2583. return null
  2584. }
  2585. function getXHeight(font) {
  2586. for (var i=0; i<X_HEIGHTS.length; i++) {
  2587. var id = X_HEIGHTS[i].charCodeAt(0)
  2588. var idx = findChar(font.chars, id)
  2589. if (idx >= 0)
  2590. return font.chars[idx].height
  2591. }
  2592. return 0
  2593. }
  2594. function getMGlyph(font) {
  2595. for (var i=0; i<M_WIDTHS.length; i++) {
  2596. var id = M_WIDTHS[i].charCodeAt(0)
  2597. var idx = findChar(font.chars, id)
  2598. if (idx >= 0)
  2599. return font.chars[idx]
  2600. }
  2601. return 0
  2602. }
  2603. function getCapHeight(font) {
  2604. for (var i=0; i<CAP_HEIGHTS.length; i++) {
  2605. var id = CAP_HEIGHTS[i].charCodeAt(0)
  2606. var idx = findChar(font.chars, id)
  2607. if (idx >= 0)
  2608. return font.chars[idx].height
  2609. }
  2610. return 0
  2611. }
  2612. function getKerning(font, left, right) {
  2613. if (!font.kernings || font.kernings.length === 0)
  2614. return 0
  2615. var table = font.kernings
  2616. for (var i=0; i<table.length; i++) {
  2617. var kern = table[i]
  2618. if (kern.first === left && kern.second === right)
  2619. return kern.amount
  2620. }
  2621. return 0
  2622. }
  2623. function getAlignType(align) {
  2624. if (align === 'center')
  2625. return ALIGN_CENTER
  2626. else if (align === 'right')
  2627. return ALIGN_RIGHT
  2628. return ALIGN_LEFT
  2629. }
  2630. function findChar (array, value, start) {
  2631. start = start || 0
  2632. for (var i = start; i < array.length; i++) {
  2633. if (array[i].id === value) {
  2634. return i
  2635. }
  2636. }
  2637. return -1
  2638. }
  2639. },{"as-number":2,"word-wrapper":47,"xtend":50}],23:[function(_dereq_,module,exports){
  2640. (function (Buffer){
  2641. var xhr = _dereq_('xhr')
  2642. var noop = function(){}
  2643. var parseASCII = _dereq_('parse-bmfont-ascii')
  2644. var parseXML = _dereq_('parse-bmfont-xml')
  2645. var readBinary = _dereq_('parse-bmfont-binary')
  2646. var isBinaryFormat = _dereq_('./lib/is-binary')
  2647. var xtend = _dereq_('xtend')
  2648. var xml2 = (function hasXML2() {
  2649. return self.XMLHttpRequest && "withCredentials" in new XMLHttpRequest
  2650. })()
  2651. module.exports = function(opt, cb) {
  2652. cb = typeof cb === 'function' ? cb : noop
  2653. if (typeof opt === 'string')
  2654. opt = { uri: opt }
  2655. else if (!opt)
  2656. opt = {}
  2657. var expectBinary = opt.binary
  2658. if (expectBinary)
  2659. opt = getBinaryOpts(opt)
  2660. xhr(opt, function(err, res, body) {
  2661. if (err)
  2662. return cb(err)
  2663. if (!/^2/.test(res.statusCode))
  2664. return cb(new Error('http status code: '+res.statusCode))
  2665. if (!body)
  2666. return cb(new Error('no body result'))
  2667. var binary = false
  2668. //if the response type is an array buffer,
  2669. //we need to convert it into a regular Buffer object
  2670. if (isArrayBuffer(body)) {
  2671. var array = new Uint8Array(body)
  2672. body = new Buffer(array, 'binary')
  2673. }
  2674. //now check the string/Buffer response
  2675. //and see if it has a binary BMF header
  2676. if (isBinaryFormat(body)) {
  2677. binary = true
  2678. //if we have a string, turn it into a Buffer
  2679. if (typeof body === 'string')
  2680. body = new Buffer(body, 'binary')
  2681. }
  2682. //we are not parsing a binary format, just ASCII/XML/etc
  2683. if (!binary) {
  2684. //might still be a buffer if responseType is 'arraybuffer'
  2685. if (Buffer.isBuffer(body))
  2686. body = body.toString(opt.encoding)
  2687. body = body.trim()
  2688. }
  2689. var result
  2690. try {
  2691. var type = res.headers['content-type']
  2692. if (binary)
  2693. result = readBinary(body)
  2694. else if (/json/.test(type) || body.charAt(0) === '{')
  2695. result = JSON.parse(body)
  2696. else if (/xml/.test(type) || body.charAt(0) === '<')
  2697. result = parseXML(body)
  2698. else
  2699. result = parseASCII(body)
  2700. } catch (e) {
  2701. cb(new Error('error parsing font '+e.message))
  2702. cb = noop
  2703. }
  2704. cb(null, result)
  2705. })
  2706. }
  2707. function isArrayBuffer(arr) {
  2708. var str = Object.prototype.toString
  2709. return str.call(arr) === '[object ArrayBuffer]'
  2710. }
  2711. function getBinaryOpts(opt) {
  2712. //IE10+ and other modern browsers support array buffers
  2713. if (xml2)
  2714. return xtend(opt, { responseType: 'arraybuffer' })
  2715. if (typeof self.XMLHttpRequest === 'undefined')
  2716. throw new Error('your browser does not support XHR loading')
  2717. //IE9 and XML1 browsers could still use an override
  2718. var req = new self.XMLHttpRequest()
  2719. req.overrideMimeType('text/plain; charset=x-user-defined')
  2720. return xtend({
  2721. xhr: req
  2722. }, opt)
  2723. }
  2724. }).call(this,_dereq_("buffer").Buffer)
  2725. },{"./lib/is-binary":24,"buffer":6,"parse-bmfont-ascii":26,"parse-bmfont-binary":27,"parse-bmfont-xml":28,"xhr":48,"xtend":50}],24:[function(_dereq_,module,exports){
  2726. (function (Buffer){
  2727. var equal = _dereq_('buffer-equal')
  2728. var HEADER = new Buffer([66, 77, 70, 3])
  2729. module.exports = function(buf) {
  2730. if (typeof buf === 'string')
  2731. return buf.substring(0, 3) === 'BMF'
  2732. return buf.length > 4 && equal(buf.slice(0, 4), HEADER)
  2733. }
  2734. }).call(this,_dereq_("buffer").Buffer)
  2735. },{"buffer":6,"buffer-equal":5}],25:[function(_dereq_,module,exports){
  2736. /*
  2737. object-assign
  2738. (c) Sindre Sorhus
  2739. @license MIT
  2740. */
  2741. 'use strict';
  2742. /* eslint-disable no-unused-vars */
  2743. var getOwnPropertySymbols = Object.getOwnPropertySymbols;
  2744. var hasOwnProperty = Object.prototype.hasOwnProperty;
  2745. var propIsEnumerable = Object.prototype.propertyIsEnumerable;
  2746. function toObject(val) {
  2747. if (val === null || val === undefined) {
  2748. throw new TypeError('Object.assign cannot be called with null or undefined');
  2749. }
  2750. return Object(val);
  2751. }
  2752. function shouldUseNative() {
  2753. try {
  2754. if (!Object.assign) {
  2755. return false;
  2756. }
  2757. // Detect buggy property enumeration order in older V8 versions.
  2758. // https://bugs.chromium.org/p/v8/issues/detail?id=4118
  2759. var test1 = new String('abc'); // eslint-disable-line no-new-wrappers
  2760. test1[5] = 'de';
  2761. if (Object.getOwnPropertyNames(test1)[0] === '5') {
  2762. return false;
  2763. }
  2764. // https://bugs.chromium.org/p/v8/issues/detail?id=3056
  2765. var test2 = {};
  2766. for (var i = 0; i < 10; i++) {
  2767. test2['_' + String.fromCharCode(i)] = i;
  2768. }
  2769. var order2 = Object.getOwnPropertyNames(test2).map(function (n) {
  2770. return test2[n];
  2771. });
  2772. if (order2.join('') !== '0123456789') {
  2773. return false;
  2774. }
  2775. // https://bugs.chromium.org/p/v8/issues/detail?id=3056
  2776. var test3 = {};
  2777. 'abcdefghijklmnopqrst'.split('').forEach(function (letter) {
  2778. test3[letter] = letter;
  2779. });
  2780. if (Object.keys(Object.assign({}, test3)).join('') !==
  2781. 'abcdefghijklmnopqrst') {
  2782. return false;
  2783. }
  2784. return true;
  2785. } catch (err) {
  2786. // We don't expect any of the above to throw, but better to be safe.
  2787. return false;
  2788. }
  2789. }
  2790. module.exports = shouldUseNative() ? Object.assign : function (target, source) {
  2791. var from;
  2792. var to = toObject(target);
  2793. var symbols;
  2794. for (var s = 1; s < arguments.length; s++) {
  2795. from = Object(arguments[s]);
  2796. for (var key in from) {
  2797. if (hasOwnProperty.call(from, key)) {
  2798. to[key] = from[key];
  2799. }
  2800. }
  2801. if (getOwnPropertySymbols) {
  2802. symbols = getOwnPropertySymbols(from);
  2803. for (var i = 0; i < symbols.length; i++) {
  2804. if (propIsEnumerable.call(from, symbols[i])) {
  2805. to[symbols[i]] = from[symbols[i]];
  2806. }
  2807. }
  2808. }
  2809. }
  2810. return to;
  2811. };
  2812. },{}],26:[function(_dereq_,module,exports){
  2813. module.exports = function parseBMFontAscii(data) {
  2814. if (!data)
  2815. throw new Error('no data provided')
  2816. data = data.toString().trim()
  2817. var output = {
  2818. pages: [],
  2819. chars: [],
  2820. kernings: []
  2821. }
  2822. var lines = data.split(/\r\n?|\n/g)
  2823. if (lines.length === 0)
  2824. throw new Error('no data in BMFont file')
  2825. for (var i = 0; i < lines.length; i++) {
  2826. var lineData = splitLine(lines[i], i)
  2827. if (!lineData) //skip empty lines
  2828. continue
  2829. if (lineData.key === 'page') {
  2830. if (typeof lineData.data.id !== 'number')
  2831. throw new Error('malformed file at line ' + i + ' -- needs page id=N')
  2832. if (typeof lineData.data.file !== 'string')
  2833. throw new Error('malformed file at line ' + i + ' -- needs page file="path"')
  2834. output.pages[lineData.data.id] = lineData.data.file
  2835. } else if (lineData.key === 'chars' || lineData.key === 'kernings') {
  2836. //... do nothing for these two ...
  2837. } else if (lineData.key === 'char') {
  2838. output.chars.push(lineData.data)
  2839. } else if (lineData.key === 'kerning') {
  2840. output.kernings.push(lineData.data)
  2841. } else {
  2842. output[lineData.key] = lineData.data
  2843. }
  2844. }
  2845. return output
  2846. }
  2847. function splitLine(line, idx) {
  2848. line = line.replace(/\t+/g, ' ').trim()
  2849. if (!line)
  2850. return null
  2851. var space = line.indexOf(' ')
  2852. if (space === -1)
  2853. throw new Error("no named row at line " + idx)
  2854. var key = line.substring(0, space)
  2855. line = line.substring(space + 1)
  2856. //clear "letter" field as it is non-standard and
  2857. //requires additional complexity to parse " / = symbols
  2858. line = line.replace(/letter=[\'\"]\S+[\'\"]/gi, '')
  2859. line = line.split("=")
  2860. line = line.map(function(str) {
  2861. return str.trim().match((/(".*?"|[^"\s]+)+(?=\s*|\s*$)/g))
  2862. })
  2863. var data = []
  2864. for (var i = 0; i < line.length; i++) {
  2865. var dt = line[i]
  2866. if (i === 0) {
  2867. data.push({
  2868. key: dt[0],
  2869. data: ""
  2870. })
  2871. } else if (i === line.length - 1) {
  2872. data[data.length - 1].data = parseData(dt[0])
  2873. } else {
  2874. data[data.length - 1].data = parseData(dt[0])
  2875. data.push({
  2876. key: dt[1],
  2877. data: ""
  2878. })
  2879. }
  2880. }
  2881. var out = {
  2882. key: key,
  2883. data: {}
  2884. }
  2885. data.forEach(function(v) {
  2886. out.data[v.key] = v.data;
  2887. })
  2888. return out
  2889. }
  2890. function parseData(data) {
  2891. if (!data || data.length === 0)
  2892. return ""
  2893. if (data.indexOf('"') === 0 || data.indexOf("'") === 0)
  2894. return data.substring(1, data.length - 1)
  2895. if (data.indexOf(',') !== -1)
  2896. return parseIntList(data)
  2897. return parseInt(data, 10)
  2898. }
  2899. function parseIntList(data) {
  2900. return data.split(',').map(function(val) {
  2901. return parseInt(val, 10)
  2902. })
  2903. }
  2904. },{}],27:[function(_dereq_,module,exports){
  2905. var HEADER = [66, 77, 70]
  2906. module.exports = function readBMFontBinary(buf) {
  2907. if (buf.length < 6)
  2908. throw new Error('invalid buffer length for BMFont')
  2909. var header = HEADER.every(function(byte, i) {
  2910. return buf.readUInt8(i) === byte
  2911. })
  2912. if (!header)
  2913. throw new Error('BMFont missing BMF byte header')
  2914. var i = 3
  2915. var vers = buf.readUInt8(i++)
  2916. if (vers > 3)
  2917. throw new Error('Only supports BMFont Binary v3 (BMFont App v1.10)')
  2918. var target = { kernings: [], chars: [] }
  2919. for (var b=0; b<5; b++)
  2920. i += readBlock(target, buf, i)
  2921. return target
  2922. }
  2923. function readBlock(target, buf, i) {
  2924. if (i > buf.length-1)
  2925. return 0
  2926. var blockID = buf.readUInt8(i++)
  2927. var blockSize = buf.readInt32LE(i)
  2928. i += 4
  2929. switch(blockID) {
  2930. case 1:
  2931. target.info = readInfo(buf, i)
  2932. break
  2933. case 2:
  2934. target.common = readCommon(buf, i)
  2935. break
  2936. case 3:
  2937. target.pages = readPages(buf, i, blockSize)
  2938. break
  2939. case 4:
  2940. target.chars = readChars(buf, i, blockSize)
  2941. break
  2942. case 5:
  2943. target.kernings = readKernings(buf, i, blockSize)
  2944. break
  2945. }
  2946. return 5 + blockSize
  2947. }
  2948. function readInfo(buf, i) {
  2949. var info = {}
  2950. info.size = buf.readInt16LE(i)
  2951. var bitField = buf.readUInt8(i+2)
  2952. info.smooth = (bitField >> 7) & 1
  2953. info.unicode = (bitField >> 6) & 1
  2954. info.italic = (bitField >> 5) & 1
  2955. info.bold = (bitField >> 4) & 1
  2956. //fixedHeight is only mentioned in binary spec
  2957. if ((bitField >> 3) & 1)
  2958. info.fixedHeight = 1
  2959. info.charset = buf.readUInt8(i+3) || ''
  2960. info.stretchH = buf.readUInt16LE(i+4)
  2961. info.aa = buf.readUInt8(i+6)
  2962. info.padding = [
  2963. buf.readInt8(i+7),
  2964. buf.readInt8(i+8),
  2965. buf.readInt8(i+9),
  2966. buf.readInt8(i+10)
  2967. ]
  2968. info.spacing = [
  2969. buf.readInt8(i+11),
  2970. buf.readInt8(i+12)
  2971. ]
  2972. info.outline = buf.readUInt8(i+13)
  2973. info.face = readStringNT(buf, i+14)
  2974. return info
  2975. }
  2976. function readCommon(buf, i) {
  2977. var common = {}
  2978. common.lineHeight = buf.readUInt16LE(i)
  2979. common.base = buf.readUInt16LE(i+2)
  2980. common.scaleW = buf.readUInt16LE(i+4)
  2981. common.scaleH = buf.readUInt16LE(i+6)
  2982. common.pages = buf.readUInt16LE(i+8)
  2983. var bitField = buf.readUInt8(i+10)
  2984. common.packed = 0
  2985. common.alphaChnl = buf.readUInt8(i+11)
  2986. common.redChnl = buf.readUInt8(i+12)
  2987. common.greenChnl = buf.readUInt8(i+13)
  2988. common.blueChnl = buf.readUInt8(i+14)
  2989. return common
  2990. }
  2991. function readPages(buf, i, size) {
  2992. var pages = []
  2993. var text = readNameNT(buf, i)
  2994. var len = text.length+1
  2995. var count = size / len
  2996. for (var c=0; c<count; c++) {
  2997. pages[c] = buf.slice(i, i+text.length).toString('utf8')
  2998. i += len
  2999. }
  3000. return pages
  3001. }
  3002. function readChars(buf, i, blockSize) {
  3003. var chars = []
  3004. var count = blockSize / 20
  3005. for (var c=0; c<count; c++) {
  3006. var char = {}
  3007. var off = c*20
  3008. char.id = buf.readUInt32LE(i + 0 + off)
  3009. char.x = buf.readUInt16LE(i + 4 + off)
  3010. char.y = buf.readUInt16LE(i + 6 + off)
  3011. char.width = buf.readUInt16LE(i + 8 + off)
  3012. char.height = buf.readUInt16LE(i + 10 + off)
  3013. char.xoffset = buf.readInt16LE(i + 12 + off)
  3014. char.yoffset = buf.readInt16LE(i + 14 + off)
  3015. char.xadvance = buf.readInt16LE(i + 16 + off)
  3016. char.page = buf.readUInt8(i + 18 + off)
  3017. char.chnl = buf.readUInt8(i + 19 + off)
  3018. chars[c] = char
  3019. }
  3020. return chars
  3021. }
  3022. function readKernings(buf, i, blockSize) {
  3023. var kernings = []
  3024. var count = blockSize / 10
  3025. for (var c=0; c<count; c++) {
  3026. var kern = {}
  3027. var off = c*10
  3028. kern.first = buf.readUInt32LE(i + 0 + off)
  3029. kern.second = buf.readUInt32LE(i + 4 + off)
  3030. kern.amount = buf.readInt16LE(i + 8 + off)
  3031. kernings[c] = kern
  3032. }
  3033. return kernings
  3034. }
  3035. function readNameNT(buf, offset) {
  3036. var pos=offset
  3037. for (; pos<buf.length; pos++) {
  3038. if (buf[pos] === 0x00)
  3039. break
  3040. }
  3041. return buf.slice(offset, pos)
  3042. }
  3043. function readStringNT(buf, offset) {
  3044. return readNameNT(buf, offset).toString('utf8')
  3045. }
  3046. },{}],28:[function(_dereq_,module,exports){
  3047. var parseAttributes = _dereq_('./parse-attribs')
  3048. var parseFromString = _dereq_('xml-parse-from-string')
  3049. //In some cases element.attribute.nodeName can return
  3050. //all lowercase values.. so we need to map them to the correct
  3051. //case
  3052. var NAME_MAP = {
  3053. scaleh: 'scaleH',
  3054. scalew: 'scaleW',
  3055. stretchh: 'stretchH',
  3056. lineheight: 'lineHeight',
  3057. alphachnl: 'alphaChnl',
  3058. redchnl: 'redChnl',
  3059. greenchnl: 'greenChnl',
  3060. bluechnl: 'blueChnl'
  3061. }
  3062. module.exports = function parse(data) {
  3063. data = data.toString()
  3064. var xmlRoot = parseFromString(data)
  3065. var output = {
  3066. pages: [],
  3067. chars: [],
  3068. kernings: []
  3069. }
  3070. //get config settings
  3071. ;['info', 'common'].forEach(function(key) {
  3072. var element = xmlRoot.getElementsByTagName(key)[0]
  3073. if (element)
  3074. output[key] = parseAttributes(getAttribs(element))
  3075. })
  3076. //get page info
  3077. var pageRoot = xmlRoot.getElementsByTagName('pages')[0]
  3078. if (!pageRoot)
  3079. throw new Error('malformed file -- no <pages> element')
  3080. var pages = pageRoot.getElementsByTagName('page')
  3081. for (var i=0; i<pages.length; i++) {
  3082. var p = pages[i]
  3083. var id = parseInt(p.getAttribute('id'), 10)
  3084. var file = p.getAttribute('file')
  3085. if (isNaN(id))
  3086. throw new Error('malformed file -- page "id" attribute is NaN')
  3087. if (!file)
  3088. throw new Error('malformed file -- needs page "file" attribute')
  3089. output.pages[parseInt(id, 10)] = file
  3090. }
  3091. //get kernings / chars
  3092. ;['chars', 'kernings'].forEach(function(key) {
  3093. var element = xmlRoot.getElementsByTagName(key)[0]
  3094. if (!element)
  3095. return
  3096. var childTag = key.substring(0, key.length-1)
  3097. var children = element.getElementsByTagName(childTag)
  3098. for (var i=0; i<children.length; i++) {
  3099. var child = children[i]
  3100. output[key].push(parseAttributes(getAttribs(child)))
  3101. }
  3102. })
  3103. return output
  3104. }
  3105. function getAttribs(element) {
  3106. var attribs = getAttribList(element)
  3107. return attribs.reduce(function(dict, attrib) {
  3108. var key = mapName(attrib.nodeName)
  3109. dict[key] = attrib.nodeValue
  3110. return dict
  3111. }, {})
  3112. }
  3113. function getAttribList(element) {
  3114. //IE8+ and modern browsers
  3115. var attribs = []
  3116. for (var i=0; i<element.attributes.length; i++)
  3117. attribs.push(element.attributes[i])
  3118. return attribs
  3119. }
  3120. function mapName(nodeName) {
  3121. return NAME_MAP[nodeName.toLowerCase()] || nodeName
  3122. }
  3123. },{"./parse-attribs":29,"xml-parse-from-string":49}],29:[function(_dereq_,module,exports){
  3124. //Some versions of GlyphDesigner have a typo
  3125. //that causes some bugs with parsing.
  3126. //Need to confirm with recent version of the software
  3127. //to see whether this is still an issue or not.
  3128. var GLYPH_DESIGNER_ERROR = 'chasrset'
  3129. module.exports = function parseAttributes(obj) {
  3130. if (GLYPH_DESIGNER_ERROR in obj) {
  3131. obj['charset'] = obj[GLYPH_DESIGNER_ERROR]
  3132. delete obj[GLYPH_DESIGNER_ERROR]
  3133. }
  3134. for (var k in obj) {
  3135. if (k === 'face' || k === 'charset')
  3136. continue
  3137. else if (k === 'padding' || k === 'spacing')
  3138. obj[k] = parseIntList(obj[k])
  3139. else
  3140. obj[k] = parseInt(obj[k], 10)
  3141. }
  3142. return obj
  3143. }
  3144. function parseIntList(data) {
  3145. return data.split(',').map(function(val) {
  3146. return parseInt(val, 10)
  3147. })
  3148. }
  3149. },{}],30:[function(_dereq_,module,exports){
  3150. var trim = _dereq_('trim')
  3151. , forEach = _dereq_('for-each')
  3152. , isArray = function(arg) {
  3153. return Object.prototype.toString.call(arg) === '[object Array]';
  3154. }
  3155. module.exports = function (headers) {
  3156. if (!headers)
  3157. return {}
  3158. var result = {}
  3159. forEach(
  3160. trim(headers).split('\n')
  3161. , function (row) {
  3162. var index = row.indexOf(':')
  3163. , key = trim(row.slice(0, index)).toLowerCase()
  3164. , value = trim(row.slice(index + 1))
  3165. if (typeof(result[key]) === 'undefined') {
  3166. result[key] = value
  3167. } else if (isArray(result[key])) {
  3168. result[key].push(value)
  3169. } else {
  3170. result[key] = [ result[key], value ]
  3171. }
  3172. }
  3173. )
  3174. return result
  3175. }
  3176. },{"for-each":14,"trim":45}],31:[function(_dereq_,module,exports){
  3177. (function (global){
  3178. var performance = global.performance || {};
  3179. var present = (function () {
  3180. var names = ['now', 'webkitNow', 'msNow', 'mozNow', 'oNow'];
  3181. while (names.length) {
  3182. var name = names.shift();
  3183. if (name in performance) {
  3184. return performance[name].bind(performance);
  3185. }
  3186. }
  3187. var dateNow = Date.now || function () { return new Date().getTime(); };
  3188. var navigationStart = (performance.timing || {}).navigationStart || dateNow();
  3189. return function () {
  3190. return dateNow() - navigationStart;
  3191. };
  3192. }());
  3193. present.performanceNow = performance.now;
  3194. present.noConflict = function () {
  3195. performance.now = present.performanceNow;
  3196. };
  3197. present.conflict = function () {
  3198. performance.now = present;
  3199. };
  3200. present.conflict();
  3201. module.exports = present;
  3202. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  3203. },{}],32:[function(_dereq_,module,exports){
  3204. // shim for using process in browser
  3205. var process = module.exports = {};
  3206. // cached from whatever global is present so that test runners that stub it
  3207. // don't break things. But we need to wrap it in a try catch in case it is
  3208. // wrapped in strict mode code which doesn't define any globals. It's inside a
  3209. // function because try/catches deoptimize in certain engines.
  3210. var cachedSetTimeout;
  3211. var cachedClearTimeout;
  3212. function defaultSetTimout() {
  3213. throw new Error('setTimeout has not been defined');
  3214. }
  3215. function defaultClearTimeout () {
  3216. throw new Error('clearTimeout has not been defined');
  3217. }
  3218. (function () {
  3219. try {
  3220. if (typeof setTimeout === 'function') {
  3221. cachedSetTimeout = setTimeout;
  3222. } else {
  3223. cachedSetTimeout = defaultSetTimout;
  3224. }
  3225. } catch (e) {
  3226. cachedSetTimeout = defaultSetTimout;
  3227. }
  3228. try {
  3229. if (typeof clearTimeout === 'function') {
  3230. cachedClearTimeout = clearTimeout;
  3231. } else {
  3232. cachedClearTimeout = defaultClearTimeout;
  3233. }
  3234. } catch (e) {
  3235. cachedClearTimeout = defaultClearTimeout;
  3236. }
  3237. } ())
  3238. function runTimeout(fun) {
  3239. if (cachedSetTimeout === setTimeout) {
  3240. //normal enviroments in sane situations
  3241. return setTimeout(fun, 0);
  3242. }
  3243. // if setTimeout wasn't available but was latter defined
  3244. if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
  3245. cachedSetTimeout = setTimeout;
  3246. return setTimeout(fun, 0);
  3247. }
  3248. try {
  3249. // when when somebody has screwed with setTimeout but no I.E. maddness
  3250. return cachedSetTimeout(fun, 0);
  3251. } catch(e){
  3252. try {
  3253. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  3254. return cachedSetTimeout.call(null, fun, 0);
  3255. } catch(e){
  3256. // 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
  3257. return cachedSetTimeout.call(this, fun, 0);
  3258. }
  3259. }
  3260. }
  3261. function runClearTimeout(marker) {
  3262. if (cachedClearTimeout === clearTimeout) {
  3263. //normal enviroments in sane situations
  3264. return clearTimeout(marker);
  3265. }
  3266. // if clearTimeout wasn't available but was latter defined
  3267. if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
  3268. cachedClearTimeout = clearTimeout;
  3269. return clearTimeout(marker);
  3270. }
  3271. try {
  3272. // when when somebody has screwed with setTimeout but no I.E. maddness
  3273. return cachedClearTimeout(marker);
  3274. } catch (e){
  3275. try {
  3276. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  3277. return cachedClearTimeout.call(null, marker);
  3278. } catch (e){
  3279. // 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.
  3280. // Some versions of I.E. have different rules for clearTimeout vs setTimeout
  3281. return cachedClearTimeout.call(this, marker);
  3282. }
  3283. }
  3284. }
  3285. var queue = [];
  3286. var draining = false;
  3287. var currentQueue;
  3288. var queueIndex = -1;
  3289. function cleanUpNextTick() {
  3290. if (!draining || !currentQueue) {
  3291. return;
  3292. }
  3293. draining = false;
  3294. if (currentQueue.length) {
  3295. queue = currentQueue.concat(queue);
  3296. } else {
  3297. queueIndex = -1;
  3298. }
  3299. if (queue.length) {
  3300. drainQueue();
  3301. }
  3302. }
  3303. function drainQueue() {
  3304. if (draining) {
  3305. return;
  3306. }
  3307. var timeout = runTimeout(cleanUpNextTick);
  3308. draining = true;
  3309. var len = queue.length;
  3310. while(len) {
  3311. currentQueue = queue;
  3312. queue = [];
  3313. while (++queueIndex < len) {
  3314. if (currentQueue) {
  3315. currentQueue[queueIndex].run();
  3316. }
  3317. }
  3318. queueIndex = -1;
  3319. len = queue.length;
  3320. }
  3321. currentQueue = null;
  3322. draining = false;
  3323. runClearTimeout(timeout);
  3324. }
  3325. process.nextTick = function (fun) {
  3326. var args = new Array(arguments.length - 1);
  3327. if (arguments.length > 1) {
  3328. for (var i = 1; i < arguments.length; i++) {
  3329. args[i - 1] = arguments[i];
  3330. }
  3331. }
  3332. queue.push(new Item(fun, args));
  3333. if (queue.length === 1 && !draining) {
  3334. runTimeout(drainQueue);
  3335. }
  3336. };
  3337. // v8 likes predictible objects
  3338. function Item(fun, array) {
  3339. this.fun = fun;
  3340. this.array = array;
  3341. }
  3342. Item.prototype.run = function () {
  3343. this.fun.apply(null, this.array);
  3344. };
  3345. process.title = 'browser';
  3346. process.browser = true;
  3347. process.env = {};
  3348. process.argv = [];
  3349. process.version = ''; // empty string to avoid regexp issues
  3350. process.versions = {};
  3351. function noop() {}
  3352. process.on = noop;
  3353. process.addListener = noop;
  3354. process.once = noop;
  3355. process.off = noop;
  3356. process.removeListener = noop;
  3357. process.removeAllListeners = noop;
  3358. process.emit = noop;
  3359. process.prependListener = noop;
  3360. process.prependOnceListener = noop;
  3361. process.listeners = function (name) { return [] }
  3362. process.binding = function (name) {
  3363. throw new Error('process.binding is not supported');
  3364. };
  3365. process.cwd = function () { return '/' };
  3366. process.chdir = function (dir) {
  3367. throw new Error('process.chdir is not supported');
  3368. };
  3369. process.umask = function() { return 0; };
  3370. },{}],33:[function(_dereq_,module,exports){
  3371. (function(root) {
  3372. // Store setTimeout reference so promise-polyfill will be unaffected by
  3373. // other code modifying setTimeout (like sinon.useFakeTimers())
  3374. var setTimeoutFunc = setTimeout;
  3375. // Use polyfill for setImmediate for performance gains
  3376. var asap = (typeof setImmediate === 'function' && setImmediate) ||
  3377. function(fn) { setTimeoutFunc(fn, 1); };
  3378. // Polyfill for Function.prototype.bind
  3379. function bind(fn, thisArg) {
  3380. return function() {
  3381. fn.apply(thisArg, arguments);
  3382. }
  3383. }
  3384. var isArray = Array.isArray || function(value) { return Object.prototype.toString.call(value) === "[object Array]" };
  3385. function Promise(fn) {
  3386. if (typeof this !== 'object') throw new TypeError('Promises must be constructed via new');
  3387. if (typeof fn !== 'function') throw new TypeError('not a function');
  3388. this._state = null;
  3389. this._value = null;
  3390. this._deferreds = []
  3391. doResolve(fn, bind(resolve, this), bind(reject, this))
  3392. }
  3393. function handle(deferred) {
  3394. var me = this;
  3395. if (this._state === null) {
  3396. this._deferreds.push(deferred);
  3397. return
  3398. }
  3399. asap(function() {
  3400. var cb = me._state ? deferred.onFulfilled : deferred.onRejected
  3401. if (cb === null) {
  3402. (me._state ? deferred.resolve : deferred.reject)(me._value);
  3403. return;
  3404. }
  3405. var ret;
  3406. try {
  3407. ret = cb(me._value);
  3408. }
  3409. catch (e) {
  3410. deferred.reject(e);
  3411. return;
  3412. }
  3413. deferred.resolve(ret);
  3414. })
  3415. }
  3416. function resolve(newValue) {
  3417. try { //Promise Resolution Procedure: https://github.com/promises-aplus/promises-spec#the-promise-resolution-procedure
  3418. if (newValue === this) throw new TypeError('A promise cannot be resolved with itself.');
  3419. if (newValue && (typeof newValue === 'object' || typeof newValue === 'function')) {
  3420. var then = newValue.then;
  3421. if (typeof then === 'function') {
  3422. doResolve(bind(then, newValue), bind(resolve, this), bind(reject, this));
  3423. return;
  3424. }
  3425. }
  3426. this._state = true;
  3427. this._value = newValue;
  3428. finale.call(this);
  3429. } catch (e) { reject.call(this, e); }
  3430. }
  3431. function reject(newValue) {
  3432. this._state = false;
  3433. this._value = newValue;
  3434. finale.call(this);
  3435. }
  3436. function finale() {
  3437. for (var i = 0, len = this._deferreds.length; i < len; i++) {
  3438. handle.call(this, this._deferreds[i]);
  3439. }
  3440. this._deferreds = null;
  3441. }
  3442. function Handler(onFulfilled, onRejected, resolve, reject){
  3443. this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null;
  3444. this.onRejected = typeof onRejected === 'function' ? onRejected : null;
  3445. this.resolve = resolve;
  3446. this.reject = reject;
  3447. }
  3448. /**
  3449. * Take a potentially misbehaving resolver function and make sure
  3450. * onFulfilled and onRejected are only called once.
  3451. *
  3452. * Makes no guarantees about asynchrony.
  3453. */
  3454. function doResolve(fn, onFulfilled, onRejected) {
  3455. var done = false;
  3456. try {
  3457. fn(function (value) {
  3458. if (done) return;
  3459. done = true;
  3460. onFulfilled(value);
  3461. }, function (reason) {
  3462. if (done) return;
  3463. done = true;
  3464. onRejected(reason);
  3465. })
  3466. } catch (ex) {
  3467. if (done) return;
  3468. done = true;
  3469. onRejected(ex);
  3470. }
  3471. }
  3472. Promise.prototype['catch'] = function (onRejected) {
  3473. return this.then(null, onRejected);
  3474. };
  3475. Promise.prototype.then = function(onFulfilled, onRejected) {
  3476. var me = this;
  3477. return new Promise(function(resolve, reject) {
  3478. handle.call(me, new Handler(onFulfilled, onRejected, resolve, reject));
  3479. })
  3480. };
  3481. Promise.all = function () {
  3482. var args = Array.prototype.slice.call(arguments.length === 1 && isArray(arguments[0]) ? arguments[0] : arguments);
  3483. return new Promise(function (resolve, reject) {
  3484. if (args.length === 0) return resolve([]);
  3485. var remaining = args.length;
  3486. function res(i, val) {
  3487. try {
  3488. if (val && (typeof val === 'object' || typeof val === 'function')) {
  3489. var then = val.then;
  3490. if (typeof then === 'function') {
  3491. then.call(val, function (val) { res(i, val) }, reject);
  3492. return;
  3493. }
  3494. }
  3495. args[i] = val;
  3496. if (--remaining === 0) {
  3497. resolve(args);
  3498. }
  3499. } catch (ex) {
  3500. reject(ex);
  3501. }
  3502. }
  3503. for (var i = 0; i < args.length; i++) {
  3504. res(i, args[i]);
  3505. }
  3506. });
  3507. };
  3508. Promise.resolve = function (value) {
  3509. if (value && typeof value === 'object' && value.constructor === Promise) {
  3510. return value;
  3511. }
  3512. return new Promise(function (resolve) {
  3513. resolve(value);
  3514. });
  3515. };
  3516. Promise.reject = function (value) {
  3517. return new Promise(function (resolve, reject) {
  3518. reject(value);
  3519. });
  3520. };
  3521. Promise.race = function (values) {
  3522. return new Promise(function (resolve, reject) {
  3523. for(var i = 0, len = values.length; i < len; i++) {
  3524. values[i].then(resolve, reject);
  3525. }
  3526. });
  3527. };
  3528. /**
  3529. * Set the immediate function to execute callbacks
  3530. * @param fn {function} Function to execute
  3531. * @private
  3532. */
  3533. Promise._setImmediateFn = function _setImmediateFn(fn) {
  3534. asap = fn;
  3535. };
  3536. if (typeof module !== 'undefined' && module.exports) {
  3537. module.exports = Promise;
  3538. } else if (!root.Promise) {
  3539. root.Promise = Promise;
  3540. }
  3541. })(this);
  3542. },{}],34:[function(_dereq_,module,exports){
  3543. var dtype = _dereq_('dtype')
  3544. var anArray = _dereq_('an-array')
  3545. var isBuffer = _dereq_('is-buffer')
  3546. var CW = [0, 2, 3]
  3547. var CCW = [2, 1, 3]
  3548. module.exports = function createQuadElements(array, opt) {
  3549. //if user didn't specify an output array
  3550. if (!array || !(anArray(array) || isBuffer(array))) {
  3551. opt = array || {}
  3552. array = null
  3553. }
  3554. if (typeof opt === 'number') //backwards-compatible
  3555. opt = { count: opt }
  3556. else
  3557. opt = opt || {}
  3558. var type = typeof opt.type === 'string' ? opt.type : 'uint16'
  3559. var count = typeof opt.count === 'number' ? opt.count : 1
  3560. var start = (opt.start || 0)
  3561. var dir = opt.clockwise !== false ? CW : CCW,
  3562. a = dir[0],
  3563. b = dir[1],
  3564. c = dir[2]
  3565. var numIndices = count * 6
  3566. var indices = array || new (dtype(type))(numIndices)
  3567. for (var i = 0, j = 0; i < numIndices; i += 6, j += 4) {
  3568. var x = i + start
  3569. indices[x + 0] = j + 0
  3570. indices[x + 1] = j + 1
  3571. indices[x + 2] = j + 2
  3572. indices[x + 3] = j + a
  3573. indices[x + 4] = j + b
  3574. indices[x + 5] = j + c
  3575. }
  3576. return indices
  3577. }
  3578. },{"an-array":1,"dtype":12,"is-buffer":18}],35:[function(_dereq_,module,exports){
  3579. /*
  3580. * anime.js v3.0.0
  3581. * (c) 2019 Julian Garnier
  3582. * Released under the MIT license
  3583. * animejs.com
  3584. */
  3585. 'use strict';
  3586. // Defaults
  3587. var defaultInstanceSettings = {
  3588. update: null,
  3589. begin: null,
  3590. loopBegin: null,
  3591. changeBegin: null,
  3592. change: null,
  3593. changeComplete: null,
  3594. loopComplete: null,
  3595. complete: null,
  3596. loop: 1,
  3597. direction: 'normal',
  3598. autoplay: true,
  3599. timelineOffset: 0
  3600. };
  3601. var defaultTweenSettings = {
  3602. duration: 1000,
  3603. delay: 0,
  3604. endDelay: 0,
  3605. easing: 'easeOutElastic(1, .5)',
  3606. round: 0
  3607. };
  3608. var validTransforms = ['translateX', 'translateY', 'translateZ', 'rotate', 'rotateX', 'rotateY', 'rotateZ', 'scale', 'scaleX', 'scaleY', 'scaleZ', 'skew', 'skewX', 'skewY', 'perspective'];
  3609. // Caching
  3610. var cache = {
  3611. CSS: {},
  3612. springs: {}
  3613. };
  3614. // Utils
  3615. function minMax(val, min, max) {
  3616. return Math.min(Math.max(val, min), max);
  3617. }
  3618. function stringContains(str, text) {
  3619. return str.indexOf(text) > -1;
  3620. }
  3621. function applyArguments(func, args) {
  3622. return func.apply(null, args);
  3623. }
  3624. var hexRegex = /(^#[0-9A-F]{6}$)|(^#[0-9A-F]{3}$)/i;
  3625. var rgbPrefixRegex = /^rgb/;
  3626. var hslRegex = /^hsl/;
  3627. var is = {
  3628. arr: function (a) { return Array.isArray(a); },
  3629. obj: function (a) { return stringContains(Object.prototype.toString.call(a), 'Object'); },
  3630. pth: function (a) { return is.obj(a) && a.hasOwnProperty('totalLength'); },
  3631. svg: function (a) { return a instanceof SVGElement; },
  3632. inp: function (a) { return a instanceof HTMLInputElement; },
  3633. dom: function (a) { return a.nodeType || is.svg(a); },
  3634. str: function (a) { return typeof a === 'string'; },
  3635. fnc: function (a) { return typeof a === 'function'; },
  3636. und: function (a) { return typeof a === 'undefined'; },
  3637. hex: function (a) { return hexRegex.test(a); },
  3638. rgb: function (a) { return rgbPrefixRegex.test(a); },
  3639. hsl: function (a) { return hslRegex.test(a); },
  3640. col: function (a) { return (is.hex(a) || is.rgb(a) || is.hsl(a)); },
  3641. key: function (a) { return !defaultInstanceSettings.hasOwnProperty(a) && !defaultTweenSettings.hasOwnProperty(a) && a !== 'targets' && a !== 'keyframes'; }
  3642. };
  3643. // Easings
  3644. var easingFunctionRegex = /\(([^)]+)\)/;
  3645. function parseEasingParameters(string) {
  3646. var match = easingFunctionRegex.exec(string);
  3647. return match ? match[1].split(',').map(function (p) { return parseFloat(p); }) : [];
  3648. }
  3649. // Spring solver inspired by Webkit Copyright © 2016 Apple Inc. All rights reserved. https://webkit.org/demos/spring/spring.js
  3650. function spring(string, duration) {
  3651. var params = parseEasingParameters(string);
  3652. var mass = minMax(is.und(params[0]) ? 1 : params[0], .1, 100);
  3653. var stiffness = minMax(is.und(params[1]) ? 100 : params[1], .1, 100);
  3654. var damping = minMax(is.und(params[2]) ? 10 : params[2], .1, 100);
  3655. var velocity = minMax(is.und(params[3]) ? 0 : params[3], .1, 100);
  3656. var w0 = Math.sqrt(stiffness / mass);
  3657. var zeta = damping / (2 * Math.sqrt(stiffness * mass));
  3658. var wd = zeta < 1 ? w0 * Math.sqrt(1 - zeta * zeta) : 0;
  3659. var a = 1;
  3660. var b = zeta < 1 ? (zeta * w0 + -velocity) / wd : -velocity + w0;
  3661. function solver(t) {
  3662. var progress = duration ? (duration * t) / 1000 : t;
  3663. if (zeta < 1) {
  3664. progress = Math.exp(-progress * zeta * w0) * (a * Math.cos(wd * progress) + b * Math.sin(wd * progress));
  3665. } else {
  3666. progress = (a + b * progress) * Math.exp(-progress * w0);
  3667. }
  3668. if (t === 0 || t === 1) { return t; }
  3669. return 1 - progress;
  3670. }
  3671. function getDuration() {
  3672. var cached = cache.springs[string];
  3673. if (cached) { return cached; }
  3674. var frame = 1/6;
  3675. var elapsed = 0;
  3676. var rest = 0;
  3677. while(true) {
  3678. elapsed += frame;
  3679. if (solver(elapsed) === 1) {
  3680. rest++;
  3681. if (rest >= 16) { break; }
  3682. } else {
  3683. rest = 0;
  3684. }
  3685. }
  3686. var duration = elapsed * frame * 1000;
  3687. cache.springs[string] = duration;
  3688. return duration;
  3689. }
  3690. return duration ? solver : getDuration;
  3691. }
  3692. // Elastic easing adapted from jQueryUI http://api.jqueryui.com/easings/
  3693. function elastic(amplitude, period) {
  3694. if ( amplitude === void 0 ) amplitude = 1;
  3695. if ( period === void 0 ) period = .5;
  3696. var a = minMax(amplitude, 1, 10);
  3697. var p = minMax(period, .1, 2);
  3698. return function (t) {
  3699. return (t === 0 || t === 1) ? t :
  3700. -a * Math.pow(2, 10 * (t - 1)) * Math.sin((((t - 1) - (p / (Math.PI * 2) * Math.asin(1 / a))) * (Math.PI * 2)) / p);
  3701. }
  3702. }
  3703. // Basic steps easing implementation https://developer.mozilla.org/fr/docs/Web/CSS/transition-timing-function
  3704. function steps(steps) {
  3705. if ( steps === void 0 ) steps = 10;
  3706. return function (t) { return Math.round(t * steps) * (1 / steps); };
  3707. }
  3708. // BezierEasing https://github.com/gre/bezier-easing
  3709. var bezier = (function () {
  3710. var kSplineTableSize = 11;
  3711. var kSampleStepSize = 1.0 / (kSplineTableSize - 1.0);
  3712. function A(aA1, aA2) { return 1.0 - 3.0 * aA2 + 3.0 * aA1 }
  3713. function B(aA1, aA2) { return 3.0 * aA2 - 6.0 * aA1 }
  3714. function C(aA1) { return 3.0 * aA1 }
  3715. function calcBezier(aT, aA1, aA2) { return ((A(aA1, aA2) * aT + B(aA1, aA2)) * aT + C(aA1)) * aT }
  3716. function getSlope(aT, aA1, aA2) { return 3.0 * A(aA1, aA2) * aT * aT + 2.0 * B(aA1, aA2) * aT + C(aA1) }
  3717. function binarySubdivide(aX, aA, aB, mX1, mX2) {
  3718. var currentX, currentT, i = 0;
  3719. do {
  3720. currentT = aA + (aB - aA) / 2.0;
  3721. currentX = calcBezier(currentT, mX1, mX2) - aX;
  3722. if (currentX > 0.0) { aB = currentT; } else { aA = currentT; }
  3723. } while (Math.abs(currentX) > 0.0000001 && ++i < 10);
  3724. return currentT;
  3725. }
  3726. function newtonRaphsonIterate(aX, aGuessT, mX1, mX2) {
  3727. for (var i = 0; i < 4; ++i) {
  3728. var currentSlope = getSlope(aGuessT, mX1, mX2);
  3729. if (currentSlope === 0.0) { return aGuessT; }
  3730. var currentX = calcBezier(aGuessT, mX1, mX2) - aX;
  3731. aGuessT -= currentX / currentSlope;
  3732. }
  3733. return aGuessT;
  3734. }
  3735. function bezier(mX1, mY1, mX2, mY2) {
  3736. if (!(0 <= mX1 && mX1 <= 1 && 0 <= mX2 && mX2 <= 1)) { return; }
  3737. var sampleValues = new Float32Array(kSplineTableSize);
  3738. if (mX1 !== mY1 || mX2 !== mY2) {
  3739. for (var i = 0; i < kSplineTableSize; ++i) {
  3740. sampleValues[i] = calcBezier(i * kSampleStepSize, mX1, mX2);
  3741. }
  3742. }
  3743. function getTForX(aX) {
  3744. var intervalStart = 0;
  3745. var currentSample = 1;
  3746. var lastSample = kSplineTableSize - 1;
  3747. for (; currentSample !== lastSample && sampleValues[currentSample] <= aX; ++currentSample) {
  3748. intervalStart += kSampleStepSize;
  3749. }
  3750. --currentSample;
  3751. var dist = (aX - sampleValues[currentSample]) / (sampleValues[currentSample + 1] - sampleValues[currentSample]);
  3752. var guessForT = intervalStart + dist * kSampleStepSize;
  3753. var initialSlope = getSlope(guessForT, mX1, mX2);
  3754. if (initialSlope >= 0.001) {
  3755. return newtonRaphsonIterate(aX, guessForT, mX1, mX2);
  3756. } else if (initialSlope === 0.0) {
  3757. return guessForT;
  3758. } else {
  3759. return binarySubdivide(aX, intervalStart, intervalStart + kSampleStepSize, mX1, mX2);
  3760. }
  3761. }
  3762. return function (x) {
  3763. if (mX1 === mY1 && mX2 === mY2) { return x; }
  3764. if (x === 0 || x === 1) { return x; }
  3765. return calcBezier(getTForX(x), mY1, mY2);
  3766. }
  3767. }
  3768. return bezier;
  3769. })();
  3770. var penner = (function () {
  3771. var names = ['Quad', 'Cubic', 'Quart', 'Quint', 'Sine', 'Expo', 'Circ', 'Back', 'Elastic'];
  3772. // Approximated Penner equations http://matthewlein.com/ceaser/
  3773. var curves = {
  3774. In: [
  3775. [0.550, 0.085, 0.680, 0.530], /* inQuad */
  3776. [0.550, 0.055, 0.675, 0.190], /* inCubic */
  3777. [0.895, 0.030, 0.685, 0.220], /* inQuart */
  3778. [0.755, 0.050, 0.855, 0.060], /* inQuint */
  3779. [0.470, 0.000, 0.745, 0.715], /* inSine */
  3780. [0.950, 0.050, 0.795, 0.035], /* inExpo */
  3781. [0.600, 0.040, 0.980, 0.335], /* inCirc */
  3782. [0.600,-0.280, 0.735, 0.045], /* inBack */
  3783. elastic /* inElastic */
  3784. ],
  3785. Out: [
  3786. [0.250, 0.460, 0.450, 0.940], /* outQuad */
  3787. [0.215, 0.610, 0.355, 1.000], /* outCubic */
  3788. [0.165, 0.840, 0.440, 1.000], /* outQuart */
  3789. [0.230, 1.000, 0.320, 1.000], /* outQuint */
  3790. [0.390, 0.575, 0.565, 1.000], /* outSine */
  3791. [0.190, 1.000, 0.220, 1.000], /* outExpo */
  3792. [0.075, 0.820, 0.165, 1.000], /* outCirc */
  3793. [0.175, 0.885, 0.320, 1.275], /* outBack */
  3794. function (a, p) { return function (t) { return 1 - elastic(a, p)(1 - t); }; } /* outElastic */
  3795. ],
  3796. InOut: [
  3797. [0.455, 0.030, 0.515, 0.955], /* inOutQuad */
  3798. [0.645, 0.045, 0.355, 1.000], /* inOutCubic */
  3799. [0.770, 0.000, 0.175, 1.000], /* inOutQuart */
  3800. [0.860, 0.000, 0.070, 1.000], /* inOutQuint */
  3801. [0.445, 0.050, 0.550, 0.950], /* inOutSine */
  3802. [1.000, 0.000, 0.000, 1.000], /* inOutExpo */
  3803. [0.785, 0.135, 0.150, 0.860], /* inOutCirc */
  3804. [0.680,-0.550, 0.265, 1.550], /* inOutBack */
  3805. function (a, p) { return function (t) { return t < .5 ? elastic(a, p)(t * 2) / 2 : 1 - elastic(a, p)(t * -2 + 2) / 2; }; } /* inOutElastic */
  3806. ]
  3807. };
  3808. var eases = {
  3809. linear: [0.250, 0.250, 0.750, 0.750]
  3810. };
  3811. for (var coords in curves) {
  3812. for (var i = 0, len = curves[coords].length; i < len; i++) {
  3813. eases['ease'+coords+names[i]] = curves[coords][i];
  3814. }
  3815. }
  3816. return eases;
  3817. })();
  3818. function parseEasings(easing, duration) {
  3819. if (is.fnc(easing)) { return easing; }
  3820. var name = easing.split('(')[0];
  3821. var ease = penner[name];
  3822. var args = parseEasingParameters(easing);
  3823. switch (name) {
  3824. case 'spring' : return spring(easing, duration);
  3825. case 'cubicBezier' : return applyArguments(bezier, args);
  3826. case 'steps' : return applyArguments(steps, args);
  3827. default : return is.fnc(ease) ? applyArguments(ease, args) : applyArguments(bezier, ease);
  3828. }
  3829. }
  3830. // Strings
  3831. function selectString(str) {
  3832. try {
  3833. var nodes = document.querySelectorAll(str);
  3834. return nodes;
  3835. } catch(e) {
  3836. return;
  3837. }
  3838. }
  3839. // Arrays
  3840. var auxArrayFilter = [];
  3841. function filterArray(arr, callback) {
  3842. var result = auxArrayFilter;
  3843. var len = arr.length;
  3844. var thisArg = arguments.length >= 2 ? arguments[1] : void 0;
  3845. for (var i = 0; i < len; i++) {
  3846. if (i in arr) {
  3847. var val = arr[i];
  3848. if (callback.call(thisArg, val, i, arr)) {
  3849. result.push(val);
  3850. }
  3851. }
  3852. }
  3853. // arr turns into the auxArray and we return the previously aux array.
  3854. auxArrayFilter = arr;
  3855. auxArrayFilter.length = 0;
  3856. return result;
  3857. }
  3858. var auxArrayFlatten = [];
  3859. function flattenArray(arr) {
  3860. if (!arr.length) { return arr; }
  3861. var result = auxArrayFlatten;
  3862. var node = arr.pop();
  3863. do {
  3864. if (node.constructor === Array) {
  3865. for (var i = 0; i < node.length; i++) {
  3866. arr.push(node[i]);
  3867. }
  3868. } else {
  3869. result.push(node);
  3870. }
  3871. } while (arr.length && (node = arr.pop()) !== undefined);
  3872. result.reverse(); // Reverse result to restore the original order.
  3873. // arr turns into the auxArray and we return the previously aux array.
  3874. auxArrayFlatten = arr;
  3875. auxArrayFilter.length = 0;
  3876. return result;
  3877. }
  3878. function toArray(o) {
  3879. if (is.arr(o)) { return o; }
  3880. if (is.str(o)) { o = selectString(o) || o; }
  3881. if (o instanceof NodeList || o instanceof HTMLCollection) { return [].slice.call(o); }
  3882. return [o];
  3883. }
  3884. function arrayContains(arr, val) {
  3885. return arr.some(function (a) { return a === val; });
  3886. }
  3887. // Objects
  3888. function cloneObject(o) {
  3889. var clone = {};
  3890. for (var p in o) { clone[p] = o[p]; }
  3891. return clone;
  3892. }
  3893. function replaceObjectProps(o1, o2) {
  3894. var o = cloneObject(o1);
  3895. for (var p in o1) { o[p] = o2.hasOwnProperty(p) ? o2[p] : o1[p]; }
  3896. return o;
  3897. }
  3898. function mergeObjects(o1, o2) {
  3899. var o = cloneObject(o1);
  3900. for (var p in o2) { o[p] = is.und(o1[p]) ? o2[p] : o1[p]; }
  3901. return o;
  3902. }
  3903. // Colors
  3904. var rgbRegex = /rgb\((\d+,\s*[\d]+,\s*[\d]+)\)/g;
  3905. function rgbToRgba(rgbValue) {
  3906. var rgb = rgbRegex.exec(rgbValue);
  3907. return rgb ? ("rgba(" + (rgb[1]) + ",1)") : rgbValue;
  3908. }
  3909. var hexToRgbaHexRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
  3910. var hexToRgbaRgbRegex = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i;
  3911. function hexToRgba(hexValue) {
  3912. var hex = hexValue.replace(hexToRgbaHexRegex, function (m, r, g, b) { return r + r + g + g + b + b; } );
  3913. var rgb = hexToRgbaRgbRegex.exec(hex);
  3914. var r = parseInt(rgb[1], 16);
  3915. var g = parseInt(rgb[2], 16);
  3916. var b = parseInt(rgb[3], 16);
  3917. return ("rgba(" + r + "," + g + "," + b + ",1)");
  3918. }
  3919. var hslToRgbaHsl1Regex = /hsl\((\d+),\s*([\d.]+)%,\s*([\d.]+)%\)/g;
  3920. var hslToRgbaHsl2Regex = /hsla\((\d+),\s*([\d.]+)%,\s*([\d.]+)%,\s*([\d.]+)\)/g;
  3921. function hslToRgba(hslValue) {
  3922. var hsl = hslToRgbaHsl1Regex.exec(hslValue) || hslToRgbaHsl2Regex.exec(hslValue);
  3923. var h = parseInt(hsl[1], 10) / 360;
  3924. var s = parseInt(hsl[2], 10) / 100;
  3925. var l = parseInt(hsl[3], 10) / 100;
  3926. var a = hsl[4] || 1;
  3927. function hue2rgb(p, q, t) {
  3928. if (t < 0) { t += 1; }
  3929. if (t > 1) { t -= 1; }
  3930. if (t < 1/6) { return p + (q - p) * 6 * t; }
  3931. if (t < 1/2) { return q; }
  3932. if (t < 2/3) { return p + (q - p) * (2/3 - t) * 6; }
  3933. return p;
  3934. }
  3935. var r, g, b;
  3936. if (s == 0) {
  3937. r = g = b = l;
  3938. } else {
  3939. var q = l < 0.5 ? l * (1 + s) : l + s - l * s;
  3940. var p = 2 * l - q;
  3941. r = hue2rgb(p, q, h + 1/3);
  3942. g = hue2rgb(p, q, h);
  3943. b = hue2rgb(p, q, h - 1/3);
  3944. }
  3945. return ("rgba(" + (r * 255) + "," + (g * 255) + "," + (b * 255) + "," + a + ")");
  3946. }
  3947. function colorToRgb(val) {
  3948. if (is.rgb(val)) { return rgbToRgba(val); }
  3949. if (is.hex(val)) { return hexToRgba(val); }
  3950. if (is.hsl(val)) { return hslToRgba(val); }
  3951. }
  3952. // Units
  3953. var unitRegex = /([\+\-]?[0-9#\.]+)(%|px|pt|em|rem|in|cm|mm|ex|ch|pc|vw|vh|vmin|vmax|deg|rad|turn)?$/;
  3954. function getUnit(val) {
  3955. var split = unitRegex.exec(val);
  3956. if (split) { return split[2]; }
  3957. }
  3958. function getTransformUnit(propName) {
  3959. if (stringContains(propName, 'translate') || propName === 'perspective') { return 'px'; }
  3960. if (stringContains(propName, 'rotate') || stringContains(propName, 'skew')) { return 'deg'; }
  3961. }
  3962. // Values
  3963. function getFunctionValue(val, animatable) {
  3964. if (!is.fnc(val)) { return val; }
  3965. return val(animatable.target, animatable.id, animatable.total);
  3966. }
  3967. function getAttribute(el, prop) {
  3968. return el.getAttribute(prop);
  3969. }
  3970. function convertPxToUnit(el, value, unit) {
  3971. var valueUnit = getUnit(value);
  3972. if (arrayContains([unit, 'deg', 'rad', 'turn'], valueUnit)) { return value; }
  3973. var cached = cache.CSS[value + unit];
  3974. if (!is.und(cached)) { return cached; }
  3975. var baseline = 100;
  3976. var tempEl = document.createElement(el.tagName);
  3977. var parentEl = (el.parentNode && (el.parentNode !== document)) ? el.parentNode : document.body;
  3978. parentEl.appendChild(tempEl);
  3979. tempEl.style.position = 'absolute';
  3980. tempEl.style.width = baseline + unit;
  3981. var factor = baseline / tempEl.offsetWidth;
  3982. parentEl.removeChild(tempEl);
  3983. var convertedUnit = factor * parseFloat(value);
  3984. cache.CSS[value + unit] = convertedUnit;
  3985. return convertedUnit;
  3986. }
  3987. function getCSSValue(el, prop, unit) {
  3988. if (prop in el.style) {
  3989. var uppercasePropName = prop.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();
  3990. var value = el.style[prop] || getComputedStyle(el).getPropertyValue(uppercasePropName) || '0';
  3991. return unit ? convertPxToUnit(el, value, unit) : value;
  3992. }
  3993. }
  3994. function getAnimationType(el, prop) {
  3995. if (is.dom(el) && !is.inp(el) && (getAttribute(el, prop) || (is.svg(el) && el[prop]))) { return 'attribute'; }
  3996. if (is.dom(el) && arrayContains(validTransforms, prop)) { return 'transform'; }
  3997. if (is.dom(el) && (prop !== 'transform' && getCSSValue(el, prop))) { return 'css'; }
  3998. if (el[prop] != null) { return 'object'; }
  3999. }
  4000. var transformRegex = /(\w+)\(([^)]*)\)/g;
  4001. function getElementTransforms(el) {
  4002. if (!is.dom(el)) { return; }
  4003. var str = el.style.transform || '';
  4004. var transforms = new Map();
  4005. var m; while (m = transformRegex.exec(str)) { transforms.set(m[1], m[2]); }
  4006. return transforms;
  4007. }
  4008. function getTransformValue(el, propName, animatable, unit) {
  4009. var defaultVal = stringContains(propName, 'scale') ? 1 : 0 + getTransformUnit(propName);
  4010. var value = getElementTransforms(el).get(propName) || defaultVal;
  4011. if (animatable) {
  4012. animatable.transforms.list.set(propName, value);
  4013. animatable.transforms['last'] = propName;
  4014. }
  4015. return unit ? convertPxToUnit(el, value, unit) : value;
  4016. }
  4017. function getOriginalTargetValue(target, propName, unit, animatable) {
  4018. switch (getAnimationType(target, propName)) {
  4019. case 'transform': return getTransformValue(target, propName, animatable, unit);
  4020. case 'css': return getCSSValue(target, propName, unit);
  4021. case 'attribute': return getAttribute(target, propName);
  4022. default: return target[propName] || 0;
  4023. }
  4024. }
  4025. var operatorRegex = /^(\*=|\+=|-=)/;
  4026. function getRelativeValue(to, from) {
  4027. var operator = operatorRegex.exec(to);
  4028. if (!operator) { return to; }
  4029. var u = getUnit(to) || 0;
  4030. var x = parseFloat(from);
  4031. var y = parseFloat(to.replace(operator[0], ''));
  4032. switch (operator[0][0]) {
  4033. case '+': return x + y + u;
  4034. case '-': return x - y + u;
  4035. case '*': return x * y + u;
  4036. }
  4037. }
  4038. var whitespaceRegex = /\s/g;
  4039. function validateValue(val, unit) {
  4040. if (is.col(val)) { return colorToRgb(val); }
  4041. var originalUnit = getUnit(val);
  4042. var unitLess = originalUnit ? val.substr(0, val.length - originalUnit.length) : val;
  4043. return unit && !whitespaceRegex.test(val) ? unitLess + unit : unitLess;
  4044. }
  4045. // getTotalLength() equivalent for circle, rect, polyline, polygon and line shapes
  4046. // adapted from https://gist.github.com/SebLambla/3e0550c496c236709744
  4047. function getDistance(p1, p2) {
  4048. return Math.sqrt(Math.pow(p2.x - p1.x, 2) + Math.pow(p2.y - p1.y, 2));
  4049. }
  4050. function getCircleLength(el) {
  4051. return Math.PI * 2 * getAttribute(el, 'r');
  4052. }
  4053. function getRectLength(el) {
  4054. return (getAttribute(el, 'width') * 2) + (getAttribute(el, 'height') * 2);
  4055. }
  4056. function getLineLength(el) {
  4057. return getDistance(
  4058. {x: getAttribute(el, 'x1'), y: getAttribute(el, 'y1')},
  4059. {x: getAttribute(el, 'x2'), y: getAttribute(el, 'y2')}
  4060. );
  4061. }
  4062. function getPolylineLength(el) {
  4063. var points = el.points;
  4064. var totalLength = 0;
  4065. var previousPos;
  4066. for (var i = 0 ; i < points.numberOfItems; i++) {
  4067. var currentPos = points.getItem(i);
  4068. if (i > 0) { totalLength += getDistance(previousPos, currentPos); }
  4069. previousPos = currentPos;
  4070. }
  4071. return totalLength;
  4072. }
  4073. function getPolygonLength(el) {
  4074. var points = el.points;
  4075. return getPolylineLength(el) + getDistance(points.getItem(points.numberOfItems - 1), points.getItem(0));
  4076. }
  4077. // Path animation
  4078. function getTotalLength(el) {
  4079. if (el.getTotalLength) { return el.getTotalLength(); }
  4080. switch(el.tagName.toLowerCase()) {
  4081. case 'circle': return getCircleLength(el);
  4082. case 'rect': return getRectLength(el);
  4083. case 'line': return getLineLength(el);
  4084. case 'polyline': return getPolylineLength(el);
  4085. case 'polygon': return getPolygonLength(el);
  4086. }
  4087. }
  4088. function setDashoffset(el) {
  4089. var pathLength = getTotalLength(el);
  4090. el.setAttribute('stroke-dasharray', pathLength);
  4091. return pathLength;
  4092. }
  4093. // Motion path
  4094. function getParentSvgEl(el) {
  4095. var parentEl = el.parentNode;
  4096. while (is.svg(parentEl)) {
  4097. parentEl = parentEl.parentNode;
  4098. if (!is.svg(parentEl.parentNode)) { break; }
  4099. }
  4100. return parentEl;
  4101. }
  4102. function getParentSvg(pathEl, svgData) {
  4103. var svg = svgData || {};
  4104. var parentSvgEl = svg.el || getParentSvgEl(pathEl);
  4105. var rect = parentSvgEl.getBoundingClientRect();
  4106. var viewBoxAttr = getAttribute(parentSvgEl, 'viewBox');
  4107. var width = rect.width;
  4108. var height = rect.height;
  4109. var viewBox = svg.viewBox || (viewBoxAttr ? viewBoxAttr.split(' ') : [0, 0, width, height]);
  4110. return {
  4111. el: parentSvgEl,
  4112. viewBox: viewBox,
  4113. x: viewBox[0] / 1,
  4114. y: viewBox[1] / 1,
  4115. w: width / viewBox[2],
  4116. h: height / viewBox[3]
  4117. }
  4118. }
  4119. function getPath(path, percent) {
  4120. var pathEl = is.str(path) ? selectString(path)[0] : path;
  4121. var p = percent || 100;
  4122. return function(property) {
  4123. return {
  4124. property: property,
  4125. el: pathEl,
  4126. svg: getParentSvg(pathEl),
  4127. totalLength: getTotalLength(pathEl) * (p / 100)
  4128. }
  4129. }
  4130. }
  4131. function getPathProgress(path, progress) {
  4132. function point(offset) {
  4133. if ( offset === void 0 ) offset = 0;
  4134. var l = progress + offset >= 1 ? progress + offset : 0;
  4135. return path.el.getPointAtLength(l);
  4136. }
  4137. var svg = getParentSvg(path.el, path.svg);
  4138. var p = point();
  4139. var p0 = point(-1);
  4140. var p1 = point(+1);
  4141. switch (path.property) {
  4142. case 'x': return (p.x - svg.x) * svg.w;
  4143. case 'y': return (p.y - svg.y) * svg.h;
  4144. case 'angle': return Math.atan2(p1.y - p0.y, p1.x - p0.x) * 180 / Math.PI;
  4145. }
  4146. }
  4147. // Decompose value
  4148. var valueRegex = /-?\d*\.?\d+/g;
  4149. function decomposeValue(val, unit) {
  4150. var value = validateValue((is.pth(val) ? val.totalLength : val), unit) + '';
  4151. return {
  4152. original: value,
  4153. numbers: value.match(valueRegex) ? value.match(valueRegex).map(Number) : [0],
  4154. strings: (is.str(val) || unit) ? value.split(valueRegex) : []
  4155. }
  4156. }
  4157. // Animatables
  4158. function parseTargets(targets) {
  4159. var targetsArray = targets ? (flattenArray(is.arr(targets) ? targets.map(toArray) : toArray(targets))) : [];
  4160. return filterArray(targetsArray, function (item, pos, self) { return self.indexOf(item) === pos; });
  4161. }
  4162. function getAnimatables(targets) {
  4163. var parsed = parseTargets(targets);
  4164. return parsed.map(function (t, i) {
  4165. return {target: t, id: i, total: parsed.length, transforms: { list: getElementTransforms(t) } };
  4166. });
  4167. }
  4168. // Properties
  4169. var springRegex = /^spring/;
  4170. function normalizePropertyTweens(prop, tweenSettings) {
  4171. var settings = cloneObject(tweenSettings);
  4172. // Override duration if easing is a spring
  4173. if (springRegex.test(settings.easing)) { settings.duration = spring(settings.easing); }
  4174. if (is.arr(prop)) {
  4175. var l = prop.length;
  4176. var isFromTo = (l === 2 && !is.obj(prop[0]));
  4177. if (!isFromTo) {
  4178. // Duration divided by the number of tweens
  4179. if (!is.fnc(tweenSettings.duration)) { settings.duration = tweenSettings.duration / l; }
  4180. } else {
  4181. // Transform [from, to] values shorthand to a valid tween value
  4182. prop = {value: prop};
  4183. }
  4184. }
  4185. var propArray = is.arr(prop) ? prop : [prop];
  4186. return propArray.map(function (v, i) {
  4187. var obj = (is.obj(v) && !is.pth(v)) ? v : {value: v};
  4188. // Default delay value should only be applied to the first tween
  4189. if (is.und(obj.delay)) { obj.delay = !i ? tweenSettings.delay : 0; }
  4190. // Default endDelay value should only be applied to the last tween
  4191. if (is.und(obj.endDelay)) { obj.endDelay = i === propArray.length - 1 ? tweenSettings.endDelay : 0; }
  4192. return obj;
  4193. }).map(function (k) { return mergeObjects(k, settings); });
  4194. }
  4195. function flattenKeyframes(keyframes) {
  4196. var propertyNames = filterArray(flattenArray(keyframes.map(function (key) { return Object.keys(key); })), function (p) { return is.key(p); })
  4197. .reduce(function (a,b) { if (a.indexOf(b) < 0) { a.push(b); } return a; }, []);
  4198. var properties = {};
  4199. var loop = function ( i ) {
  4200. var propName = propertyNames[i];
  4201. properties[propName] = keyframes.map(function (key) {
  4202. var newKey = {};
  4203. for (var p in key) {
  4204. if (is.key(p)) {
  4205. if (p == propName) { newKey.value = key[p]; }
  4206. } else {
  4207. newKey[p] = key[p];
  4208. }
  4209. }
  4210. return newKey;
  4211. });
  4212. };
  4213. for (var i = 0; i < propertyNames.length; i++) loop( i );
  4214. return properties;
  4215. }
  4216. function getProperties(tweenSettings, params) {
  4217. var properties = [];
  4218. var keyframes = params.keyframes;
  4219. if (keyframes) { params = mergeObjects(flattenKeyframes(keyframes), params); }
  4220. for (var p in params) {
  4221. if (is.key(p)) {
  4222. properties.push({
  4223. name: p,
  4224. tweens: normalizePropertyTweens(params[p], tweenSettings)
  4225. });
  4226. }
  4227. }
  4228. return properties;
  4229. }
  4230. // Tweens
  4231. function normalizeTweenValues(tween, animatable) {
  4232. var t = {};
  4233. for (var p in tween) {
  4234. var value = getFunctionValue(tween[p], animatable);
  4235. if (is.arr(value)) {
  4236. value = value.map(function (v) { return getFunctionValue(v, animatable); });
  4237. if (value.length === 1) { value = value[0]; }
  4238. }
  4239. t[p] = value;
  4240. }
  4241. t.duration = parseFloat(t.duration);
  4242. t.delay = parseFloat(t.delay);
  4243. return t;
  4244. }
  4245. function normalizeTweens(prop, animatable) {
  4246. var previousTween;
  4247. return prop.tweens.map(function (t) {
  4248. var tween = normalizeTweenValues(t, animatable);
  4249. var tweenValue = tween.value;
  4250. var to = is.arr(tweenValue) ? tweenValue[1] : tweenValue;
  4251. var toUnit = getUnit(to);
  4252. var originalValue = getOriginalTargetValue(animatable.target, prop.name, toUnit, animatable);
  4253. var previousValue = previousTween ? previousTween.to.original : originalValue;
  4254. var from = is.arr(tweenValue) ? tweenValue[0] : previousValue;
  4255. var fromUnit = getUnit(from) || getUnit(originalValue);
  4256. var unit = toUnit || fromUnit;
  4257. if (is.und(to)) { to = previousValue; }
  4258. tween.from = decomposeValue(from, unit);
  4259. tween.to = decomposeValue(getRelativeValue(to, from), unit);
  4260. tween.start = previousTween ? previousTween.end : 0;
  4261. tween.end = tween.start + tween.delay + tween.duration + tween.endDelay;
  4262. tween.easing = parseEasings(tween.easing, tween.duration);
  4263. tween.isPath = is.pth(tweenValue);
  4264. tween.isColor = is.col(tween.from.original);
  4265. if (tween.isColor) { tween.round = 1; }
  4266. previousTween = tween;
  4267. return tween;
  4268. });
  4269. }
  4270. // Tween progress
  4271. var setProgressValue = {
  4272. css: function (t, p, v) { return t.style[p] = v; },
  4273. attribute: function (t, p, v) { return t.setAttribute(p, v); },
  4274. object: function (t, p, v) { return t[p] = v; },
  4275. transform: function (t, p, v, transforms, manual) {
  4276. transforms.list.set(p, v);
  4277. if (p === transforms.last || manual) {
  4278. var str = '';
  4279. transforms.list.forEach(function (value, prop) { str += prop + "(" + value + ") "; });
  4280. t.style.transform = str;
  4281. }
  4282. }
  4283. };
  4284. // Set Value helper
  4285. function setTargetsValue(targets, properties) {
  4286. var animatables = getAnimatables(targets);
  4287. for (var i = 0, len = animatables.length; i < len; i++) {
  4288. var animatable = animatables[i];
  4289. for (var property in properties) {
  4290. var value = getFunctionValue(properties[property], animatable);
  4291. var target = animatable.target;
  4292. var valueUnit = getUnit(value);
  4293. var originalValue = getOriginalTargetValue(target, property, valueUnit, animatable);
  4294. var unit = valueUnit || getUnit(originalValue);
  4295. var to = getRelativeValue(validateValue(value, unit), originalValue);
  4296. var animType = getAnimationType(target, property);
  4297. setProgressValue[animType](target, property, to, animatable.transforms, true);
  4298. }
  4299. }
  4300. }
  4301. // Animations
  4302. function createAnimation(animatable, prop) {
  4303. var animType = getAnimationType(animatable.target, prop.name);
  4304. if (animType) {
  4305. var tweens = normalizeTweens(prop, animatable);
  4306. var lastTween = tweens[tweens.length - 1];
  4307. return {
  4308. type: animType,
  4309. property: prop.name,
  4310. animatable: animatable,
  4311. tweens: tweens,
  4312. duration: lastTween.end,
  4313. delay: tweens[0].delay,
  4314. endDelay: lastTween.endDelay
  4315. }
  4316. }
  4317. }
  4318. function getAnimations(animatables, properties) {
  4319. return filterArray(flattenArray(animatables.map(function (animatable) {
  4320. return properties.map(function (prop) {
  4321. return createAnimation(animatable, prop);
  4322. });
  4323. })), function (a) { return !is.und(a); });
  4324. }
  4325. // Create Instance
  4326. function getInstanceTimings(animations, tweenSettings) {
  4327. var animLength = animations.length;
  4328. var getTlOffset = function (anim) { return anim.timelineOffset ? anim.timelineOffset : 0; };
  4329. var timings = {};
  4330. timings.duration = animLength ? Math.max.apply(Math, animations.map(function (anim) { return getTlOffset(anim) + anim.duration; })) : tweenSettings.duration;
  4331. timings.delay = animLength ? Math.min.apply(Math, animations.map(function (anim) { return getTlOffset(anim) + anim.delay; })) : tweenSettings.delay;
  4332. timings.endDelay = animLength ? timings.duration - Math.max.apply(Math, animations.map(function (anim) { return getTlOffset(anim) + anim.duration - anim.endDelay; })) : tweenSettings.endDelay;
  4333. return timings;
  4334. }
  4335. var instanceID = 0;
  4336. function createNewInstance(params) {
  4337. var instanceSettings = replaceObjectProps(defaultInstanceSettings, params);
  4338. var tweenSettings = replaceObjectProps(defaultTweenSettings, params);
  4339. var properties = getProperties(tweenSettings, params);
  4340. var animatables = getAnimatables(params.targets);
  4341. var animations = getAnimations(animatables, properties);
  4342. var timings = getInstanceTimings(animations, tweenSettings);
  4343. var id = instanceID;
  4344. instanceID++;
  4345. return mergeObjects(instanceSettings, {
  4346. id: id,
  4347. children: [],
  4348. animatables: animatables,
  4349. animations: animations,
  4350. duration: timings.duration,
  4351. delay: timings.delay,
  4352. endDelay: timings.endDelay
  4353. });
  4354. }
  4355. // Core
  4356. var activeInstances = [];
  4357. var pausedInstances = [];
  4358. var raf;
  4359. var engine = (function () {
  4360. function play() {
  4361. raf = requestAnimationFrame(step);
  4362. }
  4363. function step(t) {
  4364. var activeInstancesLength = activeInstances.length;
  4365. if (activeInstancesLength) {
  4366. var i = 0;
  4367. while (i < activeInstancesLength) {
  4368. var activeInstance = activeInstances[i];
  4369. if (!activeInstance.paused) {
  4370. activeInstance.tick(t);
  4371. } else {
  4372. var instanceIndex = activeInstances.indexOf(activeInstance);
  4373. if (instanceIndex > -1) {
  4374. activeInstances.splice(instanceIndex, 1);
  4375. activeInstancesLength = activeInstances.length;
  4376. }
  4377. }
  4378. i++;
  4379. }
  4380. play();
  4381. } else {
  4382. raf = cancelAnimationFrame(raf);
  4383. }
  4384. }
  4385. return play;
  4386. })();
  4387. function handleVisibilityChange() {
  4388. if (document.hidden) {
  4389. for (var i = 0, len = activeInstances.length; i < len; i++) {
  4390. activeInstance[i].pause();
  4391. }
  4392. pausedInstances = activeInstances.slice(0);
  4393. activeInstances = [];
  4394. } else {
  4395. for (var i$1 = 0, len$1 = pausedInstances.length; i$1 < len$1; i$1++) {
  4396. pausedInstances[i$1].play();
  4397. }
  4398. }
  4399. }
  4400. document.addEventListener('visibilitychange', handleVisibilityChange);
  4401. // Public Instance
  4402. function anime(params) {
  4403. if ( params === void 0 ) params = {};
  4404. var startTime = 0, lastTime = 0, now = 0;
  4405. var children, childrenLength = 0;
  4406. var resolve = null;
  4407. function makePromise() {
  4408. return window.Promise && new Promise(function (_resolve) { return resolve = _resolve; });
  4409. }
  4410. var promise = makePromise();
  4411. var instance = createNewInstance(params);
  4412. function toggleInstanceDirection() {
  4413. instance.reversed = !instance.reversed;
  4414. for (var i = 0, len = children.length; i < len; i++) {
  4415. children[i].reversed = instance.reversed;
  4416. }
  4417. }
  4418. function adjustTime(time) {
  4419. return instance.reversed ? instance.duration - time : time;
  4420. }
  4421. function resetTime() {
  4422. startTime = 0;
  4423. lastTime = adjustTime(instance.currentTime) * (1 / anime.speed);
  4424. }
  4425. function seekCild(time, child) {
  4426. if (child) { child.seek(time - child.timelineOffset); }
  4427. }
  4428. function syncInstanceChildren(time) {
  4429. if (!instance.reversePlayback) {
  4430. for (var i = 0; i < childrenLength; i++) { seekCild(time, children[i]); }
  4431. } else {
  4432. for (var i$1 = childrenLength; i$1--;) { seekCild(time, children[i$1]); }
  4433. }
  4434. }
  4435. function setAnimationsProgress(insTime) {
  4436. var i = 0;
  4437. var animations = instance.animations;
  4438. var animationsLength = animations.length;
  4439. while (i < animationsLength) {
  4440. var anim = animations[i];
  4441. var animatable = anim.animatable;
  4442. var tweens = anim.tweens;
  4443. var tweenLength = tweens.length - 1;
  4444. var tween = tweens[tweenLength];
  4445. // Only check for keyframes if there is more than one tween
  4446. if (tweenLength) { tween = filterArray(tweens, function (t) { return (insTime < t.end); })[0] || tween; }
  4447. var elapsed = minMax(insTime - tween.start - tween.delay, 0, tween.duration) / tween.duration;
  4448. var eased = isNaN(elapsed) ? 1 : tween.easing(elapsed);
  4449. var strings = tween.to.strings;
  4450. var round = tween.round;
  4451. var numbers = [];
  4452. var toNumbersLength = tween.to.numbers.length;
  4453. var progress = (void 0);
  4454. for (var n = 0; n < toNumbersLength; n++) {
  4455. var value = (void 0);
  4456. var toNumber = tween.to.numbers[n];
  4457. var fromNumber = tween.from.numbers[n] || 0;
  4458. if (!tween.isPath) {
  4459. value = fromNumber + (eased * (toNumber - fromNumber));
  4460. } else {
  4461. value = getPathProgress(tween.value, eased * toNumber);
  4462. }
  4463. if (round) {
  4464. if (!(tween.isColor && n > 2)) {
  4465. value = Math.round(value * round) / round;
  4466. }
  4467. }
  4468. numbers.push(value);
  4469. }
  4470. // Manual Array.reduce for better performances
  4471. var stringsLength = strings.length;
  4472. if (!stringsLength) {
  4473. progress = numbers[0];
  4474. } else {
  4475. progress = strings[0];
  4476. for (var s = 0; s < stringsLength; s++) {
  4477. var a = strings[s];
  4478. var b = strings[s + 1];
  4479. var n$1 = numbers[s];
  4480. if (!isNaN(n$1)) {
  4481. if (!b) {
  4482. progress += n$1 + ' ';
  4483. } else {
  4484. progress += n$1 + b;
  4485. }
  4486. }
  4487. }
  4488. }
  4489. setProgressValue[anim.type](animatable.target, anim.property, progress, animatable.transforms);
  4490. anim.currentValue = progress;
  4491. i++;
  4492. }
  4493. }
  4494. function setCallback(cb) {
  4495. if (instance[cb] && !instance.passThrough) { instance[cb](instance); }
  4496. }
  4497. function countIteration() {
  4498. if (instance.remaining && instance.remaining !== true) {
  4499. instance.remaining--;
  4500. }
  4501. }
  4502. function setInstanceProgress(engineTime) {
  4503. var insDuration = instance.duration;
  4504. var insDelay = instance.delay;
  4505. var insEndDelay = insDuration - instance.endDelay;
  4506. var insTime = adjustTime(engineTime);
  4507. instance.progress = minMax((insTime / insDuration) * 100, 0, 100);
  4508. instance.reversePlayback = insTime < instance.currentTime;
  4509. if (children) { syncInstanceChildren(insTime); }
  4510. if (!instance.began && instance.currentTime > 0) {
  4511. instance.began = true;
  4512. setCallback('begin');
  4513. setCallback('loopBegin');
  4514. }
  4515. if (insTime <= insDelay && instance.currentTime !== 0) {
  4516. setAnimationsProgress(0);
  4517. }
  4518. if ((insTime >= insEndDelay && instance.currentTime !== insDuration) || !insDuration) {
  4519. setAnimationsProgress(insDuration);
  4520. }
  4521. if (insTime > insDelay && insTime < insEndDelay) {
  4522. if (!instance.changeBegan) {
  4523. instance.changeBegan = true;
  4524. instance.changeCompleted = false;
  4525. setCallback('changeBegin');
  4526. }
  4527. setCallback('change');
  4528. setAnimationsProgress(insTime);
  4529. } else {
  4530. if (instance.changeBegan) {
  4531. instance.changeCompleted = true;
  4532. instance.changeBegan = false;
  4533. setCallback('changeComplete');
  4534. }
  4535. }
  4536. instance.currentTime = minMax(insTime, 0, insDuration);
  4537. if (instance.began) { setCallback('update'); }
  4538. if (engineTime >= insDuration) {
  4539. lastTime = 0;
  4540. countIteration();
  4541. if (instance.remaining) {
  4542. startTime = now;
  4543. setCallback('loopComplete');
  4544. setCallback('loopBegin');
  4545. if (instance.direction === 'alternate') { toggleInstanceDirection(); }
  4546. } else {
  4547. instance.paused = true;
  4548. if (!instance.completed) {
  4549. instance.completed = true;
  4550. setCallback('loopComplete');
  4551. setCallback('complete');
  4552. if ('Promise' in window) {
  4553. resolve();
  4554. promise = makePromise();
  4555. }
  4556. }
  4557. }
  4558. }
  4559. }
  4560. instance.reset = function() {
  4561. var direction = instance.direction;
  4562. instance.passThrough = false;
  4563. instance.currentTime = 0;
  4564. instance.progress = 0;
  4565. instance.paused = true;
  4566. instance.began = false;
  4567. instance.changeBegan = false;
  4568. instance.completed = false;
  4569. instance.changeCompleted = false;
  4570. instance.reversePlayback = false;
  4571. instance.reversed = direction === 'reverse';
  4572. instance.remaining = instance.loop;
  4573. children = instance.children;
  4574. childrenLength = children.length;
  4575. for (var i = childrenLength; i--;) { instance.children[i].reset(); }
  4576. if (instance.reversed && instance.loop !== true || (direction === 'alternate' && instance.loop === 1)) { instance.remaining++; }
  4577. setAnimationsProgress(0);
  4578. };
  4579. // Set Value helper
  4580. instance.set = function(targets, properties) {
  4581. setTargetsValue(targets, properties);
  4582. return instance;
  4583. };
  4584. instance.tick = function(t) {
  4585. now = t;
  4586. if (!startTime) { startTime = now; }
  4587. setInstanceProgress((now + (lastTime - startTime)) * anime.speed);
  4588. };
  4589. instance.seek = function(time) {
  4590. setInstanceProgress(adjustTime(time));
  4591. };
  4592. instance.pause = function() {
  4593. instance.paused = true;
  4594. resetTime();
  4595. };
  4596. instance.play = function() {
  4597. if (!instance.paused) { return; }
  4598. instance.paused = false;
  4599. activeInstances.push(instance);
  4600. resetTime();
  4601. if (!raf) { engine(); }
  4602. };
  4603. instance.reverse = function() {
  4604. toggleInstanceDirection();
  4605. resetTime();
  4606. };
  4607. instance.restart = function() {
  4608. instance.reset();
  4609. instance.play();
  4610. };
  4611. instance.finished = promise;
  4612. instance.reset();
  4613. if (instance.autoplay) { instance.play(); }
  4614. return instance;
  4615. }
  4616. // Remove targets from animation
  4617. function removeTargetsFromAnimations(targetsArray, animations) {
  4618. for (var a = animations.length; a--;) {
  4619. if (arrayContains(targetsArray, animations[a].animatable.target)) {
  4620. animations.splice(a, 1);
  4621. }
  4622. }
  4623. }
  4624. function removeTargets(targets) {
  4625. var targetsArray = parseTargets(targets);
  4626. for (var i = activeInstances.length; i--;) {
  4627. var instance = activeInstances[i];
  4628. var animations = instance.animations;
  4629. var children = instance.children;
  4630. removeTargetsFromAnimations(targetsArray, animations);
  4631. for (var c = children.length; c--;) {
  4632. var child = children[c];
  4633. var childAnimations = child.animations;
  4634. removeTargetsFromAnimations(targetsArray, childAnimations);
  4635. if (!childAnimations.length && !child.children.length) { children.splice(c, 1); }
  4636. }
  4637. if (!animations.length && !children.length) { instance.pause(); }
  4638. }
  4639. }
  4640. // Stagger helpers
  4641. function stagger(val, params) {
  4642. if ( params === void 0 ) params = {};
  4643. var direction = params.direction || 'normal';
  4644. var easing = params.easing ? parseEasings(params.easing) : null;
  4645. var grid = params.grid;
  4646. var axis = params.axis;
  4647. var fromIndex = params.from || 0;
  4648. var fromFirst = fromIndex === 'first';
  4649. var fromCenter = fromIndex === 'center';
  4650. var fromLast = fromIndex === 'last';
  4651. var isRange = is.arr(val);
  4652. var val1 = isRange ? parseFloat(val[0]) : parseFloat(val);
  4653. var val2 = isRange ? parseFloat(val[1]) : 0;
  4654. var unit = getUnit(isRange ? val[1] : val) || 0;
  4655. var start = params.start || 0 + (isRange ? val1 : 0);
  4656. var values = [];
  4657. var maxValue = 0;
  4658. return function (el, i, t) {
  4659. if (fromFirst) { fromIndex = 0; }
  4660. if (fromCenter) { fromIndex = (t - 1) / 2; }
  4661. if (fromLast) { fromIndex = t - 1; }
  4662. if (!values.length) {
  4663. for (var index = 0; index < t; index++) {
  4664. if (!grid) {
  4665. values.push(Math.abs(fromIndex - index));
  4666. } else {
  4667. var fromX = !fromCenter ? fromIndex%grid[0] : (grid[0]-1)/2;
  4668. var fromY = !fromCenter ? Math.floor(fromIndex/grid[0]) : (grid[1]-1)/2;
  4669. var toX = index%grid[0];
  4670. var toY = Math.floor(index/grid[0]);
  4671. var distanceX = fromX - toX;
  4672. var distanceY = fromY - toY;
  4673. var value = Math.sqrt(distanceX * distanceX + distanceY * distanceY);
  4674. if (axis === 'x') { value = -distanceX; }
  4675. if (axis === 'y') { value = -distanceY; }
  4676. values.push(value);
  4677. }
  4678. maxValue = Math.max.apply(Math, values);
  4679. }
  4680. if (easing) { values = values.map(function (val) { return easing(val / maxValue) * maxValue; }); }
  4681. if (direction === 'reverse') { values = values.map(function (val) { return axis ? (val < 0) ? val * -1 : -val : Math.abs(maxValue - val); }); }
  4682. }
  4683. var spacing = isRange ? (val2 - val1) / maxValue : val1;
  4684. return start + (spacing * (Math.round(values[i] * 100) / 100)) + unit;
  4685. }
  4686. }
  4687. // Timeline
  4688. function timeline(params) {
  4689. if ( params === void 0 ) params = {};
  4690. var tl = anime(params);
  4691. tl.duration = 0;
  4692. tl.add = function(instanceParams, timelineOffset) {
  4693. var tlIndex = activeInstances.indexOf(tl);
  4694. var children = tl.children;
  4695. if (tlIndex > -1) { activeInstances.splice(tlIndex, 1); }
  4696. function passThrough(ins) { ins.passThrough = true; }
  4697. for (var i = 0; i < children.length; i++) { passThrough(children[i]); }
  4698. var insParams = mergeObjects(instanceParams, replaceObjectProps(defaultTweenSettings, params));
  4699. insParams.targets = insParams.targets || params.targets;
  4700. var tlDuration = tl.duration;
  4701. insParams.autoplay = false;
  4702. insParams.direction = tl.direction;
  4703. insParams.timelineOffset = is.und(timelineOffset) ? tlDuration : getRelativeValue(timelineOffset, tlDuration);
  4704. passThrough(tl);
  4705. tl.seek(insParams.timelineOffset);
  4706. var ins = anime(insParams);
  4707. passThrough(ins);
  4708. children.push(ins);
  4709. var timings = getInstanceTimings(children, params);
  4710. tl.delay = timings.delay;
  4711. tl.endDelay = timings.endDelay;
  4712. tl.duration = timings.duration;
  4713. tl.seek(0);
  4714. tl.reset();
  4715. if (tl.autoplay) { tl.play(); }
  4716. return tl;
  4717. };
  4718. return tl;
  4719. }
  4720. anime.version = '3.0.0';
  4721. anime.speed = 1;
  4722. anime.running = activeInstances;
  4723. anime.remove = removeTargets;
  4724. anime.get = getOriginalTargetValue;
  4725. anime.set = setTargetsValue;
  4726. anime.convertPx = convertPxToUnit;
  4727. anime.path = getPath;
  4728. anime.setDashoffset = setDashoffset;
  4729. anime.stagger = stagger;
  4730. anime.timeline = timeline;
  4731. anime.easing = parseEasings;
  4732. anime.penner = penner;
  4733. anime.random = function (min, max) { return Math.floor(Math.random() * (max - min + 1)) + min; };
  4734. module.exports = anime;
  4735. },{}],36:[function(_dereq_,module,exports){
  4736. (function (global, factory) {
  4737. typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
  4738. typeof define === 'function' && define.amd ? define(['exports'], factory) :
  4739. (global = global || self, factory(global.THREE = {}));
  4740. }(this, function (exports) { 'use strict';
  4741. // Polyfills
  4742. if ( Number.EPSILON === undefined ) {
  4743. Number.EPSILON = Math.pow( 2, - 52 );
  4744. }
  4745. if ( Number.isInteger === undefined ) {
  4746. // Missing in IE
  4747. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isInteger
  4748. Number.isInteger = function ( value ) {
  4749. return typeof value === 'number' && isFinite( value ) && Math.floor( value ) === value;
  4750. };
  4751. }
  4752. //
  4753. if ( Math.sign === undefined ) {
  4754. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sign
  4755. Math.sign = function ( x ) {
  4756. return ( x < 0 ) ? - 1 : ( x > 0 ) ? 1 : + x;
  4757. };
  4758. }
  4759. if ( 'name' in Function.prototype === false ) {
  4760. // Missing in IE
  4761. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name
  4762. Object.defineProperty( Function.prototype, 'name', {
  4763. get: function () {
  4764. return this.toString().match( /^\s*function\s*([^\(\s]*)/ )[ 1 ];
  4765. }
  4766. } );
  4767. }
  4768. if ( Object.assign === undefined ) {
  4769. // Missing in IE
  4770. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
  4771. ( function () {
  4772. Object.assign = function ( target ) {
  4773. if ( target === undefined || target === null ) {
  4774. throw new TypeError( 'Cannot convert undefined or null to object' );
  4775. }
  4776. var output = Object( target );
  4777. for ( var index = 1; index < arguments.length; index ++ ) {
  4778. var source = arguments[ index ];
  4779. if ( source !== undefined && source !== null ) {
  4780. for ( var nextKey in source ) {
  4781. if ( Object.prototype.hasOwnProperty.call( source, nextKey ) ) {
  4782. output[ nextKey ] = source[ nextKey ];
  4783. }
  4784. }
  4785. }
  4786. }
  4787. return output;
  4788. };
  4789. } )();
  4790. }
  4791. /**
  4792. * https://github.com/mrdoob/eventdispatcher.js/
  4793. */
  4794. function EventDispatcher() {}
  4795. Object.assign( EventDispatcher.prototype, {
  4796. addEventListener: function ( type, listener ) {
  4797. if ( this._listeners === undefined ) this._listeners = {};
  4798. var listeners = this._listeners;
  4799. if ( listeners[ type ] === undefined ) {
  4800. listeners[ type ] = [];
  4801. }
  4802. if ( listeners[ type ].indexOf( listener ) === - 1 ) {
  4803. listeners[ type ].push( listener );
  4804. }
  4805. },
  4806. hasEventListener: function ( type, listener ) {
  4807. if ( this._listeners === undefined ) return false;
  4808. var listeners = this._listeners;
  4809. return listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1;
  4810. },
  4811. removeEventListener: function ( type, listener ) {
  4812. if ( this._listeners === undefined ) return;
  4813. var listeners = this._listeners;
  4814. var listenerArray = listeners[ type ];
  4815. if ( listenerArray !== undefined ) {
  4816. var index = listenerArray.indexOf( listener );
  4817. if ( index !== - 1 ) {
  4818. listenerArray.splice( index, 1 );
  4819. }
  4820. }
  4821. },
  4822. dispatchEvent: function ( event ) {
  4823. if ( this._listeners === undefined ) return;
  4824. var listeners = this._listeners;
  4825. var listenerArray = listeners[ event.type ];
  4826. if ( listenerArray !== undefined ) {
  4827. event.target = this;
  4828. var array = listenerArray.slice( 0 );
  4829. for ( var i = 0, l = array.length; i < l; i ++ ) {
  4830. array[ i ].call( this, event );
  4831. }
  4832. }
  4833. }
  4834. } );
  4835. var REVISION = '103dev';
  4836. var MOUSE = { LEFT: 0, MIDDLE: 1, RIGHT: 2 };
  4837. var CullFaceNone = 0;
  4838. var CullFaceBack = 1;
  4839. var CullFaceFront = 2;
  4840. var CullFaceFrontBack = 3;
  4841. var FrontFaceDirectionCW = 0;
  4842. var FrontFaceDirectionCCW = 1;
  4843. var BasicShadowMap = 0;
  4844. var PCFShadowMap = 1;
  4845. var PCFSoftShadowMap = 2;
  4846. var FrontSide = 0;
  4847. var BackSide = 1;
  4848. var DoubleSide = 2;
  4849. var FlatShading = 1;
  4850. var SmoothShading = 2;
  4851. var NoColors = 0;
  4852. var FaceColors = 1;
  4853. var VertexColors = 2;
  4854. var NoBlending = 0;
  4855. var NormalBlending = 1;
  4856. var AdditiveBlending = 2;
  4857. var SubtractiveBlending = 3;
  4858. var MultiplyBlending = 4;
  4859. var CustomBlending = 5;
  4860. var AddEquation = 100;
  4861. var SubtractEquation = 101;
  4862. var ReverseSubtractEquation = 102;
  4863. var MinEquation = 103;
  4864. var MaxEquation = 104;
  4865. var ZeroFactor = 200;
  4866. var OneFactor = 201;
  4867. var SrcColorFactor = 202;
  4868. var OneMinusSrcColorFactor = 203;
  4869. var SrcAlphaFactor = 204;
  4870. var OneMinusSrcAlphaFactor = 205;
  4871. var DstAlphaFactor = 206;
  4872. var OneMinusDstAlphaFactor = 207;
  4873. var DstColorFactor = 208;
  4874. var OneMinusDstColorFactor = 209;
  4875. var SrcAlphaSaturateFactor = 210;
  4876. var NeverDepth = 0;
  4877. var AlwaysDepth = 1;
  4878. var LessDepth = 2;
  4879. var LessEqualDepth = 3;
  4880. var EqualDepth = 4;
  4881. var GreaterEqualDepth = 5;
  4882. var GreaterDepth = 6;
  4883. var NotEqualDepth = 7;
  4884. var MultiplyOperation = 0;
  4885. var MixOperation = 1;
  4886. var AddOperation = 2;
  4887. var NoToneMapping = 0;
  4888. var LinearToneMapping = 1;
  4889. var ReinhardToneMapping = 2;
  4890. var Uncharted2ToneMapping = 3;
  4891. var CineonToneMapping = 4;
  4892. var ACESFilmicToneMapping = 5;
  4893. var UVMapping = 300;
  4894. var CubeReflectionMapping = 301;
  4895. var CubeRefractionMapping = 302;
  4896. var EquirectangularReflectionMapping = 303;
  4897. var EquirectangularRefractionMapping = 304;
  4898. var SphericalReflectionMapping = 305;
  4899. var CubeUVReflectionMapping = 306;
  4900. var CubeUVRefractionMapping = 307;
  4901. var RepeatWrapping = 1000;
  4902. var ClampToEdgeWrapping = 1001;
  4903. var MirroredRepeatWrapping = 1002;
  4904. var NearestFilter = 1003;
  4905. var NearestMipMapNearestFilter = 1004;
  4906. var NearestMipMapLinearFilter = 1005;
  4907. var LinearFilter = 1006;
  4908. var LinearMipMapNearestFilter = 1007;
  4909. var LinearMipMapLinearFilter = 1008;
  4910. var UnsignedByteType = 1009;
  4911. var ByteType = 1010;
  4912. var ShortType = 1011;
  4913. var UnsignedShortType = 1012;
  4914. var IntType = 1013;
  4915. var UnsignedIntType = 1014;
  4916. var FloatType = 1015;
  4917. var HalfFloatType = 1016;
  4918. var UnsignedShort4444Type = 1017;
  4919. var UnsignedShort5551Type = 1018;
  4920. var UnsignedShort565Type = 1019;
  4921. var UnsignedInt248Type = 1020;
  4922. var AlphaFormat = 1021;
  4923. var RGBFormat = 1022;
  4924. var RGBAFormat = 1023;
  4925. var LuminanceFormat = 1024;
  4926. var LuminanceAlphaFormat = 1025;
  4927. var RGBEFormat = RGBAFormat;
  4928. var DepthFormat = 1026;
  4929. var DepthStencilFormat = 1027;
  4930. var RedFormat = 1028;
  4931. var RGB_S3TC_DXT1_Format = 33776;
  4932. var RGBA_S3TC_DXT1_Format = 33777;
  4933. var RGBA_S3TC_DXT3_Format = 33778;
  4934. var RGBA_S3TC_DXT5_Format = 33779;
  4935. var RGB_PVRTC_4BPPV1_Format = 35840;
  4936. var RGB_PVRTC_2BPPV1_Format = 35841;
  4937. var RGBA_PVRTC_4BPPV1_Format = 35842;
  4938. var RGBA_PVRTC_2BPPV1_Format = 35843;
  4939. var RGB_ETC1_Format = 36196;
  4940. var RGBA_ASTC_4x4_Format = 37808;
  4941. var RGBA_ASTC_5x4_Format = 37809;
  4942. var RGBA_ASTC_5x5_Format = 37810;
  4943. var RGBA_ASTC_6x5_Format = 37811;
  4944. var RGBA_ASTC_6x6_Format = 37812;
  4945. var RGBA_ASTC_8x5_Format = 37813;
  4946. var RGBA_ASTC_8x6_Format = 37814;
  4947. var RGBA_ASTC_8x8_Format = 37815;
  4948. var RGBA_ASTC_10x5_Format = 37816;
  4949. var RGBA_ASTC_10x6_Format = 37817;
  4950. var RGBA_ASTC_10x8_Format = 37818;
  4951. var RGBA_ASTC_10x10_Format = 37819;
  4952. var RGBA_ASTC_12x10_Format = 37820;
  4953. var RGBA_ASTC_12x12_Format = 37821;
  4954. var LoopOnce = 2200;
  4955. var LoopRepeat = 2201;
  4956. var LoopPingPong = 2202;
  4957. var InterpolateDiscrete = 2300;
  4958. var InterpolateLinear = 2301;
  4959. var InterpolateSmooth = 2302;
  4960. var ZeroCurvatureEnding = 2400;
  4961. var ZeroSlopeEnding = 2401;
  4962. var WrapAroundEnding = 2402;
  4963. var TrianglesDrawMode = 0;
  4964. var TriangleStripDrawMode = 1;
  4965. var TriangleFanDrawMode = 2;
  4966. var LinearEncoding = 3000;
  4967. var sRGBEncoding = 3001;
  4968. var GammaEncoding = 3007;
  4969. var RGBEEncoding = 3002;
  4970. var LogLuvEncoding = 3003;
  4971. var RGBM7Encoding = 3004;
  4972. var RGBM16Encoding = 3005;
  4973. var RGBDEncoding = 3006;
  4974. var BasicDepthPacking = 3200;
  4975. var RGBADepthPacking = 3201;
  4976. var TangentSpaceNormalMap = 0;
  4977. var ObjectSpaceNormalMap = 1;
  4978. /**
  4979. * @author alteredq / http://alteredqualia.com/
  4980. * @author mrdoob / http://mrdoob.com/
  4981. */
  4982. var _Math = {
  4983. DEG2RAD: Math.PI / 180,
  4984. RAD2DEG: 180 / Math.PI,
  4985. generateUUID: ( function () {
  4986. // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/21963136#21963136
  4987. var lut = [];
  4988. for ( var i = 0; i < 256; i ++ ) {
  4989. lut[ i ] = ( i < 16 ? '0' : '' ) + ( i ).toString( 16 );
  4990. }
  4991. return function generateUUID() {
  4992. var d0 = Math.random() * 0xffffffff | 0;
  4993. var d1 = Math.random() * 0xffffffff | 0;
  4994. var d2 = Math.random() * 0xffffffff | 0;
  4995. var d3 = Math.random() * 0xffffffff | 0;
  4996. var uuid = lut[ d0 & 0xff ] + lut[ d0 >> 8 & 0xff ] + lut[ d0 >> 16 & 0xff ] + lut[ d0 >> 24 & 0xff ] + '-' +
  4997. lut[ d1 & 0xff ] + lut[ d1 >> 8 & 0xff ] + '-' + lut[ d1 >> 16 & 0x0f | 0x40 ] + lut[ d1 >> 24 & 0xff ] + '-' +
  4998. lut[ d2 & 0x3f | 0x80 ] + lut[ d2 >> 8 & 0xff ] + '-' + lut[ d2 >> 16 & 0xff ] + lut[ d2 >> 24 & 0xff ] +
  4999. lut[ d3 & 0xff ] + lut[ d3 >> 8 & 0xff ] + lut[ d3 >> 16 & 0xff ] + lut[ d3 >> 24 & 0xff ];
  5000. // .toUpperCase() here flattens concatenated strings to save heap memory space.
  5001. return uuid.toUpperCase();
  5002. };
  5003. } )(),
  5004. clamp: function ( value, min, max ) {
  5005. return Math.max( min, Math.min( max, value ) );
  5006. },
  5007. // compute euclidian modulo of m % n
  5008. // https://en.wikipedia.org/wiki/Modulo_operation
  5009. euclideanModulo: function ( n, m ) {
  5010. return ( ( n % m ) + m ) % m;
  5011. },
  5012. // Linear mapping from range <a1, a2> to range <b1, b2>
  5013. mapLinear: function ( x, a1, a2, b1, b2 ) {
  5014. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  5015. },
  5016. // https://en.wikipedia.org/wiki/Linear_interpolation
  5017. lerp: function ( x, y, t ) {
  5018. return ( 1 - t ) * x + t * y;
  5019. },
  5020. // http://en.wikipedia.org/wiki/Smoothstep
  5021. smoothstep: function ( x, min, max ) {
  5022. if ( x <= min ) return 0;
  5023. if ( x >= max ) return 1;
  5024. x = ( x - min ) / ( max - min );
  5025. return x * x * ( 3 - 2 * x );
  5026. },
  5027. smootherstep: function ( x, min, max ) {
  5028. if ( x <= min ) return 0;
  5029. if ( x >= max ) return 1;
  5030. x = ( x - min ) / ( max - min );
  5031. return x * x * x * ( x * ( x * 6 - 15 ) + 10 );
  5032. },
  5033. // Random integer from <low, high> interval
  5034. randInt: function ( low, high ) {
  5035. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  5036. },
  5037. // Random float from <low, high> interval
  5038. randFloat: function ( low, high ) {
  5039. return low + Math.random() * ( high - low );
  5040. },
  5041. // Random float from <-range/2, range/2> interval
  5042. randFloatSpread: function ( range ) {
  5043. return range * ( 0.5 - Math.random() );
  5044. },
  5045. degToRad: function ( degrees ) {
  5046. return degrees * _Math.DEG2RAD;
  5047. },
  5048. radToDeg: function ( radians ) {
  5049. return radians * _Math.RAD2DEG;
  5050. },
  5051. isPowerOfTwo: function ( value ) {
  5052. return ( value & ( value - 1 ) ) === 0 && value !== 0;
  5053. },
  5054. ceilPowerOfTwo: function ( value ) {
  5055. return Math.pow( 2, Math.ceil( Math.log( value ) / Math.LN2 ) );
  5056. },
  5057. floorPowerOfTwo: function ( value ) {
  5058. return Math.pow( 2, Math.floor( Math.log( value ) / Math.LN2 ) );
  5059. }
  5060. };
  5061. /**
  5062. * @author mrdoob / http://mrdoob.com/
  5063. * @author philogb / http://blog.thejit.org/
  5064. * @author egraether / http://egraether.com/
  5065. * @author zz85 / http://www.lab4games.net/zz85/blog
  5066. */
  5067. function Vector2( x, y ) {
  5068. this.x = x || 0;
  5069. this.y = y || 0;
  5070. }
  5071. Object.defineProperties( Vector2.prototype, {
  5072. "width": {
  5073. get: function () {
  5074. return this.x;
  5075. },
  5076. set: function ( value ) {
  5077. this.x = value;
  5078. }
  5079. },
  5080. "height": {
  5081. get: function () {
  5082. return this.y;
  5083. },
  5084. set: function ( value ) {
  5085. this.y = value;
  5086. }
  5087. }
  5088. } );
  5089. Object.assign( Vector2.prototype, {
  5090. isVector2: true,
  5091. set: function ( x, y ) {
  5092. this.x = x;
  5093. this.y = y;
  5094. return this;
  5095. },
  5096. setScalar: function ( scalar ) {
  5097. this.x = scalar;
  5098. this.y = scalar;
  5099. return this;
  5100. },
  5101. setX: function ( x ) {
  5102. this.x = x;
  5103. return this;
  5104. },
  5105. setY: function ( y ) {
  5106. this.y = y;
  5107. return this;
  5108. },
  5109. setComponent: function ( index, value ) {
  5110. switch ( index ) {
  5111. case 0: this.x = value; break;
  5112. case 1: this.y = value; break;
  5113. default: throw new Error( 'index is out of range: ' + index );
  5114. }
  5115. return this;
  5116. },
  5117. getComponent: function ( index ) {
  5118. switch ( index ) {
  5119. case 0: return this.x;
  5120. case 1: return this.y;
  5121. default: throw new Error( 'index is out of range: ' + index );
  5122. }
  5123. },
  5124. clone: function () {
  5125. return new this.constructor( this.x, this.y );
  5126. },
  5127. copy: function ( v ) {
  5128. this.x = v.x;
  5129. this.y = v.y;
  5130. return this;
  5131. },
  5132. add: function ( v, w ) {
  5133. if ( w !== undefined ) {
  5134. console.warn( 'THREE.Vector2: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  5135. return this.addVectors( v, w );
  5136. }
  5137. this.x += v.x;
  5138. this.y += v.y;
  5139. return this;
  5140. },
  5141. addScalar: function ( s ) {
  5142. this.x += s;
  5143. this.y += s;
  5144. return this;
  5145. },
  5146. addVectors: function ( a, b ) {
  5147. this.x = a.x + b.x;
  5148. this.y = a.y + b.y;
  5149. return this;
  5150. },
  5151. addScaledVector: function ( v, s ) {
  5152. this.x += v.x * s;
  5153. this.y += v.y * s;
  5154. return this;
  5155. },
  5156. sub: function ( v, w ) {
  5157. if ( w !== undefined ) {
  5158. console.warn( 'THREE.Vector2: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  5159. return this.subVectors( v, w );
  5160. }
  5161. this.x -= v.x;
  5162. this.y -= v.y;
  5163. return this;
  5164. },
  5165. subScalar: function ( s ) {
  5166. this.x -= s;
  5167. this.y -= s;
  5168. return this;
  5169. },
  5170. subVectors: function ( a, b ) {
  5171. this.x = a.x - b.x;
  5172. this.y = a.y - b.y;
  5173. return this;
  5174. },
  5175. multiply: function ( v ) {
  5176. this.x *= v.x;
  5177. this.y *= v.y;
  5178. return this;
  5179. },
  5180. multiplyScalar: function ( scalar ) {
  5181. this.x *= scalar;
  5182. this.y *= scalar;
  5183. return this;
  5184. },
  5185. divide: function ( v ) {
  5186. this.x /= v.x;
  5187. this.y /= v.y;
  5188. return this;
  5189. },
  5190. divideScalar: function ( scalar ) {
  5191. return this.multiplyScalar( 1 / scalar );
  5192. },
  5193. applyMatrix3: function ( m ) {
  5194. var x = this.x, y = this.y;
  5195. var e = m.elements;
  5196. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ];
  5197. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ];
  5198. return this;
  5199. },
  5200. min: function ( v ) {
  5201. this.x = Math.min( this.x, v.x );
  5202. this.y = Math.min( this.y, v.y );
  5203. return this;
  5204. },
  5205. max: function ( v ) {
  5206. this.x = Math.max( this.x, v.x );
  5207. this.y = Math.max( this.y, v.y );
  5208. return this;
  5209. },
  5210. clamp: function ( min, max ) {
  5211. // assumes min < max, componentwise
  5212. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  5213. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  5214. return this;
  5215. },
  5216. clampScalar: function () {
  5217. var min = new Vector2();
  5218. var max = new Vector2();
  5219. return function clampScalar( minVal, maxVal ) {
  5220. min.set( minVal, minVal );
  5221. max.set( maxVal, maxVal );
  5222. return this.clamp( min, max );
  5223. };
  5224. }(),
  5225. clampLength: function ( min, max ) {
  5226. var length = this.length();
  5227. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  5228. },
  5229. floor: function () {
  5230. this.x = Math.floor( this.x );
  5231. this.y = Math.floor( this.y );
  5232. return this;
  5233. },
  5234. ceil: function () {
  5235. this.x = Math.ceil( this.x );
  5236. this.y = Math.ceil( this.y );
  5237. return this;
  5238. },
  5239. round: function () {
  5240. this.x = Math.round( this.x );
  5241. this.y = Math.round( this.y );
  5242. return this;
  5243. },
  5244. roundToZero: function () {
  5245. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  5246. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  5247. return this;
  5248. },
  5249. negate: function () {
  5250. this.x = - this.x;
  5251. this.y = - this.y;
  5252. return this;
  5253. },
  5254. dot: function ( v ) {
  5255. return this.x * v.x + this.y * v.y;
  5256. },
  5257. cross: function ( v ) {
  5258. return this.x * v.y - this.y * v.x;
  5259. },
  5260. lengthSq: function () {
  5261. return this.x * this.x + this.y * this.y;
  5262. },
  5263. length: function () {
  5264. return Math.sqrt( this.x * this.x + this.y * this.y );
  5265. },
  5266. manhattanLength: function () {
  5267. return Math.abs( this.x ) + Math.abs( this.y );
  5268. },
  5269. normalize: function () {
  5270. return this.divideScalar( this.length() || 1 );
  5271. },
  5272. angle: function () {
  5273. // computes the angle in radians with respect to the positive x-axis
  5274. var angle = Math.atan2( this.y, this.x );
  5275. if ( angle < 0 ) angle += 2 * Math.PI;
  5276. return angle;
  5277. },
  5278. distanceTo: function ( v ) {
  5279. return Math.sqrt( this.distanceToSquared( v ) );
  5280. },
  5281. distanceToSquared: function ( v ) {
  5282. var dx = this.x - v.x, dy = this.y - v.y;
  5283. return dx * dx + dy * dy;
  5284. },
  5285. manhattanDistanceTo: function ( v ) {
  5286. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y );
  5287. },
  5288. setLength: function ( length ) {
  5289. return this.normalize().multiplyScalar( length );
  5290. },
  5291. lerp: function ( v, alpha ) {
  5292. this.x += ( v.x - this.x ) * alpha;
  5293. this.y += ( v.y - this.y ) * alpha;
  5294. return this;
  5295. },
  5296. lerpVectors: function ( v1, v2, alpha ) {
  5297. return this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 );
  5298. },
  5299. equals: function ( v ) {
  5300. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  5301. },
  5302. fromArray: function ( array, offset ) {
  5303. if ( offset === undefined ) offset = 0;
  5304. this.x = array[ offset ];
  5305. this.y = array[ offset + 1 ];
  5306. return this;
  5307. },
  5308. toArray: function ( array, offset ) {
  5309. if ( array === undefined ) array = [];
  5310. if ( offset === undefined ) offset = 0;
  5311. array[ offset ] = this.x;
  5312. array[ offset + 1 ] = this.y;
  5313. return array;
  5314. },
  5315. fromBufferAttribute: function ( attribute, index, offset ) {
  5316. if ( offset !== undefined ) {
  5317. console.warn( 'THREE.Vector2: offset has been removed from .fromBufferAttribute().' );
  5318. }
  5319. this.x = attribute.getX( index );
  5320. this.y = attribute.getY( index );
  5321. return this;
  5322. },
  5323. rotateAround: function ( center, angle ) {
  5324. var c = Math.cos( angle ), s = Math.sin( angle );
  5325. var x = this.x - center.x;
  5326. var y = this.y - center.y;
  5327. this.x = x * c - y * s + center.x;
  5328. this.y = x * s + y * c + center.y;
  5329. return this;
  5330. }
  5331. } );
  5332. /**
  5333. * @author mrdoob / http://mrdoob.com/
  5334. * @author supereggbert / http://www.paulbrunt.co.uk/
  5335. * @author philogb / http://blog.thejit.org/
  5336. * @author jordi_ros / http://plattsoft.com
  5337. * @author D1plo1d / http://github.com/D1plo1d
  5338. * @author alteredq / http://alteredqualia.com/
  5339. * @author mikael emtinger / http://gomo.se/
  5340. * @author timknip / http://www.floorplanner.com/
  5341. * @author bhouston / http://clara.io
  5342. * @author WestLangley / http://github.com/WestLangley
  5343. */
  5344. function Matrix4() {
  5345. this.elements = [
  5346. 1, 0, 0, 0,
  5347. 0, 1, 0, 0,
  5348. 0, 0, 1, 0,
  5349. 0, 0, 0, 1
  5350. ];
  5351. if ( arguments.length > 0 ) {
  5352. console.error( 'THREE.Matrix4: the constructor no longer reads arguments. use .set() instead.' );
  5353. }
  5354. }
  5355. Object.assign( Matrix4.prototype, {
  5356. isMatrix4: true,
  5357. set: function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  5358. var te = this.elements;
  5359. te[ 0 ] = n11; te[ 4 ] = n12; te[ 8 ] = n13; te[ 12 ] = n14;
  5360. te[ 1 ] = n21; te[ 5 ] = n22; te[ 9 ] = n23; te[ 13 ] = n24;
  5361. te[ 2 ] = n31; te[ 6 ] = n32; te[ 10 ] = n33; te[ 14 ] = n34;
  5362. te[ 3 ] = n41; te[ 7 ] = n42; te[ 11 ] = n43; te[ 15 ] = n44;
  5363. return this;
  5364. },
  5365. identity: function () {
  5366. this.set(
  5367. 1, 0, 0, 0,
  5368. 0, 1, 0, 0,
  5369. 0, 0, 1, 0,
  5370. 0, 0, 0, 1
  5371. );
  5372. return this;
  5373. },
  5374. clone: function () {
  5375. return new Matrix4().fromArray( this.elements );
  5376. },
  5377. copy: function ( m ) {
  5378. var te = this.elements;
  5379. var me = m.elements;
  5380. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ]; te[ 3 ] = me[ 3 ];
  5381. te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ]; te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ];
  5382. te[ 8 ] = me[ 8 ]; te[ 9 ] = me[ 9 ]; te[ 10 ] = me[ 10 ]; te[ 11 ] = me[ 11 ];
  5383. te[ 12 ] = me[ 12 ]; te[ 13 ] = me[ 13 ]; te[ 14 ] = me[ 14 ]; te[ 15 ] = me[ 15 ];
  5384. return this;
  5385. },
  5386. copyPosition: function ( m ) {
  5387. var te = this.elements, me = m.elements;
  5388. te[ 12 ] = me[ 12 ];
  5389. te[ 13 ] = me[ 13 ];
  5390. te[ 14 ] = me[ 14 ];
  5391. return this;
  5392. },
  5393. extractBasis: function ( xAxis, yAxis, zAxis ) {
  5394. xAxis.setFromMatrixColumn( this, 0 );
  5395. yAxis.setFromMatrixColumn( this, 1 );
  5396. zAxis.setFromMatrixColumn( this, 2 );
  5397. return this;
  5398. },
  5399. makeBasis: function ( xAxis, yAxis, zAxis ) {
  5400. this.set(
  5401. xAxis.x, yAxis.x, zAxis.x, 0,
  5402. xAxis.y, yAxis.y, zAxis.y, 0,
  5403. xAxis.z, yAxis.z, zAxis.z, 0,
  5404. 0, 0, 0, 1
  5405. );
  5406. return this;
  5407. },
  5408. extractRotation: function () {
  5409. var v1 = new Vector3();
  5410. return function extractRotation( m ) {
  5411. // this method does not support reflection matrices
  5412. var te = this.elements;
  5413. var me = m.elements;
  5414. var scaleX = 1 / v1.setFromMatrixColumn( m, 0 ).length();
  5415. var scaleY = 1 / v1.setFromMatrixColumn( m, 1 ).length();
  5416. var scaleZ = 1 / v1.setFromMatrixColumn( m, 2 ).length();
  5417. te[ 0 ] = me[ 0 ] * scaleX;
  5418. te[ 1 ] = me[ 1 ] * scaleX;
  5419. te[ 2 ] = me[ 2 ] * scaleX;
  5420. te[ 3 ] = 0;
  5421. te[ 4 ] = me[ 4 ] * scaleY;
  5422. te[ 5 ] = me[ 5 ] * scaleY;
  5423. te[ 6 ] = me[ 6 ] * scaleY;
  5424. te[ 7 ] = 0;
  5425. te[ 8 ] = me[ 8 ] * scaleZ;
  5426. te[ 9 ] = me[ 9 ] * scaleZ;
  5427. te[ 10 ] = me[ 10 ] * scaleZ;
  5428. te[ 11 ] = 0;
  5429. te[ 12 ] = 0;
  5430. te[ 13 ] = 0;
  5431. te[ 14 ] = 0;
  5432. te[ 15 ] = 1;
  5433. return this;
  5434. };
  5435. }(),
  5436. makeRotationFromEuler: function ( euler ) {
  5437. if ( ! ( euler && euler.isEuler ) ) {
  5438. console.error( 'THREE.Matrix4: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.' );
  5439. }
  5440. var te = this.elements;
  5441. var x = euler.x, y = euler.y, z = euler.z;
  5442. var a = Math.cos( x ), b = Math.sin( x );
  5443. var c = Math.cos( y ), d = Math.sin( y );
  5444. var e = Math.cos( z ), f = Math.sin( z );
  5445. if ( euler.order === 'XYZ' ) {
  5446. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  5447. te[ 0 ] = c * e;
  5448. te[ 4 ] = - c * f;
  5449. te[ 8 ] = d;
  5450. te[ 1 ] = af + be * d;
  5451. te[ 5 ] = ae - bf * d;
  5452. te[ 9 ] = - b * c;
  5453. te[ 2 ] = bf - ae * d;
  5454. te[ 6 ] = be + af * d;
  5455. te[ 10 ] = a * c;
  5456. } else if ( euler.order === 'YXZ' ) {
  5457. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  5458. te[ 0 ] = ce + df * b;
  5459. te[ 4 ] = de * b - cf;
  5460. te[ 8 ] = a * d;
  5461. te[ 1 ] = a * f;
  5462. te[ 5 ] = a * e;
  5463. te[ 9 ] = - b;
  5464. te[ 2 ] = cf * b - de;
  5465. te[ 6 ] = df + ce * b;
  5466. te[ 10 ] = a * c;
  5467. } else if ( euler.order === 'ZXY' ) {
  5468. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  5469. te[ 0 ] = ce - df * b;
  5470. te[ 4 ] = - a * f;
  5471. te[ 8 ] = de + cf * b;
  5472. te[ 1 ] = cf + de * b;
  5473. te[ 5 ] = a * e;
  5474. te[ 9 ] = df - ce * b;
  5475. te[ 2 ] = - a * d;
  5476. te[ 6 ] = b;
  5477. te[ 10 ] = a * c;
  5478. } else if ( euler.order === 'ZYX' ) {
  5479. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  5480. te[ 0 ] = c * e;
  5481. te[ 4 ] = be * d - af;
  5482. te[ 8 ] = ae * d + bf;
  5483. te[ 1 ] = c * f;
  5484. te[ 5 ] = bf * d + ae;
  5485. te[ 9 ] = af * d - be;
  5486. te[ 2 ] = - d;
  5487. te[ 6 ] = b * c;
  5488. te[ 10 ] = a * c;
  5489. } else if ( euler.order === 'YZX' ) {
  5490. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  5491. te[ 0 ] = c * e;
  5492. te[ 4 ] = bd - ac * f;
  5493. te[ 8 ] = bc * f + ad;
  5494. te[ 1 ] = f;
  5495. te[ 5 ] = a * e;
  5496. te[ 9 ] = - b * e;
  5497. te[ 2 ] = - d * e;
  5498. te[ 6 ] = ad * f + bc;
  5499. te[ 10 ] = ac - bd * f;
  5500. } else if ( euler.order === 'XZY' ) {
  5501. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  5502. te[ 0 ] = c * e;
  5503. te[ 4 ] = - f;
  5504. te[ 8 ] = d * e;
  5505. te[ 1 ] = ac * f + bd;
  5506. te[ 5 ] = a * e;
  5507. te[ 9 ] = ad * f - bc;
  5508. te[ 2 ] = bc * f - ad;
  5509. te[ 6 ] = b * e;
  5510. te[ 10 ] = bd * f + ac;
  5511. }
  5512. // bottom row
  5513. te[ 3 ] = 0;
  5514. te[ 7 ] = 0;
  5515. te[ 11 ] = 0;
  5516. // last column
  5517. te[ 12 ] = 0;
  5518. te[ 13 ] = 0;
  5519. te[ 14 ] = 0;
  5520. te[ 15 ] = 1;
  5521. return this;
  5522. },
  5523. makeRotationFromQuaternion: function () {
  5524. var zero = new Vector3( 0, 0, 0 );
  5525. var one = new Vector3( 1, 1, 1 );
  5526. return function makeRotationFromQuaternion( q ) {
  5527. return this.compose( zero, q, one );
  5528. };
  5529. }(),
  5530. lookAt: function () {
  5531. var x = new Vector3();
  5532. var y = new Vector3();
  5533. var z = new Vector3();
  5534. return function lookAt( eye, target, up ) {
  5535. var te = this.elements;
  5536. z.subVectors( eye, target );
  5537. if ( z.lengthSq() === 0 ) {
  5538. // eye and target are in the same position
  5539. z.z = 1;
  5540. }
  5541. z.normalize();
  5542. x.crossVectors( up, z );
  5543. if ( x.lengthSq() === 0 ) {
  5544. // up and z are parallel
  5545. if ( Math.abs( up.z ) === 1 ) {
  5546. z.x += 0.0001;
  5547. } else {
  5548. z.z += 0.0001;
  5549. }
  5550. z.normalize();
  5551. x.crossVectors( up, z );
  5552. }
  5553. x.normalize();
  5554. y.crossVectors( z, x );
  5555. te[ 0 ] = x.x; te[ 4 ] = y.x; te[ 8 ] = z.x;
  5556. te[ 1 ] = x.y; te[ 5 ] = y.y; te[ 9 ] = z.y;
  5557. te[ 2 ] = x.z; te[ 6 ] = y.z; te[ 10 ] = z.z;
  5558. return this;
  5559. };
  5560. }(),
  5561. multiply: function ( m, n ) {
  5562. if ( n !== undefined ) {
  5563. console.warn( 'THREE.Matrix4: .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead.' );
  5564. return this.multiplyMatrices( m, n );
  5565. }
  5566. return this.multiplyMatrices( this, m );
  5567. },
  5568. premultiply: function ( m ) {
  5569. return this.multiplyMatrices( m, this );
  5570. },
  5571. multiplyMatrices: function ( a, b ) {
  5572. var ae = a.elements;
  5573. var be = b.elements;
  5574. var te = this.elements;
  5575. var a11 = ae[ 0 ], a12 = ae[ 4 ], a13 = ae[ 8 ], a14 = ae[ 12 ];
  5576. var a21 = ae[ 1 ], a22 = ae[ 5 ], a23 = ae[ 9 ], a24 = ae[ 13 ];
  5577. var a31 = ae[ 2 ], a32 = ae[ 6 ], a33 = ae[ 10 ], a34 = ae[ 14 ];
  5578. var a41 = ae[ 3 ], a42 = ae[ 7 ], a43 = ae[ 11 ], a44 = ae[ 15 ];
  5579. var b11 = be[ 0 ], b12 = be[ 4 ], b13 = be[ 8 ], b14 = be[ 12 ];
  5580. var b21 = be[ 1 ], b22 = be[ 5 ], b23 = be[ 9 ], b24 = be[ 13 ];
  5581. var b31 = be[ 2 ], b32 = be[ 6 ], b33 = be[ 10 ], b34 = be[ 14 ];
  5582. var b41 = be[ 3 ], b42 = be[ 7 ], b43 = be[ 11 ], b44 = be[ 15 ];
  5583. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  5584. te[ 4 ] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  5585. te[ 8 ] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  5586. te[ 12 ] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  5587. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  5588. te[ 5 ] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  5589. te[ 9 ] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  5590. te[ 13 ] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  5591. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  5592. te[ 6 ] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  5593. te[ 10 ] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  5594. te[ 14 ] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  5595. te[ 3 ] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  5596. te[ 7 ] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  5597. te[ 11 ] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  5598. te[ 15 ] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  5599. return this;
  5600. },
  5601. multiplyScalar: function ( s ) {
  5602. var te = this.elements;
  5603. te[ 0 ] *= s; te[ 4 ] *= s; te[ 8 ] *= s; te[ 12 ] *= s;
  5604. te[ 1 ] *= s; te[ 5 ] *= s; te[ 9 ] *= s; te[ 13 ] *= s;
  5605. te[ 2 ] *= s; te[ 6 ] *= s; te[ 10 ] *= s; te[ 14 ] *= s;
  5606. te[ 3 ] *= s; te[ 7 ] *= s; te[ 11 ] *= s; te[ 15 ] *= s;
  5607. return this;
  5608. },
  5609. applyToBufferAttribute: function () {
  5610. var v1 = new Vector3();
  5611. return function applyToBufferAttribute( attribute ) {
  5612. for ( var i = 0, l = attribute.count; i < l; i ++ ) {
  5613. v1.x = attribute.getX( i );
  5614. v1.y = attribute.getY( i );
  5615. v1.z = attribute.getZ( i );
  5616. v1.applyMatrix4( this );
  5617. attribute.setXYZ( i, v1.x, v1.y, v1.z );
  5618. }
  5619. return attribute;
  5620. };
  5621. }(),
  5622. determinant: function () {
  5623. var te = this.elements;
  5624. var n11 = te[ 0 ], n12 = te[ 4 ], n13 = te[ 8 ], n14 = te[ 12 ];
  5625. var n21 = te[ 1 ], n22 = te[ 5 ], n23 = te[ 9 ], n24 = te[ 13 ];
  5626. var n31 = te[ 2 ], n32 = te[ 6 ], n33 = te[ 10 ], n34 = te[ 14 ];
  5627. var n41 = te[ 3 ], n42 = te[ 7 ], n43 = te[ 11 ], n44 = te[ 15 ];
  5628. //TODO: make this more efficient
  5629. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  5630. return (
  5631. n41 * (
  5632. + n14 * n23 * n32
  5633. - n13 * n24 * n32
  5634. - n14 * n22 * n33
  5635. + n12 * n24 * n33
  5636. + n13 * n22 * n34
  5637. - n12 * n23 * n34
  5638. ) +
  5639. n42 * (
  5640. + n11 * n23 * n34
  5641. - n11 * n24 * n33
  5642. + n14 * n21 * n33
  5643. - n13 * n21 * n34
  5644. + n13 * n24 * n31
  5645. - n14 * n23 * n31
  5646. ) +
  5647. n43 * (
  5648. + n11 * n24 * n32
  5649. - n11 * n22 * n34
  5650. - n14 * n21 * n32
  5651. + n12 * n21 * n34
  5652. + n14 * n22 * n31
  5653. - n12 * n24 * n31
  5654. ) +
  5655. n44 * (
  5656. - n13 * n22 * n31
  5657. - n11 * n23 * n32
  5658. + n11 * n22 * n33
  5659. + n13 * n21 * n32
  5660. - n12 * n21 * n33
  5661. + n12 * n23 * n31
  5662. )
  5663. );
  5664. },
  5665. transpose: function () {
  5666. var te = this.elements;
  5667. var tmp;
  5668. tmp = te[ 1 ]; te[ 1 ] = te[ 4 ]; te[ 4 ] = tmp;
  5669. tmp = te[ 2 ]; te[ 2 ] = te[ 8 ]; te[ 8 ] = tmp;
  5670. tmp = te[ 6 ]; te[ 6 ] = te[ 9 ]; te[ 9 ] = tmp;
  5671. tmp = te[ 3 ]; te[ 3 ] = te[ 12 ]; te[ 12 ] = tmp;
  5672. tmp = te[ 7 ]; te[ 7 ] = te[ 13 ]; te[ 13 ] = tmp;
  5673. tmp = te[ 11 ]; te[ 11 ] = te[ 14 ]; te[ 14 ] = tmp;
  5674. return this;
  5675. },
  5676. setPosition: function ( v ) {
  5677. var te = this.elements;
  5678. te[ 12 ] = v.x;
  5679. te[ 13 ] = v.y;
  5680. te[ 14 ] = v.z;
  5681. return this;
  5682. },
  5683. getInverse: function ( m, throwOnDegenerate ) {
  5684. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  5685. var te = this.elements,
  5686. me = m.elements,
  5687. n11 = me[ 0 ], n21 = me[ 1 ], n31 = me[ 2 ], n41 = me[ 3 ],
  5688. n12 = me[ 4 ], n22 = me[ 5 ], n32 = me[ 6 ], n42 = me[ 7 ],
  5689. n13 = me[ 8 ], n23 = me[ 9 ], n33 = me[ 10 ], n43 = me[ 11 ],
  5690. n14 = me[ 12 ], n24 = me[ 13 ], n34 = me[ 14 ], n44 = me[ 15 ],
  5691. t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44,
  5692. t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44,
  5693. t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44,
  5694. t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;
  5695. var det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14;
  5696. if ( det === 0 ) {
  5697. var msg = "THREE.Matrix4: .getInverse() can't invert matrix, determinant is 0";
  5698. if ( throwOnDegenerate === true ) {
  5699. throw new Error( msg );
  5700. } else {
  5701. console.warn( msg );
  5702. }
  5703. return this.identity();
  5704. }
  5705. var detInv = 1 / det;
  5706. te[ 0 ] = t11 * detInv;
  5707. te[ 1 ] = ( n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44 ) * detInv;
  5708. te[ 2 ] = ( n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44 ) * detInv;
  5709. te[ 3 ] = ( n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43 ) * detInv;
  5710. te[ 4 ] = t12 * detInv;
  5711. te[ 5 ] = ( n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44 ) * detInv;
  5712. te[ 6 ] = ( n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44 ) * detInv;
  5713. te[ 7 ] = ( n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43 ) * detInv;
  5714. te[ 8 ] = t13 * detInv;
  5715. te[ 9 ] = ( n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44 ) * detInv;
  5716. te[ 10 ] = ( n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44 ) * detInv;
  5717. te[ 11 ] = ( n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43 ) * detInv;
  5718. te[ 12 ] = t14 * detInv;
  5719. te[ 13 ] = ( n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34 ) * detInv;
  5720. te[ 14 ] = ( n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34 ) * detInv;
  5721. te[ 15 ] = ( n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33 ) * detInv;
  5722. return this;
  5723. },
  5724. scale: function ( v ) {
  5725. var te = this.elements;
  5726. var x = v.x, y = v.y, z = v.z;
  5727. te[ 0 ] *= x; te[ 4 ] *= y; te[ 8 ] *= z;
  5728. te[ 1 ] *= x; te[ 5 ] *= y; te[ 9 ] *= z;
  5729. te[ 2 ] *= x; te[ 6 ] *= y; te[ 10 ] *= z;
  5730. te[ 3 ] *= x; te[ 7 ] *= y; te[ 11 ] *= z;
  5731. return this;
  5732. },
  5733. getMaxScaleOnAxis: function () {
  5734. var te = this.elements;
  5735. var scaleXSq = te[ 0 ] * te[ 0 ] + te[ 1 ] * te[ 1 ] + te[ 2 ] * te[ 2 ];
  5736. var scaleYSq = te[ 4 ] * te[ 4 ] + te[ 5 ] * te[ 5 ] + te[ 6 ] * te[ 6 ];
  5737. var scaleZSq = te[ 8 ] * te[ 8 ] + te[ 9 ] * te[ 9 ] + te[ 10 ] * te[ 10 ];
  5738. return Math.sqrt( Math.max( scaleXSq, scaleYSq, scaleZSq ) );
  5739. },
  5740. makeTranslation: function ( x, y, z ) {
  5741. this.set(
  5742. 1, 0, 0, x,
  5743. 0, 1, 0, y,
  5744. 0, 0, 1, z,
  5745. 0, 0, 0, 1
  5746. );
  5747. return this;
  5748. },
  5749. makeRotationX: function ( theta ) {
  5750. var c = Math.cos( theta ), s = Math.sin( theta );
  5751. this.set(
  5752. 1, 0, 0, 0,
  5753. 0, c, - s, 0,
  5754. 0, s, c, 0,
  5755. 0, 0, 0, 1
  5756. );
  5757. return this;
  5758. },
  5759. makeRotationY: function ( theta ) {
  5760. var c = Math.cos( theta ), s = Math.sin( theta );
  5761. this.set(
  5762. c, 0, s, 0,
  5763. 0, 1, 0, 0,
  5764. - s, 0, c, 0,
  5765. 0, 0, 0, 1
  5766. );
  5767. return this;
  5768. },
  5769. makeRotationZ: function ( theta ) {
  5770. var c = Math.cos( theta ), s = Math.sin( theta );
  5771. this.set(
  5772. c, - s, 0, 0,
  5773. s, c, 0, 0,
  5774. 0, 0, 1, 0,
  5775. 0, 0, 0, 1
  5776. );
  5777. return this;
  5778. },
  5779. makeRotationAxis: function ( axis, angle ) {
  5780. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  5781. var c = Math.cos( angle );
  5782. var s = Math.sin( angle );
  5783. var t = 1 - c;
  5784. var x = axis.x, y = axis.y, z = axis.z;
  5785. var tx = t * x, ty = t * y;
  5786. this.set(
  5787. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  5788. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  5789. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  5790. 0, 0, 0, 1
  5791. );
  5792. return this;
  5793. },
  5794. makeScale: function ( x, y, z ) {
  5795. this.set(
  5796. x, 0, 0, 0,
  5797. 0, y, 0, 0,
  5798. 0, 0, z, 0,
  5799. 0, 0, 0, 1
  5800. );
  5801. return this;
  5802. },
  5803. makeShear: function ( x, y, z ) {
  5804. this.set(
  5805. 1, y, z, 0,
  5806. x, 1, z, 0,
  5807. x, y, 1, 0,
  5808. 0, 0, 0, 1
  5809. );
  5810. return this;
  5811. },
  5812. compose: function ( position, quaternion, scale ) {
  5813. var te = this.elements;
  5814. var x = quaternion._x, y = quaternion._y, z = quaternion._z, w = quaternion._w;
  5815. var x2 = x + x, y2 = y + y, z2 = z + z;
  5816. var xx = x * x2, xy = x * y2, xz = x * z2;
  5817. var yy = y * y2, yz = y * z2, zz = z * z2;
  5818. var wx = w * x2, wy = w * y2, wz = w * z2;
  5819. var sx = scale.x, sy = scale.y, sz = scale.z;
  5820. te[ 0 ] = ( 1 - ( yy + zz ) ) * sx;
  5821. te[ 1 ] = ( xy + wz ) * sx;
  5822. te[ 2 ] = ( xz - wy ) * sx;
  5823. te[ 3 ] = 0;
  5824. te[ 4 ] = ( xy - wz ) * sy;
  5825. te[ 5 ] = ( 1 - ( xx + zz ) ) * sy;
  5826. te[ 6 ] = ( yz + wx ) * sy;
  5827. te[ 7 ] = 0;
  5828. te[ 8 ] = ( xz + wy ) * sz;
  5829. te[ 9 ] = ( yz - wx ) * sz;
  5830. te[ 10 ] = ( 1 - ( xx + yy ) ) * sz;
  5831. te[ 11 ] = 0;
  5832. te[ 12 ] = position.x;
  5833. te[ 13 ] = position.y;
  5834. te[ 14 ] = position.z;
  5835. te[ 15 ] = 1;
  5836. return this;
  5837. },
  5838. decompose: function () {
  5839. var vector = new Vector3();
  5840. var matrix = new Matrix4();
  5841. return function decompose( position, quaternion, scale ) {
  5842. var te = this.elements;
  5843. var sx = vector.set( te[ 0 ], te[ 1 ], te[ 2 ] ).length();
  5844. var sy = vector.set( te[ 4 ], te[ 5 ], te[ 6 ] ).length();
  5845. var sz = vector.set( te[ 8 ], te[ 9 ], te[ 10 ] ).length();
  5846. // if determine is negative, we need to invert one scale
  5847. var det = this.determinant();
  5848. if ( det < 0 ) sx = - sx;
  5849. position.x = te[ 12 ];
  5850. position.y = te[ 13 ];
  5851. position.z = te[ 14 ];
  5852. // scale the rotation part
  5853. matrix.copy( this );
  5854. var invSX = 1 / sx;
  5855. var invSY = 1 / sy;
  5856. var invSZ = 1 / sz;
  5857. matrix.elements[ 0 ] *= invSX;
  5858. matrix.elements[ 1 ] *= invSX;
  5859. matrix.elements[ 2 ] *= invSX;
  5860. matrix.elements[ 4 ] *= invSY;
  5861. matrix.elements[ 5 ] *= invSY;
  5862. matrix.elements[ 6 ] *= invSY;
  5863. matrix.elements[ 8 ] *= invSZ;
  5864. matrix.elements[ 9 ] *= invSZ;
  5865. matrix.elements[ 10 ] *= invSZ;
  5866. quaternion.setFromRotationMatrix( matrix );
  5867. scale.x = sx;
  5868. scale.y = sy;
  5869. scale.z = sz;
  5870. return this;
  5871. };
  5872. }(),
  5873. makePerspective: function ( left, right, top, bottom, near, far ) {
  5874. if ( far === undefined ) {
  5875. console.warn( 'THREE.Matrix4: .makePerspective() has been redefined and has a new signature. Please check the docs.' );
  5876. }
  5877. var te = this.elements;
  5878. var x = 2 * near / ( right - left );
  5879. var y = 2 * near / ( top - bottom );
  5880. var a = ( right + left ) / ( right - left );
  5881. var b = ( top + bottom ) / ( top - bottom );
  5882. var c = - ( far + near ) / ( far - near );
  5883. var d = - 2 * far * near / ( far - near );
  5884. te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = a; te[ 12 ] = 0;
  5885. te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = b; te[ 13 ] = 0;
  5886. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d;
  5887. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = - 1; te[ 15 ] = 0;
  5888. return this;
  5889. },
  5890. makeOrthographic: function ( left, right, top, bottom, near, far ) {
  5891. var te = this.elements;
  5892. var w = 1.0 / ( right - left );
  5893. var h = 1.0 / ( top - bottom );
  5894. var p = 1.0 / ( far - near );
  5895. var x = ( right + left ) * w;
  5896. var y = ( top + bottom ) * h;
  5897. var z = ( far + near ) * p;
  5898. te[ 0 ] = 2 * w; te[ 4 ] = 0; te[ 8 ] = 0; te[ 12 ] = - x;
  5899. te[ 1 ] = 0; te[ 5 ] = 2 * h; te[ 9 ] = 0; te[ 13 ] = - y;
  5900. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = - 2 * p; te[ 14 ] = - z;
  5901. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = 0; te[ 15 ] = 1;
  5902. return this;
  5903. },
  5904. equals: function ( matrix ) {
  5905. var te = this.elements;
  5906. var me = matrix.elements;
  5907. for ( var i = 0; i < 16; i ++ ) {
  5908. if ( te[ i ] !== me[ i ] ) return false;
  5909. }
  5910. return true;
  5911. },
  5912. fromArray: function ( array, offset ) {
  5913. if ( offset === undefined ) offset = 0;
  5914. for ( var i = 0; i < 16; i ++ ) {
  5915. this.elements[ i ] = array[ i + offset ];
  5916. }
  5917. return this;
  5918. },
  5919. toArray: function ( array, offset ) {
  5920. if ( array === undefined ) array = [];
  5921. if ( offset === undefined ) offset = 0;
  5922. var te = this.elements;
  5923. array[ offset ] = te[ 0 ];
  5924. array[ offset + 1 ] = te[ 1 ];
  5925. array[ offset + 2 ] = te[ 2 ];
  5926. array[ offset + 3 ] = te[ 3 ];
  5927. array[ offset + 4 ] = te[ 4 ];
  5928. array[ offset + 5 ] = te[ 5 ];
  5929. array[ offset + 6 ] = te[ 6 ];
  5930. array[ offset + 7 ] = te[ 7 ];
  5931. array[ offset + 8 ] = te[ 8 ];
  5932. array[ offset + 9 ] = te[ 9 ];
  5933. array[ offset + 10 ] = te[ 10 ];
  5934. array[ offset + 11 ] = te[ 11 ];
  5935. array[ offset + 12 ] = te[ 12 ];
  5936. array[ offset + 13 ] = te[ 13 ];
  5937. array[ offset + 14 ] = te[ 14 ];
  5938. array[ offset + 15 ] = te[ 15 ];
  5939. return array;
  5940. }
  5941. } );
  5942. /**
  5943. * @author mikael emtinger / http://gomo.se/
  5944. * @author alteredq / http://alteredqualia.com/
  5945. * @author WestLangley / http://github.com/WestLangley
  5946. * @author bhouston / http://clara.io
  5947. */
  5948. function Quaternion( x, y, z, w ) {
  5949. this._x = x || 0;
  5950. this._y = y || 0;
  5951. this._z = z || 0;
  5952. this._w = ( w !== undefined ) ? w : 1;
  5953. }
  5954. Object.assign( Quaternion, {
  5955. slerp: function ( qa, qb, qm, t ) {
  5956. return qm.copy( qa ).slerp( qb, t );
  5957. },
  5958. slerpFlat: function ( dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t ) {
  5959. // fuzz-free, array-based Quaternion SLERP operation
  5960. var x0 = src0[ srcOffset0 + 0 ],
  5961. y0 = src0[ srcOffset0 + 1 ],
  5962. z0 = src0[ srcOffset0 + 2 ],
  5963. w0 = src0[ srcOffset0 + 3 ],
  5964. x1 = src1[ srcOffset1 + 0 ],
  5965. y1 = src1[ srcOffset1 + 1 ],
  5966. z1 = src1[ srcOffset1 + 2 ],
  5967. w1 = src1[ srcOffset1 + 3 ];
  5968. if ( w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1 ) {
  5969. var s = 1 - t,
  5970. cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1,
  5971. dir = ( cos >= 0 ? 1 : - 1 ),
  5972. sqrSin = 1 - cos * cos;
  5973. // Skip the Slerp for tiny steps to avoid numeric problems:
  5974. if ( sqrSin > Number.EPSILON ) {
  5975. var sin = Math.sqrt( sqrSin ),
  5976. len = Math.atan2( sin, cos * dir );
  5977. s = Math.sin( s * len ) / sin;
  5978. t = Math.sin( t * len ) / sin;
  5979. }
  5980. var tDir = t * dir;
  5981. x0 = x0 * s + x1 * tDir;
  5982. y0 = y0 * s + y1 * tDir;
  5983. z0 = z0 * s + z1 * tDir;
  5984. w0 = w0 * s + w1 * tDir;
  5985. // Normalize in case we just did a lerp:
  5986. if ( s === 1 - t ) {
  5987. var f = 1 / Math.sqrt( x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0 );
  5988. x0 *= f;
  5989. y0 *= f;
  5990. z0 *= f;
  5991. w0 *= f;
  5992. }
  5993. }
  5994. dst[ dstOffset ] = x0;
  5995. dst[ dstOffset + 1 ] = y0;
  5996. dst[ dstOffset + 2 ] = z0;
  5997. dst[ dstOffset + 3 ] = w0;
  5998. }
  5999. } );
  6000. Object.defineProperties( Quaternion.prototype, {
  6001. x: {
  6002. get: function () {
  6003. return this._x;
  6004. },
  6005. set: function ( value ) {
  6006. this._x = value;
  6007. this.onChangeCallback();
  6008. }
  6009. },
  6010. y: {
  6011. get: function () {
  6012. return this._y;
  6013. },
  6014. set: function ( value ) {
  6015. this._y = value;
  6016. this.onChangeCallback();
  6017. }
  6018. },
  6019. z: {
  6020. get: function () {
  6021. return this._z;
  6022. },
  6023. set: function ( value ) {
  6024. this._z = value;
  6025. this.onChangeCallback();
  6026. }
  6027. },
  6028. w: {
  6029. get: function () {
  6030. return this._w;
  6031. },
  6032. set: function ( value ) {
  6033. this._w = value;
  6034. this.onChangeCallback();
  6035. }
  6036. }
  6037. } );
  6038. Object.assign( Quaternion.prototype, {
  6039. isQuaternion: true,
  6040. set: function ( x, y, z, w ) {
  6041. this._x = x;
  6042. this._y = y;
  6043. this._z = z;
  6044. this._w = w;
  6045. this.onChangeCallback();
  6046. return this;
  6047. },
  6048. clone: function () {
  6049. return new this.constructor( this._x, this._y, this._z, this._w );
  6050. },
  6051. copy: function ( quaternion ) {
  6052. this._x = quaternion.x;
  6053. this._y = quaternion.y;
  6054. this._z = quaternion.z;
  6055. this._w = quaternion.w;
  6056. this.onChangeCallback();
  6057. return this;
  6058. },
  6059. setFromEuler: function ( euler, update ) {
  6060. if ( ! ( euler && euler.isEuler ) ) {
  6061. throw new Error( 'THREE.Quaternion: .setFromEuler() now expects an Euler rotation rather than a Vector3 and order.' );
  6062. }
  6063. var x = euler._x, y = euler._y, z = euler._z, order = euler.order;
  6064. // http://www.mathworks.com/matlabcentral/fileexchange/
  6065. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  6066. // content/SpinCalc.m
  6067. var cos = Math.cos;
  6068. var sin = Math.sin;
  6069. var c1 = cos( x / 2 );
  6070. var c2 = cos( y / 2 );
  6071. var c3 = cos( z / 2 );
  6072. var s1 = sin( x / 2 );
  6073. var s2 = sin( y / 2 );
  6074. var s3 = sin( z / 2 );
  6075. if ( order === 'XYZ' ) {
  6076. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  6077. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  6078. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  6079. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  6080. } else if ( order === 'YXZ' ) {
  6081. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  6082. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  6083. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  6084. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  6085. } else if ( order === 'ZXY' ) {
  6086. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  6087. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  6088. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  6089. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  6090. } else if ( order === 'ZYX' ) {
  6091. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  6092. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  6093. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  6094. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  6095. } else if ( order === 'YZX' ) {
  6096. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  6097. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  6098. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  6099. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  6100. } else if ( order === 'XZY' ) {
  6101. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  6102. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  6103. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  6104. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  6105. }
  6106. if ( update !== false ) this.onChangeCallback();
  6107. return this;
  6108. },
  6109. setFromAxisAngle: function ( axis, angle ) {
  6110. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  6111. // assumes axis is normalized
  6112. var halfAngle = angle / 2, s = Math.sin( halfAngle );
  6113. this._x = axis.x * s;
  6114. this._y = axis.y * s;
  6115. this._z = axis.z * s;
  6116. this._w = Math.cos( halfAngle );
  6117. this.onChangeCallback();
  6118. return this;
  6119. },
  6120. setFromRotationMatrix: function ( m ) {
  6121. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  6122. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  6123. var te = m.elements,
  6124. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  6125. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  6126. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ],
  6127. trace = m11 + m22 + m33,
  6128. s;
  6129. if ( trace > 0 ) {
  6130. s = 0.5 / Math.sqrt( trace + 1.0 );
  6131. this._w = 0.25 / s;
  6132. this._x = ( m32 - m23 ) * s;
  6133. this._y = ( m13 - m31 ) * s;
  6134. this._z = ( m21 - m12 ) * s;
  6135. } else if ( m11 > m22 && m11 > m33 ) {
  6136. s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  6137. this._w = ( m32 - m23 ) / s;
  6138. this._x = 0.25 * s;
  6139. this._y = ( m12 + m21 ) / s;
  6140. this._z = ( m13 + m31 ) / s;
  6141. } else if ( m22 > m33 ) {
  6142. s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  6143. this._w = ( m13 - m31 ) / s;
  6144. this._x = ( m12 + m21 ) / s;
  6145. this._y = 0.25 * s;
  6146. this._z = ( m23 + m32 ) / s;
  6147. } else {
  6148. s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  6149. this._w = ( m21 - m12 ) / s;
  6150. this._x = ( m13 + m31 ) / s;
  6151. this._y = ( m23 + m32 ) / s;
  6152. this._z = 0.25 * s;
  6153. }
  6154. this.onChangeCallback();
  6155. return this;
  6156. },
  6157. setFromUnitVectors: function () {
  6158. // assumes direction vectors vFrom and vTo are normalized
  6159. var v1 = new Vector3();
  6160. var r;
  6161. var EPS = 0.000001;
  6162. return function setFromUnitVectors( vFrom, vTo ) {
  6163. if ( v1 === undefined ) v1 = new Vector3();
  6164. r = vFrom.dot( vTo ) + 1;
  6165. if ( r < EPS ) {
  6166. r = 0;
  6167. if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) {
  6168. v1.set( - vFrom.y, vFrom.x, 0 );
  6169. } else {
  6170. v1.set( 0, - vFrom.z, vFrom.y );
  6171. }
  6172. } else {
  6173. v1.crossVectors( vFrom, vTo );
  6174. }
  6175. this._x = v1.x;
  6176. this._y = v1.y;
  6177. this._z = v1.z;
  6178. this._w = r;
  6179. return this.normalize();
  6180. };
  6181. }(),
  6182. angleTo: function ( q ) {
  6183. return 2 * Math.acos( Math.abs( _Math.clamp( this.dot( q ), - 1, 1 ) ) );
  6184. },
  6185. rotateTowards: function ( q, step ) {
  6186. var angle = this.angleTo( q );
  6187. if ( angle === 0 ) return this;
  6188. var t = Math.min( 1, step / angle );
  6189. this.slerp( q, t );
  6190. return this;
  6191. },
  6192. inverse: function () {
  6193. // quaternion is assumed to have unit length
  6194. return this.conjugate();
  6195. },
  6196. conjugate: function () {
  6197. this._x *= - 1;
  6198. this._y *= - 1;
  6199. this._z *= - 1;
  6200. this.onChangeCallback();
  6201. return this;
  6202. },
  6203. dot: function ( v ) {
  6204. return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
  6205. },
  6206. lengthSq: function () {
  6207. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  6208. },
  6209. length: function () {
  6210. return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w );
  6211. },
  6212. normalize: function () {
  6213. var l = this.length();
  6214. if ( l === 0 ) {
  6215. this._x = 0;
  6216. this._y = 0;
  6217. this._z = 0;
  6218. this._w = 1;
  6219. } else {
  6220. l = 1 / l;
  6221. this._x = this._x * l;
  6222. this._y = this._y * l;
  6223. this._z = this._z * l;
  6224. this._w = this._w * l;
  6225. }
  6226. this.onChangeCallback();
  6227. return this;
  6228. },
  6229. multiply: function ( q, p ) {
  6230. if ( p !== undefined ) {
  6231. console.warn( 'THREE.Quaternion: .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead.' );
  6232. return this.multiplyQuaternions( q, p );
  6233. }
  6234. return this.multiplyQuaternions( this, q );
  6235. },
  6236. premultiply: function ( q ) {
  6237. return this.multiplyQuaternions( q, this );
  6238. },
  6239. multiplyQuaternions: function ( a, b ) {
  6240. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  6241. var qax = a._x, qay = a._y, qaz = a._z, qaw = a._w;
  6242. var qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w;
  6243. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  6244. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  6245. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  6246. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  6247. this.onChangeCallback();
  6248. return this;
  6249. },
  6250. slerp: function ( qb, t ) {
  6251. if ( t === 0 ) return this;
  6252. if ( t === 1 ) return this.copy( qb );
  6253. var x = this._x, y = this._y, z = this._z, w = this._w;
  6254. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  6255. var cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  6256. if ( cosHalfTheta < 0 ) {
  6257. this._w = - qb._w;
  6258. this._x = - qb._x;
  6259. this._y = - qb._y;
  6260. this._z = - qb._z;
  6261. cosHalfTheta = - cosHalfTheta;
  6262. } else {
  6263. this.copy( qb );
  6264. }
  6265. if ( cosHalfTheta >= 1.0 ) {
  6266. this._w = w;
  6267. this._x = x;
  6268. this._y = y;
  6269. this._z = z;
  6270. return this;
  6271. }
  6272. var sqrSinHalfTheta = 1.0 - cosHalfTheta * cosHalfTheta;
  6273. if ( sqrSinHalfTheta <= Number.EPSILON ) {
  6274. var s = 1 - t;
  6275. this._w = s * w + t * this._w;
  6276. this._x = s * x + t * this._x;
  6277. this._y = s * y + t * this._y;
  6278. this._z = s * z + t * this._z;
  6279. return this.normalize();
  6280. }
  6281. var sinHalfTheta = Math.sqrt( sqrSinHalfTheta );
  6282. var halfTheta = Math.atan2( sinHalfTheta, cosHalfTheta );
  6283. var ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  6284. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  6285. this._w = ( w * ratioA + this._w * ratioB );
  6286. this._x = ( x * ratioA + this._x * ratioB );
  6287. this._y = ( y * ratioA + this._y * ratioB );
  6288. this._z = ( z * ratioA + this._z * ratioB );
  6289. this.onChangeCallback();
  6290. return this;
  6291. },
  6292. equals: function ( quaternion ) {
  6293. return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w );
  6294. },
  6295. fromArray: function ( array, offset ) {
  6296. if ( offset === undefined ) offset = 0;
  6297. this._x = array[ offset ];
  6298. this._y = array[ offset + 1 ];
  6299. this._z = array[ offset + 2 ];
  6300. this._w = array[ offset + 3 ];
  6301. this.onChangeCallback();
  6302. return this;
  6303. },
  6304. toArray: function ( array, offset ) {
  6305. if ( array === undefined ) array = [];
  6306. if ( offset === undefined ) offset = 0;
  6307. array[ offset ] = this._x;
  6308. array[ offset + 1 ] = this._y;
  6309. array[ offset + 2 ] = this._z;
  6310. array[ offset + 3 ] = this._w;
  6311. return array;
  6312. },
  6313. onChange: function ( callback ) {
  6314. this.onChangeCallback = callback;
  6315. return this;
  6316. },
  6317. onChangeCallback: function () {}
  6318. } );
  6319. /**
  6320. * @author mrdoob / http://mrdoob.com/
  6321. * @author kile / http://kile.stravaganza.org/
  6322. * @author philogb / http://blog.thejit.org/
  6323. * @author mikael emtinger / http://gomo.se/
  6324. * @author egraether / http://egraether.com/
  6325. * @author WestLangley / http://github.com/WestLangley
  6326. */
  6327. function Vector3( x, y, z ) {
  6328. this.x = x || 0;
  6329. this.y = y || 0;
  6330. this.z = z || 0;
  6331. }
  6332. Object.assign( Vector3.prototype, {
  6333. isVector3: true,
  6334. set: function ( x, y, z ) {
  6335. this.x = x;
  6336. this.y = y;
  6337. this.z = z;
  6338. return this;
  6339. },
  6340. setScalar: function ( scalar ) {
  6341. this.x = scalar;
  6342. this.y = scalar;
  6343. this.z = scalar;
  6344. return this;
  6345. },
  6346. setX: function ( x ) {
  6347. this.x = x;
  6348. return this;
  6349. },
  6350. setY: function ( y ) {
  6351. this.y = y;
  6352. return this;
  6353. },
  6354. setZ: function ( z ) {
  6355. this.z = z;
  6356. return this;
  6357. },
  6358. setComponent: function ( index, value ) {
  6359. switch ( index ) {
  6360. case 0: this.x = value; break;
  6361. case 1: this.y = value; break;
  6362. case 2: this.z = value; break;
  6363. default: throw new Error( 'index is out of range: ' + index );
  6364. }
  6365. return this;
  6366. },
  6367. getComponent: function ( index ) {
  6368. switch ( index ) {
  6369. case 0: return this.x;
  6370. case 1: return this.y;
  6371. case 2: return this.z;
  6372. default: throw new Error( 'index is out of range: ' + index );
  6373. }
  6374. },
  6375. clone: function () {
  6376. return new this.constructor( this.x, this.y, this.z );
  6377. },
  6378. copy: function ( v ) {
  6379. this.x = v.x;
  6380. this.y = v.y;
  6381. this.z = v.z;
  6382. return this;
  6383. },
  6384. add: function ( v, w ) {
  6385. if ( w !== undefined ) {
  6386. console.warn( 'THREE.Vector3: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  6387. return this.addVectors( v, w );
  6388. }
  6389. this.x += v.x;
  6390. this.y += v.y;
  6391. this.z += v.z;
  6392. return this;
  6393. },
  6394. addScalar: function ( s ) {
  6395. this.x += s;
  6396. this.y += s;
  6397. this.z += s;
  6398. return this;
  6399. },
  6400. addVectors: function ( a, b ) {
  6401. this.x = a.x + b.x;
  6402. this.y = a.y + b.y;
  6403. this.z = a.z + b.z;
  6404. return this;
  6405. },
  6406. addScaledVector: function ( v, s ) {
  6407. this.x += v.x * s;
  6408. this.y += v.y * s;
  6409. this.z += v.z * s;
  6410. return this;
  6411. },
  6412. sub: function ( v, w ) {
  6413. if ( w !== undefined ) {
  6414. console.warn( 'THREE.Vector3: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  6415. return this.subVectors( v, w );
  6416. }
  6417. this.x -= v.x;
  6418. this.y -= v.y;
  6419. this.z -= v.z;
  6420. return this;
  6421. },
  6422. subScalar: function ( s ) {
  6423. this.x -= s;
  6424. this.y -= s;
  6425. this.z -= s;
  6426. return this;
  6427. },
  6428. subVectors: function ( a, b ) {
  6429. this.x = a.x - b.x;
  6430. this.y = a.y - b.y;
  6431. this.z = a.z - b.z;
  6432. return this;
  6433. },
  6434. multiply: function ( v, w ) {
  6435. if ( w !== undefined ) {
  6436. console.warn( 'THREE.Vector3: .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead.' );
  6437. return this.multiplyVectors( v, w );
  6438. }
  6439. this.x *= v.x;
  6440. this.y *= v.y;
  6441. this.z *= v.z;
  6442. return this;
  6443. },
  6444. multiplyScalar: function ( scalar ) {
  6445. this.x *= scalar;
  6446. this.y *= scalar;
  6447. this.z *= scalar;
  6448. return this;
  6449. },
  6450. multiplyVectors: function ( a, b ) {
  6451. this.x = a.x * b.x;
  6452. this.y = a.y * b.y;
  6453. this.z = a.z * b.z;
  6454. return this;
  6455. },
  6456. applyEuler: function () {
  6457. var quaternion = new Quaternion();
  6458. return function applyEuler( euler ) {
  6459. if ( ! ( euler && euler.isEuler ) ) {
  6460. console.error( 'THREE.Vector3: .applyEuler() now expects an Euler rotation rather than a Vector3 and order.' );
  6461. }
  6462. return this.applyQuaternion( quaternion.setFromEuler( euler ) );
  6463. };
  6464. }(),
  6465. applyAxisAngle: function () {
  6466. var quaternion = new Quaternion();
  6467. return function applyAxisAngle( axis, angle ) {
  6468. return this.applyQuaternion( quaternion.setFromAxisAngle( axis, angle ) );
  6469. };
  6470. }(),
  6471. applyMatrix3: function ( m ) {
  6472. var x = this.x, y = this.y, z = this.z;
  6473. var e = m.elements;
  6474. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ] * z;
  6475. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ] * z;
  6476. this.z = e[ 2 ] * x + e[ 5 ] * y + e[ 8 ] * z;
  6477. return this;
  6478. },
  6479. applyMatrix4: function ( m ) {
  6480. var x = this.x, y = this.y, z = this.z;
  6481. var e = m.elements;
  6482. var w = 1 / ( e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] );
  6483. this.x = ( e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] ) * w;
  6484. this.y = ( e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] ) * w;
  6485. this.z = ( e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] ) * w;
  6486. return this;
  6487. },
  6488. applyQuaternion: function ( q ) {
  6489. var x = this.x, y = this.y, z = this.z;
  6490. var qx = q.x, qy = q.y, qz = q.z, qw = q.w;
  6491. // calculate quat * vector
  6492. var ix = qw * x + qy * z - qz * y;
  6493. var iy = qw * y + qz * x - qx * z;
  6494. var iz = qw * z + qx * y - qy * x;
  6495. var iw = - qx * x - qy * y - qz * z;
  6496. // calculate result * inverse quat
  6497. this.x = ix * qw + iw * - qx + iy * - qz - iz * - qy;
  6498. this.y = iy * qw + iw * - qy + iz * - qx - ix * - qz;
  6499. this.z = iz * qw + iw * - qz + ix * - qy - iy * - qx;
  6500. return this;
  6501. },
  6502. project: function ( camera ) {
  6503. return this.applyMatrix4( camera.matrixWorldInverse ).applyMatrix4( camera.projectionMatrix );
  6504. },
  6505. unproject: function () {
  6506. var matrix = new Matrix4();
  6507. return function unproject( camera ) {
  6508. return this.applyMatrix4( matrix.getInverse( camera.projectionMatrix ) ).applyMatrix4( camera.matrixWorld );
  6509. };
  6510. }(),
  6511. transformDirection: function ( m ) {
  6512. // input: THREE.Matrix4 affine matrix
  6513. // vector interpreted as a direction
  6514. var x = this.x, y = this.y, z = this.z;
  6515. var e = m.elements;
  6516. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z;
  6517. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z;
  6518. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z;
  6519. return this.normalize();
  6520. },
  6521. divide: function ( v ) {
  6522. this.x /= v.x;
  6523. this.y /= v.y;
  6524. this.z /= v.z;
  6525. return this;
  6526. },
  6527. divideScalar: function ( scalar ) {
  6528. return this.multiplyScalar( 1 / scalar );
  6529. },
  6530. min: function ( v ) {
  6531. this.x = Math.min( this.x, v.x );
  6532. this.y = Math.min( this.y, v.y );
  6533. this.z = Math.min( this.z, v.z );
  6534. return this;
  6535. },
  6536. max: function ( v ) {
  6537. this.x = Math.max( this.x, v.x );
  6538. this.y = Math.max( this.y, v.y );
  6539. this.z = Math.max( this.z, v.z );
  6540. return this;
  6541. },
  6542. clamp: function ( min, max ) {
  6543. // assumes min < max, componentwise
  6544. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  6545. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  6546. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  6547. return this;
  6548. },
  6549. clampScalar: function () {
  6550. var min = new Vector3();
  6551. var max = new Vector3();
  6552. return function clampScalar( minVal, maxVal ) {
  6553. min.set( minVal, minVal, minVal );
  6554. max.set( maxVal, maxVal, maxVal );
  6555. return this.clamp( min, max );
  6556. };
  6557. }(),
  6558. clampLength: function ( min, max ) {
  6559. var length = this.length();
  6560. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  6561. },
  6562. floor: function () {
  6563. this.x = Math.floor( this.x );
  6564. this.y = Math.floor( this.y );
  6565. this.z = Math.floor( this.z );
  6566. return this;
  6567. },
  6568. ceil: function () {
  6569. this.x = Math.ceil( this.x );
  6570. this.y = Math.ceil( this.y );
  6571. this.z = Math.ceil( this.z );
  6572. return this;
  6573. },
  6574. round: function () {
  6575. this.x = Math.round( this.x );
  6576. this.y = Math.round( this.y );
  6577. this.z = Math.round( this.z );
  6578. return this;
  6579. },
  6580. roundToZero: function () {
  6581. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  6582. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  6583. this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
  6584. return this;
  6585. },
  6586. negate: function () {
  6587. this.x = - this.x;
  6588. this.y = - this.y;
  6589. this.z = - this.z;
  6590. return this;
  6591. },
  6592. dot: function ( v ) {
  6593. return this.x * v.x + this.y * v.y + this.z * v.z;
  6594. },
  6595. // TODO lengthSquared?
  6596. lengthSq: function () {
  6597. return this.x * this.x + this.y * this.y + this.z * this.z;
  6598. },
  6599. length: function () {
  6600. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
  6601. },
  6602. manhattanLength: function () {
  6603. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  6604. },
  6605. normalize: function () {
  6606. return this.divideScalar( this.length() || 1 );
  6607. },
  6608. setLength: function ( length ) {
  6609. return this.normalize().multiplyScalar( length );
  6610. },
  6611. lerp: function ( v, alpha ) {
  6612. this.x += ( v.x - this.x ) * alpha;
  6613. this.y += ( v.y - this.y ) * alpha;
  6614. this.z += ( v.z - this.z ) * alpha;
  6615. return this;
  6616. },
  6617. lerpVectors: function ( v1, v2, alpha ) {
  6618. return this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 );
  6619. },
  6620. cross: function ( v, w ) {
  6621. if ( w !== undefined ) {
  6622. console.warn( 'THREE.Vector3: .cross() now only accepts one argument. Use .crossVectors( a, b ) instead.' );
  6623. return this.crossVectors( v, w );
  6624. }
  6625. return this.crossVectors( this, v );
  6626. },
  6627. crossVectors: function ( a, b ) {
  6628. var ax = a.x, ay = a.y, az = a.z;
  6629. var bx = b.x, by = b.y, bz = b.z;
  6630. this.x = ay * bz - az * by;
  6631. this.y = az * bx - ax * bz;
  6632. this.z = ax * by - ay * bx;
  6633. return this;
  6634. },
  6635. projectOnVector: function ( vector ) {
  6636. var scalar = vector.dot( this ) / vector.lengthSq();
  6637. return this.copy( vector ).multiplyScalar( scalar );
  6638. },
  6639. projectOnPlane: function () {
  6640. var v1 = new Vector3();
  6641. return function projectOnPlane( planeNormal ) {
  6642. v1.copy( this ).projectOnVector( planeNormal );
  6643. return this.sub( v1 );
  6644. };
  6645. }(),
  6646. reflect: function () {
  6647. // reflect incident vector off plane orthogonal to normal
  6648. // normal is assumed to have unit length
  6649. var v1 = new Vector3();
  6650. return function reflect( normal ) {
  6651. return this.sub( v1.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) );
  6652. };
  6653. }(),
  6654. angleTo: function ( v ) {
  6655. var theta = this.dot( v ) / ( Math.sqrt( this.lengthSq() * v.lengthSq() ) );
  6656. // clamp, to handle numerical problems
  6657. return Math.acos( _Math.clamp( theta, - 1, 1 ) );
  6658. },
  6659. distanceTo: function ( v ) {
  6660. return Math.sqrt( this.distanceToSquared( v ) );
  6661. },
  6662. distanceToSquared: function ( v ) {
  6663. var dx = this.x - v.x, dy = this.y - v.y, dz = this.z - v.z;
  6664. return dx * dx + dy * dy + dz * dz;
  6665. },
  6666. manhattanDistanceTo: function ( v ) {
  6667. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y ) + Math.abs( this.z - v.z );
  6668. },
  6669. setFromSpherical: function ( s ) {
  6670. return this.setFromSphericalCoords( s.radius, s.phi, s.theta );
  6671. },
  6672. setFromSphericalCoords: function ( radius, phi, theta ) {
  6673. var sinPhiRadius = Math.sin( phi ) * radius;
  6674. this.x = sinPhiRadius * Math.sin( theta );
  6675. this.y = Math.cos( phi ) * radius;
  6676. this.z = sinPhiRadius * Math.cos( theta );
  6677. return this;
  6678. },
  6679. setFromCylindrical: function ( c ) {
  6680. return this.setFromCylindricalCoords( c.radius, c.theta, c.y );
  6681. },
  6682. setFromCylindricalCoords: function ( radius, theta, y ) {
  6683. this.x = radius * Math.sin( theta );
  6684. this.y = y;
  6685. this.z = radius * Math.cos( theta );
  6686. return this;
  6687. },
  6688. setFromMatrixPosition: function ( m ) {
  6689. var e = m.elements;
  6690. this.x = e[ 12 ];
  6691. this.y = e[ 13 ];
  6692. this.z = e[ 14 ];
  6693. return this;
  6694. },
  6695. setFromMatrixScale: function ( m ) {
  6696. var sx = this.setFromMatrixColumn( m, 0 ).length();
  6697. var sy = this.setFromMatrixColumn( m, 1 ).length();
  6698. var sz = this.setFromMatrixColumn( m, 2 ).length();
  6699. this.x = sx;
  6700. this.y = sy;
  6701. this.z = sz;
  6702. return this;
  6703. },
  6704. setFromMatrixColumn: function ( m, index ) {
  6705. return this.fromArray( m.elements, index * 4 );
  6706. },
  6707. equals: function ( v ) {
  6708. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  6709. },
  6710. fromArray: function ( array, offset ) {
  6711. if ( offset === undefined ) offset = 0;
  6712. this.x = array[ offset ];
  6713. this.y = array[ offset + 1 ];
  6714. this.z = array[ offset + 2 ];
  6715. return this;
  6716. },
  6717. toArray: function ( array, offset ) {
  6718. if ( array === undefined ) array = [];
  6719. if ( offset === undefined ) offset = 0;
  6720. array[ offset ] = this.x;
  6721. array[ offset + 1 ] = this.y;
  6722. array[ offset + 2 ] = this.z;
  6723. return array;
  6724. },
  6725. fromBufferAttribute: function ( attribute, index, offset ) {
  6726. if ( offset !== undefined ) {
  6727. console.warn( 'THREE.Vector3: offset has been removed from .fromBufferAttribute().' );
  6728. }
  6729. this.x = attribute.getX( index );
  6730. this.y = attribute.getY( index );
  6731. this.z = attribute.getZ( index );
  6732. return this;
  6733. }
  6734. } );
  6735. /**
  6736. * @author alteredq / http://alteredqualia.com/
  6737. * @author WestLangley / http://github.com/WestLangley
  6738. * @author bhouston / http://clara.io
  6739. * @author tschw
  6740. */
  6741. function Matrix3() {
  6742. this.elements = [
  6743. 1, 0, 0,
  6744. 0, 1, 0,
  6745. 0, 0, 1
  6746. ];
  6747. if ( arguments.length > 0 ) {
  6748. console.error( 'THREE.Matrix3: the constructor no longer reads arguments. use .set() instead.' );
  6749. }
  6750. }
  6751. Object.assign( Matrix3.prototype, {
  6752. isMatrix3: true,
  6753. set: function ( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  6754. var te = this.elements;
  6755. te[ 0 ] = n11; te[ 1 ] = n21; te[ 2 ] = n31;
  6756. te[ 3 ] = n12; te[ 4 ] = n22; te[ 5 ] = n32;
  6757. te[ 6 ] = n13; te[ 7 ] = n23; te[ 8 ] = n33;
  6758. return this;
  6759. },
  6760. identity: function () {
  6761. this.set(
  6762. 1, 0, 0,
  6763. 0, 1, 0,
  6764. 0, 0, 1
  6765. );
  6766. return this;
  6767. },
  6768. clone: function () {
  6769. return new this.constructor().fromArray( this.elements );
  6770. },
  6771. copy: function ( m ) {
  6772. var te = this.elements;
  6773. var me = m.elements;
  6774. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ];
  6775. te[ 3 ] = me[ 3 ]; te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ];
  6776. te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ]; te[ 8 ] = me[ 8 ];
  6777. return this;
  6778. },
  6779. setFromMatrix4: function ( m ) {
  6780. var me = m.elements;
  6781. this.set(
  6782. me[ 0 ], me[ 4 ], me[ 8 ],
  6783. me[ 1 ], me[ 5 ], me[ 9 ],
  6784. me[ 2 ], me[ 6 ], me[ 10 ]
  6785. );
  6786. return this;
  6787. },
  6788. applyToBufferAttribute: function () {
  6789. var v1 = new Vector3();
  6790. return function applyToBufferAttribute( attribute ) {
  6791. for ( var i = 0, l = attribute.count; i < l; i ++ ) {
  6792. v1.x = attribute.getX( i );
  6793. v1.y = attribute.getY( i );
  6794. v1.z = attribute.getZ( i );
  6795. v1.applyMatrix3( this );
  6796. attribute.setXYZ( i, v1.x, v1.y, v1.z );
  6797. }
  6798. return attribute;
  6799. };
  6800. }(),
  6801. multiply: function ( m ) {
  6802. return this.multiplyMatrices( this, m );
  6803. },
  6804. premultiply: function ( m ) {
  6805. return this.multiplyMatrices( m, this );
  6806. },
  6807. multiplyMatrices: function ( a, b ) {
  6808. var ae = a.elements;
  6809. var be = b.elements;
  6810. var te = this.elements;
  6811. var a11 = ae[ 0 ], a12 = ae[ 3 ], a13 = ae[ 6 ];
  6812. var a21 = ae[ 1 ], a22 = ae[ 4 ], a23 = ae[ 7 ];
  6813. var a31 = ae[ 2 ], a32 = ae[ 5 ], a33 = ae[ 8 ];
  6814. var b11 = be[ 0 ], b12 = be[ 3 ], b13 = be[ 6 ];
  6815. var b21 = be[ 1 ], b22 = be[ 4 ], b23 = be[ 7 ];
  6816. var b31 = be[ 2 ], b32 = be[ 5 ], b33 = be[ 8 ];
  6817. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31;
  6818. te[ 3 ] = a11 * b12 + a12 * b22 + a13 * b32;
  6819. te[ 6 ] = a11 * b13 + a12 * b23 + a13 * b33;
  6820. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31;
  6821. te[ 4 ] = a21 * b12 + a22 * b22 + a23 * b32;
  6822. te[ 7 ] = a21 * b13 + a22 * b23 + a23 * b33;
  6823. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31;
  6824. te[ 5 ] = a31 * b12 + a32 * b22 + a33 * b32;
  6825. te[ 8 ] = a31 * b13 + a32 * b23 + a33 * b33;
  6826. return this;
  6827. },
  6828. multiplyScalar: function ( s ) {
  6829. var te = this.elements;
  6830. te[ 0 ] *= s; te[ 3 ] *= s; te[ 6 ] *= s;
  6831. te[ 1 ] *= s; te[ 4 ] *= s; te[ 7 ] *= s;
  6832. te[ 2 ] *= s; te[ 5 ] *= s; te[ 8 ] *= s;
  6833. return this;
  6834. },
  6835. determinant: function () {
  6836. var te = this.elements;
  6837. var a = te[ 0 ], b = te[ 1 ], c = te[ 2 ],
  6838. d = te[ 3 ], e = te[ 4 ], f = te[ 5 ],
  6839. g = te[ 6 ], h = te[ 7 ], i = te[ 8 ];
  6840. return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;
  6841. },
  6842. getInverse: function ( matrix, throwOnDegenerate ) {
  6843. if ( matrix && matrix.isMatrix4 ) {
  6844. console.error( "THREE.Matrix3: .getInverse() no longer takes a Matrix4 argument." );
  6845. }
  6846. var me = matrix.elements,
  6847. te = this.elements,
  6848. n11 = me[ 0 ], n21 = me[ 1 ], n31 = me[ 2 ],
  6849. n12 = me[ 3 ], n22 = me[ 4 ], n32 = me[ 5 ],
  6850. n13 = me[ 6 ], n23 = me[ 7 ], n33 = me[ 8 ],
  6851. t11 = n33 * n22 - n32 * n23,
  6852. t12 = n32 * n13 - n33 * n12,
  6853. t13 = n23 * n12 - n22 * n13,
  6854. det = n11 * t11 + n21 * t12 + n31 * t13;
  6855. if ( det === 0 ) {
  6856. var msg = "THREE.Matrix3: .getInverse() can't invert matrix, determinant is 0";
  6857. if ( throwOnDegenerate === true ) {
  6858. throw new Error( msg );
  6859. } else {
  6860. console.warn( msg );
  6861. }
  6862. return this.identity();
  6863. }
  6864. var detInv = 1 / det;
  6865. te[ 0 ] = t11 * detInv;
  6866. te[ 1 ] = ( n31 * n23 - n33 * n21 ) * detInv;
  6867. te[ 2 ] = ( n32 * n21 - n31 * n22 ) * detInv;
  6868. te[ 3 ] = t12 * detInv;
  6869. te[ 4 ] = ( n33 * n11 - n31 * n13 ) * detInv;
  6870. te[ 5 ] = ( n31 * n12 - n32 * n11 ) * detInv;
  6871. te[ 6 ] = t13 * detInv;
  6872. te[ 7 ] = ( n21 * n13 - n23 * n11 ) * detInv;
  6873. te[ 8 ] = ( n22 * n11 - n21 * n12 ) * detInv;
  6874. return this;
  6875. },
  6876. transpose: function () {
  6877. var tmp, m = this.elements;
  6878. tmp = m[ 1 ]; m[ 1 ] = m[ 3 ]; m[ 3 ] = tmp;
  6879. tmp = m[ 2 ]; m[ 2 ] = m[ 6 ]; m[ 6 ] = tmp;
  6880. tmp = m[ 5 ]; m[ 5 ] = m[ 7 ]; m[ 7 ] = tmp;
  6881. return this;
  6882. },
  6883. getNormalMatrix: function ( matrix4 ) {
  6884. return this.setFromMatrix4( matrix4 ).getInverse( this ).transpose();
  6885. },
  6886. transposeIntoArray: function ( r ) {
  6887. var m = this.elements;
  6888. r[ 0 ] = m[ 0 ];
  6889. r[ 1 ] = m[ 3 ];
  6890. r[ 2 ] = m[ 6 ];
  6891. r[ 3 ] = m[ 1 ];
  6892. r[ 4 ] = m[ 4 ];
  6893. r[ 5 ] = m[ 7 ];
  6894. r[ 6 ] = m[ 2 ];
  6895. r[ 7 ] = m[ 5 ];
  6896. r[ 8 ] = m[ 8 ];
  6897. return this;
  6898. },
  6899. setUvTransform: function ( tx, ty, sx, sy, rotation, cx, cy ) {
  6900. var c = Math.cos( rotation );
  6901. var s = Math.sin( rotation );
  6902. this.set(
  6903. sx * c, sx * s, - sx * ( c * cx + s * cy ) + cx + tx,
  6904. - sy * s, sy * c, - sy * ( - s * cx + c * cy ) + cy + ty,
  6905. 0, 0, 1
  6906. );
  6907. },
  6908. scale: function ( sx, sy ) {
  6909. var te = this.elements;
  6910. te[ 0 ] *= sx; te[ 3 ] *= sx; te[ 6 ] *= sx;
  6911. te[ 1 ] *= sy; te[ 4 ] *= sy; te[ 7 ] *= sy;
  6912. return this;
  6913. },
  6914. rotate: function ( theta ) {
  6915. var c = Math.cos( theta );
  6916. var s = Math.sin( theta );
  6917. var te = this.elements;
  6918. var a11 = te[ 0 ], a12 = te[ 3 ], a13 = te[ 6 ];
  6919. var a21 = te[ 1 ], a22 = te[ 4 ], a23 = te[ 7 ];
  6920. te[ 0 ] = c * a11 + s * a21;
  6921. te[ 3 ] = c * a12 + s * a22;
  6922. te[ 6 ] = c * a13 + s * a23;
  6923. te[ 1 ] = - s * a11 + c * a21;
  6924. te[ 4 ] = - s * a12 + c * a22;
  6925. te[ 7 ] = - s * a13 + c * a23;
  6926. return this;
  6927. },
  6928. translate: function ( tx, ty ) {
  6929. var te = this.elements;
  6930. te[ 0 ] += tx * te[ 2 ]; te[ 3 ] += tx * te[ 5 ]; te[ 6 ] += tx * te[ 8 ];
  6931. te[ 1 ] += ty * te[ 2 ]; te[ 4 ] += ty * te[ 5 ]; te[ 7 ] += ty * te[ 8 ];
  6932. return this;
  6933. },
  6934. equals: function ( matrix ) {
  6935. var te = this.elements;
  6936. var me = matrix.elements;
  6937. for ( var i = 0; i < 9; i ++ ) {
  6938. if ( te[ i ] !== me[ i ] ) return false;
  6939. }
  6940. return true;
  6941. },
  6942. fromArray: function ( array, offset ) {
  6943. if ( offset === undefined ) offset = 0;
  6944. for ( var i = 0; i < 9; i ++ ) {
  6945. this.elements[ i ] = array[ i + offset ];
  6946. }
  6947. return this;
  6948. },
  6949. toArray: function ( array, offset ) {
  6950. if ( array === undefined ) array = [];
  6951. if ( offset === undefined ) offset = 0;
  6952. var te = this.elements;
  6953. array[ offset ] = te[ 0 ];
  6954. array[ offset + 1 ] = te[ 1 ];
  6955. array[ offset + 2 ] = te[ 2 ];
  6956. array[ offset + 3 ] = te[ 3 ];
  6957. array[ offset + 4 ] = te[ 4 ];
  6958. array[ offset + 5 ] = te[ 5 ];
  6959. array[ offset + 6 ] = te[ 6 ];
  6960. array[ offset + 7 ] = te[ 7 ];
  6961. array[ offset + 8 ] = te[ 8 ];
  6962. return array;
  6963. }
  6964. } );
  6965. /**
  6966. * @author mrdoob / http://mrdoob.com/
  6967. * @author alteredq / http://alteredqualia.com/
  6968. * @author szimek / https://github.com/szimek/
  6969. */
  6970. var _canvas;
  6971. var ImageUtils = {
  6972. getDataURL: function ( image ) {
  6973. var canvas;
  6974. if ( typeof HTMLCanvasElement == 'undefined' ) {
  6975. return image.src;
  6976. } else if ( image instanceof HTMLCanvasElement ) {
  6977. canvas = image;
  6978. } else {
  6979. if ( _canvas === undefined ) _canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  6980. _canvas.width = image.width;
  6981. _canvas.height = image.height;
  6982. var context = _canvas.getContext( '2d' );
  6983. if ( image instanceof ImageData ) {
  6984. context.putImageData( image, 0, 0 );
  6985. } else {
  6986. context.drawImage( image, 0, 0, image.width, image.height );
  6987. }
  6988. canvas = _canvas;
  6989. }
  6990. if ( canvas.width > 2048 || canvas.height > 2048 ) {
  6991. return canvas.toDataURL( 'image/jpeg', 0.6 );
  6992. } else {
  6993. return canvas.toDataURL( 'image/png' );
  6994. }
  6995. }
  6996. };
  6997. /**
  6998. * @author mrdoob / http://mrdoob.com/
  6999. * @author alteredq / http://alteredqualia.com/
  7000. * @author szimek / https://github.com/szimek/
  7001. */
  7002. var textureId = 0;
  7003. function Texture( image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ) {
  7004. Object.defineProperty( this, 'id', { value: textureId ++ } );
  7005. this.uuid = _Math.generateUUID();
  7006. this.name = '';
  7007. this.image = image !== undefined ? image : Texture.DEFAULT_IMAGE;
  7008. this.mipmaps = [];
  7009. this.mapping = mapping !== undefined ? mapping : Texture.DEFAULT_MAPPING;
  7010. this.wrapS = wrapS !== undefined ? wrapS : ClampToEdgeWrapping;
  7011. this.wrapT = wrapT !== undefined ? wrapT : ClampToEdgeWrapping;
  7012. this.magFilter = magFilter !== undefined ? magFilter : LinearFilter;
  7013. this.minFilter = minFilter !== undefined ? minFilter : LinearMipMapLinearFilter;
  7014. this.anisotropy = anisotropy !== undefined ? anisotropy : 1;
  7015. this.format = format !== undefined ? format : RGBAFormat;
  7016. this.type = type !== undefined ? type : UnsignedByteType;
  7017. this.offset = new Vector2( 0, 0 );
  7018. this.repeat = new Vector2( 1, 1 );
  7019. this.center = new Vector2( 0, 0 );
  7020. this.rotation = 0;
  7021. this.matrixAutoUpdate = true;
  7022. this.matrix = new Matrix3();
  7023. this.generateMipmaps = true;
  7024. this.premultiplyAlpha = false;
  7025. this.flipY = true;
  7026. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  7027. // Values of encoding !== THREE.LinearEncoding only supported on map, envMap and emissiveMap.
  7028. //
  7029. // Also changing the encoding after already used by a Material will not automatically make the Material
  7030. // update. You need to explicitly call Material.needsUpdate to trigger it to recompile.
  7031. this.encoding = encoding !== undefined ? encoding : LinearEncoding;
  7032. this.version = 0;
  7033. this.onUpdate = null;
  7034. }
  7035. Texture.DEFAULT_IMAGE = undefined;
  7036. Texture.DEFAULT_MAPPING = UVMapping;
  7037. Texture.prototype = Object.assign( Object.create( EventDispatcher.prototype ), {
  7038. constructor: Texture,
  7039. isTexture: true,
  7040. updateMatrix: function () {
  7041. this.matrix.setUvTransform( this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y );
  7042. },
  7043. clone: function () {
  7044. return new this.constructor().copy( this );
  7045. },
  7046. copy: function ( source ) {
  7047. this.name = source.name;
  7048. this.image = source.image;
  7049. this.mipmaps = source.mipmaps.slice( 0 );
  7050. this.mapping = source.mapping;
  7051. this.wrapS = source.wrapS;
  7052. this.wrapT = source.wrapT;
  7053. this.magFilter = source.magFilter;
  7054. this.minFilter = source.minFilter;
  7055. this.anisotropy = source.anisotropy;
  7056. this.format = source.format;
  7057. this.type = source.type;
  7058. this.offset.copy( source.offset );
  7059. this.repeat.copy( source.repeat );
  7060. this.center.copy( source.center );
  7061. this.rotation = source.rotation;
  7062. this.matrixAutoUpdate = source.matrixAutoUpdate;
  7063. this.matrix.copy( source.matrix );
  7064. this.generateMipmaps = source.generateMipmaps;
  7065. this.premultiplyAlpha = source.premultiplyAlpha;
  7066. this.flipY = source.flipY;
  7067. this.unpackAlignment = source.unpackAlignment;
  7068. this.encoding = source.encoding;
  7069. return this;
  7070. },
  7071. toJSON: function ( meta ) {
  7072. var isRootObject = ( meta === undefined || typeof meta === 'string' );
  7073. if ( ! isRootObject && meta.textures[ this.uuid ] !== undefined ) {
  7074. return meta.textures[ this.uuid ];
  7075. }
  7076. var output = {
  7077. metadata: {
  7078. version: 4.5,
  7079. type: 'Texture',
  7080. generator: 'Texture.toJSON'
  7081. },
  7082. uuid: this.uuid,
  7083. name: this.name,
  7084. mapping: this.mapping,
  7085. repeat: [ this.repeat.x, this.repeat.y ],
  7086. offset: [ this.offset.x, this.offset.y ],
  7087. center: [ this.center.x, this.center.y ],
  7088. rotation: this.rotation,
  7089. wrap: [ this.wrapS, this.wrapT ],
  7090. format: this.format,
  7091. type: this.type,
  7092. encoding: this.encoding,
  7093. minFilter: this.minFilter,
  7094. magFilter: this.magFilter,
  7095. anisotropy: this.anisotropy,
  7096. flipY: this.flipY,
  7097. premultiplyAlpha: this.premultiplyAlpha,
  7098. unpackAlignment: this.unpackAlignment
  7099. };
  7100. if ( this.image !== undefined ) {
  7101. // TODO: Move to THREE.Image
  7102. var image = this.image;
  7103. if ( image.uuid === undefined ) {
  7104. image.uuid = _Math.generateUUID(); // UGH
  7105. }
  7106. if ( ! isRootObject && meta.images[ image.uuid ] === undefined ) {
  7107. var url;
  7108. if ( Array.isArray( image ) ) {
  7109. // process array of images e.g. CubeTexture
  7110. url = [];
  7111. for ( var i = 0, l = image.length; i < l; i ++ ) {
  7112. url.push( ImageUtils.getDataURL( image[ i ] ) );
  7113. }
  7114. } else {
  7115. // process single image
  7116. url = ImageUtils.getDataURL( image );
  7117. }
  7118. meta.images[ image.uuid ] = {
  7119. uuid: image.uuid,
  7120. url: url
  7121. };
  7122. }
  7123. output.image = image.uuid;
  7124. }
  7125. if ( ! isRootObject ) {
  7126. meta.textures[ this.uuid ] = output;
  7127. }
  7128. return output;
  7129. },
  7130. dispose: function () {
  7131. this.dispatchEvent( { type: 'dispose' } );
  7132. },
  7133. transformUv: function ( uv ) {
  7134. if ( this.mapping !== UVMapping ) return uv;
  7135. uv.applyMatrix3( this.matrix );
  7136. if ( uv.x < 0 || uv.x > 1 ) {
  7137. switch ( this.wrapS ) {
  7138. case RepeatWrapping:
  7139. uv.x = uv.x - Math.floor( uv.x );
  7140. break;
  7141. case ClampToEdgeWrapping:
  7142. uv.x = uv.x < 0 ? 0 : 1;
  7143. break;
  7144. case MirroredRepeatWrapping:
  7145. if ( Math.abs( Math.floor( uv.x ) % 2 ) === 1 ) {
  7146. uv.x = Math.ceil( uv.x ) - uv.x;
  7147. } else {
  7148. uv.x = uv.x - Math.floor( uv.x );
  7149. }
  7150. break;
  7151. }
  7152. }
  7153. if ( uv.y < 0 || uv.y > 1 ) {
  7154. switch ( this.wrapT ) {
  7155. case RepeatWrapping:
  7156. uv.y = uv.y - Math.floor( uv.y );
  7157. break;
  7158. case ClampToEdgeWrapping:
  7159. uv.y = uv.y < 0 ? 0 : 1;
  7160. break;
  7161. case MirroredRepeatWrapping:
  7162. if ( Math.abs( Math.floor( uv.y ) % 2 ) === 1 ) {
  7163. uv.y = Math.ceil( uv.y ) - uv.y;
  7164. } else {
  7165. uv.y = uv.y - Math.floor( uv.y );
  7166. }
  7167. break;
  7168. }
  7169. }
  7170. if ( this.flipY ) {
  7171. uv.y = 1 - uv.y;
  7172. }
  7173. return uv;
  7174. }
  7175. } );
  7176. Object.defineProperty( Texture.prototype, "needsUpdate", {
  7177. set: function ( value ) {
  7178. if ( value === true ) this.version ++;
  7179. }
  7180. } );
  7181. /**
  7182. * @author supereggbert / http://www.paulbrunt.co.uk/
  7183. * @author philogb / http://blog.thejit.org/
  7184. * @author mikael emtinger / http://gomo.se/
  7185. * @author egraether / http://egraether.com/
  7186. * @author WestLangley / http://github.com/WestLangley
  7187. */
  7188. function Vector4( x, y, z, w ) {
  7189. this.x = x || 0;
  7190. this.y = y || 0;
  7191. this.z = z || 0;
  7192. this.w = ( w !== undefined ) ? w : 1;
  7193. }
  7194. Object.assign( Vector4.prototype, {
  7195. isVector4: true,
  7196. set: function ( x, y, z, w ) {
  7197. this.x = x;
  7198. this.y = y;
  7199. this.z = z;
  7200. this.w = w;
  7201. return this;
  7202. },
  7203. setScalar: function ( scalar ) {
  7204. this.x = scalar;
  7205. this.y = scalar;
  7206. this.z = scalar;
  7207. this.w = scalar;
  7208. return this;
  7209. },
  7210. setX: function ( x ) {
  7211. this.x = x;
  7212. return this;
  7213. },
  7214. setY: function ( y ) {
  7215. this.y = y;
  7216. return this;
  7217. },
  7218. setZ: function ( z ) {
  7219. this.z = z;
  7220. return this;
  7221. },
  7222. setW: function ( w ) {
  7223. this.w = w;
  7224. return this;
  7225. },
  7226. setComponent: function ( index, value ) {
  7227. switch ( index ) {
  7228. case 0: this.x = value; break;
  7229. case 1: this.y = value; break;
  7230. case 2: this.z = value; break;
  7231. case 3: this.w = value; break;
  7232. default: throw new Error( 'index is out of range: ' + index );
  7233. }
  7234. return this;
  7235. },
  7236. getComponent: function ( index ) {
  7237. switch ( index ) {
  7238. case 0: return this.x;
  7239. case 1: return this.y;
  7240. case 2: return this.z;
  7241. case 3: return this.w;
  7242. default: throw new Error( 'index is out of range: ' + index );
  7243. }
  7244. },
  7245. clone: function () {
  7246. return new this.constructor( this.x, this.y, this.z, this.w );
  7247. },
  7248. copy: function ( v ) {
  7249. this.x = v.x;
  7250. this.y = v.y;
  7251. this.z = v.z;
  7252. this.w = ( v.w !== undefined ) ? v.w : 1;
  7253. return this;
  7254. },
  7255. add: function ( v, w ) {
  7256. if ( w !== undefined ) {
  7257. console.warn( 'THREE.Vector4: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  7258. return this.addVectors( v, w );
  7259. }
  7260. this.x += v.x;
  7261. this.y += v.y;
  7262. this.z += v.z;
  7263. this.w += v.w;
  7264. return this;
  7265. },
  7266. addScalar: function ( s ) {
  7267. this.x += s;
  7268. this.y += s;
  7269. this.z += s;
  7270. this.w += s;
  7271. return this;
  7272. },
  7273. addVectors: function ( a, b ) {
  7274. this.x = a.x + b.x;
  7275. this.y = a.y + b.y;
  7276. this.z = a.z + b.z;
  7277. this.w = a.w + b.w;
  7278. return this;
  7279. },
  7280. addScaledVector: function ( v, s ) {
  7281. this.x += v.x * s;
  7282. this.y += v.y * s;
  7283. this.z += v.z * s;
  7284. this.w += v.w * s;
  7285. return this;
  7286. },
  7287. sub: function ( v, w ) {
  7288. if ( w !== undefined ) {
  7289. console.warn( 'THREE.Vector4: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  7290. return this.subVectors( v, w );
  7291. }
  7292. this.x -= v.x;
  7293. this.y -= v.y;
  7294. this.z -= v.z;
  7295. this.w -= v.w;
  7296. return this;
  7297. },
  7298. subScalar: function ( s ) {
  7299. this.x -= s;
  7300. this.y -= s;
  7301. this.z -= s;
  7302. this.w -= s;
  7303. return this;
  7304. },
  7305. subVectors: function ( a, b ) {
  7306. this.x = a.x - b.x;
  7307. this.y = a.y - b.y;
  7308. this.z = a.z - b.z;
  7309. this.w = a.w - b.w;
  7310. return this;
  7311. },
  7312. multiplyScalar: function ( scalar ) {
  7313. this.x *= scalar;
  7314. this.y *= scalar;
  7315. this.z *= scalar;
  7316. this.w *= scalar;
  7317. return this;
  7318. },
  7319. applyMatrix4: function ( m ) {
  7320. var x = this.x, y = this.y, z = this.z, w = this.w;
  7321. var e = m.elements;
  7322. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] * w;
  7323. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] * w;
  7324. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] * w;
  7325. this.w = e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] * w;
  7326. return this;
  7327. },
  7328. divideScalar: function ( scalar ) {
  7329. return this.multiplyScalar( 1 / scalar );
  7330. },
  7331. setAxisAngleFromQuaternion: function ( q ) {
  7332. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  7333. // q is assumed to be normalized
  7334. this.w = 2 * Math.acos( q.w );
  7335. var s = Math.sqrt( 1 - q.w * q.w );
  7336. if ( s < 0.0001 ) {
  7337. this.x = 1;
  7338. this.y = 0;
  7339. this.z = 0;
  7340. } else {
  7341. this.x = q.x / s;
  7342. this.y = q.y / s;
  7343. this.z = q.z / s;
  7344. }
  7345. return this;
  7346. },
  7347. setAxisAngleFromRotationMatrix: function ( m ) {
  7348. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  7349. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  7350. var angle, x, y, z, // variables for result
  7351. epsilon = 0.01, // margin to allow for rounding errors
  7352. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  7353. te = m.elements,
  7354. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  7355. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  7356. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  7357. if ( ( Math.abs( m12 - m21 ) < epsilon ) &&
  7358. ( Math.abs( m13 - m31 ) < epsilon ) &&
  7359. ( Math.abs( m23 - m32 ) < epsilon ) ) {
  7360. // singularity found
  7361. // first check for identity matrix which must have +1 for all terms
  7362. // in leading diagonal and zero in other terms
  7363. if ( ( Math.abs( m12 + m21 ) < epsilon2 ) &&
  7364. ( Math.abs( m13 + m31 ) < epsilon2 ) &&
  7365. ( Math.abs( m23 + m32 ) < epsilon2 ) &&
  7366. ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  7367. // this singularity is identity matrix so angle = 0
  7368. this.set( 1, 0, 0, 0 );
  7369. return this; // zero angle, arbitrary axis
  7370. }
  7371. // otherwise this singularity is angle = 180
  7372. angle = Math.PI;
  7373. var xx = ( m11 + 1 ) / 2;
  7374. var yy = ( m22 + 1 ) / 2;
  7375. var zz = ( m33 + 1 ) / 2;
  7376. var xy = ( m12 + m21 ) / 4;
  7377. var xz = ( m13 + m31 ) / 4;
  7378. var yz = ( m23 + m32 ) / 4;
  7379. if ( ( xx > yy ) && ( xx > zz ) ) {
  7380. // m11 is the largest diagonal term
  7381. if ( xx < epsilon ) {
  7382. x = 0;
  7383. y = 0.707106781;
  7384. z = 0.707106781;
  7385. } else {
  7386. x = Math.sqrt( xx );
  7387. y = xy / x;
  7388. z = xz / x;
  7389. }
  7390. } else if ( yy > zz ) {
  7391. // m22 is the largest diagonal term
  7392. if ( yy < epsilon ) {
  7393. x = 0.707106781;
  7394. y = 0;
  7395. z = 0.707106781;
  7396. } else {
  7397. y = Math.sqrt( yy );
  7398. x = xy / y;
  7399. z = yz / y;
  7400. }
  7401. } else {
  7402. // m33 is the largest diagonal term so base result on this
  7403. if ( zz < epsilon ) {
  7404. x = 0.707106781;
  7405. y = 0.707106781;
  7406. z = 0;
  7407. } else {
  7408. z = Math.sqrt( zz );
  7409. x = xz / z;
  7410. y = yz / z;
  7411. }
  7412. }
  7413. this.set( x, y, z, angle );
  7414. return this; // return 180 deg rotation
  7415. }
  7416. // as we have reached here there are no singularities so we can handle normally
  7417. var s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 ) +
  7418. ( m13 - m31 ) * ( m13 - m31 ) +
  7419. ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  7420. if ( Math.abs( s ) < 0.001 ) s = 1;
  7421. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  7422. // caught by singularity test above, but I've left it in just in case
  7423. this.x = ( m32 - m23 ) / s;
  7424. this.y = ( m13 - m31 ) / s;
  7425. this.z = ( m21 - m12 ) / s;
  7426. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  7427. return this;
  7428. },
  7429. min: function ( v ) {
  7430. this.x = Math.min( this.x, v.x );
  7431. this.y = Math.min( this.y, v.y );
  7432. this.z = Math.min( this.z, v.z );
  7433. this.w = Math.min( this.w, v.w );
  7434. return this;
  7435. },
  7436. max: function ( v ) {
  7437. this.x = Math.max( this.x, v.x );
  7438. this.y = Math.max( this.y, v.y );
  7439. this.z = Math.max( this.z, v.z );
  7440. this.w = Math.max( this.w, v.w );
  7441. return this;
  7442. },
  7443. clamp: function ( min, max ) {
  7444. // assumes min < max, componentwise
  7445. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  7446. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  7447. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  7448. this.w = Math.max( min.w, Math.min( max.w, this.w ) );
  7449. return this;
  7450. },
  7451. clampScalar: function () {
  7452. var min, max;
  7453. return function clampScalar( minVal, maxVal ) {
  7454. if ( min === undefined ) {
  7455. min = new Vector4();
  7456. max = new Vector4();
  7457. }
  7458. min.set( minVal, minVal, minVal, minVal );
  7459. max.set( maxVal, maxVal, maxVal, maxVal );
  7460. return this.clamp( min, max );
  7461. };
  7462. }(),
  7463. clampLength: function ( min, max ) {
  7464. var length = this.length();
  7465. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  7466. },
  7467. floor: function () {
  7468. this.x = Math.floor( this.x );
  7469. this.y = Math.floor( this.y );
  7470. this.z = Math.floor( this.z );
  7471. this.w = Math.floor( this.w );
  7472. return this;
  7473. },
  7474. ceil: function () {
  7475. this.x = Math.ceil( this.x );
  7476. this.y = Math.ceil( this.y );
  7477. this.z = Math.ceil( this.z );
  7478. this.w = Math.ceil( this.w );
  7479. return this;
  7480. },
  7481. round: function () {
  7482. this.x = Math.round( this.x );
  7483. this.y = Math.round( this.y );
  7484. this.z = Math.round( this.z );
  7485. this.w = Math.round( this.w );
  7486. return this;
  7487. },
  7488. roundToZero: function () {
  7489. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  7490. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  7491. this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
  7492. this.w = ( this.w < 0 ) ? Math.ceil( this.w ) : Math.floor( this.w );
  7493. return this;
  7494. },
  7495. negate: function () {
  7496. this.x = - this.x;
  7497. this.y = - this.y;
  7498. this.z = - this.z;
  7499. this.w = - this.w;
  7500. return this;
  7501. },
  7502. dot: function ( v ) {
  7503. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  7504. },
  7505. lengthSq: function () {
  7506. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  7507. },
  7508. length: function () {
  7509. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  7510. },
  7511. manhattanLength: function () {
  7512. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  7513. },
  7514. normalize: function () {
  7515. return this.divideScalar( this.length() || 1 );
  7516. },
  7517. setLength: function ( length ) {
  7518. return this.normalize().multiplyScalar( length );
  7519. },
  7520. lerp: function ( v, alpha ) {
  7521. this.x += ( v.x - this.x ) * alpha;
  7522. this.y += ( v.y - this.y ) * alpha;
  7523. this.z += ( v.z - this.z ) * alpha;
  7524. this.w += ( v.w - this.w ) * alpha;
  7525. return this;
  7526. },
  7527. lerpVectors: function ( v1, v2, alpha ) {
  7528. return this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 );
  7529. },
  7530. equals: function ( v ) {
  7531. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  7532. },
  7533. fromArray: function ( array, offset ) {
  7534. if ( offset === undefined ) offset = 0;
  7535. this.x = array[ offset ];
  7536. this.y = array[ offset + 1 ];
  7537. this.z = array[ offset + 2 ];
  7538. this.w = array[ offset + 3 ];
  7539. return this;
  7540. },
  7541. toArray: function ( array, offset ) {
  7542. if ( array === undefined ) array = [];
  7543. if ( offset === undefined ) offset = 0;
  7544. array[ offset ] = this.x;
  7545. array[ offset + 1 ] = this.y;
  7546. array[ offset + 2 ] = this.z;
  7547. array[ offset + 3 ] = this.w;
  7548. return array;
  7549. },
  7550. fromBufferAttribute: function ( attribute, index, offset ) {
  7551. if ( offset !== undefined ) {
  7552. console.warn( 'THREE.Vector4: offset has been removed from .fromBufferAttribute().' );
  7553. }
  7554. this.x = attribute.getX( index );
  7555. this.y = attribute.getY( index );
  7556. this.z = attribute.getZ( index );
  7557. this.w = attribute.getW( index );
  7558. return this;
  7559. }
  7560. } );
  7561. /**
  7562. * @author szimek / https://github.com/szimek/
  7563. * @author alteredq / http://alteredqualia.com/
  7564. * @author Marius Kintel / https://github.com/kintel
  7565. */
  7566. /*
  7567. In options, we can specify:
  7568. * Texture parameters for an auto-generated target texture
  7569. * depthBuffer/stencilBuffer: Booleans to indicate if we should generate these buffers
  7570. */
  7571. function WebGLRenderTarget( width, height, options ) {
  7572. this.width = width;
  7573. this.height = height;
  7574. this.scissor = new Vector4( 0, 0, width, height );
  7575. this.scissorTest = false;
  7576. this.viewport = new Vector4( 0, 0, width, height );
  7577. options = options || {};
  7578. this.texture = new Texture( undefined, undefined, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding );
  7579. this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
  7580. this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
  7581. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  7582. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : true;
  7583. this.depthTexture = options.depthTexture !== undefined ? options.depthTexture : null;
  7584. }
  7585. WebGLRenderTarget.prototype = Object.assign( Object.create( EventDispatcher.prototype ), {
  7586. constructor: WebGLRenderTarget,
  7587. isWebGLRenderTarget: true,
  7588. setSize: function ( width, height ) {
  7589. if ( this.width !== width || this.height !== height ) {
  7590. this.width = width;
  7591. this.height = height;
  7592. this.dispose();
  7593. }
  7594. this.viewport.set( 0, 0, width, height );
  7595. this.scissor.set( 0, 0, width, height );
  7596. },
  7597. clone: function () {
  7598. return new this.constructor().copy( this );
  7599. },
  7600. copy: function ( source ) {
  7601. this.width = source.width;
  7602. this.height = source.height;
  7603. this.viewport.copy( source.viewport );
  7604. this.texture = source.texture.clone();
  7605. this.depthBuffer = source.depthBuffer;
  7606. this.stencilBuffer = source.stencilBuffer;
  7607. this.depthTexture = source.depthTexture;
  7608. return this;
  7609. },
  7610. dispose: function () {
  7611. this.dispatchEvent( { type: 'dispose' } );
  7612. }
  7613. } );
  7614. /**
  7615. * @author Mugen87 / https://github.com/Mugen87
  7616. * @author Matt DesLauriers / @mattdesl
  7617. */
  7618. function WebGLMultisampleRenderTarget( width, height, options ) {
  7619. WebGLRenderTarget.call( this, width, height, options );
  7620. this.samples = 4;
  7621. }
  7622. WebGLMultisampleRenderTarget.prototype = Object.assign( Object.create( WebGLRenderTarget.prototype ), {
  7623. constructor: WebGLMultisampleRenderTarget,
  7624. isWebGLMultisampleRenderTarget: true,
  7625. copy: function ( source ) {
  7626. WebGLRenderTarget.prototype.copy.call( this, source );
  7627. this.samples = source.samples;
  7628. return this;
  7629. }
  7630. } );
  7631. /**
  7632. * @author alteredq / http://alteredqualia.com
  7633. */
  7634. function WebGLRenderTargetCube( width, height, options ) {
  7635. WebGLRenderTarget.call( this, width, height, options );
  7636. }
  7637. WebGLRenderTargetCube.prototype = Object.create( WebGLRenderTarget.prototype );
  7638. WebGLRenderTargetCube.prototype.constructor = WebGLRenderTargetCube;
  7639. WebGLRenderTargetCube.prototype.isWebGLRenderTargetCube = true;
  7640. /**
  7641. * @author alteredq / http://alteredqualia.com/
  7642. */
  7643. function DataTexture( data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding ) {
  7644. Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  7645. this.image = { data: data, width: width, height: height };
  7646. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  7647. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  7648. this.generateMipmaps = false;
  7649. this.flipY = false;
  7650. this.unpackAlignment = 1;
  7651. }
  7652. DataTexture.prototype = Object.create( Texture.prototype );
  7653. DataTexture.prototype.constructor = DataTexture;
  7654. DataTexture.prototype.isDataTexture = true;
  7655. /**
  7656. * @author bhouston / http://clara.io
  7657. * @author WestLangley / http://github.com/WestLangley
  7658. */
  7659. function Box3( min, max ) {
  7660. this.min = ( min !== undefined ) ? min : new Vector3( + Infinity, + Infinity, + Infinity );
  7661. this.max = ( max !== undefined ) ? max : new Vector3( - Infinity, - Infinity, - Infinity );
  7662. }
  7663. Object.assign( Box3.prototype, {
  7664. isBox3: true,
  7665. set: function ( min, max ) {
  7666. this.min.copy( min );
  7667. this.max.copy( max );
  7668. return this;
  7669. },
  7670. setFromArray: function ( array ) {
  7671. var minX = + Infinity;
  7672. var minY = + Infinity;
  7673. var minZ = + Infinity;
  7674. var maxX = - Infinity;
  7675. var maxY = - Infinity;
  7676. var maxZ = - Infinity;
  7677. for ( var i = 0, l = array.length; i < l; i += 3 ) {
  7678. var x = array[ i ];
  7679. var y = array[ i + 1 ];
  7680. var z = array[ i + 2 ];
  7681. if ( x < minX ) minX = x;
  7682. if ( y < minY ) minY = y;
  7683. if ( z < minZ ) minZ = z;
  7684. if ( x > maxX ) maxX = x;
  7685. if ( y > maxY ) maxY = y;
  7686. if ( z > maxZ ) maxZ = z;
  7687. }
  7688. this.min.set( minX, minY, minZ );
  7689. this.max.set( maxX, maxY, maxZ );
  7690. return this;
  7691. },
  7692. setFromBufferAttribute: function ( attribute ) {
  7693. var minX = + Infinity;
  7694. var minY = + Infinity;
  7695. var minZ = + Infinity;
  7696. var maxX = - Infinity;
  7697. var maxY = - Infinity;
  7698. var maxZ = - Infinity;
  7699. for ( var i = 0, l = attribute.count; i < l; i ++ ) {
  7700. var x = attribute.getX( i );
  7701. var y = attribute.getY( i );
  7702. var z = attribute.getZ( i );
  7703. if ( x < minX ) minX = x;
  7704. if ( y < minY ) minY = y;
  7705. if ( z < minZ ) minZ = z;
  7706. if ( x > maxX ) maxX = x;
  7707. if ( y > maxY ) maxY = y;
  7708. if ( z > maxZ ) maxZ = z;
  7709. }
  7710. this.min.set( minX, minY, minZ );
  7711. this.max.set( maxX, maxY, maxZ );
  7712. return this;
  7713. },
  7714. setFromPoints: function ( points ) {
  7715. this.makeEmpty();
  7716. for ( var i = 0, il = points.length; i < il; i ++ ) {
  7717. this.expandByPoint( points[ i ] );
  7718. }
  7719. return this;
  7720. },
  7721. setFromCenterAndSize: function () {
  7722. var v1 = new Vector3();
  7723. return function setFromCenterAndSize( center, size ) {
  7724. var halfSize = v1.copy( size ).multiplyScalar( 0.5 );
  7725. this.min.copy( center ).sub( halfSize );
  7726. this.max.copy( center ).add( halfSize );
  7727. return this;
  7728. };
  7729. }(),
  7730. setFromObject: function ( object ) {
  7731. this.makeEmpty();
  7732. return this.expandByObject( object );
  7733. },
  7734. clone: function () {
  7735. return new this.constructor().copy( this );
  7736. },
  7737. copy: function ( box ) {
  7738. this.min.copy( box.min );
  7739. this.max.copy( box.max );
  7740. return this;
  7741. },
  7742. makeEmpty: function () {
  7743. this.min.x = this.min.y = this.min.z = + Infinity;
  7744. this.max.x = this.max.y = this.max.z = - Infinity;
  7745. return this;
  7746. },
  7747. isEmpty: function () {
  7748. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  7749. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  7750. },
  7751. getCenter: function ( target ) {
  7752. if ( target === undefined ) {
  7753. console.warn( 'THREE.Box3: .getCenter() target is now required' );
  7754. target = new Vector3();
  7755. }
  7756. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  7757. },
  7758. getSize: function ( target ) {
  7759. if ( target === undefined ) {
  7760. console.warn( 'THREE.Box3: .getSize() target is now required' );
  7761. target = new Vector3();
  7762. }
  7763. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.subVectors( this.max, this.min );
  7764. },
  7765. expandByPoint: function ( point ) {
  7766. this.min.min( point );
  7767. this.max.max( point );
  7768. return this;
  7769. },
  7770. expandByVector: function ( vector ) {
  7771. this.min.sub( vector );
  7772. this.max.add( vector );
  7773. return this;
  7774. },
  7775. expandByScalar: function ( scalar ) {
  7776. this.min.addScalar( - scalar );
  7777. this.max.addScalar( scalar );
  7778. return this;
  7779. },
  7780. expandByObject: function () {
  7781. // Computes the world-axis-aligned bounding box of an object (including its children),
  7782. // accounting for both the object's, and children's, world transforms
  7783. var scope, i, l;
  7784. var v1 = new Vector3();
  7785. function traverse( node ) {
  7786. var geometry = node.geometry;
  7787. if ( geometry !== undefined ) {
  7788. if ( geometry.isGeometry ) {
  7789. var vertices = geometry.vertices;
  7790. for ( i = 0, l = vertices.length; i < l; i ++ ) {
  7791. v1.copy( vertices[ i ] );
  7792. v1.applyMatrix4( node.matrixWorld );
  7793. scope.expandByPoint( v1 );
  7794. }
  7795. } else if ( geometry.isBufferGeometry ) {
  7796. var attribute = geometry.attributes.position;
  7797. if ( attribute !== undefined ) {
  7798. for ( i = 0, l = attribute.count; i < l; i ++ ) {
  7799. v1.fromBufferAttribute( attribute, i ).applyMatrix4( node.matrixWorld );
  7800. scope.expandByPoint( v1 );
  7801. }
  7802. }
  7803. }
  7804. }
  7805. }
  7806. return function expandByObject( object ) {
  7807. scope = this;
  7808. object.updateMatrixWorld( true );
  7809. object.traverse( traverse );
  7810. return this;
  7811. };
  7812. }(),
  7813. containsPoint: function ( point ) {
  7814. return point.x < this.min.x || point.x > this.max.x ||
  7815. point.y < this.min.y || point.y > this.max.y ||
  7816. point.z < this.min.z || point.z > this.max.z ? false : true;
  7817. },
  7818. containsBox: function ( box ) {
  7819. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  7820. this.min.y <= box.min.y && box.max.y <= this.max.y &&
  7821. this.min.z <= box.min.z && box.max.z <= this.max.z;
  7822. },
  7823. getParameter: function ( point, target ) {
  7824. // This can potentially have a divide by zero if the box
  7825. // has a size dimension of 0.
  7826. if ( target === undefined ) {
  7827. console.warn( 'THREE.Box3: .getParameter() target is now required' );
  7828. target = new Vector3();
  7829. }
  7830. return target.set(
  7831. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  7832. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  7833. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  7834. );
  7835. },
  7836. intersectsBox: function ( box ) {
  7837. // using 6 splitting planes to rule out intersections.
  7838. return box.max.x < this.min.x || box.min.x > this.max.x ||
  7839. box.max.y < this.min.y || box.min.y > this.max.y ||
  7840. box.max.z < this.min.z || box.min.z > this.max.z ? false : true;
  7841. },
  7842. intersectsSphere: ( function () {
  7843. var closestPoint = new Vector3();
  7844. return function intersectsSphere( sphere ) {
  7845. // Find the point on the AABB closest to the sphere center.
  7846. this.clampPoint( sphere.center, closestPoint );
  7847. // If that point is inside the sphere, the AABB and sphere intersect.
  7848. return closestPoint.distanceToSquared( sphere.center ) <= ( sphere.radius * sphere.radius );
  7849. };
  7850. } )(),
  7851. intersectsPlane: function ( plane ) {
  7852. // We compute the minimum and maximum dot product values. If those values
  7853. // are on the same side (back or front) of the plane, then there is no intersection.
  7854. var min, max;
  7855. if ( plane.normal.x > 0 ) {
  7856. min = plane.normal.x * this.min.x;
  7857. max = plane.normal.x * this.max.x;
  7858. } else {
  7859. min = plane.normal.x * this.max.x;
  7860. max = plane.normal.x * this.min.x;
  7861. }
  7862. if ( plane.normal.y > 0 ) {
  7863. min += plane.normal.y * this.min.y;
  7864. max += plane.normal.y * this.max.y;
  7865. } else {
  7866. min += plane.normal.y * this.max.y;
  7867. max += plane.normal.y * this.min.y;
  7868. }
  7869. if ( plane.normal.z > 0 ) {
  7870. min += plane.normal.z * this.min.z;
  7871. max += plane.normal.z * this.max.z;
  7872. } else {
  7873. min += plane.normal.z * this.max.z;
  7874. max += plane.normal.z * this.min.z;
  7875. }
  7876. return ( min <= - plane.constant && max >= - plane.constant );
  7877. },
  7878. intersectsTriangle: ( function () {
  7879. // triangle centered vertices
  7880. var v0 = new Vector3();
  7881. var v1 = new Vector3();
  7882. var v2 = new Vector3();
  7883. // triangle edge vectors
  7884. var f0 = new Vector3();
  7885. var f1 = new Vector3();
  7886. var f2 = new Vector3();
  7887. var testAxis = new Vector3();
  7888. var center = new Vector3();
  7889. var extents = new Vector3();
  7890. var triangleNormal = new Vector3();
  7891. function satForAxes( axes ) {
  7892. var i, j;
  7893. for ( i = 0, j = axes.length - 3; i <= j; i += 3 ) {
  7894. testAxis.fromArray( axes, i );
  7895. // project the aabb onto the seperating axis
  7896. var r = extents.x * Math.abs( testAxis.x ) + extents.y * Math.abs( testAxis.y ) + extents.z * Math.abs( testAxis.z );
  7897. // project all 3 vertices of the triangle onto the seperating axis
  7898. var p0 = v0.dot( testAxis );
  7899. var p1 = v1.dot( testAxis );
  7900. var p2 = v2.dot( testAxis );
  7901. // actual test, basically see if either of the most extreme of the triangle points intersects r
  7902. if ( Math.max( - Math.max( p0, p1, p2 ), Math.min( p0, p1, p2 ) ) > r ) {
  7903. // points of the projected triangle are outside the projected half-length of the aabb
  7904. // the axis is seperating and we can exit
  7905. return false;
  7906. }
  7907. }
  7908. return true;
  7909. }
  7910. return function intersectsTriangle( triangle ) {
  7911. if ( this.isEmpty() ) {
  7912. return false;
  7913. }
  7914. // compute box center and extents
  7915. this.getCenter( center );
  7916. extents.subVectors( this.max, center );
  7917. // translate triangle to aabb origin
  7918. v0.subVectors( triangle.a, center );
  7919. v1.subVectors( triangle.b, center );
  7920. v2.subVectors( triangle.c, center );
  7921. // compute edge vectors for triangle
  7922. f0.subVectors( v1, v0 );
  7923. f1.subVectors( v2, v1 );
  7924. f2.subVectors( v0, v2 );
  7925. // test against axes that are given by cross product combinations of the edges of the triangle and the edges of the aabb
  7926. // 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
  7927. // axis_ij = u_i x f_j (u0, u1, u2 = face normals of aabb = x,y,z axes vectors since aabb is axis aligned)
  7928. var axes = [
  7929. 0, - f0.z, f0.y, 0, - f1.z, f1.y, 0, - f2.z, f2.y,
  7930. f0.z, 0, - f0.x, f1.z, 0, - f1.x, f2.z, 0, - f2.x,
  7931. - f0.y, f0.x, 0, - f1.y, f1.x, 0, - f2.y, f2.x, 0
  7932. ];
  7933. if ( ! satForAxes( axes ) ) {
  7934. return false;
  7935. }
  7936. // test 3 face normals from the aabb
  7937. axes = [ 1, 0, 0, 0, 1, 0, 0, 0, 1 ];
  7938. if ( ! satForAxes( axes ) ) {
  7939. return false;
  7940. }
  7941. // finally testing the face normal of the triangle
  7942. // use already existing triangle edge vectors here
  7943. triangleNormal.crossVectors( f0, f1 );
  7944. axes = [ triangleNormal.x, triangleNormal.y, triangleNormal.z ];
  7945. return satForAxes( axes );
  7946. };
  7947. } )(),
  7948. clampPoint: function ( point, target ) {
  7949. if ( target === undefined ) {
  7950. console.warn( 'THREE.Box3: .clampPoint() target is now required' );
  7951. target = new Vector3();
  7952. }
  7953. return target.copy( point ).clamp( this.min, this.max );
  7954. },
  7955. distanceToPoint: function () {
  7956. var v1 = new Vector3();
  7957. return function distanceToPoint( point ) {
  7958. var clampedPoint = v1.copy( point ).clamp( this.min, this.max );
  7959. return clampedPoint.sub( point ).length();
  7960. };
  7961. }(),
  7962. getBoundingSphere: function () {
  7963. var v1 = new Vector3();
  7964. return function getBoundingSphere( target ) {
  7965. if ( target === undefined ) {
  7966. console.warn( 'THREE.Box3: .getBoundingSphere() target is now required' );
  7967. target = new Sphere();
  7968. }
  7969. this.getCenter( target.center );
  7970. target.radius = this.getSize( v1 ).length() * 0.5;
  7971. return target;
  7972. };
  7973. }(),
  7974. intersect: function ( box ) {
  7975. this.min.max( box.min );
  7976. this.max.min( box.max );
  7977. // 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.
  7978. if ( this.isEmpty() ) this.makeEmpty();
  7979. return this;
  7980. },
  7981. union: function ( box ) {
  7982. this.min.min( box.min );
  7983. this.max.max( box.max );
  7984. return this;
  7985. },
  7986. applyMatrix4: function () {
  7987. var points = [
  7988. new Vector3(),
  7989. new Vector3(),
  7990. new Vector3(),
  7991. new Vector3(),
  7992. new Vector3(),
  7993. new Vector3(),
  7994. new Vector3(),
  7995. new Vector3()
  7996. ];
  7997. return function applyMatrix4( matrix ) {
  7998. // transform of empty box is an empty box.
  7999. if ( this.isEmpty() ) return this;
  8000. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  8001. points[ 0 ].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000
  8002. points[ 1 ].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001
  8003. points[ 2 ].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010
  8004. points[ 3 ].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011
  8005. points[ 4 ].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100
  8006. points[ 5 ].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101
  8007. points[ 6 ].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110
  8008. points[ 7 ].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111
  8009. this.setFromPoints( points );
  8010. return this;
  8011. };
  8012. }(),
  8013. translate: function ( offset ) {
  8014. this.min.add( offset );
  8015. this.max.add( offset );
  8016. return this;
  8017. },
  8018. equals: function ( box ) {
  8019. return box.min.equals( this.min ) && box.max.equals( this.max );
  8020. }
  8021. } );
  8022. /**
  8023. * @author bhouston / http://clara.io
  8024. * @author mrdoob / http://mrdoob.com/
  8025. */
  8026. function Sphere( center, radius ) {
  8027. this.center = ( center !== undefined ) ? center : new Vector3();
  8028. this.radius = ( radius !== undefined ) ? radius : 0;
  8029. }
  8030. Object.assign( Sphere.prototype, {
  8031. set: function ( center, radius ) {
  8032. this.center.copy( center );
  8033. this.radius = radius;
  8034. return this;
  8035. },
  8036. setFromPoints: function () {
  8037. var box = new Box3();
  8038. return function setFromPoints( points, optionalCenter ) {
  8039. var center = this.center;
  8040. if ( optionalCenter !== undefined ) {
  8041. center.copy( optionalCenter );
  8042. } else {
  8043. box.setFromPoints( points ).getCenter( center );
  8044. }
  8045. var maxRadiusSq = 0;
  8046. for ( var i = 0, il = points.length; i < il; i ++ ) {
  8047. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) );
  8048. }
  8049. this.radius = Math.sqrt( maxRadiusSq );
  8050. return this;
  8051. };
  8052. }(),
  8053. clone: function () {
  8054. return new this.constructor().copy( this );
  8055. },
  8056. copy: function ( sphere ) {
  8057. this.center.copy( sphere.center );
  8058. this.radius = sphere.radius;
  8059. return this;
  8060. },
  8061. empty: function () {
  8062. return ( this.radius <= 0 );
  8063. },
  8064. containsPoint: function ( point ) {
  8065. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  8066. },
  8067. distanceToPoint: function ( point ) {
  8068. return ( point.distanceTo( this.center ) - this.radius );
  8069. },
  8070. intersectsSphere: function ( sphere ) {
  8071. var radiusSum = this.radius + sphere.radius;
  8072. return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );
  8073. },
  8074. intersectsBox: function ( box ) {
  8075. return box.intersectsSphere( this );
  8076. },
  8077. intersectsPlane: function ( plane ) {
  8078. return Math.abs( plane.distanceToPoint( this.center ) ) <= this.radius;
  8079. },
  8080. clampPoint: function ( point, target ) {
  8081. var deltaLengthSq = this.center.distanceToSquared( point );
  8082. if ( target === undefined ) {
  8083. console.warn( 'THREE.Sphere: .clampPoint() target is now required' );
  8084. target = new Vector3();
  8085. }
  8086. target.copy( point );
  8087. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  8088. target.sub( this.center ).normalize();
  8089. target.multiplyScalar( this.radius ).add( this.center );
  8090. }
  8091. return target;
  8092. },
  8093. getBoundingBox: function ( target ) {
  8094. if ( target === undefined ) {
  8095. console.warn( 'THREE.Sphere: .getBoundingBox() target is now required' );
  8096. target = new Box3();
  8097. }
  8098. target.set( this.center, this.center );
  8099. target.expandByScalar( this.radius );
  8100. return target;
  8101. },
  8102. applyMatrix4: function ( matrix ) {
  8103. this.center.applyMatrix4( matrix );
  8104. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  8105. return this;
  8106. },
  8107. translate: function ( offset ) {
  8108. this.center.add( offset );
  8109. return this;
  8110. },
  8111. equals: function ( sphere ) {
  8112. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  8113. }
  8114. } );
  8115. /**
  8116. * @author bhouston / http://clara.io
  8117. */
  8118. function Plane( normal, constant ) {
  8119. // normal is assumed to be normalized
  8120. this.normal = ( normal !== undefined ) ? normal : new Vector3( 1, 0, 0 );
  8121. this.constant = ( constant !== undefined ) ? constant : 0;
  8122. }
  8123. Object.assign( Plane.prototype, {
  8124. set: function ( normal, constant ) {
  8125. this.normal.copy( normal );
  8126. this.constant = constant;
  8127. return this;
  8128. },
  8129. setComponents: function ( x, y, z, w ) {
  8130. this.normal.set( x, y, z );
  8131. this.constant = w;
  8132. return this;
  8133. },
  8134. setFromNormalAndCoplanarPoint: function ( normal, point ) {
  8135. this.normal.copy( normal );
  8136. this.constant = - point.dot( this.normal );
  8137. return this;
  8138. },
  8139. setFromCoplanarPoints: function () {
  8140. var v1 = new Vector3();
  8141. var v2 = new Vector3();
  8142. return function setFromCoplanarPoints( a, b, c ) {
  8143. var normal = v1.subVectors( c, b ).cross( v2.subVectors( a, b ) ).normalize();
  8144. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  8145. this.setFromNormalAndCoplanarPoint( normal, a );
  8146. return this;
  8147. };
  8148. }(),
  8149. clone: function () {
  8150. return new this.constructor().copy( this );
  8151. },
  8152. copy: function ( plane ) {
  8153. this.normal.copy( plane.normal );
  8154. this.constant = plane.constant;
  8155. return this;
  8156. },
  8157. normalize: function () {
  8158. // Note: will lead to a divide by zero if the plane is invalid.
  8159. var inverseNormalLength = 1.0 / this.normal.length();
  8160. this.normal.multiplyScalar( inverseNormalLength );
  8161. this.constant *= inverseNormalLength;
  8162. return this;
  8163. },
  8164. negate: function () {
  8165. this.constant *= - 1;
  8166. this.normal.negate();
  8167. return this;
  8168. },
  8169. distanceToPoint: function ( point ) {
  8170. return this.normal.dot( point ) + this.constant;
  8171. },
  8172. distanceToSphere: function ( sphere ) {
  8173. return this.distanceToPoint( sphere.center ) - sphere.radius;
  8174. },
  8175. projectPoint: function ( point, target ) {
  8176. if ( target === undefined ) {
  8177. console.warn( 'THREE.Plane: .projectPoint() target is now required' );
  8178. target = new Vector3();
  8179. }
  8180. return target.copy( this.normal ).multiplyScalar( - this.distanceToPoint( point ) ).add( point );
  8181. },
  8182. intersectLine: function () {
  8183. var v1 = new Vector3();
  8184. return function intersectLine( line, target ) {
  8185. if ( target === undefined ) {
  8186. console.warn( 'THREE.Plane: .intersectLine() target is now required' );
  8187. target = new Vector3();
  8188. }
  8189. var direction = line.delta( v1 );
  8190. var denominator = this.normal.dot( direction );
  8191. if ( denominator === 0 ) {
  8192. // line is coplanar, return origin
  8193. if ( this.distanceToPoint( line.start ) === 0 ) {
  8194. return target.copy( line.start );
  8195. }
  8196. // Unsure if this is the correct method to handle this case.
  8197. return undefined;
  8198. }
  8199. var t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
  8200. if ( t < 0 || t > 1 ) {
  8201. return undefined;
  8202. }
  8203. return target.copy( direction ).multiplyScalar( t ).add( line.start );
  8204. };
  8205. }(),
  8206. intersectsLine: function ( line ) {
  8207. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  8208. var startSign = this.distanceToPoint( line.start );
  8209. var endSign = this.distanceToPoint( line.end );
  8210. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  8211. },
  8212. intersectsBox: function ( box ) {
  8213. return box.intersectsPlane( this );
  8214. },
  8215. intersectsSphere: function ( sphere ) {
  8216. return sphere.intersectsPlane( this );
  8217. },
  8218. coplanarPoint: function ( target ) {
  8219. if ( target === undefined ) {
  8220. console.warn( 'THREE.Plane: .coplanarPoint() target is now required' );
  8221. target = new Vector3();
  8222. }
  8223. return target.copy( this.normal ).multiplyScalar( - this.constant );
  8224. },
  8225. applyMatrix4: function () {
  8226. var v1 = new Vector3();
  8227. var m1 = new Matrix3();
  8228. return function applyMatrix4( matrix, optionalNormalMatrix ) {
  8229. var normalMatrix = optionalNormalMatrix || m1.getNormalMatrix( matrix );
  8230. var referencePoint = this.coplanarPoint( v1 ).applyMatrix4( matrix );
  8231. var normal = this.normal.applyMatrix3( normalMatrix ).normalize();
  8232. this.constant = - referencePoint.dot( normal );
  8233. return this;
  8234. };
  8235. }(),
  8236. translate: function ( offset ) {
  8237. this.constant -= offset.dot( this.normal );
  8238. return this;
  8239. },
  8240. equals: function ( plane ) {
  8241. return plane.normal.equals( this.normal ) && ( plane.constant === this.constant );
  8242. }
  8243. } );
  8244. /**
  8245. * @author mrdoob / http://mrdoob.com/
  8246. * @author alteredq / http://alteredqualia.com/
  8247. * @author bhouston / http://clara.io
  8248. */
  8249. function Frustum( p0, p1, p2, p3, p4, p5 ) {
  8250. this.planes = [
  8251. ( p0 !== undefined ) ? p0 : new Plane(),
  8252. ( p1 !== undefined ) ? p1 : new Plane(),
  8253. ( p2 !== undefined ) ? p2 : new Plane(),
  8254. ( p3 !== undefined ) ? p3 : new Plane(),
  8255. ( p4 !== undefined ) ? p4 : new Plane(),
  8256. ( p5 !== undefined ) ? p5 : new Plane()
  8257. ];
  8258. }
  8259. Object.assign( Frustum.prototype, {
  8260. set: function ( p0, p1, p2, p3, p4, p5 ) {
  8261. var planes = this.planes;
  8262. planes[ 0 ].copy( p0 );
  8263. planes[ 1 ].copy( p1 );
  8264. planes[ 2 ].copy( p2 );
  8265. planes[ 3 ].copy( p3 );
  8266. planes[ 4 ].copy( p4 );
  8267. planes[ 5 ].copy( p5 );
  8268. return this;
  8269. },
  8270. clone: function () {
  8271. return new this.constructor().copy( this );
  8272. },
  8273. copy: function ( frustum ) {
  8274. var planes = this.planes;
  8275. for ( var i = 0; i < 6; i ++ ) {
  8276. planes[ i ].copy( frustum.planes[ i ] );
  8277. }
  8278. return this;
  8279. },
  8280. setFromMatrix: function ( m ) {
  8281. var planes = this.planes;
  8282. var me = m.elements;
  8283. var me0 = me[ 0 ], me1 = me[ 1 ], me2 = me[ 2 ], me3 = me[ 3 ];
  8284. var me4 = me[ 4 ], me5 = me[ 5 ], me6 = me[ 6 ], me7 = me[ 7 ];
  8285. var me8 = me[ 8 ], me9 = me[ 9 ], me10 = me[ 10 ], me11 = me[ 11 ];
  8286. var me12 = me[ 12 ], me13 = me[ 13 ], me14 = me[ 14 ], me15 = me[ 15 ];
  8287. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  8288. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  8289. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  8290. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  8291. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize();
  8292. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize();
  8293. return this;
  8294. },
  8295. intersectsObject: function () {
  8296. var sphere = new Sphere();
  8297. return function intersectsObject( object ) {
  8298. var geometry = object.geometry;
  8299. if ( geometry.boundingSphere === null )
  8300. geometry.computeBoundingSphere();
  8301. sphere.copy( geometry.boundingSphere )
  8302. .applyMatrix4( object.matrixWorld );
  8303. return this.intersectsSphere( sphere );
  8304. };
  8305. }(),
  8306. intersectsSprite: function () {
  8307. var sphere = new Sphere();
  8308. return function intersectsSprite( sprite ) {
  8309. sphere.center.set( 0, 0, 0 );
  8310. sphere.radius = 0.7071067811865476;
  8311. sphere.applyMatrix4( sprite.matrixWorld );
  8312. return this.intersectsSphere( sphere );
  8313. };
  8314. }(),
  8315. intersectsSphere: function ( sphere ) {
  8316. var planes = this.planes;
  8317. var center = sphere.center;
  8318. var negRadius = - sphere.radius;
  8319. for ( var i = 0; i < 6; i ++ ) {
  8320. var distance = planes[ i ].distanceToPoint( center );
  8321. if ( distance < negRadius ) {
  8322. return false;
  8323. }
  8324. }
  8325. return true;
  8326. },
  8327. intersectsBox: function () {
  8328. var p = new Vector3();
  8329. return function intersectsBox( box ) {
  8330. var planes = this.planes;
  8331. for ( var i = 0; i < 6; i ++ ) {
  8332. var plane = planes[ i ];
  8333. // corner at max distance
  8334. p.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  8335. p.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  8336. p.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  8337. if ( plane.distanceToPoint( p ) < 0 ) {
  8338. return false;
  8339. }
  8340. }
  8341. return true;
  8342. };
  8343. }(),
  8344. containsPoint: function ( point ) {
  8345. var planes = this.planes;
  8346. for ( var i = 0; i < 6; i ++ ) {
  8347. if ( planes[ i ].distanceToPoint( point ) < 0 ) {
  8348. return false;
  8349. }
  8350. }
  8351. return true;
  8352. }
  8353. } );
  8354. var alphamap_fragment = "#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vUv ).g;\n#endif";
  8355. var alphamap_pars_fragment = "#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif";
  8356. var alphatest_fragment = "#ifdef ALPHATEST\n\tif ( diffuseColor.a < ALPHATEST ) discard;\n#endif";
  8357. 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( PHYSICAL )\n\t\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\t\treflectedLight.indirectSpecular *= computeSpecularOcclusion( dotNV, ambientOcclusion, material.specularRoughness );\n\t#endif\n#endif";
  8358. var aomap_pars_fragment = "#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif";
  8359. var begin_vertex = "vec3 transformed = vec3( position );";
  8360. var beginnormal_vertex = "vec3 objectNormal = vec3( normal );\n#ifdef USE_TANGENT\n\tvec3 objectTangent = vec3( tangent.xyz );\n#endif";
  8361. 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}\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 GeometricContext geometry, const in vec3 specularColor, const in float roughness ) {\n\tfloat alpha = pow2( roughness );\n\tvec3 halfDir = normalize( incidentLight.direction + geometry.viewDir );\n\tfloat dotNL = saturate( dot( geometry.normal, incidentLight.direction ) );\n\tfloat dotNV = saturate( dot( geometry.normal, 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_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 GeometricContext geometry, const in vec3 specularColor, const in float roughness ) {\n\tfloat dotNV = saturate( dot( geometry.normal, geometry.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( specularColor, dotNV );\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}";
  8362. 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";
  8363. var clipping_planes_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tvec4 plane;\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {\n\t\tplane = clippingPlanes[ i ];\n\t\tif ( dot( vViewPosition, plane.xyz ) > plane.w ) discard;\n\t}\n\t#if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES\n\t\tbool clipped = true;\n\t\t#pragma unroll_loop\n\t\tfor ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {\n\t\t\tplane = clippingPlanes[ i ];\n\t\t\tclipped = ( dot( vViewPosition, plane.xyz ) > plane.w ) && clipped;\n\t\t}\n\t\tif ( clipped ) discard;\n\t#endif\n#endif";
  8364. var clipping_planes_pars_fragment = "#if NUM_CLIPPING_PLANES > 0\n\t#if ! defined( PHYSICAL ) && ! defined( PHONG ) && ! defined( MATCAP )\n\t\tvarying vec3 vViewPosition;\n\t#endif\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif";
  8365. var clipping_planes_pars_vertex = "#if NUM_CLIPPING_PLANES > 0 && ! defined( PHYSICAL ) && ! defined( PHONG ) && ! defined( MATCAP )\n\tvarying vec3 vViewPosition;\n#endif";
  8366. var clipping_planes_vertex = "#if NUM_CLIPPING_PLANES > 0 && ! defined( PHYSICAL ) && ! defined( PHONG ) && ! defined( MATCAP )\n\tvViewPosition = - mvPosition.xyz;\n#endif";
  8367. var color_fragment = "#ifdef USE_COLOR\n\tdiffuseColor.rgb *= vColor;\n#endif";
  8368. var color_pars_fragment = "#ifdef USE_COLOR\n\tvarying vec3 vColor;\n#endif";
  8369. var color_pars_vertex = "#ifdef USE_COLOR\n\tvarying vec3 vColor;\n#endif";
  8370. var color_vertex = "#ifdef USE_COLOR\n\tvColor.xyz = color.xyz;\n#endif";
  8371. 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#define saturate(a) clamp( a, 0.0, 1.0 )\n#define whiteCompliment(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}\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};\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}";
  8372. var cube_uv_reflection_fragment = "#ifdef ENVMAP_TYPE_CUBE_UV\n#define cubeUV_textureSize (1024.0)\nint getFaceFromDirection(vec3 direction) {\n\tvec3 absDirection = abs(direction);\n\tint face = -1;\n\tif( absDirection.x > absDirection.z ) {\n\t\tif(absDirection.x > absDirection.y )\n\t\t\tface = direction.x > 0.0 ? 0 : 3;\n\t\telse\n\t\t\tface = direction.y > 0.0 ? 1 : 4;\n\t}\n\telse {\n\t\tif(absDirection.z > absDirection.y )\n\t\t\tface = direction.z > 0.0 ? 2 : 5;\n\t\telse\n\t\t\tface = direction.y > 0.0 ? 1 : 4;\n\t}\n\treturn face;\n}\n#define cubeUV_maxLods1 (log2(cubeUV_textureSize*0.25) - 1.0)\n#define cubeUV_rangeClamp (exp2((6.0 - 1.0) * 2.0))\nvec2 MipLevelInfo( vec3 vec, float roughnessLevel, float roughness ) {\n\tfloat scale = exp2(cubeUV_maxLods1 - roughnessLevel);\n\tfloat dxRoughness = dFdx(roughness);\n\tfloat dyRoughness = dFdy(roughness);\n\tvec3 dx = dFdx( vec * scale * dxRoughness );\n\tvec3 dy = dFdy( vec * scale * dyRoughness );\n\tfloat d = max( dot( dx, dx ), dot( dy, dy ) );\n\td = clamp(d, 1.0, cubeUV_rangeClamp);\n\tfloat mipLevel = 0.5 * log2(d);\n\treturn vec2(floor(mipLevel), fract(mipLevel));\n}\n#define cubeUV_maxLods2 (log2(cubeUV_textureSize*0.25) - 2.0)\n#define cubeUV_rcpTextureSize (1.0 / cubeUV_textureSize)\nvec2 getCubeUV(vec3 direction, float roughnessLevel, float mipLevel) {\n\tmipLevel = roughnessLevel > cubeUV_maxLods2 - 3.0 ? 0.0 : mipLevel;\n\tfloat a = 16.0 * cubeUV_rcpTextureSize;\n\tvec2 exp2_packed = exp2( vec2( roughnessLevel, mipLevel ) );\n\tvec2 rcp_exp2_packed = vec2( 1.0 ) / exp2_packed;\n\tfloat powScale = exp2_packed.x * exp2_packed.y;\n\tfloat scale = rcp_exp2_packed.x * rcp_exp2_packed.y * 0.25;\n\tfloat mipOffset = 0.75*(1.0 - rcp_exp2_packed.y) * rcp_exp2_packed.x;\n\tbool bRes = mipLevel == 0.0;\n\tscale = bRes && (scale < a) ? a : scale;\n\tvec3 r;\n\tvec2 offset;\n\tint face = getFaceFromDirection(direction);\n\tfloat rcpPowScale = 1.0 / powScale;\n\tif( face == 0) {\n\t\tr = vec3(direction.x, -direction.z, direction.y);\n\t\toffset = vec2(0.0+mipOffset,0.75 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? a : offset.y;\n\t}\n\telse if( face == 1) {\n\t\tr = vec3(direction.y, direction.x, direction.z);\n\t\toffset = vec2(scale+mipOffset, 0.75 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? a : offset.y;\n\t}\n\telse if( face == 2) {\n\t\tr = vec3(direction.z, direction.x, direction.y);\n\t\toffset = vec2(2.0*scale+mipOffset, 0.75 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? a : offset.y;\n\t}\n\telse if( face == 3) {\n\t\tr = vec3(direction.x, direction.z, direction.y);\n\t\toffset = vec2(0.0+mipOffset,0.5 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? 0.0 : offset.y;\n\t}\n\telse if( face == 4) {\n\t\tr = vec3(direction.y, direction.x, -direction.z);\n\t\toffset = vec2(scale+mipOffset, 0.5 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? 0.0 : offset.y;\n\t}\n\telse {\n\t\tr = vec3(direction.z, -direction.x, direction.y);\n\t\toffset = vec2(2.0*scale+mipOffset, 0.5 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? 0.0 : offset.y;\n\t}\n\tr = normalize(r);\n\tfloat texelOffset = 0.5 * cubeUV_rcpTextureSize;\n\tvec2 s = ( r.yz / abs( r.x ) + vec2( 1.0 ) ) * 0.5;\n\tvec2 base = offset + vec2( texelOffset );\n\treturn base + s * ( scale - 2.0 * texelOffset );\n}\n#define cubeUV_maxLods3 (log2(cubeUV_textureSize*0.25) - 3.0)\nvec4 textureCubeUV( sampler2D envMap, vec3 reflectedDirection, float roughness ) {\n\tfloat roughnessVal = roughness* cubeUV_maxLods3;\n\tfloat r1 = floor(roughnessVal);\n\tfloat r2 = r1 + 1.0;\n\tfloat t = fract(roughnessVal);\n\tvec2 mipInfo = MipLevelInfo(reflectedDirection, r1, roughness);\n\tfloat s = mipInfo.y;\n\tfloat level0 = mipInfo.x;\n\tfloat level1 = level0 + 1.0;\n\tlevel1 = level1 > 5.0 ? 5.0 : level1;\n\tlevel0 += min( floor( s + 0.5 ), 5.0 );\n\tvec2 uv_10 = getCubeUV(reflectedDirection, r1, level0);\n\tvec4 color10 = envMapTexelToLinear(texture2D(envMap, uv_10));\n\tvec2 uv_20 = getCubeUV(reflectedDirection, r2, level0);\n\tvec4 color20 = envMapTexelToLinear(texture2D(envMap, uv_20));\n\tvec4 result = mix(color10, color20, t);\n\treturn vec4(result.rgb, 1.0);\n}\n#endif";
  8373. var defaultnormal_vertex = "vec3 transformedNormal = normalMatrix * objectNormal;\n#ifdef FLIP_SIDED\n\ttransformedNormal = - transformedNormal;\n#endif\n#ifdef USE_TANGENT\n\tvec3 transformedTangent = normalMatrix * objectTangent;\n\t#ifdef FLIP_SIDED\n\t\ttransformedTangent = - transformedTangent;\n\t#endif\n#endif";
  8374. var displacementmap_pars_vertex = "#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif";
  8375. var displacementmap_vertex = "#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normalize( objectNormal ) * ( texture2D( displacementMap, uv ).x * displacementScale + displacementBias );\n#endif";
  8376. var emissivemap_fragment = "#ifdef USE_EMISSIVEMAP\n\tvec4 emissiveColor = texture2D( emissiveMap, vUv );\n\temissiveColor.rgb = emissiveMapTexelToLinear( emissiveColor ).rgb;\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n#endif";
  8377. var emissivemap_pars_fragment = "#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif";
  8378. var encodings_fragment = "gl_FragColor = linearToOutputTexel( gl_FragColor );";
  8379. 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 = min( floor( D ) / 255.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}";
  8380. var envmap_fragment = "#ifdef USE_ENVMAP\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG )\n\t\tvec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );\n\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvec3 reflectVec = reflect( cameraToVertex, worldNormal );\n\t\t#else\n\t\t\tvec3 reflectVec = refract( cameraToVertex, 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_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\tenvColor = envMapTexelToLinear( envColor );\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";
  8381. var envmap_pars_fragment = "#if defined( USE_ENVMAP ) || defined( PHYSICAL )\n\tuniform float reflectivity;\n\tuniform float envMapIntensity;\n#endif\n#ifdef USE_ENVMAP\n\t#if ! defined( PHYSICAL ) && ( defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) )\n\t\tvarying vec3 vWorldPosition;\n\t#endif\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tuniform samplerCube envMap;\n\t#else\n\t\tuniform sampler2D envMap;\n\t#endif\n\tuniform float flipEnvMap;\n\tuniform int maxMipLevel;\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( PHYSICAL )\n\t\tuniform float refractionRatio;\n\t#else\n\t\tvarying vec3 vReflect;\n\t#endif\n#endif";
  8382. var envmap_pars_vertex = "#ifdef USE_ENVMAP\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG )\n\t\tvarying vec3 vWorldPosition;\n\t#else\n\t\tvarying vec3 vReflect;\n\t\tuniform float refractionRatio;\n\t#endif\n#endif";
  8383. var envmap_vertex = "#ifdef USE_ENVMAP\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG )\n\t\tvWorldPosition = worldPosition.xyz;\n\t#else\n\t\tvec3 cameraToVertex = normalize( worldPosition.xyz - cameraPosition );\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";
  8384. var fog_vertex = "#ifdef USE_FOG\n\tfogDepth = -mvPosition.z;\n#endif";
  8385. var fog_pars_vertex = "#ifdef USE_FOG\n\tvarying float fogDepth;\n#endif";
  8386. var fog_fragment = "#ifdef USE_FOG\n\t#ifdef FOG_EXP2\n\t\tfloat fogFactor = whiteCompliment( exp2( - fogDensity * fogDensity * fogDepth * fogDepth * LOG2 ) );\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";
  8387. 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";
  8388. var gradientmap_pars_fragment = "#ifdef TOON\n\tuniform sampler2D gradientMap;\n\tvec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) {\n\t\tfloat dotNL = dot( normal, lightDirection );\n\t\tvec2 coord = vec2( dotNL * 0.5 + 0.5, 0.0 );\n\t\t#ifdef USE_GRADIENTMAP\n\t\t\treturn texture2D( gradientMap, coord ).rgb;\n\t\t#else\n\t\t\treturn ( coord.x < 0.7 ) ? vec3( 0.7 ) : vec3( 1.0 );\n\t\t#endif\n\t}\n#endif";
  8389. var lightmap_fragment = "#ifdef USE_LIGHTMAP\n\treflectedLight.indirectDiffuse += PI * texture2D( lightMap, vUv2 ).xyz * lightMapIntensity;\n#endif";
  8390. var lightmap_pars_fragment = "#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif";
  8391. var lights_lambert_vertex = "vec3 diffuse = vec3( 1.0 );\nGeometricContext geometry;\ngeometry.position = mvPosition.xyz;\ngeometry.normal = normalize( transformedNormal );\ngeometry.viewDir = 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\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#endif\n#if NUM_SPOT_LIGHTS > 0\n\t#pragma unroll_loop\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#endif\n#if NUM_DIR_LIGHTS > 0\n\t#pragma unroll_loop\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#endif\n#if NUM_HEMI_LIGHTS > 0\n\t#pragma unroll_loop\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#endif";
  8392. var lights_pars_begin = "uniform vec3 ambientLightColor;\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\tint shadow;\n\t\tfloat shadowBias;\n\t\tfloat shadowRadius;\n\t\tvec2 shadowMapSize;\n\t};\n\tuniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ];\n\tvoid getDirectionalDirectLightIrradiance( const in DirectionalLight directionalLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\t\tdirectLight.color = directionalLight.color;\n\t\tdirectLight.direction = directionalLight.direction;\n\t\tdirectLight.visible = true;\n\t}\n#endif\n#if NUM_POINT_LIGHTS > 0\n\tstruct PointLight {\n\t\tvec3 position;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t\tint shadow;\n\t\tfloat shadowBias;\n\t\tfloat shadowRadius;\n\t\tvec2 shadowMapSize;\n\t\tfloat shadowCameraNear;\n\t\tfloat shadowCameraFar;\n\t};\n\tuniform PointLight pointLights[ NUM_POINT_LIGHTS ];\n\tvoid getPointDirectLightIrradiance( const in PointLight pointLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\t\tvec3 lVector = pointLight.position - geometry.position;\n\t\tdirectLight.direction = normalize( lVector );\n\t\tfloat lightDistance = length( lVector );\n\t\tdirectLight.color = pointLight.color;\n\t\tdirectLight.color *= punctualLightIntensityToIrradianceFactor( lightDistance, pointLight.distance, pointLight.decay );\n\t\tdirectLight.visible = ( directLight.color != vec3( 0.0 ) );\n\t}\n#endif\n#if NUM_SPOT_LIGHTS > 0\n\tstruct SpotLight {\n\t\tvec3 position;\n\t\tvec3 direction;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t\tfloat coneCos;\n\t\tfloat penumbraCos;\n\t\tint shadow;\n\t\tfloat shadowBias;\n\t\tfloat shadowRadius;\n\t\tvec2 shadowMapSize;\n\t};\n\tuniform SpotLight spotLights[ NUM_SPOT_LIGHTS ];\n\tvoid getSpotDirectLightIrradiance( const in SpotLight spotLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\t\tvec3 lVector = spotLight.position - geometry.position;\n\t\tdirectLight.direction = normalize( lVector );\n\t\tfloat lightDistance = length( lVector );\n\t\tfloat angleCos = dot( directLight.direction, spotLight.direction );\n\t\tif ( angleCos > spotLight.coneCos ) {\n\t\t\tfloat spotEffect = smoothstep( spotLight.coneCos, spotLight.penumbraCos, angleCos );\n\t\t\tdirectLight.color = spotLight.color;\n\t\t\tdirectLight.color *= spotEffect * punctualLightIntensityToIrradianceFactor( lightDistance, spotLight.distance, spotLight.decay );\n\t\t\tdirectLight.visible = true;\n\t\t} else {\n\t\t\tdirectLight.color = vec3( 0.0 );\n\t\t\tdirectLight.visible = false;\n\t\t}\n\t}\n#endif\n#if NUM_RECT_AREA_LIGHTS > 0\n\tstruct RectAreaLight {\n\t\tvec3 color;\n\t\tvec3 position;\n\t\tvec3 halfWidth;\n\t\tvec3 halfHeight;\n\t};\n\tuniform sampler2D ltc_1;\tuniform sampler2D ltc_2;\n\tuniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ];\n#endif\n#if NUM_HEMI_LIGHTS > 0\n\tstruct HemisphereLight {\n\t\tvec3 direction;\n\t\tvec3 skyColor;\n\t\tvec3 groundColor;\n\t};\n\tuniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ];\n\tvec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in GeometricContext geometry ) {\n\t\tfloat dotNL = dot( geometry.normal, hemiLight.direction );\n\t\tfloat hemiDiffuseWeight = 0.5 * dotNL + 0.5;\n\t\tvec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight );\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\t\tirradiance *= PI;\n\t\t#endif\n\t\treturn irradiance;\n\t}\n#endif";
  8393. var envmap_physical_pars_fragment = "#if defined( USE_ENVMAP ) && defined( PHYSICAL )\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\tvec3 queryVec = vec3( flipEnvMap * worldNormal.x, worldNormal.yz );\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, queryVec, 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 blinnShininessExponent, const in int maxMIPLevel ) {\n\t\tfloat maxMIPLevelScalar = float( maxMIPLevel );\n\t\tfloat desiredMIPLevel = maxMIPLevelScalar + 0.79248 - 0.5 * log2( pow2( blinnShininessExponent ) + 1.0 );\n\t\treturn clamp( desiredMIPLevel, 0.0, maxMIPLevelScalar );\n\t}\n\tvec3 getLightProbeIndirectRadiance( const in GeometricContext geometry, const in float blinnShininessExponent, const in int maxMIPLevel ) {\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvec3 reflectVec = reflect( -geometry.viewDir, geometry.normal );\n\t\t#else\n\t\t\tvec3 reflectVec = refract( -geometry.viewDir, geometry.normal, refractionRatio );\n\t\t#endif\n\t\treflectVec = inverseTransformDirection( reflectVec, viewMatrix );\n\t\tfloat specularMIPLevel = getSpecularMIPLevel( blinnShininessExponent, 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\tvec3 queryReflectVec = vec3( flipEnvMap * reflectVec.x, reflectVec.yz );\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, queryReflectVec, BlinnExponentToGGXRoughness(blinnShininessExponent ));\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";
  8394. var lights_phong_fragment = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;";
  8395. 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\t#ifdef TOON\n\t\tvec3 irradiance = getGradientIrradiance( geometry.normal, directLight.direction ) * directLight.color;\n\t#else\n\t\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\t\tvec3 irradiance = dotNL * directLight.color;\n\t#endif\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)";
  8396. var lights_physical_fragment = "PhysicalMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor );\nmaterial.specularRoughness = clamp( roughnessFactor, 0.04, 1.0 );\n#ifdef STANDARD\n\tmaterial.specularColor = mix( vec3( DEFAULT_SPECULAR_COEFFICIENT ), diffuseColor.rgb, metalnessFactor );\n#else\n\tmaterial.specularColor = mix( vec3( MAXIMUM_SPECULAR_COEFFICIENT * pow2( reflectivity ) ), diffuseColor.rgb, metalnessFactor );\n\tmaterial.clearCoat = saturate( clearCoat );\tmaterial.clearCoatRoughness = clamp( clearCoatRoughness, 0.04, 1.0 );\n#endif";
  8397. var lights_physical_pars_fragment = "struct PhysicalMaterial {\n\tvec3\tdiffuseColor;\n\tfloat\tspecularRoughness;\n\tvec3\tspecularColor;\n\t#ifndef STANDARD\n\t\tfloat clearCoat;\n\t\tfloat clearCoatRoughness;\n\t#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#ifndef STANDARD\n\t\tfloat clearCoatDHR = material.clearCoat * clearCoatDHRApprox( material.clearCoatRoughness, dotNL );\n\t#else\n\t\tfloat clearCoatDHR = 0.0;\n\t#endif\n\treflectedLight.directSpecular += ( 1.0 - clearCoatDHR ) * irradiance * BRDF_Specular_GGX( directLight, geometry, material.specularColor, material.specularRoughness );\n\treflectedLight.directDiffuse += ( 1.0 - clearCoatDHR ) * irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n\t#ifndef STANDARD\n\t\treflectedLight.directSpecular += irradiance * material.clearCoat * BRDF_Specular_GGX( directLight, geometry, vec3( DEFAULT_SPECULAR_COEFFICIENT ), material.clearCoatRoughness );\n\t#endif\n}\nvoid RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\t#ifndef ENVMAP_TYPE_CUBE_UV\n\t\treflectedLight.indirectDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n\t#endif\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#ifndef STANDARD\n\t\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\t\tfloat dotNL = dotNV;\n\t\tfloat clearCoatDHR = material.clearCoat * clearCoatDHRApprox( material.clearCoatRoughness, dotNL );\n\t#else\n\t\tfloat clearCoatDHR = 0.0;\n\t#endif\n\tfloat clearCoatInv = 1.0 - clearCoatDHR;\n\t#if defined( ENVMAP_TYPE_CUBE_UV )\n\t\tvec3 singleScattering = vec3( 0.0 );\n\t\tvec3 multiScattering = vec3( 0.0 );\n\t\tvec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI;\n\t\tBRDF_Specular_Multiscattering_Environment( geometry, material.specularColor, material.specularRoughness, singleScattering, multiScattering );\n\t\tvec3 diffuse = material.diffuseColor;\n\t\treflectedLight.indirectSpecular += clearCoatInv * radiance * singleScattering;\n\t\treflectedLight.indirectDiffuse += multiScattering * cosineWeightedIrradiance;\n\t\treflectedLight.indirectDiffuse += diffuse * cosineWeightedIrradiance;\n\t#else\n\t\treflectedLight.indirectSpecular += clearCoatInv * radiance * BRDF_Specular_GGX_Environment( geometry, material.specularColor, material.specularRoughness );\n\t#endif\n\t#ifndef STANDARD\n\t\treflectedLight.indirectSpecular += clearCoatRadiance * material.clearCoat * BRDF_Specular_GGX_Environment( geometry, vec3( DEFAULT_SPECULAR_COEFFICIENT ), material.clearCoatRoughness );\n\t#endif\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\n#define Material_BlinnShininessExponent( material ) GGXRoughnessToBlinnExponent( material.specularRoughness )\n#define Material_ClearCoat_BlinnShininessExponent( material ) GGXRoughnessToBlinnExponent( material.clearCoatRoughness )\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}";
  8398. var lights_fragment_begin = "\nGeometricContext geometry;\ngeometry.position = - vViewPosition;\ngeometry.normal = normal;\ngeometry.viewDir = normalize( vViewPosition );\nIncidentLight directLight;\n#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )\n\tPointLight pointLight;\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tpointLight = pointLights[ i ];\n\t\tgetPointDirectLightIrradiance( pointLight, geometry, directLight );\n\t\t#ifdef USE_SHADOWMAP\n\t\tdirectLight.color *= all( bvec2( pointLight.shadow, directLight.visible ) ) ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n#endif\n#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )\n\tSpotLight spotLight;\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tspotLight = spotLights[ i ];\n\t\tgetSpotDirectLightIrradiance( spotLight, geometry, directLight );\n\t\t#ifdef USE_SHADOWMAP\n\t\tdirectLight.color *= all( bvec2( spotLight.shadow, directLight.visible ) ) ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowBias, spotLight.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n#endif\n#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )\n\tDirectionalLight directionalLight;\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tdirectionalLight = directionalLights[ i ];\n\t\tgetDirectionalDirectLightIrradiance( directionalLight, geometry, directLight );\n\t\t#ifdef USE_SHADOWMAP\n\t\tdirectLight.color *= all( bvec2( directionalLight.shadow, directLight.visible ) ) ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n#endif\n#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea )\n\tRectAreaLight rectAreaLight;\n\t#pragma unroll_loop\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#endif\n#if defined( RE_IndirectDiffuse )\n\tvec3 irradiance = getAmbientLightIrradiance( ambientLightColor );\n\t#if ( NUM_HEMI_LIGHTS > 0 )\n\t\t#pragma unroll_loop\n\t\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\t\tirradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry );\n\t\t}\n\t#endif\n#endif\n#if defined( RE_IndirectSpecular )\n\tvec3 radiance = vec3( 0.0 );\n\tvec3 clearCoatRadiance = vec3( 0.0 );\n#endif";
  8399. var lights_fragment_maps = "#if defined( RE_IndirectDiffuse )\n\t#ifdef USE_LIGHTMAP\n\t\tvec3 lightMapIrradiance = texture2D( lightMap, vUv2 ).xyz * 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( PHYSICAL ) && defined( ENVMAP_TYPE_CUBE_UV )\n\t\tirradiance += getLightProbeIndirectIrradiance( geometry, maxMipLevel );\n\t#endif\n#endif\n#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )\n\tradiance += getLightProbeIndirectRadiance( geometry, Material_BlinnShininessExponent( material ), maxMipLevel );\n\t#ifndef STANDARD\n\t\tclearCoatRadiance += getLightProbeIndirectRadiance( geometry, Material_ClearCoat_BlinnShininessExponent( material ), maxMipLevel );\n\t#endif\n#endif";
  8400. 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, irradiance, clearCoatRadiance, geometry, material, reflectedLight );\n#endif";
  8401. var logdepthbuf_fragment = "#if defined( USE_LOGDEPTHBUF ) && defined( USE_LOGDEPTHBUF_EXT )\n\tgl_FragDepthEXT = log2( vFragDepth ) * logDepthBufFC * 0.5;\n#endif";
  8402. var logdepthbuf_pars_fragment = "#if defined( USE_LOGDEPTHBUF ) && defined( USE_LOGDEPTHBUF_EXT )\n\tuniform float logDepthBufFC;\n\tvarying float vFragDepth;\n#endif";
  8403. var logdepthbuf_pars_vertex = "#ifdef USE_LOGDEPTHBUF\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvarying float vFragDepth;\n\t#else\n\t\tuniform float logDepthBufFC;\n\t#endif\n#endif";
  8404. var logdepthbuf_vertex = "#ifdef USE_LOGDEPTHBUF\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvFragDepth = 1.0 + gl_Position.w;\n\t#else\n\t\tgl_Position.z = log2( max( EPSILON, gl_Position.w + 1.0 ) ) * logDepthBufFC - 1.0;\n\t\tgl_Position.z *= gl_Position.w;\n\t#endif\n#endif";
  8405. var map_fragment = "#ifdef USE_MAP\n\tvec4 texelColor = texture2D( map, vUv );\n\ttexelColor = mapTexelToLinear( texelColor );\n\tdiffuseColor *= texelColor;\n#endif";
  8406. var map_pars_fragment = "#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif";
  8407. var map_particle_fragment = "#ifdef USE_MAP\n\tvec2 uv = ( uvTransform * vec3( gl_PointCoord.x, 1.0 - gl_PointCoord.y, 1 ) ).xy;\n\tvec4 mapTexel = texture2D( map, uv );\n\tdiffuseColor *= mapTexelToLinear( mapTexel );\n#endif";
  8408. var map_particle_pars_fragment = "#ifdef USE_MAP\n\tuniform mat3 uvTransform;\n\tuniform sampler2D map;\n#endif";
  8409. var metalnessmap_fragment = "float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vUv );\n\tmetalnessFactor *= texelMetalness.b;\n#endif";
  8410. var metalnessmap_pars_fragment = "#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif";
  8411. var morphnormal_vertex = "#ifdef USE_MORPHNORMALS\n\tobjectNormal += ( morphNormal0 - normal ) * morphTargetInfluences[ 0 ];\n\tobjectNormal += ( morphNormal1 - normal ) * morphTargetInfluences[ 1 ];\n\tobjectNormal += ( morphNormal2 - normal ) * morphTargetInfluences[ 2 ];\n\tobjectNormal += ( morphNormal3 - normal ) * morphTargetInfluences[ 3 ];\n#endif";
  8412. var morphtarget_pars_vertex = "#ifdef USE_MORPHTARGETS\n\t#ifndef USE_MORPHNORMALS\n\tuniform float morphTargetInfluences[ 8 ];\n\t#else\n\tuniform float morphTargetInfluences[ 4 ];\n\t#endif\n#endif";
  8413. var morphtarget_vertex = "#ifdef USE_MORPHTARGETS\n\ttransformed += ( morphTarget0 - position ) * morphTargetInfluences[ 0 ];\n\ttransformed += ( morphTarget1 - position ) * morphTargetInfluences[ 1 ];\n\ttransformed += ( morphTarget2 - position ) * morphTargetInfluences[ 2 ];\n\ttransformed += ( morphTarget3 - position ) * morphTargetInfluences[ 3 ];\n\t#ifndef USE_MORPHNORMALS\n\ttransformed += ( morphTarget4 - position ) * morphTargetInfluences[ 4 ];\n\ttransformed += ( morphTarget5 - position ) * morphTargetInfluences[ 5 ];\n\ttransformed += ( morphTarget6 - position ) * morphTargetInfluences[ 6 ];\n\ttransformed += ( morphTarget7 - position ) * morphTargetInfluences[ 7 ];\n\t#endif\n#endif";
  8414. 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#endif\n#endif";
  8415. var normal_fragment_maps = "#ifdef USE_NORMALMAP\n\t#ifdef OBJECTSPACE_NORMALMAP\n\t\tnormal = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;\n\t\t#ifdef FLIP_SIDED\n\t\t\tnormal = - normal;\n\t\t#endif\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tnormal = normal * ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n\t\t#endif\n\t\tnormal = normalize( normalMatrix * normal );\n\t#else\n\t\t#ifdef USE_TANGENT\n\t\t\tmat3 vTBN = mat3( tangent, bitangent, normal );\n\t\t\tvec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;\n\t\t\tmapN.xy = normalScale * mapN.xy;\n\t\t\tnormal = normalize( vTBN * mapN );\n\t\t#else\n\t\t\tnormal = perturbNormal2Arb( -vViewPosition, normal );\n\t\t#endif\n\t#endif\n#elif defined( USE_BUMPMAP )\n\tnormal = perturbNormalArb( -vViewPosition, normal, dHdxy_fwd() );\n#endif";
  8416. var normalmap_pars_fragment = "#ifdef USE_NORMALMAP\n\tuniform sampler2D normalMap;\n\tuniform vec2 normalScale;\n\t#ifdef OBJECTSPACE_NORMALMAP\n\t\tuniform mat3 normalMatrix;\n\t#else\n\t\tvec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm ) {\n\t\t\tvec3 q0 = vec3( dFdx( eye_pos.x ), dFdx( eye_pos.y ), dFdx( eye_pos.z ) );\n\t\t\tvec3 q1 = vec3( dFdy( eye_pos.x ), dFdy( eye_pos.y ), dFdy( eye_pos.z ) );\n\t\t\tvec2 st0 = dFdx( vUv.st );\n\t\t\tvec2 st1 = dFdy( vUv.st );\n\t\t\tfloat scale = sign( st1.t * st0.s - st0.t * st1.s );\n\t\t\tvec3 S = normalize( ( q0 * st1.t - q1 * st0.t ) * scale );\n\t\t\tvec3 T = normalize( ( - q0 * st1.s + q1 * st0.s ) * scale );\n\t\t\tvec3 N = normalize( surf_norm );\n\t\t\tmat3 tsn = mat3( S, T, N );\n\t\t\tvec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;\n\t\t\tmapN.xy *= normalScale;\n\t\t\tmapN.xy *= ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n\t\t\treturn normalize( tsn * mapN );\n\t\t}\n\t#endif\n#endif";
  8417. 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}\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}";
  8418. var premultiplied_alpha_fragment = "#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif";
  8419. var project_vertex = "vec4 mvPosition = modelViewMatrix * vec4( transformed, 1.0 );\ngl_Position = projectionMatrix * mvPosition;";
  8420. var dithering_fragment = "#if defined( DITHERING )\n\tgl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif";
  8421. var dithering_pars_fragment = "#if defined( 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";
  8422. var roughnessmap_fragment = "float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vUv );\n\troughnessFactor *= texelRoughness.g;\n#endif";
  8423. var roughnessmap_pars_fragment = "#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif";
  8424. var shadowmap_pars_fragment = "#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHTS > 0\n\t\tuniform sampler2D directionalShadowMap[ NUM_DIR_LIGHTS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHTS ];\n\t#endif\n\t#if NUM_SPOT_LIGHTS > 0\n\t\tuniform sampler2D spotShadowMap[ NUM_SPOT_LIGHTS ];\n\t\tvarying vec4 vSpotShadowCoord[ NUM_SPOT_LIGHTS ];\n\t#endif\n\t#if NUM_POINT_LIGHTS > 0\n\t\tuniform sampler2D pointShadowMap[ NUM_POINT_LIGHTS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHTS ];\n\t#endif\n\tfloat texture2DCompare( sampler2D depths, vec2 uv, float compare ) {\n\t\treturn step( compare, unpackRGBAToDepth( texture2D( depths, uv ) ) );\n\t}\n\tfloat texture2DShadowLerp( sampler2D depths, vec2 size, vec2 uv, float compare ) {\n\t\tconst vec2 offset = vec2( 0.0, 1.0 );\n\t\tvec2 texelSize = vec2( 1.0 ) / size;\n\t\tvec2 centroidUV = floor( uv * size + 0.5 ) / size;\n\t\tfloat lb = texture2DCompare( depths, centroidUV + texelSize * offset.xx, compare );\n\t\tfloat lt = texture2DCompare( depths, centroidUV + texelSize * offset.xy, compare );\n\t\tfloat rb = texture2DCompare( depths, centroidUV + texelSize * offset.yx, compare );\n\t\tfloat rt = texture2DCompare( depths, centroidUV + texelSize * offset.yy, compare );\n\t\tvec2 f = fract( uv * size + 0.5 );\n\t\tfloat a = mix( lb, lt, f.y );\n\t\tfloat b = mix( rb, rt, f.y );\n\t\tfloat c = mix( a, b, f.x );\n\t\treturn c;\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\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( dx0, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy, 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( 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 / 9.0 );\n\t\t#elif defined( SHADOWMAP_TYPE_PCF_SOFT )\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\tshadow = (\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy, shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )\n\t\t\t) * ( 1.0 / 9.0 );\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 )\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";
  8425. var shadowmap_pars_vertex = "#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHTS > 0\n\t\tuniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHTS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHTS ];\n\t#endif\n\t#if NUM_SPOT_LIGHTS > 0\n\t\tuniform mat4 spotShadowMatrix[ NUM_SPOT_LIGHTS ];\n\t\tvarying vec4 vSpotShadowCoord[ NUM_SPOT_LIGHTS ];\n\t#endif\n\t#if NUM_POINT_LIGHTS > 0\n\t\tuniform mat4 pointShadowMatrix[ NUM_POINT_LIGHTS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHTS ];\n\t#endif\n#endif";
  8426. var shadowmap_vertex = "#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHTS > 0\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tvDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * worldPosition;\n\t}\n\t#endif\n\t#if NUM_SPOT_LIGHTS > 0\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tvSpotShadowCoord[ i ] = spotShadowMatrix[ i ] * worldPosition;\n\t}\n\t#endif\n\t#if NUM_POINT_LIGHTS > 0\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tvPointShadowCoord[ i ] = pointShadowMatrix[ i ] * worldPosition;\n\t}\n\t#endif\n#endif";
  8427. var shadowmask_pars_fragment = "float getShadowMask() {\n\tfloat shadow = 1.0;\n\t#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHTS > 0\n\tDirectionalLight directionalLight;\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tdirectionalLight = directionalLights[ i ];\n\t\tshadow *= bool( directionalLight.shadow ) ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t}\n\t#endif\n\t#if NUM_SPOT_LIGHTS > 0\n\tSpotLight spotLight;\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tspotLight = spotLights[ i ];\n\t\tshadow *= bool( spotLight.shadow ) ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowBias, spotLight.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\n\t}\n\t#endif\n\t#if NUM_POINT_LIGHTS > 0\n\tPointLight pointLight;\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tpointLight = pointLights[ i ];\n\t\tshadow *= bool( pointLight.shadow ) ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0;\n\t}\n\t#endif\n\t#endif\n\treturn shadow;\n}";
  8428. 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";
  8429. var skinning_pars_vertex = "#ifdef USE_SKINNING\n\tuniform mat4 bindMatrix;\n\tuniform mat4 bindMatrixInverse;\n\t#ifdef BONE_TEXTURE\n\t\tuniform 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";
  8430. 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";
  8431. 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";
  8432. 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";
  8433. var specularmap_pars_fragment = "#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif";
  8434. var tonemapping_fragment = "#if defined( TONE_MAPPING )\n\tgl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif";
  8435. var tonemapping_pars_fragment = "#ifndef saturate\n\t#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}";
  8436. var uv_pars_fragment = "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP ) || defined( USE_ALPHAMAP ) || defined( USE_EMISSIVEMAP ) || defined( USE_ROUGHNESSMAP ) || defined( USE_METALNESSMAP )\n\tvarying vec2 vUv;\n#endif";
  8437. var uv_pars_vertex = "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP ) || defined( USE_ALPHAMAP ) || defined( USE_EMISSIVEMAP ) || defined( USE_ROUGHNESSMAP ) || defined( USE_METALNESSMAP )\n\tvarying vec2 vUv;\n\tuniform mat3 uvTransform;\n#endif";
  8438. var uv_vertex = "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP ) || defined( USE_ALPHAMAP ) || defined( USE_EMISSIVEMAP ) || defined( USE_ROUGHNESSMAP ) || defined( USE_METALNESSMAP )\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n#endif";
  8439. var uv2_pars_fragment = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvarying vec2 vUv2;\n#endif";
  8440. var uv2_pars_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tattribute vec2 uv2;\n\tvarying vec2 vUv2;\n#endif";
  8441. var uv2_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvUv2 = uv2;\n#endif";
  8442. var worldpos_vertex = "#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP )\n\tvec4 worldPosition = modelMatrix * vec4( transformed, 1.0 );\n#endif";
  8443. 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}";
  8444. 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}";
  8445. var cube_frag = "uniform samplerCube tCube;\nuniform float tFlip;\nuniform float opacity;\nvarying vec3 vWorldDirection;\nvoid main() {\n\tvec4 texColor = textureCube( tCube, vec3( tFlip * vWorldDirection.x, vWorldDirection.yz ) );\n\tgl_FragColor = mapTexelToLinear( texColor );\n\tgl_FragColor.a *= opacity;\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n}";
  8446. 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}";
  8447. 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>\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\t#if DEPTH_PACKING == 3200\n\t\tgl_FragColor = vec4( vec3( 1.0 - gl_FragCoord.z ), opacity );\n\t#elif DEPTH_PACKING == 3201\n\t\tgl_FragColor = packDepthToRGBA( gl_FragCoord.z );\n\t#endif\n}";
  8448. 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>\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}";
  8449. 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}";
  8450. 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}";
  8451. 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}";
  8452. 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}";
  8453. 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 <premultiplied_alpha_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}";
  8454. 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\t#include <color_vertex>\n\tvLineDistance = scale * lineDistance;\n\tvec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );\n\tgl_Position = projectionMatrix * mvPosition;\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <fog_vertex>\n}";
  8455. 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_pars_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\treflectedLight.indirectDiffuse += texture2D( lightMap, vUv2 ).xyz * 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 <premultiplied_alpha_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}";
  8456. 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}";
  8457. 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_pars_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}";
  8458. 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}";
  8459. 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 <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 <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 <premultiplied_alpha_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}";
  8460. 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 <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 <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}";
  8461. 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_pars_fragment>\n#include <gradientmap_pars_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}";
  8462. 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}";
  8463. var meshphysical_frag = "#define PHYSICAL\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float roughness;\nuniform float metalness;\nuniform float opacity;\n#ifndef STANDARD\n\tuniform float clearCoat;\n\tuniform float clearCoatRoughness;\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_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 <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 <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\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}";
  8464. var meshphysical_vert = "#define PHYSICAL\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}";
  8465. var normal_frag = "#define NORMAL\nuniform float opacity;\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || ( defined( USE_NORMALMAP ) && ! defined( OBJECTSPACE_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>\nvoid main() {\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}";
  8466. var normal_vert = "#define NORMAL\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || ( defined( USE_NORMALMAP ) && ! defined( OBJECTSPACE_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 <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_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#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || ( defined( USE_NORMALMAP ) && ! defined( OBJECTSPACE_NORMALMAP ) )\n\tvViewPosition = - mvPosition.xyz;\n#endif\n}";
  8467. 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 <premultiplied_alpha_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}";
  8468. 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 = ( projectionMatrix[ 2 ][ 3 ] == - 1.0 );\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}";
  8469. 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 <fog_fragment>\n}";
  8470. 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}";
  8471. var sprite_frag = "uniform vec3 diffuse;\nuniform float opacity;\n#include <common>\n#include <uv_pars_fragment>\n#include <map_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 <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}";
  8472. 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 = ( projectionMatrix[ 2 ][ 3 ] == - 1.0 );\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}";
  8473. var ShaderChunk = {
  8474. alphamap_fragment: alphamap_fragment,
  8475. alphamap_pars_fragment: alphamap_pars_fragment,
  8476. alphatest_fragment: alphatest_fragment,
  8477. aomap_fragment: aomap_fragment,
  8478. aomap_pars_fragment: aomap_pars_fragment,
  8479. begin_vertex: begin_vertex,
  8480. beginnormal_vertex: beginnormal_vertex,
  8481. bsdfs: bsdfs,
  8482. bumpmap_pars_fragment: bumpmap_pars_fragment,
  8483. clipping_planes_fragment: clipping_planes_fragment,
  8484. clipping_planes_pars_fragment: clipping_planes_pars_fragment,
  8485. clipping_planes_pars_vertex: clipping_planes_pars_vertex,
  8486. clipping_planes_vertex: clipping_planes_vertex,
  8487. color_fragment: color_fragment,
  8488. color_pars_fragment: color_pars_fragment,
  8489. color_pars_vertex: color_pars_vertex,
  8490. color_vertex: color_vertex,
  8491. common: common,
  8492. cube_uv_reflection_fragment: cube_uv_reflection_fragment,
  8493. defaultnormal_vertex: defaultnormal_vertex,
  8494. displacementmap_pars_vertex: displacementmap_pars_vertex,
  8495. displacementmap_vertex: displacementmap_vertex,
  8496. emissivemap_fragment: emissivemap_fragment,
  8497. emissivemap_pars_fragment: emissivemap_pars_fragment,
  8498. encodings_fragment: encodings_fragment,
  8499. encodings_pars_fragment: encodings_pars_fragment,
  8500. envmap_fragment: envmap_fragment,
  8501. envmap_pars_fragment: envmap_pars_fragment,
  8502. envmap_pars_vertex: envmap_pars_vertex,
  8503. envmap_physical_pars_fragment: envmap_physical_pars_fragment,
  8504. envmap_vertex: envmap_vertex,
  8505. fog_vertex: fog_vertex,
  8506. fog_pars_vertex: fog_pars_vertex,
  8507. fog_fragment: fog_fragment,
  8508. fog_pars_fragment: fog_pars_fragment,
  8509. gradientmap_pars_fragment: gradientmap_pars_fragment,
  8510. lightmap_fragment: lightmap_fragment,
  8511. lightmap_pars_fragment: lightmap_pars_fragment,
  8512. lights_lambert_vertex: lights_lambert_vertex,
  8513. lights_pars_begin: lights_pars_begin,
  8514. lights_phong_fragment: lights_phong_fragment,
  8515. lights_phong_pars_fragment: lights_phong_pars_fragment,
  8516. lights_physical_fragment: lights_physical_fragment,
  8517. lights_physical_pars_fragment: lights_physical_pars_fragment,
  8518. lights_fragment_begin: lights_fragment_begin,
  8519. lights_fragment_maps: lights_fragment_maps,
  8520. lights_fragment_end: lights_fragment_end,
  8521. logdepthbuf_fragment: logdepthbuf_fragment,
  8522. logdepthbuf_pars_fragment: logdepthbuf_pars_fragment,
  8523. logdepthbuf_pars_vertex: logdepthbuf_pars_vertex,
  8524. logdepthbuf_vertex: logdepthbuf_vertex,
  8525. map_fragment: map_fragment,
  8526. map_pars_fragment: map_pars_fragment,
  8527. map_particle_fragment: map_particle_fragment,
  8528. map_particle_pars_fragment: map_particle_pars_fragment,
  8529. metalnessmap_fragment: metalnessmap_fragment,
  8530. metalnessmap_pars_fragment: metalnessmap_pars_fragment,
  8531. morphnormal_vertex: morphnormal_vertex,
  8532. morphtarget_pars_vertex: morphtarget_pars_vertex,
  8533. morphtarget_vertex: morphtarget_vertex,
  8534. normal_fragment_begin: normal_fragment_begin,
  8535. normal_fragment_maps: normal_fragment_maps,
  8536. normalmap_pars_fragment: normalmap_pars_fragment,
  8537. packing: packing,
  8538. premultiplied_alpha_fragment: premultiplied_alpha_fragment,
  8539. project_vertex: project_vertex,
  8540. dithering_fragment: dithering_fragment,
  8541. dithering_pars_fragment: dithering_pars_fragment,
  8542. roughnessmap_fragment: roughnessmap_fragment,
  8543. roughnessmap_pars_fragment: roughnessmap_pars_fragment,
  8544. shadowmap_pars_fragment: shadowmap_pars_fragment,
  8545. shadowmap_pars_vertex: shadowmap_pars_vertex,
  8546. shadowmap_vertex: shadowmap_vertex,
  8547. shadowmask_pars_fragment: shadowmask_pars_fragment,
  8548. skinbase_vertex: skinbase_vertex,
  8549. skinning_pars_vertex: skinning_pars_vertex,
  8550. skinning_vertex: skinning_vertex,
  8551. skinnormal_vertex: skinnormal_vertex,
  8552. specularmap_fragment: specularmap_fragment,
  8553. specularmap_pars_fragment: specularmap_pars_fragment,
  8554. tonemapping_fragment: tonemapping_fragment,
  8555. tonemapping_pars_fragment: tonemapping_pars_fragment,
  8556. uv_pars_fragment: uv_pars_fragment,
  8557. uv_pars_vertex: uv_pars_vertex,
  8558. uv_vertex: uv_vertex,
  8559. uv2_pars_fragment: uv2_pars_fragment,
  8560. uv2_pars_vertex: uv2_pars_vertex,
  8561. uv2_vertex: uv2_vertex,
  8562. worldpos_vertex: worldpos_vertex,
  8563. background_frag: background_frag,
  8564. background_vert: background_vert,
  8565. cube_frag: cube_frag,
  8566. cube_vert: cube_vert,
  8567. depth_frag: depth_frag,
  8568. depth_vert: depth_vert,
  8569. distanceRGBA_frag: distanceRGBA_frag,
  8570. distanceRGBA_vert: distanceRGBA_vert,
  8571. equirect_frag: equirect_frag,
  8572. equirect_vert: equirect_vert,
  8573. linedashed_frag: linedashed_frag,
  8574. linedashed_vert: linedashed_vert,
  8575. meshbasic_frag: meshbasic_frag,
  8576. meshbasic_vert: meshbasic_vert,
  8577. meshlambert_frag: meshlambert_frag,
  8578. meshlambert_vert: meshlambert_vert,
  8579. meshmatcap_frag: meshmatcap_frag,
  8580. meshmatcap_vert: meshmatcap_vert,
  8581. meshphong_frag: meshphong_frag,
  8582. meshphong_vert: meshphong_vert,
  8583. meshphysical_frag: meshphysical_frag,
  8584. meshphysical_vert: meshphysical_vert,
  8585. normal_frag: normal_frag,
  8586. normal_vert: normal_vert,
  8587. points_frag: points_frag,
  8588. points_vert: points_vert,
  8589. shadow_frag: shadow_frag,
  8590. shadow_vert: shadow_vert,
  8591. sprite_frag: sprite_frag,
  8592. sprite_vert: sprite_vert
  8593. };
  8594. /**
  8595. * Uniform Utilities
  8596. */
  8597. function cloneUniforms( src ) {
  8598. var dst = {};
  8599. for ( var u in src ) {
  8600. dst[ u ] = {};
  8601. for ( var p in src[ u ] ) {
  8602. var property = src[ u ][ p ];
  8603. if ( property && ( property.isColor ||
  8604. property.isMatrix3 || property.isMatrix4 ||
  8605. property.isVector2 || property.isVector3 || property.isVector4 ||
  8606. property.isTexture ) ) {
  8607. dst[ u ][ p ] = property.clone();
  8608. } else if ( Array.isArray( property ) ) {
  8609. dst[ u ][ p ] = property.slice();
  8610. } else {
  8611. dst[ u ][ p ] = property;
  8612. }
  8613. }
  8614. }
  8615. return dst;
  8616. }
  8617. function mergeUniforms( uniforms ) {
  8618. var merged = {};
  8619. for ( var u = 0; u < uniforms.length; u ++ ) {
  8620. var tmp = cloneUniforms( uniforms[ u ] );
  8621. for ( var p in tmp ) {
  8622. merged[ p ] = tmp[ p ];
  8623. }
  8624. }
  8625. return merged;
  8626. }
  8627. // Legacy
  8628. var UniformsUtils = { clone: cloneUniforms, merge: mergeUniforms };
  8629. /**
  8630. * @author mrdoob / http://mrdoob.com/
  8631. */
  8632. var ColorKeywords = { 'aliceblue': 0xF0F8FF, 'antiquewhite': 0xFAEBD7, 'aqua': 0x00FFFF, 'aquamarine': 0x7FFFD4, 'azure': 0xF0FFFF,
  8633. 'beige': 0xF5F5DC, 'bisque': 0xFFE4C4, 'black': 0x000000, 'blanchedalmond': 0xFFEBCD, 'blue': 0x0000FF, 'blueviolet': 0x8A2BE2,
  8634. 'brown': 0xA52A2A, 'burlywood': 0xDEB887, 'cadetblue': 0x5F9EA0, 'chartreuse': 0x7FFF00, 'chocolate': 0xD2691E, 'coral': 0xFF7F50,
  8635. 'cornflowerblue': 0x6495ED, 'cornsilk': 0xFFF8DC, 'crimson': 0xDC143C, 'cyan': 0x00FFFF, 'darkblue': 0x00008B, 'darkcyan': 0x008B8B,
  8636. 'darkgoldenrod': 0xB8860B, 'darkgray': 0xA9A9A9, 'darkgreen': 0x006400, 'darkgrey': 0xA9A9A9, 'darkkhaki': 0xBDB76B, 'darkmagenta': 0x8B008B,
  8637. 'darkolivegreen': 0x556B2F, 'darkorange': 0xFF8C00, 'darkorchid': 0x9932CC, 'darkred': 0x8B0000, 'darksalmon': 0xE9967A, 'darkseagreen': 0x8FBC8F,
  8638. 'darkslateblue': 0x483D8B, 'darkslategray': 0x2F4F4F, 'darkslategrey': 0x2F4F4F, 'darkturquoise': 0x00CED1, 'darkviolet': 0x9400D3,
  8639. 'deeppink': 0xFF1493, 'deepskyblue': 0x00BFFF, 'dimgray': 0x696969, 'dimgrey': 0x696969, 'dodgerblue': 0x1E90FF, 'firebrick': 0xB22222,
  8640. 'floralwhite': 0xFFFAF0, 'forestgreen': 0x228B22, 'fuchsia': 0xFF00FF, 'gainsboro': 0xDCDCDC, 'ghostwhite': 0xF8F8FF, 'gold': 0xFFD700,
  8641. 'goldenrod': 0xDAA520, 'gray': 0x808080, 'green': 0x008000, 'greenyellow': 0xADFF2F, 'grey': 0x808080, 'honeydew': 0xF0FFF0, 'hotpink': 0xFF69B4,
  8642. 'indianred': 0xCD5C5C, 'indigo': 0x4B0082, 'ivory': 0xFFFFF0, 'khaki': 0xF0E68C, 'lavender': 0xE6E6FA, 'lavenderblush': 0xFFF0F5, 'lawngreen': 0x7CFC00,
  8643. 'lemonchiffon': 0xFFFACD, 'lightblue': 0xADD8E6, 'lightcoral': 0xF08080, 'lightcyan': 0xE0FFFF, 'lightgoldenrodyellow': 0xFAFAD2, 'lightgray': 0xD3D3D3,
  8644. 'lightgreen': 0x90EE90, 'lightgrey': 0xD3D3D3, 'lightpink': 0xFFB6C1, 'lightsalmon': 0xFFA07A, 'lightseagreen': 0x20B2AA, 'lightskyblue': 0x87CEFA,
  8645. 'lightslategray': 0x778899, 'lightslategrey': 0x778899, 'lightsteelblue': 0xB0C4DE, 'lightyellow': 0xFFFFE0, 'lime': 0x00FF00, 'limegreen': 0x32CD32,
  8646. 'linen': 0xFAF0E6, 'magenta': 0xFF00FF, 'maroon': 0x800000, 'mediumaquamarine': 0x66CDAA, 'mediumblue': 0x0000CD, 'mediumorchid': 0xBA55D3,
  8647. 'mediumpurple': 0x9370DB, 'mediumseagreen': 0x3CB371, 'mediumslateblue': 0x7B68EE, 'mediumspringgreen': 0x00FA9A, 'mediumturquoise': 0x48D1CC,
  8648. 'mediumvioletred': 0xC71585, 'midnightblue': 0x191970, 'mintcream': 0xF5FFFA, 'mistyrose': 0xFFE4E1, 'moccasin': 0xFFE4B5, 'navajowhite': 0xFFDEAD,
  8649. 'navy': 0x000080, 'oldlace': 0xFDF5E6, 'olive': 0x808000, 'olivedrab': 0x6B8E23, 'orange': 0xFFA500, 'orangered': 0xFF4500, 'orchid': 0xDA70D6,
  8650. 'palegoldenrod': 0xEEE8AA, 'palegreen': 0x98FB98, 'paleturquoise': 0xAFEEEE, 'palevioletred': 0xDB7093, 'papayawhip': 0xFFEFD5, 'peachpuff': 0xFFDAB9,
  8651. 'peru': 0xCD853F, 'pink': 0xFFC0CB, 'plum': 0xDDA0DD, 'powderblue': 0xB0E0E6, 'purple': 0x800080, 'rebeccapurple': 0x663399, 'red': 0xFF0000, 'rosybrown': 0xBC8F8F,
  8652. 'royalblue': 0x4169E1, 'saddlebrown': 0x8B4513, 'salmon': 0xFA8072, 'sandybrown': 0xF4A460, 'seagreen': 0x2E8B57, 'seashell': 0xFFF5EE,
  8653. 'sienna': 0xA0522D, 'silver': 0xC0C0C0, 'skyblue': 0x87CEEB, 'slateblue': 0x6A5ACD, 'slategray': 0x708090, 'slategrey': 0x708090, 'snow': 0xFFFAFA,
  8654. 'springgreen': 0x00FF7F, 'steelblue': 0x4682B4, 'tan': 0xD2B48C, 'teal': 0x008080, 'thistle': 0xD8BFD8, 'tomato': 0xFF6347, 'turquoise': 0x40E0D0,
  8655. 'violet': 0xEE82EE, 'wheat': 0xF5DEB3, 'white': 0xFFFFFF, 'whitesmoke': 0xF5F5F5, 'yellow': 0xFFFF00, 'yellowgreen': 0x9ACD32 };
  8656. function Color( r, g, b ) {
  8657. if ( g === undefined && b === undefined ) {
  8658. // r is THREE.Color, hex or string
  8659. return this.set( r );
  8660. }
  8661. return this.setRGB( r, g, b );
  8662. }
  8663. Object.assign( Color.prototype, {
  8664. isColor: true,
  8665. r: 1, g: 1, b: 1,
  8666. set: function ( value ) {
  8667. if ( value && value.isColor ) {
  8668. this.copy( value );
  8669. } else if ( typeof value === 'number' ) {
  8670. this.setHex( value );
  8671. } else if ( typeof value === 'string' ) {
  8672. this.setStyle( value );
  8673. }
  8674. return this;
  8675. },
  8676. setScalar: function ( scalar ) {
  8677. this.r = scalar;
  8678. this.g = scalar;
  8679. this.b = scalar;
  8680. return this;
  8681. },
  8682. setHex: function ( hex ) {
  8683. hex = Math.floor( hex );
  8684. this.r = ( hex >> 16 & 255 ) / 255;
  8685. this.g = ( hex >> 8 & 255 ) / 255;
  8686. this.b = ( hex & 255 ) / 255;
  8687. return this;
  8688. },
  8689. setRGB: function ( r, g, b ) {
  8690. this.r = r;
  8691. this.g = g;
  8692. this.b = b;
  8693. return this;
  8694. },
  8695. setHSL: function () {
  8696. function hue2rgb( p, q, t ) {
  8697. if ( t < 0 ) t += 1;
  8698. if ( t > 1 ) t -= 1;
  8699. if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t;
  8700. if ( t < 1 / 2 ) return q;
  8701. if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t );
  8702. return p;
  8703. }
  8704. return function setHSL( h, s, l ) {
  8705. // h,s,l ranges are in 0.0 - 1.0
  8706. h = _Math.euclideanModulo( h, 1 );
  8707. s = _Math.clamp( s, 0, 1 );
  8708. l = _Math.clamp( l, 0, 1 );
  8709. if ( s === 0 ) {
  8710. this.r = this.g = this.b = l;
  8711. } else {
  8712. var p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s );
  8713. var q = ( 2 * l ) - p;
  8714. this.r = hue2rgb( q, p, h + 1 / 3 );
  8715. this.g = hue2rgb( q, p, h );
  8716. this.b = hue2rgb( q, p, h - 1 / 3 );
  8717. }
  8718. return this;
  8719. };
  8720. }(),
  8721. setStyle: function ( style ) {
  8722. function handleAlpha( string ) {
  8723. if ( string === undefined ) return;
  8724. if ( parseFloat( string ) < 1 ) {
  8725. console.warn( 'THREE.Color: Alpha component of ' + style + ' will be ignored.' );
  8726. }
  8727. }
  8728. var m;
  8729. if ( m = /^((?:rgb|hsl)a?)\(\s*([^\)]*)\)/.exec( style ) ) {
  8730. // rgb / hsl
  8731. var color;
  8732. var name = m[ 1 ];
  8733. var components = m[ 2 ];
  8734. switch ( name ) {
  8735. case 'rgb':
  8736. case 'rgba':
  8737. if ( color = /^(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec( components ) ) {
  8738. // rgb(255,0,0) rgba(255,0,0,0.5)
  8739. this.r = Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255;
  8740. this.g = Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255;
  8741. this.b = Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255;
  8742. handleAlpha( color[ 5 ] );
  8743. return this;
  8744. }
  8745. if ( color = /^(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec( components ) ) {
  8746. // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
  8747. this.r = Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100;
  8748. this.g = Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100;
  8749. this.b = Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100;
  8750. handleAlpha( color[ 5 ] );
  8751. return this;
  8752. }
  8753. break;
  8754. case 'hsl':
  8755. case 'hsla':
  8756. if ( color = /^([0-9]*\.?[0-9]+)\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec( components ) ) {
  8757. // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
  8758. var h = parseFloat( color[ 1 ] ) / 360;
  8759. var s = parseInt( color[ 2 ], 10 ) / 100;
  8760. var l = parseInt( color[ 3 ], 10 ) / 100;
  8761. handleAlpha( color[ 5 ] );
  8762. return this.setHSL( h, s, l );
  8763. }
  8764. break;
  8765. }
  8766. } else if ( m = /^\#([A-Fa-f0-9]+)$/.exec( style ) ) {
  8767. // hex color
  8768. var hex = m[ 1 ];
  8769. var size = hex.length;
  8770. if ( size === 3 ) {
  8771. // #ff0
  8772. this.r = parseInt( hex.charAt( 0 ) + hex.charAt( 0 ), 16 ) / 255;
  8773. this.g = parseInt( hex.charAt( 1 ) + hex.charAt( 1 ), 16 ) / 255;
  8774. this.b = parseInt( hex.charAt( 2 ) + hex.charAt( 2 ), 16 ) / 255;
  8775. return this;
  8776. } else if ( size === 6 ) {
  8777. // #ff0000
  8778. this.r = parseInt( hex.charAt( 0 ) + hex.charAt( 1 ), 16 ) / 255;
  8779. this.g = parseInt( hex.charAt( 2 ) + hex.charAt( 3 ), 16 ) / 255;
  8780. this.b = parseInt( hex.charAt( 4 ) + hex.charAt( 5 ), 16 ) / 255;
  8781. return this;
  8782. }
  8783. }
  8784. if ( style && style.length > 0 ) {
  8785. // color keywords
  8786. var hex = ColorKeywords[ style ];
  8787. if ( hex !== undefined ) {
  8788. // red
  8789. this.setHex( hex );
  8790. } else {
  8791. // unknown color
  8792. console.warn( 'THREE.Color: Unknown color ' + style );
  8793. }
  8794. }
  8795. return this;
  8796. },
  8797. clone: function () {
  8798. return new this.constructor( this.r, this.g, this.b );
  8799. },
  8800. copy: function ( color ) {
  8801. this.r = color.r;
  8802. this.g = color.g;
  8803. this.b = color.b;
  8804. return this;
  8805. },
  8806. copyGammaToLinear: function ( color, gammaFactor ) {
  8807. if ( gammaFactor === undefined ) gammaFactor = 2.0;
  8808. this.r = Math.pow( color.r, gammaFactor );
  8809. this.g = Math.pow( color.g, gammaFactor );
  8810. this.b = Math.pow( color.b, gammaFactor );
  8811. return this;
  8812. },
  8813. copyLinearToGamma: function ( color, gammaFactor ) {
  8814. if ( gammaFactor === undefined ) gammaFactor = 2.0;
  8815. var safeInverse = ( gammaFactor > 0 ) ? ( 1.0 / gammaFactor ) : 1.0;
  8816. this.r = Math.pow( color.r, safeInverse );
  8817. this.g = Math.pow( color.g, safeInverse );
  8818. this.b = Math.pow( color.b, safeInverse );
  8819. return this;
  8820. },
  8821. convertGammaToLinear: function ( gammaFactor ) {
  8822. this.copyGammaToLinear( this, gammaFactor );
  8823. return this;
  8824. },
  8825. convertLinearToGamma: function ( gammaFactor ) {
  8826. this.copyLinearToGamma( this, gammaFactor );
  8827. return this;
  8828. },
  8829. copySRGBToLinear: function () {
  8830. function SRGBToLinear( c ) {
  8831. return ( c < 0.04045 ) ? c * 0.0773993808 : Math.pow( c * 0.9478672986 + 0.0521327014, 2.4 );
  8832. }
  8833. return function copySRGBToLinear( color ) {
  8834. this.r = SRGBToLinear( color.r );
  8835. this.g = SRGBToLinear( color.g );
  8836. this.b = SRGBToLinear( color.b );
  8837. return this;
  8838. };
  8839. }(),
  8840. copyLinearToSRGB: function () {
  8841. function LinearToSRGB( c ) {
  8842. return ( c < 0.0031308 ) ? c * 12.92 : 1.055 * ( Math.pow( c, 0.41666 ) ) - 0.055;
  8843. }
  8844. return function copyLinearToSRGB( color ) {
  8845. this.r = LinearToSRGB( color.r );
  8846. this.g = LinearToSRGB( color.g );
  8847. this.b = LinearToSRGB( color.b );
  8848. return this;
  8849. };
  8850. }(),
  8851. convertSRGBToLinear: function () {
  8852. this.copySRGBToLinear( this );
  8853. return this;
  8854. },
  8855. convertLinearToSRGB: function () {
  8856. this.copyLinearToSRGB( this );
  8857. return this;
  8858. },
  8859. getHex: function () {
  8860. return ( this.r * 255 ) << 16 ^ ( this.g * 255 ) << 8 ^ ( this.b * 255 ) << 0;
  8861. },
  8862. getHexString: function () {
  8863. return ( '000000' + this.getHex().toString( 16 ) ).slice( - 6 );
  8864. },
  8865. getHSL: function ( target ) {
  8866. // h,s,l ranges are in 0.0 - 1.0
  8867. if ( target === undefined ) {
  8868. console.warn( 'THREE.Color: .getHSL() target is now required' );
  8869. target = { h: 0, s: 0, l: 0 };
  8870. }
  8871. var r = this.r, g = this.g, b = this.b;
  8872. var max = Math.max( r, g, b );
  8873. var min = Math.min( r, g, b );
  8874. var hue, saturation;
  8875. var lightness = ( min + max ) / 2.0;
  8876. if ( min === max ) {
  8877. hue = 0;
  8878. saturation = 0;
  8879. } else {
  8880. var delta = max - min;
  8881. saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min );
  8882. switch ( max ) {
  8883. case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break;
  8884. case g: hue = ( b - r ) / delta + 2; break;
  8885. case b: hue = ( r - g ) / delta + 4; break;
  8886. }
  8887. hue /= 6;
  8888. }
  8889. target.h = hue;
  8890. target.s = saturation;
  8891. target.l = lightness;
  8892. return target;
  8893. },
  8894. getStyle: function () {
  8895. return 'rgb(' + ( ( this.r * 255 ) | 0 ) + ',' + ( ( this.g * 255 ) | 0 ) + ',' + ( ( this.b * 255 ) | 0 ) + ')';
  8896. },
  8897. offsetHSL: function () {
  8898. var hsl = {};
  8899. return function ( h, s, l ) {
  8900. this.getHSL( hsl );
  8901. hsl.h += h; hsl.s += s; hsl.l += l;
  8902. this.setHSL( hsl.h, hsl.s, hsl.l );
  8903. return this;
  8904. };
  8905. }(),
  8906. add: function ( color ) {
  8907. this.r += color.r;
  8908. this.g += color.g;
  8909. this.b += color.b;
  8910. return this;
  8911. },
  8912. addColors: function ( color1, color2 ) {
  8913. this.r = color1.r + color2.r;
  8914. this.g = color1.g + color2.g;
  8915. this.b = color1.b + color2.b;
  8916. return this;
  8917. },
  8918. addScalar: function ( s ) {
  8919. this.r += s;
  8920. this.g += s;
  8921. this.b += s;
  8922. return this;
  8923. },
  8924. sub: function ( color ) {
  8925. this.r = Math.max( 0, this.r - color.r );
  8926. this.g = Math.max( 0, this.g - color.g );
  8927. this.b = Math.max( 0, this.b - color.b );
  8928. return this;
  8929. },
  8930. multiply: function ( color ) {
  8931. this.r *= color.r;
  8932. this.g *= color.g;
  8933. this.b *= color.b;
  8934. return this;
  8935. },
  8936. multiplyScalar: function ( s ) {
  8937. this.r *= s;
  8938. this.g *= s;
  8939. this.b *= s;
  8940. return this;
  8941. },
  8942. lerp: function ( color, alpha ) {
  8943. this.r += ( color.r - this.r ) * alpha;
  8944. this.g += ( color.g - this.g ) * alpha;
  8945. this.b += ( color.b - this.b ) * alpha;
  8946. return this;
  8947. },
  8948. lerpHSL: function () {
  8949. var hslA = { h: 0, s: 0, l: 0 };
  8950. var hslB = { h: 0, s: 0, l: 0 };
  8951. return function lerpHSL( color, alpha ) {
  8952. this.getHSL( hslA );
  8953. color.getHSL( hslB );
  8954. var h = _Math.lerp( hslA.h, hslB.h, alpha );
  8955. var s = _Math.lerp( hslA.s, hslB.s, alpha );
  8956. var l = _Math.lerp( hslA.l, hslB.l, alpha );
  8957. this.setHSL( h, s, l );
  8958. return this;
  8959. };
  8960. }(),
  8961. equals: function ( c ) {
  8962. return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b );
  8963. },
  8964. fromArray: function ( array, offset ) {
  8965. if ( offset === undefined ) offset = 0;
  8966. this.r = array[ offset ];
  8967. this.g = array[ offset + 1 ];
  8968. this.b = array[ offset + 2 ];
  8969. return this;
  8970. },
  8971. toArray: function ( array, offset ) {
  8972. if ( array === undefined ) array = [];
  8973. if ( offset === undefined ) offset = 0;
  8974. array[ offset ] = this.r;
  8975. array[ offset + 1 ] = this.g;
  8976. array[ offset + 2 ] = this.b;
  8977. return array;
  8978. },
  8979. toJSON: function () {
  8980. return this.getHex();
  8981. }
  8982. } );
  8983. /**
  8984. * Uniforms library for shared webgl shaders
  8985. */
  8986. var UniformsLib = {
  8987. common: {
  8988. diffuse: { value: new Color( 0xeeeeee ) },
  8989. opacity: { value: 1.0 },
  8990. map: { value: null },
  8991. uvTransform: { value: new Matrix3() },
  8992. alphaMap: { value: null },
  8993. },
  8994. specularmap: {
  8995. specularMap: { value: null },
  8996. },
  8997. envmap: {
  8998. envMap: { value: null },
  8999. flipEnvMap: { value: - 1 },
  9000. reflectivity: { value: 1.0 },
  9001. refractionRatio: { value: 0.98 },
  9002. maxMipLevel: { value: 0 }
  9003. },
  9004. aomap: {
  9005. aoMap: { value: null },
  9006. aoMapIntensity: { value: 1 }
  9007. },
  9008. lightmap: {
  9009. lightMap: { value: null },
  9010. lightMapIntensity: { value: 1 }
  9011. },
  9012. emissivemap: {
  9013. emissiveMap: { value: null }
  9014. },
  9015. bumpmap: {
  9016. bumpMap: { value: null },
  9017. bumpScale: { value: 1 }
  9018. },
  9019. normalmap: {
  9020. normalMap: { value: null },
  9021. normalScale: { value: new Vector2( 1, 1 ) }
  9022. },
  9023. displacementmap: {
  9024. displacementMap: { value: null },
  9025. displacementScale: { value: 1 },
  9026. displacementBias: { value: 0 }
  9027. },
  9028. roughnessmap: {
  9029. roughnessMap: { value: null }
  9030. },
  9031. metalnessmap: {
  9032. metalnessMap: { value: null }
  9033. },
  9034. gradientmap: {
  9035. gradientMap: { value: null }
  9036. },
  9037. fog: {
  9038. fogDensity: { value: 0.00025 },
  9039. fogNear: { value: 1 },
  9040. fogFar: { value: 2000 },
  9041. fogColor: { value: new Color( 0xffffff ) }
  9042. },
  9043. lights: {
  9044. ambientLightColor: { value: [] },
  9045. directionalLights: { value: [], properties: {
  9046. direction: {},
  9047. color: {},
  9048. shadow: {},
  9049. shadowBias: {},
  9050. shadowRadius: {},
  9051. shadowMapSize: {}
  9052. } },
  9053. directionalShadowMap: { value: [] },
  9054. directionalShadowMatrix: { value: [] },
  9055. spotLights: { value: [], properties: {
  9056. color: {},
  9057. position: {},
  9058. direction: {},
  9059. distance: {},
  9060. coneCos: {},
  9061. penumbraCos: {},
  9062. decay: {},
  9063. shadow: {},
  9064. shadowBias: {},
  9065. shadowRadius: {},
  9066. shadowMapSize: {}
  9067. } },
  9068. spotShadowMap: { value: [] },
  9069. spotShadowMatrix: { value: [] },
  9070. pointLights: { value: [], properties: {
  9071. color: {},
  9072. position: {},
  9073. decay: {},
  9074. distance: {},
  9075. shadow: {},
  9076. shadowBias: {},
  9077. shadowRadius: {},
  9078. shadowMapSize: {},
  9079. shadowCameraNear: {},
  9080. shadowCameraFar: {}
  9081. } },
  9082. pointShadowMap: { value: [] },
  9083. pointShadowMatrix: { value: [] },
  9084. hemisphereLights: { value: [], properties: {
  9085. direction: {},
  9086. skyColor: {},
  9087. groundColor: {}
  9088. } },
  9089. // TODO (abelnation): RectAreaLight BRDF data needs to be moved from example to main src
  9090. rectAreaLights: { value: [], properties: {
  9091. color: {},
  9092. position: {},
  9093. width: {},
  9094. height: {}
  9095. } }
  9096. },
  9097. points: {
  9098. diffuse: { value: new Color( 0xeeeeee ) },
  9099. opacity: { value: 1.0 },
  9100. size: { value: 1.0 },
  9101. scale: { value: 1.0 },
  9102. map: { value: null },
  9103. uvTransform: { value: new Matrix3() }
  9104. },
  9105. sprite: {
  9106. diffuse: { value: new Color( 0xeeeeee ) },
  9107. opacity: { value: 1.0 },
  9108. center: { value: new Vector2( 0.5, 0.5 ) },
  9109. rotation: { value: 0.0 },
  9110. map: { value: null },
  9111. uvTransform: { value: new Matrix3() }
  9112. }
  9113. };
  9114. /**
  9115. * @author alteredq / http://alteredqualia.com/
  9116. * @author mrdoob / http://mrdoob.com/
  9117. * @author mikael emtinger / http://gomo.se/
  9118. */
  9119. var ShaderLib = {
  9120. basic: {
  9121. uniforms: mergeUniforms( [
  9122. UniformsLib.common,
  9123. UniformsLib.specularmap,
  9124. UniformsLib.envmap,
  9125. UniformsLib.aomap,
  9126. UniformsLib.lightmap,
  9127. UniformsLib.fog
  9128. ] ),
  9129. vertexShader: ShaderChunk.meshbasic_vert,
  9130. fragmentShader: ShaderChunk.meshbasic_frag
  9131. },
  9132. lambert: {
  9133. uniforms: mergeUniforms( [
  9134. UniformsLib.common,
  9135. UniformsLib.specularmap,
  9136. UniformsLib.envmap,
  9137. UniformsLib.aomap,
  9138. UniformsLib.lightmap,
  9139. UniformsLib.emissivemap,
  9140. UniformsLib.fog,
  9141. UniformsLib.lights,
  9142. {
  9143. emissive: { value: new Color( 0x000000 ) }
  9144. }
  9145. ] ),
  9146. vertexShader: ShaderChunk.meshlambert_vert,
  9147. fragmentShader: ShaderChunk.meshlambert_frag
  9148. },
  9149. phong: {
  9150. uniforms: mergeUniforms( [
  9151. UniformsLib.common,
  9152. UniformsLib.specularmap,
  9153. UniformsLib.envmap,
  9154. UniformsLib.aomap,
  9155. UniformsLib.lightmap,
  9156. UniformsLib.emissivemap,
  9157. UniformsLib.bumpmap,
  9158. UniformsLib.normalmap,
  9159. UniformsLib.displacementmap,
  9160. UniformsLib.gradientmap,
  9161. UniformsLib.fog,
  9162. UniformsLib.lights,
  9163. {
  9164. emissive: { value: new Color( 0x000000 ) },
  9165. specular: { value: new Color( 0x111111 ) },
  9166. shininess: { value: 30 }
  9167. }
  9168. ] ),
  9169. vertexShader: ShaderChunk.meshphong_vert,
  9170. fragmentShader: ShaderChunk.meshphong_frag
  9171. },
  9172. standard: {
  9173. uniforms: mergeUniforms( [
  9174. UniformsLib.common,
  9175. UniformsLib.envmap,
  9176. UniformsLib.aomap,
  9177. UniformsLib.lightmap,
  9178. UniformsLib.emissivemap,
  9179. UniformsLib.bumpmap,
  9180. UniformsLib.normalmap,
  9181. UniformsLib.displacementmap,
  9182. UniformsLib.roughnessmap,
  9183. UniformsLib.metalnessmap,
  9184. UniformsLib.fog,
  9185. UniformsLib.lights,
  9186. {
  9187. emissive: { value: new Color( 0x000000 ) },
  9188. roughness: { value: 0.5 },
  9189. metalness: { value: 0.5 },
  9190. envMapIntensity: { value: 1 } // temporary
  9191. }
  9192. ] ),
  9193. vertexShader: ShaderChunk.meshphysical_vert,
  9194. fragmentShader: ShaderChunk.meshphysical_frag
  9195. },
  9196. matcap: {
  9197. uniforms: mergeUniforms( [
  9198. UniformsLib.common,
  9199. UniformsLib.bumpmap,
  9200. UniformsLib.normalmap,
  9201. UniformsLib.displacementmap,
  9202. UniformsLib.fog,
  9203. {
  9204. matcap: { value: null }
  9205. }
  9206. ] ),
  9207. vertexShader: ShaderChunk.meshmatcap_vert,
  9208. fragmentShader: ShaderChunk.meshmatcap_frag
  9209. },
  9210. points: {
  9211. uniforms: mergeUniforms( [
  9212. UniformsLib.points,
  9213. UniformsLib.fog
  9214. ] ),
  9215. vertexShader: ShaderChunk.points_vert,
  9216. fragmentShader: ShaderChunk.points_frag
  9217. },
  9218. dashed: {
  9219. uniforms: mergeUniforms( [
  9220. UniformsLib.common,
  9221. UniformsLib.fog,
  9222. {
  9223. scale: { value: 1 },
  9224. dashSize: { value: 1 },
  9225. totalSize: { value: 2 }
  9226. }
  9227. ] ),
  9228. vertexShader: ShaderChunk.linedashed_vert,
  9229. fragmentShader: ShaderChunk.linedashed_frag
  9230. },
  9231. depth: {
  9232. uniforms: mergeUniforms( [
  9233. UniformsLib.common,
  9234. UniformsLib.displacementmap
  9235. ] ),
  9236. vertexShader: ShaderChunk.depth_vert,
  9237. fragmentShader: ShaderChunk.depth_frag
  9238. },
  9239. normal: {
  9240. uniforms: mergeUniforms( [
  9241. UniformsLib.common,
  9242. UniformsLib.bumpmap,
  9243. UniformsLib.normalmap,
  9244. UniformsLib.displacementmap,
  9245. {
  9246. opacity: { value: 1.0 }
  9247. }
  9248. ] ),
  9249. vertexShader: ShaderChunk.normal_vert,
  9250. fragmentShader: ShaderChunk.normal_frag
  9251. },
  9252. sprite: {
  9253. uniforms: mergeUniforms( [
  9254. UniformsLib.sprite,
  9255. UniformsLib.fog
  9256. ] ),
  9257. vertexShader: ShaderChunk.sprite_vert,
  9258. fragmentShader: ShaderChunk.sprite_frag
  9259. },
  9260. background: {
  9261. uniforms: {
  9262. uvTransform: { value: new Matrix3() },
  9263. t2D: { value: null },
  9264. },
  9265. vertexShader: ShaderChunk.background_vert,
  9266. fragmentShader: ShaderChunk.background_frag
  9267. },
  9268. /* -------------------------------------------------------------------------
  9269. // Cube map shader
  9270. ------------------------------------------------------------------------- */
  9271. cube: {
  9272. uniforms: {
  9273. tCube: { value: null },
  9274. tFlip: { value: - 1 },
  9275. opacity: { value: 1.0 }
  9276. },
  9277. vertexShader: ShaderChunk.cube_vert,
  9278. fragmentShader: ShaderChunk.cube_frag
  9279. },
  9280. equirect: {
  9281. uniforms: {
  9282. tEquirect: { value: null },
  9283. },
  9284. vertexShader: ShaderChunk.equirect_vert,
  9285. fragmentShader: ShaderChunk.equirect_frag
  9286. },
  9287. distanceRGBA: {
  9288. uniforms: mergeUniforms( [
  9289. UniformsLib.common,
  9290. UniformsLib.displacementmap,
  9291. {
  9292. referencePosition: { value: new Vector3() },
  9293. nearDistance: { value: 1 },
  9294. farDistance: { value: 1000 }
  9295. }
  9296. ] ),
  9297. vertexShader: ShaderChunk.distanceRGBA_vert,
  9298. fragmentShader: ShaderChunk.distanceRGBA_frag
  9299. },
  9300. shadow: {
  9301. uniforms: mergeUniforms( [
  9302. UniformsLib.lights,
  9303. UniformsLib.fog,
  9304. {
  9305. color: { value: new Color( 0x00000 ) },
  9306. opacity: { value: 1.0 }
  9307. },
  9308. ] ),
  9309. vertexShader: ShaderChunk.shadow_vert,
  9310. fragmentShader: ShaderChunk.shadow_frag
  9311. }
  9312. };
  9313. ShaderLib.physical = {
  9314. uniforms: mergeUniforms( [
  9315. ShaderLib.standard.uniforms,
  9316. {
  9317. clearCoat: { value: 0 },
  9318. clearCoatRoughness: { value: 0 }
  9319. }
  9320. ] ),
  9321. vertexShader: ShaderChunk.meshphysical_vert,
  9322. fragmentShader: ShaderChunk.meshphysical_frag
  9323. };
  9324. /**
  9325. * @author mrdoob / http://mrdoob.com/
  9326. */
  9327. function WebGLAnimation() {
  9328. var context = null;
  9329. var isAnimating = false;
  9330. var animationLoop = null;
  9331. function onAnimationFrame( time, frame ) {
  9332. if ( isAnimating === false ) return;
  9333. animationLoop( time, frame );
  9334. context.requestAnimationFrame( onAnimationFrame );
  9335. }
  9336. return {
  9337. start: function () {
  9338. if ( isAnimating === true ) return;
  9339. if ( animationLoop === null ) return;
  9340. context.requestAnimationFrame( onAnimationFrame );
  9341. isAnimating = true;
  9342. },
  9343. stop: function () {
  9344. isAnimating = false;
  9345. },
  9346. setAnimationLoop: function ( callback ) {
  9347. animationLoop = callback;
  9348. },
  9349. setContext: function ( value ) {
  9350. context = value;
  9351. }
  9352. };
  9353. }
  9354. /**
  9355. * @author mrdoob / http://mrdoob.com/
  9356. */
  9357. function WebGLAttributes( gl ) {
  9358. var buffers = new WeakMap();
  9359. function createBuffer( attribute, bufferType ) {
  9360. var array = attribute.array;
  9361. var usage = attribute.dynamic ? 35048 : 35044;
  9362. var buffer = gl.createBuffer();
  9363. gl.bindBuffer( bufferType, buffer );
  9364. gl.bufferData( bufferType, array, usage );
  9365. attribute.onUploadCallback();
  9366. var type = 5126;
  9367. if ( array instanceof Float32Array ) {
  9368. type = 5126;
  9369. } else if ( array instanceof Float64Array ) {
  9370. console.warn( 'THREE.WebGLAttributes: Unsupported data buffer format: Float64Array.' );
  9371. } else if ( array instanceof Uint16Array ) {
  9372. type = 5123;
  9373. } else if ( array instanceof Int16Array ) {
  9374. type = 5122;
  9375. } else if ( array instanceof Uint32Array ) {
  9376. type = 5125;
  9377. } else if ( array instanceof Int32Array ) {
  9378. type = 5124;
  9379. } else if ( array instanceof Int8Array ) {
  9380. type = 5120;
  9381. } else if ( array instanceof Uint8Array ) {
  9382. type = 5121;
  9383. }
  9384. return {
  9385. buffer: buffer,
  9386. type: type,
  9387. bytesPerElement: array.BYTES_PER_ELEMENT,
  9388. version: attribute.version
  9389. };
  9390. }
  9391. function updateBuffer( buffer, attribute, bufferType ) {
  9392. var array = attribute.array;
  9393. var updateRange = attribute.updateRange;
  9394. gl.bindBuffer( bufferType, buffer );
  9395. if ( attribute.dynamic === false ) {
  9396. gl.bufferData( bufferType, array, 35044 );
  9397. } else if ( updateRange.count === - 1 ) {
  9398. // Not using update ranges
  9399. gl.bufferSubData( bufferType, 0, array );
  9400. } else if ( updateRange.count === 0 ) {
  9401. console.error( 'THREE.WebGLObjects.updateBuffer: dynamic THREE.BufferAttribute marked as needsUpdate but updateRange.count is 0, ensure you are using set methods or updating manually.' );
  9402. } else {
  9403. gl.bufferSubData( bufferType, updateRange.offset * array.BYTES_PER_ELEMENT,
  9404. array.subarray( updateRange.offset, updateRange.offset + updateRange.count ) );
  9405. updateRange.count = - 1; // reset range
  9406. }
  9407. }
  9408. //
  9409. function get( attribute ) {
  9410. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  9411. return buffers.get( attribute );
  9412. }
  9413. function remove( attribute ) {
  9414. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  9415. var data = buffers.get( attribute );
  9416. if ( data ) {
  9417. gl.deleteBuffer( data.buffer );
  9418. buffers.delete( attribute );
  9419. }
  9420. }
  9421. function update( attribute, bufferType ) {
  9422. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  9423. var data = buffers.get( attribute );
  9424. if ( data === undefined ) {
  9425. buffers.set( attribute, createBuffer( attribute, bufferType ) );
  9426. } else if ( data.version < attribute.version ) {
  9427. updateBuffer( data.buffer, attribute, bufferType );
  9428. data.version = attribute.version;
  9429. }
  9430. }
  9431. return {
  9432. get: get,
  9433. remove: remove,
  9434. update: update
  9435. };
  9436. }
  9437. /**
  9438. * @author mrdoob / http://mrdoob.com/
  9439. * @author alteredq / http://alteredqualia.com/
  9440. */
  9441. function Face3( a, b, c, normal, color, materialIndex ) {
  9442. this.a = a;
  9443. this.b = b;
  9444. this.c = c;
  9445. this.normal = ( normal && normal.isVector3 ) ? normal : new Vector3();
  9446. this.vertexNormals = Array.isArray( normal ) ? normal : [];
  9447. this.color = ( color && color.isColor ) ? color : new Color();
  9448. this.vertexColors = Array.isArray( color ) ? color : [];
  9449. this.materialIndex = materialIndex !== undefined ? materialIndex : 0;
  9450. }
  9451. Object.assign( Face3.prototype, {
  9452. clone: function () {
  9453. return new this.constructor().copy( this );
  9454. },
  9455. copy: function ( source ) {
  9456. this.a = source.a;
  9457. this.b = source.b;
  9458. this.c = source.c;
  9459. this.normal.copy( source.normal );
  9460. this.color.copy( source.color );
  9461. this.materialIndex = source.materialIndex;
  9462. for ( var i = 0, il = source.vertexNormals.length; i < il; i ++ ) {
  9463. this.vertexNormals[ i ] = source.vertexNormals[ i ].clone();
  9464. }
  9465. for ( var i = 0, il = source.vertexColors.length; i < il; i ++ ) {
  9466. this.vertexColors[ i ] = source.vertexColors[ i ].clone();
  9467. }
  9468. return this;
  9469. }
  9470. } );
  9471. /**
  9472. * @author mrdoob / http://mrdoob.com/
  9473. * @author WestLangley / http://github.com/WestLangley
  9474. * @author bhouston / http://clara.io
  9475. */
  9476. function Euler( x, y, z, order ) {
  9477. this._x = x || 0;
  9478. this._y = y || 0;
  9479. this._z = z || 0;
  9480. this._order = order || Euler.DefaultOrder;
  9481. }
  9482. Euler.RotationOrders = [ 'XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX' ];
  9483. Euler.DefaultOrder = 'XYZ';
  9484. Object.defineProperties( Euler.prototype, {
  9485. x: {
  9486. get: function () {
  9487. return this._x;
  9488. },
  9489. set: function ( value ) {
  9490. this._x = value;
  9491. this.onChangeCallback();
  9492. }
  9493. },
  9494. y: {
  9495. get: function () {
  9496. return this._y;
  9497. },
  9498. set: function ( value ) {
  9499. this._y = value;
  9500. this.onChangeCallback();
  9501. }
  9502. },
  9503. z: {
  9504. get: function () {
  9505. return this._z;
  9506. },
  9507. set: function ( value ) {
  9508. this._z = value;
  9509. this.onChangeCallback();
  9510. }
  9511. },
  9512. order: {
  9513. get: function () {
  9514. return this._order;
  9515. },
  9516. set: function ( value ) {
  9517. this._order = value;
  9518. this.onChangeCallback();
  9519. }
  9520. }
  9521. } );
  9522. Object.assign( Euler.prototype, {
  9523. isEuler: true,
  9524. set: function ( x, y, z, order ) {
  9525. this._x = x;
  9526. this._y = y;
  9527. this._z = z;
  9528. this._order = order || this._order;
  9529. this.onChangeCallback();
  9530. return this;
  9531. },
  9532. clone: function () {
  9533. return new this.constructor( this._x, this._y, this._z, this._order );
  9534. },
  9535. copy: function ( euler ) {
  9536. this._x = euler._x;
  9537. this._y = euler._y;
  9538. this._z = euler._z;
  9539. this._order = euler._order;
  9540. this.onChangeCallback();
  9541. return this;
  9542. },
  9543. setFromRotationMatrix: function ( m, order, update ) {
  9544. var clamp = _Math.clamp;
  9545. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  9546. var te = m.elements;
  9547. var m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ];
  9548. var m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ];
  9549. var m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  9550. order = order || this._order;
  9551. if ( order === 'XYZ' ) {
  9552. this._y = Math.asin( clamp( m13, - 1, 1 ) );
  9553. if ( Math.abs( m13 ) < 0.99999 ) {
  9554. this._x = Math.atan2( - m23, m33 );
  9555. this._z = Math.atan2( - m12, m11 );
  9556. } else {
  9557. this._x = Math.atan2( m32, m22 );
  9558. this._z = 0;
  9559. }
  9560. } else if ( order === 'YXZ' ) {
  9561. this._x = Math.asin( - clamp( m23, - 1, 1 ) );
  9562. if ( Math.abs( m23 ) < 0.99999 ) {
  9563. this._y = Math.atan2( m13, m33 );
  9564. this._z = Math.atan2( m21, m22 );
  9565. } else {
  9566. this._y = Math.atan2( - m31, m11 );
  9567. this._z = 0;
  9568. }
  9569. } else if ( order === 'ZXY' ) {
  9570. this._x = Math.asin( clamp( m32, - 1, 1 ) );
  9571. if ( Math.abs( m32 ) < 0.99999 ) {
  9572. this._y = Math.atan2( - m31, m33 );
  9573. this._z = Math.atan2( - m12, m22 );
  9574. } else {
  9575. this._y = 0;
  9576. this._z = Math.atan2( m21, m11 );
  9577. }
  9578. } else if ( order === 'ZYX' ) {
  9579. this._y = Math.asin( - clamp( m31, - 1, 1 ) );
  9580. if ( Math.abs( m31 ) < 0.99999 ) {
  9581. this._x = Math.atan2( m32, m33 );
  9582. this._z = Math.atan2( m21, m11 );
  9583. } else {
  9584. this._x = 0;
  9585. this._z = Math.atan2( - m12, m22 );
  9586. }
  9587. } else if ( order === 'YZX' ) {
  9588. this._z = Math.asin( clamp( m21, - 1, 1 ) );
  9589. if ( Math.abs( m21 ) < 0.99999 ) {
  9590. this._x = Math.atan2( - m23, m22 );
  9591. this._y = Math.atan2( - m31, m11 );
  9592. } else {
  9593. this._x = 0;
  9594. this._y = Math.atan2( m13, m33 );
  9595. }
  9596. } else if ( order === 'XZY' ) {
  9597. this._z = Math.asin( - clamp( m12, - 1, 1 ) );
  9598. if ( Math.abs( m12 ) < 0.99999 ) {
  9599. this._x = Math.atan2( m32, m22 );
  9600. this._y = Math.atan2( m13, m11 );
  9601. } else {
  9602. this._x = Math.atan2( - m23, m33 );
  9603. this._y = 0;
  9604. }
  9605. } else {
  9606. console.warn( 'THREE.Euler: .setFromRotationMatrix() given unsupported order: ' + order );
  9607. }
  9608. this._order = order;
  9609. if ( update !== false ) this.onChangeCallback();
  9610. return this;
  9611. },
  9612. setFromQuaternion: function () {
  9613. var matrix = new Matrix4();
  9614. return function setFromQuaternion( q, order, update ) {
  9615. matrix.makeRotationFromQuaternion( q );
  9616. return this.setFromRotationMatrix( matrix, order, update );
  9617. };
  9618. }(),
  9619. setFromVector3: function ( v, order ) {
  9620. return this.set( v.x, v.y, v.z, order || this._order );
  9621. },
  9622. reorder: function () {
  9623. // WARNING: this discards revolution information -bhouston
  9624. var q = new Quaternion();
  9625. return function reorder( newOrder ) {
  9626. q.setFromEuler( this );
  9627. return this.setFromQuaternion( q, newOrder );
  9628. };
  9629. }(),
  9630. equals: function ( euler ) {
  9631. return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order );
  9632. },
  9633. fromArray: function ( array ) {
  9634. this._x = array[ 0 ];
  9635. this._y = array[ 1 ];
  9636. this._z = array[ 2 ];
  9637. if ( array[ 3 ] !== undefined ) this._order = array[ 3 ];
  9638. this.onChangeCallback();
  9639. return this;
  9640. },
  9641. toArray: function ( array, offset ) {
  9642. if ( array === undefined ) array = [];
  9643. if ( offset === undefined ) offset = 0;
  9644. array[ offset ] = this._x;
  9645. array[ offset + 1 ] = this._y;
  9646. array[ offset + 2 ] = this._z;
  9647. array[ offset + 3 ] = this._order;
  9648. return array;
  9649. },
  9650. toVector3: function ( optionalResult ) {
  9651. if ( optionalResult ) {
  9652. return optionalResult.set( this._x, this._y, this._z );
  9653. } else {
  9654. return new Vector3( this._x, this._y, this._z );
  9655. }
  9656. },
  9657. onChange: function ( callback ) {
  9658. this.onChangeCallback = callback;
  9659. return this;
  9660. },
  9661. onChangeCallback: function () {}
  9662. } );
  9663. /**
  9664. * @author mrdoob / http://mrdoob.com/
  9665. */
  9666. function Layers() {
  9667. this.mask = 1 | 0;
  9668. }
  9669. Object.assign( Layers.prototype, {
  9670. set: function ( channel ) {
  9671. this.mask = 1 << channel | 0;
  9672. },
  9673. enable: function ( channel ) {
  9674. this.mask |= 1 << channel | 0;
  9675. },
  9676. toggle: function ( channel ) {
  9677. this.mask ^= 1 << channel | 0;
  9678. },
  9679. disable: function ( channel ) {
  9680. this.mask &= ~ ( 1 << channel | 0 );
  9681. },
  9682. test: function ( layers ) {
  9683. return ( this.mask & layers.mask ) !== 0;
  9684. }
  9685. } );
  9686. /**
  9687. * @author mrdoob / http://mrdoob.com/
  9688. * @author mikael emtinger / http://gomo.se/
  9689. * @author alteredq / http://alteredqualia.com/
  9690. * @author WestLangley / http://github.com/WestLangley
  9691. * @author elephantatwork / www.elephantatwork.ch
  9692. */
  9693. var object3DId = 0;
  9694. function Object3D() {
  9695. Object.defineProperty( this, 'id', { value: object3DId ++ } );
  9696. this.uuid = _Math.generateUUID();
  9697. this.name = '';
  9698. this.type = 'Object3D';
  9699. this.parent = null;
  9700. this.children = [];
  9701. this.up = Object3D.DefaultUp.clone();
  9702. var position = new Vector3();
  9703. var rotation = new Euler();
  9704. var quaternion = new Quaternion();
  9705. var scale = new Vector3( 1, 1, 1 );
  9706. function onRotationChange() {
  9707. quaternion.setFromEuler( rotation, false );
  9708. }
  9709. function onQuaternionChange() {
  9710. rotation.setFromQuaternion( quaternion, undefined, false );
  9711. }
  9712. rotation.onChange( onRotationChange );
  9713. quaternion.onChange( onQuaternionChange );
  9714. Object.defineProperties( this, {
  9715. position: {
  9716. configurable: true,
  9717. enumerable: true,
  9718. value: position
  9719. },
  9720. rotation: {
  9721. configurable: true,
  9722. enumerable: true,
  9723. value: rotation
  9724. },
  9725. quaternion: {
  9726. configurable: true,
  9727. enumerable: true,
  9728. value: quaternion
  9729. },
  9730. scale: {
  9731. configurable: true,
  9732. enumerable: true,
  9733. value: scale
  9734. },
  9735. modelViewMatrix: {
  9736. value: new Matrix4()
  9737. },
  9738. normalMatrix: {
  9739. value: new Matrix3()
  9740. }
  9741. } );
  9742. this.matrix = new Matrix4();
  9743. this.matrixWorld = new Matrix4();
  9744. this.matrixAutoUpdate = Object3D.DefaultMatrixAutoUpdate;
  9745. this.matrixWorldNeedsUpdate = false;
  9746. this.layers = new Layers();
  9747. this.visible = true;
  9748. this.castShadow = false;
  9749. this.receiveShadow = false;
  9750. this.frustumCulled = true;
  9751. this.renderOrder = 0;
  9752. this.userData = {};
  9753. }
  9754. Object3D.DefaultUp = new Vector3( 0, 1, 0 );
  9755. Object3D.DefaultMatrixAutoUpdate = true;
  9756. Object3D.prototype = Object.assign( Object.create( EventDispatcher.prototype ), {
  9757. constructor: Object3D,
  9758. isObject3D: true,
  9759. onBeforeRender: function () {},
  9760. onAfterRender: function () {},
  9761. applyMatrix: function ( matrix ) {
  9762. this.matrix.multiplyMatrices( matrix, this.matrix );
  9763. this.matrix.decompose( this.position, this.quaternion, this.scale );
  9764. },
  9765. applyQuaternion: function ( q ) {
  9766. this.quaternion.premultiply( q );
  9767. return this;
  9768. },
  9769. setRotationFromAxisAngle: function ( axis, angle ) {
  9770. // assumes axis is normalized
  9771. this.quaternion.setFromAxisAngle( axis, angle );
  9772. },
  9773. setRotationFromEuler: function ( euler ) {
  9774. this.quaternion.setFromEuler( euler, true );
  9775. },
  9776. setRotationFromMatrix: function ( m ) {
  9777. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  9778. this.quaternion.setFromRotationMatrix( m );
  9779. },
  9780. setRotationFromQuaternion: function ( q ) {
  9781. // assumes q is normalized
  9782. this.quaternion.copy( q );
  9783. },
  9784. rotateOnAxis: function () {
  9785. // rotate object on axis in object space
  9786. // axis is assumed to be normalized
  9787. var q1 = new Quaternion();
  9788. return function rotateOnAxis( axis, angle ) {
  9789. q1.setFromAxisAngle( axis, angle );
  9790. this.quaternion.multiply( q1 );
  9791. return this;
  9792. };
  9793. }(),
  9794. rotateOnWorldAxis: function () {
  9795. // rotate object on axis in world space
  9796. // axis is assumed to be normalized
  9797. // method assumes no rotated parent
  9798. var q1 = new Quaternion();
  9799. return function rotateOnWorldAxis( axis, angle ) {
  9800. q1.setFromAxisAngle( axis, angle );
  9801. this.quaternion.premultiply( q1 );
  9802. return this;
  9803. };
  9804. }(),
  9805. rotateX: function () {
  9806. var v1 = new Vector3( 1, 0, 0 );
  9807. return function rotateX( angle ) {
  9808. return this.rotateOnAxis( v1, angle );
  9809. };
  9810. }(),
  9811. rotateY: function () {
  9812. var v1 = new Vector3( 0, 1, 0 );
  9813. return function rotateY( angle ) {
  9814. return this.rotateOnAxis( v1, angle );
  9815. };
  9816. }(),
  9817. rotateZ: function () {
  9818. var v1 = new Vector3( 0, 0, 1 );
  9819. return function rotateZ( angle ) {
  9820. return this.rotateOnAxis( v1, angle );
  9821. };
  9822. }(),
  9823. translateOnAxis: function () {
  9824. // translate object by distance along axis in object space
  9825. // axis is assumed to be normalized
  9826. var v1 = new Vector3();
  9827. return function translateOnAxis( axis, distance ) {
  9828. v1.copy( axis ).applyQuaternion( this.quaternion );
  9829. this.position.add( v1.multiplyScalar( distance ) );
  9830. return this;
  9831. };
  9832. }(),
  9833. translateX: function () {
  9834. var v1 = new Vector3( 1, 0, 0 );
  9835. return function translateX( distance ) {
  9836. return this.translateOnAxis( v1, distance );
  9837. };
  9838. }(),
  9839. translateY: function () {
  9840. var v1 = new Vector3( 0, 1, 0 );
  9841. return function translateY( distance ) {
  9842. return this.translateOnAxis( v1, distance );
  9843. };
  9844. }(),
  9845. translateZ: function () {
  9846. var v1 = new Vector3( 0, 0, 1 );
  9847. return function translateZ( distance ) {
  9848. return this.translateOnAxis( v1, distance );
  9849. };
  9850. }(),
  9851. localToWorld: function ( vector ) {
  9852. return vector.applyMatrix4( this.matrixWorld );
  9853. },
  9854. worldToLocal: function () {
  9855. var m1 = new Matrix4();
  9856. return function worldToLocal( vector ) {
  9857. return vector.applyMatrix4( m1.getInverse( this.matrixWorld ) );
  9858. };
  9859. }(),
  9860. lookAt: function () {
  9861. // This method does not support objects having non-uniformly-scaled parent(s)
  9862. var q1 = new Quaternion();
  9863. var m1 = new Matrix4();
  9864. var target = new Vector3();
  9865. var position = new Vector3();
  9866. return function lookAt( x, y, z ) {
  9867. if ( x.isVector3 ) {
  9868. target.copy( x );
  9869. } else {
  9870. target.set( x, y, z );
  9871. }
  9872. var parent = this.parent;
  9873. this.updateWorldMatrix( true, false );
  9874. position.setFromMatrixPosition( this.matrixWorld );
  9875. if ( this.isCamera || this.isLight ) {
  9876. m1.lookAt( position, target, this.up );
  9877. } else {
  9878. m1.lookAt( target, position, this.up );
  9879. }
  9880. this.quaternion.setFromRotationMatrix( m1 );
  9881. if ( parent ) {
  9882. m1.extractRotation( parent.matrixWorld );
  9883. q1.setFromRotationMatrix( m1 );
  9884. this.quaternion.premultiply( q1.inverse() );
  9885. }
  9886. };
  9887. }(),
  9888. add: function ( object ) {
  9889. if ( arguments.length > 1 ) {
  9890. for ( var i = 0; i < arguments.length; i ++ ) {
  9891. this.add( arguments[ i ] );
  9892. }
  9893. return this;
  9894. }
  9895. if ( object === this ) {
  9896. console.error( "THREE.Object3D.add: object can't be added as a child of itself.", object );
  9897. return this;
  9898. }
  9899. if ( ( object && object.isObject3D ) ) {
  9900. if ( object.parent !== null ) {
  9901. object.parent.remove( object );
  9902. }
  9903. object.parent = this;
  9904. object.dispatchEvent( { type: 'added' } );
  9905. this.children.push( object );
  9906. } else {
  9907. console.error( "THREE.Object3D.add: object not an instance of THREE.Object3D.", object );
  9908. }
  9909. return this;
  9910. },
  9911. remove: function ( object ) {
  9912. if ( arguments.length > 1 ) {
  9913. for ( var i = 0; i < arguments.length; i ++ ) {
  9914. this.remove( arguments[ i ] );
  9915. }
  9916. return this;
  9917. }
  9918. var index = this.children.indexOf( object );
  9919. if ( index !== - 1 ) {
  9920. object.parent = null;
  9921. object.dispatchEvent( { type: 'removed' } );
  9922. this.children.splice( index, 1 );
  9923. }
  9924. return this;
  9925. },
  9926. getObjectById: function ( id ) {
  9927. return this.getObjectByProperty( 'id', id );
  9928. },
  9929. getObjectByName: function ( name ) {
  9930. return this.getObjectByProperty( 'name', name );
  9931. },
  9932. getObjectByProperty: function ( name, value ) {
  9933. if ( this[ name ] === value ) return this;
  9934. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  9935. var child = this.children[ i ];
  9936. var object = child.getObjectByProperty( name, value );
  9937. if ( object !== undefined ) {
  9938. return object;
  9939. }
  9940. }
  9941. return undefined;
  9942. },
  9943. getWorldPosition: function ( target ) {
  9944. if ( target === undefined ) {
  9945. console.warn( 'THREE.Object3D: .getWorldPosition() target is now required' );
  9946. target = new Vector3();
  9947. }
  9948. this.updateMatrixWorld( true );
  9949. return target.setFromMatrixPosition( this.matrixWorld );
  9950. },
  9951. getWorldQuaternion: function () {
  9952. var position = new Vector3();
  9953. var scale = new Vector3();
  9954. return function getWorldQuaternion( target ) {
  9955. if ( target === undefined ) {
  9956. console.warn( 'THREE.Object3D: .getWorldQuaternion() target is now required' );
  9957. target = new Quaternion();
  9958. }
  9959. this.updateMatrixWorld( true );
  9960. this.matrixWorld.decompose( position, target, scale );
  9961. return target;
  9962. };
  9963. }(),
  9964. getWorldScale: function () {
  9965. var position = new Vector3();
  9966. var quaternion = new Quaternion();
  9967. return function getWorldScale( target ) {
  9968. if ( target === undefined ) {
  9969. console.warn( 'THREE.Object3D: .getWorldScale() target is now required' );
  9970. target = new Vector3();
  9971. }
  9972. this.updateMatrixWorld( true );
  9973. this.matrixWorld.decompose( position, quaternion, target );
  9974. return target;
  9975. };
  9976. }(),
  9977. getWorldDirection: function ( target ) {
  9978. if ( target === undefined ) {
  9979. console.warn( 'THREE.Object3D: .getWorldDirection() target is now required' );
  9980. target = new Vector3();
  9981. }
  9982. this.updateMatrixWorld( true );
  9983. var e = this.matrixWorld.elements;
  9984. return target.set( e[ 8 ], e[ 9 ], e[ 10 ] ).normalize();
  9985. },
  9986. raycast: function () {},
  9987. traverse: function ( callback ) {
  9988. callback( this );
  9989. var children = this.children;
  9990. for ( var i = 0, l = children.length; i < l; i ++ ) {
  9991. children[ i ].traverse( callback );
  9992. }
  9993. },
  9994. traverseVisible: function ( callback ) {
  9995. if ( this.visible === false ) return;
  9996. callback( this );
  9997. var children = this.children;
  9998. for ( var i = 0, l = children.length; i < l; i ++ ) {
  9999. children[ i ].traverseVisible( callback );
  10000. }
  10001. },
  10002. traverseAncestors: function ( callback ) {
  10003. var parent = this.parent;
  10004. if ( parent !== null ) {
  10005. callback( parent );
  10006. parent.traverseAncestors( callback );
  10007. }
  10008. },
  10009. updateMatrix: function () {
  10010. this.matrix.compose( this.position, this.quaternion, this.scale );
  10011. this.matrixWorldNeedsUpdate = true;
  10012. },
  10013. updateMatrixWorld: function ( force ) {
  10014. if ( this.matrixAutoUpdate ) this.updateMatrix();
  10015. if ( this.matrixWorldNeedsUpdate || force ) {
  10016. if ( this.parent === null ) {
  10017. this.matrixWorld.copy( this.matrix );
  10018. } else {
  10019. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  10020. }
  10021. this.matrixWorldNeedsUpdate = false;
  10022. force = true;
  10023. }
  10024. // update children
  10025. var children = this.children;
  10026. for ( var i = 0, l = children.length; i < l; i ++ ) {
  10027. children[ i ].updateMatrixWorld( force );
  10028. }
  10029. },
  10030. updateWorldMatrix: function ( updateParents, updateChildren ) {
  10031. var parent = this.parent;
  10032. if ( updateParents === true && parent !== null ) {
  10033. parent.updateWorldMatrix( true, false );
  10034. }
  10035. if ( this.matrixAutoUpdate ) this.updateMatrix();
  10036. if ( this.parent === null ) {
  10037. this.matrixWorld.copy( this.matrix );
  10038. } else {
  10039. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  10040. }
  10041. // update children
  10042. if ( updateChildren === true ) {
  10043. var children = this.children;
  10044. for ( var i = 0, l = children.length; i < l; i ++ ) {
  10045. children[ i ].updateWorldMatrix( false, true );
  10046. }
  10047. }
  10048. },
  10049. toJSON: function ( meta ) {
  10050. // meta is a string when called from JSON.stringify
  10051. var isRootObject = ( meta === undefined || typeof meta === 'string' );
  10052. var output = {};
  10053. // meta is a hash used to collect geometries, materials.
  10054. // not providing it implies that this is the root object
  10055. // being serialized.
  10056. if ( isRootObject ) {
  10057. // initialize meta obj
  10058. meta = {
  10059. geometries: {},
  10060. materials: {},
  10061. textures: {},
  10062. images: {},
  10063. shapes: {}
  10064. };
  10065. output.metadata = {
  10066. version: 4.5,
  10067. type: 'Object',
  10068. generator: 'Object3D.toJSON'
  10069. };
  10070. }
  10071. // standard Object3D serialization
  10072. var object = {};
  10073. object.uuid = this.uuid;
  10074. object.type = this.type;
  10075. if ( this.name !== '' ) object.name = this.name;
  10076. if ( this.castShadow === true ) object.castShadow = true;
  10077. if ( this.receiveShadow === true ) object.receiveShadow = true;
  10078. if ( this.visible === false ) object.visible = false;
  10079. if ( this.frustumCulled === false ) object.frustumCulled = false;
  10080. if ( this.renderOrder !== 0 ) object.renderOrder = this.renderOrder;
  10081. if ( JSON.stringify( this.userData ) !== '{}' ) object.userData = this.userData;
  10082. object.layers = this.layers.mask;
  10083. object.matrix = this.matrix.toArray();
  10084. if ( this.matrixAutoUpdate === false ) object.matrixAutoUpdate = false;
  10085. // object specific properties
  10086. if ( this.isMesh && this.drawMode !== TrianglesDrawMode ) object.drawMode = this.drawMode;
  10087. //
  10088. function serialize( library, element ) {
  10089. if ( library[ element.uuid ] === undefined ) {
  10090. library[ element.uuid ] = element.toJSON( meta );
  10091. }
  10092. return element.uuid;
  10093. }
  10094. if ( this.isMesh || this.isLine || this.isPoints ) {
  10095. object.geometry = serialize( meta.geometries, this.geometry );
  10096. var parameters = this.geometry.parameters;
  10097. if ( parameters !== undefined && parameters.shapes !== undefined ) {
  10098. var shapes = parameters.shapes;
  10099. if ( Array.isArray( shapes ) ) {
  10100. for ( var i = 0, l = shapes.length; i < l; i ++ ) {
  10101. var shape = shapes[ i ];
  10102. serialize( meta.shapes, shape );
  10103. }
  10104. } else {
  10105. serialize( meta.shapes, shapes );
  10106. }
  10107. }
  10108. }
  10109. if ( this.material !== undefined ) {
  10110. if ( Array.isArray( this.material ) ) {
  10111. var uuids = [];
  10112. for ( var i = 0, l = this.material.length; i < l; i ++ ) {
  10113. uuids.push( serialize( meta.materials, this.material[ i ] ) );
  10114. }
  10115. object.material = uuids;
  10116. } else {
  10117. object.material = serialize( meta.materials, this.material );
  10118. }
  10119. }
  10120. //
  10121. if ( this.children.length > 0 ) {
  10122. object.children = [];
  10123. for ( var i = 0; i < this.children.length; i ++ ) {
  10124. object.children.push( this.children[ i ].toJSON( meta ).object );
  10125. }
  10126. }
  10127. if ( isRootObject ) {
  10128. var geometries = extractFromCache( meta.geometries );
  10129. var materials = extractFromCache( meta.materials );
  10130. var textures = extractFromCache( meta.textures );
  10131. var images = extractFromCache( meta.images );
  10132. var shapes = extractFromCache( meta.shapes );
  10133. if ( geometries.length > 0 ) output.geometries = geometries;
  10134. if ( materials.length > 0 ) output.materials = materials;
  10135. if ( textures.length > 0 ) output.textures = textures;
  10136. if ( images.length > 0 ) output.images = images;
  10137. if ( shapes.length > 0 ) output.shapes = shapes;
  10138. }
  10139. output.object = object;
  10140. return output;
  10141. // extract data from the cache hash
  10142. // remove metadata on each item
  10143. // and return as array
  10144. function extractFromCache( cache ) {
  10145. var values = [];
  10146. for ( var key in cache ) {
  10147. var data = cache[ key ];
  10148. delete data.metadata;
  10149. values.push( data );
  10150. }
  10151. return values;
  10152. }
  10153. },
  10154. clone: function ( recursive ) {
  10155. return new this.constructor().copy( this, recursive );
  10156. },
  10157. copy: function ( source, recursive ) {
  10158. if ( recursive === undefined ) recursive = true;
  10159. this.name = source.name;
  10160. this.up.copy( source.up );
  10161. this.position.copy( source.position );
  10162. this.quaternion.copy( source.quaternion );
  10163. this.scale.copy( source.scale );
  10164. this.matrix.copy( source.matrix );
  10165. this.matrixWorld.copy( source.matrixWorld );
  10166. this.matrixAutoUpdate = source.matrixAutoUpdate;
  10167. this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  10168. this.layers.mask = source.layers.mask;
  10169. this.visible = source.visible;
  10170. this.castShadow = source.castShadow;
  10171. this.receiveShadow = source.receiveShadow;
  10172. this.frustumCulled = source.frustumCulled;
  10173. this.renderOrder = source.renderOrder;
  10174. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  10175. if ( recursive === true ) {
  10176. for ( var i = 0; i < source.children.length; i ++ ) {
  10177. var child = source.children[ i ];
  10178. this.add( child.clone() );
  10179. }
  10180. }
  10181. return this;
  10182. }
  10183. } );
  10184. /**
  10185. * @author mrdoob / http://mrdoob.com/
  10186. * @author kile / http://kile.stravaganza.org/
  10187. * @author alteredq / http://alteredqualia.com/
  10188. * @author mikael emtinger / http://gomo.se/
  10189. * @author zz85 / http://www.lab4games.net/zz85/blog
  10190. * @author bhouston / http://clara.io
  10191. */
  10192. var geometryId = 0; // Geometry uses even numbers as Id
  10193. function Geometry() {
  10194. Object.defineProperty( this, 'id', { value: geometryId += 2 } );
  10195. this.uuid = _Math.generateUUID();
  10196. this.name = '';
  10197. this.type = 'Geometry';
  10198. this.vertices = [];
  10199. this.colors = [];
  10200. this.faces = [];
  10201. this.faceVertexUvs = [[]];
  10202. this.morphTargets = [];
  10203. this.morphNormals = [];
  10204. this.skinWeights = [];
  10205. this.skinIndices = [];
  10206. this.lineDistances = [];
  10207. this.boundingBox = null;
  10208. this.boundingSphere = null;
  10209. // update flags
  10210. this.elementsNeedUpdate = false;
  10211. this.verticesNeedUpdate = false;
  10212. this.uvsNeedUpdate = false;
  10213. this.normalsNeedUpdate = false;
  10214. this.colorsNeedUpdate = false;
  10215. this.lineDistancesNeedUpdate = false;
  10216. this.groupsNeedUpdate = false;
  10217. }
  10218. Geometry.prototype = Object.assign( Object.create( EventDispatcher.prototype ), {
  10219. constructor: Geometry,
  10220. isGeometry: true,
  10221. applyMatrix: function ( matrix ) {
  10222. var normalMatrix = new Matrix3().getNormalMatrix( matrix );
  10223. for ( var i = 0, il = this.vertices.length; i < il; i ++ ) {
  10224. var vertex = this.vertices[ i ];
  10225. vertex.applyMatrix4( matrix );
  10226. }
  10227. for ( var i = 0, il = this.faces.length; i < il; i ++ ) {
  10228. var face = this.faces[ i ];
  10229. face.normal.applyMatrix3( normalMatrix ).normalize();
  10230. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  10231. face.vertexNormals[ j ].applyMatrix3( normalMatrix ).normalize();
  10232. }
  10233. }
  10234. if ( this.boundingBox !== null ) {
  10235. this.computeBoundingBox();
  10236. }
  10237. if ( this.boundingSphere !== null ) {
  10238. this.computeBoundingSphere();
  10239. }
  10240. this.verticesNeedUpdate = true;
  10241. this.normalsNeedUpdate = true;
  10242. return this;
  10243. },
  10244. rotateX: function () {
  10245. // rotate geometry around world x-axis
  10246. var m1 = new Matrix4();
  10247. return function rotateX( angle ) {
  10248. m1.makeRotationX( angle );
  10249. this.applyMatrix( m1 );
  10250. return this;
  10251. };
  10252. }(),
  10253. rotateY: function () {
  10254. // rotate geometry around world y-axis
  10255. var m1 = new Matrix4();
  10256. return function rotateY( angle ) {
  10257. m1.makeRotationY( angle );
  10258. this.applyMatrix( m1 );
  10259. return this;
  10260. };
  10261. }(),
  10262. rotateZ: function () {
  10263. // rotate geometry around world z-axis
  10264. var m1 = new Matrix4();
  10265. return function rotateZ( angle ) {
  10266. m1.makeRotationZ( angle );
  10267. this.applyMatrix( m1 );
  10268. return this;
  10269. };
  10270. }(),
  10271. translate: function () {
  10272. // translate geometry
  10273. var m1 = new Matrix4();
  10274. return function translate( x, y, z ) {
  10275. m1.makeTranslation( x, y, z );
  10276. this.applyMatrix( m1 );
  10277. return this;
  10278. };
  10279. }(),
  10280. scale: function () {
  10281. // scale geometry
  10282. var m1 = new Matrix4();
  10283. return function scale( x, y, z ) {
  10284. m1.makeScale( x, y, z );
  10285. this.applyMatrix( m1 );
  10286. return this;
  10287. };
  10288. }(),
  10289. lookAt: function () {
  10290. var obj = new Object3D();
  10291. return function lookAt( vector ) {
  10292. obj.lookAt( vector );
  10293. obj.updateMatrix();
  10294. this.applyMatrix( obj.matrix );
  10295. };
  10296. }(),
  10297. fromBufferGeometry: function ( geometry ) {
  10298. var scope = this;
  10299. var indices = geometry.index !== null ? geometry.index.array : undefined;
  10300. var attributes = geometry.attributes;
  10301. var positions = attributes.position.array;
  10302. var normals = attributes.normal !== undefined ? attributes.normal.array : undefined;
  10303. var colors = attributes.color !== undefined ? attributes.color.array : undefined;
  10304. var uvs = attributes.uv !== undefined ? attributes.uv.array : undefined;
  10305. var uvs2 = attributes.uv2 !== undefined ? attributes.uv2.array : undefined;
  10306. if ( uvs2 !== undefined ) this.faceVertexUvs[ 1 ] = [];
  10307. for ( var i = 0, j = 0; i < positions.length; i += 3, j += 2 ) {
  10308. scope.vertices.push( new Vector3().fromArray( positions, i ) );
  10309. if ( colors !== undefined ) {
  10310. scope.colors.push( new Color().fromArray( colors, i ) );
  10311. }
  10312. }
  10313. function addFace( a, b, c, materialIndex ) {
  10314. var vertexColors = ( colors === undefined ) ? [] : [
  10315. scope.colors[ a ].clone(),
  10316. scope.colors[ b ].clone(),
  10317. scope.colors[ c ].clone() ];
  10318. var vertexNormals = ( normals === undefined ) ? [] : [
  10319. new Vector3().fromArray( normals, a * 3 ),
  10320. new Vector3().fromArray( normals, b * 3 ),
  10321. new Vector3().fromArray( normals, c * 3 )
  10322. ];
  10323. var face = new Face3( a, b, c, vertexNormals, vertexColors, materialIndex );
  10324. scope.faces.push( face );
  10325. if ( uvs !== undefined ) {
  10326. scope.faceVertexUvs[ 0 ].push( [
  10327. new Vector2().fromArray( uvs, a * 2 ),
  10328. new Vector2().fromArray( uvs, b * 2 ),
  10329. new Vector2().fromArray( uvs, c * 2 )
  10330. ] );
  10331. }
  10332. if ( uvs2 !== undefined ) {
  10333. scope.faceVertexUvs[ 1 ].push( [
  10334. new Vector2().fromArray( uvs2, a * 2 ),
  10335. new Vector2().fromArray( uvs2, b * 2 ),
  10336. new Vector2().fromArray( uvs2, c * 2 )
  10337. ] );
  10338. }
  10339. }
  10340. var groups = geometry.groups;
  10341. if ( groups.length > 0 ) {
  10342. for ( var i = 0; i < groups.length; i ++ ) {
  10343. var group = groups[ i ];
  10344. var start = group.start;
  10345. var count = group.count;
  10346. for ( var j = start, jl = start + count; j < jl; j += 3 ) {
  10347. if ( indices !== undefined ) {
  10348. addFace( indices[ j ], indices[ j + 1 ], indices[ j + 2 ], group.materialIndex );
  10349. } else {
  10350. addFace( j, j + 1, j + 2, group.materialIndex );
  10351. }
  10352. }
  10353. }
  10354. } else {
  10355. if ( indices !== undefined ) {
  10356. for ( var i = 0; i < indices.length; i += 3 ) {
  10357. addFace( indices[ i ], indices[ i + 1 ], indices[ i + 2 ] );
  10358. }
  10359. } else {
  10360. for ( var i = 0; i < positions.length / 3; i += 3 ) {
  10361. addFace( i, i + 1, i + 2 );
  10362. }
  10363. }
  10364. }
  10365. this.computeFaceNormals();
  10366. if ( geometry.boundingBox !== null ) {
  10367. this.boundingBox = geometry.boundingBox.clone();
  10368. }
  10369. if ( geometry.boundingSphere !== null ) {
  10370. this.boundingSphere = geometry.boundingSphere.clone();
  10371. }
  10372. return this;
  10373. },
  10374. center: function () {
  10375. var offset = new Vector3();
  10376. return function center() {
  10377. this.computeBoundingBox();
  10378. this.boundingBox.getCenter( offset ).negate();
  10379. this.translate( offset.x, offset.y, offset.z );
  10380. return this;
  10381. };
  10382. }(),
  10383. normalize: function () {
  10384. this.computeBoundingSphere();
  10385. var center = this.boundingSphere.center;
  10386. var radius = this.boundingSphere.radius;
  10387. var s = radius === 0 ? 1 : 1.0 / radius;
  10388. var matrix = new Matrix4();
  10389. matrix.set(
  10390. s, 0, 0, - s * center.x,
  10391. 0, s, 0, - s * center.y,
  10392. 0, 0, s, - s * center.z,
  10393. 0, 0, 0, 1
  10394. );
  10395. this.applyMatrix( matrix );
  10396. return this;
  10397. },
  10398. computeFaceNormals: function () {
  10399. var cb = new Vector3(), ab = new Vector3();
  10400. for ( var f = 0, fl = this.faces.length; f < fl; f ++ ) {
  10401. var face = this.faces[ f ];
  10402. var vA = this.vertices[ face.a ];
  10403. var vB = this.vertices[ face.b ];
  10404. var vC = this.vertices[ face.c ];
  10405. cb.subVectors( vC, vB );
  10406. ab.subVectors( vA, vB );
  10407. cb.cross( ab );
  10408. cb.normalize();
  10409. face.normal.copy( cb );
  10410. }
  10411. },
  10412. computeVertexNormals: function ( areaWeighted ) {
  10413. if ( areaWeighted === undefined ) areaWeighted = true;
  10414. var v, vl, f, fl, face, vertices;
  10415. vertices = new Array( this.vertices.length );
  10416. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  10417. vertices[ v ] = new Vector3();
  10418. }
  10419. if ( areaWeighted ) {
  10420. // vertex normals weighted by triangle areas
  10421. // http://www.iquilezles.org/www/articles/normals/normals.htm
  10422. var vA, vB, vC;
  10423. var cb = new Vector3(), ab = new Vector3();
  10424. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  10425. face = this.faces[ f ];
  10426. vA = this.vertices[ face.a ];
  10427. vB = this.vertices[ face.b ];
  10428. vC = this.vertices[ face.c ];
  10429. cb.subVectors( vC, vB );
  10430. ab.subVectors( vA, vB );
  10431. cb.cross( ab );
  10432. vertices[ face.a ].add( cb );
  10433. vertices[ face.b ].add( cb );
  10434. vertices[ face.c ].add( cb );
  10435. }
  10436. } else {
  10437. this.computeFaceNormals();
  10438. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  10439. face = this.faces[ f ];
  10440. vertices[ face.a ].add( face.normal );
  10441. vertices[ face.b ].add( face.normal );
  10442. vertices[ face.c ].add( face.normal );
  10443. }
  10444. }
  10445. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  10446. vertices[ v ].normalize();
  10447. }
  10448. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  10449. face = this.faces[ f ];
  10450. var vertexNormals = face.vertexNormals;
  10451. if ( vertexNormals.length === 3 ) {
  10452. vertexNormals[ 0 ].copy( vertices[ face.a ] );
  10453. vertexNormals[ 1 ].copy( vertices[ face.b ] );
  10454. vertexNormals[ 2 ].copy( vertices[ face.c ] );
  10455. } else {
  10456. vertexNormals[ 0 ] = vertices[ face.a ].clone();
  10457. vertexNormals[ 1 ] = vertices[ face.b ].clone();
  10458. vertexNormals[ 2 ] = vertices[ face.c ].clone();
  10459. }
  10460. }
  10461. if ( this.faces.length > 0 ) {
  10462. this.normalsNeedUpdate = true;
  10463. }
  10464. },
  10465. computeFlatVertexNormals: function () {
  10466. var f, fl, face;
  10467. this.computeFaceNormals();
  10468. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  10469. face = this.faces[ f ];
  10470. var vertexNormals = face.vertexNormals;
  10471. if ( vertexNormals.length === 3 ) {
  10472. vertexNormals[ 0 ].copy( face.normal );
  10473. vertexNormals[ 1 ].copy( face.normal );
  10474. vertexNormals[ 2 ].copy( face.normal );
  10475. } else {
  10476. vertexNormals[ 0 ] = face.normal.clone();
  10477. vertexNormals[ 1 ] = face.normal.clone();
  10478. vertexNormals[ 2 ] = face.normal.clone();
  10479. }
  10480. }
  10481. if ( this.faces.length > 0 ) {
  10482. this.normalsNeedUpdate = true;
  10483. }
  10484. },
  10485. computeMorphNormals: function () {
  10486. var i, il, f, fl, face;
  10487. // save original normals
  10488. // - create temp variables on first access
  10489. // otherwise just copy (for faster repeated calls)
  10490. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  10491. face = this.faces[ f ];
  10492. if ( ! face.__originalFaceNormal ) {
  10493. face.__originalFaceNormal = face.normal.clone();
  10494. } else {
  10495. face.__originalFaceNormal.copy( face.normal );
  10496. }
  10497. if ( ! face.__originalVertexNormals ) face.__originalVertexNormals = [];
  10498. for ( i = 0, il = face.vertexNormals.length; i < il; i ++ ) {
  10499. if ( ! face.__originalVertexNormals[ i ] ) {
  10500. face.__originalVertexNormals[ i ] = face.vertexNormals[ i ].clone();
  10501. } else {
  10502. face.__originalVertexNormals[ i ].copy( face.vertexNormals[ i ] );
  10503. }
  10504. }
  10505. }
  10506. // use temp geometry to compute face and vertex normals for each morph
  10507. var tmpGeo = new Geometry();
  10508. tmpGeo.faces = this.faces;
  10509. for ( i = 0, il = this.morphTargets.length; i < il; i ++ ) {
  10510. // create on first access
  10511. if ( ! this.morphNormals[ i ] ) {
  10512. this.morphNormals[ i ] = {};
  10513. this.morphNormals[ i ].faceNormals = [];
  10514. this.morphNormals[ i ].vertexNormals = [];
  10515. var dstNormalsFace = this.morphNormals[ i ].faceNormals;
  10516. var dstNormalsVertex = this.morphNormals[ i ].vertexNormals;
  10517. var faceNormal, vertexNormals;
  10518. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  10519. faceNormal = new Vector3();
  10520. vertexNormals = { a: new Vector3(), b: new Vector3(), c: new Vector3() };
  10521. dstNormalsFace.push( faceNormal );
  10522. dstNormalsVertex.push( vertexNormals );
  10523. }
  10524. }
  10525. var morphNormals = this.morphNormals[ i ];
  10526. // set vertices to morph target
  10527. tmpGeo.vertices = this.morphTargets[ i ].vertices;
  10528. // compute morph normals
  10529. tmpGeo.computeFaceNormals();
  10530. tmpGeo.computeVertexNormals();
  10531. // store morph normals
  10532. var faceNormal, vertexNormals;
  10533. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  10534. face = this.faces[ f ];
  10535. faceNormal = morphNormals.faceNormals[ f ];
  10536. vertexNormals = morphNormals.vertexNormals[ f ];
  10537. faceNormal.copy( face.normal );
  10538. vertexNormals.a.copy( face.vertexNormals[ 0 ] );
  10539. vertexNormals.b.copy( face.vertexNormals[ 1 ] );
  10540. vertexNormals.c.copy( face.vertexNormals[ 2 ] );
  10541. }
  10542. }
  10543. // restore original normals
  10544. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  10545. face = this.faces[ f ];
  10546. face.normal = face.__originalFaceNormal;
  10547. face.vertexNormals = face.__originalVertexNormals;
  10548. }
  10549. },
  10550. computeBoundingBox: function () {
  10551. if ( this.boundingBox === null ) {
  10552. this.boundingBox = new Box3();
  10553. }
  10554. this.boundingBox.setFromPoints( this.vertices );
  10555. },
  10556. computeBoundingSphere: function () {
  10557. if ( this.boundingSphere === null ) {
  10558. this.boundingSphere = new Sphere();
  10559. }
  10560. this.boundingSphere.setFromPoints( this.vertices );
  10561. },
  10562. merge: function ( geometry, matrix, materialIndexOffset ) {
  10563. if ( ! ( geometry && geometry.isGeometry ) ) {
  10564. console.error( 'THREE.Geometry.merge(): geometry not an instance of THREE.Geometry.', geometry );
  10565. return;
  10566. }
  10567. var normalMatrix,
  10568. vertexOffset = this.vertices.length,
  10569. vertices1 = this.vertices,
  10570. vertices2 = geometry.vertices,
  10571. faces1 = this.faces,
  10572. faces2 = geometry.faces,
  10573. uvs1 = this.faceVertexUvs[ 0 ],
  10574. uvs2 = geometry.faceVertexUvs[ 0 ],
  10575. colors1 = this.colors,
  10576. colors2 = geometry.colors;
  10577. if ( materialIndexOffset === undefined ) materialIndexOffset = 0;
  10578. if ( matrix !== undefined ) {
  10579. normalMatrix = new Matrix3().getNormalMatrix( matrix );
  10580. }
  10581. // vertices
  10582. for ( var i = 0, il = vertices2.length; i < il; i ++ ) {
  10583. var vertex = vertices2[ i ];
  10584. var vertexCopy = vertex.clone();
  10585. if ( matrix !== undefined ) vertexCopy.applyMatrix4( matrix );
  10586. vertices1.push( vertexCopy );
  10587. }
  10588. // colors
  10589. for ( var i = 0, il = colors2.length; i < il; i ++ ) {
  10590. colors1.push( colors2[ i ].clone() );
  10591. }
  10592. // faces
  10593. for ( i = 0, il = faces2.length; i < il; i ++ ) {
  10594. var face = faces2[ i ], faceCopy, normal, color,
  10595. faceVertexNormals = face.vertexNormals,
  10596. faceVertexColors = face.vertexColors;
  10597. faceCopy = new Face3( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset );
  10598. faceCopy.normal.copy( face.normal );
  10599. if ( normalMatrix !== undefined ) {
  10600. faceCopy.normal.applyMatrix3( normalMatrix ).normalize();
  10601. }
  10602. for ( var j = 0, jl = faceVertexNormals.length; j < jl; j ++ ) {
  10603. normal = faceVertexNormals[ j ].clone();
  10604. if ( normalMatrix !== undefined ) {
  10605. normal.applyMatrix3( normalMatrix ).normalize();
  10606. }
  10607. faceCopy.vertexNormals.push( normal );
  10608. }
  10609. faceCopy.color.copy( face.color );
  10610. for ( var j = 0, jl = faceVertexColors.length; j < jl; j ++ ) {
  10611. color = faceVertexColors[ j ];
  10612. faceCopy.vertexColors.push( color.clone() );
  10613. }
  10614. faceCopy.materialIndex = face.materialIndex + materialIndexOffset;
  10615. faces1.push( faceCopy );
  10616. }
  10617. // uvs
  10618. for ( i = 0, il = uvs2.length; i < il; i ++ ) {
  10619. var uv = uvs2[ i ], uvCopy = [];
  10620. if ( uv === undefined ) {
  10621. continue;
  10622. }
  10623. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  10624. uvCopy.push( uv[ j ].clone() );
  10625. }
  10626. uvs1.push( uvCopy );
  10627. }
  10628. },
  10629. mergeMesh: function ( mesh ) {
  10630. if ( ! ( mesh && mesh.isMesh ) ) {
  10631. console.error( 'THREE.Geometry.mergeMesh(): mesh not an instance of THREE.Mesh.', mesh );
  10632. return;
  10633. }
  10634. if ( mesh.matrixAutoUpdate ) mesh.updateMatrix();
  10635. this.merge( mesh.geometry, mesh.matrix );
  10636. },
  10637. /*
  10638. * Checks for duplicate vertices with hashmap.
  10639. * Duplicated vertices are removed
  10640. * and faces' vertices are updated.
  10641. */
  10642. mergeVertices: function () {
  10643. var verticesMap = {}; // Hashmap for looking up vertices by position coordinates (and making sure they are unique)
  10644. var unique = [], changes = [];
  10645. var v, key;
  10646. var precisionPoints = 4; // number of decimal points, e.g. 4 for epsilon of 0.0001
  10647. var precision = Math.pow( 10, precisionPoints );
  10648. var i, il, face;
  10649. var indices, j, jl;
  10650. for ( i = 0, il = this.vertices.length; i < il; i ++ ) {
  10651. v = this.vertices[ i ];
  10652. key = Math.round( v.x * precision ) + '_' + Math.round( v.y * precision ) + '_' + Math.round( v.z * precision );
  10653. if ( verticesMap[ key ] === undefined ) {
  10654. verticesMap[ key ] = i;
  10655. unique.push( this.vertices[ i ] );
  10656. changes[ i ] = unique.length - 1;
  10657. } else {
  10658. //console.log('Duplicate vertex found. ', i, ' could be using ', verticesMap[key]);
  10659. changes[ i ] = changes[ verticesMap[ key ] ];
  10660. }
  10661. }
  10662. // if faces are completely degenerate after merging vertices, we
  10663. // have to remove them from the geometry.
  10664. var faceIndicesToRemove = [];
  10665. for ( i = 0, il = this.faces.length; i < il; i ++ ) {
  10666. face = this.faces[ i ];
  10667. face.a = changes[ face.a ];
  10668. face.b = changes[ face.b ];
  10669. face.c = changes[ face.c ];
  10670. indices = [ face.a, face.b, face.c ];
  10671. // if any duplicate vertices are found in a Face3
  10672. // we have to remove the face as nothing can be saved
  10673. for ( var n = 0; n < 3; n ++ ) {
  10674. if ( indices[ n ] === indices[ ( n + 1 ) % 3 ] ) {
  10675. faceIndicesToRemove.push( i );
  10676. break;
  10677. }
  10678. }
  10679. }
  10680. for ( i = faceIndicesToRemove.length - 1; i >= 0; i -- ) {
  10681. var idx = faceIndicesToRemove[ i ];
  10682. this.faces.splice( idx, 1 );
  10683. for ( j = 0, jl = this.faceVertexUvs.length; j < jl; j ++ ) {
  10684. this.faceVertexUvs[ j ].splice( idx, 1 );
  10685. }
  10686. }
  10687. // Use unique set of vertices
  10688. var diff = this.vertices.length - unique.length;
  10689. this.vertices = unique;
  10690. return diff;
  10691. },
  10692. setFromPoints: function ( points ) {
  10693. this.vertices = [];
  10694. for ( var i = 0, l = points.length; i < l; i ++ ) {
  10695. var point = points[ i ];
  10696. this.vertices.push( new Vector3( point.x, point.y, point.z || 0 ) );
  10697. }
  10698. return this;
  10699. },
  10700. sortFacesByMaterialIndex: function () {
  10701. var faces = this.faces;
  10702. var length = faces.length;
  10703. // tag faces
  10704. for ( var i = 0; i < length; i ++ ) {
  10705. faces[ i ]._id = i;
  10706. }
  10707. // sort faces
  10708. function materialIndexSort( a, b ) {
  10709. return a.materialIndex - b.materialIndex;
  10710. }
  10711. faces.sort( materialIndexSort );
  10712. // sort uvs
  10713. var uvs1 = this.faceVertexUvs[ 0 ];
  10714. var uvs2 = this.faceVertexUvs[ 1 ];
  10715. var newUvs1, newUvs2;
  10716. if ( uvs1 && uvs1.length === length ) newUvs1 = [];
  10717. if ( uvs2 && uvs2.length === length ) newUvs2 = [];
  10718. for ( var i = 0; i < length; i ++ ) {
  10719. var id = faces[ i ]._id;
  10720. if ( newUvs1 ) newUvs1.push( uvs1[ id ] );
  10721. if ( newUvs2 ) newUvs2.push( uvs2[ id ] );
  10722. }
  10723. if ( newUvs1 ) this.faceVertexUvs[ 0 ] = newUvs1;
  10724. if ( newUvs2 ) this.faceVertexUvs[ 1 ] = newUvs2;
  10725. },
  10726. toJSON: function () {
  10727. var data = {
  10728. metadata: {
  10729. version: 4.5,
  10730. type: 'Geometry',
  10731. generator: 'Geometry.toJSON'
  10732. }
  10733. };
  10734. // standard Geometry serialization
  10735. data.uuid = this.uuid;
  10736. data.type = this.type;
  10737. if ( this.name !== '' ) data.name = this.name;
  10738. if ( this.parameters !== undefined ) {
  10739. var parameters = this.parameters;
  10740. for ( var key in parameters ) {
  10741. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  10742. }
  10743. return data;
  10744. }
  10745. var vertices = [];
  10746. for ( var i = 0; i < this.vertices.length; i ++ ) {
  10747. var vertex = this.vertices[ i ];
  10748. vertices.push( vertex.x, vertex.y, vertex.z );
  10749. }
  10750. var faces = [];
  10751. var normals = [];
  10752. var normalsHash = {};
  10753. var colors = [];
  10754. var colorsHash = {};
  10755. var uvs = [];
  10756. var uvsHash = {};
  10757. for ( var i = 0; i < this.faces.length; i ++ ) {
  10758. var face = this.faces[ i ];
  10759. var hasMaterial = true;
  10760. var hasFaceUv = false; // deprecated
  10761. var hasFaceVertexUv = this.faceVertexUvs[ 0 ][ i ] !== undefined;
  10762. var hasFaceNormal = face.normal.length() > 0;
  10763. var hasFaceVertexNormal = face.vertexNormals.length > 0;
  10764. var hasFaceColor = face.color.r !== 1 || face.color.g !== 1 || face.color.b !== 1;
  10765. var hasFaceVertexColor = face.vertexColors.length > 0;
  10766. var faceType = 0;
  10767. faceType = setBit( faceType, 0, 0 ); // isQuad
  10768. faceType = setBit( faceType, 1, hasMaterial );
  10769. faceType = setBit( faceType, 2, hasFaceUv );
  10770. faceType = setBit( faceType, 3, hasFaceVertexUv );
  10771. faceType = setBit( faceType, 4, hasFaceNormal );
  10772. faceType = setBit( faceType, 5, hasFaceVertexNormal );
  10773. faceType = setBit( faceType, 6, hasFaceColor );
  10774. faceType = setBit( faceType, 7, hasFaceVertexColor );
  10775. faces.push( faceType );
  10776. faces.push( face.a, face.b, face.c );
  10777. faces.push( face.materialIndex );
  10778. if ( hasFaceVertexUv ) {
  10779. var faceVertexUvs = this.faceVertexUvs[ 0 ][ i ];
  10780. faces.push(
  10781. getUvIndex( faceVertexUvs[ 0 ] ),
  10782. getUvIndex( faceVertexUvs[ 1 ] ),
  10783. getUvIndex( faceVertexUvs[ 2 ] )
  10784. );
  10785. }
  10786. if ( hasFaceNormal ) {
  10787. faces.push( getNormalIndex( face.normal ) );
  10788. }
  10789. if ( hasFaceVertexNormal ) {
  10790. var vertexNormals = face.vertexNormals;
  10791. faces.push(
  10792. getNormalIndex( vertexNormals[ 0 ] ),
  10793. getNormalIndex( vertexNormals[ 1 ] ),
  10794. getNormalIndex( vertexNormals[ 2 ] )
  10795. );
  10796. }
  10797. if ( hasFaceColor ) {
  10798. faces.push( getColorIndex( face.color ) );
  10799. }
  10800. if ( hasFaceVertexColor ) {
  10801. var vertexColors = face.vertexColors;
  10802. faces.push(
  10803. getColorIndex( vertexColors[ 0 ] ),
  10804. getColorIndex( vertexColors[ 1 ] ),
  10805. getColorIndex( vertexColors[ 2 ] )
  10806. );
  10807. }
  10808. }
  10809. function setBit( value, position, enabled ) {
  10810. return enabled ? value | ( 1 << position ) : value & ( ~ ( 1 << position ) );
  10811. }
  10812. function getNormalIndex( normal ) {
  10813. var hash = normal.x.toString() + normal.y.toString() + normal.z.toString();
  10814. if ( normalsHash[ hash ] !== undefined ) {
  10815. return normalsHash[ hash ];
  10816. }
  10817. normalsHash[ hash ] = normals.length / 3;
  10818. normals.push( normal.x, normal.y, normal.z );
  10819. return normalsHash[ hash ];
  10820. }
  10821. function getColorIndex( color ) {
  10822. var hash = color.r.toString() + color.g.toString() + color.b.toString();
  10823. if ( colorsHash[ hash ] !== undefined ) {
  10824. return colorsHash[ hash ];
  10825. }
  10826. colorsHash[ hash ] = colors.length;
  10827. colors.push( color.getHex() );
  10828. return colorsHash[ hash ];
  10829. }
  10830. function getUvIndex( uv ) {
  10831. var hash = uv.x.toString() + uv.y.toString();
  10832. if ( uvsHash[ hash ] !== undefined ) {
  10833. return uvsHash[ hash ];
  10834. }
  10835. uvsHash[ hash ] = uvs.length / 2;
  10836. uvs.push( uv.x, uv.y );
  10837. return uvsHash[ hash ];
  10838. }
  10839. data.data = {};
  10840. data.data.vertices = vertices;
  10841. data.data.normals = normals;
  10842. if ( colors.length > 0 ) data.data.colors = colors;
  10843. if ( uvs.length > 0 ) data.data.uvs = [ uvs ]; // temporal backward compatibility
  10844. data.data.faces = faces;
  10845. return data;
  10846. },
  10847. clone: function () {
  10848. /*
  10849. // Handle primitives
  10850. var parameters = this.parameters;
  10851. if ( parameters !== undefined ) {
  10852. var values = [];
  10853. for ( var key in parameters ) {
  10854. values.push( parameters[ key ] );
  10855. }
  10856. var geometry = Object.create( this.constructor.prototype );
  10857. this.constructor.apply( geometry, values );
  10858. return geometry;
  10859. }
  10860. return new this.constructor().copy( this );
  10861. */
  10862. return new Geometry().copy( this );
  10863. },
  10864. copy: function ( source ) {
  10865. var i, il, j, jl, k, kl;
  10866. // reset
  10867. this.vertices = [];
  10868. this.colors = [];
  10869. this.faces = [];
  10870. this.faceVertexUvs = [[]];
  10871. this.morphTargets = [];
  10872. this.morphNormals = [];
  10873. this.skinWeights = [];
  10874. this.skinIndices = [];
  10875. this.lineDistances = [];
  10876. this.boundingBox = null;
  10877. this.boundingSphere = null;
  10878. // name
  10879. this.name = source.name;
  10880. // vertices
  10881. var vertices = source.vertices;
  10882. for ( i = 0, il = vertices.length; i < il; i ++ ) {
  10883. this.vertices.push( vertices[ i ].clone() );
  10884. }
  10885. // colors
  10886. var colors = source.colors;
  10887. for ( i = 0, il = colors.length; i < il; i ++ ) {
  10888. this.colors.push( colors[ i ].clone() );
  10889. }
  10890. // faces
  10891. var faces = source.faces;
  10892. for ( i = 0, il = faces.length; i < il; i ++ ) {
  10893. this.faces.push( faces[ i ].clone() );
  10894. }
  10895. // face vertex uvs
  10896. for ( i = 0, il = source.faceVertexUvs.length; i < il; i ++ ) {
  10897. var faceVertexUvs = source.faceVertexUvs[ i ];
  10898. if ( this.faceVertexUvs[ i ] === undefined ) {
  10899. this.faceVertexUvs[ i ] = [];
  10900. }
  10901. for ( j = 0, jl = faceVertexUvs.length; j < jl; j ++ ) {
  10902. var uvs = faceVertexUvs[ j ], uvsCopy = [];
  10903. for ( k = 0, kl = uvs.length; k < kl; k ++ ) {
  10904. var uv = uvs[ k ];
  10905. uvsCopy.push( uv.clone() );
  10906. }
  10907. this.faceVertexUvs[ i ].push( uvsCopy );
  10908. }
  10909. }
  10910. // morph targets
  10911. var morphTargets = source.morphTargets;
  10912. for ( i = 0, il = morphTargets.length; i < il; i ++ ) {
  10913. var morphTarget = {};
  10914. morphTarget.name = morphTargets[ i ].name;
  10915. // vertices
  10916. if ( morphTargets[ i ].vertices !== undefined ) {
  10917. morphTarget.vertices = [];
  10918. for ( j = 0, jl = morphTargets[ i ].vertices.length; j < jl; j ++ ) {
  10919. morphTarget.vertices.push( morphTargets[ i ].vertices[ j ].clone() );
  10920. }
  10921. }
  10922. // normals
  10923. if ( morphTargets[ i ].normals !== undefined ) {
  10924. morphTarget.normals = [];
  10925. for ( j = 0, jl = morphTargets[ i ].normals.length; j < jl; j ++ ) {
  10926. morphTarget.normals.push( morphTargets[ i ].normals[ j ].clone() );
  10927. }
  10928. }
  10929. this.morphTargets.push( morphTarget );
  10930. }
  10931. // morph normals
  10932. var morphNormals = source.morphNormals;
  10933. for ( i = 0, il = morphNormals.length; i < il; i ++ ) {
  10934. var morphNormal = {};
  10935. // vertex normals
  10936. if ( morphNormals[ i ].vertexNormals !== undefined ) {
  10937. morphNormal.vertexNormals = [];
  10938. for ( j = 0, jl = morphNormals[ i ].vertexNormals.length; j < jl; j ++ ) {
  10939. var srcVertexNormal = morphNormals[ i ].vertexNormals[ j ];
  10940. var destVertexNormal = {};
  10941. destVertexNormal.a = srcVertexNormal.a.clone();
  10942. destVertexNormal.b = srcVertexNormal.b.clone();
  10943. destVertexNormal.c = srcVertexNormal.c.clone();
  10944. morphNormal.vertexNormals.push( destVertexNormal );
  10945. }
  10946. }
  10947. // face normals
  10948. if ( morphNormals[ i ].faceNormals !== undefined ) {
  10949. morphNormal.faceNormals = [];
  10950. for ( j = 0, jl = morphNormals[ i ].faceNormals.length; j < jl; j ++ ) {
  10951. morphNormal.faceNormals.push( morphNormals[ i ].faceNormals[ j ].clone() );
  10952. }
  10953. }
  10954. this.morphNormals.push( morphNormal );
  10955. }
  10956. // skin weights
  10957. var skinWeights = source.skinWeights;
  10958. for ( i = 0, il = skinWeights.length; i < il; i ++ ) {
  10959. this.skinWeights.push( skinWeights[ i ].clone() );
  10960. }
  10961. // skin indices
  10962. var skinIndices = source.skinIndices;
  10963. for ( i = 0, il = skinIndices.length; i < il; i ++ ) {
  10964. this.skinIndices.push( skinIndices[ i ].clone() );
  10965. }
  10966. // line distances
  10967. var lineDistances = source.lineDistances;
  10968. for ( i = 0, il = lineDistances.length; i < il; i ++ ) {
  10969. this.lineDistances.push( lineDistances[ i ] );
  10970. }
  10971. // bounding box
  10972. var boundingBox = source.boundingBox;
  10973. if ( boundingBox !== null ) {
  10974. this.boundingBox = boundingBox.clone();
  10975. }
  10976. // bounding sphere
  10977. var boundingSphere = source.boundingSphere;
  10978. if ( boundingSphere !== null ) {
  10979. this.boundingSphere = boundingSphere.clone();
  10980. }
  10981. // update flags
  10982. this.elementsNeedUpdate = source.elementsNeedUpdate;
  10983. this.verticesNeedUpdate = source.verticesNeedUpdate;
  10984. this.uvsNeedUpdate = source.uvsNeedUpdate;
  10985. this.normalsNeedUpdate = source.normalsNeedUpdate;
  10986. this.colorsNeedUpdate = source.colorsNeedUpdate;
  10987. this.lineDistancesNeedUpdate = source.lineDistancesNeedUpdate;
  10988. this.groupsNeedUpdate = source.groupsNeedUpdate;
  10989. return this;
  10990. },
  10991. dispose: function () {
  10992. this.dispatchEvent( { type: 'dispose' } );
  10993. }
  10994. } );
  10995. /**
  10996. * @author mrdoob / http://mrdoob.com/
  10997. */
  10998. function BufferAttribute( array, itemSize, normalized ) {
  10999. if ( Array.isArray( array ) ) {
  11000. throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );
  11001. }
  11002. this.name = '';
  11003. this.array = array;
  11004. this.itemSize = itemSize;
  11005. this.count = array !== undefined ? array.length / itemSize : 0;
  11006. this.normalized = normalized === true;
  11007. this.dynamic = false;
  11008. this.updateRange = { offset: 0, count: - 1 };
  11009. this.version = 0;
  11010. }
  11011. Object.defineProperty( BufferAttribute.prototype, 'needsUpdate', {
  11012. set: function ( value ) {
  11013. if ( value === true ) this.version ++;
  11014. }
  11015. } );
  11016. Object.assign( BufferAttribute.prototype, {
  11017. isBufferAttribute: true,
  11018. onUploadCallback: function () {},
  11019. setArray: function ( array ) {
  11020. if ( Array.isArray( array ) ) {
  11021. throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );
  11022. }
  11023. this.count = array !== undefined ? array.length / this.itemSize : 0;
  11024. this.array = array;
  11025. return this;
  11026. },
  11027. setDynamic: function ( value ) {
  11028. this.dynamic = value;
  11029. return this;
  11030. },
  11031. copy: function ( source ) {
  11032. this.name = source.name;
  11033. this.array = new source.array.constructor( source.array );
  11034. this.itemSize = source.itemSize;
  11035. this.count = source.count;
  11036. this.normalized = source.normalized;
  11037. this.dynamic = source.dynamic;
  11038. return this;
  11039. },
  11040. copyAt: function ( index1, attribute, index2 ) {
  11041. index1 *= this.itemSize;
  11042. index2 *= attribute.itemSize;
  11043. for ( var i = 0, l = this.itemSize; i < l; i ++ ) {
  11044. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  11045. }
  11046. return this;
  11047. },
  11048. copyArray: function ( array ) {
  11049. this.array.set( array );
  11050. return this;
  11051. },
  11052. copyColorsArray: function ( colors ) {
  11053. var array = this.array, offset = 0;
  11054. for ( var i = 0, l = colors.length; i < l; i ++ ) {
  11055. var color = colors[ i ];
  11056. if ( color === undefined ) {
  11057. console.warn( 'THREE.BufferAttribute.copyColorsArray(): color is undefined', i );
  11058. color = new Color();
  11059. }
  11060. array[ offset ++ ] = color.r;
  11061. array[ offset ++ ] = color.g;
  11062. array[ offset ++ ] = color.b;
  11063. }
  11064. return this;
  11065. },
  11066. copyVector2sArray: function ( vectors ) {
  11067. var array = this.array, offset = 0;
  11068. for ( var i = 0, l = vectors.length; i < l; i ++ ) {
  11069. var vector = vectors[ i ];
  11070. if ( vector === undefined ) {
  11071. console.warn( 'THREE.BufferAttribute.copyVector2sArray(): vector is undefined', i );
  11072. vector = new Vector2();
  11073. }
  11074. array[ offset ++ ] = vector.x;
  11075. array[ offset ++ ] = vector.y;
  11076. }
  11077. return this;
  11078. },
  11079. copyVector3sArray: function ( vectors ) {
  11080. var array = this.array, offset = 0;
  11081. for ( var i = 0, l = vectors.length; i < l; i ++ ) {
  11082. var vector = vectors[ i ];
  11083. if ( vector === undefined ) {
  11084. console.warn( 'THREE.BufferAttribute.copyVector3sArray(): vector is undefined', i );
  11085. vector = new Vector3();
  11086. }
  11087. array[ offset ++ ] = vector.x;
  11088. array[ offset ++ ] = vector.y;
  11089. array[ offset ++ ] = vector.z;
  11090. }
  11091. return this;
  11092. },
  11093. copyVector4sArray: function ( vectors ) {
  11094. var array = this.array, offset = 0;
  11095. for ( var i = 0, l = vectors.length; i < l; i ++ ) {
  11096. var vector = vectors[ i ];
  11097. if ( vector === undefined ) {
  11098. console.warn( 'THREE.BufferAttribute.copyVector4sArray(): vector is undefined', i );
  11099. vector = new Vector4();
  11100. }
  11101. array[ offset ++ ] = vector.x;
  11102. array[ offset ++ ] = vector.y;
  11103. array[ offset ++ ] = vector.z;
  11104. array[ offset ++ ] = vector.w;
  11105. }
  11106. return this;
  11107. },
  11108. set: function ( value, offset ) {
  11109. if ( offset === undefined ) offset = 0;
  11110. this.array.set( value, offset );
  11111. return this;
  11112. },
  11113. getX: function ( index ) {
  11114. return this.array[ index * this.itemSize ];
  11115. },
  11116. setX: function ( index, x ) {
  11117. this.array[ index * this.itemSize ] = x;
  11118. return this;
  11119. },
  11120. getY: function ( index ) {
  11121. return this.array[ index * this.itemSize + 1 ];
  11122. },
  11123. setY: function ( index, y ) {
  11124. this.array[ index * this.itemSize + 1 ] = y;
  11125. return this;
  11126. },
  11127. getZ: function ( index ) {
  11128. return this.array[ index * this.itemSize + 2 ];
  11129. },
  11130. setZ: function ( index, z ) {
  11131. this.array[ index * this.itemSize + 2 ] = z;
  11132. return this;
  11133. },
  11134. getW: function ( index ) {
  11135. return this.array[ index * this.itemSize + 3 ];
  11136. },
  11137. setW: function ( index, w ) {
  11138. this.array[ index * this.itemSize + 3 ] = w;
  11139. return this;
  11140. },
  11141. setXY: function ( index, x, y ) {
  11142. index *= this.itemSize;
  11143. this.array[ index + 0 ] = x;
  11144. this.array[ index + 1 ] = y;
  11145. return this;
  11146. },
  11147. setXYZ: function ( index, x, y, z ) {
  11148. index *= this.itemSize;
  11149. this.array[ index + 0 ] = x;
  11150. this.array[ index + 1 ] = y;
  11151. this.array[ index + 2 ] = z;
  11152. return this;
  11153. },
  11154. setXYZW: function ( index, x, y, z, w ) {
  11155. index *= this.itemSize;
  11156. this.array[ index + 0 ] = x;
  11157. this.array[ index + 1 ] = y;
  11158. this.array[ index + 2 ] = z;
  11159. this.array[ index + 3 ] = w;
  11160. return this;
  11161. },
  11162. onUpload: function ( callback ) {
  11163. this.onUploadCallback = callback;
  11164. return this;
  11165. },
  11166. clone: function () {
  11167. return new this.constructor( this.array, this.itemSize ).copy( this );
  11168. }
  11169. } );
  11170. //
  11171. function Int8BufferAttribute( array, itemSize, normalized ) {
  11172. BufferAttribute.call( this, new Int8Array( array ), itemSize, normalized );
  11173. }
  11174. Int8BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  11175. Int8BufferAttribute.prototype.constructor = Int8BufferAttribute;
  11176. function Uint8BufferAttribute( array, itemSize, normalized ) {
  11177. BufferAttribute.call( this, new Uint8Array( array ), itemSize, normalized );
  11178. }
  11179. Uint8BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  11180. Uint8BufferAttribute.prototype.constructor = Uint8BufferAttribute;
  11181. function Uint8ClampedBufferAttribute( array, itemSize, normalized ) {
  11182. BufferAttribute.call( this, new Uint8ClampedArray( array ), itemSize, normalized );
  11183. }
  11184. Uint8ClampedBufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  11185. Uint8ClampedBufferAttribute.prototype.constructor = Uint8ClampedBufferAttribute;
  11186. function Int16BufferAttribute( array, itemSize, normalized ) {
  11187. BufferAttribute.call( this, new Int16Array( array ), itemSize, normalized );
  11188. }
  11189. Int16BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  11190. Int16BufferAttribute.prototype.constructor = Int16BufferAttribute;
  11191. function Uint16BufferAttribute( array, itemSize, normalized ) {
  11192. BufferAttribute.call( this, new Uint16Array( array ), itemSize, normalized );
  11193. }
  11194. Uint16BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  11195. Uint16BufferAttribute.prototype.constructor = Uint16BufferAttribute;
  11196. function Int32BufferAttribute( array, itemSize, normalized ) {
  11197. BufferAttribute.call( this, new Int32Array( array ), itemSize, normalized );
  11198. }
  11199. Int32BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  11200. Int32BufferAttribute.prototype.constructor = Int32BufferAttribute;
  11201. function Uint32BufferAttribute( array, itemSize, normalized ) {
  11202. BufferAttribute.call( this, new Uint32Array( array ), itemSize, normalized );
  11203. }
  11204. Uint32BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  11205. Uint32BufferAttribute.prototype.constructor = Uint32BufferAttribute;
  11206. function Float32BufferAttribute( array, itemSize, normalized ) {
  11207. BufferAttribute.call( this, new Float32Array( array ), itemSize, normalized );
  11208. }
  11209. Float32BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  11210. Float32BufferAttribute.prototype.constructor = Float32BufferAttribute;
  11211. function Float64BufferAttribute( array, itemSize, normalized ) {
  11212. BufferAttribute.call( this, new Float64Array( array ), itemSize, normalized );
  11213. }
  11214. Float64BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  11215. Float64BufferAttribute.prototype.constructor = Float64BufferAttribute;
  11216. /**
  11217. * @author mrdoob / http://mrdoob.com/
  11218. */
  11219. function DirectGeometry() {
  11220. this.vertices = [];
  11221. this.normals = [];
  11222. this.colors = [];
  11223. this.uvs = [];
  11224. this.uvs2 = [];
  11225. this.groups = [];
  11226. this.morphTargets = {};
  11227. this.skinWeights = [];
  11228. this.skinIndices = [];
  11229. // this.lineDistances = [];
  11230. this.boundingBox = null;
  11231. this.boundingSphere = null;
  11232. // update flags
  11233. this.verticesNeedUpdate = false;
  11234. this.normalsNeedUpdate = false;
  11235. this.colorsNeedUpdate = false;
  11236. this.uvsNeedUpdate = false;
  11237. this.groupsNeedUpdate = false;
  11238. }
  11239. Object.assign( DirectGeometry.prototype, {
  11240. computeGroups: function ( geometry ) {
  11241. var group;
  11242. var groups = [];
  11243. var materialIndex = undefined;
  11244. var faces = geometry.faces;
  11245. for ( var i = 0; i < faces.length; i ++ ) {
  11246. var face = faces[ i ];
  11247. // materials
  11248. if ( face.materialIndex !== materialIndex ) {
  11249. materialIndex = face.materialIndex;
  11250. if ( group !== undefined ) {
  11251. group.count = ( i * 3 ) - group.start;
  11252. groups.push( group );
  11253. }
  11254. group = {
  11255. start: i * 3,
  11256. materialIndex: materialIndex
  11257. };
  11258. }
  11259. }
  11260. if ( group !== undefined ) {
  11261. group.count = ( i * 3 ) - group.start;
  11262. groups.push( group );
  11263. }
  11264. this.groups = groups;
  11265. },
  11266. fromGeometry: function ( geometry ) {
  11267. var faces = geometry.faces;
  11268. var vertices = geometry.vertices;
  11269. var faceVertexUvs = geometry.faceVertexUvs;
  11270. var hasFaceVertexUv = faceVertexUvs[ 0 ] && faceVertexUvs[ 0 ].length > 0;
  11271. var hasFaceVertexUv2 = faceVertexUvs[ 1 ] && faceVertexUvs[ 1 ].length > 0;
  11272. // morphs
  11273. var morphTargets = geometry.morphTargets;
  11274. var morphTargetsLength = morphTargets.length;
  11275. var morphTargetsPosition;
  11276. if ( morphTargetsLength > 0 ) {
  11277. morphTargetsPosition = [];
  11278. for ( var i = 0; i < morphTargetsLength; i ++ ) {
  11279. morphTargetsPosition[ i ] = {
  11280. name: morphTargets[ i ].name,
  11281. data: []
  11282. };
  11283. }
  11284. this.morphTargets.position = morphTargetsPosition;
  11285. }
  11286. var morphNormals = geometry.morphNormals;
  11287. var morphNormalsLength = morphNormals.length;
  11288. var morphTargetsNormal;
  11289. if ( morphNormalsLength > 0 ) {
  11290. morphTargetsNormal = [];
  11291. for ( var i = 0; i < morphNormalsLength; i ++ ) {
  11292. morphTargetsNormal[ i ] = {
  11293. name: morphNormals[ i ].name,
  11294. data: []
  11295. };
  11296. }
  11297. this.morphTargets.normal = morphTargetsNormal;
  11298. }
  11299. // skins
  11300. var skinIndices = geometry.skinIndices;
  11301. var skinWeights = geometry.skinWeights;
  11302. var hasSkinIndices = skinIndices.length === vertices.length;
  11303. var hasSkinWeights = skinWeights.length === vertices.length;
  11304. //
  11305. if ( vertices.length > 0 && faces.length === 0 ) {
  11306. console.error( 'THREE.DirectGeometry: Faceless geometries are not supported.' );
  11307. }
  11308. for ( var i = 0; i < faces.length; i ++ ) {
  11309. var face = faces[ i ];
  11310. this.vertices.push( vertices[ face.a ], vertices[ face.b ], vertices[ face.c ] );
  11311. var vertexNormals = face.vertexNormals;
  11312. if ( vertexNormals.length === 3 ) {
  11313. this.normals.push( vertexNormals[ 0 ], vertexNormals[ 1 ], vertexNormals[ 2 ] );
  11314. } else {
  11315. var normal = face.normal;
  11316. this.normals.push( normal, normal, normal );
  11317. }
  11318. var vertexColors = face.vertexColors;
  11319. if ( vertexColors.length === 3 ) {
  11320. this.colors.push( vertexColors[ 0 ], vertexColors[ 1 ], vertexColors[ 2 ] );
  11321. } else {
  11322. var color = face.color;
  11323. this.colors.push( color, color, color );
  11324. }
  11325. if ( hasFaceVertexUv === true ) {
  11326. var vertexUvs = faceVertexUvs[ 0 ][ i ];
  11327. if ( vertexUvs !== undefined ) {
  11328. this.uvs.push( vertexUvs[ 0 ], vertexUvs[ 1 ], vertexUvs[ 2 ] );
  11329. } else {
  11330. console.warn( 'THREE.DirectGeometry.fromGeometry(): Undefined vertexUv ', i );
  11331. this.uvs.push( new Vector2(), new Vector2(), new Vector2() );
  11332. }
  11333. }
  11334. if ( hasFaceVertexUv2 === true ) {
  11335. var vertexUvs = faceVertexUvs[ 1 ][ i ];
  11336. if ( vertexUvs !== undefined ) {
  11337. this.uvs2.push( vertexUvs[ 0 ], vertexUvs[ 1 ], vertexUvs[ 2 ] );
  11338. } else {
  11339. console.warn( 'THREE.DirectGeometry.fromGeometry(): Undefined vertexUv2 ', i );
  11340. this.uvs2.push( new Vector2(), new Vector2(), new Vector2() );
  11341. }
  11342. }
  11343. // morphs
  11344. for ( var j = 0; j < morphTargetsLength; j ++ ) {
  11345. var morphTarget = morphTargets[ j ].vertices;
  11346. morphTargetsPosition[ j ].data.push( morphTarget[ face.a ], morphTarget[ face.b ], morphTarget[ face.c ] );
  11347. }
  11348. for ( var j = 0; j < morphNormalsLength; j ++ ) {
  11349. var morphNormal = morphNormals[ j ].vertexNormals[ i ];
  11350. morphTargetsNormal[ j ].data.push( morphNormal.a, morphNormal.b, morphNormal.c );
  11351. }
  11352. // skins
  11353. if ( hasSkinIndices ) {
  11354. this.skinIndices.push( skinIndices[ face.a ], skinIndices[ face.b ], skinIndices[ face.c ] );
  11355. }
  11356. if ( hasSkinWeights ) {
  11357. this.skinWeights.push( skinWeights[ face.a ], skinWeights[ face.b ], skinWeights[ face.c ] );
  11358. }
  11359. }
  11360. this.computeGroups( geometry );
  11361. this.verticesNeedUpdate = geometry.verticesNeedUpdate;
  11362. this.normalsNeedUpdate = geometry.normalsNeedUpdate;
  11363. this.colorsNeedUpdate = geometry.colorsNeedUpdate;
  11364. this.uvsNeedUpdate = geometry.uvsNeedUpdate;
  11365. this.groupsNeedUpdate = geometry.groupsNeedUpdate;
  11366. return this;
  11367. }
  11368. } );
  11369. /**
  11370. * @author mrdoob / http://mrdoob.com/
  11371. */
  11372. function arrayMax( array ) {
  11373. if ( array.length === 0 ) return - Infinity;
  11374. var max = array[ 0 ];
  11375. for ( var i = 1, l = array.length; i < l; ++ i ) {
  11376. if ( array[ i ] > max ) max = array[ i ];
  11377. }
  11378. return max;
  11379. }
  11380. /**
  11381. * @author alteredq / http://alteredqualia.com/
  11382. * @author mrdoob / http://mrdoob.com/
  11383. */
  11384. var bufferGeometryId = 1; // BufferGeometry uses odd numbers as Id
  11385. function BufferGeometry() {
  11386. Object.defineProperty( this, 'id', { value: bufferGeometryId += 2 } );
  11387. this.uuid = _Math.generateUUID();
  11388. this.name = '';
  11389. this.type = 'BufferGeometry';
  11390. this.index = null;
  11391. this.attributes = {};
  11392. this.morphAttributes = {};
  11393. this.groups = [];
  11394. this.boundingBox = null;
  11395. this.boundingSphere = null;
  11396. this.drawRange = { start: 0, count: Infinity };
  11397. this.userData = {};
  11398. }
  11399. BufferGeometry.prototype = Object.assign( Object.create( EventDispatcher.prototype ), {
  11400. constructor: BufferGeometry,
  11401. isBufferGeometry: true,
  11402. getIndex: function () {
  11403. return this.index;
  11404. },
  11405. setIndex: function ( index ) {
  11406. if ( Array.isArray( index ) ) {
  11407. this.index = new ( arrayMax( index ) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute )( index, 1 );
  11408. } else {
  11409. this.index = index;
  11410. }
  11411. },
  11412. addAttribute: function ( name, attribute ) {
  11413. if ( ! ( attribute && attribute.isBufferAttribute ) && ! ( attribute && attribute.isInterleavedBufferAttribute ) ) {
  11414. console.warn( 'THREE.BufferGeometry: .addAttribute() now expects ( name, attribute ).' );
  11415. return this.addAttribute( name, new BufferAttribute( arguments[ 1 ], arguments[ 2 ] ) );
  11416. }
  11417. if ( name === 'index' ) {
  11418. console.warn( 'THREE.BufferGeometry.addAttribute: Use .setIndex() for index attribute.' );
  11419. this.setIndex( attribute );
  11420. return this;
  11421. }
  11422. this.attributes[ name ] = attribute;
  11423. return this;
  11424. },
  11425. getAttribute: function ( name ) {
  11426. return this.attributes[ name ];
  11427. },
  11428. removeAttribute: function ( name ) {
  11429. delete this.attributes[ name ];
  11430. return this;
  11431. },
  11432. addGroup: function ( start, count, materialIndex ) {
  11433. this.groups.push( {
  11434. start: start,
  11435. count: count,
  11436. materialIndex: materialIndex !== undefined ? materialIndex : 0
  11437. } );
  11438. },
  11439. clearGroups: function () {
  11440. this.groups = [];
  11441. },
  11442. setDrawRange: function ( start, count ) {
  11443. this.drawRange.start = start;
  11444. this.drawRange.count = count;
  11445. },
  11446. applyMatrix: function ( matrix ) {
  11447. var position = this.attributes.position;
  11448. if ( position !== undefined ) {
  11449. matrix.applyToBufferAttribute( position );
  11450. position.needsUpdate = true;
  11451. }
  11452. var normal = this.attributes.normal;
  11453. if ( normal !== undefined ) {
  11454. var normalMatrix = new Matrix3().getNormalMatrix( matrix );
  11455. normalMatrix.applyToBufferAttribute( normal );
  11456. normal.needsUpdate = true;
  11457. }
  11458. var tangent = this.attributes.tangent;
  11459. if ( tangent !== undefined ) {
  11460. var normalMatrix = new Matrix3().getNormalMatrix( matrix );
  11461. // Tangent is vec4, but the '.w' component is a sign value (+1/-1).
  11462. normalMatrix.applyToBufferAttribute( tangent );
  11463. tangent.needsUpdate = true;
  11464. }
  11465. if ( this.boundingBox !== null ) {
  11466. this.computeBoundingBox();
  11467. }
  11468. if ( this.boundingSphere !== null ) {
  11469. this.computeBoundingSphere();
  11470. }
  11471. return this;
  11472. },
  11473. rotateX: function () {
  11474. // rotate geometry around world x-axis
  11475. var m1 = new Matrix4();
  11476. return function rotateX( angle ) {
  11477. m1.makeRotationX( angle );
  11478. this.applyMatrix( m1 );
  11479. return this;
  11480. };
  11481. }(),
  11482. rotateY: function () {
  11483. // rotate geometry around world y-axis
  11484. var m1 = new Matrix4();
  11485. return function rotateY( angle ) {
  11486. m1.makeRotationY( angle );
  11487. this.applyMatrix( m1 );
  11488. return this;
  11489. };
  11490. }(),
  11491. rotateZ: function () {
  11492. // rotate geometry around world z-axis
  11493. var m1 = new Matrix4();
  11494. return function rotateZ( angle ) {
  11495. m1.makeRotationZ( angle );
  11496. this.applyMatrix( m1 );
  11497. return this;
  11498. };
  11499. }(),
  11500. translate: function () {
  11501. // translate geometry
  11502. var m1 = new Matrix4();
  11503. return function translate( x, y, z ) {
  11504. m1.makeTranslation( x, y, z );
  11505. this.applyMatrix( m1 );
  11506. return this;
  11507. };
  11508. }(),
  11509. scale: function () {
  11510. // scale geometry
  11511. var m1 = new Matrix4();
  11512. return function scale( x, y, z ) {
  11513. m1.makeScale( x, y, z );
  11514. this.applyMatrix( m1 );
  11515. return this;
  11516. };
  11517. }(),
  11518. lookAt: function () {
  11519. var obj = new Object3D();
  11520. return function lookAt( vector ) {
  11521. obj.lookAt( vector );
  11522. obj.updateMatrix();
  11523. this.applyMatrix( obj.matrix );
  11524. };
  11525. }(),
  11526. center: function () {
  11527. var offset = new Vector3();
  11528. return function center() {
  11529. this.computeBoundingBox();
  11530. this.boundingBox.getCenter( offset ).negate();
  11531. this.translate( offset.x, offset.y, offset.z );
  11532. return this;
  11533. };
  11534. }(),
  11535. setFromObject: function ( object ) {
  11536. // console.log( 'THREE.BufferGeometry.setFromObject(). Converting', object, this );
  11537. var geometry = object.geometry;
  11538. if ( object.isPoints || object.isLine ) {
  11539. var positions = new Float32BufferAttribute( geometry.vertices.length * 3, 3 );
  11540. var colors = new Float32BufferAttribute( geometry.colors.length * 3, 3 );
  11541. this.addAttribute( 'position', positions.copyVector3sArray( geometry.vertices ) );
  11542. this.addAttribute( 'color', colors.copyColorsArray( geometry.colors ) );
  11543. if ( geometry.lineDistances && geometry.lineDistances.length === geometry.vertices.length ) {
  11544. var lineDistances = new Float32BufferAttribute( geometry.lineDistances.length, 1 );
  11545. this.addAttribute( 'lineDistance', lineDistances.copyArray( geometry.lineDistances ) );
  11546. }
  11547. if ( geometry.boundingSphere !== null ) {
  11548. this.boundingSphere = geometry.boundingSphere.clone();
  11549. }
  11550. if ( geometry.boundingBox !== null ) {
  11551. this.boundingBox = geometry.boundingBox.clone();
  11552. }
  11553. } else if ( object.isMesh ) {
  11554. if ( geometry && geometry.isGeometry ) {
  11555. this.fromGeometry( geometry );
  11556. }
  11557. }
  11558. return this;
  11559. },
  11560. setFromPoints: function ( points ) {
  11561. var position = [];
  11562. for ( var i = 0, l = points.length; i < l; i ++ ) {
  11563. var point = points[ i ];
  11564. position.push( point.x, point.y, point.z || 0 );
  11565. }
  11566. this.addAttribute( 'position', new Float32BufferAttribute( position, 3 ) );
  11567. return this;
  11568. },
  11569. updateFromObject: function ( object ) {
  11570. var geometry = object.geometry;
  11571. if ( object.isMesh ) {
  11572. var direct = geometry.__directGeometry;
  11573. if ( geometry.elementsNeedUpdate === true ) {
  11574. direct = undefined;
  11575. geometry.elementsNeedUpdate = false;
  11576. }
  11577. if ( direct === undefined ) {
  11578. return this.fromGeometry( geometry );
  11579. }
  11580. direct.verticesNeedUpdate = geometry.verticesNeedUpdate;
  11581. direct.normalsNeedUpdate = geometry.normalsNeedUpdate;
  11582. direct.colorsNeedUpdate = geometry.colorsNeedUpdate;
  11583. direct.uvsNeedUpdate = geometry.uvsNeedUpdate;
  11584. direct.groupsNeedUpdate = geometry.groupsNeedUpdate;
  11585. geometry.verticesNeedUpdate = false;
  11586. geometry.normalsNeedUpdate = false;
  11587. geometry.colorsNeedUpdate = false;
  11588. geometry.uvsNeedUpdate = false;
  11589. geometry.groupsNeedUpdate = false;
  11590. geometry = direct;
  11591. }
  11592. var attribute;
  11593. if ( geometry.verticesNeedUpdate === true ) {
  11594. attribute = this.attributes.position;
  11595. if ( attribute !== undefined ) {
  11596. attribute.copyVector3sArray( geometry.vertices );
  11597. attribute.needsUpdate = true;
  11598. }
  11599. geometry.verticesNeedUpdate = false;
  11600. }
  11601. if ( geometry.normalsNeedUpdate === true ) {
  11602. attribute = this.attributes.normal;
  11603. if ( attribute !== undefined ) {
  11604. attribute.copyVector3sArray( geometry.normals );
  11605. attribute.needsUpdate = true;
  11606. }
  11607. geometry.normalsNeedUpdate = false;
  11608. }
  11609. if ( geometry.colorsNeedUpdate === true ) {
  11610. attribute = this.attributes.color;
  11611. if ( attribute !== undefined ) {
  11612. attribute.copyColorsArray( geometry.colors );
  11613. attribute.needsUpdate = true;
  11614. }
  11615. geometry.colorsNeedUpdate = false;
  11616. }
  11617. if ( geometry.uvsNeedUpdate ) {
  11618. attribute = this.attributes.uv;
  11619. if ( attribute !== undefined ) {
  11620. attribute.copyVector2sArray( geometry.uvs );
  11621. attribute.needsUpdate = true;
  11622. }
  11623. geometry.uvsNeedUpdate = false;
  11624. }
  11625. if ( geometry.lineDistancesNeedUpdate ) {
  11626. attribute = this.attributes.lineDistance;
  11627. if ( attribute !== undefined ) {
  11628. attribute.copyArray( geometry.lineDistances );
  11629. attribute.needsUpdate = true;
  11630. }
  11631. geometry.lineDistancesNeedUpdate = false;
  11632. }
  11633. if ( geometry.groupsNeedUpdate ) {
  11634. geometry.computeGroups( object.geometry );
  11635. this.groups = geometry.groups;
  11636. geometry.groupsNeedUpdate = false;
  11637. }
  11638. return this;
  11639. },
  11640. fromGeometry: function ( geometry ) {
  11641. geometry.__directGeometry = new DirectGeometry().fromGeometry( geometry );
  11642. return this.fromDirectGeometry( geometry.__directGeometry );
  11643. },
  11644. fromDirectGeometry: function ( geometry ) {
  11645. var positions = new Float32Array( geometry.vertices.length * 3 );
  11646. this.addAttribute( 'position', new BufferAttribute( positions, 3 ).copyVector3sArray( geometry.vertices ) );
  11647. if ( geometry.normals.length > 0 ) {
  11648. var normals = new Float32Array( geometry.normals.length * 3 );
  11649. this.addAttribute( 'normal', new BufferAttribute( normals, 3 ).copyVector3sArray( geometry.normals ) );
  11650. }
  11651. if ( geometry.colors.length > 0 ) {
  11652. var colors = new Float32Array( geometry.colors.length * 3 );
  11653. this.addAttribute( 'color', new BufferAttribute( colors, 3 ).copyColorsArray( geometry.colors ) );
  11654. }
  11655. if ( geometry.uvs.length > 0 ) {
  11656. var uvs = new Float32Array( geometry.uvs.length * 2 );
  11657. this.addAttribute( 'uv', new BufferAttribute( uvs, 2 ).copyVector2sArray( geometry.uvs ) );
  11658. }
  11659. if ( geometry.uvs2.length > 0 ) {
  11660. var uvs2 = new Float32Array( geometry.uvs2.length * 2 );
  11661. this.addAttribute( 'uv2', new BufferAttribute( uvs2, 2 ).copyVector2sArray( geometry.uvs2 ) );
  11662. }
  11663. // groups
  11664. this.groups = geometry.groups;
  11665. // morphs
  11666. for ( var name in geometry.morphTargets ) {
  11667. var array = [];
  11668. var morphTargets = geometry.morphTargets[ name ];
  11669. for ( var i = 0, l = morphTargets.length; i < l; i ++ ) {
  11670. var morphTarget = morphTargets[ i ];
  11671. var attribute = new Float32BufferAttribute( morphTarget.data.length * 3, 3 );
  11672. attribute.name = morphTarget.name;
  11673. array.push( attribute.copyVector3sArray( morphTarget.data ) );
  11674. }
  11675. this.morphAttributes[ name ] = array;
  11676. }
  11677. // skinning
  11678. if ( geometry.skinIndices.length > 0 ) {
  11679. var skinIndices = new Float32BufferAttribute( geometry.skinIndices.length * 4, 4 );
  11680. this.addAttribute( 'skinIndex', skinIndices.copyVector4sArray( geometry.skinIndices ) );
  11681. }
  11682. if ( geometry.skinWeights.length > 0 ) {
  11683. var skinWeights = new Float32BufferAttribute( geometry.skinWeights.length * 4, 4 );
  11684. this.addAttribute( 'skinWeight', skinWeights.copyVector4sArray( geometry.skinWeights ) );
  11685. }
  11686. //
  11687. if ( geometry.boundingSphere !== null ) {
  11688. this.boundingSphere = geometry.boundingSphere.clone();
  11689. }
  11690. if ( geometry.boundingBox !== null ) {
  11691. this.boundingBox = geometry.boundingBox.clone();
  11692. }
  11693. return this;
  11694. },
  11695. computeBoundingBox: function () {
  11696. var box = new Box3();
  11697. return function computeBoundingBox() {
  11698. if ( this.boundingBox === null ) {
  11699. this.boundingBox = new Box3();
  11700. }
  11701. var position = this.attributes.position;
  11702. var morphAttributesPosition = this.morphAttributes.position;
  11703. if ( position !== undefined ) {
  11704. this.boundingBox.setFromBufferAttribute( position );
  11705. // process morph attributes if present
  11706. if ( morphAttributesPosition ) {
  11707. for ( var i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  11708. var morphAttribute = morphAttributesPosition[ i ];
  11709. box.setFromBufferAttribute( morphAttribute );
  11710. this.boundingBox.expandByPoint( box.min );
  11711. this.boundingBox.expandByPoint( box.max );
  11712. }
  11713. }
  11714. } else {
  11715. this.boundingBox.makeEmpty();
  11716. }
  11717. if ( isNaN( this.boundingBox.min.x ) || isNaN( this.boundingBox.min.y ) || isNaN( this.boundingBox.min.z ) ) {
  11718. console.error( 'THREE.BufferGeometry.computeBoundingBox: Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this );
  11719. }
  11720. };
  11721. }(),
  11722. computeBoundingSphere: function () {
  11723. var box = new Box3();
  11724. var boxMorphTargets = new Box3();
  11725. var vector = new Vector3();
  11726. return function computeBoundingSphere() {
  11727. if ( this.boundingSphere === null ) {
  11728. this.boundingSphere = new Sphere();
  11729. }
  11730. var position = this.attributes.position;
  11731. var morphAttributesPosition = this.morphAttributes.position;
  11732. if ( position ) {
  11733. // first, find the center of the bounding sphere
  11734. var center = this.boundingSphere.center;
  11735. box.setFromBufferAttribute( position );
  11736. // process morph attributes if present
  11737. if ( morphAttributesPosition ) {
  11738. for ( var i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  11739. var morphAttribute = morphAttributesPosition[ i ];
  11740. boxMorphTargets.setFromBufferAttribute( morphAttribute );
  11741. box.expandByPoint( boxMorphTargets.min );
  11742. box.expandByPoint( boxMorphTargets.max );
  11743. }
  11744. }
  11745. box.getCenter( center );
  11746. // second, try to find a boundingSphere with a radius smaller than the
  11747. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  11748. var maxRadiusSq = 0;
  11749. for ( var i = 0, il = position.count; i < il; i ++ ) {
  11750. vector.fromBufferAttribute( position, i );
  11751. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( vector ) );
  11752. }
  11753. // process morph attributes if present
  11754. if ( morphAttributesPosition ) {
  11755. for ( var i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  11756. var morphAttribute = morphAttributesPosition[ i ];
  11757. for ( var j = 0, jl = morphAttribute.count; j < jl; j ++ ) {
  11758. vector.fromBufferAttribute( morphAttribute, i );
  11759. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( vector ) );
  11760. }
  11761. }
  11762. }
  11763. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  11764. if ( isNaN( this.boundingSphere.radius ) ) {
  11765. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this );
  11766. }
  11767. }
  11768. };
  11769. }(),
  11770. computeFaceNormals: function () {
  11771. // backwards compatibility
  11772. },
  11773. computeVertexNormals: function () {
  11774. var index = this.index;
  11775. var attributes = this.attributes;
  11776. if ( attributes.position ) {
  11777. var positions = attributes.position.array;
  11778. if ( attributes.normal === undefined ) {
  11779. this.addAttribute( 'normal', new BufferAttribute( new Float32Array( positions.length ), 3 ) );
  11780. } else {
  11781. // reset existing normals to zero
  11782. var array = attributes.normal.array;
  11783. for ( var i = 0, il = array.length; i < il; i ++ ) {
  11784. array[ i ] = 0;
  11785. }
  11786. }
  11787. var normals = attributes.normal.array;
  11788. var vA, vB, vC;
  11789. var pA = new Vector3(), pB = new Vector3(), pC = new Vector3();
  11790. var cb = new Vector3(), ab = new Vector3();
  11791. // indexed elements
  11792. if ( index ) {
  11793. var indices = index.array;
  11794. for ( var i = 0, il = index.count; i < il; i += 3 ) {
  11795. vA = indices[ i + 0 ] * 3;
  11796. vB = indices[ i + 1 ] * 3;
  11797. vC = indices[ i + 2 ] * 3;
  11798. pA.fromArray( positions, vA );
  11799. pB.fromArray( positions, vB );
  11800. pC.fromArray( positions, vC );
  11801. cb.subVectors( pC, pB );
  11802. ab.subVectors( pA, pB );
  11803. cb.cross( ab );
  11804. normals[ vA ] += cb.x;
  11805. normals[ vA + 1 ] += cb.y;
  11806. normals[ vA + 2 ] += cb.z;
  11807. normals[ vB ] += cb.x;
  11808. normals[ vB + 1 ] += cb.y;
  11809. normals[ vB + 2 ] += cb.z;
  11810. normals[ vC ] += cb.x;
  11811. normals[ vC + 1 ] += cb.y;
  11812. normals[ vC + 2 ] += cb.z;
  11813. }
  11814. } else {
  11815. // non-indexed elements (unconnected triangle soup)
  11816. for ( var i = 0, il = positions.length; i < il; i += 9 ) {
  11817. pA.fromArray( positions, i );
  11818. pB.fromArray( positions, i + 3 );
  11819. pC.fromArray( positions, i + 6 );
  11820. cb.subVectors( pC, pB );
  11821. ab.subVectors( pA, pB );
  11822. cb.cross( ab );
  11823. normals[ i ] = cb.x;
  11824. normals[ i + 1 ] = cb.y;
  11825. normals[ i + 2 ] = cb.z;
  11826. normals[ i + 3 ] = cb.x;
  11827. normals[ i + 4 ] = cb.y;
  11828. normals[ i + 5 ] = cb.z;
  11829. normals[ i + 6 ] = cb.x;
  11830. normals[ i + 7 ] = cb.y;
  11831. normals[ i + 8 ] = cb.z;
  11832. }
  11833. }
  11834. this.normalizeNormals();
  11835. attributes.normal.needsUpdate = true;
  11836. }
  11837. },
  11838. merge: function ( geometry, offset ) {
  11839. if ( ! ( geometry && geometry.isBufferGeometry ) ) {
  11840. console.error( 'THREE.BufferGeometry.merge(): geometry not an instance of THREE.BufferGeometry.', geometry );
  11841. return;
  11842. }
  11843. if ( offset === undefined ) {
  11844. offset = 0;
  11845. console.warn(
  11846. 'THREE.BufferGeometry.merge(): Overwriting original geometry, starting at offset=0. '
  11847. + 'Use BufferGeometryUtils.mergeBufferGeometries() for lossless merge.'
  11848. );
  11849. }
  11850. var attributes = this.attributes;
  11851. for ( var key in attributes ) {
  11852. if ( geometry.attributes[ key ] === undefined ) continue;
  11853. var attribute1 = attributes[ key ];
  11854. var attributeArray1 = attribute1.array;
  11855. var attribute2 = geometry.attributes[ key ];
  11856. var attributeArray2 = attribute2.array;
  11857. var attributeSize = attribute2.itemSize;
  11858. for ( var i = 0, j = attributeSize * offset; i < attributeArray2.length; i ++, j ++ ) {
  11859. attributeArray1[ j ] = attributeArray2[ i ];
  11860. }
  11861. }
  11862. return this;
  11863. },
  11864. normalizeNormals: function () {
  11865. var vector = new Vector3();
  11866. return function normalizeNormals() {
  11867. var normals = this.attributes.normal;
  11868. for ( var i = 0, il = normals.count; i < il; i ++ ) {
  11869. vector.x = normals.getX( i );
  11870. vector.y = normals.getY( i );
  11871. vector.z = normals.getZ( i );
  11872. vector.normalize();
  11873. normals.setXYZ( i, vector.x, vector.y, vector.z );
  11874. }
  11875. };
  11876. }(),
  11877. toNonIndexed: function () {
  11878. function convertBufferAttribute( attribute, indices ) {
  11879. var array = attribute.array;
  11880. var itemSize = attribute.itemSize;
  11881. var array2 = new array.constructor( indices.length * itemSize );
  11882. var index = 0, index2 = 0;
  11883. for ( var i = 0, l = indices.length; i < l; i ++ ) {
  11884. index = indices[ i ] * itemSize;
  11885. for ( var j = 0; j < itemSize; j ++ ) {
  11886. array2[ index2 ++ ] = array[ index ++ ];
  11887. }
  11888. }
  11889. return new BufferAttribute( array2, itemSize );
  11890. }
  11891. //
  11892. if ( this.index === null ) {
  11893. console.warn( 'THREE.BufferGeometry.toNonIndexed(): Geometry is already non-indexed.' );
  11894. return this;
  11895. }
  11896. var geometry2 = new BufferGeometry();
  11897. var indices = this.index.array;
  11898. var attributes = this.attributes;
  11899. // attributes
  11900. for ( var name in attributes ) {
  11901. var attribute = attributes[ name ];
  11902. var newAttribute = convertBufferAttribute( attribute, indices );
  11903. geometry2.addAttribute( name, newAttribute );
  11904. }
  11905. // morph attributes
  11906. var morphAttributes = this.morphAttributes;
  11907. for ( name in morphAttributes ) {
  11908. var morphArray = [];
  11909. var morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  11910. for ( var i = 0, il = morphAttribute.length; i < il; i ++ ) {
  11911. var attribute = morphAttribute[ i ];
  11912. var newAttribute = convertBufferAttribute( attribute, indices );
  11913. morphArray.push( newAttribute );
  11914. }
  11915. geometry2.morphAttributes[ name ] = morphArray;
  11916. }
  11917. // groups
  11918. var groups = this.groups;
  11919. for ( var i = 0, l = groups.length; i < l; i ++ ) {
  11920. var group = groups[ i ];
  11921. geometry2.addGroup( group.start, group.count, group.materialIndex );
  11922. }
  11923. return geometry2;
  11924. },
  11925. toJSON: function () {
  11926. var data = {
  11927. metadata: {
  11928. version: 4.5,
  11929. type: 'BufferGeometry',
  11930. generator: 'BufferGeometry.toJSON'
  11931. }
  11932. };
  11933. // standard BufferGeometry serialization
  11934. data.uuid = this.uuid;
  11935. data.type = this.type;
  11936. if ( this.name !== '' ) data.name = this.name;
  11937. if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData;
  11938. if ( this.parameters !== undefined ) {
  11939. var parameters = this.parameters;
  11940. for ( var key in parameters ) {
  11941. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  11942. }
  11943. return data;
  11944. }
  11945. data.data = { attributes: {} };
  11946. var index = this.index;
  11947. if ( index !== null ) {
  11948. data.data.index = {
  11949. type: index.array.constructor.name,
  11950. array: Array.prototype.slice.call( index.array )
  11951. };
  11952. }
  11953. var attributes = this.attributes;
  11954. for ( var key in attributes ) {
  11955. var attribute = attributes[ key ];
  11956. var attributeData = {
  11957. itemSize: attribute.itemSize,
  11958. type: attribute.array.constructor.name,
  11959. array: Array.prototype.slice.call( attribute.array ),
  11960. normalized: attribute.normalized
  11961. };
  11962. if ( attribute.name !== '' ) attributeData.name = attribute.name;
  11963. data.data.attributes[ key ] = attributeData;
  11964. }
  11965. var morphAttributes = {};
  11966. var hasMorphAttributes = false;
  11967. for ( var key in this.morphAttributes ) {
  11968. var attributeArray = this.morphAttributes[ key ];
  11969. var array = [];
  11970. for ( var i = 0, il = attributeArray.length; i < il; i ++ ) {
  11971. var attribute = attributeArray[ i ];
  11972. var attributeData = {
  11973. itemSize: attribute.itemSize,
  11974. type: attribute.array.constructor.name,
  11975. array: Array.prototype.slice.call( attribute.array ),
  11976. normalized: attribute.normalized
  11977. };
  11978. if ( attribute.name !== '' ) attributeData.name = attribute.name;
  11979. array.push( attributeData );
  11980. }
  11981. if ( array.length > 0 ) {
  11982. morphAttributes[ key ] = array;
  11983. hasMorphAttributes = true;
  11984. }
  11985. }
  11986. if ( hasMorphAttributes ) data.data.morphAttributes = morphAttributes;
  11987. var groups = this.groups;
  11988. if ( groups.length > 0 ) {
  11989. data.data.groups = JSON.parse( JSON.stringify( groups ) );
  11990. }
  11991. var boundingSphere = this.boundingSphere;
  11992. if ( boundingSphere !== null ) {
  11993. data.data.boundingSphere = {
  11994. center: boundingSphere.center.toArray(),
  11995. radius: boundingSphere.radius
  11996. };
  11997. }
  11998. return data;
  11999. },
  12000. clone: function () {
  12001. /*
  12002. // Handle primitives
  12003. var parameters = this.parameters;
  12004. if ( parameters !== undefined ) {
  12005. var values = [];
  12006. for ( var key in parameters ) {
  12007. values.push( parameters[ key ] );
  12008. }
  12009. var geometry = Object.create( this.constructor.prototype );
  12010. this.constructor.apply( geometry, values );
  12011. return geometry;
  12012. }
  12013. return new this.constructor().copy( this );
  12014. */
  12015. return new BufferGeometry().copy( this );
  12016. },
  12017. copy: function ( source ) {
  12018. var name, i, l;
  12019. // reset
  12020. this.index = null;
  12021. this.attributes = {};
  12022. this.morphAttributes = {};
  12023. this.groups = [];
  12024. this.boundingBox = null;
  12025. this.boundingSphere = null;
  12026. // name
  12027. this.name = source.name;
  12028. // index
  12029. var index = source.index;
  12030. if ( index !== null ) {
  12031. this.setIndex( index.clone() );
  12032. }
  12033. // attributes
  12034. var attributes = source.attributes;
  12035. for ( name in attributes ) {
  12036. var attribute = attributes[ name ];
  12037. this.addAttribute( name, attribute.clone() );
  12038. }
  12039. // morph attributes
  12040. var morphAttributes = source.morphAttributes;
  12041. for ( name in morphAttributes ) {
  12042. var array = [];
  12043. var morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  12044. for ( i = 0, l = morphAttribute.length; i < l; i ++ ) {
  12045. array.push( morphAttribute[ i ].clone() );
  12046. }
  12047. this.morphAttributes[ name ] = array;
  12048. }
  12049. // groups
  12050. var groups = source.groups;
  12051. for ( i = 0, l = groups.length; i < l; i ++ ) {
  12052. var group = groups[ i ];
  12053. this.addGroup( group.start, group.count, group.materialIndex );
  12054. }
  12055. // bounding box
  12056. var boundingBox = source.boundingBox;
  12057. if ( boundingBox !== null ) {
  12058. this.boundingBox = boundingBox.clone();
  12059. }
  12060. // bounding sphere
  12061. var boundingSphere = source.boundingSphere;
  12062. if ( boundingSphere !== null ) {
  12063. this.boundingSphere = boundingSphere.clone();
  12064. }
  12065. // draw range
  12066. this.drawRange.start = source.drawRange.start;
  12067. this.drawRange.count = source.drawRange.count;
  12068. // user data
  12069. this.userData = source.userData;
  12070. return this;
  12071. },
  12072. dispose: function () {
  12073. this.dispatchEvent( { type: 'dispose' } );
  12074. }
  12075. } );
  12076. /**
  12077. * @author mrdoob / http://mrdoob.com/
  12078. * @author Mugen87 / https://github.com/Mugen87
  12079. */
  12080. // BoxGeometry
  12081. function BoxGeometry( width, height, depth, widthSegments, heightSegments, depthSegments ) {
  12082. Geometry.call( this );
  12083. this.type = 'BoxGeometry';
  12084. this.parameters = {
  12085. width: width,
  12086. height: height,
  12087. depth: depth,
  12088. widthSegments: widthSegments,
  12089. heightSegments: heightSegments,
  12090. depthSegments: depthSegments
  12091. };
  12092. this.fromBufferGeometry( new BoxBufferGeometry( width, height, depth, widthSegments, heightSegments, depthSegments ) );
  12093. this.mergeVertices();
  12094. }
  12095. BoxGeometry.prototype = Object.create( Geometry.prototype );
  12096. BoxGeometry.prototype.constructor = BoxGeometry;
  12097. // BoxBufferGeometry
  12098. function BoxBufferGeometry( width, height, depth, widthSegments, heightSegments, depthSegments ) {
  12099. BufferGeometry.call( this );
  12100. this.type = 'BoxBufferGeometry';
  12101. this.parameters = {
  12102. width: width,
  12103. height: height,
  12104. depth: depth,
  12105. widthSegments: widthSegments,
  12106. heightSegments: heightSegments,
  12107. depthSegments: depthSegments
  12108. };
  12109. var scope = this;
  12110. width = width || 1;
  12111. height = height || 1;
  12112. depth = depth || 1;
  12113. // segments
  12114. widthSegments = Math.floor( widthSegments ) || 1;
  12115. heightSegments = Math.floor( heightSegments ) || 1;
  12116. depthSegments = Math.floor( depthSegments ) || 1;
  12117. // buffers
  12118. var indices = [];
  12119. var vertices = [];
  12120. var normals = [];
  12121. var uvs = [];
  12122. // helper variables
  12123. var numberOfVertices = 0;
  12124. var groupStart = 0;
  12125. // build each side of the box geometry
  12126. buildPlane( 'z', 'y', 'x', - 1, - 1, depth, height, width, depthSegments, heightSegments, 0 ); // px
  12127. buildPlane( 'z', 'y', 'x', 1, - 1, depth, height, - width, depthSegments, heightSegments, 1 ); // nx
  12128. buildPlane( 'x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2 ); // py
  12129. buildPlane( 'x', 'z', 'y', 1, - 1, width, depth, - height, widthSegments, depthSegments, 3 ); // ny
  12130. buildPlane( 'x', 'y', 'z', 1, - 1, width, height, depth, widthSegments, heightSegments, 4 ); // pz
  12131. buildPlane( 'x', 'y', 'z', - 1, - 1, width, height, - depth, widthSegments, heightSegments, 5 ); // nz
  12132. // build geometry
  12133. this.setIndex( indices );
  12134. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  12135. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  12136. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  12137. function buildPlane( u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex ) {
  12138. var segmentWidth = width / gridX;
  12139. var segmentHeight = height / gridY;
  12140. var widthHalf = width / 2;
  12141. var heightHalf = height / 2;
  12142. var depthHalf = depth / 2;
  12143. var gridX1 = gridX + 1;
  12144. var gridY1 = gridY + 1;
  12145. var vertexCounter = 0;
  12146. var groupCount = 0;
  12147. var ix, iy;
  12148. var vector = new Vector3();
  12149. // generate vertices, normals and uvs
  12150. for ( iy = 0; iy < gridY1; iy ++ ) {
  12151. var y = iy * segmentHeight - heightHalf;
  12152. for ( ix = 0; ix < gridX1; ix ++ ) {
  12153. var x = ix * segmentWidth - widthHalf;
  12154. // set values to correct vector component
  12155. vector[ u ] = x * udir;
  12156. vector[ v ] = y * vdir;
  12157. vector[ w ] = depthHalf;
  12158. // now apply vector to vertex buffer
  12159. vertices.push( vector.x, vector.y, vector.z );
  12160. // set values to correct vector component
  12161. vector[ u ] = 0;
  12162. vector[ v ] = 0;
  12163. vector[ w ] = depth > 0 ? 1 : - 1;
  12164. // now apply vector to normal buffer
  12165. normals.push( vector.x, vector.y, vector.z );
  12166. // uvs
  12167. uvs.push( ix / gridX );
  12168. uvs.push( 1 - ( iy / gridY ) );
  12169. // counters
  12170. vertexCounter += 1;
  12171. }
  12172. }
  12173. // indices
  12174. // 1. you need three indices to draw a single face
  12175. // 2. a single segment consists of two faces
  12176. // 3. so we need to generate six (2*3) indices per segment
  12177. for ( iy = 0; iy < gridY; iy ++ ) {
  12178. for ( ix = 0; ix < gridX; ix ++ ) {
  12179. var a = numberOfVertices + ix + gridX1 * iy;
  12180. var b = numberOfVertices + ix + gridX1 * ( iy + 1 );
  12181. var c = numberOfVertices + ( ix + 1 ) + gridX1 * ( iy + 1 );
  12182. var d = numberOfVertices + ( ix + 1 ) + gridX1 * iy;
  12183. // faces
  12184. indices.push( a, b, d );
  12185. indices.push( b, c, d );
  12186. // increase counter
  12187. groupCount += 6;
  12188. }
  12189. }
  12190. // add a group to the geometry. this will ensure multi material support
  12191. scope.addGroup( groupStart, groupCount, materialIndex );
  12192. // calculate new start value for groups
  12193. groupStart += groupCount;
  12194. // update total number of vertices
  12195. numberOfVertices += vertexCounter;
  12196. }
  12197. }
  12198. BoxBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  12199. BoxBufferGeometry.prototype.constructor = BoxBufferGeometry;
  12200. /**
  12201. * @author mrdoob / http://mrdoob.com/
  12202. * @author Mugen87 / https://github.com/Mugen87
  12203. */
  12204. // PlaneGeometry
  12205. function PlaneGeometry( width, height, widthSegments, heightSegments ) {
  12206. Geometry.call( this );
  12207. this.type = 'PlaneGeometry';
  12208. this.parameters = {
  12209. width: width,
  12210. height: height,
  12211. widthSegments: widthSegments,
  12212. heightSegments: heightSegments
  12213. };
  12214. this.fromBufferGeometry( new PlaneBufferGeometry( width, height, widthSegments, heightSegments ) );
  12215. this.mergeVertices();
  12216. }
  12217. PlaneGeometry.prototype = Object.create( Geometry.prototype );
  12218. PlaneGeometry.prototype.constructor = PlaneGeometry;
  12219. // PlaneBufferGeometry
  12220. function PlaneBufferGeometry( width, height, widthSegments, heightSegments ) {
  12221. BufferGeometry.call( this );
  12222. this.type = 'PlaneBufferGeometry';
  12223. this.parameters = {
  12224. width: width,
  12225. height: height,
  12226. widthSegments: widthSegments,
  12227. heightSegments: heightSegments
  12228. };
  12229. width = width || 1;
  12230. height = height || 1;
  12231. var width_half = width / 2;
  12232. var height_half = height / 2;
  12233. var gridX = Math.floor( widthSegments ) || 1;
  12234. var gridY = Math.floor( heightSegments ) || 1;
  12235. var gridX1 = gridX + 1;
  12236. var gridY1 = gridY + 1;
  12237. var segment_width = width / gridX;
  12238. var segment_height = height / gridY;
  12239. var ix, iy;
  12240. // buffers
  12241. var indices = [];
  12242. var vertices = [];
  12243. var normals = [];
  12244. var uvs = [];
  12245. // generate vertices, normals and uvs
  12246. for ( iy = 0; iy < gridY1; iy ++ ) {
  12247. var y = iy * segment_height - height_half;
  12248. for ( ix = 0; ix < gridX1; ix ++ ) {
  12249. var x = ix * segment_width - width_half;
  12250. vertices.push( x, - y, 0 );
  12251. normals.push( 0, 0, 1 );
  12252. uvs.push( ix / gridX );
  12253. uvs.push( 1 - ( iy / gridY ) );
  12254. }
  12255. }
  12256. // indices
  12257. for ( iy = 0; iy < gridY; iy ++ ) {
  12258. for ( ix = 0; ix < gridX; ix ++ ) {
  12259. var a = ix + gridX1 * iy;
  12260. var b = ix + gridX1 * ( iy + 1 );
  12261. var c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  12262. var d = ( ix + 1 ) + gridX1 * iy;
  12263. // faces
  12264. indices.push( a, b, d );
  12265. indices.push( b, c, d );
  12266. }
  12267. }
  12268. // build geometry
  12269. this.setIndex( indices );
  12270. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  12271. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  12272. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  12273. }
  12274. PlaneBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  12275. PlaneBufferGeometry.prototype.constructor = PlaneBufferGeometry;
  12276. /**
  12277. * @author mrdoob / http://mrdoob.com/
  12278. * @author alteredq / http://alteredqualia.com/
  12279. */
  12280. var materialId = 0;
  12281. function Material() {
  12282. Object.defineProperty( this, 'id', { value: materialId ++ } );
  12283. this.uuid = _Math.generateUUID();
  12284. this.name = '';
  12285. this.type = 'Material';
  12286. this.fog = true;
  12287. this.lights = true;
  12288. this.blending = NormalBlending;
  12289. this.side = FrontSide;
  12290. this.flatShading = false;
  12291. this.vertexTangents = false;
  12292. this.vertexColors = NoColors; // THREE.NoColors, THREE.VertexColors, THREE.FaceColors
  12293. this.opacity = 1;
  12294. this.transparent = false;
  12295. this.blendSrc = SrcAlphaFactor;
  12296. this.blendDst = OneMinusSrcAlphaFactor;
  12297. this.blendEquation = AddEquation;
  12298. this.blendSrcAlpha = null;
  12299. this.blendDstAlpha = null;
  12300. this.blendEquationAlpha = null;
  12301. this.depthFunc = LessEqualDepth;
  12302. this.depthTest = true;
  12303. this.depthWrite = true;
  12304. this.clippingPlanes = null;
  12305. this.clipIntersection = false;
  12306. this.clipShadows = false;
  12307. this.shadowSide = null;
  12308. this.colorWrite = true;
  12309. this.precision = null; // override the renderer's default precision for this material
  12310. this.polygonOffset = false;
  12311. this.polygonOffsetFactor = 0;
  12312. this.polygonOffsetUnits = 0;
  12313. this.dithering = false;
  12314. this.alphaTest = 0;
  12315. this.premultipliedAlpha = false;
  12316. this.visible = true;
  12317. this.userData = {};
  12318. this.needsUpdate = true;
  12319. }
  12320. Material.prototype = Object.assign( Object.create( EventDispatcher.prototype ), {
  12321. constructor: Material,
  12322. isMaterial: true,
  12323. onBeforeCompile: function () {},
  12324. setValues: function ( values ) {
  12325. if ( values === undefined ) return;
  12326. for ( var key in values ) {
  12327. var newValue = values[ key ];
  12328. if ( newValue === undefined ) {
  12329. console.warn( "THREE.Material: '" + key + "' parameter is undefined." );
  12330. continue;
  12331. }
  12332. // for backward compatability if shading is set in the constructor
  12333. if ( key === 'shading' ) {
  12334. console.warn( 'THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.' );
  12335. this.flatShading = ( newValue === FlatShading ) ? true : false;
  12336. continue;
  12337. }
  12338. var currentValue = this[ key ];
  12339. if ( currentValue === undefined ) {
  12340. console.warn( "THREE." + this.type + ": '" + key + "' is not a property of this material." );
  12341. continue;
  12342. }
  12343. if ( currentValue && currentValue.isColor ) {
  12344. currentValue.set( newValue );
  12345. } else if ( ( currentValue && currentValue.isVector3 ) && ( newValue && newValue.isVector3 ) ) {
  12346. currentValue.copy( newValue );
  12347. } else {
  12348. this[ key ] = newValue;
  12349. }
  12350. }
  12351. },
  12352. toJSON: function ( meta ) {
  12353. var isRoot = ( meta === undefined || typeof meta === 'string' );
  12354. if ( isRoot ) {
  12355. meta = {
  12356. textures: {},
  12357. images: {}
  12358. };
  12359. }
  12360. var data = {
  12361. metadata: {
  12362. version: 4.5,
  12363. type: 'Material',
  12364. generator: 'Material.toJSON'
  12365. }
  12366. };
  12367. // standard Material serialization
  12368. data.uuid = this.uuid;
  12369. data.type = this.type;
  12370. if ( this.name !== '' ) data.name = this.name;
  12371. if ( this.color && this.color.isColor ) data.color = this.color.getHex();
  12372. if ( this.roughness !== undefined ) data.roughness = this.roughness;
  12373. if ( this.metalness !== undefined ) data.metalness = this.metalness;
  12374. if ( this.emissive && this.emissive.isColor ) data.emissive = this.emissive.getHex();
  12375. if ( this.emissiveIntensity !== 1 ) data.emissiveIntensity = this.emissiveIntensity;
  12376. if ( this.specular && this.specular.isColor ) data.specular = this.specular.getHex();
  12377. if ( this.shininess !== undefined ) data.shininess = this.shininess;
  12378. if ( this.clearCoat !== undefined ) data.clearCoat = this.clearCoat;
  12379. if ( this.clearCoatRoughness !== undefined ) data.clearCoatRoughness = this.clearCoatRoughness;
  12380. if ( this.map && this.map.isTexture ) data.map = this.map.toJSON( meta ).uuid;
  12381. if ( this.alphaMap && this.alphaMap.isTexture ) data.alphaMap = this.alphaMap.toJSON( meta ).uuid;
  12382. if ( this.lightMap && this.lightMap.isTexture ) data.lightMap = this.lightMap.toJSON( meta ).uuid;
  12383. if ( this.aoMap && this.aoMap.isTexture ) {
  12384. data.aoMap = this.aoMap.toJSON( meta ).uuid;
  12385. data.aoMapIntensity = this.aoMapIntensity;
  12386. }
  12387. if ( this.bumpMap && this.bumpMap.isTexture ) {
  12388. data.bumpMap = this.bumpMap.toJSON( meta ).uuid;
  12389. data.bumpScale = this.bumpScale;
  12390. }
  12391. if ( this.normalMap && this.normalMap.isTexture ) {
  12392. data.normalMap = this.normalMap.toJSON( meta ).uuid;
  12393. data.normalMapType = this.normalMapType;
  12394. data.normalScale = this.normalScale.toArray();
  12395. }
  12396. if ( this.displacementMap && this.displacementMap.isTexture ) {
  12397. data.displacementMap = this.displacementMap.toJSON( meta ).uuid;
  12398. data.displacementScale = this.displacementScale;
  12399. data.displacementBias = this.displacementBias;
  12400. }
  12401. if ( this.roughnessMap && this.roughnessMap.isTexture ) data.roughnessMap = this.roughnessMap.toJSON( meta ).uuid;
  12402. if ( this.metalnessMap && this.metalnessMap.isTexture ) data.metalnessMap = this.metalnessMap.toJSON( meta ).uuid;
  12403. if ( this.emissiveMap && this.emissiveMap.isTexture ) data.emissiveMap = this.emissiveMap.toJSON( meta ).uuid;
  12404. if ( this.specularMap && this.specularMap.isTexture ) data.specularMap = this.specularMap.toJSON( meta ).uuid;
  12405. if ( this.envMap && this.envMap.isTexture ) {
  12406. data.envMap = this.envMap.toJSON( meta ).uuid;
  12407. data.reflectivity = this.reflectivity; // Scale behind envMap
  12408. if ( this.combine !== undefined ) data.combine = this.combine;
  12409. if ( this.envMapIntensity !== undefined ) data.envMapIntensity = this.envMapIntensity;
  12410. }
  12411. if ( this.gradientMap && this.gradientMap.isTexture ) {
  12412. data.gradientMap = this.gradientMap.toJSON( meta ).uuid;
  12413. }
  12414. if ( this.size !== undefined ) data.size = this.size;
  12415. if ( this.sizeAttenuation !== undefined ) data.sizeAttenuation = this.sizeAttenuation;
  12416. if ( this.blending !== NormalBlending ) data.blending = this.blending;
  12417. if ( this.flatShading === true ) data.flatShading = this.flatShading;
  12418. if ( this.side !== FrontSide ) data.side = this.side;
  12419. if ( this.vertexColors !== NoColors ) data.vertexColors = this.vertexColors;
  12420. if ( this.opacity < 1 ) data.opacity = this.opacity;
  12421. if ( this.transparent === true ) data.transparent = this.transparent;
  12422. data.depthFunc = this.depthFunc;
  12423. data.depthTest = this.depthTest;
  12424. data.depthWrite = this.depthWrite;
  12425. // rotation (SpriteMaterial)
  12426. if ( this.rotation !== 0 ) data.rotation = this.rotation;
  12427. if ( this.polygonOffset === true ) data.polygonOffset = true;
  12428. if ( this.polygonOffsetFactor !== 0 ) data.polygonOffsetFactor = this.polygonOffsetFactor;
  12429. if ( this.polygonOffsetUnits !== 0 ) data.polygonOffsetUnits = this.polygonOffsetUnits;
  12430. if ( this.linewidth !== 1 ) data.linewidth = this.linewidth;
  12431. if ( this.dashSize !== undefined ) data.dashSize = this.dashSize;
  12432. if ( this.gapSize !== undefined ) data.gapSize = this.gapSize;
  12433. if ( this.scale !== undefined ) data.scale = this.scale;
  12434. if ( this.dithering === true ) data.dithering = true;
  12435. if ( this.alphaTest > 0 ) data.alphaTest = this.alphaTest;
  12436. if ( this.premultipliedAlpha === true ) data.premultipliedAlpha = this.premultipliedAlpha;
  12437. if ( this.wireframe === true ) data.wireframe = this.wireframe;
  12438. if ( this.wireframeLinewidth > 1 ) data.wireframeLinewidth = this.wireframeLinewidth;
  12439. if ( this.wireframeLinecap !== 'round' ) data.wireframeLinecap = this.wireframeLinecap;
  12440. if ( this.wireframeLinejoin !== 'round' ) data.wireframeLinejoin = this.wireframeLinejoin;
  12441. if ( this.morphTargets === true ) data.morphTargets = true;
  12442. if ( this.skinning === true ) data.skinning = true;
  12443. if ( this.visible === false ) data.visible = false;
  12444. if ( JSON.stringify( this.userData ) !== '{}' ) data.userData = this.userData;
  12445. // TODO: Copied from Object3D.toJSON
  12446. function extractFromCache( cache ) {
  12447. var values = [];
  12448. for ( var key in cache ) {
  12449. var data = cache[ key ];
  12450. delete data.metadata;
  12451. values.push( data );
  12452. }
  12453. return values;
  12454. }
  12455. if ( isRoot ) {
  12456. var textures = extractFromCache( meta.textures );
  12457. var images = extractFromCache( meta.images );
  12458. if ( textures.length > 0 ) data.textures = textures;
  12459. if ( images.length > 0 ) data.images = images;
  12460. }
  12461. return data;
  12462. },
  12463. clone: function () {
  12464. return new this.constructor().copy( this );
  12465. },
  12466. copy: function ( source ) {
  12467. this.name = source.name;
  12468. this.fog = source.fog;
  12469. this.lights = source.lights;
  12470. this.blending = source.blending;
  12471. this.side = source.side;
  12472. this.flatShading = source.flatShading;
  12473. this.vertexColors = source.vertexColors;
  12474. this.opacity = source.opacity;
  12475. this.transparent = source.transparent;
  12476. this.blendSrc = source.blendSrc;
  12477. this.blendDst = source.blendDst;
  12478. this.blendEquation = source.blendEquation;
  12479. this.blendSrcAlpha = source.blendSrcAlpha;
  12480. this.blendDstAlpha = source.blendDstAlpha;
  12481. this.blendEquationAlpha = source.blendEquationAlpha;
  12482. this.depthFunc = source.depthFunc;
  12483. this.depthTest = source.depthTest;
  12484. this.depthWrite = source.depthWrite;
  12485. this.colorWrite = source.colorWrite;
  12486. this.precision = source.precision;
  12487. this.polygonOffset = source.polygonOffset;
  12488. this.polygonOffsetFactor = source.polygonOffsetFactor;
  12489. this.polygonOffsetUnits = source.polygonOffsetUnits;
  12490. this.dithering = source.dithering;
  12491. this.alphaTest = source.alphaTest;
  12492. this.premultipliedAlpha = source.premultipliedAlpha;
  12493. this.visible = source.visible;
  12494. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  12495. this.clipShadows = source.clipShadows;
  12496. this.clipIntersection = source.clipIntersection;
  12497. var srcPlanes = source.clippingPlanes,
  12498. dstPlanes = null;
  12499. if ( srcPlanes !== null ) {
  12500. var n = srcPlanes.length;
  12501. dstPlanes = new Array( n );
  12502. for ( var i = 0; i !== n; ++ i )
  12503. dstPlanes[ i ] = srcPlanes[ i ].clone();
  12504. }
  12505. this.clippingPlanes = dstPlanes;
  12506. this.shadowSide = source.shadowSide;
  12507. return this;
  12508. },
  12509. dispose: function () {
  12510. this.dispatchEvent( { type: 'dispose' } );
  12511. }
  12512. } );
  12513. var default_vertex = "void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}";
  12514. var default_fragment = "void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}";
  12515. /**
  12516. * @author alteredq / http://alteredqualia.com/
  12517. *
  12518. * parameters = {
  12519. * defines: { "label" : "value" },
  12520. * uniforms: { "parameter1": { value: 1.0 }, "parameter2": { value2: 2 } },
  12521. *
  12522. * fragmentShader: <string>,
  12523. * vertexShader: <string>,
  12524. *
  12525. * wireframe: <boolean>,
  12526. * wireframeLinewidth: <float>,
  12527. *
  12528. * lights: <bool>,
  12529. *
  12530. * skinning: <bool>,
  12531. * morphTargets: <bool>,
  12532. * morphNormals: <bool>
  12533. * }
  12534. */
  12535. function ShaderMaterial( parameters ) {
  12536. Material.call( this );
  12537. this.type = 'ShaderMaterial';
  12538. this.defines = {};
  12539. this.uniforms = {};
  12540. this.vertexShader = default_vertex;
  12541. this.fragmentShader = default_fragment;
  12542. this.linewidth = 1;
  12543. this.wireframe = false;
  12544. this.wireframeLinewidth = 1;
  12545. this.fog = false; // set to use scene fog
  12546. this.lights = false; // set to use scene lights
  12547. this.clipping = false; // set to use user-defined clipping planes
  12548. this.skinning = false; // set to use skinning attribute streams
  12549. this.morphTargets = false; // set to use morph targets
  12550. this.morphNormals = false; // set to use morph normals
  12551. this.extensions = {
  12552. derivatives: false, // set to use derivatives
  12553. fragDepth: false, // set to use fragment depth values
  12554. drawBuffers: false, // set to use draw buffers
  12555. shaderTextureLOD: false // set to use shader texture LOD
  12556. };
  12557. // When rendered geometry doesn't include these attributes but the material does,
  12558. // use these default values in WebGL. This avoids errors when buffer data is missing.
  12559. this.defaultAttributeValues = {
  12560. 'color': [ 1, 1, 1 ],
  12561. 'uv': [ 0, 0 ],
  12562. 'uv2': [ 0, 0 ]
  12563. };
  12564. this.index0AttributeName = undefined;
  12565. this.uniformsNeedUpdate = false;
  12566. if ( parameters !== undefined ) {
  12567. if ( parameters.attributes !== undefined ) {
  12568. console.error( 'THREE.ShaderMaterial: attributes should now be defined in THREE.BufferGeometry instead.' );
  12569. }
  12570. this.setValues( parameters );
  12571. }
  12572. }
  12573. ShaderMaterial.prototype = Object.create( Material.prototype );
  12574. ShaderMaterial.prototype.constructor = ShaderMaterial;
  12575. ShaderMaterial.prototype.isShaderMaterial = true;
  12576. ShaderMaterial.prototype.copy = function ( source ) {
  12577. Material.prototype.copy.call( this, source );
  12578. this.fragmentShader = source.fragmentShader;
  12579. this.vertexShader = source.vertexShader;
  12580. this.uniforms = cloneUniforms( source.uniforms );
  12581. this.defines = Object.assign( {}, source.defines );
  12582. this.wireframe = source.wireframe;
  12583. this.wireframeLinewidth = source.wireframeLinewidth;
  12584. this.lights = source.lights;
  12585. this.clipping = source.clipping;
  12586. this.skinning = source.skinning;
  12587. this.morphTargets = source.morphTargets;
  12588. this.morphNormals = source.morphNormals;
  12589. this.extensions = source.extensions;
  12590. return this;
  12591. };
  12592. ShaderMaterial.prototype.toJSON = function ( meta ) {
  12593. var data = Material.prototype.toJSON.call( this, meta );
  12594. data.uniforms = {};
  12595. for ( var name in this.uniforms ) {
  12596. var uniform = this.uniforms[ name ];
  12597. var value = uniform.value;
  12598. if ( value && value.isTexture ) {
  12599. data.uniforms[ name ] = {
  12600. type: 't',
  12601. value: value.toJSON( meta ).uuid
  12602. };
  12603. } else if ( value && value.isColor ) {
  12604. data.uniforms[ name ] = {
  12605. type: 'c',
  12606. value: value.getHex()
  12607. };
  12608. } else if ( value && value.isVector2 ) {
  12609. data.uniforms[ name ] = {
  12610. type: 'v2',
  12611. value: value.toArray()
  12612. };
  12613. } else if ( value && value.isVector3 ) {
  12614. data.uniforms[ name ] = {
  12615. type: 'v3',
  12616. value: value.toArray()
  12617. };
  12618. } else if ( value && value.isVector4 ) {
  12619. data.uniforms[ name ] = {
  12620. type: 'v4',
  12621. value: value.toArray()
  12622. };
  12623. } else if ( value && value.isMatrix3 ) {
  12624. data.uniforms[ name ] = {
  12625. type: 'm3',
  12626. value: value.toArray()
  12627. };
  12628. } else if ( value && value.isMatrix4 ) {
  12629. data.uniforms[ name ] = {
  12630. type: 'm4',
  12631. value: value.toArray()
  12632. };
  12633. } else {
  12634. data.uniforms[ name ] = {
  12635. value: value
  12636. };
  12637. // note: the array variants v2v, v3v, v4v, m4v and tv are not supported so far
  12638. }
  12639. }
  12640. if ( Object.keys( this.defines ).length > 0 ) data.defines = this.defines;
  12641. data.vertexShader = this.vertexShader;
  12642. data.fragmentShader = this.fragmentShader;
  12643. var extensions = {};
  12644. for ( var key in this.extensions ) {
  12645. if ( this.extensions[ key ] === true ) extensions[ key ] = true;
  12646. }
  12647. if ( Object.keys( extensions ).length > 0 ) data.extensions = extensions;
  12648. return data;
  12649. };
  12650. /**
  12651. * @author bhouston / http://clara.io
  12652. */
  12653. function Ray( origin, direction ) {
  12654. this.origin = ( origin !== undefined ) ? origin : new Vector3();
  12655. this.direction = ( direction !== undefined ) ? direction : new Vector3();
  12656. }
  12657. Object.assign( Ray.prototype, {
  12658. set: function ( origin, direction ) {
  12659. this.origin.copy( origin );
  12660. this.direction.copy( direction );
  12661. return this;
  12662. },
  12663. clone: function () {
  12664. return new this.constructor().copy( this );
  12665. },
  12666. copy: function ( ray ) {
  12667. this.origin.copy( ray.origin );
  12668. this.direction.copy( ray.direction );
  12669. return this;
  12670. },
  12671. at: function ( t, target ) {
  12672. if ( target === undefined ) {
  12673. console.warn( 'THREE.Ray: .at() target is now required' );
  12674. target = new Vector3();
  12675. }
  12676. return target.copy( this.direction ).multiplyScalar( t ).add( this.origin );
  12677. },
  12678. lookAt: function ( v ) {
  12679. this.direction.copy( v ).sub( this.origin ).normalize();
  12680. return this;
  12681. },
  12682. recast: function () {
  12683. var v1 = new Vector3();
  12684. return function recast( t ) {
  12685. this.origin.copy( this.at( t, v1 ) );
  12686. return this;
  12687. };
  12688. }(),
  12689. closestPointToPoint: function ( point, target ) {
  12690. if ( target === undefined ) {
  12691. console.warn( 'THREE.Ray: .closestPointToPoint() target is now required' );
  12692. target = new Vector3();
  12693. }
  12694. target.subVectors( point, this.origin );
  12695. var directionDistance = target.dot( this.direction );
  12696. if ( directionDistance < 0 ) {
  12697. return target.copy( this.origin );
  12698. }
  12699. return target.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  12700. },
  12701. distanceToPoint: function ( point ) {
  12702. return Math.sqrt( this.distanceSqToPoint( point ) );
  12703. },
  12704. distanceSqToPoint: function () {
  12705. var v1 = new Vector3();
  12706. return function distanceSqToPoint( point ) {
  12707. var directionDistance = v1.subVectors( point, this.origin ).dot( this.direction );
  12708. // point behind the ray
  12709. if ( directionDistance < 0 ) {
  12710. return this.origin.distanceToSquared( point );
  12711. }
  12712. v1.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  12713. return v1.distanceToSquared( point );
  12714. };
  12715. }(),
  12716. distanceSqToSegment: function () {
  12717. var segCenter = new Vector3();
  12718. var segDir = new Vector3();
  12719. var diff = new Vector3();
  12720. return function distanceSqToSegment( v0, v1, optionalPointOnRay, optionalPointOnSegment ) {
  12721. // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteDistRaySegment.h
  12722. // It returns the min distance between the ray and the segment
  12723. // defined by v0 and v1
  12724. // It can also set two optional targets :
  12725. // - The closest point on the ray
  12726. // - The closest point on the segment
  12727. segCenter.copy( v0 ).add( v1 ).multiplyScalar( 0.5 );
  12728. segDir.copy( v1 ).sub( v0 ).normalize();
  12729. diff.copy( this.origin ).sub( segCenter );
  12730. var segExtent = v0.distanceTo( v1 ) * 0.5;
  12731. var a01 = - this.direction.dot( segDir );
  12732. var b0 = diff.dot( this.direction );
  12733. var b1 = - diff.dot( segDir );
  12734. var c = diff.lengthSq();
  12735. var det = Math.abs( 1 - a01 * a01 );
  12736. var s0, s1, sqrDist, extDet;
  12737. if ( det > 0 ) {
  12738. // The ray and segment are not parallel.
  12739. s0 = a01 * b1 - b0;
  12740. s1 = a01 * b0 - b1;
  12741. extDet = segExtent * det;
  12742. if ( s0 >= 0 ) {
  12743. if ( s1 >= - extDet ) {
  12744. if ( s1 <= extDet ) {
  12745. // region 0
  12746. // Minimum at interior points of ray and segment.
  12747. var invDet = 1 / det;
  12748. s0 *= invDet;
  12749. s1 *= invDet;
  12750. sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c;
  12751. } else {
  12752. // region 1
  12753. s1 = segExtent;
  12754. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  12755. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  12756. }
  12757. } else {
  12758. // region 5
  12759. s1 = - segExtent;
  12760. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  12761. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  12762. }
  12763. } else {
  12764. if ( s1 <= - extDet ) {
  12765. // region 4
  12766. s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) );
  12767. s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  12768. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  12769. } else if ( s1 <= extDet ) {
  12770. // region 3
  12771. s0 = 0;
  12772. s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent );
  12773. sqrDist = s1 * ( s1 + 2 * b1 ) + c;
  12774. } else {
  12775. // region 2
  12776. s0 = Math.max( 0, - ( a01 * segExtent + b0 ) );
  12777. s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  12778. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  12779. }
  12780. }
  12781. } else {
  12782. // Ray and segment are parallel.
  12783. s1 = ( a01 > 0 ) ? - segExtent : segExtent;
  12784. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  12785. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  12786. }
  12787. if ( optionalPointOnRay ) {
  12788. optionalPointOnRay.copy( this.direction ).multiplyScalar( s0 ).add( this.origin );
  12789. }
  12790. if ( optionalPointOnSegment ) {
  12791. optionalPointOnSegment.copy( segDir ).multiplyScalar( s1 ).add( segCenter );
  12792. }
  12793. return sqrDist;
  12794. };
  12795. }(),
  12796. intersectSphere: function () {
  12797. var v1 = new Vector3();
  12798. return function intersectSphere( sphere, target ) {
  12799. v1.subVectors( sphere.center, this.origin );
  12800. var tca = v1.dot( this.direction );
  12801. var d2 = v1.dot( v1 ) - tca * tca;
  12802. var radius2 = sphere.radius * sphere.radius;
  12803. if ( d2 > radius2 ) return null;
  12804. var thc = Math.sqrt( radius2 - d2 );
  12805. // t0 = first intersect point - entrance on front of sphere
  12806. var t0 = tca - thc;
  12807. // t1 = second intersect point - exit point on back of sphere
  12808. var t1 = tca + thc;
  12809. // test to see if both t0 and t1 are behind the ray - if so, return null
  12810. if ( t0 < 0 && t1 < 0 ) return null;
  12811. // test to see if t0 is behind the ray:
  12812. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  12813. // in order to always return an intersect point that is in front of the ray.
  12814. if ( t0 < 0 ) return this.at( t1, target );
  12815. // else t0 is in front of the ray, so return the first collision point scaled by t0
  12816. return this.at( t0, target );
  12817. };
  12818. }(),
  12819. intersectsSphere: function ( sphere ) {
  12820. return this.distanceSqToPoint( sphere.center ) <= ( sphere.radius * sphere.radius );
  12821. },
  12822. distanceToPlane: function ( plane ) {
  12823. var denominator = plane.normal.dot( this.direction );
  12824. if ( denominator === 0 ) {
  12825. // line is coplanar, return origin
  12826. if ( plane.distanceToPoint( this.origin ) === 0 ) {
  12827. return 0;
  12828. }
  12829. // Null is preferable to undefined since undefined means.... it is undefined
  12830. return null;
  12831. }
  12832. var t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  12833. // Return if the ray never intersects the plane
  12834. return t >= 0 ? t : null;
  12835. },
  12836. intersectPlane: function ( plane, target ) {
  12837. var t = this.distanceToPlane( plane );
  12838. if ( t === null ) {
  12839. return null;
  12840. }
  12841. return this.at( t, target );
  12842. },
  12843. intersectsPlane: function ( plane ) {
  12844. // check if the ray lies on the plane first
  12845. var distToPoint = plane.distanceToPoint( this.origin );
  12846. if ( distToPoint === 0 ) {
  12847. return true;
  12848. }
  12849. var denominator = plane.normal.dot( this.direction );
  12850. if ( denominator * distToPoint < 0 ) {
  12851. return true;
  12852. }
  12853. // ray origin is behind the plane (and is pointing behind it)
  12854. return false;
  12855. },
  12856. intersectBox: function ( box, target ) {
  12857. var tmin, tmax, tymin, tymax, tzmin, tzmax;
  12858. var invdirx = 1 / this.direction.x,
  12859. invdiry = 1 / this.direction.y,
  12860. invdirz = 1 / this.direction.z;
  12861. var origin = this.origin;
  12862. if ( invdirx >= 0 ) {
  12863. tmin = ( box.min.x - origin.x ) * invdirx;
  12864. tmax = ( box.max.x - origin.x ) * invdirx;
  12865. } else {
  12866. tmin = ( box.max.x - origin.x ) * invdirx;
  12867. tmax = ( box.min.x - origin.x ) * invdirx;
  12868. }
  12869. if ( invdiry >= 0 ) {
  12870. tymin = ( box.min.y - origin.y ) * invdiry;
  12871. tymax = ( box.max.y - origin.y ) * invdiry;
  12872. } else {
  12873. tymin = ( box.max.y - origin.y ) * invdiry;
  12874. tymax = ( box.min.y - origin.y ) * invdiry;
  12875. }
  12876. if ( ( tmin > tymax ) || ( tymin > tmax ) ) return null;
  12877. // These lines also handle the case where tmin or tmax is NaN
  12878. // (result of 0 * Infinity). x !== x returns true if x is NaN
  12879. if ( tymin > tmin || tmin !== tmin ) tmin = tymin;
  12880. if ( tymax < tmax || tmax !== tmax ) tmax = tymax;
  12881. if ( invdirz >= 0 ) {
  12882. tzmin = ( box.min.z - origin.z ) * invdirz;
  12883. tzmax = ( box.max.z - origin.z ) * invdirz;
  12884. } else {
  12885. tzmin = ( box.max.z - origin.z ) * invdirz;
  12886. tzmax = ( box.min.z - origin.z ) * invdirz;
  12887. }
  12888. if ( ( tmin > tzmax ) || ( tzmin > tmax ) ) return null;
  12889. if ( tzmin > tmin || tmin !== tmin ) tmin = tzmin;
  12890. if ( tzmax < tmax || tmax !== tmax ) tmax = tzmax;
  12891. //return point closest to the ray (positive side)
  12892. if ( tmax < 0 ) return null;
  12893. return this.at( tmin >= 0 ? tmin : tmax, target );
  12894. },
  12895. intersectsBox: ( function () {
  12896. var v = new Vector3();
  12897. return function intersectsBox( box ) {
  12898. return this.intersectBox( box, v ) !== null;
  12899. };
  12900. } )(),
  12901. intersectTriangle: function () {
  12902. // Compute the offset origin, edges, and normal.
  12903. var diff = new Vector3();
  12904. var edge1 = new Vector3();
  12905. var edge2 = new Vector3();
  12906. var normal = new Vector3();
  12907. return function intersectTriangle( a, b, c, backfaceCulling, target ) {
  12908. // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h
  12909. edge1.subVectors( b, a );
  12910. edge2.subVectors( c, a );
  12911. normal.crossVectors( edge1, edge2 );
  12912. // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  12913. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  12914. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  12915. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  12916. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  12917. var DdN = this.direction.dot( normal );
  12918. var sign;
  12919. if ( DdN > 0 ) {
  12920. if ( backfaceCulling ) return null;
  12921. sign = 1;
  12922. } else if ( DdN < 0 ) {
  12923. sign = - 1;
  12924. DdN = - DdN;
  12925. } else {
  12926. return null;
  12927. }
  12928. diff.subVectors( this.origin, a );
  12929. var DdQxE2 = sign * this.direction.dot( edge2.crossVectors( diff, edge2 ) );
  12930. // b1 < 0, no intersection
  12931. if ( DdQxE2 < 0 ) {
  12932. return null;
  12933. }
  12934. var DdE1xQ = sign * this.direction.dot( edge1.cross( diff ) );
  12935. // b2 < 0, no intersection
  12936. if ( DdE1xQ < 0 ) {
  12937. return null;
  12938. }
  12939. // b1+b2 > 1, no intersection
  12940. if ( DdQxE2 + DdE1xQ > DdN ) {
  12941. return null;
  12942. }
  12943. // Line intersects triangle, check if ray does.
  12944. var QdN = - sign * diff.dot( normal );
  12945. // t < 0, no intersection
  12946. if ( QdN < 0 ) {
  12947. return null;
  12948. }
  12949. // Ray intersects triangle.
  12950. return this.at( QdN / DdN, target );
  12951. };
  12952. }(),
  12953. applyMatrix4: function ( matrix4 ) {
  12954. this.origin.applyMatrix4( matrix4 );
  12955. this.direction.transformDirection( matrix4 );
  12956. return this;
  12957. },
  12958. equals: function ( ray ) {
  12959. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  12960. }
  12961. } );
  12962. /**
  12963. * @author bhouston / http://clara.io
  12964. * @author mrdoob / http://mrdoob.com/
  12965. */
  12966. function Triangle( a, b, c ) {
  12967. this.a = ( a !== undefined ) ? a : new Vector3();
  12968. this.b = ( b !== undefined ) ? b : new Vector3();
  12969. this.c = ( c !== undefined ) ? c : new Vector3();
  12970. }
  12971. Object.assign( Triangle, {
  12972. getNormal: function () {
  12973. var v0 = new Vector3();
  12974. return function getNormal( a, b, c, target ) {
  12975. if ( target === undefined ) {
  12976. console.warn( 'THREE.Triangle: .getNormal() target is now required' );
  12977. target = new Vector3();
  12978. }
  12979. target.subVectors( c, b );
  12980. v0.subVectors( a, b );
  12981. target.cross( v0 );
  12982. var targetLengthSq = target.lengthSq();
  12983. if ( targetLengthSq > 0 ) {
  12984. return target.multiplyScalar( 1 / Math.sqrt( targetLengthSq ) );
  12985. }
  12986. return target.set( 0, 0, 0 );
  12987. };
  12988. }(),
  12989. // static/instance method to calculate barycentric coordinates
  12990. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  12991. getBarycoord: function () {
  12992. var v0 = new Vector3();
  12993. var v1 = new Vector3();
  12994. var v2 = new Vector3();
  12995. return function getBarycoord( point, a, b, c, target ) {
  12996. v0.subVectors( c, a );
  12997. v1.subVectors( b, a );
  12998. v2.subVectors( point, a );
  12999. var dot00 = v0.dot( v0 );
  13000. var dot01 = v0.dot( v1 );
  13001. var dot02 = v0.dot( v2 );
  13002. var dot11 = v1.dot( v1 );
  13003. var dot12 = v1.dot( v2 );
  13004. var denom = ( dot00 * dot11 - dot01 * dot01 );
  13005. if ( target === undefined ) {
  13006. console.warn( 'THREE.Triangle: .getBarycoord() target is now required' );
  13007. target = new Vector3();
  13008. }
  13009. // collinear or singular triangle
  13010. if ( denom === 0 ) {
  13011. // arbitrary location outside of triangle?
  13012. // not sure if this is the best idea, maybe should be returning undefined
  13013. return target.set( - 2, - 1, - 1 );
  13014. }
  13015. var invDenom = 1 / denom;
  13016. var u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  13017. var v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  13018. // barycentric coordinates must always sum to 1
  13019. return target.set( 1 - u - v, v, u );
  13020. };
  13021. }(),
  13022. containsPoint: function () {
  13023. var v1 = new Vector3();
  13024. return function containsPoint( point, a, b, c ) {
  13025. Triangle.getBarycoord( point, a, b, c, v1 );
  13026. return ( v1.x >= 0 ) && ( v1.y >= 0 ) && ( ( v1.x + v1.y ) <= 1 );
  13027. };
  13028. }(),
  13029. getUV: function () {
  13030. var barycoord = new Vector3();
  13031. return function getUV( point, p1, p2, p3, uv1, uv2, uv3, target ) {
  13032. this.getBarycoord( point, p1, p2, p3, barycoord );
  13033. target.set( 0, 0 );
  13034. target.addScaledVector( uv1, barycoord.x );
  13035. target.addScaledVector( uv2, barycoord.y );
  13036. target.addScaledVector( uv3, barycoord.z );
  13037. return target;
  13038. };
  13039. }()
  13040. } );
  13041. Object.assign( Triangle.prototype, {
  13042. set: function ( a, b, c ) {
  13043. this.a.copy( a );
  13044. this.b.copy( b );
  13045. this.c.copy( c );
  13046. return this;
  13047. },
  13048. setFromPointsAndIndices: function ( points, i0, i1, i2 ) {
  13049. this.a.copy( points[ i0 ] );
  13050. this.b.copy( points[ i1 ] );
  13051. this.c.copy( points[ i2 ] );
  13052. return this;
  13053. },
  13054. clone: function () {
  13055. return new this.constructor().copy( this );
  13056. },
  13057. copy: function ( triangle ) {
  13058. this.a.copy( triangle.a );
  13059. this.b.copy( triangle.b );
  13060. this.c.copy( triangle.c );
  13061. return this;
  13062. },
  13063. getArea: function () {
  13064. var v0 = new Vector3();
  13065. var v1 = new Vector3();
  13066. return function getArea() {
  13067. v0.subVectors( this.c, this.b );
  13068. v1.subVectors( this.a, this.b );
  13069. return v0.cross( v1 ).length() * 0.5;
  13070. };
  13071. }(),
  13072. getMidpoint: function ( target ) {
  13073. if ( target === undefined ) {
  13074. console.warn( 'THREE.Triangle: .getMidpoint() target is now required' );
  13075. target = new Vector3();
  13076. }
  13077. return target.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  13078. },
  13079. getNormal: function ( target ) {
  13080. return Triangle.getNormal( this.a, this.b, this.c, target );
  13081. },
  13082. getPlane: function ( target ) {
  13083. if ( target === undefined ) {
  13084. console.warn( 'THREE.Triangle: .getPlane() target is now required' );
  13085. target = new Vector3();
  13086. }
  13087. return target.setFromCoplanarPoints( this.a, this.b, this.c );
  13088. },
  13089. getBarycoord: function ( point, target ) {
  13090. return Triangle.getBarycoord( point, this.a, this.b, this.c, target );
  13091. },
  13092. containsPoint: function ( point ) {
  13093. return Triangle.containsPoint( point, this.a, this.b, this.c );
  13094. },
  13095. getUV: function ( point, uv1, uv2, uv3, result ) {
  13096. return Triangle.getUV( point, this.a, this.b, this.c, uv1, uv2, uv3, result );
  13097. },
  13098. intersectsBox: function ( box ) {
  13099. return box.intersectsTriangle( this );
  13100. },
  13101. closestPointToPoint: function () {
  13102. var vab = new Vector3();
  13103. var vac = new Vector3();
  13104. var vbc = new Vector3();
  13105. var vap = new Vector3();
  13106. var vbp = new Vector3();
  13107. var vcp = new Vector3();
  13108. return function closestPointToPoint( p, target ) {
  13109. if ( target === undefined ) {
  13110. console.warn( 'THREE.Triangle: .closestPointToPoint() target is now required' );
  13111. target = new Vector3();
  13112. }
  13113. var a = this.a, b = this.b, c = this.c;
  13114. var v, w;
  13115. // algorithm thanks to Real-Time Collision Detection by Christer Ericson,
  13116. // published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc.,
  13117. // under the accompanying license; see chapter 5.1.5 for detailed explanation.
  13118. // basically, we're distinguishing which of the voronoi regions of the triangle
  13119. // the point lies in with the minimum amount of redundant computation.
  13120. vab.subVectors( b, a );
  13121. vac.subVectors( c, a );
  13122. vap.subVectors( p, a );
  13123. var d1 = vab.dot( vap );
  13124. var d2 = vac.dot( vap );
  13125. if ( d1 <= 0 && d2 <= 0 ) {
  13126. // vertex region of A; barycentric coords (1, 0, 0)
  13127. return target.copy( a );
  13128. }
  13129. vbp.subVectors( p, b );
  13130. var d3 = vab.dot( vbp );
  13131. var d4 = vac.dot( vbp );
  13132. if ( d3 >= 0 && d4 <= d3 ) {
  13133. // vertex region of B; barycentric coords (0, 1, 0)
  13134. return target.copy( b );
  13135. }
  13136. var vc = d1 * d4 - d3 * d2;
  13137. if ( vc <= 0 && d1 >= 0 && d3 <= 0 ) {
  13138. v = d1 / ( d1 - d3 );
  13139. // edge region of AB; barycentric coords (1-v, v, 0)
  13140. return target.copy( a ).addScaledVector( vab, v );
  13141. }
  13142. vcp.subVectors( p, c );
  13143. var d5 = vab.dot( vcp );
  13144. var d6 = vac.dot( vcp );
  13145. if ( d6 >= 0 && d5 <= d6 ) {
  13146. // vertex region of C; barycentric coords (0, 0, 1)
  13147. return target.copy( c );
  13148. }
  13149. var vb = d5 * d2 - d1 * d6;
  13150. if ( vb <= 0 && d2 >= 0 && d6 <= 0 ) {
  13151. w = d2 / ( d2 - d6 );
  13152. // edge region of AC; barycentric coords (1-w, 0, w)
  13153. return target.copy( a ).addScaledVector( vac, w );
  13154. }
  13155. var va = d3 * d6 - d5 * d4;
  13156. if ( va <= 0 && ( d4 - d3 ) >= 0 && ( d5 - d6 ) >= 0 ) {
  13157. vbc.subVectors( c, b );
  13158. w = ( d4 - d3 ) / ( ( d4 - d3 ) + ( d5 - d6 ) );
  13159. // edge region of BC; barycentric coords (0, 1-w, w)
  13160. return target.copy( b ).addScaledVector( vbc, w ); // edge region of BC
  13161. }
  13162. // face region
  13163. var denom = 1 / ( va + vb + vc );
  13164. // u = va * denom
  13165. v = vb * denom;
  13166. w = vc * denom;
  13167. return target.copy( a ).addScaledVector( vab, v ).addScaledVector( vac, w );
  13168. };
  13169. }(),
  13170. equals: function ( triangle ) {
  13171. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  13172. }
  13173. } );
  13174. /**
  13175. * @author mrdoob / http://mrdoob.com/
  13176. * @author alteredq / http://alteredqualia.com/
  13177. *
  13178. * parameters = {
  13179. * color: <hex>,
  13180. * opacity: <float>,
  13181. * map: new THREE.Texture( <Image> ),
  13182. *
  13183. * lightMap: new THREE.Texture( <Image> ),
  13184. * lightMapIntensity: <float>
  13185. *
  13186. * aoMap: new THREE.Texture( <Image> ),
  13187. * aoMapIntensity: <float>
  13188. *
  13189. * specularMap: new THREE.Texture( <Image> ),
  13190. *
  13191. * alphaMap: new THREE.Texture( <Image> ),
  13192. *
  13193. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  13194. * combine: THREE.Multiply,
  13195. * reflectivity: <float>,
  13196. * refractionRatio: <float>,
  13197. *
  13198. * depthTest: <bool>,
  13199. * depthWrite: <bool>,
  13200. *
  13201. * wireframe: <boolean>,
  13202. * wireframeLinewidth: <float>,
  13203. *
  13204. * skinning: <bool>,
  13205. * morphTargets: <bool>
  13206. * }
  13207. */
  13208. function MeshBasicMaterial( parameters ) {
  13209. Material.call( this );
  13210. this.type = 'MeshBasicMaterial';
  13211. this.color = new Color( 0xffffff ); // emissive
  13212. this.map = null;
  13213. this.lightMap = null;
  13214. this.lightMapIntensity = 1.0;
  13215. this.aoMap = null;
  13216. this.aoMapIntensity = 1.0;
  13217. this.specularMap = null;
  13218. this.alphaMap = null;
  13219. this.envMap = null;
  13220. this.combine = MultiplyOperation;
  13221. this.reflectivity = 1;
  13222. this.refractionRatio = 0.98;
  13223. this.wireframe = false;
  13224. this.wireframeLinewidth = 1;
  13225. this.wireframeLinecap = 'round';
  13226. this.wireframeLinejoin = 'round';
  13227. this.skinning = false;
  13228. this.morphTargets = false;
  13229. this.lights = false;
  13230. this.setValues( parameters );
  13231. }
  13232. MeshBasicMaterial.prototype = Object.create( Material.prototype );
  13233. MeshBasicMaterial.prototype.constructor = MeshBasicMaterial;
  13234. MeshBasicMaterial.prototype.isMeshBasicMaterial = true;
  13235. MeshBasicMaterial.prototype.copy = function ( source ) {
  13236. Material.prototype.copy.call( this, source );
  13237. this.color.copy( source.color );
  13238. this.map = source.map;
  13239. this.lightMap = source.lightMap;
  13240. this.lightMapIntensity = source.lightMapIntensity;
  13241. this.aoMap = source.aoMap;
  13242. this.aoMapIntensity = source.aoMapIntensity;
  13243. this.specularMap = source.specularMap;
  13244. this.alphaMap = source.alphaMap;
  13245. this.envMap = source.envMap;
  13246. this.combine = source.combine;
  13247. this.reflectivity = source.reflectivity;
  13248. this.refractionRatio = source.refractionRatio;
  13249. this.wireframe = source.wireframe;
  13250. this.wireframeLinewidth = source.wireframeLinewidth;
  13251. this.wireframeLinecap = source.wireframeLinecap;
  13252. this.wireframeLinejoin = source.wireframeLinejoin;
  13253. this.skinning = source.skinning;
  13254. this.morphTargets = source.morphTargets;
  13255. return this;
  13256. };
  13257. /**
  13258. * @author mrdoob / http://mrdoob.com/
  13259. * @author alteredq / http://alteredqualia.com/
  13260. * @author mikael emtinger / http://gomo.se/
  13261. * @author jonobr1 / http://jonobr1.com/
  13262. */
  13263. function Mesh( geometry, material ) {
  13264. Object3D.call( this );
  13265. this.type = 'Mesh';
  13266. this.geometry = geometry !== undefined ? geometry : new BufferGeometry();
  13267. this.material = material !== undefined ? material : new MeshBasicMaterial( { color: Math.random() * 0xffffff } );
  13268. this.drawMode = TrianglesDrawMode;
  13269. this.updateMorphTargets();
  13270. }
  13271. Mesh.prototype = Object.assign( Object.create( Object3D.prototype ), {
  13272. constructor: Mesh,
  13273. isMesh: true,
  13274. setDrawMode: function ( value ) {
  13275. this.drawMode = value;
  13276. },
  13277. copy: function ( source ) {
  13278. Object3D.prototype.copy.call( this, source );
  13279. this.drawMode = source.drawMode;
  13280. if ( source.morphTargetInfluences !== undefined ) {
  13281. this.morphTargetInfluences = source.morphTargetInfluences.slice();
  13282. }
  13283. if ( source.morphTargetDictionary !== undefined ) {
  13284. this.morphTargetDictionary = Object.assign( {}, source.morphTargetDictionary );
  13285. }
  13286. return this;
  13287. },
  13288. updateMorphTargets: function () {
  13289. var geometry = this.geometry;
  13290. var m, ml, name;
  13291. if ( geometry.isBufferGeometry ) {
  13292. var morphAttributes = geometry.morphAttributes;
  13293. var keys = Object.keys( morphAttributes );
  13294. if ( keys.length > 0 ) {
  13295. var morphAttribute = morphAttributes[ keys[ 0 ] ];
  13296. if ( morphAttribute !== undefined ) {
  13297. this.morphTargetInfluences = [];
  13298. this.morphTargetDictionary = {};
  13299. for ( m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  13300. name = morphAttribute[ m ].name || String( m );
  13301. this.morphTargetInfluences.push( 0 );
  13302. this.morphTargetDictionary[ name ] = m;
  13303. }
  13304. }
  13305. }
  13306. } else {
  13307. var morphTargets = geometry.morphTargets;
  13308. if ( morphTargets !== undefined && morphTargets.length > 0 ) {
  13309. console.error( 'THREE.Mesh.updateMorphTargets() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.' );
  13310. }
  13311. }
  13312. },
  13313. raycast: ( function () {
  13314. var inverseMatrix = new Matrix4();
  13315. var ray = new Ray();
  13316. var sphere = new Sphere();
  13317. var vA = new Vector3();
  13318. var vB = new Vector3();
  13319. var vC = new Vector3();
  13320. var tempA = new Vector3();
  13321. var tempB = new Vector3();
  13322. var tempC = new Vector3();
  13323. var morphA = new Vector3();
  13324. var morphB = new Vector3();
  13325. var morphC = new Vector3();
  13326. var uvA = new Vector2();
  13327. var uvB = new Vector2();
  13328. var uvC = new Vector2();
  13329. var intersectionPoint = new Vector3();
  13330. var intersectionPointWorld = new Vector3();
  13331. function checkIntersection( object, material, raycaster, ray, pA, pB, pC, point ) {
  13332. var intersect;
  13333. if ( material.side === BackSide ) {
  13334. intersect = ray.intersectTriangle( pC, pB, pA, true, point );
  13335. } else {
  13336. intersect = ray.intersectTriangle( pA, pB, pC, material.side !== DoubleSide, point );
  13337. }
  13338. if ( intersect === null ) return null;
  13339. intersectionPointWorld.copy( point );
  13340. intersectionPointWorld.applyMatrix4( object.matrixWorld );
  13341. var distance = raycaster.ray.origin.distanceTo( intersectionPointWorld );
  13342. if ( distance < raycaster.near || distance > raycaster.far ) return null;
  13343. return {
  13344. distance: distance,
  13345. point: intersectionPointWorld.clone(),
  13346. object: object
  13347. };
  13348. }
  13349. function checkBufferGeometryIntersection( object, material, raycaster, ray, position, morphPosition, uv, a, b, c ) {
  13350. vA.fromBufferAttribute( position, a );
  13351. vB.fromBufferAttribute( position, b );
  13352. vC.fromBufferAttribute( position, c );
  13353. var morphInfluences = object.morphTargetInfluences;
  13354. if ( material.morphTargets && morphPosition && morphInfluences ) {
  13355. morphA.set( 0, 0, 0 );
  13356. morphB.set( 0, 0, 0 );
  13357. morphC.set( 0, 0, 0 );
  13358. for ( var i = 0, il = morphPosition.length; i < il; i ++ ) {
  13359. var influence = morphInfluences[ i ];
  13360. var morphAttribute = morphPosition[ i ];
  13361. if ( influence === 0 ) continue;
  13362. tempA.fromBufferAttribute( morphAttribute, a );
  13363. tempB.fromBufferAttribute( morphAttribute, b );
  13364. tempC.fromBufferAttribute( morphAttribute, c );
  13365. morphA.addScaledVector( tempA.sub( vA ), influence );
  13366. morphB.addScaledVector( tempB.sub( vB ), influence );
  13367. morphC.addScaledVector( tempC.sub( vC ), influence );
  13368. }
  13369. vA.add( morphA );
  13370. vB.add( morphB );
  13371. vC.add( morphC );
  13372. }
  13373. var intersection = checkIntersection( object, material, raycaster, ray, vA, vB, vC, intersectionPoint );
  13374. if ( intersection ) {
  13375. if ( uv ) {
  13376. uvA.fromBufferAttribute( uv, a );
  13377. uvB.fromBufferAttribute( uv, b );
  13378. uvC.fromBufferAttribute( uv, c );
  13379. intersection.uv = Triangle.getUV( intersectionPoint, vA, vB, vC, uvA, uvB, uvC, new Vector2() );
  13380. }
  13381. var face = new Face3( a, b, c );
  13382. Triangle.getNormal( vA, vB, vC, face.normal );
  13383. intersection.face = face;
  13384. }
  13385. return intersection;
  13386. }
  13387. return function raycast( raycaster, intersects ) {
  13388. var geometry = this.geometry;
  13389. var material = this.material;
  13390. var matrixWorld = this.matrixWorld;
  13391. if ( material === undefined ) return;
  13392. // Checking boundingSphere distance to ray
  13393. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  13394. sphere.copy( geometry.boundingSphere );
  13395. sphere.applyMatrix4( matrixWorld );
  13396. if ( raycaster.ray.intersectsSphere( sphere ) === false ) return;
  13397. //
  13398. inverseMatrix.getInverse( matrixWorld );
  13399. ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  13400. // Check boundingBox before continuing
  13401. if ( geometry.boundingBox !== null ) {
  13402. if ( ray.intersectsBox( geometry.boundingBox ) === false ) return;
  13403. }
  13404. var intersection;
  13405. if ( geometry.isBufferGeometry ) {
  13406. var a, b, c;
  13407. var index = geometry.index;
  13408. var position = geometry.attributes.position;
  13409. var morphPosition = geometry.morphAttributes.position;
  13410. var uv = geometry.attributes.uv;
  13411. var groups = geometry.groups;
  13412. var drawRange = geometry.drawRange;
  13413. var i, j, il, jl;
  13414. var group, groupMaterial;
  13415. var start, end;
  13416. if ( index !== null ) {
  13417. // indexed buffer geometry
  13418. if ( Array.isArray( material ) ) {
  13419. for ( i = 0, il = groups.length; i < il; i ++ ) {
  13420. group = groups[ i ];
  13421. groupMaterial = material[ group.materialIndex ];
  13422. start = Math.max( group.start, drawRange.start );
  13423. end = Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) );
  13424. for ( j = start, jl = end; j < jl; j += 3 ) {
  13425. a = index.getX( j );
  13426. b = index.getX( j + 1 );
  13427. c = index.getX( j + 2 );
  13428. intersection = checkBufferGeometryIntersection( this, groupMaterial, raycaster, ray, position, morphPosition, uv, a, b, c );
  13429. if ( intersection ) {
  13430. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in indexed buffer semantics
  13431. intersection.face.materialIndex = group.materialIndex;
  13432. intersects.push( intersection );
  13433. }
  13434. }
  13435. }
  13436. } else {
  13437. start = Math.max( 0, drawRange.start );
  13438. end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  13439. for ( i = start, il = end; i < il; i += 3 ) {
  13440. a = index.getX( i );
  13441. b = index.getX( i + 1 );
  13442. c = index.getX( i + 2 );
  13443. intersection = checkBufferGeometryIntersection( this, material, raycaster, ray, position, morphPosition, uv, a, b, c );
  13444. if ( intersection ) {
  13445. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in indexed buffer semantics
  13446. intersects.push( intersection );
  13447. }
  13448. }
  13449. }
  13450. } else if ( position !== undefined ) {
  13451. // non-indexed buffer geometry
  13452. if ( Array.isArray( material ) ) {
  13453. for ( i = 0, il = groups.length; i < il; i ++ ) {
  13454. group = groups[ i ];
  13455. groupMaterial = material[ group.materialIndex ];
  13456. start = Math.max( group.start, drawRange.start );
  13457. end = Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) );
  13458. for ( j = start, jl = end; j < jl; j += 3 ) {
  13459. a = j;
  13460. b = j + 1;
  13461. c = j + 2;
  13462. intersection = checkBufferGeometryIntersection( this, groupMaterial, raycaster, ray, position, morphPosition, uv, a, b, c );
  13463. if ( intersection ) {
  13464. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in non-indexed buffer semantics
  13465. intersection.face.materialIndex = group.materialIndex;
  13466. intersects.push( intersection );
  13467. }
  13468. }
  13469. }
  13470. } else {
  13471. start = Math.max( 0, drawRange.start );
  13472. end = Math.min( position.count, ( drawRange.start + drawRange.count ) );
  13473. for ( i = start, il = end; i < il; i += 3 ) {
  13474. a = i;
  13475. b = i + 1;
  13476. c = i + 2;
  13477. intersection = checkBufferGeometryIntersection( this, material, raycaster, ray, position, morphPosition, uv, a, b, c );
  13478. if ( intersection ) {
  13479. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in non-indexed buffer semantics
  13480. intersects.push( intersection );
  13481. }
  13482. }
  13483. }
  13484. }
  13485. } else if ( geometry.isGeometry ) {
  13486. var fvA, fvB, fvC;
  13487. var isMultiMaterial = Array.isArray( material );
  13488. var vertices = geometry.vertices;
  13489. var faces = geometry.faces;
  13490. var uvs;
  13491. var faceVertexUvs = geometry.faceVertexUvs[ 0 ];
  13492. if ( faceVertexUvs.length > 0 ) uvs = faceVertexUvs;
  13493. for ( var f = 0, fl = faces.length; f < fl; f ++ ) {
  13494. var face = faces[ f ];
  13495. var faceMaterial = isMultiMaterial ? material[ face.materialIndex ] : material;
  13496. if ( faceMaterial === undefined ) continue;
  13497. fvA = vertices[ face.a ];
  13498. fvB = vertices[ face.b ];
  13499. fvC = vertices[ face.c ];
  13500. intersection = checkIntersection( this, faceMaterial, raycaster, ray, fvA, fvB, fvC, intersectionPoint );
  13501. if ( intersection ) {
  13502. if ( uvs && uvs[ f ] ) {
  13503. var uvs_f = uvs[ f ];
  13504. uvA.copy( uvs_f[ 0 ] );
  13505. uvB.copy( uvs_f[ 1 ] );
  13506. uvC.copy( uvs_f[ 2 ] );
  13507. intersection.uv = Triangle.getUV( intersectionPoint, fvA, fvB, fvC, uvA, uvB, uvC, new Vector2() );
  13508. }
  13509. intersection.face = face;
  13510. intersection.faceIndex = f;
  13511. intersects.push( intersection );
  13512. }
  13513. }
  13514. }
  13515. };
  13516. }() ),
  13517. clone: function () {
  13518. return new this.constructor( this.geometry, this.material ).copy( this );
  13519. }
  13520. } );
  13521. /**
  13522. * @author mrdoob / http://mrdoob.com/
  13523. */
  13524. function WebGLBackground( renderer, state, objects, premultipliedAlpha ) {
  13525. var clearColor = new Color( 0x000000 );
  13526. var clearAlpha = 0;
  13527. var planeMesh;
  13528. var boxMesh;
  13529. // Store the current background texture and its `version`
  13530. // so we can recompile the material accordingly.
  13531. var currentBackground = null;
  13532. var currentBackgroundVersion = 0;
  13533. function render( renderList, scene, camera, forceClear ) {
  13534. var background = scene.background;
  13535. // Ignore background in AR
  13536. // TODO: Reconsider this.
  13537. var vr = renderer.vr;
  13538. var session = vr.getSession && vr.getSession();
  13539. if ( session && session.environmentBlendMode === 'additive' ) {
  13540. background = null;
  13541. }
  13542. if ( background === null ) {
  13543. setClear( clearColor, clearAlpha );
  13544. currentBackground = null;
  13545. currentBackgroundVersion = 0;
  13546. } else if ( background && background.isColor ) {
  13547. setClear( background, 1 );
  13548. forceClear = true;
  13549. currentBackground = null;
  13550. currentBackgroundVersion = 0;
  13551. }
  13552. if ( renderer.autoClear || forceClear ) {
  13553. renderer.clear( renderer.autoClearColor, renderer.autoClearDepth, renderer.autoClearStencil );
  13554. }
  13555. if ( background && ( background.isCubeTexture || background.isWebGLRenderTargetCube ) ) {
  13556. if ( boxMesh === undefined ) {
  13557. boxMesh = new Mesh(
  13558. new BoxBufferGeometry( 1, 1, 1 ),
  13559. new ShaderMaterial( {
  13560. type: 'BackgroundCubeMaterial',
  13561. uniforms: cloneUniforms( ShaderLib.cube.uniforms ),
  13562. vertexShader: ShaderLib.cube.vertexShader,
  13563. fragmentShader: ShaderLib.cube.fragmentShader,
  13564. side: BackSide,
  13565. depthTest: false,
  13566. depthWrite: false,
  13567. fog: false
  13568. } )
  13569. );
  13570. boxMesh.geometry.removeAttribute( 'normal' );
  13571. boxMesh.geometry.removeAttribute( 'uv' );
  13572. boxMesh.onBeforeRender = function ( renderer, scene, camera ) {
  13573. this.matrixWorld.copyPosition( camera.matrixWorld );
  13574. };
  13575. // enable code injection for non-built-in material
  13576. Object.defineProperty( boxMesh.material, 'map', {
  13577. get: function () {
  13578. return this.uniforms.tCube.value;
  13579. }
  13580. } );
  13581. objects.update( boxMesh );
  13582. }
  13583. var texture = background.isWebGLRenderTargetCube ? background.texture : background;
  13584. boxMesh.material.uniforms.tCube.value = texture;
  13585. boxMesh.material.uniforms.tFlip.value = ( background.isWebGLRenderTargetCube ) ? 1 : - 1;
  13586. if ( currentBackground !== background ||
  13587. currentBackgroundVersion !== texture.version ) {
  13588. boxMesh.material.needsUpdate = true;
  13589. currentBackground = background;
  13590. currentBackgroundVersion = texture.version;
  13591. }
  13592. // push to the pre-sorted opaque render list
  13593. renderList.unshift( boxMesh, boxMesh.geometry, boxMesh.material, 0, 0, null );
  13594. } else if ( background && background.isTexture ) {
  13595. if ( planeMesh === undefined ) {
  13596. planeMesh = new Mesh(
  13597. new PlaneBufferGeometry( 2, 2 ),
  13598. new ShaderMaterial( {
  13599. type: 'BackgroundMaterial',
  13600. uniforms: cloneUniforms( ShaderLib.background.uniforms ),
  13601. vertexShader: ShaderLib.background.vertexShader,
  13602. fragmentShader: ShaderLib.background.fragmentShader,
  13603. side: FrontSide,
  13604. depthTest: false,
  13605. depthWrite: false,
  13606. fog: false
  13607. } )
  13608. );
  13609. planeMesh.geometry.removeAttribute( 'normal' );
  13610. // enable code injection for non-built-in material
  13611. Object.defineProperty( planeMesh.material, 'map', {
  13612. get: function () {
  13613. return this.uniforms.t2D.value;
  13614. }
  13615. } );
  13616. objects.update( planeMesh );
  13617. }
  13618. planeMesh.material.uniforms.t2D.value = background;
  13619. if ( background.matrixAutoUpdate === true ) {
  13620. background.updateMatrix();
  13621. }
  13622. planeMesh.material.uniforms.uvTransform.value.copy( background.matrix );
  13623. if ( currentBackground !== background ||
  13624. currentBackgroundVersion !== background.version ) {
  13625. planeMesh.material.needsUpdate = true;
  13626. currentBackground = background;
  13627. currentBackgroundVersion = background.version;
  13628. }
  13629. // push to the pre-sorted opaque render list
  13630. renderList.unshift( planeMesh, planeMesh.geometry, planeMesh.material, 0, 0, null );
  13631. }
  13632. }
  13633. function setClear( color, alpha ) {
  13634. state.buffers.color.setClear( color.r, color.g, color.b, alpha, premultipliedAlpha );
  13635. }
  13636. return {
  13637. getClearColor: function () {
  13638. return clearColor;
  13639. },
  13640. setClearColor: function ( color, alpha ) {
  13641. clearColor.set( color );
  13642. clearAlpha = alpha !== undefined ? alpha : 1;
  13643. setClear( clearColor, clearAlpha );
  13644. },
  13645. getClearAlpha: function () {
  13646. return clearAlpha;
  13647. },
  13648. setClearAlpha: function ( alpha ) {
  13649. clearAlpha = alpha;
  13650. setClear( clearColor, clearAlpha );
  13651. },
  13652. render: render
  13653. };
  13654. }
  13655. /**
  13656. * @author mrdoob / http://mrdoob.com/
  13657. */
  13658. function WebGLBufferRenderer( gl, extensions, info, capabilities ) {
  13659. var mode;
  13660. function setMode( value ) {
  13661. mode = value;
  13662. }
  13663. function render( start, count ) {
  13664. gl.drawArrays( mode, start, count );
  13665. info.update( count, mode );
  13666. }
  13667. function renderInstances( geometry, start, count ) {
  13668. var extension;
  13669. if ( capabilities.isWebGL2 ) {
  13670. extension = gl;
  13671. } else {
  13672. extension = extensions.get( 'ANGLE_instanced_arrays' );
  13673. if ( extension === null ) {
  13674. console.error( 'THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  13675. return;
  13676. }
  13677. }
  13678. extension[ capabilities.isWebGL2 ? 'drawArraysInstanced' : 'drawArraysInstancedANGLE' ]( mode, start, count, geometry.maxInstancedCount );
  13679. info.update( count, mode, geometry.maxInstancedCount );
  13680. }
  13681. //
  13682. this.setMode = setMode;
  13683. this.render = render;
  13684. this.renderInstances = renderInstances;
  13685. }
  13686. /**
  13687. * @author mrdoob / http://mrdoob.com/
  13688. */
  13689. function WebGLCapabilities( gl, extensions, parameters ) {
  13690. var maxAnisotropy;
  13691. function getMaxAnisotropy() {
  13692. if ( maxAnisotropy !== undefined ) return maxAnisotropy;
  13693. var extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  13694. if ( extension !== null ) {
  13695. maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  13696. } else {
  13697. maxAnisotropy = 0;
  13698. }
  13699. return maxAnisotropy;
  13700. }
  13701. function getMaxPrecision( precision ) {
  13702. if ( precision === 'highp' ) {
  13703. if ( gl.getShaderPrecisionFormat( 35633, 36338 ).precision > 0 &&
  13704. gl.getShaderPrecisionFormat( 35632, 36338 ).precision > 0 ) {
  13705. return 'highp';
  13706. }
  13707. precision = 'mediump';
  13708. }
  13709. if ( precision === 'mediump' ) {
  13710. if ( gl.getShaderPrecisionFormat( 35633, 36337 ).precision > 0 &&
  13711. gl.getShaderPrecisionFormat( 35632, 36337 ).precision > 0 ) {
  13712. return 'mediump';
  13713. }
  13714. }
  13715. return 'lowp';
  13716. }
  13717. var isWebGL2 = typeof WebGL2RenderingContext !== 'undefined' && gl instanceof WebGL2RenderingContext;
  13718. var precision = parameters.precision !== undefined ? parameters.precision : 'highp';
  13719. var maxPrecision = getMaxPrecision( precision );
  13720. if ( maxPrecision !== precision ) {
  13721. console.warn( 'THREE.WebGLRenderer:', precision, 'not supported, using', maxPrecision, 'instead.' );
  13722. precision = maxPrecision;
  13723. }
  13724. var logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true;
  13725. var maxTextures = gl.getParameter( 34930 );
  13726. var maxVertexTextures = gl.getParameter( 35660 );
  13727. var maxTextureSize = gl.getParameter( 3379 );
  13728. var maxCubemapSize = gl.getParameter( 34076 );
  13729. var maxAttributes = gl.getParameter( 34921 );
  13730. var maxVertexUniforms = gl.getParameter( 36347 );
  13731. var maxVaryings = gl.getParameter( 36348 );
  13732. var maxFragmentUniforms = gl.getParameter( 36349 );
  13733. var vertexTextures = maxVertexTextures > 0;
  13734. var floatFragmentTextures = isWebGL2 || !! extensions.get( 'OES_texture_float' );
  13735. var floatVertexTextures = vertexTextures && floatFragmentTextures;
  13736. var maxSamples = isWebGL2 ? gl.getParameter( 36183 ) : 0;
  13737. return {
  13738. isWebGL2: isWebGL2,
  13739. getMaxAnisotropy: getMaxAnisotropy,
  13740. getMaxPrecision: getMaxPrecision,
  13741. precision: precision,
  13742. logarithmicDepthBuffer: logarithmicDepthBuffer,
  13743. maxTextures: maxTextures,
  13744. maxVertexTextures: maxVertexTextures,
  13745. maxTextureSize: maxTextureSize,
  13746. maxCubemapSize: maxCubemapSize,
  13747. maxAttributes: maxAttributes,
  13748. maxVertexUniforms: maxVertexUniforms,
  13749. maxVaryings: maxVaryings,
  13750. maxFragmentUniforms: maxFragmentUniforms,
  13751. vertexTextures: vertexTextures,
  13752. floatFragmentTextures: floatFragmentTextures,
  13753. floatVertexTextures: floatVertexTextures,
  13754. maxSamples: maxSamples
  13755. };
  13756. }
  13757. /**
  13758. * @author tschw
  13759. */
  13760. function WebGLClipping() {
  13761. var scope = this,
  13762. globalState = null,
  13763. numGlobalPlanes = 0,
  13764. localClippingEnabled = false,
  13765. renderingShadows = false,
  13766. plane = new Plane(),
  13767. viewNormalMatrix = new Matrix3(),
  13768. uniform = { value: null, needsUpdate: false };
  13769. this.uniform = uniform;
  13770. this.numPlanes = 0;
  13771. this.numIntersection = 0;
  13772. this.init = function ( planes, enableLocalClipping, camera ) {
  13773. var enabled =
  13774. planes.length !== 0 ||
  13775. enableLocalClipping ||
  13776. // enable state of previous frame - the clipping code has to
  13777. // run another frame in order to reset the state:
  13778. numGlobalPlanes !== 0 ||
  13779. localClippingEnabled;
  13780. localClippingEnabled = enableLocalClipping;
  13781. globalState = projectPlanes( planes, camera, 0 );
  13782. numGlobalPlanes = planes.length;
  13783. return enabled;
  13784. };
  13785. this.beginShadows = function () {
  13786. renderingShadows = true;
  13787. projectPlanes( null );
  13788. };
  13789. this.endShadows = function () {
  13790. renderingShadows = false;
  13791. resetGlobalState();
  13792. };
  13793. this.setState = function ( planes, clipIntersection, clipShadows, camera, cache, fromCache ) {
  13794. if ( ! localClippingEnabled || planes === null || planes.length === 0 || renderingShadows && ! clipShadows ) {
  13795. // there's no local clipping
  13796. if ( renderingShadows ) {
  13797. // there's no global clipping
  13798. projectPlanes( null );
  13799. } else {
  13800. resetGlobalState();
  13801. }
  13802. } else {
  13803. var nGlobal = renderingShadows ? 0 : numGlobalPlanes,
  13804. lGlobal = nGlobal * 4,
  13805. dstArray = cache.clippingState || null;
  13806. uniform.value = dstArray; // ensure unique state
  13807. dstArray = projectPlanes( planes, camera, lGlobal, fromCache );
  13808. for ( var i = 0; i !== lGlobal; ++ i ) {
  13809. dstArray[ i ] = globalState[ i ];
  13810. }
  13811. cache.clippingState = dstArray;
  13812. this.numIntersection = clipIntersection ? this.numPlanes : 0;
  13813. this.numPlanes += nGlobal;
  13814. }
  13815. };
  13816. function resetGlobalState() {
  13817. if ( uniform.value !== globalState ) {
  13818. uniform.value = globalState;
  13819. uniform.needsUpdate = numGlobalPlanes > 0;
  13820. }
  13821. scope.numPlanes = numGlobalPlanes;
  13822. scope.numIntersection = 0;
  13823. }
  13824. function projectPlanes( planes, camera, dstOffset, skipTransform ) {
  13825. var nPlanes = planes !== null ? planes.length : 0,
  13826. dstArray = null;
  13827. if ( nPlanes !== 0 ) {
  13828. dstArray = uniform.value;
  13829. if ( skipTransform !== true || dstArray === null ) {
  13830. var flatSize = dstOffset + nPlanes * 4,
  13831. viewMatrix = camera.matrixWorldInverse;
  13832. viewNormalMatrix.getNormalMatrix( viewMatrix );
  13833. if ( dstArray === null || dstArray.length < flatSize ) {
  13834. dstArray = new Float32Array( flatSize );
  13835. }
  13836. for ( var i = 0, i4 = dstOffset; i !== nPlanes; ++ i, i4 += 4 ) {
  13837. plane.copy( planes[ i ] ).applyMatrix4( viewMatrix, viewNormalMatrix );
  13838. plane.normal.toArray( dstArray, i4 );
  13839. dstArray[ i4 + 3 ] = plane.constant;
  13840. }
  13841. }
  13842. uniform.value = dstArray;
  13843. uniform.needsUpdate = true;
  13844. }
  13845. scope.numPlanes = nPlanes;
  13846. return dstArray;
  13847. }
  13848. }
  13849. /**
  13850. * @author mrdoob / http://mrdoob.com/
  13851. */
  13852. function WebGLExtensions( gl ) {
  13853. var extensions = {};
  13854. return {
  13855. get: function ( name ) {
  13856. if ( extensions[ name ] !== undefined ) {
  13857. return extensions[ name ];
  13858. }
  13859. var extension;
  13860. switch ( name ) {
  13861. case 'WEBGL_depth_texture':
  13862. extension = gl.getExtension( 'WEBGL_depth_texture' ) || gl.getExtension( 'MOZ_WEBGL_depth_texture' ) || gl.getExtension( 'WEBKIT_WEBGL_depth_texture' );
  13863. break;
  13864. case 'EXT_texture_filter_anisotropic':
  13865. extension = gl.getExtension( 'EXT_texture_filter_anisotropic' ) || gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) || gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' );
  13866. break;
  13867. case 'WEBGL_compressed_texture_s3tc':
  13868. extension = gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' );
  13869. break;
  13870. case 'WEBGL_compressed_texture_pvrtc':
  13871. extension = gl.getExtension( 'WEBGL_compressed_texture_pvrtc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_pvrtc' );
  13872. break;
  13873. default:
  13874. extension = gl.getExtension( name );
  13875. }
  13876. if ( extension === null ) {
  13877. console.warn( 'THREE.WebGLRenderer: ' + name + ' extension not supported.' );
  13878. }
  13879. extensions[ name ] = extension;
  13880. return extension;
  13881. }
  13882. };
  13883. }
  13884. /**
  13885. * @author mrdoob / http://mrdoob.com/
  13886. */
  13887. function WebGLGeometries( gl, attributes, info ) {
  13888. var geometries = {};
  13889. var wireframeAttributes = {};
  13890. function onGeometryDispose( event ) {
  13891. var geometry = event.target;
  13892. var buffergeometry = geometries[ geometry.id ];
  13893. if ( buffergeometry.index !== null ) {
  13894. attributes.remove( buffergeometry.index );
  13895. }
  13896. for ( var name in buffergeometry.attributes ) {
  13897. attributes.remove( buffergeometry.attributes[ name ] );
  13898. }
  13899. geometry.removeEventListener( 'dispose', onGeometryDispose );
  13900. delete geometries[ geometry.id ];
  13901. var attribute = wireframeAttributes[ buffergeometry.id ];
  13902. if ( attribute ) {
  13903. attributes.remove( attribute );
  13904. delete wireframeAttributes[ buffergeometry.id ];
  13905. }
  13906. //
  13907. info.memory.geometries --;
  13908. }
  13909. function get( object, geometry ) {
  13910. var buffergeometry = geometries[ geometry.id ];
  13911. if ( buffergeometry ) return buffergeometry;
  13912. geometry.addEventListener( 'dispose', onGeometryDispose );
  13913. if ( geometry.isBufferGeometry ) {
  13914. buffergeometry = geometry;
  13915. } else if ( geometry.isGeometry ) {
  13916. if ( geometry._bufferGeometry === undefined ) {
  13917. geometry._bufferGeometry = new BufferGeometry().setFromObject( object );
  13918. }
  13919. buffergeometry = geometry._bufferGeometry;
  13920. }
  13921. geometries[ geometry.id ] = buffergeometry;
  13922. info.memory.geometries ++;
  13923. return buffergeometry;
  13924. }
  13925. function update( geometry ) {
  13926. var index = geometry.index;
  13927. var geometryAttributes = geometry.attributes;
  13928. if ( index !== null ) {
  13929. attributes.update( index, 34963 );
  13930. }
  13931. for ( var name in geometryAttributes ) {
  13932. attributes.update( geometryAttributes[ name ], 34962 );
  13933. }
  13934. // morph targets
  13935. var morphAttributes = geometry.morphAttributes;
  13936. for ( var name in morphAttributes ) {
  13937. var array = morphAttributes[ name ];
  13938. for ( var i = 0, l = array.length; i < l; i ++ ) {
  13939. attributes.update( array[ i ], 34962 );
  13940. }
  13941. }
  13942. }
  13943. function getWireframeAttribute( geometry ) {
  13944. var attribute = wireframeAttributes[ geometry.id ];
  13945. if ( attribute ) return attribute;
  13946. var indices = [];
  13947. var geometryIndex = geometry.index;
  13948. var geometryAttributes = geometry.attributes;
  13949. // console.time( 'wireframe' );
  13950. if ( geometryIndex !== null ) {
  13951. var array = geometryIndex.array;
  13952. for ( var i = 0, l = array.length; i < l; i += 3 ) {
  13953. var a = array[ i + 0 ];
  13954. var b = array[ i + 1 ];
  13955. var c = array[ i + 2 ];
  13956. indices.push( a, b, b, c, c, a );
  13957. }
  13958. } else {
  13959. var array = geometryAttributes.position.array;
  13960. for ( var i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
  13961. var a = i + 0;
  13962. var b = i + 1;
  13963. var c = i + 2;
  13964. indices.push( a, b, b, c, c, a );
  13965. }
  13966. }
  13967. // console.timeEnd( 'wireframe' );
  13968. attribute = new ( arrayMax( indices ) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 );
  13969. attributes.update( attribute, 34963 );
  13970. wireframeAttributes[ geometry.id ] = attribute;
  13971. return attribute;
  13972. }
  13973. return {
  13974. get: get,
  13975. update: update,
  13976. getWireframeAttribute: getWireframeAttribute
  13977. };
  13978. }
  13979. /**
  13980. * @author mrdoob / http://mrdoob.com/
  13981. */
  13982. function WebGLIndexedBufferRenderer( gl, extensions, info, capabilities ) {
  13983. var mode;
  13984. function setMode( value ) {
  13985. mode = value;
  13986. }
  13987. var type, bytesPerElement;
  13988. function setIndex( value ) {
  13989. type = value.type;
  13990. bytesPerElement = value.bytesPerElement;
  13991. }
  13992. function render( start, count ) {
  13993. gl.drawElements( mode, count, type, start * bytesPerElement );
  13994. info.update( count, mode );
  13995. }
  13996. function renderInstances( geometry, start, count ) {
  13997. var extension;
  13998. if ( capabilities.isWebGL2 ) {
  13999. extension = gl;
  14000. } else {
  14001. var extension = extensions.get( 'ANGLE_instanced_arrays' );
  14002. if ( extension === null ) {
  14003. console.error( 'THREE.WebGLIndexedBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  14004. return;
  14005. }
  14006. }
  14007. extension[ capabilities.isWebGL2 ? 'drawElementsInstanced' : 'drawElementsInstancedANGLE' ]( mode, count, type, start * bytesPerElement, geometry.maxInstancedCount );
  14008. info.update( count, mode, geometry.maxInstancedCount );
  14009. }
  14010. //
  14011. this.setMode = setMode;
  14012. this.setIndex = setIndex;
  14013. this.render = render;
  14014. this.renderInstances = renderInstances;
  14015. }
  14016. /**
  14017. * @author Mugen87 / https://github.com/Mugen87
  14018. */
  14019. function WebGLInfo( gl ) {
  14020. var memory = {
  14021. geometries: 0,
  14022. textures: 0
  14023. };
  14024. var render = {
  14025. frame: 0,
  14026. calls: 0,
  14027. triangles: 0,
  14028. points: 0,
  14029. lines: 0
  14030. };
  14031. function update( count, mode, instanceCount ) {
  14032. instanceCount = instanceCount || 1;
  14033. render.calls ++;
  14034. switch ( mode ) {
  14035. case 4:
  14036. render.triangles += instanceCount * ( count / 3 );
  14037. break;
  14038. case 5:
  14039. case 6:
  14040. render.triangles += instanceCount * ( count - 2 );
  14041. break;
  14042. case 1:
  14043. render.lines += instanceCount * ( count / 2 );
  14044. break;
  14045. case 3:
  14046. render.lines += instanceCount * ( count - 1 );
  14047. break;
  14048. case 2:
  14049. render.lines += instanceCount * count;
  14050. break;
  14051. case 0:
  14052. render.points += instanceCount * count;
  14053. break;
  14054. default:
  14055. console.error( 'THREE.WebGLInfo: Unknown draw mode:', mode );
  14056. break;
  14057. }
  14058. }
  14059. function reset() {
  14060. render.frame ++;
  14061. render.calls = 0;
  14062. render.triangles = 0;
  14063. render.points = 0;
  14064. render.lines = 0;
  14065. }
  14066. return {
  14067. memory: memory,
  14068. render: render,
  14069. programs: null,
  14070. autoReset: true,
  14071. reset: reset,
  14072. update: update
  14073. };
  14074. }
  14075. /**
  14076. * @author mrdoob / http://mrdoob.com/
  14077. */
  14078. function absNumericalSort( a, b ) {
  14079. return Math.abs( b[ 1 ] ) - Math.abs( a[ 1 ] );
  14080. }
  14081. function WebGLMorphtargets( gl ) {
  14082. var influencesList = {};
  14083. var morphInfluences = new Float32Array( 8 );
  14084. function update( object, geometry, material, program ) {
  14085. var objectInfluences = object.morphTargetInfluences;
  14086. var length = objectInfluences.length;
  14087. var influences = influencesList[ geometry.id ];
  14088. if ( influences === undefined ) {
  14089. // initialise list
  14090. influences = [];
  14091. for ( var i = 0; i < length; i ++ ) {
  14092. influences[ i ] = [ i, 0 ];
  14093. }
  14094. influencesList[ geometry.id ] = influences;
  14095. }
  14096. var morphTargets = material.morphTargets && geometry.morphAttributes.position;
  14097. var morphNormals = material.morphNormals && geometry.morphAttributes.normal;
  14098. // Remove current morphAttributes
  14099. for ( var i = 0; i < length; i ++ ) {
  14100. var influence = influences[ i ];
  14101. if ( influence[ 1 ] !== 0 ) {
  14102. if ( morphTargets ) geometry.removeAttribute( 'morphTarget' + i );
  14103. if ( morphNormals ) geometry.removeAttribute( 'morphNormal' + i );
  14104. }
  14105. }
  14106. // Collect influences
  14107. for ( var i = 0; i < length; i ++ ) {
  14108. var influence = influences[ i ];
  14109. influence[ 0 ] = i;
  14110. influence[ 1 ] = objectInfluences[ i ];
  14111. }
  14112. influences.sort( absNumericalSort );
  14113. // Add morphAttributes
  14114. for ( var i = 0; i < 8; i ++ ) {
  14115. var influence = influences[ i ];
  14116. if ( influence ) {
  14117. var index = influence[ 0 ];
  14118. var value = influence[ 1 ];
  14119. if ( value ) {
  14120. if ( morphTargets ) geometry.addAttribute( 'morphTarget' + i, morphTargets[ index ] );
  14121. if ( morphNormals ) geometry.addAttribute( 'morphNormal' + i, morphNormals[ index ] );
  14122. morphInfluences[ i ] = value;
  14123. continue;
  14124. }
  14125. }
  14126. morphInfluences[ i ] = 0;
  14127. }
  14128. program.getUniforms().setValue( gl, 'morphTargetInfluences', morphInfluences );
  14129. }
  14130. return {
  14131. update: update
  14132. };
  14133. }
  14134. /**
  14135. * @author mrdoob / http://mrdoob.com/
  14136. */
  14137. function WebGLObjects( geometries, info ) {
  14138. var updateList = {};
  14139. function update( object ) {
  14140. var frame = info.render.frame;
  14141. var geometry = object.geometry;
  14142. var buffergeometry = geometries.get( object, geometry );
  14143. // Update once per frame
  14144. if ( updateList[ buffergeometry.id ] !== frame ) {
  14145. if ( geometry.isGeometry ) {
  14146. buffergeometry.updateFromObject( object );
  14147. }
  14148. geometries.update( buffergeometry );
  14149. updateList[ buffergeometry.id ] = frame;
  14150. }
  14151. return buffergeometry;
  14152. }
  14153. function dispose() {
  14154. updateList = {};
  14155. }
  14156. return {
  14157. update: update,
  14158. dispose: dispose
  14159. };
  14160. }
  14161. /**
  14162. * @author mrdoob / http://mrdoob.com/
  14163. */
  14164. function CubeTexture( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ) {
  14165. images = images !== undefined ? images : [];
  14166. mapping = mapping !== undefined ? mapping : CubeReflectionMapping;
  14167. format = format !== undefined ? format : RGBFormat;
  14168. Texture.call( this, images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  14169. this.flipY = false;
  14170. }
  14171. CubeTexture.prototype = Object.create( Texture.prototype );
  14172. CubeTexture.prototype.constructor = CubeTexture;
  14173. CubeTexture.prototype.isCubeTexture = true;
  14174. Object.defineProperty( CubeTexture.prototype, 'images', {
  14175. get: function () {
  14176. return this.image;
  14177. },
  14178. set: function ( value ) {
  14179. this.image = value;
  14180. }
  14181. } );
  14182. /**
  14183. * @author Takahiro https://github.com/takahirox
  14184. */
  14185. function DataTexture2DArray( data, width, height, depth ) {
  14186. Texture.call( this, null );
  14187. this.image = { data: data, width: width, height: height, depth: depth };
  14188. this.magFilter = NearestFilter;
  14189. this.minFilter = NearestFilter;
  14190. this.wrapR = ClampToEdgeWrapping;
  14191. this.generateMipmaps = false;
  14192. this.flipY = false;
  14193. }
  14194. DataTexture2DArray.prototype = Object.create( Texture.prototype );
  14195. DataTexture2DArray.prototype.constructor = DataTexture2DArray;
  14196. DataTexture2DArray.prototype.isDataTexture2DArray = true;
  14197. /**
  14198. * @author Artur Trzesiok
  14199. */
  14200. function DataTexture3D( data, width, height, depth ) {
  14201. // We're going to add .setXXX() methods for setting properties later.
  14202. // Users can still set in DataTexture3D directly.
  14203. //
  14204. // var texture = new THREE.DataTexture3D( data, width, height, depth );
  14205. // texture.anisotropy = 16;
  14206. //
  14207. // See #14839
  14208. Texture.call( this, null );
  14209. this.image = { data: data, width: width, height: height, depth: depth };
  14210. this.magFilter = NearestFilter;
  14211. this.minFilter = NearestFilter;
  14212. this.wrapR = ClampToEdgeWrapping;
  14213. this.generateMipmaps = false;
  14214. this.flipY = false;
  14215. }
  14216. DataTexture3D.prototype = Object.create( Texture.prototype );
  14217. DataTexture3D.prototype.constructor = DataTexture3D;
  14218. DataTexture3D.prototype.isDataTexture3D = true;
  14219. /**
  14220. * @author tschw
  14221. * @author Mugen87 / https://github.com/Mugen87
  14222. * @author mrdoob / http://mrdoob.com/
  14223. *
  14224. * Uniforms of a program.
  14225. * Those form a tree structure with a special top-level container for the root,
  14226. * which you get by calling 'new WebGLUniforms( gl, program, renderer )'.
  14227. *
  14228. *
  14229. * Properties of inner nodes including the top-level container:
  14230. *
  14231. * .seq - array of nested uniforms
  14232. * .map - nested uniforms by name
  14233. *
  14234. *
  14235. * Methods of all nodes except the top-level container:
  14236. *
  14237. * .setValue( gl, value, [renderer] )
  14238. *
  14239. * uploads a uniform value(s)
  14240. * the 'renderer' parameter is needed for sampler uniforms
  14241. *
  14242. *
  14243. * Static methods of the top-level container (renderer factorizations):
  14244. *
  14245. * .upload( gl, seq, values, renderer )
  14246. *
  14247. * sets uniforms in 'seq' to 'values[id].value'
  14248. *
  14249. * .seqWithValue( seq, values ) : filteredSeq
  14250. *
  14251. * filters 'seq' entries with corresponding entry in values
  14252. *
  14253. *
  14254. * Methods of the top-level container (renderer factorizations):
  14255. *
  14256. * .setValue( gl, name, value )
  14257. *
  14258. * sets uniform with name 'name' to 'value'
  14259. *
  14260. * .set( gl, obj, prop )
  14261. *
  14262. * sets uniform from object and property with same name than uniform
  14263. *
  14264. * .setOptional( gl, obj, prop )
  14265. *
  14266. * like .set for an optional property of the object
  14267. *
  14268. */
  14269. var emptyTexture = new Texture();
  14270. var emptyTexture2dArray = new DataTexture2DArray();
  14271. var emptyTexture3d = new DataTexture3D();
  14272. var emptyCubeTexture = new CubeTexture();
  14273. // --- Base for inner nodes (including the root) ---
  14274. function UniformContainer() {
  14275. this.seq = [];
  14276. this.map = {};
  14277. }
  14278. // --- Utilities ---
  14279. // Array Caches (provide typed arrays for temporary by size)
  14280. var arrayCacheF32 = [];
  14281. var arrayCacheI32 = [];
  14282. // Float32Array caches used for uploading Matrix uniforms
  14283. var mat4array = new Float32Array( 16 );
  14284. var mat3array = new Float32Array( 9 );
  14285. var mat2array = new Float32Array( 4 );
  14286. // Flattening for arrays of vectors and matrices
  14287. function flatten( array, nBlocks, blockSize ) {
  14288. var firstElem = array[ 0 ];
  14289. if ( firstElem <= 0 || firstElem > 0 ) return array;
  14290. // unoptimized: ! isNaN( firstElem )
  14291. // see http://jacksondunstan.com/articles/983
  14292. var n = nBlocks * blockSize,
  14293. r = arrayCacheF32[ n ];
  14294. if ( r === undefined ) {
  14295. r = new Float32Array( n );
  14296. arrayCacheF32[ n ] = r;
  14297. }
  14298. if ( nBlocks !== 0 ) {
  14299. firstElem.toArray( r, 0 );
  14300. for ( var i = 1, offset = 0; i !== nBlocks; ++ i ) {
  14301. offset += blockSize;
  14302. array[ i ].toArray( r, offset );
  14303. }
  14304. }
  14305. return r;
  14306. }
  14307. function arraysEqual( a, b ) {
  14308. if ( a.length !== b.length ) return false;
  14309. for ( var i = 0, l = a.length; i < l; i ++ ) {
  14310. if ( a[ i ] !== b[ i ] ) return false;
  14311. }
  14312. return true;
  14313. }
  14314. function copyArray( a, b ) {
  14315. for ( var i = 0, l = b.length; i < l; i ++ ) {
  14316. a[ i ] = b[ i ];
  14317. }
  14318. }
  14319. // Texture unit allocation
  14320. function allocTexUnits( renderer, n ) {
  14321. var r = arrayCacheI32[ n ];
  14322. if ( r === undefined ) {
  14323. r = new Int32Array( n );
  14324. arrayCacheI32[ n ] = r;
  14325. }
  14326. for ( var i = 0; i !== n; ++ i )
  14327. r[ i ] = renderer.allocTextureUnit();
  14328. return r;
  14329. }
  14330. // --- Setters ---
  14331. // Note: Defining these methods externally, because they come in a bunch
  14332. // and this way their names minify.
  14333. // Single scalar
  14334. function setValue1f( gl, v ) {
  14335. var cache = this.cache;
  14336. if ( cache[ 0 ] === v ) return;
  14337. gl.uniform1f( this.addr, v );
  14338. cache[ 0 ] = v;
  14339. }
  14340. function setValue1i( gl, v ) {
  14341. var cache = this.cache;
  14342. if ( cache[ 0 ] === v ) return;
  14343. gl.uniform1i( this.addr, v );
  14344. cache[ 0 ] = v;
  14345. }
  14346. // Single float vector (from flat array or THREE.VectorN)
  14347. function setValue2fv( gl, v ) {
  14348. var cache = this.cache;
  14349. if ( v.x !== undefined ) {
  14350. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) {
  14351. gl.uniform2f( this.addr, v.x, v.y );
  14352. cache[ 0 ] = v.x;
  14353. cache[ 1 ] = v.y;
  14354. }
  14355. } else {
  14356. if ( arraysEqual( cache, v ) ) return;
  14357. gl.uniform2fv( this.addr, v );
  14358. copyArray( cache, v );
  14359. }
  14360. }
  14361. function setValue3fv( gl, v ) {
  14362. var cache = this.cache;
  14363. if ( v.x !== undefined ) {
  14364. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) {
  14365. gl.uniform3f( this.addr, v.x, v.y, v.z );
  14366. cache[ 0 ] = v.x;
  14367. cache[ 1 ] = v.y;
  14368. cache[ 2 ] = v.z;
  14369. }
  14370. } else if ( v.r !== undefined ) {
  14371. if ( cache[ 0 ] !== v.r || cache[ 1 ] !== v.g || cache[ 2 ] !== v.b ) {
  14372. gl.uniform3f( this.addr, v.r, v.g, v.b );
  14373. cache[ 0 ] = v.r;
  14374. cache[ 1 ] = v.g;
  14375. cache[ 2 ] = v.b;
  14376. }
  14377. } else {
  14378. if ( arraysEqual( cache, v ) ) return;
  14379. gl.uniform3fv( this.addr, v );
  14380. copyArray( cache, v );
  14381. }
  14382. }
  14383. function setValue4fv( gl, v ) {
  14384. var cache = this.cache;
  14385. if ( v.x !== undefined ) {
  14386. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) {
  14387. gl.uniform4f( this.addr, v.x, v.y, v.z, v.w );
  14388. cache[ 0 ] = v.x;
  14389. cache[ 1 ] = v.y;
  14390. cache[ 2 ] = v.z;
  14391. cache[ 3 ] = v.w;
  14392. }
  14393. } else {
  14394. if ( arraysEqual( cache, v ) ) return;
  14395. gl.uniform4fv( this.addr, v );
  14396. copyArray( cache, v );
  14397. }
  14398. }
  14399. // Single matrix (from flat array or MatrixN)
  14400. function setValue2fm( gl, v ) {
  14401. var cache = this.cache;
  14402. var elements = v.elements;
  14403. if ( elements === undefined ) {
  14404. if ( arraysEqual( cache, v ) ) return;
  14405. gl.uniformMatrix2fv( this.addr, false, v );
  14406. copyArray( cache, v );
  14407. } else {
  14408. if ( arraysEqual( cache, elements ) ) return;
  14409. mat2array.set( elements );
  14410. gl.uniformMatrix2fv( this.addr, false, mat2array );
  14411. copyArray( cache, elements );
  14412. }
  14413. }
  14414. function setValue3fm( gl, v ) {
  14415. var cache = this.cache;
  14416. var elements = v.elements;
  14417. if ( elements === undefined ) {
  14418. if ( arraysEqual( cache, v ) ) return;
  14419. gl.uniformMatrix3fv( this.addr, false, v );
  14420. copyArray( cache, v );
  14421. } else {
  14422. if ( arraysEqual( cache, elements ) ) return;
  14423. mat3array.set( elements );
  14424. gl.uniformMatrix3fv( this.addr, false, mat3array );
  14425. copyArray( cache, elements );
  14426. }
  14427. }
  14428. function setValue4fm( gl, v ) {
  14429. var cache = this.cache;
  14430. var elements = v.elements;
  14431. if ( elements === undefined ) {
  14432. if ( arraysEqual( cache, v ) ) return;
  14433. gl.uniformMatrix4fv( this.addr, false, v );
  14434. copyArray( cache, v );
  14435. } else {
  14436. if ( arraysEqual( cache, elements ) ) return;
  14437. mat4array.set( elements );
  14438. gl.uniformMatrix4fv( this.addr, false, mat4array );
  14439. copyArray( cache, elements );
  14440. }
  14441. }
  14442. // Single texture (2D / Cube)
  14443. function setValueT1( gl, v, renderer ) {
  14444. var cache = this.cache;
  14445. var unit = renderer.allocTextureUnit();
  14446. if ( cache[ 0 ] !== unit ) {
  14447. gl.uniform1i( this.addr, unit );
  14448. cache[ 0 ] = unit;
  14449. }
  14450. renderer.setTexture2D( v || emptyTexture, unit );
  14451. }
  14452. function setValueT2DArray1( gl, v, renderer ) {
  14453. var cache = this.cache;
  14454. var unit = renderer.allocTextureUnit();
  14455. if ( cache[ 0 ] !== unit ) {
  14456. gl.uniform1i( this.addr, unit );
  14457. cache[ 0 ] = unit;
  14458. }
  14459. renderer.setTexture2DArray( v || emptyTexture2dArray, unit );
  14460. }
  14461. function setValueT3D1( gl, v, renderer ) {
  14462. var cache = this.cache;
  14463. var unit = renderer.allocTextureUnit();
  14464. if ( cache[ 0 ] !== unit ) {
  14465. gl.uniform1i( this.addr, unit );
  14466. cache[ 0 ] = unit;
  14467. }
  14468. renderer.setTexture3D( v || emptyTexture3d, unit );
  14469. }
  14470. function setValueT6( gl, v, renderer ) {
  14471. var cache = this.cache;
  14472. var unit = renderer.allocTextureUnit();
  14473. if ( cache[ 0 ] !== unit ) {
  14474. gl.uniform1i( this.addr, unit );
  14475. cache[ 0 ] = unit;
  14476. }
  14477. renderer.setTextureCube( v || emptyCubeTexture, unit );
  14478. }
  14479. // Integer / Boolean vectors or arrays thereof (always flat arrays)
  14480. function setValue2iv( gl, v ) {
  14481. var cache = this.cache;
  14482. if ( arraysEqual( cache, v ) ) return;
  14483. gl.uniform2iv( this.addr, v );
  14484. copyArray( cache, v );
  14485. }
  14486. function setValue3iv( gl, v ) {
  14487. var cache = this.cache;
  14488. if ( arraysEqual( cache, v ) ) return;
  14489. gl.uniform3iv( this.addr, v );
  14490. copyArray( cache, v );
  14491. }
  14492. function setValue4iv( gl, v ) {
  14493. var cache = this.cache;
  14494. if ( arraysEqual( cache, v ) ) return;
  14495. gl.uniform4iv( this.addr, v );
  14496. copyArray( cache, v );
  14497. }
  14498. // Helper to pick the right setter for the singular case
  14499. function getSingularSetter( type ) {
  14500. switch ( type ) {
  14501. case 0x1406: return setValue1f; // FLOAT
  14502. case 0x8b50: return setValue2fv; // _VEC2
  14503. case 0x8b51: return setValue3fv; // _VEC3
  14504. case 0x8b52: return setValue4fv; // _VEC4
  14505. case 0x8b5a: return setValue2fm; // _MAT2
  14506. case 0x8b5b: return setValue3fm; // _MAT3
  14507. case 0x8b5c: return setValue4fm; // _MAT4
  14508. case 0x8b5e: case 0x8d66: return setValueT1; // SAMPLER_2D, SAMPLER_EXTERNAL_OES
  14509. case 0x8b5f: return setValueT3D1; // SAMPLER_3D
  14510. case 0x8b60: return setValueT6; // SAMPLER_CUBE
  14511. case 0x8DC1: return setValueT2DArray1; // SAMPLER_2D_ARRAY
  14512. case 0x1404: case 0x8b56: return setValue1i; // INT, BOOL
  14513. case 0x8b53: case 0x8b57: return setValue2iv; // _VEC2
  14514. case 0x8b54: case 0x8b58: return setValue3iv; // _VEC3
  14515. case 0x8b55: case 0x8b59: return setValue4iv; // _VEC4
  14516. }
  14517. }
  14518. // Array of scalars
  14519. function setValue1fv( gl, v ) {
  14520. var cache = this.cache;
  14521. if ( arraysEqual( cache, v ) ) return;
  14522. gl.uniform1fv( this.addr, v );
  14523. copyArray( cache, v );
  14524. }
  14525. function setValue1iv( gl, v ) {
  14526. var cache = this.cache;
  14527. if ( arraysEqual( cache, v ) ) return;
  14528. gl.uniform1iv( this.addr, v );
  14529. copyArray( cache, v );
  14530. }
  14531. // Array of vectors (flat or from THREE classes)
  14532. function setValueV2a( gl, v ) {
  14533. var cache = this.cache;
  14534. var data = flatten( v, this.size, 2 );
  14535. if ( arraysEqual( cache, data ) ) return;
  14536. gl.uniform2fv( this.addr, data );
  14537. this.updateCache( data );
  14538. }
  14539. function setValueV3a( gl, v ) {
  14540. var cache = this.cache;
  14541. var data = flatten( v, this.size, 3 );
  14542. if ( arraysEqual( cache, data ) ) return;
  14543. gl.uniform3fv( this.addr, data );
  14544. this.updateCache( data );
  14545. }
  14546. function setValueV4a( gl, v ) {
  14547. var cache = this.cache;
  14548. var data = flatten( v, this.size, 4 );
  14549. if ( arraysEqual( cache, data ) ) return;
  14550. gl.uniform4fv( this.addr, data );
  14551. this.updateCache( data );
  14552. }
  14553. // Array of matrices (flat or from THREE clases)
  14554. function setValueM2a( gl, v ) {
  14555. var cache = this.cache;
  14556. var data = flatten( v, this.size, 4 );
  14557. if ( arraysEqual( cache, data ) ) return;
  14558. gl.uniformMatrix2fv( this.addr, false, data );
  14559. this.updateCache( data );
  14560. }
  14561. function setValueM3a( gl, v ) {
  14562. var cache = this.cache;
  14563. var data = flatten( v, this.size, 9 );
  14564. if ( arraysEqual( cache, data ) ) return;
  14565. gl.uniformMatrix3fv( this.addr, false, data );
  14566. this.updateCache( data );
  14567. }
  14568. function setValueM4a( gl, v ) {
  14569. var cache = this.cache;
  14570. var data = flatten( v, this.size, 16 );
  14571. if ( arraysEqual( cache, data ) ) return;
  14572. gl.uniformMatrix4fv( this.addr, false, data );
  14573. this.updateCache( data );
  14574. }
  14575. // Array of textures (2D / Cube)
  14576. function setValueT1a( gl, v, renderer ) {
  14577. var cache = this.cache;
  14578. var n = v.length;
  14579. var units = allocTexUnits( renderer, n );
  14580. if ( arraysEqual( cache, units ) === false ) {
  14581. gl.uniform1iv( this.addr, units );
  14582. copyArray( cache, units );
  14583. }
  14584. for ( var i = 0; i !== n; ++ i ) {
  14585. renderer.setTexture2D( v[ i ] || emptyTexture, units[ i ] );
  14586. }
  14587. }
  14588. function setValueT6a( gl, v, renderer ) {
  14589. var cache = this.cache;
  14590. var n = v.length;
  14591. var units = allocTexUnits( renderer, n );
  14592. if ( arraysEqual( cache, units ) === false ) {
  14593. gl.uniform1iv( this.addr, units );
  14594. copyArray( cache, units );
  14595. }
  14596. for ( var i = 0; i !== n; ++ i ) {
  14597. renderer.setTextureCube( v[ i ] || emptyCubeTexture, units[ i ] );
  14598. }
  14599. }
  14600. // Helper to pick the right setter for a pure (bottom-level) array
  14601. function getPureArraySetter( type ) {
  14602. switch ( type ) {
  14603. case 0x1406: return setValue1fv; // FLOAT
  14604. case 0x8b50: return setValueV2a; // _VEC2
  14605. case 0x8b51: return setValueV3a; // _VEC3
  14606. case 0x8b52: return setValueV4a; // _VEC4
  14607. case 0x8b5a: return setValueM2a; // _MAT2
  14608. case 0x8b5b: return setValueM3a; // _MAT3
  14609. case 0x8b5c: return setValueM4a; // _MAT4
  14610. case 0x8b5e: return setValueT1a; // SAMPLER_2D
  14611. case 0x8b60: return setValueT6a; // SAMPLER_CUBE
  14612. case 0x1404: case 0x8b56: return setValue1iv; // INT, BOOL
  14613. case 0x8b53: case 0x8b57: return setValue2iv; // _VEC2
  14614. case 0x8b54: case 0x8b58: return setValue3iv; // _VEC3
  14615. case 0x8b55: case 0x8b59: return setValue4iv; // _VEC4
  14616. }
  14617. }
  14618. // --- Uniform Classes ---
  14619. function SingleUniform( id, activeInfo, addr ) {
  14620. this.id = id;
  14621. this.addr = addr;
  14622. this.cache = [];
  14623. this.setValue = getSingularSetter( activeInfo.type );
  14624. // this.path = activeInfo.name; // DEBUG
  14625. }
  14626. function PureArrayUniform( id, activeInfo, addr ) {
  14627. this.id = id;
  14628. this.addr = addr;
  14629. this.cache = [];
  14630. this.size = activeInfo.size;
  14631. this.setValue = getPureArraySetter( activeInfo.type );
  14632. // this.path = activeInfo.name; // DEBUG
  14633. }
  14634. PureArrayUniform.prototype.updateCache = function ( data ) {
  14635. var cache = this.cache;
  14636. if ( data instanceof Float32Array && cache.length !== data.length ) {
  14637. this.cache = new Float32Array( data.length );
  14638. }
  14639. copyArray( cache, data );
  14640. };
  14641. function StructuredUniform( id ) {
  14642. this.id = id;
  14643. UniformContainer.call( this ); // mix-in
  14644. }
  14645. StructuredUniform.prototype.setValue = function ( gl, value, renderer ) {
  14646. var seq = this.seq;
  14647. for ( var i = 0, n = seq.length; i !== n; ++ i ) {
  14648. var u = seq[ i ];
  14649. u.setValue( gl, value[ u.id ], renderer );
  14650. }
  14651. };
  14652. // --- Top-level ---
  14653. // Parser - builds up the property tree from the path strings
  14654. var RePathPart = /([\w\d_]+)(\])?(\[|\.)?/g;
  14655. // extracts
  14656. // - the identifier (member name or array index)
  14657. // - followed by an optional right bracket (found when array index)
  14658. // - followed by an optional left bracket or dot (type of subscript)
  14659. //
  14660. // Note: These portions can be read in a non-overlapping fashion and
  14661. // allow straightforward parsing of the hierarchy that WebGL encodes
  14662. // in the uniform names.
  14663. function addUniform( container, uniformObject ) {
  14664. container.seq.push( uniformObject );
  14665. container.map[ uniformObject.id ] = uniformObject;
  14666. }
  14667. function parseUniform( activeInfo, addr, container ) {
  14668. var path = activeInfo.name,
  14669. pathLength = path.length;
  14670. // reset RegExp object, because of the early exit of a previous run
  14671. RePathPart.lastIndex = 0;
  14672. while ( true ) {
  14673. var match = RePathPart.exec( path ),
  14674. matchEnd = RePathPart.lastIndex,
  14675. id = match[ 1 ],
  14676. idIsIndex = match[ 2 ] === ']',
  14677. subscript = match[ 3 ];
  14678. if ( idIsIndex ) id = id | 0; // convert to integer
  14679. if ( subscript === undefined || subscript === '[' && matchEnd + 2 === pathLength ) {
  14680. // bare name or "pure" bottom-level array "[0]" suffix
  14681. addUniform( container, subscript === undefined ?
  14682. new SingleUniform( id, activeInfo, addr ) :
  14683. new PureArrayUniform( id, activeInfo, addr ) );
  14684. break;
  14685. } else {
  14686. // step into inner node / create it in case it doesn't exist
  14687. var map = container.map, next = map[ id ];
  14688. if ( next === undefined ) {
  14689. next = new StructuredUniform( id );
  14690. addUniform( container, next );
  14691. }
  14692. container = next;
  14693. }
  14694. }
  14695. }
  14696. // Root Container
  14697. function WebGLUniforms( gl, program, renderer ) {
  14698. UniformContainer.call( this );
  14699. this.renderer = renderer;
  14700. var n = gl.getProgramParameter( program, 35718 );
  14701. for ( var i = 0; i < n; ++ i ) {
  14702. var info = gl.getActiveUniform( program, i ),
  14703. addr = gl.getUniformLocation( program, info.name );
  14704. parseUniform( info, addr, this );
  14705. }
  14706. }
  14707. WebGLUniforms.prototype.setValue = function ( gl, name, value ) {
  14708. var u = this.map[ name ];
  14709. if ( u !== undefined ) u.setValue( gl, value, this.renderer );
  14710. };
  14711. WebGLUniforms.prototype.setOptional = function ( gl, object, name ) {
  14712. var v = object[ name ];
  14713. if ( v !== undefined ) this.setValue( gl, name, v );
  14714. };
  14715. // Static interface
  14716. WebGLUniforms.upload = function ( gl, seq, values, renderer ) {
  14717. for ( var i = 0, n = seq.length; i !== n; ++ i ) {
  14718. var u = seq[ i ],
  14719. v = values[ u.id ];
  14720. if ( v.needsUpdate !== false ) {
  14721. // note: always updating when .needsUpdate is undefined
  14722. u.setValue( gl, v.value, renderer );
  14723. }
  14724. }
  14725. };
  14726. WebGLUniforms.seqWithValue = function ( seq, values ) {
  14727. var r = [];
  14728. for ( var i = 0, n = seq.length; i !== n; ++ i ) {
  14729. var u = seq[ i ];
  14730. if ( u.id in values ) r.push( u );
  14731. }
  14732. return r;
  14733. };
  14734. /**
  14735. * @author mrdoob / http://mrdoob.com/
  14736. */
  14737. function addLineNumbers( string ) {
  14738. var lines = string.split( '\n' );
  14739. for ( var i = 0; i < lines.length; i ++ ) {
  14740. lines[ i ] = ( i + 1 ) + ': ' + lines[ i ];
  14741. }
  14742. return lines.join( '\n' );
  14743. }
  14744. function WebGLShader( gl, type, string ) {
  14745. var shader = gl.createShader( type );
  14746. gl.shaderSource( shader, string );
  14747. gl.compileShader( shader );
  14748. if ( gl.getShaderParameter( shader, 35713 ) === false ) {
  14749. console.error( 'THREE.WebGLShader: Shader couldn\'t compile.' );
  14750. }
  14751. if ( gl.getShaderInfoLog( shader ) !== '' ) {
  14752. console.warn( 'THREE.WebGLShader: gl.getShaderInfoLog()', type === 35633 ? 'vertex' : 'fragment', gl.getShaderInfoLog( shader ), addLineNumbers( string ) );
  14753. }
  14754. // --enable-privileged-webgl-extension
  14755. // console.log( type, gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) );
  14756. return shader;
  14757. }
  14758. /**
  14759. * @author mrdoob / http://mrdoob.com/
  14760. */
  14761. var programIdCount = 0;
  14762. function getEncodingComponents( encoding ) {
  14763. switch ( encoding ) {
  14764. case LinearEncoding:
  14765. return [ 'Linear', '( value )' ];
  14766. case sRGBEncoding:
  14767. return [ 'sRGB', '( value )' ];
  14768. case RGBEEncoding:
  14769. return [ 'RGBE', '( value )' ];
  14770. case RGBM7Encoding:
  14771. return [ 'RGBM', '( value, 7.0 )' ];
  14772. case RGBM16Encoding:
  14773. return [ 'RGBM', '( value, 16.0 )' ];
  14774. case RGBDEncoding:
  14775. return [ 'RGBD', '( value, 256.0 )' ];
  14776. case GammaEncoding:
  14777. return [ 'Gamma', '( value, float( GAMMA_FACTOR ) )' ];
  14778. default:
  14779. throw new Error( 'unsupported encoding: ' + encoding );
  14780. }
  14781. }
  14782. function getTexelDecodingFunction( functionName, encoding ) {
  14783. var components = getEncodingComponents( encoding );
  14784. return 'vec4 ' + functionName + '( vec4 value ) { return ' + components[ 0 ] + 'ToLinear' + components[ 1 ] + '; }';
  14785. }
  14786. function getTexelEncodingFunction( functionName, encoding ) {
  14787. var components = getEncodingComponents( encoding );
  14788. return 'vec4 ' + functionName + '( vec4 value ) { return LinearTo' + components[ 0 ] + components[ 1 ] + '; }';
  14789. }
  14790. function getToneMappingFunction( functionName, toneMapping ) {
  14791. var toneMappingName;
  14792. switch ( toneMapping ) {
  14793. case LinearToneMapping:
  14794. toneMappingName = 'Linear';
  14795. break;
  14796. case ReinhardToneMapping:
  14797. toneMappingName = 'Reinhard';
  14798. break;
  14799. case Uncharted2ToneMapping:
  14800. toneMappingName = 'Uncharted2';
  14801. break;
  14802. case CineonToneMapping:
  14803. toneMappingName = 'OptimizedCineon';
  14804. break;
  14805. case ACESFilmicToneMapping:
  14806. toneMappingName = 'ACESFilmic';
  14807. break;
  14808. default:
  14809. throw new Error( 'unsupported toneMapping: ' + toneMapping );
  14810. }
  14811. return 'vec3 ' + functionName + '( vec3 color ) { return ' + toneMappingName + 'ToneMapping( color ); }';
  14812. }
  14813. function generateExtensions( extensions, parameters, rendererExtensions ) {
  14814. extensions = extensions || {};
  14815. var chunks = [
  14816. ( extensions.derivatives || parameters.envMapCubeUV || parameters.bumpMap || ( parameters.normalMap && ! parameters.objectSpaceNormalMap ) || parameters.flatShading ) ? '#extension GL_OES_standard_derivatives : enable' : '',
  14817. ( extensions.fragDepth || parameters.logarithmicDepthBuffer ) && rendererExtensions.get( 'EXT_frag_depth' ) ? '#extension GL_EXT_frag_depth : enable' : '',
  14818. ( extensions.drawBuffers ) && rendererExtensions.get( 'WEBGL_draw_buffers' ) ? '#extension GL_EXT_draw_buffers : require' : '',
  14819. ( extensions.shaderTextureLOD || parameters.envMap ) && rendererExtensions.get( 'EXT_shader_texture_lod' ) ? '#extension GL_EXT_shader_texture_lod : enable' : ''
  14820. ];
  14821. return chunks.filter( filterEmptyLine ).join( '\n' );
  14822. }
  14823. function generateDefines( defines ) {
  14824. var chunks = [];
  14825. for ( var name in defines ) {
  14826. var value = defines[ name ];
  14827. if ( value === false ) continue;
  14828. chunks.push( '#define ' + name + ' ' + value );
  14829. }
  14830. return chunks.join( '\n' );
  14831. }
  14832. function fetchAttributeLocations( gl, program ) {
  14833. var attributes = {};
  14834. var n = gl.getProgramParameter( program, 35721 );
  14835. for ( var i = 0; i < n; i ++ ) {
  14836. var info = gl.getActiveAttrib( program, i );
  14837. var name = info.name;
  14838. // console.log( 'THREE.WebGLProgram: ACTIVE VERTEX ATTRIBUTE:', name, i );
  14839. attributes[ name ] = gl.getAttribLocation( program, name );
  14840. }
  14841. return attributes;
  14842. }
  14843. function filterEmptyLine( string ) {
  14844. return string !== '';
  14845. }
  14846. function replaceLightNums( string, parameters ) {
  14847. return string
  14848. .replace( /NUM_DIR_LIGHTS/g, parameters.numDirLights )
  14849. .replace( /NUM_SPOT_LIGHTS/g, parameters.numSpotLights )
  14850. .replace( /NUM_RECT_AREA_LIGHTS/g, parameters.numRectAreaLights )
  14851. .replace( /NUM_POINT_LIGHTS/g, parameters.numPointLights )
  14852. .replace( /NUM_HEMI_LIGHTS/g, parameters.numHemiLights );
  14853. }
  14854. function replaceClippingPlaneNums( string, parameters ) {
  14855. return string
  14856. .replace( /NUM_CLIPPING_PLANES/g, parameters.numClippingPlanes )
  14857. .replace( /UNION_CLIPPING_PLANES/g, ( parameters.numClippingPlanes - parameters.numClipIntersection ) );
  14858. }
  14859. function parseIncludes( string ) {
  14860. var pattern = /^[ \t]*#include +<([\w\d./]+)>/gm;
  14861. function replace( match, include ) {
  14862. var replace = ShaderChunk[ include ];
  14863. if ( replace === undefined ) {
  14864. throw new Error( 'Can not resolve #include <' + include + '>' );
  14865. }
  14866. return parseIncludes( replace );
  14867. }
  14868. return string.replace( pattern, replace );
  14869. }
  14870. function unrollLoops( string ) {
  14871. var pattern = /#pragma unroll_loop[\s]+?for \( int i \= (\d+)\; i < (\d+)\; i \+\+ \) \{([\s\S]+?)(?=\})\}/g;
  14872. function replace( match, start, end, snippet ) {
  14873. var unroll = '';
  14874. for ( var i = parseInt( start ); i < parseInt( end ); i ++ ) {
  14875. unroll += snippet.replace( /\[ i \]/g, '[ ' + i + ' ]' );
  14876. }
  14877. return unroll;
  14878. }
  14879. return string.replace( pattern, replace );
  14880. }
  14881. function WebGLProgram( renderer, extensions, code, material, shader, parameters, capabilities ) {
  14882. var gl = renderer.context;
  14883. var defines = material.defines;
  14884. var vertexShader = shader.vertexShader;
  14885. var fragmentShader = shader.fragmentShader;
  14886. var shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC';
  14887. if ( parameters.shadowMapType === PCFShadowMap ) {
  14888. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF';
  14889. } else if ( parameters.shadowMapType === PCFSoftShadowMap ) {
  14890. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT';
  14891. }
  14892. var envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  14893. var envMapModeDefine = 'ENVMAP_MODE_REFLECTION';
  14894. var envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  14895. if ( parameters.envMap ) {
  14896. switch ( material.envMap.mapping ) {
  14897. case CubeReflectionMapping:
  14898. case CubeRefractionMapping:
  14899. envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  14900. break;
  14901. case CubeUVReflectionMapping:
  14902. case CubeUVRefractionMapping:
  14903. envMapTypeDefine = 'ENVMAP_TYPE_CUBE_UV';
  14904. break;
  14905. case EquirectangularReflectionMapping:
  14906. case EquirectangularRefractionMapping:
  14907. envMapTypeDefine = 'ENVMAP_TYPE_EQUIREC';
  14908. break;
  14909. case SphericalReflectionMapping:
  14910. envMapTypeDefine = 'ENVMAP_TYPE_SPHERE';
  14911. break;
  14912. }
  14913. switch ( material.envMap.mapping ) {
  14914. case CubeRefractionMapping:
  14915. case EquirectangularRefractionMapping:
  14916. envMapModeDefine = 'ENVMAP_MODE_REFRACTION';
  14917. break;
  14918. }
  14919. switch ( material.combine ) {
  14920. case MultiplyOperation:
  14921. envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  14922. break;
  14923. case MixOperation:
  14924. envMapBlendingDefine = 'ENVMAP_BLENDING_MIX';
  14925. break;
  14926. case AddOperation:
  14927. envMapBlendingDefine = 'ENVMAP_BLENDING_ADD';
  14928. break;
  14929. }
  14930. }
  14931. var gammaFactorDefine = ( renderer.gammaFactor > 0 ) ? renderer.gammaFactor : 1.0;
  14932. // console.log( 'building new program ' );
  14933. //
  14934. var customExtensions = capabilities.isWebGL2 ? '' : generateExtensions( material.extensions, parameters, extensions );
  14935. var customDefines = generateDefines( defines );
  14936. //
  14937. var program = gl.createProgram();
  14938. var prefixVertex, prefixFragment;
  14939. if ( material.isRawShaderMaterial ) {
  14940. prefixVertex = [
  14941. customDefines
  14942. ].filter( filterEmptyLine ).join( '\n' );
  14943. if ( prefixVertex.length > 0 ) {
  14944. prefixVertex += '\n';
  14945. }
  14946. prefixFragment = [
  14947. customExtensions,
  14948. customDefines
  14949. ].filter( filterEmptyLine ).join( '\n' );
  14950. if ( prefixFragment.length > 0 ) {
  14951. prefixFragment += '\n';
  14952. }
  14953. } else {
  14954. prefixVertex = [
  14955. 'precision ' + parameters.precision + ' float;',
  14956. 'precision ' + parameters.precision + ' int;',
  14957. '#define SHADER_NAME ' + shader.name,
  14958. customDefines,
  14959. parameters.supportsVertexTextures ? '#define VERTEX_TEXTURES' : '',
  14960. '#define GAMMA_FACTOR ' + gammaFactorDefine,
  14961. '#define MAX_BONES ' + parameters.maxBones,
  14962. ( parameters.useFog && parameters.fog ) ? '#define USE_FOG' : '',
  14963. ( parameters.useFog && parameters.fogExp ) ? '#define FOG_EXP2' : '',
  14964. parameters.map ? '#define USE_MAP' : '',
  14965. parameters.envMap ? '#define USE_ENVMAP' : '',
  14966. parameters.envMap ? '#define ' + envMapModeDefine : '',
  14967. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  14968. parameters.aoMap ? '#define USE_AOMAP' : '',
  14969. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  14970. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  14971. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  14972. ( parameters.normalMap && parameters.objectSpaceNormalMap ) ? '#define OBJECTSPACE_NORMALMAP' : '',
  14973. parameters.displacementMap && parameters.supportsVertexTextures ? '#define USE_DISPLACEMENTMAP' : '',
  14974. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  14975. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  14976. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  14977. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  14978. parameters.vertexTangents ? '#define USE_TANGENT' : '',
  14979. parameters.vertexColors ? '#define USE_COLOR' : '',
  14980. parameters.flatShading ? '#define FLAT_SHADED' : '',
  14981. parameters.skinning ? '#define USE_SKINNING' : '',
  14982. parameters.useVertexTexture ? '#define BONE_TEXTURE' : '',
  14983. parameters.morphTargets ? '#define USE_MORPHTARGETS' : '',
  14984. parameters.morphNormals && parameters.flatShading === false ? '#define USE_MORPHNORMALS' : '',
  14985. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  14986. parameters.flipSided ? '#define FLIP_SIDED' : '',
  14987. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  14988. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  14989. parameters.sizeAttenuation ? '#define USE_SIZEATTENUATION' : '',
  14990. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  14991. parameters.logarithmicDepthBuffer && ( capabilities.isWebGL2 || extensions.get( 'EXT_frag_depth' ) ) ? '#define USE_LOGDEPTHBUF_EXT' : '',
  14992. 'uniform mat4 modelMatrix;',
  14993. 'uniform mat4 modelViewMatrix;',
  14994. 'uniform mat4 projectionMatrix;',
  14995. 'uniform mat4 viewMatrix;',
  14996. 'uniform mat3 normalMatrix;',
  14997. 'uniform vec3 cameraPosition;',
  14998. 'attribute vec3 position;',
  14999. 'attribute vec3 normal;',
  15000. 'attribute vec2 uv;',
  15001. '#ifdef USE_TANGENT',
  15002. ' attribute vec4 tangent;',
  15003. '#endif',
  15004. '#ifdef USE_COLOR',
  15005. ' attribute vec3 color;',
  15006. '#endif',
  15007. '#ifdef USE_MORPHTARGETS',
  15008. ' attribute vec3 morphTarget0;',
  15009. ' attribute vec3 morphTarget1;',
  15010. ' attribute vec3 morphTarget2;',
  15011. ' attribute vec3 morphTarget3;',
  15012. ' #ifdef USE_MORPHNORMALS',
  15013. ' attribute vec3 morphNormal0;',
  15014. ' attribute vec3 morphNormal1;',
  15015. ' attribute vec3 morphNormal2;',
  15016. ' attribute vec3 morphNormal3;',
  15017. ' #else',
  15018. ' attribute vec3 morphTarget4;',
  15019. ' attribute vec3 morphTarget5;',
  15020. ' attribute vec3 morphTarget6;',
  15021. ' attribute vec3 morphTarget7;',
  15022. ' #endif',
  15023. '#endif',
  15024. '#ifdef USE_SKINNING',
  15025. ' attribute vec4 skinIndex;',
  15026. ' attribute vec4 skinWeight;',
  15027. '#endif',
  15028. '\n'
  15029. ].filter( filterEmptyLine ).join( '\n' );
  15030. prefixFragment = [
  15031. customExtensions,
  15032. 'precision ' + parameters.precision + ' float;',
  15033. 'precision ' + parameters.precision + ' int;',
  15034. '#define SHADER_NAME ' + shader.name,
  15035. customDefines,
  15036. parameters.alphaTest ? '#define ALPHATEST ' + parameters.alphaTest + ( parameters.alphaTest % 1 ? '' : '.0' ) : '', // add '.0' if integer
  15037. '#define GAMMA_FACTOR ' + gammaFactorDefine,
  15038. ( parameters.useFog && parameters.fog ) ? '#define USE_FOG' : '',
  15039. ( parameters.useFog && parameters.fogExp ) ? '#define FOG_EXP2' : '',
  15040. parameters.map ? '#define USE_MAP' : '',
  15041. parameters.matcap ? '#define USE_MATCAP' : '',
  15042. parameters.envMap ? '#define USE_ENVMAP' : '',
  15043. parameters.envMap ? '#define ' + envMapTypeDefine : '',
  15044. parameters.envMap ? '#define ' + envMapModeDefine : '',
  15045. parameters.envMap ? '#define ' + envMapBlendingDefine : '',
  15046. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  15047. parameters.aoMap ? '#define USE_AOMAP' : '',
  15048. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  15049. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  15050. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  15051. ( parameters.normalMap && parameters.objectSpaceNormalMap ) ? '#define OBJECTSPACE_NORMALMAP' : '',
  15052. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  15053. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  15054. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  15055. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  15056. parameters.vertexTangents ? '#define USE_TANGENT' : '',
  15057. parameters.vertexColors ? '#define USE_COLOR' : '',
  15058. parameters.gradientMap ? '#define USE_GRADIENTMAP' : '',
  15059. parameters.flatShading ? '#define FLAT_SHADED' : '',
  15060. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  15061. parameters.flipSided ? '#define FLIP_SIDED' : '',
  15062. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  15063. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  15064. parameters.premultipliedAlpha ? '#define PREMULTIPLIED_ALPHA' : '',
  15065. parameters.physicallyCorrectLights ? '#define PHYSICALLY_CORRECT_LIGHTS' : '',
  15066. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  15067. parameters.logarithmicDepthBuffer && ( capabilities.isWebGL2 || extensions.get( 'EXT_frag_depth' ) ) ? '#define USE_LOGDEPTHBUF_EXT' : '',
  15068. parameters.envMap && ( capabilities.isWebGL2 || extensions.get( 'EXT_shader_texture_lod' ) ) ? '#define TEXTURE_LOD_EXT' : '',
  15069. 'uniform mat4 viewMatrix;',
  15070. 'uniform vec3 cameraPosition;',
  15071. ( parameters.toneMapping !== NoToneMapping ) ? '#define TONE_MAPPING' : '',
  15072. ( parameters.toneMapping !== NoToneMapping ) ? ShaderChunk[ 'tonemapping_pars_fragment' ] : '', // this code is required here because it is used by the toneMapping() function defined below
  15073. ( parameters.toneMapping !== NoToneMapping ) ? getToneMappingFunction( 'toneMapping', parameters.toneMapping ) : '',
  15074. parameters.dithering ? '#define DITHERING' : '',
  15075. ( parameters.outputEncoding || parameters.mapEncoding || parameters.matcapEncoding || parameters.envMapEncoding || parameters.emissiveMapEncoding ) ?
  15076. ShaderChunk[ 'encodings_pars_fragment' ] : '', // this code is required here because it is used by the various encoding/decoding function defined below
  15077. parameters.mapEncoding ? getTexelDecodingFunction( 'mapTexelToLinear', parameters.mapEncoding ) : '',
  15078. parameters.matcapEncoding ? getTexelDecodingFunction( 'matcapTexelToLinear', parameters.matcapEncoding ) : '',
  15079. parameters.envMapEncoding ? getTexelDecodingFunction( 'envMapTexelToLinear', parameters.envMapEncoding ) : '',
  15080. parameters.emissiveMapEncoding ? getTexelDecodingFunction( 'emissiveMapTexelToLinear', parameters.emissiveMapEncoding ) : '',
  15081. parameters.outputEncoding ? getTexelEncodingFunction( 'linearToOutputTexel', parameters.outputEncoding ) : '',
  15082. parameters.depthPacking ? '#define DEPTH_PACKING ' + material.depthPacking : '',
  15083. '\n'
  15084. ].filter( filterEmptyLine ).join( '\n' );
  15085. }
  15086. vertexShader = parseIncludes( vertexShader );
  15087. vertexShader = replaceLightNums( vertexShader, parameters );
  15088. vertexShader = replaceClippingPlaneNums( vertexShader, parameters );
  15089. fragmentShader = parseIncludes( fragmentShader );
  15090. fragmentShader = replaceLightNums( fragmentShader, parameters );
  15091. fragmentShader = replaceClippingPlaneNums( fragmentShader, parameters );
  15092. vertexShader = unrollLoops( vertexShader );
  15093. fragmentShader = unrollLoops( fragmentShader );
  15094. if ( capabilities.isWebGL2 && ! material.isRawShaderMaterial ) {
  15095. var isGLSL3ShaderMaterial = false;
  15096. var versionRegex = /^\s*#version\s+300\s+es\s*\n/;
  15097. if ( material.isShaderMaterial &&
  15098. vertexShader.match( versionRegex ) !== null &&
  15099. fragmentShader.match( versionRegex ) !== null ) {
  15100. isGLSL3ShaderMaterial = true;
  15101. vertexShader = vertexShader.replace( versionRegex, '' );
  15102. fragmentShader = fragmentShader.replace( versionRegex, '' );
  15103. }
  15104. // GLSL 3.0 conversion
  15105. prefixVertex = [
  15106. '#version 300 es\n',
  15107. '#define attribute in',
  15108. '#define varying out',
  15109. '#define texture2D texture'
  15110. ].join( '\n' ) + '\n' + prefixVertex;
  15111. prefixFragment = [
  15112. '#version 300 es\n',
  15113. '#define varying in',
  15114. isGLSL3ShaderMaterial ? '' : 'out highp vec4 pc_fragColor;',
  15115. isGLSL3ShaderMaterial ? '' : '#define gl_FragColor pc_fragColor',
  15116. '#define gl_FragDepthEXT gl_FragDepth',
  15117. '#define texture2D texture',
  15118. '#define textureCube texture',
  15119. '#define texture2DProj textureProj',
  15120. '#define texture2DLodEXT textureLod',
  15121. '#define texture2DProjLodEXT textureProjLod',
  15122. '#define textureCubeLodEXT textureLod',
  15123. '#define texture2DGradEXT textureGrad',
  15124. '#define texture2DProjGradEXT textureProjGrad',
  15125. '#define textureCubeGradEXT textureGrad'
  15126. ].join( '\n' ) + '\n' + prefixFragment;
  15127. }
  15128. var vertexGlsl = prefixVertex + vertexShader;
  15129. var fragmentGlsl = prefixFragment + fragmentShader;
  15130. // console.log( '*VERTEX*', vertexGlsl );
  15131. // console.log( '*FRAGMENT*', fragmentGlsl );
  15132. var glVertexShader = WebGLShader( gl, 35633, vertexGlsl );
  15133. var glFragmentShader = WebGLShader( gl, 35632, fragmentGlsl );
  15134. gl.attachShader( program, glVertexShader );
  15135. gl.attachShader( program, glFragmentShader );
  15136. // Force a particular attribute to index 0.
  15137. if ( material.index0AttributeName !== undefined ) {
  15138. gl.bindAttribLocation( program, 0, material.index0AttributeName );
  15139. } else if ( parameters.morphTargets === true ) {
  15140. // programs with morphTargets displace position out of attribute 0
  15141. gl.bindAttribLocation( program, 0, 'position' );
  15142. }
  15143. gl.linkProgram( program );
  15144. var programLog = gl.getProgramInfoLog( program ).trim();
  15145. var vertexLog = gl.getShaderInfoLog( glVertexShader ).trim();
  15146. var fragmentLog = gl.getShaderInfoLog( glFragmentShader ).trim();
  15147. var runnable = true;
  15148. var haveDiagnostics = true;
  15149. // console.log( '**VERTEX**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( glVertexShader ) );
  15150. // console.log( '**FRAGMENT**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( glFragmentShader ) );
  15151. if ( gl.getProgramParameter( program, 35714 ) === false ) {
  15152. runnable = false;
  15153. console.error( 'THREE.WebGLProgram: shader error: ', gl.getError(), '35715', gl.getProgramParameter( program, 35715 ), 'gl.getProgramInfoLog', programLog, vertexLog, fragmentLog );
  15154. } else if ( programLog !== '' ) {
  15155. console.warn( 'THREE.WebGLProgram: gl.getProgramInfoLog()', programLog );
  15156. } else if ( vertexLog === '' || fragmentLog === '' ) {
  15157. haveDiagnostics = false;
  15158. }
  15159. if ( haveDiagnostics ) {
  15160. this.diagnostics = {
  15161. runnable: runnable,
  15162. material: material,
  15163. programLog: programLog,
  15164. vertexShader: {
  15165. log: vertexLog,
  15166. prefix: prefixVertex
  15167. },
  15168. fragmentShader: {
  15169. log: fragmentLog,
  15170. prefix: prefixFragment
  15171. }
  15172. };
  15173. }
  15174. // clean up
  15175. gl.deleteShader( glVertexShader );
  15176. gl.deleteShader( glFragmentShader );
  15177. // set up caching for uniform locations
  15178. var cachedUniforms;
  15179. this.getUniforms = function () {
  15180. if ( cachedUniforms === undefined ) {
  15181. cachedUniforms = new WebGLUniforms( gl, program, renderer );
  15182. }
  15183. return cachedUniforms;
  15184. };
  15185. // set up caching for attribute locations
  15186. var cachedAttributes;
  15187. this.getAttributes = function () {
  15188. if ( cachedAttributes === undefined ) {
  15189. cachedAttributes = fetchAttributeLocations( gl, program );
  15190. }
  15191. return cachedAttributes;
  15192. };
  15193. // free resource
  15194. this.destroy = function () {
  15195. gl.deleteProgram( program );
  15196. this.program = undefined;
  15197. };
  15198. // DEPRECATED
  15199. Object.defineProperties( this, {
  15200. uniforms: {
  15201. get: function () {
  15202. console.warn( 'THREE.WebGLProgram: .uniforms is now .getUniforms().' );
  15203. return this.getUniforms();
  15204. }
  15205. },
  15206. attributes: {
  15207. get: function () {
  15208. console.warn( 'THREE.WebGLProgram: .attributes is now .getAttributes().' );
  15209. return this.getAttributes();
  15210. }
  15211. }
  15212. } );
  15213. //
  15214. this.name = shader.name;
  15215. this.id = programIdCount ++;
  15216. this.code = code;
  15217. this.usedTimes = 1;
  15218. this.program = program;
  15219. this.vertexShader = glVertexShader;
  15220. this.fragmentShader = glFragmentShader;
  15221. return this;
  15222. }
  15223. /**
  15224. * @author mrdoob / http://mrdoob.com/
  15225. */
  15226. function WebGLPrograms( renderer, extensions, capabilities ) {
  15227. var programs = [];
  15228. var shaderIDs = {
  15229. MeshDepthMaterial: 'depth',
  15230. MeshDistanceMaterial: 'distanceRGBA',
  15231. MeshNormalMaterial: 'normal',
  15232. MeshBasicMaterial: 'basic',
  15233. MeshLambertMaterial: 'lambert',
  15234. MeshPhongMaterial: 'phong',
  15235. MeshToonMaterial: 'phong',
  15236. MeshStandardMaterial: 'physical',
  15237. MeshPhysicalMaterial: 'physical',
  15238. MeshMatcapMaterial: 'matcap',
  15239. LineBasicMaterial: 'basic',
  15240. LineDashedMaterial: 'dashed',
  15241. PointsMaterial: 'points',
  15242. ShadowMaterial: 'shadow',
  15243. SpriteMaterial: 'sprite'
  15244. };
  15245. var parameterNames = [
  15246. "precision", "supportsVertexTextures", "map", "mapEncoding", "matcap", "matcapEncoding", "envMap", "envMapMode", "envMapEncoding",
  15247. "lightMap", "aoMap", "emissiveMap", "emissiveMapEncoding", "bumpMap", "normalMap", "objectSpaceNormalMap", "displacementMap", "specularMap",
  15248. "roughnessMap", "metalnessMap", "gradientMap",
  15249. "alphaMap", "combine", "vertexColors", "vertexTangents", "fog", "useFog", "fogExp",
  15250. "flatShading", "sizeAttenuation", "logarithmicDepthBuffer", "skinning",
  15251. "maxBones", "useVertexTexture", "morphTargets", "morphNormals",
  15252. "maxMorphTargets", "maxMorphNormals", "premultipliedAlpha",
  15253. "numDirLights", "numPointLights", "numSpotLights", "numHemiLights", "numRectAreaLights",
  15254. "shadowMapEnabled", "shadowMapType", "toneMapping", 'physicallyCorrectLights',
  15255. "alphaTest", "doubleSided", "flipSided", "numClippingPlanes", "numClipIntersection", "depthPacking", "dithering"
  15256. ];
  15257. function allocateBones( object ) {
  15258. var skeleton = object.skeleton;
  15259. var bones = skeleton.bones;
  15260. if ( capabilities.floatVertexTextures ) {
  15261. return 1024;
  15262. } else {
  15263. // default for when object is not specified
  15264. // ( for example when prebuilding shader to be used with multiple objects )
  15265. //
  15266. // - leave some extra space for other uniforms
  15267. // - limit here is ANGLE's 254 max uniform vectors
  15268. // (up to 54 should be safe)
  15269. var nVertexUniforms = capabilities.maxVertexUniforms;
  15270. var nVertexMatrices = Math.floor( ( nVertexUniforms - 20 ) / 4 );
  15271. var maxBones = Math.min( nVertexMatrices, bones.length );
  15272. if ( maxBones < bones.length ) {
  15273. console.warn( 'THREE.WebGLRenderer: Skeleton has ' + bones.length + ' bones. This GPU supports ' + maxBones + '.' );
  15274. return 0;
  15275. }
  15276. return maxBones;
  15277. }
  15278. }
  15279. function getTextureEncodingFromMap( map, gammaOverrideLinear ) {
  15280. var encoding;
  15281. if ( ! map ) {
  15282. encoding = LinearEncoding;
  15283. } else if ( map.isTexture ) {
  15284. encoding = map.encoding;
  15285. } else if ( map.isWebGLRenderTarget ) {
  15286. console.warn( "THREE.WebGLPrograms.getTextureEncodingFromMap: don't use render targets as textures. Use their .texture property instead." );
  15287. encoding = map.texture.encoding;
  15288. }
  15289. // add backwards compatibility for WebGLRenderer.gammaInput/gammaOutput parameter, should probably be removed at some point.
  15290. if ( encoding === LinearEncoding && gammaOverrideLinear ) {
  15291. encoding = GammaEncoding;
  15292. }
  15293. return encoding;
  15294. }
  15295. this.getParameters = function ( material, lights, shadows, fog, nClipPlanes, nClipIntersection, object ) {
  15296. var shaderID = shaderIDs[ material.type ];
  15297. // heuristics to create shader parameters according to lights in the scene
  15298. // (not to blow over maxLights budget)
  15299. var maxBones = object.isSkinnedMesh ? allocateBones( object ) : 0;
  15300. var precision = capabilities.precision;
  15301. if ( material.precision !== null ) {
  15302. precision = capabilities.getMaxPrecision( material.precision );
  15303. if ( precision !== material.precision ) {
  15304. console.warn( 'THREE.WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.' );
  15305. }
  15306. }
  15307. var currentRenderTarget = renderer.getRenderTarget();
  15308. var parameters = {
  15309. shaderID: shaderID,
  15310. precision: precision,
  15311. supportsVertexTextures: capabilities.vertexTextures,
  15312. outputEncoding: getTextureEncodingFromMap( ( ! currentRenderTarget ) ? null : currentRenderTarget.texture, renderer.gammaOutput ),
  15313. map: !! material.map,
  15314. mapEncoding: getTextureEncodingFromMap( material.map, renderer.gammaInput ),
  15315. matcap: !! material.matcap,
  15316. matcapEncoding: getTextureEncodingFromMap( material.matcap, renderer.gammaInput ),
  15317. envMap: !! material.envMap,
  15318. envMapMode: material.envMap && material.envMap.mapping,
  15319. envMapEncoding: getTextureEncodingFromMap( material.envMap, renderer.gammaInput ),
  15320. envMapCubeUV: ( !! material.envMap ) && ( ( material.envMap.mapping === CubeUVReflectionMapping ) || ( material.envMap.mapping === CubeUVRefractionMapping ) ),
  15321. lightMap: !! material.lightMap,
  15322. aoMap: !! material.aoMap,
  15323. emissiveMap: !! material.emissiveMap,
  15324. emissiveMapEncoding: getTextureEncodingFromMap( material.emissiveMap, renderer.gammaInput ),
  15325. bumpMap: !! material.bumpMap,
  15326. normalMap: !! material.normalMap,
  15327. objectSpaceNormalMap: material.normalMapType === ObjectSpaceNormalMap,
  15328. displacementMap: !! material.displacementMap,
  15329. roughnessMap: !! material.roughnessMap,
  15330. metalnessMap: !! material.metalnessMap,
  15331. specularMap: !! material.specularMap,
  15332. alphaMap: !! material.alphaMap,
  15333. gradientMap: !! material.gradientMap,
  15334. combine: material.combine,
  15335. vertexTangents: ( material.normalMap && material.vertexTangents ),
  15336. vertexColors: material.vertexColors,
  15337. fog: !! fog,
  15338. useFog: material.fog,
  15339. fogExp: ( fog && fog.isFogExp2 ),
  15340. flatShading: material.flatShading,
  15341. sizeAttenuation: material.sizeAttenuation,
  15342. logarithmicDepthBuffer: capabilities.logarithmicDepthBuffer,
  15343. skinning: material.skinning && maxBones > 0,
  15344. maxBones: maxBones,
  15345. useVertexTexture: capabilities.floatVertexTextures,
  15346. morphTargets: material.morphTargets,
  15347. morphNormals: material.morphNormals,
  15348. maxMorphTargets: renderer.maxMorphTargets,
  15349. maxMorphNormals: renderer.maxMorphNormals,
  15350. numDirLights: lights.directional.length,
  15351. numPointLights: lights.point.length,
  15352. numSpotLights: lights.spot.length,
  15353. numRectAreaLights: lights.rectArea.length,
  15354. numHemiLights: lights.hemi.length,
  15355. numClippingPlanes: nClipPlanes,
  15356. numClipIntersection: nClipIntersection,
  15357. dithering: material.dithering,
  15358. shadowMapEnabled: renderer.shadowMap.enabled && object.receiveShadow && shadows.length > 0,
  15359. shadowMapType: renderer.shadowMap.type,
  15360. toneMapping: renderer.toneMapping,
  15361. physicallyCorrectLights: renderer.physicallyCorrectLights,
  15362. premultipliedAlpha: material.premultipliedAlpha,
  15363. alphaTest: material.alphaTest,
  15364. doubleSided: material.side === DoubleSide,
  15365. flipSided: material.side === BackSide,
  15366. depthPacking: ( material.depthPacking !== undefined ) ? material.depthPacking : false
  15367. };
  15368. return parameters;
  15369. };
  15370. this.getProgramCode = function ( material, parameters ) {
  15371. var array = [];
  15372. if ( parameters.shaderID ) {
  15373. array.push( parameters.shaderID );
  15374. } else {
  15375. array.push( material.fragmentShader );
  15376. array.push( material.vertexShader );
  15377. }
  15378. if ( material.defines !== undefined ) {
  15379. for ( var name in material.defines ) {
  15380. array.push( name );
  15381. array.push( material.defines[ name ] );
  15382. }
  15383. }
  15384. for ( var i = 0; i < parameterNames.length; i ++ ) {
  15385. array.push( parameters[ parameterNames[ i ] ] );
  15386. }
  15387. array.push( material.onBeforeCompile.toString() );
  15388. array.push( renderer.gammaOutput );
  15389. array.push( renderer.gammaFactor );
  15390. return array.join();
  15391. };
  15392. this.acquireProgram = function ( material, shader, parameters, code ) {
  15393. var program;
  15394. // Check if code has been already compiled
  15395. for ( var p = 0, pl = programs.length; p < pl; p ++ ) {
  15396. var programInfo = programs[ p ];
  15397. if ( programInfo.code === code ) {
  15398. program = programInfo;
  15399. ++ program.usedTimes;
  15400. break;
  15401. }
  15402. }
  15403. if ( program === undefined ) {
  15404. program = new WebGLProgram( renderer, extensions, code, material, shader, parameters, capabilities );
  15405. programs.push( program );
  15406. }
  15407. return program;
  15408. };
  15409. this.releaseProgram = function ( program ) {
  15410. if ( -- program.usedTimes === 0 ) {
  15411. // Remove from unordered set
  15412. var i = programs.indexOf( program );
  15413. programs[ i ] = programs[ programs.length - 1 ];
  15414. programs.pop();
  15415. // Free WebGL resources
  15416. program.destroy();
  15417. }
  15418. };
  15419. // Exposed for resource monitoring & error feedback via renderer.info:
  15420. this.programs = programs;
  15421. }
  15422. /**
  15423. * @author fordacious / fordacious.github.io
  15424. */
  15425. function WebGLProperties() {
  15426. var properties = new WeakMap();
  15427. function get( object ) {
  15428. var map = properties.get( object );
  15429. if ( map === undefined ) {
  15430. map = {};
  15431. properties.set( object, map );
  15432. }
  15433. return map;
  15434. }
  15435. function remove( object ) {
  15436. properties.delete( object );
  15437. }
  15438. function update( object, key, value ) {
  15439. properties.get( object )[ key ] = value;
  15440. }
  15441. function dispose() {
  15442. properties = new WeakMap();
  15443. }
  15444. return {
  15445. get: get,
  15446. remove: remove,
  15447. update: update,
  15448. dispose: dispose
  15449. };
  15450. }
  15451. /**
  15452. * @author mrdoob / http://mrdoob.com/
  15453. */
  15454. function painterSortStable( a, b ) {
  15455. if ( a.groupOrder !== b.groupOrder ) {
  15456. return a.groupOrder - b.groupOrder;
  15457. } else if ( a.renderOrder !== b.renderOrder ) {
  15458. return a.renderOrder - b.renderOrder;
  15459. } else if ( a.program && b.program && a.program !== b.program ) {
  15460. return a.program.id - b.program.id;
  15461. } else if ( a.material.id !== b.material.id ) {
  15462. return a.material.id - b.material.id;
  15463. } else if ( a.z !== b.z ) {
  15464. return a.z - b.z;
  15465. } else {
  15466. return a.id - b.id;
  15467. }
  15468. }
  15469. function reversePainterSortStable( a, b ) {
  15470. if ( a.groupOrder !== b.groupOrder ) {
  15471. return a.groupOrder - b.groupOrder;
  15472. } else if ( a.renderOrder !== b.renderOrder ) {
  15473. return a.renderOrder - b.renderOrder;
  15474. } else if ( a.z !== b.z ) {
  15475. return b.z - a.z;
  15476. } else {
  15477. return a.id - b.id;
  15478. }
  15479. }
  15480. function WebGLRenderList() {
  15481. var renderItems = [];
  15482. var renderItemsIndex = 0;
  15483. var opaque = [];
  15484. var transparent = [];
  15485. function init() {
  15486. renderItemsIndex = 0;
  15487. opaque.length = 0;
  15488. transparent.length = 0;
  15489. }
  15490. function getNextRenderItem( object, geometry, material, groupOrder, z, group ) {
  15491. var renderItem = renderItems[ renderItemsIndex ];
  15492. if ( renderItem === undefined ) {
  15493. renderItem = {
  15494. id: object.id,
  15495. object: object,
  15496. geometry: geometry,
  15497. material: material,
  15498. program: material.program,
  15499. groupOrder: groupOrder,
  15500. renderOrder: object.renderOrder,
  15501. z: z,
  15502. group: group
  15503. };
  15504. renderItems[ renderItemsIndex ] = renderItem;
  15505. } else {
  15506. renderItem.id = object.id;
  15507. renderItem.object = object;
  15508. renderItem.geometry = geometry;
  15509. renderItem.material = material;
  15510. renderItem.program = material.program;
  15511. renderItem.groupOrder = groupOrder;
  15512. renderItem.renderOrder = object.renderOrder;
  15513. renderItem.z = z;
  15514. renderItem.group = group;
  15515. }
  15516. renderItemsIndex ++;
  15517. return renderItem;
  15518. }
  15519. function push( object, geometry, material, groupOrder, z, group ) {
  15520. var renderItem = getNextRenderItem( object, geometry, material, groupOrder, z, group );
  15521. ( material.transparent === true ? transparent : opaque ).push( renderItem );
  15522. }
  15523. function unshift( object, geometry, material, groupOrder, z, group ) {
  15524. var renderItem = getNextRenderItem( object, geometry, material, groupOrder, z, group );
  15525. ( material.transparent === true ? transparent : opaque ).unshift( renderItem );
  15526. }
  15527. function sort() {
  15528. if ( opaque.length > 1 ) opaque.sort( painterSortStable );
  15529. if ( transparent.length > 1 ) transparent.sort( reversePainterSortStable );
  15530. }
  15531. return {
  15532. opaque: opaque,
  15533. transparent: transparent,
  15534. init: init,
  15535. push: push,
  15536. unshift: unshift,
  15537. sort: sort
  15538. };
  15539. }
  15540. function WebGLRenderLists() {
  15541. var lists = {};
  15542. function onSceneDispose( event ) {
  15543. var scene = event.target;
  15544. scene.removeEventListener( 'dispose', onSceneDispose );
  15545. delete lists[ scene.id ];
  15546. }
  15547. function get( scene, camera ) {
  15548. var cameras = lists[ scene.id ];
  15549. var list;
  15550. if ( cameras === undefined ) {
  15551. list = new WebGLRenderList();
  15552. lists[ scene.id ] = {};
  15553. lists[ scene.id ][ camera.id ] = list;
  15554. scene.addEventListener( 'dispose', onSceneDispose );
  15555. } else {
  15556. list = cameras[ camera.id ];
  15557. if ( list === undefined ) {
  15558. list = new WebGLRenderList();
  15559. cameras[ camera.id ] = list;
  15560. }
  15561. }
  15562. return list;
  15563. }
  15564. function dispose() {
  15565. lists = {};
  15566. }
  15567. return {
  15568. get: get,
  15569. dispose: dispose
  15570. };
  15571. }
  15572. /**
  15573. * @author mrdoob / http://mrdoob.com/
  15574. */
  15575. function UniformsCache() {
  15576. var lights = {};
  15577. return {
  15578. get: function ( light ) {
  15579. if ( lights[ light.id ] !== undefined ) {
  15580. return lights[ light.id ];
  15581. }
  15582. var uniforms;
  15583. switch ( light.type ) {
  15584. case 'DirectionalLight':
  15585. uniforms = {
  15586. direction: new Vector3(),
  15587. color: new Color(),
  15588. shadow: false,
  15589. shadowBias: 0,
  15590. shadowRadius: 1,
  15591. shadowMapSize: new Vector2()
  15592. };
  15593. break;
  15594. case 'SpotLight':
  15595. uniforms = {
  15596. position: new Vector3(),
  15597. direction: new Vector3(),
  15598. color: new Color(),
  15599. distance: 0,
  15600. coneCos: 0,
  15601. penumbraCos: 0,
  15602. decay: 0,
  15603. shadow: false,
  15604. shadowBias: 0,
  15605. shadowRadius: 1,
  15606. shadowMapSize: new Vector2()
  15607. };
  15608. break;
  15609. case 'PointLight':
  15610. uniforms = {
  15611. position: new Vector3(),
  15612. color: new Color(),
  15613. distance: 0,
  15614. decay: 0,
  15615. shadow: false,
  15616. shadowBias: 0,
  15617. shadowRadius: 1,
  15618. shadowMapSize: new Vector2(),
  15619. shadowCameraNear: 1,
  15620. shadowCameraFar: 1000
  15621. };
  15622. break;
  15623. case 'HemisphereLight':
  15624. uniforms = {
  15625. direction: new Vector3(),
  15626. skyColor: new Color(),
  15627. groundColor: new Color()
  15628. };
  15629. break;
  15630. case 'RectAreaLight':
  15631. uniforms = {
  15632. color: new Color(),
  15633. position: new Vector3(),
  15634. halfWidth: new Vector3(),
  15635. halfHeight: new Vector3()
  15636. // TODO (abelnation): set RectAreaLight shadow uniforms
  15637. };
  15638. break;
  15639. }
  15640. lights[ light.id ] = uniforms;
  15641. return uniforms;
  15642. }
  15643. };
  15644. }
  15645. var count = 0;
  15646. function WebGLLights() {
  15647. var cache = new UniformsCache();
  15648. var state = {
  15649. id: count ++,
  15650. hash: {
  15651. stateID: - 1,
  15652. directionalLength: - 1,
  15653. pointLength: - 1,
  15654. spotLength: - 1,
  15655. rectAreaLength: - 1,
  15656. hemiLength: - 1,
  15657. shadowsLength: - 1
  15658. },
  15659. ambient: [ 0, 0, 0 ],
  15660. directional: [],
  15661. directionalShadowMap: [],
  15662. directionalShadowMatrix: [],
  15663. spot: [],
  15664. spotShadowMap: [],
  15665. spotShadowMatrix: [],
  15666. rectArea: [],
  15667. point: [],
  15668. pointShadowMap: [],
  15669. pointShadowMatrix: [],
  15670. hemi: []
  15671. };
  15672. var vector3 = new Vector3();
  15673. var matrix4 = new Matrix4();
  15674. var matrix42 = new Matrix4();
  15675. function setup( lights, shadows, camera ) {
  15676. var r = 0, g = 0, b = 0;
  15677. var directionalLength = 0;
  15678. var pointLength = 0;
  15679. var spotLength = 0;
  15680. var rectAreaLength = 0;
  15681. var hemiLength = 0;
  15682. var viewMatrix = camera.matrixWorldInverse;
  15683. for ( var i = 0, l = lights.length; i < l; i ++ ) {
  15684. var light = lights[ i ];
  15685. var color = light.color;
  15686. var intensity = light.intensity;
  15687. var distance = light.distance;
  15688. var shadowMap = ( light.shadow && light.shadow.map ) ? light.shadow.map.texture : null;
  15689. if ( light.isAmbientLight ) {
  15690. r += color.r * intensity;
  15691. g += color.g * intensity;
  15692. b += color.b * intensity;
  15693. } else if ( light.isDirectionalLight ) {
  15694. var uniforms = cache.get( light );
  15695. uniforms.color.copy( light.color ).multiplyScalar( light.intensity );
  15696. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  15697. vector3.setFromMatrixPosition( light.target.matrixWorld );
  15698. uniforms.direction.sub( vector3 );
  15699. uniforms.direction.transformDirection( viewMatrix );
  15700. uniforms.shadow = light.castShadow;
  15701. if ( light.castShadow ) {
  15702. var shadow = light.shadow;
  15703. uniforms.shadowBias = shadow.bias;
  15704. uniforms.shadowRadius = shadow.radius;
  15705. uniforms.shadowMapSize = shadow.mapSize;
  15706. }
  15707. state.directionalShadowMap[ directionalLength ] = shadowMap;
  15708. state.directionalShadowMatrix[ directionalLength ] = light.shadow.matrix;
  15709. state.directional[ directionalLength ] = uniforms;
  15710. directionalLength ++;
  15711. } else if ( light.isSpotLight ) {
  15712. var uniforms = cache.get( light );
  15713. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  15714. uniforms.position.applyMatrix4( viewMatrix );
  15715. uniforms.color.copy( color ).multiplyScalar( intensity );
  15716. uniforms.distance = distance;
  15717. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  15718. vector3.setFromMatrixPosition( light.target.matrixWorld );
  15719. uniforms.direction.sub( vector3 );
  15720. uniforms.direction.transformDirection( viewMatrix );
  15721. uniforms.coneCos = Math.cos( light.angle );
  15722. uniforms.penumbraCos = Math.cos( light.angle * ( 1 - light.penumbra ) );
  15723. uniforms.decay = light.decay;
  15724. uniforms.shadow = light.castShadow;
  15725. if ( light.castShadow ) {
  15726. var shadow = light.shadow;
  15727. uniforms.shadowBias = shadow.bias;
  15728. uniforms.shadowRadius = shadow.radius;
  15729. uniforms.shadowMapSize = shadow.mapSize;
  15730. }
  15731. state.spotShadowMap[ spotLength ] = shadowMap;
  15732. state.spotShadowMatrix[ spotLength ] = light.shadow.matrix;
  15733. state.spot[ spotLength ] = uniforms;
  15734. spotLength ++;
  15735. } else if ( light.isRectAreaLight ) {
  15736. var uniforms = cache.get( light );
  15737. // (a) intensity is the total visible light emitted
  15738. //uniforms.color.copy( color ).multiplyScalar( intensity / ( light.width * light.height * Math.PI ) );
  15739. // (b) intensity is the brightness of the light
  15740. uniforms.color.copy( color ).multiplyScalar( intensity );
  15741. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  15742. uniforms.position.applyMatrix4( viewMatrix );
  15743. // extract local rotation of light to derive width/height half vectors
  15744. matrix42.identity();
  15745. matrix4.copy( light.matrixWorld );
  15746. matrix4.premultiply( viewMatrix );
  15747. matrix42.extractRotation( matrix4 );
  15748. uniforms.halfWidth.set( light.width * 0.5, 0.0, 0.0 );
  15749. uniforms.halfHeight.set( 0.0, light.height * 0.5, 0.0 );
  15750. uniforms.halfWidth.applyMatrix4( matrix42 );
  15751. uniforms.halfHeight.applyMatrix4( matrix42 );
  15752. // TODO (abelnation): RectAreaLight distance?
  15753. // uniforms.distance = distance;
  15754. state.rectArea[ rectAreaLength ] = uniforms;
  15755. rectAreaLength ++;
  15756. } else if ( light.isPointLight ) {
  15757. var uniforms = cache.get( light );
  15758. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  15759. uniforms.position.applyMatrix4( viewMatrix );
  15760. uniforms.color.copy( light.color ).multiplyScalar( light.intensity );
  15761. uniforms.distance = light.distance;
  15762. uniforms.decay = light.decay;
  15763. uniforms.shadow = light.castShadow;
  15764. if ( light.castShadow ) {
  15765. var shadow = light.shadow;
  15766. uniforms.shadowBias = shadow.bias;
  15767. uniforms.shadowRadius = shadow.radius;
  15768. uniforms.shadowMapSize = shadow.mapSize;
  15769. uniforms.shadowCameraNear = shadow.camera.near;
  15770. uniforms.shadowCameraFar = shadow.camera.far;
  15771. }
  15772. state.pointShadowMap[ pointLength ] = shadowMap;
  15773. state.pointShadowMatrix[ pointLength ] = light.shadow.matrix;
  15774. state.point[ pointLength ] = uniforms;
  15775. pointLength ++;
  15776. } else if ( light.isHemisphereLight ) {
  15777. var uniforms = cache.get( light );
  15778. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  15779. uniforms.direction.transformDirection( viewMatrix );
  15780. uniforms.direction.normalize();
  15781. uniforms.skyColor.copy( light.color ).multiplyScalar( intensity );
  15782. uniforms.groundColor.copy( light.groundColor ).multiplyScalar( intensity );
  15783. state.hemi[ hemiLength ] = uniforms;
  15784. hemiLength ++;
  15785. }
  15786. }
  15787. state.ambient[ 0 ] = r;
  15788. state.ambient[ 1 ] = g;
  15789. state.ambient[ 2 ] = b;
  15790. state.directional.length = directionalLength;
  15791. state.spot.length = spotLength;
  15792. state.rectArea.length = rectAreaLength;
  15793. state.point.length = pointLength;
  15794. state.hemi.length = hemiLength;
  15795. state.hash.stateID = state.id;
  15796. state.hash.directionalLength = directionalLength;
  15797. state.hash.pointLength = pointLength;
  15798. state.hash.spotLength = spotLength;
  15799. state.hash.rectAreaLength = rectAreaLength;
  15800. state.hash.hemiLength = hemiLength;
  15801. state.hash.shadowsLength = shadows.length;
  15802. }
  15803. return {
  15804. setup: setup,
  15805. state: state
  15806. };
  15807. }
  15808. /**
  15809. * @author Mugen87 / https://github.com/Mugen87
  15810. */
  15811. function WebGLRenderState() {
  15812. var lights = new WebGLLights();
  15813. var lightsArray = [];
  15814. var shadowsArray = [];
  15815. function init() {
  15816. lightsArray.length = 0;
  15817. shadowsArray.length = 0;
  15818. }
  15819. function pushLight( light ) {
  15820. lightsArray.push( light );
  15821. }
  15822. function pushShadow( shadowLight ) {
  15823. shadowsArray.push( shadowLight );
  15824. }
  15825. function setupLights( camera ) {
  15826. lights.setup( lightsArray, shadowsArray, camera );
  15827. }
  15828. var state = {
  15829. lightsArray: lightsArray,
  15830. shadowsArray: shadowsArray,
  15831. lights: lights
  15832. };
  15833. return {
  15834. init: init,
  15835. state: state,
  15836. setupLights: setupLights,
  15837. pushLight: pushLight,
  15838. pushShadow: pushShadow
  15839. };
  15840. }
  15841. function WebGLRenderStates() {
  15842. var renderStates = {};
  15843. function onSceneDispose( event ) {
  15844. var scene = event.target;
  15845. scene.removeEventListener( 'dispose', onSceneDispose );
  15846. delete renderStates[ scene.id ];
  15847. }
  15848. function get( scene, camera ) {
  15849. var renderState;
  15850. if ( renderStates[ scene.id ] === undefined ) {
  15851. renderState = new WebGLRenderState();
  15852. renderStates[ scene.id ] = {};
  15853. renderStates[ scene.id ][ camera.id ] = renderState;
  15854. scene.addEventListener( 'dispose', onSceneDispose );
  15855. } else {
  15856. if ( renderStates[ scene.id ][ camera.id ] === undefined ) {
  15857. renderState = new WebGLRenderState();
  15858. renderStates[ scene.id ][ camera.id ] = renderState;
  15859. } else {
  15860. renderState = renderStates[ scene.id ][ camera.id ];
  15861. }
  15862. }
  15863. return renderState;
  15864. }
  15865. function dispose() {
  15866. renderStates = {};
  15867. }
  15868. return {
  15869. get: get,
  15870. dispose: dispose
  15871. };
  15872. }
  15873. /**
  15874. * @author mrdoob / http://mrdoob.com/
  15875. * @author alteredq / http://alteredqualia.com/
  15876. * @author bhouston / https://clara.io
  15877. * @author WestLangley / http://github.com/WestLangley
  15878. *
  15879. * parameters = {
  15880. *
  15881. * opacity: <float>,
  15882. *
  15883. * map: new THREE.Texture( <Image> ),
  15884. *
  15885. * alphaMap: new THREE.Texture( <Image> ),
  15886. *
  15887. * displacementMap: new THREE.Texture( <Image> ),
  15888. * displacementScale: <float>,
  15889. * displacementBias: <float>,
  15890. *
  15891. * wireframe: <boolean>,
  15892. * wireframeLinewidth: <float>
  15893. * }
  15894. */
  15895. function MeshDepthMaterial( parameters ) {
  15896. Material.call( this );
  15897. this.type = 'MeshDepthMaterial';
  15898. this.depthPacking = BasicDepthPacking;
  15899. this.skinning = false;
  15900. this.morphTargets = false;
  15901. this.map = null;
  15902. this.alphaMap = null;
  15903. this.displacementMap = null;
  15904. this.displacementScale = 1;
  15905. this.displacementBias = 0;
  15906. this.wireframe = false;
  15907. this.wireframeLinewidth = 1;
  15908. this.fog = false;
  15909. this.lights = false;
  15910. this.setValues( parameters );
  15911. }
  15912. MeshDepthMaterial.prototype = Object.create( Material.prototype );
  15913. MeshDepthMaterial.prototype.constructor = MeshDepthMaterial;
  15914. MeshDepthMaterial.prototype.isMeshDepthMaterial = true;
  15915. MeshDepthMaterial.prototype.copy = function ( source ) {
  15916. Material.prototype.copy.call( this, source );
  15917. this.depthPacking = source.depthPacking;
  15918. this.skinning = source.skinning;
  15919. this.morphTargets = source.morphTargets;
  15920. this.map = source.map;
  15921. this.alphaMap = source.alphaMap;
  15922. this.displacementMap = source.displacementMap;
  15923. this.displacementScale = source.displacementScale;
  15924. this.displacementBias = source.displacementBias;
  15925. this.wireframe = source.wireframe;
  15926. this.wireframeLinewidth = source.wireframeLinewidth;
  15927. return this;
  15928. };
  15929. /**
  15930. * @author WestLangley / http://github.com/WestLangley
  15931. *
  15932. * parameters = {
  15933. *
  15934. * referencePosition: <float>,
  15935. * nearDistance: <float>,
  15936. * farDistance: <float>,
  15937. *
  15938. * skinning: <bool>,
  15939. * morphTargets: <bool>,
  15940. *
  15941. * map: new THREE.Texture( <Image> ),
  15942. *
  15943. * alphaMap: new THREE.Texture( <Image> ),
  15944. *
  15945. * displacementMap: new THREE.Texture( <Image> ),
  15946. * displacementScale: <float>,
  15947. * displacementBias: <float>
  15948. *
  15949. * }
  15950. */
  15951. function MeshDistanceMaterial( parameters ) {
  15952. Material.call( this );
  15953. this.type = 'MeshDistanceMaterial';
  15954. this.referencePosition = new Vector3();
  15955. this.nearDistance = 1;
  15956. this.farDistance = 1000;
  15957. this.skinning = false;
  15958. this.morphTargets = false;
  15959. this.map = null;
  15960. this.alphaMap = null;
  15961. this.displacementMap = null;
  15962. this.displacementScale = 1;
  15963. this.displacementBias = 0;
  15964. this.fog = false;
  15965. this.lights = false;
  15966. this.setValues( parameters );
  15967. }
  15968. MeshDistanceMaterial.prototype = Object.create( Material.prototype );
  15969. MeshDistanceMaterial.prototype.constructor = MeshDistanceMaterial;
  15970. MeshDistanceMaterial.prototype.isMeshDistanceMaterial = true;
  15971. MeshDistanceMaterial.prototype.copy = function ( source ) {
  15972. Material.prototype.copy.call( this, source );
  15973. this.referencePosition.copy( source.referencePosition );
  15974. this.nearDistance = source.nearDistance;
  15975. this.farDistance = source.farDistance;
  15976. this.skinning = source.skinning;
  15977. this.morphTargets = source.morphTargets;
  15978. this.map = source.map;
  15979. this.alphaMap = source.alphaMap;
  15980. this.displacementMap = source.displacementMap;
  15981. this.displacementScale = source.displacementScale;
  15982. this.displacementBias = source.displacementBias;
  15983. return this;
  15984. };
  15985. /**
  15986. * @author alteredq / http://alteredqualia.com/
  15987. * @author mrdoob / http://mrdoob.com/
  15988. */
  15989. function WebGLShadowMap( _renderer, _objects, maxTextureSize ) {
  15990. var _frustum = new Frustum(),
  15991. _projScreenMatrix = new Matrix4(),
  15992. _shadowMapSize = new Vector2(),
  15993. _maxShadowMapSize = new Vector2( maxTextureSize, maxTextureSize ),
  15994. _lookTarget = new Vector3(),
  15995. _lightPositionWorld = new Vector3(),
  15996. _MorphingFlag = 1,
  15997. _SkinningFlag = 2,
  15998. _NumberOfMaterialVariants = ( _MorphingFlag | _SkinningFlag ) + 1,
  15999. _depthMaterials = new Array( _NumberOfMaterialVariants ),
  16000. _distanceMaterials = new Array( _NumberOfMaterialVariants ),
  16001. _materialCache = {};
  16002. var shadowSide = { 0: BackSide, 1: FrontSide, 2: DoubleSide };
  16003. var cubeDirections = [
  16004. new Vector3( 1, 0, 0 ), new Vector3( - 1, 0, 0 ), new Vector3( 0, 0, 1 ),
  16005. new Vector3( 0, 0, - 1 ), new Vector3( 0, 1, 0 ), new Vector3( 0, - 1, 0 )
  16006. ];
  16007. var cubeUps = [
  16008. new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ),
  16009. new Vector3( 0, 1, 0 ), new Vector3( 0, 0, 1 ), new Vector3( 0, 0, - 1 )
  16010. ];
  16011. var cube2DViewPorts = [
  16012. new Vector4(), new Vector4(), new Vector4(),
  16013. new Vector4(), new Vector4(), new Vector4()
  16014. ];
  16015. // init
  16016. for ( var i = 0; i !== _NumberOfMaterialVariants; ++ i ) {
  16017. var useMorphing = ( i & _MorphingFlag ) !== 0;
  16018. var useSkinning = ( i & _SkinningFlag ) !== 0;
  16019. var depthMaterial = new MeshDepthMaterial( {
  16020. depthPacking: RGBADepthPacking,
  16021. morphTargets: useMorphing,
  16022. skinning: useSkinning
  16023. } );
  16024. _depthMaterials[ i ] = depthMaterial;
  16025. //
  16026. var distanceMaterial = new MeshDistanceMaterial( {
  16027. morphTargets: useMorphing,
  16028. skinning: useSkinning
  16029. } );
  16030. _distanceMaterials[ i ] = distanceMaterial;
  16031. }
  16032. //
  16033. var scope = this;
  16034. this.enabled = false;
  16035. this.autoUpdate = true;
  16036. this.needsUpdate = false;
  16037. this.type = PCFShadowMap;
  16038. this.render = function ( lights, scene, camera ) {
  16039. if ( scope.enabled === false ) return;
  16040. if ( scope.autoUpdate === false && scope.needsUpdate === false ) return;
  16041. if ( lights.length === 0 ) return;
  16042. var currentRenderTarget = _renderer.getRenderTarget();
  16043. var _state = _renderer.state;
  16044. // Set GL state for depth map.
  16045. _state.setBlending( NoBlending );
  16046. _state.buffers.color.setClear( 1, 1, 1, 1 );
  16047. _state.buffers.depth.setTest( true );
  16048. _state.setScissorTest( false );
  16049. // render depth map
  16050. var faceCount;
  16051. for ( var i = 0, il = lights.length; i < il; i ++ ) {
  16052. var light = lights[ i ];
  16053. var shadow = light.shadow;
  16054. var isPointLight = light && light.isPointLight;
  16055. if ( shadow === undefined ) {
  16056. console.warn( 'THREE.WebGLShadowMap:', light, 'has no shadow.' );
  16057. continue;
  16058. }
  16059. var shadowCamera = shadow.camera;
  16060. _shadowMapSize.copy( shadow.mapSize );
  16061. _shadowMapSize.min( _maxShadowMapSize );
  16062. if ( isPointLight ) {
  16063. var vpWidth = _shadowMapSize.x;
  16064. var vpHeight = _shadowMapSize.y;
  16065. // These viewports map a cube-map onto a 2D texture with the
  16066. // following orientation:
  16067. //
  16068. // xzXZ
  16069. // y Y
  16070. //
  16071. // X - Positive x direction
  16072. // x - Negative x direction
  16073. // Y - Positive y direction
  16074. // y - Negative y direction
  16075. // Z - Positive z direction
  16076. // z - Negative z direction
  16077. // positive X
  16078. cube2DViewPorts[ 0 ].set( vpWidth * 2, vpHeight, vpWidth, vpHeight );
  16079. // negative X
  16080. cube2DViewPorts[ 1 ].set( 0, vpHeight, vpWidth, vpHeight );
  16081. // positive Z
  16082. cube2DViewPorts[ 2 ].set( vpWidth * 3, vpHeight, vpWidth, vpHeight );
  16083. // negative Z
  16084. cube2DViewPorts[ 3 ].set( vpWidth, vpHeight, vpWidth, vpHeight );
  16085. // positive Y
  16086. cube2DViewPorts[ 4 ].set( vpWidth * 3, 0, vpWidth, vpHeight );
  16087. // negative Y
  16088. cube2DViewPorts[ 5 ].set( vpWidth, 0, vpWidth, vpHeight );
  16089. _shadowMapSize.x *= 4.0;
  16090. _shadowMapSize.y *= 2.0;
  16091. }
  16092. if ( shadow.map === null ) {
  16093. var pars = { minFilter: NearestFilter, magFilter: NearestFilter, format: RGBAFormat };
  16094. shadow.map = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars );
  16095. shadow.map.texture.name = light.name + ".shadowMap";
  16096. shadowCamera.updateProjectionMatrix();
  16097. }
  16098. if ( shadow.isSpotLightShadow ) {
  16099. shadow.update( light );
  16100. }
  16101. var shadowMap = shadow.map;
  16102. var shadowMatrix = shadow.matrix;
  16103. _lightPositionWorld.setFromMatrixPosition( light.matrixWorld );
  16104. shadowCamera.position.copy( _lightPositionWorld );
  16105. if ( isPointLight ) {
  16106. faceCount = 6;
  16107. // for point lights we set the shadow matrix to be a translation-only matrix
  16108. // equal to inverse of the light's position
  16109. shadowMatrix.makeTranslation( - _lightPositionWorld.x, - _lightPositionWorld.y, - _lightPositionWorld.z );
  16110. } else {
  16111. faceCount = 1;
  16112. _lookTarget.setFromMatrixPosition( light.target.matrixWorld );
  16113. shadowCamera.lookAt( _lookTarget );
  16114. shadowCamera.updateMatrixWorld();
  16115. // compute shadow matrix
  16116. shadowMatrix.set(
  16117. 0.5, 0.0, 0.0, 0.5,
  16118. 0.0, 0.5, 0.0, 0.5,
  16119. 0.0, 0.0, 0.5, 0.5,
  16120. 0.0, 0.0, 0.0, 1.0
  16121. );
  16122. shadowMatrix.multiply( shadowCamera.projectionMatrix );
  16123. shadowMatrix.multiply( shadowCamera.matrixWorldInverse );
  16124. }
  16125. _renderer.setRenderTarget( shadowMap );
  16126. _renderer.clear();
  16127. // render shadow map for each cube face (if omni-directional) or
  16128. // run a single pass if not
  16129. for ( var face = 0; face < faceCount; face ++ ) {
  16130. if ( isPointLight ) {
  16131. _lookTarget.copy( shadowCamera.position );
  16132. _lookTarget.add( cubeDirections[ face ] );
  16133. shadowCamera.up.copy( cubeUps[ face ] );
  16134. shadowCamera.lookAt( _lookTarget );
  16135. shadowCamera.updateMatrixWorld();
  16136. var vpDimensions = cube2DViewPorts[ face ];
  16137. _state.viewport( vpDimensions );
  16138. }
  16139. // update camera matrices and frustum
  16140. _projScreenMatrix.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  16141. _frustum.setFromMatrix( _projScreenMatrix );
  16142. // set object matrices & frustum culling
  16143. renderObject( scene, camera, shadowCamera, isPointLight );
  16144. }
  16145. }
  16146. scope.needsUpdate = false;
  16147. _renderer.setRenderTarget( currentRenderTarget );
  16148. };
  16149. function getDepthMaterial( object, material, isPointLight, lightPositionWorld, shadowCameraNear, shadowCameraFar ) {
  16150. var geometry = object.geometry;
  16151. var result = null;
  16152. var materialVariants = _depthMaterials;
  16153. var customMaterial = object.customDepthMaterial;
  16154. if ( isPointLight ) {
  16155. materialVariants = _distanceMaterials;
  16156. customMaterial = object.customDistanceMaterial;
  16157. }
  16158. if ( ! customMaterial ) {
  16159. var useMorphing = false;
  16160. if ( material.morphTargets ) {
  16161. if ( geometry && geometry.isBufferGeometry ) {
  16162. useMorphing = geometry.morphAttributes && geometry.morphAttributes.position && geometry.morphAttributes.position.length > 0;
  16163. } else if ( geometry && geometry.isGeometry ) {
  16164. useMorphing = geometry.morphTargets && geometry.morphTargets.length > 0;
  16165. }
  16166. }
  16167. if ( object.isSkinnedMesh && material.skinning === false ) {
  16168. console.warn( 'THREE.WebGLShadowMap: THREE.SkinnedMesh with material.skinning set to false:', object );
  16169. }
  16170. var useSkinning = object.isSkinnedMesh && material.skinning;
  16171. var variantIndex = 0;
  16172. if ( useMorphing ) variantIndex |= _MorphingFlag;
  16173. if ( useSkinning ) variantIndex |= _SkinningFlag;
  16174. result = materialVariants[ variantIndex ];
  16175. } else {
  16176. result = customMaterial;
  16177. }
  16178. if ( _renderer.localClippingEnabled &&
  16179. material.clipShadows === true &&
  16180. material.clippingPlanes.length !== 0 ) {
  16181. // in this case we need a unique material instance reflecting the
  16182. // appropriate state
  16183. var keyA = result.uuid, keyB = material.uuid;
  16184. var materialsForVariant = _materialCache[ keyA ];
  16185. if ( materialsForVariant === undefined ) {
  16186. materialsForVariant = {};
  16187. _materialCache[ keyA ] = materialsForVariant;
  16188. }
  16189. var cachedMaterial = materialsForVariant[ keyB ];
  16190. if ( cachedMaterial === undefined ) {
  16191. cachedMaterial = result.clone();
  16192. materialsForVariant[ keyB ] = cachedMaterial;
  16193. }
  16194. result = cachedMaterial;
  16195. }
  16196. result.visible = material.visible;
  16197. result.wireframe = material.wireframe;
  16198. result.side = ( material.shadowSide != null ) ? material.shadowSide : shadowSide[ material.side ];
  16199. result.clipShadows = material.clipShadows;
  16200. result.clippingPlanes = material.clippingPlanes;
  16201. result.clipIntersection = material.clipIntersection;
  16202. result.wireframeLinewidth = material.wireframeLinewidth;
  16203. result.linewidth = material.linewidth;
  16204. if ( isPointLight && result.isMeshDistanceMaterial ) {
  16205. result.referencePosition.copy( lightPositionWorld );
  16206. result.nearDistance = shadowCameraNear;
  16207. result.farDistance = shadowCameraFar;
  16208. }
  16209. return result;
  16210. }
  16211. function renderObject( object, camera, shadowCamera, isPointLight ) {
  16212. if ( object.visible === false ) return;
  16213. var visible = object.layers.test( camera.layers );
  16214. if ( visible && ( object.isMesh || object.isLine || object.isPoints ) ) {
  16215. if ( object.castShadow && ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) ) {
  16216. object.modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  16217. var geometry = _objects.update( object );
  16218. var material = object.material;
  16219. if ( Array.isArray( material ) ) {
  16220. var groups = geometry.groups;
  16221. for ( var k = 0, kl = groups.length; k < kl; k ++ ) {
  16222. var group = groups[ k ];
  16223. var groupMaterial = material[ group.materialIndex ];
  16224. if ( groupMaterial && groupMaterial.visible ) {
  16225. var depthMaterial = getDepthMaterial( object, groupMaterial, isPointLight, _lightPositionWorld, shadowCamera.near, shadowCamera.far );
  16226. _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, group );
  16227. }
  16228. }
  16229. } else if ( material.visible ) {
  16230. var depthMaterial = getDepthMaterial( object, material, isPointLight, _lightPositionWorld, shadowCamera.near, shadowCamera.far );
  16231. _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, null );
  16232. }
  16233. }
  16234. }
  16235. var children = object.children;
  16236. for ( var i = 0, l = children.length; i < l; i ++ ) {
  16237. renderObject( children[ i ], camera, shadowCamera, isPointLight );
  16238. }
  16239. }
  16240. }
  16241. /**
  16242. * @author mrdoob / http://mrdoob.com/
  16243. */
  16244. function WebGLState( gl, extensions, utils, capabilities ) {
  16245. function ColorBuffer() {
  16246. var locked = false;
  16247. var color = new Vector4();
  16248. var currentColorMask = null;
  16249. var currentColorClear = new Vector4( 0, 0, 0, 0 );
  16250. return {
  16251. setMask: function ( colorMask ) {
  16252. if ( currentColorMask !== colorMask && ! locked ) {
  16253. gl.colorMask( colorMask, colorMask, colorMask, colorMask );
  16254. currentColorMask = colorMask;
  16255. }
  16256. },
  16257. setLocked: function ( lock ) {
  16258. locked = lock;
  16259. },
  16260. setClear: function ( r, g, b, a, premultipliedAlpha ) {
  16261. if ( premultipliedAlpha === true ) {
  16262. r *= a; g *= a; b *= a;
  16263. }
  16264. color.set( r, g, b, a );
  16265. if ( currentColorClear.equals( color ) === false ) {
  16266. gl.clearColor( r, g, b, a );
  16267. currentColorClear.copy( color );
  16268. }
  16269. },
  16270. reset: function () {
  16271. locked = false;
  16272. currentColorMask = null;
  16273. currentColorClear.set( - 1, 0, 0, 0 ); // set to invalid state
  16274. }
  16275. };
  16276. }
  16277. function DepthBuffer() {
  16278. var locked = false;
  16279. var currentDepthMask = null;
  16280. var currentDepthFunc = null;
  16281. var currentDepthClear = null;
  16282. return {
  16283. setTest: function ( depthTest ) {
  16284. if ( depthTest ) {
  16285. enable( 2929 );
  16286. } else {
  16287. disable( 2929 );
  16288. }
  16289. },
  16290. setMask: function ( depthMask ) {
  16291. if ( currentDepthMask !== depthMask && ! locked ) {
  16292. gl.depthMask( depthMask );
  16293. currentDepthMask = depthMask;
  16294. }
  16295. },
  16296. setFunc: function ( depthFunc ) {
  16297. if ( currentDepthFunc !== depthFunc ) {
  16298. if ( depthFunc ) {
  16299. switch ( depthFunc ) {
  16300. case NeverDepth:
  16301. gl.depthFunc( 512 );
  16302. break;
  16303. case AlwaysDepth:
  16304. gl.depthFunc( 519 );
  16305. break;
  16306. case LessDepth:
  16307. gl.depthFunc( 513 );
  16308. break;
  16309. case LessEqualDepth:
  16310. gl.depthFunc( 515 );
  16311. break;
  16312. case EqualDepth:
  16313. gl.depthFunc( 514 );
  16314. break;
  16315. case GreaterEqualDepth:
  16316. gl.depthFunc( 518 );
  16317. break;
  16318. case GreaterDepth:
  16319. gl.depthFunc( 516 );
  16320. break;
  16321. case NotEqualDepth:
  16322. gl.depthFunc( 517 );
  16323. break;
  16324. default:
  16325. gl.depthFunc( 515 );
  16326. }
  16327. } else {
  16328. gl.depthFunc( 515 );
  16329. }
  16330. currentDepthFunc = depthFunc;
  16331. }
  16332. },
  16333. setLocked: function ( lock ) {
  16334. locked = lock;
  16335. },
  16336. setClear: function ( depth ) {
  16337. if ( currentDepthClear !== depth ) {
  16338. gl.clearDepth( depth );
  16339. currentDepthClear = depth;
  16340. }
  16341. },
  16342. reset: function () {
  16343. locked = false;
  16344. currentDepthMask = null;
  16345. currentDepthFunc = null;
  16346. currentDepthClear = null;
  16347. }
  16348. };
  16349. }
  16350. function StencilBuffer() {
  16351. var locked = false;
  16352. var currentStencilMask = null;
  16353. var currentStencilFunc = null;
  16354. var currentStencilRef = null;
  16355. var currentStencilFuncMask = null;
  16356. var currentStencilFail = null;
  16357. var currentStencilZFail = null;
  16358. var currentStencilZPass = null;
  16359. var currentStencilClear = null;
  16360. return {
  16361. setTest: function ( stencilTest ) {
  16362. if ( stencilTest ) {
  16363. enable( 2960 );
  16364. } else {
  16365. disable( 2960 );
  16366. }
  16367. },
  16368. setMask: function ( stencilMask ) {
  16369. if ( currentStencilMask !== stencilMask && ! locked ) {
  16370. gl.stencilMask( stencilMask );
  16371. currentStencilMask = stencilMask;
  16372. }
  16373. },
  16374. setFunc: function ( stencilFunc, stencilRef, stencilMask ) {
  16375. if ( currentStencilFunc !== stencilFunc ||
  16376. currentStencilRef !== stencilRef ||
  16377. currentStencilFuncMask !== stencilMask ) {
  16378. gl.stencilFunc( stencilFunc, stencilRef, stencilMask );
  16379. currentStencilFunc = stencilFunc;
  16380. currentStencilRef = stencilRef;
  16381. currentStencilFuncMask = stencilMask;
  16382. }
  16383. },
  16384. setOp: function ( stencilFail, stencilZFail, stencilZPass ) {
  16385. if ( currentStencilFail !== stencilFail ||
  16386. currentStencilZFail !== stencilZFail ||
  16387. currentStencilZPass !== stencilZPass ) {
  16388. gl.stencilOp( stencilFail, stencilZFail, stencilZPass );
  16389. currentStencilFail = stencilFail;
  16390. currentStencilZFail = stencilZFail;
  16391. currentStencilZPass = stencilZPass;
  16392. }
  16393. },
  16394. setLocked: function ( lock ) {
  16395. locked = lock;
  16396. },
  16397. setClear: function ( stencil ) {
  16398. if ( currentStencilClear !== stencil ) {
  16399. gl.clearStencil( stencil );
  16400. currentStencilClear = stencil;
  16401. }
  16402. },
  16403. reset: function () {
  16404. locked = false;
  16405. currentStencilMask = null;
  16406. currentStencilFunc = null;
  16407. currentStencilRef = null;
  16408. currentStencilFuncMask = null;
  16409. currentStencilFail = null;
  16410. currentStencilZFail = null;
  16411. currentStencilZPass = null;
  16412. currentStencilClear = null;
  16413. }
  16414. };
  16415. }
  16416. //
  16417. var colorBuffer = new ColorBuffer();
  16418. var depthBuffer = new DepthBuffer();
  16419. var stencilBuffer = new StencilBuffer();
  16420. var maxVertexAttributes = gl.getParameter( 34921 );
  16421. var newAttributes = new Uint8Array( maxVertexAttributes );
  16422. var enabledAttributes = new Uint8Array( maxVertexAttributes );
  16423. var attributeDivisors = new Uint8Array( maxVertexAttributes );
  16424. var enabledCapabilities = {};
  16425. var compressedTextureFormats = null;
  16426. var currentProgram = null;
  16427. var currentBlendingEnabled = null;
  16428. var currentBlending = null;
  16429. var currentBlendEquation = null;
  16430. var currentBlendSrc = null;
  16431. var currentBlendDst = null;
  16432. var currentBlendEquationAlpha = null;
  16433. var currentBlendSrcAlpha = null;
  16434. var currentBlendDstAlpha = null;
  16435. var currentPremultipledAlpha = false;
  16436. var currentFlipSided = null;
  16437. var currentCullFace = null;
  16438. var currentLineWidth = null;
  16439. var currentPolygonOffsetFactor = null;
  16440. var currentPolygonOffsetUnits = null;
  16441. var maxTextures = gl.getParameter( 35661 );
  16442. var lineWidthAvailable = false;
  16443. var version = 0;
  16444. var glVersion = gl.getParameter( 7938 );
  16445. if ( glVersion.indexOf( 'WebGL' ) !== - 1 ) {
  16446. version = parseFloat( /^WebGL\ ([0-9])/.exec( glVersion )[ 1 ] );
  16447. lineWidthAvailable = ( version >= 1.0 );
  16448. } else if ( glVersion.indexOf( 'OpenGL ES' ) !== - 1 ) {
  16449. version = parseFloat( /^OpenGL\ ES\ ([0-9])/.exec( glVersion )[ 1 ] );
  16450. lineWidthAvailable = ( version >= 2.0 );
  16451. }
  16452. var currentTextureSlot = null;
  16453. var currentBoundTextures = {};
  16454. var currentScissor = new Vector4();
  16455. var currentViewport = new Vector4();
  16456. function createTexture( type, target, count ) {
  16457. var data = new Uint8Array( 4 ); // 4 is required to match default unpack alignment of 4.
  16458. var texture = gl.createTexture();
  16459. gl.bindTexture( type, texture );
  16460. gl.texParameteri( type, 10241, 9728 );
  16461. gl.texParameteri( type, 10240, 9728 );
  16462. for ( var i = 0; i < count; i ++ ) {
  16463. gl.texImage2D( target + i, 0, 6408, 1, 1, 0, 6408, 5121, data );
  16464. }
  16465. return texture;
  16466. }
  16467. var emptyTextures = {};
  16468. emptyTextures[ 3553 ] = createTexture( 3553, 3553, 1 );
  16469. emptyTextures[ 34067 ] = createTexture( 34067, 34069, 6 );
  16470. // init
  16471. colorBuffer.setClear( 0, 0, 0, 1 );
  16472. depthBuffer.setClear( 1 );
  16473. stencilBuffer.setClear( 0 );
  16474. enable( 2929 );
  16475. depthBuffer.setFunc( LessEqualDepth );
  16476. setFlipSided( false );
  16477. setCullFace( CullFaceBack );
  16478. enable( 2884 );
  16479. setBlending( NoBlending );
  16480. //
  16481. function initAttributes() {
  16482. for ( var i = 0, l = newAttributes.length; i < l; i ++ ) {
  16483. newAttributes[ i ] = 0;
  16484. }
  16485. }
  16486. function enableAttribute( attribute ) {
  16487. enableAttributeAndDivisor( attribute, 0 );
  16488. }
  16489. function enableAttributeAndDivisor( attribute, meshPerAttribute ) {
  16490. newAttributes[ attribute ] = 1;
  16491. if ( enabledAttributes[ attribute ] === 0 ) {
  16492. gl.enableVertexAttribArray( attribute );
  16493. enabledAttributes[ attribute ] = 1;
  16494. }
  16495. if ( attributeDivisors[ attribute ] !== meshPerAttribute ) {
  16496. var extension = capabilities.isWebGL2 ? gl : extensions.get( 'ANGLE_instanced_arrays' );
  16497. extension[ capabilities.isWebGL2 ? 'vertexAttribDivisor' : 'vertexAttribDivisorANGLE' ]( attribute, meshPerAttribute );
  16498. attributeDivisors[ attribute ] = meshPerAttribute;
  16499. }
  16500. }
  16501. function disableUnusedAttributes() {
  16502. for ( var i = 0, l = enabledAttributes.length; i !== l; ++ i ) {
  16503. if ( enabledAttributes[ i ] !== newAttributes[ i ] ) {
  16504. gl.disableVertexAttribArray( i );
  16505. enabledAttributes[ i ] = 0;
  16506. }
  16507. }
  16508. }
  16509. function enable( id ) {
  16510. if ( enabledCapabilities[ id ] !== true ) {
  16511. gl.enable( id );
  16512. enabledCapabilities[ id ] = true;
  16513. }
  16514. }
  16515. function disable( id ) {
  16516. if ( enabledCapabilities[ id ] !== false ) {
  16517. gl.disable( id );
  16518. enabledCapabilities[ id ] = false;
  16519. }
  16520. }
  16521. function getCompressedTextureFormats() {
  16522. if ( compressedTextureFormats === null ) {
  16523. compressedTextureFormats = [];
  16524. if ( extensions.get( 'WEBGL_compressed_texture_pvrtc' ) ||
  16525. extensions.get( 'WEBGL_compressed_texture_s3tc' ) ||
  16526. extensions.get( 'WEBGL_compressed_texture_etc1' ) ||
  16527. extensions.get( 'WEBGL_compressed_texture_astc' ) ) {
  16528. var formats = gl.getParameter( 34467 );
  16529. for ( var i = 0; i < formats.length; i ++ ) {
  16530. compressedTextureFormats.push( formats[ i ] );
  16531. }
  16532. }
  16533. }
  16534. return compressedTextureFormats;
  16535. }
  16536. function useProgram( program ) {
  16537. if ( currentProgram !== program ) {
  16538. gl.useProgram( program );
  16539. currentProgram = program;
  16540. return true;
  16541. }
  16542. return false;
  16543. }
  16544. function setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha ) {
  16545. if ( blending === NoBlending ) {
  16546. if ( currentBlendingEnabled ) {
  16547. disable( 3042 );
  16548. currentBlendingEnabled = false;
  16549. }
  16550. return;
  16551. }
  16552. if ( ! currentBlendingEnabled ) {
  16553. enable( 3042 );
  16554. currentBlendingEnabled = true;
  16555. }
  16556. if ( blending !== CustomBlending ) {
  16557. if ( blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha ) {
  16558. if ( currentBlendEquation !== AddEquation || currentBlendEquationAlpha !== AddEquation ) {
  16559. gl.blendEquation( 32774 );
  16560. currentBlendEquation = AddEquation;
  16561. currentBlendEquationAlpha = AddEquation;
  16562. }
  16563. if ( premultipliedAlpha ) {
  16564. switch ( blending ) {
  16565. case NormalBlending:
  16566. gl.blendFuncSeparate( 1, 771, 1, 771 );
  16567. break;
  16568. case AdditiveBlending:
  16569. gl.blendFunc( 1, 1 );
  16570. break;
  16571. case SubtractiveBlending:
  16572. gl.blendFuncSeparate( 0, 0, 769, 771 );
  16573. break;
  16574. case MultiplyBlending:
  16575. gl.blendFuncSeparate( 0, 768, 0, 770 );
  16576. break;
  16577. default:
  16578. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  16579. break;
  16580. }
  16581. } else {
  16582. switch ( blending ) {
  16583. case NormalBlending:
  16584. gl.blendFuncSeparate( 770, 771, 1, 771 );
  16585. break;
  16586. case AdditiveBlending:
  16587. gl.blendFunc( 770, 1 );
  16588. break;
  16589. case SubtractiveBlending:
  16590. gl.blendFunc( 0, 769 );
  16591. break;
  16592. case MultiplyBlending:
  16593. gl.blendFunc( 0, 768 );
  16594. break;
  16595. default:
  16596. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  16597. break;
  16598. }
  16599. }
  16600. currentBlendSrc = null;
  16601. currentBlendDst = null;
  16602. currentBlendSrcAlpha = null;
  16603. currentBlendDstAlpha = null;
  16604. currentBlending = blending;
  16605. currentPremultipledAlpha = premultipliedAlpha;
  16606. }
  16607. return;
  16608. }
  16609. // custom blending
  16610. blendEquationAlpha = blendEquationAlpha || blendEquation;
  16611. blendSrcAlpha = blendSrcAlpha || blendSrc;
  16612. blendDstAlpha = blendDstAlpha || blendDst;
  16613. if ( blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha ) {
  16614. gl.blendEquationSeparate( utils.convert( blendEquation ), utils.convert( blendEquationAlpha ) );
  16615. currentBlendEquation = blendEquation;
  16616. currentBlendEquationAlpha = blendEquationAlpha;
  16617. }
  16618. if ( blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha ) {
  16619. gl.blendFuncSeparate( utils.convert( blendSrc ), utils.convert( blendDst ), utils.convert( blendSrcAlpha ), utils.convert( blendDstAlpha ) );
  16620. currentBlendSrc = blendSrc;
  16621. currentBlendDst = blendDst;
  16622. currentBlendSrcAlpha = blendSrcAlpha;
  16623. currentBlendDstAlpha = blendDstAlpha;
  16624. }
  16625. currentBlending = blending;
  16626. currentPremultipledAlpha = null;
  16627. }
  16628. function setMaterial( material, frontFaceCW ) {
  16629. material.side === DoubleSide
  16630. ? disable( 2884 )
  16631. : enable( 2884 );
  16632. var flipSided = ( material.side === BackSide );
  16633. if ( frontFaceCW ) flipSided = ! flipSided;
  16634. setFlipSided( flipSided );
  16635. ( material.blending === NormalBlending && material.transparent === false )
  16636. ? setBlending( NoBlending )
  16637. : setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha );
  16638. depthBuffer.setFunc( material.depthFunc );
  16639. depthBuffer.setTest( material.depthTest );
  16640. depthBuffer.setMask( material.depthWrite );
  16641. colorBuffer.setMask( material.colorWrite );
  16642. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  16643. }
  16644. //
  16645. function setFlipSided( flipSided ) {
  16646. if ( currentFlipSided !== flipSided ) {
  16647. if ( flipSided ) {
  16648. gl.frontFace( 2304 );
  16649. } else {
  16650. gl.frontFace( 2305 );
  16651. }
  16652. currentFlipSided = flipSided;
  16653. }
  16654. }
  16655. function setCullFace( cullFace ) {
  16656. if ( cullFace !== CullFaceNone ) {
  16657. enable( 2884 );
  16658. if ( cullFace !== currentCullFace ) {
  16659. if ( cullFace === CullFaceBack ) {
  16660. gl.cullFace( 1029 );
  16661. } else if ( cullFace === CullFaceFront ) {
  16662. gl.cullFace( 1028 );
  16663. } else {
  16664. gl.cullFace( 1032 );
  16665. }
  16666. }
  16667. } else {
  16668. disable( 2884 );
  16669. }
  16670. currentCullFace = cullFace;
  16671. }
  16672. function setLineWidth( width ) {
  16673. if ( width !== currentLineWidth ) {
  16674. if ( lineWidthAvailable ) gl.lineWidth( width );
  16675. currentLineWidth = width;
  16676. }
  16677. }
  16678. function setPolygonOffset( polygonOffset, factor, units ) {
  16679. if ( polygonOffset ) {
  16680. enable( 32823 );
  16681. if ( currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units ) {
  16682. gl.polygonOffset( factor, units );
  16683. currentPolygonOffsetFactor = factor;
  16684. currentPolygonOffsetUnits = units;
  16685. }
  16686. } else {
  16687. disable( 32823 );
  16688. }
  16689. }
  16690. function setScissorTest( scissorTest ) {
  16691. if ( scissorTest ) {
  16692. enable( 3089 );
  16693. } else {
  16694. disable( 3089 );
  16695. }
  16696. }
  16697. // texture
  16698. function activeTexture( webglSlot ) {
  16699. if ( webglSlot === undefined ) webglSlot = 33984 + maxTextures - 1;
  16700. if ( currentTextureSlot !== webglSlot ) {
  16701. gl.activeTexture( webglSlot );
  16702. currentTextureSlot = webglSlot;
  16703. }
  16704. }
  16705. function bindTexture( webglType, webglTexture ) {
  16706. if ( currentTextureSlot === null ) {
  16707. activeTexture();
  16708. }
  16709. var boundTexture = currentBoundTextures[ currentTextureSlot ];
  16710. if ( boundTexture === undefined ) {
  16711. boundTexture = { type: undefined, texture: undefined };
  16712. currentBoundTextures[ currentTextureSlot ] = boundTexture;
  16713. }
  16714. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  16715. gl.bindTexture( webglType, webglTexture || emptyTextures[ webglType ] );
  16716. boundTexture.type = webglType;
  16717. boundTexture.texture = webglTexture;
  16718. }
  16719. }
  16720. function compressedTexImage2D() {
  16721. try {
  16722. gl.compressedTexImage2D.apply( gl, arguments );
  16723. } catch ( error ) {
  16724. console.error( 'THREE.WebGLState:', error );
  16725. }
  16726. }
  16727. function texImage2D() {
  16728. try {
  16729. gl.texImage2D.apply( gl, arguments );
  16730. } catch ( error ) {
  16731. console.error( 'THREE.WebGLState:', error );
  16732. }
  16733. }
  16734. function texImage3D() {
  16735. try {
  16736. gl.texImage3D.apply( gl, arguments );
  16737. } catch ( error ) {
  16738. console.error( 'THREE.WebGLState:', error );
  16739. }
  16740. }
  16741. //
  16742. function scissor( scissor ) {
  16743. if ( currentScissor.equals( scissor ) === false ) {
  16744. gl.scissor( scissor.x, scissor.y, scissor.z, scissor.w );
  16745. currentScissor.copy( scissor );
  16746. }
  16747. }
  16748. function viewport( viewport ) {
  16749. if ( currentViewport.equals( viewport ) === false ) {
  16750. gl.viewport( viewport.x, viewport.y, viewport.z, viewport.w );
  16751. currentViewport.copy( viewport );
  16752. }
  16753. }
  16754. //
  16755. function reset() {
  16756. for ( var i = 0; i < enabledAttributes.length; i ++ ) {
  16757. if ( enabledAttributes[ i ] === 1 ) {
  16758. gl.disableVertexAttribArray( i );
  16759. enabledAttributes[ i ] = 0;
  16760. }
  16761. }
  16762. enabledCapabilities = {};
  16763. compressedTextureFormats = null;
  16764. currentTextureSlot = null;
  16765. currentBoundTextures = {};
  16766. currentProgram = null;
  16767. currentBlending = null;
  16768. currentFlipSided = null;
  16769. currentCullFace = null;
  16770. colorBuffer.reset();
  16771. depthBuffer.reset();
  16772. stencilBuffer.reset();
  16773. }
  16774. return {
  16775. buffers: {
  16776. color: colorBuffer,
  16777. depth: depthBuffer,
  16778. stencil: stencilBuffer
  16779. },
  16780. initAttributes: initAttributes,
  16781. enableAttribute: enableAttribute,
  16782. enableAttributeAndDivisor: enableAttributeAndDivisor,
  16783. disableUnusedAttributes: disableUnusedAttributes,
  16784. enable: enable,
  16785. disable: disable,
  16786. getCompressedTextureFormats: getCompressedTextureFormats,
  16787. useProgram: useProgram,
  16788. setBlending: setBlending,
  16789. setMaterial: setMaterial,
  16790. setFlipSided: setFlipSided,
  16791. setCullFace: setCullFace,
  16792. setLineWidth: setLineWidth,
  16793. setPolygonOffset: setPolygonOffset,
  16794. setScissorTest: setScissorTest,
  16795. activeTexture: activeTexture,
  16796. bindTexture: bindTexture,
  16797. compressedTexImage2D: compressedTexImage2D,
  16798. texImage2D: texImage2D,
  16799. texImage3D: texImage3D,
  16800. scissor: scissor,
  16801. viewport: viewport,
  16802. reset: reset
  16803. };
  16804. }
  16805. /**
  16806. * @author mrdoob / http://mrdoob.com/
  16807. */
  16808. function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info ) {
  16809. var _videoTextures = {};
  16810. var _canvas;
  16811. //
  16812. var useOffscreenCanvas = typeof OffscreenCanvas !== 'undefined';
  16813. function createCanvas( width, height ) {
  16814. // Use OffscreenCanvas when available. Specially needed in web workers
  16815. return useOffscreenCanvas ?
  16816. new OffscreenCanvas( width, height ) :
  16817. document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  16818. }
  16819. function resizeImage( image, needsPowerOfTwo, needsNewCanvas, maxSize ) {
  16820. var scale = 1;
  16821. // handle case if texture exceeds max size
  16822. if ( image.width > maxSize || image.height > maxSize ) {
  16823. scale = maxSize / Math.max( image.width, image.height );
  16824. }
  16825. // only perform resize if necessary
  16826. if ( scale < 1 || needsPowerOfTwo === true ) {
  16827. // only perform resize for certain image types
  16828. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  16829. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  16830. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  16831. var floor = needsPowerOfTwo ? _Math.floorPowerOfTwo : Math.floor;
  16832. var width = floor( scale * image.width );
  16833. var height = floor( scale * image.height );
  16834. if ( _canvas === undefined ) _canvas = createCanvas( width, height );
  16835. // cube textures can't reuse the same canvas
  16836. var canvas = needsNewCanvas ? createCanvas( width, height ) : _canvas;
  16837. canvas.width = width;
  16838. canvas.height = height;
  16839. var context = canvas.getContext( '2d' );
  16840. context.drawImage( image, 0, 0, width, height );
  16841. console.warn( 'THREE.WebGLRenderer: Texture has been resized from (' + image.width + 'x' + image.height + ') to (' + width + 'x' + height + ').' );
  16842. return canvas;
  16843. } else {
  16844. if ( 'data' in image ) {
  16845. console.warn( 'THREE.WebGLRenderer: Image in DataTexture is too big (' + image.width + 'x' + image.height + ').' );
  16846. }
  16847. return image;
  16848. }
  16849. }
  16850. return image;
  16851. }
  16852. function isPowerOfTwo( image ) {
  16853. return _Math.isPowerOfTwo( image.width ) && _Math.isPowerOfTwo( image.height );
  16854. }
  16855. function textureNeedsPowerOfTwo( texture ) {
  16856. if ( capabilities.isWebGL2 ) return false;
  16857. return ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) ||
  16858. ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter );
  16859. }
  16860. function textureNeedsGenerateMipmaps( texture, supportsMips ) {
  16861. return texture.generateMipmaps && supportsMips &&
  16862. texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter;
  16863. }
  16864. function generateMipmap( target, texture, width, height ) {
  16865. _gl.generateMipmap( target );
  16866. var textureProperties = properties.get( texture );
  16867. // Note: Math.log( x ) * Math.LOG2E used instead of Math.log2( x ) which is not supported by IE11
  16868. textureProperties.__maxMipLevel = Math.log( Math.max( width, height ) ) * Math.LOG2E;
  16869. }
  16870. function getInternalFormat( glFormat, glType ) {
  16871. if ( ! capabilities.isWebGL2 ) return glFormat;
  16872. var internalFormat = glFormat;
  16873. if ( glFormat === 6403 ) {
  16874. if ( glType === 5126 ) internalFormat = 33326;
  16875. if ( glType === 5131 ) internalFormat = 33325;
  16876. if ( glType === 5121 ) internalFormat = 33321;
  16877. }
  16878. if ( glFormat === 6407 ) {
  16879. if ( glType === 5126 ) internalFormat = 34837;
  16880. if ( glType === 5131 ) internalFormat = 34843;
  16881. if ( glType === 5121 ) internalFormat = 32849;
  16882. }
  16883. if ( glFormat === 6408 ) {
  16884. if ( glType === 5126 ) internalFormat = 34836;
  16885. if ( glType === 5131 ) internalFormat = 34842;
  16886. if ( glType === 5121 ) internalFormat = 32856;
  16887. }
  16888. if ( internalFormat === 33325 || internalFormat === 33326 ||
  16889. internalFormat === 34842 || internalFormat === 34836 ) {
  16890. extensions.get( 'EXT_color_buffer_float' );
  16891. } else if ( internalFormat === 34843 || internalFormat === 34837 ) {
  16892. console.warn( 'THREE.WebGLRenderer: Floating point textures with RGB format not supported. Please use RGBA instead.' );
  16893. }
  16894. return internalFormat;
  16895. }
  16896. // Fallback filters for non-power-of-2 textures
  16897. function filterFallback( f ) {
  16898. if ( f === NearestFilter || f === NearestMipMapNearestFilter || f === NearestMipMapLinearFilter ) {
  16899. return 9728;
  16900. }
  16901. return 9729;
  16902. }
  16903. //
  16904. function onTextureDispose( event ) {
  16905. var texture = event.target;
  16906. texture.removeEventListener( 'dispose', onTextureDispose );
  16907. deallocateTexture( texture );
  16908. if ( texture.isVideoTexture ) {
  16909. delete _videoTextures[ texture.id ];
  16910. }
  16911. info.memory.textures --;
  16912. }
  16913. function onRenderTargetDispose( event ) {
  16914. var renderTarget = event.target;
  16915. renderTarget.removeEventListener( 'dispose', onRenderTargetDispose );
  16916. deallocateRenderTarget( renderTarget );
  16917. info.memory.textures --;
  16918. }
  16919. //
  16920. function deallocateTexture( texture ) {
  16921. var textureProperties = properties.get( texture );
  16922. if ( textureProperties.__webglInit === undefined ) return;
  16923. _gl.deleteTexture( textureProperties.__webglTexture );
  16924. properties.remove( texture );
  16925. }
  16926. function deallocateRenderTarget( renderTarget ) {
  16927. var renderTargetProperties = properties.get( renderTarget );
  16928. var textureProperties = properties.get( renderTarget.texture );
  16929. if ( ! renderTarget ) return;
  16930. if ( textureProperties.__webglTexture !== undefined ) {
  16931. _gl.deleteTexture( textureProperties.__webglTexture );
  16932. }
  16933. if ( renderTarget.depthTexture ) {
  16934. renderTarget.depthTexture.dispose();
  16935. }
  16936. if ( renderTarget.isWebGLRenderTargetCube ) {
  16937. for ( var i = 0; i < 6; i ++ ) {
  16938. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ i ] );
  16939. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer[ i ] );
  16940. }
  16941. } else {
  16942. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer );
  16943. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer );
  16944. }
  16945. properties.remove( renderTarget.texture );
  16946. properties.remove( renderTarget );
  16947. }
  16948. //
  16949. function setTexture2D( texture, slot ) {
  16950. var textureProperties = properties.get( texture );
  16951. if ( texture.isVideoTexture ) updateVideoTexture( texture );
  16952. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  16953. var image = texture.image;
  16954. if ( image === undefined ) {
  16955. console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is undefined' );
  16956. } else if ( image.complete === false ) {
  16957. console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is incomplete' );
  16958. } else {
  16959. uploadTexture( textureProperties, texture, slot );
  16960. return;
  16961. }
  16962. }
  16963. state.activeTexture( 33984 + slot );
  16964. state.bindTexture( 3553, textureProperties.__webglTexture );
  16965. }
  16966. function setTexture2DArray( texture, slot ) {
  16967. var textureProperties = properties.get( texture );
  16968. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  16969. uploadTexture( textureProperties, texture, slot );
  16970. return;
  16971. }
  16972. state.activeTexture( 33984 + slot );
  16973. state.bindTexture( 35866, textureProperties.__webglTexture );
  16974. }
  16975. function setTexture3D( texture, slot ) {
  16976. var textureProperties = properties.get( texture );
  16977. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  16978. uploadTexture( textureProperties, texture, slot );
  16979. return;
  16980. }
  16981. state.activeTexture( 33984 + slot );
  16982. state.bindTexture( 32879, textureProperties.__webglTexture );
  16983. }
  16984. function setTextureCube( texture, slot ) {
  16985. var textureProperties = properties.get( texture );
  16986. if ( texture.image.length === 6 ) {
  16987. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  16988. initTexture( textureProperties, texture );
  16989. state.activeTexture( 33984 + slot );
  16990. state.bindTexture( 34067, textureProperties.__webglTexture );
  16991. _gl.pixelStorei( 37440, texture.flipY );
  16992. var isCompressed = ( texture && texture.isCompressedTexture );
  16993. var isDataTexture = ( texture.image[ 0 ] && texture.image[ 0 ].isDataTexture );
  16994. var cubeImage = [];
  16995. for ( var i = 0; i < 6; i ++ ) {
  16996. if ( ! isCompressed && ! isDataTexture ) {
  16997. cubeImage[ i ] = resizeImage( texture.image[ i ], false, true, capabilities.maxCubemapSize );
  16998. } else {
  16999. cubeImage[ i ] = isDataTexture ? texture.image[ i ].image : texture.image[ i ];
  17000. }
  17001. }
  17002. var image = cubeImage[ 0 ],
  17003. supportsMips = isPowerOfTwo( image ) || capabilities.isWebGL2,
  17004. glFormat = utils.convert( texture.format ),
  17005. glType = utils.convert( texture.type ),
  17006. glInternalFormat = getInternalFormat( glFormat, glType );
  17007. setTextureParameters( 34067, texture, supportsMips );
  17008. for ( var i = 0; i < 6; i ++ ) {
  17009. if ( ! isCompressed ) {
  17010. if ( isDataTexture ) {
  17011. state.texImage2D( 34069 + i, 0, glInternalFormat, cubeImage[ i ].width, cubeImage[ i ].height, 0, glFormat, glType, cubeImage[ i ].data );
  17012. } else {
  17013. state.texImage2D( 34069 + i, 0, glInternalFormat, glFormat, glType, cubeImage[ i ] );
  17014. }
  17015. } else {
  17016. var mipmap, mipmaps = cubeImage[ i ].mipmaps;
  17017. for ( var j = 0, jl = mipmaps.length; j < jl; j ++ ) {
  17018. mipmap = mipmaps[ j ];
  17019. if ( texture.format !== RGBAFormat && texture.format !== RGBFormat ) {
  17020. if ( state.getCompressedTextureFormats().indexOf( glFormat ) > - 1 ) {
  17021. state.compressedTexImage2D( 34069 + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  17022. } else {
  17023. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()' );
  17024. }
  17025. } else {
  17026. state.texImage2D( 34069 + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  17027. }
  17028. }
  17029. }
  17030. }
  17031. if ( ! isCompressed ) {
  17032. textureProperties.__maxMipLevel = 0;
  17033. } else {
  17034. textureProperties.__maxMipLevel = mipmaps.length - 1;
  17035. }
  17036. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  17037. // We assume images for cube map have the same size.
  17038. generateMipmap( 34067, texture, image.width, image.height );
  17039. }
  17040. textureProperties.__version = texture.version;
  17041. if ( texture.onUpdate ) texture.onUpdate( texture );
  17042. } else {
  17043. state.activeTexture( 33984 + slot );
  17044. state.bindTexture( 34067, textureProperties.__webglTexture );
  17045. }
  17046. }
  17047. }
  17048. function setTextureCubeDynamic( texture, slot ) {
  17049. state.activeTexture( 33984 + slot );
  17050. state.bindTexture( 34067, properties.get( texture ).__webglTexture );
  17051. }
  17052. function setTextureParameters( textureType, texture, supportsMips ) {
  17053. var extension;
  17054. if ( supportsMips ) {
  17055. _gl.texParameteri( textureType, 10242, utils.convert( texture.wrapS ) );
  17056. _gl.texParameteri( textureType, 10243, utils.convert( texture.wrapT ) );
  17057. if ( textureType === 32879 || textureType === 35866 ) {
  17058. _gl.texParameteri( textureType, 32882, utils.convert( texture.wrapR ) );
  17059. }
  17060. _gl.texParameteri( textureType, 10240, utils.convert( texture.magFilter ) );
  17061. _gl.texParameteri( textureType, 10241, utils.convert( texture.minFilter ) );
  17062. } else {
  17063. _gl.texParameteri( textureType, 10242, 33071 );
  17064. _gl.texParameteri( textureType, 10243, 33071 );
  17065. if ( textureType === 32879 || textureType === 35866 ) {
  17066. _gl.texParameteri( textureType, 32882, 33071 );
  17067. }
  17068. if ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) {
  17069. console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping.' );
  17070. }
  17071. _gl.texParameteri( textureType, 10240, filterFallback( texture.magFilter ) );
  17072. _gl.texParameteri( textureType, 10241, filterFallback( texture.minFilter ) );
  17073. if ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ) {
  17074. console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.' );
  17075. }
  17076. }
  17077. extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  17078. if ( extension ) {
  17079. if ( texture.type === FloatType && extensions.get( 'OES_texture_float_linear' ) === null ) return;
  17080. if ( texture.type === HalfFloatType && ( capabilities.isWebGL2 || extensions.get( 'OES_texture_half_float_linear' ) ) === null ) return;
  17081. if ( texture.anisotropy > 1 || properties.get( texture ).__currentAnisotropy ) {
  17082. _gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, capabilities.getMaxAnisotropy() ) );
  17083. properties.get( texture ).__currentAnisotropy = texture.anisotropy;
  17084. }
  17085. }
  17086. }
  17087. function initTexture( textureProperties, texture ) {
  17088. if ( textureProperties.__webglInit === undefined ) {
  17089. textureProperties.__webglInit = true;
  17090. texture.addEventListener( 'dispose', onTextureDispose );
  17091. textureProperties.__webglTexture = _gl.createTexture();
  17092. info.memory.textures ++;
  17093. }
  17094. }
  17095. function uploadTexture( textureProperties, texture, slot ) {
  17096. var textureType = 3553;
  17097. if ( texture.isDataTexture2DArray ) textureType = 35866;
  17098. if ( texture.isDataTexture3D ) textureType = 32879;
  17099. initTexture( textureProperties, texture );
  17100. state.activeTexture( 33984 + slot );
  17101. state.bindTexture( textureType, textureProperties.__webglTexture );
  17102. _gl.pixelStorei( 37440, texture.flipY );
  17103. _gl.pixelStorei( 37441, texture.premultiplyAlpha );
  17104. _gl.pixelStorei( 3317, texture.unpackAlignment );
  17105. var needsPowerOfTwo = textureNeedsPowerOfTwo( texture ) && isPowerOfTwo( texture.image ) === false;
  17106. var image = resizeImage( texture.image, needsPowerOfTwo, false, capabilities.maxTextureSize );
  17107. var supportsMips = isPowerOfTwo( image ) || capabilities.isWebGL2,
  17108. glFormat = utils.convert( texture.format ),
  17109. glType = utils.convert( texture.type ),
  17110. glInternalFormat = getInternalFormat( glFormat, glType );
  17111. setTextureParameters( textureType, texture, supportsMips );
  17112. var mipmap, mipmaps = texture.mipmaps;
  17113. if ( texture.isDepthTexture ) {
  17114. // populate depth texture with dummy data
  17115. glInternalFormat = 6402;
  17116. if ( texture.type === FloatType ) {
  17117. if ( ! capabilities.isWebGL2 ) throw new Error( 'Float Depth Texture only supported in WebGL2.0' );
  17118. glInternalFormat = 36012;
  17119. } else if ( capabilities.isWebGL2 ) {
  17120. // WebGL 2.0 requires signed internalformat for glTexImage2D
  17121. glInternalFormat = 33189;
  17122. }
  17123. if ( texture.format === DepthFormat && glInternalFormat === 6402 ) {
  17124. // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  17125. // DEPTH_COMPONENT and type is not UNSIGNED_SHORT or UNSIGNED_INT
  17126. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  17127. if ( texture.type !== UnsignedShortType && texture.type !== UnsignedIntType ) {
  17128. console.warn( 'THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture.' );
  17129. texture.type = UnsignedShortType;
  17130. glType = utils.convert( texture.type );
  17131. }
  17132. }
  17133. // Depth stencil textures need the DEPTH_STENCIL internal format
  17134. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  17135. if ( texture.format === DepthStencilFormat ) {
  17136. glInternalFormat = 34041;
  17137. // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  17138. // DEPTH_STENCIL and type is not UNSIGNED_INT_24_8_WEBGL.
  17139. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  17140. if ( texture.type !== UnsignedInt248Type ) {
  17141. console.warn( 'THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture.' );
  17142. texture.type = UnsignedInt248Type;
  17143. glType = utils.convert( texture.type );
  17144. }
  17145. }
  17146. state.texImage2D( 3553, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, null );
  17147. } else if ( texture.isDataTexture ) {
  17148. // use manually created mipmaps if available
  17149. // if there are no manual mipmaps
  17150. // set 0 level mipmap and then use GL to generate other mipmap levels
  17151. if ( mipmaps.length > 0 && supportsMips ) {
  17152. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  17153. mipmap = mipmaps[ i ];
  17154. state.texImage2D( 3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  17155. }
  17156. texture.generateMipmaps = false;
  17157. textureProperties.__maxMipLevel = mipmaps.length - 1;
  17158. } else {
  17159. state.texImage2D( 3553, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, image.data );
  17160. textureProperties.__maxMipLevel = 0;
  17161. }
  17162. } else if ( texture.isCompressedTexture ) {
  17163. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  17164. mipmap = mipmaps[ i ];
  17165. if ( texture.format !== RGBAFormat && texture.format !== RGBFormat ) {
  17166. if ( state.getCompressedTextureFormats().indexOf( glFormat ) > - 1 ) {
  17167. state.compressedTexImage2D( 3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  17168. } else {
  17169. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  17170. }
  17171. } else {
  17172. state.texImage2D( 3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  17173. }
  17174. }
  17175. textureProperties.__maxMipLevel = mipmaps.length - 1;
  17176. } else if ( texture.isDataTexture2DArray ) {
  17177. state.texImage3D( 35866, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data );
  17178. textureProperties.__maxMipLevel = 0;
  17179. } else if ( texture.isDataTexture3D ) {
  17180. state.texImage3D( 32879, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data );
  17181. textureProperties.__maxMipLevel = 0;
  17182. } else {
  17183. // regular Texture (image, video, canvas)
  17184. // use manually created mipmaps if available
  17185. // if there are no manual mipmaps
  17186. // set 0 level mipmap and then use GL to generate other mipmap levels
  17187. if ( mipmaps.length > 0 && supportsMips ) {
  17188. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  17189. mipmap = mipmaps[ i ];
  17190. state.texImage2D( 3553, i, glInternalFormat, glFormat, glType, mipmap );
  17191. }
  17192. texture.generateMipmaps = false;
  17193. textureProperties.__maxMipLevel = mipmaps.length - 1;
  17194. } else {
  17195. state.texImage2D( 3553, 0, glInternalFormat, glFormat, glType, image );
  17196. textureProperties.__maxMipLevel = 0;
  17197. }
  17198. }
  17199. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  17200. generateMipmap( 3553, texture, image.width, image.height );
  17201. }
  17202. textureProperties.__version = texture.version;
  17203. if ( texture.onUpdate ) texture.onUpdate( texture );
  17204. }
  17205. // Render targets
  17206. // Setup storage for target texture and bind it to correct framebuffer
  17207. function setupFrameBufferTexture( framebuffer, renderTarget, attachment, textureTarget ) {
  17208. var glFormat = utils.convert( renderTarget.texture.format );
  17209. var glType = utils.convert( renderTarget.texture.type );
  17210. var glInternalFormat = getInternalFormat( glFormat, glType );
  17211. state.texImage2D( textureTarget, 0, glInternalFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  17212. _gl.bindFramebuffer( 36160, framebuffer );
  17213. _gl.framebufferTexture2D( 36160, attachment, textureTarget, properties.get( renderTarget.texture ).__webglTexture, 0 );
  17214. _gl.bindFramebuffer( 36160, null );
  17215. }
  17216. // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  17217. function setupRenderBufferStorage( renderbuffer, renderTarget, isMultisample ) {
  17218. _gl.bindRenderbuffer( 36161, renderbuffer );
  17219. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  17220. if ( isMultisample ) {
  17221. var samples = getRenderTargetSamples( renderTarget );
  17222. _gl.renderbufferStorageMultisample( 36161, samples, 33189, renderTarget.width, renderTarget.height );
  17223. } else {
  17224. _gl.renderbufferStorage( 36161, 33189, renderTarget.width, renderTarget.height );
  17225. }
  17226. _gl.framebufferRenderbuffer( 36160, 36096, 36161, renderbuffer );
  17227. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  17228. if ( isMultisample ) {
  17229. var samples = getRenderTargetSamples( renderTarget );
  17230. _gl.renderbufferStorageMultisample( 36161, samples, 34041, renderTarget.width, renderTarget.height );
  17231. } else {
  17232. _gl.renderbufferStorage( 36161, 34041, renderTarget.width, renderTarget.height );
  17233. }
  17234. _gl.framebufferRenderbuffer( 36160, 33306, 36161, renderbuffer );
  17235. } else {
  17236. var glFormat = utils.convert( renderTarget.texture.format );
  17237. var glType = utils.convert( renderTarget.texture.type );
  17238. var glInternalFormat = getInternalFormat( glFormat, glType );
  17239. if ( isMultisample ) {
  17240. var samples = getRenderTargetSamples( renderTarget );
  17241. _gl.renderbufferStorageMultisample( 36161, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  17242. } else {
  17243. _gl.renderbufferStorage( 36161, glInternalFormat, renderTarget.width, renderTarget.height );
  17244. }
  17245. }
  17246. _gl.bindRenderbuffer( 36161, null );
  17247. }
  17248. // Setup resources for a Depth Texture for a FBO (needs an extension)
  17249. function setupDepthTexture( framebuffer, renderTarget ) {
  17250. var isCube = ( renderTarget && renderTarget.isWebGLRenderTargetCube );
  17251. if ( isCube ) throw new Error( 'Depth Texture with cube render targets is not supported' );
  17252. _gl.bindFramebuffer( 36160, framebuffer );
  17253. if ( ! ( renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture ) ) {
  17254. throw new Error( 'renderTarget.depthTexture must be an instance of THREE.DepthTexture' );
  17255. }
  17256. // upload an empty depth texture with framebuffer size
  17257. if ( ! properties.get( renderTarget.depthTexture ).__webglTexture ||
  17258. renderTarget.depthTexture.image.width !== renderTarget.width ||
  17259. renderTarget.depthTexture.image.height !== renderTarget.height ) {
  17260. renderTarget.depthTexture.image.width = renderTarget.width;
  17261. renderTarget.depthTexture.image.height = renderTarget.height;
  17262. renderTarget.depthTexture.needsUpdate = true;
  17263. }
  17264. setTexture2D( renderTarget.depthTexture, 0 );
  17265. var webglDepthTexture = properties.get( renderTarget.depthTexture ).__webglTexture;
  17266. if ( renderTarget.depthTexture.format === DepthFormat ) {
  17267. _gl.framebufferTexture2D( 36160, 36096, 3553, webglDepthTexture, 0 );
  17268. } else if ( renderTarget.depthTexture.format === DepthStencilFormat ) {
  17269. _gl.framebufferTexture2D( 36160, 33306, 3553, webglDepthTexture, 0 );
  17270. } else {
  17271. throw new Error( 'Unknown depthTexture format' );
  17272. }
  17273. }
  17274. // Setup GL resources for a non-texture depth buffer
  17275. function setupDepthRenderbuffer( renderTarget ) {
  17276. var renderTargetProperties = properties.get( renderTarget );
  17277. var isCube = ( renderTarget.isWebGLRenderTargetCube === true );
  17278. if ( renderTarget.depthTexture ) {
  17279. if ( isCube ) throw new Error( 'target.depthTexture not supported in Cube render targets' );
  17280. setupDepthTexture( renderTargetProperties.__webglFramebuffer, renderTarget );
  17281. } else {
  17282. if ( isCube ) {
  17283. renderTargetProperties.__webglDepthbuffer = [];
  17284. for ( var i = 0; i < 6; i ++ ) {
  17285. _gl.bindFramebuffer( 36160, renderTargetProperties.__webglFramebuffer[ i ] );
  17286. renderTargetProperties.__webglDepthbuffer[ i ] = _gl.createRenderbuffer();
  17287. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer[ i ], renderTarget );
  17288. }
  17289. } else {
  17290. _gl.bindFramebuffer( 36160, renderTargetProperties.__webglFramebuffer );
  17291. renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer();
  17292. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer, renderTarget );
  17293. }
  17294. }
  17295. _gl.bindFramebuffer( 36160, null );
  17296. }
  17297. // Set up GL resources for the render target
  17298. function setupRenderTarget( renderTarget ) {
  17299. var renderTargetProperties = properties.get( renderTarget );
  17300. var textureProperties = properties.get( renderTarget.texture );
  17301. renderTarget.addEventListener( 'dispose', onRenderTargetDispose );
  17302. textureProperties.__webglTexture = _gl.createTexture();
  17303. info.memory.textures ++;
  17304. var isCube = ( renderTarget.isWebGLRenderTargetCube === true );
  17305. var isMultisample = ( renderTarget.isWebGLMultisampleRenderTarget === true );
  17306. var supportsMips = isPowerOfTwo( renderTarget ) || capabilities.isWebGL2;
  17307. // Setup framebuffer
  17308. if ( isCube ) {
  17309. renderTargetProperties.__webglFramebuffer = [];
  17310. for ( var i = 0; i < 6; i ++ ) {
  17311. renderTargetProperties.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  17312. }
  17313. } else {
  17314. renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer();
  17315. if ( isMultisample ) {
  17316. if ( capabilities.isWebGL2 ) {
  17317. renderTargetProperties.__webglMultisampledFramebuffer = _gl.createFramebuffer();
  17318. renderTargetProperties.__webglColorRenderbuffer = _gl.createRenderbuffer();
  17319. _gl.bindRenderbuffer( 36161, renderTargetProperties.__webglColorRenderbuffer );
  17320. var glFormat = utils.convert( renderTarget.texture.format );
  17321. var glType = utils.convert( renderTarget.texture.type );
  17322. var glInternalFormat = getInternalFormat( glFormat, glType );
  17323. var samples = getRenderTargetSamples( renderTarget );
  17324. _gl.renderbufferStorageMultisample( 36161, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  17325. _gl.bindFramebuffer( 36160, renderTargetProperties.__webglMultisampledFramebuffer );
  17326. _gl.framebufferRenderbuffer( 36160, 36064, 36161, renderTargetProperties.__webglColorRenderbuffer );
  17327. _gl.bindRenderbuffer( 36161, null );
  17328. if ( renderTarget.depthBuffer ) {
  17329. renderTargetProperties.__webglDepthRenderbuffer = _gl.createRenderbuffer();
  17330. setupRenderBufferStorage( renderTargetProperties.__webglDepthRenderbuffer, renderTarget, true );
  17331. }
  17332. _gl.bindFramebuffer( 36160, null );
  17333. } else {
  17334. console.warn( 'THREE.WebGLRenderer: WebGLMultisampleRenderTarget can only be used with WebGL2.' );
  17335. }
  17336. }
  17337. }
  17338. // Setup color buffer
  17339. if ( isCube ) {
  17340. state.bindTexture( 34067, textureProperties.__webglTexture );
  17341. setTextureParameters( 34067, renderTarget.texture, supportsMips );
  17342. for ( var i = 0; i < 6; i ++ ) {
  17343. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ i ], renderTarget, 36064, 34069 + i );
  17344. }
  17345. if ( textureNeedsGenerateMipmaps( renderTarget.texture, supportsMips ) ) {
  17346. generateMipmap( 34067, renderTarget.texture, renderTarget.width, renderTarget.height );
  17347. }
  17348. state.bindTexture( 34067, null );
  17349. } else {
  17350. state.bindTexture( 3553, textureProperties.__webglTexture );
  17351. setTextureParameters( 3553, renderTarget.texture, supportsMips );
  17352. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, 36064, 3553 );
  17353. if ( textureNeedsGenerateMipmaps( renderTarget.texture, supportsMips ) ) {
  17354. generateMipmap( 3553, renderTarget.texture, renderTarget.width, renderTarget.height );
  17355. }
  17356. state.bindTexture( 3553, null );
  17357. }
  17358. // Setup depth and stencil buffers
  17359. if ( renderTarget.depthBuffer ) {
  17360. setupDepthRenderbuffer( renderTarget );
  17361. }
  17362. }
  17363. function updateRenderTargetMipmap( renderTarget ) {
  17364. var texture = renderTarget.texture;
  17365. var supportsMips = isPowerOfTwo( renderTarget ) || capabilities.isWebGL2;
  17366. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  17367. var target = renderTarget.isWebGLRenderTargetCube ? 34067 : 3553;
  17368. var webglTexture = properties.get( texture ).__webglTexture;
  17369. state.bindTexture( target, webglTexture );
  17370. generateMipmap( target, texture, renderTarget.width, renderTarget.height );
  17371. state.bindTexture( target, null );
  17372. }
  17373. }
  17374. function updateMultisampleRenderTarget( renderTarget ) {
  17375. if ( renderTarget.isWebGLMultisampleRenderTarget ) {
  17376. if ( capabilities.isWebGL2 ) {
  17377. var renderTargetProperties = properties.get( renderTarget );
  17378. _gl.bindFramebuffer( 36008, renderTargetProperties.__webglMultisampledFramebuffer );
  17379. _gl.bindFramebuffer( 36009, renderTargetProperties.__webglFramebuffer );
  17380. var width = renderTarget.width;
  17381. var height = renderTarget.height;
  17382. var mask = 16384;
  17383. if ( renderTarget.depthBuffer ) mask |= 256;
  17384. if ( renderTarget.stencilBuffer ) mask |= 1024;
  17385. _gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, mask, 9728 );
  17386. } else {
  17387. console.warn( 'THREE.WebGLRenderer: WebGLMultisampleRenderTarget can only be used with WebGL2.' );
  17388. }
  17389. }
  17390. }
  17391. function getRenderTargetSamples( renderTarget ) {
  17392. return ( capabilities.isWebGL2 && renderTarget.isWebGLMultisampleRenderTarget ) ?
  17393. Math.min( capabilities.maxSamples, renderTarget.samples ) : 0;
  17394. }
  17395. function updateVideoTexture( texture ) {
  17396. var id = texture.id;
  17397. var frame = info.render.frame;
  17398. // Check the last frame we updated the VideoTexture
  17399. if ( _videoTextures[ id ] !== frame ) {
  17400. _videoTextures[ id ] = frame;
  17401. texture.update();
  17402. }
  17403. }
  17404. this.setTexture2D = setTexture2D;
  17405. this.setTexture2DArray = setTexture2DArray;
  17406. this.setTexture3D = setTexture3D;
  17407. this.setTextureCube = setTextureCube;
  17408. this.setTextureCubeDynamic = setTextureCubeDynamic;
  17409. this.setupRenderTarget = setupRenderTarget;
  17410. this.updateRenderTargetMipmap = updateRenderTargetMipmap;
  17411. this.updateMultisampleRenderTarget = updateMultisampleRenderTarget;
  17412. }
  17413. /**
  17414. * @author thespite / http://www.twitter.com/thespite
  17415. */
  17416. function WebGLUtils( gl, extensions, capabilities ) {
  17417. function convert( p ) {
  17418. var extension;
  17419. if ( p === RepeatWrapping ) return 10497;
  17420. if ( p === ClampToEdgeWrapping ) return 33071;
  17421. if ( p === MirroredRepeatWrapping ) return 33648;
  17422. if ( p === NearestFilter ) return 9728;
  17423. if ( p === NearestMipMapNearestFilter ) return 9984;
  17424. if ( p === NearestMipMapLinearFilter ) return 9986;
  17425. if ( p === LinearFilter ) return 9729;
  17426. if ( p === LinearMipMapNearestFilter ) return 9985;
  17427. if ( p === LinearMipMapLinearFilter ) return 9987;
  17428. if ( p === UnsignedByteType ) return 5121;
  17429. if ( p === UnsignedShort4444Type ) return 32819;
  17430. if ( p === UnsignedShort5551Type ) return 32820;
  17431. if ( p === UnsignedShort565Type ) return 33635;
  17432. if ( p === ByteType ) return 5120;
  17433. if ( p === ShortType ) return 5122;
  17434. if ( p === UnsignedShortType ) return 5123;
  17435. if ( p === IntType ) return 5124;
  17436. if ( p === UnsignedIntType ) return 5125;
  17437. if ( p === FloatType ) return 5126;
  17438. if ( p === HalfFloatType ) {
  17439. if ( capabilities.isWebGL2 ) return 5131;
  17440. extension = extensions.get( 'OES_texture_half_float' );
  17441. if ( extension !== null ) return extension.HALF_FLOAT_OES;
  17442. }
  17443. if ( p === AlphaFormat ) return 6406;
  17444. if ( p === RGBFormat ) return 6407;
  17445. if ( p === RGBAFormat ) return 6408;
  17446. if ( p === LuminanceFormat ) return 6409;
  17447. if ( p === LuminanceAlphaFormat ) return 6410;
  17448. if ( p === DepthFormat ) return 6402;
  17449. if ( p === DepthStencilFormat ) return 34041;
  17450. if ( p === RedFormat ) return 6403;
  17451. if ( p === AddEquation ) return 32774;
  17452. if ( p === SubtractEquation ) return 32778;
  17453. if ( p === ReverseSubtractEquation ) return 32779;
  17454. if ( p === ZeroFactor ) return 0;
  17455. if ( p === OneFactor ) return 1;
  17456. if ( p === SrcColorFactor ) return 768;
  17457. if ( p === OneMinusSrcColorFactor ) return 769;
  17458. if ( p === SrcAlphaFactor ) return 770;
  17459. if ( p === OneMinusSrcAlphaFactor ) return 771;
  17460. if ( p === DstAlphaFactor ) return 772;
  17461. if ( p === OneMinusDstAlphaFactor ) return 773;
  17462. if ( p === DstColorFactor ) return 774;
  17463. if ( p === OneMinusDstColorFactor ) return 775;
  17464. if ( p === SrcAlphaSaturateFactor ) return 776;
  17465. if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format ||
  17466. p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) {
  17467. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  17468. if ( extension !== null ) {
  17469. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  17470. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  17471. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  17472. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  17473. }
  17474. }
  17475. if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format ||
  17476. p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {
  17477. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  17478. if ( extension !== null ) {
  17479. if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  17480. if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  17481. if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  17482. if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  17483. }
  17484. }
  17485. if ( p === RGB_ETC1_Format ) {
  17486. extension = extensions.get( 'WEBGL_compressed_texture_etc1' );
  17487. if ( extension !== null ) return extension.COMPRESSED_RGB_ETC1_WEBGL;
  17488. }
  17489. if ( p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format ||
  17490. p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format ||
  17491. p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format ||
  17492. p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format ||
  17493. p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format ) {
  17494. extension = extensions.get( 'WEBGL_compressed_texture_astc' );
  17495. if ( extension !== null ) {
  17496. return p;
  17497. }
  17498. }
  17499. if ( p === MinEquation || p === MaxEquation ) {
  17500. if ( capabilities.isWebGL2 ) {
  17501. if ( p === MinEquation ) return 32775;
  17502. if ( p === MaxEquation ) return 32776;
  17503. }
  17504. extension = extensions.get( 'EXT_blend_minmax' );
  17505. if ( extension !== null ) {
  17506. if ( p === MinEquation ) return extension.MIN_EXT;
  17507. if ( p === MaxEquation ) return extension.MAX_EXT;
  17508. }
  17509. }
  17510. if ( p === UnsignedInt248Type ) {
  17511. if ( capabilities.isWebGL2 ) return 34042;
  17512. extension = extensions.get( 'WEBGL_depth_texture' );
  17513. if ( extension !== null ) return extension.UNSIGNED_INT_24_8_WEBGL;
  17514. }
  17515. return 0;
  17516. }
  17517. return { convert: convert };
  17518. }
  17519. /**
  17520. * @author mrdoob / http://mrdoob.com/
  17521. */
  17522. function Group() {
  17523. Object3D.call( this );
  17524. this.type = 'Group';
  17525. }
  17526. Group.prototype = Object.assign( Object.create( Object3D.prototype ), {
  17527. constructor: Group,
  17528. isGroup: true
  17529. } );
  17530. /**
  17531. * @author mrdoob / http://mrdoob.com/
  17532. * @author mikael emtinger / http://gomo.se/
  17533. * @author WestLangley / http://github.com/WestLangley
  17534. */
  17535. function Camera() {
  17536. Object3D.call( this );
  17537. this.type = 'Camera';
  17538. this.matrixWorldInverse = new Matrix4();
  17539. this.projectionMatrix = new Matrix4();
  17540. this.projectionMatrixInverse = new Matrix4();
  17541. }
  17542. Camera.prototype = Object.assign( Object.create( Object3D.prototype ), {
  17543. constructor: Camera,
  17544. isCamera: true,
  17545. copy: function ( source, recursive ) {
  17546. Object3D.prototype.copy.call( this, source, recursive );
  17547. this.matrixWorldInverse.copy( source.matrixWorldInverse );
  17548. this.projectionMatrix.copy( source.projectionMatrix );
  17549. this.projectionMatrixInverse.copy( source.projectionMatrixInverse );
  17550. return this;
  17551. },
  17552. getWorldDirection: function ( target ) {
  17553. if ( target === undefined ) {
  17554. console.warn( 'THREE.Camera: .getWorldDirection() target is now required' );
  17555. target = new Vector3();
  17556. }
  17557. this.updateMatrixWorld( true );
  17558. var e = this.matrixWorld.elements;
  17559. return target.set( - e[ 8 ], - e[ 9 ], - e[ 10 ] ).normalize();
  17560. },
  17561. updateMatrixWorld: function ( force ) {
  17562. Object3D.prototype.updateMatrixWorld.call( this, force );
  17563. this.matrixWorldInverse.getInverse( this.matrixWorld );
  17564. },
  17565. clone: function () {
  17566. return new this.constructor().copy( this );
  17567. }
  17568. } );
  17569. /**
  17570. * @author mrdoob / http://mrdoob.com/
  17571. * @author greggman / http://games.greggman.com/
  17572. * @author zz85 / http://www.lab4games.net/zz85/blog
  17573. * @author tschw
  17574. */
  17575. function PerspectiveCamera( fov, aspect, near, far ) {
  17576. Camera.call( this );
  17577. this.type = 'PerspectiveCamera';
  17578. this.fov = fov !== undefined ? fov : 50;
  17579. this.zoom = 1;
  17580. this.near = near !== undefined ? near : 0.1;
  17581. this.far = far !== undefined ? far : 2000;
  17582. this.focus = 10;
  17583. this.aspect = aspect !== undefined ? aspect : 1;
  17584. this.view = null;
  17585. this.filmGauge = 35; // width of the film (default in millimeters)
  17586. this.filmOffset = 0; // horizontal film offset (same unit as gauge)
  17587. this.updateProjectionMatrix();
  17588. }
  17589. PerspectiveCamera.prototype = Object.assign( Object.create( Camera.prototype ), {
  17590. constructor: PerspectiveCamera,
  17591. isPerspectiveCamera: true,
  17592. copy: function ( source, recursive ) {
  17593. Camera.prototype.copy.call( this, source, recursive );
  17594. this.fov = source.fov;
  17595. this.zoom = source.zoom;
  17596. this.near = source.near;
  17597. this.far = source.far;
  17598. this.focus = source.focus;
  17599. this.aspect = source.aspect;
  17600. this.view = source.view === null ? null : Object.assign( {}, source.view );
  17601. this.filmGauge = source.filmGauge;
  17602. this.filmOffset = source.filmOffset;
  17603. return this;
  17604. },
  17605. /**
  17606. * Sets the FOV by focal length in respect to the current .filmGauge.
  17607. *
  17608. * The default film gauge is 35, so that the focal length can be specified for
  17609. * a 35mm (full frame) camera.
  17610. *
  17611. * Values for focal length and film gauge must have the same unit.
  17612. */
  17613. setFocalLength: function ( focalLength ) {
  17614. // see http://www.bobatkins.com/photography/technical/field_of_view.html
  17615. var vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
  17616. this.fov = _Math.RAD2DEG * 2 * Math.atan( vExtentSlope );
  17617. this.updateProjectionMatrix();
  17618. },
  17619. /**
  17620. * Calculates the focal length from the current .fov and .filmGauge.
  17621. */
  17622. getFocalLength: function () {
  17623. var vExtentSlope = Math.tan( _Math.DEG2RAD * 0.5 * this.fov );
  17624. return 0.5 * this.getFilmHeight() / vExtentSlope;
  17625. },
  17626. getEffectiveFOV: function () {
  17627. return _Math.RAD2DEG * 2 * Math.atan(
  17628. Math.tan( _Math.DEG2RAD * 0.5 * this.fov ) / this.zoom );
  17629. },
  17630. getFilmWidth: function () {
  17631. // film not completely covered in portrait format (aspect < 1)
  17632. return this.filmGauge * Math.min( this.aspect, 1 );
  17633. },
  17634. getFilmHeight: function () {
  17635. // film not completely covered in landscape format (aspect > 1)
  17636. return this.filmGauge / Math.max( this.aspect, 1 );
  17637. },
  17638. /**
  17639. * Sets an offset in a larger frustum. This is useful for multi-window or
  17640. * multi-monitor/multi-machine setups.
  17641. *
  17642. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  17643. * the monitors are in grid like this
  17644. *
  17645. * +---+---+---+
  17646. * | A | B | C |
  17647. * +---+---+---+
  17648. * | D | E | F |
  17649. * +---+---+---+
  17650. *
  17651. * then for each monitor you would call it like this
  17652. *
  17653. * var w = 1920;
  17654. * var h = 1080;
  17655. * var fullWidth = w * 3;
  17656. * var fullHeight = h * 2;
  17657. *
  17658. * --A--
  17659. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  17660. * --B--
  17661. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  17662. * --C--
  17663. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  17664. * --D--
  17665. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  17666. * --E--
  17667. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  17668. * --F--
  17669. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  17670. *
  17671. * Note there is no reason monitors have to be the same size or in a grid.
  17672. */
  17673. setViewOffset: function ( fullWidth, fullHeight, x, y, width, height ) {
  17674. this.aspect = fullWidth / fullHeight;
  17675. if ( this.view === null ) {
  17676. this.view = {
  17677. enabled: true,
  17678. fullWidth: 1,
  17679. fullHeight: 1,
  17680. offsetX: 0,
  17681. offsetY: 0,
  17682. width: 1,
  17683. height: 1
  17684. };
  17685. }
  17686. this.view.enabled = true;
  17687. this.view.fullWidth = fullWidth;
  17688. this.view.fullHeight = fullHeight;
  17689. this.view.offsetX = x;
  17690. this.view.offsetY = y;
  17691. this.view.width = width;
  17692. this.view.height = height;
  17693. this.updateProjectionMatrix();
  17694. },
  17695. clearViewOffset: function () {
  17696. if ( this.view !== null ) {
  17697. this.view.enabled = false;
  17698. }
  17699. this.updateProjectionMatrix();
  17700. },
  17701. updateProjectionMatrix: function () {
  17702. var near = this.near,
  17703. top = near * Math.tan( _Math.DEG2RAD * 0.5 * this.fov ) / this.zoom,
  17704. height = 2 * top,
  17705. width = this.aspect * height,
  17706. left = - 0.5 * width,
  17707. view = this.view;
  17708. if ( this.view !== null && this.view.enabled ) {
  17709. var fullWidth = view.fullWidth,
  17710. fullHeight = view.fullHeight;
  17711. left += view.offsetX * width / fullWidth;
  17712. top -= view.offsetY * height / fullHeight;
  17713. width *= view.width / fullWidth;
  17714. height *= view.height / fullHeight;
  17715. }
  17716. var skew = this.filmOffset;
  17717. if ( skew !== 0 ) left += near * skew / this.getFilmWidth();
  17718. this.projectionMatrix.makePerspective( left, left + width, top, top - height, near, this.far );
  17719. this.projectionMatrixInverse.getInverse( this.projectionMatrix );
  17720. },
  17721. toJSON: function ( meta ) {
  17722. var data = Object3D.prototype.toJSON.call( this, meta );
  17723. data.object.fov = this.fov;
  17724. data.object.zoom = this.zoom;
  17725. data.object.near = this.near;
  17726. data.object.far = this.far;
  17727. data.object.focus = this.focus;
  17728. data.object.aspect = this.aspect;
  17729. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  17730. data.object.filmGauge = this.filmGauge;
  17731. data.object.filmOffset = this.filmOffset;
  17732. return data;
  17733. }
  17734. } );
  17735. /**
  17736. * @author mrdoob / http://mrdoob.com/
  17737. */
  17738. function ArrayCamera( array ) {
  17739. PerspectiveCamera.call( this );
  17740. this.cameras = array || [];
  17741. }
  17742. ArrayCamera.prototype = Object.assign( Object.create( PerspectiveCamera.prototype ), {
  17743. constructor: ArrayCamera,
  17744. isArrayCamera: true
  17745. } );
  17746. /**
  17747. * @author jsantell / https://www.jsantell.com/
  17748. * @author mrdoob / http://mrdoob.com/
  17749. */
  17750. var cameraLPos = new Vector3();
  17751. var cameraRPos = new Vector3();
  17752. /**
  17753. * Assumes 2 cameras that are parallel and share an X-axis, and that
  17754. * the cameras' projection and world matrices have already been set.
  17755. * And that near and far planes are identical for both cameras.
  17756. * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765
  17757. */
  17758. function setProjectionFromUnion( camera, cameraL, cameraR ) {
  17759. cameraLPos.setFromMatrixPosition( cameraL.matrixWorld );
  17760. cameraRPos.setFromMatrixPosition( cameraR.matrixWorld );
  17761. var ipd = cameraLPos.distanceTo( cameraRPos );
  17762. var projL = cameraL.projectionMatrix.elements;
  17763. var projR = cameraR.projectionMatrix.elements;
  17764. // VR systems will have identical far and near planes, and
  17765. // most likely identical top and bottom frustum extents.
  17766. // Use the left camera for these values.
  17767. var near = projL[ 14 ] / ( projL[ 10 ] - 1 );
  17768. var far = projL[ 14 ] / ( projL[ 10 ] + 1 );
  17769. var topFov = ( projL[ 9 ] + 1 ) / projL[ 5 ];
  17770. var bottomFov = ( projL[ 9 ] - 1 ) / projL[ 5 ];
  17771. var leftFov = ( projL[ 8 ] - 1 ) / projL[ 0 ];
  17772. var rightFov = ( projR[ 8 ] + 1 ) / projR[ 0 ];
  17773. var left = near * leftFov;
  17774. var right = near * rightFov;
  17775. // Calculate the new camera's position offset from the
  17776. // left camera. xOffset should be roughly half `ipd`.
  17777. var zOffset = ipd / ( - leftFov + rightFov );
  17778. var xOffset = zOffset * - leftFov;
  17779. // TODO: Better way to apply this offset?
  17780. cameraL.matrixWorld.decompose( camera.position, camera.quaternion, camera.scale );
  17781. camera.translateX( xOffset );
  17782. camera.translateZ( zOffset );
  17783. camera.matrixWorld.compose( camera.position, camera.quaternion, camera.scale );
  17784. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  17785. // Find the union of the frustum values of the cameras and scale
  17786. // the values so that the near plane's position does not change in world space,
  17787. // although must now be relative to the new union camera.
  17788. var near2 = near + zOffset;
  17789. var far2 = far + zOffset;
  17790. var left2 = left - xOffset;
  17791. var right2 = right + ( ipd - xOffset );
  17792. var top2 = topFov * far / far2 * near2;
  17793. var bottom2 = bottomFov * far / far2 * near2;
  17794. camera.projectionMatrix.makePerspective( left2, right2, top2, bottom2, near2, far2 );
  17795. }
  17796. /**
  17797. * @author mrdoob / http://mrdoob.com/
  17798. */
  17799. function WebVRManager( renderer ) {
  17800. var scope = this;
  17801. var device = null;
  17802. var frameData = null;
  17803. var poseTarget = null;
  17804. var controllers = [];
  17805. var standingMatrix = new Matrix4();
  17806. var standingMatrixInverse = new Matrix4();
  17807. var framebufferScaleFactor = 1.0;
  17808. var frameOfReferenceType = 'stage';
  17809. if ( typeof window !== 'undefined' && 'VRFrameData' in window ) {
  17810. frameData = new window.VRFrameData();
  17811. window.addEventListener( 'vrdisplaypresentchange', onVRDisplayPresentChange, false );
  17812. }
  17813. var matrixWorldInverse = new Matrix4();
  17814. var tempQuaternion = new Quaternion();
  17815. var tempPosition = new Vector3();
  17816. var cameraL = new PerspectiveCamera();
  17817. cameraL.bounds = new Vector4( 0.0, 0.0, 0.5, 1.0 );
  17818. cameraL.layers.enable( 1 );
  17819. var cameraR = new PerspectiveCamera();
  17820. cameraR.bounds = new Vector4( 0.5, 0.0, 0.5, 1.0 );
  17821. cameraR.layers.enable( 2 );
  17822. var cameraVR = new ArrayCamera( [ cameraL, cameraR ] );
  17823. cameraVR.layers.enable( 1 );
  17824. cameraVR.layers.enable( 2 );
  17825. //
  17826. function isPresenting() {
  17827. return device !== null && device.isPresenting === true;
  17828. }
  17829. var currentSize = new Vector2(), currentPixelRatio;
  17830. function onVRDisplayPresentChange() {
  17831. updateDrawingBufferSize();
  17832. if ( isPresenting() ) {
  17833. animation.start();
  17834. } else {
  17835. animation.stop();
  17836. }
  17837. }
  17838. //
  17839. var triggers = [];
  17840. function findGamepad( id ) {
  17841. var gamepads = navigator.getGamepads && navigator.getGamepads();
  17842. for ( var i = 0, j = 0, l = gamepads.length; i < l; i ++ ) {
  17843. var gamepad = gamepads[ i ];
  17844. if ( gamepad && ( gamepad.id === 'Daydream Controller' ||
  17845. gamepad.id === 'Gear VR Controller' || gamepad.id === 'Oculus Go Controller' ||
  17846. gamepad.id === 'OpenVR Gamepad' || gamepad.id.startsWith( 'Oculus Touch' ) ||
  17847. gamepad.id.startsWith( 'Spatial Controller' ) ) ) {
  17848. if ( j === id ) return gamepad;
  17849. j ++;
  17850. }
  17851. }
  17852. }
  17853. function updateDrawingBufferSize() {
  17854. if ( isPresenting() ) {
  17855. var eyeParameters = device.getEyeParameters( 'left' );
  17856. var renderWidth = eyeParameters.renderWidth * framebufferScaleFactor;
  17857. var renderHeight = eyeParameters.renderHeight * framebufferScaleFactor;
  17858. renderer.setDrawingBufferSize( renderWidth * 2, renderHeight, 1 );
  17859. } else {
  17860. if ( scope.enabled ) {
  17861. currentPixelRatio = renderer.getPixelRatio();
  17862. renderer.getSize( currentSize );
  17863. renderer.setDrawingBufferSize( currentSize.width, currentSize.height, currentPixelRatio );
  17864. }
  17865. }
  17866. }
  17867. function updateControllers() {
  17868. for ( var i = 0; i < controllers.length; i ++ ) {
  17869. var controller = controllers[ i ];
  17870. var gamepad = findGamepad( i );
  17871. if ( gamepad !== undefined && gamepad.pose !== undefined ) {
  17872. if ( gamepad.pose === null ) return;
  17873. // Pose
  17874. var pose = gamepad.pose;
  17875. if ( pose.hasPosition === false ) controller.position.set( 0.2, - 0.6, - 0.05 );
  17876. if ( pose.position !== null ) controller.position.fromArray( pose.position );
  17877. if ( pose.orientation !== null ) controller.quaternion.fromArray( pose.orientation );
  17878. controller.matrix.compose( controller.position, controller.quaternion, controller.scale );
  17879. controller.matrix.premultiply( standingMatrix );
  17880. controller.matrix.decompose( controller.position, controller.quaternion, controller.scale );
  17881. controller.matrixWorldNeedsUpdate = true;
  17882. controller.visible = true;
  17883. // Trigger
  17884. var buttonId = gamepad.id === 'Daydream Controller' ? 0 : 1;
  17885. if ( triggers[ i ] !== gamepad.buttons[ buttonId ].pressed ) {
  17886. triggers[ i ] = gamepad.buttons[ buttonId ].pressed;
  17887. if ( triggers[ i ] === true ) {
  17888. controller.dispatchEvent( { type: 'selectstart' } );
  17889. } else {
  17890. controller.dispatchEvent( { type: 'selectend' } );
  17891. controller.dispatchEvent( { type: 'select' } );
  17892. }
  17893. }
  17894. } else {
  17895. controller.visible = false;
  17896. }
  17897. }
  17898. }
  17899. //
  17900. this.enabled = false;
  17901. this.getController = function ( id ) {
  17902. var controller = controllers[ id ];
  17903. if ( controller === undefined ) {
  17904. controller = new Group();
  17905. controller.matrixAutoUpdate = false;
  17906. controller.visible = false;
  17907. controllers[ id ] = controller;
  17908. }
  17909. return controller;
  17910. };
  17911. this.getDevice = function () {
  17912. return device;
  17913. };
  17914. this.setDevice = function ( value ) {
  17915. if ( value !== undefined ) device = value;
  17916. animation.setContext( value );
  17917. updateDrawingBufferSize();
  17918. if ( isPresenting() ) animation.start();
  17919. };
  17920. this.setFramebufferScaleFactor = function ( value ) {
  17921. framebufferScaleFactor = value;
  17922. };
  17923. this.setFrameOfReferenceType = function ( value ) {
  17924. frameOfReferenceType = value;
  17925. };
  17926. this.setPoseTarget = function ( object ) {
  17927. if ( object !== undefined ) poseTarget = object;
  17928. };
  17929. this.getCamera = function ( camera ) {
  17930. var userHeight = frameOfReferenceType === 'stage' ? 1.6 : 0;
  17931. if ( isPresenting() === false ) {
  17932. camera.position.set( 0, userHeight, 0 );
  17933. camera.rotation.set( 0, 0, 0 );
  17934. return camera;
  17935. }
  17936. device.depthNear = camera.near;
  17937. device.depthFar = camera.far;
  17938. device.getFrameData( frameData );
  17939. //
  17940. if ( frameOfReferenceType === 'stage' ) {
  17941. var stageParameters = device.stageParameters;
  17942. if ( stageParameters ) {
  17943. standingMatrix.fromArray( stageParameters.sittingToStandingTransform );
  17944. } else {
  17945. standingMatrix.makeTranslation( 0, userHeight, 0 );
  17946. }
  17947. }
  17948. var pose = frameData.pose;
  17949. var poseObject = poseTarget !== null ? poseTarget : camera;
  17950. // We want to manipulate poseObject by its position and quaternion components since users may rely on them.
  17951. poseObject.matrix.copy( standingMatrix );
  17952. poseObject.matrix.decompose( poseObject.position, poseObject.quaternion, poseObject.scale );
  17953. if ( pose.orientation !== null ) {
  17954. tempQuaternion.fromArray( pose.orientation );
  17955. poseObject.quaternion.multiply( tempQuaternion );
  17956. }
  17957. if ( pose.position !== null ) {
  17958. tempQuaternion.setFromRotationMatrix( standingMatrix );
  17959. tempPosition.fromArray( pose.position );
  17960. tempPosition.applyQuaternion( tempQuaternion );
  17961. poseObject.position.add( tempPosition );
  17962. }
  17963. poseObject.updateMatrixWorld();
  17964. //
  17965. cameraL.near = camera.near;
  17966. cameraR.near = camera.near;
  17967. cameraL.far = camera.far;
  17968. cameraR.far = camera.far;
  17969. cameraL.matrixWorldInverse.fromArray( frameData.leftViewMatrix );
  17970. cameraR.matrixWorldInverse.fromArray( frameData.rightViewMatrix );
  17971. // TODO (mrdoob) Double check this code
  17972. standingMatrixInverse.getInverse( standingMatrix );
  17973. if ( frameOfReferenceType === 'stage' ) {
  17974. cameraL.matrixWorldInverse.multiply( standingMatrixInverse );
  17975. cameraR.matrixWorldInverse.multiply( standingMatrixInverse );
  17976. }
  17977. var parent = poseObject.parent;
  17978. if ( parent !== null ) {
  17979. matrixWorldInverse.getInverse( parent.matrixWorld );
  17980. cameraL.matrixWorldInverse.multiply( matrixWorldInverse );
  17981. cameraR.matrixWorldInverse.multiply( matrixWorldInverse );
  17982. }
  17983. // envMap and Mirror needs camera.matrixWorld
  17984. cameraL.matrixWorld.getInverse( cameraL.matrixWorldInverse );
  17985. cameraR.matrixWorld.getInverse( cameraR.matrixWorldInverse );
  17986. cameraL.projectionMatrix.fromArray( frameData.leftProjectionMatrix );
  17987. cameraR.projectionMatrix.fromArray( frameData.rightProjectionMatrix );
  17988. setProjectionFromUnion( cameraVR, cameraL, cameraR );
  17989. //
  17990. var layers = device.getLayers();
  17991. if ( layers.length ) {
  17992. var layer = layers[ 0 ];
  17993. if ( layer.leftBounds !== null && layer.leftBounds.length === 4 ) {
  17994. cameraL.bounds.fromArray( layer.leftBounds );
  17995. }
  17996. if ( layer.rightBounds !== null && layer.rightBounds.length === 4 ) {
  17997. cameraR.bounds.fromArray( layer.rightBounds );
  17998. }
  17999. }
  18000. updateControllers();
  18001. return cameraVR;
  18002. };
  18003. this.getStandingMatrix = function () {
  18004. return standingMatrix;
  18005. };
  18006. this.isPresenting = isPresenting;
  18007. // Animation Loop
  18008. var animation = new WebGLAnimation();
  18009. this.setAnimationLoop = function ( callback ) {
  18010. animation.setAnimationLoop( callback );
  18011. if ( isPresenting() ) animation.start();
  18012. };
  18013. this.submitFrame = function () {
  18014. if ( isPresenting() ) device.submitFrame();
  18015. };
  18016. this.dispose = function () {
  18017. if ( typeof window !== 'undefined' ) {
  18018. window.removeEventListener( 'vrdisplaypresentchange', onVRDisplayPresentChange );
  18019. }
  18020. };
  18021. }
  18022. /**
  18023. * @author mrdoob / http://mrdoob.com/
  18024. */
  18025. function WebXRManager( renderer ) {
  18026. var gl = renderer.context;
  18027. var device = null;
  18028. var session = null;
  18029. var framebufferScaleFactor = 1.0;
  18030. var frameOfReference = null;
  18031. var frameOfReferenceType = 'stage';
  18032. var pose = null;
  18033. var poseTarget = null;
  18034. var controllers = [];
  18035. var inputSources = [];
  18036. function isPresenting() {
  18037. return session !== null && frameOfReference !== null;
  18038. }
  18039. //
  18040. var cameraL = new PerspectiveCamera();
  18041. cameraL.layers.enable( 1 );
  18042. cameraL.viewport = new Vector4();
  18043. var cameraR = new PerspectiveCamera();
  18044. cameraR.layers.enable( 2 );
  18045. cameraR.viewport = new Vector4();
  18046. var cameraVR = new ArrayCamera( [ cameraL, cameraR ] );
  18047. cameraVR.layers.enable( 1 );
  18048. cameraVR.layers.enable( 2 );
  18049. //
  18050. this.enabled = false;
  18051. this.getController = function ( id ) {
  18052. var controller = controllers[ id ];
  18053. if ( controller === undefined ) {
  18054. controller = new Group();
  18055. controller.matrixAutoUpdate = false;
  18056. controller.visible = false;
  18057. controllers[ id ] = controller;
  18058. }
  18059. return controller;
  18060. };
  18061. this.getDevice = function () {
  18062. return device;
  18063. };
  18064. this.setDevice = function ( value ) {
  18065. if ( value !== undefined ) device = value;
  18066. if ( value instanceof XRDevice ) gl.setCompatibleXRDevice( value );
  18067. };
  18068. //
  18069. function onSessionEvent( event ) {
  18070. var controller = controllers[ inputSources.indexOf( event.inputSource ) ];
  18071. if ( controller ) controller.dispatchEvent( { type: event.type } );
  18072. }
  18073. function onSessionEnd() {
  18074. renderer.setFramebuffer( null );
  18075. renderer.setRenderTarget( renderer.getRenderTarget() ); // Hack #15830
  18076. animation.stop();
  18077. }
  18078. this.setFramebufferScaleFactor = function ( value ) {
  18079. framebufferScaleFactor = value;
  18080. };
  18081. this.setFrameOfReferenceType = function ( value ) {
  18082. frameOfReferenceType = value;
  18083. };
  18084. this.setSession = function ( value ) {
  18085. session = value;
  18086. if ( session !== null ) {
  18087. session.addEventListener( 'select', onSessionEvent );
  18088. session.addEventListener( 'selectstart', onSessionEvent );
  18089. session.addEventListener( 'selectend', onSessionEvent );
  18090. session.addEventListener( 'end', onSessionEnd );
  18091. session.baseLayer = new XRWebGLLayer( session, gl, { framebufferScaleFactor: framebufferScaleFactor } );
  18092. session.requestFrameOfReference( frameOfReferenceType ).then( function ( value ) {
  18093. frameOfReference = value;
  18094. renderer.setFramebuffer( session.baseLayer.framebuffer );
  18095. animation.setContext( session );
  18096. animation.start();
  18097. } );
  18098. //
  18099. inputSources = session.getInputSources();
  18100. session.addEventListener( 'inputsourceschange', function () {
  18101. inputSources = session.getInputSources();
  18102. console.log( inputSources );
  18103. for ( var i = 0; i < controllers.length; i ++ ) {
  18104. var controller = controllers[ i ];
  18105. controller.userData.inputSource = inputSources[ i ];
  18106. }
  18107. } );
  18108. }
  18109. };
  18110. function updateCamera( camera, parent ) {
  18111. if ( parent === null ) {
  18112. camera.matrixWorld.copy( camera.matrix );
  18113. } else {
  18114. camera.matrixWorld.multiplyMatrices( parent.matrixWorld, camera.matrix );
  18115. }
  18116. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  18117. }
  18118. this.setPoseTarget = function ( object ) {
  18119. if ( object !== undefined ) poseTarget = object;
  18120. };
  18121. this.getCamera = function ( camera ) {
  18122. if ( isPresenting() ) {
  18123. var parent = camera.parent;
  18124. var cameras = cameraVR.cameras;
  18125. var object = poseTarget || camera;
  18126. updateCamera( cameraVR, parent );
  18127. for ( var i = 0; i < cameras.length; i ++ ) {
  18128. updateCamera( cameras[ i ], parent );
  18129. }
  18130. // update camera and its children
  18131. object.matrixWorld.copy( cameraVR.matrixWorld );
  18132. var children = object.children;
  18133. for ( var i = 0, l = children.length; i < l; i ++ ) {
  18134. children[ i ].updateMatrixWorld( true );
  18135. }
  18136. setProjectionFromUnion( cameraVR, cameraL, cameraR );
  18137. return cameraVR;
  18138. }
  18139. return camera;
  18140. };
  18141. this.getCameraPose = function ( ) {
  18142. return pose;
  18143. };
  18144. this.isPresenting = isPresenting;
  18145. // Animation Loop
  18146. var onAnimationFrameCallback = null;
  18147. function onAnimationFrame( time, frame ) {
  18148. pose = frame.getDevicePose( frameOfReference );
  18149. if ( pose !== null ) {
  18150. var layer = session.baseLayer;
  18151. var views = frame.views;
  18152. for ( var i = 0; i < views.length; i ++ ) {
  18153. var view = views[ i ];
  18154. var viewport = layer.getViewport( view );
  18155. var viewMatrix = pose.getViewMatrix( view );
  18156. var camera = cameraVR.cameras[ i ];
  18157. camera.matrix.fromArray( viewMatrix ).getInverse( camera.matrix );
  18158. camera.projectionMatrix.fromArray( view.projectionMatrix );
  18159. camera.viewport.set( viewport.x, viewport.y, viewport.width, viewport.height );
  18160. if ( i === 0 ) {
  18161. cameraVR.matrix.copy( camera.matrix );
  18162. }
  18163. }
  18164. }
  18165. //
  18166. for ( var i = 0; i < controllers.length; i ++ ) {
  18167. var controller = controllers[ i ];
  18168. var inputSource = inputSources[ i ];
  18169. if ( inputSource ) {
  18170. var inputPose = frame.getInputPose( inputSource, frameOfReference );
  18171. if ( inputPose !== null ) {
  18172. if ( 'targetRay' in inputPose ) {
  18173. controller.matrix.elements = inputPose.targetRay.transformMatrix;
  18174. } else if ( 'pointerMatrix' in inputPose ) {
  18175. // DEPRECATED
  18176. controller.matrix.elements = inputPose.pointerMatrix;
  18177. }
  18178. controller.matrix.decompose( controller.position, controller.rotation, controller.scale );
  18179. controller.visible = true;
  18180. continue;
  18181. }
  18182. }
  18183. controller.visible = false;
  18184. }
  18185. if ( onAnimationFrameCallback ) onAnimationFrameCallback( time, frame );
  18186. }
  18187. var animation = new WebGLAnimation();
  18188. animation.setAnimationLoop( onAnimationFrame );
  18189. this.setAnimationLoop = function ( callback ) {
  18190. onAnimationFrameCallback = callback;
  18191. };
  18192. this.dispose = function () {};
  18193. // DEPRECATED
  18194. this.getStandingMatrix = function () {
  18195. console.warn( 'THREE.WebXRManager: getStandingMatrix() is no longer needed.' );
  18196. return new Matrix4();
  18197. };
  18198. this.submitFrame = function () {};
  18199. }
  18200. /**
  18201. * @author supereggbert / http://www.paulbrunt.co.uk/
  18202. * @author mrdoob / http://mrdoob.com/
  18203. * @author alteredq / http://alteredqualia.com/
  18204. * @author szimek / https://github.com/szimek/
  18205. * @author tschw
  18206. */
  18207. function WebGLRenderer( parameters ) {
  18208. console.log( 'THREE.WebGLRenderer', REVISION );
  18209. parameters = parameters || {};
  18210. var _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' ),
  18211. _context = parameters.context !== undefined ? parameters.context : null,
  18212. _alpha = parameters.alpha !== undefined ? parameters.alpha : false,
  18213. _depth = parameters.depth !== undefined ? parameters.depth : true,
  18214. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  18215. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  18216. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  18217. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
  18218. _powerPreference = parameters.powerPreference !== undefined ? parameters.powerPreference : 'default';
  18219. var currentRenderList = null;
  18220. var currentRenderState = null;
  18221. // public properties
  18222. this.domElement = _canvas;
  18223. this.context = null;
  18224. // clearing
  18225. this.autoClear = true;
  18226. this.autoClearColor = true;
  18227. this.autoClearDepth = true;
  18228. this.autoClearStencil = true;
  18229. // scene graph
  18230. this.sortObjects = true;
  18231. // user-defined clipping
  18232. this.clippingPlanes = [];
  18233. this.localClippingEnabled = false;
  18234. // physically based shading
  18235. this.gammaFactor = 2.0; // for backwards compatibility
  18236. this.gammaInput = false;
  18237. this.gammaOutput = false;
  18238. // physical lights
  18239. this.physicallyCorrectLights = false;
  18240. // tone mapping
  18241. this.toneMapping = LinearToneMapping;
  18242. this.toneMappingExposure = 1.0;
  18243. this.toneMappingWhitePoint = 1.0;
  18244. // morphs
  18245. this.maxMorphTargets = 8;
  18246. this.maxMorphNormals = 4;
  18247. // internal properties
  18248. var _this = this,
  18249. _isContextLost = false,
  18250. // internal state cache
  18251. _framebuffer = null,
  18252. _currentRenderTarget = null,
  18253. _currentFramebuffer = null,
  18254. _currentMaterialId = - 1,
  18255. // geometry and program caching
  18256. _currentGeometryProgram = {
  18257. geometry: null,
  18258. program: null,
  18259. wireframe: false
  18260. },
  18261. _currentCamera = null,
  18262. _currentArrayCamera = null,
  18263. _currentViewport = new Vector4(),
  18264. _currentScissor = new Vector4(),
  18265. _currentScissorTest = null,
  18266. //
  18267. _usedTextureUnits = 0,
  18268. //
  18269. _width = _canvas.width,
  18270. _height = _canvas.height,
  18271. _pixelRatio = 1,
  18272. _viewport = new Vector4( 0, 0, _width, _height ),
  18273. _scissor = new Vector4( 0, 0, _width, _height ),
  18274. _scissorTest = false,
  18275. // frustum
  18276. _frustum = new Frustum(),
  18277. // clipping
  18278. _clipping = new WebGLClipping(),
  18279. _clippingEnabled = false,
  18280. _localClippingEnabled = false,
  18281. // camera matrices cache
  18282. _projScreenMatrix = new Matrix4(),
  18283. _vector3 = new Vector3();
  18284. function getTargetPixelRatio() {
  18285. return _currentRenderTarget === null ? _pixelRatio : 1;
  18286. }
  18287. // initialize
  18288. var _gl;
  18289. try {
  18290. var contextAttributes = {
  18291. alpha: _alpha,
  18292. depth: _depth,
  18293. stencil: _stencil,
  18294. antialias: _antialias,
  18295. premultipliedAlpha: _premultipliedAlpha,
  18296. preserveDrawingBuffer: _preserveDrawingBuffer,
  18297. powerPreference: _powerPreference
  18298. };
  18299. // event listeners must be registered before WebGL context is created, see #12753
  18300. _canvas.addEventListener( 'webglcontextlost', onContextLost, false );
  18301. _canvas.addEventListener( 'webglcontextrestored', onContextRestore, false );
  18302. _gl = _context || _canvas.getContext( 'webgl', contextAttributes ) || _canvas.getContext( 'experimental-webgl', contextAttributes );
  18303. if ( _gl === null ) {
  18304. if ( _canvas.getContext( 'webgl' ) !== null ) {
  18305. throw new Error( 'Error creating WebGL context with your selected attributes.' );
  18306. } else {
  18307. throw new Error( 'Error creating WebGL context.' );
  18308. }
  18309. }
  18310. // Some experimental-webgl implementations do not have getShaderPrecisionFormat
  18311. if ( _gl.getShaderPrecisionFormat === undefined ) {
  18312. _gl.getShaderPrecisionFormat = function () {
  18313. return { 'rangeMin': 1, 'rangeMax': 1, 'precision': 1 };
  18314. };
  18315. }
  18316. } catch ( error ) {
  18317. console.error( 'THREE.WebGLRenderer: ' + error.message );
  18318. throw error;
  18319. }
  18320. var extensions, capabilities, state, info;
  18321. var properties, textures, attributes, geometries, objects;
  18322. var programCache, renderLists, renderStates;
  18323. var background, morphtargets, bufferRenderer, indexedBufferRenderer;
  18324. var utils;
  18325. function initGLContext() {
  18326. extensions = new WebGLExtensions( _gl );
  18327. capabilities = new WebGLCapabilities( _gl, extensions, parameters );
  18328. if ( ! capabilities.isWebGL2 ) {
  18329. extensions.get( 'WEBGL_depth_texture' );
  18330. extensions.get( 'OES_texture_float' );
  18331. extensions.get( 'OES_texture_half_float' );
  18332. extensions.get( 'OES_texture_half_float_linear' );
  18333. extensions.get( 'OES_standard_derivatives' );
  18334. extensions.get( 'OES_element_index_uint' );
  18335. extensions.get( 'ANGLE_instanced_arrays' );
  18336. }
  18337. extensions.get( 'OES_texture_float_linear' );
  18338. utils = new WebGLUtils( _gl, extensions, capabilities );
  18339. state = new WebGLState( _gl, extensions, utils, capabilities );
  18340. state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ) );
  18341. state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ) );
  18342. info = new WebGLInfo( _gl );
  18343. properties = new WebGLProperties();
  18344. textures = new WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info );
  18345. attributes = new WebGLAttributes( _gl );
  18346. geometries = new WebGLGeometries( _gl, attributes, info );
  18347. objects = new WebGLObjects( geometries, info );
  18348. morphtargets = new WebGLMorphtargets( _gl );
  18349. programCache = new WebGLPrograms( _this, extensions, capabilities );
  18350. renderLists = new WebGLRenderLists();
  18351. renderStates = new WebGLRenderStates();
  18352. background = new WebGLBackground( _this, state, objects, _premultipliedAlpha );
  18353. bufferRenderer = new WebGLBufferRenderer( _gl, extensions, info, capabilities );
  18354. indexedBufferRenderer = new WebGLIndexedBufferRenderer( _gl, extensions, info, capabilities );
  18355. info.programs = programCache.programs;
  18356. _this.context = _gl;
  18357. _this.capabilities = capabilities;
  18358. _this.extensions = extensions;
  18359. _this.properties = properties;
  18360. _this.renderLists = renderLists;
  18361. _this.state = state;
  18362. _this.info = info;
  18363. }
  18364. initGLContext();
  18365. // vr
  18366. var vr = null;
  18367. if ( typeof navigator !== 'undefined' ) {
  18368. vr = ( 'xr' in navigator ) ? new WebXRManager( _this ) : new WebVRManager( _this );
  18369. }
  18370. this.vr = vr;
  18371. // shadow map
  18372. var shadowMap = new WebGLShadowMap( _this, objects, capabilities.maxTextureSize );
  18373. this.shadowMap = shadowMap;
  18374. // API
  18375. this.getContext = function () {
  18376. return _gl;
  18377. };
  18378. this.getContextAttributes = function () {
  18379. return _gl.getContextAttributes();
  18380. };
  18381. this.forceContextLoss = function () {
  18382. var extension = extensions.get( 'WEBGL_lose_context' );
  18383. if ( extension ) extension.loseContext();
  18384. };
  18385. this.forceContextRestore = function () {
  18386. var extension = extensions.get( 'WEBGL_lose_context' );
  18387. if ( extension ) extension.restoreContext();
  18388. };
  18389. this.getPixelRatio = function () {
  18390. return _pixelRatio;
  18391. };
  18392. this.setPixelRatio = function ( value ) {
  18393. if ( value === undefined ) return;
  18394. _pixelRatio = value;
  18395. this.setSize( _width, _height, false );
  18396. };
  18397. this.getSize = function ( target ) {
  18398. if ( target === undefined ) {
  18399. console.warn( 'WebGLRenderer: .getsize() now requires a Vector2 as an argument' );
  18400. target = new Vector2();
  18401. }
  18402. return target.set( _width, _height );
  18403. };
  18404. this.setSize = function ( width, height, updateStyle ) {
  18405. if ( vr.isPresenting() ) {
  18406. console.warn( 'THREE.WebGLRenderer: Can\'t change size while VR device is presenting.' );
  18407. return;
  18408. }
  18409. _width = width;
  18410. _height = height;
  18411. _canvas.width = width * _pixelRatio;
  18412. _canvas.height = height * _pixelRatio;
  18413. if ( updateStyle !== false ) {
  18414. _canvas.style.width = width + 'px';
  18415. _canvas.style.height = height + 'px';
  18416. }
  18417. this.setViewport( 0, 0, width, height );
  18418. };
  18419. this.getDrawingBufferSize = function ( target ) {
  18420. if ( target === undefined ) {
  18421. console.warn( 'WebGLRenderer: .getdrawingBufferSize() now requires a Vector2 as an argument' );
  18422. target = new Vector2();
  18423. }
  18424. return target.set( _width * _pixelRatio, _height * _pixelRatio );
  18425. };
  18426. this.setDrawingBufferSize = function ( width, height, pixelRatio ) {
  18427. _width = width;
  18428. _height = height;
  18429. _pixelRatio = pixelRatio;
  18430. _canvas.width = width * pixelRatio;
  18431. _canvas.height = height * pixelRatio;
  18432. this.setViewport( 0, 0, width, height );
  18433. };
  18434. this.getCurrentViewport = function ( target ) {
  18435. if ( target === undefined ) {
  18436. console.warn( 'WebGLRenderer: .getCurrentViewport() now requires a Vector4 as an argument' );
  18437. target = new Vector4();
  18438. }
  18439. return target.copy( _currentViewport );
  18440. };
  18441. this.getViewport = function ( target ) {
  18442. return target.copy( _viewport );
  18443. };
  18444. this.setViewport = function ( x, y, width, height ) {
  18445. if ( x.isVector4 ) {
  18446. _viewport.set( x.x, x.y, x.z, x.w );
  18447. } else {
  18448. _viewport.set( x, y, width, height );
  18449. }
  18450. state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ) );
  18451. };
  18452. this.getScissor = function ( target ) {
  18453. return target.copy( _scissor );
  18454. };
  18455. this.setScissor = function ( x, y, width, height ) {
  18456. if ( x.isVector4 ) {
  18457. _scissor.set( x.x, x.y, x.z, x.w );
  18458. } else {
  18459. _scissor.set( x, y, width, height );
  18460. }
  18461. state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ) );
  18462. };
  18463. this.getScissorTest = function () {
  18464. return _scissorTest;
  18465. };
  18466. this.setScissorTest = function ( boolean ) {
  18467. state.setScissorTest( _scissorTest = boolean );
  18468. };
  18469. // Clearing
  18470. this.getClearColor = function () {
  18471. return background.getClearColor();
  18472. };
  18473. this.setClearColor = function () {
  18474. background.setClearColor.apply( background, arguments );
  18475. };
  18476. this.getClearAlpha = function () {
  18477. return background.getClearAlpha();
  18478. };
  18479. this.setClearAlpha = function () {
  18480. background.setClearAlpha.apply( background, arguments );
  18481. };
  18482. this.clear = function ( color, depth, stencil ) {
  18483. var bits = 0;
  18484. if ( color === undefined || color ) bits |= 16384;
  18485. if ( depth === undefined || depth ) bits |= 256;
  18486. if ( stencil === undefined || stencil ) bits |= 1024;
  18487. _gl.clear( bits );
  18488. };
  18489. this.clearColor = function () {
  18490. this.clear( true, false, false );
  18491. };
  18492. this.clearDepth = function () {
  18493. this.clear( false, true, false );
  18494. };
  18495. this.clearStencil = function () {
  18496. this.clear( false, false, true );
  18497. };
  18498. //
  18499. this.dispose = function () {
  18500. _canvas.removeEventListener( 'webglcontextlost', onContextLost, false );
  18501. _canvas.removeEventListener( 'webglcontextrestored', onContextRestore, false );
  18502. renderLists.dispose();
  18503. renderStates.dispose();
  18504. properties.dispose();
  18505. objects.dispose();
  18506. vr.dispose();
  18507. animation.stop();
  18508. };
  18509. // Events
  18510. function onContextLost( event ) {
  18511. event.preventDefault();
  18512. console.log( 'THREE.WebGLRenderer: Context Lost.' );
  18513. _isContextLost = true;
  18514. }
  18515. function onContextRestore( /* event */ ) {
  18516. console.log( 'THREE.WebGLRenderer: Context Restored.' );
  18517. _isContextLost = false;
  18518. initGLContext();
  18519. }
  18520. function onMaterialDispose( event ) {
  18521. var material = event.target;
  18522. material.removeEventListener( 'dispose', onMaterialDispose );
  18523. deallocateMaterial( material );
  18524. }
  18525. // Buffer deallocation
  18526. function deallocateMaterial( material ) {
  18527. releaseMaterialProgramReference( material );
  18528. properties.remove( material );
  18529. }
  18530. function releaseMaterialProgramReference( material ) {
  18531. var programInfo = properties.get( material ).program;
  18532. material.program = undefined;
  18533. if ( programInfo !== undefined ) {
  18534. programCache.releaseProgram( programInfo );
  18535. }
  18536. }
  18537. // Buffer rendering
  18538. function renderObjectImmediate( object, program ) {
  18539. object.render( function ( object ) {
  18540. _this.renderBufferImmediate( object, program );
  18541. } );
  18542. }
  18543. this.renderBufferImmediate = function ( object, program ) {
  18544. state.initAttributes();
  18545. var buffers = properties.get( object );
  18546. if ( object.hasPositions && ! buffers.position ) buffers.position = _gl.createBuffer();
  18547. if ( object.hasNormals && ! buffers.normal ) buffers.normal = _gl.createBuffer();
  18548. if ( object.hasUvs && ! buffers.uv ) buffers.uv = _gl.createBuffer();
  18549. if ( object.hasColors && ! buffers.color ) buffers.color = _gl.createBuffer();
  18550. var programAttributes = program.getAttributes();
  18551. if ( object.hasPositions ) {
  18552. _gl.bindBuffer( 34962, buffers.position );
  18553. _gl.bufferData( 34962, object.positionArray, 35048 );
  18554. state.enableAttribute( programAttributes.position );
  18555. _gl.vertexAttribPointer( programAttributes.position, 3, 5126, false, 0, 0 );
  18556. }
  18557. if ( object.hasNormals ) {
  18558. _gl.bindBuffer( 34962, buffers.normal );
  18559. _gl.bufferData( 34962, object.normalArray, 35048 );
  18560. state.enableAttribute( programAttributes.normal );
  18561. _gl.vertexAttribPointer( programAttributes.normal, 3, 5126, false, 0, 0 );
  18562. }
  18563. if ( object.hasUvs ) {
  18564. _gl.bindBuffer( 34962, buffers.uv );
  18565. _gl.bufferData( 34962, object.uvArray, 35048 );
  18566. state.enableAttribute( programAttributes.uv );
  18567. _gl.vertexAttribPointer( programAttributes.uv, 2, 5126, false, 0, 0 );
  18568. }
  18569. if ( object.hasColors ) {
  18570. _gl.bindBuffer( 34962, buffers.color );
  18571. _gl.bufferData( 34962, object.colorArray, 35048 );
  18572. state.enableAttribute( programAttributes.color );
  18573. _gl.vertexAttribPointer( programAttributes.color, 3, 5126, false, 0, 0 );
  18574. }
  18575. state.disableUnusedAttributes();
  18576. _gl.drawArrays( 4, 0, object.count );
  18577. object.count = 0;
  18578. };
  18579. this.renderBufferDirect = function ( camera, fog, geometry, material, object, group ) {
  18580. var frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  18581. state.setMaterial( material, frontFaceCW );
  18582. var program = setProgram( camera, fog, material, object );
  18583. var updateBuffers = false;
  18584. if ( _currentGeometryProgram.geometry !== geometry.id ||
  18585. _currentGeometryProgram.program !== program.id ||
  18586. _currentGeometryProgram.wireframe !== ( material.wireframe === true ) ) {
  18587. _currentGeometryProgram.geometry = geometry.id;
  18588. _currentGeometryProgram.program = program.id;
  18589. _currentGeometryProgram.wireframe = material.wireframe === true;
  18590. updateBuffers = true;
  18591. }
  18592. if ( object.morphTargetInfluences ) {
  18593. morphtargets.update( object, geometry, material, program );
  18594. updateBuffers = true;
  18595. }
  18596. //
  18597. var index = geometry.index;
  18598. var position = geometry.attributes.position;
  18599. var rangeFactor = 1;
  18600. if ( material.wireframe === true ) {
  18601. index = geometries.getWireframeAttribute( geometry );
  18602. rangeFactor = 2;
  18603. }
  18604. var attribute;
  18605. var renderer = bufferRenderer;
  18606. if ( index !== null ) {
  18607. attribute = attributes.get( index );
  18608. renderer = indexedBufferRenderer;
  18609. renderer.setIndex( attribute );
  18610. }
  18611. if ( updateBuffers ) {
  18612. setupVertexAttributes( material, program, geometry );
  18613. if ( index !== null ) {
  18614. _gl.bindBuffer( 34963, attribute.buffer );
  18615. }
  18616. }
  18617. //
  18618. var dataCount = Infinity;
  18619. if ( index !== null ) {
  18620. dataCount = index.count;
  18621. } else if ( position !== undefined ) {
  18622. dataCount = position.count;
  18623. }
  18624. var rangeStart = geometry.drawRange.start * rangeFactor;
  18625. var rangeCount = geometry.drawRange.count * rangeFactor;
  18626. var groupStart = group !== null ? group.start * rangeFactor : 0;
  18627. var groupCount = group !== null ? group.count * rangeFactor : Infinity;
  18628. var drawStart = Math.max( rangeStart, groupStart );
  18629. var drawEnd = Math.min( dataCount, rangeStart + rangeCount, groupStart + groupCount ) - 1;
  18630. var drawCount = Math.max( 0, drawEnd - drawStart + 1 );
  18631. if ( drawCount === 0 ) return;
  18632. //
  18633. if ( object.isMesh ) {
  18634. if ( material.wireframe === true ) {
  18635. state.setLineWidth( material.wireframeLinewidth * getTargetPixelRatio() );
  18636. renderer.setMode( 1 );
  18637. } else {
  18638. switch ( object.drawMode ) {
  18639. case TrianglesDrawMode:
  18640. renderer.setMode( 4 );
  18641. break;
  18642. case TriangleStripDrawMode:
  18643. renderer.setMode( 5 );
  18644. break;
  18645. case TriangleFanDrawMode:
  18646. renderer.setMode( 6 );
  18647. break;
  18648. }
  18649. }
  18650. } else if ( object.isLine ) {
  18651. var lineWidth = material.linewidth;
  18652. if ( lineWidth === undefined ) lineWidth = 1; // Not using Line*Material
  18653. state.setLineWidth( lineWidth * getTargetPixelRatio() );
  18654. if ( object.isLineSegments ) {
  18655. renderer.setMode( 1 );
  18656. } else if ( object.isLineLoop ) {
  18657. renderer.setMode( 2 );
  18658. } else {
  18659. renderer.setMode( 3 );
  18660. }
  18661. } else if ( object.isPoints ) {
  18662. renderer.setMode( 0 );
  18663. } else if ( object.isSprite ) {
  18664. renderer.setMode( 4 );
  18665. }
  18666. if ( geometry && geometry.isInstancedBufferGeometry ) {
  18667. if ( geometry.maxInstancedCount > 0 ) {
  18668. renderer.renderInstances( geometry, drawStart, drawCount );
  18669. }
  18670. } else {
  18671. renderer.render( drawStart, drawCount );
  18672. }
  18673. };
  18674. function setupVertexAttributes( material, program, geometry ) {
  18675. if ( geometry && geometry.isInstancedBufferGeometry && ! capabilities.isWebGL2 ) {
  18676. if ( extensions.get( 'ANGLE_instanced_arrays' ) === null ) {
  18677. console.error( 'THREE.WebGLRenderer.setupVertexAttributes: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  18678. return;
  18679. }
  18680. }
  18681. state.initAttributes();
  18682. var geometryAttributes = geometry.attributes;
  18683. var programAttributes = program.getAttributes();
  18684. var materialDefaultAttributeValues = material.defaultAttributeValues;
  18685. for ( var name in programAttributes ) {
  18686. var programAttribute = programAttributes[ name ];
  18687. if ( programAttribute >= 0 ) {
  18688. var geometryAttribute = geometryAttributes[ name ];
  18689. if ( geometryAttribute !== undefined ) {
  18690. var normalized = geometryAttribute.normalized;
  18691. var size = geometryAttribute.itemSize;
  18692. var attribute = attributes.get( geometryAttribute );
  18693. // TODO Attribute may not be available on context restore
  18694. if ( attribute === undefined ) continue;
  18695. var buffer = attribute.buffer;
  18696. var type = attribute.type;
  18697. var bytesPerElement = attribute.bytesPerElement;
  18698. if ( geometryAttribute.isInterleavedBufferAttribute ) {
  18699. var data = geometryAttribute.data;
  18700. var stride = data.stride;
  18701. var offset = geometryAttribute.offset;
  18702. if ( data && data.isInstancedInterleavedBuffer ) {
  18703. state.enableAttributeAndDivisor( programAttribute, data.meshPerAttribute );
  18704. if ( geometry.maxInstancedCount === undefined ) {
  18705. geometry.maxInstancedCount = data.meshPerAttribute * data.count;
  18706. }
  18707. } else {
  18708. state.enableAttribute( programAttribute );
  18709. }
  18710. _gl.bindBuffer( 34962, buffer );
  18711. _gl.vertexAttribPointer( programAttribute, size, type, normalized, stride * bytesPerElement, offset * bytesPerElement );
  18712. } else {
  18713. if ( geometryAttribute.isInstancedBufferAttribute ) {
  18714. state.enableAttributeAndDivisor( programAttribute, geometryAttribute.meshPerAttribute );
  18715. if ( geometry.maxInstancedCount === undefined ) {
  18716. geometry.maxInstancedCount = geometryAttribute.meshPerAttribute * geometryAttribute.count;
  18717. }
  18718. } else {
  18719. state.enableAttribute( programAttribute );
  18720. }
  18721. _gl.bindBuffer( 34962, buffer );
  18722. _gl.vertexAttribPointer( programAttribute, size, type, normalized, 0, 0 );
  18723. }
  18724. } else if ( materialDefaultAttributeValues !== undefined ) {
  18725. var value = materialDefaultAttributeValues[ name ];
  18726. if ( value !== undefined ) {
  18727. switch ( value.length ) {
  18728. case 2:
  18729. _gl.vertexAttrib2fv( programAttribute, value );
  18730. break;
  18731. case 3:
  18732. _gl.vertexAttrib3fv( programAttribute, value );
  18733. break;
  18734. case 4:
  18735. _gl.vertexAttrib4fv( programAttribute, value );
  18736. break;
  18737. default:
  18738. _gl.vertexAttrib1fv( programAttribute, value );
  18739. }
  18740. }
  18741. }
  18742. }
  18743. }
  18744. state.disableUnusedAttributes();
  18745. }
  18746. // Compile
  18747. this.compile = function ( scene, camera ) {
  18748. currentRenderState = renderStates.get( scene, camera );
  18749. currentRenderState.init();
  18750. scene.traverse( function ( object ) {
  18751. if ( object.isLight ) {
  18752. currentRenderState.pushLight( object );
  18753. if ( object.castShadow ) {
  18754. currentRenderState.pushShadow( object );
  18755. }
  18756. }
  18757. } );
  18758. currentRenderState.setupLights( camera );
  18759. scene.traverse( function ( object ) {
  18760. if ( object.material ) {
  18761. if ( Array.isArray( object.material ) ) {
  18762. for ( var i = 0; i < object.material.length; i ++ ) {
  18763. initMaterial( object.material[ i ], scene.fog, object );
  18764. }
  18765. } else {
  18766. initMaterial( object.material, scene.fog, object );
  18767. }
  18768. }
  18769. } );
  18770. };
  18771. // Animation Loop
  18772. var onAnimationFrameCallback = null;
  18773. function onAnimationFrame( time ) {
  18774. if ( vr.isPresenting() ) return;
  18775. if ( onAnimationFrameCallback ) onAnimationFrameCallback( time );
  18776. }
  18777. var animation = new WebGLAnimation();
  18778. animation.setAnimationLoop( onAnimationFrame );
  18779. if ( typeof window !== 'undefined' ) animation.setContext( window );
  18780. this.setAnimationLoop = function ( callback ) {
  18781. onAnimationFrameCallback = callback;
  18782. vr.setAnimationLoop( callback );
  18783. animation.start();
  18784. };
  18785. // Rendering
  18786. this.render = function ( scene, camera ) {
  18787. var renderTarget, forceClear;
  18788. if ( arguments[ 2 ] !== undefined ) {
  18789. console.warn( 'THREE.WebGLRenderer.render(): the renderTarget argument has been removed. Use .setRenderTarget() instead.' );
  18790. renderTarget = arguments[ 2 ];
  18791. }
  18792. if ( arguments[ 3 ] !== undefined ) {
  18793. console.warn( 'THREE.WebGLRenderer.render(): the forceClear argument has been removed. Use .clear() instead.' );
  18794. forceClear = arguments[ 3 ];
  18795. }
  18796. if ( ! ( camera && camera.isCamera ) ) {
  18797. console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  18798. return;
  18799. }
  18800. if ( _isContextLost ) return;
  18801. // reset caching for this frame
  18802. _currentGeometryProgram.geometry = null;
  18803. _currentGeometryProgram.program = null;
  18804. _currentGeometryProgram.wireframe = false;
  18805. _currentMaterialId = - 1;
  18806. _currentCamera = null;
  18807. // update scene graph
  18808. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  18809. // update camera matrices and frustum
  18810. if ( camera.parent === null ) camera.updateMatrixWorld();
  18811. if ( vr.enabled ) {
  18812. camera = vr.getCamera( camera );
  18813. }
  18814. //
  18815. currentRenderState = renderStates.get( scene, camera );
  18816. currentRenderState.init();
  18817. scene.onBeforeRender( _this, scene, camera, renderTarget || _currentRenderTarget );
  18818. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  18819. _frustum.setFromMatrix( _projScreenMatrix );
  18820. _localClippingEnabled = this.localClippingEnabled;
  18821. _clippingEnabled = _clipping.init( this.clippingPlanes, _localClippingEnabled, camera );
  18822. currentRenderList = renderLists.get( scene, camera );
  18823. currentRenderList.init();
  18824. projectObject( scene, camera, 0, _this.sortObjects );
  18825. if ( _this.sortObjects === true ) {
  18826. currentRenderList.sort();
  18827. }
  18828. //
  18829. if ( _clippingEnabled ) _clipping.beginShadows();
  18830. var shadowsArray = currentRenderState.state.shadowsArray;
  18831. shadowMap.render( shadowsArray, scene, camera );
  18832. currentRenderState.setupLights( camera );
  18833. if ( _clippingEnabled ) _clipping.endShadows();
  18834. //
  18835. if ( this.info.autoReset ) this.info.reset();
  18836. if ( renderTarget !== undefined ) {
  18837. this.setRenderTarget( renderTarget );
  18838. }
  18839. //
  18840. background.render( currentRenderList, scene, camera, forceClear );
  18841. // render scene
  18842. var opaqueObjects = currentRenderList.opaque;
  18843. var transparentObjects = currentRenderList.transparent;
  18844. if ( scene.overrideMaterial ) {
  18845. var overrideMaterial = scene.overrideMaterial;
  18846. if ( opaqueObjects.length ) renderObjects( opaqueObjects, scene, camera, overrideMaterial );
  18847. if ( transparentObjects.length ) renderObjects( transparentObjects, scene, camera, overrideMaterial );
  18848. } else {
  18849. // opaque pass (front-to-back order)
  18850. if ( opaqueObjects.length ) renderObjects( opaqueObjects, scene, camera );
  18851. // transparent pass (back-to-front order)
  18852. if ( transparentObjects.length ) renderObjects( transparentObjects, scene, camera );
  18853. }
  18854. //
  18855. scene.onAfterRender( _this, scene, camera );
  18856. //
  18857. if ( _currentRenderTarget !== null ) {
  18858. // Generate mipmap if we're using any kind of mipmap filtering
  18859. textures.updateRenderTargetMipmap( _currentRenderTarget );
  18860. // resolve multisample renderbuffers to a single-sample texture if necessary
  18861. textures.updateMultisampleRenderTarget( _currentRenderTarget );
  18862. }
  18863. // Ensure depth buffer writing is enabled so it can be cleared on next render
  18864. state.buffers.depth.setTest( true );
  18865. state.buffers.depth.setMask( true );
  18866. state.buffers.color.setMask( true );
  18867. state.setPolygonOffset( false );
  18868. if ( vr.enabled ) {
  18869. vr.submitFrame();
  18870. }
  18871. // _gl.finish();
  18872. currentRenderList = null;
  18873. currentRenderState = null;
  18874. };
  18875. function projectObject( object, camera, groupOrder, sortObjects ) {
  18876. if ( object.visible === false ) return;
  18877. var visible = object.layers.test( camera.layers );
  18878. if ( visible ) {
  18879. if ( object.isGroup ) {
  18880. groupOrder = object.renderOrder;
  18881. } else if ( object.isLight ) {
  18882. currentRenderState.pushLight( object );
  18883. if ( object.castShadow ) {
  18884. currentRenderState.pushShadow( object );
  18885. }
  18886. } else if ( object.isSprite ) {
  18887. if ( ! object.frustumCulled || _frustum.intersectsSprite( object ) ) {
  18888. if ( sortObjects ) {
  18889. _vector3.setFromMatrixPosition( object.matrixWorld )
  18890. .applyMatrix4( _projScreenMatrix );
  18891. }
  18892. var geometry = objects.update( object );
  18893. var material = object.material;
  18894. if ( material.visible ) {
  18895. currentRenderList.push( object, geometry, material, groupOrder, _vector3.z, null );
  18896. }
  18897. }
  18898. } else if ( object.isImmediateRenderObject ) {
  18899. if ( sortObjects ) {
  18900. _vector3.setFromMatrixPosition( object.matrixWorld )
  18901. .applyMatrix4( _projScreenMatrix );
  18902. }
  18903. currentRenderList.push( object, null, object.material, groupOrder, _vector3.z, null );
  18904. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  18905. if ( object.isSkinnedMesh ) {
  18906. object.skeleton.update();
  18907. }
  18908. if ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) {
  18909. if ( sortObjects ) {
  18910. _vector3.setFromMatrixPosition( object.matrixWorld )
  18911. .applyMatrix4( _projScreenMatrix );
  18912. }
  18913. var geometry = objects.update( object );
  18914. var material = object.material;
  18915. if ( Array.isArray( material ) ) {
  18916. var groups = geometry.groups;
  18917. for ( var i = 0, l = groups.length; i < l; i ++ ) {
  18918. var group = groups[ i ];
  18919. var groupMaterial = material[ group.materialIndex ];
  18920. if ( groupMaterial && groupMaterial.visible ) {
  18921. currentRenderList.push( object, geometry, groupMaterial, groupOrder, _vector3.z, group );
  18922. }
  18923. }
  18924. } else if ( material.visible ) {
  18925. currentRenderList.push( object, geometry, material, groupOrder, _vector3.z, null );
  18926. }
  18927. }
  18928. }
  18929. }
  18930. var children = object.children;
  18931. for ( var i = 0, l = children.length; i < l; i ++ ) {
  18932. projectObject( children[ i ], camera, groupOrder, sortObjects );
  18933. }
  18934. }
  18935. function renderObjects( renderList, scene, camera, overrideMaterial ) {
  18936. for ( var i = 0, l = renderList.length; i < l; i ++ ) {
  18937. var renderItem = renderList[ i ];
  18938. var object = renderItem.object;
  18939. var geometry = renderItem.geometry;
  18940. var material = overrideMaterial === undefined ? renderItem.material : overrideMaterial;
  18941. var group = renderItem.group;
  18942. if ( camera.isArrayCamera ) {
  18943. _currentArrayCamera = camera;
  18944. var cameras = camera.cameras;
  18945. for ( var j = 0, jl = cameras.length; j < jl; j ++ ) {
  18946. var camera2 = cameras[ j ];
  18947. if ( object.layers.test( camera2.layers ) ) {
  18948. if ( 'viewport' in camera2 ) { // XR
  18949. state.viewport( _currentViewport.copy( camera2.viewport ) );
  18950. } else {
  18951. var bounds = camera2.bounds;
  18952. var x = bounds.x * _width;
  18953. var y = bounds.y * _height;
  18954. var width = bounds.z * _width;
  18955. var height = bounds.w * _height;
  18956. state.viewport( _currentViewport.set( x, y, width, height ).multiplyScalar( _pixelRatio ) );
  18957. }
  18958. currentRenderState.setupLights( camera2 );
  18959. renderObject( object, scene, camera2, geometry, material, group );
  18960. }
  18961. }
  18962. } else {
  18963. _currentArrayCamera = null;
  18964. renderObject( object, scene, camera, geometry, material, group );
  18965. }
  18966. }
  18967. }
  18968. function renderObject( object, scene, camera, geometry, material, group ) {
  18969. object.onBeforeRender( _this, scene, camera, geometry, material, group );
  18970. currentRenderState = renderStates.get( scene, _currentArrayCamera || camera );
  18971. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  18972. object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  18973. if ( object.isImmediateRenderObject ) {
  18974. state.setMaterial( material );
  18975. var program = setProgram( camera, scene.fog, material, object );
  18976. _currentGeometryProgram.geometry = null;
  18977. _currentGeometryProgram.program = null;
  18978. _currentGeometryProgram.wireframe = false;
  18979. renderObjectImmediate( object, program );
  18980. } else {
  18981. _this.renderBufferDirect( camera, scene.fog, geometry, material, object, group );
  18982. }
  18983. object.onAfterRender( _this, scene, camera, geometry, material, group );
  18984. currentRenderState = renderStates.get( scene, _currentArrayCamera || camera );
  18985. }
  18986. function initMaterial( material, fog, object ) {
  18987. var materialProperties = properties.get( material );
  18988. var lights = currentRenderState.state.lights;
  18989. var shadowsArray = currentRenderState.state.shadowsArray;
  18990. var lightsHash = materialProperties.lightsHash;
  18991. var lightsStateHash = lights.state.hash;
  18992. var parameters = programCache.getParameters(
  18993. material, lights.state, shadowsArray, fog, _clipping.numPlanes, _clipping.numIntersection, object );
  18994. var code = programCache.getProgramCode( material, parameters );
  18995. var program = materialProperties.program;
  18996. var programChange = true;
  18997. if ( program === undefined ) {
  18998. // new material
  18999. material.addEventListener( 'dispose', onMaterialDispose );
  19000. } else if ( program.code !== code ) {
  19001. // changed glsl or parameters
  19002. releaseMaterialProgramReference( material );
  19003. } else if ( lightsHash.stateID !== lightsStateHash.stateID ||
  19004. lightsHash.directionalLength !== lightsStateHash.directionalLength ||
  19005. lightsHash.pointLength !== lightsStateHash.pointLength ||
  19006. lightsHash.spotLength !== lightsStateHash.spotLength ||
  19007. lightsHash.rectAreaLength !== lightsStateHash.rectAreaLength ||
  19008. lightsHash.hemiLength !== lightsStateHash.hemiLength ||
  19009. lightsHash.shadowsLength !== lightsStateHash.shadowsLength ) {
  19010. lightsHash.stateID = lightsStateHash.stateID;
  19011. lightsHash.directionalLength = lightsStateHash.directionalLength;
  19012. lightsHash.pointLength = lightsStateHash.pointLength;
  19013. lightsHash.spotLength = lightsStateHash.spotLength;
  19014. lightsHash.rectAreaLength = lightsStateHash.rectAreaLength;
  19015. lightsHash.hemiLength = lightsStateHash.hemiLength;
  19016. lightsHash.shadowsLength = lightsStateHash.shadowsLength;
  19017. programChange = false;
  19018. } else if ( parameters.shaderID !== undefined ) {
  19019. // same glsl and uniform list
  19020. return;
  19021. } else {
  19022. // only rebuild uniform list
  19023. programChange = false;
  19024. }
  19025. if ( programChange ) {
  19026. if ( parameters.shaderID ) {
  19027. var shader = ShaderLib[ parameters.shaderID ];
  19028. materialProperties.shader = {
  19029. name: material.type,
  19030. uniforms: cloneUniforms( shader.uniforms ),
  19031. vertexShader: shader.vertexShader,
  19032. fragmentShader: shader.fragmentShader
  19033. };
  19034. } else {
  19035. materialProperties.shader = {
  19036. name: material.type,
  19037. uniforms: material.uniforms,
  19038. vertexShader: material.vertexShader,
  19039. fragmentShader: material.fragmentShader
  19040. };
  19041. }
  19042. material.onBeforeCompile( materialProperties.shader, _this );
  19043. // Computing code again as onBeforeCompile may have changed the shaders
  19044. code = programCache.getProgramCode( material, parameters );
  19045. program = programCache.acquireProgram( material, materialProperties.shader, parameters, code );
  19046. materialProperties.program = program;
  19047. material.program = program;
  19048. }
  19049. var programAttributes = program.getAttributes();
  19050. if ( material.morphTargets ) {
  19051. material.numSupportedMorphTargets = 0;
  19052. for ( var i = 0; i < _this.maxMorphTargets; i ++ ) {
  19053. if ( programAttributes[ 'morphTarget' + i ] >= 0 ) {
  19054. material.numSupportedMorphTargets ++;
  19055. }
  19056. }
  19057. }
  19058. if ( material.morphNormals ) {
  19059. material.numSupportedMorphNormals = 0;
  19060. for ( var i = 0; i < _this.maxMorphNormals; i ++ ) {
  19061. if ( programAttributes[ 'morphNormal' + i ] >= 0 ) {
  19062. material.numSupportedMorphNormals ++;
  19063. }
  19064. }
  19065. }
  19066. var uniforms = materialProperties.shader.uniforms;
  19067. if ( ! material.isShaderMaterial &&
  19068. ! material.isRawShaderMaterial ||
  19069. material.clipping === true ) {
  19070. materialProperties.numClippingPlanes = _clipping.numPlanes;
  19071. materialProperties.numIntersection = _clipping.numIntersection;
  19072. uniforms.clippingPlanes = _clipping.uniform;
  19073. }
  19074. materialProperties.fog = fog;
  19075. // store the light setup it was created for
  19076. if ( lightsHash === undefined ) {
  19077. materialProperties.lightsHash = lightsHash = {};
  19078. }
  19079. lightsHash.stateID = lightsStateHash.stateID;
  19080. lightsHash.directionalLength = lightsStateHash.directionalLength;
  19081. lightsHash.pointLength = lightsStateHash.pointLength;
  19082. lightsHash.spotLength = lightsStateHash.spotLength;
  19083. lightsHash.rectAreaLength = lightsStateHash.rectAreaLength;
  19084. lightsHash.hemiLength = lightsStateHash.hemiLength;
  19085. lightsHash.shadowsLength = lightsStateHash.shadowsLength;
  19086. if ( material.lights ) {
  19087. // wire up the material to this renderer's lighting state
  19088. uniforms.ambientLightColor.value = lights.state.ambient;
  19089. uniforms.directionalLights.value = lights.state.directional;
  19090. uniforms.spotLights.value = lights.state.spot;
  19091. uniforms.rectAreaLights.value = lights.state.rectArea;
  19092. uniforms.pointLights.value = lights.state.point;
  19093. uniforms.hemisphereLights.value = lights.state.hemi;
  19094. uniforms.directionalShadowMap.value = lights.state.directionalShadowMap;
  19095. uniforms.directionalShadowMatrix.value = lights.state.directionalShadowMatrix;
  19096. uniforms.spotShadowMap.value = lights.state.spotShadowMap;
  19097. uniforms.spotShadowMatrix.value = lights.state.spotShadowMatrix;
  19098. uniforms.pointShadowMap.value = lights.state.pointShadowMap;
  19099. uniforms.pointShadowMatrix.value = lights.state.pointShadowMatrix;
  19100. // TODO (abelnation): add area lights shadow info to uniforms
  19101. }
  19102. var progUniforms = materialProperties.program.getUniforms(),
  19103. uniformsList =
  19104. WebGLUniforms.seqWithValue( progUniforms.seq, uniforms );
  19105. materialProperties.uniformsList = uniformsList;
  19106. }
  19107. function setProgram( camera, fog, material, object ) {
  19108. _usedTextureUnits = 0;
  19109. var materialProperties = properties.get( material );
  19110. var lights = currentRenderState.state.lights;
  19111. var lightsHash = materialProperties.lightsHash;
  19112. var lightsStateHash = lights.state.hash;
  19113. if ( _clippingEnabled ) {
  19114. if ( _localClippingEnabled || camera !== _currentCamera ) {
  19115. var useCache =
  19116. camera === _currentCamera &&
  19117. material.id === _currentMaterialId;
  19118. // we might want to call this function with some ClippingGroup
  19119. // object instead of the material, once it becomes feasible
  19120. // (#8465, #8379)
  19121. _clipping.setState(
  19122. material.clippingPlanes, material.clipIntersection, material.clipShadows,
  19123. camera, materialProperties, useCache );
  19124. }
  19125. }
  19126. if ( material.needsUpdate === false ) {
  19127. if ( materialProperties.program === undefined ) {
  19128. material.needsUpdate = true;
  19129. } else if ( material.fog && materialProperties.fog !== fog ) {
  19130. material.needsUpdate = true;
  19131. } else if ( material.lights && ( lightsHash.stateID !== lightsStateHash.stateID ||
  19132. lightsHash.directionalLength !== lightsStateHash.directionalLength ||
  19133. lightsHash.pointLength !== lightsStateHash.pointLength ||
  19134. lightsHash.spotLength !== lightsStateHash.spotLength ||
  19135. lightsHash.rectAreaLength !== lightsStateHash.rectAreaLength ||
  19136. lightsHash.hemiLength !== lightsStateHash.hemiLength ||
  19137. lightsHash.shadowsLength !== lightsStateHash.shadowsLength ) ) {
  19138. material.needsUpdate = true;
  19139. } else if ( materialProperties.numClippingPlanes !== undefined &&
  19140. ( materialProperties.numClippingPlanes !== _clipping.numPlanes ||
  19141. materialProperties.numIntersection !== _clipping.numIntersection ) ) {
  19142. material.needsUpdate = true;
  19143. }
  19144. }
  19145. if ( material.needsUpdate ) {
  19146. initMaterial( material, fog, object );
  19147. material.needsUpdate = false;
  19148. }
  19149. var refreshProgram = false;
  19150. var refreshMaterial = false;
  19151. var refreshLights = false;
  19152. var program = materialProperties.program,
  19153. p_uniforms = program.getUniforms(),
  19154. m_uniforms = materialProperties.shader.uniforms;
  19155. if ( state.useProgram( program.program ) ) {
  19156. refreshProgram = true;
  19157. refreshMaterial = true;
  19158. refreshLights = true;
  19159. }
  19160. if ( material.id !== _currentMaterialId ) {
  19161. _currentMaterialId = material.id;
  19162. refreshMaterial = true;
  19163. }
  19164. if ( refreshProgram || _currentCamera !== camera ) {
  19165. p_uniforms.setValue( _gl, 'projectionMatrix', camera.projectionMatrix );
  19166. if ( capabilities.logarithmicDepthBuffer ) {
  19167. p_uniforms.setValue( _gl, 'logDepthBufFC',
  19168. 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) );
  19169. }
  19170. if ( _currentCamera !== camera ) {
  19171. _currentCamera = camera;
  19172. // lighting uniforms depend on the camera so enforce an update
  19173. // now, in case this material supports lights - or later, when
  19174. // the next material that does gets activated:
  19175. refreshMaterial = true; // set to true on material change
  19176. refreshLights = true; // remains set until update done
  19177. }
  19178. // load material specific uniforms
  19179. // (shader material also gets them for the sake of genericity)
  19180. if ( material.isShaderMaterial ||
  19181. material.isMeshPhongMaterial ||
  19182. material.isMeshStandardMaterial ||
  19183. material.envMap ) {
  19184. var uCamPos = p_uniforms.map.cameraPosition;
  19185. if ( uCamPos !== undefined ) {
  19186. uCamPos.setValue( _gl,
  19187. _vector3.setFromMatrixPosition( camera.matrixWorld ) );
  19188. }
  19189. }
  19190. if ( material.isMeshPhongMaterial ||
  19191. material.isMeshLambertMaterial ||
  19192. material.isMeshBasicMaterial ||
  19193. material.isMeshStandardMaterial ||
  19194. material.isShaderMaterial ||
  19195. material.skinning ) {
  19196. p_uniforms.setValue( _gl, 'viewMatrix', camera.matrixWorldInverse );
  19197. }
  19198. }
  19199. // skinning uniforms must be set even if material didn't change
  19200. // auto-setting of texture unit for bone texture must go before other textures
  19201. // not sure why, but otherwise weird things happen
  19202. if ( material.skinning ) {
  19203. p_uniforms.setOptional( _gl, object, 'bindMatrix' );
  19204. p_uniforms.setOptional( _gl, object, 'bindMatrixInverse' );
  19205. var skeleton = object.skeleton;
  19206. if ( skeleton ) {
  19207. var bones = skeleton.bones;
  19208. if ( capabilities.floatVertexTextures ) {
  19209. if ( skeleton.boneTexture === undefined ) {
  19210. // layout (1 matrix = 4 pixels)
  19211. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  19212. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  19213. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  19214. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  19215. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  19216. var size = Math.sqrt( bones.length * 4 ); // 4 pixels needed for 1 matrix
  19217. size = _Math.ceilPowerOfTwo( size );
  19218. size = Math.max( size, 4 );
  19219. var boneMatrices = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  19220. boneMatrices.set( skeleton.boneMatrices ); // copy current values
  19221. var boneTexture = new DataTexture( boneMatrices, size, size, RGBAFormat, FloatType );
  19222. boneTexture.needsUpdate = true;
  19223. skeleton.boneMatrices = boneMatrices;
  19224. skeleton.boneTexture = boneTexture;
  19225. skeleton.boneTextureSize = size;
  19226. }
  19227. p_uniforms.setValue( _gl, 'boneTexture', skeleton.boneTexture );
  19228. p_uniforms.setValue( _gl, 'boneTextureSize', skeleton.boneTextureSize );
  19229. } else {
  19230. p_uniforms.setOptional( _gl, skeleton, 'boneMatrices' );
  19231. }
  19232. }
  19233. }
  19234. if ( refreshMaterial ) {
  19235. p_uniforms.setValue( _gl, 'toneMappingExposure', _this.toneMappingExposure );
  19236. p_uniforms.setValue( _gl, 'toneMappingWhitePoint', _this.toneMappingWhitePoint );
  19237. if ( material.lights ) {
  19238. // the current material requires lighting info
  19239. // note: all lighting uniforms are always set correctly
  19240. // they simply reference the renderer's state for their
  19241. // values
  19242. //
  19243. // use the current material's .needsUpdate flags to set
  19244. // the GL state when required
  19245. markUniformsLightsNeedsUpdate( m_uniforms, refreshLights );
  19246. }
  19247. // refresh uniforms common to several materials
  19248. if ( fog && material.fog ) {
  19249. refreshUniformsFog( m_uniforms, fog );
  19250. }
  19251. if ( material.isMeshBasicMaterial ) {
  19252. refreshUniformsCommon( m_uniforms, material );
  19253. } else if ( material.isMeshLambertMaterial ) {
  19254. refreshUniformsCommon( m_uniforms, material );
  19255. refreshUniformsLambert( m_uniforms, material );
  19256. } else if ( material.isMeshPhongMaterial ) {
  19257. refreshUniformsCommon( m_uniforms, material );
  19258. if ( material.isMeshToonMaterial ) {
  19259. refreshUniformsToon( m_uniforms, material );
  19260. } else {
  19261. refreshUniformsPhong( m_uniforms, material );
  19262. }
  19263. } else if ( material.isMeshStandardMaterial ) {
  19264. refreshUniformsCommon( m_uniforms, material );
  19265. if ( material.isMeshPhysicalMaterial ) {
  19266. refreshUniformsPhysical( m_uniforms, material );
  19267. } else {
  19268. refreshUniformsStandard( m_uniforms, material );
  19269. }
  19270. } else if ( material.isMeshMatcapMaterial ) {
  19271. refreshUniformsCommon( m_uniforms, material );
  19272. refreshUniformsMatcap( m_uniforms, material );
  19273. } else if ( material.isMeshDepthMaterial ) {
  19274. refreshUniformsCommon( m_uniforms, material );
  19275. refreshUniformsDepth( m_uniforms, material );
  19276. } else if ( material.isMeshDistanceMaterial ) {
  19277. refreshUniformsCommon( m_uniforms, material );
  19278. refreshUniformsDistance( m_uniforms, material );
  19279. } else if ( material.isMeshNormalMaterial ) {
  19280. refreshUniformsCommon( m_uniforms, material );
  19281. refreshUniformsNormal( m_uniforms, material );
  19282. } else if ( material.isLineBasicMaterial ) {
  19283. refreshUniformsLine( m_uniforms, material );
  19284. if ( material.isLineDashedMaterial ) {
  19285. refreshUniformsDash( m_uniforms, material );
  19286. }
  19287. } else if ( material.isPointsMaterial ) {
  19288. refreshUniformsPoints( m_uniforms, material );
  19289. } else if ( material.isSpriteMaterial ) {
  19290. refreshUniformsSprites( m_uniforms, material );
  19291. } else if ( material.isShadowMaterial ) {
  19292. m_uniforms.color.value = material.color;
  19293. m_uniforms.opacity.value = material.opacity;
  19294. }
  19295. // RectAreaLight Texture
  19296. // TODO (mrdoob): Find a nicer implementation
  19297. if ( m_uniforms.ltc_1 !== undefined ) m_uniforms.ltc_1.value = UniformsLib.LTC_1;
  19298. if ( m_uniforms.ltc_2 !== undefined ) m_uniforms.ltc_2.value = UniformsLib.LTC_2;
  19299. WebGLUniforms.upload( _gl, materialProperties.uniformsList, m_uniforms, _this );
  19300. }
  19301. if ( material.isShaderMaterial && material.uniformsNeedUpdate === true ) {
  19302. WebGLUniforms.upload( _gl, materialProperties.uniformsList, m_uniforms, _this );
  19303. material.uniformsNeedUpdate = false;
  19304. }
  19305. if ( material.isSpriteMaterial ) {
  19306. p_uniforms.setValue( _gl, 'center', object.center );
  19307. }
  19308. // common matrices
  19309. p_uniforms.setValue( _gl, 'modelViewMatrix', object.modelViewMatrix );
  19310. p_uniforms.setValue( _gl, 'normalMatrix', object.normalMatrix );
  19311. p_uniforms.setValue( _gl, 'modelMatrix', object.matrixWorld );
  19312. return program;
  19313. }
  19314. // Uniforms (refresh uniforms objects)
  19315. function refreshUniformsCommon( uniforms, material ) {
  19316. uniforms.opacity.value = material.opacity;
  19317. if ( material.color ) {
  19318. uniforms.diffuse.value = material.color;
  19319. }
  19320. if ( material.emissive ) {
  19321. uniforms.emissive.value.copy( material.emissive ).multiplyScalar( material.emissiveIntensity );
  19322. }
  19323. if ( material.map ) {
  19324. uniforms.map.value = material.map;
  19325. }
  19326. if ( material.alphaMap ) {
  19327. uniforms.alphaMap.value = material.alphaMap;
  19328. }
  19329. if ( material.specularMap ) {
  19330. uniforms.specularMap.value = material.specularMap;
  19331. }
  19332. if ( material.envMap ) {
  19333. uniforms.envMap.value = material.envMap;
  19334. // don't flip CubeTexture envMaps, flip everything else:
  19335. // WebGLRenderTargetCube will be flipped for backwards compatibility
  19336. // WebGLRenderTargetCube.texture will be flipped because it's a Texture and NOT a CubeTexture
  19337. // this check must be handled differently, or removed entirely, if WebGLRenderTargetCube uses a CubeTexture in the future
  19338. uniforms.flipEnvMap.value = material.envMap.isCubeTexture ? - 1 : 1;
  19339. uniforms.reflectivity.value = material.reflectivity;
  19340. uniforms.refractionRatio.value = material.refractionRatio;
  19341. uniforms.maxMipLevel.value = properties.get( material.envMap ).__maxMipLevel;
  19342. }
  19343. if ( material.lightMap ) {
  19344. uniforms.lightMap.value = material.lightMap;
  19345. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  19346. }
  19347. if ( material.aoMap ) {
  19348. uniforms.aoMap.value = material.aoMap;
  19349. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  19350. }
  19351. // uv repeat and offset setting priorities
  19352. // 1. color map
  19353. // 2. specular map
  19354. // 3. normal map
  19355. // 4. bump map
  19356. // 5. alpha map
  19357. // 6. emissive map
  19358. var uvScaleMap;
  19359. if ( material.map ) {
  19360. uvScaleMap = material.map;
  19361. } else if ( material.specularMap ) {
  19362. uvScaleMap = material.specularMap;
  19363. } else if ( material.displacementMap ) {
  19364. uvScaleMap = material.displacementMap;
  19365. } else if ( material.normalMap ) {
  19366. uvScaleMap = material.normalMap;
  19367. } else if ( material.bumpMap ) {
  19368. uvScaleMap = material.bumpMap;
  19369. } else if ( material.roughnessMap ) {
  19370. uvScaleMap = material.roughnessMap;
  19371. } else if ( material.metalnessMap ) {
  19372. uvScaleMap = material.metalnessMap;
  19373. } else if ( material.alphaMap ) {
  19374. uvScaleMap = material.alphaMap;
  19375. } else if ( material.emissiveMap ) {
  19376. uvScaleMap = material.emissiveMap;
  19377. }
  19378. if ( uvScaleMap !== undefined ) {
  19379. // backwards compatibility
  19380. if ( uvScaleMap.isWebGLRenderTarget ) {
  19381. uvScaleMap = uvScaleMap.texture;
  19382. }
  19383. if ( uvScaleMap.matrixAutoUpdate === true ) {
  19384. uvScaleMap.updateMatrix();
  19385. }
  19386. uniforms.uvTransform.value.copy( uvScaleMap.matrix );
  19387. }
  19388. }
  19389. function refreshUniformsLine( uniforms, material ) {
  19390. uniforms.diffuse.value = material.color;
  19391. uniforms.opacity.value = material.opacity;
  19392. }
  19393. function refreshUniformsDash( uniforms, material ) {
  19394. uniforms.dashSize.value = material.dashSize;
  19395. uniforms.totalSize.value = material.dashSize + material.gapSize;
  19396. uniforms.scale.value = material.scale;
  19397. }
  19398. function refreshUniformsPoints( uniforms, material ) {
  19399. uniforms.diffuse.value = material.color;
  19400. uniforms.opacity.value = material.opacity;
  19401. uniforms.size.value = material.size * _pixelRatio;
  19402. uniforms.scale.value = _height * 0.5;
  19403. uniforms.map.value = material.map;
  19404. if ( material.map !== null ) {
  19405. if ( material.map.matrixAutoUpdate === true ) {
  19406. material.map.updateMatrix();
  19407. }
  19408. uniforms.uvTransform.value.copy( material.map.matrix );
  19409. }
  19410. }
  19411. function refreshUniformsSprites( uniforms, material ) {
  19412. uniforms.diffuse.value = material.color;
  19413. uniforms.opacity.value = material.opacity;
  19414. uniforms.rotation.value = material.rotation;
  19415. uniforms.map.value = material.map;
  19416. if ( material.map !== null ) {
  19417. if ( material.map.matrixAutoUpdate === true ) {
  19418. material.map.updateMatrix();
  19419. }
  19420. uniforms.uvTransform.value.copy( material.map.matrix );
  19421. }
  19422. }
  19423. function refreshUniformsFog( uniforms, fog ) {
  19424. uniforms.fogColor.value = fog.color;
  19425. if ( fog.isFog ) {
  19426. uniforms.fogNear.value = fog.near;
  19427. uniforms.fogFar.value = fog.far;
  19428. } else if ( fog.isFogExp2 ) {
  19429. uniforms.fogDensity.value = fog.density;
  19430. }
  19431. }
  19432. function refreshUniformsLambert( uniforms, material ) {
  19433. if ( material.emissiveMap ) {
  19434. uniforms.emissiveMap.value = material.emissiveMap;
  19435. }
  19436. }
  19437. function refreshUniformsPhong( uniforms, material ) {
  19438. uniforms.specular.value = material.specular;
  19439. uniforms.shininess.value = Math.max( material.shininess, 1e-4 ); // to prevent pow( 0.0, 0.0 )
  19440. if ( material.emissiveMap ) {
  19441. uniforms.emissiveMap.value = material.emissiveMap;
  19442. }
  19443. if ( material.bumpMap ) {
  19444. uniforms.bumpMap.value = material.bumpMap;
  19445. uniforms.bumpScale.value = material.bumpScale;
  19446. if ( material.side === BackSide ) uniforms.bumpScale.value *= - 1;
  19447. }
  19448. if ( material.normalMap ) {
  19449. uniforms.normalMap.value = material.normalMap;
  19450. uniforms.normalScale.value.copy( material.normalScale );
  19451. if ( material.side === BackSide ) uniforms.normalScale.value.negate();
  19452. }
  19453. if ( material.displacementMap ) {
  19454. uniforms.displacementMap.value = material.displacementMap;
  19455. uniforms.displacementScale.value = material.displacementScale;
  19456. uniforms.displacementBias.value = material.displacementBias;
  19457. }
  19458. }
  19459. function refreshUniformsToon( uniforms, material ) {
  19460. refreshUniformsPhong( uniforms, material );
  19461. if ( material.gradientMap ) {
  19462. uniforms.gradientMap.value = material.gradientMap;
  19463. }
  19464. }
  19465. function refreshUniformsStandard( uniforms, material ) {
  19466. uniforms.roughness.value = material.roughness;
  19467. uniforms.metalness.value = material.metalness;
  19468. if ( material.roughnessMap ) {
  19469. uniforms.roughnessMap.value = material.roughnessMap;
  19470. }
  19471. if ( material.metalnessMap ) {
  19472. uniforms.metalnessMap.value = material.metalnessMap;
  19473. }
  19474. if ( material.emissiveMap ) {
  19475. uniforms.emissiveMap.value = material.emissiveMap;
  19476. }
  19477. if ( material.bumpMap ) {
  19478. uniforms.bumpMap.value = material.bumpMap;
  19479. uniforms.bumpScale.value = material.bumpScale;
  19480. if ( material.side === BackSide ) uniforms.bumpScale.value *= - 1;
  19481. }
  19482. if ( material.normalMap ) {
  19483. uniforms.normalMap.value = material.normalMap;
  19484. uniforms.normalScale.value.copy( material.normalScale );
  19485. if ( material.side === BackSide ) uniforms.normalScale.value.negate();
  19486. }
  19487. if ( material.displacementMap ) {
  19488. uniforms.displacementMap.value = material.displacementMap;
  19489. uniforms.displacementScale.value = material.displacementScale;
  19490. uniforms.displacementBias.value = material.displacementBias;
  19491. }
  19492. if ( material.envMap ) {
  19493. //uniforms.envMap.value = material.envMap; // part of uniforms common
  19494. uniforms.envMapIntensity.value = material.envMapIntensity;
  19495. }
  19496. }
  19497. function refreshUniformsPhysical( uniforms, material ) {
  19498. refreshUniformsStandard( uniforms, material );
  19499. uniforms.reflectivity.value = material.reflectivity; // also part of uniforms common
  19500. uniforms.clearCoat.value = material.clearCoat;
  19501. uniforms.clearCoatRoughness.value = material.clearCoatRoughness;
  19502. }
  19503. function refreshUniformsMatcap( uniforms, material ) {
  19504. if ( material.matcap ) {
  19505. uniforms.matcap.value = material.matcap;
  19506. }
  19507. if ( material.bumpMap ) {
  19508. uniforms.bumpMap.value = material.bumpMap;
  19509. uniforms.bumpScale.value = material.bumpScale;
  19510. if ( material.side === BackSide ) uniforms.bumpScale.value *= - 1;
  19511. }
  19512. if ( material.normalMap ) {
  19513. uniforms.normalMap.value = material.normalMap;
  19514. uniforms.normalScale.value.copy( material.normalScale );
  19515. if ( material.side === BackSide ) uniforms.normalScale.value.negate();
  19516. }
  19517. if ( material.displacementMap ) {
  19518. uniforms.displacementMap.value = material.displacementMap;
  19519. uniforms.displacementScale.value = material.displacementScale;
  19520. uniforms.displacementBias.value = material.displacementBias;
  19521. }
  19522. }
  19523. function refreshUniformsDepth( uniforms, material ) {
  19524. if ( material.displacementMap ) {
  19525. uniforms.displacementMap.value = material.displacementMap;
  19526. uniforms.displacementScale.value = material.displacementScale;
  19527. uniforms.displacementBias.value = material.displacementBias;
  19528. }
  19529. }
  19530. function refreshUniformsDistance( uniforms, material ) {
  19531. if ( material.displacementMap ) {
  19532. uniforms.displacementMap.value = material.displacementMap;
  19533. uniforms.displacementScale.value = material.displacementScale;
  19534. uniforms.displacementBias.value = material.displacementBias;
  19535. }
  19536. uniforms.referencePosition.value.copy( material.referencePosition );
  19537. uniforms.nearDistance.value = material.nearDistance;
  19538. uniforms.farDistance.value = material.farDistance;
  19539. }
  19540. function refreshUniformsNormal( uniforms, material ) {
  19541. if ( material.bumpMap ) {
  19542. uniforms.bumpMap.value = material.bumpMap;
  19543. uniforms.bumpScale.value = material.bumpScale;
  19544. if ( material.side === BackSide ) uniforms.bumpScale.value *= - 1;
  19545. }
  19546. if ( material.normalMap ) {
  19547. uniforms.normalMap.value = material.normalMap;
  19548. uniforms.normalScale.value.copy( material.normalScale );
  19549. if ( material.side === BackSide ) uniforms.normalScale.value.negate();
  19550. }
  19551. if ( material.displacementMap ) {
  19552. uniforms.displacementMap.value = material.displacementMap;
  19553. uniforms.displacementScale.value = material.displacementScale;
  19554. uniforms.displacementBias.value = material.displacementBias;
  19555. }
  19556. }
  19557. // If uniforms are marked as clean, they don't need to be loaded to the GPU.
  19558. function markUniformsLightsNeedsUpdate( uniforms, value ) {
  19559. uniforms.ambientLightColor.needsUpdate = value;
  19560. uniforms.directionalLights.needsUpdate = value;
  19561. uniforms.pointLights.needsUpdate = value;
  19562. uniforms.spotLights.needsUpdate = value;
  19563. uniforms.rectAreaLights.needsUpdate = value;
  19564. uniforms.hemisphereLights.needsUpdate = value;
  19565. }
  19566. // Textures
  19567. function allocTextureUnit() {
  19568. var textureUnit = _usedTextureUnits;
  19569. if ( textureUnit >= capabilities.maxTextures ) {
  19570. console.warn( 'THREE.WebGLRenderer: Trying to use ' + textureUnit + ' texture units while this GPU supports only ' + capabilities.maxTextures );
  19571. }
  19572. _usedTextureUnits += 1;
  19573. return textureUnit;
  19574. }
  19575. this.allocTextureUnit = allocTextureUnit;
  19576. // this.setTexture2D = setTexture2D;
  19577. this.setTexture2D = ( function () {
  19578. var warned = false;
  19579. // backwards compatibility: peel texture.texture
  19580. return function setTexture2D( texture, slot ) {
  19581. if ( texture && texture.isWebGLRenderTarget ) {
  19582. if ( ! warned ) {
  19583. console.warn( "THREE.WebGLRenderer.setTexture2D: don't use render targets as textures. Use their .texture property instead." );
  19584. warned = true;
  19585. }
  19586. texture = texture.texture;
  19587. }
  19588. textures.setTexture2D( texture, slot );
  19589. };
  19590. }() );
  19591. this.setTexture2DArray = function ( texture, slot ) {
  19592. textures.setTexture2DArray( texture, slot );
  19593. };
  19594. this.setTexture3D = function ( texture, slot ) {
  19595. textures.setTexture3D( texture, slot );
  19596. };
  19597. this.setTexture = ( function () {
  19598. var warned = false;
  19599. return function setTexture( texture, slot ) {
  19600. if ( ! warned ) {
  19601. console.warn( "THREE.WebGLRenderer: .setTexture is deprecated, use setTexture2D instead." );
  19602. warned = true;
  19603. }
  19604. textures.setTexture2D( texture, slot );
  19605. };
  19606. }() );
  19607. this.setTextureCube = ( function () {
  19608. var warned = false;
  19609. return function setTextureCube( texture, slot ) {
  19610. // backwards compatibility: peel texture.texture
  19611. if ( texture && texture.isWebGLRenderTargetCube ) {
  19612. if ( ! warned ) {
  19613. console.warn( "THREE.WebGLRenderer.setTextureCube: don't use cube render targets as textures. Use their .texture property instead." );
  19614. warned = true;
  19615. }
  19616. texture = texture.texture;
  19617. }
  19618. // currently relying on the fact that WebGLRenderTargetCube.texture is a Texture and NOT a CubeTexture
  19619. // TODO: unify these code paths
  19620. if ( ( texture && texture.isCubeTexture ) ||
  19621. ( Array.isArray( texture.image ) && texture.image.length === 6 ) ) {
  19622. // CompressedTexture can have Array in image :/
  19623. // this function alone should take care of cube textures
  19624. textures.setTextureCube( texture, slot );
  19625. } else {
  19626. // assumed: texture property of THREE.WebGLRenderTargetCube
  19627. textures.setTextureCubeDynamic( texture, slot );
  19628. }
  19629. };
  19630. }() );
  19631. //
  19632. this.setFramebuffer = function ( value ) {
  19633. _framebuffer = value;
  19634. };
  19635. this.getRenderTarget = function () {
  19636. return _currentRenderTarget;
  19637. };
  19638. this.setRenderTarget = function ( renderTarget, activeCubeFace, activeMipMapLevel ) {
  19639. _currentRenderTarget = renderTarget;
  19640. if ( renderTarget && properties.get( renderTarget ).__webglFramebuffer === undefined ) {
  19641. textures.setupRenderTarget( renderTarget );
  19642. }
  19643. var framebuffer = _framebuffer;
  19644. var isCube = false;
  19645. if ( renderTarget ) {
  19646. var __webglFramebuffer = properties.get( renderTarget ).__webglFramebuffer;
  19647. if ( renderTarget.isWebGLRenderTargetCube ) {
  19648. framebuffer = __webglFramebuffer[ activeCubeFace || 0 ];
  19649. isCube = true;
  19650. } else if ( renderTarget.isWebGLMultisampleRenderTarget ) {
  19651. framebuffer = properties.get( renderTarget ).__webglMultisampledFramebuffer;
  19652. } else {
  19653. framebuffer = __webglFramebuffer;
  19654. }
  19655. _currentViewport.copy( renderTarget.viewport );
  19656. _currentScissor.copy( renderTarget.scissor );
  19657. _currentScissorTest = renderTarget.scissorTest;
  19658. } else {
  19659. _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio );
  19660. _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio );
  19661. _currentScissorTest = _scissorTest;
  19662. }
  19663. if ( _currentFramebuffer !== framebuffer ) {
  19664. _gl.bindFramebuffer( 36160, framebuffer );
  19665. _currentFramebuffer = framebuffer;
  19666. }
  19667. state.viewport( _currentViewport );
  19668. state.scissor( _currentScissor );
  19669. state.setScissorTest( _currentScissorTest );
  19670. if ( isCube ) {
  19671. var textureProperties = properties.get( renderTarget.texture );
  19672. _gl.framebufferTexture2D( 36160, 36064, 34069 + ( activeCubeFace || 0 ), textureProperties.__webglTexture, activeMipMapLevel || 0 );
  19673. }
  19674. };
  19675. this.readRenderTargetPixels = function ( renderTarget, x, y, width, height, buffer ) {
  19676. if ( ! ( renderTarget && renderTarget.isWebGLRenderTarget ) ) {
  19677. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' );
  19678. return;
  19679. }
  19680. var framebuffer = properties.get( renderTarget ).__webglFramebuffer;
  19681. if ( framebuffer ) {
  19682. var restore = false;
  19683. if ( framebuffer !== _currentFramebuffer ) {
  19684. _gl.bindFramebuffer( 36160, framebuffer );
  19685. restore = true;
  19686. }
  19687. try {
  19688. var texture = renderTarget.texture;
  19689. var textureFormat = texture.format;
  19690. var textureType = texture.type;
  19691. if ( textureFormat !== RGBAFormat && utils.convert( textureFormat ) !== _gl.getParameter( 35739 ) ) {
  19692. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.' );
  19693. return;
  19694. }
  19695. if ( textureType !== UnsignedByteType && utils.convert( textureType ) !== _gl.getParameter( 35738 ) && // IE11, Edge and Chrome Mac < 52 (#9513)
  19696. ! ( textureType === FloatType && ( capabilities.isWebGL2 || extensions.get( 'OES_texture_float' ) || extensions.get( 'WEBGL_color_buffer_float' ) ) ) && // Chrome Mac >= 52 and Firefox
  19697. ! ( textureType === HalfFloatType && ( capabilities.isWebGL2 ? extensions.get( 'EXT_color_buffer_float' ) : extensions.get( 'EXT_color_buffer_half_float' ) ) ) ) {
  19698. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.' );
  19699. return;
  19700. }
  19701. if ( _gl.checkFramebufferStatus( 36160 ) === 36053 ) {
  19702. // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  19703. if ( ( x >= 0 && x <= ( renderTarget.width - width ) ) && ( y >= 0 && y <= ( renderTarget.height - height ) ) ) {
  19704. _gl.readPixels( x, y, width, height, utils.convert( textureFormat ), utils.convert( textureType ), buffer );
  19705. }
  19706. } else {
  19707. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete.' );
  19708. }
  19709. } finally {
  19710. if ( restore ) {
  19711. _gl.bindFramebuffer( 36160, _currentFramebuffer );
  19712. }
  19713. }
  19714. }
  19715. };
  19716. this.copyFramebufferToTexture = function ( position, texture, level ) {
  19717. var width = texture.image.width;
  19718. var height = texture.image.height;
  19719. var glFormat = utils.convert( texture.format );
  19720. this.setTexture2D( texture, 0 );
  19721. _gl.copyTexImage2D( 3553, level || 0, glFormat, position.x, position.y, width, height, 0 );
  19722. };
  19723. this.copyTextureToTexture = function ( position, srcTexture, dstTexture, level ) {
  19724. var width = srcTexture.image.width;
  19725. var height = srcTexture.image.height;
  19726. var glFormat = utils.convert( dstTexture.format );
  19727. var glType = utils.convert( dstTexture.type );
  19728. this.setTexture2D( dstTexture, 0 );
  19729. if ( srcTexture.isDataTexture ) {
  19730. _gl.texSubImage2D( 3553, level || 0, position.x, position.y, width, height, glFormat, glType, srcTexture.image.data );
  19731. } else {
  19732. _gl.texSubImage2D( 3553, level || 0, position.x, position.y, glFormat, glType, srcTexture.image );
  19733. }
  19734. };
  19735. }
  19736. /**
  19737. * @author mrdoob / http://mrdoob.com/
  19738. * @author alteredq / http://alteredqualia.com/
  19739. */
  19740. function FogExp2( color, density ) {
  19741. this.name = '';
  19742. this.color = new Color( color );
  19743. this.density = ( density !== undefined ) ? density : 0.00025;
  19744. }
  19745. Object.assign( FogExp2.prototype, {
  19746. isFogExp2: true,
  19747. clone: function () {
  19748. return new FogExp2( this.color, this.density );
  19749. },
  19750. toJSON: function ( /* meta */ ) {
  19751. return {
  19752. type: 'FogExp2',
  19753. color: this.color.getHex(),
  19754. density: this.density
  19755. };
  19756. }
  19757. } );
  19758. /**
  19759. * @author mrdoob / http://mrdoob.com/
  19760. * @author alteredq / http://alteredqualia.com/
  19761. */
  19762. function Fog( color, near, far ) {
  19763. this.name = '';
  19764. this.color = new Color( color );
  19765. this.near = ( near !== undefined ) ? near : 1;
  19766. this.far = ( far !== undefined ) ? far : 1000;
  19767. }
  19768. Object.assign( Fog.prototype, {
  19769. isFog: true,
  19770. clone: function () {
  19771. return new Fog( this.color, this.near, this.far );
  19772. },
  19773. toJSON: function ( /* meta */ ) {
  19774. return {
  19775. type: 'Fog',
  19776. color: this.color.getHex(),
  19777. near: this.near,
  19778. far: this.far
  19779. };
  19780. }
  19781. } );
  19782. /**
  19783. * @author mrdoob / http://mrdoob.com/
  19784. */
  19785. function Scene() {
  19786. Object3D.call( this );
  19787. this.type = 'Scene';
  19788. this.background = null;
  19789. this.fog = null;
  19790. this.overrideMaterial = null;
  19791. this.autoUpdate = true; // checked by the renderer
  19792. }
  19793. Scene.prototype = Object.assign( Object.create( Object3D.prototype ), {
  19794. constructor: Scene,
  19795. isScene: true,
  19796. copy: function ( source, recursive ) {
  19797. Object3D.prototype.copy.call( this, source, recursive );
  19798. if ( source.background !== null ) this.background = source.background.clone();
  19799. if ( source.fog !== null ) this.fog = source.fog.clone();
  19800. if ( source.overrideMaterial !== null ) this.overrideMaterial = source.overrideMaterial.clone();
  19801. this.autoUpdate = source.autoUpdate;
  19802. this.matrixAutoUpdate = source.matrixAutoUpdate;
  19803. return this;
  19804. },
  19805. toJSON: function ( meta ) {
  19806. var data = Object3D.prototype.toJSON.call( this, meta );
  19807. if ( this.background !== null ) data.object.background = this.background.toJSON( meta );
  19808. if ( this.fog !== null ) data.object.fog = this.fog.toJSON();
  19809. return data;
  19810. },
  19811. dispose: function () {
  19812. this.dispatchEvent( { type: 'dispose' } );
  19813. }
  19814. } );
  19815. /**
  19816. * @author benaadams / https://twitter.com/ben_a_adams
  19817. */
  19818. function InterleavedBuffer( array, stride ) {
  19819. this.array = array;
  19820. this.stride = stride;
  19821. this.count = array !== undefined ? array.length / stride : 0;
  19822. this.dynamic = false;
  19823. this.updateRange = { offset: 0, count: - 1 };
  19824. this.version = 0;
  19825. }
  19826. Object.defineProperty( InterleavedBuffer.prototype, 'needsUpdate', {
  19827. set: function ( value ) {
  19828. if ( value === true ) this.version ++;
  19829. }
  19830. } );
  19831. Object.assign( InterleavedBuffer.prototype, {
  19832. isInterleavedBuffer: true,
  19833. onUploadCallback: function () {},
  19834. setArray: function ( array ) {
  19835. if ( Array.isArray( array ) ) {
  19836. throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );
  19837. }
  19838. this.count = array !== undefined ? array.length / this.stride : 0;
  19839. this.array = array;
  19840. return this;
  19841. },
  19842. setDynamic: function ( value ) {
  19843. this.dynamic = value;
  19844. return this;
  19845. },
  19846. copy: function ( source ) {
  19847. this.array = new source.array.constructor( source.array );
  19848. this.count = source.count;
  19849. this.stride = source.stride;
  19850. this.dynamic = source.dynamic;
  19851. return this;
  19852. },
  19853. copyAt: function ( index1, attribute, index2 ) {
  19854. index1 *= this.stride;
  19855. index2 *= attribute.stride;
  19856. for ( var i = 0, l = this.stride; i < l; i ++ ) {
  19857. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  19858. }
  19859. return this;
  19860. },
  19861. set: function ( value, offset ) {
  19862. if ( offset === undefined ) offset = 0;
  19863. this.array.set( value, offset );
  19864. return this;
  19865. },
  19866. clone: function () {
  19867. return new this.constructor().copy( this );
  19868. },
  19869. onUpload: function ( callback ) {
  19870. this.onUploadCallback = callback;
  19871. return this;
  19872. }
  19873. } );
  19874. /**
  19875. * @author benaadams / https://twitter.com/ben_a_adams
  19876. */
  19877. function InterleavedBufferAttribute( interleavedBuffer, itemSize, offset, normalized ) {
  19878. this.data = interleavedBuffer;
  19879. this.itemSize = itemSize;
  19880. this.offset = offset;
  19881. this.normalized = normalized === true;
  19882. }
  19883. Object.defineProperties( InterleavedBufferAttribute.prototype, {
  19884. count: {
  19885. get: function () {
  19886. return this.data.count;
  19887. }
  19888. },
  19889. array: {
  19890. get: function () {
  19891. return this.data.array;
  19892. }
  19893. }
  19894. } );
  19895. Object.assign( InterleavedBufferAttribute.prototype, {
  19896. isInterleavedBufferAttribute: true,
  19897. setX: function ( index, x ) {
  19898. this.data.array[ index * this.data.stride + this.offset ] = x;
  19899. return this;
  19900. },
  19901. setY: function ( index, y ) {
  19902. this.data.array[ index * this.data.stride + this.offset + 1 ] = y;
  19903. return this;
  19904. },
  19905. setZ: function ( index, z ) {
  19906. this.data.array[ index * this.data.stride + this.offset + 2 ] = z;
  19907. return this;
  19908. },
  19909. setW: function ( index, w ) {
  19910. this.data.array[ index * this.data.stride + this.offset + 3 ] = w;
  19911. return this;
  19912. },
  19913. getX: function ( index ) {
  19914. return this.data.array[ index * this.data.stride + this.offset ];
  19915. },
  19916. getY: function ( index ) {
  19917. return this.data.array[ index * this.data.stride + this.offset + 1 ];
  19918. },
  19919. getZ: function ( index ) {
  19920. return this.data.array[ index * this.data.stride + this.offset + 2 ];
  19921. },
  19922. getW: function ( index ) {
  19923. return this.data.array[ index * this.data.stride + this.offset + 3 ];
  19924. },
  19925. setXY: function ( index, x, y ) {
  19926. index = index * this.data.stride + this.offset;
  19927. this.data.array[ index + 0 ] = x;
  19928. this.data.array[ index + 1 ] = y;
  19929. return this;
  19930. },
  19931. setXYZ: function ( index, x, y, z ) {
  19932. index = index * this.data.stride + this.offset;
  19933. this.data.array[ index + 0 ] = x;
  19934. this.data.array[ index + 1 ] = y;
  19935. this.data.array[ index + 2 ] = z;
  19936. return this;
  19937. },
  19938. setXYZW: function ( index, x, y, z, w ) {
  19939. index = index * this.data.stride + this.offset;
  19940. this.data.array[ index + 0 ] = x;
  19941. this.data.array[ index + 1 ] = y;
  19942. this.data.array[ index + 2 ] = z;
  19943. this.data.array[ index + 3 ] = w;
  19944. return this;
  19945. }
  19946. } );
  19947. /**
  19948. * @author alteredq / http://alteredqualia.com/
  19949. *
  19950. * parameters = {
  19951. * color: <hex>,
  19952. * map: new THREE.Texture( <Image> ),
  19953. * rotation: <float>,
  19954. * sizeAttenuation: <bool>
  19955. * }
  19956. */
  19957. function SpriteMaterial( parameters ) {
  19958. Material.call( this );
  19959. this.type = 'SpriteMaterial';
  19960. this.color = new Color( 0xffffff );
  19961. this.map = null;
  19962. this.rotation = 0;
  19963. this.sizeAttenuation = true;
  19964. this.lights = false;
  19965. this.transparent = true;
  19966. this.setValues( parameters );
  19967. }
  19968. SpriteMaterial.prototype = Object.create( Material.prototype );
  19969. SpriteMaterial.prototype.constructor = SpriteMaterial;
  19970. SpriteMaterial.prototype.isSpriteMaterial = true;
  19971. SpriteMaterial.prototype.copy = function ( source ) {
  19972. Material.prototype.copy.call( this, source );
  19973. this.color.copy( source.color );
  19974. this.map = source.map;
  19975. this.rotation = source.rotation;
  19976. this.sizeAttenuation = source.sizeAttenuation;
  19977. return this;
  19978. };
  19979. /**
  19980. * @author mikael emtinger / http://gomo.se/
  19981. * @author alteredq / http://alteredqualia.com/
  19982. */
  19983. var geometry;
  19984. function Sprite( material ) {
  19985. Object3D.call( this );
  19986. this.type = 'Sprite';
  19987. if ( geometry === undefined ) {
  19988. geometry = new BufferGeometry();
  19989. var float32Array = new Float32Array( [
  19990. - 0.5, - 0.5, 0, 0, 0,
  19991. 0.5, - 0.5, 0, 1, 0,
  19992. 0.5, 0.5, 0, 1, 1,
  19993. - 0.5, 0.5, 0, 0, 1
  19994. ] );
  19995. var interleavedBuffer = new InterleavedBuffer( float32Array, 5 );
  19996. geometry.setIndex( [ 0, 1, 2, 0, 2, 3 ] );
  19997. geometry.addAttribute( 'position', new InterleavedBufferAttribute( interleavedBuffer, 3, 0, false ) );
  19998. geometry.addAttribute( 'uv', new InterleavedBufferAttribute( interleavedBuffer, 2, 3, false ) );
  19999. }
  20000. this.geometry = geometry;
  20001. this.material = ( material !== undefined ) ? material : new SpriteMaterial();
  20002. this.center = new Vector2( 0.5, 0.5 );
  20003. }
  20004. Sprite.prototype = Object.assign( Object.create( Object3D.prototype ), {
  20005. constructor: Sprite,
  20006. isSprite: true,
  20007. raycast: ( function () {
  20008. var intersectPoint = new Vector3();
  20009. var worldScale = new Vector3();
  20010. var mvPosition = new Vector3();
  20011. var alignedPosition = new Vector2();
  20012. var rotatedPosition = new Vector2();
  20013. var viewWorldMatrix = new Matrix4();
  20014. var vA = new Vector3();
  20015. var vB = new Vector3();
  20016. var vC = new Vector3();
  20017. var uvA = new Vector2();
  20018. var uvB = new Vector2();
  20019. var uvC = new Vector2();
  20020. function transformVertex( vertexPosition, mvPosition, center, scale, sin, cos ) {
  20021. // compute position in camera space
  20022. alignedPosition.subVectors( vertexPosition, center ).addScalar( 0.5 ).multiply( scale );
  20023. // to check if rotation is not zero
  20024. if ( sin !== undefined ) {
  20025. rotatedPosition.x = ( cos * alignedPosition.x ) - ( sin * alignedPosition.y );
  20026. rotatedPosition.y = ( sin * alignedPosition.x ) + ( cos * alignedPosition.y );
  20027. } else {
  20028. rotatedPosition.copy( alignedPosition );
  20029. }
  20030. vertexPosition.copy( mvPosition );
  20031. vertexPosition.x += rotatedPosition.x;
  20032. vertexPosition.y += rotatedPosition.y;
  20033. // transform to world space
  20034. vertexPosition.applyMatrix4( viewWorldMatrix );
  20035. }
  20036. return function raycast( raycaster, intersects ) {
  20037. worldScale.setFromMatrixScale( this.matrixWorld );
  20038. viewWorldMatrix.getInverse( this.modelViewMatrix ).premultiply( this.matrixWorld );
  20039. mvPosition.setFromMatrixPosition( this.modelViewMatrix );
  20040. var rotation = this.material.rotation;
  20041. var sin, cos;
  20042. if ( rotation !== 0 ) {
  20043. cos = Math.cos( rotation );
  20044. sin = Math.sin( rotation );
  20045. }
  20046. var center = this.center;
  20047. transformVertex( vA.set( - 0.5, - 0.5, 0 ), mvPosition, center, worldScale, sin, cos );
  20048. transformVertex( vB.set( 0.5, - 0.5, 0 ), mvPosition, center, worldScale, sin, cos );
  20049. transformVertex( vC.set( 0.5, 0.5, 0 ), mvPosition, center, worldScale, sin, cos );
  20050. uvA.set( 0, 0 );
  20051. uvB.set( 1, 0 );
  20052. uvC.set( 1, 1 );
  20053. // check first triangle
  20054. var intersect = raycaster.ray.intersectTriangle( vA, vB, vC, false, intersectPoint );
  20055. if ( intersect === null ) {
  20056. // check second triangle
  20057. transformVertex( vB.set( - 0.5, 0.5, 0 ), mvPosition, center, worldScale, sin, cos );
  20058. uvB.set( 0, 1 );
  20059. intersect = raycaster.ray.intersectTriangle( vA, vC, vB, false, intersectPoint );
  20060. if ( intersect === null ) {
  20061. return;
  20062. }
  20063. }
  20064. var distance = raycaster.ray.origin.distanceTo( intersectPoint );
  20065. if ( distance < raycaster.near || distance > raycaster.far ) return;
  20066. intersects.push( {
  20067. distance: distance,
  20068. point: intersectPoint.clone(),
  20069. uv: Triangle.getUV( intersectPoint, vA, vB, vC, uvA, uvB, uvC, new Vector2() ),
  20070. face: null,
  20071. object: this
  20072. } );
  20073. };
  20074. }() ),
  20075. clone: function () {
  20076. return new this.constructor( this.material ).copy( this );
  20077. },
  20078. copy: function ( source ) {
  20079. Object3D.prototype.copy.call( this, source );
  20080. if ( source.center !== undefined ) this.center.copy( source.center );
  20081. return this;
  20082. }
  20083. } );
  20084. /**
  20085. * @author mikael emtinger / http://gomo.se/
  20086. * @author alteredq / http://alteredqualia.com/
  20087. * @author mrdoob / http://mrdoob.com/
  20088. */
  20089. function LOD() {
  20090. Object3D.call( this );
  20091. this.type = 'LOD';
  20092. Object.defineProperties( this, {
  20093. levels: {
  20094. enumerable: true,
  20095. value: []
  20096. }
  20097. } );
  20098. }
  20099. LOD.prototype = Object.assign( Object.create( Object3D.prototype ), {
  20100. constructor: LOD,
  20101. copy: function ( source ) {
  20102. Object3D.prototype.copy.call( this, source, false );
  20103. var levels = source.levels;
  20104. for ( var i = 0, l = levels.length; i < l; i ++ ) {
  20105. var level = levels[ i ];
  20106. this.addLevel( level.object.clone(), level.distance );
  20107. }
  20108. return this;
  20109. },
  20110. addLevel: function ( object, distance ) {
  20111. if ( distance === undefined ) distance = 0;
  20112. distance = Math.abs( distance );
  20113. var levels = this.levels;
  20114. for ( var l = 0; l < levels.length; l ++ ) {
  20115. if ( distance < levels[ l ].distance ) {
  20116. break;
  20117. }
  20118. }
  20119. levels.splice( l, 0, { distance: distance, object: object } );
  20120. this.add( object );
  20121. },
  20122. getObjectForDistance: function ( distance ) {
  20123. var levels = this.levels;
  20124. for ( var i = 1, l = levels.length; i < l; i ++ ) {
  20125. if ( distance < levels[ i ].distance ) {
  20126. break;
  20127. }
  20128. }
  20129. return levels[ i - 1 ].object;
  20130. },
  20131. raycast: ( function () {
  20132. var matrixPosition = new Vector3();
  20133. return function raycast( raycaster, intersects ) {
  20134. matrixPosition.setFromMatrixPosition( this.matrixWorld );
  20135. var distance = raycaster.ray.origin.distanceTo( matrixPosition );
  20136. this.getObjectForDistance( distance ).raycast( raycaster, intersects );
  20137. };
  20138. }() ),
  20139. update: function () {
  20140. var v1 = new Vector3();
  20141. var v2 = new Vector3();
  20142. return function update( camera ) {
  20143. var levels = this.levels;
  20144. if ( levels.length > 1 ) {
  20145. v1.setFromMatrixPosition( camera.matrixWorld );
  20146. v2.setFromMatrixPosition( this.matrixWorld );
  20147. var distance = v1.distanceTo( v2 );
  20148. levels[ 0 ].object.visible = true;
  20149. for ( var i = 1, l = levels.length; i < l; i ++ ) {
  20150. if ( distance >= levels[ i ].distance ) {
  20151. levels[ i - 1 ].object.visible = false;
  20152. levels[ i ].object.visible = true;
  20153. } else {
  20154. break;
  20155. }
  20156. }
  20157. for ( ; i < l; i ++ ) {
  20158. levels[ i ].object.visible = false;
  20159. }
  20160. }
  20161. };
  20162. }(),
  20163. toJSON: function ( meta ) {
  20164. var data = Object3D.prototype.toJSON.call( this, meta );
  20165. data.object.levels = [];
  20166. var levels = this.levels;
  20167. for ( var i = 0, l = levels.length; i < l; i ++ ) {
  20168. var level = levels[ i ];
  20169. data.object.levels.push( {
  20170. object: level.object.uuid,
  20171. distance: level.distance
  20172. } );
  20173. }
  20174. return data;
  20175. }
  20176. } );
  20177. /**
  20178. * @author mikael emtinger / http://gomo.se/
  20179. * @author alteredq / http://alteredqualia.com/
  20180. * @author ikerr / http://verold.com
  20181. */
  20182. function SkinnedMesh( geometry, material ) {
  20183. if ( geometry && geometry.isGeometry ) {
  20184. console.error( 'THREE.SkinnedMesh no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.' );
  20185. }
  20186. Mesh.call( this, geometry, material );
  20187. this.type = 'SkinnedMesh';
  20188. this.bindMode = 'attached';
  20189. this.bindMatrix = new Matrix4();
  20190. this.bindMatrixInverse = new Matrix4();
  20191. }
  20192. SkinnedMesh.prototype = Object.assign( Object.create( Mesh.prototype ), {
  20193. constructor: SkinnedMesh,
  20194. isSkinnedMesh: true,
  20195. bind: function ( skeleton, bindMatrix ) {
  20196. this.skeleton = skeleton;
  20197. if ( bindMatrix === undefined ) {
  20198. this.updateMatrixWorld( true );
  20199. this.skeleton.calculateInverses();
  20200. bindMatrix = this.matrixWorld;
  20201. }
  20202. this.bindMatrix.copy( bindMatrix );
  20203. this.bindMatrixInverse.getInverse( bindMatrix );
  20204. },
  20205. pose: function () {
  20206. this.skeleton.pose();
  20207. },
  20208. normalizeSkinWeights: function () {
  20209. var vector = new Vector4();
  20210. var skinWeight = this.geometry.attributes.skinWeight;
  20211. for ( var i = 0, l = skinWeight.count; i < l; i ++ ) {
  20212. vector.x = skinWeight.getX( i );
  20213. vector.y = skinWeight.getY( i );
  20214. vector.z = skinWeight.getZ( i );
  20215. vector.w = skinWeight.getW( i );
  20216. var scale = 1.0 / vector.manhattanLength();
  20217. if ( scale !== Infinity ) {
  20218. vector.multiplyScalar( scale );
  20219. } else {
  20220. vector.set( 1, 0, 0, 0 ); // do something reasonable
  20221. }
  20222. skinWeight.setXYZW( i, vector.x, vector.y, vector.z, vector.w );
  20223. }
  20224. },
  20225. updateMatrixWorld: function ( force ) {
  20226. Mesh.prototype.updateMatrixWorld.call( this, force );
  20227. if ( this.bindMode === 'attached' ) {
  20228. this.bindMatrixInverse.getInverse( this.matrixWorld );
  20229. } else if ( this.bindMode === 'detached' ) {
  20230. this.bindMatrixInverse.getInverse( this.bindMatrix );
  20231. } else {
  20232. console.warn( 'THREE.SkinnedMesh: Unrecognized bindMode: ' + this.bindMode );
  20233. }
  20234. },
  20235. clone: function () {
  20236. return new this.constructor( this.geometry, this.material ).copy( this );
  20237. }
  20238. } );
  20239. /**
  20240. * @author mikael emtinger / http://gomo.se/
  20241. * @author alteredq / http://alteredqualia.com/
  20242. * @author michael guerrero / http://realitymeltdown.com
  20243. * @author ikerr / http://verold.com
  20244. */
  20245. function Skeleton( bones, boneInverses ) {
  20246. // copy the bone array
  20247. bones = bones || [];
  20248. this.bones = bones.slice( 0 );
  20249. this.boneMatrices = new Float32Array( this.bones.length * 16 );
  20250. // use the supplied bone inverses or calculate the inverses
  20251. if ( boneInverses === undefined ) {
  20252. this.calculateInverses();
  20253. } else {
  20254. if ( this.bones.length === boneInverses.length ) {
  20255. this.boneInverses = boneInverses.slice( 0 );
  20256. } else {
  20257. console.warn( 'THREE.Skeleton boneInverses is the wrong length.' );
  20258. this.boneInverses = [];
  20259. for ( var i = 0, il = this.bones.length; i < il; i ++ ) {
  20260. this.boneInverses.push( new Matrix4() );
  20261. }
  20262. }
  20263. }
  20264. }
  20265. Object.assign( Skeleton.prototype, {
  20266. calculateInverses: function () {
  20267. this.boneInverses = [];
  20268. for ( var i = 0, il = this.bones.length; i < il; i ++ ) {
  20269. var inverse = new Matrix4();
  20270. if ( this.bones[ i ] ) {
  20271. inverse.getInverse( this.bones[ i ].matrixWorld );
  20272. }
  20273. this.boneInverses.push( inverse );
  20274. }
  20275. },
  20276. pose: function () {
  20277. var bone, i, il;
  20278. // recover the bind-time world matrices
  20279. for ( i = 0, il = this.bones.length; i < il; i ++ ) {
  20280. bone = this.bones[ i ];
  20281. if ( bone ) {
  20282. bone.matrixWorld.getInverse( this.boneInverses[ i ] );
  20283. }
  20284. }
  20285. // compute the local matrices, positions, rotations and scales
  20286. for ( i = 0, il = this.bones.length; i < il; i ++ ) {
  20287. bone = this.bones[ i ];
  20288. if ( bone ) {
  20289. if ( bone.parent && bone.parent.isBone ) {
  20290. bone.matrix.getInverse( bone.parent.matrixWorld );
  20291. bone.matrix.multiply( bone.matrixWorld );
  20292. } else {
  20293. bone.matrix.copy( bone.matrixWorld );
  20294. }
  20295. bone.matrix.decompose( bone.position, bone.quaternion, bone.scale );
  20296. }
  20297. }
  20298. },
  20299. update: ( function () {
  20300. var offsetMatrix = new Matrix4();
  20301. var identityMatrix = new Matrix4();
  20302. return function update() {
  20303. var bones = this.bones;
  20304. var boneInverses = this.boneInverses;
  20305. var boneMatrices = this.boneMatrices;
  20306. var boneTexture = this.boneTexture;
  20307. // flatten bone matrices to array
  20308. for ( var i = 0, il = bones.length; i < il; i ++ ) {
  20309. // compute the offset between the current and the original transform
  20310. var matrix = bones[ i ] ? bones[ i ].matrixWorld : identityMatrix;
  20311. offsetMatrix.multiplyMatrices( matrix, boneInverses[ i ] );
  20312. offsetMatrix.toArray( boneMatrices, i * 16 );
  20313. }
  20314. if ( boneTexture !== undefined ) {
  20315. boneTexture.needsUpdate = true;
  20316. }
  20317. };
  20318. } )(),
  20319. clone: function () {
  20320. return new Skeleton( this.bones, this.boneInverses );
  20321. },
  20322. getBoneByName: function ( name ) {
  20323. for ( var i = 0, il = this.bones.length; i < il; i ++ ) {
  20324. var bone = this.bones[ i ];
  20325. if ( bone.name === name ) {
  20326. return bone;
  20327. }
  20328. }
  20329. return undefined;
  20330. }
  20331. } );
  20332. /**
  20333. * @author mikael emtinger / http://gomo.se/
  20334. * @author alteredq / http://alteredqualia.com/
  20335. * @author ikerr / http://verold.com
  20336. */
  20337. function Bone() {
  20338. Object3D.call( this );
  20339. this.type = 'Bone';
  20340. }
  20341. Bone.prototype = Object.assign( Object.create( Object3D.prototype ), {
  20342. constructor: Bone,
  20343. isBone: true
  20344. } );
  20345. /**
  20346. * @author mrdoob / http://mrdoob.com/
  20347. * @author alteredq / http://alteredqualia.com/
  20348. *
  20349. * parameters = {
  20350. * color: <hex>,
  20351. * opacity: <float>,
  20352. *
  20353. * linewidth: <float>,
  20354. * linecap: "round",
  20355. * linejoin: "round"
  20356. * }
  20357. */
  20358. function LineBasicMaterial( parameters ) {
  20359. Material.call( this );
  20360. this.type = 'LineBasicMaterial';
  20361. this.color = new Color( 0xffffff );
  20362. this.linewidth = 1;
  20363. this.linecap = 'round';
  20364. this.linejoin = 'round';
  20365. this.lights = false;
  20366. this.setValues( parameters );
  20367. }
  20368. LineBasicMaterial.prototype = Object.create( Material.prototype );
  20369. LineBasicMaterial.prototype.constructor = LineBasicMaterial;
  20370. LineBasicMaterial.prototype.isLineBasicMaterial = true;
  20371. LineBasicMaterial.prototype.copy = function ( source ) {
  20372. Material.prototype.copy.call( this, source );
  20373. this.color.copy( source.color );
  20374. this.linewidth = source.linewidth;
  20375. this.linecap = source.linecap;
  20376. this.linejoin = source.linejoin;
  20377. return this;
  20378. };
  20379. /**
  20380. * @author mrdoob / http://mrdoob.com/
  20381. */
  20382. function Line( geometry, material, mode ) {
  20383. if ( mode === 1 ) {
  20384. console.error( 'THREE.Line: parameter THREE.LinePieces no longer supported. Use THREE.LineSegments instead.' );
  20385. }
  20386. Object3D.call( this );
  20387. this.type = 'Line';
  20388. this.geometry = geometry !== undefined ? geometry : new BufferGeometry();
  20389. this.material = material !== undefined ? material : new LineBasicMaterial( { color: Math.random() * 0xffffff } );
  20390. }
  20391. Line.prototype = Object.assign( Object.create( Object3D.prototype ), {
  20392. constructor: Line,
  20393. isLine: true,
  20394. computeLineDistances: ( function () {
  20395. var start = new Vector3();
  20396. var end = new Vector3();
  20397. return function computeLineDistances() {
  20398. var geometry = this.geometry;
  20399. if ( geometry.isBufferGeometry ) {
  20400. // we assume non-indexed geometry
  20401. if ( geometry.index === null ) {
  20402. var positionAttribute = geometry.attributes.position;
  20403. var lineDistances = [ 0 ];
  20404. for ( var i = 1, l = positionAttribute.count; i < l; i ++ ) {
  20405. start.fromBufferAttribute( positionAttribute, i - 1 );
  20406. end.fromBufferAttribute( positionAttribute, i );
  20407. lineDistances[ i ] = lineDistances[ i - 1 ];
  20408. lineDistances[ i ] += start.distanceTo( end );
  20409. }
  20410. geometry.addAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  20411. } else {
  20412. console.warn( 'THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  20413. }
  20414. } else if ( geometry.isGeometry ) {
  20415. var vertices = geometry.vertices;
  20416. var lineDistances = geometry.lineDistances;
  20417. lineDistances[ 0 ] = 0;
  20418. for ( var i = 1, l = vertices.length; i < l; i ++ ) {
  20419. lineDistances[ i ] = lineDistances[ i - 1 ];
  20420. lineDistances[ i ] += vertices[ i - 1 ].distanceTo( vertices[ i ] );
  20421. }
  20422. }
  20423. return this;
  20424. };
  20425. }() ),
  20426. raycast: ( function () {
  20427. var inverseMatrix = new Matrix4();
  20428. var ray = new Ray();
  20429. var sphere = new Sphere();
  20430. return function raycast( raycaster, intersects ) {
  20431. var precision = raycaster.linePrecision;
  20432. var geometry = this.geometry;
  20433. var matrixWorld = this.matrixWorld;
  20434. // Checking boundingSphere distance to ray
  20435. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  20436. sphere.copy( geometry.boundingSphere );
  20437. sphere.applyMatrix4( matrixWorld );
  20438. sphere.radius += precision;
  20439. if ( raycaster.ray.intersectsSphere( sphere ) === false ) return;
  20440. //
  20441. inverseMatrix.getInverse( matrixWorld );
  20442. ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  20443. var localPrecision = precision / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  20444. var localPrecisionSq = localPrecision * localPrecision;
  20445. var vStart = new Vector3();
  20446. var vEnd = new Vector3();
  20447. var interSegment = new Vector3();
  20448. var interRay = new Vector3();
  20449. var step = ( this && this.isLineSegments ) ? 2 : 1;
  20450. if ( geometry.isBufferGeometry ) {
  20451. var index = geometry.index;
  20452. var attributes = geometry.attributes;
  20453. var positions = attributes.position.array;
  20454. if ( index !== null ) {
  20455. var indices = index.array;
  20456. for ( var i = 0, l = indices.length - 1; i < l; i += step ) {
  20457. var a = indices[ i ];
  20458. var b = indices[ i + 1 ];
  20459. vStart.fromArray( positions, a * 3 );
  20460. vEnd.fromArray( positions, b * 3 );
  20461. var distSq = ray.distanceSqToSegment( vStart, vEnd, interRay, interSegment );
  20462. if ( distSq > localPrecisionSq ) continue;
  20463. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  20464. var distance = raycaster.ray.origin.distanceTo( interRay );
  20465. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  20466. intersects.push( {
  20467. distance: distance,
  20468. // What do we want? intersection point on the ray or on the segment??
  20469. // point: raycaster.ray.at( distance ),
  20470. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  20471. index: i,
  20472. face: null,
  20473. faceIndex: null,
  20474. object: this
  20475. } );
  20476. }
  20477. } else {
  20478. for ( var i = 0, l = positions.length / 3 - 1; i < l; i += step ) {
  20479. vStart.fromArray( positions, 3 * i );
  20480. vEnd.fromArray( positions, 3 * i + 3 );
  20481. var distSq = ray.distanceSqToSegment( vStart, vEnd, interRay, interSegment );
  20482. if ( distSq > localPrecisionSq ) continue;
  20483. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  20484. var distance = raycaster.ray.origin.distanceTo( interRay );
  20485. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  20486. intersects.push( {
  20487. distance: distance,
  20488. // What do we want? intersection point on the ray or on the segment??
  20489. // point: raycaster.ray.at( distance ),
  20490. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  20491. index: i,
  20492. face: null,
  20493. faceIndex: null,
  20494. object: this
  20495. } );
  20496. }
  20497. }
  20498. } else if ( geometry.isGeometry ) {
  20499. var vertices = geometry.vertices;
  20500. var nbVertices = vertices.length;
  20501. for ( var i = 0; i < nbVertices - 1; i += step ) {
  20502. var distSq = ray.distanceSqToSegment( vertices[ i ], vertices[ i + 1 ], interRay, interSegment );
  20503. if ( distSq > localPrecisionSq ) continue;
  20504. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  20505. var distance = raycaster.ray.origin.distanceTo( interRay );
  20506. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  20507. intersects.push( {
  20508. distance: distance,
  20509. // What do we want? intersection point on the ray or on the segment??
  20510. // point: raycaster.ray.at( distance ),
  20511. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  20512. index: i,
  20513. face: null,
  20514. faceIndex: null,
  20515. object: this
  20516. } );
  20517. }
  20518. }
  20519. };
  20520. }() ),
  20521. clone: function () {
  20522. return new this.constructor( this.geometry, this.material ).copy( this );
  20523. }
  20524. } );
  20525. /**
  20526. * @author mrdoob / http://mrdoob.com/
  20527. */
  20528. function LineSegments( geometry, material ) {
  20529. Line.call( this, geometry, material );
  20530. this.type = 'LineSegments';
  20531. }
  20532. LineSegments.prototype = Object.assign( Object.create( Line.prototype ), {
  20533. constructor: LineSegments,
  20534. isLineSegments: true,
  20535. computeLineDistances: ( function () {
  20536. var start = new Vector3();
  20537. var end = new Vector3();
  20538. return function computeLineDistances() {
  20539. var geometry = this.geometry;
  20540. if ( geometry.isBufferGeometry ) {
  20541. // we assume non-indexed geometry
  20542. if ( geometry.index === null ) {
  20543. var positionAttribute = geometry.attributes.position;
  20544. var lineDistances = [];
  20545. for ( var i = 0, l = positionAttribute.count; i < l; i += 2 ) {
  20546. start.fromBufferAttribute( positionAttribute, i );
  20547. end.fromBufferAttribute( positionAttribute, i + 1 );
  20548. lineDistances[ i ] = ( i === 0 ) ? 0 : lineDistances[ i - 1 ];
  20549. lineDistances[ i + 1 ] = lineDistances[ i ] + start.distanceTo( end );
  20550. }
  20551. geometry.addAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  20552. } else {
  20553. console.warn( 'THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  20554. }
  20555. } else if ( geometry.isGeometry ) {
  20556. var vertices = geometry.vertices;
  20557. var lineDistances = geometry.lineDistances;
  20558. for ( var i = 0, l = vertices.length; i < l; i += 2 ) {
  20559. start.copy( vertices[ i ] );
  20560. end.copy( vertices[ i + 1 ] );
  20561. lineDistances[ i ] = ( i === 0 ) ? 0 : lineDistances[ i - 1 ];
  20562. lineDistances[ i + 1 ] = lineDistances[ i ] + start.distanceTo( end );
  20563. }
  20564. }
  20565. return this;
  20566. };
  20567. }() )
  20568. } );
  20569. /**
  20570. * @author mgreter / http://github.com/mgreter
  20571. */
  20572. function LineLoop( geometry, material ) {
  20573. Line.call( this, geometry, material );
  20574. this.type = 'LineLoop';
  20575. }
  20576. LineLoop.prototype = Object.assign( Object.create( Line.prototype ), {
  20577. constructor: LineLoop,
  20578. isLineLoop: true,
  20579. } );
  20580. /**
  20581. * @author mrdoob / http://mrdoob.com/
  20582. * @author alteredq / http://alteredqualia.com/
  20583. *
  20584. * parameters = {
  20585. * color: <hex>,
  20586. * opacity: <float>,
  20587. * map: new THREE.Texture( <Image> ),
  20588. *
  20589. * size: <float>,
  20590. * sizeAttenuation: <bool>
  20591. *
  20592. * morphTargets: <bool>
  20593. * }
  20594. */
  20595. function PointsMaterial( parameters ) {
  20596. Material.call( this );
  20597. this.type = 'PointsMaterial';
  20598. this.color = new Color( 0xffffff );
  20599. this.map = null;
  20600. this.size = 1;
  20601. this.sizeAttenuation = true;
  20602. this.morphTargets = false;
  20603. this.lights = false;
  20604. this.setValues( parameters );
  20605. }
  20606. PointsMaterial.prototype = Object.create( Material.prototype );
  20607. PointsMaterial.prototype.constructor = PointsMaterial;
  20608. PointsMaterial.prototype.isPointsMaterial = true;
  20609. PointsMaterial.prototype.copy = function ( source ) {
  20610. Material.prototype.copy.call( this, source );
  20611. this.color.copy( source.color );
  20612. this.map = source.map;
  20613. this.size = source.size;
  20614. this.sizeAttenuation = source.sizeAttenuation;
  20615. this.morphTargets = source.morphTargets;
  20616. return this;
  20617. };
  20618. /**
  20619. * @author alteredq / http://alteredqualia.com/
  20620. */
  20621. function Points( geometry, material ) {
  20622. Object3D.call( this );
  20623. this.type = 'Points';
  20624. this.geometry = geometry !== undefined ? geometry : new BufferGeometry();
  20625. this.material = material !== undefined ? material : new PointsMaterial( { color: Math.random() * 0xffffff } );
  20626. }
  20627. Points.prototype = Object.assign( Object.create( Object3D.prototype ), {
  20628. constructor: Points,
  20629. isPoints: true,
  20630. raycast: ( function () {
  20631. var inverseMatrix = new Matrix4();
  20632. var ray = new Ray();
  20633. var sphere = new Sphere();
  20634. return function raycast( raycaster, intersects ) {
  20635. var object = this;
  20636. var geometry = this.geometry;
  20637. var matrixWorld = this.matrixWorld;
  20638. var threshold = raycaster.params.Points.threshold;
  20639. // Checking boundingSphere distance to ray
  20640. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  20641. sphere.copy( geometry.boundingSphere );
  20642. sphere.applyMatrix4( matrixWorld );
  20643. sphere.radius += threshold;
  20644. if ( raycaster.ray.intersectsSphere( sphere ) === false ) return;
  20645. //
  20646. inverseMatrix.getInverse( matrixWorld );
  20647. ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  20648. var localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  20649. var localThresholdSq = localThreshold * localThreshold;
  20650. var position = new Vector3();
  20651. var intersectPoint = new Vector3();
  20652. function testPoint( point, index ) {
  20653. var rayPointDistanceSq = ray.distanceSqToPoint( point );
  20654. if ( rayPointDistanceSq < localThresholdSq ) {
  20655. ray.closestPointToPoint( point, intersectPoint );
  20656. intersectPoint.applyMatrix4( matrixWorld );
  20657. var distance = raycaster.ray.origin.distanceTo( intersectPoint );
  20658. if ( distance < raycaster.near || distance > raycaster.far ) return;
  20659. intersects.push( {
  20660. distance: distance,
  20661. distanceToRay: Math.sqrt( rayPointDistanceSq ),
  20662. point: intersectPoint.clone(),
  20663. index: index,
  20664. face: null,
  20665. object: object
  20666. } );
  20667. }
  20668. }
  20669. if ( geometry.isBufferGeometry ) {
  20670. var index = geometry.index;
  20671. var attributes = geometry.attributes;
  20672. var positions = attributes.position.array;
  20673. if ( index !== null ) {
  20674. var indices = index.array;
  20675. for ( var i = 0, il = indices.length; i < il; i ++ ) {
  20676. var a = indices[ i ];
  20677. position.fromArray( positions, a * 3 );
  20678. testPoint( position, a );
  20679. }
  20680. } else {
  20681. for ( var i = 0, l = positions.length / 3; i < l; i ++ ) {
  20682. position.fromArray( positions, i * 3 );
  20683. testPoint( position, i );
  20684. }
  20685. }
  20686. } else {
  20687. var vertices = geometry.vertices;
  20688. for ( var i = 0, l = vertices.length; i < l; i ++ ) {
  20689. testPoint( vertices[ i ], i );
  20690. }
  20691. }
  20692. };
  20693. }() ),
  20694. clone: function () {
  20695. return new this.constructor( this.geometry, this.material ).copy( this );
  20696. }
  20697. } );
  20698. /**
  20699. * @author mrdoob / http://mrdoob.com/
  20700. */
  20701. function VideoTexture( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  20702. Texture.call( this, video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  20703. this.format = format !== undefined ? format : RGBFormat;
  20704. this.minFilter = minFilter !== undefined ? minFilter : LinearFilter;
  20705. this.magFilter = magFilter !== undefined ? magFilter : LinearFilter;
  20706. this.generateMipmaps = false;
  20707. }
  20708. VideoTexture.prototype = Object.assign( Object.create( Texture.prototype ), {
  20709. constructor: VideoTexture,
  20710. isVideoTexture: true,
  20711. update: function () {
  20712. var video = this.image;
  20713. if ( video.readyState >= video.HAVE_CURRENT_DATA ) {
  20714. this.needsUpdate = true;
  20715. }
  20716. }
  20717. } );
  20718. /**
  20719. * @author alteredq / http://alteredqualia.com/
  20720. */
  20721. function CompressedTexture( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding ) {
  20722. Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  20723. this.image = { width: width, height: height };
  20724. this.mipmaps = mipmaps;
  20725. // no flipping for cube textures
  20726. // (also flipping doesn't work for compressed textures )
  20727. this.flipY = false;
  20728. // can't generate mipmaps for compressed textures
  20729. // mips must be embedded in DDS files
  20730. this.generateMipmaps = false;
  20731. }
  20732. CompressedTexture.prototype = Object.create( Texture.prototype );
  20733. CompressedTexture.prototype.constructor = CompressedTexture;
  20734. CompressedTexture.prototype.isCompressedTexture = true;
  20735. /**
  20736. * @author mrdoob / http://mrdoob.com/
  20737. */
  20738. function CanvasTexture( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  20739. Texture.call( this, canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  20740. this.needsUpdate = true;
  20741. }
  20742. CanvasTexture.prototype = Object.create( Texture.prototype );
  20743. CanvasTexture.prototype.constructor = CanvasTexture;
  20744. CanvasTexture.prototype.isCanvasTexture = true;
  20745. /**
  20746. * @author Matt DesLauriers / @mattdesl
  20747. * @author atix / arthursilber.de
  20748. */
  20749. function DepthTexture( width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format ) {
  20750. format = format !== undefined ? format : DepthFormat;
  20751. if ( format !== DepthFormat && format !== DepthStencilFormat ) {
  20752. throw new Error( 'DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat' );
  20753. }
  20754. if ( type === undefined && format === DepthFormat ) type = UnsignedShortType;
  20755. if ( type === undefined && format === DepthStencilFormat ) type = UnsignedInt248Type;
  20756. Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  20757. this.image = { width: width, height: height };
  20758. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  20759. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  20760. this.flipY = false;
  20761. this.generateMipmaps = false;
  20762. }
  20763. DepthTexture.prototype = Object.create( Texture.prototype );
  20764. DepthTexture.prototype.constructor = DepthTexture;
  20765. DepthTexture.prototype.isDepthTexture = true;
  20766. /**
  20767. * @author mrdoob / http://mrdoob.com/
  20768. * @author Mugen87 / https://github.com/Mugen87
  20769. */
  20770. function WireframeGeometry( geometry ) {
  20771. BufferGeometry.call( this );
  20772. this.type = 'WireframeGeometry';
  20773. // buffer
  20774. var vertices = [];
  20775. // helper variables
  20776. var i, j, l, o, ol;
  20777. var edge = [ 0, 0 ], edges = {}, e, edge1, edge2;
  20778. var key, keys = [ 'a', 'b', 'c' ];
  20779. var vertex;
  20780. // different logic for Geometry and BufferGeometry
  20781. if ( geometry && geometry.isGeometry ) {
  20782. // create a data structure that contains all edges without duplicates
  20783. var faces = geometry.faces;
  20784. for ( i = 0, l = faces.length; i < l; i ++ ) {
  20785. var face = faces[ i ];
  20786. for ( j = 0; j < 3; j ++ ) {
  20787. edge1 = face[ keys[ j ] ];
  20788. edge2 = face[ keys[ ( j + 1 ) % 3 ] ];
  20789. edge[ 0 ] = Math.min( edge1, edge2 ); // sorting prevents duplicates
  20790. edge[ 1 ] = Math.max( edge1, edge2 );
  20791. key = edge[ 0 ] + ',' + edge[ 1 ];
  20792. if ( edges[ key ] === undefined ) {
  20793. edges[ key ] = { index1: edge[ 0 ], index2: edge[ 1 ] };
  20794. }
  20795. }
  20796. }
  20797. // generate vertices
  20798. for ( key in edges ) {
  20799. e = edges[ key ];
  20800. vertex = geometry.vertices[ e.index1 ];
  20801. vertices.push( vertex.x, vertex.y, vertex.z );
  20802. vertex = geometry.vertices[ e.index2 ];
  20803. vertices.push( vertex.x, vertex.y, vertex.z );
  20804. }
  20805. } else if ( geometry && geometry.isBufferGeometry ) {
  20806. var position, indices, groups;
  20807. var group, start, count;
  20808. var index1, index2;
  20809. vertex = new Vector3();
  20810. if ( geometry.index !== null ) {
  20811. // indexed BufferGeometry
  20812. position = geometry.attributes.position;
  20813. indices = geometry.index;
  20814. groups = geometry.groups;
  20815. if ( groups.length === 0 ) {
  20816. groups = [ { start: 0, count: indices.count, materialIndex: 0 } ];
  20817. }
  20818. // create a data structure that contains all eges without duplicates
  20819. for ( o = 0, ol = groups.length; o < ol; ++ o ) {
  20820. group = groups[ o ];
  20821. start = group.start;
  20822. count = group.count;
  20823. for ( i = start, l = ( start + count ); i < l; i += 3 ) {
  20824. for ( j = 0; j < 3; j ++ ) {
  20825. edge1 = indices.getX( i + j );
  20826. edge2 = indices.getX( i + ( j + 1 ) % 3 );
  20827. edge[ 0 ] = Math.min( edge1, edge2 ); // sorting prevents duplicates
  20828. edge[ 1 ] = Math.max( edge1, edge2 );
  20829. key = edge[ 0 ] + ',' + edge[ 1 ];
  20830. if ( edges[ key ] === undefined ) {
  20831. edges[ key ] = { index1: edge[ 0 ], index2: edge[ 1 ] };
  20832. }
  20833. }
  20834. }
  20835. }
  20836. // generate vertices
  20837. for ( key in edges ) {
  20838. e = edges[ key ];
  20839. vertex.fromBufferAttribute( position, e.index1 );
  20840. vertices.push( vertex.x, vertex.y, vertex.z );
  20841. vertex.fromBufferAttribute( position, e.index2 );
  20842. vertices.push( vertex.x, vertex.y, vertex.z );
  20843. }
  20844. } else {
  20845. // non-indexed BufferGeometry
  20846. position = geometry.attributes.position;
  20847. for ( i = 0, l = ( position.count / 3 ); i < l; i ++ ) {
  20848. for ( j = 0; j < 3; j ++ ) {
  20849. // three edges per triangle, an edge is represented as (index1, index2)
  20850. // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0)
  20851. index1 = 3 * i + j;
  20852. vertex.fromBufferAttribute( position, index1 );
  20853. vertices.push( vertex.x, vertex.y, vertex.z );
  20854. index2 = 3 * i + ( ( j + 1 ) % 3 );
  20855. vertex.fromBufferAttribute( position, index2 );
  20856. vertices.push( vertex.x, vertex.y, vertex.z );
  20857. }
  20858. }
  20859. }
  20860. }
  20861. // build geometry
  20862. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20863. }
  20864. WireframeGeometry.prototype = Object.create( BufferGeometry.prototype );
  20865. WireframeGeometry.prototype.constructor = WireframeGeometry;
  20866. /**
  20867. * @author zz85 / https://github.com/zz85
  20868. * @author Mugen87 / https://github.com/Mugen87
  20869. *
  20870. * Parametric Surfaces Geometry
  20871. * based on the brilliant article by @prideout http://prideout.net/blog/?p=44
  20872. */
  20873. // ParametricGeometry
  20874. function ParametricGeometry( func, slices, stacks ) {
  20875. Geometry.call( this );
  20876. this.type = 'ParametricGeometry';
  20877. this.parameters = {
  20878. func: func,
  20879. slices: slices,
  20880. stacks: stacks
  20881. };
  20882. this.fromBufferGeometry( new ParametricBufferGeometry( func, slices, stacks ) );
  20883. this.mergeVertices();
  20884. }
  20885. ParametricGeometry.prototype = Object.create( Geometry.prototype );
  20886. ParametricGeometry.prototype.constructor = ParametricGeometry;
  20887. // ParametricBufferGeometry
  20888. function ParametricBufferGeometry( func, slices, stacks ) {
  20889. BufferGeometry.call( this );
  20890. this.type = 'ParametricBufferGeometry';
  20891. this.parameters = {
  20892. func: func,
  20893. slices: slices,
  20894. stacks: stacks
  20895. };
  20896. // buffers
  20897. var indices = [];
  20898. var vertices = [];
  20899. var normals = [];
  20900. var uvs = [];
  20901. var EPS = 0.00001;
  20902. var normal = new Vector3();
  20903. var p0 = new Vector3(), p1 = new Vector3();
  20904. var pu = new Vector3(), pv = new Vector3();
  20905. var i, j;
  20906. if ( func.length < 3 ) {
  20907. console.error( 'THREE.ParametricGeometry: Function must now modify a Vector3 as third parameter.' );
  20908. }
  20909. // generate vertices, normals and uvs
  20910. var sliceCount = slices + 1;
  20911. for ( i = 0; i <= stacks; i ++ ) {
  20912. var v = i / stacks;
  20913. for ( j = 0; j <= slices; j ++ ) {
  20914. var u = j / slices;
  20915. // vertex
  20916. func( u, v, p0 );
  20917. vertices.push( p0.x, p0.y, p0.z );
  20918. // normal
  20919. // approximate tangent vectors via finite differences
  20920. if ( u - EPS >= 0 ) {
  20921. func( u - EPS, v, p1 );
  20922. pu.subVectors( p0, p1 );
  20923. } else {
  20924. func( u + EPS, v, p1 );
  20925. pu.subVectors( p1, p0 );
  20926. }
  20927. if ( v - EPS >= 0 ) {
  20928. func( u, v - EPS, p1 );
  20929. pv.subVectors( p0, p1 );
  20930. } else {
  20931. func( u, v + EPS, p1 );
  20932. pv.subVectors( p1, p0 );
  20933. }
  20934. // cross product of tangent vectors returns surface normal
  20935. normal.crossVectors( pu, pv ).normalize();
  20936. normals.push( normal.x, normal.y, normal.z );
  20937. // uv
  20938. uvs.push( u, v );
  20939. }
  20940. }
  20941. // generate indices
  20942. for ( i = 0; i < stacks; i ++ ) {
  20943. for ( j = 0; j < slices; j ++ ) {
  20944. var a = i * sliceCount + j;
  20945. var b = i * sliceCount + j + 1;
  20946. var c = ( i + 1 ) * sliceCount + j + 1;
  20947. var d = ( i + 1 ) * sliceCount + j;
  20948. // faces one and two
  20949. indices.push( a, b, d );
  20950. indices.push( b, c, d );
  20951. }
  20952. }
  20953. // build geometry
  20954. this.setIndex( indices );
  20955. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20956. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  20957. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  20958. }
  20959. ParametricBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  20960. ParametricBufferGeometry.prototype.constructor = ParametricBufferGeometry;
  20961. /**
  20962. * @author clockworkgeek / https://github.com/clockworkgeek
  20963. * @author timothypratley / https://github.com/timothypratley
  20964. * @author WestLangley / http://github.com/WestLangley
  20965. * @author Mugen87 / https://github.com/Mugen87
  20966. */
  20967. // PolyhedronGeometry
  20968. function PolyhedronGeometry( vertices, indices, radius, detail ) {
  20969. Geometry.call( this );
  20970. this.type = 'PolyhedronGeometry';
  20971. this.parameters = {
  20972. vertices: vertices,
  20973. indices: indices,
  20974. radius: radius,
  20975. detail: detail
  20976. };
  20977. this.fromBufferGeometry( new PolyhedronBufferGeometry( vertices, indices, radius, detail ) );
  20978. this.mergeVertices();
  20979. }
  20980. PolyhedronGeometry.prototype = Object.create( Geometry.prototype );
  20981. PolyhedronGeometry.prototype.constructor = PolyhedronGeometry;
  20982. // PolyhedronBufferGeometry
  20983. function PolyhedronBufferGeometry( vertices, indices, radius, detail ) {
  20984. BufferGeometry.call( this );
  20985. this.type = 'PolyhedronBufferGeometry';
  20986. this.parameters = {
  20987. vertices: vertices,
  20988. indices: indices,
  20989. radius: radius,
  20990. detail: detail
  20991. };
  20992. radius = radius || 1;
  20993. detail = detail || 0;
  20994. // default buffer data
  20995. var vertexBuffer = [];
  20996. var uvBuffer = [];
  20997. // the subdivision creates the vertex buffer data
  20998. subdivide( detail );
  20999. // all vertices should lie on a conceptual sphere with a given radius
  21000. appplyRadius( radius );
  21001. // finally, create the uv data
  21002. generateUVs();
  21003. // build non-indexed geometry
  21004. this.addAttribute( 'position', new Float32BufferAttribute( vertexBuffer, 3 ) );
  21005. this.addAttribute( 'normal', new Float32BufferAttribute( vertexBuffer.slice(), 3 ) );
  21006. this.addAttribute( 'uv', new Float32BufferAttribute( uvBuffer, 2 ) );
  21007. if ( detail === 0 ) {
  21008. this.computeVertexNormals(); // flat normals
  21009. } else {
  21010. this.normalizeNormals(); // smooth normals
  21011. }
  21012. // helper functions
  21013. function subdivide( detail ) {
  21014. var a = new Vector3();
  21015. var b = new Vector3();
  21016. var c = new Vector3();
  21017. // iterate over all faces and apply a subdivison with the given detail value
  21018. for ( var i = 0; i < indices.length; i += 3 ) {
  21019. // get the vertices of the face
  21020. getVertexByIndex( indices[ i + 0 ], a );
  21021. getVertexByIndex( indices[ i + 1 ], b );
  21022. getVertexByIndex( indices[ i + 2 ], c );
  21023. // perform subdivision
  21024. subdivideFace( a, b, c, detail );
  21025. }
  21026. }
  21027. function subdivideFace( a, b, c, detail ) {
  21028. var cols = Math.pow( 2, detail );
  21029. // we use this multidimensional array as a data structure for creating the subdivision
  21030. var v = [];
  21031. var i, j;
  21032. // construct all of the vertices for this subdivision
  21033. for ( i = 0; i <= cols; i ++ ) {
  21034. v[ i ] = [];
  21035. var aj = a.clone().lerp( c, i / cols );
  21036. var bj = b.clone().lerp( c, i / cols );
  21037. var rows = cols - i;
  21038. for ( j = 0; j <= rows; j ++ ) {
  21039. if ( j === 0 && i === cols ) {
  21040. v[ i ][ j ] = aj;
  21041. } else {
  21042. v[ i ][ j ] = aj.clone().lerp( bj, j / rows );
  21043. }
  21044. }
  21045. }
  21046. // construct all of the faces
  21047. for ( i = 0; i < cols; i ++ ) {
  21048. for ( j = 0; j < 2 * ( cols - i ) - 1; j ++ ) {
  21049. var k = Math.floor( j / 2 );
  21050. if ( j % 2 === 0 ) {
  21051. pushVertex( v[ i ][ k + 1 ] );
  21052. pushVertex( v[ i + 1 ][ k ] );
  21053. pushVertex( v[ i ][ k ] );
  21054. } else {
  21055. pushVertex( v[ i ][ k + 1 ] );
  21056. pushVertex( v[ i + 1 ][ k + 1 ] );
  21057. pushVertex( v[ i + 1 ][ k ] );
  21058. }
  21059. }
  21060. }
  21061. }
  21062. function appplyRadius( radius ) {
  21063. var vertex = new Vector3();
  21064. // iterate over the entire buffer and apply the radius to each vertex
  21065. for ( var i = 0; i < vertexBuffer.length; i += 3 ) {
  21066. vertex.x = vertexBuffer[ i + 0 ];
  21067. vertex.y = vertexBuffer[ i + 1 ];
  21068. vertex.z = vertexBuffer[ i + 2 ];
  21069. vertex.normalize().multiplyScalar( radius );
  21070. vertexBuffer[ i + 0 ] = vertex.x;
  21071. vertexBuffer[ i + 1 ] = vertex.y;
  21072. vertexBuffer[ i + 2 ] = vertex.z;
  21073. }
  21074. }
  21075. function generateUVs() {
  21076. var vertex = new Vector3();
  21077. for ( var i = 0; i < vertexBuffer.length; i += 3 ) {
  21078. vertex.x = vertexBuffer[ i + 0 ];
  21079. vertex.y = vertexBuffer[ i + 1 ];
  21080. vertex.z = vertexBuffer[ i + 2 ];
  21081. var u = azimuth( vertex ) / 2 / Math.PI + 0.5;
  21082. var v = inclination( vertex ) / Math.PI + 0.5;
  21083. uvBuffer.push( u, 1 - v );
  21084. }
  21085. correctUVs();
  21086. correctSeam();
  21087. }
  21088. function correctSeam() {
  21089. // handle case when face straddles the seam, see #3269
  21090. for ( var i = 0; i < uvBuffer.length; i += 6 ) {
  21091. // uv data of a single face
  21092. var x0 = uvBuffer[ i + 0 ];
  21093. var x1 = uvBuffer[ i + 2 ];
  21094. var x2 = uvBuffer[ i + 4 ];
  21095. var max = Math.max( x0, x1, x2 );
  21096. var min = Math.min( x0, x1, x2 );
  21097. // 0.9 is somewhat arbitrary
  21098. if ( max > 0.9 && min < 0.1 ) {
  21099. if ( x0 < 0.2 ) uvBuffer[ i + 0 ] += 1;
  21100. if ( x1 < 0.2 ) uvBuffer[ i + 2 ] += 1;
  21101. if ( x2 < 0.2 ) uvBuffer[ i + 4 ] += 1;
  21102. }
  21103. }
  21104. }
  21105. function pushVertex( vertex ) {
  21106. vertexBuffer.push( vertex.x, vertex.y, vertex.z );
  21107. }
  21108. function getVertexByIndex( index, vertex ) {
  21109. var stride = index * 3;
  21110. vertex.x = vertices[ stride + 0 ];
  21111. vertex.y = vertices[ stride + 1 ];
  21112. vertex.z = vertices[ stride + 2 ];
  21113. }
  21114. function correctUVs() {
  21115. var a = new Vector3();
  21116. var b = new Vector3();
  21117. var c = new Vector3();
  21118. var centroid = new Vector3();
  21119. var uvA = new Vector2();
  21120. var uvB = new Vector2();
  21121. var uvC = new Vector2();
  21122. for ( var i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6 ) {
  21123. a.set( vertexBuffer[ i + 0 ], vertexBuffer[ i + 1 ], vertexBuffer[ i + 2 ] );
  21124. b.set( vertexBuffer[ i + 3 ], vertexBuffer[ i + 4 ], vertexBuffer[ i + 5 ] );
  21125. c.set( vertexBuffer[ i + 6 ], vertexBuffer[ i + 7 ], vertexBuffer[ i + 8 ] );
  21126. uvA.set( uvBuffer[ j + 0 ], uvBuffer[ j + 1 ] );
  21127. uvB.set( uvBuffer[ j + 2 ], uvBuffer[ j + 3 ] );
  21128. uvC.set( uvBuffer[ j + 4 ], uvBuffer[ j + 5 ] );
  21129. centroid.copy( a ).add( b ).add( c ).divideScalar( 3 );
  21130. var azi = azimuth( centroid );
  21131. correctUV( uvA, j + 0, a, azi );
  21132. correctUV( uvB, j + 2, b, azi );
  21133. correctUV( uvC, j + 4, c, azi );
  21134. }
  21135. }
  21136. function correctUV( uv, stride, vector, azimuth ) {
  21137. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) {
  21138. uvBuffer[ stride ] = uv.x - 1;
  21139. }
  21140. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) {
  21141. uvBuffer[ stride ] = azimuth / 2 / Math.PI + 0.5;
  21142. }
  21143. }
  21144. // Angle around the Y axis, counter-clockwise when looking from above.
  21145. function azimuth( vector ) {
  21146. return Math.atan2( vector.z, - vector.x );
  21147. }
  21148. // Angle above the XZ plane.
  21149. function inclination( vector ) {
  21150. return Math.atan2( - vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  21151. }
  21152. }
  21153. PolyhedronBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  21154. PolyhedronBufferGeometry.prototype.constructor = PolyhedronBufferGeometry;
  21155. /**
  21156. * @author timothypratley / https://github.com/timothypratley
  21157. * @author Mugen87 / https://github.com/Mugen87
  21158. */
  21159. // TetrahedronGeometry
  21160. function TetrahedronGeometry( radius, detail ) {
  21161. Geometry.call( this );
  21162. this.type = 'TetrahedronGeometry';
  21163. this.parameters = {
  21164. radius: radius,
  21165. detail: detail
  21166. };
  21167. this.fromBufferGeometry( new TetrahedronBufferGeometry( radius, detail ) );
  21168. this.mergeVertices();
  21169. }
  21170. TetrahedronGeometry.prototype = Object.create( Geometry.prototype );
  21171. TetrahedronGeometry.prototype.constructor = TetrahedronGeometry;
  21172. // TetrahedronBufferGeometry
  21173. function TetrahedronBufferGeometry( radius, detail ) {
  21174. var vertices = [
  21175. 1, 1, 1, - 1, - 1, 1, - 1, 1, - 1, 1, - 1, - 1
  21176. ];
  21177. var indices = [
  21178. 2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1
  21179. ];
  21180. PolyhedronBufferGeometry.call( this, vertices, indices, radius, detail );
  21181. this.type = 'TetrahedronBufferGeometry';
  21182. this.parameters = {
  21183. radius: radius,
  21184. detail: detail
  21185. };
  21186. }
  21187. TetrahedronBufferGeometry.prototype = Object.create( PolyhedronBufferGeometry.prototype );
  21188. TetrahedronBufferGeometry.prototype.constructor = TetrahedronBufferGeometry;
  21189. /**
  21190. * @author timothypratley / https://github.com/timothypratley
  21191. * @author Mugen87 / https://github.com/Mugen87
  21192. */
  21193. // OctahedronGeometry
  21194. function OctahedronGeometry( radius, detail ) {
  21195. Geometry.call( this );
  21196. this.type = 'OctahedronGeometry';
  21197. this.parameters = {
  21198. radius: radius,
  21199. detail: detail
  21200. };
  21201. this.fromBufferGeometry( new OctahedronBufferGeometry( radius, detail ) );
  21202. this.mergeVertices();
  21203. }
  21204. OctahedronGeometry.prototype = Object.create( Geometry.prototype );
  21205. OctahedronGeometry.prototype.constructor = OctahedronGeometry;
  21206. // OctahedronBufferGeometry
  21207. function OctahedronBufferGeometry( radius, detail ) {
  21208. var vertices = [
  21209. 1, 0, 0, - 1, 0, 0, 0, 1, 0,
  21210. 0, - 1, 0, 0, 0, 1, 0, 0, - 1
  21211. ];
  21212. var indices = [
  21213. 0, 2, 4, 0, 4, 3, 0, 3, 5,
  21214. 0, 5, 2, 1, 2, 5, 1, 5, 3,
  21215. 1, 3, 4, 1, 4, 2
  21216. ];
  21217. PolyhedronBufferGeometry.call( this, vertices, indices, radius, detail );
  21218. this.type = 'OctahedronBufferGeometry';
  21219. this.parameters = {
  21220. radius: radius,
  21221. detail: detail
  21222. };
  21223. }
  21224. OctahedronBufferGeometry.prototype = Object.create( PolyhedronBufferGeometry.prototype );
  21225. OctahedronBufferGeometry.prototype.constructor = OctahedronBufferGeometry;
  21226. /**
  21227. * @author timothypratley / https://github.com/timothypratley
  21228. * @author Mugen87 / https://github.com/Mugen87
  21229. */
  21230. // IcosahedronGeometry
  21231. function IcosahedronGeometry( radius, detail ) {
  21232. Geometry.call( this );
  21233. this.type = 'IcosahedronGeometry';
  21234. this.parameters = {
  21235. radius: radius,
  21236. detail: detail
  21237. };
  21238. this.fromBufferGeometry( new IcosahedronBufferGeometry( radius, detail ) );
  21239. this.mergeVertices();
  21240. }
  21241. IcosahedronGeometry.prototype = Object.create( Geometry.prototype );
  21242. IcosahedronGeometry.prototype.constructor = IcosahedronGeometry;
  21243. // IcosahedronBufferGeometry
  21244. function IcosahedronBufferGeometry( radius, detail ) {
  21245. var t = ( 1 + Math.sqrt( 5 ) ) / 2;
  21246. var vertices = [
  21247. - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t, 0,
  21248. 0, - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t,
  21249. t, 0, - 1, t, 0, 1, - t, 0, - 1, - t, 0, 1
  21250. ];
  21251. var indices = [
  21252. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11,
  21253. 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8,
  21254. 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9,
  21255. 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1
  21256. ];
  21257. PolyhedronBufferGeometry.call( this, vertices, indices, radius, detail );
  21258. this.type = 'IcosahedronBufferGeometry';
  21259. this.parameters = {
  21260. radius: radius,
  21261. detail: detail
  21262. };
  21263. }
  21264. IcosahedronBufferGeometry.prototype = Object.create( PolyhedronBufferGeometry.prototype );
  21265. IcosahedronBufferGeometry.prototype.constructor = IcosahedronBufferGeometry;
  21266. /**
  21267. * @author Abe Pazos / https://hamoid.com
  21268. * @author Mugen87 / https://github.com/Mugen87
  21269. */
  21270. // DodecahedronGeometry
  21271. function DodecahedronGeometry( radius, detail ) {
  21272. Geometry.call( this );
  21273. this.type = 'DodecahedronGeometry';
  21274. this.parameters = {
  21275. radius: radius,
  21276. detail: detail
  21277. };
  21278. this.fromBufferGeometry( new DodecahedronBufferGeometry( radius, detail ) );
  21279. this.mergeVertices();
  21280. }
  21281. DodecahedronGeometry.prototype = Object.create( Geometry.prototype );
  21282. DodecahedronGeometry.prototype.constructor = DodecahedronGeometry;
  21283. // DodecahedronBufferGeometry
  21284. function DodecahedronBufferGeometry( radius, detail ) {
  21285. var t = ( 1 + Math.sqrt( 5 ) ) / 2;
  21286. var r = 1 / t;
  21287. var vertices = [
  21288. // (±1, ±1, ±1)
  21289. - 1, - 1, - 1, - 1, - 1, 1,
  21290. - 1, 1, - 1, - 1, 1, 1,
  21291. 1, - 1, - 1, 1, - 1, 1,
  21292. 1, 1, - 1, 1, 1, 1,
  21293. // (0, ±1/φ, ±φ)
  21294. 0, - r, - t, 0, - r, t,
  21295. 0, r, - t, 0, r, t,
  21296. // (±1/φ, ±φ, 0)
  21297. - r, - t, 0, - r, t, 0,
  21298. r, - t, 0, r, t, 0,
  21299. // (±φ, 0, ±1/φ)
  21300. - t, 0, - r, t, 0, - r,
  21301. - t, 0, r, t, 0, r
  21302. ];
  21303. var indices = [
  21304. 3, 11, 7, 3, 7, 15, 3, 15, 13,
  21305. 7, 19, 17, 7, 17, 6, 7, 6, 15,
  21306. 17, 4, 8, 17, 8, 10, 17, 10, 6,
  21307. 8, 0, 16, 8, 16, 2, 8, 2, 10,
  21308. 0, 12, 1, 0, 1, 18, 0, 18, 16,
  21309. 6, 10, 2, 6, 2, 13, 6, 13, 15,
  21310. 2, 16, 18, 2, 18, 3, 2, 3, 13,
  21311. 18, 1, 9, 18, 9, 11, 18, 11, 3,
  21312. 4, 14, 12, 4, 12, 0, 4, 0, 8,
  21313. 11, 9, 5, 11, 5, 19, 11, 19, 7,
  21314. 19, 5, 14, 19, 14, 4, 19, 4, 17,
  21315. 1, 12, 14, 1, 14, 5, 1, 5, 9
  21316. ];
  21317. PolyhedronBufferGeometry.call( this, vertices, indices, radius, detail );
  21318. this.type = 'DodecahedronBufferGeometry';
  21319. this.parameters = {
  21320. radius: radius,
  21321. detail: detail
  21322. };
  21323. }
  21324. DodecahedronBufferGeometry.prototype = Object.create( PolyhedronBufferGeometry.prototype );
  21325. DodecahedronBufferGeometry.prototype.constructor = DodecahedronBufferGeometry;
  21326. /**
  21327. * @author oosmoxiecode / https://github.com/oosmoxiecode
  21328. * @author WestLangley / https://github.com/WestLangley
  21329. * @author zz85 / https://github.com/zz85
  21330. * @author miningold / https://github.com/miningold
  21331. * @author jonobr1 / https://github.com/jonobr1
  21332. * @author Mugen87 / https://github.com/Mugen87
  21333. *
  21334. */
  21335. // TubeGeometry
  21336. function TubeGeometry( path, tubularSegments, radius, radialSegments, closed, taper ) {
  21337. Geometry.call( this );
  21338. this.type = 'TubeGeometry';
  21339. this.parameters = {
  21340. path: path,
  21341. tubularSegments: tubularSegments,
  21342. radius: radius,
  21343. radialSegments: radialSegments,
  21344. closed: closed
  21345. };
  21346. if ( taper !== undefined ) console.warn( 'THREE.TubeGeometry: taper has been removed.' );
  21347. var bufferGeometry = new TubeBufferGeometry( path, tubularSegments, radius, radialSegments, closed );
  21348. // expose internals
  21349. this.tangents = bufferGeometry.tangents;
  21350. this.normals = bufferGeometry.normals;
  21351. this.binormals = bufferGeometry.binormals;
  21352. // create geometry
  21353. this.fromBufferGeometry( bufferGeometry );
  21354. this.mergeVertices();
  21355. }
  21356. TubeGeometry.prototype = Object.create( Geometry.prototype );
  21357. TubeGeometry.prototype.constructor = TubeGeometry;
  21358. // TubeBufferGeometry
  21359. function TubeBufferGeometry( path, tubularSegments, radius, radialSegments, closed ) {
  21360. BufferGeometry.call( this );
  21361. this.type = 'TubeBufferGeometry';
  21362. this.parameters = {
  21363. path: path,
  21364. tubularSegments: tubularSegments,
  21365. radius: radius,
  21366. radialSegments: radialSegments,
  21367. closed: closed
  21368. };
  21369. tubularSegments = tubularSegments || 64;
  21370. radius = radius || 1;
  21371. radialSegments = radialSegments || 8;
  21372. closed = closed || false;
  21373. var frames = path.computeFrenetFrames( tubularSegments, closed );
  21374. // expose internals
  21375. this.tangents = frames.tangents;
  21376. this.normals = frames.normals;
  21377. this.binormals = frames.binormals;
  21378. // helper variables
  21379. var vertex = new Vector3();
  21380. var normal = new Vector3();
  21381. var uv = new Vector2();
  21382. var P = new Vector3();
  21383. var i, j;
  21384. // buffer
  21385. var vertices = [];
  21386. var normals = [];
  21387. var uvs = [];
  21388. var indices = [];
  21389. // create buffer data
  21390. generateBufferData();
  21391. // build geometry
  21392. this.setIndex( indices );
  21393. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21394. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  21395. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  21396. // functions
  21397. function generateBufferData() {
  21398. for ( i = 0; i < tubularSegments; i ++ ) {
  21399. generateSegment( i );
  21400. }
  21401. // if the geometry is not closed, generate the last row of vertices and normals
  21402. // at the regular position on the given path
  21403. //
  21404. // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ)
  21405. generateSegment( ( closed === false ) ? tubularSegments : 0 );
  21406. // uvs are generated in a separate function.
  21407. // this makes it easy compute correct values for closed geometries
  21408. generateUVs();
  21409. // finally create faces
  21410. generateIndices();
  21411. }
  21412. function generateSegment( i ) {
  21413. // we use getPointAt to sample evenly distributed points from the given path
  21414. P = path.getPointAt( i / tubularSegments, P );
  21415. // retrieve corresponding normal and binormal
  21416. var N = frames.normals[ i ];
  21417. var B = frames.binormals[ i ];
  21418. // generate normals and vertices for the current segment
  21419. for ( j = 0; j <= radialSegments; j ++ ) {
  21420. var v = j / radialSegments * Math.PI * 2;
  21421. var sin = Math.sin( v );
  21422. var cos = - Math.cos( v );
  21423. // normal
  21424. normal.x = ( cos * N.x + sin * B.x );
  21425. normal.y = ( cos * N.y + sin * B.y );
  21426. normal.z = ( cos * N.z + sin * B.z );
  21427. normal.normalize();
  21428. normals.push( normal.x, normal.y, normal.z );
  21429. // vertex
  21430. vertex.x = P.x + radius * normal.x;
  21431. vertex.y = P.y + radius * normal.y;
  21432. vertex.z = P.z + radius * normal.z;
  21433. vertices.push( vertex.x, vertex.y, vertex.z );
  21434. }
  21435. }
  21436. function generateIndices() {
  21437. for ( j = 1; j <= tubularSegments; j ++ ) {
  21438. for ( i = 1; i <= radialSegments; i ++ ) {
  21439. var a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  21440. var b = ( radialSegments + 1 ) * j + ( i - 1 );
  21441. var c = ( radialSegments + 1 ) * j + i;
  21442. var d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  21443. // faces
  21444. indices.push( a, b, d );
  21445. indices.push( b, c, d );
  21446. }
  21447. }
  21448. }
  21449. function generateUVs() {
  21450. for ( i = 0; i <= tubularSegments; i ++ ) {
  21451. for ( j = 0; j <= radialSegments; j ++ ) {
  21452. uv.x = i / tubularSegments;
  21453. uv.y = j / radialSegments;
  21454. uvs.push( uv.x, uv.y );
  21455. }
  21456. }
  21457. }
  21458. }
  21459. TubeBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  21460. TubeBufferGeometry.prototype.constructor = TubeBufferGeometry;
  21461. TubeBufferGeometry.prototype.toJSON = function () {
  21462. var data = BufferGeometry.prototype.toJSON.call( this );
  21463. data.path = this.parameters.path.toJSON();
  21464. return data;
  21465. };
  21466. /**
  21467. * @author oosmoxiecode
  21468. * @author Mugen87 / https://github.com/Mugen87
  21469. *
  21470. * based on http://www.blackpawn.com/texts/pqtorus/
  21471. */
  21472. // TorusKnotGeometry
  21473. function TorusKnotGeometry( radius, tube, tubularSegments, radialSegments, p, q, heightScale ) {
  21474. Geometry.call( this );
  21475. this.type = 'TorusKnotGeometry';
  21476. this.parameters = {
  21477. radius: radius,
  21478. tube: tube,
  21479. tubularSegments: tubularSegments,
  21480. radialSegments: radialSegments,
  21481. p: p,
  21482. q: q
  21483. };
  21484. if ( heightScale !== undefined ) console.warn( 'THREE.TorusKnotGeometry: heightScale has been deprecated. Use .scale( x, y, z ) instead.' );
  21485. this.fromBufferGeometry( new TorusKnotBufferGeometry( radius, tube, tubularSegments, radialSegments, p, q ) );
  21486. this.mergeVertices();
  21487. }
  21488. TorusKnotGeometry.prototype = Object.create( Geometry.prototype );
  21489. TorusKnotGeometry.prototype.constructor = TorusKnotGeometry;
  21490. // TorusKnotBufferGeometry
  21491. function TorusKnotBufferGeometry( radius, tube, tubularSegments, radialSegments, p, q ) {
  21492. BufferGeometry.call( this );
  21493. this.type = 'TorusKnotBufferGeometry';
  21494. this.parameters = {
  21495. radius: radius,
  21496. tube: tube,
  21497. tubularSegments: tubularSegments,
  21498. radialSegments: radialSegments,
  21499. p: p,
  21500. q: q
  21501. };
  21502. radius = radius || 1;
  21503. tube = tube || 0.4;
  21504. tubularSegments = Math.floor( tubularSegments ) || 64;
  21505. radialSegments = Math.floor( radialSegments ) || 8;
  21506. p = p || 2;
  21507. q = q || 3;
  21508. // buffers
  21509. var indices = [];
  21510. var vertices = [];
  21511. var normals = [];
  21512. var uvs = [];
  21513. // helper variables
  21514. var i, j;
  21515. var vertex = new Vector3();
  21516. var normal = new Vector3();
  21517. var P1 = new Vector3();
  21518. var P2 = new Vector3();
  21519. var B = new Vector3();
  21520. var T = new Vector3();
  21521. var N = new Vector3();
  21522. // generate vertices, normals and uvs
  21523. for ( i = 0; i <= tubularSegments; ++ i ) {
  21524. // the radian "u" is used to calculate the position on the torus curve of the current tubular segement
  21525. var u = i / tubularSegments * p * Math.PI * 2;
  21526. // now we calculate two points. P1 is our current position on the curve, P2 is a little farther ahead.
  21527. // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions
  21528. calculatePositionOnCurve( u, p, q, radius, P1 );
  21529. calculatePositionOnCurve( u + 0.01, p, q, radius, P2 );
  21530. // calculate orthonormal basis
  21531. T.subVectors( P2, P1 );
  21532. N.addVectors( P2, P1 );
  21533. B.crossVectors( T, N );
  21534. N.crossVectors( B, T );
  21535. // normalize B, N. T can be ignored, we don't use it
  21536. B.normalize();
  21537. N.normalize();
  21538. for ( j = 0; j <= radialSegments; ++ j ) {
  21539. // now calculate the vertices. they are nothing more than an extrusion of the torus curve.
  21540. // because we extrude a shape in the xy-plane, there is no need to calculate a z-value.
  21541. var v = j / radialSegments * Math.PI * 2;
  21542. var cx = - tube * Math.cos( v );
  21543. var cy = tube * Math.sin( v );
  21544. // now calculate the final vertex position.
  21545. // first we orient the extrusion with our basis vectos, then we add it to the current position on the curve
  21546. vertex.x = P1.x + ( cx * N.x + cy * B.x );
  21547. vertex.y = P1.y + ( cx * N.y + cy * B.y );
  21548. vertex.z = P1.z + ( cx * N.z + cy * B.z );
  21549. vertices.push( vertex.x, vertex.y, vertex.z );
  21550. // normal (P1 is always the center/origin of the extrusion, thus we can use it to calculate the normal)
  21551. normal.subVectors( vertex, P1 ).normalize();
  21552. normals.push( normal.x, normal.y, normal.z );
  21553. // uv
  21554. uvs.push( i / tubularSegments );
  21555. uvs.push( j / radialSegments );
  21556. }
  21557. }
  21558. // generate indices
  21559. for ( j = 1; j <= tubularSegments; j ++ ) {
  21560. for ( i = 1; i <= radialSegments; i ++ ) {
  21561. // indices
  21562. var a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  21563. var b = ( radialSegments + 1 ) * j + ( i - 1 );
  21564. var c = ( radialSegments + 1 ) * j + i;
  21565. var d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  21566. // faces
  21567. indices.push( a, b, d );
  21568. indices.push( b, c, d );
  21569. }
  21570. }
  21571. // build geometry
  21572. this.setIndex( indices );
  21573. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21574. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  21575. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  21576. // this function calculates the current position on the torus curve
  21577. function calculatePositionOnCurve( u, p, q, radius, position ) {
  21578. var cu = Math.cos( u );
  21579. var su = Math.sin( u );
  21580. var quOverP = q / p * u;
  21581. var cs = Math.cos( quOverP );
  21582. position.x = radius * ( 2 + cs ) * 0.5 * cu;
  21583. position.y = radius * ( 2 + cs ) * su * 0.5;
  21584. position.z = radius * Math.sin( quOverP ) * 0.5;
  21585. }
  21586. }
  21587. TorusKnotBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  21588. TorusKnotBufferGeometry.prototype.constructor = TorusKnotBufferGeometry;
  21589. /**
  21590. * @author oosmoxiecode
  21591. * @author mrdoob / http://mrdoob.com/
  21592. * @author Mugen87 / https://github.com/Mugen87
  21593. */
  21594. // TorusGeometry
  21595. function TorusGeometry( radius, tube, radialSegments, tubularSegments, arc ) {
  21596. Geometry.call( this );
  21597. this.type = 'TorusGeometry';
  21598. this.parameters = {
  21599. radius: radius,
  21600. tube: tube,
  21601. radialSegments: radialSegments,
  21602. tubularSegments: tubularSegments,
  21603. arc: arc
  21604. };
  21605. this.fromBufferGeometry( new TorusBufferGeometry( radius, tube, radialSegments, tubularSegments, arc ) );
  21606. this.mergeVertices();
  21607. }
  21608. TorusGeometry.prototype = Object.create( Geometry.prototype );
  21609. TorusGeometry.prototype.constructor = TorusGeometry;
  21610. // TorusBufferGeometry
  21611. function TorusBufferGeometry( radius, tube, radialSegments, tubularSegments, arc ) {
  21612. BufferGeometry.call( this );
  21613. this.type = 'TorusBufferGeometry';
  21614. this.parameters = {
  21615. radius: radius,
  21616. tube: tube,
  21617. radialSegments: radialSegments,
  21618. tubularSegments: tubularSegments,
  21619. arc: arc
  21620. };
  21621. radius = radius || 1;
  21622. tube = tube || 0.4;
  21623. radialSegments = Math.floor( radialSegments ) || 8;
  21624. tubularSegments = Math.floor( tubularSegments ) || 6;
  21625. arc = arc || Math.PI * 2;
  21626. // buffers
  21627. var indices = [];
  21628. var vertices = [];
  21629. var normals = [];
  21630. var uvs = [];
  21631. // helper variables
  21632. var center = new Vector3();
  21633. var vertex = new Vector3();
  21634. var normal = new Vector3();
  21635. var j, i;
  21636. // generate vertices, normals and uvs
  21637. for ( j = 0; j <= radialSegments; j ++ ) {
  21638. for ( i = 0; i <= tubularSegments; i ++ ) {
  21639. var u = i / tubularSegments * arc;
  21640. var v = j / radialSegments * Math.PI * 2;
  21641. // vertex
  21642. vertex.x = ( radius + tube * Math.cos( v ) ) * Math.cos( u );
  21643. vertex.y = ( radius + tube * Math.cos( v ) ) * Math.sin( u );
  21644. vertex.z = tube * Math.sin( v );
  21645. vertices.push( vertex.x, vertex.y, vertex.z );
  21646. // normal
  21647. center.x = radius * Math.cos( u );
  21648. center.y = radius * Math.sin( u );
  21649. normal.subVectors( vertex, center ).normalize();
  21650. normals.push( normal.x, normal.y, normal.z );
  21651. // uv
  21652. uvs.push( i / tubularSegments );
  21653. uvs.push( j / radialSegments );
  21654. }
  21655. }
  21656. // generate indices
  21657. for ( j = 1; j <= radialSegments; j ++ ) {
  21658. for ( i = 1; i <= tubularSegments; i ++ ) {
  21659. // indices
  21660. var a = ( tubularSegments + 1 ) * j + i - 1;
  21661. var b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  21662. var c = ( tubularSegments + 1 ) * ( j - 1 ) + i;
  21663. var d = ( tubularSegments + 1 ) * j + i;
  21664. // faces
  21665. indices.push( a, b, d );
  21666. indices.push( b, c, d );
  21667. }
  21668. }
  21669. // build geometry
  21670. this.setIndex( indices );
  21671. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21672. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  21673. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  21674. }
  21675. TorusBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  21676. TorusBufferGeometry.prototype.constructor = TorusBufferGeometry;
  21677. /**
  21678. * @author Mugen87 / https://github.com/Mugen87
  21679. * Port from https://github.com/mapbox/earcut (v2.1.2)
  21680. */
  21681. var Earcut = {
  21682. triangulate: function ( data, holeIndices, dim ) {
  21683. dim = dim || 2;
  21684. var hasHoles = holeIndices && holeIndices.length,
  21685. outerLen = hasHoles ? holeIndices[ 0 ] * dim : data.length,
  21686. outerNode = linkedList( data, 0, outerLen, dim, true ),
  21687. triangles = [];
  21688. if ( ! outerNode ) return triangles;
  21689. var minX, minY, maxX, maxY, x, y, invSize;
  21690. if ( hasHoles ) outerNode = eliminateHoles( data, holeIndices, outerNode, dim );
  21691. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  21692. if ( data.length > 80 * dim ) {
  21693. minX = maxX = data[ 0 ];
  21694. minY = maxY = data[ 1 ];
  21695. for ( var i = dim; i < outerLen; i += dim ) {
  21696. x = data[ i ];
  21697. y = data[ i + 1 ];
  21698. if ( x < minX ) minX = x;
  21699. if ( y < minY ) minY = y;
  21700. if ( x > maxX ) maxX = x;
  21701. if ( y > maxY ) maxY = y;
  21702. }
  21703. // minX, minY and invSize are later used to transform coords into integers for z-order calculation
  21704. invSize = Math.max( maxX - minX, maxY - minY );
  21705. invSize = invSize !== 0 ? 1 / invSize : 0;
  21706. }
  21707. earcutLinked( outerNode, triangles, dim, minX, minY, invSize );
  21708. return triangles;
  21709. }
  21710. };
  21711. // create a circular doubly linked list from polygon points in the specified winding order
  21712. function linkedList( data, start, end, dim, clockwise ) {
  21713. var i, last;
  21714. if ( clockwise === ( signedArea( data, start, end, dim ) > 0 ) ) {
  21715. for ( i = start; i < end; i += dim ) last = insertNode( i, data[ i ], data[ i + 1 ], last );
  21716. } else {
  21717. for ( i = end - dim; i >= start; i -= dim ) last = insertNode( i, data[ i ], data[ i + 1 ], last );
  21718. }
  21719. if ( last && equals( last, last.next ) ) {
  21720. removeNode( last );
  21721. last = last.next;
  21722. }
  21723. return last;
  21724. }
  21725. // eliminate colinear or duplicate points
  21726. function filterPoints( start, end ) {
  21727. if ( ! start ) return start;
  21728. if ( ! end ) end = start;
  21729. var p = start, again;
  21730. do {
  21731. again = false;
  21732. if ( ! p.steiner && ( equals( p, p.next ) || area( p.prev, p, p.next ) === 0 ) ) {
  21733. removeNode( p );
  21734. p = end = p.prev;
  21735. if ( p === p.next ) break;
  21736. again = true;
  21737. } else {
  21738. p = p.next;
  21739. }
  21740. } while ( again || p !== end );
  21741. return end;
  21742. }
  21743. // main ear slicing loop which triangulates a polygon (given as a linked list)
  21744. function earcutLinked( ear, triangles, dim, minX, minY, invSize, pass ) {
  21745. if ( ! ear ) return;
  21746. // interlink polygon nodes in z-order
  21747. if ( ! pass && invSize ) indexCurve( ear, minX, minY, invSize );
  21748. var stop = ear, prev, next;
  21749. // iterate through ears, slicing them one by one
  21750. while ( ear.prev !== ear.next ) {
  21751. prev = ear.prev;
  21752. next = ear.next;
  21753. if ( invSize ? isEarHashed( ear, minX, minY, invSize ) : isEar( ear ) ) {
  21754. // cut off the triangle
  21755. triangles.push( prev.i / dim );
  21756. triangles.push( ear.i / dim );
  21757. triangles.push( next.i / dim );
  21758. removeNode( ear );
  21759. // skipping the next vertice leads to less sliver triangles
  21760. ear = next.next;
  21761. stop = next.next;
  21762. continue;
  21763. }
  21764. ear = next;
  21765. // if we looped through the whole remaining polygon and can't find any more ears
  21766. if ( ear === stop ) {
  21767. // try filtering points and slicing again
  21768. if ( ! pass ) {
  21769. earcutLinked( filterPoints( ear ), triangles, dim, minX, minY, invSize, 1 );
  21770. // if this didn't work, try curing all small self-intersections locally
  21771. } else if ( pass === 1 ) {
  21772. ear = cureLocalIntersections( ear, triangles, dim );
  21773. earcutLinked( ear, triangles, dim, minX, minY, invSize, 2 );
  21774. // as a last resort, try splitting the remaining polygon into two
  21775. } else if ( pass === 2 ) {
  21776. splitEarcut( ear, triangles, dim, minX, minY, invSize );
  21777. }
  21778. break;
  21779. }
  21780. }
  21781. }
  21782. // check whether a polygon node forms a valid ear with adjacent nodes
  21783. function isEar( ear ) {
  21784. var a = ear.prev,
  21785. b = ear,
  21786. c = ear.next;
  21787. if ( area( a, b, c ) >= 0 ) return false; // reflex, can't be an ear
  21788. // now make sure we don't have other points inside the potential ear
  21789. var p = ear.next.next;
  21790. while ( p !== ear.prev ) {
  21791. if ( pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y ) && area( p.prev, p, p.next ) >= 0 ) {
  21792. return false;
  21793. }
  21794. p = p.next;
  21795. }
  21796. return true;
  21797. }
  21798. function isEarHashed( ear, minX, minY, invSize ) {
  21799. var a = ear.prev,
  21800. b = ear,
  21801. c = ear.next;
  21802. if ( area( a, b, c ) >= 0 ) return false; // reflex, can't be an ear
  21803. // triangle bbox; min & max are calculated like this for speed
  21804. var minTX = a.x < b.x ? ( a.x < c.x ? a.x : c.x ) : ( b.x < c.x ? b.x : c.x ),
  21805. minTY = a.y < b.y ? ( a.y < c.y ? a.y : c.y ) : ( b.y < c.y ? b.y : c.y ),
  21806. maxTX = a.x > b.x ? ( a.x > c.x ? a.x : c.x ) : ( b.x > c.x ? b.x : c.x ),
  21807. maxTY = a.y > b.y ? ( a.y > c.y ? a.y : c.y ) : ( b.y > c.y ? b.y : c.y );
  21808. // z-order range for the current triangle bbox;
  21809. var minZ = zOrder( minTX, minTY, minX, minY, invSize ),
  21810. maxZ = zOrder( maxTX, maxTY, minX, minY, invSize );
  21811. // first look for points inside the triangle in increasing z-order
  21812. var p = ear.nextZ;
  21813. while ( p && p.z <= maxZ ) {
  21814. if ( p !== ear.prev && p !== ear.next &&
  21815. pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y ) &&
  21816. area( p.prev, p, p.next ) >= 0 ) return false;
  21817. p = p.nextZ;
  21818. }
  21819. // then look for points in decreasing z-order
  21820. p = ear.prevZ;
  21821. while ( p && p.z >= minZ ) {
  21822. if ( p !== ear.prev && p !== ear.next &&
  21823. pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y ) &&
  21824. area( p.prev, p, p.next ) >= 0 ) return false;
  21825. p = p.prevZ;
  21826. }
  21827. return true;
  21828. }
  21829. // go through all polygon nodes and cure small local self-intersections
  21830. function cureLocalIntersections( start, triangles, dim ) {
  21831. var p = start;
  21832. do {
  21833. var a = p.prev, b = p.next.next;
  21834. if ( ! equals( a, b ) && intersects( a, p, p.next, b ) && locallyInside( a, b ) && locallyInside( b, a ) ) {
  21835. triangles.push( a.i / dim );
  21836. triangles.push( p.i / dim );
  21837. triangles.push( b.i / dim );
  21838. // remove two nodes involved
  21839. removeNode( p );
  21840. removeNode( p.next );
  21841. p = start = b;
  21842. }
  21843. p = p.next;
  21844. } while ( p !== start );
  21845. return p;
  21846. }
  21847. // try splitting polygon into two and triangulate them independently
  21848. function splitEarcut( start, triangles, dim, minX, minY, invSize ) {
  21849. // look for a valid diagonal that divides the polygon into two
  21850. var a = start;
  21851. do {
  21852. var b = a.next.next;
  21853. while ( b !== a.prev ) {
  21854. if ( a.i !== b.i && isValidDiagonal( a, b ) ) {
  21855. // split the polygon in two by the diagonal
  21856. var c = splitPolygon( a, b );
  21857. // filter colinear points around the cuts
  21858. a = filterPoints( a, a.next );
  21859. c = filterPoints( c, c.next );
  21860. // run earcut on each half
  21861. earcutLinked( a, triangles, dim, minX, minY, invSize );
  21862. earcutLinked( c, triangles, dim, minX, minY, invSize );
  21863. return;
  21864. }
  21865. b = b.next;
  21866. }
  21867. a = a.next;
  21868. } while ( a !== start );
  21869. }
  21870. // link every hole into the outer loop, producing a single-ring polygon without holes
  21871. function eliminateHoles( data, holeIndices, outerNode, dim ) {
  21872. var queue = [], i, len, start, end, list;
  21873. for ( i = 0, len = holeIndices.length; i < len; i ++ ) {
  21874. start = holeIndices[ i ] * dim;
  21875. end = i < len - 1 ? holeIndices[ i + 1 ] * dim : data.length;
  21876. list = linkedList( data, start, end, dim, false );
  21877. if ( list === list.next ) list.steiner = true;
  21878. queue.push( getLeftmost( list ) );
  21879. }
  21880. queue.sort( compareX );
  21881. // process holes from left to right
  21882. for ( i = 0; i < queue.length; i ++ ) {
  21883. eliminateHole( queue[ i ], outerNode );
  21884. outerNode = filterPoints( outerNode, outerNode.next );
  21885. }
  21886. return outerNode;
  21887. }
  21888. function compareX( a, b ) {
  21889. return a.x - b.x;
  21890. }
  21891. // find a bridge between vertices that connects hole with an outer ring and and link it
  21892. function eliminateHole( hole, outerNode ) {
  21893. outerNode = findHoleBridge( hole, outerNode );
  21894. if ( outerNode ) {
  21895. var b = splitPolygon( outerNode, hole );
  21896. filterPoints( b, b.next );
  21897. }
  21898. }
  21899. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  21900. function findHoleBridge( hole, outerNode ) {
  21901. var p = outerNode,
  21902. hx = hole.x,
  21903. hy = hole.y,
  21904. qx = - Infinity,
  21905. m;
  21906. // find a segment intersected by a ray from the hole's leftmost point to the left;
  21907. // segment's endpoint with lesser x will be potential connection point
  21908. do {
  21909. if ( hy <= p.y && hy >= p.next.y && p.next.y !== p.y ) {
  21910. var x = p.x + ( hy - p.y ) * ( p.next.x - p.x ) / ( p.next.y - p.y );
  21911. if ( x <= hx && x > qx ) {
  21912. qx = x;
  21913. if ( x === hx ) {
  21914. if ( hy === p.y ) return p;
  21915. if ( hy === p.next.y ) return p.next;
  21916. }
  21917. m = p.x < p.next.x ? p : p.next;
  21918. }
  21919. }
  21920. p = p.next;
  21921. } while ( p !== outerNode );
  21922. if ( ! m ) return null;
  21923. if ( hx === qx ) return m.prev; // hole touches outer segment; pick lower endpoint
  21924. // look for points inside the triangle of hole point, segment intersection and endpoint;
  21925. // if there are no points found, we have a valid connection;
  21926. // otherwise choose the point of the minimum angle with the ray as connection point
  21927. var stop = m,
  21928. mx = m.x,
  21929. my = m.y,
  21930. tanMin = Infinity,
  21931. tan;
  21932. p = m.next;
  21933. while ( p !== stop ) {
  21934. if ( hx >= p.x && p.x >= mx && hx !== p.x &&
  21935. pointInTriangle( hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y ) ) {
  21936. tan = Math.abs( hy - p.y ) / ( hx - p.x ); // tangential
  21937. if ( ( tan < tanMin || ( tan === tanMin && p.x > m.x ) ) && locallyInside( p, hole ) ) {
  21938. m = p;
  21939. tanMin = tan;
  21940. }
  21941. }
  21942. p = p.next;
  21943. }
  21944. return m;
  21945. }
  21946. // interlink polygon nodes in z-order
  21947. function indexCurve( start, minX, minY, invSize ) {
  21948. var p = start;
  21949. do {
  21950. if ( p.z === null ) p.z = zOrder( p.x, p.y, minX, minY, invSize );
  21951. p.prevZ = p.prev;
  21952. p.nextZ = p.next;
  21953. p = p.next;
  21954. } while ( p !== start );
  21955. p.prevZ.nextZ = null;
  21956. p.prevZ = null;
  21957. sortLinked( p );
  21958. }
  21959. // Simon Tatham's linked list merge sort algorithm
  21960. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  21961. function sortLinked( list ) {
  21962. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  21963. do {
  21964. p = list;
  21965. list = null;
  21966. tail = null;
  21967. numMerges = 0;
  21968. while ( p ) {
  21969. numMerges ++;
  21970. q = p;
  21971. pSize = 0;
  21972. for ( i = 0; i < inSize; i ++ ) {
  21973. pSize ++;
  21974. q = q.nextZ;
  21975. if ( ! q ) break;
  21976. }
  21977. qSize = inSize;
  21978. while ( pSize > 0 || ( qSize > 0 && q ) ) {
  21979. if ( pSize !== 0 && ( qSize === 0 || ! q || p.z <= q.z ) ) {
  21980. e = p;
  21981. p = p.nextZ;
  21982. pSize --;
  21983. } else {
  21984. e = q;
  21985. q = q.nextZ;
  21986. qSize --;
  21987. }
  21988. if ( tail ) tail.nextZ = e;
  21989. else list = e;
  21990. e.prevZ = tail;
  21991. tail = e;
  21992. }
  21993. p = q;
  21994. }
  21995. tail.nextZ = null;
  21996. inSize *= 2;
  21997. } while ( numMerges > 1 );
  21998. return list;
  21999. }
  22000. // z-order of a point given coords and inverse of the longer side of data bbox
  22001. function zOrder( x, y, minX, minY, invSize ) {
  22002. // coords are transformed into non-negative 15-bit integer range
  22003. x = 32767 * ( x - minX ) * invSize;
  22004. y = 32767 * ( y - minY ) * invSize;
  22005. x = ( x | ( x << 8 ) ) & 0x00FF00FF;
  22006. x = ( x | ( x << 4 ) ) & 0x0F0F0F0F;
  22007. x = ( x | ( x << 2 ) ) & 0x33333333;
  22008. x = ( x | ( x << 1 ) ) & 0x55555555;
  22009. y = ( y | ( y << 8 ) ) & 0x00FF00FF;
  22010. y = ( y | ( y << 4 ) ) & 0x0F0F0F0F;
  22011. y = ( y | ( y << 2 ) ) & 0x33333333;
  22012. y = ( y | ( y << 1 ) ) & 0x55555555;
  22013. return x | ( y << 1 );
  22014. }
  22015. // find the leftmost node of a polygon ring
  22016. function getLeftmost( start ) {
  22017. var p = start, leftmost = start;
  22018. do {
  22019. if ( p.x < leftmost.x ) leftmost = p;
  22020. p = p.next;
  22021. } while ( p !== start );
  22022. return leftmost;
  22023. }
  22024. // check if a point lies within a convex triangle
  22025. function pointInTriangle( ax, ay, bx, by, cx, cy, px, py ) {
  22026. return ( cx - px ) * ( ay - py ) - ( ax - px ) * ( cy - py ) >= 0 &&
  22027. ( ax - px ) * ( by - py ) - ( bx - px ) * ( ay - py ) >= 0 &&
  22028. ( bx - px ) * ( cy - py ) - ( cx - px ) * ( by - py ) >= 0;
  22029. }
  22030. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  22031. function isValidDiagonal( a, b ) {
  22032. return a.next.i !== b.i && a.prev.i !== b.i && ! intersectsPolygon( a, b ) &&
  22033. locallyInside( a, b ) && locallyInside( b, a ) && middleInside( a, b );
  22034. }
  22035. // signed area of a triangle
  22036. function area( p, q, r ) {
  22037. return ( q.y - p.y ) * ( r.x - q.x ) - ( q.x - p.x ) * ( r.y - q.y );
  22038. }
  22039. // check if two points are equal
  22040. function equals( p1, p2 ) {
  22041. return p1.x === p2.x && p1.y === p2.y;
  22042. }
  22043. // check if two segments intersect
  22044. function intersects( p1, q1, p2, q2 ) {
  22045. if ( ( equals( p1, q1 ) && equals( p2, q2 ) ) ||
  22046. ( equals( p1, q2 ) && equals( p2, q1 ) ) ) return true;
  22047. return area( p1, q1, p2 ) > 0 !== area( p1, q1, q2 ) > 0 &&
  22048. area( p2, q2, p1 ) > 0 !== area( p2, q2, q1 ) > 0;
  22049. }
  22050. // check if a polygon diagonal intersects any polygon segments
  22051. function intersectsPolygon( a, b ) {
  22052. var p = a;
  22053. do {
  22054. if ( p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i &&
  22055. intersects( p, p.next, a, b ) ) {
  22056. return true;
  22057. }
  22058. p = p.next;
  22059. } while ( p !== a );
  22060. return false;
  22061. }
  22062. // check if a polygon diagonal is locally inside the polygon
  22063. function locallyInside( a, b ) {
  22064. return area( a.prev, a, a.next ) < 0 ?
  22065. area( a, b, a.next ) >= 0 && area( a, a.prev, b ) >= 0 :
  22066. area( a, b, a.prev ) < 0 || area( a, a.next, b ) < 0;
  22067. }
  22068. // check if the middle point of a polygon diagonal is inside the polygon
  22069. function middleInside( a, b ) {
  22070. var p = a,
  22071. inside = false,
  22072. px = ( a.x + b.x ) / 2,
  22073. py = ( a.y + b.y ) / 2;
  22074. do {
  22075. if ( ( ( p.y > py ) !== ( p.next.y > py ) ) && p.next.y !== p.y &&
  22076. ( px < ( p.next.x - p.x ) * ( py - p.y ) / ( p.next.y - p.y ) + p.x ) ) {
  22077. inside = ! inside;
  22078. }
  22079. p = p.next;
  22080. } while ( p !== a );
  22081. return inside;
  22082. }
  22083. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  22084. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  22085. function splitPolygon( a, b ) {
  22086. var a2 = new Node( a.i, a.x, a.y ),
  22087. b2 = new Node( b.i, b.x, b.y ),
  22088. an = a.next,
  22089. bp = b.prev;
  22090. a.next = b;
  22091. b.prev = a;
  22092. a2.next = an;
  22093. an.prev = a2;
  22094. b2.next = a2;
  22095. a2.prev = b2;
  22096. bp.next = b2;
  22097. b2.prev = bp;
  22098. return b2;
  22099. }
  22100. // create a node and optionally link it with previous one (in a circular doubly linked list)
  22101. function insertNode( i, x, y, last ) {
  22102. var p = new Node( i, x, y );
  22103. if ( ! last ) {
  22104. p.prev = p;
  22105. p.next = p;
  22106. } else {
  22107. p.next = last.next;
  22108. p.prev = last;
  22109. last.next.prev = p;
  22110. last.next = p;
  22111. }
  22112. return p;
  22113. }
  22114. function removeNode( p ) {
  22115. p.next.prev = p.prev;
  22116. p.prev.next = p.next;
  22117. if ( p.prevZ ) p.prevZ.nextZ = p.nextZ;
  22118. if ( p.nextZ ) p.nextZ.prevZ = p.prevZ;
  22119. }
  22120. function Node( i, x, y ) {
  22121. // vertice index in coordinates array
  22122. this.i = i;
  22123. // vertex coordinates
  22124. this.x = x;
  22125. this.y = y;
  22126. // previous and next vertice nodes in a polygon ring
  22127. this.prev = null;
  22128. this.next = null;
  22129. // z-order curve value
  22130. this.z = null;
  22131. // previous and next nodes in z-order
  22132. this.prevZ = null;
  22133. this.nextZ = null;
  22134. // indicates whether this is a steiner point
  22135. this.steiner = false;
  22136. }
  22137. function signedArea( data, start, end, dim ) {
  22138. var sum = 0;
  22139. for ( var i = start, j = end - dim; i < end; i += dim ) {
  22140. sum += ( data[ j ] - data[ i ] ) * ( data[ i + 1 ] + data[ j + 1 ] );
  22141. j = i;
  22142. }
  22143. return sum;
  22144. }
  22145. /**
  22146. * @author zz85 / http://www.lab4games.net/zz85/blog
  22147. */
  22148. var ShapeUtils = {
  22149. // calculate area of the contour polygon
  22150. area: function ( contour ) {
  22151. var n = contour.length;
  22152. var a = 0.0;
  22153. for ( var p = n - 1, q = 0; q < n; p = q ++ ) {
  22154. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  22155. }
  22156. return a * 0.5;
  22157. },
  22158. isClockWise: function ( pts ) {
  22159. return ShapeUtils.area( pts ) < 0;
  22160. },
  22161. triangulateShape: function ( contour, holes ) {
  22162. var vertices = []; // flat array of vertices like [ x0,y0, x1,y1, x2,y2, ... ]
  22163. var holeIndices = []; // array of hole indices
  22164. var faces = []; // final array of vertex indices like [ [ a,b,d ], [ b,c,d ] ]
  22165. removeDupEndPts( contour );
  22166. addContour( vertices, contour );
  22167. //
  22168. var holeIndex = contour.length;
  22169. holes.forEach( removeDupEndPts );
  22170. for ( var i = 0; i < holes.length; i ++ ) {
  22171. holeIndices.push( holeIndex );
  22172. holeIndex += holes[ i ].length;
  22173. addContour( vertices, holes[ i ] );
  22174. }
  22175. //
  22176. var triangles = Earcut.triangulate( vertices, holeIndices );
  22177. //
  22178. for ( var i = 0; i < triangles.length; i += 3 ) {
  22179. faces.push( triangles.slice( i, i + 3 ) );
  22180. }
  22181. return faces;
  22182. }
  22183. };
  22184. function removeDupEndPts( points ) {
  22185. var l = points.length;
  22186. if ( l > 2 && points[ l - 1 ].equals( points[ 0 ] ) ) {
  22187. points.pop();
  22188. }
  22189. }
  22190. function addContour( vertices, contour ) {
  22191. for ( var i = 0; i < contour.length; i ++ ) {
  22192. vertices.push( contour[ i ].x );
  22193. vertices.push( contour[ i ].y );
  22194. }
  22195. }
  22196. /**
  22197. * @author zz85 / http://www.lab4games.net/zz85/blog
  22198. *
  22199. * Creates extruded geometry from a path shape.
  22200. *
  22201. * parameters = {
  22202. *
  22203. * curveSegments: <int>, // number of points on the curves
  22204. * steps: <int>, // number of points for z-side extrusions / used for subdividing segments of extrude spline too
  22205. * depth: <float>, // Depth to extrude the shape
  22206. *
  22207. * bevelEnabled: <bool>, // turn on bevel
  22208. * bevelThickness: <float>, // how deep into the original shape bevel goes
  22209. * bevelSize: <float>, // how far from shape outline is bevel
  22210. * bevelSegments: <int>, // number of bevel layers
  22211. *
  22212. * extrudePath: <THREE.Curve> // curve to extrude shape along
  22213. *
  22214. * UVGenerator: <Object> // object that provides UV generator functions
  22215. *
  22216. * }
  22217. */
  22218. // ExtrudeGeometry
  22219. function ExtrudeGeometry( shapes, options ) {
  22220. Geometry.call( this );
  22221. this.type = 'ExtrudeGeometry';
  22222. this.parameters = {
  22223. shapes: shapes,
  22224. options: options
  22225. };
  22226. this.fromBufferGeometry( new ExtrudeBufferGeometry( shapes, options ) );
  22227. this.mergeVertices();
  22228. }
  22229. ExtrudeGeometry.prototype = Object.create( Geometry.prototype );
  22230. ExtrudeGeometry.prototype.constructor = ExtrudeGeometry;
  22231. ExtrudeGeometry.prototype.toJSON = function () {
  22232. var data = Geometry.prototype.toJSON.call( this );
  22233. var shapes = this.parameters.shapes;
  22234. var options = this.parameters.options;
  22235. return toJSON( shapes, options, data );
  22236. };
  22237. // ExtrudeBufferGeometry
  22238. function ExtrudeBufferGeometry( shapes, options ) {
  22239. BufferGeometry.call( this );
  22240. this.type = 'ExtrudeBufferGeometry';
  22241. this.parameters = {
  22242. shapes: shapes,
  22243. options: options
  22244. };
  22245. shapes = Array.isArray( shapes ) ? shapes : [ shapes ];
  22246. var scope = this;
  22247. var verticesArray = [];
  22248. var uvArray = [];
  22249. for ( var i = 0, l = shapes.length; i < l; i ++ ) {
  22250. var shape = shapes[ i ];
  22251. addShape( shape );
  22252. }
  22253. // build geometry
  22254. this.addAttribute( 'position', new Float32BufferAttribute( verticesArray, 3 ) );
  22255. this.addAttribute( 'uv', new Float32BufferAttribute( uvArray, 2 ) );
  22256. this.computeVertexNormals();
  22257. // functions
  22258. function addShape( shape ) {
  22259. var placeholder = [];
  22260. // options
  22261. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  22262. var steps = options.steps !== undefined ? options.steps : 1;
  22263. var depth = options.depth !== undefined ? options.depth : 100;
  22264. var bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true;
  22265. var bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6;
  22266. var bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2;
  22267. var bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  22268. var extrudePath = options.extrudePath;
  22269. var uvgen = options.UVGenerator !== undefined ? options.UVGenerator : WorldUVGenerator;
  22270. // deprecated options
  22271. if ( options.amount !== undefined ) {
  22272. console.warn( 'THREE.ExtrudeBufferGeometry: amount has been renamed to depth.' );
  22273. depth = options.amount;
  22274. }
  22275. //
  22276. var extrudePts, extrudeByPath = false;
  22277. var splineTube, binormal, normal, position2;
  22278. if ( extrudePath ) {
  22279. extrudePts = extrudePath.getSpacedPoints( steps );
  22280. extrudeByPath = true;
  22281. bevelEnabled = false; // bevels not supported for path extrusion
  22282. // SETUP TNB variables
  22283. // TODO1 - have a .isClosed in spline?
  22284. splineTube = extrudePath.computeFrenetFrames( steps, false );
  22285. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  22286. binormal = new Vector3();
  22287. normal = new Vector3();
  22288. position2 = new Vector3();
  22289. }
  22290. // Safeguards if bevels are not enabled
  22291. if ( ! bevelEnabled ) {
  22292. bevelSegments = 0;
  22293. bevelThickness = 0;
  22294. bevelSize = 0;
  22295. }
  22296. // Variables initialization
  22297. var ahole, h, hl; // looping of holes
  22298. var shapePoints = shape.extractPoints( curveSegments );
  22299. var vertices = shapePoints.shape;
  22300. var holes = shapePoints.holes;
  22301. var reverse = ! ShapeUtils.isClockWise( vertices );
  22302. if ( reverse ) {
  22303. vertices = vertices.reverse();
  22304. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  22305. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  22306. ahole = holes[ h ];
  22307. if ( ShapeUtils.isClockWise( ahole ) ) {
  22308. holes[ h ] = ahole.reverse();
  22309. }
  22310. }
  22311. }
  22312. var faces = ShapeUtils.triangulateShape( vertices, holes );
  22313. /* Vertices */
  22314. var contour = vertices; // vertices has all points but contour has only points of circumference
  22315. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  22316. ahole = holes[ h ];
  22317. vertices = vertices.concat( ahole );
  22318. }
  22319. function scalePt2( pt, vec, size ) {
  22320. if ( ! vec ) console.error( "THREE.ExtrudeGeometry: vec does not exist" );
  22321. return vec.clone().multiplyScalar( size ).add( pt );
  22322. }
  22323. var b, bs, t, z,
  22324. vert, vlen = vertices.length,
  22325. face, flen = faces.length;
  22326. // Find directions for point movement
  22327. function getBevelVec( inPt, inPrev, inNext ) {
  22328. // computes for inPt the corresponding point inPt' on a new contour
  22329. // shifted by 1 unit (length of normalized vector) to the left
  22330. // if we walk along contour clockwise, this new contour is outside the old one
  22331. //
  22332. // inPt' is the intersection of the two lines parallel to the two
  22333. // adjacent edges of inPt at a distance of 1 unit on the left side.
  22334. var v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPt
  22335. // good reading for geometry algorithms (here: line-line intersection)
  22336. // http://geomalgorithms.com/a05-_intersect-1.html
  22337. var v_prev_x = inPt.x - inPrev.x,
  22338. v_prev_y = inPt.y - inPrev.y;
  22339. var v_next_x = inNext.x - inPt.x,
  22340. v_next_y = inNext.y - inPt.y;
  22341. var v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y );
  22342. // check for collinear edges
  22343. var collinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  22344. if ( Math.abs( collinear0 ) > Number.EPSILON ) {
  22345. // not collinear
  22346. // length of vectors for normalizing
  22347. var v_prev_len = Math.sqrt( v_prev_lensq );
  22348. var v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y );
  22349. // shift adjacent points by unit vectors to the left
  22350. var ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len );
  22351. var ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len );
  22352. var ptNextShift_x = ( inNext.x - v_next_y / v_next_len );
  22353. var ptNextShift_y = ( inNext.y + v_next_x / v_next_len );
  22354. // scaling factor for v_prev to intersection point
  22355. var sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y -
  22356. ( ptNextShift_y - ptPrevShift_y ) * v_next_x ) /
  22357. ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  22358. // vector from inPt to intersection point
  22359. v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x );
  22360. v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y );
  22361. // Don't normalize!, otherwise sharp corners become ugly
  22362. // but prevent crazy spikes
  22363. var v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y );
  22364. if ( v_trans_lensq <= 2 ) {
  22365. return new Vector2( v_trans_x, v_trans_y );
  22366. } else {
  22367. shrink_by = Math.sqrt( v_trans_lensq / 2 );
  22368. }
  22369. } else {
  22370. // handle special case of collinear edges
  22371. var direction_eq = false; // assumes: opposite
  22372. if ( v_prev_x > Number.EPSILON ) {
  22373. if ( v_next_x > Number.EPSILON ) {
  22374. direction_eq = true;
  22375. }
  22376. } else {
  22377. if ( v_prev_x < - Number.EPSILON ) {
  22378. if ( v_next_x < - Number.EPSILON ) {
  22379. direction_eq = true;
  22380. }
  22381. } else {
  22382. if ( Math.sign( v_prev_y ) === Math.sign( v_next_y ) ) {
  22383. direction_eq = true;
  22384. }
  22385. }
  22386. }
  22387. if ( direction_eq ) {
  22388. // console.log("Warning: lines are a straight sequence");
  22389. v_trans_x = - v_prev_y;
  22390. v_trans_y = v_prev_x;
  22391. shrink_by = Math.sqrt( v_prev_lensq );
  22392. } else {
  22393. // console.log("Warning: lines are a straight spike");
  22394. v_trans_x = v_prev_x;
  22395. v_trans_y = v_prev_y;
  22396. shrink_by = Math.sqrt( v_prev_lensq / 2 );
  22397. }
  22398. }
  22399. return new Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by );
  22400. }
  22401. var contourMovements = [];
  22402. for ( var i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  22403. if ( j === il ) j = 0;
  22404. if ( k === il ) k = 0;
  22405. // (j)---(i)---(k)
  22406. // console.log('i,j,k', i, j , k)
  22407. contourMovements[ i ] = getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  22408. }
  22409. var holesMovements = [],
  22410. oneHoleMovements, verticesMovements = contourMovements.concat();
  22411. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  22412. ahole = holes[ h ];
  22413. oneHoleMovements = [];
  22414. for ( i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  22415. if ( j === il ) j = 0;
  22416. if ( k === il ) k = 0;
  22417. // (j)---(i)---(k)
  22418. oneHoleMovements[ i ] = getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  22419. }
  22420. holesMovements.push( oneHoleMovements );
  22421. verticesMovements = verticesMovements.concat( oneHoleMovements );
  22422. }
  22423. // Loop bevelSegments, 1 for the front, 1 for the back
  22424. for ( b = 0; b < bevelSegments; b ++ ) {
  22425. //for ( b = bevelSegments; b > 0; b -- ) {
  22426. t = b / bevelSegments;
  22427. z = bevelThickness * Math.cos( t * Math.PI / 2 );
  22428. bs = bevelSize * Math.sin( t * Math.PI / 2 );
  22429. // contract shape
  22430. for ( i = 0, il = contour.length; i < il; i ++ ) {
  22431. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  22432. v( vert.x, vert.y, - z );
  22433. }
  22434. // expand holes
  22435. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  22436. ahole = holes[ h ];
  22437. oneHoleMovements = holesMovements[ h ];
  22438. for ( i = 0, il = ahole.length; i < il; i ++ ) {
  22439. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  22440. v( vert.x, vert.y, - z );
  22441. }
  22442. }
  22443. }
  22444. bs = bevelSize;
  22445. // Back facing vertices
  22446. for ( i = 0; i < vlen; i ++ ) {
  22447. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  22448. if ( ! extrudeByPath ) {
  22449. v( vert.x, vert.y, 0 );
  22450. } else {
  22451. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  22452. normal.copy( splineTube.normals[ 0 ] ).multiplyScalar( vert.x );
  22453. binormal.copy( splineTube.binormals[ 0 ] ).multiplyScalar( vert.y );
  22454. position2.copy( extrudePts[ 0 ] ).add( normal ).add( binormal );
  22455. v( position2.x, position2.y, position2.z );
  22456. }
  22457. }
  22458. // Add stepped vertices...
  22459. // Including front facing vertices
  22460. var s;
  22461. for ( s = 1; s <= steps; s ++ ) {
  22462. for ( i = 0; i < vlen; i ++ ) {
  22463. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  22464. if ( ! extrudeByPath ) {
  22465. v( vert.x, vert.y, depth / steps * s );
  22466. } else {
  22467. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  22468. normal.copy( splineTube.normals[ s ] ).multiplyScalar( vert.x );
  22469. binormal.copy( splineTube.binormals[ s ] ).multiplyScalar( vert.y );
  22470. position2.copy( extrudePts[ s ] ).add( normal ).add( binormal );
  22471. v( position2.x, position2.y, position2.z );
  22472. }
  22473. }
  22474. }
  22475. // Add bevel segments planes
  22476. //for ( b = 1; b <= bevelSegments; b ++ ) {
  22477. for ( b = bevelSegments - 1; b >= 0; b -- ) {
  22478. t = b / bevelSegments;
  22479. z = bevelThickness * Math.cos( t * Math.PI / 2 );
  22480. bs = bevelSize * Math.sin( t * Math.PI / 2 );
  22481. // contract shape
  22482. for ( i = 0, il = contour.length; i < il; i ++ ) {
  22483. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  22484. v( vert.x, vert.y, depth + z );
  22485. }
  22486. // expand holes
  22487. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  22488. ahole = holes[ h ];
  22489. oneHoleMovements = holesMovements[ h ];
  22490. for ( i = 0, il = ahole.length; i < il; i ++ ) {
  22491. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  22492. if ( ! extrudeByPath ) {
  22493. v( vert.x, vert.y, depth + z );
  22494. } else {
  22495. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  22496. }
  22497. }
  22498. }
  22499. }
  22500. /* Faces */
  22501. // Top and bottom faces
  22502. buildLidFaces();
  22503. // Sides faces
  22504. buildSideFaces();
  22505. ///// Internal functions
  22506. function buildLidFaces() {
  22507. var start = verticesArray.length / 3;
  22508. if ( bevelEnabled ) {
  22509. var layer = 0; // steps + 1
  22510. var offset = vlen * layer;
  22511. // Bottom faces
  22512. for ( i = 0; i < flen; i ++ ) {
  22513. face = faces[ i ];
  22514. f3( face[ 2 ] + offset, face[ 1 ] + offset, face[ 0 ] + offset );
  22515. }
  22516. layer = steps + bevelSegments * 2;
  22517. offset = vlen * layer;
  22518. // Top faces
  22519. for ( i = 0; i < flen; i ++ ) {
  22520. face = faces[ i ];
  22521. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset );
  22522. }
  22523. } else {
  22524. // Bottom faces
  22525. for ( i = 0; i < flen; i ++ ) {
  22526. face = faces[ i ];
  22527. f3( face[ 2 ], face[ 1 ], face[ 0 ] );
  22528. }
  22529. // Top faces
  22530. for ( i = 0; i < flen; i ++ ) {
  22531. face = faces[ i ];
  22532. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps );
  22533. }
  22534. }
  22535. scope.addGroup( start, verticesArray.length / 3 - start, 0 );
  22536. }
  22537. // Create faces for the z-sides of the shape
  22538. function buildSideFaces() {
  22539. var start = verticesArray.length / 3;
  22540. var layeroffset = 0;
  22541. sidewalls( contour, layeroffset );
  22542. layeroffset += contour.length;
  22543. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  22544. ahole = holes[ h ];
  22545. sidewalls( ahole, layeroffset );
  22546. //, true
  22547. layeroffset += ahole.length;
  22548. }
  22549. scope.addGroup( start, verticesArray.length / 3 - start, 1 );
  22550. }
  22551. function sidewalls( contour, layeroffset ) {
  22552. var j, k;
  22553. i = contour.length;
  22554. while ( -- i >= 0 ) {
  22555. j = i;
  22556. k = i - 1;
  22557. if ( k < 0 ) k = contour.length - 1;
  22558. //console.log('b', i,j, i-1, k,vertices.length);
  22559. var s = 0,
  22560. sl = steps + bevelSegments * 2;
  22561. for ( s = 0; s < sl; s ++ ) {
  22562. var slen1 = vlen * s;
  22563. var slen2 = vlen * ( s + 1 );
  22564. var a = layeroffset + j + slen1,
  22565. b = layeroffset + k + slen1,
  22566. c = layeroffset + k + slen2,
  22567. d = layeroffset + j + slen2;
  22568. f4( a, b, c, d );
  22569. }
  22570. }
  22571. }
  22572. function v( x, y, z ) {
  22573. placeholder.push( x );
  22574. placeholder.push( y );
  22575. placeholder.push( z );
  22576. }
  22577. function f3( a, b, c ) {
  22578. addVertex( a );
  22579. addVertex( b );
  22580. addVertex( c );
  22581. var nextIndex = verticesArray.length / 3;
  22582. var uvs = uvgen.generateTopUV( scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  22583. addUV( uvs[ 0 ] );
  22584. addUV( uvs[ 1 ] );
  22585. addUV( uvs[ 2 ] );
  22586. }
  22587. function f4( a, b, c, d ) {
  22588. addVertex( a );
  22589. addVertex( b );
  22590. addVertex( d );
  22591. addVertex( b );
  22592. addVertex( c );
  22593. addVertex( d );
  22594. var nextIndex = verticesArray.length / 3;
  22595. var uvs = uvgen.generateSideWallUV( scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  22596. addUV( uvs[ 0 ] );
  22597. addUV( uvs[ 1 ] );
  22598. addUV( uvs[ 3 ] );
  22599. addUV( uvs[ 1 ] );
  22600. addUV( uvs[ 2 ] );
  22601. addUV( uvs[ 3 ] );
  22602. }
  22603. function addVertex( index ) {
  22604. verticesArray.push( placeholder[ index * 3 + 0 ] );
  22605. verticesArray.push( placeholder[ index * 3 + 1 ] );
  22606. verticesArray.push( placeholder[ index * 3 + 2 ] );
  22607. }
  22608. function addUV( vector2 ) {
  22609. uvArray.push( vector2.x );
  22610. uvArray.push( vector2.y );
  22611. }
  22612. }
  22613. }
  22614. ExtrudeBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  22615. ExtrudeBufferGeometry.prototype.constructor = ExtrudeBufferGeometry;
  22616. ExtrudeBufferGeometry.prototype.toJSON = function () {
  22617. var data = BufferGeometry.prototype.toJSON.call( this );
  22618. var shapes = this.parameters.shapes;
  22619. var options = this.parameters.options;
  22620. return toJSON( shapes, options, data );
  22621. };
  22622. //
  22623. var WorldUVGenerator = {
  22624. generateTopUV: function ( geometry, vertices, indexA, indexB, indexC ) {
  22625. var a_x = vertices[ indexA * 3 ];
  22626. var a_y = vertices[ indexA * 3 + 1 ];
  22627. var b_x = vertices[ indexB * 3 ];
  22628. var b_y = vertices[ indexB * 3 + 1 ];
  22629. var c_x = vertices[ indexC * 3 ];
  22630. var c_y = vertices[ indexC * 3 + 1 ];
  22631. return [
  22632. new Vector2( a_x, a_y ),
  22633. new Vector2( b_x, b_y ),
  22634. new Vector2( c_x, c_y )
  22635. ];
  22636. },
  22637. generateSideWallUV: function ( geometry, vertices, indexA, indexB, indexC, indexD ) {
  22638. var a_x = vertices[ indexA * 3 ];
  22639. var a_y = vertices[ indexA * 3 + 1 ];
  22640. var a_z = vertices[ indexA * 3 + 2 ];
  22641. var b_x = vertices[ indexB * 3 ];
  22642. var b_y = vertices[ indexB * 3 + 1 ];
  22643. var b_z = vertices[ indexB * 3 + 2 ];
  22644. var c_x = vertices[ indexC * 3 ];
  22645. var c_y = vertices[ indexC * 3 + 1 ];
  22646. var c_z = vertices[ indexC * 3 + 2 ];
  22647. var d_x = vertices[ indexD * 3 ];
  22648. var d_y = vertices[ indexD * 3 + 1 ];
  22649. var d_z = vertices[ indexD * 3 + 2 ];
  22650. if ( Math.abs( a_y - b_y ) < 0.01 ) {
  22651. return [
  22652. new Vector2( a_x, 1 - a_z ),
  22653. new Vector2( b_x, 1 - b_z ),
  22654. new Vector2( c_x, 1 - c_z ),
  22655. new Vector2( d_x, 1 - d_z )
  22656. ];
  22657. } else {
  22658. return [
  22659. new Vector2( a_y, 1 - a_z ),
  22660. new Vector2( b_y, 1 - b_z ),
  22661. new Vector2( c_y, 1 - c_z ),
  22662. new Vector2( d_y, 1 - d_z )
  22663. ];
  22664. }
  22665. }
  22666. };
  22667. function toJSON( shapes, options, data ) {
  22668. //
  22669. data.shapes = [];
  22670. if ( Array.isArray( shapes ) ) {
  22671. for ( var i = 0, l = shapes.length; i < l; i ++ ) {
  22672. var shape = shapes[ i ];
  22673. data.shapes.push( shape.uuid );
  22674. }
  22675. } else {
  22676. data.shapes.push( shapes.uuid );
  22677. }
  22678. //
  22679. if ( options.extrudePath !== undefined ) data.options.extrudePath = options.extrudePath.toJSON();
  22680. return data;
  22681. }
  22682. /**
  22683. * @author zz85 / http://www.lab4games.net/zz85/blog
  22684. * @author alteredq / http://alteredqualia.com/
  22685. *
  22686. * Text = 3D Text
  22687. *
  22688. * parameters = {
  22689. * font: <THREE.Font>, // font
  22690. *
  22691. * size: <float>, // size of the text
  22692. * height: <float>, // thickness to extrude text
  22693. * curveSegments: <int>, // number of points on the curves
  22694. *
  22695. * bevelEnabled: <bool>, // turn on bevel
  22696. * bevelThickness: <float>, // how deep into text bevel goes
  22697. * bevelSize: <float> // how far from text outline is bevel
  22698. * }
  22699. */
  22700. // TextGeometry
  22701. function TextGeometry( text, parameters ) {
  22702. Geometry.call( this );
  22703. this.type = 'TextGeometry';
  22704. this.parameters = {
  22705. text: text,
  22706. parameters: parameters
  22707. };
  22708. this.fromBufferGeometry( new TextBufferGeometry( text, parameters ) );
  22709. this.mergeVertices();
  22710. }
  22711. TextGeometry.prototype = Object.create( Geometry.prototype );
  22712. TextGeometry.prototype.constructor = TextGeometry;
  22713. // TextBufferGeometry
  22714. function TextBufferGeometry( text, parameters ) {
  22715. parameters = parameters || {};
  22716. var font = parameters.font;
  22717. if ( ! ( font && font.isFont ) ) {
  22718. console.error( 'THREE.TextGeometry: font parameter is not an instance of THREE.Font.' );
  22719. return new Geometry();
  22720. }
  22721. var shapes = font.generateShapes( text, parameters.size );
  22722. // translate parameters to ExtrudeGeometry API
  22723. parameters.depth = parameters.height !== undefined ? parameters.height : 50;
  22724. // defaults
  22725. if ( parameters.bevelThickness === undefined ) parameters.bevelThickness = 10;
  22726. if ( parameters.bevelSize === undefined ) parameters.bevelSize = 8;
  22727. if ( parameters.bevelEnabled === undefined ) parameters.bevelEnabled = false;
  22728. ExtrudeBufferGeometry.call( this, shapes, parameters );
  22729. this.type = 'TextBufferGeometry';
  22730. }
  22731. TextBufferGeometry.prototype = Object.create( ExtrudeBufferGeometry.prototype );
  22732. TextBufferGeometry.prototype.constructor = TextBufferGeometry;
  22733. /**
  22734. * @author mrdoob / http://mrdoob.com/
  22735. * @author benaadams / https://twitter.com/ben_a_adams
  22736. * @author Mugen87 / https://github.com/Mugen87
  22737. */
  22738. // SphereGeometry
  22739. function SphereGeometry( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {
  22740. Geometry.call( this );
  22741. this.type = 'SphereGeometry';
  22742. this.parameters = {
  22743. radius: radius,
  22744. widthSegments: widthSegments,
  22745. heightSegments: heightSegments,
  22746. phiStart: phiStart,
  22747. phiLength: phiLength,
  22748. thetaStart: thetaStart,
  22749. thetaLength: thetaLength
  22750. };
  22751. this.fromBufferGeometry( new SphereBufferGeometry( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) );
  22752. this.mergeVertices();
  22753. }
  22754. SphereGeometry.prototype = Object.create( Geometry.prototype );
  22755. SphereGeometry.prototype.constructor = SphereGeometry;
  22756. // SphereBufferGeometry
  22757. function SphereBufferGeometry( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {
  22758. BufferGeometry.call( this );
  22759. this.type = 'SphereBufferGeometry';
  22760. this.parameters = {
  22761. radius: radius,
  22762. widthSegments: widthSegments,
  22763. heightSegments: heightSegments,
  22764. phiStart: phiStart,
  22765. phiLength: phiLength,
  22766. thetaStart: thetaStart,
  22767. thetaLength: thetaLength
  22768. };
  22769. radius = radius || 1;
  22770. widthSegments = Math.max( 3, Math.floor( widthSegments ) || 8 );
  22771. heightSegments = Math.max( 2, Math.floor( heightSegments ) || 6 );
  22772. phiStart = phiStart !== undefined ? phiStart : 0;
  22773. phiLength = phiLength !== undefined ? phiLength : Math.PI * 2;
  22774. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  22775. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI;
  22776. var thetaEnd = thetaStart + thetaLength;
  22777. var ix, iy;
  22778. var index = 0;
  22779. var grid = [];
  22780. var vertex = new Vector3();
  22781. var normal = new Vector3();
  22782. // buffers
  22783. var indices = [];
  22784. var vertices = [];
  22785. var normals = [];
  22786. var uvs = [];
  22787. // generate vertices, normals and uvs
  22788. for ( iy = 0; iy <= heightSegments; iy ++ ) {
  22789. var verticesRow = [];
  22790. var v = iy / heightSegments;
  22791. for ( ix = 0; ix <= widthSegments; ix ++ ) {
  22792. var u = ix / widthSegments;
  22793. // vertex
  22794. vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  22795. vertex.y = radius * Math.cos( thetaStart + v * thetaLength );
  22796. vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  22797. vertices.push( vertex.x, vertex.y, vertex.z );
  22798. // normal
  22799. normal.set( vertex.x, vertex.y, vertex.z ).normalize();
  22800. normals.push( normal.x, normal.y, normal.z );
  22801. // uv
  22802. uvs.push( u, 1 - v );
  22803. verticesRow.push( index ++ );
  22804. }
  22805. grid.push( verticesRow );
  22806. }
  22807. // indices
  22808. for ( iy = 0; iy < heightSegments; iy ++ ) {
  22809. for ( ix = 0; ix < widthSegments; ix ++ ) {
  22810. var a = grid[ iy ][ ix + 1 ];
  22811. var b = grid[ iy ][ ix ];
  22812. var c = grid[ iy + 1 ][ ix ];
  22813. var d = grid[ iy + 1 ][ ix + 1 ];
  22814. if ( iy !== 0 || thetaStart > 0 ) indices.push( a, b, d );
  22815. if ( iy !== heightSegments - 1 || thetaEnd < Math.PI ) indices.push( b, c, d );
  22816. }
  22817. }
  22818. // build geometry
  22819. this.setIndex( indices );
  22820. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22821. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  22822. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  22823. }
  22824. SphereBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  22825. SphereBufferGeometry.prototype.constructor = SphereBufferGeometry;
  22826. /**
  22827. * @author Kaleb Murphy
  22828. * @author Mugen87 / https://github.com/Mugen87
  22829. */
  22830. // RingGeometry
  22831. function RingGeometry( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) {
  22832. Geometry.call( this );
  22833. this.type = 'RingGeometry';
  22834. this.parameters = {
  22835. innerRadius: innerRadius,
  22836. outerRadius: outerRadius,
  22837. thetaSegments: thetaSegments,
  22838. phiSegments: phiSegments,
  22839. thetaStart: thetaStart,
  22840. thetaLength: thetaLength
  22841. };
  22842. this.fromBufferGeometry( new RingBufferGeometry( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) );
  22843. this.mergeVertices();
  22844. }
  22845. RingGeometry.prototype = Object.create( Geometry.prototype );
  22846. RingGeometry.prototype.constructor = RingGeometry;
  22847. // RingBufferGeometry
  22848. function RingBufferGeometry( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) {
  22849. BufferGeometry.call( this );
  22850. this.type = 'RingBufferGeometry';
  22851. this.parameters = {
  22852. innerRadius: innerRadius,
  22853. outerRadius: outerRadius,
  22854. thetaSegments: thetaSegments,
  22855. phiSegments: phiSegments,
  22856. thetaStart: thetaStart,
  22857. thetaLength: thetaLength
  22858. };
  22859. innerRadius = innerRadius || 0.5;
  22860. outerRadius = outerRadius || 1;
  22861. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  22862. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  22863. thetaSegments = thetaSegments !== undefined ? Math.max( 3, thetaSegments ) : 8;
  22864. phiSegments = phiSegments !== undefined ? Math.max( 1, phiSegments ) : 1;
  22865. // buffers
  22866. var indices = [];
  22867. var vertices = [];
  22868. var normals = [];
  22869. var uvs = [];
  22870. // some helper variables
  22871. var segment;
  22872. var radius = innerRadius;
  22873. var radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
  22874. var vertex = new Vector3();
  22875. var uv = new Vector2();
  22876. var j, i;
  22877. // generate vertices, normals and uvs
  22878. for ( j = 0; j <= phiSegments; j ++ ) {
  22879. for ( i = 0; i <= thetaSegments; i ++ ) {
  22880. // values are generate from the inside of the ring to the outside
  22881. segment = thetaStart + i / thetaSegments * thetaLength;
  22882. // vertex
  22883. vertex.x = radius * Math.cos( segment );
  22884. vertex.y = radius * Math.sin( segment );
  22885. vertices.push( vertex.x, vertex.y, vertex.z );
  22886. // normal
  22887. normals.push( 0, 0, 1 );
  22888. // uv
  22889. uv.x = ( vertex.x / outerRadius + 1 ) / 2;
  22890. uv.y = ( vertex.y / outerRadius + 1 ) / 2;
  22891. uvs.push( uv.x, uv.y );
  22892. }
  22893. // increase the radius for next row of vertices
  22894. radius += radiusStep;
  22895. }
  22896. // indices
  22897. for ( j = 0; j < phiSegments; j ++ ) {
  22898. var thetaSegmentLevel = j * ( thetaSegments + 1 );
  22899. for ( i = 0; i < thetaSegments; i ++ ) {
  22900. segment = i + thetaSegmentLevel;
  22901. var a = segment;
  22902. var b = segment + thetaSegments + 1;
  22903. var c = segment + thetaSegments + 2;
  22904. var d = segment + 1;
  22905. // faces
  22906. indices.push( a, b, d );
  22907. indices.push( b, c, d );
  22908. }
  22909. }
  22910. // build geometry
  22911. this.setIndex( indices );
  22912. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22913. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  22914. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  22915. }
  22916. RingBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  22917. RingBufferGeometry.prototype.constructor = RingBufferGeometry;
  22918. /**
  22919. * @author zz85 / https://github.com/zz85
  22920. * @author bhouston / http://clara.io
  22921. * @author Mugen87 / https://github.com/Mugen87
  22922. */
  22923. // LatheGeometry
  22924. function LatheGeometry( points, segments, phiStart, phiLength ) {
  22925. Geometry.call( this );
  22926. this.type = 'LatheGeometry';
  22927. this.parameters = {
  22928. points: points,
  22929. segments: segments,
  22930. phiStart: phiStart,
  22931. phiLength: phiLength
  22932. };
  22933. this.fromBufferGeometry( new LatheBufferGeometry( points, segments, phiStart, phiLength ) );
  22934. this.mergeVertices();
  22935. }
  22936. LatheGeometry.prototype = Object.create( Geometry.prototype );
  22937. LatheGeometry.prototype.constructor = LatheGeometry;
  22938. // LatheBufferGeometry
  22939. function LatheBufferGeometry( points, segments, phiStart, phiLength ) {
  22940. BufferGeometry.call( this );
  22941. this.type = 'LatheBufferGeometry';
  22942. this.parameters = {
  22943. points: points,
  22944. segments: segments,
  22945. phiStart: phiStart,
  22946. phiLength: phiLength
  22947. };
  22948. segments = Math.floor( segments ) || 12;
  22949. phiStart = phiStart || 0;
  22950. phiLength = phiLength || Math.PI * 2;
  22951. // clamp phiLength so it's in range of [ 0, 2PI ]
  22952. phiLength = _Math.clamp( phiLength, 0, Math.PI * 2 );
  22953. // buffers
  22954. var indices = [];
  22955. var vertices = [];
  22956. var uvs = [];
  22957. // helper variables
  22958. var base;
  22959. var inverseSegments = 1.0 / segments;
  22960. var vertex = new Vector3();
  22961. var uv = new Vector2();
  22962. var i, j;
  22963. // generate vertices and uvs
  22964. for ( i = 0; i <= segments; i ++ ) {
  22965. var phi = phiStart + i * inverseSegments * phiLength;
  22966. var sin = Math.sin( phi );
  22967. var cos = Math.cos( phi );
  22968. for ( j = 0; j <= ( points.length - 1 ); j ++ ) {
  22969. // vertex
  22970. vertex.x = points[ j ].x * sin;
  22971. vertex.y = points[ j ].y;
  22972. vertex.z = points[ j ].x * cos;
  22973. vertices.push( vertex.x, vertex.y, vertex.z );
  22974. // uv
  22975. uv.x = i / segments;
  22976. uv.y = j / ( points.length - 1 );
  22977. uvs.push( uv.x, uv.y );
  22978. }
  22979. }
  22980. // indices
  22981. for ( i = 0; i < segments; i ++ ) {
  22982. for ( j = 0; j < ( points.length - 1 ); j ++ ) {
  22983. base = j + i * points.length;
  22984. var a = base;
  22985. var b = base + points.length;
  22986. var c = base + points.length + 1;
  22987. var d = base + 1;
  22988. // faces
  22989. indices.push( a, b, d );
  22990. indices.push( b, c, d );
  22991. }
  22992. }
  22993. // build geometry
  22994. this.setIndex( indices );
  22995. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22996. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  22997. // generate normals
  22998. this.computeVertexNormals();
  22999. // if the geometry is closed, we need to average the normals along the seam.
  23000. // because the corresponding vertices are identical (but still have different UVs).
  23001. if ( phiLength === Math.PI * 2 ) {
  23002. var normals = this.attributes.normal.array;
  23003. var n1 = new Vector3();
  23004. var n2 = new Vector3();
  23005. var n = new Vector3();
  23006. // this is the buffer offset for the last line of vertices
  23007. base = segments * points.length * 3;
  23008. for ( i = 0, j = 0; i < points.length; i ++, j += 3 ) {
  23009. // select the normal of the vertex in the first line
  23010. n1.x = normals[ j + 0 ];
  23011. n1.y = normals[ j + 1 ];
  23012. n1.z = normals[ j + 2 ];
  23013. // select the normal of the vertex in the last line
  23014. n2.x = normals[ base + j + 0 ];
  23015. n2.y = normals[ base + j + 1 ];
  23016. n2.z = normals[ base + j + 2 ];
  23017. // average normals
  23018. n.addVectors( n1, n2 ).normalize();
  23019. // assign the new values to both normals
  23020. normals[ j + 0 ] = normals[ base + j + 0 ] = n.x;
  23021. normals[ j + 1 ] = normals[ base + j + 1 ] = n.y;
  23022. normals[ j + 2 ] = normals[ base + j + 2 ] = n.z;
  23023. }
  23024. }
  23025. }
  23026. LatheBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  23027. LatheBufferGeometry.prototype.constructor = LatheBufferGeometry;
  23028. /**
  23029. * @author jonobr1 / http://jonobr1.com
  23030. * @author Mugen87 / https://github.com/Mugen87
  23031. */
  23032. // ShapeGeometry
  23033. function ShapeGeometry( shapes, curveSegments ) {
  23034. Geometry.call( this );
  23035. this.type = 'ShapeGeometry';
  23036. if ( typeof curveSegments === 'object' ) {
  23037. console.warn( 'THREE.ShapeGeometry: Options parameter has been removed.' );
  23038. curveSegments = curveSegments.curveSegments;
  23039. }
  23040. this.parameters = {
  23041. shapes: shapes,
  23042. curveSegments: curveSegments
  23043. };
  23044. this.fromBufferGeometry( new ShapeBufferGeometry( shapes, curveSegments ) );
  23045. this.mergeVertices();
  23046. }
  23047. ShapeGeometry.prototype = Object.create( Geometry.prototype );
  23048. ShapeGeometry.prototype.constructor = ShapeGeometry;
  23049. ShapeGeometry.prototype.toJSON = function () {
  23050. var data = Geometry.prototype.toJSON.call( this );
  23051. var shapes = this.parameters.shapes;
  23052. return toJSON$1( shapes, data );
  23053. };
  23054. // ShapeBufferGeometry
  23055. function ShapeBufferGeometry( shapes, curveSegments ) {
  23056. BufferGeometry.call( this );
  23057. this.type = 'ShapeBufferGeometry';
  23058. this.parameters = {
  23059. shapes: shapes,
  23060. curveSegments: curveSegments
  23061. };
  23062. curveSegments = curveSegments || 12;
  23063. // buffers
  23064. var indices = [];
  23065. var vertices = [];
  23066. var normals = [];
  23067. var uvs = [];
  23068. // helper variables
  23069. var groupStart = 0;
  23070. var groupCount = 0;
  23071. // allow single and array values for "shapes" parameter
  23072. if ( Array.isArray( shapes ) === false ) {
  23073. addShape( shapes );
  23074. } else {
  23075. for ( var i = 0; i < shapes.length; i ++ ) {
  23076. addShape( shapes[ i ] );
  23077. this.addGroup( groupStart, groupCount, i ); // enables MultiMaterial support
  23078. groupStart += groupCount;
  23079. groupCount = 0;
  23080. }
  23081. }
  23082. // build geometry
  23083. this.setIndex( indices );
  23084. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  23085. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  23086. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  23087. // helper functions
  23088. function addShape( shape ) {
  23089. var i, l, shapeHole;
  23090. var indexOffset = vertices.length / 3;
  23091. var points = shape.extractPoints( curveSegments );
  23092. var shapeVertices = points.shape;
  23093. var shapeHoles = points.holes;
  23094. // check direction of vertices
  23095. if ( ShapeUtils.isClockWise( shapeVertices ) === false ) {
  23096. shapeVertices = shapeVertices.reverse();
  23097. }
  23098. for ( i = 0, l = shapeHoles.length; i < l; i ++ ) {
  23099. shapeHole = shapeHoles[ i ];
  23100. if ( ShapeUtils.isClockWise( shapeHole ) === true ) {
  23101. shapeHoles[ i ] = shapeHole.reverse();
  23102. }
  23103. }
  23104. var faces = ShapeUtils.triangulateShape( shapeVertices, shapeHoles );
  23105. // join vertices of inner and outer paths to a single array
  23106. for ( i = 0, l = shapeHoles.length; i < l; i ++ ) {
  23107. shapeHole = shapeHoles[ i ];
  23108. shapeVertices = shapeVertices.concat( shapeHole );
  23109. }
  23110. // vertices, normals, uvs
  23111. for ( i = 0, l = shapeVertices.length; i < l; i ++ ) {
  23112. var vertex = shapeVertices[ i ];
  23113. vertices.push( vertex.x, vertex.y, 0 );
  23114. normals.push( 0, 0, 1 );
  23115. uvs.push( vertex.x, vertex.y ); // world uvs
  23116. }
  23117. // incides
  23118. for ( i = 0, l = faces.length; i < l; i ++ ) {
  23119. var face = faces[ i ];
  23120. var a = face[ 0 ] + indexOffset;
  23121. var b = face[ 1 ] + indexOffset;
  23122. var c = face[ 2 ] + indexOffset;
  23123. indices.push( a, b, c );
  23124. groupCount += 3;
  23125. }
  23126. }
  23127. }
  23128. ShapeBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  23129. ShapeBufferGeometry.prototype.constructor = ShapeBufferGeometry;
  23130. ShapeBufferGeometry.prototype.toJSON = function () {
  23131. var data = BufferGeometry.prototype.toJSON.call( this );
  23132. var shapes = this.parameters.shapes;
  23133. return toJSON$1( shapes, data );
  23134. };
  23135. //
  23136. function toJSON$1( shapes, data ) {
  23137. data.shapes = [];
  23138. if ( Array.isArray( shapes ) ) {
  23139. for ( var i = 0, l = shapes.length; i < l; i ++ ) {
  23140. var shape = shapes[ i ];
  23141. data.shapes.push( shape.uuid );
  23142. }
  23143. } else {
  23144. data.shapes.push( shapes.uuid );
  23145. }
  23146. return data;
  23147. }
  23148. /**
  23149. * @author WestLangley / http://github.com/WestLangley
  23150. * @author Mugen87 / https://github.com/Mugen87
  23151. */
  23152. function EdgesGeometry( geometry, thresholdAngle ) {
  23153. BufferGeometry.call( this );
  23154. this.type = 'EdgesGeometry';
  23155. this.parameters = {
  23156. thresholdAngle: thresholdAngle
  23157. };
  23158. thresholdAngle = ( thresholdAngle !== undefined ) ? thresholdAngle : 1;
  23159. // buffer
  23160. var vertices = [];
  23161. // helper variables
  23162. var thresholdDot = Math.cos( _Math.DEG2RAD * thresholdAngle );
  23163. var edge = [ 0, 0 ], edges = {}, edge1, edge2;
  23164. var key, keys = [ 'a', 'b', 'c' ];
  23165. // prepare source geometry
  23166. var geometry2;
  23167. if ( geometry.isBufferGeometry ) {
  23168. geometry2 = new Geometry();
  23169. geometry2.fromBufferGeometry( geometry );
  23170. } else {
  23171. geometry2 = geometry.clone();
  23172. }
  23173. geometry2.mergeVertices();
  23174. geometry2.computeFaceNormals();
  23175. var sourceVertices = geometry2.vertices;
  23176. var faces = geometry2.faces;
  23177. // now create a data structure where each entry represents an edge with its adjoining faces
  23178. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  23179. var face = faces[ i ];
  23180. for ( var j = 0; j < 3; j ++ ) {
  23181. edge1 = face[ keys[ j ] ];
  23182. edge2 = face[ keys[ ( j + 1 ) % 3 ] ];
  23183. edge[ 0 ] = Math.min( edge1, edge2 );
  23184. edge[ 1 ] = Math.max( edge1, edge2 );
  23185. key = edge[ 0 ] + ',' + edge[ 1 ];
  23186. if ( edges[ key ] === undefined ) {
  23187. edges[ key ] = { index1: edge[ 0 ], index2: edge[ 1 ], face1: i, face2: undefined };
  23188. } else {
  23189. edges[ key ].face2 = i;
  23190. }
  23191. }
  23192. }
  23193. // generate vertices
  23194. for ( key in edges ) {
  23195. var e = edges[ key ];
  23196. // an edge is only rendered if the angle (in degrees) between the face normals of the adjoining faces exceeds this value. default = 1 degree.
  23197. if ( e.face2 === undefined || faces[ e.face1 ].normal.dot( faces[ e.face2 ].normal ) <= thresholdDot ) {
  23198. var vertex = sourceVertices[ e.index1 ];
  23199. vertices.push( vertex.x, vertex.y, vertex.z );
  23200. vertex = sourceVertices[ e.index2 ];
  23201. vertices.push( vertex.x, vertex.y, vertex.z );
  23202. }
  23203. }
  23204. // build geometry
  23205. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  23206. }
  23207. EdgesGeometry.prototype = Object.create( BufferGeometry.prototype );
  23208. EdgesGeometry.prototype.constructor = EdgesGeometry;
  23209. /**
  23210. * @author mrdoob / http://mrdoob.com/
  23211. * @author Mugen87 / https://github.com/Mugen87
  23212. */
  23213. // CylinderGeometry
  23214. function CylinderGeometry( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  23215. Geometry.call( this );
  23216. this.type = 'CylinderGeometry';
  23217. this.parameters = {
  23218. radiusTop: radiusTop,
  23219. radiusBottom: radiusBottom,
  23220. height: height,
  23221. radialSegments: radialSegments,
  23222. heightSegments: heightSegments,
  23223. openEnded: openEnded,
  23224. thetaStart: thetaStart,
  23225. thetaLength: thetaLength
  23226. };
  23227. this.fromBufferGeometry( new CylinderBufferGeometry( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) );
  23228. this.mergeVertices();
  23229. }
  23230. CylinderGeometry.prototype = Object.create( Geometry.prototype );
  23231. CylinderGeometry.prototype.constructor = CylinderGeometry;
  23232. // CylinderBufferGeometry
  23233. function CylinderBufferGeometry( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  23234. BufferGeometry.call( this );
  23235. this.type = 'CylinderBufferGeometry';
  23236. this.parameters = {
  23237. radiusTop: radiusTop,
  23238. radiusBottom: radiusBottom,
  23239. height: height,
  23240. radialSegments: radialSegments,
  23241. heightSegments: heightSegments,
  23242. openEnded: openEnded,
  23243. thetaStart: thetaStart,
  23244. thetaLength: thetaLength
  23245. };
  23246. var scope = this;
  23247. radiusTop = radiusTop !== undefined ? radiusTop : 1;
  23248. radiusBottom = radiusBottom !== undefined ? radiusBottom : 1;
  23249. height = height || 1;
  23250. radialSegments = Math.floor( radialSegments ) || 8;
  23251. heightSegments = Math.floor( heightSegments ) || 1;
  23252. openEnded = openEnded !== undefined ? openEnded : false;
  23253. thetaStart = thetaStart !== undefined ? thetaStart : 0.0;
  23254. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  23255. // buffers
  23256. var indices = [];
  23257. var vertices = [];
  23258. var normals = [];
  23259. var uvs = [];
  23260. // helper variables
  23261. var index = 0;
  23262. var indexArray = [];
  23263. var halfHeight = height / 2;
  23264. var groupStart = 0;
  23265. // generate geometry
  23266. generateTorso();
  23267. if ( openEnded === false ) {
  23268. if ( radiusTop > 0 ) generateCap( true );
  23269. if ( radiusBottom > 0 ) generateCap( false );
  23270. }
  23271. // build geometry
  23272. this.setIndex( indices );
  23273. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  23274. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  23275. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  23276. function generateTorso() {
  23277. var x, y;
  23278. var normal = new Vector3();
  23279. var vertex = new Vector3();
  23280. var groupCount = 0;
  23281. // this will be used to calculate the normal
  23282. var slope = ( radiusBottom - radiusTop ) / height;
  23283. // generate vertices, normals and uvs
  23284. for ( y = 0; y <= heightSegments; y ++ ) {
  23285. var indexRow = [];
  23286. var v = y / heightSegments;
  23287. // calculate the radius of the current row
  23288. var radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  23289. for ( x = 0; x <= radialSegments; x ++ ) {
  23290. var u = x / radialSegments;
  23291. var theta = u * thetaLength + thetaStart;
  23292. var sinTheta = Math.sin( theta );
  23293. var cosTheta = Math.cos( theta );
  23294. // vertex
  23295. vertex.x = radius * sinTheta;
  23296. vertex.y = - v * height + halfHeight;
  23297. vertex.z = radius * cosTheta;
  23298. vertices.push( vertex.x, vertex.y, vertex.z );
  23299. // normal
  23300. normal.set( sinTheta, slope, cosTheta ).normalize();
  23301. normals.push( normal.x, normal.y, normal.z );
  23302. // uv
  23303. uvs.push( u, 1 - v );
  23304. // save index of vertex in respective row
  23305. indexRow.push( index ++ );
  23306. }
  23307. // now save vertices of the row in our index array
  23308. indexArray.push( indexRow );
  23309. }
  23310. // generate indices
  23311. for ( x = 0; x < radialSegments; x ++ ) {
  23312. for ( y = 0; y < heightSegments; y ++ ) {
  23313. // we use the index array to access the correct indices
  23314. var a = indexArray[ y ][ x ];
  23315. var b = indexArray[ y + 1 ][ x ];
  23316. var c = indexArray[ y + 1 ][ x + 1 ];
  23317. var d = indexArray[ y ][ x + 1 ];
  23318. // faces
  23319. indices.push( a, b, d );
  23320. indices.push( b, c, d );
  23321. // update group counter
  23322. groupCount += 6;
  23323. }
  23324. }
  23325. // add a group to the geometry. this will ensure multi material support
  23326. scope.addGroup( groupStart, groupCount, 0 );
  23327. // calculate new start value for groups
  23328. groupStart += groupCount;
  23329. }
  23330. function generateCap( top ) {
  23331. var x, centerIndexStart, centerIndexEnd;
  23332. var uv = new Vector2();
  23333. var vertex = new Vector3();
  23334. var groupCount = 0;
  23335. var radius = ( top === true ) ? radiusTop : radiusBottom;
  23336. var sign = ( top === true ) ? 1 : - 1;
  23337. // save the index of the first center vertex
  23338. centerIndexStart = index;
  23339. // first we generate the center vertex data of the cap.
  23340. // because the geometry needs one set of uvs per face,
  23341. // we must generate a center vertex per face/segment
  23342. for ( x = 1; x <= radialSegments; x ++ ) {
  23343. // vertex
  23344. vertices.push( 0, halfHeight * sign, 0 );
  23345. // normal
  23346. normals.push( 0, sign, 0 );
  23347. // uv
  23348. uvs.push( 0.5, 0.5 );
  23349. // increase index
  23350. index ++;
  23351. }
  23352. // save the index of the last center vertex
  23353. centerIndexEnd = index;
  23354. // now we generate the surrounding vertices, normals and uvs
  23355. for ( x = 0; x <= radialSegments; x ++ ) {
  23356. var u = x / radialSegments;
  23357. var theta = u * thetaLength + thetaStart;
  23358. var cosTheta = Math.cos( theta );
  23359. var sinTheta = Math.sin( theta );
  23360. // vertex
  23361. vertex.x = radius * sinTheta;
  23362. vertex.y = halfHeight * sign;
  23363. vertex.z = radius * cosTheta;
  23364. vertices.push( vertex.x, vertex.y, vertex.z );
  23365. // normal
  23366. normals.push( 0, sign, 0 );
  23367. // uv
  23368. uv.x = ( cosTheta * 0.5 ) + 0.5;
  23369. uv.y = ( sinTheta * 0.5 * sign ) + 0.5;
  23370. uvs.push( uv.x, uv.y );
  23371. // increase index
  23372. index ++;
  23373. }
  23374. // generate indices
  23375. for ( x = 0; x < radialSegments; x ++ ) {
  23376. var c = centerIndexStart + x;
  23377. var i = centerIndexEnd + x;
  23378. if ( top === true ) {
  23379. // face top
  23380. indices.push( i, i + 1, c );
  23381. } else {
  23382. // face bottom
  23383. indices.push( i + 1, i, c );
  23384. }
  23385. groupCount += 3;
  23386. }
  23387. // add a group to the geometry. this will ensure multi material support
  23388. scope.addGroup( groupStart, groupCount, top === true ? 1 : 2 );
  23389. // calculate new start value for groups
  23390. groupStart += groupCount;
  23391. }
  23392. }
  23393. CylinderBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  23394. CylinderBufferGeometry.prototype.constructor = CylinderBufferGeometry;
  23395. /**
  23396. * @author abelnation / http://github.com/abelnation
  23397. */
  23398. // ConeGeometry
  23399. function ConeGeometry( radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  23400. CylinderGeometry.call( this, 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  23401. this.type = 'ConeGeometry';
  23402. this.parameters = {
  23403. radius: radius,
  23404. height: height,
  23405. radialSegments: radialSegments,
  23406. heightSegments: heightSegments,
  23407. openEnded: openEnded,
  23408. thetaStart: thetaStart,
  23409. thetaLength: thetaLength
  23410. };
  23411. }
  23412. ConeGeometry.prototype = Object.create( CylinderGeometry.prototype );
  23413. ConeGeometry.prototype.constructor = ConeGeometry;
  23414. // ConeBufferGeometry
  23415. function ConeBufferGeometry( radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  23416. CylinderBufferGeometry.call( this, 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  23417. this.type = 'ConeBufferGeometry';
  23418. this.parameters = {
  23419. radius: radius,
  23420. height: height,
  23421. radialSegments: radialSegments,
  23422. heightSegments: heightSegments,
  23423. openEnded: openEnded,
  23424. thetaStart: thetaStart,
  23425. thetaLength: thetaLength
  23426. };
  23427. }
  23428. ConeBufferGeometry.prototype = Object.create( CylinderBufferGeometry.prototype );
  23429. ConeBufferGeometry.prototype.constructor = ConeBufferGeometry;
  23430. /**
  23431. * @author benaadams / https://twitter.com/ben_a_adams
  23432. * @author Mugen87 / https://github.com/Mugen87
  23433. * @author hughes
  23434. */
  23435. // CircleGeometry
  23436. function CircleGeometry( radius, segments, thetaStart, thetaLength ) {
  23437. Geometry.call( this );
  23438. this.type = 'CircleGeometry';
  23439. this.parameters = {
  23440. radius: radius,
  23441. segments: segments,
  23442. thetaStart: thetaStart,
  23443. thetaLength: thetaLength
  23444. };
  23445. this.fromBufferGeometry( new CircleBufferGeometry( radius, segments, thetaStart, thetaLength ) );
  23446. this.mergeVertices();
  23447. }
  23448. CircleGeometry.prototype = Object.create( Geometry.prototype );
  23449. CircleGeometry.prototype.constructor = CircleGeometry;
  23450. // CircleBufferGeometry
  23451. function CircleBufferGeometry( radius, segments, thetaStart, thetaLength ) {
  23452. BufferGeometry.call( this );
  23453. this.type = 'CircleBufferGeometry';
  23454. this.parameters = {
  23455. radius: radius,
  23456. segments: segments,
  23457. thetaStart: thetaStart,
  23458. thetaLength: thetaLength
  23459. };
  23460. radius = radius || 1;
  23461. segments = segments !== undefined ? Math.max( 3, segments ) : 8;
  23462. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  23463. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  23464. // buffers
  23465. var indices = [];
  23466. var vertices = [];
  23467. var normals = [];
  23468. var uvs = [];
  23469. // helper variables
  23470. var i, s;
  23471. var vertex = new Vector3();
  23472. var uv = new Vector2();
  23473. // center point
  23474. vertices.push( 0, 0, 0 );
  23475. normals.push( 0, 0, 1 );
  23476. uvs.push( 0.5, 0.5 );
  23477. for ( s = 0, i = 3; s <= segments; s ++, i += 3 ) {
  23478. var segment = thetaStart + s / segments * thetaLength;
  23479. // vertex
  23480. vertex.x = radius * Math.cos( segment );
  23481. vertex.y = radius * Math.sin( segment );
  23482. vertices.push( vertex.x, vertex.y, vertex.z );
  23483. // normal
  23484. normals.push( 0, 0, 1 );
  23485. // uvs
  23486. uv.x = ( vertices[ i ] / radius + 1 ) / 2;
  23487. uv.y = ( vertices[ i + 1 ] / radius + 1 ) / 2;
  23488. uvs.push( uv.x, uv.y );
  23489. }
  23490. // indices
  23491. for ( i = 1; i <= segments; i ++ ) {
  23492. indices.push( i, i + 1, 0 );
  23493. }
  23494. // build geometry
  23495. this.setIndex( indices );
  23496. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  23497. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  23498. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  23499. }
  23500. CircleBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  23501. CircleBufferGeometry.prototype.constructor = CircleBufferGeometry;
  23502. var Geometries = /*#__PURE__*/Object.freeze({
  23503. WireframeGeometry: WireframeGeometry,
  23504. ParametricGeometry: ParametricGeometry,
  23505. ParametricBufferGeometry: ParametricBufferGeometry,
  23506. TetrahedronGeometry: TetrahedronGeometry,
  23507. TetrahedronBufferGeometry: TetrahedronBufferGeometry,
  23508. OctahedronGeometry: OctahedronGeometry,
  23509. OctahedronBufferGeometry: OctahedronBufferGeometry,
  23510. IcosahedronGeometry: IcosahedronGeometry,
  23511. IcosahedronBufferGeometry: IcosahedronBufferGeometry,
  23512. DodecahedronGeometry: DodecahedronGeometry,
  23513. DodecahedronBufferGeometry: DodecahedronBufferGeometry,
  23514. PolyhedronGeometry: PolyhedronGeometry,
  23515. PolyhedronBufferGeometry: PolyhedronBufferGeometry,
  23516. TubeGeometry: TubeGeometry,
  23517. TubeBufferGeometry: TubeBufferGeometry,
  23518. TorusKnotGeometry: TorusKnotGeometry,
  23519. TorusKnotBufferGeometry: TorusKnotBufferGeometry,
  23520. TorusGeometry: TorusGeometry,
  23521. TorusBufferGeometry: TorusBufferGeometry,
  23522. TextGeometry: TextGeometry,
  23523. TextBufferGeometry: TextBufferGeometry,
  23524. SphereGeometry: SphereGeometry,
  23525. SphereBufferGeometry: SphereBufferGeometry,
  23526. RingGeometry: RingGeometry,
  23527. RingBufferGeometry: RingBufferGeometry,
  23528. PlaneGeometry: PlaneGeometry,
  23529. PlaneBufferGeometry: PlaneBufferGeometry,
  23530. LatheGeometry: LatheGeometry,
  23531. LatheBufferGeometry: LatheBufferGeometry,
  23532. ShapeGeometry: ShapeGeometry,
  23533. ShapeBufferGeometry: ShapeBufferGeometry,
  23534. ExtrudeGeometry: ExtrudeGeometry,
  23535. ExtrudeBufferGeometry: ExtrudeBufferGeometry,
  23536. EdgesGeometry: EdgesGeometry,
  23537. ConeGeometry: ConeGeometry,
  23538. ConeBufferGeometry: ConeBufferGeometry,
  23539. CylinderGeometry: CylinderGeometry,
  23540. CylinderBufferGeometry: CylinderBufferGeometry,
  23541. CircleGeometry: CircleGeometry,
  23542. CircleBufferGeometry: CircleBufferGeometry,
  23543. BoxGeometry: BoxGeometry,
  23544. BoxBufferGeometry: BoxBufferGeometry
  23545. });
  23546. /**
  23547. * @author mrdoob / http://mrdoob.com/
  23548. *
  23549. * parameters = {
  23550. * color: <THREE.Color>
  23551. * }
  23552. */
  23553. function ShadowMaterial( parameters ) {
  23554. Material.call( this );
  23555. this.type = 'ShadowMaterial';
  23556. this.color = new Color( 0x000000 );
  23557. this.transparent = true;
  23558. this.setValues( parameters );
  23559. }
  23560. ShadowMaterial.prototype = Object.create( Material.prototype );
  23561. ShadowMaterial.prototype.constructor = ShadowMaterial;
  23562. ShadowMaterial.prototype.isShadowMaterial = true;
  23563. ShadowMaterial.prototype.copy = function ( source ) {
  23564. Material.prototype.copy.call( this, source );
  23565. this.color.copy( source.color );
  23566. return this;
  23567. };
  23568. /**
  23569. * @author mrdoob / http://mrdoob.com/
  23570. */
  23571. function RawShaderMaterial( parameters ) {
  23572. ShaderMaterial.call( this, parameters );
  23573. this.type = 'RawShaderMaterial';
  23574. }
  23575. RawShaderMaterial.prototype = Object.create( ShaderMaterial.prototype );
  23576. RawShaderMaterial.prototype.constructor = RawShaderMaterial;
  23577. RawShaderMaterial.prototype.isRawShaderMaterial = true;
  23578. /**
  23579. * @author WestLangley / http://github.com/WestLangley
  23580. *
  23581. * parameters = {
  23582. * color: <hex>,
  23583. * roughness: <float>,
  23584. * metalness: <float>,
  23585. * opacity: <float>,
  23586. *
  23587. * map: new THREE.Texture( <Image> ),
  23588. *
  23589. * lightMap: new THREE.Texture( <Image> ),
  23590. * lightMapIntensity: <float>
  23591. *
  23592. * aoMap: new THREE.Texture( <Image> ),
  23593. * aoMapIntensity: <float>
  23594. *
  23595. * emissive: <hex>,
  23596. * emissiveIntensity: <float>
  23597. * emissiveMap: new THREE.Texture( <Image> ),
  23598. *
  23599. * bumpMap: new THREE.Texture( <Image> ),
  23600. * bumpScale: <float>,
  23601. *
  23602. * normalMap: new THREE.Texture( <Image> ),
  23603. * normalMapType: THREE.TangentSpaceNormalMap,
  23604. * normalScale: <Vector2>,
  23605. *
  23606. * displacementMap: new THREE.Texture( <Image> ),
  23607. * displacementScale: <float>,
  23608. * displacementBias: <float>,
  23609. *
  23610. * roughnessMap: new THREE.Texture( <Image> ),
  23611. *
  23612. * metalnessMap: new THREE.Texture( <Image> ),
  23613. *
  23614. * alphaMap: new THREE.Texture( <Image> ),
  23615. *
  23616. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  23617. * envMapIntensity: <float>
  23618. *
  23619. * refractionRatio: <float>,
  23620. *
  23621. * wireframe: <boolean>,
  23622. * wireframeLinewidth: <float>,
  23623. *
  23624. * skinning: <bool>,
  23625. * morphTargets: <bool>,
  23626. * morphNormals: <bool>
  23627. * }
  23628. */
  23629. function MeshStandardMaterial( parameters ) {
  23630. Material.call( this );
  23631. this.defines = { 'STANDARD': '' };
  23632. this.type = 'MeshStandardMaterial';
  23633. this.color = new Color( 0xffffff ); // diffuse
  23634. this.roughness = 0.5;
  23635. this.metalness = 0.5;
  23636. this.map = null;
  23637. this.lightMap = null;
  23638. this.lightMapIntensity = 1.0;
  23639. this.aoMap = null;
  23640. this.aoMapIntensity = 1.0;
  23641. this.emissive = new Color( 0x000000 );
  23642. this.emissiveIntensity = 1.0;
  23643. this.emissiveMap = null;
  23644. this.bumpMap = null;
  23645. this.bumpScale = 1;
  23646. this.normalMap = null;
  23647. this.normalMapType = TangentSpaceNormalMap;
  23648. this.normalScale = new Vector2( 1, 1 );
  23649. this.displacementMap = null;
  23650. this.displacementScale = 1;
  23651. this.displacementBias = 0;
  23652. this.roughnessMap = null;
  23653. this.metalnessMap = null;
  23654. this.alphaMap = null;
  23655. this.envMap = null;
  23656. this.envMapIntensity = 1.0;
  23657. this.refractionRatio = 0.98;
  23658. this.wireframe = false;
  23659. this.wireframeLinewidth = 1;
  23660. this.wireframeLinecap = 'round';
  23661. this.wireframeLinejoin = 'round';
  23662. this.skinning = false;
  23663. this.morphTargets = false;
  23664. this.morphNormals = false;
  23665. this.setValues( parameters );
  23666. }
  23667. MeshStandardMaterial.prototype = Object.create( Material.prototype );
  23668. MeshStandardMaterial.prototype.constructor = MeshStandardMaterial;
  23669. MeshStandardMaterial.prototype.isMeshStandardMaterial = true;
  23670. MeshStandardMaterial.prototype.copy = function ( source ) {
  23671. Material.prototype.copy.call( this, source );
  23672. this.defines = { 'STANDARD': '' };
  23673. this.color.copy( source.color );
  23674. this.roughness = source.roughness;
  23675. this.metalness = source.metalness;
  23676. this.map = source.map;
  23677. this.lightMap = source.lightMap;
  23678. this.lightMapIntensity = source.lightMapIntensity;
  23679. this.aoMap = source.aoMap;
  23680. this.aoMapIntensity = source.aoMapIntensity;
  23681. this.emissive.copy( source.emissive );
  23682. this.emissiveMap = source.emissiveMap;
  23683. this.emissiveIntensity = source.emissiveIntensity;
  23684. this.bumpMap = source.bumpMap;
  23685. this.bumpScale = source.bumpScale;
  23686. this.normalMap = source.normalMap;
  23687. this.normalMapType = source.normalMapType;
  23688. this.normalScale.copy( source.normalScale );
  23689. this.displacementMap = source.displacementMap;
  23690. this.displacementScale = source.displacementScale;
  23691. this.displacementBias = source.displacementBias;
  23692. this.roughnessMap = source.roughnessMap;
  23693. this.metalnessMap = source.metalnessMap;
  23694. this.alphaMap = source.alphaMap;
  23695. this.envMap = source.envMap;
  23696. this.envMapIntensity = source.envMapIntensity;
  23697. this.refractionRatio = source.refractionRatio;
  23698. this.wireframe = source.wireframe;
  23699. this.wireframeLinewidth = source.wireframeLinewidth;
  23700. this.wireframeLinecap = source.wireframeLinecap;
  23701. this.wireframeLinejoin = source.wireframeLinejoin;
  23702. this.skinning = source.skinning;
  23703. this.morphTargets = source.morphTargets;
  23704. this.morphNormals = source.morphNormals;
  23705. return this;
  23706. };
  23707. /**
  23708. * @author WestLangley / http://github.com/WestLangley
  23709. *
  23710. * parameters = {
  23711. * reflectivity: <float>
  23712. * clearCoat: <float>
  23713. * clearCoatRoughness: <float>
  23714. * }
  23715. */
  23716. function MeshPhysicalMaterial( parameters ) {
  23717. MeshStandardMaterial.call( this );
  23718. this.defines = { 'PHYSICAL': '' };
  23719. this.type = 'MeshPhysicalMaterial';
  23720. this.reflectivity = 0.5; // maps to F0 = 0.04
  23721. this.clearCoat = 0.0;
  23722. this.clearCoatRoughness = 0.0;
  23723. this.setValues( parameters );
  23724. }
  23725. MeshPhysicalMaterial.prototype = Object.create( MeshStandardMaterial.prototype );
  23726. MeshPhysicalMaterial.prototype.constructor = MeshPhysicalMaterial;
  23727. MeshPhysicalMaterial.prototype.isMeshPhysicalMaterial = true;
  23728. MeshPhysicalMaterial.prototype.copy = function ( source ) {
  23729. MeshStandardMaterial.prototype.copy.call( this, source );
  23730. this.defines = { 'PHYSICAL': '' };
  23731. this.reflectivity = source.reflectivity;
  23732. this.clearCoat = source.clearCoat;
  23733. this.clearCoatRoughness = source.clearCoatRoughness;
  23734. return this;
  23735. };
  23736. /**
  23737. * @author mrdoob / http://mrdoob.com/
  23738. * @author alteredq / http://alteredqualia.com/
  23739. *
  23740. * parameters = {
  23741. * color: <hex>,
  23742. * specular: <hex>,
  23743. * shininess: <float>,
  23744. * opacity: <float>,
  23745. *
  23746. * map: new THREE.Texture( <Image> ),
  23747. *
  23748. * lightMap: new THREE.Texture( <Image> ),
  23749. * lightMapIntensity: <float>
  23750. *
  23751. * aoMap: new THREE.Texture( <Image> ),
  23752. * aoMapIntensity: <float>
  23753. *
  23754. * emissive: <hex>,
  23755. * emissiveIntensity: <float>
  23756. * emissiveMap: new THREE.Texture( <Image> ),
  23757. *
  23758. * bumpMap: new THREE.Texture( <Image> ),
  23759. * bumpScale: <float>,
  23760. *
  23761. * normalMap: new THREE.Texture( <Image> ),
  23762. * normalMapType: THREE.TangentSpaceNormalMap,
  23763. * normalScale: <Vector2>,
  23764. *
  23765. * displacementMap: new THREE.Texture( <Image> ),
  23766. * displacementScale: <float>,
  23767. * displacementBias: <float>,
  23768. *
  23769. * specularMap: new THREE.Texture( <Image> ),
  23770. *
  23771. * alphaMap: new THREE.Texture( <Image> ),
  23772. *
  23773. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  23774. * combine: THREE.Multiply,
  23775. * reflectivity: <float>,
  23776. * refractionRatio: <float>,
  23777. *
  23778. * wireframe: <boolean>,
  23779. * wireframeLinewidth: <float>,
  23780. *
  23781. * skinning: <bool>,
  23782. * morphTargets: <bool>,
  23783. * morphNormals: <bool>
  23784. * }
  23785. */
  23786. function MeshPhongMaterial( parameters ) {
  23787. Material.call( this );
  23788. this.type = 'MeshPhongMaterial';
  23789. this.color = new Color( 0xffffff ); // diffuse
  23790. this.specular = new Color( 0x111111 );
  23791. this.shininess = 30;
  23792. this.map = null;
  23793. this.lightMap = null;
  23794. this.lightMapIntensity = 1.0;
  23795. this.aoMap = null;
  23796. this.aoMapIntensity = 1.0;
  23797. this.emissive = new Color( 0x000000 );
  23798. this.emissiveIntensity = 1.0;
  23799. this.emissiveMap = null;
  23800. this.bumpMap = null;
  23801. this.bumpScale = 1;
  23802. this.normalMap = null;
  23803. this.normalMapType = TangentSpaceNormalMap;
  23804. this.normalScale = new Vector2( 1, 1 );
  23805. this.displacementMap = null;
  23806. this.displacementScale = 1;
  23807. this.displacementBias = 0;
  23808. this.specularMap = null;
  23809. this.alphaMap = null;
  23810. this.envMap = null;
  23811. this.combine = MultiplyOperation;
  23812. this.reflectivity = 1;
  23813. this.refractionRatio = 0.98;
  23814. this.wireframe = false;
  23815. this.wireframeLinewidth = 1;
  23816. this.wireframeLinecap = 'round';
  23817. this.wireframeLinejoin = 'round';
  23818. this.skinning = false;
  23819. this.morphTargets = false;
  23820. this.morphNormals = false;
  23821. this.setValues( parameters );
  23822. }
  23823. MeshPhongMaterial.prototype = Object.create( Material.prototype );
  23824. MeshPhongMaterial.prototype.constructor = MeshPhongMaterial;
  23825. MeshPhongMaterial.prototype.isMeshPhongMaterial = true;
  23826. MeshPhongMaterial.prototype.copy = function ( source ) {
  23827. Material.prototype.copy.call( this, source );
  23828. this.color.copy( source.color );
  23829. this.specular.copy( source.specular );
  23830. this.shininess = source.shininess;
  23831. this.map = source.map;
  23832. this.lightMap = source.lightMap;
  23833. this.lightMapIntensity = source.lightMapIntensity;
  23834. this.aoMap = source.aoMap;
  23835. this.aoMapIntensity = source.aoMapIntensity;
  23836. this.emissive.copy( source.emissive );
  23837. this.emissiveMap = source.emissiveMap;
  23838. this.emissiveIntensity = source.emissiveIntensity;
  23839. this.bumpMap = source.bumpMap;
  23840. this.bumpScale = source.bumpScale;
  23841. this.normalMap = source.normalMap;
  23842. this.normalMapType = source.normalMapType;
  23843. this.normalScale.copy( source.normalScale );
  23844. this.displacementMap = source.displacementMap;
  23845. this.displacementScale = source.displacementScale;
  23846. this.displacementBias = source.displacementBias;
  23847. this.specularMap = source.specularMap;
  23848. this.alphaMap = source.alphaMap;
  23849. this.envMap = source.envMap;
  23850. this.combine = source.combine;
  23851. this.reflectivity = source.reflectivity;
  23852. this.refractionRatio = source.refractionRatio;
  23853. this.wireframe = source.wireframe;
  23854. this.wireframeLinewidth = source.wireframeLinewidth;
  23855. this.wireframeLinecap = source.wireframeLinecap;
  23856. this.wireframeLinejoin = source.wireframeLinejoin;
  23857. this.skinning = source.skinning;
  23858. this.morphTargets = source.morphTargets;
  23859. this.morphNormals = source.morphNormals;
  23860. return this;
  23861. };
  23862. /**
  23863. * @author takahirox / http://github.com/takahirox
  23864. *
  23865. * parameters = {
  23866. * gradientMap: new THREE.Texture( <Image> )
  23867. * }
  23868. */
  23869. function MeshToonMaterial( parameters ) {
  23870. MeshPhongMaterial.call( this );
  23871. this.defines = { 'TOON': '' };
  23872. this.type = 'MeshToonMaterial';
  23873. this.gradientMap = null;
  23874. this.setValues( parameters );
  23875. }
  23876. MeshToonMaterial.prototype = Object.create( MeshPhongMaterial.prototype );
  23877. MeshToonMaterial.prototype.constructor = MeshToonMaterial;
  23878. MeshToonMaterial.prototype.isMeshToonMaterial = true;
  23879. MeshToonMaterial.prototype.copy = function ( source ) {
  23880. MeshPhongMaterial.prototype.copy.call( this, source );
  23881. this.gradientMap = source.gradientMap;
  23882. return this;
  23883. };
  23884. /**
  23885. * @author mrdoob / http://mrdoob.com/
  23886. * @author WestLangley / http://github.com/WestLangley
  23887. *
  23888. * parameters = {
  23889. * opacity: <float>,
  23890. *
  23891. * bumpMap: new THREE.Texture( <Image> ),
  23892. * bumpScale: <float>,
  23893. *
  23894. * normalMap: new THREE.Texture( <Image> ),
  23895. * normalMapType: THREE.TangentSpaceNormalMap,
  23896. * normalScale: <Vector2>,
  23897. *
  23898. * displacementMap: new THREE.Texture( <Image> ),
  23899. * displacementScale: <float>,
  23900. * displacementBias: <float>,
  23901. *
  23902. * wireframe: <boolean>,
  23903. * wireframeLinewidth: <float>
  23904. *
  23905. * skinning: <bool>,
  23906. * morphTargets: <bool>,
  23907. * morphNormals: <bool>
  23908. * }
  23909. */
  23910. function MeshNormalMaterial( parameters ) {
  23911. Material.call( this );
  23912. this.type = 'MeshNormalMaterial';
  23913. this.bumpMap = null;
  23914. this.bumpScale = 1;
  23915. this.normalMap = null;
  23916. this.normalMapType = TangentSpaceNormalMap;
  23917. this.normalScale = new Vector2( 1, 1 );
  23918. this.displacementMap = null;
  23919. this.displacementScale = 1;
  23920. this.displacementBias = 0;
  23921. this.wireframe = false;
  23922. this.wireframeLinewidth = 1;
  23923. this.fog = false;
  23924. this.lights = false;
  23925. this.skinning = false;
  23926. this.morphTargets = false;
  23927. this.morphNormals = false;
  23928. this.setValues( parameters );
  23929. }
  23930. MeshNormalMaterial.prototype = Object.create( Material.prototype );
  23931. MeshNormalMaterial.prototype.constructor = MeshNormalMaterial;
  23932. MeshNormalMaterial.prototype.isMeshNormalMaterial = true;
  23933. MeshNormalMaterial.prototype.copy = function ( source ) {
  23934. Material.prototype.copy.call( this, source );
  23935. this.bumpMap = source.bumpMap;
  23936. this.bumpScale = source.bumpScale;
  23937. this.normalMap = source.normalMap;
  23938. this.normalMapType = source.normalMapType;
  23939. this.normalScale.copy( source.normalScale );
  23940. this.displacementMap = source.displacementMap;
  23941. this.displacementScale = source.displacementScale;
  23942. this.displacementBias = source.displacementBias;
  23943. this.wireframe = source.wireframe;
  23944. this.wireframeLinewidth = source.wireframeLinewidth;
  23945. this.skinning = source.skinning;
  23946. this.morphTargets = source.morphTargets;
  23947. this.morphNormals = source.morphNormals;
  23948. return this;
  23949. };
  23950. /**
  23951. * @author mrdoob / http://mrdoob.com/
  23952. * @author alteredq / http://alteredqualia.com/
  23953. *
  23954. * parameters = {
  23955. * color: <hex>,
  23956. * opacity: <float>,
  23957. *
  23958. * map: new THREE.Texture( <Image> ),
  23959. *
  23960. * lightMap: new THREE.Texture( <Image> ),
  23961. * lightMapIntensity: <float>
  23962. *
  23963. * aoMap: new THREE.Texture( <Image> ),
  23964. * aoMapIntensity: <float>
  23965. *
  23966. * emissive: <hex>,
  23967. * emissiveIntensity: <float>
  23968. * emissiveMap: new THREE.Texture( <Image> ),
  23969. *
  23970. * specularMap: new THREE.Texture( <Image> ),
  23971. *
  23972. * alphaMap: new THREE.Texture( <Image> ),
  23973. *
  23974. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  23975. * combine: THREE.Multiply,
  23976. * reflectivity: <float>,
  23977. * refractionRatio: <float>,
  23978. *
  23979. * wireframe: <boolean>,
  23980. * wireframeLinewidth: <float>,
  23981. *
  23982. * skinning: <bool>,
  23983. * morphTargets: <bool>,
  23984. * morphNormals: <bool>
  23985. * }
  23986. */
  23987. function MeshLambertMaterial( parameters ) {
  23988. Material.call( this );
  23989. this.type = 'MeshLambertMaterial';
  23990. this.color = new Color( 0xffffff ); // diffuse
  23991. this.map = null;
  23992. this.lightMap = null;
  23993. this.lightMapIntensity = 1.0;
  23994. this.aoMap = null;
  23995. this.aoMapIntensity = 1.0;
  23996. this.emissive = new Color( 0x000000 );
  23997. this.emissiveIntensity = 1.0;
  23998. this.emissiveMap = null;
  23999. this.specularMap = null;
  24000. this.alphaMap = null;
  24001. this.envMap = null;
  24002. this.combine = MultiplyOperation;
  24003. this.reflectivity = 1;
  24004. this.refractionRatio = 0.98;
  24005. this.wireframe = false;
  24006. this.wireframeLinewidth = 1;
  24007. this.wireframeLinecap = 'round';
  24008. this.wireframeLinejoin = 'round';
  24009. this.skinning = false;
  24010. this.morphTargets = false;
  24011. this.morphNormals = false;
  24012. this.setValues( parameters );
  24013. }
  24014. MeshLambertMaterial.prototype = Object.create( Material.prototype );
  24015. MeshLambertMaterial.prototype.constructor = MeshLambertMaterial;
  24016. MeshLambertMaterial.prototype.isMeshLambertMaterial = true;
  24017. MeshLambertMaterial.prototype.copy = function ( source ) {
  24018. Material.prototype.copy.call( this, source );
  24019. this.color.copy( source.color );
  24020. this.map = source.map;
  24021. this.lightMap = source.lightMap;
  24022. this.lightMapIntensity = source.lightMapIntensity;
  24023. this.aoMap = source.aoMap;
  24024. this.aoMapIntensity = source.aoMapIntensity;
  24025. this.emissive.copy( source.emissive );
  24026. this.emissiveMap = source.emissiveMap;
  24027. this.emissiveIntensity = source.emissiveIntensity;
  24028. this.specularMap = source.specularMap;
  24029. this.alphaMap = source.alphaMap;
  24030. this.envMap = source.envMap;
  24031. this.combine = source.combine;
  24032. this.reflectivity = source.reflectivity;
  24033. this.refractionRatio = source.refractionRatio;
  24034. this.wireframe = source.wireframe;
  24035. this.wireframeLinewidth = source.wireframeLinewidth;
  24036. this.wireframeLinecap = source.wireframeLinecap;
  24037. this.wireframeLinejoin = source.wireframeLinejoin;
  24038. this.skinning = source.skinning;
  24039. this.morphTargets = source.morphTargets;
  24040. this.morphNormals = source.morphNormals;
  24041. return this;
  24042. };
  24043. /**
  24044. * @author WestLangley / http://github.com/WestLangley
  24045. *
  24046. * parameters = {
  24047. * color: <hex>,
  24048. * opacity: <float>,
  24049. *
  24050. * matcap: new THREE.Texture( <Image> ),
  24051. *
  24052. * map: new THREE.Texture( <Image> ),
  24053. *
  24054. * bumpMap: new THREE.Texture( <Image> ),
  24055. * bumpScale: <float>,
  24056. *
  24057. * normalMap: new THREE.Texture( <Image> ),
  24058. * normalMapType: THREE.TangentSpaceNormalMap,
  24059. * normalScale: <Vector2>,
  24060. *
  24061. * displacementMap: new THREE.Texture( <Image> ),
  24062. * displacementScale: <float>,
  24063. * displacementBias: <float>,
  24064. *
  24065. * alphaMap: new THREE.Texture( <Image> ),
  24066. *
  24067. * skinning: <bool>,
  24068. * morphTargets: <bool>,
  24069. * morphNormals: <bool>
  24070. * }
  24071. */
  24072. function MeshMatcapMaterial( parameters ) {
  24073. Material.call( this );
  24074. this.defines = { 'MATCAP': '' };
  24075. this.type = 'MeshMatcapMaterial';
  24076. this.color = new Color( 0xffffff ); // diffuse
  24077. this.matcap = null;
  24078. this.map = null;
  24079. this.bumpMap = null;
  24080. this.bumpScale = 1;
  24081. this.normalMap = null;
  24082. this.normalMapType = TangentSpaceNormalMap;
  24083. this.normalScale = new Vector2( 1, 1 );
  24084. this.displacementMap = null;
  24085. this.displacementScale = 1;
  24086. this.displacementBias = 0;
  24087. this.alphaMap = null;
  24088. this.skinning = false;
  24089. this.morphTargets = false;
  24090. this.morphNormals = false;
  24091. this.lights = false;
  24092. this.setValues( parameters );
  24093. }
  24094. MeshMatcapMaterial.prototype = Object.create( Material.prototype );
  24095. MeshMatcapMaterial.prototype.constructor = MeshMatcapMaterial;
  24096. MeshMatcapMaterial.prototype.isMeshMatcapMaterial = true;
  24097. MeshMatcapMaterial.prototype.copy = function ( source ) {
  24098. Material.prototype.copy.call( this, source );
  24099. this.defines = { 'MATCAP': '' };
  24100. this.color.copy( source.color );
  24101. this.matcap = source.matcap;
  24102. this.map = source.map;
  24103. this.bumpMap = source.bumpMap;
  24104. this.bumpScale = source.bumpScale;
  24105. this.normalMap = source.normalMap;
  24106. this.normalMapType = source.normalMapType;
  24107. this.normalScale.copy( source.normalScale );
  24108. this.displacementMap = source.displacementMap;
  24109. this.displacementScale = source.displacementScale;
  24110. this.displacementBias = source.displacementBias;
  24111. this.alphaMap = source.alphaMap;
  24112. this.skinning = source.skinning;
  24113. this.morphTargets = source.morphTargets;
  24114. this.morphNormals = source.morphNormals;
  24115. return this;
  24116. };
  24117. /**
  24118. * @author alteredq / http://alteredqualia.com/
  24119. *
  24120. * parameters = {
  24121. * color: <hex>,
  24122. * opacity: <float>,
  24123. *
  24124. * linewidth: <float>,
  24125. *
  24126. * scale: <float>,
  24127. * dashSize: <float>,
  24128. * gapSize: <float>
  24129. * }
  24130. */
  24131. function LineDashedMaterial( parameters ) {
  24132. LineBasicMaterial.call( this );
  24133. this.type = 'LineDashedMaterial';
  24134. this.scale = 1;
  24135. this.dashSize = 3;
  24136. this.gapSize = 1;
  24137. this.setValues( parameters );
  24138. }
  24139. LineDashedMaterial.prototype = Object.create( LineBasicMaterial.prototype );
  24140. LineDashedMaterial.prototype.constructor = LineDashedMaterial;
  24141. LineDashedMaterial.prototype.isLineDashedMaterial = true;
  24142. LineDashedMaterial.prototype.copy = function ( source ) {
  24143. LineBasicMaterial.prototype.copy.call( this, source );
  24144. this.scale = source.scale;
  24145. this.dashSize = source.dashSize;
  24146. this.gapSize = source.gapSize;
  24147. return this;
  24148. };
  24149. var Materials = /*#__PURE__*/Object.freeze({
  24150. ShadowMaterial: ShadowMaterial,
  24151. SpriteMaterial: SpriteMaterial,
  24152. RawShaderMaterial: RawShaderMaterial,
  24153. ShaderMaterial: ShaderMaterial,
  24154. PointsMaterial: PointsMaterial,
  24155. MeshPhysicalMaterial: MeshPhysicalMaterial,
  24156. MeshStandardMaterial: MeshStandardMaterial,
  24157. MeshPhongMaterial: MeshPhongMaterial,
  24158. MeshToonMaterial: MeshToonMaterial,
  24159. MeshNormalMaterial: MeshNormalMaterial,
  24160. MeshLambertMaterial: MeshLambertMaterial,
  24161. MeshDepthMaterial: MeshDepthMaterial,
  24162. MeshDistanceMaterial: MeshDistanceMaterial,
  24163. MeshBasicMaterial: MeshBasicMaterial,
  24164. MeshMatcapMaterial: MeshMatcapMaterial,
  24165. LineDashedMaterial: LineDashedMaterial,
  24166. LineBasicMaterial: LineBasicMaterial,
  24167. Material: Material
  24168. });
  24169. /**
  24170. * @author tschw
  24171. * @author Ben Houston / http://clara.io/
  24172. * @author David Sarno / http://lighthaus.us/
  24173. */
  24174. var AnimationUtils = {
  24175. // same as Array.prototype.slice, but also works on typed arrays
  24176. arraySlice: function ( array, from, to ) {
  24177. if ( AnimationUtils.isTypedArray( array ) ) {
  24178. // in ios9 array.subarray(from, undefined) will return empty array
  24179. // but array.subarray(from) or array.subarray(from, len) is correct
  24180. return new array.constructor( array.subarray( from, to !== undefined ? to : array.length ) );
  24181. }
  24182. return array.slice( from, to );
  24183. },
  24184. // converts an array to a specific type
  24185. convertArray: function ( array, type, forceClone ) {
  24186. if ( ! array || // let 'undefined' and 'null' pass
  24187. ! forceClone && array.constructor === type ) return array;
  24188. if ( typeof type.BYTES_PER_ELEMENT === 'number' ) {
  24189. return new type( array ); // create typed array
  24190. }
  24191. return Array.prototype.slice.call( array ); // create Array
  24192. },
  24193. isTypedArray: function ( object ) {
  24194. return ArrayBuffer.isView( object ) &&
  24195. ! ( object instanceof DataView );
  24196. },
  24197. // returns an array by which times and values can be sorted
  24198. getKeyframeOrder: function ( times ) {
  24199. function compareTime( i, j ) {
  24200. return times[ i ] - times[ j ];
  24201. }
  24202. var n = times.length;
  24203. var result = new Array( n );
  24204. for ( var i = 0; i !== n; ++ i ) result[ i ] = i;
  24205. result.sort( compareTime );
  24206. return result;
  24207. },
  24208. // uses the array previously returned by 'getKeyframeOrder' to sort data
  24209. sortedArray: function ( values, stride, order ) {
  24210. var nValues = values.length;
  24211. var result = new values.constructor( nValues );
  24212. for ( var i = 0, dstOffset = 0; dstOffset !== nValues; ++ i ) {
  24213. var srcOffset = order[ i ] * stride;
  24214. for ( var j = 0; j !== stride; ++ j ) {
  24215. result[ dstOffset ++ ] = values[ srcOffset + j ];
  24216. }
  24217. }
  24218. return result;
  24219. },
  24220. // function for parsing AOS keyframe formats
  24221. flattenJSON: function ( jsonKeys, times, values, valuePropertyName ) {
  24222. var i = 1, key = jsonKeys[ 0 ];
  24223. while ( key !== undefined && key[ valuePropertyName ] === undefined ) {
  24224. key = jsonKeys[ i ++ ];
  24225. }
  24226. if ( key === undefined ) return; // no data
  24227. var value = key[ valuePropertyName ];
  24228. if ( value === undefined ) return; // no data
  24229. if ( Array.isArray( value ) ) {
  24230. do {
  24231. value = key[ valuePropertyName ];
  24232. if ( value !== undefined ) {
  24233. times.push( key.time );
  24234. values.push.apply( values, value ); // push all elements
  24235. }
  24236. key = jsonKeys[ i ++ ];
  24237. } while ( key !== undefined );
  24238. } else if ( value.toArray !== undefined ) {
  24239. // ...assume THREE.Math-ish
  24240. do {
  24241. value = key[ valuePropertyName ];
  24242. if ( value !== undefined ) {
  24243. times.push( key.time );
  24244. value.toArray( values, values.length );
  24245. }
  24246. key = jsonKeys[ i ++ ];
  24247. } while ( key !== undefined );
  24248. } else {
  24249. // otherwise push as-is
  24250. do {
  24251. value = key[ valuePropertyName ];
  24252. if ( value !== undefined ) {
  24253. times.push( key.time );
  24254. values.push( value );
  24255. }
  24256. key = jsonKeys[ i ++ ];
  24257. } while ( key !== undefined );
  24258. }
  24259. }
  24260. };
  24261. /**
  24262. * Abstract base class of interpolants over parametric samples.
  24263. *
  24264. * The parameter domain is one dimensional, typically the time or a path
  24265. * along a curve defined by the data.
  24266. *
  24267. * The sample values can have any dimensionality and derived classes may
  24268. * apply special interpretations to the data.
  24269. *
  24270. * This class provides the interval seek in a Template Method, deferring
  24271. * the actual interpolation to derived classes.
  24272. *
  24273. * Time complexity is O(1) for linear access crossing at most two points
  24274. * and O(log N) for random access, where N is the number of positions.
  24275. *
  24276. * References:
  24277. *
  24278. * http://www.oodesign.com/template-method-pattern.html
  24279. *
  24280. * @author tschw
  24281. */
  24282. function Interpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  24283. this.parameterPositions = parameterPositions;
  24284. this._cachedIndex = 0;
  24285. this.resultBuffer = resultBuffer !== undefined ?
  24286. resultBuffer : new sampleValues.constructor( sampleSize );
  24287. this.sampleValues = sampleValues;
  24288. this.valueSize = sampleSize;
  24289. }
  24290. Object.assign( Interpolant.prototype, {
  24291. evaluate: function ( t ) {
  24292. var pp = this.parameterPositions,
  24293. i1 = this._cachedIndex,
  24294. t1 = pp[ i1 ],
  24295. t0 = pp[ i1 - 1 ];
  24296. validate_interval: {
  24297. seek: {
  24298. var right;
  24299. linear_scan: {
  24300. //- See http://jsperf.com/comparison-to-undefined/3
  24301. //- slower code:
  24302. //-
  24303. //- if ( t >= t1 || t1 === undefined ) {
  24304. forward_scan: if ( ! ( t < t1 ) ) {
  24305. for ( var giveUpAt = i1 + 2; ; ) {
  24306. if ( t1 === undefined ) {
  24307. if ( t < t0 ) break forward_scan;
  24308. // after end
  24309. i1 = pp.length;
  24310. this._cachedIndex = i1;
  24311. return this.afterEnd_( i1 - 1, t, t0 );
  24312. }
  24313. if ( i1 === giveUpAt ) break; // this loop
  24314. t0 = t1;
  24315. t1 = pp[ ++ i1 ];
  24316. if ( t < t1 ) {
  24317. // we have arrived at the sought interval
  24318. break seek;
  24319. }
  24320. }
  24321. // prepare binary search on the right side of the index
  24322. right = pp.length;
  24323. break linear_scan;
  24324. }
  24325. //- slower code:
  24326. //- if ( t < t0 || t0 === undefined ) {
  24327. if ( ! ( t >= t0 ) ) {
  24328. // looping?
  24329. var t1global = pp[ 1 ];
  24330. if ( t < t1global ) {
  24331. i1 = 2; // + 1, using the scan for the details
  24332. t0 = t1global;
  24333. }
  24334. // linear reverse scan
  24335. for ( var giveUpAt = i1 - 2; ; ) {
  24336. if ( t0 === undefined ) {
  24337. // before start
  24338. this._cachedIndex = 0;
  24339. return this.beforeStart_( 0, t, t1 );
  24340. }
  24341. if ( i1 === giveUpAt ) break; // this loop
  24342. t1 = t0;
  24343. t0 = pp[ -- i1 - 1 ];
  24344. if ( t >= t0 ) {
  24345. // we have arrived at the sought interval
  24346. break seek;
  24347. }
  24348. }
  24349. // prepare binary search on the left side of the index
  24350. right = i1;
  24351. i1 = 0;
  24352. break linear_scan;
  24353. }
  24354. // the interval is valid
  24355. break validate_interval;
  24356. } // linear scan
  24357. // binary search
  24358. while ( i1 < right ) {
  24359. var mid = ( i1 + right ) >>> 1;
  24360. if ( t < pp[ mid ] ) {
  24361. right = mid;
  24362. } else {
  24363. i1 = mid + 1;
  24364. }
  24365. }
  24366. t1 = pp[ i1 ];
  24367. t0 = pp[ i1 - 1 ];
  24368. // check boundary cases, again
  24369. if ( t0 === undefined ) {
  24370. this._cachedIndex = 0;
  24371. return this.beforeStart_( 0, t, t1 );
  24372. }
  24373. if ( t1 === undefined ) {
  24374. i1 = pp.length;
  24375. this._cachedIndex = i1;
  24376. return this.afterEnd_( i1 - 1, t0, t );
  24377. }
  24378. } // seek
  24379. this._cachedIndex = i1;
  24380. this.intervalChanged_( i1, t0, t1 );
  24381. } // validate_interval
  24382. return this.interpolate_( i1, t0, t, t1 );
  24383. },
  24384. settings: null, // optional, subclass-specific settings structure
  24385. // Note: The indirection allows central control of many interpolants.
  24386. // --- Protected interface
  24387. DefaultSettings_: {},
  24388. getSettings_: function () {
  24389. return this.settings || this.DefaultSettings_;
  24390. },
  24391. copySampleValue_: function ( index ) {
  24392. // copies a sample value to the result buffer
  24393. var result = this.resultBuffer,
  24394. values = this.sampleValues,
  24395. stride = this.valueSize,
  24396. offset = index * stride;
  24397. for ( var i = 0; i !== stride; ++ i ) {
  24398. result[ i ] = values[ offset + i ];
  24399. }
  24400. return result;
  24401. },
  24402. // Template methods for derived classes:
  24403. interpolate_: function ( /* i1, t0, t, t1 */ ) {
  24404. throw new Error( 'call to abstract method' );
  24405. // implementations shall return this.resultBuffer
  24406. },
  24407. intervalChanged_: function ( /* i1, t0, t1 */ ) {
  24408. // empty
  24409. }
  24410. } );
  24411. //!\ DECLARE ALIAS AFTER assign prototype !
  24412. Object.assign( Interpolant.prototype, {
  24413. //( 0, t, t0 ), returns this.resultBuffer
  24414. beforeStart_: Interpolant.prototype.copySampleValue_,
  24415. //( N-1, tN-1, t ), returns this.resultBuffer
  24416. afterEnd_: Interpolant.prototype.copySampleValue_,
  24417. } );
  24418. /**
  24419. * Fast and simple cubic spline interpolant.
  24420. *
  24421. * It was derived from a Hermitian construction setting the first derivative
  24422. * at each sample position to the linear slope between neighboring positions
  24423. * over their parameter interval.
  24424. *
  24425. * @author tschw
  24426. */
  24427. function CubicInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  24428. Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  24429. this._weightPrev = - 0;
  24430. this._offsetPrev = - 0;
  24431. this._weightNext = - 0;
  24432. this._offsetNext = - 0;
  24433. }
  24434. CubicInterpolant.prototype = Object.assign( Object.create( Interpolant.prototype ), {
  24435. constructor: CubicInterpolant,
  24436. DefaultSettings_: {
  24437. endingStart: ZeroCurvatureEnding,
  24438. endingEnd: ZeroCurvatureEnding
  24439. },
  24440. intervalChanged_: function ( i1, t0, t1 ) {
  24441. var pp = this.parameterPositions,
  24442. iPrev = i1 - 2,
  24443. iNext = i1 + 1,
  24444. tPrev = pp[ iPrev ],
  24445. tNext = pp[ iNext ];
  24446. if ( tPrev === undefined ) {
  24447. switch ( this.getSettings_().endingStart ) {
  24448. case ZeroSlopeEnding:
  24449. // f'(t0) = 0
  24450. iPrev = i1;
  24451. tPrev = 2 * t0 - t1;
  24452. break;
  24453. case WrapAroundEnding:
  24454. // use the other end of the curve
  24455. iPrev = pp.length - 2;
  24456. tPrev = t0 + pp[ iPrev ] - pp[ iPrev + 1 ];
  24457. break;
  24458. default: // ZeroCurvatureEnding
  24459. // f''(t0) = 0 a.k.a. Natural Spline
  24460. iPrev = i1;
  24461. tPrev = t1;
  24462. }
  24463. }
  24464. if ( tNext === undefined ) {
  24465. switch ( this.getSettings_().endingEnd ) {
  24466. case ZeroSlopeEnding:
  24467. // f'(tN) = 0
  24468. iNext = i1;
  24469. tNext = 2 * t1 - t0;
  24470. break;
  24471. case WrapAroundEnding:
  24472. // use the other end of the curve
  24473. iNext = 1;
  24474. tNext = t1 + pp[ 1 ] - pp[ 0 ];
  24475. break;
  24476. default: // ZeroCurvatureEnding
  24477. // f''(tN) = 0, a.k.a. Natural Spline
  24478. iNext = i1 - 1;
  24479. tNext = t0;
  24480. }
  24481. }
  24482. var halfDt = ( t1 - t0 ) * 0.5,
  24483. stride = this.valueSize;
  24484. this._weightPrev = halfDt / ( t0 - tPrev );
  24485. this._weightNext = halfDt / ( tNext - t1 );
  24486. this._offsetPrev = iPrev * stride;
  24487. this._offsetNext = iNext * stride;
  24488. },
  24489. interpolate_: function ( i1, t0, t, t1 ) {
  24490. var result = this.resultBuffer,
  24491. values = this.sampleValues,
  24492. stride = this.valueSize,
  24493. o1 = i1 * stride, o0 = o1 - stride,
  24494. oP = this._offsetPrev, oN = this._offsetNext,
  24495. wP = this._weightPrev, wN = this._weightNext,
  24496. p = ( t - t0 ) / ( t1 - t0 ),
  24497. pp = p * p,
  24498. ppp = pp * p;
  24499. // evaluate polynomials
  24500. var sP = - wP * ppp + 2 * wP * pp - wP * p;
  24501. var s0 = ( 1 + wP ) * ppp + ( - 1.5 - 2 * wP ) * pp + ( - 0.5 + wP ) * p + 1;
  24502. var s1 = ( - 1 - wN ) * ppp + ( 1.5 + wN ) * pp + 0.5 * p;
  24503. var sN = wN * ppp - wN * pp;
  24504. // combine data linearly
  24505. for ( var i = 0; i !== stride; ++ i ) {
  24506. result[ i ] =
  24507. sP * values[ oP + i ] +
  24508. s0 * values[ o0 + i ] +
  24509. s1 * values[ o1 + i ] +
  24510. sN * values[ oN + i ];
  24511. }
  24512. return result;
  24513. }
  24514. } );
  24515. /**
  24516. * @author tschw
  24517. */
  24518. function LinearInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  24519. Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  24520. }
  24521. LinearInterpolant.prototype = Object.assign( Object.create( Interpolant.prototype ), {
  24522. constructor: LinearInterpolant,
  24523. interpolate_: function ( i1, t0, t, t1 ) {
  24524. var result = this.resultBuffer,
  24525. values = this.sampleValues,
  24526. stride = this.valueSize,
  24527. offset1 = i1 * stride,
  24528. offset0 = offset1 - stride,
  24529. weight1 = ( t - t0 ) / ( t1 - t0 ),
  24530. weight0 = 1 - weight1;
  24531. for ( var i = 0; i !== stride; ++ i ) {
  24532. result[ i ] =
  24533. values[ offset0 + i ] * weight0 +
  24534. values[ offset1 + i ] * weight1;
  24535. }
  24536. return result;
  24537. }
  24538. } );
  24539. /**
  24540. *
  24541. * Interpolant that evaluates to the sample value at the position preceeding
  24542. * the parameter.
  24543. *
  24544. * @author tschw
  24545. */
  24546. function DiscreteInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  24547. Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  24548. }
  24549. DiscreteInterpolant.prototype = Object.assign( Object.create( Interpolant.prototype ), {
  24550. constructor: DiscreteInterpolant,
  24551. interpolate_: function ( i1 /*, t0, t, t1 */ ) {
  24552. return this.copySampleValue_( i1 - 1 );
  24553. }
  24554. } );
  24555. /**
  24556. *
  24557. * A timed sequence of keyframes for a specific property.
  24558. *
  24559. *
  24560. * @author Ben Houston / http://clara.io/
  24561. * @author David Sarno / http://lighthaus.us/
  24562. * @author tschw
  24563. */
  24564. function KeyframeTrack( name, times, values, interpolation ) {
  24565. if ( name === undefined ) throw new Error( 'THREE.KeyframeTrack: track name is undefined' );
  24566. if ( times === undefined || times.length === 0 ) throw new Error( 'THREE.KeyframeTrack: no keyframes in track named ' + name );
  24567. this.name = name;
  24568. this.times = AnimationUtils.convertArray( times, this.TimeBufferType );
  24569. this.values = AnimationUtils.convertArray( values, this.ValueBufferType );
  24570. this.setInterpolation( interpolation || this.DefaultInterpolation );
  24571. }
  24572. // Static methods
  24573. Object.assign( KeyframeTrack, {
  24574. // Serialization (in static context, because of constructor invocation
  24575. // and automatic invocation of .toJSON):
  24576. toJSON: function ( track ) {
  24577. var trackType = track.constructor;
  24578. var json;
  24579. // derived classes can define a static toJSON method
  24580. if ( trackType.toJSON !== undefined ) {
  24581. json = trackType.toJSON( track );
  24582. } else {
  24583. // by default, we assume the data can be serialized as-is
  24584. json = {
  24585. 'name': track.name,
  24586. 'times': AnimationUtils.convertArray( track.times, Array ),
  24587. 'values': AnimationUtils.convertArray( track.values, Array )
  24588. };
  24589. var interpolation = track.getInterpolation();
  24590. if ( interpolation !== track.DefaultInterpolation ) {
  24591. json.interpolation = interpolation;
  24592. }
  24593. }
  24594. json.type = track.ValueTypeName; // mandatory
  24595. return json;
  24596. }
  24597. } );
  24598. Object.assign( KeyframeTrack.prototype, {
  24599. constructor: KeyframeTrack,
  24600. TimeBufferType: Float32Array,
  24601. ValueBufferType: Float32Array,
  24602. DefaultInterpolation: InterpolateLinear,
  24603. InterpolantFactoryMethodDiscrete: function ( result ) {
  24604. return new DiscreteInterpolant( this.times, this.values, this.getValueSize(), result );
  24605. },
  24606. InterpolantFactoryMethodLinear: function ( result ) {
  24607. return new LinearInterpolant( this.times, this.values, this.getValueSize(), result );
  24608. },
  24609. InterpolantFactoryMethodSmooth: function ( result ) {
  24610. return new CubicInterpolant( this.times, this.values, this.getValueSize(), result );
  24611. },
  24612. setInterpolation: function ( interpolation ) {
  24613. var factoryMethod;
  24614. switch ( interpolation ) {
  24615. case InterpolateDiscrete:
  24616. factoryMethod = this.InterpolantFactoryMethodDiscrete;
  24617. break;
  24618. case InterpolateLinear:
  24619. factoryMethod = this.InterpolantFactoryMethodLinear;
  24620. break;
  24621. case InterpolateSmooth:
  24622. factoryMethod = this.InterpolantFactoryMethodSmooth;
  24623. break;
  24624. }
  24625. if ( factoryMethod === undefined ) {
  24626. var message = "unsupported interpolation for " +
  24627. this.ValueTypeName + " keyframe track named " + this.name;
  24628. if ( this.createInterpolant === undefined ) {
  24629. // fall back to default, unless the default itself is messed up
  24630. if ( interpolation !== this.DefaultInterpolation ) {
  24631. this.setInterpolation( this.DefaultInterpolation );
  24632. } else {
  24633. throw new Error( message ); // fatal, in this case
  24634. }
  24635. }
  24636. console.warn( 'THREE.KeyframeTrack:', message );
  24637. return this;
  24638. }
  24639. this.createInterpolant = factoryMethod;
  24640. return this;
  24641. },
  24642. getInterpolation: function () {
  24643. switch ( this.createInterpolant ) {
  24644. case this.InterpolantFactoryMethodDiscrete:
  24645. return InterpolateDiscrete;
  24646. case this.InterpolantFactoryMethodLinear:
  24647. return InterpolateLinear;
  24648. case this.InterpolantFactoryMethodSmooth:
  24649. return InterpolateSmooth;
  24650. }
  24651. },
  24652. getValueSize: function () {
  24653. return this.values.length / this.times.length;
  24654. },
  24655. // move all keyframes either forwards or backwards in time
  24656. shift: function ( timeOffset ) {
  24657. if ( timeOffset !== 0.0 ) {
  24658. var times = this.times;
  24659. for ( var i = 0, n = times.length; i !== n; ++ i ) {
  24660. times[ i ] += timeOffset;
  24661. }
  24662. }
  24663. return this;
  24664. },
  24665. // scale all keyframe times by a factor (useful for frame <-> seconds conversions)
  24666. scale: function ( timeScale ) {
  24667. if ( timeScale !== 1.0 ) {
  24668. var times = this.times;
  24669. for ( var i = 0, n = times.length; i !== n; ++ i ) {
  24670. times[ i ] *= timeScale;
  24671. }
  24672. }
  24673. return this;
  24674. },
  24675. // removes keyframes before and after animation without changing any values within the range [startTime, endTime].
  24676. // IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values
  24677. trim: function ( startTime, endTime ) {
  24678. var times = this.times,
  24679. nKeys = times.length,
  24680. from = 0,
  24681. to = nKeys - 1;
  24682. while ( from !== nKeys && times[ from ] < startTime ) {
  24683. ++ from;
  24684. }
  24685. while ( to !== - 1 && times[ to ] > endTime ) {
  24686. -- to;
  24687. }
  24688. ++ to; // inclusive -> exclusive bound
  24689. if ( from !== 0 || to !== nKeys ) {
  24690. // empty tracks are forbidden, so keep at least one keyframe
  24691. if ( from >= to ) to = Math.max( to, 1 ), from = to - 1;
  24692. var stride = this.getValueSize();
  24693. this.times = AnimationUtils.arraySlice( times, from, to );
  24694. this.values = AnimationUtils.arraySlice( this.values, from * stride, to * stride );
  24695. }
  24696. return this;
  24697. },
  24698. // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable
  24699. validate: function () {
  24700. var valid = true;
  24701. var valueSize = this.getValueSize();
  24702. if ( valueSize - Math.floor( valueSize ) !== 0 ) {
  24703. console.error( 'THREE.KeyframeTrack: Invalid value size in track.', this );
  24704. valid = false;
  24705. }
  24706. var times = this.times,
  24707. values = this.values,
  24708. nKeys = times.length;
  24709. if ( nKeys === 0 ) {
  24710. console.error( 'THREE.KeyframeTrack: Track is empty.', this );
  24711. valid = false;
  24712. }
  24713. var prevTime = null;
  24714. for ( var i = 0; i !== nKeys; i ++ ) {
  24715. var currTime = times[ i ];
  24716. if ( typeof currTime === 'number' && isNaN( currTime ) ) {
  24717. console.error( 'THREE.KeyframeTrack: Time is not a valid number.', this, i, currTime );
  24718. valid = false;
  24719. break;
  24720. }
  24721. if ( prevTime !== null && prevTime > currTime ) {
  24722. console.error( 'THREE.KeyframeTrack: Out of order keys.', this, i, currTime, prevTime );
  24723. valid = false;
  24724. break;
  24725. }
  24726. prevTime = currTime;
  24727. }
  24728. if ( values !== undefined ) {
  24729. if ( AnimationUtils.isTypedArray( values ) ) {
  24730. for ( var i = 0, n = values.length; i !== n; ++ i ) {
  24731. var value = values[ i ];
  24732. if ( isNaN( value ) ) {
  24733. console.error( 'THREE.KeyframeTrack: Value is not a valid number.', this, i, value );
  24734. valid = false;
  24735. break;
  24736. }
  24737. }
  24738. }
  24739. }
  24740. return valid;
  24741. },
  24742. // removes equivalent sequential keys as common in morph target sequences
  24743. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  24744. optimize: function () {
  24745. var times = this.times,
  24746. values = this.values,
  24747. stride = this.getValueSize(),
  24748. smoothInterpolation = this.getInterpolation() === InterpolateSmooth,
  24749. writeIndex = 1,
  24750. lastIndex = times.length - 1;
  24751. for ( var i = 1; i < lastIndex; ++ i ) {
  24752. var keep = false;
  24753. var time = times[ i ];
  24754. var timeNext = times[ i + 1 ];
  24755. // remove adjacent keyframes scheduled at the same time
  24756. if ( time !== timeNext && ( i !== 1 || time !== time[ 0 ] ) ) {
  24757. if ( ! smoothInterpolation ) {
  24758. // remove unnecessary keyframes same as their neighbors
  24759. var offset = i * stride,
  24760. offsetP = offset - stride,
  24761. offsetN = offset + stride;
  24762. for ( var j = 0; j !== stride; ++ j ) {
  24763. var value = values[ offset + j ];
  24764. if ( value !== values[ offsetP + j ] ||
  24765. value !== values[ offsetN + j ] ) {
  24766. keep = true;
  24767. break;
  24768. }
  24769. }
  24770. } else {
  24771. keep = true;
  24772. }
  24773. }
  24774. // in-place compaction
  24775. if ( keep ) {
  24776. if ( i !== writeIndex ) {
  24777. times[ writeIndex ] = times[ i ];
  24778. var readOffset = i * stride,
  24779. writeOffset = writeIndex * stride;
  24780. for ( var j = 0; j !== stride; ++ j ) {
  24781. values[ writeOffset + j ] = values[ readOffset + j ];
  24782. }
  24783. }
  24784. ++ writeIndex;
  24785. }
  24786. }
  24787. // flush last keyframe (compaction looks ahead)
  24788. if ( lastIndex > 0 ) {
  24789. times[ writeIndex ] = times[ lastIndex ];
  24790. for ( var readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++ j ) {
  24791. values[ writeOffset + j ] = values[ readOffset + j ];
  24792. }
  24793. ++ writeIndex;
  24794. }
  24795. if ( writeIndex !== times.length ) {
  24796. this.times = AnimationUtils.arraySlice( times, 0, writeIndex );
  24797. this.values = AnimationUtils.arraySlice( values, 0, writeIndex * stride );
  24798. }
  24799. return this;
  24800. },
  24801. clone: function () {
  24802. var times = AnimationUtils.arraySlice( this.times, 0 );
  24803. var values = AnimationUtils.arraySlice( this.values, 0 );
  24804. var TypedKeyframeTrack = this.constructor;
  24805. var track = new TypedKeyframeTrack( this.name, times, values );
  24806. // Interpolant argument to constructor is not saved, so copy the factory method directly.
  24807. track.createInterpolant = this.createInterpolant;
  24808. return track;
  24809. }
  24810. } );
  24811. /**
  24812. *
  24813. * A Track of Boolean keyframe values.
  24814. *
  24815. *
  24816. * @author Ben Houston / http://clara.io/
  24817. * @author David Sarno / http://lighthaus.us/
  24818. * @author tschw
  24819. */
  24820. function BooleanKeyframeTrack( name, times, values ) {
  24821. KeyframeTrack.call( this, name, times, values );
  24822. }
  24823. BooleanKeyframeTrack.prototype = Object.assign( Object.create( KeyframeTrack.prototype ), {
  24824. constructor: BooleanKeyframeTrack,
  24825. ValueTypeName: 'bool',
  24826. ValueBufferType: Array,
  24827. DefaultInterpolation: InterpolateDiscrete,
  24828. InterpolantFactoryMethodLinear: undefined,
  24829. InterpolantFactoryMethodSmooth: undefined
  24830. // Note: Actually this track could have a optimized / compressed
  24831. // representation of a single value and a custom interpolant that
  24832. // computes "firstValue ^ isOdd( index )".
  24833. } );
  24834. /**
  24835. *
  24836. * A Track of keyframe values that represent color.
  24837. *
  24838. *
  24839. * @author Ben Houston / http://clara.io/
  24840. * @author David Sarno / http://lighthaus.us/
  24841. * @author tschw
  24842. */
  24843. function ColorKeyframeTrack( name, times, values, interpolation ) {
  24844. KeyframeTrack.call( this, name, times, values, interpolation );
  24845. }
  24846. ColorKeyframeTrack.prototype = Object.assign( Object.create( KeyframeTrack.prototype ), {
  24847. constructor: ColorKeyframeTrack,
  24848. ValueTypeName: 'color'
  24849. // ValueBufferType is inherited
  24850. // DefaultInterpolation is inherited
  24851. // Note: Very basic implementation and nothing special yet.
  24852. // However, this is the place for color space parameterization.
  24853. } );
  24854. /**
  24855. *
  24856. * A Track of numeric keyframe values.
  24857. *
  24858. * @author Ben Houston / http://clara.io/
  24859. * @author David Sarno / http://lighthaus.us/
  24860. * @author tschw
  24861. */
  24862. function NumberKeyframeTrack( name, times, values, interpolation ) {
  24863. KeyframeTrack.call( this, name, times, values, interpolation );
  24864. }
  24865. NumberKeyframeTrack.prototype = Object.assign( Object.create( KeyframeTrack.prototype ), {
  24866. constructor: NumberKeyframeTrack,
  24867. ValueTypeName: 'number'
  24868. // ValueBufferType is inherited
  24869. // DefaultInterpolation is inherited
  24870. } );
  24871. /**
  24872. * Spherical linear unit quaternion interpolant.
  24873. *
  24874. * @author tschw
  24875. */
  24876. function QuaternionLinearInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  24877. Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  24878. }
  24879. QuaternionLinearInterpolant.prototype = Object.assign( Object.create( Interpolant.prototype ), {
  24880. constructor: QuaternionLinearInterpolant,
  24881. interpolate_: function ( i1, t0, t, t1 ) {
  24882. var result = this.resultBuffer,
  24883. values = this.sampleValues,
  24884. stride = this.valueSize,
  24885. offset = i1 * stride,
  24886. alpha = ( t - t0 ) / ( t1 - t0 );
  24887. for ( var end = offset + stride; offset !== end; offset += 4 ) {
  24888. Quaternion.slerpFlat( result, 0, values, offset - stride, values, offset, alpha );
  24889. }
  24890. return result;
  24891. }
  24892. } );
  24893. /**
  24894. *
  24895. * A Track of quaternion keyframe values.
  24896. *
  24897. * @author Ben Houston / http://clara.io/
  24898. * @author David Sarno / http://lighthaus.us/
  24899. * @author tschw
  24900. */
  24901. function QuaternionKeyframeTrack( name, times, values, interpolation ) {
  24902. KeyframeTrack.call( this, name, times, values, interpolation );
  24903. }
  24904. QuaternionKeyframeTrack.prototype = Object.assign( Object.create( KeyframeTrack.prototype ), {
  24905. constructor: QuaternionKeyframeTrack,
  24906. ValueTypeName: 'quaternion',
  24907. // ValueBufferType is inherited
  24908. DefaultInterpolation: InterpolateLinear,
  24909. InterpolantFactoryMethodLinear: function ( result ) {
  24910. return new QuaternionLinearInterpolant( this.times, this.values, this.getValueSize(), result );
  24911. },
  24912. InterpolantFactoryMethodSmooth: undefined // not yet implemented
  24913. } );
  24914. /**
  24915. *
  24916. * A Track that interpolates Strings
  24917. *
  24918. *
  24919. * @author Ben Houston / http://clara.io/
  24920. * @author David Sarno / http://lighthaus.us/
  24921. * @author tschw
  24922. */
  24923. function StringKeyframeTrack( name, times, values, interpolation ) {
  24924. KeyframeTrack.call( this, name, times, values, interpolation );
  24925. }
  24926. StringKeyframeTrack.prototype = Object.assign( Object.create( KeyframeTrack.prototype ), {
  24927. constructor: StringKeyframeTrack,
  24928. ValueTypeName: 'string',
  24929. ValueBufferType: Array,
  24930. DefaultInterpolation: InterpolateDiscrete,
  24931. InterpolantFactoryMethodLinear: undefined,
  24932. InterpolantFactoryMethodSmooth: undefined
  24933. } );
  24934. /**
  24935. *
  24936. * A Track of vectored keyframe values.
  24937. *
  24938. *
  24939. * @author Ben Houston / http://clara.io/
  24940. * @author David Sarno / http://lighthaus.us/
  24941. * @author tschw
  24942. */
  24943. function VectorKeyframeTrack( name, times, values, interpolation ) {
  24944. KeyframeTrack.call( this, name, times, values, interpolation );
  24945. }
  24946. VectorKeyframeTrack.prototype = Object.assign( Object.create( KeyframeTrack.prototype ), {
  24947. constructor: VectorKeyframeTrack,
  24948. ValueTypeName: 'vector'
  24949. // ValueBufferType is inherited
  24950. // DefaultInterpolation is inherited
  24951. } );
  24952. /**
  24953. *
  24954. * Reusable set of Tracks that represent an animation.
  24955. *
  24956. * @author Ben Houston / http://clara.io/
  24957. * @author David Sarno / http://lighthaus.us/
  24958. */
  24959. function AnimationClip( name, duration, tracks ) {
  24960. this.name = name;
  24961. this.tracks = tracks;
  24962. this.duration = ( duration !== undefined ) ? duration : - 1;
  24963. this.uuid = _Math.generateUUID();
  24964. // this means it should figure out its duration by scanning the tracks
  24965. if ( this.duration < 0 ) {
  24966. this.resetDuration();
  24967. }
  24968. }
  24969. function getTrackTypeForValueTypeName( typeName ) {
  24970. switch ( typeName.toLowerCase() ) {
  24971. case 'scalar':
  24972. case 'double':
  24973. case 'float':
  24974. case 'number':
  24975. case 'integer':
  24976. return NumberKeyframeTrack;
  24977. case 'vector':
  24978. case 'vector2':
  24979. case 'vector3':
  24980. case 'vector4':
  24981. return VectorKeyframeTrack;
  24982. case 'color':
  24983. return ColorKeyframeTrack;
  24984. case 'quaternion':
  24985. return QuaternionKeyframeTrack;
  24986. case 'bool':
  24987. case 'boolean':
  24988. return BooleanKeyframeTrack;
  24989. case 'string':
  24990. return StringKeyframeTrack;
  24991. }
  24992. throw new Error( 'THREE.KeyframeTrack: Unsupported typeName: ' + typeName );
  24993. }
  24994. function parseKeyframeTrack( json ) {
  24995. if ( json.type === undefined ) {
  24996. throw new Error( 'THREE.KeyframeTrack: track type undefined, can not parse' );
  24997. }
  24998. var trackType = getTrackTypeForValueTypeName( json.type );
  24999. if ( json.times === undefined ) {
  25000. var times = [], values = [];
  25001. AnimationUtils.flattenJSON( json.keys, times, values, 'value' );
  25002. json.times = times;
  25003. json.values = values;
  25004. }
  25005. // derived classes can define a static parse method
  25006. if ( trackType.parse !== undefined ) {
  25007. return trackType.parse( json );
  25008. } else {
  25009. // by default, we assume a constructor compatible with the base
  25010. return new trackType( json.name, json.times, json.values, json.interpolation );
  25011. }
  25012. }
  25013. Object.assign( AnimationClip, {
  25014. parse: function ( json ) {
  25015. var tracks = [],
  25016. jsonTracks = json.tracks,
  25017. frameTime = 1.0 / ( json.fps || 1.0 );
  25018. for ( var i = 0, n = jsonTracks.length; i !== n; ++ i ) {
  25019. tracks.push( parseKeyframeTrack( jsonTracks[ i ] ).scale( frameTime ) );
  25020. }
  25021. return new AnimationClip( json.name, json.duration, tracks );
  25022. },
  25023. toJSON: function ( clip ) {
  25024. var tracks = [],
  25025. clipTracks = clip.tracks;
  25026. var json = {
  25027. 'name': clip.name,
  25028. 'duration': clip.duration,
  25029. 'tracks': tracks,
  25030. 'uuid': clip.uuid
  25031. };
  25032. for ( var i = 0, n = clipTracks.length; i !== n; ++ i ) {
  25033. tracks.push( KeyframeTrack.toJSON( clipTracks[ i ] ) );
  25034. }
  25035. return json;
  25036. },
  25037. CreateFromMorphTargetSequence: function ( name, morphTargetSequence, fps, noLoop ) {
  25038. var numMorphTargets = morphTargetSequence.length;
  25039. var tracks = [];
  25040. for ( var i = 0; i < numMorphTargets; i ++ ) {
  25041. var times = [];
  25042. var values = [];
  25043. times.push(
  25044. ( i + numMorphTargets - 1 ) % numMorphTargets,
  25045. i,
  25046. ( i + 1 ) % numMorphTargets );
  25047. values.push( 0, 1, 0 );
  25048. var order = AnimationUtils.getKeyframeOrder( times );
  25049. times = AnimationUtils.sortedArray( times, 1, order );
  25050. values = AnimationUtils.sortedArray( values, 1, order );
  25051. // if there is a key at the first frame, duplicate it as the
  25052. // last frame as well for perfect loop.
  25053. if ( ! noLoop && times[ 0 ] === 0 ) {
  25054. times.push( numMorphTargets );
  25055. values.push( values[ 0 ] );
  25056. }
  25057. tracks.push(
  25058. new NumberKeyframeTrack(
  25059. '.morphTargetInfluences[' + morphTargetSequence[ i ].name + ']',
  25060. times, values
  25061. ).scale( 1.0 / fps ) );
  25062. }
  25063. return new AnimationClip( name, - 1, tracks );
  25064. },
  25065. findByName: function ( objectOrClipArray, name ) {
  25066. var clipArray = objectOrClipArray;
  25067. if ( ! Array.isArray( objectOrClipArray ) ) {
  25068. var o = objectOrClipArray;
  25069. clipArray = o.geometry && o.geometry.animations || o.animations;
  25070. }
  25071. for ( var i = 0; i < clipArray.length; i ++ ) {
  25072. if ( clipArray[ i ].name === name ) {
  25073. return clipArray[ i ];
  25074. }
  25075. }
  25076. return null;
  25077. },
  25078. CreateClipsFromMorphTargetSequences: function ( morphTargets, fps, noLoop ) {
  25079. var animationToMorphTargets = {};
  25080. // tested with https://regex101.com/ on trick sequences
  25081. // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  25082. var pattern = /^([\w-]*?)([\d]+)$/;
  25083. // sort morph target names into animation groups based
  25084. // patterns like Walk_001, Walk_002, Run_001, Run_002
  25085. for ( var i = 0, il = morphTargets.length; i < il; i ++ ) {
  25086. var morphTarget = morphTargets[ i ];
  25087. var parts = morphTarget.name.match( pattern );
  25088. if ( parts && parts.length > 1 ) {
  25089. var name = parts[ 1 ];
  25090. var animationMorphTargets = animationToMorphTargets[ name ];
  25091. if ( ! animationMorphTargets ) {
  25092. animationToMorphTargets[ name ] = animationMorphTargets = [];
  25093. }
  25094. animationMorphTargets.push( morphTarget );
  25095. }
  25096. }
  25097. var clips = [];
  25098. for ( var name in animationToMorphTargets ) {
  25099. clips.push( AnimationClip.CreateFromMorphTargetSequence( name, animationToMorphTargets[ name ], fps, noLoop ) );
  25100. }
  25101. return clips;
  25102. },
  25103. // parse the animation.hierarchy format
  25104. parseAnimation: function ( animation, bones ) {
  25105. if ( ! animation ) {
  25106. console.error( 'THREE.AnimationClip: No animation in JSONLoader data.' );
  25107. return null;
  25108. }
  25109. var addNonemptyTrack = function ( trackType, trackName, animationKeys, propertyName, destTracks ) {
  25110. // only return track if there are actually keys.
  25111. if ( animationKeys.length !== 0 ) {
  25112. var times = [];
  25113. var values = [];
  25114. AnimationUtils.flattenJSON( animationKeys, times, values, propertyName );
  25115. // empty keys are filtered out, so check again
  25116. if ( times.length !== 0 ) {
  25117. destTracks.push( new trackType( trackName, times, values ) );
  25118. }
  25119. }
  25120. };
  25121. var tracks = [];
  25122. var clipName = animation.name || 'default';
  25123. // automatic length determination in AnimationClip.
  25124. var duration = animation.length || - 1;
  25125. var fps = animation.fps || 30;
  25126. var hierarchyTracks = animation.hierarchy || [];
  25127. for ( var h = 0; h < hierarchyTracks.length; h ++ ) {
  25128. var animationKeys = hierarchyTracks[ h ].keys;
  25129. // skip empty tracks
  25130. if ( ! animationKeys || animationKeys.length === 0 ) continue;
  25131. // process morph targets
  25132. if ( animationKeys[ 0 ].morphTargets ) {
  25133. // figure out all morph targets used in this track
  25134. var morphTargetNames = {};
  25135. for ( var k = 0; k < animationKeys.length; k ++ ) {
  25136. if ( animationKeys[ k ].morphTargets ) {
  25137. for ( var m = 0; m < animationKeys[ k ].morphTargets.length; m ++ ) {
  25138. morphTargetNames[ animationKeys[ k ].morphTargets[ m ] ] = - 1;
  25139. }
  25140. }
  25141. }
  25142. // create a track for each morph target with all zero
  25143. // morphTargetInfluences except for the keys in which
  25144. // the morphTarget is named.
  25145. for ( var morphTargetName in morphTargetNames ) {
  25146. var times = [];
  25147. var values = [];
  25148. for ( var m = 0; m !== animationKeys[ k ].morphTargets.length; ++ m ) {
  25149. var animationKey = animationKeys[ k ];
  25150. times.push( animationKey.time );
  25151. values.push( ( animationKey.morphTarget === morphTargetName ) ? 1 : 0 );
  25152. }
  25153. tracks.push( new NumberKeyframeTrack( '.morphTargetInfluence[' + morphTargetName + ']', times, values ) );
  25154. }
  25155. duration = morphTargetNames.length * ( fps || 1.0 );
  25156. } else {
  25157. // ...assume skeletal animation
  25158. var boneName = '.bones[' + bones[ h ].name + ']';
  25159. addNonemptyTrack(
  25160. VectorKeyframeTrack, boneName + '.position',
  25161. animationKeys, 'pos', tracks );
  25162. addNonemptyTrack(
  25163. QuaternionKeyframeTrack, boneName + '.quaternion',
  25164. animationKeys, 'rot', tracks );
  25165. addNonemptyTrack(
  25166. VectorKeyframeTrack, boneName + '.scale',
  25167. animationKeys, 'scl', tracks );
  25168. }
  25169. }
  25170. if ( tracks.length === 0 ) {
  25171. return null;
  25172. }
  25173. var clip = new AnimationClip( clipName, duration, tracks );
  25174. return clip;
  25175. }
  25176. } );
  25177. Object.assign( AnimationClip.prototype, {
  25178. resetDuration: function () {
  25179. var tracks = this.tracks, duration = 0;
  25180. for ( var i = 0, n = tracks.length; i !== n; ++ i ) {
  25181. var track = this.tracks[ i ];
  25182. duration = Math.max( duration, track.times[ track.times.length - 1 ] );
  25183. }
  25184. this.duration = duration;
  25185. return this;
  25186. },
  25187. trim: function () {
  25188. for ( var i = 0; i < this.tracks.length; i ++ ) {
  25189. this.tracks[ i ].trim( 0, this.duration );
  25190. }
  25191. return this;
  25192. },
  25193. validate: function () {
  25194. var valid = true;
  25195. for ( var i = 0; i < this.tracks.length; i ++ ) {
  25196. valid = valid && this.tracks[ i ].validate();
  25197. }
  25198. return valid;
  25199. },
  25200. optimize: function () {
  25201. for ( var i = 0; i < this.tracks.length; i ++ ) {
  25202. this.tracks[ i ].optimize();
  25203. }
  25204. return this;
  25205. },
  25206. clone: function () {
  25207. var tracks = [];
  25208. for ( var i = 0; i < this.tracks.length; i ++ ) {
  25209. tracks.push( this.tracks[ i ].clone() );
  25210. }
  25211. return new AnimationClip( this.name, this.duration, tracks );
  25212. }
  25213. } );
  25214. /**
  25215. * @author mrdoob / http://mrdoob.com/
  25216. */
  25217. var Cache = {
  25218. enabled: false,
  25219. files: {},
  25220. add: function ( key, file ) {
  25221. if ( this.enabled === false ) return;
  25222. // console.log( 'THREE.Cache', 'Adding key:', key );
  25223. this.files[ key ] = file;
  25224. },
  25225. get: function ( key ) {
  25226. if ( this.enabled === false ) return;
  25227. // console.log( 'THREE.Cache', 'Checking key:', key );
  25228. return this.files[ key ];
  25229. },
  25230. remove: function ( key ) {
  25231. delete this.files[ key ];
  25232. },
  25233. clear: function () {
  25234. this.files = {};
  25235. }
  25236. };
  25237. /**
  25238. * @author mrdoob / http://mrdoob.com/
  25239. */
  25240. function LoadingManager( onLoad, onProgress, onError ) {
  25241. var scope = this;
  25242. var isLoading = false;
  25243. var itemsLoaded = 0;
  25244. var itemsTotal = 0;
  25245. var urlModifier = undefined;
  25246. // Refer to #5689 for the reason why we don't set .onStart
  25247. // in the constructor
  25248. this.onStart = undefined;
  25249. this.onLoad = onLoad;
  25250. this.onProgress = onProgress;
  25251. this.onError = onError;
  25252. this.itemStart = function ( url ) {
  25253. itemsTotal ++;
  25254. if ( isLoading === false ) {
  25255. if ( scope.onStart !== undefined ) {
  25256. scope.onStart( url, itemsLoaded, itemsTotal );
  25257. }
  25258. }
  25259. isLoading = true;
  25260. };
  25261. this.itemEnd = function ( url ) {
  25262. itemsLoaded ++;
  25263. if ( scope.onProgress !== undefined ) {
  25264. scope.onProgress( url, itemsLoaded, itemsTotal );
  25265. }
  25266. if ( itemsLoaded === itemsTotal ) {
  25267. isLoading = false;
  25268. if ( scope.onLoad !== undefined ) {
  25269. scope.onLoad();
  25270. }
  25271. }
  25272. };
  25273. this.itemError = function ( url ) {
  25274. if ( scope.onError !== undefined ) {
  25275. scope.onError( url );
  25276. }
  25277. };
  25278. this.resolveURL = function ( url ) {
  25279. if ( urlModifier ) {
  25280. return urlModifier( url );
  25281. }
  25282. return url;
  25283. };
  25284. this.setURLModifier = function ( transform ) {
  25285. urlModifier = transform;
  25286. return this;
  25287. };
  25288. }
  25289. var DefaultLoadingManager = new LoadingManager();
  25290. /**
  25291. * @author mrdoob / http://mrdoob.com/
  25292. */
  25293. var loading = {};
  25294. function FileLoader( manager ) {
  25295. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  25296. }
  25297. Object.assign( FileLoader.prototype, {
  25298. load: function ( url, onLoad, onProgress, onError ) {
  25299. if ( url === undefined ) url = '';
  25300. if ( this.path !== undefined ) url = this.path + url;
  25301. url = this.manager.resolveURL( url );
  25302. var scope = this;
  25303. var cached = Cache.get( url );
  25304. if ( cached !== undefined ) {
  25305. scope.manager.itemStart( url );
  25306. setTimeout( function () {
  25307. if ( onLoad ) onLoad( cached );
  25308. scope.manager.itemEnd( url );
  25309. }, 0 );
  25310. return cached;
  25311. }
  25312. // Check if request is duplicate
  25313. if ( loading[ url ] !== undefined ) {
  25314. loading[ url ].push( {
  25315. onLoad: onLoad,
  25316. onProgress: onProgress,
  25317. onError: onError
  25318. } );
  25319. return;
  25320. }
  25321. // Check for data: URI
  25322. var dataUriRegex = /^data:(.*?)(;base64)?,(.*)$/;
  25323. var dataUriRegexResult = url.match( dataUriRegex );
  25324. // Safari can not handle Data URIs through XMLHttpRequest so process manually
  25325. if ( dataUriRegexResult ) {
  25326. var mimeType = dataUriRegexResult[ 1 ];
  25327. var isBase64 = !! dataUriRegexResult[ 2 ];
  25328. var data = dataUriRegexResult[ 3 ];
  25329. data = decodeURIComponent( data );
  25330. if ( isBase64 ) data = atob( data );
  25331. try {
  25332. var response;
  25333. var responseType = ( this.responseType || '' ).toLowerCase();
  25334. switch ( responseType ) {
  25335. case 'arraybuffer':
  25336. case 'blob':
  25337. var view = new Uint8Array( data.length );
  25338. for ( var i = 0; i < data.length; i ++ ) {
  25339. view[ i ] = data.charCodeAt( i );
  25340. }
  25341. if ( responseType === 'blob' ) {
  25342. response = new Blob( [ view.buffer ], { type: mimeType } );
  25343. } else {
  25344. response = view.buffer;
  25345. }
  25346. break;
  25347. case 'document':
  25348. var parser = new DOMParser();
  25349. response = parser.parseFromString( data, mimeType );
  25350. break;
  25351. case 'json':
  25352. response = JSON.parse( data );
  25353. break;
  25354. default: // 'text' or other
  25355. response = data;
  25356. break;
  25357. }
  25358. // Wait for next browser tick like standard XMLHttpRequest event dispatching does
  25359. setTimeout( function () {
  25360. if ( onLoad ) onLoad( response );
  25361. scope.manager.itemEnd( url );
  25362. }, 0 );
  25363. } catch ( error ) {
  25364. // Wait for next browser tick like standard XMLHttpRequest event dispatching does
  25365. setTimeout( function () {
  25366. if ( onError ) onError( error );
  25367. scope.manager.itemError( url );
  25368. scope.manager.itemEnd( url );
  25369. }, 0 );
  25370. }
  25371. } else {
  25372. // Initialise array for duplicate requests
  25373. loading[ url ] = [];
  25374. loading[ url ].push( {
  25375. onLoad: onLoad,
  25376. onProgress: onProgress,
  25377. onError: onError
  25378. } );
  25379. var request = new XMLHttpRequest();
  25380. request.open( 'GET', url, true );
  25381. request.addEventListener( 'load', function ( event ) {
  25382. var response = this.response;
  25383. Cache.add( url, response );
  25384. var callbacks = loading[ url ];
  25385. delete loading[ url ];
  25386. if ( this.status === 200 || this.status === 0 ) {
  25387. // Some browsers return HTTP Status 0 when using non-http protocol
  25388. // e.g. 'file://' or 'data://'. Handle as success.
  25389. if ( this.status === 0 ) console.warn( 'THREE.FileLoader: HTTP Status 0 received.' );
  25390. for ( var i = 0, il = callbacks.length; i < il; i ++ ) {
  25391. var callback = callbacks[ i ];
  25392. if ( callback.onLoad ) callback.onLoad( response );
  25393. }
  25394. scope.manager.itemEnd( url );
  25395. } else {
  25396. for ( var i = 0, il = callbacks.length; i < il; i ++ ) {
  25397. var callback = callbacks[ i ];
  25398. if ( callback.onError ) callback.onError( event );
  25399. }
  25400. scope.manager.itemError( url );
  25401. scope.manager.itemEnd( url );
  25402. }
  25403. }, false );
  25404. request.addEventListener( 'progress', function ( event ) {
  25405. var callbacks = loading[ url ];
  25406. for ( var i = 0, il = callbacks.length; i < il; i ++ ) {
  25407. var callback = callbacks[ i ];
  25408. if ( callback.onProgress ) callback.onProgress( event );
  25409. }
  25410. }, false );
  25411. request.addEventListener( 'error', function ( event ) {
  25412. var callbacks = loading[ url ];
  25413. delete loading[ url ];
  25414. for ( var i = 0, il = callbacks.length; i < il; i ++ ) {
  25415. var callback = callbacks[ i ];
  25416. if ( callback.onError ) callback.onError( event );
  25417. }
  25418. scope.manager.itemError( url );
  25419. scope.manager.itemEnd( url );
  25420. }, false );
  25421. request.addEventListener( 'abort', function ( event ) {
  25422. var callbacks = loading[ url ];
  25423. delete loading[ url ];
  25424. for ( var i = 0, il = callbacks.length; i < il; i ++ ) {
  25425. var callback = callbacks[ i ];
  25426. if ( callback.onError ) callback.onError( event );
  25427. }
  25428. scope.manager.itemError( url );
  25429. scope.manager.itemEnd( url );
  25430. }, false );
  25431. if ( this.responseType !== undefined ) request.responseType = this.responseType;
  25432. if ( this.withCredentials !== undefined ) request.withCredentials = this.withCredentials;
  25433. if ( request.overrideMimeType ) request.overrideMimeType( this.mimeType !== undefined ? this.mimeType : 'text/plain' );
  25434. for ( var header in this.requestHeader ) {
  25435. request.setRequestHeader( header, this.requestHeader[ header ] );
  25436. }
  25437. request.send( null );
  25438. }
  25439. scope.manager.itemStart( url );
  25440. return request;
  25441. },
  25442. setPath: function ( value ) {
  25443. this.path = value;
  25444. return this;
  25445. },
  25446. setResponseType: function ( value ) {
  25447. this.responseType = value;
  25448. return this;
  25449. },
  25450. setWithCredentials: function ( value ) {
  25451. this.withCredentials = value;
  25452. return this;
  25453. },
  25454. setMimeType: function ( value ) {
  25455. this.mimeType = value;
  25456. return this;
  25457. },
  25458. setRequestHeader: function ( value ) {
  25459. this.requestHeader = value;
  25460. return this;
  25461. }
  25462. } );
  25463. /**
  25464. * @author bhouston / http://clara.io/
  25465. */
  25466. function AnimationLoader( manager ) {
  25467. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  25468. }
  25469. Object.assign( AnimationLoader.prototype, {
  25470. load: function ( url, onLoad, onProgress, onError ) {
  25471. var scope = this;
  25472. var loader = new FileLoader( scope.manager );
  25473. loader.setPath( scope.path );
  25474. loader.load( url, function ( text ) {
  25475. onLoad( scope.parse( JSON.parse( text ) ) );
  25476. }, onProgress, onError );
  25477. },
  25478. parse: function ( json ) {
  25479. var animations = [];
  25480. for ( var i = 0; i < json.length; i ++ ) {
  25481. var clip = AnimationClip.parse( json[ i ] );
  25482. animations.push( clip );
  25483. }
  25484. return animations;
  25485. },
  25486. setPath: function ( value ) {
  25487. this.path = value;
  25488. return this;
  25489. }
  25490. } );
  25491. /**
  25492. * @author mrdoob / http://mrdoob.com/
  25493. *
  25494. * Abstract Base class to block based textures loader (dds, pvr, ...)
  25495. */
  25496. function CompressedTextureLoader( manager ) {
  25497. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  25498. // override in sub classes
  25499. this._parser = null;
  25500. }
  25501. Object.assign( CompressedTextureLoader.prototype, {
  25502. load: function ( url, onLoad, onProgress, onError ) {
  25503. var scope = this;
  25504. var images = [];
  25505. var texture = new CompressedTexture();
  25506. texture.image = images;
  25507. var loader = new FileLoader( this.manager );
  25508. loader.setPath( this.path );
  25509. loader.setResponseType( 'arraybuffer' );
  25510. function loadTexture( i ) {
  25511. loader.load( url[ i ], function ( buffer ) {
  25512. var texDatas = scope._parser( buffer, true );
  25513. images[ i ] = {
  25514. width: texDatas.width,
  25515. height: texDatas.height,
  25516. format: texDatas.format,
  25517. mipmaps: texDatas.mipmaps
  25518. };
  25519. loaded += 1;
  25520. if ( loaded === 6 ) {
  25521. if ( texDatas.mipmapCount === 1 )
  25522. texture.minFilter = LinearFilter;
  25523. texture.format = texDatas.format;
  25524. texture.needsUpdate = true;
  25525. if ( onLoad ) onLoad( texture );
  25526. }
  25527. }, onProgress, onError );
  25528. }
  25529. if ( Array.isArray( url ) ) {
  25530. var loaded = 0;
  25531. for ( var i = 0, il = url.length; i < il; ++ i ) {
  25532. loadTexture( i );
  25533. }
  25534. } else {
  25535. // compressed cubemap texture stored in a single DDS file
  25536. loader.load( url, function ( buffer ) {
  25537. var texDatas = scope._parser( buffer, true );
  25538. if ( texDatas.isCubemap ) {
  25539. var faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  25540. for ( var f = 0; f < faces; f ++ ) {
  25541. images[ f ] = { mipmaps: [] };
  25542. for ( var i = 0; i < texDatas.mipmapCount; i ++ ) {
  25543. images[ f ].mipmaps.push( texDatas.mipmaps[ f * texDatas.mipmapCount + i ] );
  25544. images[ f ].format = texDatas.format;
  25545. images[ f ].width = texDatas.width;
  25546. images[ f ].height = texDatas.height;
  25547. }
  25548. }
  25549. } else {
  25550. texture.image.width = texDatas.width;
  25551. texture.image.height = texDatas.height;
  25552. texture.mipmaps = texDatas.mipmaps;
  25553. }
  25554. if ( texDatas.mipmapCount === 1 ) {
  25555. texture.minFilter = LinearFilter;
  25556. }
  25557. texture.format = texDatas.format;
  25558. texture.needsUpdate = true;
  25559. if ( onLoad ) onLoad( texture );
  25560. }, onProgress, onError );
  25561. }
  25562. return texture;
  25563. },
  25564. setPath: function ( value ) {
  25565. this.path = value;
  25566. return this;
  25567. }
  25568. } );
  25569. /**
  25570. * @author Nikos M. / https://github.com/foo123/
  25571. *
  25572. * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...)
  25573. */
  25574. function DataTextureLoader( manager ) {
  25575. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  25576. // override in sub classes
  25577. this._parser = null;
  25578. }
  25579. Object.assign( DataTextureLoader.prototype, {
  25580. load: function ( url, onLoad, onProgress, onError ) {
  25581. var scope = this;
  25582. var texture = new DataTexture();
  25583. var loader = new FileLoader( this.manager );
  25584. loader.setResponseType( 'arraybuffer' );
  25585. loader.setPath( this.path );
  25586. loader.load( url, function ( buffer ) {
  25587. var texData = scope._parser( buffer );
  25588. if ( ! texData ) return;
  25589. if ( texData.image !== undefined ) {
  25590. texture.image = texData.image;
  25591. } else if ( texData.data !== undefined ) {
  25592. texture.image.width = texData.width;
  25593. texture.image.height = texData.height;
  25594. texture.image.data = texData.data;
  25595. }
  25596. texture.wrapS = texData.wrapS !== undefined ? texData.wrapS : ClampToEdgeWrapping;
  25597. texture.wrapT = texData.wrapT !== undefined ? texData.wrapT : ClampToEdgeWrapping;
  25598. texture.magFilter = texData.magFilter !== undefined ? texData.magFilter : LinearFilter;
  25599. texture.minFilter = texData.minFilter !== undefined ? texData.minFilter : LinearMipMapLinearFilter;
  25600. texture.anisotropy = texData.anisotropy !== undefined ? texData.anisotropy : 1;
  25601. if ( texData.format !== undefined ) {
  25602. texture.format = texData.format;
  25603. }
  25604. if ( texData.type !== undefined ) {
  25605. texture.type = texData.type;
  25606. }
  25607. if ( texData.mipmaps !== undefined ) {
  25608. texture.mipmaps = texData.mipmaps;
  25609. }
  25610. if ( texData.mipmapCount === 1 ) {
  25611. texture.minFilter = LinearFilter;
  25612. }
  25613. texture.needsUpdate = true;
  25614. if ( onLoad ) onLoad( texture, texData );
  25615. }, onProgress, onError );
  25616. return texture;
  25617. },
  25618. setPath: function ( value ) {
  25619. this.path = value;
  25620. return this;
  25621. }
  25622. } );
  25623. /**
  25624. * @author mrdoob / http://mrdoob.com/
  25625. */
  25626. function ImageLoader( manager ) {
  25627. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  25628. }
  25629. Object.assign( ImageLoader.prototype, {
  25630. crossOrigin: 'anonymous',
  25631. load: function ( url, onLoad, onProgress, onError ) {
  25632. if ( url === undefined ) url = '';
  25633. if ( this.path !== undefined ) url = this.path + url;
  25634. url = this.manager.resolveURL( url );
  25635. var scope = this;
  25636. var cached = Cache.get( url );
  25637. if ( cached !== undefined ) {
  25638. scope.manager.itemStart( url );
  25639. setTimeout( function () {
  25640. if ( onLoad ) onLoad( cached );
  25641. scope.manager.itemEnd( url );
  25642. }, 0 );
  25643. return cached;
  25644. }
  25645. var image = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'img' );
  25646. function onImageLoad() {
  25647. image.removeEventListener( 'load', onImageLoad, false );
  25648. image.removeEventListener( 'error', onImageError, false );
  25649. Cache.add( url, this );
  25650. if ( onLoad ) onLoad( this );
  25651. scope.manager.itemEnd( url );
  25652. }
  25653. function onImageError( event ) {
  25654. image.removeEventListener( 'load', onImageLoad, false );
  25655. image.removeEventListener( 'error', onImageError, false );
  25656. if ( onError ) onError( event );
  25657. scope.manager.itemError( url );
  25658. scope.manager.itemEnd( url );
  25659. }
  25660. image.addEventListener( 'load', onImageLoad, false );
  25661. image.addEventListener( 'error', onImageError, false );
  25662. if ( url.substr( 0, 5 ) !== 'data:' ) {
  25663. if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin;
  25664. }
  25665. scope.manager.itemStart( url );
  25666. image.src = url;
  25667. return image;
  25668. },
  25669. setCrossOrigin: function ( value ) {
  25670. this.crossOrigin = value;
  25671. return this;
  25672. },
  25673. setPath: function ( value ) {
  25674. this.path = value;
  25675. return this;
  25676. }
  25677. } );
  25678. /**
  25679. * @author mrdoob / http://mrdoob.com/
  25680. */
  25681. function CubeTextureLoader( manager ) {
  25682. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  25683. }
  25684. Object.assign( CubeTextureLoader.prototype, {
  25685. crossOrigin: 'anonymous',
  25686. load: function ( urls, onLoad, onProgress, onError ) {
  25687. var texture = new CubeTexture();
  25688. var loader = new ImageLoader( this.manager );
  25689. loader.setCrossOrigin( this.crossOrigin );
  25690. loader.setPath( this.path );
  25691. var loaded = 0;
  25692. function loadTexture( i ) {
  25693. loader.load( urls[ i ], function ( image ) {
  25694. texture.images[ i ] = image;
  25695. loaded ++;
  25696. if ( loaded === 6 ) {
  25697. texture.needsUpdate = true;
  25698. if ( onLoad ) onLoad( texture );
  25699. }
  25700. }, undefined, onError );
  25701. }
  25702. for ( var i = 0; i < urls.length; ++ i ) {
  25703. loadTexture( i );
  25704. }
  25705. return texture;
  25706. },
  25707. setCrossOrigin: function ( value ) {
  25708. this.crossOrigin = value;
  25709. return this;
  25710. },
  25711. setPath: function ( value ) {
  25712. this.path = value;
  25713. return this;
  25714. }
  25715. } );
  25716. /**
  25717. * @author mrdoob / http://mrdoob.com/
  25718. */
  25719. function TextureLoader( manager ) {
  25720. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  25721. }
  25722. Object.assign( TextureLoader.prototype, {
  25723. crossOrigin: 'anonymous',
  25724. load: function ( url, onLoad, onProgress, onError ) {
  25725. var texture = new Texture();
  25726. var loader = new ImageLoader( this.manager );
  25727. loader.setCrossOrigin( this.crossOrigin );
  25728. loader.setPath( this.path );
  25729. loader.load( url, function ( image ) {
  25730. texture.image = image;
  25731. // JPEGs can't have an alpha channel, so memory can be saved by storing them as RGB.
  25732. var isJPEG = url.search( /\.jpe?g($|\?)/i ) > 0 || url.search( /^data\:image\/jpeg/ ) === 0;
  25733. texture.format = isJPEG ? RGBFormat : RGBAFormat;
  25734. texture.needsUpdate = true;
  25735. if ( onLoad !== undefined ) {
  25736. onLoad( texture );
  25737. }
  25738. }, onProgress, onError );
  25739. return texture;
  25740. },
  25741. setCrossOrigin: function ( value ) {
  25742. this.crossOrigin = value;
  25743. return this;
  25744. },
  25745. setPath: function ( value ) {
  25746. this.path = value;
  25747. return this;
  25748. }
  25749. } );
  25750. /**
  25751. * @author zz85 / http://www.lab4games.net/zz85/blog
  25752. * Extensible curve object
  25753. *
  25754. * Some common of curve methods:
  25755. * .getPoint( t, optionalTarget ), .getTangent( t )
  25756. * .getPointAt( u, optionalTarget ), .getTangentAt( u )
  25757. * .getPoints(), .getSpacedPoints()
  25758. * .getLength()
  25759. * .updateArcLengths()
  25760. *
  25761. * This following curves inherit from THREE.Curve:
  25762. *
  25763. * -- 2D curves --
  25764. * THREE.ArcCurve
  25765. * THREE.CubicBezierCurve
  25766. * THREE.EllipseCurve
  25767. * THREE.LineCurve
  25768. * THREE.QuadraticBezierCurve
  25769. * THREE.SplineCurve
  25770. *
  25771. * -- 3D curves --
  25772. * THREE.CatmullRomCurve3
  25773. * THREE.CubicBezierCurve3
  25774. * THREE.LineCurve3
  25775. * THREE.QuadraticBezierCurve3
  25776. *
  25777. * A series of curves can be represented as a THREE.CurvePath.
  25778. *
  25779. **/
  25780. /**************************************************************
  25781. * Abstract Curve base class
  25782. **************************************************************/
  25783. function Curve() {
  25784. this.type = 'Curve';
  25785. this.arcLengthDivisions = 200;
  25786. }
  25787. Object.assign( Curve.prototype, {
  25788. // Virtual base class method to overwrite and implement in subclasses
  25789. // - t [0 .. 1]
  25790. getPoint: function ( /* t, optionalTarget */ ) {
  25791. console.warn( 'THREE.Curve: .getPoint() not implemented.' );
  25792. return null;
  25793. },
  25794. // Get point at relative position in curve according to arc length
  25795. // - u [0 .. 1]
  25796. getPointAt: function ( u, optionalTarget ) {
  25797. var t = this.getUtoTmapping( u );
  25798. return this.getPoint( t, optionalTarget );
  25799. },
  25800. // Get sequence of points using getPoint( t )
  25801. getPoints: function ( divisions ) {
  25802. if ( divisions === undefined ) divisions = 5;
  25803. var points = [];
  25804. for ( var d = 0; d <= divisions; d ++ ) {
  25805. points.push( this.getPoint( d / divisions ) );
  25806. }
  25807. return points;
  25808. },
  25809. // Get sequence of points using getPointAt( u )
  25810. getSpacedPoints: function ( divisions ) {
  25811. if ( divisions === undefined ) divisions = 5;
  25812. var points = [];
  25813. for ( var d = 0; d <= divisions; d ++ ) {
  25814. points.push( this.getPointAt( d / divisions ) );
  25815. }
  25816. return points;
  25817. },
  25818. // Get total curve arc length
  25819. getLength: function () {
  25820. var lengths = this.getLengths();
  25821. return lengths[ lengths.length - 1 ];
  25822. },
  25823. // Get list of cumulative segment lengths
  25824. getLengths: function ( divisions ) {
  25825. if ( divisions === undefined ) divisions = this.arcLengthDivisions;
  25826. if ( this.cacheArcLengths &&
  25827. ( this.cacheArcLengths.length === divisions + 1 ) &&
  25828. ! this.needsUpdate ) {
  25829. return this.cacheArcLengths;
  25830. }
  25831. this.needsUpdate = false;
  25832. var cache = [];
  25833. var current, last = this.getPoint( 0 );
  25834. var p, sum = 0;
  25835. cache.push( 0 );
  25836. for ( p = 1; p <= divisions; p ++ ) {
  25837. current = this.getPoint( p / divisions );
  25838. sum += current.distanceTo( last );
  25839. cache.push( sum );
  25840. last = current;
  25841. }
  25842. this.cacheArcLengths = cache;
  25843. return cache; // { sums: cache, sum: sum }; Sum is in the last element.
  25844. },
  25845. updateArcLengths: function () {
  25846. this.needsUpdate = true;
  25847. this.getLengths();
  25848. },
  25849. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant
  25850. getUtoTmapping: function ( u, distance ) {
  25851. var arcLengths = this.getLengths();
  25852. var i = 0, il = arcLengths.length;
  25853. var targetArcLength; // The targeted u distance value to get
  25854. if ( distance ) {
  25855. targetArcLength = distance;
  25856. } else {
  25857. targetArcLength = u * arcLengths[ il - 1 ];
  25858. }
  25859. // binary search for the index with largest value smaller than target u distance
  25860. var low = 0, high = il - 1, comparison;
  25861. while ( low <= high ) {
  25862. 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
  25863. comparison = arcLengths[ i ] - targetArcLength;
  25864. if ( comparison < 0 ) {
  25865. low = i + 1;
  25866. } else if ( comparison > 0 ) {
  25867. high = i - 1;
  25868. } else {
  25869. high = i;
  25870. break;
  25871. // DONE
  25872. }
  25873. }
  25874. i = high;
  25875. if ( arcLengths[ i ] === targetArcLength ) {
  25876. return i / ( il - 1 );
  25877. }
  25878. // we could get finer grain at lengths, or use simple interpolation between two points
  25879. var lengthBefore = arcLengths[ i ];
  25880. var lengthAfter = arcLengths[ i + 1 ];
  25881. var segmentLength = lengthAfter - lengthBefore;
  25882. // determine where we are between the 'before' and 'after' points
  25883. var segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  25884. // add that fractional amount to t
  25885. var t = ( i + segmentFraction ) / ( il - 1 );
  25886. return t;
  25887. },
  25888. // Returns a unit vector tangent at t
  25889. // In case any sub curve does not implement its tangent derivation,
  25890. // 2 points a small delta apart will be used to find its gradient
  25891. // which seems to give a reasonable approximation
  25892. getTangent: function ( t ) {
  25893. var delta = 0.0001;
  25894. var t1 = t - delta;
  25895. var t2 = t + delta;
  25896. // Capping in case of danger
  25897. if ( t1 < 0 ) t1 = 0;
  25898. if ( t2 > 1 ) t2 = 1;
  25899. var pt1 = this.getPoint( t1 );
  25900. var pt2 = this.getPoint( t2 );
  25901. var vec = pt2.clone().sub( pt1 );
  25902. return vec.normalize();
  25903. },
  25904. getTangentAt: function ( u ) {
  25905. var t = this.getUtoTmapping( u );
  25906. return this.getTangent( t );
  25907. },
  25908. computeFrenetFrames: function ( segments, closed ) {
  25909. // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  25910. var normal = new Vector3();
  25911. var tangents = [];
  25912. var normals = [];
  25913. var binormals = [];
  25914. var vec = new Vector3();
  25915. var mat = new Matrix4();
  25916. var i, u, theta;
  25917. // compute the tangent vectors for each segment on the curve
  25918. for ( i = 0; i <= segments; i ++ ) {
  25919. u = i / segments;
  25920. tangents[ i ] = this.getTangentAt( u );
  25921. tangents[ i ].normalize();
  25922. }
  25923. // select an initial normal vector perpendicular to the first tangent vector,
  25924. // and in the direction of the minimum tangent xyz component
  25925. normals[ 0 ] = new Vector3();
  25926. binormals[ 0 ] = new Vector3();
  25927. var min = Number.MAX_VALUE;
  25928. var tx = Math.abs( tangents[ 0 ].x );
  25929. var ty = Math.abs( tangents[ 0 ].y );
  25930. var tz = Math.abs( tangents[ 0 ].z );
  25931. if ( tx <= min ) {
  25932. min = tx;
  25933. normal.set( 1, 0, 0 );
  25934. }
  25935. if ( ty <= min ) {
  25936. min = ty;
  25937. normal.set( 0, 1, 0 );
  25938. }
  25939. if ( tz <= min ) {
  25940. normal.set( 0, 0, 1 );
  25941. }
  25942. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  25943. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  25944. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  25945. // compute the slowly-varying normal and binormal vectors for each segment on the curve
  25946. for ( i = 1; i <= segments; i ++ ) {
  25947. normals[ i ] = normals[ i - 1 ].clone();
  25948. binormals[ i ] = binormals[ i - 1 ].clone();
  25949. vec.crossVectors( tangents[ i - 1 ], tangents[ i ] );
  25950. if ( vec.length() > Number.EPSILON ) {
  25951. vec.normalize();
  25952. theta = Math.acos( _Math.clamp( tangents[ i - 1 ].dot( tangents[ i ] ), - 1, 1 ) ); // clamp for floating pt errors
  25953. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  25954. }
  25955. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  25956. }
  25957. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  25958. if ( closed === true ) {
  25959. theta = Math.acos( _Math.clamp( normals[ 0 ].dot( normals[ segments ] ), - 1, 1 ) );
  25960. theta /= segments;
  25961. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ segments ] ) ) > 0 ) {
  25962. theta = - theta;
  25963. }
  25964. for ( i = 1; i <= segments; i ++ ) {
  25965. // twist a little...
  25966. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  25967. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  25968. }
  25969. }
  25970. return {
  25971. tangents: tangents,
  25972. normals: normals,
  25973. binormals: binormals
  25974. };
  25975. },
  25976. clone: function () {
  25977. return new this.constructor().copy( this );
  25978. },
  25979. copy: function ( source ) {
  25980. this.arcLengthDivisions = source.arcLengthDivisions;
  25981. return this;
  25982. },
  25983. toJSON: function () {
  25984. var data = {
  25985. metadata: {
  25986. version: 4.5,
  25987. type: 'Curve',
  25988. generator: 'Curve.toJSON'
  25989. }
  25990. };
  25991. data.arcLengthDivisions = this.arcLengthDivisions;
  25992. data.type = this.type;
  25993. return data;
  25994. },
  25995. fromJSON: function ( json ) {
  25996. this.arcLengthDivisions = json.arcLengthDivisions;
  25997. return this;
  25998. }
  25999. } );
  26000. function EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  26001. Curve.call( this );
  26002. this.type = 'EllipseCurve';
  26003. this.aX = aX || 0;
  26004. this.aY = aY || 0;
  26005. this.xRadius = xRadius || 1;
  26006. this.yRadius = yRadius || 1;
  26007. this.aStartAngle = aStartAngle || 0;
  26008. this.aEndAngle = aEndAngle || 2 * Math.PI;
  26009. this.aClockwise = aClockwise || false;
  26010. this.aRotation = aRotation || 0;
  26011. }
  26012. EllipseCurve.prototype = Object.create( Curve.prototype );
  26013. EllipseCurve.prototype.constructor = EllipseCurve;
  26014. EllipseCurve.prototype.isEllipseCurve = true;
  26015. EllipseCurve.prototype.getPoint = function ( t, optionalTarget ) {
  26016. var point = optionalTarget || new Vector2();
  26017. var twoPi = Math.PI * 2;
  26018. var deltaAngle = this.aEndAngle - this.aStartAngle;
  26019. var samePoints = Math.abs( deltaAngle ) < Number.EPSILON;
  26020. // ensures that deltaAngle is 0 .. 2 PI
  26021. while ( deltaAngle < 0 ) deltaAngle += twoPi;
  26022. while ( deltaAngle > twoPi ) deltaAngle -= twoPi;
  26023. if ( deltaAngle < Number.EPSILON ) {
  26024. if ( samePoints ) {
  26025. deltaAngle = 0;
  26026. } else {
  26027. deltaAngle = twoPi;
  26028. }
  26029. }
  26030. if ( this.aClockwise === true && ! samePoints ) {
  26031. if ( deltaAngle === twoPi ) {
  26032. deltaAngle = - twoPi;
  26033. } else {
  26034. deltaAngle = deltaAngle - twoPi;
  26035. }
  26036. }
  26037. var angle = this.aStartAngle + t * deltaAngle;
  26038. var x = this.aX + this.xRadius * Math.cos( angle );
  26039. var y = this.aY + this.yRadius * Math.sin( angle );
  26040. if ( this.aRotation !== 0 ) {
  26041. var cos = Math.cos( this.aRotation );
  26042. var sin = Math.sin( this.aRotation );
  26043. var tx = x - this.aX;
  26044. var ty = y - this.aY;
  26045. // Rotate the point about the center of the ellipse.
  26046. x = tx * cos - ty * sin + this.aX;
  26047. y = tx * sin + ty * cos + this.aY;
  26048. }
  26049. return point.set( x, y );
  26050. };
  26051. EllipseCurve.prototype.copy = function ( source ) {
  26052. Curve.prototype.copy.call( this, source );
  26053. this.aX = source.aX;
  26054. this.aY = source.aY;
  26055. this.xRadius = source.xRadius;
  26056. this.yRadius = source.yRadius;
  26057. this.aStartAngle = source.aStartAngle;
  26058. this.aEndAngle = source.aEndAngle;
  26059. this.aClockwise = source.aClockwise;
  26060. this.aRotation = source.aRotation;
  26061. return this;
  26062. };
  26063. EllipseCurve.prototype.toJSON = function () {
  26064. var data = Curve.prototype.toJSON.call( this );
  26065. data.aX = this.aX;
  26066. data.aY = this.aY;
  26067. data.xRadius = this.xRadius;
  26068. data.yRadius = this.yRadius;
  26069. data.aStartAngle = this.aStartAngle;
  26070. data.aEndAngle = this.aEndAngle;
  26071. data.aClockwise = this.aClockwise;
  26072. data.aRotation = this.aRotation;
  26073. return data;
  26074. };
  26075. EllipseCurve.prototype.fromJSON = function ( json ) {
  26076. Curve.prototype.fromJSON.call( this, json );
  26077. this.aX = json.aX;
  26078. this.aY = json.aY;
  26079. this.xRadius = json.xRadius;
  26080. this.yRadius = json.yRadius;
  26081. this.aStartAngle = json.aStartAngle;
  26082. this.aEndAngle = json.aEndAngle;
  26083. this.aClockwise = json.aClockwise;
  26084. this.aRotation = json.aRotation;
  26085. return this;
  26086. };
  26087. function ArcCurve( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  26088. EllipseCurve.call( this, aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  26089. this.type = 'ArcCurve';
  26090. }
  26091. ArcCurve.prototype = Object.create( EllipseCurve.prototype );
  26092. ArcCurve.prototype.constructor = ArcCurve;
  26093. ArcCurve.prototype.isArcCurve = true;
  26094. /**
  26095. * @author zz85 https://github.com/zz85
  26096. *
  26097. * Centripetal CatmullRom Curve - which is useful for avoiding
  26098. * cusps and self-intersections in non-uniform catmull rom curves.
  26099. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  26100. *
  26101. * curve.type accepts centripetal(default), chordal and catmullrom
  26102. * curve.tension is used for catmullrom which defaults to 0.5
  26103. */
  26104. /*
  26105. Based on an optimized c++ solution in
  26106. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  26107. - http://ideone.com/NoEbVM
  26108. This CubicPoly class could be used for reusing some variables and calculations,
  26109. but for three.js curve use, it could be possible inlined and flatten into a single function call
  26110. which can be placed in CurveUtils.
  26111. */
  26112. function CubicPoly() {
  26113. var c0 = 0, c1 = 0, c2 = 0, c3 = 0;
  26114. /*
  26115. * Compute coefficients for a cubic polynomial
  26116. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  26117. * such that
  26118. * p(0) = x0, p(1) = x1
  26119. * and
  26120. * p'(0) = t0, p'(1) = t1.
  26121. */
  26122. function init( x0, x1, t0, t1 ) {
  26123. c0 = x0;
  26124. c1 = t0;
  26125. c2 = - 3 * x0 + 3 * x1 - 2 * t0 - t1;
  26126. c3 = 2 * x0 - 2 * x1 + t0 + t1;
  26127. }
  26128. return {
  26129. initCatmullRom: function ( x0, x1, x2, x3, tension ) {
  26130. init( x1, x2, tension * ( x2 - x0 ), tension * ( x3 - x1 ) );
  26131. },
  26132. initNonuniformCatmullRom: function ( x0, x1, x2, x3, dt0, dt1, dt2 ) {
  26133. // compute tangents when parameterized in [t1,t2]
  26134. var t1 = ( x1 - x0 ) / dt0 - ( x2 - x0 ) / ( dt0 + dt1 ) + ( x2 - x1 ) / dt1;
  26135. var t2 = ( x2 - x1 ) / dt1 - ( x3 - x1 ) / ( dt1 + dt2 ) + ( x3 - x2 ) / dt2;
  26136. // rescale tangents for parametrization in [0,1]
  26137. t1 *= dt1;
  26138. t2 *= dt1;
  26139. init( x1, x2, t1, t2 );
  26140. },
  26141. calc: function ( t ) {
  26142. var t2 = t * t;
  26143. var t3 = t2 * t;
  26144. return c0 + c1 * t + c2 * t2 + c3 * t3;
  26145. }
  26146. };
  26147. }
  26148. //
  26149. var tmp = new Vector3();
  26150. var px = new CubicPoly(), py = new CubicPoly(), pz = new CubicPoly();
  26151. function CatmullRomCurve3( points, closed, curveType, tension ) {
  26152. Curve.call( this );
  26153. this.type = 'CatmullRomCurve3';
  26154. this.points = points || [];
  26155. this.closed = closed || false;
  26156. this.curveType = curveType || 'centripetal';
  26157. this.tension = tension || 0.5;
  26158. }
  26159. CatmullRomCurve3.prototype = Object.create( Curve.prototype );
  26160. CatmullRomCurve3.prototype.constructor = CatmullRomCurve3;
  26161. CatmullRomCurve3.prototype.isCatmullRomCurve3 = true;
  26162. CatmullRomCurve3.prototype.getPoint = function ( t, optionalTarget ) {
  26163. var point = optionalTarget || new Vector3();
  26164. var points = this.points;
  26165. var l = points.length;
  26166. var p = ( l - ( this.closed ? 0 : 1 ) ) * t;
  26167. var intPoint = Math.floor( p );
  26168. var weight = p - intPoint;
  26169. if ( this.closed ) {
  26170. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / l ) + 1 ) * l;
  26171. } else if ( weight === 0 && intPoint === l - 1 ) {
  26172. intPoint = l - 2;
  26173. weight = 1;
  26174. }
  26175. var p0, p1, p2, p3; // 4 points
  26176. if ( this.closed || intPoint > 0 ) {
  26177. p0 = points[ ( intPoint - 1 ) % l ];
  26178. } else {
  26179. // extrapolate first point
  26180. tmp.subVectors( points[ 0 ], points[ 1 ] ).add( points[ 0 ] );
  26181. p0 = tmp;
  26182. }
  26183. p1 = points[ intPoint % l ];
  26184. p2 = points[ ( intPoint + 1 ) % l ];
  26185. if ( this.closed || intPoint + 2 < l ) {
  26186. p3 = points[ ( intPoint + 2 ) % l ];
  26187. } else {
  26188. // extrapolate last point
  26189. tmp.subVectors( points[ l - 1 ], points[ l - 2 ] ).add( points[ l - 1 ] );
  26190. p3 = tmp;
  26191. }
  26192. if ( this.curveType === 'centripetal' || this.curveType === 'chordal' ) {
  26193. // init Centripetal / Chordal Catmull-Rom
  26194. var pow = this.curveType === 'chordal' ? 0.5 : 0.25;
  26195. var dt0 = Math.pow( p0.distanceToSquared( p1 ), pow );
  26196. var dt1 = Math.pow( p1.distanceToSquared( p2 ), pow );
  26197. var dt2 = Math.pow( p2.distanceToSquared( p3 ), pow );
  26198. // safety check for repeated points
  26199. if ( dt1 < 1e-4 ) dt1 = 1.0;
  26200. if ( dt0 < 1e-4 ) dt0 = dt1;
  26201. if ( dt2 < 1e-4 ) dt2 = dt1;
  26202. px.initNonuniformCatmullRom( p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2 );
  26203. py.initNonuniformCatmullRom( p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2 );
  26204. pz.initNonuniformCatmullRom( p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2 );
  26205. } else if ( this.curveType === 'catmullrom' ) {
  26206. px.initCatmullRom( p0.x, p1.x, p2.x, p3.x, this.tension );
  26207. py.initCatmullRom( p0.y, p1.y, p2.y, p3.y, this.tension );
  26208. pz.initCatmullRom( p0.z, p1.z, p2.z, p3.z, this.tension );
  26209. }
  26210. point.set(
  26211. px.calc( weight ),
  26212. py.calc( weight ),
  26213. pz.calc( weight )
  26214. );
  26215. return point;
  26216. };
  26217. CatmullRomCurve3.prototype.copy = function ( source ) {
  26218. Curve.prototype.copy.call( this, source );
  26219. this.points = [];
  26220. for ( var i = 0, l = source.points.length; i < l; i ++ ) {
  26221. var point = source.points[ i ];
  26222. this.points.push( point.clone() );
  26223. }
  26224. this.closed = source.closed;
  26225. this.curveType = source.curveType;
  26226. this.tension = source.tension;
  26227. return this;
  26228. };
  26229. CatmullRomCurve3.prototype.toJSON = function () {
  26230. var data = Curve.prototype.toJSON.call( this );
  26231. data.points = [];
  26232. for ( var i = 0, l = this.points.length; i < l; i ++ ) {
  26233. var point = this.points[ i ];
  26234. data.points.push( point.toArray() );
  26235. }
  26236. data.closed = this.closed;
  26237. data.curveType = this.curveType;
  26238. data.tension = this.tension;
  26239. return data;
  26240. };
  26241. CatmullRomCurve3.prototype.fromJSON = function ( json ) {
  26242. Curve.prototype.fromJSON.call( this, json );
  26243. this.points = [];
  26244. for ( var i = 0, l = json.points.length; i < l; i ++ ) {
  26245. var point = json.points[ i ];
  26246. this.points.push( new Vector3().fromArray( point ) );
  26247. }
  26248. this.closed = json.closed;
  26249. this.curveType = json.curveType;
  26250. this.tension = json.tension;
  26251. return this;
  26252. };
  26253. /**
  26254. * @author zz85 / http://www.lab4games.net/zz85/blog
  26255. *
  26256. * Bezier Curves formulas obtained from
  26257. * http://en.wikipedia.org/wiki/Bézier_curve
  26258. */
  26259. function CatmullRom( t, p0, p1, p2, p3 ) {
  26260. var v0 = ( p2 - p0 ) * 0.5;
  26261. var v1 = ( p3 - p1 ) * 0.5;
  26262. var t2 = t * t;
  26263. var t3 = t * t2;
  26264. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  26265. }
  26266. //
  26267. function QuadraticBezierP0( t, p ) {
  26268. var k = 1 - t;
  26269. return k * k * p;
  26270. }
  26271. function QuadraticBezierP1( t, p ) {
  26272. return 2 * ( 1 - t ) * t * p;
  26273. }
  26274. function QuadraticBezierP2( t, p ) {
  26275. return t * t * p;
  26276. }
  26277. function QuadraticBezier( t, p0, p1, p2 ) {
  26278. return QuadraticBezierP0( t, p0 ) + QuadraticBezierP1( t, p1 ) +
  26279. QuadraticBezierP2( t, p2 );
  26280. }
  26281. //
  26282. function CubicBezierP0( t, p ) {
  26283. var k = 1 - t;
  26284. return k * k * k * p;
  26285. }
  26286. function CubicBezierP1( t, p ) {
  26287. var k = 1 - t;
  26288. return 3 * k * k * t * p;
  26289. }
  26290. function CubicBezierP2( t, p ) {
  26291. return 3 * ( 1 - t ) * t * t * p;
  26292. }
  26293. function CubicBezierP3( t, p ) {
  26294. return t * t * t * p;
  26295. }
  26296. function CubicBezier( t, p0, p1, p2, p3 ) {
  26297. return CubicBezierP0( t, p0 ) + CubicBezierP1( t, p1 ) + CubicBezierP2( t, p2 ) +
  26298. CubicBezierP3( t, p3 );
  26299. }
  26300. function CubicBezierCurve( v0, v1, v2, v3 ) {
  26301. Curve.call( this );
  26302. this.type = 'CubicBezierCurve';
  26303. this.v0 = v0 || new Vector2();
  26304. this.v1 = v1 || new Vector2();
  26305. this.v2 = v2 || new Vector2();
  26306. this.v3 = v3 || new Vector2();
  26307. }
  26308. CubicBezierCurve.prototype = Object.create( Curve.prototype );
  26309. CubicBezierCurve.prototype.constructor = CubicBezierCurve;
  26310. CubicBezierCurve.prototype.isCubicBezierCurve = true;
  26311. CubicBezierCurve.prototype.getPoint = function ( t, optionalTarget ) {
  26312. var point = optionalTarget || new Vector2();
  26313. var v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  26314. point.set(
  26315. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  26316. CubicBezier( t, v0.y, v1.y, v2.y, v3.y )
  26317. );
  26318. return point;
  26319. };
  26320. CubicBezierCurve.prototype.copy = function ( source ) {
  26321. Curve.prototype.copy.call( this, source );
  26322. this.v0.copy( source.v0 );
  26323. this.v1.copy( source.v1 );
  26324. this.v2.copy( source.v2 );
  26325. this.v3.copy( source.v3 );
  26326. return this;
  26327. };
  26328. CubicBezierCurve.prototype.toJSON = function () {
  26329. var data = Curve.prototype.toJSON.call( this );
  26330. data.v0 = this.v0.toArray();
  26331. data.v1 = this.v1.toArray();
  26332. data.v2 = this.v2.toArray();
  26333. data.v3 = this.v3.toArray();
  26334. return data;
  26335. };
  26336. CubicBezierCurve.prototype.fromJSON = function ( json ) {
  26337. Curve.prototype.fromJSON.call( this, json );
  26338. this.v0.fromArray( json.v0 );
  26339. this.v1.fromArray( json.v1 );
  26340. this.v2.fromArray( json.v2 );
  26341. this.v3.fromArray( json.v3 );
  26342. return this;
  26343. };
  26344. function CubicBezierCurve3( v0, v1, v2, v3 ) {
  26345. Curve.call( this );
  26346. this.type = 'CubicBezierCurve3';
  26347. this.v0 = v0 || new Vector3();
  26348. this.v1 = v1 || new Vector3();
  26349. this.v2 = v2 || new Vector3();
  26350. this.v3 = v3 || new Vector3();
  26351. }
  26352. CubicBezierCurve3.prototype = Object.create( Curve.prototype );
  26353. CubicBezierCurve3.prototype.constructor = CubicBezierCurve3;
  26354. CubicBezierCurve3.prototype.isCubicBezierCurve3 = true;
  26355. CubicBezierCurve3.prototype.getPoint = function ( t, optionalTarget ) {
  26356. var point = optionalTarget || new Vector3();
  26357. var v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  26358. point.set(
  26359. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  26360. CubicBezier( t, v0.y, v1.y, v2.y, v3.y ),
  26361. CubicBezier( t, v0.z, v1.z, v2.z, v3.z )
  26362. );
  26363. return point;
  26364. };
  26365. CubicBezierCurve3.prototype.copy = function ( source ) {
  26366. Curve.prototype.copy.call( this, source );
  26367. this.v0.copy( source.v0 );
  26368. this.v1.copy( source.v1 );
  26369. this.v2.copy( source.v2 );
  26370. this.v3.copy( source.v3 );
  26371. return this;
  26372. };
  26373. CubicBezierCurve3.prototype.toJSON = function () {
  26374. var data = Curve.prototype.toJSON.call( this );
  26375. data.v0 = this.v0.toArray();
  26376. data.v1 = this.v1.toArray();
  26377. data.v2 = this.v2.toArray();
  26378. data.v3 = this.v3.toArray();
  26379. return data;
  26380. };
  26381. CubicBezierCurve3.prototype.fromJSON = function ( json ) {
  26382. Curve.prototype.fromJSON.call( this, json );
  26383. this.v0.fromArray( json.v0 );
  26384. this.v1.fromArray( json.v1 );
  26385. this.v2.fromArray( json.v2 );
  26386. this.v3.fromArray( json.v3 );
  26387. return this;
  26388. };
  26389. function LineCurve( v1, v2 ) {
  26390. Curve.call( this );
  26391. this.type = 'LineCurve';
  26392. this.v1 = v1 || new Vector2();
  26393. this.v2 = v2 || new Vector2();
  26394. }
  26395. LineCurve.prototype = Object.create( Curve.prototype );
  26396. LineCurve.prototype.constructor = LineCurve;
  26397. LineCurve.prototype.isLineCurve = true;
  26398. LineCurve.prototype.getPoint = function ( t, optionalTarget ) {
  26399. var point = optionalTarget || new Vector2();
  26400. if ( t === 1 ) {
  26401. point.copy( this.v2 );
  26402. } else {
  26403. point.copy( this.v2 ).sub( this.v1 );
  26404. point.multiplyScalar( t ).add( this.v1 );
  26405. }
  26406. return point;
  26407. };
  26408. // Line curve is linear, so we can overwrite default getPointAt
  26409. LineCurve.prototype.getPointAt = function ( u, optionalTarget ) {
  26410. return this.getPoint( u, optionalTarget );
  26411. };
  26412. LineCurve.prototype.getTangent = function ( /* t */ ) {
  26413. var tangent = this.v2.clone().sub( this.v1 );
  26414. return tangent.normalize();
  26415. };
  26416. LineCurve.prototype.copy = function ( source ) {
  26417. Curve.prototype.copy.call( this, source );
  26418. this.v1.copy( source.v1 );
  26419. this.v2.copy( source.v2 );
  26420. return this;
  26421. };
  26422. LineCurve.prototype.toJSON = function () {
  26423. var data = Curve.prototype.toJSON.call( this );
  26424. data.v1 = this.v1.toArray();
  26425. data.v2 = this.v2.toArray();
  26426. return data;
  26427. };
  26428. LineCurve.prototype.fromJSON = function ( json ) {
  26429. Curve.prototype.fromJSON.call( this, json );
  26430. this.v1.fromArray( json.v1 );
  26431. this.v2.fromArray( json.v2 );
  26432. return this;
  26433. };
  26434. function LineCurve3( v1, v2 ) {
  26435. Curve.call( this );
  26436. this.type = 'LineCurve3';
  26437. this.v1 = v1 || new Vector3();
  26438. this.v2 = v2 || new Vector3();
  26439. }
  26440. LineCurve3.prototype = Object.create( Curve.prototype );
  26441. LineCurve3.prototype.constructor = LineCurve3;
  26442. LineCurve3.prototype.isLineCurve3 = true;
  26443. LineCurve3.prototype.getPoint = function ( t, optionalTarget ) {
  26444. var point = optionalTarget || new Vector3();
  26445. if ( t === 1 ) {
  26446. point.copy( this.v2 );
  26447. } else {
  26448. point.copy( this.v2 ).sub( this.v1 );
  26449. point.multiplyScalar( t ).add( this.v1 );
  26450. }
  26451. return point;
  26452. };
  26453. // Line curve is linear, so we can overwrite default getPointAt
  26454. LineCurve3.prototype.getPointAt = function ( u, optionalTarget ) {
  26455. return this.getPoint( u, optionalTarget );
  26456. };
  26457. LineCurve3.prototype.copy = function ( source ) {
  26458. Curve.prototype.copy.call( this, source );
  26459. this.v1.copy( source.v1 );
  26460. this.v2.copy( source.v2 );
  26461. return this;
  26462. };
  26463. LineCurve3.prototype.toJSON = function () {
  26464. var data = Curve.prototype.toJSON.call( this );
  26465. data.v1 = this.v1.toArray();
  26466. data.v2 = this.v2.toArray();
  26467. return data;
  26468. };
  26469. LineCurve3.prototype.fromJSON = function ( json ) {
  26470. Curve.prototype.fromJSON.call( this, json );
  26471. this.v1.fromArray( json.v1 );
  26472. this.v2.fromArray( json.v2 );
  26473. return this;
  26474. };
  26475. function QuadraticBezierCurve( v0, v1, v2 ) {
  26476. Curve.call( this );
  26477. this.type = 'QuadraticBezierCurve';
  26478. this.v0 = v0 || new Vector2();
  26479. this.v1 = v1 || new Vector2();
  26480. this.v2 = v2 || new Vector2();
  26481. }
  26482. QuadraticBezierCurve.prototype = Object.create( Curve.prototype );
  26483. QuadraticBezierCurve.prototype.constructor = QuadraticBezierCurve;
  26484. QuadraticBezierCurve.prototype.isQuadraticBezierCurve = true;
  26485. QuadraticBezierCurve.prototype.getPoint = function ( t, optionalTarget ) {
  26486. var point = optionalTarget || new Vector2();
  26487. var v0 = this.v0, v1 = this.v1, v2 = this.v2;
  26488. point.set(
  26489. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  26490. QuadraticBezier( t, v0.y, v1.y, v2.y )
  26491. );
  26492. return point;
  26493. };
  26494. QuadraticBezierCurve.prototype.copy = function ( source ) {
  26495. Curve.prototype.copy.call( this, source );
  26496. this.v0.copy( source.v0 );
  26497. this.v1.copy( source.v1 );
  26498. this.v2.copy( source.v2 );
  26499. return this;
  26500. };
  26501. QuadraticBezierCurve.prototype.toJSON = function () {
  26502. var data = Curve.prototype.toJSON.call( this );
  26503. data.v0 = this.v0.toArray();
  26504. data.v1 = this.v1.toArray();
  26505. data.v2 = this.v2.toArray();
  26506. return data;
  26507. };
  26508. QuadraticBezierCurve.prototype.fromJSON = function ( json ) {
  26509. Curve.prototype.fromJSON.call( this, json );
  26510. this.v0.fromArray( json.v0 );
  26511. this.v1.fromArray( json.v1 );
  26512. this.v2.fromArray( json.v2 );
  26513. return this;
  26514. };
  26515. function QuadraticBezierCurve3( v0, v1, v2 ) {
  26516. Curve.call( this );
  26517. this.type = 'QuadraticBezierCurve3';
  26518. this.v0 = v0 || new Vector3();
  26519. this.v1 = v1 || new Vector3();
  26520. this.v2 = v2 || new Vector3();
  26521. }
  26522. QuadraticBezierCurve3.prototype = Object.create( Curve.prototype );
  26523. QuadraticBezierCurve3.prototype.constructor = QuadraticBezierCurve3;
  26524. QuadraticBezierCurve3.prototype.isQuadraticBezierCurve3 = true;
  26525. QuadraticBezierCurve3.prototype.getPoint = function ( t, optionalTarget ) {
  26526. var point = optionalTarget || new Vector3();
  26527. var v0 = this.v0, v1 = this.v1, v2 = this.v2;
  26528. point.set(
  26529. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  26530. QuadraticBezier( t, v0.y, v1.y, v2.y ),
  26531. QuadraticBezier( t, v0.z, v1.z, v2.z )
  26532. );
  26533. return point;
  26534. };
  26535. QuadraticBezierCurve3.prototype.copy = function ( source ) {
  26536. Curve.prototype.copy.call( this, source );
  26537. this.v0.copy( source.v0 );
  26538. this.v1.copy( source.v1 );
  26539. this.v2.copy( source.v2 );
  26540. return this;
  26541. };
  26542. QuadraticBezierCurve3.prototype.toJSON = function () {
  26543. var data = Curve.prototype.toJSON.call( this );
  26544. data.v0 = this.v0.toArray();
  26545. data.v1 = this.v1.toArray();
  26546. data.v2 = this.v2.toArray();
  26547. return data;
  26548. };
  26549. QuadraticBezierCurve3.prototype.fromJSON = function ( json ) {
  26550. Curve.prototype.fromJSON.call( this, json );
  26551. this.v0.fromArray( json.v0 );
  26552. this.v1.fromArray( json.v1 );
  26553. this.v2.fromArray( json.v2 );
  26554. return this;
  26555. };
  26556. function SplineCurve( points /* array of Vector2 */ ) {
  26557. Curve.call( this );
  26558. this.type = 'SplineCurve';
  26559. this.points = points || [];
  26560. }
  26561. SplineCurve.prototype = Object.create( Curve.prototype );
  26562. SplineCurve.prototype.constructor = SplineCurve;
  26563. SplineCurve.prototype.isSplineCurve = true;
  26564. SplineCurve.prototype.getPoint = function ( t, optionalTarget ) {
  26565. var point = optionalTarget || new Vector2();
  26566. var points = this.points;
  26567. var p = ( points.length - 1 ) * t;
  26568. var intPoint = Math.floor( p );
  26569. var weight = p - intPoint;
  26570. var p0 = points[ intPoint === 0 ? intPoint : intPoint - 1 ];
  26571. var p1 = points[ intPoint ];
  26572. var p2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ];
  26573. var p3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ];
  26574. point.set(
  26575. CatmullRom( weight, p0.x, p1.x, p2.x, p3.x ),
  26576. CatmullRom( weight, p0.y, p1.y, p2.y, p3.y )
  26577. );
  26578. return point;
  26579. };
  26580. SplineCurve.prototype.copy = function ( source ) {
  26581. Curve.prototype.copy.call( this, source );
  26582. this.points = [];
  26583. for ( var i = 0, l = source.points.length; i < l; i ++ ) {
  26584. var point = source.points[ i ];
  26585. this.points.push( point.clone() );
  26586. }
  26587. return this;
  26588. };
  26589. SplineCurve.prototype.toJSON = function () {
  26590. var data = Curve.prototype.toJSON.call( this );
  26591. data.points = [];
  26592. for ( var i = 0, l = this.points.length; i < l; i ++ ) {
  26593. var point = this.points[ i ];
  26594. data.points.push( point.toArray() );
  26595. }
  26596. return data;
  26597. };
  26598. SplineCurve.prototype.fromJSON = function ( json ) {
  26599. Curve.prototype.fromJSON.call( this, json );
  26600. this.points = [];
  26601. for ( var i = 0, l = json.points.length; i < l; i ++ ) {
  26602. var point = json.points[ i ];
  26603. this.points.push( new Vector2().fromArray( point ) );
  26604. }
  26605. return this;
  26606. };
  26607. var Curves = /*#__PURE__*/Object.freeze({
  26608. ArcCurve: ArcCurve,
  26609. CatmullRomCurve3: CatmullRomCurve3,
  26610. CubicBezierCurve: CubicBezierCurve,
  26611. CubicBezierCurve3: CubicBezierCurve3,
  26612. EllipseCurve: EllipseCurve,
  26613. LineCurve: LineCurve,
  26614. LineCurve3: LineCurve3,
  26615. QuadraticBezierCurve: QuadraticBezierCurve,
  26616. QuadraticBezierCurve3: QuadraticBezierCurve3,
  26617. SplineCurve: SplineCurve
  26618. });
  26619. /**
  26620. * @author zz85 / http://www.lab4games.net/zz85/blog
  26621. *
  26622. **/
  26623. /**************************************************************
  26624. * Curved Path - a curve path is simply a array of connected
  26625. * curves, but retains the api of a curve
  26626. **************************************************************/
  26627. function CurvePath() {
  26628. Curve.call( this );
  26629. this.type = 'CurvePath';
  26630. this.curves = [];
  26631. this.autoClose = false; // Automatically closes the path
  26632. }
  26633. CurvePath.prototype = Object.assign( Object.create( Curve.prototype ), {
  26634. constructor: CurvePath,
  26635. add: function ( curve ) {
  26636. this.curves.push( curve );
  26637. },
  26638. closePath: function () {
  26639. // Add a line curve if start and end of lines are not connected
  26640. var startPoint = this.curves[ 0 ].getPoint( 0 );
  26641. var endPoint = this.curves[ this.curves.length - 1 ].getPoint( 1 );
  26642. if ( ! startPoint.equals( endPoint ) ) {
  26643. this.curves.push( new LineCurve( endPoint, startPoint ) );
  26644. }
  26645. },
  26646. // To get accurate point with reference to
  26647. // entire path distance at time t,
  26648. // following has to be done:
  26649. // 1. Length of each sub path have to be known
  26650. // 2. Locate and identify type of curve
  26651. // 3. Get t for the curve
  26652. // 4. Return curve.getPointAt(t')
  26653. getPoint: function ( t ) {
  26654. var d = t * this.getLength();
  26655. var curveLengths = this.getCurveLengths();
  26656. var i = 0;
  26657. // To think about boundaries points.
  26658. while ( i < curveLengths.length ) {
  26659. if ( curveLengths[ i ] >= d ) {
  26660. var diff = curveLengths[ i ] - d;
  26661. var curve = this.curves[ i ];
  26662. var segmentLength = curve.getLength();
  26663. var u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;
  26664. return curve.getPointAt( u );
  26665. }
  26666. i ++;
  26667. }
  26668. return null;
  26669. // loop where sum != 0, sum > d , sum+1 <d
  26670. },
  26671. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  26672. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  26673. // getPoint() depends on getLength
  26674. getLength: function () {
  26675. var lens = this.getCurveLengths();
  26676. return lens[ lens.length - 1 ];
  26677. },
  26678. // cacheLengths must be recalculated.
  26679. updateArcLengths: function () {
  26680. this.needsUpdate = true;
  26681. this.cacheLengths = null;
  26682. this.getCurveLengths();
  26683. },
  26684. // Compute lengths and cache them
  26685. // We cannot overwrite getLengths() because UtoT mapping uses it.
  26686. getCurveLengths: function () {
  26687. // We use cache values if curves and cache array are same length
  26688. if ( this.cacheLengths && this.cacheLengths.length === this.curves.length ) {
  26689. return this.cacheLengths;
  26690. }
  26691. // Get length of sub-curve
  26692. // Push sums into cached array
  26693. var lengths = [], sums = 0;
  26694. for ( var i = 0, l = this.curves.length; i < l; i ++ ) {
  26695. sums += this.curves[ i ].getLength();
  26696. lengths.push( sums );
  26697. }
  26698. this.cacheLengths = lengths;
  26699. return lengths;
  26700. },
  26701. getSpacedPoints: function ( divisions ) {
  26702. if ( divisions === undefined ) divisions = 40;
  26703. var points = [];
  26704. for ( var i = 0; i <= divisions; i ++ ) {
  26705. points.push( this.getPoint( i / divisions ) );
  26706. }
  26707. if ( this.autoClose ) {
  26708. points.push( points[ 0 ] );
  26709. }
  26710. return points;
  26711. },
  26712. getPoints: function ( divisions ) {
  26713. divisions = divisions || 12;
  26714. var points = [], last;
  26715. for ( var i = 0, curves = this.curves; i < curves.length; i ++ ) {
  26716. var curve = curves[ i ];
  26717. var resolution = ( curve && curve.isEllipseCurve ) ? divisions * 2
  26718. : ( curve && ( curve.isLineCurve || curve.isLineCurve3 ) ) ? 1
  26719. : ( curve && curve.isSplineCurve ) ? divisions * curve.points.length
  26720. : divisions;
  26721. var pts = curve.getPoints( resolution );
  26722. for ( var j = 0; j < pts.length; j ++ ) {
  26723. var point = pts[ j ];
  26724. if ( last && last.equals( point ) ) continue; // ensures no consecutive points are duplicates
  26725. points.push( point );
  26726. last = point;
  26727. }
  26728. }
  26729. if ( this.autoClose && points.length > 1 && ! points[ points.length - 1 ].equals( points[ 0 ] ) ) {
  26730. points.push( points[ 0 ] );
  26731. }
  26732. return points;
  26733. },
  26734. copy: function ( source ) {
  26735. Curve.prototype.copy.call( this, source );
  26736. this.curves = [];
  26737. for ( var i = 0, l = source.curves.length; i < l; i ++ ) {
  26738. var curve = source.curves[ i ];
  26739. this.curves.push( curve.clone() );
  26740. }
  26741. this.autoClose = source.autoClose;
  26742. return this;
  26743. },
  26744. toJSON: function () {
  26745. var data = Curve.prototype.toJSON.call( this );
  26746. data.autoClose = this.autoClose;
  26747. data.curves = [];
  26748. for ( var i = 0, l = this.curves.length; i < l; i ++ ) {
  26749. var curve = this.curves[ i ];
  26750. data.curves.push( curve.toJSON() );
  26751. }
  26752. return data;
  26753. },
  26754. fromJSON: function ( json ) {
  26755. Curve.prototype.fromJSON.call( this, json );
  26756. this.autoClose = json.autoClose;
  26757. this.curves = [];
  26758. for ( var i = 0, l = json.curves.length; i < l; i ++ ) {
  26759. var curve = json.curves[ i ];
  26760. this.curves.push( new Curves[ curve.type ]().fromJSON( curve ) );
  26761. }
  26762. return this;
  26763. }
  26764. } );
  26765. /**
  26766. * @author zz85 / http://www.lab4games.net/zz85/blog
  26767. * Creates free form 2d path using series of points, lines or curves.
  26768. **/
  26769. function Path( points ) {
  26770. CurvePath.call( this );
  26771. this.type = 'Path';
  26772. this.currentPoint = new Vector2();
  26773. if ( points ) {
  26774. this.setFromPoints( points );
  26775. }
  26776. }
  26777. Path.prototype = Object.assign( Object.create( CurvePath.prototype ), {
  26778. constructor: Path,
  26779. setFromPoints: function ( points ) {
  26780. this.moveTo( points[ 0 ].x, points[ 0 ].y );
  26781. for ( var i = 1, l = points.length; i < l; i ++ ) {
  26782. this.lineTo( points[ i ].x, points[ i ].y );
  26783. }
  26784. },
  26785. moveTo: function ( x, y ) {
  26786. this.currentPoint.set( x, y ); // TODO consider referencing vectors instead of copying?
  26787. },
  26788. lineTo: function ( x, y ) {
  26789. var curve = new LineCurve( this.currentPoint.clone(), new Vector2( x, y ) );
  26790. this.curves.push( curve );
  26791. this.currentPoint.set( x, y );
  26792. },
  26793. quadraticCurveTo: function ( aCPx, aCPy, aX, aY ) {
  26794. var curve = new QuadraticBezierCurve(
  26795. this.currentPoint.clone(),
  26796. new Vector2( aCPx, aCPy ),
  26797. new Vector2( aX, aY )
  26798. );
  26799. this.curves.push( curve );
  26800. this.currentPoint.set( aX, aY );
  26801. },
  26802. bezierCurveTo: function ( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  26803. var curve = new CubicBezierCurve(
  26804. this.currentPoint.clone(),
  26805. new Vector2( aCP1x, aCP1y ),
  26806. new Vector2( aCP2x, aCP2y ),
  26807. new Vector2( aX, aY )
  26808. );
  26809. this.curves.push( curve );
  26810. this.currentPoint.set( aX, aY );
  26811. },
  26812. splineThru: function ( pts /*Array of Vector*/ ) {
  26813. var npts = [ this.currentPoint.clone() ].concat( pts );
  26814. var curve = new SplineCurve( npts );
  26815. this.curves.push( curve );
  26816. this.currentPoint.copy( pts[ pts.length - 1 ] );
  26817. },
  26818. arc: function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  26819. var x0 = this.currentPoint.x;
  26820. var y0 = this.currentPoint.y;
  26821. this.absarc( aX + x0, aY + y0, aRadius,
  26822. aStartAngle, aEndAngle, aClockwise );
  26823. },
  26824. absarc: function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  26825. this.absellipse( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  26826. },
  26827. ellipse: function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  26828. var x0 = this.currentPoint.x;
  26829. var y0 = this.currentPoint.y;
  26830. this.absellipse( aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  26831. },
  26832. absellipse: function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  26833. var curve = new EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  26834. if ( this.curves.length > 0 ) {
  26835. // if a previous curve is present, attempt to join
  26836. var firstPoint = curve.getPoint( 0 );
  26837. if ( ! firstPoint.equals( this.currentPoint ) ) {
  26838. this.lineTo( firstPoint.x, firstPoint.y );
  26839. }
  26840. }
  26841. this.curves.push( curve );
  26842. var lastPoint = curve.getPoint( 1 );
  26843. this.currentPoint.copy( lastPoint );
  26844. },
  26845. copy: function ( source ) {
  26846. CurvePath.prototype.copy.call( this, source );
  26847. this.currentPoint.copy( source.currentPoint );
  26848. return this;
  26849. },
  26850. toJSON: function () {
  26851. var data = CurvePath.prototype.toJSON.call( this );
  26852. data.currentPoint = this.currentPoint.toArray();
  26853. return data;
  26854. },
  26855. fromJSON: function ( json ) {
  26856. CurvePath.prototype.fromJSON.call( this, json );
  26857. this.currentPoint.fromArray( json.currentPoint );
  26858. return this;
  26859. }
  26860. } );
  26861. /**
  26862. * @author zz85 / http://www.lab4games.net/zz85/blog
  26863. * Defines a 2d shape plane using paths.
  26864. **/
  26865. // STEP 1 Create a path.
  26866. // STEP 2 Turn path into shape.
  26867. // STEP 3 ExtrudeGeometry takes in Shape/Shapes
  26868. // STEP 3a - Extract points from each shape, turn to vertices
  26869. // STEP 3b - Triangulate each shape, add faces.
  26870. function Shape( points ) {
  26871. Path.call( this, points );
  26872. this.uuid = _Math.generateUUID();
  26873. this.type = 'Shape';
  26874. this.holes = [];
  26875. }
  26876. Shape.prototype = Object.assign( Object.create( Path.prototype ), {
  26877. constructor: Shape,
  26878. getPointsHoles: function ( divisions ) {
  26879. var holesPts = [];
  26880. for ( var i = 0, l = this.holes.length; i < l; i ++ ) {
  26881. holesPts[ i ] = this.holes[ i ].getPoints( divisions );
  26882. }
  26883. return holesPts;
  26884. },
  26885. // get points of shape and holes (keypoints based on segments parameter)
  26886. extractPoints: function ( divisions ) {
  26887. return {
  26888. shape: this.getPoints( divisions ),
  26889. holes: this.getPointsHoles( divisions )
  26890. };
  26891. },
  26892. copy: function ( source ) {
  26893. Path.prototype.copy.call( this, source );
  26894. this.holes = [];
  26895. for ( var i = 0, l = source.holes.length; i < l; i ++ ) {
  26896. var hole = source.holes[ i ];
  26897. this.holes.push( hole.clone() );
  26898. }
  26899. return this;
  26900. },
  26901. toJSON: function () {
  26902. var data = Path.prototype.toJSON.call( this );
  26903. data.uuid = this.uuid;
  26904. data.holes = [];
  26905. for ( var i = 0, l = this.holes.length; i < l; i ++ ) {
  26906. var hole = this.holes[ i ];
  26907. data.holes.push( hole.toJSON() );
  26908. }
  26909. return data;
  26910. },
  26911. fromJSON: function ( json ) {
  26912. Path.prototype.fromJSON.call( this, json );
  26913. this.uuid = json.uuid;
  26914. this.holes = [];
  26915. for ( var i = 0, l = json.holes.length; i < l; i ++ ) {
  26916. var hole = json.holes[ i ];
  26917. this.holes.push( new Path().fromJSON( hole ) );
  26918. }
  26919. return this;
  26920. }
  26921. } );
  26922. /**
  26923. * @author mrdoob / http://mrdoob.com/
  26924. * @author alteredq / http://alteredqualia.com/
  26925. */
  26926. function Light( color, intensity ) {
  26927. Object3D.call( this );
  26928. this.type = 'Light';
  26929. this.color = new Color( color );
  26930. this.intensity = intensity !== undefined ? intensity : 1;
  26931. this.receiveShadow = undefined;
  26932. }
  26933. Light.prototype = Object.assign( Object.create( Object3D.prototype ), {
  26934. constructor: Light,
  26935. isLight: true,
  26936. copy: function ( source ) {
  26937. Object3D.prototype.copy.call( this, source );
  26938. this.color.copy( source.color );
  26939. this.intensity = source.intensity;
  26940. return this;
  26941. },
  26942. toJSON: function ( meta ) {
  26943. var data = Object3D.prototype.toJSON.call( this, meta );
  26944. data.object.color = this.color.getHex();
  26945. data.object.intensity = this.intensity;
  26946. if ( this.groundColor !== undefined ) data.object.groundColor = this.groundColor.getHex();
  26947. if ( this.distance !== undefined ) data.object.distance = this.distance;
  26948. if ( this.angle !== undefined ) data.object.angle = this.angle;
  26949. if ( this.decay !== undefined ) data.object.decay = this.decay;
  26950. if ( this.penumbra !== undefined ) data.object.penumbra = this.penumbra;
  26951. if ( this.shadow !== undefined ) data.object.shadow = this.shadow.toJSON();
  26952. return data;
  26953. }
  26954. } );
  26955. /**
  26956. * @author alteredq / http://alteredqualia.com/
  26957. */
  26958. function HemisphereLight( skyColor, groundColor, intensity ) {
  26959. Light.call( this, skyColor, intensity );
  26960. this.type = 'HemisphereLight';
  26961. this.castShadow = undefined;
  26962. this.position.copy( Object3D.DefaultUp );
  26963. this.updateMatrix();
  26964. this.groundColor = new Color( groundColor );
  26965. }
  26966. HemisphereLight.prototype = Object.assign( Object.create( Light.prototype ), {
  26967. constructor: HemisphereLight,
  26968. isHemisphereLight: true,
  26969. copy: function ( source ) {
  26970. Light.prototype.copy.call( this, source );
  26971. this.groundColor.copy( source.groundColor );
  26972. return this;
  26973. }
  26974. } );
  26975. /**
  26976. * @author mrdoob / http://mrdoob.com/
  26977. */
  26978. function LightShadow( camera ) {
  26979. this.camera = camera;
  26980. this.bias = 0;
  26981. this.radius = 1;
  26982. this.mapSize = new Vector2( 512, 512 );
  26983. this.map = null;
  26984. this.matrix = new Matrix4();
  26985. }
  26986. Object.assign( LightShadow.prototype, {
  26987. copy: function ( source ) {
  26988. this.camera = source.camera.clone();
  26989. this.bias = source.bias;
  26990. this.radius = source.radius;
  26991. this.mapSize.copy( source.mapSize );
  26992. return this;
  26993. },
  26994. clone: function () {
  26995. return new this.constructor().copy( this );
  26996. },
  26997. toJSON: function () {
  26998. var object = {};
  26999. if ( this.bias !== 0 ) object.bias = this.bias;
  27000. if ( this.radius !== 1 ) object.radius = this.radius;
  27001. if ( this.mapSize.x !== 512 || this.mapSize.y !== 512 ) object.mapSize = this.mapSize.toArray();
  27002. object.camera = this.camera.toJSON( false ).object;
  27003. delete object.camera.matrix;
  27004. return object;
  27005. }
  27006. } );
  27007. /**
  27008. * @author mrdoob / http://mrdoob.com/
  27009. */
  27010. function SpotLightShadow() {
  27011. LightShadow.call( this, new PerspectiveCamera( 50, 1, 0.5, 500 ) );
  27012. }
  27013. SpotLightShadow.prototype = Object.assign( Object.create( LightShadow.prototype ), {
  27014. constructor: SpotLightShadow,
  27015. isSpotLightShadow: true,
  27016. update: function ( light ) {
  27017. var camera = this.camera;
  27018. var fov = _Math.RAD2DEG * 2 * light.angle;
  27019. var aspect = this.mapSize.width / this.mapSize.height;
  27020. var far = light.distance || camera.far;
  27021. if ( fov !== camera.fov || aspect !== camera.aspect || far !== camera.far ) {
  27022. camera.fov = fov;
  27023. camera.aspect = aspect;
  27024. camera.far = far;
  27025. camera.updateProjectionMatrix();
  27026. }
  27027. }
  27028. } );
  27029. /**
  27030. * @author alteredq / http://alteredqualia.com/
  27031. */
  27032. function SpotLight( color, intensity, distance, angle, penumbra, decay ) {
  27033. Light.call( this, color, intensity );
  27034. this.type = 'SpotLight';
  27035. this.position.copy( Object3D.DefaultUp );
  27036. this.updateMatrix();
  27037. this.target = new Object3D();
  27038. Object.defineProperty( this, 'power', {
  27039. get: function () {
  27040. // intensity = power per solid angle.
  27041. // ref: equation (17) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  27042. return this.intensity * Math.PI;
  27043. },
  27044. set: function ( power ) {
  27045. // intensity = power per solid angle.
  27046. // ref: equation (17) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  27047. this.intensity = power / Math.PI;
  27048. }
  27049. } );
  27050. this.distance = ( distance !== undefined ) ? distance : 0;
  27051. this.angle = ( angle !== undefined ) ? angle : Math.PI / 3;
  27052. this.penumbra = ( penumbra !== undefined ) ? penumbra : 0;
  27053. this.decay = ( decay !== undefined ) ? decay : 1; // for physically correct lights, should be 2.
  27054. this.shadow = new SpotLightShadow();
  27055. }
  27056. SpotLight.prototype = Object.assign( Object.create( Light.prototype ), {
  27057. constructor: SpotLight,
  27058. isSpotLight: true,
  27059. copy: function ( source ) {
  27060. Light.prototype.copy.call( this, source );
  27061. this.distance = source.distance;
  27062. this.angle = source.angle;
  27063. this.penumbra = source.penumbra;
  27064. this.decay = source.decay;
  27065. this.target = source.target.clone();
  27066. this.shadow = source.shadow.clone();
  27067. return this;
  27068. }
  27069. } );
  27070. /**
  27071. * @author mrdoob / http://mrdoob.com/
  27072. */
  27073. function PointLight( color, intensity, distance, decay ) {
  27074. Light.call( this, color, intensity );
  27075. this.type = 'PointLight';
  27076. Object.defineProperty( this, 'power', {
  27077. get: function () {
  27078. // intensity = power per solid angle.
  27079. // ref: equation (15) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  27080. return this.intensity * 4 * Math.PI;
  27081. },
  27082. set: function ( power ) {
  27083. // intensity = power per solid angle.
  27084. // ref: equation (15) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  27085. this.intensity = power / ( 4 * Math.PI );
  27086. }
  27087. } );
  27088. this.distance = ( distance !== undefined ) ? distance : 0;
  27089. this.decay = ( decay !== undefined ) ? decay : 1; // for physically correct lights, should be 2.
  27090. this.shadow = new LightShadow( new PerspectiveCamera( 90, 1, 0.5, 500 ) );
  27091. }
  27092. PointLight.prototype = Object.assign( Object.create( Light.prototype ), {
  27093. constructor: PointLight,
  27094. isPointLight: true,
  27095. copy: function ( source ) {
  27096. Light.prototype.copy.call( this, source );
  27097. this.distance = source.distance;
  27098. this.decay = source.decay;
  27099. this.shadow = source.shadow.clone();
  27100. return this;
  27101. }
  27102. } );
  27103. /**
  27104. * @author alteredq / http://alteredqualia.com/
  27105. * @author arose / http://github.com/arose
  27106. */
  27107. function OrthographicCamera( left, right, top, bottom, near, far ) {
  27108. Camera.call( this );
  27109. this.type = 'OrthographicCamera';
  27110. this.zoom = 1;
  27111. this.view = null;
  27112. this.left = ( left !== undefined ) ? left : - 1;
  27113. this.right = ( right !== undefined ) ? right : 1;
  27114. this.top = ( top !== undefined ) ? top : 1;
  27115. this.bottom = ( bottom !== undefined ) ? bottom : - 1;
  27116. this.near = ( near !== undefined ) ? near : 0.1;
  27117. this.far = ( far !== undefined ) ? far : 2000;
  27118. this.updateProjectionMatrix();
  27119. }
  27120. OrthographicCamera.prototype = Object.assign( Object.create( Camera.prototype ), {
  27121. constructor: OrthographicCamera,
  27122. isOrthographicCamera: true,
  27123. copy: function ( source, recursive ) {
  27124. Camera.prototype.copy.call( this, source, recursive );
  27125. this.left = source.left;
  27126. this.right = source.right;
  27127. this.top = source.top;
  27128. this.bottom = source.bottom;
  27129. this.near = source.near;
  27130. this.far = source.far;
  27131. this.zoom = source.zoom;
  27132. this.view = source.view === null ? null : Object.assign( {}, source.view );
  27133. return this;
  27134. },
  27135. setViewOffset: function ( fullWidth, fullHeight, x, y, width, height ) {
  27136. if ( this.view === null ) {
  27137. this.view = {
  27138. enabled: true,
  27139. fullWidth: 1,
  27140. fullHeight: 1,
  27141. offsetX: 0,
  27142. offsetY: 0,
  27143. width: 1,
  27144. height: 1
  27145. };
  27146. }
  27147. this.view.enabled = true;
  27148. this.view.fullWidth = fullWidth;
  27149. this.view.fullHeight = fullHeight;
  27150. this.view.offsetX = x;
  27151. this.view.offsetY = y;
  27152. this.view.width = width;
  27153. this.view.height = height;
  27154. this.updateProjectionMatrix();
  27155. },
  27156. clearViewOffset: function () {
  27157. if ( this.view !== null ) {
  27158. this.view.enabled = false;
  27159. }
  27160. this.updateProjectionMatrix();
  27161. },
  27162. updateProjectionMatrix: function () {
  27163. var dx = ( this.right - this.left ) / ( 2 * this.zoom );
  27164. var dy = ( this.top - this.bottom ) / ( 2 * this.zoom );
  27165. var cx = ( this.right + this.left ) / 2;
  27166. var cy = ( this.top + this.bottom ) / 2;
  27167. var left = cx - dx;
  27168. var right = cx + dx;
  27169. var top = cy + dy;
  27170. var bottom = cy - dy;
  27171. if ( this.view !== null && this.view.enabled ) {
  27172. var zoomW = this.zoom / ( this.view.width / this.view.fullWidth );
  27173. var zoomH = this.zoom / ( this.view.height / this.view.fullHeight );
  27174. var scaleW = ( this.right - this.left ) / this.view.width;
  27175. var scaleH = ( this.top - this.bottom ) / this.view.height;
  27176. left += scaleW * ( this.view.offsetX / zoomW );
  27177. right = left + scaleW * ( this.view.width / zoomW );
  27178. top -= scaleH * ( this.view.offsetY / zoomH );
  27179. bottom = top - scaleH * ( this.view.height / zoomH );
  27180. }
  27181. this.projectionMatrix.makeOrthographic( left, right, top, bottom, this.near, this.far );
  27182. this.projectionMatrixInverse.getInverse( this.projectionMatrix );
  27183. },
  27184. toJSON: function ( meta ) {
  27185. var data = Object3D.prototype.toJSON.call( this, meta );
  27186. data.object.zoom = this.zoom;
  27187. data.object.left = this.left;
  27188. data.object.right = this.right;
  27189. data.object.top = this.top;
  27190. data.object.bottom = this.bottom;
  27191. data.object.near = this.near;
  27192. data.object.far = this.far;
  27193. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  27194. return data;
  27195. }
  27196. } );
  27197. /**
  27198. * @author mrdoob / http://mrdoob.com/
  27199. */
  27200. function DirectionalLightShadow( ) {
  27201. LightShadow.call( this, new OrthographicCamera( - 5, 5, 5, - 5, 0.5, 500 ) );
  27202. }
  27203. DirectionalLightShadow.prototype = Object.assign( Object.create( LightShadow.prototype ), {
  27204. constructor: DirectionalLightShadow
  27205. } );
  27206. /**
  27207. * @author mrdoob / http://mrdoob.com/
  27208. * @author alteredq / http://alteredqualia.com/
  27209. */
  27210. function DirectionalLight( color, intensity ) {
  27211. Light.call( this, color, intensity );
  27212. this.type = 'DirectionalLight';
  27213. this.position.copy( Object3D.DefaultUp );
  27214. this.updateMatrix();
  27215. this.target = new Object3D();
  27216. this.shadow = new DirectionalLightShadow();
  27217. }
  27218. DirectionalLight.prototype = Object.assign( Object.create( Light.prototype ), {
  27219. constructor: DirectionalLight,
  27220. isDirectionalLight: true,
  27221. copy: function ( source ) {
  27222. Light.prototype.copy.call( this, source );
  27223. this.target = source.target.clone();
  27224. this.shadow = source.shadow.clone();
  27225. return this;
  27226. }
  27227. } );
  27228. /**
  27229. * @author mrdoob / http://mrdoob.com/
  27230. */
  27231. function AmbientLight( color, intensity ) {
  27232. Light.call( this, color, intensity );
  27233. this.type = 'AmbientLight';
  27234. this.castShadow = undefined;
  27235. }
  27236. AmbientLight.prototype = Object.assign( Object.create( Light.prototype ), {
  27237. constructor: AmbientLight,
  27238. isAmbientLight: true
  27239. } );
  27240. /**
  27241. * @author abelnation / http://github.com/abelnation
  27242. */
  27243. function RectAreaLight( color, intensity, width, height ) {
  27244. Light.call( this, color, intensity );
  27245. this.type = 'RectAreaLight';
  27246. this.width = ( width !== undefined ) ? width : 10;
  27247. this.height = ( height !== undefined ) ? height : 10;
  27248. }
  27249. RectAreaLight.prototype = Object.assign( Object.create( Light.prototype ), {
  27250. constructor: RectAreaLight,
  27251. isRectAreaLight: true,
  27252. copy: function ( source ) {
  27253. Light.prototype.copy.call( this, source );
  27254. this.width = source.width;
  27255. this.height = source.height;
  27256. return this;
  27257. },
  27258. toJSON: function ( meta ) {
  27259. var data = Light.prototype.toJSON.call( this, meta );
  27260. data.object.width = this.width;
  27261. data.object.height = this.height;
  27262. return data;
  27263. }
  27264. } );
  27265. /**
  27266. * @author mrdoob / http://mrdoob.com/
  27267. */
  27268. function MaterialLoader( manager ) {
  27269. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  27270. this.textures = {};
  27271. }
  27272. Object.assign( MaterialLoader.prototype, {
  27273. load: function ( url, onLoad, onProgress, onError ) {
  27274. var scope = this;
  27275. var loader = new FileLoader( scope.manager );
  27276. loader.setPath( scope.path );
  27277. loader.load( url, function ( text ) {
  27278. onLoad( scope.parse( JSON.parse( text ) ) );
  27279. }, onProgress, onError );
  27280. },
  27281. parse: function ( json ) {
  27282. var textures = this.textures;
  27283. function getTexture( name ) {
  27284. if ( textures[ name ] === undefined ) {
  27285. console.warn( 'THREE.MaterialLoader: Undefined texture', name );
  27286. }
  27287. return textures[ name ];
  27288. }
  27289. var material = new Materials[ json.type ]();
  27290. if ( json.uuid !== undefined ) material.uuid = json.uuid;
  27291. if ( json.name !== undefined ) material.name = json.name;
  27292. if ( json.color !== undefined ) material.color.setHex( json.color );
  27293. if ( json.roughness !== undefined ) material.roughness = json.roughness;
  27294. if ( json.metalness !== undefined ) material.metalness = json.metalness;
  27295. if ( json.emissive !== undefined ) material.emissive.setHex( json.emissive );
  27296. if ( json.specular !== undefined ) material.specular.setHex( json.specular );
  27297. if ( json.shininess !== undefined ) material.shininess = json.shininess;
  27298. if ( json.clearCoat !== undefined ) material.clearCoat = json.clearCoat;
  27299. if ( json.clearCoatRoughness !== undefined ) material.clearCoatRoughness = json.clearCoatRoughness;
  27300. if ( json.vertexColors !== undefined ) material.vertexColors = json.vertexColors;
  27301. if ( json.fog !== undefined ) material.fog = json.fog;
  27302. if ( json.flatShading !== undefined ) material.flatShading = json.flatShading;
  27303. if ( json.blending !== undefined ) material.blending = json.blending;
  27304. if ( json.combine !== undefined ) material.combine = json.combine;
  27305. if ( json.side !== undefined ) material.side = json.side;
  27306. if ( json.opacity !== undefined ) material.opacity = json.opacity;
  27307. if ( json.transparent !== undefined ) material.transparent = json.transparent;
  27308. if ( json.alphaTest !== undefined ) material.alphaTest = json.alphaTest;
  27309. if ( json.depthTest !== undefined ) material.depthTest = json.depthTest;
  27310. if ( json.depthWrite !== undefined ) material.depthWrite = json.depthWrite;
  27311. if ( json.colorWrite !== undefined ) material.colorWrite = json.colorWrite;
  27312. if ( json.wireframe !== undefined ) material.wireframe = json.wireframe;
  27313. if ( json.wireframeLinewidth !== undefined ) material.wireframeLinewidth = json.wireframeLinewidth;
  27314. if ( json.wireframeLinecap !== undefined ) material.wireframeLinecap = json.wireframeLinecap;
  27315. if ( json.wireframeLinejoin !== undefined ) material.wireframeLinejoin = json.wireframeLinejoin;
  27316. if ( json.rotation !== undefined ) material.rotation = json.rotation;
  27317. if ( json.linewidth !== 1 ) material.linewidth = json.linewidth;
  27318. if ( json.dashSize !== undefined ) material.dashSize = json.dashSize;
  27319. if ( json.gapSize !== undefined ) material.gapSize = json.gapSize;
  27320. if ( json.scale !== undefined ) material.scale = json.scale;
  27321. if ( json.polygonOffset !== undefined ) material.polygonOffset = json.polygonOffset;
  27322. if ( json.polygonOffsetFactor !== undefined ) material.polygonOffsetFactor = json.polygonOffsetFactor;
  27323. if ( json.polygonOffsetUnits !== undefined ) material.polygonOffsetUnits = json.polygonOffsetUnits;
  27324. if ( json.skinning !== undefined ) material.skinning = json.skinning;
  27325. if ( json.morphTargets !== undefined ) material.morphTargets = json.morphTargets;
  27326. if ( json.dithering !== undefined ) material.dithering = json.dithering;
  27327. if ( json.visible !== undefined ) material.visible = json.visible;
  27328. if ( json.userData !== undefined ) material.userData = json.userData;
  27329. // Shader Material
  27330. if ( json.uniforms !== undefined ) {
  27331. for ( var name in json.uniforms ) {
  27332. var uniform = json.uniforms[ name ];
  27333. material.uniforms[ name ] = {};
  27334. switch ( uniform.type ) {
  27335. case 't':
  27336. material.uniforms[ name ].value = getTexture( uniform.value );
  27337. break;
  27338. case 'c':
  27339. material.uniforms[ name ].value = new Color().setHex( uniform.value );
  27340. break;
  27341. case 'v2':
  27342. material.uniforms[ name ].value = new Vector2().fromArray( uniform.value );
  27343. break;
  27344. case 'v3':
  27345. material.uniforms[ name ].value = new Vector3().fromArray( uniform.value );
  27346. break;
  27347. case 'v4':
  27348. material.uniforms[ name ].value = new Vector4().fromArray( uniform.value );
  27349. break;
  27350. case 'm3':
  27351. material.uniforms[ name ].value = new Matrix3().fromArray( uniform.value );
  27352. case 'm4':
  27353. material.uniforms[ name ].value = new Matrix4().fromArray( uniform.value );
  27354. break;
  27355. default:
  27356. material.uniforms[ name ].value = uniform.value;
  27357. }
  27358. }
  27359. }
  27360. if ( json.defines !== undefined ) material.defines = json.defines;
  27361. if ( json.vertexShader !== undefined ) material.vertexShader = json.vertexShader;
  27362. if ( json.fragmentShader !== undefined ) material.fragmentShader = json.fragmentShader;
  27363. if ( json.extensions !== undefined ) {
  27364. for ( var key in json.extensions ) {
  27365. material.extensions[ key ] = json.extensions[ key ];
  27366. }
  27367. }
  27368. // Deprecated
  27369. if ( json.shading !== undefined ) material.flatShading = json.shading === 1; // THREE.FlatShading
  27370. // for PointsMaterial
  27371. if ( json.size !== undefined ) material.size = json.size;
  27372. if ( json.sizeAttenuation !== undefined ) material.sizeAttenuation = json.sizeAttenuation;
  27373. // maps
  27374. if ( json.map !== undefined ) material.map = getTexture( json.map );
  27375. if ( json.alphaMap !== undefined ) {
  27376. material.alphaMap = getTexture( json.alphaMap );
  27377. material.transparent = true;
  27378. }
  27379. if ( json.bumpMap !== undefined ) material.bumpMap = getTexture( json.bumpMap );
  27380. if ( json.bumpScale !== undefined ) material.bumpScale = json.bumpScale;
  27381. if ( json.normalMap !== undefined ) material.normalMap = getTexture( json.normalMap );
  27382. if ( json.normalMapType !== undefined ) material.normalMapType = json.normalMapType;
  27383. if ( json.normalScale !== undefined ) {
  27384. var normalScale = json.normalScale;
  27385. if ( Array.isArray( normalScale ) === false ) {
  27386. // Blender exporter used to export a scalar. See #7459
  27387. normalScale = [ normalScale, normalScale ];
  27388. }
  27389. material.normalScale = new Vector2().fromArray( normalScale );
  27390. }
  27391. if ( json.displacementMap !== undefined ) material.displacementMap = getTexture( json.displacementMap );
  27392. if ( json.displacementScale !== undefined ) material.displacementScale = json.displacementScale;
  27393. if ( json.displacementBias !== undefined ) material.displacementBias = json.displacementBias;
  27394. if ( json.roughnessMap !== undefined ) material.roughnessMap = getTexture( json.roughnessMap );
  27395. if ( json.metalnessMap !== undefined ) material.metalnessMap = getTexture( json.metalnessMap );
  27396. if ( json.emissiveMap !== undefined ) material.emissiveMap = getTexture( json.emissiveMap );
  27397. if ( json.emissiveIntensity !== undefined ) material.emissiveIntensity = json.emissiveIntensity;
  27398. if ( json.specularMap !== undefined ) material.specularMap = getTexture( json.specularMap );
  27399. if ( json.envMap !== undefined ) material.envMap = getTexture( json.envMap );
  27400. if ( json.envMapIntensity !== undefined ) material.envMapIntensity = json.envMapIntensity;
  27401. if ( json.reflectivity !== undefined ) material.reflectivity = json.reflectivity;
  27402. if ( json.lightMap !== undefined ) material.lightMap = getTexture( json.lightMap );
  27403. if ( json.lightMapIntensity !== undefined ) material.lightMapIntensity = json.lightMapIntensity;
  27404. if ( json.aoMap !== undefined ) material.aoMap = getTexture( json.aoMap );
  27405. if ( json.aoMapIntensity !== undefined ) material.aoMapIntensity = json.aoMapIntensity;
  27406. if ( json.gradientMap !== undefined ) material.gradientMap = getTexture( json.gradientMap );
  27407. return material;
  27408. },
  27409. setPath: function ( value ) {
  27410. this.path = value;
  27411. return this;
  27412. },
  27413. setTextures: function ( value ) {
  27414. this.textures = value;
  27415. return this;
  27416. }
  27417. } );
  27418. /**
  27419. * @author Don McCurdy / https://www.donmccurdy.com
  27420. */
  27421. var LoaderUtils = {
  27422. decodeText: function ( array ) {
  27423. if ( typeof TextDecoder !== 'undefined' ) {
  27424. return new TextDecoder().decode( array );
  27425. }
  27426. // Avoid the String.fromCharCode.apply(null, array) shortcut, which
  27427. // throws a "maximum call stack size exceeded" error for large arrays.
  27428. var s = '';
  27429. for ( var i = 0, il = array.length; i < il; i ++ ) {
  27430. // Implicitly assumes little-endian.
  27431. s += String.fromCharCode( array[ i ] );
  27432. }
  27433. // Merges multi-byte utf-8 characters.
  27434. return decodeURIComponent( escape( s ) );
  27435. },
  27436. extractUrlBase: function ( url ) {
  27437. var index = url.lastIndexOf( '/' );
  27438. if ( index === - 1 ) return './';
  27439. return url.substr( 0, index + 1 );
  27440. }
  27441. };
  27442. /**
  27443. * @author mrdoob / http://mrdoob.com/
  27444. */
  27445. function BufferGeometryLoader( manager ) {
  27446. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  27447. }
  27448. Object.assign( BufferGeometryLoader.prototype, {
  27449. load: function ( url, onLoad, onProgress, onError ) {
  27450. var scope = this;
  27451. var loader = new FileLoader( scope.manager );
  27452. loader.setPath( scope.path );
  27453. loader.load( url, function ( text ) {
  27454. onLoad( scope.parse( JSON.parse( text ) ) );
  27455. }, onProgress, onError );
  27456. },
  27457. parse: function ( json ) {
  27458. var geometry = new BufferGeometry();
  27459. var index = json.data.index;
  27460. if ( index !== undefined ) {
  27461. var typedArray = new TYPED_ARRAYS[ index.type ]( index.array );
  27462. geometry.setIndex( new BufferAttribute( typedArray, 1 ) );
  27463. }
  27464. var attributes = json.data.attributes;
  27465. for ( var key in attributes ) {
  27466. var attribute = attributes[ key ];
  27467. var typedArray = new TYPED_ARRAYS[ attribute.type ]( attribute.array );
  27468. var bufferAttribute = new BufferAttribute( typedArray, attribute.itemSize, attribute.normalized );
  27469. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  27470. geometry.addAttribute( key, bufferAttribute );
  27471. }
  27472. var morphAttributes = json.data.morphAttributes;
  27473. if ( morphAttributes ) {
  27474. for ( var key in morphAttributes ) {
  27475. var attributeArray = morphAttributes[ key ];
  27476. var array = [];
  27477. for ( var i = 0, il = attributeArray.length; i < il; i ++ ) {
  27478. var attribute = attributeArray[ i ];
  27479. var typedArray = new TYPED_ARRAYS[ attribute.type ]( attribute.array );
  27480. var bufferAttribute = new BufferAttribute( typedArray, attribute.itemSize, attribute.normalized );
  27481. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  27482. array.push( bufferAttribute );
  27483. }
  27484. geometry.morphAttributes[ key ] = array;
  27485. }
  27486. }
  27487. var groups = json.data.groups || json.data.drawcalls || json.data.offsets;
  27488. if ( groups !== undefined ) {
  27489. for ( var i = 0, n = groups.length; i !== n; ++ i ) {
  27490. var group = groups[ i ];
  27491. geometry.addGroup( group.start, group.count, group.materialIndex );
  27492. }
  27493. }
  27494. var boundingSphere = json.data.boundingSphere;
  27495. if ( boundingSphere !== undefined ) {
  27496. var center = new Vector3();
  27497. if ( boundingSphere.center !== undefined ) {
  27498. center.fromArray( boundingSphere.center );
  27499. }
  27500. geometry.boundingSphere = new Sphere( center, boundingSphere.radius );
  27501. }
  27502. if ( json.name ) geometry.name = json.name;
  27503. if ( json.userData ) geometry.userData = json.userData;
  27504. return geometry;
  27505. },
  27506. setPath: function ( value ) {
  27507. this.path = value;
  27508. return this;
  27509. }
  27510. } );
  27511. var TYPED_ARRAYS = {
  27512. Int8Array: Int8Array,
  27513. Uint8Array: Uint8Array,
  27514. // Workaround for IE11 pre KB2929437. See #11440
  27515. Uint8ClampedArray: typeof Uint8ClampedArray !== 'undefined' ? Uint8ClampedArray : Uint8Array,
  27516. Int16Array: Int16Array,
  27517. Uint16Array: Uint16Array,
  27518. Int32Array: Int32Array,
  27519. Uint32Array: Uint32Array,
  27520. Float32Array: Float32Array,
  27521. Float64Array: Float64Array
  27522. };
  27523. /**
  27524. * @author mrdoob / http://mrdoob.com/
  27525. */
  27526. function ObjectLoader( manager ) {
  27527. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  27528. this.resourcePath = '';
  27529. }
  27530. Object.assign( ObjectLoader.prototype, {
  27531. crossOrigin: 'anonymous',
  27532. load: function ( url, onLoad, onProgress, onError ) {
  27533. var scope = this;
  27534. var path = ( this.path === undefined ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  27535. this.resourcePath = this.resourcePath || path;
  27536. var loader = new FileLoader( scope.manager );
  27537. loader.setPath( this.path );
  27538. loader.load( url, function ( text ) {
  27539. var json = null;
  27540. try {
  27541. json = JSON.parse( text );
  27542. } catch ( error ) {
  27543. if ( onError !== undefined ) onError( error );
  27544. console.error( 'THREE:ObjectLoader: Can\'t parse ' + url + '.', error.message );
  27545. return;
  27546. }
  27547. var metadata = json.metadata;
  27548. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  27549. console.error( 'THREE.ObjectLoader: Can\'t load ' + url );
  27550. return;
  27551. }
  27552. scope.parse( json, onLoad );
  27553. }, onProgress, onError );
  27554. },
  27555. setPath: function ( value ) {
  27556. this.path = value;
  27557. return this;
  27558. },
  27559. setResourcePath: function ( value ) {
  27560. this.resourcePath = value;
  27561. return this;
  27562. },
  27563. setCrossOrigin: function ( value ) {
  27564. this.crossOrigin = value;
  27565. return this;
  27566. },
  27567. parse: function ( json, onLoad ) {
  27568. var shapes = this.parseShape( json.shapes );
  27569. var geometries = this.parseGeometries( json.geometries, shapes );
  27570. var images = this.parseImages( json.images, function () {
  27571. if ( onLoad !== undefined ) onLoad( object );
  27572. } );
  27573. var textures = this.parseTextures( json.textures, images );
  27574. var materials = this.parseMaterials( json.materials, textures );
  27575. var object = this.parseObject( json.object, geometries, materials );
  27576. if ( json.animations ) {
  27577. object.animations = this.parseAnimations( json.animations );
  27578. }
  27579. if ( json.images === undefined || json.images.length === 0 ) {
  27580. if ( onLoad !== undefined ) onLoad( object );
  27581. }
  27582. return object;
  27583. },
  27584. parseShape: function ( json ) {
  27585. var shapes = {};
  27586. if ( json !== undefined ) {
  27587. for ( var i = 0, l = json.length; i < l; i ++ ) {
  27588. var shape = new Shape().fromJSON( json[ i ] );
  27589. shapes[ shape.uuid ] = shape;
  27590. }
  27591. }
  27592. return shapes;
  27593. },
  27594. parseGeometries: function ( json, shapes ) {
  27595. var geometries = {};
  27596. if ( json !== undefined ) {
  27597. var bufferGeometryLoader = new BufferGeometryLoader();
  27598. for ( var i = 0, l = json.length; i < l; i ++ ) {
  27599. var geometry;
  27600. var data = json[ i ];
  27601. switch ( data.type ) {
  27602. case 'PlaneGeometry':
  27603. case 'PlaneBufferGeometry':
  27604. geometry = new Geometries[ data.type ](
  27605. data.width,
  27606. data.height,
  27607. data.widthSegments,
  27608. data.heightSegments
  27609. );
  27610. break;
  27611. case 'BoxGeometry':
  27612. case 'BoxBufferGeometry':
  27613. case 'CubeGeometry': // backwards compatible
  27614. geometry = new Geometries[ data.type ](
  27615. data.width,
  27616. data.height,
  27617. data.depth,
  27618. data.widthSegments,
  27619. data.heightSegments,
  27620. data.depthSegments
  27621. );
  27622. break;
  27623. case 'CircleGeometry':
  27624. case 'CircleBufferGeometry':
  27625. geometry = new Geometries[ data.type ](
  27626. data.radius,
  27627. data.segments,
  27628. data.thetaStart,
  27629. data.thetaLength
  27630. );
  27631. break;
  27632. case 'CylinderGeometry':
  27633. case 'CylinderBufferGeometry':
  27634. geometry = new Geometries[ data.type ](
  27635. data.radiusTop,
  27636. data.radiusBottom,
  27637. data.height,
  27638. data.radialSegments,
  27639. data.heightSegments,
  27640. data.openEnded,
  27641. data.thetaStart,
  27642. data.thetaLength
  27643. );
  27644. break;
  27645. case 'ConeGeometry':
  27646. case 'ConeBufferGeometry':
  27647. geometry = new Geometries[ data.type ](
  27648. data.radius,
  27649. data.height,
  27650. data.radialSegments,
  27651. data.heightSegments,
  27652. data.openEnded,
  27653. data.thetaStart,
  27654. data.thetaLength
  27655. );
  27656. break;
  27657. case 'SphereGeometry':
  27658. case 'SphereBufferGeometry':
  27659. geometry = new Geometries[ data.type ](
  27660. data.radius,
  27661. data.widthSegments,
  27662. data.heightSegments,
  27663. data.phiStart,
  27664. data.phiLength,
  27665. data.thetaStart,
  27666. data.thetaLength
  27667. );
  27668. break;
  27669. case 'DodecahedronGeometry':
  27670. case 'DodecahedronBufferGeometry':
  27671. case 'IcosahedronGeometry':
  27672. case 'IcosahedronBufferGeometry':
  27673. case 'OctahedronGeometry':
  27674. case 'OctahedronBufferGeometry':
  27675. case 'TetrahedronGeometry':
  27676. case 'TetrahedronBufferGeometry':
  27677. geometry = new Geometries[ data.type ](
  27678. data.radius,
  27679. data.detail
  27680. );
  27681. break;
  27682. case 'RingGeometry':
  27683. case 'RingBufferGeometry':
  27684. geometry = new Geometries[ data.type ](
  27685. data.innerRadius,
  27686. data.outerRadius,
  27687. data.thetaSegments,
  27688. data.phiSegments,
  27689. data.thetaStart,
  27690. data.thetaLength
  27691. );
  27692. break;
  27693. case 'TorusGeometry':
  27694. case 'TorusBufferGeometry':
  27695. geometry = new Geometries[ data.type ](
  27696. data.radius,
  27697. data.tube,
  27698. data.radialSegments,
  27699. data.tubularSegments,
  27700. data.arc
  27701. );
  27702. break;
  27703. case 'TorusKnotGeometry':
  27704. case 'TorusKnotBufferGeometry':
  27705. geometry = new Geometries[ data.type ](
  27706. data.radius,
  27707. data.tube,
  27708. data.tubularSegments,
  27709. data.radialSegments,
  27710. data.p,
  27711. data.q
  27712. );
  27713. break;
  27714. case 'TubeGeometry':
  27715. case 'TubeBufferGeometry':
  27716. // This only works for built-in curves (e.g. CatmullRomCurve3).
  27717. // User defined curves or instances of CurvePath will not be deserialized.
  27718. geometry = new Geometries[ data.type ](
  27719. new Curves[ data.path.type ]().fromJSON( data.path ),
  27720. data.tubularSegments,
  27721. data.radius,
  27722. data.radialSegments,
  27723. data.closed
  27724. );
  27725. break;
  27726. case 'LatheGeometry':
  27727. case 'LatheBufferGeometry':
  27728. geometry = new Geometries[ data.type ](
  27729. data.points,
  27730. data.segments,
  27731. data.phiStart,
  27732. data.phiLength
  27733. );
  27734. break;
  27735. case 'PolyhedronGeometry':
  27736. case 'PolyhedronBufferGeometry':
  27737. geometry = new Geometries[ data.type ](
  27738. data.vertices,
  27739. data.indices,
  27740. data.radius,
  27741. data.details
  27742. );
  27743. break;
  27744. case 'ShapeGeometry':
  27745. case 'ShapeBufferGeometry':
  27746. var geometryShapes = [];
  27747. for ( var j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  27748. var shape = shapes[ data.shapes[ j ] ];
  27749. geometryShapes.push( shape );
  27750. }
  27751. geometry = new Geometries[ data.type ](
  27752. geometryShapes,
  27753. data.curveSegments
  27754. );
  27755. break;
  27756. case 'ExtrudeGeometry':
  27757. case 'ExtrudeBufferGeometry':
  27758. var geometryShapes = [];
  27759. for ( var j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  27760. var shape = shapes[ data.shapes[ j ] ];
  27761. geometryShapes.push( shape );
  27762. }
  27763. var extrudePath = data.options.extrudePath;
  27764. if ( extrudePath !== undefined ) {
  27765. data.options.extrudePath = new Curves[ extrudePath.type ]().fromJSON( extrudePath );
  27766. }
  27767. geometry = new Geometries[ data.type ](
  27768. geometryShapes,
  27769. data.options
  27770. );
  27771. break;
  27772. case 'BufferGeometry':
  27773. geometry = bufferGeometryLoader.parse( data );
  27774. break;
  27775. case 'Geometry':
  27776. if ( 'THREE' in window && 'LegacyJSONLoader' in THREE ) {
  27777. var geometryLoader = new THREE.LegacyJSONLoader();
  27778. geometry = geometryLoader.parse( data, this.resourcePath ).geometry;
  27779. } else {
  27780. console.error( 'THREE.ObjectLoader: You have to import LegacyJSONLoader in order load geometry data of type "Geometry".' );
  27781. }
  27782. break;
  27783. default:
  27784. console.warn( 'THREE.ObjectLoader: Unsupported geometry type "' + data.type + '"' );
  27785. continue;
  27786. }
  27787. geometry.uuid = data.uuid;
  27788. if ( data.name !== undefined ) geometry.name = data.name;
  27789. if ( geometry.isBufferGeometry === true && data.userData !== undefined ) geometry.userData = data.userData;
  27790. geometries[ data.uuid ] = geometry;
  27791. }
  27792. }
  27793. return geometries;
  27794. },
  27795. parseMaterials: function ( json, textures ) {
  27796. var cache = {}; // MultiMaterial
  27797. var materials = {};
  27798. if ( json !== undefined ) {
  27799. var loader = new MaterialLoader();
  27800. loader.setTextures( textures );
  27801. for ( var i = 0, l = json.length; i < l; i ++ ) {
  27802. var data = json[ i ];
  27803. if ( data.type === 'MultiMaterial' ) {
  27804. // Deprecated
  27805. var array = [];
  27806. for ( var j = 0; j < data.materials.length; j ++ ) {
  27807. var material = data.materials[ j ];
  27808. if ( cache[ material.uuid ] === undefined ) {
  27809. cache[ material.uuid ] = loader.parse( material );
  27810. }
  27811. array.push( cache[ material.uuid ] );
  27812. }
  27813. materials[ data.uuid ] = array;
  27814. } else {
  27815. if ( cache[ data.uuid ] === undefined ) {
  27816. cache[ data.uuid ] = loader.parse( data );
  27817. }
  27818. materials[ data.uuid ] = cache[ data.uuid ];
  27819. }
  27820. }
  27821. }
  27822. return materials;
  27823. },
  27824. parseAnimations: function ( json ) {
  27825. var animations = [];
  27826. for ( var i = 0; i < json.length; i ++ ) {
  27827. var data = json[ i ];
  27828. var clip = AnimationClip.parse( data );
  27829. if ( data.uuid !== undefined ) clip.uuid = data.uuid;
  27830. animations.push( clip );
  27831. }
  27832. return animations;
  27833. },
  27834. parseImages: function ( json, onLoad ) {
  27835. var scope = this;
  27836. var images = {};
  27837. function loadImage( url ) {
  27838. scope.manager.itemStart( url );
  27839. return loader.load( url, function () {
  27840. scope.manager.itemEnd( url );
  27841. }, undefined, function () {
  27842. scope.manager.itemError( url );
  27843. scope.manager.itemEnd( url );
  27844. } );
  27845. }
  27846. if ( json !== undefined && json.length > 0 ) {
  27847. var manager = new LoadingManager( onLoad );
  27848. var loader = new ImageLoader( manager );
  27849. loader.setCrossOrigin( this.crossOrigin );
  27850. for ( var i = 0, il = json.length; i < il; i ++ ) {
  27851. var image = json[ i ];
  27852. var url = image.url;
  27853. if ( Array.isArray( url ) ) {
  27854. // load array of images e.g CubeTexture
  27855. images[ image.uuid ] = [];
  27856. for ( var j = 0, jl = url.length; j < jl; j ++ ) {
  27857. var currentUrl = url[ j ];
  27858. var path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( currentUrl ) ? currentUrl : scope.resourcePath + currentUrl;
  27859. images[ image.uuid ].push( loadImage( path ) );
  27860. }
  27861. } else {
  27862. // load single image
  27863. var path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( image.url ) ? image.url : scope.resourcePath + image.url;
  27864. images[ image.uuid ] = loadImage( path );
  27865. }
  27866. }
  27867. }
  27868. return images;
  27869. },
  27870. parseTextures: function ( json, images ) {
  27871. function parseConstant( value, type ) {
  27872. if ( typeof value === 'number' ) return value;
  27873. console.warn( 'THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value );
  27874. return type[ value ];
  27875. }
  27876. var textures = {};
  27877. if ( json !== undefined ) {
  27878. for ( var i = 0, l = json.length; i < l; i ++ ) {
  27879. var data = json[ i ];
  27880. if ( data.image === undefined ) {
  27881. console.warn( 'THREE.ObjectLoader: No "image" specified for', data.uuid );
  27882. }
  27883. if ( images[ data.image ] === undefined ) {
  27884. console.warn( 'THREE.ObjectLoader: Undefined image', data.image );
  27885. }
  27886. var texture;
  27887. if ( Array.isArray( images[ data.image ] ) ) {
  27888. texture = new CubeTexture( images[ data.image ] );
  27889. } else {
  27890. texture = new Texture( images[ data.image ] );
  27891. }
  27892. texture.needsUpdate = true;
  27893. texture.uuid = data.uuid;
  27894. if ( data.name !== undefined ) texture.name = data.name;
  27895. if ( data.mapping !== undefined ) texture.mapping = parseConstant( data.mapping, TEXTURE_MAPPING );
  27896. if ( data.offset !== undefined ) texture.offset.fromArray( data.offset );
  27897. if ( data.repeat !== undefined ) texture.repeat.fromArray( data.repeat );
  27898. if ( data.center !== undefined ) texture.center.fromArray( data.center );
  27899. if ( data.rotation !== undefined ) texture.rotation = data.rotation;
  27900. if ( data.wrap !== undefined ) {
  27901. texture.wrapS = parseConstant( data.wrap[ 0 ], TEXTURE_WRAPPING );
  27902. texture.wrapT = parseConstant( data.wrap[ 1 ], TEXTURE_WRAPPING );
  27903. }
  27904. if ( data.format !== undefined ) texture.format = data.format;
  27905. if ( data.type !== undefined ) texture.type = data.type;
  27906. if ( data.encoding !== undefined ) texture.encoding = data.encoding;
  27907. if ( data.minFilter !== undefined ) texture.minFilter = parseConstant( data.minFilter, TEXTURE_FILTER );
  27908. if ( data.magFilter !== undefined ) texture.magFilter = parseConstant( data.magFilter, TEXTURE_FILTER );
  27909. if ( data.anisotropy !== undefined ) texture.anisotropy = data.anisotropy;
  27910. if ( data.flipY !== undefined ) texture.flipY = data.flipY;
  27911. if ( data.premultiplyAlpha !== undefined ) texture.premultiplyAlpha = data.premultiplyAlpha;
  27912. if ( data.unpackAlignment !== undefined ) texture.unpackAlignment = data.unpackAlignment;
  27913. textures[ data.uuid ] = texture;
  27914. }
  27915. }
  27916. return textures;
  27917. },
  27918. parseObject: function ( data, geometries, materials ) {
  27919. var object;
  27920. function getGeometry( name ) {
  27921. if ( geometries[ name ] === undefined ) {
  27922. console.warn( 'THREE.ObjectLoader: Undefined geometry', name );
  27923. }
  27924. return geometries[ name ];
  27925. }
  27926. function getMaterial( name ) {
  27927. if ( name === undefined ) return undefined;
  27928. if ( Array.isArray( name ) ) {
  27929. var array = [];
  27930. for ( var i = 0, l = name.length; i < l; i ++ ) {
  27931. var uuid = name[ i ];
  27932. if ( materials[ uuid ] === undefined ) {
  27933. console.warn( 'THREE.ObjectLoader: Undefined material', uuid );
  27934. }
  27935. array.push( materials[ uuid ] );
  27936. }
  27937. return array;
  27938. }
  27939. if ( materials[ name ] === undefined ) {
  27940. console.warn( 'THREE.ObjectLoader: Undefined material', name );
  27941. }
  27942. return materials[ name ];
  27943. }
  27944. switch ( data.type ) {
  27945. case 'Scene':
  27946. object = new Scene();
  27947. if ( data.background !== undefined ) {
  27948. if ( Number.isInteger( data.background ) ) {
  27949. object.background = new Color( data.background );
  27950. }
  27951. }
  27952. if ( data.fog !== undefined ) {
  27953. if ( data.fog.type === 'Fog' ) {
  27954. object.fog = new Fog( data.fog.color, data.fog.near, data.fog.far );
  27955. } else if ( data.fog.type === 'FogExp2' ) {
  27956. object.fog = new FogExp2( data.fog.color, data.fog.density );
  27957. }
  27958. }
  27959. break;
  27960. case 'PerspectiveCamera':
  27961. object = new PerspectiveCamera( data.fov, data.aspect, data.near, data.far );
  27962. if ( data.focus !== undefined ) object.focus = data.focus;
  27963. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  27964. if ( data.filmGauge !== undefined ) object.filmGauge = data.filmGauge;
  27965. if ( data.filmOffset !== undefined ) object.filmOffset = data.filmOffset;
  27966. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  27967. break;
  27968. case 'OrthographicCamera':
  27969. object = new OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far );
  27970. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  27971. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  27972. break;
  27973. case 'AmbientLight':
  27974. object = new AmbientLight( data.color, data.intensity );
  27975. break;
  27976. case 'DirectionalLight':
  27977. object = new DirectionalLight( data.color, data.intensity );
  27978. break;
  27979. case 'PointLight':
  27980. object = new PointLight( data.color, data.intensity, data.distance, data.decay );
  27981. break;
  27982. case 'RectAreaLight':
  27983. object = new RectAreaLight( data.color, data.intensity, data.width, data.height );
  27984. break;
  27985. case 'SpotLight':
  27986. object = new SpotLight( data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay );
  27987. break;
  27988. case 'HemisphereLight':
  27989. object = new HemisphereLight( data.color, data.groundColor, data.intensity );
  27990. break;
  27991. case 'SkinnedMesh':
  27992. console.warn( 'THREE.ObjectLoader.parseObject() does not support SkinnedMesh yet.' );
  27993. case 'Mesh':
  27994. var geometry = getGeometry( data.geometry );
  27995. var material = getMaterial( data.material );
  27996. if ( geometry.bones && geometry.bones.length > 0 ) {
  27997. object = new SkinnedMesh( geometry, material );
  27998. } else {
  27999. object = new Mesh( geometry, material );
  28000. }
  28001. if ( data.drawMode !== undefined ) object.setDrawMode( data.drawMode );
  28002. break;
  28003. case 'LOD':
  28004. object = new LOD();
  28005. break;
  28006. case 'Line':
  28007. object = new Line( getGeometry( data.geometry ), getMaterial( data.material ), data.mode );
  28008. break;
  28009. case 'LineLoop':
  28010. object = new LineLoop( getGeometry( data.geometry ), getMaterial( data.material ) );
  28011. break;
  28012. case 'LineSegments':
  28013. object = new LineSegments( getGeometry( data.geometry ), getMaterial( data.material ) );
  28014. break;
  28015. case 'PointCloud':
  28016. case 'Points':
  28017. object = new Points( getGeometry( data.geometry ), getMaterial( data.material ) );
  28018. break;
  28019. case 'Sprite':
  28020. object = new Sprite( getMaterial( data.material ) );
  28021. break;
  28022. case 'Group':
  28023. object = new Group();
  28024. break;
  28025. default:
  28026. object = new Object3D();
  28027. }
  28028. object.uuid = data.uuid;
  28029. if ( data.name !== undefined ) object.name = data.name;
  28030. if ( data.matrix !== undefined ) {
  28031. object.matrix.fromArray( data.matrix );
  28032. if ( data.matrixAutoUpdate !== undefined ) object.matrixAutoUpdate = data.matrixAutoUpdate;
  28033. if ( object.matrixAutoUpdate ) object.matrix.decompose( object.position, object.quaternion, object.scale );
  28034. } else {
  28035. if ( data.position !== undefined ) object.position.fromArray( data.position );
  28036. if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation );
  28037. if ( data.quaternion !== undefined ) object.quaternion.fromArray( data.quaternion );
  28038. if ( data.scale !== undefined ) object.scale.fromArray( data.scale );
  28039. }
  28040. if ( data.castShadow !== undefined ) object.castShadow = data.castShadow;
  28041. if ( data.receiveShadow !== undefined ) object.receiveShadow = data.receiveShadow;
  28042. if ( data.shadow ) {
  28043. if ( data.shadow.bias !== undefined ) object.shadow.bias = data.shadow.bias;
  28044. if ( data.shadow.radius !== undefined ) object.shadow.radius = data.shadow.radius;
  28045. if ( data.shadow.mapSize !== undefined ) object.shadow.mapSize.fromArray( data.shadow.mapSize );
  28046. if ( data.shadow.camera !== undefined ) object.shadow.camera = this.parseObject( data.shadow.camera );
  28047. }
  28048. if ( data.visible !== undefined ) object.visible = data.visible;
  28049. if ( data.frustumCulled !== undefined ) object.frustumCulled = data.frustumCulled;
  28050. if ( data.renderOrder !== undefined ) object.renderOrder = data.renderOrder;
  28051. if ( data.userData !== undefined ) object.userData = data.userData;
  28052. if ( data.layers !== undefined ) object.layers.mask = data.layers;
  28053. if ( data.children !== undefined ) {
  28054. var children = data.children;
  28055. for ( var i = 0; i < children.length; i ++ ) {
  28056. object.add( this.parseObject( children[ i ], geometries, materials ) );
  28057. }
  28058. }
  28059. if ( data.type === 'LOD' ) {
  28060. var levels = data.levels;
  28061. for ( var l = 0; l < levels.length; l ++ ) {
  28062. var level = levels[ l ];
  28063. var child = object.getObjectByProperty( 'uuid', level.object );
  28064. if ( child !== undefined ) {
  28065. object.addLevel( child, level.distance );
  28066. }
  28067. }
  28068. }
  28069. return object;
  28070. }
  28071. } );
  28072. var TEXTURE_MAPPING = {
  28073. UVMapping: UVMapping,
  28074. CubeReflectionMapping: CubeReflectionMapping,
  28075. CubeRefractionMapping: CubeRefractionMapping,
  28076. EquirectangularReflectionMapping: EquirectangularReflectionMapping,
  28077. EquirectangularRefractionMapping: EquirectangularRefractionMapping,
  28078. SphericalReflectionMapping: SphericalReflectionMapping,
  28079. CubeUVReflectionMapping: CubeUVReflectionMapping,
  28080. CubeUVRefractionMapping: CubeUVRefractionMapping
  28081. };
  28082. var TEXTURE_WRAPPING = {
  28083. RepeatWrapping: RepeatWrapping,
  28084. ClampToEdgeWrapping: ClampToEdgeWrapping,
  28085. MirroredRepeatWrapping: MirroredRepeatWrapping
  28086. };
  28087. var TEXTURE_FILTER = {
  28088. NearestFilter: NearestFilter,
  28089. NearestMipMapNearestFilter: NearestMipMapNearestFilter,
  28090. NearestMipMapLinearFilter: NearestMipMapLinearFilter,
  28091. LinearFilter: LinearFilter,
  28092. LinearMipMapNearestFilter: LinearMipMapNearestFilter,
  28093. LinearMipMapLinearFilter: LinearMipMapLinearFilter
  28094. };
  28095. /**
  28096. * @author thespite / http://clicktorelease.com/
  28097. */
  28098. function ImageBitmapLoader( manager ) {
  28099. if ( typeof createImageBitmap === 'undefined' ) {
  28100. console.warn( 'THREE.ImageBitmapLoader: createImageBitmap() not supported.' );
  28101. }
  28102. if ( typeof fetch === 'undefined' ) {
  28103. console.warn( 'THREE.ImageBitmapLoader: fetch() not supported.' );
  28104. }
  28105. this.manager = manager !== undefined ? manager : DefaultLoadingManager;
  28106. this.options = undefined;
  28107. }
  28108. ImageBitmapLoader.prototype = {
  28109. constructor: ImageBitmapLoader,
  28110. setOptions: function setOptions( options ) {
  28111. this.options = options;
  28112. return this;
  28113. },
  28114. load: function ( url, onLoad, onProgress, onError ) {
  28115. if ( url === undefined ) url = '';
  28116. if ( this.path !== undefined ) url = this.path + url;
  28117. url = this.manager.resolveURL( url );
  28118. var scope = this;
  28119. var cached = Cache.get( url );
  28120. if ( cached !== undefined ) {
  28121. scope.manager.itemStart( url );
  28122. setTimeout( function () {
  28123. if ( onLoad ) onLoad( cached );
  28124. scope.manager.itemEnd( url );
  28125. }, 0 );
  28126. return cached;
  28127. }
  28128. fetch( url ).then( function ( res ) {
  28129. return res.blob();
  28130. } ).then( function ( blob ) {
  28131. if ( scope.options === undefined ) {
  28132. // Workaround for FireFox. It causes an error if you pass options.
  28133. return createImageBitmap( blob );
  28134. } else {
  28135. return createImageBitmap( blob, scope.options );
  28136. }
  28137. } ).then( function ( imageBitmap ) {
  28138. Cache.add( url, imageBitmap );
  28139. if ( onLoad ) onLoad( imageBitmap );
  28140. scope.manager.itemEnd( url );
  28141. } ).catch( function ( e ) {
  28142. if ( onError ) onError( e );
  28143. scope.manager.itemError( url );
  28144. scope.manager.itemEnd( url );
  28145. } );
  28146. scope.manager.itemStart( url );
  28147. },
  28148. setCrossOrigin: function ( /* value */ ) {
  28149. return this;
  28150. },
  28151. setPath: function ( value ) {
  28152. this.path = value;
  28153. return this;
  28154. }
  28155. };
  28156. /**
  28157. * @author zz85 / http://www.lab4games.net/zz85/blog
  28158. * minimal class for proxing functions to Path. Replaces old "extractSubpaths()"
  28159. **/
  28160. function ShapePath() {
  28161. this.type = 'ShapePath';
  28162. this.color = new Color();
  28163. this.subPaths = [];
  28164. this.currentPath = null;
  28165. }
  28166. Object.assign( ShapePath.prototype, {
  28167. moveTo: function ( x, y ) {
  28168. this.currentPath = new Path();
  28169. this.subPaths.push( this.currentPath );
  28170. this.currentPath.moveTo( x, y );
  28171. },
  28172. lineTo: function ( x, y ) {
  28173. this.currentPath.lineTo( x, y );
  28174. },
  28175. quadraticCurveTo: function ( aCPx, aCPy, aX, aY ) {
  28176. this.currentPath.quadraticCurveTo( aCPx, aCPy, aX, aY );
  28177. },
  28178. bezierCurveTo: function ( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  28179. this.currentPath.bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY );
  28180. },
  28181. splineThru: function ( pts ) {
  28182. this.currentPath.splineThru( pts );
  28183. },
  28184. toShapes: function ( isCCW, noHoles ) {
  28185. function toShapesNoHoles( inSubpaths ) {
  28186. var shapes = [];
  28187. for ( var i = 0, l = inSubpaths.length; i < l; i ++ ) {
  28188. var tmpPath = inSubpaths[ i ];
  28189. var tmpShape = new Shape();
  28190. tmpShape.curves = tmpPath.curves;
  28191. shapes.push( tmpShape );
  28192. }
  28193. return shapes;
  28194. }
  28195. function isPointInsidePolygon( inPt, inPolygon ) {
  28196. var polyLen = inPolygon.length;
  28197. // inPt on polygon contour => immediate success or
  28198. // toggling of inside/outside at every single! intersection point of an edge
  28199. // with the horizontal line through inPt, left of inPt
  28200. // not counting lowerY endpoints of edges and whole edges on that line
  28201. var inside = false;
  28202. for ( var p = polyLen - 1, q = 0; q < polyLen; p = q ++ ) {
  28203. var edgeLowPt = inPolygon[ p ];
  28204. var edgeHighPt = inPolygon[ q ];
  28205. var edgeDx = edgeHighPt.x - edgeLowPt.x;
  28206. var edgeDy = edgeHighPt.y - edgeLowPt.y;
  28207. if ( Math.abs( edgeDy ) > Number.EPSILON ) {
  28208. // not parallel
  28209. if ( edgeDy < 0 ) {
  28210. edgeLowPt = inPolygon[ q ]; edgeDx = - edgeDx;
  28211. edgeHighPt = inPolygon[ p ]; edgeDy = - edgeDy;
  28212. }
  28213. if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) continue;
  28214. if ( inPt.y === edgeLowPt.y ) {
  28215. if ( inPt.x === edgeLowPt.x ) return true; // inPt is on contour ?
  28216. // continue; // no intersection or edgeLowPt => doesn't count !!!
  28217. } else {
  28218. var perpEdge = edgeDy * ( inPt.x - edgeLowPt.x ) - edgeDx * ( inPt.y - edgeLowPt.y );
  28219. if ( perpEdge === 0 ) return true; // inPt is on contour ?
  28220. if ( perpEdge < 0 ) continue;
  28221. inside = ! inside; // true intersection left of inPt
  28222. }
  28223. } else {
  28224. // parallel or collinear
  28225. if ( inPt.y !== edgeLowPt.y ) continue; // parallel
  28226. // edge lies on the same horizontal line as inPt
  28227. if ( ( ( edgeHighPt.x <= inPt.x ) && ( inPt.x <= edgeLowPt.x ) ) ||
  28228. ( ( edgeLowPt.x <= inPt.x ) && ( inPt.x <= edgeHighPt.x ) ) ) return true; // inPt: Point on contour !
  28229. // continue;
  28230. }
  28231. }
  28232. return inside;
  28233. }
  28234. var isClockWise = ShapeUtils.isClockWise;
  28235. var subPaths = this.subPaths;
  28236. if ( subPaths.length === 0 ) return [];
  28237. if ( noHoles === true ) return toShapesNoHoles( subPaths );
  28238. var solid, tmpPath, tmpShape, shapes = [];
  28239. if ( subPaths.length === 1 ) {
  28240. tmpPath = subPaths[ 0 ];
  28241. tmpShape = new Shape();
  28242. tmpShape.curves = tmpPath.curves;
  28243. shapes.push( tmpShape );
  28244. return shapes;
  28245. }
  28246. var holesFirst = ! isClockWise( subPaths[ 0 ].getPoints() );
  28247. holesFirst = isCCW ? ! holesFirst : holesFirst;
  28248. // console.log("Holes first", holesFirst);
  28249. var betterShapeHoles = [];
  28250. var newShapes = [];
  28251. var newShapeHoles = [];
  28252. var mainIdx = 0;
  28253. var tmpPoints;
  28254. newShapes[ mainIdx ] = undefined;
  28255. newShapeHoles[ mainIdx ] = [];
  28256. for ( var i = 0, l = subPaths.length; i < l; i ++ ) {
  28257. tmpPath = subPaths[ i ];
  28258. tmpPoints = tmpPath.getPoints();
  28259. solid = isClockWise( tmpPoints );
  28260. solid = isCCW ? ! solid : solid;
  28261. if ( solid ) {
  28262. if ( ( ! holesFirst ) && ( newShapes[ mainIdx ] ) ) mainIdx ++;
  28263. newShapes[ mainIdx ] = { s: new Shape(), p: tmpPoints };
  28264. newShapes[ mainIdx ].s.curves = tmpPath.curves;
  28265. if ( holesFirst ) mainIdx ++;
  28266. newShapeHoles[ mainIdx ] = [];
  28267. //console.log('cw', i);
  28268. } else {
  28269. newShapeHoles[ mainIdx ].push( { h: tmpPath, p: tmpPoints[ 0 ] } );
  28270. //console.log('ccw', i);
  28271. }
  28272. }
  28273. // only Holes? -> probably all Shapes with wrong orientation
  28274. if ( ! newShapes[ 0 ] ) return toShapesNoHoles( subPaths );
  28275. if ( newShapes.length > 1 ) {
  28276. var ambiguous = false;
  28277. var toChange = [];
  28278. for ( var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  28279. betterShapeHoles[ sIdx ] = [];
  28280. }
  28281. for ( var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  28282. var sho = newShapeHoles[ sIdx ];
  28283. for ( var hIdx = 0; hIdx < sho.length; hIdx ++ ) {
  28284. var ho = sho[ hIdx ];
  28285. var hole_unassigned = true;
  28286. for ( var s2Idx = 0; s2Idx < newShapes.length; s2Idx ++ ) {
  28287. if ( isPointInsidePolygon( ho.p, newShapes[ s2Idx ].p ) ) {
  28288. if ( sIdx !== s2Idx ) toChange.push( { froms: sIdx, tos: s2Idx, hole: hIdx } );
  28289. if ( hole_unassigned ) {
  28290. hole_unassigned = false;
  28291. betterShapeHoles[ s2Idx ].push( ho );
  28292. } else {
  28293. ambiguous = true;
  28294. }
  28295. }
  28296. }
  28297. if ( hole_unassigned ) {
  28298. betterShapeHoles[ sIdx ].push( ho );
  28299. }
  28300. }
  28301. }
  28302. // console.log("ambiguous: ", ambiguous);
  28303. if ( toChange.length > 0 ) {
  28304. // console.log("to change: ", toChange);
  28305. if ( ! ambiguous ) newShapeHoles = betterShapeHoles;
  28306. }
  28307. }
  28308. var tmpHoles;
  28309. for ( var i = 0, il = newShapes.length; i < il; i ++ ) {
  28310. tmpShape = newShapes[ i ].s;
  28311. shapes.push( tmpShape );
  28312. tmpHoles = newShapeHoles[ i ];
  28313. for ( var j = 0, jl = tmpHoles.length; j < jl; j ++ ) {
  28314. tmpShape.holes.push( tmpHoles[ j ].h );
  28315. }
  28316. }
  28317. //console.log("shape", shapes);
  28318. return shapes;
  28319. }
  28320. } );
  28321. /**
  28322. * @author zz85 / http://www.lab4games.net/zz85/blog
  28323. * @author mrdoob / http://mrdoob.com/
  28324. */
  28325. function Font( data ) {
  28326. this.type = 'Font';
  28327. this.data = data;
  28328. }
  28329. Object.assign( Font.prototype, {
  28330. isFont: true,
  28331. generateShapes: function ( text, size ) {
  28332. if ( size === undefined ) size = 100;
  28333. var shapes = [];
  28334. var paths = createPaths( text, size, this.data );
  28335. for ( var p = 0, pl = paths.length; p < pl; p ++ ) {
  28336. Array.prototype.push.apply( shapes, paths[ p ].toShapes() );
  28337. }
  28338. return shapes;
  28339. }
  28340. } );
  28341. function createPaths( text, size, data ) {
  28342. var chars = Array.from ? Array.from( text ) : String( text ).split( '' ); // see #13988
  28343. var scale = size / data.resolution;
  28344. var line_height = ( data.boundingBox.yMax - data.boundingBox.yMin + data.underlineThickness ) * scale;
  28345. var paths = [];
  28346. var offsetX = 0, offsetY = 0;
  28347. for ( var i = 0; i < chars.length; i ++ ) {
  28348. var char = chars[ i ];
  28349. if ( char === '\n' ) {
  28350. offsetX = 0;
  28351. offsetY -= line_height;
  28352. } else {
  28353. var ret = createPath( char, scale, offsetX, offsetY, data );
  28354. offsetX += ret.offsetX;
  28355. paths.push( ret.path );
  28356. }
  28357. }
  28358. return paths;
  28359. }
  28360. function createPath( char, scale, offsetX, offsetY, data ) {
  28361. var glyph = data.glyphs[ char ] || data.glyphs[ '?' ];
  28362. if ( ! glyph ) return;
  28363. var path = new ShapePath();
  28364. var x, y, cpx, cpy, cpx1, cpy1, cpx2, cpy2;
  28365. if ( glyph.o ) {
  28366. var outline = glyph._cachedOutline || ( glyph._cachedOutline = glyph.o.split( ' ' ) );
  28367. for ( var i = 0, l = outline.length; i < l; ) {
  28368. var action = outline[ i ++ ];
  28369. switch ( action ) {
  28370. case 'm': // moveTo
  28371. x = outline[ i ++ ] * scale + offsetX;
  28372. y = outline[ i ++ ] * scale + offsetY;
  28373. path.moveTo( x, y );
  28374. break;
  28375. case 'l': // lineTo
  28376. x = outline[ i ++ ] * scale + offsetX;
  28377. y = outline[ i ++ ] * scale + offsetY;
  28378. path.lineTo( x, y );
  28379. break;
  28380. case 'q': // quadraticCurveTo
  28381. cpx = outline[ i ++ ] * scale + offsetX;
  28382. cpy = outline[ i ++ ] * scale + offsetY;
  28383. cpx1 = outline[ i ++ ] * scale + offsetX;
  28384. cpy1 = outline[ i ++ ] * scale + offsetY;
  28385. path.quadraticCurveTo( cpx1, cpy1, cpx, cpy );
  28386. break;
  28387. case 'b': // bezierCurveTo
  28388. cpx = outline[ i ++ ] * scale + offsetX;
  28389. cpy = outline[ i ++ ] * scale + offsetY;
  28390. cpx1 = outline[ i ++ ] * scale + offsetX;
  28391. cpy1 = outline[ i ++ ] * scale + offsetY;
  28392. cpx2 = outline[ i ++ ] * scale + offsetX;
  28393. cpy2 = outline[ i ++ ] * scale + offsetY;
  28394. path.bezierCurveTo( cpx1, cpy1, cpx2, cpy2, cpx, cpy );
  28395. break;
  28396. }
  28397. }
  28398. }
  28399. return { offsetX: glyph.ha * scale, path: path };
  28400. }
  28401. /**
  28402. * @author mrdoob / http://mrdoob.com/
  28403. */
  28404. function FontLoader( manager ) {
  28405. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  28406. }
  28407. Object.assign( FontLoader.prototype, {
  28408. load: function ( url, onLoad, onProgress, onError ) {
  28409. var scope = this;
  28410. var loader = new FileLoader( this.manager );
  28411. loader.setPath( this.path );
  28412. loader.load( url, function ( text ) {
  28413. var json;
  28414. try {
  28415. json = JSON.parse( text );
  28416. } catch ( e ) {
  28417. console.warn( 'THREE.FontLoader: typeface.js support is being deprecated. Use typeface.json instead.' );
  28418. json = JSON.parse( text.substring( 65, text.length - 2 ) );
  28419. }
  28420. var font = scope.parse( json );
  28421. if ( onLoad ) onLoad( font );
  28422. }, onProgress, onError );
  28423. },
  28424. parse: function ( json ) {
  28425. return new Font( json );
  28426. },
  28427. setPath: function ( value ) {
  28428. this.path = value;
  28429. return this;
  28430. }
  28431. } );
  28432. /**
  28433. * @author alteredq / http://alteredqualia.com/
  28434. */
  28435. function Loader() {}
  28436. Loader.Handlers = {
  28437. handlers: [],
  28438. add: function ( regex, loader ) {
  28439. this.handlers.push( regex, loader );
  28440. },
  28441. get: function ( file ) {
  28442. var handlers = this.handlers;
  28443. for ( var i = 0, l = handlers.length; i < l; i += 2 ) {
  28444. var regex = handlers[ i ];
  28445. var loader = handlers[ i + 1 ];
  28446. if ( regex.test( file ) ) {
  28447. return loader;
  28448. }
  28449. }
  28450. return null;
  28451. }
  28452. };
  28453. Object.assign( Loader.prototype, {
  28454. crossOrigin: 'anonymous',
  28455. onLoadStart: function () {},
  28456. onLoadProgress: function () {},
  28457. onLoadComplete: function () {},
  28458. initMaterials: function ( materials, texturePath, crossOrigin ) {
  28459. var array = [];
  28460. for ( var i = 0; i < materials.length; ++ i ) {
  28461. array[ i ] = this.createMaterial( materials[ i ], texturePath, crossOrigin );
  28462. }
  28463. return array;
  28464. },
  28465. createMaterial: ( function () {
  28466. var BlendingMode = {
  28467. NoBlending: NoBlending,
  28468. NormalBlending: NormalBlending,
  28469. AdditiveBlending: AdditiveBlending,
  28470. SubtractiveBlending: SubtractiveBlending,
  28471. MultiplyBlending: MultiplyBlending,
  28472. CustomBlending: CustomBlending
  28473. };
  28474. var color = new Color();
  28475. var textureLoader = new TextureLoader();
  28476. var materialLoader = new MaterialLoader();
  28477. return function createMaterial( m, texturePath, crossOrigin ) {
  28478. // convert from old material format
  28479. var textures = {};
  28480. function loadTexture( path, repeat, offset, wrap, anisotropy ) {
  28481. var fullPath = texturePath + path;
  28482. var loader = Loader.Handlers.get( fullPath );
  28483. var texture;
  28484. if ( loader !== null ) {
  28485. texture = loader.load( fullPath );
  28486. } else {
  28487. textureLoader.setCrossOrigin( crossOrigin );
  28488. texture = textureLoader.load( fullPath );
  28489. }
  28490. if ( repeat !== undefined ) {
  28491. texture.repeat.fromArray( repeat );
  28492. if ( repeat[ 0 ] !== 1 ) texture.wrapS = RepeatWrapping;
  28493. if ( repeat[ 1 ] !== 1 ) texture.wrapT = RepeatWrapping;
  28494. }
  28495. if ( offset !== undefined ) {
  28496. texture.offset.fromArray( offset );
  28497. }
  28498. if ( wrap !== undefined ) {
  28499. if ( wrap[ 0 ] === 'repeat' ) texture.wrapS = RepeatWrapping;
  28500. if ( wrap[ 0 ] === 'mirror' ) texture.wrapS = MirroredRepeatWrapping;
  28501. if ( wrap[ 1 ] === 'repeat' ) texture.wrapT = RepeatWrapping;
  28502. if ( wrap[ 1 ] === 'mirror' ) texture.wrapT = MirroredRepeatWrapping;
  28503. }
  28504. if ( anisotropy !== undefined ) {
  28505. texture.anisotropy = anisotropy;
  28506. }
  28507. var uuid = _Math.generateUUID();
  28508. textures[ uuid ] = texture;
  28509. return uuid;
  28510. }
  28511. //
  28512. var json = {
  28513. uuid: _Math.generateUUID(),
  28514. type: 'MeshLambertMaterial'
  28515. };
  28516. for ( var name in m ) {
  28517. var value = m[ name ];
  28518. switch ( name ) {
  28519. case 'DbgColor':
  28520. case 'DbgIndex':
  28521. case 'opticalDensity':
  28522. case 'illumination':
  28523. break;
  28524. case 'DbgName':
  28525. json.name = value;
  28526. break;
  28527. case 'blending':
  28528. json.blending = BlendingMode[ value ];
  28529. break;
  28530. case 'colorAmbient':
  28531. case 'mapAmbient':
  28532. console.warn( 'THREE.Loader.createMaterial:', name, 'is no longer supported.' );
  28533. break;
  28534. case 'colorDiffuse':
  28535. json.color = color.fromArray( value ).getHex();
  28536. break;
  28537. case 'colorSpecular':
  28538. json.specular = color.fromArray( value ).getHex();
  28539. break;
  28540. case 'colorEmissive':
  28541. json.emissive = color.fromArray( value ).getHex();
  28542. break;
  28543. case 'specularCoef':
  28544. json.shininess = value;
  28545. break;
  28546. case 'shading':
  28547. if ( value.toLowerCase() === 'basic' ) json.type = 'MeshBasicMaterial';
  28548. if ( value.toLowerCase() === 'phong' ) json.type = 'MeshPhongMaterial';
  28549. if ( value.toLowerCase() === 'standard' ) json.type = 'MeshStandardMaterial';
  28550. break;
  28551. case 'mapDiffuse':
  28552. json.map = loadTexture( value, m.mapDiffuseRepeat, m.mapDiffuseOffset, m.mapDiffuseWrap, m.mapDiffuseAnisotropy );
  28553. break;
  28554. case 'mapDiffuseRepeat':
  28555. case 'mapDiffuseOffset':
  28556. case 'mapDiffuseWrap':
  28557. case 'mapDiffuseAnisotropy':
  28558. break;
  28559. case 'mapEmissive':
  28560. json.emissiveMap = loadTexture( value, m.mapEmissiveRepeat, m.mapEmissiveOffset, m.mapEmissiveWrap, m.mapEmissiveAnisotropy );
  28561. break;
  28562. case 'mapEmissiveRepeat':
  28563. case 'mapEmissiveOffset':
  28564. case 'mapEmissiveWrap':
  28565. case 'mapEmissiveAnisotropy':
  28566. break;
  28567. case 'mapLight':
  28568. json.lightMap = loadTexture( value, m.mapLightRepeat, m.mapLightOffset, m.mapLightWrap, m.mapLightAnisotropy );
  28569. break;
  28570. case 'mapLightRepeat':
  28571. case 'mapLightOffset':
  28572. case 'mapLightWrap':
  28573. case 'mapLightAnisotropy':
  28574. break;
  28575. case 'mapAO':
  28576. json.aoMap = loadTexture( value, m.mapAORepeat, m.mapAOOffset, m.mapAOWrap, m.mapAOAnisotropy );
  28577. break;
  28578. case 'mapAORepeat':
  28579. case 'mapAOOffset':
  28580. case 'mapAOWrap':
  28581. case 'mapAOAnisotropy':
  28582. break;
  28583. case 'mapBump':
  28584. json.bumpMap = loadTexture( value, m.mapBumpRepeat, m.mapBumpOffset, m.mapBumpWrap, m.mapBumpAnisotropy );
  28585. break;
  28586. case 'mapBumpScale':
  28587. json.bumpScale = value;
  28588. break;
  28589. case 'mapBumpRepeat':
  28590. case 'mapBumpOffset':
  28591. case 'mapBumpWrap':
  28592. case 'mapBumpAnisotropy':
  28593. break;
  28594. case 'mapNormal':
  28595. json.normalMap = loadTexture( value, m.mapNormalRepeat, m.mapNormalOffset, m.mapNormalWrap, m.mapNormalAnisotropy );
  28596. break;
  28597. case 'mapNormalFactor':
  28598. json.normalScale = value;
  28599. break;
  28600. case 'mapNormalRepeat':
  28601. case 'mapNormalOffset':
  28602. case 'mapNormalWrap':
  28603. case 'mapNormalAnisotropy':
  28604. break;
  28605. case 'mapSpecular':
  28606. json.specularMap = loadTexture( value, m.mapSpecularRepeat, m.mapSpecularOffset, m.mapSpecularWrap, m.mapSpecularAnisotropy );
  28607. break;
  28608. case 'mapSpecularRepeat':
  28609. case 'mapSpecularOffset':
  28610. case 'mapSpecularWrap':
  28611. case 'mapSpecularAnisotropy':
  28612. break;
  28613. case 'mapMetalness':
  28614. json.metalnessMap = loadTexture( value, m.mapMetalnessRepeat, m.mapMetalnessOffset, m.mapMetalnessWrap, m.mapMetalnessAnisotropy );
  28615. break;
  28616. case 'mapMetalnessRepeat':
  28617. case 'mapMetalnessOffset':
  28618. case 'mapMetalnessWrap':
  28619. case 'mapMetalnessAnisotropy':
  28620. break;
  28621. case 'mapRoughness':
  28622. json.roughnessMap = loadTexture( value, m.mapRoughnessRepeat, m.mapRoughnessOffset, m.mapRoughnessWrap, m.mapRoughnessAnisotropy );
  28623. break;
  28624. case 'mapRoughnessRepeat':
  28625. case 'mapRoughnessOffset':
  28626. case 'mapRoughnessWrap':
  28627. case 'mapRoughnessAnisotropy':
  28628. break;
  28629. case 'mapAlpha':
  28630. json.alphaMap = loadTexture( value, m.mapAlphaRepeat, m.mapAlphaOffset, m.mapAlphaWrap, m.mapAlphaAnisotropy );
  28631. break;
  28632. case 'mapAlphaRepeat':
  28633. case 'mapAlphaOffset':
  28634. case 'mapAlphaWrap':
  28635. case 'mapAlphaAnisotropy':
  28636. break;
  28637. case 'flipSided':
  28638. json.side = BackSide;
  28639. break;
  28640. case 'doubleSided':
  28641. json.side = DoubleSide;
  28642. break;
  28643. case 'transparency':
  28644. console.warn( 'THREE.Loader.createMaterial: transparency has been renamed to opacity' );
  28645. json.opacity = value;
  28646. break;
  28647. case 'depthTest':
  28648. case 'depthWrite':
  28649. case 'colorWrite':
  28650. case 'opacity':
  28651. case 'reflectivity':
  28652. case 'transparent':
  28653. case 'visible':
  28654. case 'wireframe':
  28655. json[ name ] = value;
  28656. break;
  28657. case 'vertexColors':
  28658. if ( value === true ) json.vertexColors = VertexColors;
  28659. if ( value === 'face' ) json.vertexColors = FaceColors;
  28660. break;
  28661. default:
  28662. console.error( 'THREE.Loader.createMaterial: Unsupported', name, value );
  28663. break;
  28664. }
  28665. }
  28666. if ( json.type === 'MeshBasicMaterial' ) delete json.emissive;
  28667. if ( json.type !== 'MeshPhongMaterial' ) delete json.specular;
  28668. if ( json.opacity < 1 ) json.transparent = true;
  28669. materialLoader.setTextures( textures );
  28670. return materialLoader.parse( json );
  28671. };
  28672. } )()
  28673. } );
  28674. /**
  28675. * @author mrdoob / http://mrdoob.com/
  28676. */
  28677. var context;
  28678. var AudioContext = {
  28679. getContext: function () {
  28680. if ( context === undefined ) {
  28681. context = new ( window.AudioContext || window.webkitAudioContext )();
  28682. }
  28683. return context;
  28684. },
  28685. setContext: function ( value ) {
  28686. context = value;
  28687. }
  28688. };
  28689. /**
  28690. * @author Reece Aaron Lecrivain / http://reecenotes.com/
  28691. */
  28692. function AudioLoader( manager ) {
  28693. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  28694. }
  28695. Object.assign( AudioLoader.prototype, {
  28696. load: function ( url, onLoad, onProgress, onError ) {
  28697. var loader = new FileLoader( this.manager );
  28698. loader.setResponseType( 'arraybuffer' );
  28699. loader.setPath( this.path );
  28700. loader.load( url, function ( buffer ) {
  28701. // Create a copy of the buffer. The `decodeAudioData` method
  28702. // detaches the buffer when complete, preventing reuse.
  28703. var bufferCopy = buffer.slice( 0 );
  28704. var context = AudioContext.getContext();
  28705. context.decodeAudioData( bufferCopy, function ( audioBuffer ) {
  28706. onLoad( audioBuffer );
  28707. } );
  28708. }, onProgress, onError );
  28709. },
  28710. setPath: function ( value ) {
  28711. this.path = value;
  28712. return this;
  28713. }
  28714. } );
  28715. /**
  28716. * @author mrdoob / http://mrdoob.com/
  28717. */
  28718. function StereoCamera() {
  28719. this.type = 'StereoCamera';
  28720. this.aspect = 1;
  28721. this.eyeSep = 0.064;
  28722. this.cameraL = new PerspectiveCamera();
  28723. this.cameraL.layers.enable( 1 );
  28724. this.cameraL.matrixAutoUpdate = false;
  28725. this.cameraR = new PerspectiveCamera();
  28726. this.cameraR.layers.enable( 2 );
  28727. this.cameraR.matrixAutoUpdate = false;
  28728. }
  28729. Object.assign( StereoCamera.prototype, {
  28730. update: ( function () {
  28731. var instance, focus, fov, aspect, near, far, zoom, eyeSep;
  28732. var eyeRight = new Matrix4();
  28733. var eyeLeft = new Matrix4();
  28734. return function update( camera ) {
  28735. var needsUpdate = instance !== this || focus !== camera.focus || fov !== camera.fov ||
  28736. aspect !== camera.aspect * this.aspect || near !== camera.near ||
  28737. far !== camera.far || zoom !== camera.zoom || eyeSep !== this.eyeSep;
  28738. if ( needsUpdate ) {
  28739. instance = this;
  28740. focus = camera.focus;
  28741. fov = camera.fov;
  28742. aspect = camera.aspect * this.aspect;
  28743. near = camera.near;
  28744. far = camera.far;
  28745. zoom = camera.zoom;
  28746. // Off-axis stereoscopic effect based on
  28747. // http://paulbourke.net/stereographics/stereorender/
  28748. var projectionMatrix = camera.projectionMatrix.clone();
  28749. eyeSep = this.eyeSep / 2;
  28750. var eyeSepOnProjection = eyeSep * near / focus;
  28751. var ymax = ( near * Math.tan( _Math.DEG2RAD * fov * 0.5 ) ) / zoom;
  28752. var xmin, xmax;
  28753. // translate xOffset
  28754. eyeLeft.elements[ 12 ] = - eyeSep;
  28755. eyeRight.elements[ 12 ] = eyeSep;
  28756. // for left eye
  28757. xmin = - ymax * aspect + eyeSepOnProjection;
  28758. xmax = ymax * aspect + eyeSepOnProjection;
  28759. projectionMatrix.elements[ 0 ] = 2 * near / ( xmax - xmin );
  28760. projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  28761. this.cameraL.projectionMatrix.copy( projectionMatrix );
  28762. // for right eye
  28763. xmin = - ymax * aspect - eyeSepOnProjection;
  28764. xmax = ymax * aspect - eyeSepOnProjection;
  28765. projectionMatrix.elements[ 0 ] = 2 * near / ( xmax - xmin );
  28766. projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  28767. this.cameraR.projectionMatrix.copy( projectionMatrix );
  28768. }
  28769. this.cameraL.matrixWorld.copy( camera.matrixWorld ).multiply( eyeLeft );
  28770. this.cameraR.matrixWorld.copy( camera.matrixWorld ).multiply( eyeRight );
  28771. };
  28772. } )()
  28773. } );
  28774. /**
  28775. * Camera for rendering cube maps
  28776. * - renders scene into axis-aligned cube
  28777. *
  28778. * @author alteredq / http://alteredqualia.com/
  28779. */
  28780. function CubeCamera( near, far, cubeResolution, options ) {
  28781. Object3D.call( this );
  28782. this.type = 'CubeCamera';
  28783. var fov = 90, aspect = 1;
  28784. var cameraPX = new PerspectiveCamera( fov, aspect, near, far );
  28785. cameraPX.up.set( 0, - 1, 0 );
  28786. cameraPX.lookAt( new Vector3( 1, 0, 0 ) );
  28787. this.add( cameraPX );
  28788. var cameraNX = new PerspectiveCamera( fov, aspect, near, far );
  28789. cameraNX.up.set( 0, - 1, 0 );
  28790. cameraNX.lookAt( new Vector3( - 1, 0, 0 ) );
  28791. this.add( cameraNX );
  28792. var cameraPY = new PerspectiveCamera( fov, aspect, near, far );
  28793. cameraPY.up.set( 0, 0, 1 );
  28794. cameraPY.lookAt( new Vector3( 0, 1, 0 ) );
  28795. this.add( cameraPY );
  28796. var cameraNY = new PerspectiveCamera( fov, aspect, near, far );
  28797. cameraNY.up.set( 0, 0, - 1 );
  28798. cameraNY.lookAt( new Vector3( 0, - 1, 0 ) );
  28799. this.add( cameraNY );
  28800. var cameraPZ = new PerspectiveCamera( fov, aspect, near, far );
  28801. cameraPZ.up.set( 0, - 1, 0 );
  28802. cameraPZ.lookAt( new Vector3( 0, 0, 1 ) );
  28803. this.add( cameraPZ );
  28804. var cameraNZ = new PerspectiveCamera( fov, aspect, near, far );
  28805. cameraNZ.up.set( 0, - 1, 0 );
  28806. cameraNZ.lookAt( new Vector3( 0, 0, - 1 ) );
  28807. this.add( cameraNZ );
  28808. options = options || { format: RGBFormat, magFilter: LinearFilter, minFilter: LinearFilter };
  28809. this.renderTarget = new WebGLRenderTargetCube( cubeResolution, cubeResolution, options );
  28810. this.renderTarget.texture.name = "CubeCamera";
  28811. this.update = function ( renderer, scene ) {
  28812. if ( this.parent === null ) this.updateMatrixWorld();
  28813. var currentRenderTarget = renderer.getRenderTarget();
  28814. var renderTarget = this.renderTarget;
  28815. var generateMipmaps = renderTarget.texture.generateMipmaps;
  28816. renderTarget.texture.generateMipmaps = false;
  28817. renderer.setRenderTarget( renderTarget, 0 );
  28818. renderer.render( scene, cameraPX );
  28819. renderer.setRenderTarget( renderTarget, 1 );
  28820. renderer.render( scene, cameraNX );
  28821. renderer.setRenderTarget( renderTarget, 2 );
  28822. renderer.render( scene, cameraPY );
  28823. renderer.setRenderTarget( renderTarget, 3 );
  28824. renderer.render( scene, cameraNY );
  28825. renderer.setRenderTarget( renderTarget, 4 );
  28826. renderer.render( scene, cameraPZ );
  28827. renderTarget.texture.generateMipmaps = generateMipmaps;
  28828. renderer.setRenderTarget( renderTarget, 5 );
  28829. renderer.render( scene, cameraNZ );
  28830. renderer.setRenderTarget( currentRenderTarget );
  28831. };
  28832. this.clear = function ( renderer, color, depth, stencil ) {
  28833. var currentRenderTarget = renderer.getRenderTarget();
  28834. var renderTarget = this.renderTarget;
  28835. for ( var i = 0; i < 6; i ++ ) {
  28836. renderer.setRenderTarget( renderTarget, i );
  28837. renderer.clear( color, depth, stencil );
  28838. }
  28839. renderer.setRenderTarget( currentRenderTarget );
  28840. };
  28841. }
  28842. CubeCamera.prototype = Object.create( Object3D.prototype );
  28843. CubeCamera.prototype.constructor = CubeCamera;
  28844. /**
  28845. * @author alteredq / http://alteredqualia.com/
  28846. */
  28847. function Clock( autoStart ) {
  28848. this.autoStart = ( autoStart !== undefined ) ? autoStart : true;
  28849. this.startTime = 0;
  28850. this.oldTime = 0;
  28851. this.elapsedTime = 0;
  28852. this.running = false;
  28853. }
  28854. Object.assign( Clock.prototype, {
  28855. start: function () {
  28856. this.startTime = ( typeof performance === 'undefined' ? Date : performance ).now(); // see #10732
  28857. this.oldTime = this.startTime;
  28858. this.elapsedTime = 0;
  28859. this.running = true;
  28860. },
  28861. stop: function () {
  28862. this.getElapsedTime();
  28863. this.running = false;
  28864. this.autoStart = false;
  28865. },
  28866. getElapsedTime: function () {
  28867. this.getDelta();
  28868. return this.elapsedTime;
  28869. },
  28870. getDelta: function () {
  28871. var diff = 0;
  28872. if ( this.autoStart && ! this.running ) {
  28873. this.start();
  28874. return 0;
  28875. }
  28876. if ( this.running ) {
  28877. var newTime = ( typeof performance === 'undefined' ? Date : performance ).now();
  28878. diff = ( newTime - this.oldTime ) / 1000;
  28879. this.oldTime = newTime;
  28880. this.elapsedTime += diff;
  28881. }
  28882. return diff;
  28883. }
  28884. } );
  28885. /**
  28886. * @author mrdoob / http://mrdoob.com/
  28887. */
  28888. function AudioListener() {
  28889. Object3D.call( this );
  28890. this.type = 'AudioListener';
  28891. this.context = AudioContext.getContext();
  28892. this.gain = this.context.createGain();
  28893. this.gain.connect( this.context.destination );
  28894. this.filter = null;
  28895. this.timeDelta = 0;
  28896. }
  28897. AudioListener.prototype = Object.assign( Object.create( Object3D.prototype ), {
  28898. constructor: AudioListener,
  28899. getInput: function () {
  28900. return this.gain;
  28901. },
  28902. removeFilter: function ( ) {
  28903. if ( this.filter !== null ) {
  28904. this.gain.disconnect( this.filter );
  28905. this.filter.disconnect( this.context.destination );
  28906. this.gain.connect( this.context.destination );
  28907. this.filter = null;
  28908. }
  28909. return this;
  28910. },
  28911. getFilter: function () {
  28912. return this.filter;
  28913. },
  28914. setFilter: function ( value ) {
  28915. if ( this.filter !== null ) {
  28916. this.gain.disconnect( this.filter );
  28917. this.filter.disconnect( this.context.destination );
  28918. } else {
  28919. this.gain.disconnect( this.context.destination );
  28920. }
  28921. this.filter = value;
  28922. this.gain.connect( this.filter );
  28923. this.filter.connect( this.context.destination );
  28924. return this;
  28925. },
  28926. getMasterVolume: function () {
  28927. return this.gain.gain.value;
  28928. },
  28929. setMasterVolume: function ( value ) {
  28930. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  28931. return this;
  28932. },
  28933. updateMatrixWorld: ( function () {
  28934. var position = new Vector3();
  28935. var quaternion = new Quaternion();
  28936. var scale = new Vector3();
  28937. var orientation = new Vector3();
  28938. var clock = new Clock();
  28939. return function updateMatrixWorld( force ) {
  28940. Object3D.prototype.updateMatrixWorld.call( this, force );
  28941. var listener = this.context.listener;
  28942. var up = this.up;
  28943. this.timeDelta = clock.getDelta();
  28944. this.matrixWorld.decompose( position, quaternion, scale );
  28945. orientation.set( 0, 0, - 1 ).applyQuaternion( quaternion );
  28946. if ( listener.positionX ) {
  28947. // code path for Chrome (see #14393)
  28948. var endTime = this.context.currentTime + this.timeDelta;
  28949. listener.positionX.linearRampToValueAtTime( position.x, endTime );
  28950. listener.positionY.linearRampToValueAtTime( position.y, endTime );
  28951. listener.positionZ.linearRampToValueAtTime( position.z, endTime );
  28952. listener.forwardX.linearRampToValueAtTime( orientation.x, endTime );
  28953. listener.forwardY.linearRampToValueAtTime( orientation.y, endTime );
  28954. listener.forwardZ.linearRampToValueAtTime( orientation.z, endTime );
  28955. listener.upX.linearRampToValueAtTime( up.x, endTime );
  28956. listener.upY.linearRampToValueAtTime( up.y, endTime );
  28957. listener.upZ.linearRampToValueAtTime( up.z, endTime );
  28958. } else {
  28959. listener.setPosition( position.x, position.y, position.z );
  28960. listener.setOrientation( orientation.x, orientation.y, orientation.z, up.x, up.y, up.z );
  28961. }
  28962. };
  28963. } )()
  28964. } );
  28965. /**
  28966. * @author mrdoob / http://mrdoob.com/
  28967. * @author Reece Aaron Lecrivain / http://reecenotes.com/
  28968. */
  28969. function Audio( listener ) {
  28970. Object3D.call( this );
  28971. this.type = 'Audio';
  28972. this.listener = listener;
  28973. this.context = listener.context;
  28974. this.gain = this.context.createGain();
  28975. this.gain.connect( listener.getInput() );
  28976. this.autoplay = false;
  28977. this.buffer = null;
  28978. this.detune = 0;
  28979. this.loop = false;
  28980. this.startTime = 0;
  28981. this.offset = 0;
  28982. this.playbackRate = 1;
  28983. this.isPlaying = false;
  28984. this.hasPlaybackControl = true;
  28985. this.sourceType = 'empty';
  28986. this.filters = [];
  28987. }
  28988. Audio.prototype = Object.assign( Object.create( Object3D.prototype ), {
  28989. constructor: Audio,
  28990. getOutput: function () {
  28991. return this.gain;
  28992. },
  28993. setNodeSource: function ( audioNode ) {
  28994. this.hasPlaybackControl = false;
  28995. this.sourceType = 'audioNode';
  28996. this.source = audioNode;
  28997. this.connect();
  28998. return this;
  28999. },
  29000. setMediaElementSource: function ( mediaElement ) {
  29001. this.hasPlaybackControl = false;
  29002. this.sourceType = 'mediaNode';
  29003. this.source = this.context.createMediaElementSource( mediaElement );
  29004. this.connect();
  29005. return this;
  29006. },
  29007. setBuffer: function ( audioBuffer ) {
  29008. this.buffer = audioBuffer;
  29009. this.sourceType = 'buffer';
  29010. if ( this.autoplay ) this.play();
  29011. return this;
  29012. },
  29013. play: function () {
  29014. if ( this.isPlaying === true ) {
  29015. console.warn( 'THREE.Audio: Audio is already playing.' );
  29016. return;
  29017. }
  29018. if ( this.hasPlaybackControl === false ) {
  29019. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  29020. return;
  29021. }
  29022. var source = this.context.createBufferSource();
  29023. source.buffer = this.buffer;
  29024. source.loop = this.loop;
  29025. source.onended = this.onEnded.bind( this );
  29026. this.startTime = this.context.currentTime;
  29027. source.start( this.startTime, this.offset );
  29028. this.isPlaying = true;
  29029. this.source = source;
  29030. this.setDetune( this.detune );
  29031. this.setPlaybackRate( this.playbackRate );
  29032. return this.connect();
  29033. },
  29034. pause: function () {
  29035. if ( this.hasPlaybackControl === false ) {
  29036. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  29037. return;
  29038. }
  29039. if ( this.isPlaying === true ) {
  29040. this.source.stop();
  29041. this.source.onended = null;
  29042. this.offset += ( this.context.currentTime - this.startTime ) * this.playbackRate;
  29043. this.isPlaying = false;
  29044. }
  29045. return this;
  29046. },
  29047. stop: function () {
  29048. if ( this.hasPlaybackControl === false ) {
  29049. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  29050. return;
  29051. }
  29052. this.source.stop();
  29053. this.source.onended = null;
  29054. this.offset = 0;
  29055. this.isPlaying = false;
  29056. return this;
  29057. },
  29058. connect: function () {
  29059. if ( this.filters.length > 0 ) {
  29060. this.source.connect( this.filters[ 0 ] );
  29061. for ( var i = 1, l = this.filters.length; i < l; i ++ ) {
  29062. this.filters[ i - 1 ].connect( this.filters[ i ] );
  29063. }
  29064. this.filters[ this.filters.length - 1 ].connect( this.getOutput() );
  29065. } else {
  29066. this.source.connect( this.getOutput() );
  29067. }
  29068. return this;
  29069. },
  29070. disconnect: function () {
  29071. if ( this.filters.length > 0 ) {
  29072. this.source.disconnect( this.filters[ 0 ] );
  29073. for ( var i = 1, l = this.filters.length; i < l; i ++ ) {
  29074. this.filters[ i - 1 ].disconnect( this.filters[ i ] );
  29075. }
  29076. this.filters[ this.filters.length - 1 ].disconnect( this.getOutput() );
  29077. } else {
  29078. this.source.disconnect( this.getOutput() );
  29079. }
  29080. return this;
  29081. },
  29082. getFilters: function () {
  29083. return this.filters;
  29084. },
  29085. setFilters: function ( value ) {
  29086. if ( ! value ) value = [];
  29087. if ( this.isPlaying === true ) {
  29088. this.disconnect();
  29089. this.filters = value;
  29090. this.connect();
  29091. } else {
  29092. this.filters = value;
  29093. }
  29094. return this;
  29095. },
  29096. setDetune: function ( value ) {
  29097. this.detune = value;
  29098. if ( this.source.detune === undefined ) return; // only set detune when available
  29099. if ( this.isPlaying === true ) {
  29100. this.source.detune.setTargetAtTime( this.detune, this.context.currentTime, 0.01 );
  29101. }
  29102. return this;
  29103. },
  29104. getDetune: function () {
  29105. return this.detune;
  29106. },
  29107. getFilter: function () {
  29108. return this.getFilters()[ 0 ];
  29109. },
  29110. setFilter: function ( filter ) {
  29111. return this.setFilters( filter ? [ filter ] : [] );
  29112. },
  29113. setPlaybackRate: function ( value ) {
  29114. if ( this.hasPlaybackControl === false ) {
  29115. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  29116. return;
  29117. }
  29118. this.playbackRate = value;
  29119. if ( this.isPlaying === true ) {
  29120. this.source.playbackRate.setTargetAtTime( this.playbackRate, this.context.currentTime, 0.01 );
  29121. }
  29122. return this;
  29123. },
  29124. getPlaybackRate: function () {
  29125. return this.playbackRate;
  29126. },
  29127. onEnded: function () {
  29128. this.isPlaying = false;
  29129. },
  29130. getLoop: function () {
  29131. if ( this.hasPlaybackControl === false ) {
  29132. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  29133. return false;
  29134. }
  29135. return this.loop;
  29136. },
  29137. setLoop: function ( value ) {
  29138. if ( this.hasPlaybackControl === false ) {
  29139. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  29140. return;
  29141. }
  29142. this.loop = value;
  29143. if ( this.isPlaying === true ) {
  29144. this.source.loop = this.loop;
  29145. }
  29146. return this;
  29147. },
  29148. getVolume: function () {
  29149. return this.gain.gain.value;
  29150. },
  29151. setVolume: function ( value ) {
  29152. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  29153. return this;
  29154. }
  29155. } );
  29156. /**
  29157. * @author mrdoob / http://mrdoob.com/
  29158. */
  29159. function PositionalAudio( listener ) {
  29160. Audio.call( this, listener );
  29161. this.panner = this.context.createPanner();
  29162. this.panner.connect( this.gain );
  29163. }
  29164. PositionalAudio.prototype = Object.assign( Object.create( Audio.prototype ), {
  29165. constructor: PositionalAudio,
  29166. getOutput: function () {
  29167. return this.panner;
  29168. },
  29169. getRefDistance: function () {
  29170. return this.panner.refDistance;
  29171. },
  29172. setRefDistance: function ( value ) {
  29173. this.panner.refDistance = value;
  29174. return this;
  29175. },
  29176. getRolloffFactor: function () {
  29177. return this.panner.rolloffFactor;
  29178. },
  29179. setRolloffFactor: function ( value ) {
  29180. this.panner.rolloffFactor = value;
  29181. return this;
  29182. },
  29183. getDistanceModel: function () {
  29184. return this.panner.distanceModel;
  29185. },
  29186. setDistanceModel: function ( value ) {
  29187. this.panner.distanceModel = value;
  29188. return this;
  29189. },
  29190. getMaxDistance: function () {
  29191. return this.panner.maxDistance;
  29192. },
  29193. setMaxDistance: function ( value ) {
  29194. this.panner.maxDistance = value;
  29195. return this;
  29196. },
  29197. setDirectionalCone: function ( coneInnerAngle, coneOuterAngle, coneOuterGain ) {
  29198. this.panner.coneInnerAngle = coneInnerAngle;
  29199. this.panner.coneOuterAngle = coneOuterAngle;
  29200. this.panner.coneOuterGain = coneOuterGain;
  29201. return this;
  29202. },
  29203. updateMatrixWorld: ( function () {
  29204. var position = new Vector3();
  29205. var quaternion = new Quaternion();
  29206. var scale = new Vector3();
  29207. var orientation = new Vector3();
  29208. return function updateMatrixWorld( force ) {
  29209. Object3D.prototype.updateMatrixWorld.call( this, force );
  29210. if ( this.hasPlaybackControl === true && this.isPlaying === false ) return;
  29211. this.matrixWorld.decompose( position, quaternion, scale );
  29212. orientation.set( 0, 0, 1 ).applyQuaternion( quaternion );
  29213. var panner = this.panner;
  29214. if ( panner.positionX ) {
  29215. // code path for Chrome and Firefox (see #14393)
  29216. var endTime = this.context.currentTime + this.listener.timeDelta;
  29217. panner.positionX.linearRampToValueAtTime( position.x, endTime );
  29218. panner.positionY.linearRampToValueAtTime( position.y, endTime );
  29219. panner.positionZ.linearRampToValueAtTime( position.z, endTime );
  29220. panner.orientationX.linearRampToValueAtTime( orientation.x, endTime );
  29221. panner.orientationY.linearRampToValueAtTime( orientation.y, endTime );
  29222. panner.orientationZ.linearRampToValueAtTime( orientation.z, endTime );
  29223. } else {
  29224. panner.setPosition( position.x, position.y, position.z );
  29225. panner.setOrientation( orientation.x, orientation.y, orientation.z );
  29226. }
  29227. };
  29228. } )()
  29229. } );
  29230. /**
  29231. * @author mrdoob / http://mrdoob.com/
  29232. */
  29233. function AudioAnalyser( audio, fftSize ) {
  29234. this.analyser = audio.context.createAnalyser();
  29235. this.analyser.fftSize = fftSize !== undefined ? fftSize : 2048;
  29236. this.data = new Uint8Array( this.analyser.frequencyBinCount );
  29237. audio.getOutput().connect( this.analyser );
  29238. }
  29239. Object.assign( AudioAnalyser.prototype, {
  29240. getFrequencyData: function () {
  29241. this.analyser.getByteFrequencyData( this.data );
  29242. return this.data;
  29243. },
  29244. getAverageFrequency: function () {
  29245. var value = 0, data = this.getFrequencyData();
  29246. for ( var i = 0; i < data.length; i ++ ) {
  29247. value += data[ i ];
  29248. }
  29249. return value / data.length;
  29250. }
  29251. } );
  29252. /**
  29253. *
  29254. * Buffered scene graph property that allows weighted accumulation.
  29255. *
  29256. *
  29257. * @author Ben Houston / http://clara.io/
  29258. * @author David Sarno / http://lighthaus.us/
  29259. * @author tschw
  29260. */
  29261. function PropertyMixer( binding, typeName, valueSize ) {
  29262. this.binding = binding;
  29263. this.valueSize = valueSize;
  29264. var bufferType = Float64Array,
  29265. mixFunction;
  29266. switch ( typeName ) {
  29267. case 'quaternion':
  29268. mixFunction = this._slerp;
  29269. break;
  29270. case 'string':
  29271. case 'bool':
  29272. bufferType = Array;
  29273. mixFunction = this._select;
  29274. break;
  29275. default:
  29276. mixFunction = this._lerp;
  29277. }
  29278. this.buffer = new bufferType( valueSize * 4 );
  29279. // layout: [ incoming | accu0 | accu1 | orig ]
  29280. //
  29281. // interpolators can use .buffer as their .result
  29282. // the data then goes to 'incoming'
  29283. //
  29284. // 'accu0' and 'accu1' are used frame-interleaved for
  29285. // the cumulative result and are compared to detect
  29286. // changes
  29287. //
  29288. // 'orig' stores the original state of the property
  29289. this._mixBufferRegion = mixFunction;
  29290. this.cumulativeWeight = 0;
  29291. this.useCount = 0;
  29292. this.referenceCount = 0;
  29293. }
  29294. Object.assign( PropertyMixer.prototype, {
  29295. // accumulate data in the 'incoming' region into 'accu<i>'
  29296. accumulate: function ( accuIndex, weight ) {
  29297. // note: happily accumulating nothing when weight = 0, the caller knows
  29298. // the weight and shouldn't have made the call in the first place
  29299. var buffer = this.buffer,
  29300. stride = this.valueSize,
  29301. offset = accuIndex * stride + stride,
  29302. currentWeight = this.cumulativeWeight;
  29303. if ( currentWeight === 0 ) {
  29304. // accuN := incoming * weight
  29305. for ( var i = 0; i !== stride; ++ i ) {
  29306. buffer[ offset + i ] = buffer[ i ];
  29307. }
  29308. currentWeight = weight;
  29309. } else {
  29310. // accuN := accuN + incoming * weight
  29311. currentWeight += weight;
  29312. var mix = weight / currentWeight;
  29313. this._mixBufferRegion( buffer, offset, 0, mix, stride );
  29314. }
  29315. this.cumulativeWeight = currentWeight;
  29316. },
  29317. // apply the state of 'accu<i>' to the binding when accus differ
  29318. apply: function ( accuIndex ) {
  29319. var stride = this.valueSize,
  29320. buffer = this.buffer,
  29321. offset = accuIndex * stride + stride,
  29322. weight = this.cumulativeWeight,
  29323. binding = this.binding;
  29324. this.cumulativeWeight = 0;
  29325. if ( weight < 1 ) {
  29326. // accuN := accuN + original * ( 1 - cumulativeWeight )
  29327. var originalValueOffset = stride * 3;
  29328. this._mixBufferRegion(
  29329. buffer, offset, originalValueOffset, 1 - weight, stride );
  29330. }
  29331. for ( var i = stride, e = stride + stride; i !== e; ++ i ) {
  29332. if ( buffer[ i ] !== buffer[ i + stride ] ) {
  29333. // value has changed -> update scene graph
  29334. binding.setValue( buffer, offset );
  29335. break;
  29336. }
  29337. }
  29338. },
  29339. // remember the state of the bound property and copy it to both accus
  29340. saveOriginalState: function () {
  29341. var binding = this.binding;
  29342. var buffer = this.buffer,
  29343. stride = this.valueSize,
  29344. originalValueOffset = stride * 3;
  29345. binding.getValue( buffer, originalValueOffset );
  29346. // accu[0..1] := orig -- initially detect changes against the original
  29347. for ( var i = stride, e = originalValueOffset; i !== e; ++ i ) {
  29348. buffer[ i ] = buffer[ originalValueOffset + ( i % stride ) ];
  29349. }
  29350. this.cumulativeWeight = 0;
  29351. },
  29352. // apply the state previously taken via 'saveOriginalState' to the binding
  29353. restoreOriginalState: function () {
  29354. var originalValueOffset = this.valueSize * 3;
  29355. this.binding.setValue( this.buffer, originalValueOffset );
  29356. },
  29357. // mix functions
  29358. _select: function ( buffer, dstOffset, srcOffset, t, stride ) {
  29359. if ( t >= 0.5 ) {
  29360. for ( var i = 0; i !== stride; ++ i ) {
  29361. buffer[ dstOffset + i ] = buffer[ srcOffset + i ];
  29362. }
  29363. }
  29364. },
  29365. _slerp: function ( buffer, dstOffset, srcOffset, t ) {
  29366. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t );
  29367. },
  29368. _lerp: function ( buffer, dstOffset, srcOffset, t, stride ) {
  29369. var s = 1 - t;
  29370. for ( var i = 0; i !== stride; ++ i ) {
  29371. var j = dstOffset + i;
  29372. buffer[ j ] = buffer[ j ] * s + buffer[ srcOffset + i ] * t;
  29373. }
  29374. }
  29375. } );
  29376. /**
  29377. *
  29378. * A reference to a real property in the scene graph.
  29379. *
  29380. *
  29381. * @author Ben Houston / http://clara.io/
  29382. * @author David Sarno / http://lighthaus.us/
  29383. * @author tschw
  29384. */
  29385. // Characters [].:/ are reserved for track binding syntax.
  29386. var RESERVED_CHARS_RE = '\\[\\]\\.:\\/';
  29387. function Composite( targetGroup, path, optionalParsedPath ) {
  29388. var parsedPath = optionalParsedPath || PropertyBinding.parseTrackName( path );
  29389. this._targetGroup = targetGroup;
  29390. this._bindings = targetGroup.subscribe_( path, parsedPath );
  29391. }
  29392. Object.assign( Composite.prototype, {
  29393. getValue: function ( array, offset ) {
  29394. this.bind(); // bind all binding
  29395. var firstValidIndex = this._targetGroup.nCachedObjects_,
  29396. binding = this._bindings[ firstValidIndex ];
  29397. // and only call .getValue on the first
  29398. if ( binding !== undefined ) binding.getValue( array, offset );
  29399. },
  29400. setValue: function ( array, offset ) {
  29401. var bindings = this._bindings;
  29402. for ( var i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  29403. bindings[ i ].setValue( array, offset );
  29404. }
  29405. },
  29406. bind: function () {
  29407. var bindings = this._bindings;
  29408. for ( var i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  29409. bindings[ i ].bind();
  29410. }
  29411. },
  29412. unbind: function () {
  29413. var bindings = this._bindings;
  29414. for ( var i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  29415. bindings[ i ].unbind();
  29416. }
  29417. }
  29418. } );
  29419. function PropertyBinding( rootNode, path, parsedPath ) {
  29420. this.path = path;
  29421. this.parsedPath = parsedPath || PropertyBinding.parseTrackName( path );
  29422. this.node = PropertyBinding.findNode( rootNode, this.parsedPath.nodeName ) || rootNode;
  29423. this.rootNode = rootNode;
  29424. }
  29425. Object.assign( PropertyBinding, {
  29426. Composite: Composite,
  29427. create: function ( root, path, parsedPath ) {
  29428. if ( ! ( root && root.isAnimationObjectGroup ) ) {
  29429. return new PropertyBinding( root, path, parsedPath );
  29430. } else {
  29431. return new PropertyBinding.Composite( root, path, parsedPath );
  29432. }
  29433. },
  29434. /**
  29435. * Replaces spaces with underscores and removes unsupported characters from
  29436. * node names, to ensure compatibility with parseTrackName().
  29437. *
  29438. * @param {string} name Node name to be sanitized.
  29439. * @return {string}
  29440. */
  29441. sanitizeNodeName: ( function () {
  29442. var reservedRe = new RegExp( '[' + RESERVED_CHARS_RE + ']', 'g' );
  29443. return function sanitizeNodeName( name ) {
  29444. return name.replace( /\s/g, '_' ).replace( reservedRe, '' );
  29445. };
  29446. }() ),
  29447. parseTrackName: function () {
  29448. // Attempts to allow node names from any language. ES5's `\w` regexp matches
  29449. // only latin characters, and the unicode \p{L} is not yet supported. So
  29450. // instead, we exclude reserved characters and match everything else.
  29451. var wordChar = '[^' + RESERVED_CHARS_RE + ']';
  29452. var wordCharOrDot = '[^' + RESERVED_CHARS_RE.replace( '\\.', '' ) + ']';
  29453. // Parent directories, delimited by '/' or ':'. Currently unused, but must
  29454. // be matched to parse the rest of the track name.
  29455. var directoryRe = /((?:WC+[\/:])*)/.source.replace( 'WC', wordChar );
  29456. // Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'.
  29457. var nodeRe = /(WCOD+)?/.source.replace( 'WCOD', wordCharOrDot );
  29458. // Object on target node, and accessor. May not contain reserved
  29459. // characters. Accessor may contain any character except closing bracket.
  29460. var objectRe = /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace( 'WC', wordChar );
  29461. // Property and accessor. May not contain reserved characters. Accessor may
  29462. // contain any non-bracket characters.
  29463. var propertyRe = /\.(WC+)(?:\[(.+)\])?/.source.replace( 'WC', wordChar );
  29464. var trackRe = new RegExp( ''
  29465. + '^'
  29466. + directoryRe
  29467. + nodeRe
  29468. + objectRe
  29469. + propertyRe
  29470. + '$'
  29471. );
  29472. var supportedObjectNames = [ 'material', 'materials', 'bones' ];
  29473. return function parseTrackName( trackName ) {
  29474. var matches = trackRe.exec( trackName );
  29475. if ( ! matches ) {
  29476. throw new Error( 'PropertyBinding: Cannot parse trackName: ' + trackName );
  29477. }
  29478. var results = {
  29479. // directoryName: matches[ 1 ], // (tschw) currently unused
  29480. nodeName: matches[ 2 ],
  29481. objectName: matches[ 3 ],
  29482. objectIndex: matches[ 4 ],
  29483. propertyName: matches[ 5 ], // required
  29484. propertyIndex: matches[ 6 ]
  29485. };
  29486. var lastDot = results.nodeName && results.nodeName.lastIndexOf( '.' );
  29487. if ( lastDot !== undefined && lastDot !== - 1 ) {
  29488. var objectName = results.nodeName.substring( lastDot + 1 );
  29489. // Object names must be checked against a whitelist. Otherwise, there
  29490. // is no way to parse 'foo.bar.baz': 'baz' must be a property, but
  29491. // 'bar' could be the objectName, or part of a nodeName (which can
  29492. // include '.' characters).
  29493. if ( supportedObjectNames.indexOf( objectName ) !== - 1 ) {
  29494. results.nodeName = results.nodeName.substring( 0, lastDot );
  29495. results.objectName = objectName;
  29496. }
  29497. }
  29498. if ( results.propertyName === null || results.propertyName.length === 0 ) {
  29499. throw new Error( 'PropertyBinding: can not parse propertyName from trackName: ' + trackName );
  29500. }
  29501. return results;
  29502. };
  29503. }(),
  29504. findNode: function ( root, nodeName ) {
  29505. if ( ! nodeName || nodeName === "" || nodeName === "root" || nodeName === "." || nodeName === - 1 || nodeName === root.name || nodeName === root.uuid ) {
  29506. return root;
  29507. }
  29508. // search into skeleton bones.
  29509. if ( root.skeleton ) {
  29510. var bone = root.skeleton.getBoneByName( nodeName );
  29511. if ( bone !== undefined ) {
  29512. return bone;
  29513. }
  29514. }
  29515. // search into node subtree.
  29516. if ( root.children ) {
  29517. var searchNodeSubtree = function ( children ) {
  29518. for ( var i = 0; i < children.length; i ++ ) {
  29519. var childNode = children[ i ];
  29520. if ( childNode.name === nodeName || childNode.uuid === nodeName ) {
  29521. return childNode;
  29522. }
  29523. var result = searchNodeSubtree( childNode.children );
  29524. if ( result ) return result;
  29525. }
  29526. return null;
  29527. };
  29528. var subTreeNode = searchNodeSubtree( root.children );
  29529. if ( subTreeNode ) {
  29530. return subTreeNode;
  29531. }
  29532. }
  29533. return null;
  29534. }
  29535. } );
  29536. Object.assign( PropertyBinding.prototype, { // prototype, continued
  29537. // these are used to "bind" a nonexistent property
  29538. _getValue_unavailable: function () {},
  29539. _setValue_unavailable: function () {},
  29540. BindingType: {
  29541. Direct: 0,
  29542. EntireArray: 1,
  29543. ArrayElement: 2,
  29544. HasFromToArray: 3
  29545. },
  29546. Versioning: {
  29547. None: 0,
  29548. NeedsUpdate: 1,
  29549. MatrixWorldNeedsUpdate: 2
  29550. },
  29551. GetterByBindingType: [
  29552. function getValue_direct( buffer, offset ) {
  29553. buffer[ offset ] = this.node[ this.propertyName ];
  29554. },
  29555. function getValue_array( buffer, offset ) {
  29556. var source = this.resolvedProperty;
  29557. for ( var i = 0, n = source.length; i !== n; ++ i ) {
  29558. buffer[ offset ++ ] = source[ i ];
  29559. }
  29560. },
  29561. function getValue_arrayElement( buffer, offset ) {
  29562. buffer[ offset ] = this.resolvedProperty[ this.propertyIndex ];
  29563. },
  29564. function getValue_toArray( buffer, offset ) {
  29565. this.resolvedProperty.toArray( buffer, offset );
  29566. }
  29567. ],
  29568. SetterByBindingTypeAndVersioning: [
  29569. [
  29570. // Direct
  29571. function setValue_direct( buffer, offset ) {
  29572. this.targetObject[ this.propertyName ] = buffer[ offset ];
  29573. },
  29574. function setValue_direct_setNeedsUpdate( buffer, offset ) {
  29575. this.targetObject[ this.propertyName ] = buffer[ offset ];
  29576. this.targetObject.needsUpdate = true;
  29577. },
  29578. function setValue_direct_setMatrixWorldNeedsUpdate( buffer, offset ) {
  29579. this.targetObject[ this.propertyName ] = buffer[ offset ];
  29580. this.targetObject.matrixWorldNeedsUpdate = true;
  29581. }
  29582. ], [
  29583. // EntireArray
  29584. function setValue_array( buffer, offset ) {
  29585. var dest = this.resolvedProperty;
  29586. for ( var i = 0, n = dest.length; i !== n; ++ i ) {
  29587. dest[ i ] = buffer[ offset ++ ];
  29588. }
  29589. },
  29590. function setValue_array_setNeedsUpdate( buffer, offset ) {
  29591. var dest = this.resolvedProperty;
  29592. for ( var i = 0, n = dest.length; i !== n; ++ i ) {
  29593. dest[ i ] = buffer[ offset ++ ];
  29594. }
  29595. this.targetObject.needsUpdate = true;
  29596. },
  29597. function setValue_array_setMatrixWorldNeedsUpdate( buffer, offset ) {
  29598. var dest = this.resolvedProperty;
  29599. for ( var i = 0, n = dest.length; i !== n; ++ i ) {
  29600. dest[ i ] = buffer[ offset ++ ];
  29601. }
  29602. this.targetObject.matrixWorldNeedsUpdate = true;
  29603. }
  29604. ], [
  29605. // ArrayElement
  29606. function setValue_arrayElement( buffer, offset ) {
  29607. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  29608. },
  29609. function setValue_arrayElement_setNeedsUpdate( buffer, offset ) {
  29610. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  29611. this.targetObject.needsUpdate = true;
  29612. },
  29613. function setValue_arrayElement_setMatrixWorldNeedsUpdate( buffer, offset ) {
  29614. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  29615. this.targetObject.matrixWorldNeedsUpdate = true;
  29616. }
  29617. ], [
  29618. // HasToFromArray
  29619. function setValue_fromArray( buffer, offset ) {
  29620. this.resolvedProperty.fromArray( buffer, offset );
  29621. },
  29622. function setValue_fromArray_setNeedsUpdate( buffer, offset ) {
  29623. this.resolvedProperty.fromArray( buffer, offset );
  29624. this.targetObject.needsUpdate = true;
  29625. },
  29626. function setValue_fromArray_setMatrixWorldNeedsUpdate( buffer, offset ) {
  29627. this.resolvedProperty.fromArray( buffer, offset );
  29628. this.targetObject.matrixWorldNeedsUpdate = true;
  29629. }
  29630. ]
  29631. ],
  29632. getValue: function getValue_unbound( targetArray, offset ) {
  29633. this.bind();
  29634. this.getValue( targetArray, offset );
  29635. // Note: This class uses a State pattern on a per-method basis:
  29636. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  29637. // prototype version of these methods with one that represents
  29638. // the bound state. When the property is not found, the methods
  29639. // become no-ops.
  29640. },
  29641. setValue: function getValue_unbound( sourceArray, offset ) {
  29642. this.bind();
  29643. this.setValue( sourceArray, offset );
  29644. },
  29645. // create getter / setter pair for a property in the scene graph
  29646. bind: function () {
  29647. var targetObject = this.node,
  29648. parsedPath = this.parsedPath,
  29649. objectName = parsedPath.objectName,
  29650. propertyName = parsedPath.propertyName,
  29651. propertyIndex = parsedPath.propertyIndex;
  29652. if ( ! targetObject ) {
  29653. targetObject = PropertyBinding.findNode( this.rootNode, parsedPath.nodeName ) || this.rootNode;
  29654. this.node = targetObject;
  29655. }
  29656. // set fail state so we can just 'return' on error
  29657. this.getValue = this._getValue_unavailable;
  29658. this.setValue = this._setValue_unavailable;
  29659. // ensure there is a value node
  29660. if ( ! targetObject ) {
  29661. console.error( 'THREE.PropertyBinding: Trying to update node for track: ' + this.path + ' but it wasn\'t found.' );
  29662. return;
  29663. }
  29664. if ( objectName ) {
  29665. var objectIndex = parsedPath.objectIndex;
  29666. // special cases were we need to reach deeper into the hierarchy to get the face materials....
  29667. switch ( objectName ) {
  29668. case 'materials':
  29669. if ( ! targetObject.material ) {
  29670. console.error( 'THREE.PropertyBinding: Can not bind to material as node does not have a material.', this );
  29671. return;
  29672. }
  29673. if ( ! targetObject.material.materials ) {
  29674. console.error( 'THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.', this );
  29675. return;
  29676. }
  29677. targetObject = targetObject.material.materials;
  29678. break;
  29679. case 'bones':
  29680. if ( ! targetObject.skeleton ) {
  29681. console.error( 'THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.', this );
  29682. return;
  29683. }
  29684. // potential future optimization: skip this if propertyIndex is already an integer
  29685. // and convert the integer string to a true integer.
  29686. targetObject = targetObject.skeleton.bones;
  29687. // support resolving morphTarget names into indices.
  29688. for ( var i = 0; i < targetObject.length; i ++ ) {
  29689. if ( targetObject[ i ].name === objectIndex ) {
  29690. objectIndex = i;
  29691. break;
  29692. }
  29693. }
  29694. break;
  29695. default:
  29696. if ( targetObject[ objectName ] === undefined ) {
  29697. console.error( 'THREE.PropertyBinding: Can not bind to objectName of node undefined.', this );
  29698. return;
  29699. }
  29700. targetObject = targetObject[ objectName ];
  29701. }
  29702. if ( objectIndex !== undefined ) {
  29703. if ( targetObject[ objectIndex ] === undefined ) {
  29704. console.error( 'THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject );
  29705. return;
  29706. }
  29707. targetObject = targetObject[ objectIndex ];
  29708. }
  29709. }
  29710. // resolve property
  29711. var nodeProperty = targetObject[ propertyName ];
  29712. if ( nodeProperty === undefined ) {
  29713. var nodeName = parsedPath.nodeName;
  29714. console.error( 'THREE.PropertyBinding: Trying to update property for track: ' + nodeName +
  29715. '.' + propertyName + ' but it wasn\'t found.', targetObject );
  29716. return;
  29717. }
  29718. // determine versioning scheme
  29719. var versioning = this.Versioning.None;
  29720. this.targetObject = targetObject;
  29721. if ( targetObject.needsUpdate !== undefined ) { // material
  29722. versioning = this.Versioning.NeedsUpdate;
  29723. } else if ( targetObject.matrixWorldNeedsUpdate !== undefined ) { // node transform
  29724. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  29725. }
  29726. // determine how the property gets bound
  29727. var bindingType = this.BindingType.Direct;
  29728. if ( propertyIndex !== undefined ) {
  29729. // access a sub element of the property array (only primitives are supported right now)
  29730. if ( propertyName === "morphTargetInfluences" ) {
  29731. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  29732. // support resolving morphTarget names into indices.
  29733. if ( ! targetObject.geometry ) {
  29734. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this );
  29735. return;
  29736. }
  29737. if ( targetObject.geometry.isBufferGeometry ) {
  29738. if ( ! targetObject.geometry.morphAttributes ) {
  29739. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this );
  29740. return;
  29741. }
  29742. for ( var i = 0; i < this.node.geometry.morphAttributes.position.length; i ++ ) {
  29743. if ( targetObject.geometry.morphAttributes.position[ i ].name === propertyIndex ) {
  29744. propertyIndex = i;
  29745. break;
  29746. }
  29747. }
  29748. } else {
  29749. if ( ! targetObject.geometry.morphTargets ) {
  29750. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphTargets.', this );
  29751. return;
  29752. }
  29753. for ( var i = 0; i < this.node.geometry.morphTargets.length; i ++ ) {
  29754. if ( targetObject.geometry.morphTargets[ i ].name === propertyIndex ) {
  29755. propertyIndex = i;
  29756. break;
  29757. }
  29758. }
  29759. }
  29760. }
  29761. bindingType = this.BindingType.ArrayElement;
  29762. this.resolvedProperty = nodeProperty;
  29763. this.propertyIndex = propertyIndex;
  29764. } else if ( nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined ) {
  29765. // must use copy for Object3D.Euler/Quaternion
  29766. bindingType = this.BindingType.HasFromToArray;
  29767. this.resolvedProperty = nodeProperty;
  29768. } else if ( Array.isArray( nodeProperty ) ) {
  29769. bindingType = this.BindingType.EntireArray;
  29770. this.resolvedProperty = nodeProperty;
  29771. } else {
  29772. this.propertyName = propertyName;
  29773. }
  29774. // select getter / setter
  29775. this.getValue = this.GetterByBindingType[ bindingType ];
  29776. this.setValue = this.SetterByBindingTypeAndVersioning[ bindingType ][ versioning ];
  29777. },
  29778. unbind: function () {
  29779. this.node = null;
  29780. // back to the prototype version of getValue / setValue
  29781. // note: avoiding to mutate the shape of 'this' via 'delete'
  29782. this.getValue = this._getValue_unbound;
  29783. this.setValue = this._setValue_unbound;
  29784. }
  29785. } );
  29786. //!\ DECLARE ALIAS AFTER assign prototype !
  29787. Object.assign( PropertyBinding.prototype, {
  29788. // initial state of these methods that calls 'bind'
  29789. _getValue_unbound: PropertyBinding.prototype.getValue,
  29790. _setValue_unbound: PropertyBinding.prototype.setValue,
  29791. } );
  29792. /**
  29793. *
  29794. * A group of objects that receives a shared animation state.
  29795. *
  29796. * Usage:
  29797. *
  29798. * - Add objects you would otherwise pass as 'root' to the
  29799. * constructor or the .clipAction method of AnimationMixer.
  29800. *
  29801. * - Instead pass this object as 'root'.
  29802. *
  29803. * - You can also add and remove objects later when the mixer
  29804. * is running.
  29805. *
  29806. * Note:
  29807. *
  29808. * Objects of this class appear as one object to the mixer,
  29809. * so cache control of the individual objects must be done
  29810. * on the group.
  29811. *
  29812. * Limitation:
  29813. *
  29814. * - The animated properties must be compatible among the
  29815. * all objects in the group.
  29816. *
  29817. * - A single property can either be controlled through a
  29818. * target group or directly, but not both.
  29819. *
  29820. * @author tschw
  29821. */
  29822. function AnimationObjectGroup() {
  29823. this.uuid = _Math.generateUUID();
  29824. // cached objects followed by the active ones
  29825. this._objects = Array.prototype.slice.call( arguments );
  29826. this.nCachedObjects_ = 0; // threshold
  29827. // note: read by PropertyBinding.Composite
  29828. var indices = {};
  29829. this._indicesByUUID = indices; // for bookkeeping
  29830. for ( var i = 0, n = arguments.length; i !== n; ++ i ) {
  29831. indices[ arguments[ i ].uuid ] = i;
  29832. }
  29833. this._paths = []; // inside: string
  29834. this._parsedPaths = []; // inside: { we don't care, here }
  29835. this._bindings = []; // inside: Array< PropertyBinding >
  29836. this._bindingsIndicesByPath = {}; // inside: indices in these arrays
  29837. var scope = this;
  29838. this.stats = {
  29839. objects: {
  29840. get total() {
  29841. return scope._objects.length;
  29842. },
  29843. get inUse() {
  29844. return this.total - scope.nCachedObjects_;
  29845. }
  29846. },
  29847. get bindingsPerObject() {
  29848. return scope._bindings.length;
  29849. }
  29850. };
  29851. }
  29852. Object.assign( AnimationObjectGroup.prototype, {
  29853. isAnimationObjectGroup: true,
  29854. add: function () {
  29855. var objects = this._objects,
  29856. nObjects = objects.length,
  29857. nCachedObjects = this.nCachedObjects_,
  29858. indicesByUUID = this._indicesByUUID,
  29859. paths = this._paths,
  29860. parsedPaths = this._parsedPaths,
  29861. bindings = this._bindings,
  29862. nBindings = bindings.length,
  29863. knownObject = undefined;
  29864. for ( var i = 0, n = arguments.length; i !== n; ++ i ) {
  29865. var object = arguments[ i ],
  29866. uuid = object.uuid,
  29867. index = indicesByUUID[ uuid ];
  29868. if ( index === undefined ) {
  29869. // unknown object -> add it to the ACTIVE region
  29870. index = nObjects ++;
  29871. indicesByUUID[ uuid ] = index;
  29872. objects.push( object );
  29873. // accounting is done, now do the same for all bindings
  29874. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  29875. bindings[ j ].push( new PropertyBinding( object, paths[ j ], parsedPaths[ j ] ) );
  29876. }
  29877. } else if ( index < nCachedObjects ) {
  29878. knownObject = objects[ index ];
  29879. // move existing object to the ACTIVE region
  29880. var firstActiveIndex = -- nCachedObjects,
  29881. lastCachedObject = objects[ firstActiveIndex ];
  29882. indicesByUUID[ lastCachedObject.uuid ] = index;
  29883. objects[ index ] = lastCachedObject;
  29884. indicesByUUID[ uuid ] = firstActiveIndex;
  29885. objects[ firstActiveIndex ] = object;
  29886. // accounting is done, now do the same for all bindings
  29887. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  29888. var bindingsForPath = bindings[ j ],
  29889. lastCached = bindingsForPath[ firstActiveIndex ],
  29890. binding = bindingsForPath[ index ];
  29891. bindingsForPath[ index ] = lastCached;
  29892. if ( binding === undefined ) {
  29893. // since we do not bother to create new bindings
  29894. // for objects that are cached, the binding may
  29895. // or may not exist
  29896. binding = new PropertyBinding( object, paths[ j ], parsedPaths[ j ] );
  29897. }
  29898. bindingsForPath[ firstActiveIndex ] = binding;
  29899. }
  29900. } else if ( objects[ index ] !== knownObject ) {
  29901. console.error( 'THREE.AnimationObjectGroup: Different objects with the same UUID ' +
  29902. 'detected. Clean the caches or recreate your infrastructure when reloading scenes.' );
  29903. } // else the object is already where we want it to be
  29904. } // for arguments
  29905. this.nCachedObjects_ = nCachedObjects;
  29906. },
  29907. remove: function () {
  29908. var objects = this._objects,
  29909. nCachedObjects = this.nCachedObjects_,
  29910. indicesByUUID = this._indicesByUUID,
  29911. bindings = this._bindings,
  29912. nBindings = bindings.length;
  29913. for ( var i = 0, n = arguments.length; i !== n; ++ i ) {
  29914. var object = arguments[ i ],
  29915. uuid = object.uuid,
  29916. index = indicesByUUID[ uuid ];
  29917. if ( index !== undefined && index >= nCachedObjects ) {
  29918. // move existing object into the CACHED region
  29919. var lastCachedIndex = nCachedObjects ++,
  29920. firstActiveObject = objects[ lastCachedIndex ];
  29921. indicesByUUID[ firstActiveObject.uuid ] = index;
  29922. objects[ index ] = firstActiveObject;
  29923. indicesByUUID[ uuid ] = lastCachedIndex;
  29924. objects[ lastCachedIndex ] = object;
  29925. // accounting is done, now do the same for all bindings
  29926. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  29927. var bindingsForPath = bindings[ j ],
  29928. firstActive = bindingsForPath[ lastCachedIndex ],
  29929. binding = bindingsForPath[ index ];
  29930. bindingsForPath[ index ] = firstActive;
  29931. bindingsForPath[ lastCachedIndex ] = binding;
  29932. }
  29933. }
  29934. } // for arguments
  29935. this.nCachedObjects_ = nCachedObjects;
  29936. },
  29937. // remove & forget
  29938. uncache: function () {
  29939. var objects = this._objects,
  29940. nObjects = objects.length,
  29941. nCachedObjects = this.nCachedObjects_,
  29942. indicesByUUID = this._indicesByUUID,
  29943. bindings = this._bindings,
  29944. nBindings = bindings.length;
  29945. for ( var i = 0, n = arguments.length; i !== n; ++ i ) {
  29946. var object = arguments[ i ],
  29947. uuid = object.uuid,
  29948. index = indicesByUUID[ uuid ];
  29949. if ( index !== undefined ) {
  29950. delete indicesByUUID[ uuid ];
  29951. if ( index < nCachedObjects ) {
  29952. // object is cached, shrink the CACHED region
  29953. var firstActiveIndex = -- nCachedObjects,
  29954. lastCachedObject = objects[ firstActiveIndex ],
  29955. lastIndex = -- nObjects,
  29956. lastObject = objects[ lastIndex ];
  29957. // last cached object takes this object's place
  29958. indicesByUUID[ lastCachedObject.uuid ] = index;
  29959. objects[ index ] = lastCachedObject;
  29960. // last object goes to the activated slot and pop
  29961. indicesByUUID[ lastObject.uuid ] = firstActiveIndex;
  29962. objects[ firstActiveIndex ] = lastObject;
  29963. objects.pop();
  29964. // accounting is done, now do the same for all bindings
  29965. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  29966. var bindingsForPath = bindings[ j ],
  29967. lastCached = bindingsForPath[ firstActiveIndex ],
  29968. last = bindingsForPath[ lastIndex ];
  29969. bindingsForPath[ index ] = lastCached;
  29970. bindingsForPath[ firstActiveIndex ] = last;
  29971. bindingsForPath.pop();
  29972. }
  29973. } else {
  29974. // object is active, just swap with the last and pop
  29975. var lastIndex = -- nObjects,
  29976. lastObject = objects[ lastIndex ];
  29977. indicesByUUID[ lastObject.uuid ] = index;
  29978. objects[ index ] = lastObject;
  29979. objects.pop();
  29980. // accounting is done, now do the same for all bindings
  29981. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  29982. var bindingsForPath = bindings[ j ];
  29983. bindingsForPath[ index ] = bindingsForPath[ lastIndex ];
  29984. bindingsForPath.pop();
  29985. }
  29986. } // cached or active
  29987. } // if object is known
  29988. } // for arguments
  29989. this.nCachedObjects_ = nCachedObjects;
  29990. },
  29991. // Internal interface used by befriended PropertyBinding.Composite:
  29992. subscribe_: function ( path, parsedPath ) {
  29993. // returns an array of bindings for the given path that is changed
  29994. // according to the contained objects in the group
  29995. var indicesByPath = this._bindingsIndicesByPath,
  29996. index = indicesByPath[ path ],
  29997. bindings = this._bindings;
  29998. if ( index !== undefined ) return bindings[ index ];
  29999. var paths = this._paths,
  30000. parsedPaths = this._parsedPaths,
  30001. objects = this._objects,
  30002. nObjects = objects.length,
  30003. nCachedObjects = this.nCachedObjects_,
  30004. bindingsForPath = new Array( nObjects );
  30005. index = bindings.length;
  30006. indicesByPath[ path ] = index;
  30007. paths.push( path );
  30008. parsedPaths.push( parsedPath );
  30009. bindings.push( bindingsForPath );
  30010. for ( var i = nCachedObjects, n = objects.length; i !== n; ++ i ) {
  30011. var object = objects[ i ];
  30012. bindingsForPath[ i ] = new PropertyBinding( object, path, parsedPath );
  30013. }
  30014. return bindingsForPath;
  30015. },
  30016. unsubscribe_: function ( path ) {
  30017. // tells the group to forget about a property path and no longer
  30018. // update the array previously obtained with 'subscribe_'
  30019. var indicesByPath = this._bindingsIndicesByPath,
  30020. index = indicesByPath[ path ];
  30021. if ( index !== undefined ) {
  30022. var paths = this._paths,
  30023. parsedPaths = this._parsedPaths,
  30024. bindings = this._bindings,
  30025. lastBindingsIndex = bindings.length - 1,
  30026. lastBindings = bindings[ lastBindingsIndex ],
  30027. lastBindingsPath = path[ lastBindingsIndex ];
  30028. indicesByPath[ lastBindingsPath ] = index;
  30029. bindings[ index ] = lastBindings;
  30030. bindings.pop();
  30031. parsedPaths[ index ] = parsedPaths[ lastBindingsIndex ];
  30032. parsedPaths.pop();
  30033. paths[ index ] = paths[ lastBindingsIndex ];
  30034. paths.pop();
  30035. }
  30036. }
  30037. } );
  30038. /**
  30039. *
  30040. * Action provided by AnimationMixer for scheduling clip playback on specific
  30041. * objects.
  30042. *
  30043. * @author Ben Houston / http://clara.io/
  30044. * @author David Sarno / http://lighthaus.us/
  30045. * @author tschw
  30046. *
  30047. */
  30048. function AnimationAction( mixer, clip, localRoot ) {
  30049. this._mixer = mixer;
  30050. this._clip = clip;
  30051. this._localRoot = localRoot || null;
  30052. var tracks = clip.tracks,
  30053. nTracks = tracks.length,
  30054. interpolants = new Array( nTracks );
  30055. var interpolantSettings = {
  30056. endingStart: ZeroCurvatureEnding,
  30057. endingEnd: ZeroCurvatureEnding
  30058. };
  30059. for ( var i = 0; i !== nTracks; ++ i ) {
  30060. var interpolant = tracks[ i ].createInterpolant( null );
  30061. interpolants[ i ] = interpolant;
  30062. interpolant.settings = interpolantSettings;
  30063. }
  30064. this._interpolantSettings = interpolantSettings;
  30065. this._interpolants = interpolants; // bound by the mixer
  30066. // inside: PropertyMixer (managed by the mixer)
  30067. this._propertyBindings = new Array( nTracks );
  30068. this._cacheIndex = null; // for the memory manager
  30069. this._byClipCacheIndex = null; // for the memory manager
  30070. this._timeScaleInterpolant = null;
  30071. this._weightInterpolant = null;
  30072. this.loop = LoopRepeat;
  30073. this._loopCount = - 1;
  30074. // global mixer time when the action is to be started
  30075. // it's set back to 'null' upon start of the action
  30076. this._startTime = null;
  30077. // scaled local time of the action
  30078. // gets clamped or wrapped to 0..clip.duration according to loop
  30079. this.time = 0;
  30080. this.timeScale = 1;
  30081. this._effectiveTimeScale = 1;
  30082. this.weight = 1;
  30083. this._effectiveWeight = 1;
  30084. this.repetitions = Infinity; // no. of repetitions when looping
  30085. this.paused = false; // true -> zero effective time scale
  30086. this.enabled = true; // false -> zero effective weight
  30087. this.clampWhenFinished = false;// keep feeding the last frame?
  30088. this.zeroSlopeAtStart = true;// for smooth interpolation w/o separate
  30089. this.zeroSlopeAtEnd = true;// clips for start, loop and end
  30090. }
  30091. Object.assign( AnimationAction.prototype, {
  30092. // State & Scheduling
  30093. play: function () {
  30094. this._mixer._activateAction( this );
  30095. return this;
  30096. },
  30097. stop: function () {
  30098. this._mixer._deactivateAction( this );
  30099. return this.reset();
  30100. },
  30101. reset: function () {
  30102. this.paused = false;
  30103. this.enabled = true;
  30104. this.time = 0; // restart clip
  30105. this._loopCount = - 1;// forget previous loops
  30106. this._startTime = null;// forget scheduling
  30107. return this.stopFading().stopWarping();
  30108. },
  30109. isRunning: function () {
  30110. return this.enabled && ! this.paused && this.timeScale !== 0 &&
  30111. this._startTime === null && this._mixer._isActiveAction( this );
  30112. },
  30113. // return true when play has been called
  30114. isScheduled: function () {
  30115. return this._mixer._isActiveAction( this );
  30116. },
  30117. startAt: function ( time ) {
  30118. this._startTime = time;
  30119. return this;
  30120. },
  30121. setLoop: function ( mode, repetitions ) {
  30122. this.loop = mode;
  30123. this.repetitions = repetitions;
  30124. return this;
  30125. },
  30126. // Weight
  30127. // set the weight stopping any scheduled fading
  30128. // although .enabled = false yields an effective weight of zero, this
  30129. // method does *not* change .enabled, because it would be confusing
  30130. setEffectiveWeight: function ( weight ) {
  30131. this.weight = weight;
  30132. // note: same logic as when updated at runtime
  30133. this._effectiveWeight = this.enabled ? weight : 0;
  30134. return this.stopFading();
  30135. },
  30136. // return the weight considering fading and .enabled
  30137. getEffectiveWeight: function () {
  30138. return this._effectiveWeight;
  30139. },
  30140. fadeIn: function ( duration ) {
  30141. return this._scheduleFading( duration, 0, 1 );
  30142. },
  30143. fadeOut: function ( duration ) {
  30144. return this._scheduleFading( duration, 1, 0 );
  30145. },
  30146. crossFadeFrom: function ( fadeOutAction, duration, warp ) {
  30147. fadeOutAction.fadeOut( duration );
  30148. this.fadeIn( duration );
  30149. if ( warp ) {
  30150. var fadeInDuration = this._clip.duration,
  30151. fadeOutDuration = fadeOutAction._clip.duration,
  30152. startEndRatio = fadeOutDuration / fadeInDuration,
  30153. endStartRatio = fadeInDuration / fadeOutDuration;
  30154. fadeOutAction.warp( 1.0, startEndRatio, duration );
  30155. this.warp( endStartRatio, 1.0, duration );
  30156. }
  30157. return this;
  30158. },
  30159. crossFadeTo: function ( fadeInAction, duration, warp ) {
  30160. return fadeInAction.crossFadeFrom( this, duration, warp );
  30161. },
  30162. stopFading: function () {
  30163. var weightInterpolant = this._weightInterpolant;
  30164. if ( weightInterpolant !== null ) {
  30165. this._weightInterpolant = null;
  30166. this._mixer._takeBackControlInterpolant( weightInterpolant );
  30167. }
  30168. return this;
  30169. },
  30170. // Time Scale Control
  30171. // set the time scale stopping any scheduled warping
  30172. // although .paused = true yields an effective time scale of zero, this
  30173. // method does *not* change .paused, because it would be confusing
  30174. setEffectiveTimeScale: function ( timeScale ) {
  30175. this.timeScale = timeScale;
  30176. this._effectiveTimeScale = this.paused ? 0 : timeScale;
  30177. return this.stopWarping();
  30178. },
  30179. // return the time scale considering warping and .paused
  30180. getEffectiveTimeScale: function () {
  30181. return this._effectiveTimeScale;
  30182. },
  30183. setDuration: function ( duration ) {
  30184. this.timeScale = this._clip.duration / duration;
  30185. return this.stopWarping();
  30186. },
  30187. syncWith: function ( action ) {
  30188. this.time = action.time;
  30189. this.timeScale = action.timeScale;
  30190. return this.stopWarping();
  30191. },
  30192. halt: function ( duration ) {
  30193. return this.warp( this._effectiveTimeScale, 0, duration );
  30194. },
  30195. warp: function ( startTimeScale, endTimeScale, duration ) {
  30196. var mixer = this._mixer, now = mixer.time,
  30197. interpolant = this._timeScaleInterpolant,
  30198. timeScale = this.timeScale;
  30199. if ( interpolant === null ) {
  30200. interpolant = mixer._lendControlInterpolant();
  30201. this._timeScaleInterpolant = interpolant;
  30202. }
  30203. var times = interpolant.parameterPositions,
  30204. values = interpolant.sampleValues;
  30205. times[ 0 ] = now;
  30206. times[ 1 ] = now + duration;
  30207. values[ 0 ] = startTimeScale / timeScale;
  30208. values[ 1 ] = endTimeScale / timeScale;
  30209. return this;
  30210. },
  30211. stopWarping: function () {
  30212. var timeScaleInterpolant = this._timeScaleInterpolant;
  30213. if ( timeScaleInterpolant !== null ) {
  30214. this._timeScaleInterpolant = null;
  30215. this._mixer._takeBackControlInterpolant( timeScaleInterpolant );
  30216. }
  30217. return this;
  30218. },
  30219. // Object Accessors
  30220. getMixer: function () {
  30221. return this._mixer;
  30222. },
  30223. getClip: function () {
  30224. return this._clip;
  30225. },
  30226. getRoot: function () {
  30227. return this._localRoot || this._mixer._root;
  30228. },
  30229. // Interna
  30230. _update: function ( time, deltaTime, timeDirection, accuIndex ) {
  30231. // called by the mixer
  30232. if ( ! this.enabled ) {
  30233. // call ._updateWeight() to update ._effectiveWeight
  30234. this._updateWeight( time );
  30235. return;
  30236. }
  30237. var startTime = this._startTime;
  30238. if ( startTime !== null ) {
  30239. // check for scheduled start of action
  30240. var timeRunning = ( time - startTime ) * timeDirection;
  30241. if ( timeRunning < 0 || timeDirection === 0 ) {
  30242. return; // yet to come / don't decide when delta = 0
  30243. }
  30244. // start
  30245. this._startTime = null; // unschedule
  30246. deltaTime = timeDirection * timeRunning;
  30247. }
  30248. // apply time scale and advance time
  30249. deltaTime *= this._updateTimeScale( time );
  30250. var clipTime = this._updateTime( deltaTime );
  30251. // note: _updateTime may disable the action resulting in
  30252. // an effective weight of 0
  30253. var weight = this._updateWeight( time );
  30254. if ( weight > 0 ) {
  30255. var interpolants = this._interpolants;
  30256. var propertyMixers = this._propertyBindings;
  30257. for ( var j = 0, m = interpolants.length; j !== m; ++ j ) {
  30258. interpolants[ j ].evaluate( clipTime );
  30259. propertyMixers[ j ].accumulate( accuIndex, weight );
  30260. }
  30261. }
  30262. },
  30263. _updateWeight: function ( time ) {
  30264. var weight = 0;
  30265. if ( this.enabled ) {
  30266. weight = this.weight;
  30267. var interpolant = this._weightInterpolant;
  30268. if ( interpolant !== null ) {
  30269. var interpolantValue = interpolant.evaluate( time )[ 0 ];
  30270. weight *= interpolantValue;
  30271. if ( time > interpolant.parameterPositions[ 1 ] ) {
  30272. this.stopFading();
  30273. if ( interpolantValue === 0 ) {
  30274. // faded out, disable
  30275. this.enabled = false;
  30276. }
  30277. }
  30278. }
  30279. }
  30280. this._effectiveWeight = weight;
  30281. return weight;
  30282. },
  30283. _updateTimeScale: function ( time ) {
  30284. var timeScale = 0;
  30285. if ( ! this.paused ) {
  30286. timeScale = this.timeScale;
  30287. var interpolant = this._timeScaleInterpolant;
  30288. if ( interpolant !== null ) {
  30289. var interpolantValue = interpolant.evaluate( time )[ 0 ];
  30290. timeScale *= interpolantValue;
  30291. if ( time > interpolant.parameterPositions[ 1 ] ) {
  30292. this.stopWarping();
  30293. if ( timeScale === 0 ) {
  30294. // motion has halted, pause
  30295. this.paused = true;
  30296. } else {
  30297. // warp done - apply final time scale
  30298. this.timeScale = timeScale;
  30299. }
  30300. }
  30301. }
  30302. }
  30303. this._effectiveTimeScale = timeScale;
  30304. return timeScale;
  30305. },
  30306. _updateTime: function ( deltaTime ) {
  30307. var time = this.time + deltaTime;
  30308. var duration = this._clip.duration;
  30309. var loop = this.loop;
  30310. var loopCount = this._loopCount;
  30311. var pingPong = ( loop === LoopPingPong );
  30312. if ( deltaTime === 0 ) {
  30313. if ( loopCount === - 1 ) return time;
  30314. return ( pingPong && ( loopCount & 1 ) === 1 ) ? duration - time : time;
  30315. }
  30316. if ( loop === LoopOnce ) {
  30317. if ( loopCount === - 1 ) {
  30318. // just started
  30319. this._loopCount = 0;
  30320. this._setEndings( true, true, false );
  30321. }
  30322. handle_stop: {
  30323. if ( time >= duration ) {
  30324. time = duration;
  30325. } else if ( time < 0 ) {
  30326. time = 0;
  30327. } else break handle_stop;
  30328. if ( this.clampWhenFinished ) this.paused = true;
  30329. else this.enabled = false;
  30330. this._mixer.dispatchEvent( {
  30331. type: 'finished', action: this,
  30332. direction: deltaTime < 0 ? - 1 : 1
  30333. } );
  30334. }
  30335. } else { // repetitive Repeat or PingPong
  30336. if ( loopCount === - 1 ) {
  30337. // just started
  30338. if ( deltaTime >= 0 ) {
  30339. loopCount = 0;
  30340. this._setEndings( true, this.repetitions === 0, pingPong );
  30341. } else {
  30342. // when looping in reverse direction, the initial
  30343. // transition through zero counts as a repetition,
  30344. // so leave loopCount at -1
  30345. this._setEndings( this.repetitions === 0, true, pingPong );
  30346. }
  30347. }
  30348. if ( time >= duration || time < 0 ) {
  30349. // wrap around
  30350. var loopDelta = Math.floor( time / duration ); // signed
  30351. time -= duration * loopDelta;
  30352. loopCount += Math.abs( loopDelta );
  30353. var pending = this.repetitions - loopCount;
  30354. if ( pending <= 0 ) {
  30355. // have to stop (switch state, clamp time, fire event)
  30356. if ( this.clampWhenFinished ) this.paused = true;
  30357. else this.enabled = false;
  30358. time = deltaTime > 0 ? duration : 0;
  30359. this._mixer.dispatchEvent( {
  30360. type: 'finished', action: this,
  30361. direction: deltaTime > 0 ? 1 : - 1
  30362. } );
  30363. } else {
  30364. // keep running
  30365. if ( pending === 1 ) {
  30366. // entering the last round
  30367. var atStart = deltaTime < 0;
  30368. this._setEndings( atStart, ! atStart, pingPong );
  30369. } else {
  30370. this._setEndings( false, false, pingPong );
  30371. }
  30372. this._loopCount = loopCount;
  30373. this._mixer.dispatchEvent( {
  30374. type: 'loop', action: this, loopDelta: loopDelta
  30375. } );
  30376. }
  30377. }
  30378. if ( pingPong && ( loopCount & 1 ) === 1 ) {
  30379. // invert time for the "pong round"
  30380. this.time = time;
  30381. return duration - time;
  30382. }
  30383. }
  30384. this.time = time;
  30385. return time;
  30386. },
  30387. _setEndings: function ( atStart, atEnd, pingPong ) {
  30388. var settings = this._interpolantSettings;
  30389. if ( pingPong ) {
  30390. settings.endingStart = ZeroSlopeEnding;
  30391. settings.endingEnd = ZeroSlopeEnding;
  30392. } else {
  30393. // assuming for LoopOnce atStart == atEnd == true
  30394. if ( atStart ) {
  30395. settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding;
  30396. } else {
  30397. settings.endingStart = WrapAroundEnding;
  30398. }
  30399. if ( atEnd ) {
  30400. settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding;
  30401. } else {
  30402. settings.endingEnd = WrapAroundEnding;
  30403. }
  30404. }
  30405. },
  30406. _scheduleFading: function ( duration, weightNow, weightThen ) {
  30407. var mixer = this._mixer, now = mixer.time,
  30408. interpolant = this._weightInterpolant;
  30409. if ( interpolant === null ) {
  30410. interpolant = mixer._lendControlInterpolant();
  30411. this._weightInterpolant = interpolant;
  30412. }
  30413. var times = interpolant.parameterPositions,
  30414. values = interpolant.sampleValues;
  30415. times[ 0 ] = now;
  30416. values[ 0 ] = weightNow;
  30417. times[ 1 ] = now + duration;
  30418. values[ 1 ] = weightThen;
  30419. return this;
  30420. }
  30421. } );
  30422. /**
  30423. *
  30424. * Player for AnimationClips.
  30425. *
  30426. *
  30427. * @author Ben Houston / http://clara.io/
  30428. * @author David Sarno / http://lighthaus.us/
  30429. * @author tschw
  30430. */
  30431. function AnimationMixer( root ) {
  30432. this._root = root;
  30433. this._initMemoryManager();
  30434. this._accuIndex = 0;
  30435. this.time = 0;
  30436. this.timeScale = 1.0;
  30437. }
  30438. AnimationMixer.prototype = Object.assign( Object.create( EventDispatcher.prototype ), {
  30439. constructor: AnimationMixer,
  30440. _bindAction: function ( action, prototypeAction ) {
  30441. var root = action._localRoot || this._root,
  30442. tracks = action._clip.tracks,
  30443. nTracks = tracks.length,
  30444. bindings = action._propertyBindings,
  30445. interpolants = action._interpolants,
  30446. rootUuid = root.uuid,
  30447. bindingsByRoot = this._bindingsByRootAndName,
  30448. bindingsByName = bindingsByRoot[ rootUuid ];
  30449. if ( bindingsByName === undefined ) {
  30450. bindingsByName = {};
  30451. bindingsByRoot[ rootUuid ] = bindingsByName;
  30452. }
  30453. for ( var i = 0; i !== nTracks; ++ i ) {
  30454. var track = tracks[ i ],
  30455. trackName = track.name,
  30456. binding = bindingsByName[ trackName ];
  30457. if ( binding !== undefined ) {
  30458. bindings[ i ] = binding;
  30459. } else {
  30460. binding = bindings[ i ];
  30461. if ( binding !== undefined ) {
  30462. // existing binding, make sure the cache knows
  30463. if ( binding._cacheIndex === null ) {
  30464. ++ binding.referenceCount;
  30465. this._addInactiveBinding( binding, rootUuid, trackName );
  30466. }
  30467. continue;
  30468. }
  30469. var path = prototypeAction && prototypeAction.
  30470. _propertyBindings[ i ].binding.parsedPath;
  30471. binding = new PropertyMixer(
  30472. PropertyBinding.create( root, trackName, path ),
  30473. track.ValueTypeName, track.getValueSize() );
  30474. ++ binding.referenceCount;
  30475. this._addInactiveBinding( binding, rootUuid, trackName );
  30476. bindings[ i ] = binding;
  30477. }
  30478. interpolants[ i ].resultBuffer = binding.buffer;
  30479. }
  30480. },
  30481. _activateAction: function ( action ) {
  30482. if ( ! this._isActiveAction( action ) ) {
  30483. if ( action._cacheIndex === null ) {
  30484. // this action has been forgotten by the cache, but the user
  30485. // appears to be still using it -> rebind
  30486. var rootUuid = ( action._localRoot || this._root ).uuid,
  30487. clipUuid = action._clip.uuid,
  30488. actionsForClip = this._actionsByClip[ clipUuid ];
  30489. this._bindAction( action,
  30490. actionsForClip && actionsForClip.knownActions[ 0 ] );
  30491. this._addInactiveAction( action, clipUuid, rootUuid );
  30492. }
  30493. var bindings = action._propertyBindings;
  30494. // increment reference counts / sort out state
  30495. for ( var i = 0, n = bindings.length; i !== n; ++ i ) {
  30496. var binding = bindings[ i ];
  30497. if ( binding.useCount ++ === 0 ) {
  30498. this._lendBinding( binding );
  30499. binding.saveOriginalState();
  30500. }
  30501. }
  30502. this._lendAction( action );
  30503. }
  30504. },
  30505. _deactivateAction: function ( action ) {
  30506. if ( this._isActiveAction( action ) ) {
  30507. var bindings = action._propertyBindings;
  30508. // decrement reference counts / sort out state
  30509. for ( var i = 0, n = bindings.length; i !== n; ++ i ) {
  30510. var binding = bindings[ i ];
  30511. if ( -- binding.useCount === 0 ) {
  30512. binding.restoreOriginalState();
  30513. this._takeBackBinding( binding );
  30514. }
  30515. }
  30516. this._takeBackAction( action );
  30517. }
  30518. },
  30519. // Memory manager
  30520. _initMemoryManager: function () {
  30521. this._actions = []; // 'nActiveActions' followed by inactive ones
  30522. this._nActiveActions = 0;
  30523. this._actionsByClip = {};
  30524. // inside:
  30525. // {
  30526. // knownActions: Array< AnimationAction > - used as prototypes
  30527. // actionByRoot: AnimationAction - lookup
  30528. // }
  30529. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  30530. this._nActiveBindings = 0;
  30531. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  30532. this._controlInterpolants = []; // same game as above
  30533. this._nActiveControlInterpolants = 0;
  30534. var scope = this;
  30535. this.stats = {
  30536. actions: {
  30537. get total() {
  30538. return scope._actions.length;
  30539. },
  30540. get inUse() {
  30541. return scope._nActiveActions;
  30542. }
  30543. },
  30544. bindings: {
  30545. get total() {
  30546. return scope._bindings.length;
  30547. },
  30548. get inUse() {
  30549. return scope._nActiveBindings;
  30550. }
  30551. },
  30552. controlInterpolants: {
  30553. get total() {
  30554. return scope._controlInterpolants.length;
  30555. },
  30556. get inUse() {
  30557. return scope._nActiveControlInterpolants;
  30558. }
  30559. }
  30560. };
  30561. },
  30562. // Memory management for AnimationAction objects
  30563. _isActiveAction: function ( action ) {
  30564. var index = action._cacheIndex;
  30565. return index !== null && index < this._nActiveActions;
  30566. },
  30567. _addInactiveAction: function ( action, clipUuid, rootUuid ) {
  30568. var actions = this._actions,
  30569. actionsByClip = this._actionsByClip,
  30570. actionsForClip = actionsByClip[ clipUuid ];
  30571. if ( actionsForClip === undefined ) {
  30572. actionsForClip = {
  30573. knownActions: [ action ],
  30574. actionByRoot: {}
  30575. };
  30576. action._byClipCacheIndex = 0;
  30577. actionsByClip[ clipUuid ] = actionsForClip;
  30578. } else {
  30579. var knownActions = actionsForClip.knownActions;
  30580. action._byClipCacheIndex = knownActions.length;
  30581. knownActions.push( action );
  30582. }
  30583. action._cacheIndex = actions.length;
  30584. actions.push( action );
  30585. actionsForClip.actionByRoot[ rootUuid ] = action;
  30586. },
  30587. _removeInactiveAction: function ( action ) {
  30588. var actions = this._actions,
  30589. lastInactiveAction = actions[ actions.length - 1 ],
  30590. cacheIndex = action._cacheIndex;
  30591. lastInactiveAction._cacheIndex = cacheIndex;
  30592. actions[ cacheIndex ] = lastInactiveAction;
  30593. actions.pop();
  30594. action._cacheIndex = null;
  30595. var clipUuid = action._clip.uuid,
  30596. actionsByClip = this._actionsByClip,
  30597. actionsForClip = actionsByClip[ clipUuid ],
  30598. knownActionsForClip = actionsForClip.knownActions,
  30599. lastKnownAction =
  30600. knownActionsForClip[ knownActionsForClip.length - 1 ],
  30601. byClipCacheIndex = action._byClipCacheIndex;
  30602. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  30603. knownActionsForClip[ byClipCacheIndex ] = lastKnownAction;
  30604. knownActionsForClip.pop();
  30605. action._byClipCacheIndex = null;
  30606. var actionByRoot = actionsForClip.actionByRoot,
  30607. rootUuid = ( action._localRoot || this._root ).uuid;
  30608. delete actionByRoot[ rootUuid ];
  30609. if ( knownActionsForClip.length === 0 ) {
  30610. delete actionsByClip[ clipUuid ];
  30611. }
  30612. this._removeInactiveBindingsForAction( action );
  30613. },
  30614. _removeInactiveBindingsForAction: function ( action ) {
  30615. var bindings = action._propertyBindings;
  30616. for ( var i = 0, n = bindings.length; i !== n; ++ i ) {
  30617. var binding = bindings[ i ];
  30618. if ( -- binding.referenceCount === 0 ) {
  30619. this._removeInactiveBinding( binding );
  30620. }
  30621. }
  30622. },
  30623. _lendAction: function ( action ) {
  30624. // [ active actions | inactive actions ]
  30625. // [ active actions >| inactive actions ]
  30626. // s a
  30627. // <-swap->
  30628. // a s
  30629. var actions = this._actions,
  30630. prevIndex = action._cacheIndex,
  30631. lastActiveIndex = this._nActiveActions ++,
  30632. firstInactiveAction = actions[ lastActiveIndex ];
  30633. action._cacheIndex = lastActiveIndex;
  30634. actions[ lastActiveIndex ] = action;
  30635. firstInactiveAction._cacheIndex = prevIndex;
  30636. actions[ prevIndex ] = firstInactiveAction;
  30637. },
  30638. _takeBackAction: function ( action ) {
  30639. // [ active actions | inactive actions ]
  30640. // [ active actions |< inactive actions ]
  30641. // a s
  30642. // <-swap->
  30643. // s a
  30644. var actions = this._actions,
  30645. prevIndex = action._cacheIndex,
  30646. firstInactiveIndex = -- this._nActiveActions,
  30647. lastActiveAction = actions[ firstInactiveIndex ];
  30648. action._cacheIndex = firstInactiveIndex;
  30649. actions[ firstInactiveIndex ] = action;
  30650. lastActiveAction._cacheIndex = prevIndex;
  30651. actions[ prevIndex ] = lastActiveAction;
  30652. },
  30653. // Memory management for PropertyMixer objects
  30654. _addInactiveBinding: function ( binding, rootUuid, trackName ) {
  30655. var bindingsByRoot = this._bindingsByRootAndName,
  30656. bindingByName = bindingsByRoot[ rootUuid ],
  30657. bindings = this._bindings;
  30658. if ( bindingByName === undefined ) {
  30659. bindingByName = {};
  30660. bindingsByRoot[ rootUuid ] = bindingByName;
  30661. }
  30662. bindingByName[ trackName ] = binding;
  30663. binding._cacheIndex = bindings.length;
  30664. bindings.push( binding );
  30665. },
  30666. _removeInactiveBinding: function ( binding ) {
  30667. var bindings = this._bindings,
  30668. propBinding = binding.binding,
  30669. rootUuid = propBinding.rootNode.uuid,
  30670. trackName = propBinding.path,
  30671. bindingsByRoot = this._bindingsByRootAndName,
  30672. bindingByName = bindingsByRoot[ rootUuid ],
  30673. lastInactiveBinding = bindings[ bindings.length - 1 ],
  30674. cacheIndex = binding._cacheIndex;
  30675. lastInactiveBinding._cacheIndex = cacheIndex;
  30676. bindings[ cacheIndex ] = lastInactiveBinding;
  30677. bindings.pop();
  30678. delete bindingByName[ trackName ];
  30679. remove_empty_map: {
  30680. for ( var _ in bindingByName ) break remove_empty_map; // eslint-disable-line no-unused-vars
  30681. delete bindingsByRoot[ rootUuid ];
  30682. }
  30683. },
  30684. _lendBinding: function ( binding ) {
  30685. var bindings = this._bindings,
  30686. prevIndex = binding._cacheIndex,
  30687. lastActiveIndex = this._nActiveBindings ++,
  30688. firstInactiveBinding = bindings[ lastActiveIndex ];
  30689. binding._cacheIndex = lastActiveIndex;
  30690. bindings[ lastActiveIndex ] = binding;
  30691. firstInactiveBinding._cacheIndex = prevIndex;
  30692. bindings[ prevIndex ] = firstInactiveBinding;
  30693. },
  30694. _takeBackBinding: function ( binding ) {
  30695. var bindings = this._bindings,
  30696. prevIndex = binding._cacheIndex,
  30697. firstInactiveIndex = -- this._nActiveBindings,
  30698. lastActiveBinding = bindings[ firstInactiveIndex ];
  30699. binding._cacheIndex = firstInactiveIndex;
  30700. bindings[ firstInactiveIndex ] = binding;
  30701. lastActiveBinding._cacheIndex = prevIndex;
  30702. bindings[ prevIndex ] = lastActiveBinding;
  30703. },
  30704. // Memory management of Interpolants for weight and time scale
  30705. _lendControlInterpolant: function () {
  30706. var interpolants = this._controlInterpolants,
  30707. lastActiveIndex = this._nActiveControlInterpolants ++,
  30708. interpolant = interpolants[ lastActiveIndex ];
  30709. if ( interpolant === undefined ) {
  30710. interpolant = new LinearInterpolant(
  30711. new Float32Array( 2 ), new Float32Array( 2 ),
  30712. 1, this._controlInterpolantsResultBuffer );
  30713. interpolant.__cacheIndex = lastActiveIndex;
  30714. interpolants[ lastActiveIndex ] = interpolant;
  30715. }
  30716. return interpolant;
  30717. },
  30718. _takeBackControlInterpolant: function ( interpolant ) {
  30719. var interpolants = this._controlInterpolants,
  30720. prevIndex = interpolant.__cacheIndex,
  30721. firstInactiveIndex = -- this._nActiveControlInterpolants,
  30722. lastActiveInterpolant = interpolants[ firstInactiveIndex ];
  30723. interpolant.__cacheIndex = firstInactiveIndex;
  30724. interpolants[ firstInactiveIndex ] = interpolant;
  30725. lastActiveInterpolant.__cacheIndex = prevIndex;
  30726. interpolants[ prevIndex ] = lastActiveInterpolant;
  30727. },
  30728. _controlInterpolantsResultBuffer: new Float32Array( 1 ),
  30729. // return an action for a clip optionally using a custom root target
  30730. // object (this method allocates a lot of dynamic memory in case a
  30731. // previously unknown clip/root combination is specified)
  30732. clipAction: function ( clip, optionalRoot ) {
  30733. var root = optionalRoot || this._root,
  30734. rootUuid = root.uuid,
  30735. clipObject = typeof clip === 'string' ?
  30736. AnimationClip.findByName( root, clip ) : clip,
  30737. clipUuid = clipObject !== null ? clipObject.uuid : clip,
  30738. actionsForClip = this._actionsByClip[ clipUuid ],
  30739. prototypeAction = null;
  30740. if ( actionsForClip !== undefined ) {
  30741. var existingAction =
  30742. actionsForClip.actionByRoot[ rootUuid ];
  30743. if ( existingAction !== undefined ) {
  30744. return existingAction;
  30745. }
  30746. // we know the clip, so we don't have to parse all
  30747. // the bindings again but can just copy
  30748. prototypeAction = actionsForClip.knownActions[ 0 ];
  30749. // also, take the clip from the prototype action
  30750. if ( clipObject === null )
  30751. clipObject = prototypeAction._clip;
  30752. }
  30753. // clip must be known when specified via string
  30754. if ( clipObject === null ) return null;
  30755. // allocate all resources required to run it
  30756. var newAction = new AnimationAction( this, clipObject, optionalRoot );
  30757. this._bindAction( newAction, prototypeAction );
  30758. // and make the action known to the memory manager
  30759. this._addInactiveAction( newAction, clipUuid, rootUuid );
  30760. return newAction;
  30761. },
  30762. // get an existing action
  30763. existingAction: function ( clip, optionalRoot ) {
  30764. var root = optionalRoot || this._root,
  30765. rootUuid = root.uuid,
  30766. clipObject = typeof clip === 'string' ?
  30767. AnimationClip.findByName( root, clip ) : clip,
  30768. clipUuid = clipObject ? clipObject.uuid : clip,
  30769. actionsForClip = this._actionsByClip[ clipUuid ];
  30770. if ( actionsForClip !== undefined ) {
  30771. return actionsForClip.actionByRoot[ rootUuid ] || null;
  30772. }
  30773. return null;
  30774. },
  30775. // deactivates all previously scheduled actions
  30776. stopAllAction: function () {
  30777. var actions = this._actions,
  30778. nActions = this._nActiveActions,
  30779. bindings = this._bindings,
  30780. nBindings = this._nActiveBindings;
  30781. this._nActiveActions = 0;
  30782. this._nActiveBindings = 0;
  30783. for ( var i = 0; i !== nActions; ++ i ) {
  30784. actions[ i ].reset();
  30785. }
  30786. for ( var i = 0; i !== nBindings; ++ i ) {
  30787. bindings[ i ].useCount = 0;
  30788. }
  30789. return this;
  30790. },
  30791. // advance the time and update apply the animation
  30792. update: function ( deltaTime ) {
  30793. deltaTime *= this.timeScale;
  30794. var actions = this._actions,
  30795. nActions = this._nActiveActions,
  30796. time = this.time += deltaTime,
  30797. timeDirection = Math.sign( deltaTime ),
  30798. accuIndex = this._accuIndex ^= 1;
  30799. // run active actions
  30800. for ( var i = 0; i !== nActions; ++ i ) {
  30801. var action = actions[ i ];
  30802. action._update( time, deltaTime, timeDirection, accuIndex );
  30803. }
  30804. // update scene graph
  30805. var bindings = this._bindings,
  30806. nBindings = this._nActiveBindings;
  30807. for ( var i = 0; i !== nBindings; ++ i ) {
  30808. bindings[ i ].apply( accuIndex );
  30809. }
  30810. return this;
  30811. },
  30812. // return this mixer's root target object
  30813. getRoot: function () {
  30814. return this._root;
  30815. },
  30816. // free all resources specific to a particular clip
  30817. uncacheClip: function ( clip ) {
  30818. var actions = this._actions,
  30819. clipUuid = clip.uuid,
  30820. actionsByClip = this._actionsByClip,
  30821. actionsForClip = actionsByClip[ clipUuid ];
  30822. if ( actionsForClip !== undefined ) {
  30823. // note: just calling _removeInactiveAction would mess up the
  30824. // iteration state and also require updating the state we can
  30825. // just throw away
  30826. var actionsToRemove = actionsForClip.knownActions;
  30827. for ( var i = 0, n = actionsToRemove.length; i !== n; ++ i ) {
  30828. var action = actionsToRemove[ i ];
  30829. this._deactivateAction( action );
  30830. var cacheIndex = action._cacheIndex,
  30831. lastInactiveAction = actions[ actions.length - 1 ];
  30832. action._cacheIndex = null;
  30833. action._byClipCacheIndex = null;
  30834. lastInactiveAction._cacheIndex = cacheIndex;
  30835. actions[ cacheIndex ] = lastInactiveAction;
  30836. actions.pop();
  30837. this._removeInactiveBindingsForAction( action );
  30838. }
  30839. delete actionsByClip[ clipUuid ];
  30840. }
  30841. },
  30842. // free all resources specific to a particular root target object
  30843. uncacheRoot: function ( root ) {
  30844. var rootUuid = root.uuid,
  30845. actionsByClip = this._actionsByClip;
  30846. for ( var clipUuid in actionsByClip ) {
  30847. var actionByRoot = actionsByClip[ clipUuid ].actionByRoot,
  30848. action = actionByRoot[ rootUuid ];
  30849. if ( action !== undefined ) {
  30850. this._deactivateAction( action );
  30851. this._removeInactiveAction( action );
  30852. }
  30853. }
  30854. var bindingsByRoot = this._bindingsByRootAndName,
  30855. bindingByName = bindingsByRoot[ rootUuid ];
  30856. if ( bindingByName !== undefined ) {
  30857. for ( var trackName in bindingByName ) {
  30858. var binding = bindingByName[ trackName ];
  30859. binding.restoreOriginalState();
  30860. this._removeInactiveBinding( binding );
  30861. }
  30862. }
  30863. },
  30864. // remove a targeted clip from the cache
  30865. uncacheAction: function ( clip, optionalRoot ) {
  30866. var action = this.existingAction( clip, optionalRoot );
  30867. if ( action !== null ) {
  30868. this._deactivateAction( action );
  30869. this._removeInactiveAction( action );
  30870. }
  30871. }
  30872. } );
  30873. /**
  30874. * @author mrdoob / http://mrdoob.com/
  30875. */
  30876. function Uniform( value ) {
  30877. if ( typeof value === 'string' ) {
  30878. console.warn( 'THREE.Uniform: Type parameter is no longer needed.' );
  30879. value = arguments[ 1 ];
  30880. }
  30881. this.value = value;
  30882. }
  30883. Uniform.prototype.clone = function () {
  30884. return new Uniform( this.value.clone === undefined ? this.value : this.value.clone() );
  30885. };
  30886. /**
  30887. * @author benaadams / https://twitter.com/ben_a_adams
  30888. */
  30889. function InstancedBufferGeometry() {
  30890. BufferGeometry.call( this );
  30891. this.type = 'InstancedBufferGeometry';
  30892. this.maxInstancedCount = undefined;
  30893. }
  30894. InstancedBufferGeometry.prototype = Object.assign( Object.create( BufferGeometry.prototype ), {
  30895. constructor: InstancedBufferGeometry,
  30896. isInstancedBufferGeometry: true,
  30897. copy: function ( source ) {
  30898. BufferGeometry.prototype.copy.call( this, source );
  30899. this.maxInstancedCount = source.maxInstancedCount;
  30900. return this;
  30901. },
  30902. clone: function () {
  30903. return new this.constructor().copy( this );
  30904. }
  30905. } );
  30906. /**
  30907. * @author benaadams / https://twitter.com/ben_a_adams
  30908. */
  30909. function InstancedInterleavedBuffer( array, stride, meshPerAttribute ) {
  30910. InterleavedBuffer.call( this, array, stride );
  30911. this.meshPerAttribute = meshPerAttribute || 1;
  30912. }
  30913. InstancedInterleavedBuffer.prototype = Object.assign( Object.create( InterleavedBuffer.prototype ), {
  30914. constructor: InstancedInterleavedBuffer,
  30915. isInstancedInterleavedBuffer: true,
  30916. copy: function ( source ) {
  30917. InterleavedBuffer.prototype.copy.call( this, source );
  30918. this.meshPerAttribute = source.meshPerAttribute;
  30919. return this;
  30920. }
  30921. } );
  30922. /**
  30923. * @author benaadams / https://twitter.com/ben_a_adams
  30924. */
  30925. function InstancedBufferAttribute( array, itemSize, normalized, meshPerAttribute ) {
  30926. if ( typeof ( normalized ) === 'number' ) {
  30927. meshPerAttribute = normalized;
  30928. normalized = false;
  30929. console.error( 'THREE.InstancedBufferAttribute: The constructor now expects normalized as the third argument.' );
  30930. }
  30931. BufferAttribute.call( this, array, itemSize, normalized );
  30932. this.meshPerAttribute = meshPerAttribute || 1;
  30933. }
  30934. InstancedBufferAttribute.prototype = Object.assign( Object.create( BufferAttribute.prototype ), {
  30935. constructor: InstancedBufferAttribute,
  30936. isInstancedBufferAttribute: true,
  30937. copy: function ( source ) {
  30938. BufferAttribute.prototype.copy.call( this, source );
  30939. this.meshPerAttribute = source.meshPerAttribute;
  30940. return this;
  30941. }
  30942. } );
  30943. /**
  30944. * @author mrdoob / http://mrdoob.com/
  30945. * @author bhouston / http://clara.io/
  30946. * @author stephomi / http://stephaneginier.com/
  30947. */
  30948. function Raycaster( origin, direction, near, far ) {
  30949. this.ray = new Ray( origin, direction );
  30950. // direction is assumed to be normalized (for accurate distance calculations)
  30951. this.near = near || 0;
  30952. this.far = far || Infinity;
  30953. this.params = {
  30954. Mesh: {},
  30955. Line: {},
  30956. LOD: {},
  30957. Points: { threshold: 1 },
  30958. Sprite: {}
  30959. };
  30960. Object.defineProperties( this.params, {
  30961. PointCloud: {
  30962. get: function () {
  30963. console.warn( 'THREE.Raycaster: params.PointCloud has been renamed to params.Points.' );
  30964. return this.Points;
  30965. }
  30966. }
  30967. } );
  30968. }
  30969. function ascSort( a, b ) {
  30970. return a.distance - b.distance;
  30971. }
  30972. function intersectObject( object, raycaster, intersects, recursive ) {
  30973. if ( object.visible === false ) return;
  30974. object.raycast( raycaster, intersects );
  30975. if ( recursive === true ) {
  30976. var children = object.children;
  30977. for ( var i = 0, l = children.length; i < l; i ++ ) {
  30978. intersectObject( children[ i ], raycaster, intersects, true );
  30979. }
  30980. }
  30981. }
  30982. Object.assign( Raycaster.prototype, {
  30983. linePrecision: 1,
  30984. set: function ( origin, direction ) {
  30985. // direction is assumed to be normalized (for accurate distance calculations)
  30986. this.ray.set( origin, direction );
  30987. },
  30988. setFromCamera: function ( coords, camera ) {
  30989. if ( ( camera && camera.isPerspectiveCamera ) ) {
  30990. this.ray.origin.setFromMatrixPosition( camera.matrixWorld );
  30991. this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( this.ray.origin ).normalize();
  30992. } else if ( ( camera && camera.isOrthographicCamera ) ) {
  30993. this.ray.origin.set( coords.x, coords.y, ( camera.near + camera.far ) / ( camera.near - camera.far ) ).unproject( camera ); // set origin in plane of camera
  30994. this.ray.direction.set( 0, 0, - 1 ).transformDirection( camera.matrixWorld );
  30995. } else {
  30996. console.error( 'THREE.Raycaster: Unsupported camera type.' );
  30997. }
  30998. },
  30999. intersectObject: function ( object, recursive, optionalTarget ) {
  31000. var intersects = optionalTarget || [];
  31001. intersectObject( object, this, intersects, recursive );
  31002. intersects.sort( ascSort );
  31003. return intersects;
  31004. },
  31005. intersectObjects: function ( objects, recursive, optionalTarget ) {
  31006. var intersects = optionalTarget || [];
  31007. if ( Array.isArray( objects ) === false ) {
  31008. console.warn( 'THREE.Raycaster.intersectObjects: objects is not an Array.' );
  31009. return intersects;
  31010. }
  31011. for ( var i = 0, l = objects.length; i < l; i ++ ) {
  31012. intersectObject( objects[ i ], this, intersects, recursive );
  31013. }
  31014. intersects.sort( ascSort );
  31015. return intersects;
  31016. }
  31017. } );
  31018. /**
  31019. * @author bhouston / http://clara.io
  31020. * @author WestLangley / http://github.com/WestLangley
  31021. *
  31022. * Ref: https://en.wikipedia.org/wiki/Spherical_coordinate_system
  31023. *
  31024. * The polar angle (phi) is measured from the positive y-axis. The positive y-axis is up.
  31025. * The azimuthal angle (theta) is measured from the positive z-axiz.
  31026. */
  31027. function Spherical( radius, phi, theta ) {
  31028. this.radius = ( radius !== undefined ) ? radius : 1.0;
  31029. this.phi = ( phi !== undefined ) ? phi : 0; // polar angle
  31030. this.theta = ( theta !== undefined ) ? theta : 0; // azimuthal angle
  31031. return this;
  31032. }
  31033. Object.assign( Spherical.prototype, {
  31034. set: function ( radius, phi, theta ) {
  31035. this.radius = radius;
  31036. this.phi = phi;
  31037. this.theta = theta;
  31038. return this;
  31039. },
  31040. clone: function () {
  31041. return new this.constructor().copy( this );
  31042. },
  31043. copy: function ( other ) {
  31044. this.radius = other.radius;
  31045. this.phi = other.phi;
  31046. this.theta = other.theta;
  31047. return this;
  31048. },
  31049. // restrict phi to be betwee EPS and PI-EPS
  31050. makeSafe: function () {
  31051. var EPS = 0.000001;
  31052. this.phi = Math.max( EPS, Math.min( Math.PI - EPS, this.phi ) );
  31053. return this;
  31054. },
  31055. setFromVector3: function ( v ) {
  31056. return this.setFromCartesianCoords( v.x, v.y, v.z );
  31057. },
  31058. setFromCartesianCoords: function ( x, y, z ) {
  31059. this.radius = Math.sqrt( x * x + y * y + z * z );
  31060. if ( this.radius === 0 ) {
  31061. this.theta = 0;
  31062. this.phi = 0;
  31063. } else {
  31064. this.theta = Math.atan2( x, z );
  31065. this.phi = Math.acos( _Math.clamp( y / this.radius, - 1, 1 ) );
  31066. }
  31067. return this;
  31068. }
  31069. } );
  31070. /**
  31071. * @author Mugen87 / https://github.com/Mugen87
  31072. *
  31073. * Ref: https://en.wikipedia.org/wiki/Cylindrical_coordinate_system
  31074. *
  31075. */
  31076. function Cylindrical( radius, theta, y ) {
  31077. this.radius = ( radius !== undefined ) ? radius : 1.0; // distance from the origin to a point in the x-z plane
  31078. this.theta = ( theta !== undefined ) ? theta : 0; // counterclockwise angle in the x-z plane measured in radians from the positive z-axis
  31079. this.y = ( y !== undefined ) ? y : 0; // height above the x-z plane
  31080. return this;
  31081. }
  31082. Object.assign( Cylindrical.prototype, {
  31083. set: function ( radius, theta, y ) {
  31084. this.radius = radius;
  31085. this.theta = theta;
  31086. this.y = y;
  31087. return this;
  31088. },
  31089. clone: function () {
  31090. return new this.constructor().copy( this );
  31091. },
  31092. copy: function ( other ) {
  31093. this.radius = other.radius;
  31094. this.theta = other.theta;
  31095. this.y = other.y;
  31096. return this;
  31097. },
  31098. setFromVector3: function ( v ) {
  31099. return this.setFromCartesianCoords( v.x, v.y, v.z );
  31100. },
  31101. setFromCartesianCoords: function ( x, y, z ) {
  31102. this.radius = Math.sqrt( x * x + z * z );
  31103. this.theta = Math.atan2( x, z );
  31104. this.y = y;
  31105. return this;
  31106. }
  31107. } );
  31108. /**
  31109. * @author bhouston / http://clara.io
  31110. */
  31111. function Box2( min, max ) {
  31112. this.min = ( min !== undefined ) ? min : new Vector2( + Infinity, + Infinity );
  31113. this.max = ( max !== undefined ) ? max : new Vector2( - Infinity, - Infinity );
  31114. }
  31115. Object.assign( Box2.prototype, {
  31116. set: function ( min, max ) {
  31117. this.min.copy( min );
  31118. this.max.copy( max );
  31119. return this;
  31120. },
  31121. setFromPoints: function ( points ) {
  31122. this.makeEmpty();
  31123. for ( var i = 0, il = points.length; i < il; i ++ ) {
  31124. this.expandByPoint( points[ i ] );
  31125. }
  31126. return this;
  31127. },
  31128. setFromCenterAndSize: function () {
  31129. var v1 = new Vector2();
  31130. return function setFromCenterAndSize( center, size ) {
  31131. var halfSize = v1.copy( size ).multiplyScalar( 0.5 );
  31132. this.min.copy( center ).sub( halfSize );
  31133. this.max.copy( center ).add( halfSize );
  31134. return this;
  31135. };
  31136. }(),
  31137. clone: function () {
  31138. return new this.constructor().copy( this );
  31139. },
  31140. copy: function ( box ) {
  31141. this.min.copy( box.min );
  31142. this.max.copy( box.max );
  31143. return this;
  31144. },
  31145. makeEmpty: function () {
  31146. this.min.x = this.min.y = + Infinity;
  31147. this.max.x = this.max.y = - Infinity;
  31148. return this;
  31149. },
  31150. isEmpty: function () {
  31151. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  31152. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  31153. },
  31154. getCenter: function ( target ) {
  31155. if ( target === undefined ) {
  31156. console.warn( 'THREE.Box2: .getCenter() target is now required' );
  31157. target = new Vector2();
  31158. }
  31159. return this.isEmpty() ? target.set( 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  31160. },
  31161. getSize: function ( target ) {
  31162. if ( target === undefined ) {
  31163. console.warn( 'THREE.Box2: .getSize() target is now required' );
  31164. target = new Vector2();
  31165. }
  31166. return this.isEmpty() ? target.set( 0, 0 ) : target.subVectors( this.max, this.min );
  31167. },
  31168. expandByPoint: function ( point ) {
  31169. this.min.min( point );
  31170. this.max.max( point );
  31171. return this;
  31172. },
  31173. expandByVector: function ( vector ) {
  31174. this.min.sub( vector );
  31175. this.max.add( vector );
  31176. return this;
  31177. },
  31178. expandByScalar: function ( scalar ) {
  31179. this.min.addScalar( - scalar );
  31180. this.max.addScalar( scalar );
  31181. return this;
  31182. },
  31183. containsPoint: function ( point ) {
  31184. return point.x < this.min.x || point.x > this.max.x ||
  31185. point.y < this.min.y || point.y > this.max.y ? false : true;
  31186. },
  31187. containsBox: function ( box ) {
  31188. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  31189. this.min.y <= box.min.y && box.max.y <= this.max.y;
  31190. },
  31191. getParameter: function ( point, target ) {
  31192. // This can potentially have a divide by zero if the box
  31193. // has a size dimension of 0.
  31194. if ( target === undefined ) {
  31195. console.warn( 'THREE.Box2: .getParameter() target is now required' );
  31196. target = new Vector2();
  31197. }
  31198. return target.set(
  31199. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  31200. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  31201. );
  31202. },
  31203. intersectsBox: function ( box ) {
  31204. // using 4 splitting planes to rule out intersections
  31205. return box.max.x < this.min.x || box.min.x > this.max.x ||
  31206. box.max.y < this.min.y || box.min.y > this.max.y ? false : true;
  31207. },
  31208. clampPoint: function ( point, target ) {
  31209. if ( target === undefined ) {
  31210. console.warn( 'THREE.Box2: .clampPoint() target is now required' );
  31211. target = new Vector2();
  31212. }
  31213. return target.copy( point ).clamp( this.min, this.max );
  31214. },
  31215. distanceToPoint: function () {
  31216. var v1 = new Vector2();
  31217. return function distanceToPoint( point ) {
  31218. var clampedPoint = v1.copy( point ).clamp( this.min, this.max );
  31219. return clampedPoint.sub( point ).length();
  31220. };
  31221. }(),
  31222. intersect: function ( box ) {
  31223. this.min.max( box.min );
  31224. this.max.min( box.max );
  31225. return this;
  31226. },
  31227. union: function ( box ) {
  31228. this.min.min( box.min );
  31229. this.max.max( box.max );
  31230. return this;
  31231. },
  31232. translate: function ( offset ) {
  31233. this.min.add( offset );
  31234. this.max.add( offset );
  31235. return this;
  31236. },
  31237. equals: function ( box ) {
  31238. return box.min.equals( this.min ) && box.max.equals( this.max );
  31239. }
  31240. } );
  31241. /**
  31242. * @author bhouston / http://clara.io
  31243. */
  31244. function Line3( start, end ) {
  31245. this.start = ( start !== undefined ) ? start : new Vector3();
  31246. this.end = ( end !== undefined ) ? end : new Vector3();
  31247. }
  31248. Object.assign( Line3.prototype, {
  31249. set: function ( start, end ) {
  31250. this.start.copy( start );
  31251. this.end.copy( end );
  31252. return this;
  31253. },
  31254. clone: function () {
  31255. return new this.constructor().copy( this );
  31256. },
  31257. copy: function ( line ) {
  31258. this.start.copy( line.start );
  31259. this.end.copy( line.end );
  31260. return this;
  31261. },
  31262. getCenter: function ( target ) {
  31263. if ( target === undefined ) {
  31264. console.warn( 'THREE.Line3: .getCenter() target is now required' );
  31265. target = new Vector3();
  31266. }
  31267. return target.addVectors( this.start, this.end ).multiplyScalar( 0.5 );
  31268. },
  31269. delta: function ( target ) {
  31270. if ( target === undefined ) {
  31271. console.warn( 'THREE.Line3: .delta() target is now required' );
  31272. target = new Vector3();
  31273. }
  31274. return target.subVectors( this.end, this.start );
  31275. },
  31276. distanceSq: function () {
  31277. return this.start.distanceToSquared( this.end );
  31278. },
  31279. distance: function () {
  31280. return this.start.distanceTo( this.end );
  31281. },
  31282. at: function ( t, target ) {
  31283. if ( target === undefined ) {
  31284. console.warn( 'THREE.Line3: .at() target is now required' );
  31285. target = new Vector3();
  31286. }
  31287. return this.delta( target ).multiplyScalar( t ).add( this.start );
  31288. },
  31289. closestPointToPointParameter: function () {
  31290. var startP = new Vector3();
  31291. var startEnd = new Vector3();
  31292. return function closestPointToPointParameter( point, clampToLine ) {
  31293. startP.subVectors( point, this.start );
  31294. startEnd.subVectors( this.end, this.start );
  31295. var startEnd2 = startEnd.dot( startEnd );
  31296. var startEnd_startP = startEnd.dot( startP );
  31297. var t = startEnd_startP / startEnd2;
  31298. if ( clampToLine ) {
  31299. t = _Math.clamp( t, 0, 1 );
  31300. }
  31301. return t;
  31302. };
  31303. }(),
  31304. closestPointToPoint: function ( point, clampToLine, target ) {
  31305. var t = this.closestPointToPointParameter( point, clampToLine );
  31306. if ( target === undefined ) {
  31307. console.warn( 'THREE.Line3: .closestPointToPoint() target is now required' );
  31308. target = new Vector3();
  31309. }
  31310. return this.delta( target ).multiplyScalar( t ).add( this.start );
  31311. },
  31312. applyMatrix4: function ( matrix ) {
  31313. this.start.applyMatrix4( matrix );
  31314. this.end.applyMatrix4( matrix );
  31315. return this;
  31316. },
  31317. equals: function ( line ) {
  31318. return line.start.equals( this.start ) && line.end.equals( this.end );
  31319. }
  31320. } );
  31321. /**
  31322. * @author alteredq / http://alteredqualia.com/
  31323. */
  31324. function ImmediateRenderObject( material ) {
  31325. Object3D.call( this );
  31326. this.material = material;
  31327. this.render = function ( /* renderCallback */ ) {};
  31328. }
  31329. ImmediateRenderObject.prototype = Object.create( Object3D.prototype );
  31330. ImmediateRenderObject.prototype.constructor = ImmediateRenderObject;
  31331. ImmediateRenderObject.prototype.isImmediateRenderObject = true;
  31332. /**
  31333. * @author mrdoob / http://mrdoob.com/
  31334. * @author WestLangley / http://github.com/WestLangley
  31335. */
  31336. function VertexNormalsHelper( object, size, hex, linewidth ) {
  31337. this.object = object;
  31338. this.size = ( size !== undefined ) ? size : 1;
  31339. var color = ( hex !== undefined ) ? hex : 0xff0000;
  31340. var width = ( linewidth !== undefined ) ? linewidth : 1;
  31341. //
  31342. var nNormals = 0;
  31343. var objGeometry = this.object.geometry;
  31344. if ( objGeometry && objGeometry.isGeometry ) {
  31345. nNormals = objGeometry.faces.length * 3;
  31346. } else if ( objGeometry && objGeometry.isBufferGeometry ) {
  31347. nNormals = objGeometry.attributes.normal.count;
  31348. }
  31349. //
  31350. var geometry = new BufferGeometry();
  31351. var positions = new Float32BufferAttribute( nNormals * 2 * 3, 3 );
  31352. geometry.addAttribute( 'position', positions );
  31353. LineSegments.call( this, geometry, new LineBasicMaterial( { color: color, linewidth: width } ) );
  31354. //
  31355. this.matrixAutoUpdate = false;
  31356. this.update();
  31357. }
  31358. VertexNormalsHelper.prototype = Object.create( LineSegments.prototype );
  31359. VertexNormalsHelper.prototype.constructor = VertexNormalsHelper;
  31360. VertexNormalsHelper.prototype.update = ( function () {
  31361. var v1 = new Vector3();
  31362. var v2 = new Vector3();
  31363. var normalMatrix = new Matrix3();
  31364. return function update() {
  31365. var keys = [ 'a', 'b', 'c' ];
  31366. this.object.updateMatrixWorld( true );
  31367. normalMatrix.getNormalMatrix( this.object.matrixWorld );
  31368. var matrixWorld = this.object.matrixWorld;
  31369. var position = this.geometry.attributes.position;
  31370. //
  31371. var objGeometry = this.object.geometry;
  31372. if ( objGeometry && objGeometry.isGeometry ) {
  31373. var vertices = objGeometry.vertices;
  31374. var faces = objGeometry.faces;
  31375. var idx = 0;
  31376. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  31377. var face = faces[ i ];
  31378. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  31379. var vertex = vertices[ face[ keys[ j ] ] ];
  31380. var normal = face.vertexNormals[ j ];
  31381. v1.copy( vertex ).applyMatrix4( matrixWorld );
  31382. v2.copy( normal ).applyMatrix3( normalMatrix ).normalize().multiplyScalar( this.size ).add( v1 );
  31383. position.setXYZ( idx, v1.x, v1.y, v1.z );
  31384. idx = idx + 1;
  31385. position.setXYZ( idx, v2.x, v2.y, v2.z );
  31386. idx = idx + 1;
  31387. }
  31388. }
  31389. } else if ( objGeometry && objGeometry.isBufferGeometry ) {
  31390. var objPos = objGeometry.attributes.position;
  31391. var objNorm = objGeometry.attributes.normal;
  31392. var idx = 0;
  31393. // for simplicity, ignore index and drawcalls, and render every normal
  31394. for ( var j = 0, jl = objPos.count; j < jl; j ++ ) {
  31395. v1.set( objPos.getX( j ), objPos.getY( j ), objPos.getZ( j ) ).applyMatrix4( matrixWorld );
  31396. v2.set( objNorm.getX( j ), objNorm.getY( j ), objNorm.getZ( j ) );
  31397. v2.applyMatrix3( normalMatrix ).normalize().multiplyScalar( this.size ).add( v1 );
  31398. position.setXYZ( idx, v1.x, v1.y, v1.z );
  31399. idx = idx + 1;
  31400. position.setXYZ( idx, v2.x, v2.y, v2.z );
  31401. idx = idx + 1;
  31402. }
  31403. }
  31404. position.needsUpdate = true;
  31405. };
  31406. }() );
  31407. /**
  31408. * @author alteredq / http://alteredqualia.com/
  31409. * @author mrdoob / http://mrdoob.com/
  31410. * @author WestLangley / http://github.com/WestLangley
  31411. */
  31412. function SpotLightHelper( light, color ) {
  31413. Object3D.call( this );
  31414. this.light = light;
  31415. this.light.updateMatrixWorld();
  31416. this.matrix = light.matrixWorld;
  31417. this.matrixAutoUpdate = false;
  31418. this.color = color;
  31419. var geometry = new BufferGeometry();
  31420. var positions = [
  31421. 0, 0, 0, 0, 0, 1,
  31422. 0, 0, 0, 1, 0, 1,
  31423. 0, 0, 0, - 1, 0, 1,
  31424. 0, 0, 0, 0, 1, 1,
  31425. 0, 0, 0, 0, - 1, 1
  31426. ];
  31427. for ( var i = 0, j = 1, l = 32; i < l; i ++, j ++ ) {
  31428. var p1 = ( i / l ) * Math.PI * 2;
  31429. var p2 = ( j / l ) * Math.PI * 2;
  31430. positions.push(
  31431. Math.cos( p1 ), Math.sin( p1 ), 1,
  31432. Math.cos( p2 ), Math.sin( p2 ), 1
  31433. );
  31434. }
  31435. geometry.addAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  31436. var material = new LineBasicMaterial( { fog: false } );
  31437. this.cone = new LineSegments( geometry, material );
  31438. this.add( this.cone );
  31439. this.update();
  31440. }
  31441. SpotLightHelper.prototype = Object.create( Object3D.prototype );
  31442. SpotLightHelper.prototype.constructor = SpotLightHelper;
  31443. SpotLightHelper.prototype.dispose = function () {
  31444. this.cone.geometry.dispose();
  31445. this.cone.material.dispose();
  31446. };
  31447. SpotLightHelper.prototype.update = function () {
  31448. var vector = new Vector3();
  31449. return function update() {
  31450. this.light.updateMatrixWorld();
  31451. var coneLength = this.light.distance ? this.light.distance : 1000;
  31452. var coneWidth = coneLength * Math.tan( this.light.angle );
  31453. this.cone.scale.set( coneWidth, coneWidth, coneLength );
  31454. vector.setFromMatrixPosition( this.light.target.matrixWorld );
  31455. this.cone.lookAt( vector );
  31456. if ( this.color !== undefined ) {
  31457. this.cone.material.color.set( this.color );
  31458. } else {
  31459. this.cone.material.color.copy( this.light.color );
  31460. }
  31461. };
  31462. }();
  31463. /**
  31464. * @author Sean Griffin / http://twitter.com/sgrif
  31465. * @author Michael Guerrero / http://realitymeltdown.com
  31466. * @author mrdoob / http://mrdoob.com/
  31467. * @author ikerr / http://verold.com
  31468. * @author Mugen87 / https://github.com/Mugen87
  31469. */
  31470. function getBoneList( object ) {
  31471. var boneList = [];
  31472. if ( object && object.isBone ) {
  31473. boneList.push( object );
  31474. }
  31475. for ( var i = 0; i < object.children.length; i ++ ) {
  31476. boneList.push.apply( boneList, getBoneList( object.children[ i ] ) );
  31477. }
  31478. return boneList;
  31479. }
  31480. function SkeletonHelper( object ) {
  31481. var bones = getBoneList( object );
  31482. var geometry = new BufferGeometry();
  31483. var vertices = [];
  31484. var colors = [];
  31485. var color1 = new Color( 0, 0, 1 );
  31486. var color2 = new Color( 0, 1, 0 );
  31487. for ( var i = 0; i < bones.length; i ++ ) {
  31488. var bone = bones[ i ];
  31489. if ( bone.parent && bone.parent.isBone ) {
  31490. vertices.push( 0, 0, 0 );
  31491. vertices.push( 0, 0, 0 );
  31492. colors.push( color1.r, color1.g, color1.b );
  31493. colors.push( color2.r, color2.g, color2.b );
  31494. }
  31495. }
  31496. geometry.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  31497. geometry.addAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  31498. var material = new LineBasicMaterial( { vertexColors: VertexColors, depthTest: false, depthWrite: false, transparent: true } );
  31499. LineSegments.call( this, geometry, material );
  31500. this.root = object;
  31501. this.bones = bones;
  31502. this.matrix = object.matrixWorld;
  31503. this.matrixAutoUpdate = false;
  31504. }
  31505. SkeletonHelper.prototype = Object.create( LineSegments.prototype );
  31506. SkeletonHelper.prototype.constructor = SkeletonHelper;
  31507. SkeletonHelper.prototype.updateMatrixWorld = function () {
  31508. var vector = new Vector3();
  31509. var boneMatrix = new Matrix4();
  31510. var matrixWorldInv = new Matrix4();
  31511. return function updateMatrixWorld( force ) {
  31512. var bones = this.bones;
  31513. var geometry = this.geometry;
  31514. var position = geometry.getAttribute( 'position' );
  31515. matrixWorldInv.getInverse( this.root.matrixWorld );
  31516. for ( var i = 0, j = 0; i < bones.length; i ++ ) {
  31517. var bone = bones[ i ];
  31518. if ( bone.parent && bone.parent.isBone ) {
  31519. boneMatrix.multiplyMatrices( matrixWorldInv, bone.matrixWorld );
  31520. vector.setFromMatrixPosition( boneMatrix );
  31521. position.setXYZ( j, vector.x, vector.y, vector.z );
  31522. boneMatrix.multiplyMatrices( matrixWorldInv, bone.parent.matrixWorld );
  31523. vector.setFromMatrixPosition( boneMatrix );
  31524. position.setXYZ( j + 1, vector.x, vector.y, vector.z );
  31525. j += 2;
  31526. }
  31527. }
  31528. geometry.getAttribute( 'position' ).needsUpdate = true;
  31529. Object3D.prototype.updateMatrixWorld.call( this, force );
  31530. };
  31531. }();
  31532. /**
  31533. * @author alteredq / http://alteredqualia.com/
  31534. * @author mrdoob / http://mrdoob.com/
  31535. */
  31536. function PointLightHelper( light, sphereSize, color ) {
  31537. this.light = light;
  31538. this.light.updateMatrixWorld();
  31539. this.color = color;
  31540. var geometry = new SphereBufferGeometry( sphereSize, 4, 2 );
  31541. var material = new MeshBasicMaterial( { wireframe: true, fog: false } );
  31542. Mesh.call( this, geometry, material );
  31543. this.matrix = this.light.matrixWorld;
  31544. this.matrixAutoUpdate = false;
  31545. this.update();
  31546. /*
  31547. var distanceGeometry = new THREE.IcosahedronBufferGeometry( 1, 2 );
  31548. var distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  31549. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  31550. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  31551. var d = light.distance;
  31552. if ( d === 0.0 ) {
  31553. this.lightDistance.visible = false;
  31554. } else {
  31555. this.lightDistance.scale.set( d, d, d );
  31556. }
  31557. this.add( this.lightDistance );
  31558. */
  31559. }
  31560. PointLightHelper.prototype = Object.create( Mesh.prototype );
  31561. PointLightHelper.prototype.constructor = PointLightHelper;
  31562. PointLightHelper.prototype.dispose = function () {
  31563. this.geometry.dispose();
  31564. this.material.dispose();
  31565. };
  31566. PointLightHelper.prototype.update = function () {
  31567. if ( this.color !== undefined ) {
  31568. this.material.color.set( this.color );
  31569. } else {
  31570. this.material.color.copy( this.light.color );
  31571. }
  31572. /*
  31573. var d = this.light.distance;
  31574. if ( d === 0.0 ) {
  31575. this.lightDistance.visible = false;
  31576. } else {
  31577. this.lightDistance.visible = true;
  31578. this.lightDistance.scale.set( d, d, d );
  31579. }
  31580. */
  31581. };
  31582. /**
  31583. * @author abelnation / http://github.com/abelnation
  31584. * @author Mugen87 / http://github.com/Mugen87
  31585. * @author WestLangley / http://github.com/WestLangley
  31586. *
  31587. * This helper must be added as a child of the light
  31588. */
  31589. function RectAreaLightHelper( light, color ) {
  31590. this.type = 'RectAreaLightHelper';
  31591. this.light = light;
  31592. this.color = color; // optional hardwired color for the helper
  31593. var positions = [ 1, 1, 0, - 1, 1, 0, - 1, - 1, 0, 1, - 1, 0, 1, 1, 0 ];
  31594. var geometry = new BufferGeometry();
  31595. geometry.addAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  31596. geometry.computeBoundingSphere();
  31597. var material = new LineBasicMaterial( { fog: false } );
  31598. Line.call( this, geometry, material );
  31599. //
  31600. var positions2 = [ 1, 1, 0, - 1, 1, 0, - 1, - 1, 0, 1, 1, 0, - 1, - 1, 0, 1, - 1, 0 ];
  31601. var geometry2 = new BufferGeometry();
  31602. geometry2.addAttribute( 'position', new Float32BufferAttribute( positions2, 3 ) );
  31603. geometry2.computeBoundingSphere();
  31604. this.add( new Mesh( geometry2, new MeshBasicMaterial( { side: BackSide, fog: false } ) ) );
  31605. this.update();
  31606. }
  31607. RectAreaLightHelper.prototype = Object.create( Line.prototype );
  31608. RectAreaLightHelper.prototype.constructor = RectAreaLightHelper;
  31609. RectAreaLightHelper.prototype.update = function () {
  31610. this.scale.set( 0.5 * this.light.width, 0.5 * this.light.height, 1 );
  31611. if ( this.color !== undefined ) {
  31612. this.material.color.set( this.color );
  31613. this.children[ 0 ].material.color.set( this.color );
  31614. } else {
  31615. this.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  31616. // prevent hue shift
  31617. var c = this.material.color;
  31618. var max = Math.max( c.r, c.g, c.b );
  31619. if ( max > 1 ) c.multiplyScalar( 1 / max );
  31620. this.children[ 0 ].material.color.copy( this.material.color );
  31621. }
  31622. };
  31623. RectAreaLightHelper.prototype.dispose = function () {
  31624. this.geometry.dispose();
  31625. this.material.dispose();
  31626. this.children[ 0 ].geometry.dispose();
  31627. this.children[ 0 ].material.dispose();
  31628. };
  31629. /**
  31630. * @author alteredq / http://alteredqualia.com/
  31631. * @author mrdoob / http://mrdoob.com/
  31632. * @author Mugen87 / https://github.com/Mugen87
  31633. */
  31634. function HemisphereLightHelper( light, size, color ) {
  31635. Object3D.call( this );
  31636. this.light = light;
  31637. this.light.updateMatrixWorld();
  31638. this.matrix = light.matrixWorld;
  31639. this.matrixAutoUpdate = false;
  31640. this.color = color;
  31641. var geometry = new OctahedronBufferGeometry( size );
  31642. geometry.rotateY( Math.PI * 0.5 );
  31643. this.material = new MeshBasicMaterial( { wireframe: true, fog: false } );
  31644. if ( this.color === undefined ) this.material.vertexColors = VertexColors;
  31645. var position = geometry.getAttribute( 'position' );
  31646. var colors = new Float32Array( position.count * 3 );
  31647. geometry.addAttribute( 'color', new BufferAttribute( colors, 3 ) );
  31648. this.add( new Mesh( geometry, this.material ) );
  31649. this.update();
  31650. }
  31651. HemisphereLightHelper.prototype = Object.create( Object3D.prototype );
  31652. HemisphereLightHelper.prototype.constructor = HemisphereLightHelper;
  31653. HemisphereLightHelper.prototype.dispose = function () {
  31654. this.children[ 0 ].geometry.dispose();
  31655. this.children[ 0 ].material.dispose();
  31656. };
  31657. HemisphereLightHelper.prototype.update = function () {
  31658. var vector = new Vector3();
  31659. var color1 = new Color();
  31660. var color2 = new Color();
  31661. return function update() {
  31662. var mesh = this.children[ 0 ];
  31663. if ( this.color !== undefined ) {
  31664. this.material.color.set( this.color );
  31665. } else {
  31666. var colors = mesh.geometry.getAttribute( 'color' );
  31667. color1.copy( this.light.color );
  31668. color2.copy( this.light.groundColor );
  31669. for ( var i = 0, l = colors.count; i < l; i ++ ) {
  31670. var color = ( i < ( l / 2 ) ) ? color1 : color2;
  31671. colors.setXYZ( i, color.r, color.g, color.b );
  31672. }
  31673. colors.needsUpdate = true;
  31674. }
  31675. mesh.lookAt( vector.setFromMatrixPosition( this.light.matrixWorld ).negate() );
  31676. };
  31677. }();
  31678. /**
  31679. * @author mrdoob / http://mrdoob.com/
  31680. */
  31681. function GridHelper( size, divisions, color1, color2 ) {
  31682. size = size || 10;
  31683. divisions = divisions || 10;
  31684. color1 = new Color( color1 !== undefined ? color1 : 0x444444 );
  31685. color2 = new Color( color2 !== undefined ? color2 : 0x888888 );
  31686. var center = divisions / 2;
  31687. var step = size / divisions;
  31688. var halfSize = size / 2;
  31689. var vertices = [], colors = [];
  31690. for ( var i = 0, j = 0, k = - halfSize; i <= divisions; i ++, k += step ) {
  31691. vertices.push( - halfSize, 0, k, halfSize, 0, k );
  31692. vertices.push( k, 0, - halfSize, k, 0, halfSize );
  31693. var color = i === center ? color1 : color2;
  31694. color.toArray( colors, j ); j += 3;
  31695. color.toArray( colors, j ); j += 3;
  31696. color.toArray( colors, j ); j += 3;
  31697. color.toArray( colors, j ); j += 3;
  31698. }
  31699. var geometry = new BufferGeometry();
  31700. geometry.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  31701. geometry.addAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  31702. var material = new LineBasicMaterial( { vertexColors: VertexColors } );
  31703. LineSegments.call( this, geometry, material );
  31704. }
  31705. GridHelper.prototype = Object.create( LineSegments.prototype );
  31706. GridHelper.prototype.constructor = GridHelper;
  31707. /**
  31708. * @author mrdoob / http://mrdoob.com/
  31709. * @author Mugen87 / http://github.com/Mugen87
  31710. * @author Hectate / http://www.github.com/Hectate
  31711. */
  31712. function PolarGridHelper( radius, radials, circles, divisions, color1, color2 ) {
  31713. radius = radius || 10;
  31714. radials = radials || 16;
  31715. circles = circles || 8;
  31716. divisions = divisions || 64;
  31717. color1 = new Color( color1 !== undefined ? color1 : 0x444444 );
  31718. color2 = new Color( color2 !== undefined ? color2 : 0x888888 );
  31719. var vertices = [];
  31720. var colors = [];
  31721. var x, z;
  31722. var v, i, j, r, color;
  31723. // create the radials
  31724. for ( i = 0; i <= radials; i ++ ) {
  31725. v = ( i / radials ) * ( Math.PI * 2 );
  31726. x = Math.sin( v ) * radius;
  31727. z = Math.cos( v ) * radius;
  31728. vertices.push( 0, 0, 0 );
  31729. vertices.push( x, 0, z );
  31730. color = ( i & 1 ) ? color1 : color2;
  31731. colors.push( color.r, color.g, color.b );
  31732. colors.push( color.r, color.g, color.b );
  31733. }
  31734. // create the circles
  31735. for ( i = 0; i <= circles; i ++ ) {
  31736. color = ( i & 1 ) ? color1 : color2;
  31737. r = radius - ( radius / circles * i );
  31738. for ( j = 0; j < divisions; j ++ ) {
  31739. // first vertex
  31740. v = ( j / divisions ) * ( Math.PI * 2 );
  31741. x = Math.sin( v ) * r;
  31742. z = Math.cos( v ) * r;
  31743. vertices.push( x, 0, z );
  31744. colors.push( color.r, color.g, color.b );
  31745. // second vertex
  31746. v = ( ( j + 1 ) / divisions ) * ( Math.PI * 2 );
  31747. x = Math.sin( v ) * r;
  31748. z = Math.cos( v ) * r;
  31749. vertices.push( x, 0, z );
  31750. colors.push( color.r, color.g, color.b );
  31751. }
  31752. }
  31753. var geometry = new BufferGeometry();
  31754. geometry.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  31755. geometry.addAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  31756. var material = new LineBasicMaterial( { vertexColors: VertexColors } );
  31757. LineSegments.call( this, geometry, material );
  31758. }
  31759. PolarGridHelper.prototype = Object.create( LineSegments.prototype );
  31760. PolarGridHelper.prototype.constructor = PolarGridHelper;
  31761. /**
  31762. * @author Mugen87 / http://github.com/Mugen87
  31763. */
  31764. function PositionalAudioHelper( audio, range, divisionsInnerAngle, divisionsOuterAngle ) {
  31765. this.audio = audio;
  31766. this.range = range || 1;
  31767. this.divisionsInnerAngle = divisionsInnerAngle || 16;
  31768. this.divisionsOuterAngle = divisionsOuterAngle || 2;
  31769. var geometry = new BufferGeometry();
  31770. var divisions = this.divisionsInnerAngle + this.divisionsOuterAngle * 2;
  31771. var positions = new Float32Array( ( divisions * 3 + 3 ) * 3 );
  31772. geometry.addAttribute( 'position', new BufferAttribute( positions, 3 ) );
  31773. var materialInnerAngle = new LineBasicMaterial( { color: 0x00ff00 } );
  31774. var materialOuterAngle = new LineBasicMaterial( { color: 0xffff00 } );
  31775. Line.call( this, geometry, [ materialOuterAngle, materialInnerAngle ] );
  31776. this.update();
  31777. }
  31778. PositionalAudioHelper.prototype = Object.create( Line.prototype );
  31779. PositionalAudioHelper.prototype.constructor = PositionalAudioHelper;
  31780. PositionalAudioHelper.prototype.update = function () {
  31781. var audio = this.audio;
  31782. var range = this.range;
  31783. var divisionsInnerAngle = this.divisionsInnerAngle;
  31784. var divisionsOuterAngle = this.divisionsOuterAngle;
  31785. var coneInnerAngle = _Math.degToRad( audio.panner.coneInnerAngle );
  31786. var coneOuterAngle = _Math.degToRad( audio.panner.coneOuterAngle );
  31787. var halfConeInnerAngle = coneInnerAngle / 2;
  31788. var halfConeOuterAngle = coneOuterAngle / 2;
  31789. var start = 0;
  31790. var count = 0;
  31791. var i, stride;
  31792. var geometry = this.geometry;
  31793. var positionAttribute = geometry.attributes.position;
  31794. geometry.clearGroups();
  31795. //
  31796. function generateSegment( from, to, divisions, materialIndex ) {
  31797. var step = ( to - from ) / divisions;
  31798. positionAttribute.setXYZ( start, 0, 0, 0 );
  31799. count ++;
  31800. for ( i = from; i < to; i += step ) {
  31801. stride = start + count;
  31802. positionAttribute.setXYZ( stride, Math.sin( i ) * range, 0, Math.cos( i ) * range );
  31803. positionAttribute.setXYZ( stride + 1, Math.sin( Math.min( i + step, to ) ) * range, 0, Math.cos( Math.min( i + step, to ) ) * range );
  31804. positionAttribute.setXYZ( stride + 2, 0, 0, 0 );
  31805. count += 3;
  31806. }
  31807. geometry.addGroup( start, count, materialIndex );
  31808. start += count;
  31809. count = 0;
  31810. }
  31811. //
  31812. generateSegment( - halfConeOuterAngle, - halfConeInnerAngle, divisionsOuterAngle, 0 );
  31813. generateSegment( - halfConeInnerAngle, halfConeInnerAngle, divisionsInnerAngle, 1 );
  31814. generateSegment( halfConeInnerAngle, halfConeOuterAngle, divisionsOuterAngle, 0 );
  31815. //
  31816. positionAttribute.needsUpdate = true;
  31817. if ( coneInnerAngle === coneOuterAngle ) this.material[ 0 ].visible = false;
  31818. };
  31819. PositionalAudioHelper.prototype.dispose = function () {
  31820. this.geometry.dispose();
  31821. this.material[ 0 ].dispose();
  31822. this.material[ 1 ].dispose();
  31823. };
  31824. /**
  31825. * @author mrdoob / http://mrdoob.com/
  31826. * @author WestLangley / http://github.com/WestLangley
  31827. */
  31828. function FaceNormalsHelper( object, size, hex, linewidth ) {
  31829. // FaceNormalsHelper only supports THREE.Geometry
  31830. this.object = object;
  31831. this.size = ( size !== undefined ) ? size : 1;
  31832. var color = ( hex !== undefined ) ? hex : 0xffff00;
  31833. var width = ( linewidth !== undefined ) ? linewidth : 1;
  31834. //
  31835. var nNormals = 0;
  31836. var objGeometry = this.object.geometry;
  31837. if ( objGeometry && objGeometry.isGeometry ) {
  31838. nNormals = objGeometry.faces.length;
  31839. } else {
  31840. console.warn( 'THREE.FaceNormalsHelper: only THREE.Geometry is supported. Use THREE.VertexNormalsHelper, instead.' );
  31841. }
  31842. //
  31843. var geometry = new BufferGeometry();
  31844. var positions = new Float32BufferAttribute( nNormals * 2 * 3, 3 );
  31845. geometry.addAttribute( 'position', positions );
  31846. LineSegments.call( this, geometry, new LineBasicMaterial( { color: color, linewidth: width } ) );
  31847. //
  31848. this.matrixAutoUpdate = false;
  31849. this.update();
  31850. }
  31851. FaceNormalsHelper.prototype = Object.create( LineSegments.prototype );
  31852. FaceNormalsHelper.prototype.constructor = FaceNormalsHelper;
  31853. FaceNormalsHelper.prototype.update = ( function () {
  31854. var v1 = new Vector3();
  31855. var v2 = new Vector3();
  31856. var normalMatrix = new Matrix3();
  31857. return function update() {
  31858. this.object.updateMatrixWorld( true );
  31859. normalMatrix.getNormalMatrix( this.object.matrixWorld );
  31860. var matrixWorld = this.object.matrixWorld;
  31861. var position = this.geometry.attributes.position;
  31862. //
  31863. var objGeometry = this.object.geometry;
  31864. var vertices = objGeometry.vertices;
  31865. var faces = objGeometry.faces;
  31866. var idx = 0;
  31867. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  31868. var face = faces[ i ];
  31869. var normal = face.normal;
  31870. v1.copy( vertices[ face.a ] )
  31871. .add( vertices[ face.b ] )
  31872. .add( vertices[ face.c ] )
  31873. .divideScalar( 3 )
  31874. .applyMatrix4( matrixWorld );
  31875. v2.copy( normal ).applyMatrix3( normalMatrix ).normalize().multiplyScalar( this.size ).add( v1 );
  31876. position.setXYZ( idx, v1.x, v1.y, v1.z );
  31877. idx = idx + 1;
  31878. position.setXYZ( idx, v2.x, v2.y, v2.z );
  31879. idx = idx + 1;
  31880. }
  31881. position.needsUpdate = true;
  31882. };
  31883. }() );
  31884. /**
  31885. * @author alteredq / http://alteredqualia.com/
  31886. * @author mrdoob / http://mrdoob.com/
  31887. * @author WestLangley / http://github.com/WestLangley
  31888. */
  31889. function DirectionalLightHelper( light, size, color ) {
  31890. Object3D.call( this );
  31891. this.light = light;
  31892. this.light.updateMatrixWorld();
  31893. this.matrix = light.matrixWorld;
  31894. this.matrixAutoUpdate = false;
  31895. this.color = color;
  31896. if ( size === undefined ) size = 1;
  31897. var geometry = new BufferGeometry();
  31898. geometry.addAttribute( 'position', new Float32BufferAttribute( [
  31899. - size, size, 0,
  31900. size, size, 0,
  31901. size, - size, 0,
  31902. - size, - size, 0,
  31903. - size, size, 0
  31904. ], 3 ) );
  31905. var material = new LineBasicMaterial( { fog: false } );
  31906. this.lightPlane = new Line( geometry, material );
  31907. this.add( this.lightPlane );
  31908. geometry = new BufferGeometry();
  31909. geometry.addAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 0, 1 ], 3 ) );
  31910. this.targetLine = new Line( geometry, material );
  31911. this.add( this.targetLine );
  31912. this.update();
  31913. }
  31914. DirectionalLightHelper.prototype = Object.create( Object3D.prototype );
  31915. DirectionalLightHelper.prototype.constructor = DirectionalLightHelper;
  31916. DirectionalLightHelper.prototype.dispose = function () {
  31917. this.lightPlane.geometry.dispose();
  31918. this.lightPlane.material.dispose();
  31919. this.targetLine.geometry.dispose();
  31920. this.targetLine.material.dispose();
  31921. };
  31922. DirectionalLightHelper.prototype.update = function () {
  31923. var v1 = new Vector3();
  31924. var v2 = new Vector3();
  31925. var v3 = new Vector3();
  31926. return function update() {
  31927. v1.setFromMatrixPosition( this.light.matrixWorld );
  31928. v2.setFromMatrixPosition( this.light.target.matrixWorld );
  31929. v3.subVectors( v2, v1 );
  31930. this.lightPlane.lookAt( v2 );
  31931. if ( this.color !== undefined ) {
  31932. this.lightPlane.material.color.set( this.color );
  31933. this.targetLine.material.color.set( this.color );
  31934. } else {
  31935. this.lightPlane.material.color.copy( this.light.color );
  31936. this.targetLine.material.color.copy( this.light.color );
  31937. }
  31938. this.targetLine.lookAt( v2 );
  31939. this.targetLine.scale.z = v3.length();
  31940. };
  31941. }();
  31942. /**
  31943. * @author alteredq / http://alteredqualia.com/
  31944. * @author Mugen87 / https://github.com/Mugen87
  31945. *
  31946. * - shows frustum, line of sight and up of the camera
  31947. * - suitable for fast updates
  31948. * - based on frustum visualization in lightgl.js shadowmap example
  31949. * http://evanw.github.com/lightgl.js/tests/shadowmap.html
  31950. */
  31951. function CameraHelper( camera ) {
  31952. var geometry = new BufferGeometry();
  31953. var material = new LineBasicMaterial( { color: 0xffffff, vertexColors: FaceColors } );
  31954. var vertices = [];
  31955. var colors = [];
  31956. var pointMap = {};
  31957. // colors
  31958. var colorFrustum = new Color( 0xffaa00 );
  31959. var colorCone = new Color( 0xff0000 );
  31960. var colorUp = new Color( 0x00aaff );
  31961. var colorTarget = new Color( 0xffffff );
  31962. var colorCross = new Color( 0x333333 );
  31963. // near
  31964. addLine( 'n1', 'n2', colorFrustum );
  31965. addLine( 'n2', 'n4', colorFrustum );
  31966. addLine( 'n4', 'n3', colorFrustum );
  31967. addLine( 'n3', 'n1', colorFrustum );
  31968. // far
  31969. addLine( 'f1', 'f2', colorFrustum );
  31970. addLine( 'f2', 'f4', colorFrustum );
  31971. addLine( 'f4', 'f3', colorFrustum );
  31972. addLine( 'f3', 'f1', colorFrustum );
  31973. // sides
  31974. addLine( 'n1', 'f1', colorFrustum );
  31975. addLine( 'n2', 'f2', colorFrustum );
  31976. addLine( 'n3', 'f3', colorFrustum );
  31977. addLine( 'n4', 'f4', colorFrustum );
  31978. // cone
  31979. addLine( 'p', 'n1', colorCone );
  31980. addLine( 'p', 'n2', colorCone );
  31981. addLine( 'p', 'n3', colorCone );
  31982. addLine( 'p', 'n4', colorCone );
  31983. // up
  31984. addLine( 'u1', 'u2', colorUp );
  31985. addLine( 'u2', 'u3', colorUp );
  31986. addLine( 'u3', 'u1', colorUp );
  31987. // target
  31988. addLine( 'c', 't', colorTarget );
  31989. addLine( 'p', 'c', colorCross );
  31990. // cross
  31991. addLine( 'cn1', 'cn2', colorCross );
  31992. addLine( 'cn3', 'cn4', colorCross );
  31993. addLine( 'cf1', 'cf2', colorCross );
  31994. addLine( 'cf3', 'cf4', colorCross );
  31995. function addLine( a, b, color ) {
  31996. addPoint( a, color );
  31997. addPoint( b, color );
  31998. }
  31999. function addPoint( id, color ) {
  32000. vertices.push( 0, 0, 0 );
  32001. colors.push( color.r, color.g, color.b );
  32002. if ( pointMap[ id ] === undefined ) {
  32003. pointMap[ id ] = [];
  32004. }
  32005. pointMap[ id ].push( ( vertices.length / 3 ) - 1 );
  32006. }
  32007. geometry.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  32008. geometry.addAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  32009. LineSegments.call( this, geometry, material );
  32010. this.camera = camera;
  32011. if ( this.camera.updateProjectionMatrix ) this.camera.updateProjectionMatrix();
  32012. this.matrix = camera.matrixWorld;
  32013. this.matrixAutoUpdate = false;
  32014. this.pointMap = pointMap;
  32015. this.update();
  32016. }
  32017. CameraHelper.prototype = Object.create( LineSegments.prototype );
  32018. CameraHelper.prototype.constructor = CameraHelper;
  32019. CameraHelper.prototype.update = function () {
  32020. var geometry, pointMap;
  32021. var vector = new Vector3();
  32022. var camera = new Camera();
  32023. function setPoint( point, x, y, z ) {
  32024. vector.set( x, y, z ).unproject( camera );
  32025. var points = pointMap[ point ];
  32026. if ( points !== undefined ) {
  32027. var position = geometry.getAttribute( 'position' );
  32028. for ( var i = 0, l = points.length; i < l; i ++ ) {
  32029. position.setXYZ( points[ i ], vector.x, vector.y, vector.z );
  32030. }
  32031. }
  32032. }
  32033. return function update() {
  32034. geometry = this.geometry;
  32035. pointMap = this.pointMap;
  32036. var w = 1, h = 1;
  32037. // we need just camera projection matrix
  32038. // world matrix must be identity
  32039. camera.projectionMatrix.copy( this.camera.projectionMatrix );
  32040. // center / target
  32041. setPoint( 'c', 0, 0, - 1 );
  32042. setPoint( 't', 0, 0, 1 );
  32043. // near
  32044. setPoint( 'n1', - w, - h, - 1 );
  32045. setPoint( 'n2', w, - h, - 1 );
  32046. setPoint( 'n3', - w, h, - 1 );
  32047. setPoint( 'n4', w, h, - 1 );
  32048. // far
  32049. setPoint( 'f1', - w, - h, 1 );
  32050. setPoint( 'f2', w, - h, 1 );
  32051. setPoint( 'f3', - w, h, 1 );
  32052. setPoint( 'f4', w, h, 1 );
  32053. // up
  32054. setPoint( 'u1', w * 0.7, h * 1.1, - 1 );
  32055. setPoint( 'u2', - w * 0.7, h * 1.1, - 1 );
  32056. setPoint( 'u3', 0, h * 2, - 1 );
  32057. // cross
  32058. setPoint( 'cf1', - w, 0, 1 );
  32059. setPoint( 'cf2', w, 0, 1 );
  32060. setPoint( 'cf3', 0, - h, 1 );
  32061. setPoint( 'cf4', 0, h, 1 );
  32062. setPoint( 'cn1', - w, 0, - 1 );
  32063. setPoint( 'cn2', w, 0, - 1 );
  32064. setPoint( 'cn3', 0, - h, - 1 );
  32065. setPoint( 'cn4', 0, h, - 1 );
  32066. geometry.getAttribute( 'position' ).needsUpdate = true;
  32067. };
  32068. }();
  32069. /**
  32070. * @author mrdoob / http://mrdoob.com/
  32071. * @author Mugen87 / http://github.com/Mugen87
  32072. */
  32073. function BoxHelper( object, color ) {
  32074. this.object = object;
  32075. if ( color === undefined ) color = 0xffff00;
  32076. 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 ] );
  32077. var positions = new Float32Array( 8 * 3 );
  32078. var geometry = new BufferGeometry();
  32079. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  32080. geometry.addAttribute( 'position', new BufferAttribute( positions, 3 ) );
  32081. LineSegments.call( this, geometry, new LineBasicMaterial( { color: color } ) );
  32082. this.matrixAutoUpdate = false;
  32083. this.update();
  32084. }
  32085. BoxHelper.prototype = Object.create( LineSegments.prototype );
  32086. BoxHelper.prototype.constructor = BoxHelper;
  32087. BoxHelper.prototype.update = ( function () {
  32088. var box = new Box3();
  32089. return function update( object ) {
  32090. if ( object !== undefined ) {
  32091. console.warn( 'THREE.BoxHelper: .update() has no longer arguments.' );
  32092. }
  32093. if ( this.object !== undefined ) {
  32094. box.setFromObject( this.object );
  32095. }
  32096. if ( box.isEmpty() ) return;
  32097. var min = box.min;
  32098. var max = box.max;
  32099. /*
  32100. 5____4
  32101. 1/___0/|
  32102. | 6__|_7
  32103. 2/___3/
  32104. 0: max.x, max.y, max.z
  32105. 1: min.x, max.y, max.z
  32106. 2: min.x, min.y, max.z
  32107. 3: max.x, min.y, max.z
  32108. 4: max.x, max.y, min.z
  32109. 5: min.x, max.y, min.z
  32110. 6: min.x, min.y, min.z
  32111. 7: max.x, min.y, min.z
  32112. */
  32113. var position = this.geometry.attributes.position;
  32114. var array = position.array;
  32115. array[ 0 ] = max.x; array[ 1 ] = max.y; array[ 2 ] = max.z;
  32116. array[ 3 ] = min.x; array[ 4 ] = max.y; array[ 5 ] = max.z;
  32117. array[ 6 ] = min.x; array[ 7 ] = min.y; array[ 8 ] = max.z;
  32118. array[ 9 ] = max.x; array[ 10 ] = min.y; array[ 11 ] = max.z;
  32119. array[ 12 ] = max.x; array[ 13 ] = max.y; array[ 14 ] = min.z;
  32120. array[ 15 ] = min.x; array[ 16 ] = max.y; array[ 17 ] = min.z;
  32121. array[ 18 ] = min.x; array[ 19 ] = min.y; array[ 20 ] = min.z;
  32122. array[ 21 ] = max.x; array[ 22 ] = min.y; array[ 23 ] = min.z;
  32123. position.needsUpdate = true;
  32124. this.geometry.computeBoundingSphere();
  32125. };
  32126. } )();
  32127. BoxHelper.prototype.setFromObject = function ( object ) {
  32128. this.object = object;
  32129. this.update();
  32130. return this;
  32131. };
  32132. BoxHelper.prototype.copy = function ( source ) {
  32133. LineSegments.prototype.copy.call( this, source );
  32134. this.object = source.object;
  32135. return this;
  32136. };
  32137. BoxHelper.prototype.clone = function () {
  32138. return new this.constructor().copy( this );
  32139. };
  32140. /**
  32141. * @author WestLangley / http://github.com/WestLangley
  32142. */
  32143. function Box3Helper( box, hex ) {
  32144. this.type = 'Box3Helper';
  32145. this.box = box;
  32146. var color = ( hex !== undefined ) ? hex : 0xffff00;
  32147. 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 ] );
  32148. 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 ];
  32149. var geometry = new BufferGeometry();
  32150. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  32151. geometry.addAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  32152. LineSegments.call( this, geometry, new LineBasicMaterial( { color: color } ) );
  32153. this.geometry.computeBoundingSphere();
  32154. }
  32155. Box3Helper.prototype = Object.create( LineSegments.prototype );
  32156. Box3Helper.prototype.constructor = Box3Helper;
  32157. Box3Helper.prototype.updateMatrixWorld = function ( force ) {
  32158. var box = this.box;
  32159. if ( box.isEmpty() ) return;
  32160. box.getCenter( this.position );
  32161. box.getSize( this.scale );
  32162. this.scale.multiplyScalar( 0.5 );
  32163. Object3D.prototype.updateMatrixWorld.call( this, force );
  32164. };
  32165. /**
  32166. * @author WestLangley / http://github.com/WestLangley
  32167. */
  32168. function PlaneHelper( plane, size, hex ) {
  32169. this.type = 'PlaneHelper';
  32170. this.plane = plane;
  32171. this.size = ( size === undefined ) ? 1 : size;
  32172. var color = ( hex !== undefined ) ? hex : 0xffff00;
  32173. 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 ];
  32174. var geometry = new BufferGeometry();
  32175. geometry.addAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  32176. geometry.computeBoundingSphere();
  32177. Line.call( this, geometry, new LineBasicMaterial( { color: color } ) );
  32178. //
  32179. var positions2 = [ 1, 1, 1, - 1, 1, 1, - 1, - 1, 1, 1, 1, 1, - 1, - 1, 1, 1, - 1, 1 ];
  32180. var geometry2 = new BufferGeometry();
  32181. geometry2.addAttribute( 'position', new Float32BufferAttribute( positions2, 3 ) );
  32182. geometry2.computeBoundingSphere();
  32183. this.add( new Mesh( geometry2, new MeshBasicMaterial( { color: color, opacity: 0.2, transparent: true, depthWrite: false } ) ) );
  32184. }
  32185. PlaneHelper.prototype = Object.create( Line.prototype );
  32186. PlaneHelper.prototype.constructor = PlaneHelper;
  32187. PlaneHelper.prototype.updateMatrixWorld = function ( force ) {
  32188. var scale = - this.plane.constant;
  32189. if ( Math.abs( scale ) < 1e-8 ) scale = 1e-8; // sign does not matter
  32190. this.scale.set( 0.5 * this.size, 0.5 * this.size, scale );
  32191. this.children[ 0 ].material.side = ( scale < 0 ) ? BackSide : FrontSide; // renderer flips side when determinant < 0; flipping not wanted here
  32192. this.lookAt( this.plane.normal );
  32193. Object3D.prototype.updateMatrixWorld.call( this, force );
  32194. };
  32195. /**
  32196. * @author WestLangley / http://github.com/WestLangley
  32197. * @author zz85 / http://github.com/zz85
  32198. * @author bhouston / http://clara.io
  32199. *
  32200. * Creates an arrow for visualizing directions
  32201. *
  32202. * Parameters:
  32203. * dir - Vector3
  32204. * origin - Vector3
  32205. * length - Number
  32206. * color - color in hex value
  32207. * headLength - Number
  32208. * headWidth - Number
  32209. */
  32210. var lineGeometry, coneGeometry;
  32211. function ArrowHelper( dir, origin, length, color, headLength, headWidth ) {
  32212. // dir is assumed to be normalized
  32213. Object3D.call( this );
  32214. if ( dir === undefined ) dir = new Vector3( 0, 0, 1 );
  32215. if ( origin === undefined ) origin = new Vector3( 0, 0, 0 );
  32216. if ( length === undefined ) length = 1;
  32217. if ( color === undefined ) color = 0xffff00;
  32218. if ( headLength === undefined ) headLength = 0.2 * length;
  32219. if ( headWidth === undefined ) headWidth = 0.2 * headLength;
  32220. if ( lineGeometry === undefined ) {
  32221. lineGeometry = new BufferGeometry();
  32222. lineGeometry.addAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 1, 0 ], 3 ) );
  32223. coneGeometry = new CylinderBufferGeometry( 0, 0.5, 1, 5, 1 );
  32224. coneGeometry.translate( 0, - 0.5, 0 );
  32225. }
  32226. this.position.copy( origin );
  32227. this.line = new Line( lineGeometry, new LineBasicMaterial( { color: color } ) );
  32228. this.line.matrixAutoUpdate = false;
  32229. this.add( this.line );
  32230. this.cone = new Mesh( coneGeometry, new MeshBasicMaterial( { color: color } ) );
  32231. this.cone.matrixAutoUpdate = false;
  32232. this.add( this.cone );
  32233. this.setDirection( dir );
  32234. this.setLength( length, headLength, headWidth );
  32235. }
  32236. ArrowHelper.prototype = Object.create( Object3D.prototype );
  32237. ArrowHelper.prototype.constructor = ArrowHelper;
  32238. ArrowHelper.prototype.setDirection = ( function () {
  32239. var axis = new Vector3();
  32240. var radians;
  32241. return function setDirection( dir ) {
  32242. // dir is assumed to be normalized
  32243. if ( dir.y > 0.99999 ) {
  32244. this.quaternion.set( 0, 0, 0, 1 );
  32245. } else if ( dir.y < - 0.99999 ) {
  32246. this.quaternion.set( 1, 0, 0, 0 );
  32247. } else {
  32248. axis.set( dir.z, 0, - dir.x ).normalize();
  32249. radians = Math.acos( dir.y );
  32250. this.quaternion.setFromAxisAngle( axis, radians );
  32251. }
  32252. };
  32253. }() );
  32254. ArrowHelper.prototype.setLength = function ( length, headLength, headWidth ) {
  32255. if ( headLength === undefined ) headLength = 0.2 * length;
  32256. if ( headWidth === undefined ) headWidth = 0.2 * headLength;
  32257. this.line.scale.set( 1, Math.max( 0, length - headLength ), 1 );
  32258. this.line.updateMatrix();
  32259. this.cone.scale.set( headWidth, headLength, headWidth );
  32260. this.cone.position.y = length;
  32261. this.cone.updateMatrix();
  32262. };
  32263. ArrowHelper.prototype.setColor = function ( color ) {
  32264. this.line.material.color.copy( color );
  32265. this.cone.material.color.copy( color );
  32266. };
  32267. ArrowHelper.prototype.copy = function ( source ) {
  32268. Object3D.prototype.copy.call( this, source, false );
  32269. this.line.copy( source.line );
  32270. this.cone.copy( source.cone );
  32271. return this;
  32272. };
  32273. ArrowHelper.prototype.clone = function () {
  32274. return new this.constructor().copy( this );
  32275. };
  32276. /**
  32277. * @author sroucheray / http://sroucheray.org/
  32278. * @author mrdoob / http://mrdoob.com/
  32279. */
  32280. function AxesHelper( size ) {
  32281. size = size || 1;
  32282. var vertices = [
  32283. 0, 0, 0, size, 0, 0,
  32284. 0, 0, 0, 0, size, 0,
  32285. 0, 0, 0, 0, 0, size
  32286. ];
  32287. var colors = [
  32288. 1, 0, 0, 1, 0.6, 0,
  32289. 0, 1, 0, 0.6, 1, 0,
  32290. 0, 0, 1, 0, 0.6, 1
  32291. ];
  32292. var geometry = new BufferGeometry();
  32293. geometry.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  32294. geometry.addAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  32295. var material = new LineBasicMaterial( { vertexColors: VertexColors } );
  32296. LineSegments.call( this, geometry, material );
  32297. }
  32298. AxesHelper.prototype = Object.create( LineSegments.prototype );
  32299. AxesHelper.prototype.constructor = AxesHelper;
  32300. /**
  32301. * @author mrdoob / http://mrdoob.com/
  32302. */
  32303. function Face4( a, b, c, d, normal, color, materialIndex ) {
  32304. console.warn( 'THREE.Face4 has been removed. A THREE.Face3 will be created instead.' );
  32305. return new Face3( a, b, c, normal, color, materialIndex );
  32306. }
  32307. var LineStrip = 0;
  32308. var LinePieces = 1;
  32309. function MeshFaceMaterial( materials ) {
  32310. console.warn( 'THREE.MeshFaceMaterial has been removed. Use an Array instead.' );
  32311. return materials;
  32312. }
  32313. function MultiMaterial( materials ) {
  32314. if ( materials === undefined ) materials = [];
  32315. console.warn( 'THREE.MultiMaterial has been removed. Use an Array instead.' );
  32316. materials.isMultiMaterial = true;
  32317. materials.materials = materials;
  32318. materials.clone = function () {
  32319. return materials.slice();
  32320. };
  32321. return materials;
  32322. }
  32323. function PointCloud( geometry, material ) {
  32324. console.warn( 'THREE.PointCloud has been renamed to THREE.Points.' );
  32325. return new Points( geometry, material );
  32326. }
  32327. function Particle( material ) {
  32328. console.warn( 'THREE.Particle has been renamed to THREE.Sprite.' );
  32329. return new Sprite( material );
  32330. }
  32331. function ParticleSystem( geometry, material ) {
  32332. console.warn( 'THREE.ParticleSystem has been renamed to THREE.Points.' );
  32333. return new Points( geometry, material );
  32334. }
  32335. function PointCloudMaterial( parameters ) {
  32336. console.warn( 'THREE.PointCloudMaterial has been renamed to THREE.PointsMaterial.' );
  32337. return new PointsMaterial( parameters );
  32338. }
  32339. function ParticleBasicMaterial( parameters ) {
  32340. console.warn( 'THREE.ParticleBasicMaterial has been renamed to THREE.PointsMaterial.' );
  32341. return new PointsMaterial( parameters );
  32342. }
  32343. function ParticleSystemMaterial( parameters ) {
  32344. console.warn( 'THREE.ParticleSystemMaterial has been renamed to THREE.PointsMaterial.' );
  32345. return new PointsMaterial( parameters );
  32346. }
  32347. function Vertex( x, y, z ) {
  32348. console.warn( 'THREE.Vertex has been removed. Use THREE.Vector3 instead.' );
  32349. return new Vector3( x, y, z );
  32350. }
  32351. //
  32352. function DynamicBufferAttribute( array, itemSize ) {
  32353. console.warn( 'THREE.DynamicBufferAttribute has been removed. Use new THREE.BufferAttribute().setDynamic( true ) instead.' );
  32354. return new BufferAttribute( array, itemSize ).setDynamic( true );
  32355. }
  32356. function Int8Attribute( array, itemSize ) {
  32357. console.warn( 'THREE.Int8Attribute has been removed. Use new THREE.Int8BufferAttribute() instead.' );
  32358. return new Int8BufferAttribute( array, itemSize );
  32359. }
  32360. function Uint8Attribute( array, itemSize ) {
  32361. console.warn( 'THREE.Uint8Attribute has been removed. Use new THREE.Uint8BufferAttribute() instead.' );
  32362. return new Uint8BufferAttribute( array, itemSize );
  32363. }
  32364. function Uint8ClampedAttribute( array, itemSize ) {
  32365. console.warn( 'THREE.Uint8ClampedAttribute has been removed. Use new THREE.Uint8ClampedBufferAttribute() instead.' );
  32366. return new Uint8ClampedBufferAttribute( array, itemSize );
  32367. }
  32368. function Int16Attribute( array, itemSize ) {
  32369. console.warn( 'THREE.Int16Attribute has been removed. Use new THREE.Int16BufferAttribute() instead.' );
  32370. return new Int16BufferAttribute( array, itemSize );
  32371. }
  32372. function Uint16Attribute( array, itemSize ) {
  32373. console.warn( 'THREE.Uint16Attribute has been removed. Use new THREE.Uint16BufferAttribute() instead.' );
  32374. return new Uint16BufferAttribute( array, itemSize );
  32375. }
  32376. function Int32Attribute( array, itemSize ) {
  32377. console.warn( 'THREE.Int32Attribute has been removed. Use new THREE.Int32BufferAttribute() instead.' );
  32378. return new Int32BufferAttribute( array, itemSize );
  32379. }
  32380. function Uint32Attribute( array, itemSize ) {
  32381. console.warn( 'THREE.Uint32Attribute has been removed. Use new THREE.Uint32BufferAttribute() instead.' );
  32382. return new Uint32BufferAttribute( array, itemSize );
  32383. }
  32384. function Float32Attribute( array, itemSize ) {
  32385. console.warn( 'THREE.Float32Attribute has been removed. Use new THREE.Float32BufferAttribute() instead.' );
  32386. return new Float32BufferAttribute( array, itemSize );
  32387. }
  32388. function Float64Attribute( array, itemSize ) {
  32389. console.warn( 'THREE.Float64Attribute has been removed. Use new THREE.Float64BufferAttribute() instead.' );
  32390. return new Float64BufferAttribute( array, itemSize );
  32391. }
  32392. //
  32393. Curve.create = function ( construct, getPoint ) {
  32394. console.log( 'THREE.Curve.create() has been deprecated' );
  32395. construct.prototype = Object.create( Curve.prototype );
  32396. construct.prototype.constructor = construct;
  32397. construct.prototype.getPoint = getPoint;
  32398. return construct;
  32399. };
  32400. //
  32401. Object.assign( CurvePath.prototype, {
  32402. createPointsGeometry: function ( divisions ) {
  32403. console.warn( 'THREE.CurvePath: .createPointsGeometry() has been removed. Use new THREE.Geometry().setFromPoints( points ) instead.' );
  32404. // generate geometry from path points (for Line or Points objects)
  32405. var pts = this.getPoints( divisions );
  32406. return this.createGeometry( pts );
  32407. },
  32408. createSpacedPointsGeometry: function ( divisions ) {
  32409. console.warn( 'THREE.CurvePath: .createSpacedPointsGeometry() has been removed. Use new THREE.Geometry().setFromPoints( points ) instead.' );
  32410. // generate geometry from equidistant sampling along the path
  32411. var pts = this.getSpacedPoints( divisions );
  32412. return this.createGeometry( pts );
  32413. },
  32414. createGeometry: function ( points ) {
  32415. console.warn( 'THREE.CurvePath: .createGeometry() has been removed. Use new THREE.Geometry().setFromPoints( points ) instead.' );
  32416. var geometry = new Geometry();
  32417. for ( var i = 0, l = points.length; i < l; i ++ ) {
  32418. var point = points[ i ];
  32419. geometry.vertices.push( new Vector3( point.x, point.y, point.z || 0 ) );
  32420. }
  32421. return geometry;
  32422. }
  32423. } );
  32424. //
  32425. Object.assign( Path.prototype, {
  32426. fromPoints: function ( points ) {
  32427. console.warn( 'THREE.Path: .fromPoints() has been renamed to .setFromPoints().' );
  32428. this.setFromPoints( points );
  32429. }
  32430. } );
  32431. //
  32432. function ClosedSplineCurve3( points ) {
  32433. console.warn( 'THREE.ClosedSplineCurve3 has been deprecated. Use THREE.CatmullRomCurve3 instead.' );
  32434. CatmullRomCurve3.call( this, points );
  32435. this.type = 'catmullrom';
  32436. this.closed = true;
  32437. }
  32438. ClosedSplineCurve3.prototype = Object.create( CatmullRomCurve3.prototype );
  32439. //
  32440. function SplineCurve3( points ) {
  32441. console.warn( 'THREE.SplineCurve3 has been deprecated. Use THREE.CatmullRomCurve3 instead.' );
  32442. CatmullRomCurve3.call( this, points );
  32443. this.type = 'catmullrom';
  32444. }
  32445. SplineCurve3.prototype = Object.create( CatmullRomCurve3.prototype );
  32446. //
  32447. function Spline( points ) {
  32448. console.warn( 'THREE.Spline has been removed. Use THREE.CatmullRomCurve3 instead.' );
  32449. CatmullRomCurve3.call( this, points );
  32450. this.type = 'catmullrom';
  32451. }
  32452. Spline.prototype = Object.create( CatmullRomCurve3.prototype );
  32453. Object.assign( Spline.prototype, {
  32454. initFromArray: function ( /* a */ ) {
  32455. console.error( 'THREE.Spline: .initFromArray() has been removed.' );
  32456. },
  32457. getControlPointsArray: function ( /* optionalTarget */ ) {
  32458. console.error( 'THREE.Spline: .getControlPointsArray() has been removed.' );
  32459. },
  32460. reparametrizeByArcLength: function ( /* samplingCoef */ ) {
  32461. console.error( 'THREE.Spline: .reparametrizeByArcLength() has been removed.' );
  32462. }
  32463. } );
  32464. //
  32465. function AxisHelper( size ) {
  32466. console.warn( 'THREE.AxisHelper has been renamed to THREE.AxesHelper.' );
  32467. return new AxesHelper( size );
  32468. }
  32469. function BoundingBoxHelper( object, color ) {
  32470. console.warn( 'THREE.BoundingBoxHelper has been deprecated. Creating a THREE.BoxHelper instead.' );
  32471. return new BoxHelper( object, color );
  32472. }
  32473. function EdgesHelper( object, hex ) {
  32474. console.warn( 'THREE.EdgesHelper has been removed. Use THREE.EdgesGeometry instead.' );
  32475. return new LineSegments( new EdgesGeometry( object.geometry ), new LineBasicMaterial( { color: hex !== undefined ? hex : 0xffffff } ) );
  32476. }
  32477. GridHelper.prototype.setColors = function () {
  32478. console.error( 'THREE.GridHelper: setColors() has been deprecated, pass them in the constructor instead.' );
  32479. };
  32480. SkeletonHelper.prototype.update = function () {
  32481. console.error( 'THREE.SkeletonHelper: update() no longer needs to be called.' );
  32482. };
  32483. function WireframeHelper( object, hex ) {
  32484. console.warn( 'THREE.WireframeHelper has been removed. Use THREE.WireframeGeometry instead.' );
  32485. return new LineSegments( new WireframeGeometry( object.geometry ), new LineBasicMaterial( { color: hex !== undefined ? hex : 0xffffff } ) );
  32486. }
  32487. //
  32488. Object.assign( Loader.prototype, {
  32489. extractUrlBase: function ( url ) {
  32490. console.warn( 'THREE.Loader: .extractUrlBase() has been deprecated. Use THREE.LoaderUtils.extractUrlBase() instead.' );
  32491. return LoaderUtils.extractUrlBase( url );
  32492. }
  32493. } );
  32494. function XHRLoader( manager ) {
  32495. console.warn( 'THREE.XHRLoader has been renamed to THREE.FileLoader.' );
  32496. return new FileLoader( manager );
  32497. }
  32498. function BinaryTextureLoader( manager ) {
  32499. console.warn( 'THREE.BinaryTextureLoader has been renamed to THREE.DataTextureLoader.' );
  32500. return new DataTextureLoader( manager );
  32501. }
  32502. Object.assign( ObjectLoader.prototype, {
  32503. setTexturePath: function ( value ) {
  32504. console.warn( 'THREE.ObjectLoader: .setTexturePath() has been renamed to .setResourcePath().' );
  32505. return this.setResourcePath( value );
  32506. }
  32507. } );
  32508. //
  32509. Object.assign( Box2.prototype, {
  32510. center: function ( optionalTarget ) {
  32511. console.warn( 'THREE.Box2: .center() has been renamed to .getCenter().' );
  32512. return this.getCenter( optionalTarget );
  32513. },
  32514. empty: function () {
  32515. console.warn( 'THREE.Box2: .empty() has been renamed to .isEmpty().' );
  32516. return this.isEmpty();
  32517. },
  32518. isIntersectionBox: function ( box ) {
  32519. console.warn( 'THREE.Box2: .isIntersectionBox() has been renamed to .intersectsBox().' );
  32520. return this.intersectsBox( box );
  32521. },
  32522. size: function ( optionalTarget ) {
  32523. console.warn( 'THREE.Box2: .size() has been renamed to .getSize().' );
  32524. return this.getSize( optionalTarget );
  32525. }
  32526. } );
  32527. Object.assign( Box3.prototype, {
  32528. center: function ( optionalTarget ) {
  32529. console.warn( 'THREE.Box3: .center() has been renamed to .getCenter().' );
  32530. return this.getCenter( optionalTarget );
  32531. },
  32532. empty: function () {
  32533. console.warn( 'THREE.Box3: .empty() has been renamed to .isEmpty().' );
  32534. return this.isEmpty();
  32535. },
  32536. isIntersectionBox: function ( box ) {
  32537. console.warn( 'THREE.Box3: .isIntersectionBox() has been renamed to .intersectsBox().' );
  32538. return this.intersectsBox( box );
  32539. },
  32540. isIntersectionSphere: function ( sphere ) {
  32541. console.warn( 'THREE.Box3: .isIntersectionSphere() has been renamed to .intersectsSphere().' );
  32542. return this.intersectsSphere( sphere );
  32543. },
  32544. size: function ( optionalTarget ) {
  32545. console.warn( 'THREE.Box3: .size() has been renamed to .getSize().' );
  32546. return this.getSize( optionalTarget );
  32547. }
  32548. } );
  32549. Line3.prototype.center = function ( optionalTarget ) {
  32550. console.warn( 'THREE.Line3: .center() has been renamed to .getCenter().' );
  32551. return this.getCenter( optionalTarget );
  32552. };
  32553. Object.assign( _Math, {
  32554. random16: function () {
  32555. console.warn( 'THREE.Math: .random16() has been deprecated. Use Math.random() instead.' );
  32556. return Math.random();
  32557. },
  32558. nearestPowerOfTwo: function ( value ) {
  32559. console.warn( 'THREE.Math: .nearestPowerOfTwo() has been renamed to .floorPowerOfTwo().' );
  32560. return _Math.floorPowerOfTwo( value );
  32561. },
  32562. nextPowerOfTwo: function ( value ) {
  32563. console.warn( 'THREE.Math: .nextPowerOfTwo() has been renamed to .ceilPowerOfTwo().' );
  32564. return _Math.ceilPowerOfTwo( value );
  32565. }
  32566. } );
  32567. Object.assign( Matrix3.prototype, {
  32568. flattenToArrayOffset: function ( array, offset ) {
  32569. console.warn( "THREE.Matrix3: .flattenToArrayOffset() has been deprecated. Use .toArray() instead." );
  32570. return this.toArray( array, offset );
  32571. },
  32572. multiplyVector3: function ( vector ) {
  32573. console.warn( 'THREE.Matrix3: .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.' );
  32574. return vector.applyMatrix3( this );
  32575. },
  32576. multiplyVector3Array: function ( /* a */ ) {
  32577. console.error( 'THREE.Matrix3: .multiplyVector3Array() has been removed.' );
  32578. },
  32579. applyToBuffer: function ( buffer /*, offset, length */ ) {
  32580. console.warn( 'THREE.Matrix3: .applyToBuffer() has been removed. Use matrix.applyToBufferAttribute( attribute ) instead.' );
  32581. return this.applyToBufferAttribute( buffer );
  32582. },
  32583. applyToVector3Array: function ( /* array, offset, length */ ) {
  32584. console.error( 'THREE.Matrix3: .applyToVector3Array() has been removed.' );
  32585. }
  32586. } );
  32587. Object.assign( Matrix4.prototype, {
  32588. extractPosition: function ( m ) {
  32589. console.warn( 'THREE.Matrix4: .extractPosition() has been renamed to .copyPosition().' );
  32590. return this.copyPosition( m );
  32591. },
  32592. flattenToArrayOffset: function ( array, offset ) {
  32593. console.warn( "THREE.Matrix4: .flattenToArrayOffset() has been deprecated. Use .toArray() instead." );
  32594. return this.toArray( array, offset );
  32595. },
  32596. getPosition: function () {
  32597. var v1;
  32598. return function getPosition() {
  32599. if ( v1 === undefined ) v1 = new Vector3();
  32600. console.warn( 'THREE.Matrix4: .getPosition() has been removed. Use Vector3.setFromMatrixPosition( matrix ) instead.' );
  32601. return v1.setFromMatrixColumn( this, 3 );
  32602. };
  32603. }(),
  32604. setRotationFromQuaternion: function ( q ) {
  32605. console.warn( 'THREE.Matrix4: .setRotationFromQuaternion() has been renamed to .makeRotationFromQuaternion().' );
  32606. return this.makeRotationFromQuaternion( q );
  32607. },
  32608. multiplyToArray: function () {
  32609. console.warn( 'THREE.Matrix4: .multiplyToArray() has been removed.' );
  32610. },
  32611. multiplyVector3: function ( vector ) {
  32612. console.warn( 'THREE.Matrix4: .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  32613. return vector.applyMatrix4( this );
  32614. },
  32615. multiplyVector4: function ( vector ) {
  32616. console.warn( 'THREE.Matrix4: .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  32617. return vector.applyMatrix4( this );
  32618. },
  32619. multiplyVector3Array: function ( /* a */ ) {
  32620. console.error( 'THREE.Matrix4: .multiplyVector3Array() has been removed.' );
  32621. },
  32622. rotateAxis: function ( v ) {
  32623. console.warn( 'THREE.Matrix4: .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead.' );
  32624. v.transformDirection( this );
  32625. },
  32626. crossVector: function ( vector ) {
  32627. console.warn( 'THREE.Matrix4: .crossVector() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  32628. return vector.applyMatrix4( this );
  32629. },
  32630. translate: function () {
  32631. console.error( 'THREE.Matrix4: .translate() has been removed.' );
  32632. },
  32633. rotateX: function () {
  32634. console.error( 'THREE.Matrix4: .rotateX() has been removed.' );
  32635. },
  32636. rotateY: function () {
  32637. console.error( 'THREE.Matrix4: .rotateY() has been removed.' );
  32638. },
  32639. rotateZ: function () {
  32640. console.error( 'THREE.Matrix4: .rotateZ() has been removed.' );
  32641. },
  32642. rotateByAxis: function () {
  32643. console.error( 'THREE.Matrix4: .rotateByAxis() has been removed.' );
  32644. },
  32645. applyToBuffer: function ( buffer /*, offset, length */ ) {
  32646. console.warn( 'THREE.Matrix4: .applyToBuffer() has been removed. Use matrix.applyToBufferAttribute( attribute ) instead.' );
  32647. return this.applyToBufferAttribute( buffer );
  32648. },
  32649. applyToVector3Array: function ( /* array, offset, length */ ) {
  32650. console.error( 'THREE.Matrix4: .applyToVector3Array() has been removed.' );
  32651. },
  32652. makeFrustum: function ( left, right, bottom, top, near, far ) {
  32653. console.warn( 'THREE.Matrix4: .makeFrustum() has been removed. Use .makePerspective( left, right, top, bottom, near, far ) instead.' );
  32654. return this.makePerspective( left, right, top, bottom, near, far );
  32655. }
  32656. } );
  32657. Plane.prototype.isIntersectionLine = function ( line ) {
  32658. console.warn( 'THREE.Plane: .isIntersectionLine() has been renamed to .intersectsLine().' );
  32659. return this.intersectsLine( line );
  32660. };
  32661. Quaternion.prototype.multiplyVector3 = function ( vector ) {
  32662. console.warn( 'THREE.Quaternion: .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.' );
  32663. return vector.applyQuaternion( this );
  32664. };
  32665. Object.assign( Ray.prototype, {
  32666. isIntersectionBox: function ( box ) {
  32667. console.warn( 'THREE.Ray: .isIntersectionBox() has been renamed to .intersectsBox().' );
  32668. return this.intersectsBox( box );
  32669. },
  32670. isIntersectionPlane: function ( plane ) {
  32671. console.warn( 'THREE.Ray: .isIntersectionPlane() has been renamed to .intersectsPlane().' );
  32672. return this.intersectsPlane( plane );
  32673. },
  32674. isIntersectionSphere: function ( sphere ) {
  32675. console.warn( 'THREE.Ray: .isIntersectionSphere() has been renamed to .intersectsSphere().' );
  32676. return this.intersectsSphere( sphere );
  32677. }
  32678. } );
  32679. Object.assign( Triangle.prototype, {
  32680. area: function () {
  32681. console.warn( 'THREE.Triangle: .area() has been renamed to .getArea().' );
  32682. return this.getArea();
  32683. },
  32684. barycoordFromPoint: function ( point, target ) {
  32685. console.warn( 'THREE.Triangle: .barycoordFromPoint() has been renamed to .getBarycoord().' );
  32686. return this.getBarycoord( point, target );
  32687. },
  32688. midpoint: function ( target ) {
  32689. console.warn( 'THREE.Triangle: .midpoint() has been renamed to .getMidpoint().' );
  32690. return this.getMidpoint( target );
  32691. },
  32692. normal: function ( target ) {
  32693. console.warn( 'THREE.Triangle: .normal() has been renamed to .getNormal().' );
  32694. return this.getNormal( target );
  32695. },
  32696. plane: function ( target ) {
  32697. console.warn( 'THREE.Triangle: .plane() has been renamed to .getPlane().' );
  32698. return this.getPlane( target );
  32699. }
  32700. } );
  32701. Object.assign( Triangle, {
  32702. barycoordFromPoint: function ( point, a, b, c, target ) {
  32703. console.warn( 'THREE.Triangle: .barycoordFromPoint() has been renamed to .getBarycoord().' );
  32704. return Triangle.getBarycoord( point, a, b, c, target );
  32705. },
  32706. normal: function ( a, b, c, target ) {
  32707. console.warn( 'THREE.Triangle: .normal() has been renamed to .getNormal().' );
  32708. return Triangle.getNormal( a, b, c, target );
  32709. }
  32710. } );
  32711. Object.assign( Shape.prototype, {
  32712. extractAllPoints: function ( divisions ) {
  32713. console.warn( 'THREE.Shape: .extractAllPoints() has been removed. Use .extractPoints() instead.' );
  32714. return this.extractPoints( divisions );
  32715. },
  32716. extrude: function ( options ) {
  32717. console.warn( 'THREE.Shape: .extrude() has been removed. Use ExtrudeGeometry() instead.' );
  32718. return new ExtrudeGeometry( this, options );
  32719. },
  32720. makeGeometry: function ( options ) {
  32721. console.warn( 'THREE.Shape: .makeGeometry() has been removed. Use ShapeGeometry() instead.' );
  32722. return new ShapeGeometry( this, options );
  32723. }
  32724. } );
  32725. Object.assign( Vector2.prototype, {
  32726. fromAttribute: function ( attribute, index, offset ) {
  32727. console.warn( 'THREE.Vector2: .fromAttribute() has been renamed to .fromBufferAttribute().' );
  32728. return this.fromBufferAttribute( attribute, index, offset );
  32729. },
  32730. distanceToManhattan: function ( v ) {
  32731. console.warn( 'THREE.Vector2: .distanceToManhattan() has been renamed to .manhattanDistanceTo().' );
  32732. return this.manhattanDistanceTo( v );
  32733. },
  32734. lengthManhattan: function () {
  32735. console.warn( 'THREE.Vector2: .lengthManhattan() has been renamed to .manhattanLength().' );
  32736. return this.manhattanLength();
  32737. }
  32738. } );
  32739. Object.assign( Vector3.prototype, {
  32740. setEulerFromRotationMatrix: function () {
  32741. console.error( 'THREE.Vector3: .setEulerFromRotationMatrix() has been removed. Use Euler.setFromRotationMatrix() instead.' );
  32742. },
  32743. setEulerFromQuaternion: function () {
  32744. console.error( 'THREE.Vector3: .setEulerFromQuaternion() has been removed. Use Euler.setFromQuaternion() instead.' );
  32745. },
  32746. getPositionFromMatrix: function ( m ) {
  32747. console.warn( 'THREE.Vector3: .getPositionFromMatrix() has been renamed to .setFromMatrixPosition().' );
  32748. return this.setFromMatrixPosition( m );
  32749. },
  32750. getScaleFromMatrix: function ( m ) {
  32751. console.warn( 'THREE.Vector3: .getScaleFromMatrix() has been renamed to .setFromMatrixScale().' );
  32752. return this.setFromMatrixScale( m );
  32753. },
  32754. getColumnFromMatrix: function ( index, matrix ) {
  32755. console.warn( 'THREE.Vector3: .getColumnFromMatrix() has been renamed to .setFromMatrixColumn().' );
  32756. return this.setFromMatrixColumn( matrix, index );
  32757. },
  32758. applyProjection: function ( m ) {
  32759. console.warn( 'THREE.Vector3: .applyProjection() has been removed. Use .applyMatrix4( m ) instead.' );
  32760. return this.applyMatrix4( m );
  32761. },
  32762. fromAttribute: function ( attribute, index, offset ) {
  32763. console.warn( 'THREE.Vector3: .fromAttribute() has been renamed to .fromBufferAttribute().' );
  32764. return this.fromBufferAttribute( attribute, index, offset );
  32765. },
  32766. distanceToManhattan: function ( v ) {
  32767. console.warn( 'THREE.Vector3: .distanceToManhattan() has been renamed to .manhattanDistanceTo().' );
  32768. return this.manhattanDistanceTo( v );
  32769. },
  32770. lengthManhattan: function () {
  32771. console.warn( 'THREE.Vector3: .lengthManhattan() has been renamed to .manhattanLength().' );
  32772. return this.manhattanLength();
  32773. }
  32774. } );
  32775. Object.assign( Vector4.prototype, {
  32776. fromAttribute: function ( attribute, index, offset ) {
  32777. console.warn( 'THREE.Vector4: .fromAttribute() has been renamed to .fromBufferAttribute().' );
  32778. return this.fromBufferAttribute( attribute, index, offset );
  32779. },
  32780. lengthManhattan: function () {
  32781. console.warn( 'THREE.Vector4: .lengthManhattan() has been renamed to .manhattanLength().' );
  32782. return this.manhattanLength();
  32783. }
  32784. } );
  32785. //
  32786. Object.assign( Geometry.prototype, {
  32787. computeTangents: function () {
  32788. console.error( 'THREE.Geometry: .computeTangents() has been removed.' );
  32789. },
  32790. computeLineDistances: function () {
  32791. console.error( 'THREE.Geometry: .computeLineDistances() has been removed. Use THREE.Line.computeLineDistances() instead.' );
  32792. }
  32793. } );
  32794. Object.assign( Object3D.prototype, {
  32795. getChildByName: function ( name ) {
  32796. console.warn( 'THREE.Object3D: .getChildByName() has been renamed to .getObjectByName().' );
  32797. return this.getObjectByName( name );
  32798. },
  32799. renderDepth: function () {
  32800. console.warn( 'THREE.Object3D: .renderDepth has been removed. Use .renderOrder, instead.' );
  32801. },
  32802. translate: function ( distance, axis ) {
  32803. console.warn( 'THREE.Object3D: .translate() has been removed. Use .translateOnAxis( axis, distance ) instead.' );
  32804. return this.translateOnAxis( axis, distance );
  32805. },
  32806. getWorldRotation: function () {
  32807. console.error( 'THREE.Object3D: .getWorldRotation() has been removed. Use THREE.Object3D.getWorldQuaternion( target ) instead.' );
  32808. }
  32809. } );
  32810. Object.defineProperties( Object3D.prototype, {
  32811. eulerOrder: {
  32812. get: function () {
  32813. console.warn( 'THREE.Object3D: .eulerOrder is now .rotation.order.' );
  32814. return this.rotation.order;
  32815. },
  32816. set: function ( value ) {
  32817. console.warn( 'THREE.Object3D: .eulerOrder is now .rotation.order.' );
  32818. this.rotation.order = value;
  32819. }
  32820. },
  32821. useQuaternion: {
  32822. get: function () {
  32823. console.warn( 'THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.' );
  32824. },
  32825. set: function () {
  32826. console.warn( 'THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.' );
  32827. }
  32828. }
  32829. } );
  32830. Object.defineProperties( LOD.prototype, {
  32831. objects: {
  32832. get: function () {
  32833. console.warn( 'THREE.LOD: .objects has been renamed to .levels.' );
  32834. return this.levels;
  32835. }
  32836. }
  32837. } );
  32838. Object.defineProperty( Skeleton.prototype, 'useVertexTexture', {
  32839. get: function () {
  32840. console.warn( 'THREE.Skeleton: useVertexTexture has been removed.' );
  32841. },
  32842. set: function () {
  32843. console.warn( 'THREE.Skeleton: useVertexTexture has been removed.' );
  32844. }
  32845. } );
  32846. SkinnedMesh.prototype.initBones = function () {
  32847. console.error( 'THREE.SkinnedMesh: initBones() has been removed.' );
  32848. };
  32849. Object.defineProperty( Curve.prototype, '__arcLengthDivisions', {
  32850. get: function () {
  32851. console.warn( 'THREE.Curve: .__arcLengthDivisions is now .arcLengthDivisions.' );
  32852. return this.arcLengthDivisions;
  32853. },
  32854. set: function ( value ) {
  32855. console.warn( 'THREE.Curve: .__arcLengthDivisions is now .arcLengthDivisions.' );
  32856. this.arcLengthDivisions = value;
  32857. }
  32858. } );
  32859. //
  32860. PerspectiveCamera.prototype.setLens = function ( focalLength, filmGauge ) {
  32861. console.warn( "THREE.PerspectiveCamera.setLens is deprecated. " +
  32862. "Use .setFocalLength and .filmGauge for a photographic setup." );
  32863. if ( filmGauge !== undefined ) this.filmGauge = filmGauge;
  32864. this.setFocalLength( focalLength );
  32865. };
  32866. //
  32867. Object.defineProperties( Light.prototype, {
  32868. onlyShadow: {
  32869. set: function () {
  32870. console.warn( 'THREE.Light: .onlyShadow has been removed.' );
  32871. }
  32872. },
  32873. shadowCameraFov: {
  32874. set: function ( value ) {
  32875. console.warn( 'THREE.Light: .shadowCameraFov is now .shadow.camera.fov.' );
  32876. this.shadow.camera.fov = value;
  32877. }
  32878. },
  32879. shadowCameraLeft: {
  32880. set: function ( value ) {
  32881. console.warn( 'THREE.Light: .shadowCameraLeft is now .shadow.camera.left.' );
  32882. this.shadow.camera.left = value;
  32883. }
  32884. },
  32885. shadowCameraRight: {
  32886. set: function ( value ) {
  32887. console.warn( 'THREE.Light: .shadowCameraRight is now .shadow.camera.right.' );
  32888. this.shadow.camera.right = value;
  32889. }
  32890. },
  32891. shadowCameraTop: {
  32892. set: function ( value ) {
  32893. console.warn( 'THREE.Light: .shadowCameraTop is now .shadow.camera.top.' );
  32894. this.shadow.camera.top = value;
  32895. }
  32896. },
  32897. shadowCameraBottom: {
  32898. set: function ( value ) {
  32899. console.warn( 'THREE.Light: .shadowCameraBottom is now .shadow.camera.bottom.' );
  32900. this.shadow.camera.bottom = value;
  32901. }
  32902. },
  32903. shadowCameraNear: {
  32904. set: function ( value ) {
  32905. console.warn( 'THREE.Light: .shadowCameraNear is now .shadow.camera.near.' );
  32906. this.shadow.camera.near = value;
  32907. }
  32908. },
  32909. shadowCameraFar: {
  32910. set: function ( value ) {
  32911. console.warn( 'THREE.Light: .shadowCameraFar is now .shadow.camera.far.' );
  32912. this.shadow.camera.far = value;
  32913. }
  32914. },
  32915. shadowCameraVisible: {
  32916. set: function () {
  32917. console.warn( 'THREE.Light: .shadowCameraVisible has been removed. Use new THREE.CameraHelper( light.shadow.camera ) instead.' );
  32918. }
  32919. },
  32920. shadowBias: {
  32921. set: function ( value ) {
  32922. console.warn( 'THREE.Light: .shadowBias is now .shadow.bias.' );
  32923. this.shadow.bias = value;
  32924. }
  32925. },
  32926. shadowDarkness: {
  32927. set: function () {
  32928. console.warn( 'THREE.Light: .shadowDarkness has been removed.' );
  32929. }
  32930. },
  32931. shadowMapWidth: {
  32932. set: function ( value ) {
  32933. console.warn( 'THREE.Light: .shadowMapWidth is now .shadow.mapSize.width.' );
  32934. this.shadow.mapSize.width = value;
  32935. }
  32936. },
  32937. shadowMapHeight: {
  32938. set: function ( value ) {
  32939. console.warn( 'THREE.Light: .shadowMapHeight is now .shadow.mapSize.height.' );
  32940. this.shadow.mapSize.height = value;
  32941. }
  32942. }
  32943. } );
  32944. //
  32945. Object.defineProperties( BufferAttribute.prototype, {
  32946. length: {
  32947. get: function () {
  32948. console.warn( 'THREE.BufferAttribute: .length has been deprecated. Use .count instead.' );
  32949. return this.array.length;
  32950. }
  32951. },
  32952. copyIndicesArray: function ( /* indices */ ) {
  32953. console.error( 'THREE.BufferAttribute: .copyIndicesArray() has been removed.' );
  32954. }
  32955. } );
  32956. Object.assign( BufferGeometry.prototype, {
  32957. addIndex: function ( index ) {
  32958. console.warn( 'THREE.BufferGeometry: .addIndex() has been renamed to .setIndex().' );
  32959. this.setIndex( index );
  32960. },
  32961. addDrawCall: function ( start, count, indexOffset ) {
  32962. if ( indexOffset !== undefined ) {
  32963. console.warn( 'THREE.BufferGeometry: .addDrawCall() no longer supports indexOffset.' );
  32964. }
  32965. console.warn( 'THREE.BufferGeometry: .addDrawCall() is now .addGroup().' );
  32966. this.addGroup( start, count );
  32967. },
  32968. clearDrawCalls: function () {
  32969. console.warn( 'THREE.BufferGeometry: .clearDrawCalls() is now .clearGroups().' );
  32970. this.clearGroups();
  32971. },
  32972. computeTangents: function () {
  32973. console.warn( 'THREE.BufferGeometry: .computeTangents() has been removed.' );
  32974. },
  32975. computeOffsets: function () {
  32976. console.warn( 'THREE.BufferGeometry: .computeOffsets() has been removed.' );
  32977. }
  32978. } );
  32979. Object.defineProperties( BufferGeometry.prototype, {
  32980. drawcalls: {
  32981. get: function () {
  32982. console.error( 'THREE.BufferGeometry: .drawcalls has been renamed to .groups.' );
  32983. return this.groups;
  32984. }
  32985. },
  32986. offsets: {
  32987. get: function () {
  32988. console.warn( 'THREE.BufferGeometry: .offsets has been renamed to .groups.' );
  32989. return this.groups;
  32990. }
  32991. }
  32992. } );
  32993. //
  32994. Object.assign( ExtrudeBufferGeometry.prototype, {
  32995. getArrays: function () {
  32996. console.error( 'THREE.ExtrudeBufferGeometry: .getArrays() has been removed.' );
  32997. },
  32998. addShapeList: function () {
  32999. console.error( 'THREE.ExtrudeBufferGeometry: .addShapeList() has been removed.' );
  33000. },
  33001. addShape: function () {
  33002. console.error( 'THREE.ExtrudeBufferGeometry: .addShape() has been removed.' );
  33003. }
  33004. } );
  33005. //
  33006. Object.defineProperties( Uniform.prototype, {
  33007. dynamic: {
  33008. set: function () {
  33009. console.warn( 'THREE.Uniform: .dynamic has been removed. Use object.onBeforeRender() instead.' );
  33010. }
  33011. },
  33012. onUpdate: {
  33013. value: function () {
  33014. console.warn( 'THREE.Uniform: .onUpdate() has been removed. Use object.onBeforeRender() instead.' );
  33015. return this;
  33016. }
  33017. }
  33018. } );
  33019. //
  33020. Object.defineProperties( Material.prototype, {
  33021. wrapAround: {
  33022. get: function () {
  33023. console.warn( 'THREE.Material: .wrapAround has been removed.' );
  33024. },
  33025. set: function () {
  33026. console.warn( 'THREE.Material: .wrapAround has been removed.' );
  33027. }
  33028. },
  33029. overdraw: {
  33030. get: function () {
  33031. console.warn( 'THREE.Material: .overdraw has been removed.' );
  33032. },
  33033. set: function () {
  33034. console.warn( 'THREE.Material: .overdraw has been removed.' );
  33035. }
  33036. },
  33037. wrapRGB: {
  33038. get: function () {
  33039. console.warn( 'THREE.Material: .wrapRGB has been removed.' );
  33040. return new Color();
  33041. }
  33042. },
  33043. shading: {
  33044. get: function () {
  33045. console.error( 'THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.' );
  33046. },
  33047. set: function ( value ) {
  33048. console.warn( 'THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.' );
  33049. this.flatShading = ( value === FlatShading );
  33050. }
  33051. }
  33052. } );
  33053. Object.defineProperties( MeshPhongMaterial.prototype, {
  33054. metal: {
  33055. get: function () {
  33056. console.warn( 'THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead.' );
  33057. return false;
  33058. },
  33059. set: function () {
  33060. console.warn( 'THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead' );
  33061. }
  33062. }
  33063. } );
  33064. Object.defineProperties( ShaderMaterial.prototype, {
  33065. derivatives: {
  33066. get: function () {
  33067. console.warn( 'THREE.ShaderMaterial: .derivatives has been moved to .extensions.derivatives.' );
  33068. return this.extensions.derivatives;
  33069. },
  33070. set: function ( value ) {
  33071. console.warn( 'THREE. ShaderMaterial: .derivatives has been moved to .extensions.derivatives.' );
  33072. this.extensions.derivatives = value;
  33073. }
  33074. }
  33075. } );
  33076. //
  33077. Object.assign( WebGLRenderer.prototype, {
  33078. clearTarget: function ( renderTarget, color, depth, stencil ) {
  33079. console.warn( 'THREE.WebGLRenderer: .clearTarget() has been deprecated. Use .setRenderTarget() and .clear() instead.' );
  33080. this.setRenderTarget( renderTarget );
  33081. this.clear( color, depth, stencil );
  33082. },
  33083. animate: function ( callback ) {
  33084. console.warn( 'THREE.WebGLRenderer: .animate() is now .setAnimationLoop().' );
  33085. this.setAnimationLoop( callback );
  33086. },
  33087. getCurrentRenderTarget: function () {
  33088. console.warn( 'THREE.WebGLRenderer: .getCurrentRenderTarget() is now .getRenderTarget().' );
  33089. return this.getRenderTarget();
  33090. },
  33091. getMaxAnisotropy: function () {
  33092. console.warn( 'THREE.WebGLRenderer: .getMaxAnisotropy() is now .capabilities.getMaxAnisotropy().' );
  33093. return this.capabilities.getMaxAnisotropy();
  33094. },
  33095. getPrecision: function () {
  33096. console.warn( 'THREE.WebGLRenderer: .getPrecision() is now .capabilities.precision.' );
  33097. return this.capabilities.precision;
  33098. },
  33099. resetGLState: function () {
  33100. console.warn( 'THREE.WebGLRenderer: .resetGLState() is now .state.reset().' );
  33101. return this.state.reset();
  33102. },
  33103. supportsFloatTextures: function () {
  33104. console.warn( 'THREE.WebGLRenderer: .supportsFloatTextures() is now .extensions.get( \'OES_texture_float\' ).' );
  33105. return this.extensions.get( 'OES_texture_float' );
  33106. },
  33107. supportsHalfFloatTextures: function () {
  33108. console.warn( 'THREE.WebGLRenderer: .supportsHalfFloatTextures() is now .extensions.get( \'OES_texture_half_float\' ).' );
  33109. return this.extensions.get( 'OES_texture_half_float' );
  33110. },
  33111. supportsStandardDerivatives: function () {
  33112. console.warn( 'THREE.WebGLRenderer: .supportsStandardDerivatives() is now .extensions.get( \'OES_standard_derivatives\' ).' );
  33113. return this.extensions.get( 'OES_standard_derivatives' );
  33114. },
  33115. supportsCompressedTextureS3TC: function () {
  33116. console.warn( 'THREE.WebGLRenderer: .supportsCompressedTextureS3TC() is now .extensions.get( \'WEBGL_compressed_texture_s3tc\' ).' );
  33117. return this.extensions.get( 'WEBGL_compressed_texture_s3tc' );
  33118. },
  33119. supportsCompressedTexturePVRTC: function () {
  33120. console.warn( 'THREE.WebGLRenderer: .supportsCompressedTexturePVRTC() is now .extensions.get( \'WEBGL_compressed_texture_pvrtc\' ).' );
  33121. return this.extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  33122. },
  33123. supportsBlendMinMax: function () {
  33124. console.warn( 'THREE.WebGLRenderer: .supportsBlendMinMax() is now .extensions.get( \'EXT_blend_minmax\' ).' );
  33125. return this.extensions.get( 'EXT_blend_minmax' );
  33126. },
  33127. supportsVertexTextures: function () {
  33128. console.warn( 'THREE.WebGLRenderer: .supportsVertexTextures() is now .capabilities.vertexTextures.' );
  33129. return this.capabilities.vertexTextures;
  33130. },
  33131. supportsInstancedArrays: function () {
  33132. console.warn( 'THREE.WebGLRenderer: .supportsInstancedArrays() is now .extensions.get( \'ANGLE_instanced_arrays\' ).' );
  33133. return this.extensions.get( 'ANGLE_instanced_arrays' );
  33134. },
  33135. enableScissorTest: function ( boolean ) {
  33136. console.warn( 'THREE.WebGLRenderer: .enableScissorTest() is now .setScissorTest().' );
  33137. this.setScissorTest( boolean );
  33138. },
  33139. initMaterial: function () {
  33140. console.warn( 'THREE.WebGLRenderer: .initMaterial() has been removed.' );
  33141. },
  33142. addPrePlugin: function () {
  33143. console.warn( 'THREE.WebGLRenderer: .addPrePlugin() has been removed.' );
  33144. },
  33145. addPostPlugin: function () {
  33146. console.warn( 'THREE.WebGLRenderer: .addPostPlugin() has been removed.' );
  33147. },
  33148. updateShadowMap: function () {
  33149. console.warn( 'THREE.WebGLRenderer: .updateShadowMap() has been removed.' );
  33150. },
  33151. setFaceCulling: function () {
  33152. console.warn( 'THREE.WebGLRenderer: .setFaceCulling() has been removed.' );
  33153. }
  33154. } );
  33155. Object.defineProperties( WebGLRenderer.prototype, {
  33156. shadowMapEnabled: {
  33157. get: function () {
  33158. return this.shadowMap.enabled;
  33159. },
  33160. set: function ( value ) {
  33161. console.warn( 'THREE.WebGLRenderer: .shadowMapEnabled is now .shadowMap.enabled.' );
  33162. this.shadowMap.enabled = value;
  33163. }
  33164. },
  33165. shadowMapType: {
  33166. get: function () {
  33167. return this.shadowMap.type;
  33168. },
  33169. set: function ( value ) {
  33170. console.warn( 'THREE.WebGLRenderer: .shadowMapType is now .shadowMap.type.' );
  33171. this.shadowMap.type = value;
  33172. }
  33173. },
  33174. shadowMapCullFace: {
  33175. get: function () {
  33176. console.warn( 'THREE.WebGLRenderer: .shadowMapCullFace has been removed. Set Material.shadowSide instead.' );
  33177. return undefined;
  33178. },
  33179. set: function ( /* value */ ) {
  33180. console.warn( 'THREE.WebGLRenderer: .shadowMapCullFace has been removed. Set Material.shadowSide instead.' );
  33181. }
  33182. }
  33183. } );
  33184. Object.defineProperties( WebGLShadowMap.prototype, {
  33185. cullFace: {
  33186. get: function () {
  33187. console.warn( 'THREE.WebGLRenderer: .shadowMap.cullFace has been removed. Set Material.shadowSide instead.' );
  33188. return undefined;
  33189. },
  33190. set: function ( /* cullFace */ ) {
  33191. console.warn( 'THREE.WebGLRenderer: .shadowMap.cullFace has been removed. Set Material.shadowSide instead.' );
  33192. }
  33193. },
  33194. renderReverseSided: {
  33195. get: function () {
  33196. console.warn( 'THREE.WebGLRenderer: .shadowMap.renderReverseSided has been removed. Set Material.shadowSide instead.' );
  33197. return undefined;
  33198. },
  33199. set: function () {
  33200. console.warn( 'THREE.WebGLRenderer: .shadowMap.renderReverseSided has been removed. Set Material.shadowSide instead.' );
  33201. }
  33202. },
  33203. renderSingleSided: {
  33204. get: function () {
  33205. console.warn( 'THREE.WebGLRenderer: .shadowMap.renderSingleSided has been removed. Set Material.shadowSide instead.' );
  33206. return undefined;
  33207. },
  33208. set: function () {
  33209. console.warn( 'THREE.WebGLRenderer: .shadowMap.renderSingleSided has been removed. Set Material.shadowSide instead.' );
  33210. }
  33211. }
  33212. } );
  33213. //
  33214. Object.defineProperties( WebGLRenderTargetCube.prototype, {
  33215. activeCubeFace: {
  33216. set: function ( /* value */ ) {
  33217. console.warn( 'THREE.WebGLRenderTargetCube: .activeCubeFace has been removed. It is now the second parameter of WebGLRenderer.setRenderTarget().' );
  33218. }
  33219. },
  33220. activeMipMapLevel: {
  33221. set: function ( /* value */ ) {
  33222. console.warn( 'THREE.WebGLRenderTargetCube: .activeMipMapLevel has been removed. It is now the third parameter of WebGLRenderer.setRenderTarget().' );
  33223. }
  33224. }
  33225. } );
  33226. //
  33227. Object.defineProperties( WebGLRenderTarget.prototype, {
  33228. wrapS: {
  33229. get: function () {
  33230. console.warn( 'THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.' );
  33231. return this.texture.wrapS;
  33232. },
  33233. set: function ( value ) {
  33234. console.warn( 'THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.' );
  33235. this.texture.wrapS = value;
  33236. }
  33237. },
  33238. wrapT: {
  33239. get: function () {
  33240. console.warn( 'THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.' );
  33241. return this.texture.wrapT;
  33242. },
  33243. set: function ( value ) {
  33244. console.warn( 'THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.' );
  33245. this.texture.wrapT = value;
  33246. }
  33247. },
  33248. magFilter: {
  33249. get: function () {
  33250. console.warn( 'THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.' );
  33251. return this.texture.magFilter;
  33252. },
  33253. set: function ( value ) {
  33254. console.warn( 'THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.' );
  33255. this.texture.magFilter = value;
  33256. }
  33257. },
  33258. minFilter: {
  33259. get: function () {
  33260. console.warn( 'THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.' );
  33261. return this.texture.minFilter;
  33262. },
  33263. set: function ( value ) {
  33264. console.warn( 'THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.' );
  33265. this.texture.minFilter = value;
  33266. }
  33267. },
  33268. anisotropy: {
  33269. get: function () {
  33270. console.warn( 'THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.' );
  33271. return this.texture.anisotropy;
  33272. },
  33273. set: function ( value ) {
  33274. console.warn( 'THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.' );
  33275. this.texture.anisotropy = value;
  33276. }
  33277. },
  33278. offset: {
  33279. get: function () {
  33280. console.warn( 'THREE.WebGLRenderTarget: .offset is now .texture.offset.' );
  33281. return this.texture.offset;
  33282. },
  33283. set: function ( value ) {
  33284. console.warn( 'THREE.WebGLRenderTarget: .offset is now .texture.offset.' );
  33285. this.texture.offset = value;
  33286. }
  33287. },
  33288. repeat: {
  33289. get: function () {
  33290. console.warn( 'THREE.WebGLRenderTarget: .repeat is now .texture.repeat.' );
  33291. return this.texture.repeat;
  33292. },
  33293. set: function ( value ) {
  33294. console.warn( 'THREE.WebGLRenderTarget: .repeat is now .texture.repeat.' );
  33295. this.texture.repeat = value;
  33296. }
  33297. },
  33298. format: {
  33299. get: function () {
  33300. console.warn( 'THREE.WebGLRenderTarget: .format is now .texture.format.' );
  33301. return this.texture.format;
  33302. },
  33303. set: function ( value ) {
  33304. console.warn( 'THREE.WebGLRenderTarget: .format is now .texture.format.' );
  33305. this.texture.format = value;
  33306. }
  33307. },
  33308. type: {
  33309. get: function () {
  33310. console.warn( 'THREE.WebGLRenderTarget: .type is now .texture.type.' );
  33311. return this.texture.type;
  33312. },
  33313. set: function ( value ) {
  33314. console.warn( 'THREE.WebGLRenderTarget: .type is now .texture.type.' );
  33315. this.texture.type = value;
  33316. }
  33317. },
  33318. generateMipmaps: {
  33319. get: function () {
  33320. console.warn( 'THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.' );
  33321. return this.texture.generateMipmaps;
  33322. },
  33323. set: function ( value ) {
  33324. console.warn( 'THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.' );
  33325. this.texture.generateMipmaps = value;
  33326. }
  33327. }
  33328. } );
  33329. //
  33330. Object.defineProperties( WebVRManager.prototype, {
  33331. standing: {
  33332. set: function ( /* value */ ) {
  33333. console.warn( 'THREE.WebVRManager: .standing has been removed.' );
  33334. }
  33335. },
  33336. userHeight: {
  33337. set: function ( /* value */ ) {
  33338. console.warn( 'THREE.WebVRManager: .userHeight has been removed.' );
  33339. }
  33340. }
  33341. } );
  33342. //
  33343. Audio.prototype.load = function ( file ) {
  33344. console.warn( 'THREE.Audio: .load has been deprecated. Use THREE.AudioLoader instead.' );
  33345. var scope = this;
  33346. var audioLoader = new AudioLoader();
  33347. audioLoader.load( file, function ( buffer ) {
  33348. scope.setBuffer( buffer );
  33349. } );
  33350. return this;
  33351. };
  33352. AudioAnalyser.prototype.getData = function () {
  33353. console.warn( 'THREE.AudioAnalyser: .getData() is now .getFrequencyData().' );
  33354. return this.getFrequencyData();
  33355. };
  33356. //
  33357. CubeCamera.prototype.updateCubeMap = function ( renderer, scene ) {
  33358. console.warn( 'THREE.CubeCamera: .updateCubeMap() is now .update().' );
  33359. return this.update( renderer, scene );
  33360. };
  33361. //
  33362. var GeometryUtils = {
  33363. merge: function ( geometry1, geometry2, materialIndexOffset ) {
  33364. console.warn( 'THREE.GeometryUtils: .merge() has been moved to Geometry. Use geometry.merge( geometry2, matrix, materialIndexOffset ) instead.' );
  33365. var matrix;
  33366. if ( geometry2.isMesh ) {
  33367. geometry2.matrixAutoUpdate && geometry2.updateMatrix();
  33368. matrix = geometry2.matrix;
  33369. geometry2 = geometry2.geometry;
  33370. }
  33371. geometry1.merge( geometry2, matrix, materialIndexOffset );
  33372. },
  33373. center: function ( geometry ) {
  33374. console.warn( 'THREE.GeometryUtils: .center() has been moved to Geometry. Use geometry.center() instead.' );
  33375. return geometry.center();
  33376. }
  33377. };
  33378. ImageUtils.crossOrigin = undefined;
  33379. ImageUtils.loadTexture = function ( url, mapping, onLoad, onError ) {
  33380. console.warn( 'THREE.ImageUtils.loadTexture has been deprecated. Use THREE.TextureLoader() instead.' );
  33381. var loader = new TextureLoader();
  33382. loader.setCrossOrigin( this.crossOrigin );
  33383. var texture = loader.load( url, onLoad, undefined, onError );
  33384. if ( mapping ) texture.mapping = mapping;
  33385. return texture;
  33386. };
  33387. ImageUtils.loadTextureCube = function ( urls, mapping, onLoad, onError ) {
  33388. console.warn( 'THREE.ImageUtils.loadTextureCube has been deprecated. Use THREE.CubeTextureLoader() instead.' );
  33389. var loader = new CubeTextureLoader();
  33390. loader.setCrossOrigin( this.crossOrigin );
  33391. var texture = loader.load( urls, onLoad, undefined, onError );
  33392. if ( mapping ) texture.mapping = mapping;
  33393. return texture;
  33394. };
  33395. ImageUtils.loadCompressedTexture = function () {
  33396. console.error( 'THREE.ImageUtils.loadCompressedTexture has been removed. Use THREE.DDSLoader instead.' );
  33397. };
  33398. ImageUtils.loadCompressedTextureCube = function () {
  33399. console.error( 'THREE.ImageUtils.loadCompressedTextureCube has been removed. Use THREE.DDSLoader instead.' );
  33400. };
  33401. //
  33402. function Projector() {
  33403. console.error( 'THREE.Projector has been moved to /examples/js/renderers/Projector.js.' );
  33404. this.projectVector = function ( vector, camera ) {
  33405. console.warn( 'THREE.Projector: .projectVector() is now vector.project().' );
  33406. vector.project( camera );
  33407. };
  33408. this.unprojectVector = function ( vector, camera ) {
  33409. console.warn( 'THREE.Projector: .unprojectVector() is now vector.unproject().' );
  33410. vector.unproject( camera );
  33411. };
  33412. this.pickingRay = function () {
  33413. console.error( 'THREE.Projector: .pickingRay() is now raycaster.setFromCamera().' );
  33414. };
  33415. }
  33416. //
  33417. function CanvasRenderer() {
  33418. console.error( 'THREE.CanvasRenderer has been removed' );
  33419. }
  33420. //
  33421. function JSONLoader() {
  33422. console.error( 'THREE.JSONLoader has been removed.' );
  33423. }
  33424. //
  33425. var SceneUtils = {
  33426. createMultiMaterialObject: function ( /* geometry, materials */ ) {
  33427. console.error( 'THREE.SceneUtils has been moved to /examples/js/utils/SceneUtils.js' );
  33428. },
  33429. detach: function ( /* child, parent, scene */ ) {
  33430. console.error( 'THREE.SceneUtils has been moved to /examples/js/utils/SceneUtils.js' );
  33431. },
  33432. attach: function ( /* child, scene, parent */ ) {
  33433. console.error( 'THREE.SceneUtils has been moved to /examples/js/utils/SceneUtils.js' );
  33434. }
  33435. };
  33436. //
  33437. function LensFlare() {
  33438. console.error( 'THREE.LensFlare has been moved to /examples/js/objects/Lensflare.js' );
  33439. }
  33440. exports.WebGLMultisampleRenderTarget = WebGLMultisampleRenderTarget;
  33441. exports.WebGLRenderTargetCube = WebGLRenderTargetCube;
  33442. exports.WebGLRenderTarget = WebGLRenderTarget;
  33443. exports.WebGLRenderer = WebGLRenderer;
  33444. exports.ShaderLib = ShaderLib;
  33445. exports.UniformsLib = UniformsLib;
  33446. exports.UniformsUtils = UniformsUtils;
  33447. exports.ShaderChunk = ShaderChunk;
  33448. exports.FogExp2 = FogExp2;
  33449. exports.Fog = Fog;
  33450. exports.Scene = Scene;
  33451. exports.Sprite = Sprite;
  33452. exports.LOD = LOD;
  33453. exports.SkinnedMesh = SkinnedMesh;
  33454. exports.Skeleton = Skeleton;
  33455. exports.Bone = Bone;
  33456. exports.Mesh = Mesh;
  33457. exports.LineSegments = LineSegments;
  33458. exports.LineLoop = LineLoop;
  33459. exports.Line = Line;
  33460. exports.Points = Points;
  33461. exports.Group = Group;
  33462. exports.VideoTexture = VideoTexture;
  33463. exports.DataTexture = DataTexture;
  33464. exports.DataTexture2DArray = DataTexture2DArray;
  33465. exports.DataTexture3D = DataTexture3D;
  33466. exports.CompressedTexture = CompressedTexture;
  33467. exports.CubeTexture = CubeTexture;
  33468. exports.CanvasTexture = CanvasTexture;
  33469. exports.DepthTexture = DepthTexture;
  33470. exports.Texture = Texture;
  33471. exports.AnimationLoader = AnimationLoader;
  33472. exports.CompressedTextureLoader = CompressedTextureLoader;
  33473. exports.DataTextureLoader = DataTextureLoader;
  33474. exports.CubeTextureLoader = CubeTextureLoader;
  33475. exports.TextureLoader = TextureLoader;
  33476. exports.ObjectLoader = ObjectLoader;
  33477. exports.MaterialLoader = MaterialLoader;
  33478. exports.BufferGeometryLoader = BufferGeometryLoader;
  33479. exports.DefaultLoadingManager = DefaultLoadingManager;
  33480. exports.LoadingManager = LoadingManager;
  33481. exports.ImageLoader = ImageLoader;
  33482. exports.ImageBitmapLoader = ImageBitmapLoader;
  33483. exports.FontLoader = FontLoader;
  33484. exports.FileLoader = FileLoader;
  33485. exports.Loader = Loader;
  33486. exports.LoaderUtils = LoaderUtils;
  33487. exports.Cache = Cache;
  33488. exports.AudioLoader = AudioLoader;
  33489. exports.SpotLightShadow = SpotLightShadow;
  33490. exports.SpotLight = SpotLight;
  33491. exports.PointLight = PointLight;
  33492. exports.RectAreaLight = RectAreaLight;
  33493. exports.HemisphereLight = HemisphereLight;
  33494. exports.DirectionalLightShadow = DirectionalLightShadow;
  33495. exports.DirectionalLight = DirectionalLight;
  33496. exports.AmbientLight = AmbientLight;
  33497. exports.LightShadow = LightShadow;
  33498. exports.Light = Light;
  33499. exports.StereoCamera = StereoCamera;
  33500. exports.PerspectiveCamera = PerspectiveCamera;
  33501. exports.OrthographicCamera = OrthographicCamera;
  33502. exports.CubeCamera = CubeCamera;
  33503. exports.ArrayCamera = ArrayCamera;
  33504. exports.Camera = Camera;
  33505. exports.AudioListener = AudioListener;
  33506. exports.PositionalAudio = PositionalAudio;
  33507. exports.AudioContext = AudioContext;
  33508. exports.AudioAnalyser = AudioAnalyser;
  33509. exports.Audio = Audio;
  33510. exports.VectorKeyframeTrack = VectorKeyframeTrack;
  33511. exports.StringKeyframeTrack = StringKeyframeTrack;
  33512. exports.QuaternionKeyframeTrack = QuaternionKeyframeTrack;
  33513. exports.NumberKeyframeTrack = NumberKeyframeTrack;
  33514. exports.ColorKeyframeTrack = ColorKeyframeTrack;
  33515. exports.BooleanKeyframeTrack = BooleanKeyframeTrack;
  33516. exports.PropertyMixer = PropertyMixer;
  33517. exports.PropertyBinding = PropertyBinding;
  33518. exports.KeyframeTrack = KeyframeTrack;
  33519. exports.AnimationUtils = AnimationUtils;
  33520. exports.AnimationObjectGroup = AnimationObjectGroup;
  33521. exports.AnimationMixer = AnimationMixer;
  33522. exports.AnimationClip = AnimationClip;
  33523. exports.Uniform = Uniform;
  33524. exports.InstancedBufferGeometry = InstancedBufferGeometry;
  33525. exports.BufferGeometry = BufferGeometry;
  33526. exports.Geometry = Geometry;
  33527. exports.InterleavedBufferAttribute = InterleavedBufferAttribute;
  33528. exports.InstancedInterleavedBuffer = InstancedInterleavedBuffer;
  33529. exports.InterleavedBuffer = InterleavedBuffer;
  33530. exports.InstancedBufferAttribute = InstancedBufferAttribute;
  33531. exports.Face3 = Face3;
  33532. exports.Object3D = Object3D;
  33533. exports.Raycaster = Raycaster;
  33534. exports.Layers = Layers;
  33535. exports.EventDispatcher = EventDispatcher;
  33536. exports.Clock = Clock;
  33537. exports.QuaternionLinearInterpolant = QuaternionLinearInterpolant;
  33538. exports.LinearInterpolant = LinearInterpolant;
  33539. exports.DiscreteInterpolant = DiscreteInterpolant;
  33540. exports.CubicInterpolant = CubicInterpolant;
  33541. exports.Interpolant = Interpolant;
  33542. exports.Triangle = Triangle;
  33543. exports.Math = _Math;
  33544. exports.Spherical = Spherical;
  33545. exports.Cylindrical = Cylindrical;
  33546. exports.Plane = Plane;
  33547. exports.Frustum = Frustum;
  33548. exports.Sphere = Sphere;
  33549. exports.Ray = Ray;
  33550. exports.Matrix4 = Matrix4;
  33551. exports.Matrix3 = Matrix3;
  33552. exports.Box3 = Box3;
  33553. exports.Box2 = Box2;
  33554. exports.Line3 = Line3;
  33555. exports.Euler = Euler;
  33556. exports.Vector4 = Vector4;
  33557. exports.Vector3 = Vector3;
  33558. exports.Vector2 = Vector2;
  33559. exports.Quaternion = Quaternion;
  33560. exports.Color = Color;
  33561. exports.ImmediateRenderObject = ImmediateRenderObject;
  33562. exports.VertexNormalsHelper = VertexNormalsHelper;
  33563. exports.SpotLightHelper = SpotLightHelper;
  33564. exports.SkeletonHelper = SkeletonHelper;
  33565. exports.PointLightHelper = PointLightHelper;
  33566. exports.RectAreaLightHelper = RectAreaLightHelper;
  33567. exports.HemisphereLightHelper = HemisphereLightHelper;
  33568. exports.GridHelper = GridHelper;
  33569. exports.PolarGridHelper = PolarGridHelper;
  33570. exports.PositionalAudioHelper = PositionalAudioHelper;
  33571. exports.FaceNormalsHelper = FaceNormalsHelper;
  33572. exports.DirectionalLightHelper = DirectionalLightHelper;
  33573. exports.CameraHelper = CameraHelper;
  33574. exports.BoxHelper = BoxHelper;
  33575. exports.Box3Helper = Box3Helper;
  33576. exports.PlaneHelper = PlaneHelper;
  33577. exports.ArrowHelper = ArrowHelper;
  33578. exports.AxesHelper = AxesHelper;
  33579. exports.Shape = Shape;
  33580. exports.Path = Path;
  33581. exports.ShapePath = ShapePath;
  33582. exports.Font = Font;
  33583. exports.CurvePath = CurvePath;
  33584. exports.Curve = Curve;
  33585. exports.ImageUtils = ImageUtils;
  33586. exports.ShapeUtils = ShapeUtils;
  33587. exports.WebGLUtils = WebGLUtils;
  33588. exports.WireframeGeometry = WireframeGeometry;
  33589. exports.ParametricGeometry = ParametricGeometry;
  33590. exports.ParametricBufferGeometry = ParametricBufferGeometry;
  33591. exports.TetrahedronGeometry = TetrahedronGeometry;
  33592. exports.TetrahedronBufferGeometry = TetrahedronBufferGeometry;
  33593. exports.OctahedronGeometry = OctahedronGeometry;
  33594. exports.OctahedronBufferGeometry = OctahedronBufferGeometry;
  33595. exports.IcosahedronGeometry = IcosahedronGeometry;
  33596. exports.IcosahedronBufferGeometry = IcosahedronBufferGeometry;
  33597. exports.DodecahedronGeometry = DodecahedronGeometry;
  33598. exports.DodecahedronBufferGeometry = DodecahedronBufferGeometry;
  33599. exports.PolyhedronGeometry = PolyhedronGeometry;
  33600. exports.PolyhedronBufferGeometry = PolyhedronBufferGeometry;
  33601. exports.TubeGeometry = TubeGeometry;
  33602. exports.TubeBufferGeometry = TubeBufferGeometry;
  33603. exports.TorusKnotGeometry = TorusKnotGeometry;
  33604. exports.TorusKnotBufferGeometry = TorusKnotBufferGeometry;
  33605. exports.TorusGeometry = TorusGeometry;
  33606. exports.TorusBufferGeometry = TorusBufferGeometry;
  33607. exports.TextGeometry = TextGeometry;
  33608. exports.TextBufferGeometry = TextBufferGeometry;
  33609. exports.SphereGeometry = SphereGeometry;
  33610. exports.SphereBufferGeometry = SphereBufferGeometry;
  33611. exports.RingGeometry = RingGeometry;
  33612. exports.RingBufferGeometry = RingBufferGeometry;
  33613. exports.PlaneGeometry = PlaneGeometry;
  33614. exports.PlaneBufferGeometry = PlaneBufferGeometry;
  33615. exports.LatheGeometry = LatheGeometry;
  33616. exports.LatheBufferGeometry = LatheBufferGeometry;
  33617. exports.ShapeGeometry = ShapeGeometry;
  33618. exports.ShapeBufferGeometry = ShapeBufferGeometry;
  33619. exports.ExtrudeGeometry = ExtrudeGeometry;
  33620. exports.ExtrudeBufferGeometry = ExtrudeBufferGeometry;
  33621. exports.EdgesGeometry = EdgesGeometry;
  33622. exports.ConeGeometry = ConeGeometry;
  33623. exports.ConeBufferGeometry = ConeBufferGeometry;
  33624. exports.CylinderGeometry = CylinderGeometry;
  33625. exports.CylinderBufferGeometry = CylinderBufferGeometry;
  33626. exports.CircleGeometry = CircleGeometry;
  33627. exports.CircleBufferGeometry = CircleBufferGeometry;
  33628. exports.BoxGeometry = BoxGeometry;
  33629. exports.CubeGeometry = BoxGeometry;
  33630. exports.BoxBufferGeometry = BoxBufferGeometry;
  33631. exports.ShadowMaterial = ShadowMaterial;
  33632. exports.SpriteMaterial = SpriteMaterial;
  33633. exports.RawShaderMaterial = RawShaderMaterial;
  33634. exports.ShaderMaterial = ShaderMaterial;
  33635. exports.PointsMaterial = PointsMaterial;
  33636. exports.MeshPhysicalMaterial = MeshPhysicalMaterial;
  33637. exports.MeshStandardMaterial = MeshStandardMaterial;
  33638. exports.MeshPhongMaterial = MeshPhongMaterial;
  33639. exports.MeshToonMaterial = MeshToonMaterial;
  33640. exports.MeshNormalMaterial = MeshNormalMaterial;
  33641. exports.MeshLambertMaterial = MeshLambertMaterial;
  33642. exports.MeshDepthMaterial = MeshDepthMaterial;
  33643. exports.MeshDistanceMaterial = MeshDistanceMaterial;
  33644. exports.MeshBasicMaterial = MeshBasicMaterial;
  33645. exports.MeshMatcapMaterial = MeshMatcapMaterial;
  33646. exports.LineDashedMaterial = LineDashedMaterial;
  33647. exports.LineBasicMaterial = LineBasicMaterial;
  33648. exports.Material = Material;
  33649. exports.Float64BufferAttribute = Float64BufferAttribute;
  33650. exports.Float32BufferAttribute = Float32BufferAttribute;
  33651. exports.Uint32BufferAttribute = Uint32BufferAttribute;
  33652. exports.Int32BufferAttribute = Int32BufferAttribute;
  33653. exports.Uint16BufferAttribute = Uint16BufferAttribute;
  33654. exports.Int16BufferAttribute = Int16BufferAttribute;
  33655. exports.Uint8ClampedBufferAttribute = Uint8ClampedBufferAttribute;
  33656. exports.Uint8BufferAttribute = Uint8BufferAttribute;
  33657. exports.Int8BufferAttribute = Int8BufferAttribute;
  33658. exports.BufferAttribute = BufferAttribute;
  33659. exports.ArcCurve = ArcCurve;
  33660. exports.CatmullRomCurve3 = CatmullRomCurve3;
  33661. exports.CubicBezierCurve = CubicBezierCurve;
  33662. exports.CubicBezierCurve3 = CubicBezierCurve3;
  33663. exports.EllipseCurve = EllipseCurve;
  33664. exports.LineCurve = LineCurve;
  33665. exports.LineCurve3 = LineCurve3;
  33666. exports.QuadraticBezierCurve = QuadraticBezierCurve;
  33667. exports.QuadraticBezierCurve3 = QuadraticBezierCurve3;
  33668. exports.SplineCurve = SplineCurve;
  33669. exports.REVISION = REVISION;
  33670. exports.MOUSE = MOUSE;
  33671. exports.CullFaceNone = CullFaceNone;
  33672. exports.CullFaceBack = CullFaceBack;
  33673. exports.CullFaceFront = CullFaceFront;
  33674. exports.CullFaceFrontBack = CullFaceFrontBack;
  33675. exports.FrontFaceDirectionCW = FrontFaceDirectionCW;
  33676. exports.FrontFaceDirectionCCW = FrontFaceDirectionCCW;
  33677. exports.BasicShadowMap = BasicShadowMap;
  33678. exports.PCFShadowMap = PCFShadowMap;
  33679. exports.PCFSoftShadowMap = PCFSoftShadowMap;
  33680. exports.FrontSide = FrontSide;
  33681. exports.BackSide = BackSide;
  33682. exports.DoubleSide = DoubleSide;
  33683. exports.FlatShading = FlatShading;
  33684. exports.SmoothShading = SmoothShading;
  33685. exports.NoColors = NoColors;
  33686. exports.FaceColors = FaceColors;
  33687. exports.VertexColors = VertexColors;
  33688. exports.NoBlending = NoBlending;
  33689. exports.NormalBlending = NormalBlending;
  33690. exports.AdditiveBlending = AdditiveBlending;
  33691. exports.SubtractiveBlending = SubtractiveBlending;
  33692. exports.MultiplyBlending = MultiplyBlending;
  33693. exports.CustomBlending = CustomBlending;
  33694. exports.AddEquation = AddEquation;
  33695. exports.SubtractEquation = SubtractEquation;
  33696. exports.ReverseSubtractEquation = ReverseSubtractEquation;
  33697. exports.MinEquation = MinEquation;
  33698. exports.MaxEquation = MaxEquation;
  33699. exports.ZeroFactor = ZeroFactor;
  33700. exports.OneFactor = OneFactor;
  33701. exports.SrcColorFactor = SrcColorFactor;
  33702. exports.OneMinusSrcColorFactor = OneMinusSrcColorFactor;
  33703. exports.SrcAlphaFactor = SrcAlphaFactor;
  33704. exports.OneMinusSrcAlphaFactor = OneMinusSrcAlphaFactor;
  33705. exports.DstAlphaFactor = DstAlphaFactor;
  33706. exports.OneMinusDstAlphaFactor = OneMinusDstAlphaFactor;
  33707. exports.DstColorFactor = DstColorFactor;
  33708. exports.OneMinusDstColorFactor = OneMinusDstColorFactor;
  33709. exports.SrcAlphaSaturateFactor = SrcAlphaSaturateFactor;
  33710. exports.NeverDepth = NeverDepth;
  33711. exports.AlwaysDepth = AlwaysDepth;
  33712. exports.LessDepth = LessDepth;
  33713. exports.LessEqualDepth = LessEqualDepth;
  33714. exports.EqualDepth = EqualDepth;
  33715. exports.GreaterEqualDepth = GreaterEqualDepth;
  33716. exports.GreaterDepth = GreaterDepth;
  33717. exports.NotEqualDepth = NotEqualDepth;
  33718. exports.MultiplyOperation = MultiplyOperation;
  33719. exports.MixOperation = MixOperation;
  33720. exports.AddOperation = AddOperation;
  33721. exports.NoToneMapping = NoToneMapping;
  33722. exports.LinearToneMapping = LinearToneMapping;
  33723. exports.ReinhardToneMapping = ReinhardToneMapping;
  33724. exports.Uncharted2ToneMapping = Uncharted2ToneMapping;
  33725. exports.CineonToneMapping = CineonToneMapping;
  33726. exports.ACESFilmicToneMapping = ACESFilmicToneMapping;
  33727. exports.UVMapping = UVMapping;
  33728. exports.CubeReflectionMapping = CubeReflectionMapping;
  33729. exports.CubeRefractionMapping = CubeRefractionMapping;
  33730. exports.EquirectangularReflectionMapping = EquirectangularReflectionMapping;
  33731. exports.EquirectangularRefractionMapping = EquirectangularRefractionMapping;
  33732. exports.SphericalReflectionMapping = SphericalReflectionMapping;
  33733. exports.CubeUVReflectionMapping = CubeUVReflectionMapping;
  33734. exports.CubeUVRefractionMapping = CubeUVRefractionMapping;
  33735. exports.RepeatWrapping = RepeatWrapping;
  33736. exports.ClampToEdgeWrapping = ClampToEdgeWrapping;
  33737. exports.MirroredRepeatWrapping = MirroredRepeatWrapping;
  33738. exports.NearestFilter = NearestFilter;
  33739. exports.NearestMipMapNearestFilter = NearestMipMapNearestFilter;
  33740. exports.NearestMipMapLinearFilter = NearestMipMapLinearFilter;
  33741. exports.LinearFilter = LinearFilter;
  33742. exports.LinearMipMapNearestFilter = LinearMipMapNearestFilter;
  33743. exports.LinearMipMapLinearFilter = LinearMipMapLinearFilter;
  33744. exports.UnsignedByteType = UnsignedByteType;
  33745. exports.ByteType = ByteType;
  33746. exports.ShortType = ShortType;
  33747. exports.UnsignedShortType = UnsignedShortType;
  33748. exports.IntType = IntType;
  33749. exports.UnsignedIntType = UnsignedIntType;
  33750. exports.FloatType = FloatType;
  33751. exports.HalfFloatType = HalfFloatType;
  33752. exports.UnsignedShort4444Type = UnsignedShort4444Type;
  33753. exports.UnsignedShort5551Type = UnsignedShort5551Type;
  33754. exports.UnsignedShort565Type = UnsignedShort565Type;
  33755. exports.UnsignedInt248Type = UnsignedInt248Type;
  33756. exports.AlphaFormat = AlphaFormat;
  33757. exports.RGBFormat = RGBFormat;
  33758. exports.RGBAFormat = RGBAFormat;
  33759. exports.LuminanceFormat = LuminanceFormat;
  33760. exports.LuminanceAlphaFormat = LuminanceAlphaFormat;
  33761. exports.RGBEFormat = RGBEFormat;
  33762. exports.DepthFormat = DepthFormat;
  33763. exports.DepthStencilFormat = DepthStencilFormat;
  33764. exports.RedFormat = RedFormat;
  33765. exports.RGB_S3TC_DXT1_Format = RGB_S3TC_DXT1_Format;
  33766. exports.RGBA_S3TC_DXT1_Format = RGBA_S3TC_DXT1_Format;
  33767. exports.RGBA_S3TC_DXT3_Format = RGBA_S3TC_DXT3_Format;
  33768. exports.RGBA_S3TC_DXT5_Format = RGBA_S3TC_DXT5_Format;
  33769. exports.RGB_PVRTC_4BPPV1_Format = RGB_PVRTC_4BPPV1_Format;
  33770. exports.RGB_PVRTC_2BPPV1_Format = RGB_PVRTC_2BPPV1_Format;
  33771. exports.RGBA_PVRTC_4BPPV1_Format = RGBA_PVRTC_4BPPV1_Format;
  33772. exports.RGBA_PVRTC_2BPPV1_Format = RGBA_PVRTC_2BPPV1_Format;
  33773. exports.RGB_ETC1_Format = RGB_ETC1_Format;
  33774. exports.RGBA_ASTC_4x4_Format = RGBA_ASTC_4x4_Format;
  33775. exports.RGBA_ASTC_5x4_Format = RGBA_ASTC_5x4_Format;
  33776. exports.RGBA_ASTC_5x5_Format = RGBA_ASTC_5x5_Format;
  33777. exports.RGBA_ASTC_6x5_Format = RGBA_ASTC_6x5_Format;
  33778. exports.RGBA_ASTC_6x6_Format = RGBA_ASTC_6x6_Format;
  33779. exports.RGBA_ASTC_8x5_Format = RGBA_ASTC_8x5_Format;
  33780. exports.RGBA_ASTC_8x6_Format = RGBA_ASTC_8x6_Format;
  33781. exports.RGBA_ASTC_8x8_Format = RGBA_ASTC_8x8_Format;
  33782. exports.RGBA_ASTC_10x5_Format = RGBA_ASTC_10x5_Format;
  33783. exports.RGBA_ASTC_10x6_Format = RGBA_ASTC_10x6_Format;
  33784. exports.RGBA_ASTC_10x8_Format = RGBA_ASTC_10x8_Format;
  33785. exports.RGBA_ASTC_10x10_Format = RGBA_ASTC_10x10_Format;
  33786. exports.RGBA_ASTC_12x10_Format = RGBA_ASTC_12x10_Format;
  33787. exports.RGBA_ASTC_12x12_Format = RGBA_ASTC_12x12_Format;
  33788. exports.LoopOnce = LoopOnce;
  33789. exports.LoopRepeat = LoopRepeat;
  33790. exports.LoopPingPong = LoopPingPong;
  33791. exports.InterpolateDiscrete = InterpolateDiscrete;
  33792. exports.InterpolateLinear = InterpolateLinear;
  33793. exports.InterpolateSmooth = InterpolateSmooth;
  33794. exports.ZeroCurvatureEnding = ZeroCurvatureEnding;
  33795. exports.ZeroSlopeEnding = ZeroSlopeEnding;
  33796. exports.WrapAroundEnding = WrapAroundEnding;
  33797. exports.TrianglesDrawMode = TrianglesDrawMode;
  33798. exports.TriangleStripDrawMode = TriangleStripDrawMode;
  33799. exports.TriangleFanDrawMode = TriangleFanDrawMode;
  33800. exports.LinearEncoding = LinearEncoding;
  33801. exports.sRGBEncoding = sRGBEncoding;
  33802. exports.GammaEncoding = GammaEncoding;
  33803. exports.RGBEEncoding = RGBEEncoding;
  33804. exports.LogLuvEncoding = LogLuvEncoding;
  33805. exports.RGBM7Encoding = RGBM7Encoding;
  33806. exports.RGBM16Encoding = RGBM16Encoding;
  33807. exports.RGBDEncoding = RGBDEncoding;
  33808. exports.BasicDepthPacking = BasicDepthPacking;
  33809. exports.RGBADepthPacking = RGBADepthPacking;
  33810. exports.TangentSpaceNormalMap = TangentSpaceNormalMap;
  33811. exports.ObjectSpaceNormalMap = ObjectSpaceNormalMap;
  33812. exports.Face4 = Face4;
  33813. exports.LineStrip = LineStrip;
  33814. exports.LinePieces = LinePieces;
  33815. exports.MeshFaceMaterial = MeshFaceMaterial;
  33816. exports.MultiMaterial = MultiMaterial;
  33817. exports.PointCloud = PointCloud;
  33818. exports.Particle = Particle;
  33819. exports.ParticleSystem = ParticleSystem;
  33820. exports.PointCloudMaterial = PointCloudMaterial;
  33821. exports.ParticleBasicMaterial = ParticleBasicMaterial;
  33822. exports.ParticleSystemMaterial = ParticleSystemMaterial;
  33823. exports.Vertex = Vertex;
  33824. exports.DynamicBufferAttribute = DynamicBufferAttribute;
  33825. exports.Int8Attribute = Int8Attribute;
  33826. exports.Uint8Attribute = Uint8Attribute;
  33827. exports.Uint8ClampedAttribute = Uint8ClampedAttribute;
  33828. exports.Int16Attribute = Int16Attribute;
  33829. exports.Uint16Attribute = Uint16Attribute;
  33830. exports.Int32Attribute = Int32Attribute;
  33831. exports.Uint32Attribute = Uint32Attribute;
  33832. exports.Float32Attribute = Float32Attribute;
  33833. exports.Float64Attribute = Float64Attribute;
  33834. exports.ClosedSplineCurve3 = ClosedSplineCurve3;
  33835. exports.SplineCurve3 = SplineCurve3;
  33836. exports.Spline = Spline;
  33837. exports.AxisHelper = AxisHelper;
  33838. exports.BoundingBoxHelper = BoundingBoxHelper;
  33839. exports.EdgesHelper = EdgesHelper;
  33840. exports.WireframeHelper = WireframeHelper;
  33841. exports.XHRLoader = XHRLoader;
  33842. exports.BinaryTextureLoader = BinaryTextureLoader;
  33843. exports.GeometryUtils = GeometryUtils;
  33844. exports.Projector = Projector;
  33845. exports.CanvasRenderer = CanvasRenderer;
  33846. exports.JSONLoader = JSONLoader;
  33847. exports.SceneUtils = SceneUtils;
  33848. exports.LensFlare = LensFlare;
  33849. Object.defineProperty(exports, '__esModule', { value: true });
  33850. }));
  33851. },{}],37:[function(_dereq_,module,exports){
  33852. // Copyright 2016 The Draco Authors.
  33853. //
  33854. // Licensed under the Apache License, Version 2.0 (the "License");
  33855. // you may not use this file except in compliance with the License.
  33856. // You may obtain a copy of the License at
  33857. //
  33858. // http://www.apache.org/licenses/LICENSE-2.0
  33859. //
  33860. // Unless required by applicable law or agreed to in writing, software
  33861. // distributed under the License is distributed on an "AS IS" BASIS,
  33862. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  33863. // See the License for the specific language governing permissions and
  33864. // limitations under the License.
  33865. //
  33866. 'use strict';
  33867. /**
  33868. * @param {THREE.LoadingManager} manager
  33869. */
  33870. THREE.DRACOLoader = function(manager) {
  33871. this.timeLoaded = 0;
  33872. this.manager = manager || THREE.DefaultLoadingManager;
  33873. this.materials = null;
  33874. this.verbosity = 0;
  33875. this.attributeOptions = {};
  33876. this.drawMode = THREE.TrianglesDrawMode;
  33877. // Native Draco attribute type to Three.JS attribute type.
  33878. this.nativeAttributeMap = {
  33879. 'position' : 'POSITION',
  33880. 'normal' : 'NORMAL',
  33881. 'color' : 'COLOR',
  33882. 'uv' : 'TEX_COORD'
  33883. };
  33884. };
  33885. THREE.DRACOLoader.prototype = {
  33886. constructor: THREE.DRACOLoader,
  33887. load: function(url, onLoad, onProgress, onError) {
  33888. var scope = this;
  33889. var loader = new THREE.FileLoader(scope.manager);
  33890. loader.setPath(this.path);
  33891. loader.setResponseType('arraybuffer');
  33892. loader.load(url, function(blob) {
  33893. scope.decodeDracoFile(blob, onLoad);
  33894. }, onProgress, onError);
  33895. },
  33896. setPath: function(value) {
  33897. this.path = value;
  33898. return this;
  33899. },
  33900. setVerbosity: function(level) {
  33901. this.verbosity = level;
  33902. return this;
  33903. },
  33904. /**
  33905. * Sets desired mode for generated geometry indices.
  33906. * Can be either:
  33907. * THREE.TrianglesDrawMode
  33908. * THREE.TriangleStripDrawMode
  33909. */
  33910. setDrawMode: function(drawMode) {
  33911. this.drawMode = drawMode;
  33912. return this;
  33913. },
  33914. /**
  33915. * Skips dequantization for a specific attribute.
  33916. * |attributeName| is the THREE.js name of the given attribute type.
  33917. * The only currently supported |attributeName| is 'position', more may be
  33918. * added in future.
  33919. */
  33920. setSkipDequantization: function(attributeName, skip) {
  33921. var skipDequantization = true;
  33922. if (typeof skip !== 'undefined')
  33923. skipDequantization = skip;
  33924. this.getAttributeOptions(attributeName).skipDequantization =
  33925. skipDequantization;
  33926. return this;
  33927. },
  33928. /**
  33929. * Decompresses a Draco buffer. Names of attributes (for ID and type maps)
  33930. * must be one of the supported three.js types, including: position, color,
  33931. * normal, uv, uv2, skinIndex, skinWeight.
  33932. *
  33933. * @param {ArrayBuffer} rawBuffer
  33934. * @param {Function} callback
  33935. * @param {Object|undefined} attributeUniqueIdMap Provides a pre-defined ID
  33936. * for each attribute in the geometry to be decoded. If given,
  33937. * `attributeTypeMap` is required and `nativeAttributeMap` will be
  33938. * ignored.
  33939. * @param {Object|undefined} attributeTypeMap Provides a predefined data
  33940. * type (as a typed array constructor) for each attribute in the
  33941. * geometry to be decoded.
  33942. */
  33943. decodeDracoFile: function(rawBuffer, callback, attributeUniqueIdMap,
  33944. attributeTypeMap) {
  33945. var scope = this;
  33946. THREE.DRACOLoader.getDecoderModule()
  33947. .then( function ( module ) {
  33948. scope.decodeDracoFileInternal( rawBuffer, module.decoder, callback,
  33949. attributeUniqueIdMap, attributeTypeMap);
  33950. });
  33951. },
  33952. decodeDracoFileInternal: function(rawBuffer, dracoDecoder, callback,
  33953. attributeUniqueIdMap, attributeTypeMap) {
  33954. /*
  33955. * Here is how to use Draco Javascript decoder and get the geometry.
  33956. */
  33957. var buffer = new dracoDecoder.DecoderBuffer();
  33958. buffer.Init(new Int8Array(rawBuffer), rawBuffer.byteLength);
  33959. var decoder = new dracoDecoder.Decoder();
  33960. /*
  33961. * Determine what type is this file: mesh or point cloud.
  33962. */
  33963. var geometryType = decoder.GetEncodedGeometryType(buffer);
  33964. if (geometryType == dracoDecoder.TRIANGULAR_MESH) {
  33965. if (this.verbosity > 0) {
  33966. console.log('Loaded a mesh.');
  33967. }
  33968. } else if (geometryType == dracoDecoder.POINT_CLOUD) {
  33969. if (this.verbosity > 0) {
  33970. console.log('Loaded a point cloud.');
  33971. }
  33972. } else {
  33973. var errorMsg = 'THREE.DRACOLoader: Unknown geometry type.';
  33974. console.error(errorMsg);
  33975. throw new Error(errorMsg);
  33976. }
  33977. callback(this.convertDracoGeometryTo3JS(dracoDecoder, decoder,
  33978. geometryType, buffer, attributeUniqueIdMap, attributeTypeMap));
  33979. },
  33980. addAttributeToGeometry: function(dracoDecoder, decoder, dracoGeometry,
  33981. attributeName, attributeType, attribute,
  33982. geometry, geometryBuffer) {
  33983. if (attribute.ptr === 0) {
  33984. var errorMsg = 'THREE.DRACOLoader: No attribute ' + attributeName;
  33985. console.error(errorMsg);
  33986. throw new Error(errorMsg);
  33987. }
  33988. var numComponents = attribute.num_components();
  33989. var numPoints = dracoGeometry.num_points();
  33990. var numValues = numPoints * numComponents;
  33991. var attributeData;
  33992. var TypedBufferAttribute;
  33993. switch ( attributeType ) {
  33994. case Float32Array:
  33995. attributeData = new dracoDecoder.DracoFloat32Array();
  33996. decoder.GetAttributeFloatForAllPoints(
  33997. dracoGeometry, attribute, attributeData);
  33998. geometryBuffer[ attributeName ] = new Float32Array( numValues );
  33999. TypedBufferAttribute = THREE.Float32BufferAttribute;
  34000. break;
  34001. case Int8Array:
  34002. attributeData = new dracoDecoder.DracoInt8Array();
  34003. decoder.GetAttributeInt8ForAllPoints(
  34004. dracoGeometry, attribute, attributeData );
  34005. geometryBuffer[ attributeName ] = new Int8Array( numValues );
  34006. TypedBufferAttribute = THREE.Int8BufferAttribute;
  34007. break;
  34008. case Int16Array:
  34009. attributeData = new dracoDecoder.DracoInt16Array();
  34010. decoder.GetAttributeInt16ForAllPoints(
  34011. dracoGeometry, attribute, attributeData);
  34012. geometryBuffer[ attributeName ] = new Int16Array( numValues );
  34013. TypedBufferAttribute = THREE.Int16BufferAttribute;
  34014. break;
  34015. case Int32Array:
  34016. attributeData = new dracoDecoder.DracoInt32Array();
  34017. decoder.GetAttributeInt32ForAllPoints(
  34018. dracoGeometry, attribute, attributeData);
  34019. geometryBuffer[ attributeName ] = new Int32Array( numValues );
  34020. TypedBufferAttribute = THREE.Int32BufferAttribute;
  34021. break;
  34022. case Uint8Array:
  34023. attributeData = new dracoDecoder.DracoUInt8Array();
  34024. decoder.GetAttributeUInt8ForAllPoints(
  34025. dracoGeometry, attribute, attributeData);
  34026. geometryBuffer[ attributeName ] = new Uint8Array( numValues );
  34027. TypedBufferAttribute = THREE.Uint8BufferAttribute;
  34028. break;
  34029. case Uint16Array:
  34030. attributeData = new dracoDecoder.DracoUInt16Array();
  34031. decoder.GetAttributeUInt16ForAllPoints(
  34032. dracoGeometry, attribute, attributeData);
  34033. geometryBuffer[ attributeName ] = new Uint16Array( numValues );
  34034. TypedBufferAttribute = THREE.Uint16BufferAttribute;
  34035. break;
  34036. case Uint32Array:
  34037. attributeData = new dracoDecoder.DracoUInt32Array();
  34038. decoder.GetAttributeUInt32ForAllPoints(
  34039. dracoGeometry, attribute, attributeData);
  34040. geometryBuffer[ attributeName ] = new Uint32Array( numValues );
  34041. TypedBufferAttribute = THREE.Uint32BufferAttribute;
  34042. break;
  34043. default:
  34044. var errorMsg = 'THREE.DRACOLoader: Unexpected attribute type.';
  34045. console.error( errorMsg );
  34046. throw new Error( errorMsg );
  34047. }
  34048. // Copy data from decoder.
  34049. for (var i = 0; i < numValues; i++) {
  34050. geometryBuffer[attributeName][i] = attributeData.GetValue(i);
  34051. }
  34052. // Add attribute to THREEJS geometry for rendering.
  34053. geometry.addAttribute(attributeName,
  34054. new TypedBufferAttribute(geometryBuffer[attributeName],
  34055. numComponents));
  34056. dracoDecoder.destroy(attributeData);
  34057. },
  34058. convertDracoGeometryTo3JS: function(dracoDecoder, decoder, geometryType,
  34059. buffer, attributeUniqueIdMap,
  34060. attributeTypeMap) {
  34061. // TODO: Should not assume native Draco attribute IDs apply.
  34062. if (this.getAttributeOptions('position').skipDequantization === true) {
  34063. decoder.SkipAttributeTransform(dracoDecoder.POSITION);
  34064. }
  34065. var dracoGeometry;
  34066. var decodingStatus;
  34067. var start_time = performance.now();
  34068. if (geometryType === dracoDecoder.TRIANGULAR_MESH) {
  34069. dracoGeometry = new dracoDecoder.Mesh();
  34070. decodingStatus = decoder.DecodeBufferToMesh(buffer, dracoGeometry);
  34071. } else {
  34072. dracoGeometry = new dracoDecoder.PointCloud();
  34073. decodingStatus =
  34074. decoder.DecodeBufferToPointCloud(buffer, dracoGeometry);
  34075. }
  34076. if (!decodingStatus.ok() || dracoGeometry.ptr == 0) {
  34077. var errorMsg = 'THREE.DRACOLoader: Decoding failed: ';
  34078. errorMsg += decodingStatus.error_msg();
  34079. console.error(errorMsg);
  34080. dracoDecoder.destroy(decoder);
  34081. dracoDecoder.destroy(dracoGeometry);
  34082. throw new Error(errorMsg);
  34083. }
  34084. var decode_end = performance.now();
  34085. dracoDecoder.destroy(buffer);
  34086. /*
  34087. * Example on how to retrieve mesh and attributes.
  34088. */
  34089. var numFaces;
  34090. if (geometryType == dracoDecoder.TRIANGULAR_MESH) {
  34091. numFaces = dracoGeometry.num_faces();
  34092. if (this.verbosity > 0) {
  34093. console.log('Number of faces loaded: ' + numFaces.toString());
  34094. }
  34095. } else {
  34096. numFaces = 0;
  34097. }
  34098. var numPoints = dracoGeometry.num_points();
  34099. var numAttributes = dracoGeometry.num_attributes();
  34100. if (this.verbosity > 0) {
  34101. console.log('Number of points loaded: ' + numPoints.toString());
  34102. console.log('Number of attributes loaded: ' +
  34103. numAttributes.toString());
  34104. }
  34105. // Verify if there is position attribute.
  34106. // TODO: Should not assume native Draco attribute IDs apply.
  34107. var posAttId = decoder.GetAttributeId(dracoGeometry,
  34108. dracoDecoder.POSITION);
  34109. if (posAttId == -1) {
  34110. var errorMsg = 'THREE.DRACOLoader: No position attribute found.';
  34111. console.error(errorMsg);
  34112. dracoDecoder.destroy(decoder);
  34113. dracoDecoder.destroy(dracoGeometry);
  34114. throw new Error(errorMsg);
  34115. }
  34116. var posAttribute = decoder.GetAttribute(dracoGeometry, posAttId);
  34117. // Structure for converting to THREEJS geometry later.
  34118. var geometryBuffer = {};
  34119. // Import data to Three JS geometry.
  34120. var geometry = new THREE.BufferGeometry();
  34121. // Do not use both the native attribute map and a provided (e.g. glTF) map.
  34122. if ( attributeUniqueIdMap ) {
  34123. // Add attributes of user specified unique id. E.g. GLTF models.
  34124. for (var attributeName in attributeUniqueIdMap) {
  34125. var attributeType = attributeTypeMap[attributeName];
  34126. var attributeId = attributeUniqueIdMap[attributeName];
  34127. var attribute = decoder.GetAttributeByUniqueId(dracoGeometry,
  34128. attributeId);
  34129. this.addAttributeToGeometry(dracoDecoder, decoder, dracoGeometry,
  34130. attributeName, attributeType, attribute, geometry, geometryBuffer);
  34131. }
  34132. } else {
  34133. // Add native Draco attribute type to geometry.
  34134. for (var attributeName in this.nativeAttributeMap) {
  34135. var attId = decoder.GetAttributeId(dracoGeometry,
  34136. dracoDecoder[this.nativeAttributeMap[attributeName]]);
  34137. if (attId !== -1) {
  34138. if (this.verbosity > 0) {
  34139. console.log('Loaded ' + attributeName + ' attribute.');
  34140. }
  34141. var attribute = decoder.GetAttribute(dracoGeometry, attId);
  34142. this.addAttributeToGeometry(dracoDecoder, decoder, dracoGeometry,
  34143. attributeName, Float32Array, attribute, geometry, geometryBuffer);
  34144. }
  34145. }
  34146. }
  34147. // For mesh, we need to generate the faces.
  34148. if (geometryType == dracoDecoder.TRIANGULAR_MESH) {
  34149. if (this.drawMode === THREE.TriangleStripDrawMode) {
  34150. var stripsArray = new dracoDecoder.DracoInt32Array();
  34151. var numStrips = decoder.GetTriangleStripsFromMesh(
  34152. dracoGeometry, stripsArray);
  34153. geometryBuffer.indices = new Uint32Array(stripsArray.size());
  34154. for (var i = 0; i < stripsArray.size(); ++i) {
  34155. geometryBuffer.indices[i] = stripsArray.GetValue(i);
  34156. }
  34157. dracoDecoder.destroy(stripsArray);
  34158. } else {
  34159. var numIndices = numFaces * 3;
  34160. geometryBuffer.indices = new Uint32Array(numIndices);
  34161. var ia = new dracoDecoder.DracoInt32Array();
  34162. for (var i = 0; i < numFaces; ++i) {
  34163. decoder.GetFaceFromMesh(dracoGeometry, i, ia);
  34164. var index = i * 3;
  34165. geometryBuffer.indices[index] = ia.GetValue(0);
  34166. geometryBuffer.indices[index + 1] = ia.GetValue(1);
  34167. geometryBuffer.indices[index + 2] = ia.GetValue(2);
  34168. }
  34169. dracoDecoder.destroy(ia);
  34170. }
  34171. }
  34172. geometry.drawMode = this.drawMode;
  34173. if (geometryType == dracoDecoder.TRIANGULAR_MESH) {
  34174. geometry.setIndex(new(geometryBuffer.indices.length > 65535 ?
  34175. THREE.Uint32BufferAttribute : THREE.Uint16BufferAttribute)
  34176. (geometryBuffer.indices, 1));
  34177. }
  34178. // TODO: Should not assume native Draco attribute IDs apply.
  34179. // TODO: Can other attribute types be quantized?
  34180. var posTransform = new dracoDecoder.AttributeQuantizationTransform();
  34181. if (posTransform.InitFromAttribute(posAttribute)) {
  34182. // Quantized attribute. Store the quantization parameters into the
  34183. // THREE.js attribute.
  34184. geometry.attributes['position'].isQuantized = true;
  34185. geometry.attributes['position'].maxRange = posTransform.range();
  34186. geometry.attributes['position'].numQuantizationBits =
  34187. posTransform.quantization_bits();
  34188. geometry.attributes['position'].minValues = new Float32Array(3);
  34189. for (var i = 0; i < 3; ++i) {
  34190. geometry.attributes['position'].minValues[i] =
  34191. posTransform.min_value(i);
  34192. }
  34193. }
  34194. dracoDecoder.destroy(posTransform);
  34195. dracoDecoder.destroy(decoder);
  34196. dracoDecoder.destroy(dracoGeometry);
  34197. this.decode_time = decode_end - start_time;
  34198. this.import_time = performance.now() - decode_end;
  34199. if (this.verbosity > 0) {
  34200. console.log('Decode time: ' + this.decode_time);
  34201. console.log('Import time: ' + this.import_time);
  34202. }
  34203. return geometry;
  34204. },
  34205. isVersionSupported: function(version, callback) {
  34206. THREE.DRACOLoader.getDecoderModule()
  34207. .then( function ( module ) {
  34208. callback( module.decoder.isVersionSupported( version ) );
  34209. });
  34210. },
  34211. getAttributeOptions: function(attributeName) {
  34212. if (typeof this.attributeOptions[attributeName] === 'undefined')
  34213. this.attributeOptions[attributeName] = {};
  34214. return this.attributeOptions[attributeName];
  34215. }
  34216. };
  34217. THREE.DRACOLoader.decoderPath = './';
  34218. THREE.DRACOLoader.decoderConfig = {};
  34219. THREE.DRACOLoader.decoderModulePromise = null;
  34220. /**
  34221. * Sets the base path for decoder source files.
  34222. * @param {string} path
  34223. */
  34224. THREE.DRACOLoader.setDecoderPath = function ( path ) {
  34225. THREE.DRACOLoader.decoderPath = path;
  34226. };
  34227. /**
  34228. * Sets decoder configuration and releases singleton decoder module. Module
  34229. * will be recreated with the next decoding call.
  34230. * @param {Object} config
  34231. */
  34232. THREE.DRACOLoader.setDecoderConfig = function ( config ) {
  34233. var wasmBinary = THREE.DRACOLoader.decoderConfig.wasmBinary;
  34234. THREE.DRACOLoader.decoderConfig = config || {};
  34235. THREE.DRACOLoader.releaseDecoderModule();
  34236. // Reuse WASM binary.
  34237. if ( wasmBinary ) THREE.DRACOLoader.decoderConfig.wasmBinary = wasmBinary;
  34238. };
  34239. /**
  34240. * Releases the singleton DracoDecoderModule instance. Module will be recreated
  34241. * with the next decoding call.
  34242. */
  34243. THREE.DRACOLoader.releaseDecoderModule = function () {
  34244. THREE.DRACOLoader.decoderModulePromise = null;
  34245. };
  34246. /**
  34247. * Gets WebAssembly or asm.js singleton instance of DracoDecoderModule
  34248. * after testing for browser support. Returns Promise that resolves when
  34249. * module is available.
  34250. * @return {Promise<{decoder: DracoDecoderModule}>}
  34251. */
  34252. THREE.DRACOLoader.getDecoderModule = function () {
  34253. var scope = this;
  34254. var path = THREE.DRACOLoader.decoderPath;
  34255. var config = THREE.DRACOLoader.decoderConfig;
  34256. var promise = THREE.DRACOLoader.decoderModulePromise;
  34257. if ( promise ) return promise;
  34258. // Load source files.
  34259. if ( typeof DracoDecoderModule !== 'undefined' ) {
  34260. // Loaded externally.
  34261. promise = Promise.resolve();
  34262. } else if ( typeof WebAssembly !== 'object' || config.type === 'js' ) {
  34263. // Load with asm.js.
  34264. promise = THREE.DRACOLoader._loadScript( path + 'draco_decoder.js' );
  34265. } else {
  34266. // Load with WebAssembly.
  34267. config.wasmBinaryFile = path + 'draco_decoder.wasm';
  34268. promise = THREE.DRACOLoader._loadScript( path + 'draco_wasm_wrapper.js' )
  34269. .then( function () {
  34270. return THREE.DRACOLoader._loadArrayBuffer( config.wasmBinaryFile );
  34271. } )
  34272. .then( function ( wasmBinary ) {
  34273. config.wasmBinary = wasmBinary;
  34274. } );
  34275. }
  34276. // Wait for source files, then create and return a decoder.
  34277. promise = promise.then( function () {
  34278. return new Promise( function ( resolve ) {
  34279. config.onModuleLoaded = function ( decoder ) {
  34280. scope.timeLoaded = performance.now();
  34281. // Module is Promise-like. Wrap before resolving to avoid loop.
  34282. resolve( { decoder: decoder } );
  34283. };
  34284. DracoDecoderModule( config );
  34285. } );
  34286. } );
  34287. THREE.DRACOLoader.decoderModulePromise = promise;
  34288. return promise;
  34289. };
  34290. /**
  34291. * @param {string} src
  34292. * @return {Promise}
  34293. */
  34294. THREE.DRACOLoader._loadScript = function ( src ) {
  34295. var prevScript = document.getElementById( 'decoder_script' );
  34296. if ( prevScript !== null ) {
  34297. prevScript.parentNode.removeChild( prevScript );
  34298. }
  34299. var head = document.getElementsByTagName( 'head' )[ 0 ];
  34300. var script = document.createElement( 'script' );
  34301. script.id = 'decoder_script';
  34302. script.type = 'text/javascript';
  34303. script.src = src;
  34304. return new Promise( function ( resolve ) {
  34305. script.onload = resolve;
  34306. head.appendChild( script );
  34307. });
  34308. };
  34309. /**
  34310. * @param {string} src
  34311. * @return {Promise}
  34312. */
  34313. THREE.DRACOLoader._loadArrayBuffer = function ( src ) {
  34314. var loader = new THREE.FileLoader();
  34315. loader.setResponseType( 'arraybuffer' );
  34316. return new Promise( function( resolve, reject ) {
  34317. loader.load( src, resolve, undefined, reject );
  34318. });
  34319. };
  34320. },{}],38:[function(_dereq_,module,exports){
  34321. /**
  34322. * @author Rich Tibbett / https://github.com/richtr
  34323. * @author mrdoob / http://mrdoob.com/
  34324. * @author Tony Parisi / http://www.tonyparisi.com/
  34325. * @author Takahiro / https://github.com/takahirox
  34326. * @author Don McCurdy / https://www.donmccurdy.com
  34327. */
  34328. THREE.GLTFLoader = ( function () {
  34329. function GLTFLoader( manager ) {
  34330. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  34331. this.dracoLoader = null;
  34332. }
  34333. GLTFLoader.prototype = {
  34334. constructor: GLTFLoader,
  34335. crossOrigin: 'anonymous',
  34336. load: function ( url, onLoad, onProgress, onError ) {
  34337. var scope = this;
  34338. var resourcePath;
  34339. if ( this.resourcePath !== undefined ) {
  34340. resourcePath = this.resourcePath;
  34341. } else if ( this.path !== undefined ) {
  34342. resourcePath = this.path;
  34343. } else {
  34344. resourcePath = THREE.LoaderUtils.extractUrlBase( url );
  34345. }
  34346. // Tells the LoadingManager to track an extra item, which resolves after
  34347. // the model is fully loaded. This means the count of items loaded will
  34348. // be incorrect, but ensures manager.onLoad() does not fire early.
  34349. scope.manager.itemStart( url );
  34350. var _onError = function ( e ) {
  34351. if ( onError ) {
  34352. onError( e );
  34353. } else {
  34354. console.error( e );
  34355. }
  34356. scope.manager.itemError( url );
  34357. scope.manager.itemEnd( url );
  34358. };
  34359. var loader = new THREE.FileLoader( scope.manager );
  34360. loader.setPath( this.path );
  34361. loader.setResponseType( 'arraybuffer' );
  34362. loader.load( url, function ( data ) {
  34363. try {
  34364. scope.parse( data, resourcePath, function ( gltf ) {
  34365. onLoad( gltf );
  34366. scope.manager.itemEnd( url );
  34367. }, _onError );
  34368. } catch ( e ) {
  34369. _onError( e );
  34370. }
  34371. }, onProgress, _onError );
  34372. },
  34373. setCrossOrigin: function ( value ) {
  34374. this.crossOrigin = value;
  34375. return this;
  34376. },
  34377. setPath: function ( value ) {
  34378. this.path = value;
  34379. return this;
  34380. },
  34381. setResourcePath: function ( value ) {
  34382. this.resourcePath = value;
  34383. return this;
  34384. },
  34385. setDRACOLoader: function ( dracoLoader ) {
  34386. this.dracoLoader = dracoLoader;
  34387. return this;
  34388. },
  34389. parse: function ( data, path, onLoad, onError ) {
  34390. var content;
  34391. var extensions = {};
  34392. if ( typeof data === 'string' ) {
  34393. content = data;
  34394. } else {
  34395. var magic = THREE.LoaderUtils.decodeText( new Uint8Array( data, 0, 4 ) );
  34396. if ( magic === BINARY_EXTENSION_HEADER_MAGIC ) {
  34397. try {
  34398. extensions[ EXTENSIONS.KHR_BINARY_GLTF ] = new GLTFBinaryExtension( data );
  34399. } catch ( error ) {
  34400. if ( onError ) onError( error );
  34401. return;
  34402. }
  34403. content = extensions[ EXTENSIONS.KHR_BINARY_GLTF ].content;
  34404. } else {
  34405. content = THREE.LoaderUtils.decodeText( new Uint8Array( data ) );
  34406. }
  34407. }
  34408. var json = JSON.parse( content );
  34409. if ( json.asset === undefined || json.asset.version[ 0 ] < 2 ) {
  34410. if ( onError ) onError( new Error( 'THREE.GLTFLoader: Unsupported asset. glTF versions >=2.0 are supported. Use LegacyGLTFLoader instead.' ) );
  34411. return;
  34412. }
  34413. if ( json.extensionsUsed ) {
  34414. for ( var i = 0; i < json.extensionsUsed.length; ++ i ) {
  34415. var extensionName = json.extensionsUsed[ i ];
  34416. var extensionsRequired = json.extensionsRequired || [];
  34417. switch ( extensionName ) {
  34418. case EXTENSIONS.KHR_LIGHTS_PUNCTUAL:
  34419. extensions[ extensionName ] = new GLTFLightsExtension( json );
  34420. break;
  34421. case EXTENSIONS.KHR_MATERIALS_UNLIT:
  34422. extensions[ extensionName ] = new GLTFMaterialsUnlitExtension( json );
  34423. break;
  34424. case EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS:
  34425. extensions[ extensionName ] = new GLTFMaterialsPbrSpecularGlossinessExtension( json );
  34426. break;
  34427. case EXTENSIONS.KHR_DRACO_MESH_COMPRESSION:
  34428. extensions[ extensionName ] = new GLTFDracoMeshCompressionExtension( json, this.dracoLoader );
  34429. break;
  34430. case EXTENSIONS.MSFT_TEXTURE_DDS:
  34431. extensions[ EXTENSIONS.MSFT_TEXTURE_DDS ] = new GLTFTextureDDSExtension();
  34432. break;
  34433. case EXTENSIONS.KHR_TEXTURE_TRANSFORM:
  34434. extensions[ EXTENSIONS.KHR_TEXTURE_TRANSFORM ] = new GLTFTextureTransformExtension( json );
  34435. break;
  34436. default:
  34437. if ( extensionsRequired.indexOf( extensionName ) >= 0 ) {
  34438. console.warn( 'THREE.GLTFLoader: Unknown extension "' + extensionName + '".' );
  34439. }
  34440. }
  34441. }
  34442. }
  34443. var parser = new GLTFParser( json, extensions, {
  34444. path: path || this.resourcePath || '',
  34445. crossOrigin: this.crossOrigin,
  34446. manager: this.manager
  34447. } );
  34448. parser.parse( onLoad, onError );
  34449. }
  34450. };
  34451. /* GLTFREGISTRY */
  34452. function GLTFRegistry() {
  34453. var objects = {};
  34454. return {
  34455. get: function ( key ) {
  34456. return objects[ key ];
  34457. },
  34458. add: function ( key, object ) {
  34459. objects[ key ] = object;
  34460. },
  34461. remove: function ( key ) {
  34462. delete objects[ key ];
  34463. },
  34464. removeAll: function () {
  34465. objects = {};
  34466. }
  34467. };
  34468. }
  34469. /*********************************/
  34470. /********** EXTENSIONS ***********/
  34471. /*********************************/
  34472. var EXTENSIONS = {
  34473. KHR_BINARY_GLTF: 'KHR_binary_glTF',
  34474. KHR_DRACO_MESH_COMPRESSION: 'KHR_draco_mesh_compression',
  34475. KHR_LIGHTS_PUNCTUAL: 'KHR_lights_punctual',
  34476. KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS: 'KHR_materials_pbrSpecularGlossiness',
  34477. KHR_MATERIALS_UNLIT: 'KHR_materials_unlit',
  34478. KHR_TEXTURE_TRANSFORM: 'KHR_texture_transform',
  34479. MSFT_TEXTURE_DDS: 'MSFT_texture_dds'
  34480. };
  34481. /**
  34482. * DDS Texture Extension
  34483. *
  34484. * Specification:
  34485. * https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/MSFT_texture_dds
  34486. *
  34487. */
  34488. function GLTFTextureDDSExtension() {
  34489. if ( ! THREE.DDSLoader ) {
  34490. throw new Error( 'THREE.GLTFLoader: Attempting to load .dds texture without importing THREE.DDSLoader' );
  34491. }
  34492. this.name = EXTENSIONS.MSFT_TEXTURE_DDS;
  34493. this.ddsLoader = new THREE.DDSLoader();
  34494. }
  34495. /**
  34496. * Lights Extension
  34497. *
  34498. * Specification: PENDING
  34499. */
  34500. function GLTFLightsExtension( json ) {
  34501. this.name = EXTENSIONS.KHR_LIGHTS_PUNCTUAL;
  34502. var extension = ( json.extensions && json.extensions[ EXTENSIONS.KHR_LIGHTS_PUNCTUAL ] ) || {};
  34503. this.lightDefs = extension.lights || [];
  34504. }
  34505. GLTFLightsExtension.prototype.loadLight = function ( lightIndex ) {
  34506. var lightDef = this.lightDefs[ lightIndex ];
  34507. var lightNode;
  34508. var color = new THREE.Color( 0xffffff );
  34509. if ( lightDef.color !== undefined ) color.fromArray( lightDef.color );
  34510. var range = lightDef.range !== undefined ? lightDef.range : 0;
  34511. switch ( lightDef.type ) {
  34512. case 'directional':
  34513. lightNode = new THREE.DirectionalLight( color );
  34514. lightNode.target.position.set( 0, 0, - 1 );
  34515. lightNode.add( lightNode.target );
  34516. break;
  34517. case 'point':
  34518. lightNode = new THREE.PointLight( color );
  34519. lightNode.distance = range;
  34520. break;
  34521. case 'spot':
  34522. lightNode = new THREE.SpotLight( color );
  34523. lightNode.distance = range;
  34524. // Handle spotlight properties.
  34525. lightDef.spot = lightDef.spot || {};
  34526. lightDef.spot.innerConeAngle = lightDef.spot.innerConeAngle !== undefined ? lightDef.spot.innerConeAngle : 0;
  34527. lightDef.spot.outerConeAngle = lightDef.spot.outerConeAngle !== undefined ? lightDef.spot.outerConeAngle : Math.PI / 4.0;
  34528. lightNode.angle = lightDef.spot.outerConeAngle;
  34529. lightNode.penumbra = 1.0 - lightDef.spot.innerConeAngle / lightDef.spot.outerConeAngle;
  34530. lightNode.target.position.set( 0, 0, - 1 );
  34531. lightNode.add( lightNode.target );
  34532. break;
  34533. default:
  34534. throw new Error( 'THREE.GLTFLoader: Unexpected light type, "' + lightDef.type + '".' );
  34535. }
  34536. // Some lights (e.g. spot) default to a position other than the origin. Reset the position
  34537. // here, because node-level parsing will only override position if explicitly specified.
  34538. lightNode.position.set( 0, 0, 0 );
  34539. lightNode.decay = 2;
  34540. if ( lightDef.intensity !== undefined ) lightNode.intensity = lightDef.intensity;
  34541. lightNode.name = lightDef.name || ( 'light_' + lightIndex );
  34542. return Promise.resolve( lightNode );
  34543. };
  34544. /**
  34545. * Unlit Materials Extension (pending)
  34546. *
  34547. * PR: https://github.com/KhronosGroup/glTF/pull/1163
  34548. */
  34549. function GLTFMaterialsUnlitExtension( json ) {
  34550. this.name = EXTENSIONS.KHR_MATERIALS_UNLIT;
  34551. }
  34552. GLTFMaterialsUnlitExtension.prototype.getMaterialType = function ( material ) {
  34553. return THREE.MeshBasicMaterial;
  34554. };
  34555. GLTFMaterialsUnlitExtension.prototype.extendParams = function ( materialParams, material, parser ) {
  34556. var pending = [];
  34557. materialParams.color = new THREE.Color( 1.0, 1.0, 1.0 );
  34558. materialParams.opacity = 1.0;
  34559. var metallicRoughness = material.pbrMetallicRoughness;
  34560. if ( metallicRoughness ) {
  34561. if ( Array.isArray( metallicRoughness.baseColorFactor ) ) {
  34562. var array = metallicRoughness.baseColorFactor;
  34563. materialParams.color.fromArray( array );
  34564. materialParams.opacity = array[ 3 ];
  34565. }
  34566. if ( metallicRoughness.baseColorTexture !== undefined ) {
  34567. pending.push( parser.assignTexture( materialParams, 'map', metallicRoughness.baseColorTexture ) );
  34568. }
  34569. }
  34570. return Promise.all( pending );
  34571. };
  34572. /* BINARY EXTENSION */
  34573. var BINARY_EXTENSION_BUFFER_NAME = 'binary_glTF';
  34574. var BINARY_EXTENSION_HEADER_MAGIC = 'glTF';
  34575. var BINARY_EXTENSION_HEADER_LENGTH = 12;
  34576. var BINARY_EXTENSION_CHUNK_TYPES = { JSON: 0x4E4F534A, BIN: 0x004E4942 };
  34577. function GLTFBinaryExtension( data ) {
  34578. this.name = EXTENSIONS.KHR_BINARY_GLTF;
  34579. this.content = null;
  34580. this.body = null;
  34581. var headerView = new DataView( data, 0, BINARY_EXTENSION_HEADER_LENGTH );
  34582. this.header = {
  34583. magic: THREE.LoaderUtils.decodeText( new Uint8Array( data.slice( 0, 4 ) ) ),
  34584. version: headerView.getUint32( 4, true ),
  34585. length: headerView.getUint32( 8, true )
  34586. };
  34587. if ( this.header.magic !== BINARY_EXTENSION_HEADER_MAGIC ) {
  34588. throw new Error( 'THREE.GLTFLoader: Unsupported glTF-Binary header.' );
  34589. } else if ( this.header.version < 2.0 ) {
  34590. throw new Error( 'THREE.GLTFLoader: Legacy binary file detected. Use LegacyGLTFLoader instead.' );
  34591. }
  34592. var chunkView = new DataView( data, BINARY_EXTENSION_HEADER_LENGTH );
  34593. var chunkIndex = 0;
  34594. while ( chunkIndex < chunkView.byteLength ) {
  34595. var chunkLength = chunkView.getUint32( chunkIndex, true );
  34596. chunkIndex += 4;
  34597. var chunkType = chunkView.getUint32( chunkIndex, true );
  34598. chunkIndex += 4;
  34599. if ( chunkType === BINARY_EXTENSION_CHUNK_TYPES.JSON ) {
  34600. var contentArray = new Uint8Array( data, BINARY_EXTENSION_HEADER_LENGTH + chunkIndex, chunkLength );
  34601. this.content = THREE.LoaderUtils.decodeText( contentArray );
  34602. } else if ( chunkType === BINARY_EXTENSION_CHUNK_TYPES.BIN ) {
  34603. var byteOffset = BINARY_EXTENSION_HEADER_LENGTH + chunkIndex;
  34604. this.body = data.slice( byteOffset, byteOffset + chunkLength );
  34605. }
  34606. // Clients must ignore chunks with unknown types.
  34607. chunkIndex += chunkLength;
  34608. }
  34609. if ( this.content === null ) {
  34610. throw new Error( 'THREE.GLTFLoader: JSON content not found.' );
  34611. }
  34612. }
  34613. /**
  34614. * DRACO Mesh Compression Extension
  34615. *
  34616. * Specification: https://github.com/KhronosGroup/glTF/pull/874
  34617. */
  34618. function GLTFDracoMeshCompressionExtension( json, dracoLoader ) {
  34619. if ( ! dracoLoader ) {
  34620. throw new Error( 'THREE.GLTFLoader: No DRACOLoader instance provided.' );
  34621. }
  34622. this.name = EXTENSIONS.KHR_DRACO_MESH_COMPRESSION;
  34623. this.json = json;
  34624. this.dracoLoader = dracoLoader;
  34625. }
  34626. GLTFDracoMeshCompressionExtension.prototype.decodePrimitive = function ( primitive, parser ) {
  34627. var json = this.json;
  34628. var dracoLoader = this.dracoLoader;
  34629. var bufferViewIndex = primitive.extensions[ this.name ].bufferView;
  34630. var gltfAttributeMap = primitive.extensions[ this.name ].attributes;
  34631. var threeAttributeMap = {};
  34632. var attributeNormalizedMap = {};
  34633. var attributeTypeMap = {};
  34634. for ( var attributeName in gltfAttributeMap ) {
  34635. var threeAttributeName = ATTRIBUTES[ attributeName ] || attributeName.toLowerCase();
  34636. threeAttributeMap[ threeAttributeName ] = gltfAttributeMap[ attributeName ];
  34637. }
  34638. for ( attributeName in primitive.attributes ) {
  34639. var threeAttributeName = ATTRIBUTES[ attributeName ] || attributeName.toLowerCase();
  34640. if ( gltfAttributeMap[ attributeName ] !== undefined ) {
  34641. var accessorDef = json.accessors[ primitive.attributes[ attributeName ] ];
  34642. var componentType = WEBGL_COMPONENT_TYPES[ accessorDef.componentType ];
  34643. attributeTypeMap[ threeAttributeName ] = componentType;
  34644. attributeNormalizedMap[ threeAttributeName ] = accessorDef.normalized === true;
  34645. }
  34646. }
  34647. return parser.getDependency( 'bufferView', bufferViewIndex ).then( function ( bufferView ) {
  34648. return new Promise( function ( resolve ) {
  34649. dracoLoader.decodeDracoFile( bufferView, function ( geometry ) {
  34650. for ( var attributeName in geometry.attributes ) {
  34651. var attribute = geometry.attributes[ attributeName ];
  34652. var normalized = attributeNormalizedMap[ attributeName ];
  34653. if ( normalized !== undefined ) attribute.normalized = normalized;
  34654. }
  34655. resolve( geometry );
  34656. }, threeAttributeMap, attributeTypeMap );
  34657. } );
  34658. } );
  34659. };
  34660. /**
  34661. * Texture Transform Extension
  34662. *
  34663. * Specification:
  34664. */
  34665. function GLTFTextureTransformExtension( json ) {
  34666. this.name = EXTENSIONS.KHR_TEXTURE_TRANSFORM;
  34667. }
  34668. GLTFTextureTransformExtension.prototype.extendTexture = function ( texture, transform ) {
  34669. texture = texture.clone();
  34670. if ( transform.offset !== undefined ) {
  34671. texture.offset.fromArray( transform.offset );
  34672. }
  34673. if ( transform.rotation !== undefined ) {
  34674. texture.rotation = transform.rotation;
  34675. }
  34676. if ( transform.scale !== undefined ) {
  34677. texture.repeat.fromArray( transform.scale );
  34678. }
  34679. if ( transform.texCoord !== undefined ) {
  34680. console.warn( 'THREE.GLTFLoader: Custom UV sets in "' + this.name + '" extension not yet supported.' );
  34681. }
  34682. texture.needsUpdate = true;
  34683. return texture;
  34684. };
  34685. /**
  34686. * Specular-Glossiness Extension
  34687. *
  34688. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness
  34689. */
  34690. function GLTFMaterialsPbrSpecularGlossinessExtension() {
  34691. return {
  34692. name: EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS,
  34693. specularGlossinessParams: [
  34694. 'color',
  34695. 'map',
  34696. 'lightMap',
  34697. 'lightMapIntensity',
  34698. 'aoMap',
  34699. 'aoMapIntensity',
  34700. 'emissive',
  34701. 'emissiveIntensity',
  34702. 'emissiveMap',
  34703. 'bumpMap',
  34704. 'bumpScale',
  34705. 'normalMap',
  34706. 'displacementMap',
  34707. 'displacementScale',
  34708. 'displacementBias',
  34709. 'specularMap',
  34710. 'specular',
  34711. 'glossinessMap',
  34712. 'glossiness',
  34713. 'alphaMap',
  34714. 'envMap',
  34715. 'envMapIntensity',
  34716. 'refractionRatio',
  34717. ],
  34718. getMaterialType: function () {
  34719. return THREE.ShaderMaterial;
  34720. },
  34721. extendParams: function ( params, material, parser ) {
  34722. var pbrSpecularGlossiness = material.extensions[ this.name ];
  34723. var shader = THREE.ShaderLib[ 'standard' ];
  34724. var uniforms = THREE.UniformsUtils.clone( shader.uniforms );
  34725. var specularMapParsFragmentChunk = [
  34726. '#ifdef USE_SPECULARMAP',
  34727. ' uniform sampler2D specularMap;',
  34728. '#endif'
  34729. ].join( '\n' );
  34730. var glossinessMapParsFragmentChunk = [
  34731. '#ifdef USE_GLOSSINESSMAP',
  34732. ' uniform sampler2D glossinessMap;',
  34733. '#endif'
  34734. ].join( '\n' );
  34735. var specularMapFragmentChunk = [
  34736. 'vec3 specularFactor = specular;',
  34737. '#ifdef USE_SPECULARMAP',
  34738. ' vec4 texelSpecular = texture2D( specularMap, vUv );',
  34739. ' texelSpecular = sRGBToLinear( texelSpecular );',
  34740. ' // reads channel RGB, compatible with a glTF Specular-Glossiness (RGBA) texture',
  34741. ' specularFactor *= texelSpecular.rgb;',
  34742. '#endif'
  34743. ].join( '\n' );
  34744. var glossinessMapFragmentChunk = [
  34745. 'float glossinessFactor = glossiness;',
  34746. '#ifdef USE_GLOSSINESSMAP',
  34747. ' vec4 texelGlossiness = texture2D( glossinessMap, vUv );',
  34748. ' // reads channel A, compatible with a glTF Specular-Glossiness (RGBA) texture',
  34749. ' glossinessFactor *= texelGlossiness.a;',
  34750. '#endif'
  34751. ].join( '\n' );
  34752. var lightPhysicalFragmentChunk = [
  34753. 'PhysicalMaterial material;',
  34754. 'material.diffuseColor = diffuseColor.rgb;',
  34755. 'material.specularRoughness = clamp( 1.0 - glossinessFactor, 0.04, 1.0 );',
  34756. 'material.specularColor = specularFactor.rgb;',
  34757. ].join( '\n' );
  34758. var fragmentShader = shader.fragmentShader
  34759. .replace( 'uniform float roughness;', 'uniform vec3 specular;' )
  34760. .replace( 'uniform float metalness;', 'uniform float glossiness;' )
  34761. .replace( '#include <roughnessmap_pars_fragment>', specularMapParsFragmentChunk )
  34762. .replace( '#include <metalnessmap_pars_fragment>', glossinessMapParsFragmentChunk )
  34763. .replace( '#include <roughnessmap_fragment>', specularMapFragmentChunk )
  34764. .replace( '#include <metalnessmap_fragment>', glossinessMapFragmentChunk )
  34765. .replace( '#include <lights_physical_fragment>', lightPhysicalFragmentChunk );
  34766. delete uniforms.roughness;
  34767. delete uniforms.metalness;
  34768. delete uniforms.roughnessMap;
  34769. delete uniforms.metalnessMap;
  34770. uniforms.specular = { value: new THREE.Color().setHex( 0x111111 ) };
  34771. uniforms.glossiness = { value: 0.5 };
  34772. uniforms.specularMap = { value: null };
  34773. uniforms.glossinessMap = { value: null };
  34774. params.vertexShader = shader.vertexShader;
  34775. params.fragmentShader = fragmentShader;
  34776. params.uniforms = uniforms;
  34777. params.defines = { 'STANDARD': '' };
  34778. params.color = new THREE.Color( 1.0, 1.0, 1.0 );
  34779. params.opacity = 1.0;
  34780. var pending = [];
  34781. if ( Array.isArray( pbrSpecularGlossiness.diffuseFactor ) ) {
  34782. var array = pbrSpecularGlossiness.diffuseFactor;
  34783. params.color.fromArray( array );
  34784. params.opacity = array[ 3 ];
  34785. }
  34786. if ( pbrSpecularGlossiness.diffuseTexture !== undefined ) {
  34787. pending.push( parser.assignTexture( params, 'map', pbrSpecularGlossiness.diffuseTexture ) );
  34788. }
  34789. params.emissive = new THREE.Color( 0.0, 0.0, 0.0 );
  34790. params.glossiness = pbrSpecularGlossiness.glossinessFactor !== undefined ? pbrSpecularGlossiness.glossinessFactor : 1.0;
  34791. params.specular = new THREE.Color( 1.0, 1.0, 1.0 );
  34792. if ( Array.isArray( pbrSpecularGlossiness.specularFactor ) ) {
  34793. params.specular.fromArray( pbrSpecularGlossiness.specularFactor );
  34794. }
  34795. if ( pbrSpecularGlossiness.specularGlossinessTexture !== undefined ) {
  34796. var specGlossMapDef = pbrSpecularGlossiness.specularGlossinessTexture;
  34797. pending.push( parser.assignTexture( params, 'glossinessMap', specGlossMapDef ) );
  34798. pending.push( parser.assignTexture( params, 'specularMap', specGlossMapDef ) );
  34799. }
  34800. return Promise.all( pending );
  34801. },
  34802. createMaterial: function ( params ) {
  34803. // setup material properties based on MeshStandardMaterial for Specular-Glossiness
  34804. var material = new THREE.ShaderMaterial( {
  34805. defines: params.defines,
  34806. vertexShader: params.vertexShader,
  34807. fragmentShader: params.fragmentShader,
  34808. uniforms: params.uniforms,
  34809. fog: true,
  34810. lights: true,
  34811. opacity: params.opacity,
  34812. transparent: params.transparent
  34813. } );
  34814. material.isGLTFSpecularGlossinessMaterial = true;
  34815. material.color = params.color;
  34816. material.map = params.map === undefined ? null : params.map;
  34817. material.lightMap = null;
  34818. material.lightMapIntensity = 1.0;
  34819. material.aoMap = params.aoMap === undefined ? null : params.aoMap;
  34820. material.aoMapIntensity = 1.0;
  34821. material.emissive = params.emissive;
  34822. material.emissiveIntensity = 1.0;
  34823. material.emissiveMap = params.emissiveMap === undefined ? null : params.emissiveMap;
  34824. material.bumpMap = params.bumpMap === undefined ? null : params.bumpMap;
  34825. material.bumpScale = 1;
  34826. material.normalMap = params.normalMap === undefined ? null : params.normalMap;
  34827. if ( params.normalScale ) material.normalScale = params.normalScale;
  34828. material.displacementMap = null;
  34829. material.displacementScale = 1;
  34830. material.displacementBias = 0;
  34831. material.specularMap = params.specularMap === undefined ? null : params.specularMap;
  34832. material.specular = params.specular;
  34833. material.glossinessMap = params.glossinessMap === undefined ? null : params.glossinessMap;
  34834. material.glossiness = params.glossiness;
  34835. material.alphaMap = null;
  34836. material.envMap = params.envMap === undefined ? null : params.envMap;
  34837. material.envMapIntensity = 1.0;
  34838. material.refractionRatio = 0.98;
  34839. material.extensions.derivatives = true;
  34840. return material;
  34841. },
  34842. /**
  34843. * Clones a GLTFSpecularGlossinessMaterial instance. The ShaderMaterial.copy() method can
  34844. * copy only properties it knows about or inherits, and misses many properties that would
  34845. * normally be defined by MeshStandardMaterial.
  34846. *
  34847. * This method allows GLTFSpecularGlossinessMaterials to be cloned in the process of
  34848. * loading a glTF model, but cloning later (e.g. by the user) would require these changes
  34849. * AND also updating `.onBeforeRender` on the parent mesh.
  34850. *
  34851. * @param {THREE.ShaderMaterial} source
  34852. * @return {THREE.ShaderMaterial}
  34853. */
  34854. cloneMaterial: function ( source ) {
  34855. var target = source.clone();
  34856. target.isGLTFSpecularGlossinessMaterial = true;
  34857. var params = this.specularGlossinessParams;
  34858. for ( var i = 0, il = params.length; i < il; i ++ ) {
  34859. target[ params[ i ] ] = source[ params[ i ] ];
  34860. }
  34861. return target;
  34862. },
  34863. // Here's based on refreshUniformsCommon() and refreshUniformsStandard() in WebGLRenderer.
  34864. refreshUniforms: function ( renderer, scene, camera, geometry, material, group ) {
  34865. if ( material.isGLTFSpecularGlossinessMaterial !== true ) {
  34866. return;
  34867. }
  34868. var uniforms = material.uniforms;
  34869. var defines = material.defines;
  34870. uniforms.opacity.value = material.opacity;
  34871. uniforms.diffuse.value.copy( material.color );
  34872. uniforms.emissive.value.copy( material.emissive ).multiplyScalar( material.emissiveIntensity );
  34873. uniforms.map.value = material.map;
  34874. uniforms.specularMap.value = material.specularMap;
  34875. uniforms.alphaMap.value = material.alphaMap;
  34876. uniforms.lightMap.value = material.lightMap;
  34877. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  34878. uniforms.aoMap.value = material.aoMap;
  34879. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  34880. // uv repeat and offset setting priorities
  34881. // 1. color map
  34882. // 2. specular map
  34883. // 3. normal map
  34884. // 4. bump map
  34885. // 5. alpha map
  34886. // 6. emissive map
  34887. var uvScaleMap;
  34888. if ( material.map ) {
  34889. uvScaleMap = material.map;
  34890. } else if ( material.specularMap ) {
  34891. uvScaleMap = material.specularMap;
  34892. } else if ( material.displacementMap ) {
  34893. uvScaleMap = material.displacementMap;
  34894. } else if ( material.normalMap ) {
  34895. uvScaleMap = material.normalMap;
  34896. } else if ( material.bumpMap ) {
  34897. uvScaleMap = material.bumpMap;
  34898. } else if ( material.glossinessMap ) {
  34899. uvScaleMap = material.glossinessMap;
  34900. } else if ( material.alphaMap ) {
  34901. uvScaleMap = material.alphaMap;
  34902. } else if ( material.emissiveMap ) {
  34903. uvScaleMap = material.emissiveMap;
  34904. }
  34905. if ( uvScaleMap !== undefined ) {
  34906. // backwards compatibility
  34907. if ( uvScaleMap.isWebGLRenderTarget ) {
  34908. uvScaleMap = uvScaleMap.texture;
  34909. }
  34910. if ( uvScaleMap.matrixAutoUpdate === true ) {
  34911. uvScaleMap.updateMatrix();
  34912. }
  34913. uniforms.uvTransform.value.copy( uvScaleMap.matrix );
  34914. }
  34915. if ( material.envMap ) {
  34916. uniforms.envMap.value = material.envMap;
  34917. uniforms.envMapIntensity.value = material.envMapIntensity;
  34918. // don't flip CubeTexture envMaps, flip everything else:
  34919. // WebGLRenderTargetCube will be flipped for backwards compatibility
  34920. // WebGLRenderTargetCube.texture will be flipped because it's a Texture and NOT a CubeTexture
  34921. // this check must be handled differently, or removed entirely, if WebGLRenderTargetCube uses a CubeTexture in the future
  34922. uniforms.flipEnvMap.value = material.envMap.isCubeTexture ? - 1 : 1;
  34923. uniforms.reflectivity.value = material.reflectivity;
  34924. uniforms.refractionRatio.value = material.refractionRatio;
  34925. uniforms.maxMipLevel.value = renderer.properties.get( material.envMap ).__maxMipLevel;
  34926. }
  34927. uniforms.specular.value.copy( material.specular );
  34928. uniforms.glossiness.value = material.glossiness;
  34929. uniforms.glossinessMap.value = material.glossinessMap;
  34930. uniforms.emissiveMap.value = material.emissiveMap;
  34931. uniforms.bumpMap.value = material.bumpMap;
  34932. uniforms.normalMap.value = material.normalMap;
  34933. uniforms.displacementMap.value = material.displacementMap;
  34934. uniforms.displacementScale.value = material.displacementScale;
  34935. uniforms.displacementBias.value = material.displacementBias;
  34936. if ( uniforms.glossinessMap.value !== null && defines.USE_GLOSSINESSMAP === undefined ) {
  34937. defines.USE_GLOSSINESSMAP = '';
  34938. // set USE_ROUGHNESSMAP to enable vUv
  34939. defines.USE_ROUGHNESSMAP = '';
  34940. }
  34941. if ( uniforms.glossinessMap.value === null && defines.USE_GLOSSINESSMAP !== undefined ) {
  34942. delete defines.USE_GLOSSINESSMAP;
  34943. delete defines.USE_ROUGHNESSMAP;
  34944. }
  34945. }
  34946. };
  34947. }
  34948. /*********************************/
  34949. /********** INTERPOLATION ********/
  34950. /*********************************/
  34951. // Spline Interpolation
  34952. // Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#appendix-c-spline-interpolation
  34953. function GLTFCubicSplineInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  34954. THREE.Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  34955. }
  34956. GLTFCubicSplineInterpolant.prototype = Object.create( THREE.Interpolant.prototype );
  34957. GLTFCubicSplineInterpolant.prototype.constructor = GLTFCubicSplineInterpolant;
  34958. GLTFCubicSplineInterpolant.prototype.copySampleValue_ = function ( index ) {
  34959. // Copies a sample value to the result buffer. See description of glTF
  34960. // CUBICSPLINE values layout in interpolate_() function below.
  34961. var result = this.resultBuffer,
  34962. values = this.sampleValues,
  34963. valueSize = this.valueSize,
  34964. offset = index * valueSize * 3 + valueSize;
  34965. for ( var i = 0; i !== valueSize; i ++ ) {
  34966. result[ i ] = values[ offset + i ];
  34967. }
  34968. return result;
  34969. };
  34970. GLTFCubicSplineInterpolant.prototype.beforeStart_ = GLTFCubicSplineInterpolant.prototype.copySampleValue_;
  34971. GLTFCubicSplineInterpolant.prototype.afterEnd_ = GLTFCubicSplineInterpolant.prototype.copySampleValue_;
  34972. GLTFCubicSplineInterpolant.prototype.interpolate_ = function ( i1, t0, t, t1 ) {
  34973. var result = this.resultBuffer;
  34974. var values = this.sampleValues;
  34975. var stride = this.valueSize;
  34976. var stride2 = stride * 2;
  34977. var stride3 = stride * 3;
  34978. var td = t1 - t0;
  34979. var p = ( t - t0 ) / td;
  34980. var pp = p * p;
  34981. var ppp = pp * p;
  34982. var offset1 = i1 * stride3;
  34983. var offset0 = offset1 - stride3;
  34984. var s2 = - 2 * ppp + 3 * pp;
  34985. var s3 = ppp - pp;
  34986. var s0 = 1 - s2;
  34987. var s1 = s3 - pp + p;
  34988. // Layout of keyframe output values for CUBICSPLINE animations:
  34989. // [ inTangent_1, splineVertex_1, outTangent_1, inTangent_2, splineVertex_2, ... ]
  34990. for ( var i = 0; i !== stride; i ++ ) {
  34991. var p0 = values[ offset0 + i + stride ]; // splineVertex_k
  34992. var m0 = values[ offset0 + i + stride2 ] * td; // outTangent_k * (t_k+1 - t_k)
  34993. var p1 = values[ offset1 + i + stride ]; // splineVertex_k+1
  34994. var m1 = values[ offset1 + i ] * td; // inTangent_k+1 * (t_k+1 - t_k)
  34995. result[ i ] = s0 * p0 + s1 * m0 + s2 * p1 + s3 * m1;
  34996. }
  34997. return result;
  34998. };
  34999. /*********************************/
  35000. /********** INTERNALS ************/
  35001. /*********************************/
  35002. /* CONSTANTS */
  35003. var WEBGL_CONSTANTS = {
  35004. FLOAT: 5126,
  35005. //FLOAT_MAT2: 35674,
  35006. FLOAT_MAT3: 35675,
  35007. FLOAT_MAT4: 35676,
  35008. FLOAT_VEC2: 35664,
  35009. FLOAT_VEC3: 35665,
  35010. FLOAT_VEC4: 35666,
  35011. LINEAR: 9729,
  35012. REPEAT: 10497,
  35013. SAMPLER_2D: 35678,
  35014. POINTS: 0,
  35015. LINES: 1,
  35016. LINE_LOOP: 2,
  35017. LINE_STRIP: 3,
  35018. TRIANGLES: 4,
  35019. TRIANGLE_STRIP: 5,
  35020. TRIANGLE_FAN: 6,
  35021. UNSIGNED_BYTE: 5121,
  35022. UNSIGNED_SHORT: 5123
  35023. };
  35024. var WEBGL_TYPE = {
  35025. 5126: Number,
  35026. //35674: THREE.Matrix2,
  35027. 35675: THREE.Matrix3,
  35028. 35676: THREE.Matrix4,
  35029. 35664: THREE.Vector2,
  35030. 35665: THREE.Vector3,
  35031. 35666: THREE.Vector4,
  35032. 35678: THREE.Texture
  35033. };
  35034. var WEBGL_COMPONENT_TYPES = {
  35035. 5120: Int8Array,
  35036. 5121: Uint8Array,
  35037. 5122: Int16Array,
  35038. 5123: Uint16Array,
  35039. 5125: Uint32Array,
  35040. 5126: Float32Array
  35041. };
  35042. var WEBGL_FILTERS = {
  35043. 9728: THREE.NearestFilter,
  35044. 9729: THREE.LinearFilter,
  35045. 9984: THREE.NearestMipMapNearestFilter,
  35046. 9985: THREE.LinearMipMapNearestFilter,
  35047. 9986: THREE.NearestMipMapLinearFilter,
  35048. 9987: THREE.LinearMipMapLinearFilter
  35049. };
  35050. var WEBGL_WRAPPINGS = {
  35051. 33071: THREE.ClampToEdgeWrapping,
  35052. 33648: THREE.MirroredRepeatWrapping,
  35053. 10497: THREE.RepeatWrapping
  35054. };
  35055. var WEBGL_SIDES = {
  35056. 1028: THREE.BackSide, // Culling front
  35057. 1029: THREE.FrontSide // Culling back
  35058. //1032: THREE.NoSide // Culling front and back, what to do?
  35059. };
  35060. var WEBGL_DEPTH_FUNCS = {
  35061. 512: THREE.NeverDepth,
  35062. 513: THREE.LessDepth,
  35063. 514: THREE.EqualDepth,
  35064. 515: THREE.LessEqualDepth,
  35065. 516: THREE.GreaterEqualDepth,
  35066. 517: THREE.NotEqualDepth,
  35067. 518: THREE.GreaterEqualDepth,
  35068. 519: THREE.AlwaysDepth
  35069. };
  35070. var WEBGL_BLEND_EQUATIONS = {
  35071. 32774: THREE.AddEquation,
  35072. 32778: THREE.SubtractEquation,
  35073. 32779: THREE.ReverseSubtractEquation
  35074. };
  35075. var WEBGL_BLEND_FUNCS = {
  35076. 0: THREE.ZeroFactor,
  35077. 1: THREE.OneFactor,
  35078. 768: THREE.SrcColorFactor,
  35079. 769: THREE.OneMinusSrcColorFactor,
  35080. 770: THREE.SrcAlphaFactor,
  35081. 771: THREE.OneMinusSrcAlphaFactor,
  35082. 772: THREE.DstAlphaFactor,
  35083. 773: THREE.OneMinusDstAlphaFactor,
  35084. 774: THREE.DstColorFactor,
  35085. 775: THREE.OneMinusDstColorFactor,
  35086. 776: THREE.SrcAlphaSaturateFactor
  35087. // The followings are not supported by Three.js yet
  35088. //32769: CONSTANT_COLOR,
  35089. //32770: ONE_MINUS_CONSTANT_COLOR,
  35090. //32771: CONSTANT_ALPHA,
  35091. //32772: ONE_MINUS_CONSTANT_COLOR
  35092. };
  35093. var WEBGL_TYPE_SIZES = {
  35094. 'SCALAR': 1,
  35095. 'VEC2': 2,
  35096. 'VEC3': 3,
  35097. 'VEC4': 4,
  35098. 'MAT2': 4,
  35099. 'MAT3': 9,
  35100. 'MAT4': 16
  35101. };
  35102. var ATTRIBUTES = {
  35103. POSITION: 'position',
  35104. NORMAL: 'normal',
  35105. TANGENT: 'tangent',
  35106. TEXCOORD_0: 'uv',
  35107. TEXCOORD_1: 'uv2',
  35108. COLOR_0: 'color',
  35109. WEIGHTS_0: 'skinWeight',
  35110. JOINTS_0: 'skinIndex',
  35111. };
  35112. var PATH_PROPERTIES = {
  35113. scale: 'scale',
  35114. translation: 'position',
  35115. rotation: 'quaternion',
  35116. weights: 'morphTargetInfluences'
  35117. };
  35118. var INTERPOLATION = {
  35119. CUBICSPLINE: undefined, // We use a custom interpolant (GLTFCubicSplineInterpolation) for CUBICSPLINE tracks. Each
  35120. // keyframe track will be initialized with a default interpolation type, then modified.
  35121. LINEAR: THREE.InterpolateLinear,
  35122. STEP: THREE.InterpolateDiscrete
  35123. };
  35124. var STATES_ENABLES = {
  35125. 2884: 'CULL_FACE',
  35126. 2929: 'DEPTH_TEST',
  35127. 3042: 'BLEND',
  35128. 3089: 'SCISSOR_TEST',
  35129. 32823: 'POLYGON_OFFSET_FILL',
  35130. 32926: 'SAMPLE_ALPHA_TO_COVERAGE'
  35131. };
  35132. var ALPHA_MODES = {
  35133. OPAQUE: 'OPAQUE',
  35134. MASK: 'MASK',
  35135. BLEND: 'BLEND'
  35136. };
  35137. var MIME_TYPE_FORMATS = {
  35138. 'image/png': THREE.RGBAFormat,
  35139. 'image/jpeg': THREE.RGBFormat
  35140. };
  35141. /* UTILITY FUNCTIONS */
  35142. function resolveURL( url, path ) {
  35143. // Invalid URL
  35144. if ( typeof url !== 'string' || url === '' ) return '';
  35145. // Absolute URL http://,https://,//
  35146. if ( /^(https?:)?\/\//i.test( url ) ) return url;
  35147. // Data URI
  35148. if ( /^data:.*,.*$/i.test( url ) ) return url;
  35149. // Blob URL
  35150. if ( /^blob:.*$/i.test( url ) ) return url;
  35151. // Relative URL
  35152. return path + url;
  35153. }
  35154. var defaultMaterial;
  35155. /**
  35156. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#default-material
  35157. */
  35158. function createDefaultMaterial() {
  35159. defaultMaterial = defaultMaterial || new THREE.MeshStandardMaterial( {
  35160. color: 0xFFFFFF,
  35161. emissive: 0x000000,
  35162. metalness: 1,
  35163. roughness: 1,
  35164. transparent: false,
  35165. depthTest: true,
  35166. side: THREE.FrontSide
  35167. } );
  35168. return defaultMaterial;
  35169. }
  35170. function addUnknownExtensionsToUserData( knownExtensions, object, objectDef ) {
  35171. // Add unknown glTF extensions to an object's userData.
  35172. for ( var name in objectDef.extensions ) {
  35173. if ( knownExtensions[ name ] === undefined ) {
  35174. object.userData.gltfExtensions = object.userData.gltfExtensions || {};
  35175. object.userData.gltfExtensions[ name ] = objectDef.extensions[ name ];
  35176. }
  35177. }
  35178. }
  35179. /**
  35180. * @param {THREE.Object3D|THREE.Material|THREE.BufferGeometry} object
  35181. * @param {GLTF.definition} gltfDef
  35182. */
  35183. function assignExtrasToUserData( object, gltfDef ) {
  35184. if ( gltfDef.extras !== undefined ) {
  35185. if ( typeof gltfDef.extras === 'object' ) {
  35186. object.userData = gltfDef.extras;
  35187. } else {
  35188. console.warn( 'THREE.GLTFLoader: Ignoring primitive type .extras, ' + gltfDef.extras );
  35189. }
  35190. }
  35191. }
  35192. /**
  35193. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#morph-targets
  35194. *
  35195. * @param {THREE.BufferGeometry} geometry
  35196. * @param {Array<GLTF.Target>} targets
  35197. * @param {GLTFParser} parser
  35198. * @return {Promise<THREE.BufferGeometry>}
  35199. */
  35200. function addMorphTargets( geometry, targets, parser ) {
  35201. var hasMorphPosition = false;
  35202. var hasMorphNormal = false;
  35203. for ( var i = 0, il = targets.length; i < il; i ++ ) {
  35204. var target = targets[ i ];
  35205. if ( target.POSITION !== undefined ) hasMorphPosition = true;
  35206. if ( target.NORMAL !== undefined ) hasMorphNormal = true;
  35207. if ( hasMorphPosition && hasMorphNormal ) break;
  35208. }
  35209. if ( ! hasMorphPosition && ! hasMorphNormal ) return Promise.resolve( geometry );
  35210. var pendingPositionAccessors = [];
  35211. var pendingNormalAccessors = [];
  35212. for ( var i = 0, il = targets.length; i < il; i ++ ) {
  35213. var target = targets[ i ];
  35214. if ( hasMorphPosition ) {
  35215. var pendingAccessor = target.POSITION !== undefined
  35216. ? parser.getDependency( 'accessor', target.POSITION )
  35217. : geometry.attributes.position;
  35218. pendingPositionAccessors.push( pendingAccessor );
  35219. }
  35220. if ( hasMorphNormal ) {
  35221. var pendingAccessor = target.NORMAL !== undefined
  35222. ? parser.getDependency( 'accessor', target.NORMAL )
  35223. : geometry.attributes.normal;
  35224. pendingNormalAccessors.push( pendingAccessor );
  35225. }
  35226. }
  35227. return Promise.all( [
  35228. Promise.all( pendingPositionAccessors ),
  35229. Promise.all( pendingNormalAccessors )
  35230. ] ).then( function ( accessors ) {
  35231. var morphPositions = accessors[ 0 ];
  35232. var morphNormals = accessors[ 1 ];
  35233. // Clone morph target accessors before modifying them.
  35234. for ( var i = 0, il = morphPositions.length; i < il; i ++ ) {
  35235. if ( geometry.attributes.position === morphPositions[ i ] ) continue;
  35236. morphPositions[ i ] = cloneBufferAttribute( morphPositions[ i ] );
  35237. }
  35238. for ( var i = 0, il = morphNormals.length; i < il; i ++ ) {
  35239. if ( geometry.attributes.normal === morphNormals[ i ] ) continue;
  35240. morphNormals[ i ] = cloneBufferAttribute( morphNormals[ i ] );
  35241. }
  35242. for ( var i = 0, il = targets.length; i < il; i ++ ) {
  35243. var target = targets[ i ];
  35244. var attributeName = 'morphTarget' + i;
  35245. if ( hasMorphPosition ) {
  35246. // Three.js morph position is absolute value. The formula is
  35247. // basePosition
  35248. // + weight0 * ( morphPosition0 - basePosition )
  35249. // + weight1 * ( morphPosition1 - basePosition )
  35250. // ...
  35251. // while the glTF one is relative
  35252. // basePosition
  35253. // + weight0 * glTFmorphPosition0
  35254. // + weight1 * glTFmorphPosition1
  35255. // ...
  35256. // then we need to convert from relative to absolute here.
  35257. if ( target.POSITION !== undefined ) {
  35258. var positionAttribute = morphPositions[ i ];
  35259. positionAttribute.name = attributeName;
  35260. var position = geometry.attributes.position;
  35261. for ( var j = 0, jl = positionAttribute.count; j < jl; j ++ ) {
  35262. positionAttribute.setXYZ(
  35263. j,
  35264. positionAttribute.getX( j ) + position.getX( j ),
  35265. positionAttribute.getY( j ) + position.getY( j ),
  35266. positionAttribute.getZ( j ) + position.getZ( j )
  35267. );
  35268. }
  35269. }
  35270. }
  35271. if ( hasMorphNormal ) {
  35272. // see target.POSITION's comment
  35273. if ( target.NORMAL !== undefined ) {
  35274. var normalAttribute = morphNormals[ i ];
  35275. normalAttribute.name = attributeName;
  35276. var normal = geometry.attributes.normal;
  35277. for ( var j = 0, jl = normalAttribute.count; j < jl; j ++ ) {
  35278. normalAttribute.setXYZ(
  35279. j,
  35280. normalAttribute.getX( j ) + normal.getX( j ),
  35281. normalAttribute.getY( j ) + normal.getY( j ),
  35282. normalAttribute.getZ( j ) + normal.getZ( j )
  35283. );
  35284. }
  35285. }
  35286. }
  35287. }
  35288. if ( hasMorphPosition ) geometry.morphAttributes.position = morphPositions;
  35289. if ( hasMorphNormal ) geometry.morphAttributes.normal = morphNormals;
  35290. return geometry;
  35291. } );
  35292. }
  35293. /**
  35294. * @param {THREE.Mesh} mesh
  35295. * @param {GLTF.Mesh} meshDef
  35296. */
  35297. function updateMorphTargets( mesh, meshDef ) {
  35298. mesh.updateMorphTargets();
  35299. if ( meshDef.weights !== undefined ) {
  35300. for ( var i = 0, il = meshDef.weights.length; i < il; i ++ ) {
  35301. mesh.morphTargetInfluences[ i ] = meshDef.weights[ i ];
  35302. }
  35303. }
  35304. // .extras has user-defined data, so check that .extras.targetNames is an array.
  35305. if ( meshDef.extras && Array.isArray( meshDef.extras.targetNames ) ) {
  35306. var targetNames = meshDef.extras.targetNames;
  35307. if ( mesh.morphTargetInfluences.length === targetNames.length ) {
  35308. mesh.morphTargetDictionary = {};
  35309. for ( var i = 0, il = targetNames.length; i < il; i ++ ) {
  35310. mesh.morphTargetDictionary[ targetNames[ i ] ] = i;
  35311. }
  35312. } else {
  35313. console.warn( 'THREE.GLTFLoader: Invalid extras.targetNames length. Ignoring names.' );
  35314. }
  35315. }
  35316. }
  35317. function isObjectEqual( a, b ) {
  35318. if ( Object.keys( a ).length !== Object.keys( b ).length ) return false;
  35319. for ( var key in a ) {
  35320. if ( a[ key ] !== b[ key ] ) return false;
  35321. }
  35322. return true;
  35323. }
  35324. function createPrimitiveKey( primitiveDef ) {
  35325. var dracoExtension = primitiveDef.extensions && primitiveDef.extensions[ EXTENSIONS.KHR_DRACO_MESH_COMPRESSION ];
  35326. var geometryKey;
  35327. if ( dracoExtension ) {
  35328. geometryKey = 'draco:' + dracoExtension.bufferView
  35329. + ':' + dracoExtension.indices
  35330. + ':' + createAttributesKey( dracoExtension.attributes );
  35331. } else {
  35332. geometryKey = primitiveDef.indices + ':' + createAttributesKey( primitiveDef.attributes ) + ':' + primitiveDef.mode;
  35333. }
  35334. return geometryKey;
  35335. }
  35336. function createAttributesKey( attributes ) {
  35337. var attributesKey = '';
  35338. var keys = Object.keys( attributes ).sort();
  35339. for ( var i = 0, il = keys.length; i < il; i ++ ) {
  35340. attributesKey += keys[ i ] + ':' + attributes[ keys[ i ] ] + ';';
  35341. }
  35342. return attributesKey;
  35343. }
  35344. function cloneBufferAttribute( attribute ) {
  35345. if ( attribute.isInterleavedBufferAttribute ) {
  35346. var count = attribute.count;
  35347. var itemSize = attribute.itemSize;
  35348. var array = attribute.array.slice( 0, count * itemSize );
  35349. for ( var i = 0, j = 0; i < count; ++ i ) {
  35350. array[ j ++ ] = attribute.getX( i );
  35351. if ( itemSize >= 2 ) array[ j ++ ] = attribute.getY( i );
  35352. if ( itemSize >= 3 ) array[ j ++ ] = attribute.getZ( i );
  35353. if ( itemSize >= 4 ) array[ j ++ ] = attribute.getW( i );
  35354. }
  35355. return new THREE.BufferAttribute( array, itemSize, attribute.normalized );
  35356. }
  35357. return attribute.clone();
  35358. }
  35359. /* GLTF PARSER */
  35360. function GLTFParser( json, extensions, options ) {
  35361. this.json = json || {};
  35362. this.extensions = extensions || {};
  35363. this.options = options || {};
  35364. // loader object cache
  35365. this.cache = new GLTFRegistry();
  35366. // BufferGeometry caching
  35367. this.primitiveCache = {};
  35368. this.textureLoader = new THREE.TextureLoader( this.options.manager );
  35369. this.textureLoader.setCrossOrigin( this.options.crossOrigin );
  35370. this.fileLoader = new THREE.FileLoader( this.options.manager );
  35371. this.fileLoader.setResponseType( 'arraybuffer' );
  35372. }
  35373. GLTFParser.prototype.parse = function ( onLoad, onError ) {
  35374. var parser = this;
  35375. var json = this.json;
  35376. var extensions = this.extensions;
  35377. // Clear the loader cache
  35378. this.cache.removeAll();
  35379. // Mark the special nodes/meshes in json for efficient parse
  35380. this.markDefs();
  35381. Promise.all( [
  35382. this.getDependencies( 'scene' ),
  35383. this.getDependencies( 'animation' ),
  35384. this.getDependencies( 'camera' ),
  35385. ] ).then( function ( dependencies ) {
  35386. var result = {
  35387. scene: dependencies[ 0 ][ json.scene || 0 ],
  35388. scenes: dependencies[ 0 ],
  35389. animations: dependencies[ 1 ],
  35390. cameras: dependencies[ 2 ],
  35391. asset: json.asset,
  35392. parser: parser,
  35393. userData: {}
  35394. };
  35395. addUnknownExtensionsToUserData( extensions, result, json );
  35396. onLoad( result );
  35397. } ).catch( onError );
  35398. };
  35399. /**
  35400. * Marks the special nodes/meshes in json for efficient parse.
  35401. */
  35402. GLTFParser.prototype.markDefs = function () {
  35403. var nodeDefs = this.json.nodes || [];
  35404. var skinDefs = this.json.skins || [];
  35405. var meshDefs = this.json.meshes || [];
  35406. var meshReferences = {};
  35407. var meshUses = {};
  35408. // Nothing in the node definition indicates whether it is a Bone or an
  35409. // Object3D. Use the skins' joint references to mark bones.
  35410. for ( var skinIndex = 0, skinLength = skinDefs.length; skinIndex < skinLength; skinIndex ++ ) {
  35411. var joints = skinDefs[ skinIndex ].joints;
  35412. for ( var i = 0, il = joints.length; i < il; i ++ ) {
  35413. nodeDefs[ joints[ i ] ].isBone = true;
  35414. }
  35415. }
  35416. // Meshes can (and should) be reused by multiple nodes in a glTF asset. To
  35417. // avoid having more than one THREE.Mesh with the same name, count
  35418. // references and rename instances below.
  35419. //
  35420. // Example: CesiumMilkTruck sample model reuses "Wheel" meshes.
  35421. for ( var nodeIndex = 0, nodeLength = nodeDefs.length; nodeIndex < nodeLength; nodeIndex ++ ) {
  35422. var nodeDef = nodeDefs[ nodeIndex ];
  35423. if ( nodeDef.mesh !== undefined ) {
  35424. if ( meshReferences[ nodeDef.mesh ] === undefined ) {
  35425. meshReferences[ nodeDef.mesh ] = meshUses[ nodeDef.mesh ] = 0;
  35426. }
  35427. meshReferences[ nodeDef.mesh ] ++;
  35428. // Nothing in the mesh definition indicates whether it is
  35429. // a SkinnedMesh or Mesh. Use the node's mesh reference
  35430. // to mark SkinnedMesh if node has skin.
  35431. if ( nodeDef.skin !== undefined ) {
  35432. meshDefs[ nodeDef.mesh ].isSkinnedMesh = true;
  35433. }
  35434. }
  35435. }
  35436. this.json.meshReferences = meshReferences;
  35437. this.json.meshUses = meshUses;
  35438. };
  35439. /**
  35440. * Requests the specified dependency asynchronously, with caching.
  35441. * @param {string} type
  35442. * @param {number} index
  35443. * @return {Promise<THREE.Object3D|THREE.Material|THREE.Texture|THREE.AnimationClip|ArrayBuffer|Object>}
  35444. */
  35445. GLTFParser.prototype.getDependency = function ( type, index ) {
  35446. var cacheKey = type + ':' + index;
  35447. var dependency = this.cache.get( cacheKey );
  35448. if ( ! dependency ) {
  35449. switch ( type ) {
  35450. case 'scene':
  35451. dependency = this.loadScene( index );
  35452. break;
  35453. case 'node':
  35454. dependency = this.loadNode( index );
  35455. break;
  35456. case 'mesh':
  35457. dependency = this.loadMesh( index );
  35458. break;
  35459. case 'accessor':
  35460. dependency = this.loadAccessor( index );
  35461. break;
  35462. case 'bufferView':
  35463. dependency = this.loadBufferView( index );
  35464. break;
  35465. case 'buffer':
  35466. dependency = this.loadBuffer( index );
  35467. break;
  35468. case 'material':
  35469. dependency = this.loadMaterial( index );
  35470. break;
  35471. case 'texture':
  35472. dependency = this.loadTexture( index );
  35473. break;
  35474. case 'skin':
  35475. dependency = this.loadSkin( index );
  35476. break;
  35477. case 'animation':
  35478. dependency = this.loadAnimation( index );
  35479. break;
  35480. case 'camera':
  35481. dependency = this.loadCamera( index );
  35482. break;
  35483. case 'light':
  35484. dependency = this.extensions[ EXTENSIONS.KHR_LIGHTS_PUNCTUAL ].loadLight( index );
  35485. break;
  35486. default:
  35487. throw new Error( 'Unknown type: ' + type );
  35488. }
  35489. this.cache.add( cacheKey, dependency );
  35490. }
  35491. return dependency;
  35492. };
  35493. /**
  35494. * Requests all dependencies of the specified type asynchronously, with caching.
  35495. * @param {string} type
  35496. * @return {Promise<Array<Object>>}
  35497. */
  35498. GLTFParser.prototype.getDependencies = function ( type ) {
  35499. var dependencies = this.cache.get( type );
  35500. if ( ! dependencies ) {
  35501. var parser = this;
  35502. var defs = this.json[ type + ( type === 'mesh' ? 'es' : 's' ) ] || [];
  35503. dependencies = Promise.all( defs.map( function ( def, index ) {
  35504. return parser.getDependency( type, index );
  35505. } ) );
  35506. this.cache.add( type, dependencies );
  35507. }
  35508. return dependencies;
  35509. };
  35510. /**
  35511. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#buffers-and-buffer-views
  35512. * @param {number} bufferIndex
  35513. * @return {Promise<ArrayBuffer>}
  35514. */
  35515. GLTFParser.prototype.loadBuffer = function ( bufferIndex ) {
  35516. var bufferDef = this.json.buffers[ bufferIndex ];
  35517. var loader = this.fileLoader;
  35518. if ( bufferDef.type && bufferDef.type !== 'arraybuffer' ) {
  35519. throw new Error( 'THREE.GLTFLoader: ' + bufferDef.type + ' buffer type is not supported.' );
  35520. }
  35521. // If present, GLB container is required to be the first buffer.
  35522. if ( bufferDef.uri === undefined && bufferIndex === 0 ) {
  35523. return Promise.resolve( this.extensions[ EXTENSIONS.KHR_BINARY_GLTF ].body );
  35524. }
  35525. var options = this.options;
  35526. return new Promise( function ( resolve, reject ) {
  35527. loader.load( resolveURL( bufferDef.uri, options.path ), resolve, undefined, function () {
  35528. reject( new Error( 'THREE.GLTFLoader: Failed to load buffer "' + bufferDef.uri + '".' ) );
  35529. } );
  35530. } );
  35531. };
  35532. /**
  35533. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#buffers-and-buffer-views
  35534. * @param {number} bufferViewIndex
  35535. * @return {Promise<ArrayBuffer>}
  35536. */
  35537. GLTFParser.prototype.loadBufferView = function ( bufferViewIndex ) {
  35538. var bufferViewDef = this.json.bufferViews[ bufferViewIndex ];
  35539. return this.getDependency( 'buffer', bufferViewDef.buffer ).then( function ( buffer ) {
  35540. var byteLength = bufferViewDef.byteLength || 0;
  35541. var byteOffset = bufferViewDef.byteOffset || 0;
  35542. return buffer.slice( byteOffset, byteOffset + byteLength );
  35543. } );
  35544. };
  35545. /**
  35546. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#accessors
  35547. * @param {number} accessorIndex
  35548. * @return {Promise<THREE.BufferAttribute|THREE.InterleavedBufferAttribute>}
  35549. */
  35550. GLTFParser.prototype.loadAccessor = function ( accessorIndex ) {
  35551. var parser = this;
  35552. var json = this.json;
  35553. var accessorDef = this.json.accessors[ accessorIndex ];
  35554. if ( accessorDef.bufferView === undefined && accessorDef.sparse === undefined ) {
  35555. // Ignore empty accessors, which may be used to declare runtime
  35556. // information about attributes coming from another source (e.g. Draco
  35557. // compression extension).
  35558. return Promise.resolve( null );
  35559. }
  35560. var pendingBufferViews = [];
  35561. if ( accessorDef.bufferView !== undefined ) {
  35562. pendingBufferViews.push( this.getDependency( 'bufferView', accessorDef.bufferView ) );
  35563. } else {
  35564. pendingBufferViews.push( null );
  35565. }
  35566. if ( accessorDef.sparse !== undefined ) {
  35567. pendingBufferViews.push( this.getDependency( 'bufferView', accessorDef.sparse.indices.bufferView ) );
  35568. pendingBufferViews.push( this.getDependency( 'bufferView', accessorDef.sparse.values.bufferView ) );
  35569. }
  35570. return Promise.all( pendingBufferViews ).then( function ( bufferViews ) {
  35571. var bufferView = bufferViews[ 0 ];
  35572. var itemSize = WEBGL_TYPE_SIZES[ accessorDef.type ];
  35573. var TypedArray = WEBGL_COMPONENT_TYPES[ accessorDef.componentType ];
  35574. // For VEC3: itemSize is 3, elementBytes is 4, itemBytes is 12.
  35575. var elementBytes = TypedArray.BYTES_PER_ELEMENT;
  35576. var itemBytes = elementBytes * itemSize;
  35577. var byteOffset = accessorDef.byteOffset || 0;
  35578. var byteStride = accessorDef.bufferView !== undefined ? json.bufferViews[ accessorDef.bufferView ].byteStride : undefined;
  35579. var normalized = accessorDef.normalized === true;
  35580. var array, bufferAttribute;
  35581. // The buffer is not interleaved if the stride is the item size in bytes.
  35582. if ( byteStride && byteStride !== itemBytes ) {
  35583. var ibCacheKey = 'InterleavedBuffer:' + accessorDef.bufferView + ':' + accessorDef.componentType;
  35584. var ib = parser.cache.get( ibCacheKey );
  35585. if ( ! ib ) {
  35586. // Use the full buffer if it's interleaved.
  35587. array = new TypedArray( bufferView );
  35588. // Integer parameters to IB/IBA are in array elements, not bytes.
  35589. ib = new THREE.InterleavedBuffer( array, byteStride / elementBytes );
  35590. parser.cache.add( ibCacheKey, ib );
  35591. }
  35592. bufferAttribute = new THREE.InterleavedBufferAttribute( ib, itemSize, byteOffset / elementBytes, normalized );
  35593. } else {
  35594. if ( bufferView === null ) {
  35595. array = new TypedArray( accessorDef.count * itemSize );
  35596. } else {
  35597. array = new TypedArray( bufferView, byteOffset, accessorDef.count * itemSize );
  35598. }
  35599. bufferAttribute = new THREE.BufferAttribute( array, itemSize, normalized );
  35600. }
  35601. // https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#sparse-accessors
  35602. if ( accessorDef.sparse !== undefined ) {
  35603. var itemSizeIndices = WEBGL_TYPE_SIZES.SCALAR;
  35604. var TypedArrayIndices = WEBGL_COMPONENT_TYPES[ accessorDef.sparse.indices.componentType ];
  35605. var byteOffsetIndices = accessorDef.sparse.indices.byteOffset || 0;
  35606. var byteOffsetValues = accessorDef.sparse.values.byteOffset || 0;
  35607. var sparseIndices = new TypedArrayIndices( bufferViews[ 1 ], byteOffsetIndices, accessorDef.sparse.count * itemSizeIndices );
  35608. var sparseValues = new TypedArray( bufferViews[ 2 ], byteOffsetValues, accessorDef.sparse.count * itemSize );
  35609. if ( bufferView !== null ) {
  35610. // Avoid modifying the original ArrayBuffer, if the bufferView wasn't initialized with zeroes.
  35611. bufferAttribute.setArray( bufferAttribute.array.slice() );
  35612. }
  35613. for ( var i = 0, il = sparseIndices.length; i < il; i ++ ) {
  35614. var index = sparseIndices[ i ];
  35615. bufferAttribute.setX( index, sparseValues[ i * itemSize ] );
  35616. if ( itemSize >= 2 ) bufferAttribute.setY( index, sparseValues[ i * itemSize + 1 ] );
  35617. if ( itemSize >= 3 ) bufferAttribute.setZ( index, sparseValues[ i * itemSize + 2 ] );
  35618. if ( itemSize >= 4 ) bufferAttribute.setW( index, sparseValues[ i * itemSize + 3 ] );
  35619. if ( itemSize >= 5 ) throw new Error( 'THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute.' );
  35620. }
  35621. }
  35622. return bufferAttribute;
  35623. } );
  35624. };
  35625. /**
  35626. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#textures
  35627. * @param {number} textureIndex
  35628. * @return {Promise<THREE.Texture>}
  35629. */
  35630. GLTFParser.prototype.loadTexture = function ( textureIndex ) {
  35631. var parser = this;
  35632. var json = this.json;
  35633. var options = this.options;
  35634. var textureLoader = this.textureLoader;
  35635. var URL = window.URL || window.webkitURL;
  35636. var textureDef = json.textures[ textureIndex ];
  35637. var textureExtensions = textureDef.extensions || {};
  35638. var source;
  35639. if ( textureExtensions[ EXTENSIONS.MSFT_TEXTURE_DDS ] ) {
  35640. source = json.images[ textureExtensions[ EXTENSIONS.MSFT_TEXTURE_DDS ].source ];
  35641. } else {
  35642. source = json.images[ textureDef.source ];
  35643. }
  35644. var sourceURI = source.uri;
  35645. var isObjectURL = false;
  35646. if ( source.bufferView !== undefined ) {
  35647. // Load binary image data from bufferView, if provided.
  35648. sourceURI = parser.getDependency( 'bufferView', source.bufferView ).then( function ( bufferView ) {
  35649. isObjectURL = true;
  35650. var blob = new Blob( [ bufferView ], { type: source.mimeType } );
  35651. sourceURI = URL.createObjectURL( blob );
  35652. return sourceURI;
  35653. } );
  35654. }
  35655. return Promise.resolve( sourceURI ).then( function ( sourceURI ) {
  35656. // Load Texture resource.
  35657. var loader = THREE.Loader.Handlers.get( sourceURI );
  35658. if ( ! loader ) {
  35659. loader = textureExtensions[ EXTENSIONS.MSFT_TEXTURE_DDS ]
  35660. ? parser.extensions[ EXTENSIONS.MSFT_TEXTURE_DDS ].ddsLoader
  35661. : textureLoader;
  35662. }
  35663. return new Promise( function ( resolve, reject ) {
  35664. loader.load( resolveURL( sourceURI, options.path ), resolve, undefined, reject );
  35665. } );
  35666. } ).then( function ( texture ) {
  35667. // Clean up resources and configure Texture.
  35668. if ( isObjectURL === true ) {
  35669. URL.revokeObjectURL( sourceURI );
  35670. }
  35671. texture.flipY = false;
  35672. if ( textureDef.name !== undefined ) texture.name = textureDef.name;
  35673. // Ignore unknown mime types, like DDS files.
  35674. if ( source.mimeType in MIME_TYPE_FORMATS ) {
  35675. texture.format = MIME_TYPE_FORMATS[ source.mimeType ];
  35676. }
  35677. var samplers = json.samplers || {};
  35678. var sampler = samplers[ textureDef.sampler ] || {};
  35679. texture.magFilter = WEBGL_FILTERS[ sampler.magFilter ] || THREE.LinearFilter;
  35680. texture.minFilter = WEBGL_FILTERS[ sampler.minFilter ] || THREE.LinearMipMapLinearFilter;
  35681. texture.wrapS = WEBGL_WRAPPINGS[ sampler.wrapS ] || THREE.RepeatWrapping;
  35682. texture.wrapT = WEBGL_WRAPPINGS[ sampler.wrapT ] || THREE.RepeatWrapping;
  35683. return texture;
  35684. } );
  35685. };
  35686. /**
  35687. * Asynchronously assigns a texture to the given material parameters.
  35688. * @param {Object} materialParams
  35689. * @param {string} mapName
  35690. * @param {Object} mapDef
  35691. * @return {Promise}
  35692. */
  35693. GLTFParser.prototype.assignTexture = function ( materialParams, mapName, mapDef ) {
  35694. var parser = this;
  35695. return this.getDependency( 'texture', mapDef.index ).then( function ( texture ) {
  35696. switch ( mapName ) {
  35697. case 'aoMap':
  35698. case 'emissiveMap':
  35699. case 'metalnessMap':
  35700. case 'normalMap':
  35701. case 'roughnessMap':
  35702. texture.format = THREE.RGBFormat;
  35703. break;
  35704. }
  35705. if ( parser.extensions[ EXTENSIONS.KHR_TEXTURE_TRANSFORM ] ) {
  35706. var transform = mapDef.extensions !== undefined ? mapDef.extensions[ EXTENSIONS.KHR_TEXTURE_TRANSFORM ] : undefined;
  35707. if ( transform ) {
  35708. texture = parser.extensions[ EXTENSIONS.KHR_TEXTURE_TRANSFORM ].extendTexture( texture, transform );
  35709. }
  35710. }
  35711. materialParams[ mapName ] = texture;
  35712. } );
  35713. };
  35714. /**
  35715. * Assigns final material to a Mesh, Line, or Points instance. The instance
  35716. * already has a material (generated from the glTF material options alone)
  35717. * but reuse of the same glTF material may require multiple threejs materials
  35718. * to accomodate different primitive types, defines, etc. New materials will
  35719. * be created if necessary, and reused from a cache.
  35720. * @param {THREE.Object3D} mesh Mesh, Line, or Points instance.
  35721. */
  35722. GLTFParser.prototype.assignFinalMaterial = function ( mesh ) {
  35723. var geometry = mesh.geometry;
  35724. var material = mesh.material;
  35725. var extensions = this.extensions;
  35726. var useVertexTangents = geometry.attributes.tangent !== undefined;
  35727. var useVertexColors = geometry.attributes.color !== undefined;
  35728. var useFlatShading = geometry.attributes.normal === undefined;
  35729. var useSkinning = mesh.isSkinnedMesh === true;
  35730. var useMorphTargets = Object.keys( geometry.morphAttributes ).length > 0;
  35731. var useMorphNormals = useMorphTargets && geometry.morphAttributes.normal !== undefined;
  35732. if ( mesh.isPoints ) {
  35733. var cacheKey = 'PointsMaterial:' + material.uuid;
  35734. var pointsMaterial = this.cache.get( cacheKey );
  35735. if ( ! pointsMaterial ) {
  35736. pointsMaterial = new THREE.PointsMaterial();
  35737. THREE.Material.prototype.copy.call( pointsMaterial, material );
  35738. pointsMaterial.color.copy( material.color );
  35739. pointsMaterial.map = material.map;
  35740. pointsMaterial.lights = false; // PointsMaterial doesn't support lights yet
  35741. this.cache.add( cacheKey, pointsMaterial );
  35742. }
  35743. material = pointsMaterial;
  35744. } else if ( mesh.isLine ) {
  35745. var cacheKey = 'LineBasicMaterial:' + material.uuid;
  35746. var lineMaterial = this.cache.get( cacheKey );
  35747. if ( ! lineMaterial ) {
  35748. lineMaterial = new THREE.LineBasicMaterial();
  35749. THREE.Material.prototype.copy.call( lineMaterial, material );
  35750. lineMaterial.color.copy( material.color );
  35751. lineMaterial.lights = false; // LineBasicMaterial doesn't support lights yet
  35752. this.cache.add( cacheKey, lineMaterial );
  35753. }
  35754. material = lineMaterial;
  35755. }
  35756. // Clone the material if it will be modified
  35757. if ( useVertexTangents || useVertexColors || useFlatShading || useSkinning || useMorphTargets ) {
  35758. var cacheKey = 'ClonedMaterial:' + material.uuid + ':';
  35759. if ( material.isGLTFSpecularGlossinessMaterial ) cacheKey += 'specular-glossiness:';
  35760. if ( useSkinning ) cacheKey += 'skinning:';
  35761. if ( useVertexTangents ) cacheKey += 'vertex-tangents:';
  35762. if ( useVertexColors ) cacheKey += 'vertex-colors:';
  35763. if ( useFlatShading ) cacheKey += 'flat-shading:';
  35764. if ( useMorphTargets ) cacheKey += 'morph-targets:';
  35765. if ( useMorphNormals ) cacheKey += 'morph-normals:';
  35766. var cachedMaterial = this.cache.get( cacheKey );
  35767. if ( ! cachedMaterial ) {
  35768. cachedMaterial = material.isGLTFSpecularGlossinessMaterial
  35769. ? extensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ].cloneMaterial( material )
  35770. : material.clone();
  35771. if ( useSkinning ) cachedMaterial.skinning = true;
  35772. if ( useVertexTangents ) cachedMaterial.vertexTangents = true;
  35773. if ( useVertexColors ) cachedMaterial.vertexColors = THREE.VertexColors;
  35774. if ( useFlatShading ) cachedMaterial.flatShading = true;
  35775. if ( useMorphTargets ) cachedMaterial.morphTargets = true;
  35776. if ( useMorphNormals ) cachedMaterial.morphNormals = true;
  35777. this.cache.add( cacheKey, cachedMaterial );
  35778. }
  35779. material = cachedMaterial;
  35780. }
  35781. // workarounds for mesh and geometry
  35782. if ( material.aoMap && geometry.attributes.uv2 === undefined && geometry.attributes.uv !== undefined ) {
  35783. console.log( 'THREE.GLTFLoader: Duplicating UVs to support aoMap.' );
  35784. geometry.addAttribute( 'uv2', new THREE.BufferAttribute( geometry.attributes.uv.array, 2 ) );
  35785. }
  35786. if ( material.isGLTFSpecularGlossinessMaterial ) {
  35787. // for GLTFSpecularGlossinessMaterial(ShaderMaterial) uniforms runtime update
  35788. mesh.onBeforeRender = extensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ].refreshUniforms;
  35789. }
  35790. mesh.material = material;
  35791. };
  35792. /**
  35793. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#materials
  35794. * @param {number} materialIndex
  35795. * @return {Promise<THREE.Material>}
  35796. */
  35797. GLTFParser.prototype.loadMaterial = function ( materialIndex ) {
  35798. var parser = this;
  35799. var json = this.json;
  35800. var extensions = this.extensions;
  35801. var materialDef = json.materials[ materialIndex ];
  35802. var materialType;
  35803. var materialParams = {};
  35804. var materialExtensions = materialDef.extensions || {};
  35805. var pending = [];
  35806. if ( materialExtensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ] ) {
  35807. var sgExtension = extensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ];
  35808. materialType = sgExtension.getMaterialType( materialDef );
  35809. pending.push( sgExtension.extendParams( materialParams, materialDef, parser ) );
  35810. } else if ( materialExtensions[ EXTENSIONS.KHR_MATERIALS_UNLIT ] ) {
  35811. var kmuExtension = extensions[ EXTENSIONS.KHR_MATERIALS_UNLIT ];
  35812. materialType = kmuExtension.getMaterialType( materialDef );
  35813. pending.push( kmuExtension.extendParams( materialParams, materialDef, parser ) );
  35814. } else {
  35815. // Specification:
  35816. // https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#metallic-roughness-material
  35817. materialType = THREE.MeshStandardMaterial;
  35818. var metallicRoughness = materialDef.pbrMetallicRoughness || {};
  35819. materialParams.color = new THREE.Color( 1.0, 1.0, 1.0 );
  35820. materialParams.opacity = 1.0;
  35821. if ( Array.isArray( metallicRoughness.baseColorFactor ) ) {
  35822. var array = metallicRoughness.baseColorFactor;
  35823. materialParams.color.fromArray( array );
  35824. materialParams.opacity = array[ 3 ];
  35825. }
  35826. if ( metallicRoughness.baseColorTexture !== undefined ) {
  35827. pending.push( parser.assignTexture( materialParams, 'map', metallicRoughness.baseColorTexture ) );
  35828. }
  35829. materialParams.metalness = metallicRoughness.metallicFactor !== undefined ? metallicRoughness.metallicFactor : 1.0;
  35830. materialParams.roughness = metallicRoughness.roughnessFactor !== undefined ? metallicRoughness.roughnessFactor : 1.0;
  35831. if ( metallicRoughness.metallicRoughnessTexture !== undefined ) {
  35832. pending.push( parser.assignTexture( materialParams, 'metalnessMap', metallicRoughness.metallicRoughnessTexture ) );
  35833. pending.push( parser.assignTexture( materialParams, 'roughnessMap', metallicRoughness.metallicRoughnessTexture ) );
  35834. }
  35835. }
  35836. if ( materialDef.doubleSided === true ) {
  35837. materialParams.side = THREE.DoubleSide;
  35838. }
  35839. var alphaMode = materialDef.alphaMode || ALPHA_MODES.OPAQUE;
  35840. if ( alphaMode === ALPHA_MODES.BLEND ) {
  35841. materialParams.transparent = true;
  35842. } else {
  35843. materialParams.transparent = false;
  35844. if ( alphaMode === ALPHA_MODES.MASK ) {
  35845. materialParams.alphaTest = materialDef.alphaCutoff !== undefined ? materialDef.alphaCutoff : 0.5;
  35846. }
  35847. }
  35848. if ( materialDef.normalTexture !== undefined && materialType !== THREE.MeshBasicMaterial ) {
  35849. pending.push( parser.assignTexture( materialParams, 'normalMap', materialDef.normalTexture ) );
  35850. materialParams.normalScale = new THREE.Vector2( 1, 1 );
  35851. if ( materialDef.normalTexture.scale !== undefined ) {
  35852. materialParams.normalScale.set( materialDef.normalTexture.scale, materialDef.normalTexture.scale );
  35853. }
  35854. }
  35855. if ( materialDef.occlusionTexture !== undefined && materialType !== THREE.MeshBasicMaterial ) {
  35856. pending.push( parser.assignTexture( materialParams, 'aoMap', materialDef.occlusionTexture ) );
  35857. if ( materialDef.occlusionTexture.strength !== undefined ) {
  35858. materialParams.aoMapIntensity = materialDef.occlusionTexture.strength;
  35859. }
  35860. }
  35861. if ( materialDef.emissiveFactor !== undefined && materialType !== THREE.MeshBasicMaterial ) {
  35862. materialParams.emissive = new THREE.Color().fromArray( materialDef.emissiveFactor );
  35863. }
  35864. if ( materialDef.emissiveTexture !== undefined && materialType !== THREE.MeshBasicMaterial ) {
  35865. pending.push( parser.assignTexture( materialParams, 'emissiveMap', materialDef.emissiveTexture ) );
  35866. }
  35867. return Promise.all( pending ).then( function () {
  35868. var material;
  35869. if ( materialType === THREE.ShaderMaterial ) {
  35870. material = extensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ].createMaterial( materialParams );
  35871. } else {
  35872. material = new materialType( materialParams );
  35873. }
  35874. if ( materialDef.name !== undefined ) material.name = materialDef.name;
  35875. // baseColorTexture, emissiveTexture, and specularGlossinessTexture use sRGB encoding.
  35876. if ( material.map ) material.map.encoding = THREE.sRGBEncoding;
  35877. if ( material.emissiveMap ) material.emissiveMap.encoding = THREE.sRGBEncoding;
  35878. if ( material.specularMap ) material.specularMap.encoding = THREE.sRGBEncoding;
  35879. assignExtrasToUserData( material, materialDef );
  35880. if ( materialDef.extensions ) addUnknownExtensionsToUserData( extensions, material, materialDef );
  35881. return material;
  35882. } );
  35883. };
  35884. /**
  35885. * @param {THREE.BufferGeometry} geometry
  35886. * @param {GLTF.Primitive} primitiveDef
  35887. * @param {GLTFParser} parser
  35888. * @return {Promise<THREE.BufferGeometry>}
  35889. */
  35890. function addPrimitiveAttributes( geometry, primitiveDef, parser ) {
  35891. var attributes = primitiveDef.attributes;
  35892. var pending = [];
  35893. function assignAttributeAccessor( accessorIndex, attributeName ) {
  35894. return parser.getDependency( 'accessor', accessorIndex )
  35895. .then( function ( accessor ) {
  35896. geometry.addAttribute( attributeName, accessor );
  35897. } );
  35898. }
  35899. for ( var gltfAttributeName in attributes ) {
  35900. var threeAttributeName = ATTRIBUTES[ gltfAttributeName ] || gltfAttributeName.toLowerCase();
  35901. // Skip attributes already provided by e.g. Draco extension.
  35902. if ( threeAttributeName in geometry.attributes ) continue;
  35903. pending.push( assignAttributeAccessor( attributes[ gltfAttributeName ], threeAttributeName ) );
  35904. }
  35905. if ( primitiveDef.indices !== undefined && ! geometry.index ) {
  35906. var accessor = parser.getDependency( 'accessor', primitiveDef.indices ).then( function ( accessor ) {
  35907. geometry.setIndex( accessor );
  35908. } );
  35909. pending.push( accessor );
  35910. }
  35911. assignExtrasToUserData( geometry, primitiveDef );
  35912. return Promise.all( pending ).then( function () {
  35913. return primitiveDef.targets !== undefined
  35914. ? addMorphTargets( geometry, primitiveDef.targets, parser )
  35915. : geometry;
  35916. } );
  35917. }
  35918. /**
  35919. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#geometry
  35920. *
  35921. * Creates BufferGeometries from primitives.
  35922. *
  35923. * @param {Array<GLTF.Primitive>} primitives
  35924. * @return {Promise<Array<THREE.BufferGeometry>>}
  35925. */
  35926. GLTFParser.prototype.loadGeometries = function ( primitives ) {
  35927. var parser = this;
  35928. var extensions = this.extensions;
  35929. var cache = this.primitiveCache;
  35930. function createDracoPrimitive( primitive ) {
  35931. return extensions[ EXTENSIONS.KHR_DRACO_MESH_COMPRESSION ]
  35932. .decodePrimitive( primitive, parser )
  35933. .then( function ( geometry ) {
  35934. return addPrimitiveAttributes( geometry, primitive, parser );
  35935. } );
  35936. }
  35937. var pending = [];
  35938. for ( var i = 0, il = primitives.length; i < il; i ++ ) {
  35939. var primitive = primitives[ i ];
  35940. var cacheKey = createPrimitiveKey( primitive );
  35941. // See if we've already created this geometry
  35942. var cached = cache[ cacheKey ];
  35943. if ( cached ) {
  35944. // Use the cached geometry if it exists
  35945. pending.push( cached.promise );
  35946. } else {
  35947. var geometryPromise;
  35948. if ( primitive.extensions && primitive.extensions[ EXTENSIONS.KHR_DRACO_MESH_COMPRESSION ] ) {
  35949. // Use DRACO geometry if available
  35950. geometryPromise = createDracoPrimitive( primitive );
  35951. } else {
  35952. // Otherwise create a new geometry
  35953. geometryPromise = addPrimitiveAttributes( new THREE.BufferGeometry(), primitive, parser );
  35954. }
  35955. // Cache this geometry
  35956. cache[ cacheKey ] = { primitive: primitive, promise: geometryPromise };
  35957. pending.push( geometryPromise );
  35958. }
  35959. }
  35960. return Promise.all( pending );
  35961. };
  35962. /**
  35963. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#meshes
  35964. * @param {number} meshIndex
  35965. * @return {Promise<THREE.Group|THREE.Mesh|THREE.SkinnedMesh>}
  35966. */
  35967. GLTFParser.prototype.loadMesh = function ( meshIndex ) {
  35968. var parser = this;
  35969. var json = this.json;
  35970. var extensions = this.extensions;
  35971. var meshDef = json.meshes[ meshIndex ];
  35972. var primitives = meshDef.primitives;
  35973. var pending = [];
  35974. for ( var i = 0, il = primitives.length; i < il; i ++ ) {
  35975. var material = primitives[ i ].material === undefined
  35976. ? createDefaultMaterial()
  35977. : this.getDependency( 'material', primitives[ i ].material );
  35978. pending.push( material );
  35979. }
  35980. return Promise.all( pending ).then( function ( originalMaterials ) {
  35981. return parser.loadGeometries( primitives ).then( function ( geometries ) {
  35982. var meshes = [];
  35983. for ( var i = 0, il = geometries.length; i < il; i ++ ) {
  35984. var geometry = geometries[ i ];
  35985. var primitive = primitives[ i ];
  35986. // 1. create Mesh
  35987. var mesh;
  35988. var material = originalMaterials[ i ];
  35989. if ( primitive.mode === WEBGL_CONSTANTS.TRIANGLES ||
  35990. primitive.mode === WEBGL_CONSTANTS.TRIANGLE_STRIP ||
  35991. primitive.mode === WEBGL_CONSTANTS.TRIANGLE_FAN ||
  35992. primitive.mode === undefined ) {
  35993. // .isSkinnedMesh isn't in glTF spec. See .markDefs()
  35994. mesh = meshDef.isSkinnedMesh === true
  35995. ? new THREE.SkinnedMesh( geometry, material )
  35996. : new THREE.Mesh( geometry, material );
  35997. if ( mesh.isSkinnedMesh === true ) mesh.normalizeSkinWeights(); // #15319
  35998. if ( primitive.mode === WEBGL_CONSTANTS.TRIANGLE_STRIP ) {
  35999. mesh.drawMode = THREE.TriangleStripDrawMode;
  36000. } else if ( primitive.mode === WEBGL_CONSTANTS.TRIANGLE_FAN ) {
  36001. mesh.drawMode = THREE.TriangleFanDrawMode;
  36002. }
  36003. } else if ( primitive.mode === WEBGL_CONSTANTS.LINES ) {
  36004. mesh = new THREE.LineSegments( geometry, material );
  36005. } else if ( primitive.mode === WEBGL_CONSTANTS.LINE_STRIP ) {
  36006. mesh = new THREE.Line( geometry, material );
  36007. } else if ( primitive.mode === WEBGL_CONSTANTS.LINE_LOOP ) {
  36008. mesh = new THREE.LineLoop( geometry, material );
  36009. } else if ( primitive.mode === WEBGL_CONSTANTS.POINTS ) {
  36010. mesh = new THREE.Points( geometry, material );
  36011. } else {
  36012. throw new Error( 'THREE.GLTFLoader: Primitive mode unsupported: ' + primitive.mode );
  36013. }
  36014. if ( Object.keys( mesh.geometry.morphAttributes ).length > 0 ) {
  36015. updateMorphTargets( mesh, meshDef );
  36016. }
  36017. mesh.name = meshDef.name || ( 'mesh_' + meshIndex );
  36018. if ( geometries.length > 1 ) mesh.name += '_' + i;
  36019. assignExtrasToUserData( mesh, meshDef );
  36020. parser.assignFinalMaterial( mesh );
  36021. meshes.push( mesh );
  36022. }
  36023. if ( meshes.length === 1 ) {
  36024. return meshes[ 0 ];
  36025. }
  36026. var group = new THREE.Group();
  36027. for ( var i = 0, il = meshes.length; i < il; i ++ ) {
  36028. group.add( meshes[ i ] );
  36029. }
  36030. return group;
  36031. } );
  36032. } );
  36033. };
  36034. /**
  36035. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#cameras
  36036. * @param {number} cameraIndex
  36037. * @return {Promise<THREE.Camera>}
  36038. */
  36039. GLTFParser.prototype.loadCamera = function ( cameraIndex ) {
  36040. var camera;
  36041. var cameraDef = this.json.cameras[ cameraIndex ];
  36042. var params = cameraDef[ cameraDef.type ];
  36043. if ( ! params ) {
  36044. console.warn( 'THREE.GLTFLoader: Missing camera parameters.' );
  36045. return;
  36046. }
  36047. if ( cameraDef.type === 'perspective' ) {
  36048. camera = new THREE.PerspectiveCamera( THREE.Math.radToDeg( params.yfov ), params.aspectRatio || 1, params.znear || 1, params.zfar || 2e6 );
  36049. } else if ( cameraDef.type === 'orthographic' ) {
  36050. camera = new THREE.OrthographicCamera( params.xmag / - 2, params.xmag / 2, params.ymag / 2, params.ymag / - 2, params.znear, params.zfar );
  36051. }
  36052. if ( cameraDef.name !== undefined ) camera.name = cameraDef.name;
  36053. assignExtrasToUserData( camera, cameraDef );
  36054. return Promise.resolve( camera );
  36055. };
  36056. /**
  36057. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins
  36058. * @param {number} skinIndex
  36059. * @return {Promise<Object>}
  36060. */
  36061. GLTFParser.prototype.loadSkin = function ( skinIndex ) {
  36062. var skinDef = this.json.skins[ skinIndex ];
  36063. var skinEntry = { joints: skinDef.joints };
  36064. if ( skinDef.inverseBindMatrices === undefined ) {
  36065. return Promise.resolve( skinEntry );
  36066. }
  36067. return this.getDependency( 'accessor', skinDef.inverseBindMatrices ).then( function ( accessor ) {
  36068. skinEntry.inverseBindMatrices = accessor;
  36069. return skinEntry;
  36070. } );
  36071. };
  36072. /**
  36073. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#animations
  36074. * @param {number} animationIndex
  36075. * @return {Promise<THREE.AnimationClip>}
  36076. */
  36077. GLTFParser.prototype.loadAnimation = function ( animationIndex ) {
  36078. var json = this.json;
  36079. var animationDef = json.animations[ animationIndex ];
  36080. var pendingNodes = [];
  36081. var pendingInputAccessors = [];
  36082. var pendingOutputAccessors = [];
  36083. var pendingSamplers = [];
  36084. var pendingTargets = [];
  36085. for ( var i = 0, il = animationDef.channels.length; i < il; i ++ ) {
  36086. var channel = animationDef.channels[ i ];
  36087. var sampler = animationDef.samplers[ channel.sampler ];
  36088. var target = channel.target;
  36089. var name = target.node !== undefined ? target.node : target.id; // NOTE: target.id is deprecated.
  36090. var input = animationDef.parameters !== undefined ? animationDef.parameters[ sampler.input ] : sampler.input;
  36091. var output = animationDef.parameters !== undefined ? animationDef.parameters[ sampler.output ] : sampler.output;
  36092. pendingNodes.push( this.getDependency( 'node', name ) );
  36093. pendingInputAccessors.push( this.getDependency( 'accessor', input ) );
  36094. pendingOutputAccessors.push( this.getDependency( 'accessor', output ) );
  36095. pendingSamplers.push( sampler );
  36096. pendingTargets.push( target );
  36097. }
  36098. return Promise.all( [
  36099. Promise.all( pendingNodes ),
  36100. Promise.all( pendingInputAccessors ),
  36101. Promise.all( pendingOutputAccessors ),
  36102. Promise.all( pendingSamplers ),
  36103. Promise.all( pendingTargets )
  36104. ] ).then( function ( dependencies ) {
  36105. var nodes = dependencies[ 0 ];
  36106. var inputAccessors = dependencies[ 1 ];
  36107. var outputAccessors = dependencies[ 2 ];
  36108. var samplers = dependencies[ 3 ];
  36109. var targets = dependencies[ 4 ];
  36110. var tracks = [];
  36111. for ( var i = 0, il = nodes.length; i < il; i ++ ) {
  36112. var node = nodes[ i ];
  36113. var inputAccessor = inputAccessors[ i ];
  36114. var outputAccessor = outputAccessors[ i ];
  36115. var sampler = samplers[ i ];
  36116. var target = targets[ i ];
  36117. if ( node === undefined ) continue;
  36118. node.updateMatrix();
  36119. node.matrixAutoUpdate = true;
  36120. var TypedKeyframeTrack;
  36121. switch ( PATH_PROPERTIES[ target.path ] ) {
  36122. case PATH_PROPERTIES.weights:
  36123. TypedKeyframeTrack = THREE.NumberKeyframeTrack;
  36124. break;
  36125. case PATH_PROPERTIES.rotation:
  36126. TypedKeyframeTrack = THREE.QuaternionKeyframeTrack;
  36127. break;
  36128. case PATH_PROPERTIES.position:
  36129. case PATH_PROPERTIES.scale:
  36130. default:
  36131. TypedKeyframeTrack = THREE.VectorKeyframeTrack;
  36132. break;
  36133. }
  36134. var targetName = node.name ? node.name : node.uuid;
  36135. var interpolation = sampler.interpolation !== undefined ? INTERPOLATION[ sampler.interpolation ] : THREE.InterpolateLinear;
  36136. var targetNames = [];
  36137. if ( PATH_PROPERTIES[ target.path ] === PATH_PROPERTIES.weights ) {
  36138. // Node may be a THREE.Group (glTF mesh with several primitives) or a THREE.Mesh.
  36139. node.traverse( function ( object ) {
  36140. if ( object.isMesh === true && object.morphTargetInfluences ) {
  36141. targetNames.push( object.name ? object.name : object.uuid );
  36142. }
  36143. } );
  36144. } else {
  36145. targetNames.push( targetName );
  36146. }
  36147. for ( var j = 0, jl = targetNames.length; j < jl; j ++ ) {
  36148. var track = new TypedKeyframeTrack(
  36149. targetNames[ j ] + '.' + PATH_PROPERTIES[ target.path ],
  36150. inputAccessor.array,
  36151. outputAccessor.array,
  36152. interpolation
  36153. );
  36154. // Override interpolation with custom factory method.
  36155. if ( sampler.interpolation === 'CUBICSPLINE' ) {
  36156. track.createInterpolant = function InterpolantFactoryMethodGLTFCubicSpline( result ) {
  36157. // A CUBICSPLINE keyframe in glTF has three output values for each input value,
  36158. // representing inTangent, splineVertex, and outTangent. As a result, track.getValueSize()
  36159. // must be divided by three to get the interpolant's sampleSize argument.
  36160. return new GLTFCubicSplineInterpolant( this.times, this.values, this.getValueSize() / 3, result );
  36161. };
  36162. // Mark as CUBICSPLINE. `track.getInterpolation()` doesn't support custom interpolants.
  36163. track.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline = true;
  36164. }
  36165. tracks.push( track );
  36166. }
  36167. }
  36168. var name = animationDef.name !== undefined ? animationDef.name : 'animation_' + animationIndex;
  36169. return new THREE.AnimationClip( name, undefined, tracks );
  36170. } );
  36171. };
  36172. /**
  36173. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#nodes-and-hierarchy
  36174. * @param {number} nodeIndex
  36175. * @return {Promise<THREE.Object3D>}
  36176. */
  36177. GLTFParser.prototype.loadNode = function ( nodeIndex ) {
  36178. var json = this.json;
  36179. var extensions = this.extensions;
  36180. var parser = this;
  36181. var meshReferences = json.meshReferences;
  36182. var meshUses = json.meshUses;
  36183. var nodeDef = json.nodes[ nodeIndex ];
  36184. return ( function () {
  36185. // .isBone isn't in glTF spec. See .markDefs
  36186. if ( nodeDef.isBone === true ) {
  36187. return Promise.resolve( new THREE.Bone() );
  36188. } else if ( nodeDef.mesh !== undefined ) {
  36189. return parser.getDependency( 'mesh', nodeDef.mesh ).then( function ( mesh ) {
  36190. var node;
  36191. if ( meshReferences[ nodeDef.mesh ] > 1 ) {
  36192. var instanceNum = meshUses[ nodeDef.mesh ] ++;
  36193. node = mesh.clone();
  36194. node.name += '_instance_' + instanceNum;
  36195. // onBeforeRender copy for Specular-Glossiness
  36196. node.onBeforeRender = mesh.onBeforeRender;
  36197. for ( var i = 0, il = node.children.length; i < il; i ++ ) {
  36198. node.children[ i ].name += '_instance_' + instanceNum;
  36199. node.children[ i ].onBeforeRender = mesh.children[ i ].onBeforeRender;
  36200. }
  36201. } else {
  36202. node = mesh;
  36203. }
  36204. // if weights are provided on the node, override weights on the mesh.
  36205. if ( nodeDef.weights !== undefined ) {
  36206. node.traverse( function ( o ) {
  36207. if ( ! o.isMesh ) return;
  36208. for ( var i = 0, il = nodeDef.weights.length; i < il; i ++ ) {
  36209. o.morphTargetInfluences[ i ] = nodeDef.weights[ i ];
  36210. }
  36211. } );
  36212. }
  36213. return node;
  36214. } );
  36215. } else if ( nodeDef.camera !== undefined ) {
  36216. return parser.getDependency( 'camera', nodeDef.camera );
  36217. } else if ( nodeDef.extensions
  36218. && nodeDef.extensions[ EXTENSIONS.KHR_LIGHTS_PUNCTUAL ]
  36219. && nodeDef.extensions[ EXTENSIONS.KHR_LIGHTS_PUNCTUAL ].light !== undefined ) {
  36220. return parser.getDependency( 'light', nodeDef.extensions[ EXTENSIONS.KHR_LIGHTS_PUNCTUAL ].light );
  36221. } else {
  36222. return Promise.resolve( new THREE.Object3D() );
  36223. }
  36224. }() ).then( function ( node ) {
  36225. if ( nodeDef.name !== undefined ) {
  36226. node.name = THREE.PropertyBinding.sanitizeNodeName( nodeDef.name );
  36227. }
  36228. assignExtrasToUserData( node, nodeDef );
  36229. if ( nodeDef.extensions ) addUnknownExtensionsToUserData( extensions, node, nodeDef );
  36230. if ( nodeDef.matrix !== undefined ) {
  36231. var matrix = new THREE.Matrix4();
  36232. matrix.fromArray( nodeDef.matrix );
  36233. node.applyMatrix( matrix );
  36234. } else {
  36235. if ( nodeDef.translation !== undefined ) {
  36236. node.position.fromArray( nodeDef.translation );
  36237. }
  36238. if ( nodeDef.rotation !== undefined ) {
  36239. node.quaternion.fromArray( nodeDef.rotation );
  36240. }
  36241. if ( nodeDef.scale !== undefined ) {
  36242. node.scale.fromArray( nodeDef.scale );
  36243. }
  36244. }
  36245. return node;
  36246. } );
  36247. };
  36248. /**
  36249. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#scenes
  36250. * @param {number} sceneIndex
  36251. * @return {Promise<THREE.Scene>}
  36252. */
  36253. GLTFParser.prototype.loadScene = function () {
  36254. // scene node hierachy builder
  36255. function buildNodeHierachy( nodeId, parentObject, json, parser ) {
  36256. var nodeDef = json.nodes[ nodeId ];
  36257. return parser.getDependency( 'node', nodeId ).then( function ( node ) {
  36258. if ( nodeDef.skin === undefined ) return node;
  36259. // build skeleton here as well
  36260. var skinEntry;
  36261. return parser.getDependency( 'skin', nodeDef.skin ).then( function ( skin ) {
  36262. skinEntry = skin;
  36263. var pendingJoints = [];
  36264. for ( var i = 0, il = skinEntry.joints.length; i < il; i ++ ) {
  36265. pendingJoints.push( parser.getDependency( 'node', skinEntry.joints[ i ] ) );
  36266. }
  36267. return Promise.all( pendingJoints );
  36268. } ).then( function ( jointNodes ) {
  36269. var meshes = node.isGroup === true ? node.children : [ node ];
  36270. for ( var i = 0, il = meshes.length; i < il; i ++ ) {
  36271. var mesh = meshes[ i ];
  36272. var bones = [];
  36273. var boneInverses = [];
  36274. for ( var j = 0, jl = jointNodes.length; j < jl; j ++ ) {
  36275. var jointNode = jointNodes[ j ];
  36276. if ( jointNode ) {
  36277. bones.push( jointNode );
  36278. var mat = new THREE.Matrix4();
  36279. if ( skinEntry.inverseBindMatrices !== undefined ) {
  36280. mat.fromArray( skinEntry.inverseBindMatrices.array, j * 16 );
  36281. }
  36282. boneInverses.push( mat );
  36283. } else {
  36284. console.warn( 'THREE.GLTFLoader: Joint "%s" could not be found.', skinEntry.joints[ j ] );
  36285. }
  36286. }
  36287. mesh.bind( new THREE.Skeleton( bones, boneInverses ), mesh.matrixWorld );
  36288. }
  36289. return node;
  36290. } );
  36291. } ).then( function ( node ) {
  36292. // build node hierachy
  36293. parentObject.add( node );
  36294. var pending = [];
  36295. if ( nodeDef.children ) {
  36296. var children = nodeDef.children;
  36297. for ( var i = 0, il = children.length; i < il; i ++ ) {
  36298. var child = children[ i ];
  36299. pending.push( buildNodeHierachy( child, node, json, parser ) );
  36300. }
  36301. }
  36302. return Promise.all( pending );
  36303. } );
  36304. }
  36305. return function loadScene( sceneIndex ) {
  36306. var json = this.json;
  36307. var extensions = this.extensions;
  36308. var sceneDef = this.json.scenes[ sceneIndex ];
  36309. var parser = this;
  36310. var scene = new THREE.Scene();
  36311. if ( sceneDef.name !== undefined ) scene.name = sceneDef.name;
  36312. assignExtrasToUserData( scene, sceneDef );
  36313. if ( sceneDef.extensions ) addUnknownExtensionsToUserData( extensions, scene, sceneDef );
  36314. var nodeIds = sceneDef.nodes || [];
  36315. var pending = [];
  36316. for ( var i = 0, il = nodeIds.length; i < il; i ++ ) {
  36317. pending.push( buildNodeHierachy( nodeIds[ i ], scene, json, parser ) );
  36318. }
  36319. return Promise.all( pending ).then( function () {
  36320. return scene;
  36321. } );
  36322. };
  36323. }();
  36324. return GLTFLoader;
  36325. } )();
  36326. },{}],39:[function(_dereq_,module,exports){
  36327. /**
  36328. * Loads a Wavefront .mtl file specifying materials
  36329. *
  36330. * @author angelxuanchang
  36331. */
  36332. THREE.MTLLoader = function ( manager ) {
  36333. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  36334. };
  36335. THREE.MTLLoader.prototype = {
  36336. constructor: THREE.MTLLoader,
  36337. /**
  36338. * Loads and parses a MTL asset from a URL.
  36339. *
  36340. * @param {String} url - URL to the MTL file.
  36341. * @param {Function} [onLoad] - Callback invoked with the loaded object.
  36342. * @param {Function} [onProgress] - Callback for download progress.
  36343. * @param {Function} [onError] - Callback for download errors.
  36344. *
  36345. * @see setPath setResourcePath
  36346. *
  36347. * @note In order for relative texture references to resolve correctly
  36348. * you must call setResourcePath() explicitly prior to load.
  36349. */
  36350. load: function ( url, onLoad, onProgress, onError ) {
  36351. var scope = this;
  36352. var path = ( this.path === undefined ) ? THREE.LoaderUtils.extractUrlBase( url ) : this.path;
  36353. var loader = new THREE.FileLoader( this.manager );
  36354. loader.setPath( this.path );
  36355. loader.load( url, function ( text ) {
  36356. onLoad( scope.parse( text, path ) );
  36357. }, onProgress, onError );
  36358. },
  36359. /**
  36360. * Set base path for resolving references.
  36361. * If set this path will be prepended to each loaded and found reference.
  36362. *
  36363. * @see setResourcePath
  36364. * @param {String} path
  36365. * @return {THREE.MTLLoader}
  36366. *
  36367. * @example
  36368. * mtlLoader.setPath( 'assets/obj/' );
  36369. * mtlLoader.load( 'my.mtl', ... );
  36370. */
  36371. setPath: function ( path ) {
  36372. this.path = path;
  36373. return this;
  36374. },
  36375. /**
  36376. * Set base path for additional resources like textures.
  36377. *
  36378. * @see setPath
  36379. * @param {String} path
  36380. * @return {THREE.MTLLoader}
  36381. *
  36382. * @example
  36383. * mtlLoader.setPath( 'assets/obj/' );
  36384. * mtlLoader.setResourcePath( 'assets/textures/' );
  36385. * mtlLoader.load( 'my.mtl', ... );
  36386. */
  36387. setResourcePath: function ( path ) {
  36388. this.resourcePath = path;
  36389. return this;
  36390. },
  36391. setTexturePath: function ( path ) {
  36392. console.warn( 'THREE.MTLLoader: .setTexturePath() has been renamed to .setResourcePath().' );
  36393. return this.setResourcePath( path );
  36394. },
  36395. setCrossOrigin: function ( value ) {
  36396. this.crossOrigin = value;
  36397. return this;
  36398. },
  36399. setMaterialOptions: function ( value ) {
  36400. this.materialOptions = value;
  36401. return this;
  36402. },
  36403. /**
  36404. * Parses a MTL file.
  36405. *
  36406. * @param {String} text - Content of MTL file
  36407. * @return {THREE.MTLLoader.MaterialCreator}
  36408. *
  36409. * @see setPath setResourcePath
  36410. *
  36411. * @note In order for relative texture references to resolve correctly
  36412. * you must call setResourcePath() explicitly prior to parse.
  36413. */
  36414. parse: function ( text, path ) {
  36415. var lines = text.split( '\n' );
  36416. var info = {};
  36417. var delimiter_pattern = /\s+/;
  36418. var materialsInfo = {};
  36419. for ( var i = 0; i < lines.length; i ++ ) {
  36420. var line = lines[ i ];
  36421. line = line.trim();
  36422. if ( line.length === 0 || line.charAt( 0 ) === '#' ) {
  36423. // Blank line or comment ignore
  36424. continue;
  36425. }
  36426. var pos = line.indexOf( ' ' );
  36427. var key = ( pos >= 0 ) ? line.substring( 0, pos ) : line;
  36428. key = key.toLowerCase();
  36429. var value = ( pos >= 0 ) ? line.substring( pos + 1 ) : '';
  36430. value = value.trim();
  36431. if ( key === 'newmtl' ) {
  36432. // New material
  36433. info = { name: value };
  36434. materialsInfo[ value ] = info;
  36435. } else {
  36436. if ( key === 'ka' || key === 'kd' || key === 'ks' || key ==='ke' ) {
  36437. var ss = value.split( delimiter_pattern, 3 );
  36438. info[ key ] = [ parseFloat( ss[ 0 ] ), parseFloat( ss[ 1 ] ), parseFloat( ss[ 2 ] ) ];
  36439. } else {
  36440. info[ key ] = value;
  36441. }
  36442. }
  36443. }
  36444. var materialCreator = new THREE.MTLLoader.MaterialCreator( this.resourcePath || path, this.materialOptions );
  36445. materialCreator.setCrossOrigin( this.crossOrigin );
  36446. materialCreator.setManager( this.manager );
  36447. materialCreator.setMaterials( materialsInfo );
  36448. return materialCreator;
  36449. }
  36450. };
  36451. /**
  36452. * Create a new THREE-MTLLoader.MaterialCreator
  36453. * @param baseUrl - Url relative to which textures are loaded
  36454. * @param options - Set of options on how to construct the materials
  36455. * side: Which side to apply the material
  36456. * THREE.FrontSide (default), THREE.BackSide, THREE.DoubleSide
  36457. * wrap: What type of wrapping to apply for textures
  36458. * THREE.RepeatWrapping (default), THREE.ClampToEdgeWrapping, THREE.MirroredRepeatWrapping
  36459. * normalizeRGB: RGBs need to be normalized to 0-1 from 0-255
  36460. * Default: false, assumed to be already normalized
  36461. * ignoreZeroRGBs: Ignore values of RGBs (Ka,Kd,Ks) that are all 0's
  36462. * Default: false
  36463. * @constructor
  36464. */
  36465. THREE.MTLLoader.MaterialCreator = function ( baseUrl, options ) {
  36466. this.baseUrl = baseUrl || '';
  36467. this.options = options;
  36468. this.materialsInfo = {};
  36469. this.materials = {};
  36470. this.materialsArray = [];
  36471. this.nameLookup = {};
  36472. this.side = ( this.options && this.options.side ) ? this.options.side : THREE.FrontSide;
  36473. this.wrap = ( this.options && this.options.wrap ) ? this.options.wrap : THREE.RepeatWrapping;
  36474. };
  36475. THREE.MTLLoader.MaterialCreator.prototype = {
  36476. constructor: THREE.MTLLoader.MaterialCreator,
  36477. crossOrigin: 'anonymous',
  36478. setCrossOrigin: function ( value ) {
  36479. this.crossOrigin = value;
  36480. return this;
  36481. },
  36482. setManager: function ( value ) {
  36483. this.manager = value;
  36484. },
  36485. setMaterials: function ( materialsInfo ) {
  36486. this.materialsInfo = this.convert( materialsInfo );
  36487. this.materials = {};
  36488. this.materialsArray = [];
  36489. this.nameLookup = {};
  36490. },
  36491. convert: function ( materialsInfo ) {
  36492. if ( ! this.options ) return materialsInfo;
  36493. var converted = {};
  36494. for ( var mn in materialsInfo ) {
  36495. // Convert materials info into normalized form based on options
  36496. var mat = materialsInfo[ mn ];
  36497. var covmat = {};
  36498. converted[ mn ] = covmat;
  36499. for ( var prop in mat ) {
  36500. var save = true;
  36501. var value = mat[ prop ];
  36502. var lprop = prop.toLowerCase();
  36503. switch ( lprop ) {
  36504. case 'kd':
  36505. case 'ka':
  36506. case 'ks':
  36507. // Diffuse color (color under white light) using RGB values
  36508. if ( this.options && this.options.normalizeRGB ) {
  36509. value = [ value[ 0 ] / 255, value[ 1 ] / 255, value[ 2 ] / 255 ];
  36510. }
  36511. if ( this.options && this.options.ignoreZeroRGBs ) {
  36512. if ( value[ 0 ] === 0 && value[ 1 ] === 0 && value[ 2 ] === 0 ) {
  36513. // ignore
  36514. save = false;
  36515. }
  36516. }
  36517. break;
  36518. default:
  36519. break;
  36520. }
  36521. if ( save ) {
  36522. covmat[ lprop ] = value;
  36523. }
  36524. }
  36525. }
  36526. return converted;
  36527. },
  36528. preload: function () {
  36529. for ( var mn in this.materialsInfo ) {
  36530. this.create( mn );
  36531. }
  36532. },
  36533. getIndex: function ( materialName ) {
  36534. return this.nameLookup[ materialName ];
  36535. },
  36536. getAsArray: function () {
  36537. var index = 0;
  36538. for ( var mn in this.materialsInfo ) {
  36539. this.materialsArray[ index ] = this.create( mn );
  36540. this.nameLookup[ mn ] = index;
  36541. index ++;
  36542. }
  36543. return this.materialsArray;
  36544. },
  36545. create: function ( materialName ) {
  36546. if ( this.materials[ materialName ] === undefined ) {
  36547. this.createMaterial_( materialName );
  36548. }
  36549. return this.materials[ materialName ];
  36550. },
  36551. createMaterial_: function ( materialName ) {
  36552. // Create material
  36553. var scope = this;
  36554. var mat = this.materialsInfo[ materialName ];
  36555. var params = {
  36556. name: materialName,
  36557. side: this.side
  36558. };
  36559. function resolveURL( baseUrl, url ) {
  36560. if ( typeof url !== 'string' || url === '' )
  36561. return '';
  36562. // Absolute URL
  36563. if ( /^https?:\/\//i.test( url ) ) return url;
  36564. return baseUrl + url;
  36565. }
  36566. function setMapForType( mapType, value ) {
  36567. if ( params[ mapType ] ) return; // Keep the first encountered texture
  36568. var texParams = scope.getTextureParams( value, params );
  36569. var map = scope.loadTexture( resolveURL( scope.baseUrl, texParams.url ) );
  36570. map.repeat.copy( texParams.scale );
  36571. map.offset.copy( texParams.offset );
  36572. map.wrapS = scope.wrap;
  36573. map.wrapT = scope.wrap;
  36574. params[ mapType ] = map;
  36575. }
  36576. for ( var prop in mat ) {
  36577. var value = mat[ prop ];
  36578. var n;
  36579. if ( value === '' ) continue;
  36580. switch ( prop.toLowerCase() ) {
  36581. // Ns is material specular exponent
  36582. case 'kd':
  36583. // Diffuse color (color under white light) using RGB values
  36584. params.color = new THREE.Color().fromArray( value );
  36585. break;
  36586. case 'ks':
  36587. // Specular color (color when light is reflected from shiny surface) using RGB values
  36588. params.specular = new THREE.Color().fromArray( value );
  36589. break;
  36590. case 'ke':
  36591. // Emissive using RGB values
  36592. params.emissive = new THREE.Color().fromArray( value );
  36593. break;
  36594. case 'map_kd':
  36595. // Diffuse texture map
  36596. setMapForType( "map", value );
  36597. break;
  36598. case 'map_ks':
  36599. // Specular map
  36600. setMapForType( "specularMap", value );
  36601. break;
  36602. case 'map_ke':
  36603. // Emissive map
  36604. setMapForType( "emissiveMap", value );
  36605. break;
  36606. case 'norm':
  36607. setMapForType( "normalMap", value );
  36608. break;
  36609. case 'map_bump':
  36610. case 'bump':
  36611. // Bump texture map
  36612. setMapForType( "bumpMap", value );
  36613. break;
  36614. case 'map_d':
  36615. // Alpha map
  36616. setMapForType( "alphaMap", value );
  36617. params.transparent = true;
  36618. break;
  36619. case 'ns':
  36620. // The specular exponent (defines the focus of the specular highlight)
  36621. // A high exponent results in a tight, concentrated highlight. Ns values normally range from 0 to 1000.
  36622. params.shininess = parseFloat( value );
  36623. break;
  36624. case 'd':
  36625. n = parseFloat( value );
  36626. if ( n < 1 ) {
  36627. params.opacity = n;
  36628. params.transparent = true;
  36629. }
  36630. break;
  36631. case 'tr':
  36632. n = parseFloat( value );
  36633. if ( this.options && this.options.invertTrProperty ) n = 1 - n;
  36634. if ( n > 0 ) {
  36635. params.opacity = 1 - n;
  36636. params.transparent = true;
  36637. }
  36638. break;
  36639. default:
  36640. break;
  36641. }
  36642. }
  36643. this.materials[ materialName ] = new THREE.MeshPhongMaterial( params );
  36644. return this.materials[ materialName ];
  36645. },
  36646. getTextureParams: function ( value, matParams ) {
  36647. var texParams = {
  36648. scale: new THREE.Vector2( 1, 1 ),
  36649. offset: new THREE.Vector2( 0, 0 )
  36650. };
  36651. var items = value.split( /\s+/ );
  36652. var pos;
  36653. pos = items.indexOf( '-bm' );
  36654. if ( pos >= 0 ) {
  36655. matParams.bumpScale = parseFloat( items[ pos + 1 ] );
  36656. items.splice( pos, 2 );
  36657. }
  36658. pos = items.indexOf( '-s' );
  36659. if ( pos >= 0 ) {
  36660. texParams.scale.set( parseFloat( items[ pos + 1 ] ), parseFloat( items[ pos + 2 ] ) );
  36661. items.splice( pos, 4 ); // we expect 3 parameters here!
  36662. }
  36663. pos = items.indexOf( '-o' );
  36664. if ( pos >= 0 ) {
  36665. texParams.offset.set( parseFloat( items[ pos + 1 ] ), parseFloat( items[ pos + 2 ] ) );
  36666. items.splice( pos, 4 ); // we expect 3 parameters here!
  36667. }
  36668. texParams.url = items.join( ' ' ).trim();
  36669. return texParams;
  36670. },
  36671. loadTexture: function ( url, mapping, onLoad, onProgress, onError ) {
  36672. var texture;
  36673. var loader = THREE.Loader.Handlers.get( url );
  36674. var manager = ( this.manager !== undefined ) ? this.manager : THREE.DefaultLoadingManager;
  36675. if ( loader === null ) {
  36676. loader = new THREE.TextureLoader( manager );
  36677. }
  36678. if ( loader.setCrossOrigin ) loader.setCrossOrigin( this.crossOrigin );
  36679. texture = loader.load( url, onLoad, onProgress, onError );
  36680. if ( mapping !== undefined ) texture.mapping = mapping;
  36681. return texture;
  36682. }
  36683. };
  36684. },{}],40:[function(_dereq_,module,exports){
  36685. /**
  36686. * @author mrdoob / http://mrdoob.com/
  36687. */
  36688. THREE.OBJLoader = ( function () {
  36689. // o object_name | g group_name
  36690. var object_pattern = /^[og]\s*(.+)?/;
  36691. // mtllib file_reference
  36692. var material_library_pattern = /^mtllib /;
  36693. // usemtl material_name
  36694. var material_use_pattern = /^usemtl /;
  36695. function ParserState() {
  36696. var state = {
  36697. objects: [],
  36698. object: {},
  36699. vertices: [],
  36700. normals: [],
  36701. colors: [],
  36702. uvs: [],
  36703. materialLibraries: [],
  36704. startObject: function ( name, fromDeclaration ) {
  36705. // If the current object (initial from reset) is not from a g/o declaration in the parsed
  36706. // file. We need to use it for the first parsed g/o to keep things in sync.
  36707. if ( this.object && this.object.fromDeclaration === false ) {
  36708. this.object.name = name;
  36709. this.object.fromDeclaration = ( fromDeclaration !== false );
  36710. return;
  36711. }
  36712. var previousMaterial = ( this.object && typeof this.object.currentMaterial === 'function' ? this.object.currentMaterial() : undefined );
  36713. if ( this.object && typeof this.object._finalize === 'function' ) {
  36714. this.object._finalize( true );
  36715. }
  36716. this.object = {
  36717. name: name || '',
  36718. fromDeclaration: ( fromDeclaration !== false ),
  36719. geometry: {
  36720. vertices: [],
  36721. normals: [],
  36722. colors: [],
  36723. uvs: []
  36724. },
  36725. materials: [],
  36726. smooth: true,
  36727. startMaterial: function ( name, libraries ) {
  36728. var previous = this._finalize( false );
  36729. // New usemtl declaration overwrites an inherited material, except if faces were declared
  36730. // after the material, then it must be preserved for proper MultiMaterial continuation.
  36731. if ( previous && ( previous.inherited || previous.groupCount <= 0 ) ) {
  36732. this.materials.splice( previous.index, 1 );
  36733. }
  36734. var material = {
  36735. index: this.materials.length,
  36736. name: name || '',
  36737. mtllib: ( Array.isArray( libraries ) && libraries.length > 0 ? libraries[ libraries.length - 1 ] : '' ),
  36738. smooth: ( previous !== undefined ? previous.smooth : this.smooth ),
  36739. groupStart: ( previous !== undefined ? previous.groupEnd : 0 ),
  36740. groupEnd: - 1,
  36741. groupCount: - 1,
  36742. inherited: false,
  36743. clone: function ( index ) {
  36744. var cloned = {
  36745. index: ( typeof index === 'number' ? index : this.index ),
  36746. name: this.name,
  36747. mtllib: this.mtllib,
  36748. smooth: this.smooth,
  36749. groupStart: 0,
  36750. groupEnd: - 1,
  36751. groupCount: - 1,
  36752. inherited: false
  36753. };
  36754. cloned.clone = this.clone.bind( cloned );
  36755. return cloned;
  36756. }
  36757. };
  36758. this.materials.push( material );
  36759. return material;
  36760. },
  36761. currentMaterial: function () {
  36762. if ( this.materials.length > 0 ) {
  36763. return this.materials[ this.materials.length - 1 ];
  36764. }
  36765. return undefined;
  36766. },
  36767. _finalize: function ( end ) {
  36768. var lastMultiMaterial = this.currentMaterial();
  36769. if ( lastMultiMaterial && lastMultiMaterial.groupEnd === - 1 ) {
  36770. lastMultiMaterial.groupEnd = this.geometry.vertices.length / 3;
  36771. lastMultiMaterial.groupCount = lastMultiMaterial.groupEnd - lastMultiMaterial.groupStart;
  36772. lastMultiMaterial.inherited = false;
  36773. }
  36774. // Ignore objects tail materials if no face declarations followed them before a new o/g started.
  36775. if ( end && this.materials.length > 1 ) {
  36776. for ( var mi = this.materials.length - 1; mi >= 0; mi -- ) {
  36777. if ( this.materials[ mi ].groupCount <= 0 ) {
  36778. this.materials.splice( mi, 1 );
  36779. }
  36780. }
  36781. }
  36782. // Guarantee at least one empty material, this makes the creation later more straight forward.
  36783. if ( end && this.materials.length === 0 ) {
  36784. this.materials.push( {
  36785. name: '',
  36786. smooth: this.smooth
  36787. } );
  36788. }
  36789. return lastMultiMaterial;
  36790. }
  36791. };
  36792. // Inherit previous objects material.
  36793. // Spec tells us that a declared material must be set to all objects until a new material is declared.
  36794. // If a usemtl declaration is encountered while this new object is being parsed, it will
  36795. // overwrite the inherited material. Exception being that there was already face declarations
  36796. // to the inherited material, then it will be preserved for proper MultiMaterial continuation.
  36797. if ( previousMaterial && previousMaterial.name && typeof previousMaterial.clone === 'function' ) {
  36798. var declared = previousMaterial.clone( 0 );
  36799. declared.inherited = true;
  36800. this.object.materials.push( declared );
  36801. }
  36802. this.objects.push( this.object );
  36803. },
  36804. finalize: function () {
  36805. if ( this.object && typeof this.object._finalize === 'function' ) {
  36806. this.object._finalize( true );
  36807. }
  36808. },
  36809. parseVertexIndex: function ( value, len ) {
  36810. var index = parseInt( value, 10 );
  36811. return ( index >= 0 ? index - 1 : index + len / 3 ) * 3;
  36812. },
  36813. parseNormalIndex: function ( value, len ) {
  36814. var index = parseInt( value, 10 );
  36815. return ( index >= 0 ? index - 1 : index + len / 3 ) * 3;
  36816. },
  36817. parseUVIndex: function ( value, len ) {
  36818. var index = parseInt( value, 10 );
  36819. return ( index >= 0 ? index - 1 : index + len / 2 ) * 2;
  36820. },
  36821. addVertex: function ( a, b, c ) {
  36822. var src = this.vertices;
  36823. var dst = this.object.geometry.vertices;
  36824. dst.push( src[ a + 0 ], src[ a + 1 ], src[ a + 2 ] );
  36825. dst.push( src[ b + 0 ], src[ b + 1 ], src[ b + 2 ] );
  36826. dst.push( src[ c + 0 ], src[ c + 1 ], src[ c + 2 ] );
  36827. },
  36828. addVertexPoint: function ( a ) {
  36829. var src = this.vertices;
  36830. var dst = this.object.geometry.vertices;
  36831. dst.push( src[ a + 0 ], src[ a + 1 ], src[ a + 2 ] );
  36832. },
  36833. addVertexLine: function ( a ) {
  36834. var src = this.vertices;
  36835. var dst = this.object.geometry.vertices;
  36836. dst.push( src[ a + 0 ], src[ a + 1 ], src[ a + 2 ] );
  36837. },
  36838. addNormal: function ( a, b, c ) {
  36839. var src = this.normals;
  36840. var dst = this.object.geometry.normals;
  36841. dst.push( src[ a + 0 ], src[ a + 1 ], src[ a + 2 ] );
  36842. dst.push( src[ b + 0 ], src[ b + 1 ], src[ b + 2 ] );
  36843. dst.push( src[ c + 0 ], src[ c + 1 ], src[ c + 2 ] );
  36844. },
  36845. addColor: function ( a, b, c ) {
  36846. var src = this.colors;
  36847. var dst = this.object.geometry.colors;
  36848. dst.push( src[ a + 0 ], src[ a + 1 ], src[ a + 2 ] );
  36849. dst.push( src[ b + 0 ], src[ b + 1 ], src[ b + 2 ] );
  36850. dst.push( src[ c + 0 ], src[ c + 1 ], src[ c + 2 ] );
  36851. },
  36852. addUV: function ( a, b, c ) {
  36853. var src = this.uvs;
  36854. var dst = this.object.geometry.uvs;
  36855. dst.push( src[ a + 0 ], src[ a + 1 ] );
  36856. dst.push( src[ b + 0 ], src[ b + 1 ] );
  36857. dst.push( src[ c + 0 ], src[ c + 1 ] );
  36858. },
  36859. addUVLine: function ( a ) {
  36860. var src = this.uvs;
  36861. var dst = this.object.geometry.uvs;
  36862. dst.push( src[ a + 0 ], src[ a + 1 ] );
  36863. },
  36864. addFace: function ( a, b, c, ua, ub, uc, na, nb, nc ) {
  36865. var vLen = this.vertices.length;
  36866. var ia = this.parseVertexIndex( a, vLen );
  36867. var ib = this.parseVertexIndex( b, vLen );
  36868. var ic = this.parseVertexIndex( c, vLen );
  36869. this.addVertex( ia, ib, ic );
  36870. if ( ua !== undefined && ua !== '' ) {
  36871. var uvLen = this.uvs.length;
  36872. ia = this.parseUVIndex( ua, uvLen );
  36873. ib = this.parseUVIndex( ub, uvLen );
  36874. ic = this.parseUVIndex( uc, uvLen );
  36875. this.addUV( ia, ib, ic );
  36876. }
  36877. if ( na !== undefined && na !== '' ) {
  36878. // Normals are many times the same. If so, skip function call and parseInt.
  36879. var nLen = this.normals.length;
  36880. ia = this.parseNormalIndex( na, nLen );
  36881. ib = na === nb ? ia : this.parseNormalIndex( nb, nLen );
  36882. ic = na === nc ? ia : this.parseNormalIndex( nc, nLen );
  36883. this.addNormal( ia, ib, ic );
  36884. }
  36885. if ( this.colors.length > 0 ) {
  36886. this.addColor( ia, ib, ic );
  36887. }
  36888. },
  36889. addPointGeometry: function ( vertices ) {
  36890. this.object.geometry.type = 'Points';
  36891. var vLen = this.vertices.length;
  36892. for ( var vi = 0, l = vertices.length; vi < l; vi ++ ) {
  36893. this.addVertexPoint( this.parseVertexIndex( vertices[ vi ], vLen ) );
  36894. }
  36895. },
  36896. addLineGeometry: function ( vertices, uvs ) {
  36897. this.object.geometry.type = 'Line';
  36898. var vLen = this.vertices.length;
  36899. var uvLen = this.uvs.length;
  36900. for ( var vi = 0, l = vertices.length; vi < l; vi ++ ) {
  36901. this.addVertexLine( this.parseVertexIndex( vertices[ vi ], vLen ) );
  36902. }
  36903. for ( var uvi = 0, l = uvs.length; uvi < l; uvi ++ ) {
  36904. this.addUVLine( this.parseUVIndex( uvs[ uvi ], uvLen ) );
  36905. }
  36906. }
  36907. };
  36908. state.startObject( '', false );
  36909. return state;
  36910. }
  36911. //
  36912. function OBJLoader( manager ) {
  36913. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  36914. this.materials = null;
  36915. }
  36916. OBJLoader.prototype = {
  36917. constructor: OBJLoader,
  36918. load: function ( url, onLoad, onProgress, onError ) {
  36919. var scope = this;
  36920. var loader = new THREE.FileLoader( scope.manager );
  36921. loader.setPath( this.path );
  36922. loader.load( url, function ( text ) {
  36923. onLoad( scope.parse( text ) );
  36924. }, onProgress, onError );
  36925. },
  36926. setPath: function ( value ) {
  36927. this.path = value;
  36928. return this;
  36929. },
  36930. setMaterials: function ( materials ) {
  36931. this.materials = materials;
  36932. return this;
  36933. },
  36934. parse: function ( text ) {
  36935. console.time( 'OBJLoader' );
  36936. var state = new ParserState();
  36937. if ( text.indexOf( '\r\n' ) !== - 1 ) {
  36938. // This is faster than String.split with regex that splits on both
  36939. text = text.replace( /\r\n/g, '\n' );
  36940. }
  36941. if ( text.indexOf( '\\\n' ) !== - 1 ) {
  36942. // join lines separated by a line continuation character (\)
  36943. text = text.replace( /\\\n/g, '' );
  36944. }
  36945. var lines = text.split( '\n' );
  36946. var line = '', lineFirstChar = '';
  36947. var lineLength = 0;
  36948. var result = [];
  36949. // Faster to just trim left side of the line. Use if available.
  36950. var trimLeft = ( typeof ''.trimLeft === 'function' );
  36951. for ( var i = 0, l = lines.length; i < l; i ++ ) {
  36952. line = lines[ i ];
  36953. line = trimLeft ? line.trimLeft() : line.trim();
  36954. lineLength = line.length;
  36955. if ( lineLength === 0 ) continue;
  36956. lineFirstChar = line.charAt( 0 );
  36957. // @todo invoke passed in handler if any
  36958. if ( lineFirstChar === '#' ) continue;
  36959. if ( lineFirstChar === 'v' ) {
  36960. var data = line.split( /\s+/ );
  36961. switch ( data[ 0 ] ) {
  36962. case 'v':
  36963. state.vertices.push(
  36964. parseFloat( data[ 1 ] ),
  36965. parseFloat( data[ 2 ] ),
  36966. parseFloat( data[ 3 ] )
  36967. );
  36968. if ( data.length === 8 ) {
  36969. state.colors.push(
  36970. parseFloat( data[ 4 ] ),
  36971. parseFloat( data[ 5 ] ),
  36972. parseFloat( data[ 6 ] )
  36973. );
  36974. }
  36975. break;
  36976. case 'vn':
  36977. state.normals.push(
  36978. parseFloat( data[ 1 ] ),
  36979. parseFloat( data[ 2 ] ),
  36980. parseFloat( data[ 3 ] )
  36981. );
  36982. break;
  36983. case 'vt':
  36984. state.uvs.push(
  36985. parseFloat( data[ 1 ] ),
  36986. parseFloat( data[ 2 ] )
  36987. );
  36988. break;
  36989. }
  36990. } else if ( lineFirstChar === 'f' ) {
  36991. var lineData = line.substr( 1 ).trim();
  36992. var vertexData = lineData.split( /\s+/ );
  36993. var faceVertices = [];
  36994. // Parse the face vertex data into an easy to work with format
  36995. for ( var j = 0, jl = vertexData.length; j < jl; j ++ ) {
  36996. var vertex = vertexData[ j ];
  36997. if ( vertex.length > 0 ) {
  36998. var vertexParts = vertex.split( '/' );
  36999. faceVertices.push( vertexParts );
  37000. }
  37001. }
  37002. // Draw an edge between the first vertex and all subsequent vertices to form an n-gon
  37003. var v1 = faceVertices[ 0 ];
  37004. for ( var j = 1, jl = faceVertices.length - 1; j < jl; j ++ ) {
  37005. var v2 = faceVertices[ j ];
  37006. var v3 = faceVertices[ j + 1 ];
  37007. state.addFace(
  37008. v1[ 0 ], v2[ 0 ], v3[ 0 ],
  37009. v1[ 1 ], v2[ 1 ], v3[ 1 ],
  37010. v1[ 2 ], v2[ 2 ], v3[ 2 ]
  37011. );
  37012. }
  37013. } else if ( lineFirstChar === 'l' ) {
  37014. var lineParts = line.substring( 1 ).trim().split( " " );
  37015. var lineVertices = [], lineUVs = [];
  37016. if ( line.indexOf( "/" ) === - 1 ) {
  37017. lineVertices = lineParts;
  37018. } else {
  37019. for ( var li = 0, llen = lineParts.length; li < llen; li ++ ) {
  37020. var parts = lineParts[ li ].split( "/" );
  37021. if ( parts[ 0 ] !== "" ) lineVertices.push( parts[ 0 ] );
  37022. if ( parts[ 1 ] !== "" ) lineUVs.push( parts[ 1 ] );
  37023. }
  37024. }
  37025. state.addLineGeometry( lineVertices, lineUVs );
  37026. } else if ( lineFirstChar === 'p' ) {
  37027. var lineData = line.substr( 1 ).trim();
  37028. var pointData = lineData.split( " " );
  37029. state.addPointGeometry( pointData );
  37030. } else if ( ( result = object_pattern.exec( line ) ) !== null ) {
  37031. // o object_name
  37032. // or
  37033. // g group_name
  37034. // WORKAROUND: https://bugs.chromium.org/p/v8/issues/detail?id=2869
  37035. // var name = result[ 0 ].substr( 1 ).trim();
  37036. var name = ( " " + result[ 0 ].substr( 1 ).trim() ).substr( 1 );
  37037. state.startObject( name );
  37038. } else if ( material_use_pattern.test( line ) ) {
  37039. // material
  37040. state.object.startMaterial( line.substring( 7 ).trim(), state.materialLibraries );
  37041. } else if ( material_library_pattern.test( line ) ) {
  37042. // mtl file
  37043. state.materialLibraries.push( line.substring( 7 ).trim() );
  37044. } else if ( lineFirstChar === 's' ) {
  37045. result = line.split( ' ' );
  37046. // smooth shading
  37047. // @todo Handle files that have varying smooth values for a set of faces inside one geometry,
  37048. // but does not define a usemtl for each face set.
  37049. // This should be detected and a dummy material created (later MultiMaterial and geometry groups).
  37050. // This requires some care to not create extra material on each smooth value for "normal" obj files.
  37051. // where explicit usemtl defines geometry groups.
  37052. // Example asset: examples/models/obj/cerberus/Cerberus.obj
  37053. /*
  37054. * http://paulbourke.net/dataformats/obj/
  37055. * or
  37056. * http://www.cs.utah.edu/~boulos/cs3505/obj_spec.pdf
  37057. *
  37058. * From chapter "Grouping" Syntax explanation "s group_number":
  37059. * "group_number is the smoothing group number. To turn off smoothing groups, use a value of 0 or off.
  37060. * Polygonal elements use group numbers to put elements in different smoothing groups. For free-form
  37061. * surfaces, smoothing groups are either turned on or off; there is no difference between values greater
  37062. * than 0."
  37063. */
  37064. if ( result.length > 1 ) {
  37065. var value = result[ 1 ].trim().toLowerCase();
  37066. state.object.smooth = ( value !== '0' && value !== 'off' );
  37067. } else {
  37068. // ZBrush can produce "s" lines #11707
  37069. state.object.smooth = true;
  37070. }
  37071. var material = state.object.currentMaterial();
  37072. if ( material ) material.smooth = state.object.smooth;
  37073. } else {
  37074. // Handle null terminated files without exception
  37075. if ( line === '\0' ) continue;
  37076. throw new Error( 'THREE.OBJLoader: Unexpected line: "' + line + '"' );
  37077. }
  37078. }
  37079. state.finalize();
  37080. var container = new THREE.Group();
  37081. container.materialLibraries = [].concat( state.materialLibraries );
  37082. for ( var i = 0, l = state.objects.length; i < l; i ++ ) {
  37083. var object = state.objects[ i ];
  37084. var geometry = object.geometry;
  37085. var materials = object.materials;
  37086. var isLine = ( geometry.type === 'Line' );
  37087. var isPoints = ( geometry.type === 'Points' );
  37088. var hasVertexColors = false;
  37089. // Skip o/g line declarations that did not follow with any faces
  37090. if ( geometry.vertices.length === 0 ) continue;
  37091. var buffergeometry = new THREE.BufferGeometry();
  37092. buffergeometry.addAttribute( 'position', new THREE.Float32BufferAttribute( geometry.vertices, 3 ) );
  37093. if ( geometry.normals.length > 0 ) {
  37094. buffergeometry.addAttribute( 'normal', new THREE.Float32BufferAttribute( geometry.normals, 3 ) );
  37095. } else {
  37096. buffergeometry.computeVertexNormals();
  37097. }
  37098. if ( geometry.colors.length > 0 ) {
  37099. hasVertexColors = true;
  37100. buffergeometry.addAttribute( 'color', new THREE.Float32BufferAttribute( geometry.colors, 3 ) );
  37101. }
  37102. if ( geometry.uvs.length > 0 ) {
  37103. buffergeometry.addAttribute( 'uv', new THREE.Float32BufferAttribute( geometry.uvs, 2 ) );
  37104. }
  37105. // Create materials
  37106. var createdMaterials = [];
  37107. for ( var mi = 0, miLen = materials.length; mi < miLen; mi ++ ) {
  37108. var sourceMaterial = materials[ mi ];
  37109. var material = undefined;
  37110. if ( this.materials !== null ) {
  37111. material = this.materials.create( sourceMaterial.name );
  37112. // mtl etc. loaders probably can't create line materials correctly, copy properties to a line material.
  37113. if ( isLine && material && ! ( material instanceof THREE.LineBasicMaterial ) ) {
  37114. var materialLine = new THREE.LineBasicMaterial();
  37115. THREE.Material.prototype.copy.call( materialLine, material );
  37116. materialLine.color.copy( material.color );
  37117. materialLine.lights = false;
  37118. material = materialLine;
  37119. } else if ( isPoints && material && ! ( material instanceof THREE.PointsMaterial ) ) {
  37120. var materialPoints = new THREE.PointsMaterial( { size: 10, sizeAttenuation: false } );
  37121. THREE.Material.prototype.copy.call( materialPoints, material );
  37122. materialPoints.color.copy( material.color );
  37123. materialPoints.map = material.map;
  37124. materialPoints.lights = false;
  37125. material = materialPoints;
  37126. }
  37127. }
  37128. if ( ! material ) {
  37129. if ( isLine ) {
  37130. material = new THREE.LineBasicMaterial();
  37131. } else if ( isPoints ) {
  37132. material = new THREE.PointsMaterial( { size: 1, sizeAttenuation: false } );
  37133. } else {
  37134. material = new THREE.MeshPhongMaterial();
  37135. }
  37136. material.name = sourceMaterial.name;
  37137. }
  37138. material.flatShading = sourceMaterial.smooth ? false : true;
  37139. material.vertexColors = hasVertexColors ? THREE.VertexColors : THREE.NoColors;
  37140. createdMaterials.push( material );
  37141. }
  37142. // Create mesh
  37143. var mesh;
  37144. if ( createdMaterials.length > 1 ) {
  37145. for ( var mi = 0, miLen = materials.length; mi < miLen; mi ++ ) {
  37146. var sourceMaterial = materials[ mi ];
  37147. buffergeometry.addGroup( sourceMaterial.groupStart, sourceMaterial.groupCount, mi );
  37148. }
  37149. if ( isLine ) {
  37150. mesh = new THREE.LineSegments( buffergeometry, createdMaterials );
  37151. } else if ( isPoints ) {
  37152. mesh = new THREE.Points( buffergeometry, createdMaterials );
  37153. } else {
  37154. mesh = new THREE.Mesh( buffergeometry, createdMaterials );
  37155. }
  37156. } else {
  37157. if ( isLine ) {
  37158. mesh = new THREE.LineSegments( buffergeometry, createdMaterials[ 0 ] );
  37159. } else if ( isPoints ) {
  37160. mesh = new THREE.Points( buffergeometry, createdMaterials[ 0 ] );
  37161. } else {
  37162. mesh = new THREE.Mesh( buffergeometry, createdMaterials[ 0 ] );
  37163. }
  37164. }
  37165. mesh.name = object.name;
  37166. container.add( mesh );
  37167. }
  37168. console.timeEnd( 'OBJLoader' );
  37169. return container;
  37170. }
  37171. };
  37172. return OBJLoader;
  37173. } )();
  37174. },{}],41:[function(_dereq_,module,exports){
  37175. var createLayout = _dereq_('layout-bmfont-text')
  37176. var inherits = _dereq_('inherits')
  37177. var createIndices = _dereq_('quad-indices')
  37178. var buffer = _dereq_('three-buffer-vertex-data')
  37179. var assign = _dereq_('object-assign')
  37180. var vertices = _dereq_('./lib/vertices')
  37181. var utils = _dereq_('./lib/utils')
  37182. var Base = THREE.BufferGeometry
  37183. module.exports = function createTextGeometry (opt) {
  37184. return new TextGeometry(opt)
  37185. }
  37186. function TextGeometry (opt) {
  37187. Base.call(this)
  37188. if (typeof opt === 'string') {
  37189. opt = { text: opt }
  37190. }
  37191. // use these as default values for any subsequent
  37192. // calls to update()
  37193. this._opt = assign({}, opt)
  37194. // also do an initial setup...
  37195. if (opt) this.update(opt)
  37196. }
  37197. inherits(TextGeometry, Base)
  37198. TextGeometry.prototype.update = function (opt) {
  37199. if (typeof opt === 'string') {
  37200. opt = { text: opt }
  37201. }
  37202. // use constructor defaults
  37203. opt = assign({}, this._opt, opt)
  37204. if (!opt.font) {
  37205. throw new TypeError('must specify a { font } in options')
  37206. }
  37207. this.layout = createLayout(opt)
  37208. // get vec2 texcoords
  37209. var flipY = opt.flipY !== false
  37210. // the desired BMFont data
  37211. var font = opt.font
  37212. // determine texture size from font file
  37213. var texWidth = font.common.scaleW
  37214. var texHeight = font.common.scaleH
  37215. // get visible glyphs
  37216. var glyphs = this.layout.glyphs.filter(function (glyph) {
  37217. var bitmap = glyph.data
  37218. return bitmap.width * bitmap.height > 0
  37219. })
  37220. // provide visible glyphs for convenience
  37221. this.visibleGlyphs = glyphs
  37222. // get common vertex data
  37223. var positions = vertices.positions(glyphs)
  37224. var uvs = vertices.uvs(glyphs, texWidth, texHeight, flipY)
  37225. var indices = createIndices({
  37226. clockwise: true,
  37227. type: 'uint16',
  37228. count: glyphs.length
  37229. })
  37230. // update vertex data
  37231. buffer.index(this, indices, 1, 'uint16')
  37232. buffer.attr(this, 'position', positions, 2)
  37233. buffer.attr(this, 'uv', uvs, 2)
  37234. // update multipage data
  37235. if (!opt.multipage && 'page' in this.attributes) {
  37236. // disable multipage rendering
  37237. this.removeAttribute('page')
  37238. } else if (opt.multipage) {
  37239. var pages = vertices.pages(glyphs)
  37240. // enable multipage rendering
  37241. buffer.attr(this, 'page', pages, 1)
  37242. }
  37243. }
  37244. TextGeometry.prototype.computeBoundingSphere = function () {
  37245. if (this.boundingSphere === null) {
  37246. this.boundingSphere = new THREE.Sphere()
  37247. }
  37248. var positions = this.attributes.position.array
  37249. var itemSize = this.attributes.position.itemSize
  37250. if (!positions || !itemSize || positions.length < 2) {
  37251. this.boundingSphere.radius = 0
  37252. this.boundingSphere.center.set(0, 0, 0)
  37253. return
  37254. }
  37255. utils.computeSphere(positions, this.boundingSphere)
  37256. if (isNaN(this.boundingSphere.radius)) {
  37257. console.error('THREE.BufferGeometry.computeBoundingSphere(): ' +
  37258. 'Computed radius is NaN. The ' +
  37259. '"position" attribute is likely to have NaN values.')
  37260. }
  37261. }
  37262. TextGeometry.prototype.computeBoundingBox = function () {
  37263. if (this.boundingBox === null) {
  37264. this.boundingBox = new THREE.Box3()
  37265. }
  37266. var bbox = this.boundingBox
  37267. var positions = this.attributes.position.array
  37268. var itemSize = this.attributes.position.itemSize
  37269. if (!positions || !itemSize || positions.length < 2) {
  37270. bbox.makeEmpty()
  37271. return
  37272. }
  37273. utils.computeBox(positions, bbox)
  37274. }
  37275. },{"./lib/utils":42,"./lib/vertices":43,"inherits":17,"layout-bmfont-text":22,"object-assign":25,"quad-indices":34,"three-buffer-vertex-data":44}],42:[function(_dereq_,module,exports){
  37276. var itemSize = 2
  37277. var box = { min: [0, 0], max: [0, 0] }
  37278. function bounds (positions) {
  37279. var count = positions.length / itemSize
  37280. box.min[0] = positions[0]
  37281. box.min[1] = positions[1]
  37282. box.max[0] = positions[0]
  37283. box.max[1] = positions[1]
  37284. for (var i = 0; i < count; i++) {
  37285. var x = positions[i * itemSize + 0]
  37286. var y = positions[i * itemSize + 1]
  37287. box.min[0] = Math.min(x, box.min[0])
  37288. box.min[1] = Math.min(y, box.min[1])
  37289. box.max[0] = Math.max(x, box.max[0])
  37290. box.max[1] = Math.max(y, box.max[1])
  37291. }
  37292. }
  37293. module.exports.computeBox = function (positions, output) {
  37294. bounds(positions)
  37295. output.min.set(box.min[0], box.min[1], 0)
  37296. output.max.set(box.max[0], box.max[1], 0)
  37297. }
  37298. module.exports.computeSphere = function (positions, output) {
  37299. bounds(positions)
  37300. var minX = box.min[0]
  37301. var minY = box.min[1]
  37302. var maxX = box.max[0]
  37303. var maxY = box.max[1]
  37304. var width = maxX - minX
  37305. var height = maxY - minY
  37306. var length = Math.sqrt(width * width + height * height)
  37307. output.center.set(minX + width / 2, minY + height / 2, 0)
  37308. output.radius = length / 2
  37309. }
  37310. },{}],43:[function(_dereq_,module,exports){
  37311. module.exports.pages = function pages (glyphs) {
  37312. var pages = new Float32Array(glyphs.length * 4 * 1)
  37313. var i = 0
  37314. glyphs.forEach(function (glyph) {
  37315. var id = glyph.data.page || 0
  37316. pages[i++] = id
  37317. pages[i++] = id
  37318. pages[i++] = id
  37319. pages[i++] = id
  37320. })
  37321. return pages
  37322. }
  37323. module.exports.uvs = function uvs (glyphs, texWidth, texHeight, flipY) {
  37324. var uvs = new Float32Array(glyphs.length * 4 * 2)
  37325. var i = 0
  37326. glyphs.forEach(function (glyph) {
  37327. var bitmap = glyph.data
  37328. var bw = (bitmap.x + bitmap.width)
  37329. var bh = (bitmap.y + bitmap.height)
  37330. // top left position
  37331. var u0 = bitmap.x / texWidth
  37332. var v1 = bitmap.y / texHeight
  37333. var u1 = bw / texWidth
  37334. var v0 = bh / texHeight
  37335. if (flipY) {
  37336. v1 = (texHeight - bitmap.y) / texHeight
  37337. v0 = (texHeight - bh) / texHeight
  37338. }
  37339. // BL
  37340. uvs[i++] = u0
  37341. uvs[i++] = v1
  37342. // TL
  37343. uvs[i++] = u0
  37344. uvs[i++] = v0
  37345. // TR
  37346. uvs[i++] = u1
  37347. uvs[i++] = v0
  37348. // BR
  37349. uvs[i++] = u1
  37350. uvs[i++] = v1
  37351. })
  37352. return uvs
  37353. }
  37354. module.exports.positions = function positions (glyphs) {
  37355. var positions = new Float32Array(glyphs.length * 4 * 2)
  37356. var i = 0
  37357. glyphs.forEach(function (glyph) {
  37358. var bitmap = glyph.data
  37359. // bottom left position
  37360. var x = glyph.position[0] + bitmap.xoffset
  37361. var y = glyph.position[1] + bitmap.yoffset
  37362. // quad size
  37363. var w = bitmap.width
  37364. var h = bitmap.height
  37365. // BL
  37366. positions[i++] = x
  37367. positions[i++] = y
  37368. // TL
  37369. positions[i++] = x
  37370. positions[i++] = y + h
  37371. // TR
  37372. positions[i++] = x + w
  37373. positions[i++] = y + h
  37374. // BR
  37375. positions[i++] = x + w
  37376. positions[i++] = y
  37377. })
  37378. return positions
  37379. }
  37380. },{}],44:[function(_dereq_,module,exports){
  37381. var flatten = _dereq_('flatten-vertex-data')
  37382. var warned = false;
  37383. module.exports.attr = setAttribute
  37384. module.exports.index = setIndex
  37385. function setIndex (geometry, data, itemSize, dtype) {
  37386. if (typeof itemSize !== 'number') itemSize = 1
  37387. if (typeof dtype !== 'string') dtype = 'uint16'
  37388. var isR69 = !geometry.index && typeof geometry.setIndex !== 'function'
  37389. var attrib = isR69 ? geometry.getAttribute('index') : geometry.index
  37390. var newAttrib = updateAttribute(attrib, data, itemSize, dtype)
  37391. if (newAttrib) {
  37392. if (isR69) geometry.addAttribute('index', newAttrib)
  37393. else geometry.index = newAttrib
  37394. }
  37395. }
  37396. function setAttribute (geometry, key, data, itemSize, dtype) {
  37397. if (typeof itemSize !== 'number') itemSize = 3
  37398. if (typeof dtype !== 'string') dtype = 'float32'
  37399. if (Array.isArray(data) &&
  37400. Array.isArray(data[0]) &&
  37401. data[0].length !== itemSize) {
  37402. throw new Error('Nested vertex array has unexpected size; expected ' +
  37403. itemSize + ' but found ' + data[0].length)
  37404. }
  37405. var attrib = geometry.getAttribute(key)
  37406. var newAttrib = updateAttribute(attrib, data, itemSize, dtype)
  37407. if (newAttrib) {
  37408. geometry.addAttribute(key, newAttrib)
  37409. }
  37410. }
  37411. function updateAttribute (attrib, data, itemSize, dtype) {
  37412. data = data || []
  37413. if (!attrib || rebuildAttribute(attrib, data, itemSize)) {
  37414. // create a new array with desired type
  37415. data = flatten(data, dtype)
  37416. var needsNewBuffer = attrib && typeof attrib.setArray !== 'function'
  37417. if (!attrib || needsNewBuffer) {
  37418. // We are on an old version of ThreeJS which can't
  37419. // support growing / shrinking buffers, so we need
  37420. // to build a new buffer
  37421. if (needsNewBuffer && !warned) {
  37422. warned = true
  37423. console.warn([
  37424. 'A WebGL buffer is being updated with a new size or itemSize, ',
  37425. 'however this version of ThreeJS only supports fixed-size buffers.',
  37426. '\nThe old buffer may still be kept in memory.\n',
  37427. 'To avoid memory leaks, it is recommended that you dispose ',
  37428. 'your geometries and create new ones, or update to ThreeJS r82 or newer.\n',
  37429. 'See here for discussion:\n',
  37430. 'https://github.com/mrdoob/three.js/pull/9631'
  37431. ].join(''))
  37432. }
  37433. // Build a new attribute
  37434. attrib = new THREE.BufferAttribute(data, itemSize);
  37435. }
  37436. attrib.itemSize = itemSize
  37437. attrib.needsUpdate = true
  37438. // New versions of ThreeJS suggest using setArray
  37439. // to change the data. It will use bufferData internally,
  37440. // so you can change the array size without any issues
  37441. if (typeof attrib.setArray === 'function') {
  37442. attrib.setArray(data)
  37443. }
  37444. return attrib
  37445. } else {
  37446. // copy data into the existing array
  37447. flatten(data, attrib.array)
  37448. attrib.needsUpdate = true
  37449. return null
  37450. }
  37451. }
  37452. // Test whether the attribute needs to be re-created,
  37453. // returns false if we can re-use it as-is.
  37454. function rebuildAttribute (attrib, data, itemSize) {
  37455. if (attrib.itemSize !== itemSize) return true
  37456. if (!attrib.array) return true
  37457. var attribLength = attrib.array.length
  37458. if (Array.isArray(data) && Array.isArray(data[0])) {
  37459. // [ [ x, y, z ] ]
  37460. return attribLength !== data.length * itemSize
  37461. } else {
  37462. // [ x, y, z ]
  37463. return attribLength !== data.length
  37464. }
  37465. return false
  37466. }
  37467. },{"flatten-vertex-data":13}],45:[function(_dereq_,module,exports){
  37468. exports = module.exports = trim;
  37469. function trim(str){
  37470. return str.replace(/^\s*|\s*$/g, '');
  37471. }
  37472. exports.left = function(str){
  37473. return str.replace(/^\s*/, '');
  37474. };
  37475. exports.right = function(str){
  37476. return str.replace(/\s*$/, '');
  37477. };
  37478. },{}],46:[function(_dereq_,module,exports){
  37479. (function (global){
  37480. /**
  37481. * @license
  37482. * webvr-polyfill
  37483. * Copyright (c) 2015-2017 Google
  37484. * Licensed under the Apache License, Version 2.0 (the "License");
  37485. * you may not use this file except in compliance with the License.
  37486. * You may obtain a copy of the License at
  37487. *
  37488. * http://www.apache.org/licenses/LICENSE-2.0
  37489. *
  37490. * Unless required by applicable law or agreed to in writing, software
  37491. * distributed under the License is distributed on an "AS IS" BASIS,
  37492. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  37493. * See the License for the specific language governing permissions and
  37494. * limitations under the License.
  37495. */
  37496. /**
  37497. * @license
  37498. * cardboard-vr-display
  37499. * Copyright (c) 2015-2017 Google
  37500. * Licensed under the Apache License, Version 2.0 (the "License");
  37501. * you may not use this file except in compliance with the License.
  37502. * You may obtain a copy of the License at
  37503. *
  37504. * http://www.apache.org/licenses/LICENSE-2.0
  37505. *
  37506. * Unless required by applicable law or agreed to in writing, software
  37507. * distributed under the License is distributed on an "AS IS" BASIS,
  37508. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  37509. * See the License for the specific language governing permissions and
  37510. * limitations under the License.
  37511. */
  37512. /**
  37513. * @license
  37514. * webvr-polyfill-dpdb
  37515. * Copyright (c) 2017 Google
  37516. * Licensed under the Apache License, Version 2.0 (the "License");
  37517. * you may not use this file except in compliance with the License.
  37518. * You may obtain a copy of the License at
  37519. *
  37520. * http://www.apache.org/licenses/LICENSE-2.0
  37521. *
  37522. * Unless required by applicable law or agreed to in writing, software
  37523. * distributed under the License is distributed on an "AS IS" BASIS,
  37524. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  37525. * See the License for the specific language governing permissions and
  37526. * limitations under the License.
  37527. */
  37528. /**
  37529. * @license
  37530. * wglu-preserve-state
  37531. * Copyright (c) 2016, Brandon Jones.
  37532. *
  37533. * Permission is hereby granted, free of charge, to any person obtaining a copy
  37534. * of this software and associated documentation files (the "Software"), to deal
  37535. * in the Software without restriction, including without limitation the rights
  37536. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  37537. * copies of the Software, and to permit persons to whom the Software is
  37538. * furnished to do so, subject to the following conditions:
  37539. *
  37540. * The above copyright notice and this permission notice shall be included in
  37541. * all copies or substantial portions of the Software.
  37542. *
  37543. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  37544. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  37545. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  37546. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  37547. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  37548. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  37549. * THE SOFTWARE.
  37550. */
  37551. /**
  37552. * @license
  37553. * nosleep.js
  37554. * Copyright (c) 2017, Rich Tibbett
  37555. *
  37556. * Permission is hereby granted, free of charge, to any person obtaining a copy
  37557. * of this software and associated documentation files (the "Software"), to deal
  37558. * in the Software without restriction, including without limitation the rights
  37559. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  37560. * copies of the Software, and to permit persons to whom the Software is
  37561. * furnished to do so, subject to the following conditions:
  37562. *
  37563. * The above copyright notice and this permission notice shall be included in
  37564. * all copies or substantial portions of the Software.
  37565. *
  37566. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  37567. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  37568. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  37569. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  37570. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  37571. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  37572. * THE SOFTWARE.
  37573. */
  37574. (function (global, factory) {
  37575. typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
  37576. typeof define === 'function' && define.amd ? define(factory) :
  37577. (global.WebVRPolyfill = factory());
  37578. }(this, (function () { 'use strict';
  37579. var commonjsGlobal = typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
  37580. function unwrapExports (x) {
  37581. return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
  37582. }
  37583. function createCommonjsModule(fn, module) {
  37584. return module = { exports: {} }, fn(module, module.exports), module.exports;
  37585. }
  37586. var isMobile = function isMobile() {
  37587. return (/Android/i.test(navigator.userAgent) || /iPhone|iPad|iPod/i.test(navigator.userAgent)
  37588. );
  37589. };
  37590. var copyArray = function copyArray(source, dest) {
  37591. for (var i = 0, n = source.length; i < n; i++) {
  37592. dest[i] = source[i];
  37593. }
  37594. };
  37595. var extend = function extend(dest, src) {
  37596. for (var key in src) {
  37597. if (src.hasOwnProperty(key)) {
  37598. dest[key] = src[key];
  37599. }
  37600. }
  37601. return dest;
  37602. };
  37603. var cardboardVrDisplay = createCommonjsModule(function (module, exports) {
  37604. /**
  37605. * @license
  37606. * cardboard-vr-display
  37607. * Copyright (c) 2015-2017 Google
  37608. * Licensed under the Apache License, Version 2.0 (the "License");
  37609. * you may not use this file except in compliance with the License.
  37610. * You may obtain a copy of the License at
  37611. *
  37612. * http://www.apache.org/licenses/LICENSE-2.0
  37613. *
  37614. * Unless required by applicable law or agreed to in writing, software
  37615. * distributed under the License is distributed on an "AS IS" BASIS,
  37616. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  37617. * See the License for the specific language governing permissions and
  37618. * limitations under the License.
  37619. */
  37620. /**
  37621. * @license
  37622. * gl-preserve-state
  37623. * Copyright (c) 2016, Brandon Jones.
  37624. *
  37625. * Permission is hereby granted, free of charge, to any person obtaining a copy
  37626. * of this software and associated documentation files (the "Software"), to deal
  37627. * in the Software without restriction, including without limitation the rights
  37628. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  37629. * copies of the Software, and to permit persons to whom the Software is
  37630. * furnished to do so, subject to the following conditions:
  37631. *
  37632. * The above copyright notice and this permission notice shall be included in
  37633. * all copies or substantial portions of the Software.
  37634. *
  37635. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  37636. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  37637. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  37638. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  37639. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  37640. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  37641. * THE SOFTWARE.
  37642. */
  37643. /**
  37644. * @license
  37645. * webvr-polyfill-dpdb
  37646. * Copyright (c) 2015-2017 Google
  37647. * Licensed under the Apache License, Version 2.0 (the "License");
  37648. * you may not use this file except in compliance with the License.
  37649. * You may obtain a copy of the License at
  37650. *
  37651. * http://www.apache.org/licenses/LICENSE-2.0
  37652. *
  37653. * Unless required by applicable law or agreed to in writing, software
  37654. * distributed under the License is distributed on an "AS IS" BASIS,
  37655. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  37656. * See the License for the specific language governing permissions and
  37657. * limitations under the License.
  37658. */
  37659. /**
  37660. * @license
  37661. * nosleep.js
  37662. * Copyright (c) 2017, Rich Tibbett
  37663. *
  37664. * Permission is hereby granted, free of charge, to any person obtaining a copy
  37665. * of this software and associated documentation files (the "Software"), to deal
  37666. * in the Software without restriction, including without limitation the rights
  37667. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  37668. * copies of the Software, and to permit persons to whom the Software is
  37669. * furnished to do so, subject to the following conditions:
  37670. *
  37671. * The above copyright notice and this permission notice shall be included in
  37672. * all copies or substantial portions of the Software.
  37673. *
  37674. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  37675. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  37676. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  37677. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  37678. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  37679. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  37680. * THE SOFTWARE.
  37681. */
  37682. (function (global, factory) {
  37683. module.exports = factory();
  37684. }(commonjsGlobal, (function () { var classCallCheck = function (instance, Constructor) {
  37685. if (!(instance instanceof Constructor)) {
  37686. throw new TypeError("Cannot call a class as a function");
  37687. }
  37688. };
  37689. var createClass = function () {
  37690. function defineProperties(target, props) {
  37691. for (var i = 0; i < props.length; i++) {
  37692. var descriptor = props[i];
  37693. descriptor.enumerable = descriptor.enumerable || false;
  37694. descriptor.configurable = true;
  37695. if ("value" in descriptor) descriptor.writable = true;
  37696. Object.defineProperty(target, descriptor.key, descriptor);
  37697. }
  37698. }
  37699. return function (Constructor, protoProps, staticProps) {
  37700. if (protoProps) defineProperties(Constructor.prototype, protoProps);
  37701. if (staticProps) defineProperties(Constructor, staticProps);
  37702. return Constructor;
  37703. };
  37704. }();
  37705. var slicedToArray = function () {
  37706. function sliceIterator(arr, i) {
  37707. var _arr = [];
  37708. var _n = true;
  37709. var _d = false;
  37710. var _e = undefined;
  37711. try {
  37712. for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {
  37713. _arr.push(_s.value);
  37714. if (i && _arr.length === i) break;
  37715. }
  37716. } catch (err) {
  37717. _d = true;
  37718. _e = err;
  37719. } finally {
  37720. try {
  37721. if (!_n && _i["return"]) _i["return"]();
  37722. } finally {
  37723. if (_d) throw _e;
  37724. }
  37725. }
  37726. return _arr;
  37727. }
  37728. return function (arr, i) {
  37729. if (Array.isArray(arr)) {
  37730. return arr;
  37731. } else if (Symbol.iterator in Object(arr)) {
  37732. return sliceIterator(arr, i);
  37733. } else {
  37734. throw new TypeError("Invalid attempt to destructure non-iterable instance");
  37735. }
  37736. };
  37737. }();
  37738. var MIN_TIMESTEP = 0.001;
  37739. var MAX_TIMESTEP = 1;
  37740. var dataUri = function dataUri(mimeType, svg) {
  37741. return 'data:' + mimeType + ',' + encodeURIComponent(svg);
  37742. };
  37743. var lerp = function lerp(a, b, t) {
  37744. return a + (b - a) * t;
  37745. };
  37746. var isIOS = function () {
  37747. var isIOS = /iPad|iPhone|iPod/.test(navigator.platform);
  37748. return function () {
  37749. return isIOS;
  37750. };
  37751. }();
  37752. var isWebViewAndroid = function () {
  37753. var isWebViewAndroid = navigator.userAgent.indexOf('Version') !== -1 && navigator.userAgent.indexOf('Android') !== -1 && navigator.userAgent.indexOf('Chrome') !== -1;
  37754. return function () {
  37755. return isWebViewAndroid;
  37756. };
  37757. }();
  37758. var isSafari = function () {
  37759. var isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  37760. return function () {
  37761. return isSafari;
  37762. };
  37763. }();
  37764. var isFirefoxAndroid = function () {
  37765. var isFirefoxAndroid = navigator.userAgent.indexOf('Firefox') !== -1 && navigator.userAgent.indexOf('Android') !== -1;
  37766. return function () {
  37767. return isFirefoxAndroid;
  37768. };
  37769. }();
  37770. var getChromeVersion = function () {
  37771. var match = navigator.userAgent.match(/.*Chrome\/([0-9]+)/);
  37772. var value = match ? parseInt(match[1], 10) : null;
  37773. return function () {
  37774. return value;
  37775. };
  37776. }();
  37777. var isChromeWithoutDeviceMotion = function () {
  37778. var value = false;
  37779. if (getChromeVersion() === 65) {
  37780. var match = navigator.userAgent.match(/.*Chrome\/([0-9\.]*)/);
  37781. if (match) {
  37782. var _match$1$split = match[1].split('.'),
  37783. _match$1$split2 = slicedToArray(_match$1$split, 4),
  37784. major = _match$1$split2[0],
  37785. minor = _match$1$split2[1],
  37786. branch = _match$1$split2[2],
  37787. build = _match$1$split2[3];
  37788. value = parseInt(branch, 10) === 3325 && parseInt(build, 10) < 148;
  37789. }
  37790. }
  37791. return function () {
  37792. return value;
  37793. };
  37794. }();
  37795. var isR7 = function () {
  37796. var isR7 = navigator.userAgent.indexOf('R7 Build') !== -1;
  37797. return function () {
  37798. return isR7;
  37799. };
  37800. }();
  37801. var isLandscapeMode = function isLandscapeMode() {
  37802. var rtn = window.orientation == 90 || window.orientation == -90;
  37803. return isR7() ? !rtn : rtn;
  37804. };
  37805. var isTimestampDeltaValid = function isTimestampDeltaValid(timestampDeltaS) {
  37806. if (isNaN(timestampDeltaS)) {
  37807. return false;
  37808. }
  37809. if (timestampDeltaS <= MIN_TIMESTEP) {
  37810. return false;
  37811. }
  37812. if (timestampDeltaS > MAX_TIMESTEP) {
  37813. return false;
  37814. }
  37815. return true;
  37816. };
  37817. var getScreenWidth = function getScreenWidth() {
  37818. return Math.max(window.screen.width, window.screen.height) * window.devicePixelRatio;
  37819. };
  37820. var getScreenHeight = function getScreenHeight() {
  37821. return Math.min(window.screen.width, window.screen.height) * window.devicePixelRatio;
  37822. };
  37823. var requestFullscreen = function requestFullscreen(element) {
  37824. if (isWebViewAndroid()) {
  37825. return false;
  37826. }
  37827. if (element.requestFullscreen) {
  37828. element.requestFullscreen();
  37829. } else if (element.webkitRequestFullscreen) {
  37830. element.webkitRequestFullscreen();
  37831. } else if (element.mozRequestFullScreen) {
  37832. element.mozRequestFullScreen();
  37833. } else if (element.msRequestFullscreen) {
  37834. element.msRequestFullscreen();
  37835. } else {
  37836. return false;
  37837. }
  37838. return true;
  37839. };
  37840. var exitFullscreen = function exitFullscreen() {
  37841. if (document.exitFullscreen) {
  37842. document.exitFullscreen();
  37843. } else if (document.webkitExitFullscreen) {
  37844. document.webkitExitFullscreen();
  37845. } else if (document.mozCancelFullScreen) {
  37846. document.mozCancelFullScreen();
  37847. } else if (document.msExitFullscreen) {
  37848. document.msExitFullscreen();
  37849. } else {
  37850. return false;
  37851. }
  37852. return true;
  37853. };
  37854. var getFullscreenElement = function getFullscreenElement() {
  37855. return document.fullscreenElement || document.webkitFullscreenElement || document.mozFullScreenElement || document.msFullscreenElement;
  37856. };
  37857. var linkProgram = function linkProgram(gl, vertexSource, fragmentSource, attribLocationMap) {
  37858. var vertexShader = gl.createShader(gl.VERTEX_SHADER);
  37859. gl.shaderSource(vertexShader, vertexSource);
  37860. gl.compileShader(vertexShader);
  37861. var fragmentShader = gl.createShader(gl.FRAGMENT_SHADER);
  37862. gl.shaderSource(fragmentShader, fragmentSource);
  37863. gl.compileShader(fragmentShader);
  37864. var program = gl.createProgram();
  37865. gl.attachShader(program, vertexShader);
  37866. gl.attachShader(program, fragmentShader);
  37867. for (var attribName in attribLocationMap) {
  37868. gl.bindAttribLocation(program, attribLocationMap[attribName], attribName);
  37869. }gl.linkProgram(program);
  37870. gl.deleteShader(vertexShader);
  37871. gl.deleteShader(fragmentShader);
  37872. return program;
  37873. };
  37874. var getProgramUniforms = function getProgramUniforms(gl, program) {
  37875. var uniforms = {};
  37876. var uniformCount = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS);
  37877. var uniformName = '';
  37878. for (var i = 0; i < uniformCount; i++) {
  37879. var uniformInfo = gl.getActiveUniform(program, i);
  37880. uniformName = uniformInfo.name.replace('[0]', '');
  37881. uniforms[uniformName] = gl.getUniformLocation(program, uniformName);
  37882. }
  37883. return uniforms;
  37884. };
  37885. var orthoMatrix = function orthoMatrix(out, left, right, bottom, top, near, far) {
  37886. var lr = 1 / (left - right),
  37887. bt = 1 / (bottom - top),
  37888. nf = 1 / (near - far);
  37889. out[0] = -2 * lr;
  37890. out[1] = 0;
  37891. out[2] = 0;
  37892. out[3] = 0;
  37893. out[4] = 0;
  37894. out[5] = -2 * bt;
  37895. out[6] = 0;
  37896. out[7] = 0;
  37897. out[8] = 0;
  37898. out[9] = 0;
  37899. out[10] = 2 * nf;
  37900. out[11] = 0;
  37901. out[12] = (left + right) * lr;
  37902. out[13] = (top + bottom) * bt;
  37903. out[14] = (far + near) * nf;
  37904. out[15] = 1;
  37905. return out;
  37906. };
  37907. var isMobile = function isMobile() {
  37908. var check = false;
  37909. (function (a) {
  37910. 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;
  37911. })(navigator.userAgent || navigator.vendor || window.opera);
  37912. return check;
  37913. };
  37914. var extend = function extend(dest, src) {
  37915. for (var key in src) {
  37916. if (src.hasOwnProperty(key)) {
  37917. dest[key] = src[key];
  37918. }
  37919. }
  37920. return dest;
  37921. };
  37922. var safariCssSizeWorkaround = function safariCssSizeWorkaround(canvas) {
  37923. if (isIOS()) {
  37924. var width = canvas.style.width;
  37925. var height = canvas.style.height;
  37926. canvas.style.width = parseInt(width) + 1 + 'px';
  37927. canvas.style.height = parseInt(height) + 'px';
  37928. setTimeout(function () {
  37929. canvas.style.width = width;
  37930. canvas.style.height = height;
  37931. }, 100);
  37932. }
  37933. window.canvas = canvas;
  37934. };
  37935. var frameDataFromPose = function () {
  37936. var piOver180 = Math.PI / 180.0;
  37937. var rad45 = Math.PI * 0.25;
  37938. function mat4_perspectiveFromFieldOfView(out, fov, near, far) {
  37939. var upTan = Math.tan(fov ? fov.upDegrees * piOver180 : rad45),
  37940. downTan = Math.tan(fov ? fov.downDegrees * piOver180 : rad45),
  37941. leftTan = Math.tan(fov ? fov.leftDegrees * piOver180 : rad45),
  37942. rightTan = Math.tan(fov ? fov.rightDegrees * piOver180 : rad45),
  37943. xScale = 2.0 / (leftTan + rightTan),
  37944. yScale = 2.0 / (upTan + downTan);
  37945. out[0] = xScale;
  37946. out[1] = 0.0;
  37947. out[2] = 0.0;
  37948. out[3] = 0.0;
  37949. out[4] = 0.0;
  37950. out[5] = yScale;
  37951. out[6] = 0.0;
  37952. out[7] = 0.0;
  37953. out[8] = -((leftTan - rightTan) * xScale * 0.5);
  37954. out[9] = (upTan - downTan) * yScale * 0.5;
  37955. out[10] = far / (near - far);
  37956. out[11] = -1.0;
  37957. out[12] = 0.0;
  37958. out[13] = 0.0;
  37959. out[14] = far * near / (near - far);
  37960. out[15] = 0.0;
  37961. return out;
  37962. }
  37963. function mat4_fromRotationTranslation(out, q, v) {
  37964. var x = q[0],
  37965. y = q[1],
  37966. z = q[2],
  37967. w = q[3],
  37968. x2 = x + x,
  37969. y2 = y + y,
  37970. z2 = z + z,
  37971. xx = x * x2,
  37972. xy = x * y2,
  37973. xz = x * z2,
  37974. yy = y * y2,
  37975. yz = y * z2,
  37976. zz = z * z2,
  37977. wx = w * x2,
  37978. wy = w * y2,
  37979. wz = w * z2;
  37980. out[0] = 1 - (yy + zz);
  37981. out[1] = xy + wz;
  37982. out[2] = xz - wy;
  37983. out[3] = 0;
  37984. out[4] = xy - wz;
  37985. out[5] = 1 - (xx + zz);
  37986. out[6] = yz + wx;
  37987. out[7] = 0;
  37988. out[8] = xz + wy;
  37989. out[9] = yz - wx;
  37990. out[10] = 1 - (xx + yy);
  37991. out[11] = 0;
  37992. out[12] = v[0];
  37993. out[13] = v[1];
  37994. out[14] = v[2];
  37995. out[15] = 1;
  37996. return out;
  37997. }
  37998. function mat4_translate(out, a, v) {
  37999. var x = v[0],
  38000. y = v[1],
  38001. z = v[2],
  38002. a00,
  38003. a01,
  38004. a02,
  38005. a03,
  38006. a10,
  38007. a11,
  38008. a12,
  38009. a13,
  38010. a20,
  38011. a21,
  38012. a22,
  38013. a23;
  38014. if (a === out) {
  38015. out[12] = a[0] * x + a[4] * y + a[8] * z + a[12];
  38016. out[13] = a[1] * x + a[5] * y + a[9] * z + a[13];
  38017. out[14] = a[2] * x + a[6] * y + a[10] * z + a[14];
  38018. out[15] = a[3] * x + a[7] * y + a[11] * z + a[15];
  38019. } else {
  38020. a00 = a[0];a01 = a[1];a02 = a[2];a03 = a[3];
  38021. a10 = a[4];a11 = a[5];a12 = a[6];a13 = a[7];
  38022. a20 = a[8];a21 = a[9];a22 = a[10];a23 = a[11];
  38023. out[0] = a00;out[1] = a01;out[2] = a02;out[3] = a03;
  38024. out[4] = a10;out[5] = a11;out[6] = a12;out[7] = a13;
  38025. out[8] = a20;out[9] = a21;out[10] = a22;out[11] = a23;
  38026. out[12] = a00 * x + a10 * y + a20 * z + a[12];
  38027. out[13] = a01 * x + a11 * y + a21 * z + a[13];
  38028. out[14] = a02 * x + a12 * y + a22 * z + a[14];
  38029. out[15] = a03 * x + a13 * y + a23 * z + a[15];
  38030. }
  38031. return out;
  38032. }
  38033. function mat4_invert(out, a) {
  38034. var a00 = a[0],
  38035. a01 = a[1],
  38036. a02 = a[2],
  38037. a03 = a[3],
  38038. a10 = a[4],
  38039. a11 = a[5],
  38040. a12 = a[6],
  38041. a13 = a[7],
  38042. a20 = a[8],
  38043. a21 = a[9],
  38044. a22 = a[10],
  38045. a23 = a[11],
  38046. a30 = a[12],
  38047. a31 = a[13],
  38048. a32 = a[14],
  38049. a33 = a[15],
  38050. b00 = a00 * a11 - a01 * a10,
  38051. b01 = a00 * a12 - a02 * a10,
  38052. b02 = a00 * a13 - a03 * a10,
  38053. b03 = a01 * a12 - a02 * a11,
  38054. b04 = a01 * a13 - a03 * a11,
  38055. b05 = a02 * a13 - a03 * a12,
  38056. b06 = a20 * a31 - a21 * a30,
  38057. b07 = a20 * a32 - a22 * a30,
  38058. b08 = a20 * a33 - a23 * a30,
  38059. b09 = a21 * a32 - a22 * a31,
  38060. b10 = a21 * a33 - a23 * a31,
  38061. b11 = a22 * a33 - a23 * a32,
  38062. det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;
  38063. if (!det) {
  38064. return null;
  38065. }
  38066. det = 1.0 / det;
  38067. out[0] = (a11 * b11 - a12 * b10 + a13 * b09) * det;
  38068. out[1] = (a02 * b10 - a01 * b11 - a03 * b09) * det;
  38069. out[2] = (a31 * b05 - a32 * b04 + a33 * b03) * det;
  38070. out[3] = (a22 * b04 - a21 * b05 - a23 * b03) * det;
  38071. out[4] = (a12 * b08 - a10 * b11 - a13 * b07) * det;
  38072. out[5] = (a00 * b11 - a02 * b08 + a03 * b07) * det;
  38073. out[6] = (a32 * b02 - a30 * b05 - a33 * b01) * det;
  38074. out[7] = (a20 * b05 - a22 * b02 + a23 * b01) * det;
  38075. out[8] = (a10 * b10 - a11 * b08 + a13 * b06) * det;
  38076. out[9] = (a01 * b08 - a00 * b10 - a03 * b06) * det;
  38077. out[10] = (a30 * b04 - a31 * b02 + a33 * b00) * det;
  38078. out[11] = (a21 * b02 - a20 * b04 - a23 * b00) * det;
  38079. out[12] = (a11 * b07 - a10 * b09 - a12 * b06) * det;
  38080. out[13] = (a00 * b09 - a01 * b07 + a02 * b06) * det;
  38081. out[14] = (a31 * b01 - a30 * b03 - a32 * b00) * det;
  38082. out[15] = (a20 * b03 - a21 * b01 + a22 * b00) * det;
  38083. return out;
  38084. }
  38085. var defaultOrientation = new Float32Array([0, 0, 0, 1]);
  38086. var defaultPosition = new Float32Array([0, 0, 0]);
  38087. function updateEyeMatrices(projection, view, pose, fov, offset, vrDisplay) {
  38088. mat4_perspectiveFromFieldOfView(projection, fov || null, vrDisplay.depthNear, vrDisplay.depthFar);
  38089. var orientation = pose.orientation || defaultOrientation;
  38090. var position = pose.position || defaultPosition;
  38091. mat4_fromRotationTranslation(view, orientation, position);
  38092. if (offset) mat4_translate(view, view, offset);
  38093. mat4_invert(view, view);
  38094. }
  38095. return function (frameData, pose, vrDisplay) {
  38096. if (!frameData || !pose) return false;
  38097. frameData.pose = pose;
  38098. frameData.timestamp = pose.timestamp;
  38099. updateEyeMatrices(frameData.leftProjectionMatrix, frameData.leftViewMatrix, pose, vrDisplay._getFieldOfView("left"), vrDisplay._getEyeOffset("left"), vrDisplay);
  38100. updateEyeMatrices(frameData.rightProjectionMatrix, frameData.rightViewMatrix, pose, vrDisplay._getFieldOfView("right"), vrDisplay._getEyeOffset("right"), vrDisplay);
  38101. return true;
  38102. };
  38103. }();
  38104. var isInsideCrossOriginIFrame = function isInsideCrossOriginIFrame() {
  38105. var isFramed = window.self !== window.top;
  38106. var refOrigin = getOriginFromUrl(document.referrer);
  38107. var thisOrigin = getOriginFromUrl(window.location.href);
  38108. return isFramed && refOrigin !== thisOrigin;
  38109. };
  38110. var getOriginFromUrl = function getOriginFromUrl(url) {
  38111. var domainIdx;
  38112. var protoSepIdx = url.indexOf("://");
  38113. if (protoSepIdx !== -1) {
  38114. domainIdx = protoSepIdx + 3;
  38115. } else {
  38116. domainIdx = 0;
  38117. }
  38118. var domainEndIdx = url.indexOf('/', domainIdx);
  38119. if (domainEndIdx === -1) {
  38120. domainEndIdx = url.length;
  38121. }
  38122. return url.substring(0, domainEndIdx);
  38123. };
  38124. var getQuaternionAngle = function getQuaternionAngle(quat) {
  38125. if (quat.w > 1) {
  38126. console.warn('getQuaternionAngle: w > 1');
  38127. return 0;
  38128. }
  38129. var angle = 2 * Math.acos(quat.w);
  38130. return angle;
  38131. };
  38132. var warnOnce = function () {
  38133. var observedWarnings = {};
  38134. return function (key, message) {
  38135. if (observedWarnings[key] === undefined) {
  38136. console.warn('webvr-polyfill: ' + message);
  38137. observedWarnings[key] = true;
  38138. }
  38139. };
  38140. }();
  38141. var deprecateWarning = function deprecateWarning(deprecated, suggested) {
  38142. var alternative = suggested ? 'Please use ' + suggested + ' instead.' : '';
  38143. warnOnce(deprecated, deprecated + ' has been deprecated. ' + 'This may not work on native WebVR displays. ' + alternative);
  38144. };
  38145. function WGLUPreserveGLState(gl, bindings, callback) {
  38146. if (!bindings) {
  38147. callback(gl);
  38148. return;
  38149. }
  38150. var boundValues = [];
  38151. var activeTexture = null;
  38152. for (var i = 0; i < bindings.length; ++i) {
  38153. var binding = bindings[i];
  38154. switch (binding) {
  38155. case gl.TEXTURE_BINDING_2D:
  38156. case gl.TEXTURE_BINDING_CUBE_MAP:
  38157. var textureUnit = bindings[++i];
  38158. if (textureUnit < gl.TEXTURE0 || textureUnit > gl.TEXTURE31) {
  38159. console.error("TEXTURE_BINDING_2D or TEXTURE_BINDING_CUBE_MAP must be followed by a valid texture unit");
  38160. boundValues.push(null, null);
  38161. break;
  38162. }
  38163. if (!activeTexture) {
  38164. activeTexture = gl.getParameter(gl.ACTIVE_TEXTURE);
  38165. }
  38166. gl.activeTexture(textureUnit);
  38167. boundValues.push(gl.getParameter(binding), null);
  38168. break;
  38169. case gl.ACTIVE_TEXTURE:
  38170. activeTexture = gl.getParameter(gl.ACTIVE_TEXTURE);
  38171. boundValues.push(null);
  38172. break;
  38173. default:
  38174. boundValues.push(gl.getParameter(binding));
  38175. break;
  38176. }
  38177. }
  38178. callback(gl);
  38179. for (var i = 0; i < bindings.length; ++i) {
  38180. var binding = bindings[i];
  38181. var boundValue = boundValues[i];
  38182. switch (binding) {
  38183. case gl.ACTIVE_TEXTURE:
  38184. break;
  38185. case gl.ARRAY_BUFFER_BINDING:
  38186. gl.bindBuffer(gl.ARRAY_BUFFER, boundValue);
  38187. break;
  38188. case gl.COLOR_CLEAR_VALUE:
  38189. gl.clearColor(boundValue[0], boundValue[1], boundValue[2], boundValue[3]);
  38190. break;
  38191. case gl.COLOR_WRITEMASK:
  38192. gl.colorMask(boundValue[0], boundValue[1], boundValue[2], boundValue[3]);
  38193. break;
  38194. case gl.CURRENT_PROGRAM:
  38195. gl.useProgram(boundValue);
  38196. break;
  38197. case gl.ELEMENT_ARRAY_BUFFER_BINDING:
  38198. gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, boundValue);
  38199. break;
  38200. case gl.FRAMEBUFFER_BINDING:
  38201. gl.bindFramebuffer(gl.FRAMEBUFFER, boundValue);
  38202. break;
  38203. case gl.RENDERBUFFER_BINDING:
  38204. gl.bindRenderbuffer(gl.RENDERBUFFER, boundValue);
  38205. break;
  38206. case gl.TEXTURE_BINDING_2D:
  38207. var textureUnit = bindings[++i];
  38208. if (textureUnit < gl.TEXTURE0 || textureUnit > gl.TEXTURE31)
  38209. break;
  38210. gl.activeTexture(textureUnit);
  38211. gl.bindTexture(gl.TEXTURE_2D, boundValue);
  38212. break;
  38213. case gl.TEXTURE_BINDING_CUBE_MAP:
  38214. var textureUnit = bindings[++i];
  38215. if (textureUnit < gl.TEXTURE0 || textureUnit > gl.TEXTURE31)
  38216. break;
  38217. gl.activeTexture(textureUnit);
  38218. gl.bindTexture(gl.TEXTURE_CUBE_MAP, boundValue);
  38219. break;
  38220. case gl.VIEWPORT:
  38221. gl.viewport(boundValue[0], boundValue[1], boundValue[2], boundValue[3]);
  38222. break;
  38223. case gl.BLEND:
  38224. case gl.CULL_FACE:
  38225. case gl.DEPTH_TEST:
  38226. case gl.SCISSOR_TEST:
  38227. case gl.STENCIL_TEST:
  38228. if (boundValue) {
  38229. gl.enable(binding);
  38230. } else {
  38231. gl.disable(binding);
  38232. }
  38233. break;
  38234. default:
  38235. console.log("No GL restore behavior for 0x" + binding.toString(16));
  38236. break;
  38237. }
  38238. if (activeTexture) {
  38239. gl.activeTexture(activeTexture);
  38240. }
  38241. }
  38242. }
  38243. var glPreserveState = WGLUPreserveGLState;
  38244. 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');
  38245. var distortionFS = ['precision mediump float;', 'uniform sampler2D diffuse;', 'varying vec2 vTexCoord;', 'void main() {', ' gl_FragColor = texture2D(diffuse, vTexCoord);', '}'].join('\n');
  38246. function CardboardDistorter(gl, cardboardUI, bufferScale, dirtySubmitFrameBindings) {
  38247. this.gl = gl;
  38248. this.cardboardUI = cardboardUI;
  38249. this.bufferScale = bufferScale;
  38250. this.dirtySubmitFrameBindings = dirtySubmitFrameBindings;
  38251. this.ctxAttribs = gl.getContextAttributes();
  38252. this.meshWidth = 20;
  38253. this.meshHeight = 20;
  38254. this.bufferWidth = gl.drawingBufferWidth;
  38255. this.bufferHeight = gl.drawingBufferHeight;
  38256. this.realBindFramebuffer = gl.bindFramebuffer;
  38257. this.realEnable = gl.enable;
  38258. this.realDisable = gl.disable;
  38259. this.realColorMask = gl.colorMask;
  38260. this.realClearColor = gl.clearColor;
  38261. this.realViewport = gl.viewport;
  38262. if (!isIOS()) {
  38263. this.realCanvasWidth = Object.getOwnPropertyDescriptor(gl.canvas.__proto__, 'width');
  38264. this.realCanvasHeight = Object.getOwnPropertyDescriptor(gl.canvas.__proto__, 'height');
  38265. }
  38266. this.isPatched = false;
  38267. this.lastBoundFramebuffer = null;
  38268. this.cullFace = false;
  38269. this.depthTest = false;
  38270. this.blend = false;
  38271. this.scissorTest = false;
  38272. this.stencilTest = false;
  38273. this.viewport = [0, 0, 0, 0];
  38274. this.colorMask = [true, true, true, true];
  38275. this.clearColor = [0, 0, 0, 0];
  38276. this.attribs = {
  38277. position: 0,
  38278. texCoord: 1
  38279. };
  38280. this.program = linkProgram(gl, distortionVS, distortionFS, this.attribs);
  38281. this.uniforms = getProgramUniforms(gl, this.program);
  38282. this.viewportOffsetScale = new Float32Array(8);
  38283. this.setTextureBounds();
  38284. this.vertexBuffer = gl.createBuffer();
  38285. this.indexBuffer = gl.createBuffer();
  38286. this.indexCount = 0;
  38287. this.renderTarget = gl.createTexture();
  38288. this.framebuffer = gl.createFramebuffer();
  38289. this.depthStencilBuffer = null;
  38290. this.depthBuffer = null;
  38291. this.stencilBuffer = null;
  38292. if (this.ctxAttribs.depth && this.ctxAttribs.stencil) {
  38293. this.depthStencilBuffer = gl.createRenderbuffer();
  38294. } else if (this.ctxAttribs.depth) {
  38295. this.depthBuffer = gl.createRenderbuffer();
  38296. } else if (this.ctxAttribs.stencil) {
  38297. this.stencilBuffer = gl.createRenderbuffer();
  38298. }
  38299. this.patch();
  38300. this.onResize();
  38301. }
  38302. CardboardDistorter.prototype.destroy = function () {
  38303. var gl = this.gl;
  38304. this.unpatch();
  38305. gl.deleteProgram(this.program);
  38306. gl.deleteBuffer(this.vertexBuffer);
  38307. gl.deleteBuffer(this.indexBuffer);
  38308. gl.deleteTexture(this.renderTarget);
  38309. gl.deleteFramebuffer(this.framebuffer);
  38310. if (this.depthStencilBuffer) {
  38311. gl.deleteRenderbuffer(this.depthStencilBuffer);
  38312. }
  38313. if (this.depthBuffer) {
  38314. gl.deleteRenderbuffer(this.depthBuffer);
  38315. }
  38316. if (this.stencilBuffer) {
  38317. gl.deleteRenderbuffer(this.stencilBuffer);
  38318. }
  38319. if (this.cardboardUI) {
  38320. this.cardboardUI.destroy();
  38321. }
  38322. };
  38323. CardboardDistorter.prototype.onResize = function () {
  38324. var gl = this.gl;
  38325. var self = this;
  38326. var glState = [gl.RENDERBUFFER_BINDING, gl.TEXTURE_BINDING_2D, gl.TEXTURE0];
  38327. glPreserveState(gl, glState, function (gl) {
  38328. self.realBindFramebuffer.call(gl, gl.FRAMEBUFFER, null);
  38329. if (self.scissorTest) {
  38330. self.realDisable.call(gl, gl.SCISSOR_TEST);
  38331. }
  38332. self.realColorMask.call(gl, true, true, true, true);
  38333. self.realViewport.call(gl, 0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
  38334. self.realClearColor.call(gl, 0, 0, 0, 1);
  38335. gl.clear(gl.COLOR_BUFFER_BIT);
  38336. self.realBindFramebuffer.call(gl, gl.FRAMEBUFFER, self.framebuffer);
  38337. gl.bindTexture(gl.TEXTURE_2D, self.renderTarget);
  38338. 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);
  38339. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  38340. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  38341. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  38342. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  38343. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, self.renderTarget, 0);
  38344. if (self.ctxAttribs.depth && self.ctxAttribs.stencil) {
  38345. gl.bindRenderbuffer(gl.RENDERBUFFER, self.depthStencilBuffer);
  38346. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, self.bufferWidth, self.bufferHeight);
  38347. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, self.depthStencilBuffer);
  38348. } else if (self.ctxAttribs.depth) {
  38349. gl.bindRenderbuffer(gl.RENDERBUFFER, self.depthBuffer);
  38350. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, self.bufferWidth, self.bufferHeight);
  38351. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, self.depthBuffer);
  38352. } else if (self.ctxAttribs.stencil) {
  38353. gl.bindRenderbuffer(gl.RENDERBUFFER, self.stencilBuffer);
  38354. gl.renderbufferStorage(gl.RENDERBUFFER, gl.STENCIL_INDEX8, self.bufferWidth, self.bufferHeight);
  38355. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.STENCIL_ATTACHMENT, gl.RENDERBUFFER, self.stencilBuffer);
  38356. }
  38357. if (!gl.checkFramebufferStatus(gl.FRAMEBUFFER) === gl.FRAMEBUFFER_COMPLETE) {
  38358. console.error('Framebuffer incomplete!');
  38359. }
  38360. self.realBindFramebuffer.call(gl, gl.FRAMEBUFFER, self.lastBoundFramebuffer);
  38361. if (self.scissorTest) {
  38362. self.realEnable.call(gl, gl.SCISSOR_TEST);
  38363. }
  38364. self.realColorMask.apply(gl, self.colorMask);
  38365. self.realViewport.apply(gl, self.viewport);
  38366. self.realClearColor.apply(gl, self.clearColor);
  38367. });
  38368. if (this.cardboardUI) {
  38369. this.cardboardUI.onResize();
  38370. }
  38371. };
  38372. CardboardDistorter.prototype.patch = function () {
  38373. if (this.isPatched) {
  38374. return;
  38375. }
  38376. var self = this;
  38377. var canvas = this.gl.canvas;
  38378. var gl = this.gl;
  38379. if (!isIOS()) {
  38380. canvas.width = getScreenWidth() * this.bufferScale;
  38381. canvas.height = getScreenHeight() * this.bufferScale;
  38382. Object.defineProperty(canvas, 'width', {
  38383. configurable: true,
  38384. enumerable: true,
  38385. get: function get() {
  38386. return self.bufferWidth;
  38387. },
  38388. set: function set(value) {
  38389. self.bufferWidth = value;
  38390. self.realCanvasWidth.set.call(canvas, value);
  38391. self.onResize();
  38392. }
  38393. });
  38394. Object.defineProperty(canvas, 'height', {
  38395. configurable: true,
  38396. enumerable: true,
  38397. get: function get() {
  38398. return self.bufferHeight;
  38399. },
  38400. set: function set(value) {
  38401. self.bufferHeight = value;
  38402. self.realCanvasHeight.set.call(canvas, value);
  38403. self.onResize();
  38404. }
  38405. });
  38406. }
  38407. this.lastBoundFramebuffer = gl.getParameter(gl.FRAMEBUFFER_BINDING);
  38408. if (this.lastBoundFramebuffer == null) {
  38409. this.lastBoundFramebuffer = this.framebuffer;
  38410. this.gl.bindFramebuffer(gl.FRAMEBUFFER, this.framebuffer);
  38411. }
  38412. this.gl.bindFramebuffer = function (target, framebuffer) {
  38413. self.lastBoundFramebuffer = framebuffer ? framebuffer : self.framebuffer;
  38414. self.realBindFramebuffer.call(gl, target, self.lastBoundFramebuffer);
  38415. };
  38416. this.cullFace = gl.getParameter(gl.CULL_FACE);
  38417. this.depthTest = gl.getParameter(gl.DEPTH_TEST);
  38418. this.blend = gl.getParameter(gl.BLEND);
  38419. this.scissorTest = gl.getParameter(gl.SCISSOR_TEST);
  38420. this.stencilTest = gl.getParameter(gl.STENCIL_TEST);
  38421. gl.enable = function (pname) {
  38422. switch (pname) {
  38423. case gl.CULL_FACE:
  38424. self.cullFace = true;break;
  38425. case gl.DEPTH_TEST:
  38426. self.depthTest = true;break;
  38427. case gl.BLEND:
  38428. self.blend = true;break;
  38429. case gl.SCISSOR_TEST:
  38430. self.scissorTest = true;break;
  38431. case gl.STENCIL_TEST:
  38432. self.stencilTest = true;break;
  38433. }
  38434. self.realEnable.call(gl, pname);
  38435. };
  38436. gl.disable = function (pname) {
  38437. switch (pname) {
  38438. case gl.CULL_FACE:
  38439. self.cullFace = false;break;
  38440. case gl.DEPTH_TEST:
  38441. self.depthTest = false;break;
  38442. case gl.BLEND:
  38443. self.blend = false;break;
  38444. case gl.SCISSOR_TEST:
  38445. self.scissorTest = false;break;
  38446. case gl.STENCIL_TEST:
  38447. self.stencilTest = false;break;
  38448. }
  38449. self.realDisable.call(gl, pname);
  38450. };
  38451. this.colorMask = gl.getParameter(gl.COLOR_WRITEMASK);
  38452. gl.colorMask = function (r, g, b, a) {
  38453. self.colorMask[0] = r;
  38454. self.colorMask[1] = g;
  38455. self.colorMask[2] = b;
  38456. self.colorMask[3] = a;
  38457. self.realColorMask.call(gl, r, g, b, a);
  38458. };
  38459. this.clearColor = gl.getParameter(gl.COLOR_CLEAR_VALUE);
  38460. gl.clearColor = function (r, g, b, a) {
  38461. self.clearColor[0] = r;
  38462. self.clearColor[1] = g;
  38463. self.clearColor[2] = b;
  38464. self.clearColor[3] = a;
  38465. self.realClearColor.call(gl, r, g, b, a);
  38466. };
  38467. this.viewport = gl.getParameter(gl.VIEWPORT);
  38468. gl.viewport = function (x, y, w, h) {
  38469. self.viewport[0] = x;
  38470. self.viewport[1] = y;
  38471. self.viewport[2] = w;
  38472. self.viewport[3] = h;
  38473. self.realViewport.call(gl, x, y, w, h);
  38474. };
  38475. this.isPatched = true;
  38476. safariCssSizeWorkaround(canvas);
  38477. };
  38478. CardboardDistorter.prototype.unpatch = function () {
  38479. if (!this.isPatched) {
  38480. return;
  38481. }
  38482. var gl = this.gl;
  38483. var canvas = this.gl.canvas;
  38484. if (!isIOS()) {
  38485. Object.defineProperty(canvas, 'width', this.realCanvasWidth);
  38486. Object.defineProperty(canvas, 'height', this.realCanvasHeight);
  38487. }
  38488. canvas.width = this.bufferWidth;
  38489. canvas.height = this.bufferHeight;
  38490. gl.bindFramebuffer = this.realBindFramebuffer;
  38491. gl.enable = this.realEnable;
  38492. gl.disable = this.realDisable;
  38493. gl.colorMask = this.realColorMask;
  38494. gl.clearColor = this.realClearColor;
  38495. gl.viewport = this.realViewport;
  38496. if (this.lastBoundFramebuffer == this.framebuffer) {
  38497. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  38498. }
  38499. this.isPatched = false;
  38500. setTimeout(function () {
  38501. safariCssSizeWorkaround(canvas);
  38502. }, 1);
  38503. };
  38504. CardboardDistorter.prototype.setTextureBounds = function (leftBounds, rightBounds) {
  38505. if (!leftBounds) {
  38506. leftBounds = [0, 0, 0.5, 1];
  38507. }
  38508. if (!rightBounds) {
  38509. rightBounds = [0.5, 0, 0.5, 1];
  38510. }
  38511. this.viewportOffsetScale[0] = leftBounds[0];
  38512. this.viewportOffsetScale[1] = leftBounds[1];
  38513. this.viewportOffsetScale[2] = leftBounds[2];
  38514. this.viewportOffsetScale[3] = leftBounds[3];
  38515. this.viewportOffsetScale[4] = rightBounds[0];
  38516. this.viewportOffsetScale[5] = rightBounds[1];
  38517. this.viewportOffsetScale[6] = rightBounds[2];
  38518. this.viewportOffsetScale[7] = rightBounds[3];
  38519. };
  38520. CardboardDistorter.prototype.submitFrame = function () {
  38521. var gl = this.gl;
  38522. var self = this;
  38523. var glState = [];
  38524. if (!this.dirtySubmitFrameBindings) {
  38525. glState.push(gl.CURRENT_PROGRAM, gl.ARRAY_BUFFER_BINDING, gl.ELEMENT_ARRAY_BUFFER_BINDING, gl.TEXTURE_BINDING_2D, gl.TEXTURE0);
  38526. }
  38527. glPreserveState(gl, glState, function (gl) {
  38528. self.realBindFramebuffer.call(gl, gl.FRAMEBUFFER, null);
  38529. if (self.cullFace) {
  38530. self.realDisable.call(gl, gl.CULL_FACE);
  38531. }
  38532. if (self.depthTest) {
  38533. self.realDisable.call(gl, gl.DEPTH_TEST);
  38534. }
  38535. if (self.blend) {
  38536. self.realDisable.call(gl, gl.BLEND);
  38537. }
  38538. if (self.scissorTest) {
  38539. self.realDisable.call(gl, gl.SCISSOR_TEST);
  38540. }
  38541. if (self.stencilTest) {
  38542. self.realDisable.call(gl, gl.STENCIL_TEST);
  38543. }
  38544. self.realColorMask.call(gl, true, true, true, true);
  38545. self.realViewport.call(gl, 0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
  38546. if (self.ctxAttribs.alpha || isIOS()) {
  38547. self.realClearColor.call(gl, 0, 0, 0, 1);
  38548. gl.clear(gl.COLOR_BUFFER_BIT);
  38549. }
  38550. gl.useProgram(self.program);
  38551. gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, self.indexBuffer);
  38552. gl.bindBuffer(gl.ARRAY_BUFFER, self.vertexBuffer);
  38553. gl.enableVertexAttribArray(self.attribs.position);
  38554. gl.enableVertexAttribArray(self.attribs.texCoord);
  38555. gl.vertexAttribPointer(self.attribs.position, 2, gl.FLOAT, false, 20, 0);
  38556. gl.vertexAttribPointer(self.attribs.texCoord, 3, gl.FLOAT, false, 20, 8);
  38557. gl.activeTexture(gl.TEXTURE0);
  38558. gl.uniform1i(self.uniforms.diffuse, 0);
  38559. gl.bindTexture(gl.TEXTURE_2D, self.renderTarget);
  38560. gl.uniform4fv(self.uniforms.viewportOffsetScale, self.viewportOffsetScale);
  38561. gl.drawElements(gl.TRIANGLES, self.indexCount, gl.UNSIGNED_SHORT, 0);
  38562. if (self.cardboardUI) {
  38563. self.cardboardUI.renderNoState();
  38564. }
  38565. self.realBindFramebuffer.call(self.gl, gl.FRAMEBUFFER, self.framebuffer);
  38566. if (!self.ctxAttribs.preserveDrawingBuffer) {
  38567. self.realClearColor.call(gl, 0, 0, 0, 0);
  38568. gl.clear(gl.COLOR_BUFFER_BIT);
  38569. }
  38570. if (!self.dirtySubmitFrameBindings) {
  38571. self.realBindFramebuffer.call(gl, gl.FRAMEBUFFER, self.lastBoundFramebuffer);
  38572. }
  38573. if (self.cullFace) {
  38574. self.realEnable.call(gl, gl.CULL_FACE);
  38575. }
  38576. if (self.depthTest) {
  38577. self.realEnable.call(gl, gl.DEPTH_TEST);
  38578. }
  38579. if (self.blend) {
  38580. self.realEnable.call(gl, gl.BLEND);
  38581. }
  38582. if (self.scissorTest) {
  38583. self.realEnable.call(gl, gl.SCISSOR_TEST);
  38584. }
  38585. if (self.stencilTest) {
  38586. self.realEnable.call(gl, gl.STENCIL_TEST);
  38587. }
  38588. self.realColorMask.apply(gl, self.colorMask);
  38589. self.realViewport.apply(gl, self.viewport);
  38590. if (self.ctxAttribs.alpha || !self.ctxAttribs.preserveDrawingBuffer) {
  38591. self.realClearColor.apply(gl, self.clearColor);
  38592. }
  38593. });
  38594. if (isIOS()) {
  38595. var canvas = gl.canvas;
  38596. if (canvas.width != self.bufferWidth || canvas.height != self.bufferHeight) {
  38597. self.bufferWidth = canvas.width;
  38598. self.bufferHeight = canvas.height;
  38599. self.onResize();
  38600. }
  38601. }
  38602. };
  38603. CardboardDistorter.prototype.updateDeviceInfo = function (deviceInfo) {
  38604. var gl = this.gl;
  38605. var self = this;
  38606. var glState = [gl.ARRAY_BUFFER_BINDING, gl.ELEMENT_ARRAY_BUFFER_BINDING];
  38607. glPreserveState(gl, glState, function (gl) {
  38608. var vertices = self.computeMeshVertices_(self.meshWidth, self.meshHeight, deviceInfo);
  38609. gl.bindBuffer(gl.ARRAY_BUFFER, self.vertexBuffer);
  38610. gl.bufferData(gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW);
  38611. if (!self.indexCount) {
  38612. var indices = self.computeMeshIndices_(self.meshWidth, self.meshHeight);
  38613. gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, self.indexBuffer);
  38614. gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, indices, gl.STATIC_DRAW);
  38615. self.indexCount = indices.length;
  38616. }
  38617. });
  38618. };
  38619. CardboardDistorter.prototype.computeMeshVertices_ = function (width, height, deviceInfo) {
  38620. var vertices = new Float32Array(2 * width * height * 5);
  38621. var lensFrustum = deviceInfo.getLeftEyeVisibleTanAngles();
  38622. var noLensFrustum = deviceInfo.getLeftEyeNoLensTanAngles();
  38623. var viewport = deviceInfo.getLeftEyeVisibleScreenRect(noLensFrustum);
  38624. var vidx = 0;
  38625. for (var e = 0; e < 2; e++) {
  38626. for (var j = 0; j < height; j++) {
  38627. for (var i = 0; i < width; i++, vidx++) {
  38628. var u = i / (width - 1);
  38629. var v = j / (height - 1);
  38630. var s = u;
  38631. var t = v;
  38632. var x = lerp(lensFrustum[0], lensFrustum[2], u);
  38633. var y = lerp(lensFrustum[3], lensFrustum[1], v);
  38634. var d = Math.sqrt(x * x + y * y);
  38635. var r = deviceInfo.distortion.distortInverse(d);
  38636. var p = x * r / d;
  38637. var q = y * r / d;
  38638. u = (p - noLensFrustum[0]) / (noLensFrustum[2] - noLensFrustum[0]);
  38639. v = (q - noLensFrustum[3]) / (noLensFrustum[1] - noLensFrustum[3]);
  38640. u = (viewport.x + u * viewport.width - 0.5) * 2.0;
  38641. v = (viewport.y + v * viewport.height - 0.5) * 2.0;
  38642. vertices[vidx * 5 + 0] = u;
  38643. vertices[vidx * 5 + 1] = v;
  38644. vertices[vidx * 5 + 2] = s;
  38645. vertices[vidx * 5 + 3] = t;
  38646. vertices[vidx * 5 + 4] = e;
  38647. }
  38648. }
  38649. var w = lensFrustum[2] - lensFrustum[0];
  38650. lensFrustum[0] = -(w + lensFrustum[0]);
  38651. lensFrustum[2] = w - lensFrustum[2];
  38652. w = noLensFrustum[2] - noLensFrustum[0];
  38653. noLensFrustum[0] = -(w + noLensFrustum[0]);
  38654. noLensFrustum[2] = w - noLensFrustum[2];
  38655. viewport.x = 1 - (viewport.x + viewport.width);
  38656. }
  38657. return vertices;
  38658. };
  38659. CardboardDistorter.prototype.computeMeshIndices_ = function (width, height) {
  38660. var indices = new Uint16Array(2 * (width - 1) * (height - 1) * 6);
  38661. var halfwidth = width / 2;
  38662. var halfheight = height / 2;
  38663. var vidx = 0;
  38664. var iidx = 0;
  38665. for (var e = 0; e < 2; e++) {
  38666. for (var j = 0; j < height; j++) {
  38667. for (var i = 0; i < width; i++, vidx++) {
  38668. if (i == 0 || j == 0) continue;
  38669. if (i <= halfwidth == j <= halfheight) {
  38670. indices[iidx++] = vidx;
  38671. indices[iidx++] = vidx - width - 1;
  38672. indices[iidx++] = vidx - width;
  38673. indices[iidx++] = vidx - width - 1;
  38674. indices[iidx++] = vidx;
  38675. indices[iidx++] = vidx - 1;
  38676. } else {
  38677. indices[iidx++] = vidx - 1;
  38678. indices[iidx++] = vidx - width;
  38679. indices[iidx++] = vidx;
  38680. indices[iidx++] = vidx - width;
  38681. indices[iidx++] = vidx - 1;
  38682. indices[iidx++] = vidx - width - 1;
  38683. }
  38684. }
  38685. }
  38686. }
  38687. return indices;
  38688. };
  38689. CardboardDistorter.prototype.getOwnPropertyDescriptor_ = function (proto, attrName) {
  38690. var descriptor = Object.getOwnPropertyDescriptor(proto, attrName);
  38691. if (descriptor.get === undefined || descriptor.set === undefined) {
  38692. descriptor.configurable = true;
  38693. descriptor.enumerable = true;
  38694. descriptor.get = function () {
  38695. return this.getAttribute(attrName);
  38696. };
  38697. descriptor.set = function (val) {
  38698. this.setAttribute(attrName, val);
  38699. };
  38700. }
  38701. return descriptor;
  38702. };
  38703. var uiVS = ['attribute vec2 position;', 'uniform mat4 projectionMat;', 'void main() {', ' gl_Position = projectionMat * vec4( position, -1.0, 1.0 );', '}'].join('\n');
  38704. var uiFS = ['precision mediump float;', 'uniform vec4 color;', 'void main() {', ' gl_FragColor = color;', '}'].join('\n');
  38705. var DEG2RAD = Math.PI / 180.0;
  38706. var kAnglePerGearSection = 60;
  38707. var kOuterRimEndAngle = 12;
  38708. var kInnerRimBeginAngle = 20;
  38709. var kOuterRadius = 1;
  38710. var kMiddleRadius = 0.75;
  38711. var kInnerRadius = 0.3125;
  38712. var kCenterLineThicknessDp = 4;
  38713. var kButtonWidthDp = 28;
  38714. var kTouchSlopFactor = 1.5;
  38715. function CardboardUI(gl) {
  38716. this.gl = gl;
  38717. this.attribs = {
  38718. position: 0
  38719. };
  38720. this.program = linkProgram(gl, uiVS, uiFS, this.attribs);
  38721. this.uniforms = getProgramUniforms(gl, this.program);
  38722. this.vertexBuffer = gl.createBuffer();
  38723. this.gearOffset = 0;
  38724. this.gearVertexCount = 0;
  38725. this.arrowOffset = 0;
  38726. this.arrowVertexCount = 0;
  38727. this.projMat = new Float32Array(16);
  38728. this.listener = null;
  38729. this.onResize();
  38730. }
  38731. CardboardUI.prototype.destroy = function () {
  38732. var gl = this.gl;
  38733. if (this.listener) {
  38734. gl.canvas.removeEventListener('click', this.listener, false);
  38735. }
  38736. gl.deleteProgram(this.program);
  38737. gl.deleteBuffer(this.vertexBuffer);
  38738. };
  38739. CardboardUI.prototype.listen = function (optionsCallback, backCallback) {
  38740. var canvas = this.gl.canvas;
  38741. this.listener = function (event) {
  38742. var midline = canvas.clientWidth / 2;
  38743. var buttonSize = kButtonWidthDp * kTouchSlopFactor;
  38744. if (event.clientX > midline - buttonSize && event.clientX < midline + buttonSize && event.clientY > canvas.clientHeight - buttonSize) {
  38745. optionsCallback(event);
  38746. }
  38747. else if (event.clientX < buttonSize && event.clientY < buttonSize) {
  38748. backCallback(event);
  38749. }
  38750. };
  38751. canvas.addEventListener('click', this.listener, false);
  38752. };
  38753. CardboardUI.prototype.onResize = function () {
  38754. var gl = this.gl;
  38755. var self = this;
  38756. var glState = [gl.ARRAY_BUFFER_BINDING];
  38757. glPreserveState(gl, glState, function (gl) {
  38758. var vertices = [];
  38759. var midline = gl.drawingBufferWidth / 2;
  38760. var physicalPixels = Math.max(screen.width, screen.height) * window.devicePixelRatio;
  38761. var scalingRatio = gl.drawingBufferWidth / physicalPixels;
  38762. var dps = scalingRatio * window.devicePixelRatio;
  38763. var lineWidth = kCenterLineThicknessDp * dps / 2;
  38764. var buttonSize = kButtonWidthDp * kTouchSlopFactor * dps;
  38765. var buttonScale = kButtonWidthDp * dps / 2;
  38766. var buttonBorder = (kButtonWidthDp * kTouchSlopFactor - kButtonWidthDp) * dps;
  38767. vertices.push(midline - lineWidth, buttonSize);
  38768. vertices.push(midline - lineWidth, gl.drawingBufferHeight);
  38769. vertices.push(midline + lineWidth, buttonSize);
  38770. vertices.push(midline + lineWidth, gl.drawingBufferHeight);
  38771. self.gearOffset = vertices.length / 2;
  38772. function addGearSegment(theta, r) {
  38773. var angle = (90 - theta) * DEG2RAD;
  38774. var x = Math.cos(angle);
  38775. var y = Math.sin(angle);
  38776. vertices.push(kInnerRadius * x * buttonScale + midline, kInnerRadius * y * buttonScale + buttonScale);
  38777. vertices.push(r * x * buttonScale + midline, r * y * buttonScale + buttonScale);
  38778. }
  38779. for (var i = 0; i <= 6; i++) {
  38780. var segmentTheta = i * kAnglePerGearSection;
  38781. addGearSegment(segmentTheta, kOuterRadius);
  38782. addGearSegment(segmentTheta + kOuterRimEndAngle, kOuterRadius);
  38783. addGearSegment(segmentTheta + kInnerRimBeginAngle, kMiddleRadius);
  38784. addGearSegment(segmentTheta + (kAnglePerGearSection - kInnerRimBeginAngle), kMiddleRadius);
  38785. addGearSegment(segmentTheta + (kAnglePerGearSection - kOuterRimEndAngle), kOuterRadius);
  38786. }
  38787. self.gearVertexCount = vertices.length / 2 - self.gearOffset;
  38788. self.arrowOffset = vertices.length / 2;
  38789. function addArrowVertex(x, y) {
  38790. vertices.push(buttonBorder + x, gl.drawingBufferHeight - buttonBorder - y);
  38791. }
  38792. var angledLineWidth = lineWidth / Math.sin(45 * DEG2RAD);
  38793. addArrowVertex(0, buttonScale);
  38794. addArrowVertex(buttonScale, 0);
  38795. addArrowVertex(buttonScale + angledLineWidth, angledLineWidth);
  38796. addArrowVertex(angledLineWidth, buttonScale + angledLineWidth);
  38797. addArrowVertex(angledLineWidth, buttonScale - angledLineWidth);
  38798. addArrowVertex(0, buttonScale);
  38799. addArrowVertex(buttonScale, buttonScale * 2);
  38800. addArrowVertex(buttonScale + angledLineWidth, buttonScale * 2 - angledLineWidth);
  38801. addArrowVertex(angledLineWidth, buttonScale - angledLineWidth);
  38802. addArrowVertex(0, buttonScale);
  38803. addArrowVertex(angledLineWidth, buttonScale - lineWidth);
  38804. addArrowVertex(kButtonWidthDp * dps, buttonScale - lineWidth);
  38805. addArrowVertex(angledLineWidth, buttonScale + lineWidth);
  38806. addArrowVertex(kButtonWidthDp * dps, buttonScale + lineWidth);
  38807. self.arrowVertexCount = vertices.length / 2 - self.arrowOffset;
  38808. gl.bindBuffer(gl.ARRAY_BUFFER, self.vertexBuffer);
  38809. gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW);
  38810. });
  38811. };
  38812. CardboardUI.prototype.render = function () {
  38813. var gl = this.gl;
  38814. var self = this;
  38815. 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];
  38816. glPreserveState(gl, glState, function (gl) {
  38817. gl.disable(gl.CULL_FACE);
  38818. gl.disable(gl.DEPTH_TEST);
  38819. gl.disable(gl.BLEND);
  38820. gl.disable(gl.SCISSOR_TEST);
  38821. gl.disable(gl.STENCIL_TEST);
  38822. gl.colorMask(true, true, true, true);
  38823. gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
  38824. self.renderNoState();
  38825. });
  38826. };
  38827. CardboardUI.prototype.renderNoState = function () {
  38828. var gl = this.gl;
  38829. gl.useProgram(this.program);
  38830. gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer);
  38831. gl.enableVertexAttribArray(this.attribs.position);
  38832. gl.vertexAttribPointer(this.attribs.position, 2, gl.FLOAT, false, 8, 0);
  38833. gl.uniform4f(this.uniforms.color, 1.0, 1.0, 1.0, 1.0);
  38834. orthoMatrix(this.projMat, 0, gl.drawingBufferWidth, 0, gl.drawingBufferHeight, 0.1, 1024.0);
  38835. gl.uniformMatrix4fv(this.uniforms.projectionMat, false, this.projMat);
  38836. gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
  38837. gl.drawArrays(gl.TRIANGLE_STRIP, this.gearOffset, this.gearVertexCount);
  38838. gl.drawArrays(gl.TRIANGLE_STRIP, this.arrowOffset, this.arrowVertexCount);
  38839. };
  38840. function Distortion(coefficients) {
  38841. this.coefficients = coefficients;
  38842. }
  38843. Distortion.prototype.distortInverse = function (radius) {
  38844. var r0 = 0;
  38845. var r1 = 1;
  38846. var dr0 = radius - this.distort(r0);
  38847. while (Math.abs(r1 - r0) > 0.0001 ) {
  38848. var dr1 = radius - this.distort(r1);
  38849. var r2 = r1 - dr1 * ((r1 - r0) / (dr1 - dr0));
  38850. r0 = r1;
  38851. r1 = r2;
  38852. dr0 = dr1;
  38853. }
  38854. return r1;
  38855. };
  38856. Distortion.prototype.distort = function (radius) {
  38857. var r2 = radius * radius;
  38858. var ret = 0;
  38859. for (var i = 0; i < this.coefficients.length; i++) {
  38860. ret = r2 * (ret + this.coefficients[i]);
  38861. }
  38862. return (ret + 1) * radius;
  38863. };
  38864. var degToRad = Math.PI / 180;
  38865. var radToDeg = 180 / Math.PI;
  38866. var Vector3 = function Vector3(x, y, z) {
  38867. this.x = x || 0;
  38868. this.y = y || 0;
  38869. this.z = z || 0;
  38870. };
  38871. Vector3.prototype = {
  38872. constructor: Vector3,
  38873. set: function set(x, y, z) {
  38874. this.x = x;
  38875. this.y = y;
  38876. this.z = z;
  38877. return this;
  38878. },
  38879. copy: function copy(v) {
  38880. this.x = v.x;
  38881. this.y = v.y;
  38882. this.z = v.z;
  38883. return this;
  38884. },
  38885. length: function length() {
  38886. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  38887. },
  38888. normalize: function normalize() {
  38889. var scalar = this.length();
  38890. if (scalar !== 0) {
  38891. var invScalar = 1 / scalar;
  38892. this.multiplyScalar(invScalar);
  38893. } else {
  38894. this.x = 0;
  38895. this.y = 0;
  38896. this.z = 0;
  38897. }
  38898. return this;
  38899. },
  38900. multiplyScalar: function multiplyScalar(scalar) {
  38901. this.x *= scalar;
  38902. this.y *= scalar;
  38903. this.z *= scalar;
  38904. },
  38905. applyQuaternion: function applyQuaternion(q) {
  38906. var x = this.x;
  38907. var y = this.y;
  38908. var z = this.z;
  38909. var qx = q.x;
  38910. var qy = q.y;
  38911. var qz = q.z;
  38912. var qw = q.w;
  38913. var ix = qw * x + qy * z - qz * y;
  38914. var iy = qw * y + qz * x - qx * z;
  38915. var iz = qw * z + qx * y - qy * x;
  38916. var iw = -qx * x - qy * y - qz * z;
  38917. this.x = ix * qw + iw * -qx + iy * -qz - iz * -qy;
  38918. this.y = iy * qw + iw * -qy + iz * -qx - ix * -qz;
  38919. this.z = iz * qw + iw * -qz + ix * -qy - iy * -qx;
  38920. return this;
  38921. },
  38922. dot: function dot(v) {
  38923. return this.x * v.x + this.y * v.y + this.z * v.z;
  38924. },
  38925. crossVectors: function crossVectors(a, b) {
  38926. var ax = a.x,
  38927. ay = a.y,
  38928. az = a.z;
  38929. var bx = b.x,
  38930. by = b.y,
  38931. bz = b.z;
  38932. this.x = ay * bz - az * by;
  38933. this.y = az * bx - ax * bz;
  38934. this.z = ax * by - ay * bx;
  38935. return this;
  38936. }
  38937. };
  38938. var Quaternion = function Quaternion(x, y, z, w) {
  38939. this.x = x || 0;
  38940. this.y = y || 0;
  38941. this.z = z || 0;
  38942. this.w = w !== undefined ? w : 1;
  38943. };
  38944. Quaternion.prototype = {
  38945. constructor: Quaternion,
  38946. set: function set(x, y, z, w) {
  38947. this.x = x;
  38948. this.y = y;
  38949. this.z = z;
  38950. this.w = w;
  38951. return this;
  38952. },
  38953. copy: function copy(quaternion) {
  38954. this.x = quaternion.x;
  38955. this.y = quaternion.y;
  38956. this.z = quaternion.z;
  38957. this.w = quaternion.w;
  38958. return this;
  38959. },
  38960. setFromEulerXYZ: function setFromEulerXYZ(x, y, z) {
  38961. var c1 = Math.cos(x / 2);
  38962. var c2 = Math.cos(y / 2);
  38963. var c3 = Math.cos(z / 2);
  38964. var s1 = Math.sin(x / 2);
  38965. var s2 = Math.sin(y / 2);
  38966. var s3 = Math.sin(z / 2);
  38967. this.x = s1 * c2 * c3 + c1 * s2 * s3;
  38968. this.y = c1 * s2 * c3 - s1 * c2 * s3;
  38969. this.z = c1 * c2 * s3 + s1 * s2 * c3;
  38970. this.w = c1 * c2 * c3 - s1 * s2 * s3;
  38971. return this;
  38972. },
  38973. setFromEulerYXZ: function setFromEulerYXZ(x, y, z) {
  38974. var c1 = Math.cos(x / 2);
  38975. var c2 = Math.cos(y / 2);
  38976. var c3 = Math.cos(z / 2);
  38977. var s1 = Math.sin(x / 2);
  38978. var s2 = Math.sin(y / 2);
  38979. var s3 = Math.sin(z / 2);
  38980. this.x = s1 * c2 * c3 + c1 * s2 * s3;
  38981. this.y = c1 * s2 * c3 - s1 * c2 * s3;
  38982. this.z = c1 * c2 * s3 - s1 * s2 * c3;
  38983. this.w = c1 * c2 * c3 + s1 * s2 * s3;
  38984. return this;
  38985. },
  38986. setFromAxisAngle: function setFromAxisAngle(axis, angle) {
  38987. var halfAngle = angle / 2,
  38988. s = Math.sin(halfAngle);
  38989. this.x = axis.x * s;
  38990. this.y = axis.y * s;
  38991. this.z = axis.z * s;
  38992. this.w = Math.cos(halfAngle);
  38993. return this;
  38994. },
  38995. multiply: function multiply(q) {
  38996. return this.multiplyQuaternions(this, q);
  38997. },
  38998. multiplyQuaternions: function multiplyQuaternions(a, b) {
  38999. var qax = a.x,
  39000. qay = a.y,
  39001. qaz = a.z,
  39002. qaw = a.w;
  39003. var qbx = b.x,
  39004. qby = b.y,
  39005. qbz = b.z,
  39006. qbw = b.w;
  39007. this.x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  39008. this.y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  39009. this.z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  39010. this.w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  39011. return this;
  39012. },
  39013. inverse: function inverse() {
  39014. this.x *= -1;
  39015. this.y *= -1;
  39016. this.z *= -1;
  39017. this.normalize();
  39018. return this;
  39019. },
  39020. normalize: function normalize() {
  39021. var l = Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  39022. if (l === 0) {
  39023. this.x = 0;
  39024. this.y = 0;
  39025. this.z = 0;
  39026. this.w = 1;
  39027. } else {
  39028. l = 1 / l;
  39029. this.x = this.x * l;
  39030. this.y = this.y * l;
  39031. this.z = this.z * l;
  39032. this.w = this.w * l;
  39033. }
  39034. return this;
  39035. },
  39036. slerp: function slerp(qb, t) {
  39037. if (t === 0) return this;
  39038. if (t === 1) return this.copy(qb);
  39039. var x = this.x,
  39040. y = this.y,
  39041. z = this.z,
  39042. w = this.w;
  39043. var cosHalfTheta = w * qb.w + x * qb.x + y * qb.y + z * qb.z;
  39044. if (cosHalfTheta < 0) {
  39045. this.w = -qb.w;
  39046. this.x = -qb.x;
  39047. this.y = -qb.y;
  39048. this.z = -qb.z;
  39049. cosHalfTheta = -cosHalfTheta;
  39050. } else {
  39051. this.copy(qb);
  39052. }
  39053. if (cosHalfTheta >= 1.0) {
  39054. this.w = w;
  39055. this.x = x;
  39056. this.y = y;
  39057. this.z = z;
  39058. return this;
  39059. }
  39060. var halfTheta = Math.acos(cosHalfTheta);
  39061. var sinHalfTheta = Math.sqrt(1.0 - cosHalfTheta * cosHalfTheta);
  39062. if (Math.abs(sinHalfTheta) < 0.001) {
  39063. this.w = 0.5 * (w + this.w);
  39064. this.x = 0.5 * (x + this.x);
  39065. this.y = 0.5 * (y + this.y);
  39066. this.z = 0.5 * (z + this.z);
  39067. return this;
  39068. }
  39069. var ratioA = Math.sin((1 - t) * halfTheta) / sinHalfTheta,
  39070. ratioB = Math.sin(t * halfTheta) / sinHalfTheta;
  39071. this.w = w * ratioA + this.w * ratioB;
  39072. this.x = x * ratioA + this.x * ratioB;
  39073. this.y = y * ratioA + this.y * ratioB;
  39074. this.z = z * ratioA + this.z * ratioB;
  39075. return this;
  39076. },
  39077. setFromUnitVectors: function () {
  39078. var v1, r;
  39079. var EPS = 0.000001;
  39080. return function (vFrom, vTo) {
  39081. if (v1 === undefined) v1 = new Vector3();
  39082. r = vFrom.dot(vTo) + 1;
  39083. if (r < EPS) {
  39084. r = 0;
  39085. if (Math.abs(vFrom.x) > Math.abs(vFrom.z)) {
  39086. v1.set(-vFrom.y, vFrom.x, 0);
  39087. } else {
  39088. v1.set(0, -vFrom.z, vFrom.y);
  39089. }
  39090. } else {
  39091. v1.crossVectors(vFrom, vTo);
  39092. }
  39093. this.x = v1.x;
  39094. this.y = v1.y;
  39095. this.z = v1.z;
  39096. this.w = r;
  39097. this.normalize();
  39098. return this;
  39099. };
  39100. }()
  39101. };
  39102. function Device(params) {
  39103. this.width = params.width || getScreenWidth();
  39104. this.height = params.height || getScreenHeight();
  39105. this.widthMeters = params.widthMeters;
  39106. this.heightMeters = params.heightMeters;
  39107. this.bevelMeters = params.bevelMeters;
  39108. }
  39109. var DEFAULT_ANDROID = new Device({
  39110. widthMeters: 0.110,
  39111. heightMeters: 0.062,
  39112. bevelMeters: 0.004
  39113. });
  39114. var DEFAULT_IOS = new Device({
  39115. widthMeters: 0.1038,
  39116. heightMeters: 0.0584,
  39117. bevelMeters: 0.004
  39118. });
  39119. var Viewers = {
  39120. CardboardV1: new CardboardViewer({
  39121. id: 'CardboardV1',
  39122. label: 'Cardboard I/O 2014',
  39123. fov: 40,
  39124. interLensDistance: 0.060,
  39125. baselineLensDistance: 0.035,
  39126. screenLensDistance: 0.042,
  39127. distortionCoefficients: [0.441, 0.156],
  39128. 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]
  39129. }),
  39130. CardboardV2: new CardboardViewer({
  39131. id: 'CardboardV2',
  39132. label: 'Cardboard I/O 2015',
  39133. fov: 60,
  39134. interLensDistance: 0.064,
  39135. baselineLensDistance: 0.035,
  39136. screenLensDistance: 0.039,
  39137. distortionCoefficients: [0.34, 0.55],
  39138. 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]
  39139. })
  39140. };
  39141. function DeviceInfo(deviceParams, additionalViewers) {
  39142. this.viewer = Viewers.CardboardV2;
  39143. this.updateDeviceParams(deviceParams);
  39144. this.distortion = new Distortion(this.viewer.distortionCoefficients);
  39145. for (var i = 0; i < additionalViewers.length; i++) {
  39146. var viewer = additionalViewers[i];
  39147. Viewers[viewer.id] = new CardboardViewer(viewer);
  39148. }
  39149. }
  39150. DeviceInfo.prototype.updateDeviceParams = function (deviceParams) {
  39151. this.device = this.determineDevice_(deviceParams) || this.device;
  39152. };
  39153. DeviceInfo.prototype.getDevice = function () {
  39154. return this.device;
  39155. };
  39156. DeviceInfo.prototype.setViewer = function (viewer) {
  39157. this.viewer = viewer;
  39158. this.distortion = new Distortion(this.viewer.distortionCoefficients);
  39159. };
  39160. DeviceInfo.prototype.determineDevice_ = function (deviceParams) {
  39161. if (!deviceParams) {
  39162. if (isIOS()) {
  39163. console.warn('Using fallback iOS device measurements.');
  39164. return DEFAULT_IOS;
  39165. } else {
  39166. console.warn('Using fallback Android device measurements.');
  39167. return DEFAULT_ANDROID;
  39168. }
  39169. }
  39170. var METERS_PER_INCH = 0.0254;
  39171. var metersPerPixelX = METERS_PER_INCH / deviceParams.xdpi;
  39172. var metersPerPixelY = METERS_PER_INCH / deviceParams.ydpi;
  39173. var width = getScreenWidth();
  39174. var height = getScreenHeight();
  39175. return new Device({
  39176. widthMeters: metersPerPixelX * width,
  39177. heightMeters: metersPerPixelY * height,
  39178. bevelMeters: deviceParams.bevelMm * 0.001
  39179. });
  39180. };
  39181. DeviceInfo.prototype.getDistortedFieldOfViewLeftEye = function () {
  39182. var viewer = this.viewer;
  39183. var device = this.device;
  39184. var distortion = this.distortion;
  39185. var eyeToScreenDistance = viewer.screenLensDistance;
  39186. var outerDist = (device.widthMeters - viewer.interLensDistance) / 2;
  39187. var innerDist = viewer.interLensDistance / 2;
  39188. var bottomDist = viewer.baselineLensDistance - device.bevelMeters;
  39189. var topDist = device.heightMeters - bottomDist;
  39190. var outerAngle = radToDeg * Math.atan(distortion.distort(outerDist / eyeToScreenDistance));
  39191. var innerAngle = radToDeg * Math.atan(distortion.distort(innerDist / eyeToScreenDistance));
  39192. var bottomAngle = radToDeg * Math.atan(distortion.distort(bottomDist / eyeToScreenDistance));
  39193. var topAngle = radToDeg * Math.atan(distortion.distort(topDist / eyeToScreenDistance));
  39194. return {
  39195. leftDegrees: Math.min(outerAngle, viewer.fov),
  39196. rightDegrees: Math.min(innerAngle, viewer.fov),
  39197. downDegrees: Math.min(bottomAngle, viewer.fov),
  39198. upDegrees: Math.min(topAngle, viewer.fov)
  39199. };
  39200. };
  39201. DeviceInfo.prototype.getLeftEyeVisibleTanAngles = function () {
  39202. var viewer = this.viewer;
  39203. var device = this.device;
  39204. var distortion = this.distortion;
  39205. var fovLeft = Math.tan(-degToRad * viewer.fov);
  39206. var fovTop = Math.tan(degToRad * viewer.fov);
  39207. var fovRight = Math.tan(degToRad * viewer.fov);
  39208. var fovBottom = Math.tan(-degToRad * viewer.fov);
  39209. var halfWidth = device.widthMeters / 4;
  39210. var halfHeight = device.heightMeters / 2;
  39211. var verticalLensOffset = viewer.baselineLensDistance - device.bevelMeters - halfHeight;
  39212. var centerX = viewer.interLensDistance / 2 - halfWidth;
  39213. var centerY = -verticalLensOffset;
  39214. var centerZ = viewer.screenLensDistance;
  39215. var screenLeft = distortion.distort((centerX - halfWidth) / centerZ);
  39216. var screenTop = distortion.distort((centerY + halfHeight) / centerZ);
  39217. var screenRight = distortion.distort((centerX + halfWidth) / centerZ);
  39218. var screenBottom = distortion.distort((centerY - halfHeight) / centerZ);
  39219. var result = new Float32Array(4);
  39220. result[0] = Math.max(fovLeft, screenLeft);
  39221. result[1] = Math.min(fovTop, screenTop);
  39222. result[2] = Math.min(fovRight, screenRight);
  39223. result[3] = Math.max(fovBottom, screenBottom);
  39224. return result;
  39225. };
  39226. DeviceInfo.prototype.getLeftEyeNoLensTanAngles = function () {
  39227. var viewer = this.viewer;
  39228. var device = this.device;
  39229. var distortion = this.distortion;
  39230. var result = new Float32Array(4);
  39231. var fovLeft = distortion.distortInverse(Math.tan(-degToRad * viewer.fov));
  39232. var fovTop = distortion.distortInverse(Math.tan(degToRad * viewer.fov));
  39233. var fovRight = distortion.distortInverse(Math.tan(degToRad * viewer.fov));
  39234. var fovBottom = distortion.distortInverse(Math.tan(-degToRad * viewer.fov));
  39235. var halfWidth = device.widthMeters / 4;
  39236. var halfHeight = device.heightMeters / 2;
  39237. var verticalLensOffset = viewer.baselineLensDistance - device.bevelMeters - halfHeight;
  39238. var centerX = viewer.interLensDistance / 2 - halfWidth;
  39239. var centerY = -verticalLensOffset;
  39240. var centerZ = viewer.screenLensDistance;
  39241. var screenLeft = (centerX - halfWidth) / centerZ;
  39242. var screenTop = (centerY + halfHeight) / centerZ;
  39243. var screenRight = (centerX + halfWidth) / centerZ;
  39244. var screenBottom = (centerY - halfHeight) / centerZ;
  39245. result[0] = Math.max(fovLeft, screenLeft);
  39246. result[1] = Math.min(fovTop, screenTop);
  39247. result[2] = Math.min(fovRight, screenRight);
  39248. result[3] = Math.max(fovBottom, screenBottom);
  39249. return result;
  39250. };
  39251. DeviceInfo.prototype.getLeftEyeVisibleScreenRect = function (undistortedFrustum) {
  39252. var viewer = this.viewer;
  39253. var device = this.device;
  39254. var dist = viewer.screenLensDistance;
  39255. var eyeX = (device.widthMeters - viewer.interLensDistance) / 2;
  39256. var eyeY = viewer.baselineLensDistance - device.bevelMeters;
  39257. var left = (undistortedFrustum[0] * dist + eyeX) / device.widthMeters;
  39258. var top = (undistortedFrustum[1] * dist + eyeY) / device.heightMeters;
  39259. var right = (undistortedFrustum[2] * dist + eyeX) / device.widthMeters;
  39260. var bottom = (undistortedFrustum[3] * dist + eyeY) / device.heightMeters;
  39261. return {
  39262. x: left,
  39263. y: bottom,
  39264. width: right - left,
  39265. height: top - bottom
  39266. };
  39267. };
  39268. DeviceInfo.prototype.getFieldOfViewLeftEye = function (opt_isUndistorted) {
  39269. return opt_isUndistorted ? this.getUndistortedFieldOfViewLeftEye() : this.getDistortedFieldOfViewLeftEye();
  39270. };
  39271. DeviceInfo.prototype.getFieldOfViewRightEye = function (opt_isUndistorted) {
  39272. var fov = this.getFieldOfViewLeftEye(opt_isUndistorted);
  39273. return {
  39274. leftDegrees: fov.rightDegrees,
  39275. rightDegrees: fov.leftDegrees,
  39276. upDegrees: fov.upDegrees,
  39277. downDegrees: fov.downDegrees
  39278. };
  39279. };
  39280. DeviceInfo.prototype.getUndistortedFieldOfViewLeftEye = function () {
  39281. var p = this.getUndistortedParams_();
  39282. return {
  39283. leftDegrees: radToDeg * Math.atan(p.outerDist),
  39284. rightDegrees: radToDeg * Math.atan(p.innerDist),
  39285. downDegrees: radToDeg * Math.atan(p.bottomDist),
  39286. upDegrees: radToDeg * Math.atan(p.topDist)
  39287. };
  39288. };
  39289. DeviceInfo.prototype.getUndistortedViewportLeftEye = function () {
  39290. var p = this.getUndistortedParams_();
  39291. var viewer = this.viewer;
  39292. var device = this.device;
  39293. var eyeToScreenDistance = viewer.screenLensDistance;
  39294. var screenWidth = device.widthMeters / eyeToScreenDistance;
  39295. var screenHeight = device.heightMeters / eyeToScreenDistance;
  39296. var xPxPerTanAngle = device.width / screenWidth;
  39297. var yPxPerTanAngle = device.height / screenHeight;
  39298. var x = Math.round((p.eyePosX - p.outerDist) * xPxPerTanAngle);
  39299. var y = Math.round((p.eyePosY - p.bottomDist) * yPxPerTanAngle);
  39300. return {
  39301. x: x,
  39302. y: y,
  39303. width: Math.round((p.eyePosX + p.innerDist) * xPxPerTanAngle) - x,
  39304. height: Math.round((p.eyePosY + p.topDist) * yPxPerTanAngle) - y
  39305. };
  39306. };
  39307. DeviceInfo.prototype.getUndistortedParams_ = function () {
  39308. var viewer = this.viewer;
  39309. var device = this.device;
  39310. var distortion = this.distortion;
  39311. var eyeToScreenDistance = viewer.screenLensDistance;
  39312. var halfLensDistance = viewer.interLensDistance / 2 / eyeToScreenDistance;
  39313. var screenWidth = device.widthMeters / eyeToScreenDistance;
  39314. var screenHeight = device.heightMeters / eyeToScreenDistance;
  39315. var eyePosX = screenWidth / 2 - halfLensDistance;
  39316. var eyePosY = (viewer.baselineLensDistance - device.bevelMeters) / eyeToScreenDistance;
  39317. var maxFov = viewer.fov;
  39318. var viewerMax = distortion.distortInverse(Math.tan(degToRad * maxFov));
  39319. var outerDist = Math.min(eyePosX, viewerMax);
  39320. var innerDist = Math.min(halfLensDistance, viewerMax);
  39321. var bottomDist = Math.min(eyePosY, viewerMax);
  39322. var topDist = Math.min(screenHeight - eyePosY, viewerMax);
  39323. return {
  39324. outerDist: outerDist,
  39325. innerDist: innerDist,
  39326. topDist: topDist,
  39327. bottomDist: bottomDist,
  39328. eyePosX: eyePosX,
  39329. eyePosY: eyePosY
  39330. };
  39331. };
  39332. function CardboardViewer(params) {
  39333. this.id = params.id;
  39334. this.label = params.label;
  39335. this.fov = params.fov;
  39336. this.interLensDistance = params.interLensDistance;
  39337. this.baselineLensDistance = params.baselineLensDistance;
  39338. this.screenLensDistance = params.screenLensDistance;
  39339. this.distortionCoefficients = params.distortionCoefficients;
  39340. this.inverseCoefficients = params.inverseCoefficients;
  39341. }
  39342. DeviceInfo.Viewers = Viewers;
  39343. var format = 1;
  39344. var last_updated = "2018-12-10T17:01:42Z";
  39345. 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}];
  39346. var DPDB_CACHE = {
  39347. format: format,
  39348. last_updated: last_updated,
  39349. devices: devices
  39350. };
  39351. function Dpdb(url, onDeviceParamsUpdated) {
  39352. this.dpdb = DPDB_CACHE;
  39353. this.recalculateDeviceParams_();
  39354. if (url) {
  39355. this.onDeviceParamsUpdated = onDeviceParamsUpdated;
  39356. var xhr = new XMLHttpRequest();
  39357. var obj = this;
  39358. xhr.open('GET', url, true);
  39359. xhr.addEventListener('load', function () {
  39360. obj.loading = false;
  39361. if (xhr.status >= 200 && xhr.status <= 299) {
  39362. obj.dpdb = JSON.parse(xhr.response);
  39363. obj.recalculateDeviceParams_();
  39364. } else {
  39365. console.error('Error loading online DPDB!');
  39366. }
  39367. });
  39368. xhr.send();
  39369. }
  39370. }
  39371. Dpdb.prototype.getDeviceParams = function () {
  39372. return this.deviceParams;
  39373. };
  39374. Dpdb.prototype.recalculateDeviceParams_ = function () {
  39375. var newDeviceParams = this.calcDeviceParams_();
  39376. if (newDeviceParams) {
  39377. this.deviceParams = newDeviceParams;
  39378. if (this.onDeviceParamsUpdated) {
  39379. this.onDeviceParamsUpdated(this.deviceParams);
  39380. }
  39381. } else {
  39382. console.error('Failed to recalculate device parameters.');
  39383. }
  39384. };
  39385. Dpdb.prototype.calcDeviceParams_ = function () {
  39386. var db = this.dpdb;
  39387. if (!db) {
  39388. console.error('DPDB not available.');
  39389. return null;
  39390. }
  39391. if (db.format != 1) {
  39392. console.error('DPDB has unexpected format version.');
  39393. return null;
  39394. }
  39395. if (!db.devices || !db.devices.length) {
  39396. console.error('DPDB does not have a devices section.');
  39397. return null;
  39398. }
  39399. var userAgent = navigator.userAgent || navigator.vendor || window.opera;
  39400. var width = getScreenWidth();
  39401. var height = getScreenHeight();
  39402. if (!db.devices) {
  39403. console.error('DPDB has no devices section.');
  39404. return null;
  39405. }
  39406. for (var i = 0; i < db.devices.length; i++) {
  39407. var device = db.devices[i];
  39408. if (!device.rules) {
  39409. console.warn('Device[' + i + '] has no rules section.');
  39410. continue;
  39411. }
  39412. if (device.type != 'ios' && device.type != 'android') {
  39413. console.warn('Device[' + i + '] has invalid type.');
  39414. continue;
  39415. }
  39416. if (isIOS() != (device.type == 'ios')) continue;
  39417. var matched = false;
  39418. for (var j = 0; j < device.rules.length; j++) {
  39419. var rule = device.rules[j];
  39420. if (this.ruleMatches_(rule, userAgent, width, height)) {
  39421. matched = true;
  39422. break;
  39423. }
  39424. }
  39425. if (!matched) continue;
  39426. var xdpi = device.dpi[0] || device.dpi;
  39427. var ydpi = device.dpi[1] || device.dpi;
  39428. return new DeviceParams({ xdpi: xdpi, ydpi: ydpi, bevelMm: device.bw });
  39429. }
  39430. console.warn('No DPDB device match.');
  39431. return null;
  39432. };
  39433. Dpdb.prototype.ruleMatches_ = function (rule, ua, screenWidth, screenHeight) {
  39434. if (!rule.ua && !rule.res) return false;
  39435. if (rule.ua && rule.ua.substring(0, 2) === 'SM') rule.ua = rule.ua.substring(0, 7);
  39436. if (rule.ua && ua.indexOf(rule.ua) < 0) return false;
  39437. if (rule.res) {
  39438. if (!rule.res[0] || !rule.res[1]) return false;
  39439. var resX = rule.res[0];
  39440. var resY = rule.res[1];
  39441. if (Math.min(screenWidth, screenHeight) != Math.min(resX, resY) || Math.max(screenWidth, screenHeight) != Math.max(resX, resY)) {
  39442. return false;
  39443. }
  39444. }
  39445. return true;
  39446. };
  39447. function DeviceParams(params) {
  39448. this.xdpi = params.xdpi;
  39449. this.ydpi = params.ydpi;
  39450. this.bevelMm = params.bevelMm;
  39451. }
  39452. function SensorSample(sample, timestampS) {
  39453. this.set(sample, timestampS);
  39454. }
  39455. SensorSample.prototype.set = function (sample, timestampS) {
  39456. this.sample = sample;
  39457. this.timestampS = timestampS;
  39458. };
  39459. SensorSample.prototype.copy = function (sensorSample) {
  39460. this.set(sensorSample.sample, sensorSample.timestampS);
  39461. };
  39462. function ComplementaryFilter(kFilter, isDebug) {
  39463. this.kFilter = kFilter;
  39464. this.isDebug = isDebug;
  39465. this.currentAccelMeasurement = new SensorSample();
  39466. this.currentGyroMeasurement = new SensorSample();
  39467. this.previousGyroMeasurement = new SensorSample();
  39468. if (isIOS()) {
  39469. this.filterQ = new Quaternion(-1, 0, 0, 1);
  39470. } else {
  39471. this.filterQ = new Quaternion(1, 0, 0, 1);
  39472. }
  39473. this.previousFilterQ = new Quaternion();
  39474. this.previousFilterQ.copy(this.filterQ);
  39475. this.accelQ = new Quaternion();
  39476. this.isOrientationInitialized = false;
  39477. this.estimatedGravity = new Vector3();
  39478. this.measuredGravity = new Vector3();
  39479. this.gyroIntegralQ = new Quaternion();
  39480. }
  39481. ComplementaryFilter.prototype.addAccelMeasurement = function (vector, timestampS) {
  39482. this.currentAccelMeasurement.set(vector, timestampS);
  39483. };
  39484. ComplementaryFilter.prototype.addGyroMeasurement = function (vector, timestampS) {
  39485. this.currentGyroMeasurement.set(vector, timestampS);
  39486. var deltaT = timestampS - this.previousGyroMeasurement.timestampS;
  39487. if (isTimestampDeltaValid(deltaT)) {
  39488. this.run_();
  39489. }
  39490. this.previousGyroMeasurement.copy(this.currentGyroMeasurement);
  39491. };
  39492. ComplementaryFilter.prototype.run_ = function () {
  39493. if (!this.isOrientationInitialized) {
  39494. this.accelQ = this.accelToQuaternion_(this.currentAccelMeasurement.sample);
  39495. this.previousFilterQ.copy(this.accelQ);
  39496. this.isOrientationInitialized = true;
  39497. return;
  39498. }
  39499. var deltaT = this.currentGyroMeasurement.timestampS - this.previousGyroMeasurement.timestampS;
  39500. var gyroDeltaQ = this.gyroToQuaternionDelta_(this.currentGyroMeasurement.sample, deltaT);
  39501. this.gyroIntegralQ.multiply(gyroDeltaQ);
  39502. this.filterQ.copy(this.previousFilterQ);
  39503. this.filterQ.multiply(gyroDeltaQ);
  39504. var invFilterQ = new Quaternion();
  39505. invFilterQ.copy(this.filterQ);
  39506. invFilterQ.inverse();
  39507. this.estimatedGravity.set(0, 0, -1);
  39508. this.estimatedGravity.applyQuaternion(invFilterQ);
  39509. this.estimatedGravity.normalize();
  39510. this.measuredGravity.copy(this.currentAccelMeasurement.sample);
  39511. this.measuredGravity.normalize();
  39512. var deltaQ = new Quaternion();
  39513. deltaQ.setFromUnitVectors(this.estimatedGravity, this.measuredGravity);
  39514. deltaQ.inverse();
  39515. if (this.isDebug) {
  39516. 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));
  39517. }
  39518. var targetQ = new Quaternion();
  39519. targetQ.copy(this.filterQ);
  39520. targetQ.multiply(deltaQ);
  39521. this.filterQ.slerp(targetQ, 1 - this.kFilter);
  39522. this.previousFilterQ.copy(this.filterQ);
  39523. };
  39524. ComplementaryFilter.prototype.getOrientation = function () {
  39525. return this.filterQ;
  39526. };
  39527. ComplementaryFilter.prototype.accelToQuaternion_ = function (accel) {
  39528. var normAccel = new Vector3();
  39529. normAccel.copy(accel);
  39530. normAccel.normalize();
  39531. var quat = new Quaternion();
  39532. quat.setFromUnitVectors(new Vector3(0, 0, -1), normAccel);
  39533. quat.inverse();
  39534. return quat;
  39535. };
  39536. ComplementaryFilter.prototype.gyroToQuaternionDelta_ = function (gyro, dt) {
  39537. var quat = new Quaternion();
  39538. var axis = new Vector3();
  39539. axis.copy(gyro);
  39540. axis.normalize();
  39541. quat.setFromAxisAngle(axis, gyro.length() * dt);
  39542. return quat;
  39543. };
  39544. function PosePredictor(predictionTimeS, isDebug) {
  39545. this.predictionTimeS = predictionTimeS;
  39546. this.isDebug = isDebug;
  39547. this.previousQ = new Quaternion();
  39548. this.previousTimestampS = null;
  39549. this.deltaQ = new Quaternion();
  39550. this.outQ = new Quaternion();
  39551. }
  39552. PosePredictor.prototype.getPrediction = function (currentQ, gyro, timestampS) {
  39553. if (!this.previousTimestampS) {
  39554. this.previousQ.copy(currentQ);
  39555. this.previousTimestampS = timestampS;
  39556. return currentQ;
  39557. }
  39558. var axis = new Vector3();
  39559. axis.copy(gyro);
  39560. axis.normalize();
  39561. var angularSpeed = gyro.length();
  39562. if (angularSpeed < degToRad * 20) {
  39563. if (this.isDebug) {
  39564. console.log('Moving slowly, at %s deg/s: no prediction', (radToDeg * angularSpeed).toFixed(1));
  39565. }
  39566. this.outQ.copy(currentQ);
  39567. this.previousQ.copy(currentQ);
  39568. return this.outQ;
  39569. }
  39570. var predictAngle = angularSpeed * this.predictionTimeS;
  39571. this.deltaQ.setFromAxisAngle(axis, predictAngle);
  39572. this.outQ.copy(this.previousQ);
  39573. this.outQ.multiply(this.deltaQ);
  39574. this.previousQ.copy(currentQ);
  39575. this.previousTimestampS = timestampS;
  39576. return this.outQ;
  39577. };
  39578. function FusionPoseSensor(kFilter, predictionTime, yawOnly, isDebug) {
  39579. this.yawOnly = yawOnly;
  39580. this.accelerometer = new Vector3();
  39581. this.gyroscope = new Vector3();
  39582. this.filter = new ComplementaryFilter(kFilter, isDebug);
  39583. this.posePredictor = new PosePredictor(predictionTime, isDebug);
  39584. this.isFirefoxAndroid = isFirefoxAndroid();
  39585. this.isIOS = isIOS();
  39586. var chromeVersion = getChromeVersion();
  39587. this.isDeviceMotionInRadians = !this.isIOS && chromeVersion && chromeVersion < 66;
  39588. this.isWithoutDeviceMotion = isChromeWithoutDeviceMotion();
  39589. this.filterToWorldQ = new Quaternion();
  39590. if (isIOS()) {
  39591. this.filterToWorldQ.setFromAxisAngle(new Vector3(1, 0, 0), Math.PI / 2);
  39592. } else {
  39593. this.filterToWorldQ.setFromAxisAngle(new Vector3(1, 0, 0), -Math.PI / 2);
  39594. }
  39595. this.inverseWorldToScreenQ = new Quaternion();
  39596. this.worldToScreenQ = new Quaternion();
  39597. this.originalPoseAdjustQ = new Quaternion();
  39598. this.originalPoseAdjustQ.setFromAxisAngle(new Vector3(0, 0, 1), -window.orientation * Math.PI / 180);
  39599. this.setScreenTransform_();
  39600. if (isLandscapeMode()) {
  39601. this.filterToWorldQ.multiply(this.inverseWorldToScreenQ);
  39602. }
  39603. this.resetQ = new Quaternion();
  39604. this.orientationOut_ = new Float32Array(4);
  39605. this.start();
  39606. }
  39607. FusionPoseSensor.prototype.getPosition = function () {
  39608. return null;
  39609. };
  39610. FusionPoseSensor.prototype.getOrientation = function () {
  39611. var orientation = void 0;
  39612. if (this.isWithoutDeviceMotion && this._deviceOrientationQ) {
  39613. this.deviceOrientationFixQ = this.deviceOrientationFixQ || function () {
  39614. var z = new Quaternion().setFromAxisAngle(new Vector3(0, 0, -1), 0);
  39615. var y = new Quaternion();
  39616. if (window.orientation === -90) {
  39617. y.setFromAxisAngle(new Vector3(0, 1, 0), Math.PI / -2);
  39618. } else {
  39619. y.setFromAxisAngle(new Vector3(0, 1, 0), Math.PI / 2);
  39620. }
  39621. return z.multiply(y);
  39622. }();
  39623. this.deviceOrientationFilterToWorldQ = this.deviceOrientationFilterToWorldQ || function () {
  39624. var q = new Quaternion();
  39625. q.setFromAxisAngle(new Vector3(1, 0, 0), -Math.PI / 2);
  39626. return q;
  39627. }();
  39628. orientation = this._deviceOrientationQ;
  39629. var out = new Quaternion();
  39630. out.copy(orientation);
  39631. out.multiply(this.deviceOrientationFilterToWorldQ);
  39632. out.multiply(this.resetQ);
  39633. out.multiply(this.worldToScreenQ);
  39634. out.multiplyQuaternions(this.deviceOrientationFixQ, out);
  39635. if (this.yawOnly) {
  39636. out.x = 0;
  39637. out.z = 0;
  39638. out.normalize();
  39639. }
  39640. this.orientationOut_[0] = out.x;
  39641. this.orientationOut_[1] = out.y;
  39642. this.orientationOut_[2] = out.z;
  39643. this.orientationOut_[3] = out.w;
  39644. return this.orientationOut_;
  39645. } else {
  39646. var filterOrientation = this.filter.getOrientation();
  39647. orientation = this.posePredictor.getPrediction(filterOrientation, this.gyroscope, this.previousTimestampS);
  39648. }
  39649. var out = new Quaternion();
  39650. out.copy(this.filterToWorldQ);
  39651. out.multiply(this.resetQ);
  39652. out.multiply(orientation);
  39653. out.multiply(this.worldToScreenQ);
  39654. if (this.yawOnly) {
  39655. out.x = 0;
  39656. out.z = 0;
  39657. out.normalize();
  39658. }
  39659. this.orientationOut_[0] = out.x;
  39660. this.orientationOut_[1] = out.y;
  39661. this.orientationOut_[2] = out.z;
  39662. this.orientationOut_[3] = out.w;
  39663. return this.orientationOut_;
  39664. };
  39665. FusionPoseSensor.prototype.resetPose = function () {
  39666. this.resetQ.copy(this.filter.getOrientation());
  39667. this.resetQ.x = 0;
  39668. this.resetQ.y = 0;
  39669. this.resetQ.z *= -1;
  39670. this.resetQ.normalize();
  39671. if (isLandscapeMode()) {
  39672. this.resetQ.multiply(this.inverseWorldToScreenQ);
  39673. }
  39674. this.resetQ.multiply(this.originalPoseAdjustQ);
  39675. };
  39676. FusionPoseSensor.prototype.onDeviceOrientation_ = function (e) {
  39677. this._deviceOrientationQ = this._deviceOrientationQ || new Quaternion();
  39678. var alpha = e.alpha,
  39679. beta = e.beta,
  39680. gamma = e.gamma;
  39681. alpha = (alpha || 0) * Math.PI / 180;
  39682. beta = (beta || 0) * Math.PI / 180;
  39683. gamma = (gamma || 0) * Math.PI / 180;
  39684. this._deviceOrientationQ.setFromEulerYXZ(beta, alpha, -gamma);
  39685. };
  39686. FusionPoseSensor.prototype.onDeviceMotion_ = function (deviceMotion) {
  39687. this.updateDeviceMotion_(deviceMotion);
  39688. };
  39689. FusionPoseSensor.prototype.updateDeviceMotion_ = function (deviceMotion) {
  39690. var accGravity = deviceMotion.accelerationIncludingGravity;
  39691. var rotRate = deviceMotion.rotationRate;
  39692. var timestampS = deviceMotion.timeStamp / 1000;
  39693. var deltaS = timestampS - this.previousTimestampS;
  39694. if (deltaS < 0) {
  39695. warnOnce('fusion-pose-sensor:invalid:non-monotonic', 'Invalid timestamps detected: non-monotonic timestamp from devicemotion');
  39696. this.previousTimestampS = timestampS;
  39697. return;
  39698. } else if (deltaS <= MIN_TIMESTEP || deltaS > MAX_TIMESTEP) {
  39699. warnOnce('fusion-pose-sensor:invalid:outside-threshold', 'Invalid timestamps detected: Timestamp from devicemotion outside expected range.');
  39700. this.previousTimestampS = timestampS;
  39701. return;
  39702. }
  39703. this.accelerometer.set(-accGravity.x, -accGravity.y, -accGravity.z);
  39704. if (isR7()) {
  39705. this.gyroscope.set(-rotRate.beta, rotRate.alpha, rotRate.gamma);
  39706. } else {
  39707. this.gyroscope.set(rotRate.alpha, rotRate.beta, rotRate.gamma);
  39708. }
  39709. if (!this.isDeviceMotionInRadians) {
  39710. this.gyroscope.multiplyScalar(Math.PI / 180);
  39711. }
  39712. this.filter.addAccelMeasurement(this.accelerometer, timestampS);
  39713. this.filter.addGyroMeasurement(this.gyroscope, timestampS);
  39714. this.previousTimestampS = timestampS;
  39715. };
  39716. FusionPoseSensor.prototype.onOrientationChange_ = function (screenOrientation) {
  39717. this.setScreenTransform_();
  39718. };
  39719. FusionPoseSensor.prototype.onMessage_ = function (event) {
  39720. var message = event.data;
  39721. if (!message || !message.type) {
  39722. return;
  39723. }
  39724. var type = message.type.toLowerCase();
  39725. if (type !== 'devicemotion') {
  39726. return;
  39727. }
  39728. this.updateDeviceMotion_(message.deviceMotionEvent);
  39729. };
  39730. FusionPoseSensor.prototype.setScreenTransform_ = function () {
  39731. this.worldToScreenQ.set(0, 0, 0, 1);
  39732. switch (window.orientation) {
  39733. case 0:
  39734. break;
  39735. case 90:
  39736. this.worldToScreenQ.setFromAxisAngle(new Vector3(0, 0, 1), -Math.PI / 2);
  39737. break;
  39738. case -90:
  39739. this.worldToScreenQ.setFromAxisAngle(new Vector3(0, 0, 1), Math.PI / 2);
  39740. break;
  39741. case 180:
  39742. break;
  39743. }
  39744. this.inverseWorldToScreenQ.copy(this.worldToScreenQ);
  39745. this.inverseWorldToScreenQ.inverse();
  39746. };
  39747. FusionPoseSensor.prototype.start = function () {
  39748. this.onDeviceMotionCallback_ = this.onDeviceMotion_.bind(this);
  39749. this.onOrientationChangeCallback_ = this.onOrientationChange_.bind(this);
  39750. this.onMessageCallback_ = this.onMessage_.bind(this);
  39751. this.onDeviceOrientationCallback_ = this.onDeviceOrientation_.bind(this);
  39752. if (isIOS() && isInsideCrossOriginIFrame()) {
  39753. window.addEventListener('message', this.onMessageCallback_);
  39754. }
  39755. window.addEventListener('orientationchange', this.onOrientationChangeCallback_);
  39756. if (this.isWithoutDeviceMotion) {
  39757. window.addEventListener('deviceorientation', this.onDeviceOrientationCallback_);
  39758. } else {
  39759. window.addEventListener('devicemotion', this.onDeviceMotionCallback_);
  39760. }
  39761. };
  39762. FusionPoseSensor.prototype.stop = function () {
  39763. window.removeEventListener('devicemotion', this.onDeviceMotionCallback_);
  39764. window.removeEventListener('deviceorientation', this.onDeviceOrientationCallback_);
  39765. window.removeEventListener('orientationchange', this.onOrientationChangeCallback_);
  39766. window.removeEventListener('message', this.onMessageCallback_);
  39767. };
  39768. var SENSOR_FREQUENCY = 60;
  39769. var X_AXIS = new Vector3(1, 0, 0);
  39770. var Z_AXIS = new Vector3(0, 0, 1);
  39771. var SENSOR_TO_VR = new Quaternion();
  39772. SENSOR_TO_VR.setFromAxisAngle(X_AXIS, -Math.PI / 2);
  39773. SENSOR_TO_VR.multiply(new Quaternion().setFromAxisAngle(Z_AXIS, Math.PI / 2));
  39774. var PoseSensor = function () {
  39775. function PoseSensor(config) {
  39776. classCallCheck(this, PoseSensor);
  39777. this.config = config;
  39778. this.sensor = null;
  39779. this.fusionSensor = null;
  39780. this._out = new Float32Array(4);
  39781. this.api = null;
  39782. this.errors = [];
  39783. this._sensorQ = new Quaternion();
  39784. this._outQ = new Quaternion();
  39785. this._onSensorRead = this._onSensorRead.bind(this);
  39786. this._onSensorError = this._onSensorError.bind(this);
  39787. this.init();
  39788. }
  39789. createClass(PoseSensor, [{
  39790. key: 'init',
  39791. value: function init() {
  39792. var sensor = null;
  39793. try {
  39794. sensor = new RelativeOrientationSensor({
  39795. frequency: SENSOR_FREQUENCY,
  39796. referenceFrame: 'screen'
  39797. });
  39798. sensor.addEventListener('error', this._onSensorError);
  39799. } catch (error) {
  39800. this.errors.push(error);
  39801. if (error.name === 'SecurityError') {
  39802. console.error('Cannot construct sensors due to the Feature Policy');
  39803. console.warn('Attempting to fall back using "devicemotion"; however this will ' + 'fail in the future without correct permissions.');
  39804. this.useDeviceMotion();
  39805. } else if (error.name === 'ReferenceError') {
  39806. this.useDeviceMotion();
  39807. } else {
  39808. console.error(error);
  39809. }
  39810. }
  39811. if (sensor) {
  39812. this.api = 'sensor';
  39813. this.sensor = sensor;
  39814. this.sensor.addEventListener('reading', this._onSensorRead);
  39815. this.sensor.start();
  39816. }
  39817. }
  39818. }, {
  39819. key: 'useDeviceMotion',
  39820. value: function useDeviceMotion() {
  39821. this.api = 'devicemotion';
  39822. this.fusionSensor = new FusionPoseSensor(this.config.K_FILTER, this.config.PREDICTION_TIME_S, this.config.YAW_ONLY, this.config.DEBUG);
  39823. if (this.sensor) {
  39824. this.sensor.removeEventListener('reading', this._onSensorRead);
  39825. this.sensor.removeEventListener('error', this._onSensorError);
  39826. this.sensor = null;
  39827. }
  39828. }
  39829. }, {
  39830. key: 'getOrientation',
  39831. value: function getOrientation() {
  39832. if (this.fusionSensor) {
  39833. return this.fusionSensor.getOrientation();
  39834. }
  39835. if (!this.sensor || !this.sensor.quaternion) {
  39836. this._out[0] = this._out[1] = this._out[2] = 0;
  39837. this._out[3] = 1;
  39838. return this._out;
  39839. }
  39840. var q = this.sensor.quaternion;
  39841. this._sensorQ.set(q[0], q[1], q[2], q[3]);
  39842. var out = this._outQ;
  39843. out.copy(SENSOR_TO_VR);
  39844. out.multiply(this._sensorQ);
  39845. if (this.config.YAW_ONLY) {
  39846. out.x = out.z = 0;
  39847. out.normalize();
  39848. }
  39849. this._out[0] = out.x;
  39850. this._out[1] = out.y;
  39851. this._out[2] = out.z;
  39852. this._out[3] = out.w;
  39853. return this._out;
  39854. }
  39855. }, {
  39856. key: '_onSensorError',
  39857. value: function _onSensorError(event) {
  39858. this.errors.push(event.error);
  39859. if (event.error.name === 'NotAllowedError') {
  39860. console.error('Permission to access sensor was denied');
  39861. } else if (event.error.name === 'NotReadableError') {
  39862. console.error('Sensor could not be read');
  39863. } else {
  39864. console.error(event.error);
  39865. }
  39866. this.useDeviceMotion();
  39867. }
  39868. }, {
  39869. key: '_onSensorRead',
  39870. value: function _onSensorRead() {}
  39871. }]);
  39872. return PoseSensor;
  39873. }();
  39874. 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>";
  39875. function RotateInstructions() {
  39876. this.loadIcon_();
  39877. var overlay = document.createElement('div');
  39878. var s = overlay.style;
  39879. s.position = 'fixed';
  39880. s.top = 0;
  39881. s.right = 0;
  39882. s.bottom = 0;
  39883. s.left = 0;
  39884. s.backgroundColor = 'gray';
  39885. s.fontFamily = 'sans-serif';
  39886. s.zIndex = 1000000;
  39887. var img = document.createElement('img');
  39888. img.src = this.icon;
  39889. var s = img.style;
  39890. s.marginLeft = '25%';
  39891. s.marginTop = '25%';
  39892. s.width = '50%';
  39893. overlay.appendChild(img);
  39894. var text = document.createElement('div');
  39895. var s = text.style;
  39896. s.textAlign = 'center';
  39897. s.fontSize = '16px';
  39898. s.lineHeight = '24px';
  39899. s.margin = '24px 25%';
  39900. s.width = '50%';
  39901. text.innerHTML = 'Place your phone into your Cardboard viewer.';
  39902. overlay.appendChild(text);
  39903. var snackbar = document.createElement('div');
  39904. var s = snackbar.style;
  39905. s.backgroundColor = '#CFD8DC';
  39906. s.position = 'fixed';
  39907. s.bottom = 0;
  39908. s.width = '100%';
  39909. s.height = '48px';
  39910. s.padding = '14px 24px';
  39911. s.boxSizing = 'border-box';
  39912. s.color = '#656A6B';
  39913. overlay.appendChild(snackbar);
  39914. var snackbarText = document.createElement('div');
  39915. snackbarText.style.float = 'left';
  39916. snackbarText.innerHTML = 'No Cardboard viewer?';
  39917. var snackbarButton = document.createElement('a');
  39918. snackbarButton.href = 'https://www.google.com/get/cardboard/get-cardboard/';
  39919. snackbarButton.innerHTML = 'get one';
  39920. snackbarButton.target = '_blank';
  39921. var s = snackbarButton.style;
  39922. s.float = 'right';
  39923. s.fontWeight = 600;
  39924. s.textTransform = 'uppercase';
  39925. s.borderLeft = '1px solid gray';
  39926. s.paddingLeft = '24px';
  39927. s.textDecoration = 'none';
  39928. s.color = '#656A6B';
  39929. snackbar.appendChild(snackbarText);
  39930. snackbar.appendChild(snackbarButton);
  39931. this.overlay = overlay;
  39932. this.text = text;
  39933. this.hide();
  39934. }
  39935. RotateInstructions.prototype.show = function (parent) {
  39936. if (!parent && !this.overlay.parentElement) {
  39937. document.body.appendChild(this.overlay);
  39938. } else if (parent) {
  39939. if (this.overlay.parentElement && this.overlay.parentElement != parent) this.overlay.parentElement.removeChild(this.overlay);
  39940. parent.appendChild(this.overlay);
  39941. }
  39942. this.overlay.style.display = 'block';
  39943. var img = this.overlay.querySelector('img');
  39944. var s = img.style;
  39945. if (isLandscapeMode()) {
  39946. s.width = '20%';
  39947. s.marginLeft = '40%';
  39948. s.marginTop = '3%';
  39949. } else {
  39950. s.width = '50%';
  39951. s.marginLeft = '25%';
  39952. s.marginTop = '25%';
  39953. }
  39954. };
  39955. RotateInstructions.prototype.hide = function () {
  39956. this.overlay.style.display = 'none';
  39957. };
  39958. RotateInstructions.prototype.showTemporarily = function (ms, parent) {
  39959. this.show(parent);
  39960. this.timer = setTimeout(this.hide.bind(this), ms);
  39961. };
  39962. RotateInstructions.prototype.disableShowTemporarily = function () {
  39963. clearTimeout(this.timer);
  39964. };
  39965. RotateInstructions.prototype.update = function () {
  39966. this.disableShowTemporarily();
  39967. if (!isLandscapeMode() && isMobile()) {
  39968. this.show();
  39969. } else {
  39970. this.hide();
  39971. }
  39972. };
  39973. RotateInstructions.prototype.loadIcon_ = function () {
  39974. this.icon = dataUri('image/svg+xml', rotateInstructionsAsset);
  39975. };
  39976. var DEFAULT_VIEWER = 'CardboardV1';
  39977. var VIEWER_KEY = 'WEBVR_CARDBOARD_VIEWER';
  39978. var CLASS_NAME = 'webvr-polyfill-viewer-selector';
  39979. function ViewerSelector(defaultViewer) {
  39980. try {
  39981. this.selectedKey = localStorage.getItem(VIEWER_KEY);
  39982. } catch (error) {
  39983. console.error('Failed to load viewer profile: %s', error);
  39984. }
  39985. if (!this.selectedKey) {
  39986. this.selectedKey = defaultViewer || DEFAULT_VIEWER;
  39987. }
  39988. this.dialog = this.createDialog_(DeviceInfo.Viewers);
  39989. this.root = null;
  39990. this.onChangeCallbacks_ = [];
  39991. }
  39992. ViewerSelector.prototype.show = function (root) {
  39993. this.root = root;
  39994. root.appendChild(this.dialog);
  39995. var selected = this.dialog.querySelector('#' + this.selectedKey);
  39996. selected.checked = true;
  39997. this.dialog.style.display = 'block';
  39998. };
  39999. ViewerSelector.prototype.hide = function () {
  40000. if (this.root && this.root.contains(this.dialog)) {
  40001. this.root.removeChild(this.dialog);
  40002. }
  40003. this.dialog.style.display = 'none';
  40004. };
  40005. ViewerSelector.prototype.getCurrentViewer = function () {
  40006. return DeviceInfo.Viewers[this.selectedKey];
  40007. };
  40008. ViewerSelector.prototype.getSelectedKey_ = function () {
  40009. var input = this.dialog.querySelector('input[name=field]:checked');
  40010. if (input) {
  40011. return input.id;
  40012. }
  40013. return null;
  40014. };
  40015. ViewerSelector.prototype.onChange = function (cb) {
  40016. this.onChangeCallbacks_.push(cb);
  40017. };
  40018. ViewerSelector.prototype.fireOnChange_ = function (viewer) {
  40019. for (var i = 0; i < this.onChangeCallbacks_.length; i++) {
  40020. this.onChangeCallbacks_[i](viewer);
  40021. }
  40022. };
  40023. ViewerSelector.prototype.onSave_ = function () {
  40024. this.selectedKey = this.getSelectedKey_();
  40025. if (!this.selectedKey || !DeviceInfo.Viewers[this.selectedKey]) {
  40026. console.error('ViewerSelector.onSave_: this should never happen!');
  40027. return;
  40028. }
  40029. this.fireOnChange_(DeviceInfo.Viewers[this.selectedKey]);
  40030. try {
  40031. localStorage.setItem(VIEWER_KEY, this.selectedKey);
  40032. } catch (error) {
  40033. console.error('Failed to save viewer profile: %s', error);
  40034. }
  40035. this.hide();
  40036. };
  40037. ViewerSelector.prototype.createDialog_ = function (options) {
  40038. var container = document.createElement('div');
  40039. container.classList.add(CLASS_NAME);
  40040. container.style.display = 'none';
  40041. var overlay = document.createElement('div');
  40042. var s = overlay.style;
  40043. s.position = 'fixed';
  40044. s.left = 0;
  40045. s.top = 0;
  40046. s.width = '100%';
  40047. s.height = '100%';
  40048. s.background = 'rgba(0, 0, 0, 0.3)';
  40049. overlay.addEventListener('click', this.hide.bind(this));
  40050. var width = 280;
  40051. var dialog = document.createElement('div');
  40052. var s = dialog.style;
  40053. s.boxSizing = 'border-box';
  40054. s.position = 'fixed';
  40055. s.top = '24px';
  40056. s.left = '50%';
  40057. s.marginLeft = -width / 2 + 'px';
  40058. s.width = width + 'px';
  40059. s.padding = '24px';
  40060. s.overflow = 'hidden';
  40061. s.background = '#fafafa';
  40062. s.fontFamily = "'Roboto', sans-serif";
  40063. s.boxShadow = '0px 5px 20px #666';
  40064. dialog.appendChild(this.createH1_('Select your viewer'));
  40065. for (var id in options) {
  40066. dialog.appendChild(this.createChoice_(id, options[id].label));
  40067. }
  40068. dialog.appendChild(this.createButton_('Save', this.onSave_.bind(this)));
  40069. container.appendChild(overlay);
  40070. container.appendChild(dialog);
  40071. return container;
  40072. };
  40073. ViewerSelector.prototype.createH1_ = function (name) {
  40074. var h1 = document.createElement('h1');
  40075. var s = h1.style;
  40076. s.color = 'black';
  40077. s.fontSize = '20px';
  40078. s.fontWeight = 'bold';
  40079. s.marginTop = 0;
  40080. s.marginBottom = '24px';
  40081. h1.innerHTML = name;
  40082. return h1;
  40083. };
  40084. ViewerSelector.prototype.createChoice_ = function (id, name) {
  40085. var div = document.createElement('div');
  40086. div.style.marginTop = '8px';
  40087. div.style.color = 'black';
  40088. var input = document.createElement('input');
  40089. input.style.fontSize = '30px';
  40090. input.setAttribute('id', id);
  40091. input.setAttribute('type', 'radio');
  40092. input.setAttribute('value', id);
  40093. input.setAttribute('name', 'field');
  40094. var label = document.createElement('label');
  40095. label.style.marginLeft = '4px';
  40096. label.setAttribute('for', id);
  40097. label.innerHTML = name;
  40098. div.appendChild(input);
  40099. div.appendChild(label);
  40100. return div;
  40101. };
  40102. ViewerSelector.prototype.createButton_ = function (label, onclick) {
  40103. var button = document.createElement('button');
  40104. button.innerHTML = label;
  40105. var s = button.style;
  40106. s.float = 'right';
  40107. s.textTransform = 'uppercase';
  40108. s.color = '#1094f7';
  40109. s.fontSize = '14px';
  40110. s.letterSpacing = 0;
  40111. s.border = 0;
  40112. s.background = 'none';
  40113. s.marginTop = '16px';
  40114. button.addEventListener('click', onclick);
  40115. return button;
  40116. };
  40117. var commonjsGlobal$$1 = typeof window !== 'undefined' ? window : typeof commonjsGlobal !== 'undefined' ? commonjsGlobal : typeof self !== 'undefined' ? self : {};
  40118. function unwrapExports$$1 (x) {
  40119. return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
  40120. }
  40121. function createCommonjsModule$$1(fn, module) {
  40122. return module = { exports: {} }, fn(module, module.exports), module.exports;
  40123. }
  40124. var NoSleep = createCommonjsModule$$1(function (module, exports) {
  40125. (function webpackUniversalModuleDefinition(root, factory) {
  40126. module.exports = factory();
  40127. })(commonjsGlobal$$1, function() {
  40128. return (function(modules) {
  40129. var installedModules = {};
  40130. function __webpack_require__(moduleId) {
  40131. if(installedModules[moduleId]) {
  40132. return installedModules[moduleId].exports;
  40133. }
  40134. var module = installedModules[moduleId] = {
  40135. i: moduleId,
  40136. l: false,
  40137. exports: {}
  40138. };
  40139. modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
  40140. module.l = true;
  40141. return module.exports;
  40142. }
  40143. __webpack_require__.m = modules;
  40144. __webpack_require__.c = installedModules;
  40145. __webpack_require__.d = function(exports, name, getter) {
  40146. if(!__webpack_require__.o(exports, name)) {
  40147. Object.defineProperty(exports, name, {
  40148. configurable: false,
  40149. enumerable: true,
  40150. get: getter
  40151. });
  40152. }
  40153. };
  40154. __webpack_require__.n = function(module) {
  40155. var getter = module && module.__esModule ?
  40156. function getDefault() { return module['default']; } :
  40157. function getModuleExports() { return module; };
  40158. __webpack_require__.d(getter, 'a', getter);
  40159. return getter;
  40160. };
  40161. __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
  40162. __webpack_require__.p = "";
  40163. return __webpack_require__(__webpack_require__.s = 0);
  40164. })
  40165. ([
  40166. (function(module, exports, __webpack_require__) {
  40167. 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; }; }();
  40168. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  40169. var mediaFile = __webpack_require__(1);
  40170. 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;
  40171. var NoSleep = function () {
  40172. function NoSleep() {
  40173. _classCallCheck(this, NoSleep);
  40174. if (oldIOS) {
  40175. this.noSleepTimer = null;
  40176. } else {
  40177. this.noSleepVideo = document.createElement('video');
  40178. this.noSleepVideo.setAttribute('playsinline', '');
  40179. this.noSleepVideo.setAttribute('src', mediaFile);
  40180. this.noSleepVideo.addEventListener('timeupdate', function (e) {
  40181. if (this.noSleepVideo.currentTime > 0.5) {
  40182. this.noSleepVideo.currentTime = Math.random();
  40183. }
  40184. }.bind(this));
  40185. }
  40186. }
  40187. _createClass(NoSleep, [{
  40188. key: 'enable',
  40189. value: function enable() {
  40190. if (oldIOS) {
  40191. this.disable();
  40192. this.noSleepTimer = window.setInterval(function () {
  40193. window.location.href = '/';
  40194. window.setTimeout(window.stop, 0);
  40195. }, 15000);
  40196. } else {
  40197. this.noSleepVideo.play();
  40198. }
  40199. }
  40200. }, {
  40201. key: 'disable',
  40202. value: function disable() {
  40203. if (oldIOS) {
  40204. if (this.noSleepTimer) {
  40205. window.clearInterval(this.noSleepTimer);
  40206. this.noSleepTimer = null;
  40207. }
  40208. } else {
  40209. this.noSleepVideo.pause();
  40210. }
  40211. }
  40212. }]);
  40213. return NoSleep;
  40214. }();
  40215. module.exports = NoSleep;
  40216. }),
  40217. (function(module, exports, __webpack_require__) {
  40218. 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=';
  40219. })
  40220. ]);
  40221. });
  40222. });
  40223. var NoSleep$1 = unwrapExports$$1(NoSleep);
  40224. var nextDisplayId = 1000;
  40225. var defaultLeftBounds = [0, 0, 0.5, 1];
  40226. var defaultRightBounds = [0.5, 0, 0.5, 1];
  40227. var raf = window.requestAnimationFrame;
  40228. var caf = window.cancelAnimationFrame;
  40229. function VRFrameData() {
  40230. this.leftProjectionMatrix = new Float32Array(16);
  40231. this.leftViewMatrix = new Float32Array(16);
  40232. this.rightProjectionMatrix = new Float32Array(16);
  40233. this.rightViewMatrix = new Float32Array(16);
  40234. this.pose = null;
  40235. }
  40236. function VRDisplayCapabilities(config) {
  40237. Object.defineProperties(this, {
  40238. hasPosition: {
  40239. writable: false, enumerable: true, value: config.hasPosition
  40240. },
  40241. hasExternalDisplay: {
  40242. writable: false, enumerable: true, value: config.hasExternalDisplay
  40243. },
  40244. canPresent: {
  40245. writable: false, enumerable: true, value: config.canPresent
  40246. },
  40247. maxLayers: {
  40248. writable: false, enumerable: true, value: config.maxLayers
  40249. },
  40250. hasOrientation: {
  40251. enumerable: true, get: function get() {
  40252. deprecateWarning('VRDisplayCapabilities.prototype.hasOrientation', 'VRDisplay.prototype.getFrameData');
  40253. return config.hasOrientation;
  40254. }
  40255. }
  40256. });
  40257. }
  40258. function VRDisplay(config) {
  40259. config = config || {};
  40260. var USE_WAKELOCK = 'wakelock' in config ? config.wakelock : true;
  40261. this.isPolyfilled = true;
  40262. this.displayId = nextDisplayId++;
  40263. this.displayName = '';
  40264. this.depthNear = 0.01;
  40265. this.depthFar = 10000.0;
  40266. this.isPresenting = false;
  40267. Object.defineProperty(this, 'isConnected', {
  40268. get: function get() {
  40269. deprecateWarning('VRDisplay.prototype.isConnected', 'VRDisplayCapabilities.prototype.hasExternalDisplay');
  40270. return false;
  40271. }
  40272. });
  40273. this.capabilities = new VRDisplayCapabilities({
  40274. hasPosition: false,
  40275. hasOrientation: false,
  40276. hasExternalDisplay: false,
  40277. canPresent: false,
  40278. maxLayers: 1
  40279. });
  40280. this.stageParameters = null;
  40281. this.waitingForPresent_ = false;
  40282. this.layer_ = null;
  40283. this.originalParent_ = null;
  40284. this.fullscreenElement_ = null;
  40285. this.fullscreenWrapper_ = null;
  40286. this.fullscreenElementCachedStyle_ = null;
  40287. this.fullscreenEventTarget_ = null;
  40288. this.fullscreenChangeHandler_ = null;
  40289. this.fullscreenErrorHandler_ = null;
  40290. if (USE_WAKELOCK && isMobile()) {
  40291. this.wakelock_ = new NoSleep$1();
  40292. }
  40293. }
  40294. VRDisplay.prototype.getFrameData = function (frameData) {
  40295. return frameDataFromPose(frameData, this._getPose(), this);
  40296. };
  40297. VRDisplay.prototype.getPose = function () {
  40298. deprecateWarning('VRDisplay.prototype.getPose', 'VRDisplay.prototype.getFrameData');
  40299. return this._getPose();
  40300. };
  40301. VRDisplay.prototype.resetPose = function () {
  40302. deprecateWarning('VRDisplay.prototype.resetPose');
  40303. return this._resetPose();
  40304. };
  40305. VRDisplay.prototype.getImmediatePose = function () {
  40306. deprecateWarning('VRDisplay.prototype.getImmediatePose', 'VRDisplay.prototype.getFrameData');
  40307. return this._getPose();
  40308. };
  40309. VRDisplay.prototype.requestAnimationFrame = function (callback) {
  40310. return raf(callback);
  40311. };
  40312. VRDisplay.prototype.cancelAnimationFrame = function (id) {
  40313. return caf(id);
  40314. };
  40315. VRDisplay.prototype.wrapForFullscreen = function (element) {
  40316. if (isIOS()) {
  40317. return element;
  40318. }
  40319. if (!this.fullscreenWrapper_) {
  40320. this.fullscreenWrapper_ = document.createElement('div');
  40321. 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'];
  40322. this.fullscreenWrapper_.setAttribute('style', cssProperties.join('; ') + ';');
  40323. this.fullscreenWrapper_.classList.add('webvr-polyfill-fullscreen-wrapper');
  40324. }
  40325. if (this.fullscreenElement_ == element) {
  40326. return this.fullscreenWrapper_;
  40327. }
  40328. if (this.fullscreenElement_) {
  40329. if (this.originalParent_) {
  40330. this.originalParent_.appendChild(this.fullscreenElement_);
  40331. } else {
  40332. this.fullscreenElement_.parentElement.removeChild(this.fullscreenElement_);
  40333. }
  40334. }
  40335. this.fullscreenElement_ = element;
  40336. this.originalParent_ = element.parentElement;
  40337. if (!this.originalParent_) {
  40338. document.body.appendChild(element);
  40339. }
  40340. if (!this.fullscreenWrapper_.parentElement) {
  40341. var parent = this.fullscreenElement_.parentElement;
  40342. parent.insertBefore(this.fullscreenWrapper_, this.fullscreenElement_);
  40343. parent.removeChild(this.fullscreenElement_);
  40344. }
  40345. this.fullscreenWrapper_.insertBefore(this.fullscreenElement_, this.fullscreenWrapper_.firstChild);
  40346. this.fullscreenElementCachedStyle_ = this.fullscreenElement_.getAttribute('style');
  40347. var self = this;
  40348. function applyFullscreenElementStyle() {
  40349. if (!self.fullscreenElement_) {
  40350. return;
  40351. }
  40352. 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'];
  40353. self.fullscreenElement_.setAttribute('style', cssProperties.join('; ') + ';');
  40354. }
  40355. applyFullscreenElementStyle();
  40356. return this.fullscreenWrapper_;
  40357. };
  40358. VRDisplay.prototype.removeFullscreenWrapper = function () {
  40359. if (!this.fullscreenElement_) {
  40360. return;
  40361. }
  40362. var element = this.fullscreenElement_;
  40363. if (this.fullscreenElementCachedStyle_) {
  40364. element.setAttribute('style', this.fullscreenElementCachedStyle_);
  40365. } else {
  40366. element.removeAttribute('style');
  40367. }
  40368. this.fullscreenElement_ = null;
  40369. this.fullscreenElementCachedStyle_ = null;
  40370. var parent = this.fullscreenWrapper_.parentElement;
  40371. this.fullscreenWrapper_.removeChild(element);
  40372. if (this.originalParent_ === parent) {
  40373. parent.insertBefore(element, this.fullscreenWrapper_);
  40374. }
  40375. else if (this.originalParent_) {
  40376. this.originalParent_.appendChild(element);
  40377. }
  40378. parent.removeChild(this.fullscreenWrapper_);
  40379. return element;
  40380. };
  40381. VRDisplay.prototype.requestPresent = function (layers) {
  40382. var wasPresenting = this.isPresenting;
  40383. var self = this;
  40384. if (!(layers instanceof Array)) {
  40385. deprecateWarning('VRDisplay.prototype.requestPresent with non-array argument', 'an array of VRLayers as the first argument');
  40386. layers = [layers];
  40387. }
  40388. return new Promise(function (resolve, reject) {
  40389. if (!self.capabilities.canPresent) {
  40390. reject(new Error('VRDisplay is not capable of presenting.'));
  40391. return;
  40392. }
  40393. if (layers.length == 0 || layers.length > self.capabilities.maxLayers) {
  40394. reject(new Error('Invalid number of layers.'));
  40395. return;
  40396. }
  40397. var incomingLayer = layers[0];
  40398. if (!incomingLayer.source) {
  40399. resolve();
  40400. return;
  40401. }
  40402. var leftBounds = incomingLayer.leftBounds || defaultLeftBounds;
  40403. var rightBounds = incomingLayer.rightBounds || defaultRightBounds;
  40404. if (wasPresenting) {
  40405. var layer = self.layer_;
  40406. if (layer.source !== incomingLayer.source) {
  40407. layer.source = incomingLayer.source;
  40408. }
  40409. for (var i = 0; i < 4; i++) {
  40410. layer.leftBounds[i] = leftBounds[i];
  40411. layer.rightBounds[i] = rightBounds[i];
  40412. }
  40413. self.wrapForFullscreen(self.layer_.source);
  40414. self.updatePresent_();
  40415. resolve();
  40416. return;
  40417. }
  40418. self.layer_ = {
  40419. predistorted: incomingLayer.predistorted,
  40420. source: incomingLayer.source,
  40421. leftBounds: leftBounds.slice(0),
  40422. rightBounds: rightBounds.slice(0)
  40423. };
  40424. self.waitingForPresent_ = false;
  40425. if (self.layer_ && self.layer_.source) {
  40426. var fullscreenElement = self.wrapForFullscreen(self.layer_.source);
  40427. var onFullscreenChange = function onFullscreenChange() {
  40428. var actualFullscreenElement = getFullscreenElement();
  40429. self.isPresenting = fullscreenElement === actualFullscreenElement;
  40430. if (self.isPresenting) {
  40431. if (screen.orientation && screen.orientation.lock) {
  40432. screen.orientation.lock('landscape-primary').catch(function (error) {
  40433. console.error('screen.orientation.lock() failed due to', error.message);
  40434. });
  40435. }
  40436. self.waitingForPresent_ = false;
  40437. self.beginPresent_();
  40438. resolve();
  40439. } else {
  40440. if (screen.orientation && screen.orientation.unlock) {
  40441. screen.orientation.unlock();
  40442. }
  40443. self.removeFullscreenWrapper();
  40444. self.disableWakeLock();
  40445. self.endPresent_();
  40446. self.removeFullscreenListeners_();
  40447. }
  40448. self.fireVRDisplayPresentChange_();
  40449. };
  40450. var onFullscreenError = function onFullscreenError() {
  40451. if (!self.waitingForPresent_) {
  40452. return;
  40453. }
  40454. self.removeFullscreenWrapper();
  40455. self.removeFullscreenListeners_();
  40456. self.disableWakeLock();
  40457. self.waitingForPresent_ = false;
  40458. self.isPresenting = false;
  40459. reject(new Error('Unable to present.'));
  40460. };
  40461. self.addFullscreenListeners_(fullscreenElement, onFullscreenChange, onFullscreenError);
  40462. if (requestFullscreen(fullscreenElement)) {
  40463. self.enableWakeLock();
  40464. self.waitingForPresent_ = true;
  40465. } else if (isIOS() || isWebViewAndroid()) {
  40466. self.enableWakeLock();
  40467. self.isPresenting = true;
  40468. self.beginPresent_();
  40469. self.fireVRDisplayPresentChange_();
  40470. resolve();
  40471. }
  40472. }
  40473. if (!self.waitingForPresent_ && !isIOS()) {
  40474. exitFullscreen();
  40475. reject(new Error('Unable to present.'));
  40476. }
  40477. });
  40478. };
  40479. VRDisplay.prototype.exitPresent = function () {
  40480. var wasPresenting = this.isPresenting;
  40481. var self = this;
  40482. this.isPresenting = false;
  40483. this.layer_ = null;
  40484. this.disableWakeLock();
  40485. return new Promise(function (resolve, reject) {
  40486. if (wasPresenting) {
  40487. if (!exitFullscreen() && isIOS()) {
  40488. self.endPresent_();
  40489. self.fireVRDisplayPresentChange_();
  40490. }
  40491. if (isWebViewAndroid()) {
  40492. self.removeFullscreenWrapper();
  40493. self.removeFullscreenListeners_();
  40494. self.endPresent_();
  40495. self.fireVRDisplayPresentChange_();
  40496. }
  40497. resolve();
  40498. } else {
  40499. reject(new Error('Was not presenting to VRDisplay.'));
  40500. }
  40501. });
  40502. };
  40503. VRDisplay.prototype.getLayers = function () {
  40504. if (this.layer_) {
  40505. return [this.layer_];
  40506. }
  40507. return [];
  40508. };
  40509. VRDisplay.prototype.fireVRDisplayPresentChange_ = function () {
  40510. var event = new CustomEvent('vrdisplaypresentchange', { detail: { display: this } });
  40511. window.dispatchEvent(event);
  40512. };
  40513. VRDisplay.prototype.fireVRDisplayConnect_ = function () {
  40514. var event = new CustomEvent('vrdisplayconnect', { detail: { display: this } });
  40515. window.dispatchEvent(event);
  40516. };
  40517. VRDisplay.prototype.addFullscreenListeners_ = function (element, changeHandler, errorHandler) {
  40518. this.removeFullscreenListeners_();
  40519. this.fullscreenEventTarget_ = element;
  40520. this.fullscreenChangeHandler_ = changeHandler;
  40521. this.fullscreenErrorHandler_ = errorHandler;
  40522. if (changeHandler) {
  40523. if (document.fullscreenEnabled) {
  40524. element.addEventListener('fullscreenchange', changeHandler, false);
  40525. } else if (document.webkitFullscreenEnabled) {
  40526. element.addEventListener('webkitfullscreenchange', changeHandler, false);
  40527. } else if (document.mozFullScreenEnabled) {
  40528. document.addEventListener('mozfullscreenchange', changeHandler, false);
  40529. } else if (document.msFullscreenEnabled) {
  40530. element.addEventListener('msfullscreenchange', changeHandler, false);
  40531. }
  40532. }
  40533. if (errorHandler) {
  40534. if (document.fullscreenEnabled) {
  40535. element.addEventListener('fullscreenerror', errorHandler, false);
  40536. } else if (document.webkitFullscreenEnabled) {
  40537. element.addEventListener('webkitfullscreenerror', errorHandler, false);
  40538. } else if (document.mozFullScreenEnabled) {
  40539. document.addEventListener('mozfullscreenerror', errorHandler, false);
  40540. } else if (document.msFullscreenEnabled) {
  40541. element.addEventListener('msfullscreenerror', errorHandler, false);
  40542. }
  40543. }
  40544. };
  40545. VRDisplay.prototype.removeFullscreenListeners_ = function () {
  40546. if (!this.fullscreenEventTarget_) return;
  40547. var element = this.fullscreenEventTarget_;
  40548. if (this.fullscreenChangeHandler_) {
  40549. var changeHandler = this.fullscreenChangeHandler_;
  40550. element.removeEventListener('fullscreenchange', changeHandler, false);
  40551. element.removeEventListener('webkitfullscreenchange', changeHandler, false);
  40552. document.removeEventListener('mozfullscreenchange', changeHandler, false);
  40553. element.removeEventListener('msfullscreenchange', changeHandler, false);
  40554. }
  40555. if (this.fullscreenErrorHandler_) {
  40556. var errorHandler = this.fullscreenErrorHandler_;
  40557. element.removeEventListener('fullscreenerror', errorHandler, false);
  40558. element.removeEventListener('webkitfullscreenerror', errorHandler, false);
  40559. document.removeEventListener('mozfullscreenerror', errorHandler, false);
  40560. element.removeEventListener('msfullscreenerror', errorHandler, false);
  40561. }
  40562. this.fullscreenEventTarget_ = null;
  40563. this.fullscreenChangeHandler_ = null;
  40564. this.fullscreenErrorHandler_ = null;
  40565. };
  40566. VRDisplay.prototype.enableWakeLock = function () {
  40567. if (this.wakelock_) {
  40568. this.wakelock_.enable();
  40569. }
  40570. };
  40571. VRDisplay.prototype.disableWakeLock = function () {
  40572. if (this.wakelock_) {
  40573. this.wakelock_.disable();
  40574. }
  40575. };
  40576. VRDisplay.prototype.beginPresent_ = function () {
  40577. };
  40578. VRDisplay.prototype.endPresent_ = function () {
  40579. };
  40580. VRDisplay.prototype.submitFrame = function (pose) {
  40581. };
  40582. VRDisplay.prototype.getEyeParameters = function (whichEye) {
  40583. return null;
  40584. };
  40585. var config = {
  40586. ADDITIONAL_VIEWERS: [],
  40587. DEFAULT_VIEWER: '',
  40588. MOBILE_WAKE_LOCK: true,
  40589. DEBUG: false,
  40590. DPDB_URL: 'https://dpdb.webvr.rocks/dpdb.json',
  40591. K_FILTER: 0.98,
  40592. PREDICTION_TIME_S: 0.040,
  40593. CARDBOARD_UI_DISABLED: false,
  40594. ROTATE_INSTRUCTIONS_DISABLED: false,
  40595. YAW_ONLY: false,
  40596. BUFFER_SCALE: 0.5,
  40597. DIRTY_SUBMIT_FRAME_BINDINGS: false
  40598. };
  40599. var Eye = {
  40600. LEFT: 'left',
  40601. RIGHT: 'right'
  40602. };
  40603. function CardboardVRDisplay(config$$1) {
  40604. var defaults = extend({}, config);
  40605. config$$1 = extend(defaults, config$$1 || {});
  40606. VRDisplay.call(this, {
  40607. wakelock: config$$1.MOBILE_WAKE_LOCK
  40608. });
  40609. this.config = config$$1;
  40610. this.displayName = 'Cardboard VRDisplay';
  40611. this.capabilities = new VRDisplayCapabilities({
  40612. hasPosition: false,
  40613. hasOrientation: true,
  40614. hasExternalDisplay: false,
  40615. canPresent: true,
  40616. maxLayers: 1
  40617. });
  40618. this.stageParameters = null;
  40619. this.bufferScale_ = this.config.BUFFER_SCALE;
  40620. this.poseSensor_ = new PoseSensor(this.config);
  40621. this.distorter_ = null;
  40622. this.cardboardUI_ = null;
  40623. this.dpdb_ = new Dpdb(this.config.DPDB_URL, this.onDeviceParamsUpdated_.bind(this));
  40624. this.deviceInfo_ = new DeviceInfo(this.dpdb_.getDeviceParams(), config$$1.ADDITIONAL_VIEWERS);
  40625. this.viewerSelector_ = new ViewerSelector(config$$1.DEFAULT_VIEWER);
  40626. this.viewerSelector_.onChange(this.onViewerChanged_.bind(this));
  40627. this.deviceInfo_.setViewer(this.viewerSelector_.getCurrentViewer());
  40628. if (!this.config.ROTATE_INSTRUCTIONS_DISABLED) {
  40629. this.rotateInstructions_ = new RotateInstructions();
  40630. }
  40631. if (isIOS()) {
  40632. window.addEventListener('resize', this.onResize_.bind(this));
  40633. }
  40634. }
  40635. CardboardVRDisplay.prototype = Object.create(VRDisplay.prototype);
  40636. CardboardVRDisplay.prototype._getPose = function () {
  40637. return {
  40638. position: null,
  40639. orientation: this.poseSensor_.getOrientation(),
  40640. linearVelocity: null,
  40641. linearAcceleration: null,
  40642. angularVelocity: null,
  40643. angularAcceleration: null
  40644. };
  40645. };
  40646. CardboardVRDisplay.prototype._resetPose = function () {
  40647. if (this.poseSensor_.resetPose) {
  40648. this.poseSensor_.resetPose();
  40649. }
  40650. };
  40651. CardboardVRDisplay.prototype._getFieldOfView = function (whichEye) {
  40652. var fieldOfView;
  40653. if (whichEye == Eye.LEFT) {
  40654. fieldOfView = this.deviceInfo_.getFieldOfViewLeftEye();
  40655. } else if (whichEye == Eye.RIGHT) {
  40656. fieldOfView = this.deviceInfo_.getFieldOfViewRightEye();
  40657. } else {
  40658. console.error('Invalid eye provided: %s', whichEye);
  40659. return null;
  40660. }
  40661. return fieldOfView;
  40662. };
  40663. CardboardVRDisplay.prototype._getEyeOffset = function (whichEye) {
  40664. var offset;
  40665. if (whichEye == Eye.LEFT) {
  40666. offset = [-this.deviceInfo_.viewer.interLensDistance * 0.5, 0.0, 0.0];
  40667. } else if (whichEye == Eye.RIGHT) {
  40668. offset = [this.deviceInfo_.viewer.interLensDistance * 0.5, 0.0, 0.0];
  40669. } else {
  40670. console.error('Invalid eye provided: %s', whichEye);
  40671. return null;
  40672. }
  40673. return offset;
  40674. };
  40675. CardboardVRDisplay.prototype.getEyeParameters = function (whichEye) {
  40676. var offset = this._getEyeOffset(whichEye);
  40677. var fieldOfView = this._getFieldOfView(whichEye);
  40678. var eyeParams = {
  40679. offset: offset,
  40680. renderWidth: this.deviceInfo_.device.width * 0.5 * this.bufferScale_,
  40681. renderHeight: this.deviceInfo_.device.height * this.bufferScale_
  40682. };
  40683. Object.defineProperty(eyeParams, 'fieldOfView', {
  40684. enumerable: true,
  40685. get: function get() {
  40686. deprecateWarning('VRFieldOfView', 'VRFrameData\'s projection matrices');
  40687. return fieldOfView;
  40688. }
  40689. });
  40690. return eyeParams;
  40691. };
  40692. CardboardVRDisplay.prototype.onDeviceParamsUpdated_ = function (newParams) {
  40693. if (this.config.DEBUG) {
  40694. console.log('DPDB reported that device params were updated.');
  40695. }
  40696. this.deviceInfo_.updateDeviceParams(newParams);
  40697. if (this.distorter_) {
  40698. this.distorter_.updateDeviceInfo(this.deviceInfo_);
  40699. }
  40700. };
  40701. CardboardVRDisplay.prototype.updateBounds_ = function () {
  40702. if (this.layer_ && this.distorter_ && (this.layer_.leftBounds || this.layer_.rightBounds)) {
  40703. this.distorter_.setTextureBounds(this.layer_.leftBounds, this.layer_.rightBounds);
  40704. }
  40705. };
  40706. CardboardVRDisplay.prototype.beginPresent_ = function () {
  40707. var gl = this.layer_.source.getContext('webgl');
  40708. if (!gl) gl = this.layer_.source.getContext('experimental-webgl');
  40709. if (!gl) gl = this.layer_.source.getContext('webgl2');
  40710. if (!gl) return;
  40711. if (this.layer_.predistorted) {
  40712. if (!this.config.CARDBOARD_UI_DISABLED) {
  40713. gl.canvas.width = getScreenWidth() * this.bufferScale_;
  40714. gl.canvas.height = getScreenHeight() * this.bufferScale_;
  40715. this.cardboardUI_ = new CardboardUI(gl);
  40716. }
  40717. } else {
  40718. if (!this.config.CARDBOARD_UI_DISABLED) {
  40719. this.cardboardUI_ = new CardboardUI(gl);
  40720. }
  40721. this.distorter_ = new CardboardDistorter(gl, this.cardboardUI_, this.config.BUFFER_SCALE, this.config.DIRTY_SUBMIT_FRAME_BINDINGS);
  40722. this.distorter_.updateDeviceInfo(this.deviceInfo_);
  40723. }
  40724. if (this.cardboardUI_) {
  40725. this.cardboardUI_.listen(function (e) {
  40726. this.viewerSelector_.show(this.layer_.source.parentElement);
  40727. e.stopPropagation();
  40728. e.preventDefault();
  40729. }.bind(this), function (e) {
  40730. this.exitPresent();
  40731. e.stopPropagation();
  40732. e.preventDefault();
  40733. }.bind(this));
  40734. }
  40735. if (this.rotateInstructions_) {
  40736. if (isLandscapeMode() && isMobile()) {
  40737. this.rotateInstructions_.showTemporarily(3000, this.layer_.source.parentElement);
  40738. } else {
  40739. this.rotateInstructions_.update();
  40740. }
  40741. }
  40742. this.orientationHandler = this.onOrientationChange_.bind(this);
  40743. window.addEventListener('orientationchange', this.orientationHandler);
  40744. this.vrdisplaypresentchangeHandler = this.updateBounds_.bind(this);
  40745. window.addEventListener('vrdisplaypresentchange', this.vrdisplaypresentchangeHandler);
  40746. this.fireVRDisplayDeviceParamsChange_();
  40747. };
  40748. CardboardVRDisplay.prototype.endPresent_ = function () {
  40749. if (this.distorter_) {
  40750. this.distorter_.destroy();
  40751. this.distorter_ = null;
  40752. }
  40753. if (this.cardboardUI_) {
  40754. this.cardboardUI_.destroy();
  40755. this.cardboardUI_ = null;
  40756. }
  40757. if (this.rotateInstructions_) {
  40758. this.rotateInstructions_.hide();
  40759. }
  40760. this.viewerSelector_.hide();
  40761. window.removeEventListener('orientationchange', this.orientationHandler);
  40762. window.removeEventListener('vrdisplaypresentchange', this.vrdisplaypresentchangeHandler);
  40763. };
  40764. CardboardVRDisplay.prototype.updatePresent_ = function () {
  40765. this.endPresent_();
  40766. this.beginPresent_();
  40767. };
  40768. CardboardVRDisplay.prototype.submitFrame = function (pose) {
  40769. if (this.distorter_) {
  40770. this.updateBounds_();
  40771. this.distorter_.submitFrame();
  40772. } else if (this.cardboardUI_ && this.layer_) {
  40773. var canvas = this.layer_.source.getContext('webgl').canvas;
  40774. if (canvas.width != this.lastWidth || canvas.height != this.lastHeight) {
  40775. this.cardboardUI_.onResize();
  40776. }
  40777. this.lastWidth = canvas.width;
  40778. this.lastHeight = canvas.height;
  40779. this.cardboardUI_.render();
  40780. }
  40781. };
  40782. CardboardVRDisplay.prototype.onOrientationChange_ = function (e) {
  40783. this.viewerSelector_.hide();
  40784. if (this.rotateInstructions_) {
  40785. this.rotateInstructions_.update();
  40786. }
  40787. this.onResize_();
  40788. };
  40789. CardboardVRDisplay.prototype.onResize_ = function (e) {
  40790. if (this.layer_) {
  40791. var gl = this.layer_.source.getContext('webgl');
  40792. var cssProperties = ['position: absolute', 'top: 0', 'left: 0',
  40793. 'width: 100vw', 'height: 100vh', 'border: 0', 'margin: 0',
  40794. 'padding: 0px', 'box-sizing: content-box'];
  40795. gl.canvas.setAttribute('style', cssProperties.join('; ') + ';');
  40796. safariCssSizeWorkaround(gl.canvas);
  40797. }
  40798. };
  40799. CardboardVRDisplay.prototype.onViewerChanged_ = function (viewer) {
  40800. this.deviceInfo_.setViewer(viewer);
  40801. if (this.distorter_) {
  40802. this.distorter_.updateDeviceInfo(this.deviceInfo_);
  40803. }
  40804. this.fireVRDisplayDeviceParamsChange_();
  40805. };
  40806. CardboardVRDisplay.prototype.fireVRDisplayDeviceParamsChange_ = function () {
  40807. var event = new CustomEvent('vrdisplaydeviceparamschange', {
  40808. detail: {
  40809. vrdisplay: this,
  40810. deviceInfo: this.deviceInfo_
  40811. }
  40812. });
  40813. window.dispatchEvent(event);
  40814. };
  40815. CardboardVRDisplay.VRFrameData = VRFrameData;
  40816. CardboardVRDisplay.VRDisplay = VRDisplay;
  40817. return CardboardVRDisplay;
  40818. })));
  40819. });
  40820. var CardboardVRDisplay = unwrapExports(cardboardVrDisplay);
  40821. var version = "0.10.10";
  40822. var DefaultConfig = {
  40823. ADDITIONAL_VIEWERS: [],
  40824. DEFAULT_VIEWER: '',
  40825. PROVIDE_MOBILE_VRDISPLAY: true,
  40826. MOBILE_WAKE_LOCK: true,
  40827. DEBUG: false,
  40828. DPDB_URL: 'https://dpdb.webvr.rocks/dpdb.json',
  40829. K_FILTER: 0.98,
  40830. PREDICTION_TIME_S: 0.040,
  40831. CARDBOARD_UI_DISABLED: false,
  40832. ROTATE_INSTRUCTIONS_DISABLED: false,
  40833. YAW_ONLY: false,
  40834. BUFFER_SCALE: 0.5,
  40835. DIRTY_SUBMIT_FRAME_BINDINGS: false
  40836. };
  40837. function WebVRPolyfill(config) {
  40838. this.config = extend(extend({}, DefaultConfig), config);
  40839. this.polyfillDisplays = [];
  40840. this.enabled = false;
  40841. this.hasNative = 'getVRDisplays' in navigator;
  40842. this.native = {};
  40843. this.native.getVRDisplays = navigator.getVRDisplays;
  40844. this.native.VRFrameData = window.VRFrameData;
  40845. this.native.VRDisplay = window.VRDisplay;
  40846. if (!this.hasNative || this.config.PROVIDE_MOBILE_VRDISPLAY && isMobile()) {
  40847. this.enable();
  40848. this.getVRDisplays().then(function (displays) {
  40849. if (displays && displays[0] && displays[0].fireVRDisplayConnect_) {
  40850. displays[0].fireVRDisplayConnect_();
  40851. }
  40852. });
  40853. }
  40854. }
  40855. WebVRPolyfill.prototype.getPolyfillDisplays = function () {
  40856. if (this._polyfillDisplaysPopulated) {
  40857. return this.polyfillDisplays;
  40858. }
  40859. if (isMobile()) {
  40860. var vrDisplay = new CardboardVRDisplay({
  40861. ADDITIONAL_VIEWERS: this.config.ADDITIONAL_VIEWERS,
  40862. DEFAULT_VIEWER: this.config.DEFAULT_VIEWER,
  40863. MOBILE_WAKE_LOCK: this.config.MOBILE_WAKE_LOCK,
  40864. DEBUG: this.config.DEBUG,
  40865. DPDB_URL: this.config.DPDB_URL,
  40866. CARDBOARD_UI_DISABLED: this.config.CARDBOARD_UI_DISABLED,
  40867. K_FILTER: this.config.K_FILTER,
  40868. PREDICTION_TIME_S: this.config.PREDICTION_TIME_S,
  40869. ROTATE_INSTRUCTIONS_DISABLED: this.config.ROTATE_INSTRUCTIONS_DISABLED,
  40870. YAW_ONLY: this.config.YAW_ONLY,
  40871. BUFFER_SCALE: this.config.BUFFER_SCALE,
  40872. DIRTY_SUBMIT_FRAME_BINDINGS: this.config.DIRTY_SUBMIT_FRAME_BINDINGS
  40873. });
  40874. this.polyfillDisplays.push(vrDisplay);
  40875. }
  40876. this._polyfillDisplaysPopulated = true;
  40877. return this.polyfillDisplays;
  40878. };
  40879. WebVRPolyfill.prototype.enable = function () {
  40880. this.enabled = true;
  40881. if (this.hasNative && this.native.VRFrameData) {
  40882. var NativeVRFrameData = this.native.VRFrameData;
  40883. var nativeFrameData = new this.native.VRFrameData();
  40884. var nativeGetFrameData = this.native.VRDisplay.prototype.getFrameData;
  40885. window.VRDisplay.prototype.getFrameData = function (frameData) {
  40886. if (frameData instanceof NativeVRFrameData) {
  40887. nativeGetFrameData.call(this, frameData);
  40888. return;
  40889. }
  40890. nativeGetFrameData.call(this, nativeFrameData);
  40891. frameData.pose = nativeFrameData.pose;
  40892. copyArray(nativeFrameData.leftProjectionMatrix, frameData.leftProjectionMatrix);
  40893. copyArray(nativeFrameData.rightProjectionMatrix, frameData.rightProjectionMatrix);
  40894. copyArray(nativeFrameData.leftViewMatrix, frameData.leftViewMatrix);
  40895. copyArray(nativeFrameData.rightViewMatrix, frameData.rightViewMatrix);
  40896. };
  40897. }
  40898. navigator.getVRDisplays = this.getVRDisplays.bind(this);
  40899. window.VRDisplay = CardboardVRDisplay.VRDisplay;
  40900. window.VRFrameData = CardboardVRDisplay.VRFrameData;
  40901. };
  40902. WebVRPolyfill.prototype.getVRDisplays = function () {
  40903. var _this = this;
  40904. var config = this.config;
  40905. if (!this.hasNative) {
  40906. return Promise.resolve(this.getPolyfillDisplays());
  40907. }
  40908. return this.native.getVRDisplays.call(navigator).then(function (nativeDisplays) {
  40909. return nativeDisplays.length > 0 ? nativeDisplays : _this.getPolyfillDisplays();
  40910. });
  40911. };
  40912. WebVRPolyfill.version = version;
  40913. WebVRPolyfill.VRFrameData = CardboardVRDisplay.VRFrameData;
  40914. WebVRPolyfill.VRDisplay = CardboardVRDisplay.VRDisplay;
  40915. var webvrPolyfill = Object.freeze({
  40916. default: WebVRPolyfill
  40917. });
  40918. var require$$0 = ( webvrPolyfill && WebVRPolyfill ) || webvrPolyfill;
  40919. if (typeof commonjsGlobal !== 'undefined' && commonjsGlobal.window) {
  40920. if (!commonjsGlobal.document) {
  40921. commonjsGlobal.document = commonjsGlobal.window.document;
  40922. }
  40923. if (!commonjsGlobal.navigator) {
  40924. commonjsGlobal.navigator = commonjsGlobal.window.navigator;
  40925. }
  40926. }
  40927. var src = require$$0;
  40928. return src;
  40929. })));
  40930. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  40931. },{}],47:[function(_dereq_,module,exports){
  40932. var newline = /\n/
  40933. var newlineChar = '\n'
  40934. var whitespace = /\s/
  40935. module.exports = function(text, opt) {
  40936. var lines = module.exports.lines(text, opt)
  40937. return lines.map(function(line) {
  40938. return text.substring(line.start, line.end)
  40939. }).join('\n')
  40940. }
  40941. module.exports.lines = function wordwrap(text, opt) {
  40942. opt = opt||{}
  40943. //zero width results in nothing visible
  40944. if (opt.width === 0 && opt.mode !== 'nowrap')
  40945. return []
  40946. text = text||''
  40947. var width = typeof opt.width === 'number' ? opt.width : Number.MAX_VALUE
  40948. var start = Math.max(0, opt.start||0)
  40949. var end = typeof opt.end === 'number' ? opt.end : text.length
  40950. var mode = opt.mode
  40951. var measure = opt.measure || monospace
  40952. if (mode === 'pre')
  40953. return pre(measure, text, start, end, width)
  40954. else
  40955. return greedy(measure, text, start, end, width, mode)
  40956. }
  40957. function idxOf(text, chr, start, end) {
  40958. var idx = text.indexOf(chr, start)
  40959. if (idx === -1 || idx > end)
  40960. return end
  40961. return idx
  40962. }
  40963. function isWhitespace(chr) {
  40964. return whitespace.test(chr)
  40965. }
  40966. function pre(measure, text, start, end, width) {
  40967. var lines = []
  40968. var lineStart = start
  40969. for (var i=start; i<end && i<text.length; i++) {
  40970. var chr = text.charAt(i)
  40971. var isNewline = newline.test(chr)
  40972. //If we've reached a newline, then step down a line
  40973. //Or if we've reached the EOF
  40974. if (isNewline || i===end-1) {
  40975. var lineEnd = isNewline ? i : i+1
  40976. var measured = measure(text, lineStart, lineEnd, width)
  40977. lines.push(measured)
  40978. lineStart = i+1
  40979. }
  40980. }
  40981. return lines
  40982. }
  40983. function greedy(measure, text, start, end, width, mode) {
  40984. //A greedy word wrapper based on LibGDX algorithm
  40985. //https://github.com/libgdx/libgdx/blob/master/gdx/src/com/badlogic/gdx/graphics/g2d/BitmapFontCache.java
  40986. var lines = []
  40987. var testWidth = width
  40988. //if 'nowrap' is specified, we only wrap on newline chars
  40989. if (mode === 'nowrap')
  40990. testWidth = Number.MAX_VALUE
  40991. while (start < end && start < text.length) {
  40992. //get next newline position
  40993. var newLine = idxOf(text, newlineChar, start, end)
  40994. //eat whitespace at start of line
  40995. while (start < newLine) {
  40996. if (!isWhitespace( text.charAt(start) ))
  40997. break
  40998. start++
  40999. }
  41000. //determine visible # of glyphs for the available width
  41001. var measured = measure(text, start, newLine, testWidth)
  41002. var lineEnd = start + (measured.end-measured.start)
  41003. var nextStart = lineEnd + newlineChar.length
  41004. //if we had to cut the line before the next newline...
  41005. if (lineEnd < newLine) {
  41006. //find char to break on
  41007. while (lineEnd > start) {
  41008. if (isWhitespace(text.charAt(lineEnd)))
  41009. break
  41010. lineEnd--
  41011. }
  41012. if (lineEnd === start) {
  41013. if (nextStart > start + newlineChar.length) nextStart--
  41014. lineEnd = nextStart // If no characters to break, show all.
  41015. } else {
  41016. nextStart = lineEnd
  41017. //eat whitespace at end of line
  41018. while (lineEnd > start) {
  41019. if (!isWhitespace(text.charAt(lineEnd - newlineChar.length)))
  41020. break
  41021. lineEnd--
  41022. }
  41023. }
  41024. }
  41025. if (lineEnd >= start) {
  41026. var result = measure(text, start, lineEnd, testWidth)
  41027. lines.push(result)
  41028. }
  41029. start = nextStart
  41030. }
  41031. return lines
  41032. }
  41033. //determines the visible number of glyphs within a given width
  41034. function monospace(text, start, end, width) {
  41035. var glyphs = Math.min(width, end-start)
  41036. return {
  41037. start: start,
  41038. end: start+glyphs
  41039. }
  41040. }
  41041. },{}],48:[function(_dereq_,module,exports){
  41042. "use strict";
  41043. var window = _dereq_("global/window")
  41044. var isFunction = _dereq_("is-function")
  41045. var parseHeaders = _dereq_("parse-headers")
  41046. var xtend = _dereq_("xtend")
  41047. module.exports = createXHR
  41048. createXHR.XMLHttpRequest = window.XMLHttpRequest || noop
  41049. createXHR.XDomainRequest = "withCredentials" in (new createXHR.XMLHttpRequest()) ? createXHR.XMLHttpRequest : window.XDomainRequest
  41050. forEachArray(["get", "put", "post", "patch", "head", "delete"], function(method) {
  41051. createXHR[method === "delete" ? "del" : method] = function(uri, options, callback) {
  41052. options = initParams(uri, options, callback)
  41053. options.method = method.toUpperCase()
  41054. return _createXHR(options)
  41055. }
  41056. })
  41057. function forEachArray(array, iterator) {
  41058. for (var i = 0; i < array.length; i++) {
  41059. iterator(array[i])
  41060. }
  41061. }
  41062. function isEmpty(obj){
  41063. for(var i in obj){
  41064. if(obj.hasOwnProperty(i)) return false
  41065. }
  41066. return true
  41067. }
  41068. function initParams(uri, options, callback) {
  41069. var params = uri
  41070. if (isFunction(options)) {
  41071. callback = options
  41072. if (typeof uri === "string") {
  41073. params = {uri:uri}
  41074. }
  41075. } else {
  41076. params = xtend(options, {uri: uri})
  41077. }
  41078. params.callback = callback
  41079. return params
  41080. }
  41081. function createXHR(uri, options, callback) {
  41082. options = initParams(uri, options, callback)
  41083. return _createXHR(options)
  41084. }
  41085. function _createXHR(options) {
  41086. if(typeof options.callback === "undefined"){
  41087. throw new Error("callback argument missing")
  41088. }
  41089. var called = false
  41090. var callback = function cbOnce(err, response, body){
  41091. if(!called){
  41092. called = true
  41093. options.callback(err, response, body)
  41094. }
  41095. }
  41096. function readystatechange() {
  41097. if (xhr.readyState === 4) {
  41098. setTimeout(loadFunc, 0)
  41099. }
  41100. }
  41101. function getBody() {
  41102. // Chrome with requestType=blob throws errors arround when even testing access to responseText
  41103. var body = undefined
  41104. if (xhr.response) {
  41105. body = xhr.response
  41106. } else {
  41107. body = xhr.responseText || getXml(xhr)
  41108. }
  41109. if (isJson) {
  41110. try {
  41111. body = JSON.parse(body)
  41112. } catch (e) {}
  41113. }
  41114. return body
  41115. }
  41116. function errorFunc(evt) {
  41117. clearTimeout(timeoutTimer)
  41118. if(!(evt instanceof Error)){
  41119. evt = new Error("" + (evt || "Unknown XMLHttpRequest Error") )
  41120. }
  41121. evt.statusCode = 0
  41122. return callback(evt, failureResponse)
  41123. }
  41124. // will load the data & process the response in a special response object
  41125. function loadFunc() {
  41126. if (aborted) return
  41127. var status
  41128. clearTimeout(timeoutTimer)
  41129. if(options.useXDR && xhr.status===undefined) {
  41130. //IE8 CORS GET successful response doesn't have a status field, but body is fine
  41131. status = 200
  41132. } else {
  41133. status = (xhr.status === 1223 ? 204 : xhr.status)
  41134. }
  41135. var response = failureResponse
  41136. var err = null
  41137. if (status !== 0){
  41138. response = {
  41139. body: getBody(),
  41140. statusCode: status,
  41141. method: method,
  41142. headers: {},
  41143. url: uri,
  41144. rawRequest: xhr
  41145. }
  41146. if(xhr.getAllResponseHeaders){ //remember xhr can in fact be XDR for CORS in IE
  41147. response.headers = parseHeaders(xhr.getAllResponseHeaders())
  41148. }
  41149. } else {
  41150. err = new Error("Internal XMLHttpRequest Error")
  41151. }
  41152. return callback(err, response, response.body)
  41153. }
  41154. var xhr = options.xhr || null
  41155. if (!xhr) {
  41156. if (options.cors || options.useXDR) {
  41157. xhr = new createXHR.XDomainRequest()
  41158. }else{
  41159. xhr = new createXHR.XMLHttpRequest()
  41160. }
  41161. }
  41162. var key
  41163. var aborted
  41164. var uri = xhr.url = options.uri || options.url
  41165. var method = xhr.method = options.method || "GET"
  41166. var body = options.body || options.data
  41167. var headers = xhr.headers = options.headers || {}
  41168. var sync = !!options.sync
  41169. var isJson = false
  41170. var timeoutTimer
  41171. var failureResponse = {
  41172. body: undefined,
  41173. headers: {},
  41174. statusCode: 0,
  41175. method: method,
  41176. url: uri,
  41177. rawRequest: xhr
  41178. }
  41179. if ("json" in options && options.json !== false) {
  41180. isJson = true
  41181. headers["accept"] || headers["Accept"] || (headers["Accept"] = "application/json") //Don't override existing accept header declared by user
  41182. if (method !== "GET" && method !== "HEAD") {
  41183. headers["content-type"] || headers["Content-Type"] || (headers["Content-Type"] = "application/json") //Don't override existing accept header declared by user
  41184. body = JSON.stringify(options.json === true ? body : options.json)
  41185. }
  41186. }
  41187. xhr.onreadystatechange = readystatechange
  41188. xhr.onload = loadFunc
  41189. xhr.onerror = errorFunc
  41190. // IE9 must have onprogress be set to a unique function.
  41191. xhr.onprogress = function () {
  41192. // IE must die
  41193. }
  41194. xhr.onabort = function(){
  41195. aborted = true;
  41196. }
  41197. xhr.ontimeout = errorFunc
  41198. xhr.open(method, uri, !sync, options.username, options.password)
  41199. //has to be after open
  41200. if(!sync) {
  41201. xhr.withCredentials = !!options.withCredentials
  41202. }
  41203. // Cannot set timeout with sync request
  41204. // not setting timeout on the xhr object, because of old webkits etc. not handling that correctly
  41205. // both npm's request and jquery 1.x use this kind of timeout, so this is being consistent
  41206. if (!sync && options.timeout > 0 ) {
  41207. timeoutTimer = setTimeout(function(){
  41208. if (aborted) return
  41209. aborted = true//IE9 may still call readystatechange
  41210. xhr.abort("timeout")
  41211. var e = new Error("XMLHttpRequest timeout")
  41212. e.code = "ETIMEDOUT"
  41213. errorFunc(e)
  41214. }, options.timeout )
  41215. }
  41216. if (xhr.setRequestHeader) {
  41217. for(key in headers){
  41218. if(headers.hasOwnProperty(key)){
  41219. xhr.setRequestHeader(key, headers[key])
  41220. }
  41221. }
  41222. } else if (options.headers && !isEmpty(options.headers)) {
  41223. throw new Error("Headers cannot be set on an XDomainRequest object")
  41224. }
  41225. if ("responseType" in options) {
  41226. xhr.responseType = options.responseType
  41227. }
  41228. if ("beforeSend" in options &&
  41229. typeof options.beforeSend === "function"
  41230. ) {
  41231. options.beforeSend(xhr)
  41232. }
  41233. // Microsoft Edge browser sends "undefined" when send is called with undefined value.
  41234. // XMLHttpRequest spec says to pass null as body to indicate no body
  41235. // See https://github.com/naugtur/xhr/issues/100.
  41236. xhr.send(body || null)
  41237. return xhr
  41238. }
  41239. function getXml(xhr) {
  41240. // xhr.responseXML will throw Exception "InvalidStateError" or "DOMException"
  41241. // See https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/responseXML.
  41242. try {
  41243. if (xhr.responseType === "document") {
  41244. return xhr.responseXML
  41245. }
  41246. var firefoxBugTakenEffect = xhr.responseXML && xhr.responseXML.documentElement.nodeName === "parsererror"
  41247. if (xhr.responseType === "" && !firefoxBugTakenEffect) {
  41248. return xhr.responseXML
  41249. }
  41250. } catch (e) {}
  41251. return null
  41252. }
  41253. function noop() {}
  41254. },{"global/window":15,"is-function":19,"parse-headers":30,"xtend":50}],49:[function(_dereq_,module,exports){
  41255. module.exports = (function xmlparser() {
  41256. //common browsers
  41257. if (typeof self.DOMParser !== 'undefined') {
  41258. return function(str) {
  41259. var parser = new self.DOMParser()
  41260. return parser.parseFromString(str, 'application/xml')
  41261. }
  41262. }
  41263. //IE8 fallback
  41264. if (typeof self.ActiveXObject !== 'undefined'
  41265. && new self.ActiveXObject('Microsoft.XMLDOM')) {
  41266. return function(str) {
  41267. var xmlDoc = new self.ActiveXObject("Microsoft.XMLDOM")
  41268. xmlDoc.async = "false"
  41269. xmlDoc.loadXML(str)
  41270. return xmlDoc
  41271. }
  41272. }
  41273. //last resort fallback
  41274. return function(str) {
  41275. var div = document.createElement('div')
  41276. div.innerHTML = str
  41277. return div
  41278. }
  41279. })()
  41280. },{}],50:[function(_dereq_,module,exports){
  41281. module.exports = extend
  41282. var hasOwnProperty = Object.prototype.hasOwnProperty;
  41283. function extend() {
  41284. var target = {}
  41285. for (var i = 0; i < arguments.length; i++) {
  41286. var source = arguments[i]
  41287. for (var key in source) {
  41288. if (hasOwnProperty.call(source, key)) {
  41289. target[key] = source[key]
  41290. }
  41291. }
  41292. }
  41293. return target
  41294. }
  41295. },{}],51:[function(_dereq_,module,exports){
  41296. module.exports={
  41297. "name": "aframe",
  41298. "version": "0.9.2",
  41299. "description": "A web framework for building virtual reality experiences.",
  41300. "homepage": "https://aframe.io/",
  41301. "main": "dist/aframe-master.js",
  41302. "scripts": {
  41303. "browserify": "browserify src/index.js -s 'AFRAME' -p browserify-derequire",
  41304. "build": "shx mkdir -p build/ && npm run browserify -- --debug -t [envify --INSPECTOR_VERSION dev] -o build/aframe.js",
  41305. "codecov": "codecov",
  41306. "dev": "npm run build && cross-env INSPECTOR_VERSION=dev node ./scripts/budo -t envify",
  41307. "dist": "node scripts/updateVersionLog.js && npm run dist:min && npm run dist:max",
  41308. "dist:max": "npm run browserify -s -- --debug | exorcist dist/aframe-master.js.map > dist/aframe-master.js",
  41309. "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",
  41310. "docs": "markserv --dir docs --port 9001",
  41311. "preghpages": "node ./scripts/preghpages.js",
  41312. "ghpages": "ghpages -p gh-pages/",
  41313. "lint": "semistandard -v | snazzy",
  41314. "lint:fix": "semistandard --fix",
  41315. "precommit": "npm run lint",
  41316. "prepush": "node scripts/testOnlyCheck.js",
  41317. "prerelease": "node scripts/release.js 0.9.1 0.9.2",
  41318. "start": "npm run dev",
  41319. "start:https": "cross-env SSL=true npm run dev",
  41320. "test": "karma start ./tests/karma.conf.js",
  41321. "test:docs": "node scripts/docsLint.js",
  41322. "test:firefox": "npm test -- --browsers Firefox",
  41323. "test:chrome": "npm test -- --browsers Chrome",
  41324. "test:nobrowser": "NO_BROWSER=true npm test",
  41325. "test:node": "mocha --ui tdd tests/node"
  41326. },
  41327. "repository": "aframevr/aframe",
  41328. "license": "MIT",
  41329. "files": [
  41330. "dist/*",
  41331. "docs/**/*",
  41332. "src/**/*",
  41333. "vendor/**/*"
  41334. ],
  41335. "dependencies": {
  41336. "browserify-css": "^0.8.4",
  41337. "custom-event-polyfill": "^1.0.6",
  41338. "debug": "ngokevin/debug#noTimestamp",
  41339. "deep-assign": "^2.0.0",
  41340. "document-register-element": "dmarcos/document-register-element#8ccc532b7f3744be954574caf3072a5fd260ca90",
  41341. "envify": "^3.4.1",
  41342. "load-bmfont": "^1.2.3",
  41343. "object-assign": "^4.0.1",
  41344. "present": "0.0.6",
  41345. "promise-polyfill": "^3.1.0",
  41346. "style-attr": "^1.0.2",
  41347. "super-animejs": "^3.0.0",
  41348. "super-three": "^0.102.2",
  41349. "three-bmfont-text": "^2.1.0",
  41350. "webvr-polyfill": "^0.10.10"
  41351. },
  41352. "devDependencies": {
  41353. "browserify": "^13.1.0",
  41354. "browserify-derequire": "^0.9.4",
  41355. "browserify-istanbul": "^2.0.0",
  41356. "budo": "^9.2.0",
  41357. "chai": "^3.5.0",
  41358. "chai-shallow-deep-equal": "^1.4.0",
  41359. "chalk": "^1.1.3",
  41360. "codecov": "^1.0.1",
  41361. "cross-env": "^5.0.1",
  41362. "exorcist": "^0.4.0",
  41363. "ghpages": "0.0.8",
  41364. "git-rev": "^0.2.1",
  41365. "glob": "^7.1.1",
  41366. "husky": "^0.11.7",
  41367. "istanbul": "^0.4.5",
  41368. "jsdom": "^9.11.0",
  41369. "karma": "1.4.1",
  41370. "karma-browserify": "^5.1.0",
  41371. "karma-chai-shallow-deep-equal": "0.0.4",
  41372. "karma-chrome-launcher": "^2.0.0",
  41373. "karma-coverage": "^1.1.1",
  41374. "karma-env-preprocessor": "^0.1.1",
  41375. "karma-firefox-launcher": "^1.0.0",
  41376. "karma-mocha": "^1.1.1",
  41377. "karma-mocha-reporter": "^2.1.0",
  41378. "karma-sinon-chai": "1.2.4",
  41379. "lolex": "^1.5.1",
  41380. "markserv": "github:sukima/markserv#feature/fix-broken-websoketio-link",
  41381. "minifyify": "^7.3.3",
  41382. "mocha": "^3.0.2",
  41383. "mozilla-download": "^1.1.1",
  41384. "replace-in-file": "^2.5.3",
  41385. "semistandard": "^9.0.0",
  41386. "shelljs": "^0.7.7",
  41387. "shx": "^0.2.2",
  41388. "sinon": "^1.17.5",
  41389. "sinon-chai": "2.8.0",
  41390. "snazzy": "^5.0.0",
  41391. "too-wordy": "ngokevin/too-wordy",
  41392. "uglifyjs": "^2.4.10",
  41393. "write-good": "^0.9.1"
  41394. },
  41395. "link": true,
  41396. "browserify": {
  41397. "transform": [
  41398. "browserify-css",
  41399. "envify"
  41400. ]
  41401. },
  41402. "semistandard": {
  41403. "ignore": [
  41404. "build/**",
  41405. "dist/**",
  41406. "examples/**/shaders/*.js",
  41407. "**/vendor/**"
  41408. ]
  41409. },
  41410. "keywords": [
  41411. "3d",
  41412. "aframe",
  41413. "cardboard",
  41414. "components",
  41415. "oculus",
  41416. "three",
  41417. "three.js",
  41418. "rift",
  41419. "vive",
  41420. "vr",
  41421. "web-components",
  41422. "webvr"
  41423. ],
  41424. "browserify-css": {
  41425. "minify": true
  41426. },
  41427. "engines": {
  41428. "node": ">= 4.6.0",
  41429. "npm": "^2.15.9"
  41430. }
  41431. }
  41432. },{}],52:[function(_dereq_,module,exports){
  41433. var anime = _dereq_('super-animejs');
  41434. var components = _dereq_('../core/component').components;
  41435. var registerComponent = _dereq_('../core/component').registerComponent;
  41436. var THREE = _dereq_('../lib/three');
  41437. var utils = _dereq_('../utils');
  41438. var colorHelperFrom = new THREE.Color();
  41439. var colorHelperTo = new THREE.Color();
  41440. var getComponentProperty = utils.entity.getComponentProperty;
  41441. var setComponentProperty = utils.entity.setComponentProperty;
  41442. var splitCache = {};
  41443. var TYPE_COLOR = 'color';
  41444. var PROP_POSITION = 'position';
  41445. var PROP_ROTATION = 'rotation';
  41446. var PROP_SCALE = 'scale';
  41447. var STRING_COMPONENTS = 'components';
  41448. var STRING_OBJECT3D = 'object3D';
  41449. /**
  41450. * Animation component for A-Frame using anime.js.
  41451. *
  41452. * The component manually controls the tick by setting `autoplay: false` on anime.js and
  41453. * manually * calling `animation.tick()` in the tick handler. To pause or resume, we toggle a
  41454. * boolean * flag * `isAnimationPlaying`.
  41455. *
  41456. * anime.js animation config for tweenining Javascript objects and values works as:
  41457. *
  41458. * config = {
  41459. * targets: {foo: 0.0, bar: '#000'},
  41460. * foo: 1.0,
  41461. * bar: '#FFF'
  41462. * }
  41463. *
  41464. * The above will tween each property in `targets`. The `to` values are set in the root of
  41465. * the config.
  41466. *
  41467. * @member {object} animation - anime.js instance.
  41468. * @member {boolean} animationIsPlaying - Control if animation is playing.
  41469. */
  41470. module.exports.Component = registerComponent('animation', {
  41471. schema: {
  41472. autoplay: {default: true},
  41473. delay: {default: 0},
  41474. dir: {default: ''},
  41475. dur: {default: 1000},
  41476. easing: {default: 'easeInQuad'},
  41477. elasticity: {default: 400},
  41478. enabled: {default: true},
  41479. from: {default: ''},
  41480. loop: {
  41481. default: 0,
  41482. parse: function (value) {
  41483. // Boolean or integer.
  41484. if (value === true || value === 'true') { return true; }
  41485. if (value === false || value === 'false') { return false; }
  41486. return parseInt(value, 10);
  41487. }
  41488. },
  41489. property: {default: ''},
  41490. startEvents: {type: 'array'},
  41491. pauseEvents: {type: 'array'},
  41492. resumeEvents: {type: 'array'},
  41493. round: {default: false},
  41494. to: {default: ''},
  41495. type: {default: ''},
  41496. isRawProperty: {default: false}
  41497. },
  41498. multiple: true,
  41499. init: function () {
  41500. var self = this;
  41501. this.eventDetail = {name: this.attrName};
  41502. this.time = 0;
  41503. this.animation = null;
  41504. this.animationIsPlaying = false;
  41505. this.onStartEvent = this.onStartEvent.bind(this);
  41506. this.beginAnimation = this.beginAnimation.bind(this);
  41507. this.pauseAnimation = this.pauseAnimation.bind(this);
  41508. this.resumeAnimation = this.resumeAnimation.bind(this);
  41509. this.fromColor = {};
  41510. this.toColor = {};
  41511. this.targets = {};
  41512. this.targetsArray = [];
  41513. this.updateConfigForDefault = this.updateConfigForDefault.bind(this);
  41514. this.updateConfigForRawColor = this.updateConfigForRawColor.bind(this);
  41515. this.config = {
  41516. complete: function () {
  41517. self.animationIsPlaying = false;
  41518. self.el.emit('animationcomplete', self.eventDetail, false);
  41519. if (self.id) {
  41520. self.el.emit('animationcomplete__' + self.id, self.eventDetail, false);
  41521. }
  41522. }
  41523. };
  41524. },
  41525. update: function (oldData) {
  41526. var config = this.config;
  41527. var data = this.data;
  41528. this.animationIsPlaying = false;
  41529. if (!this.data.enabled) { return; }
  41530. if (!data.property) { return; }
  41531. // Base config.
  41532. config.autoplay = false;
  41533. config.direction = data.dir;
  41534. config.duration = data.dur;
  41535. config.easing = data.easing;
  41536. config.elasticity = data.elasticity;
  41537. config.loop = data.loop;
  41538. config.round = data.round;
  41539. // Start new animation.
  41540. this.createAndStartAnimation();
  41541. },
  41542. tick: function (t, dt) {
  41543. if (!this.animationIsPlaying) { return; }
  41544. this.time += dt;
  41545. this.animation.tick(this.time);
  41546. },
  41547. remove: function () {
  41548. this.pauseAnimation();
  41549. this.removeEventListeners();
  41550. },
  41551. pause: function () {
  41552. this.paused = true;
  41553. this.pausedWasPlaying = this.animationIsPlaying;
  41554. this.pauseAnimation();
  41555. this.removeEventListeners();
  41556. },
  41557. /**
  41558. * `play` handler only for resuming scene.
  41559. */
  41560. play: function () {
  41561. if (!this.paused) { return; }
  41562. this.paused = false;
  41563. this.addEventListeners();
  41564. if (this.pausedWasPlaying) {
  41565. this.resumeAnimation();
  41566. this.pausedWasPlaying = false;
  41567. }
  41568. },
  41569. /**
  41570. * Start animation from scratch.
  41571. */
  41572. createAndStartAnimation: function () {
  41573. var data = this.data;
  41574. this.updateConfig();
  41575. this.animationIsPlaying = false;
  41576. this.animation = anime(this.config);
  41577. this.animation.began = true;
  41578. this.removeEventListeners();
  41579. this.addEventListeners();
  41580. // Wait for start events for animation.
  41581. if (!data.autoplay || data.startEvents && data.startEvents.length) { return; }
  41582. // Delay animation.
  41583. if (data.delay) {
  41584. setTimeout(this.beginAnimation, data.delay);
  41585. return;
  41586. }
  41587. // Play animation.
  41588. this.beginAnimation();
  41589. },
  41590. /**
  41591. * This is before animation start (including from startEvents).
  41592. * Set to initial state (config.from, time = 0, seekTime = 0).
  41593. */
  41594. beginAnimation: function () {
  41595. this.updateConfig();
  41596. this.animation.began = true;
  41597. this.time = 0;
  41598. this.animationIsPlaying = true;
  41599. this.stopRelatedAnimations();
  41600. this.el.emit('animationbegin', this.eventDetail, false);
  41601. },
  41602. pauseAnimation: function () {
  41603. this.animationIsPlaying = false;
  41604. },
  41605. resumeAnimation: function () {
  41606. this.animationIsPlaying = true;
  41607. },
  41608. /**
  41609. * startEvents callback.
  41610. */
  41611. onStartEvent: function () {
  41612. if (!this.data.enabled) { return; }
  41613. this.updateConfig();
  41614. if (this.animation) {
  41615. this.animation.pause();
  41616. }
  41617. this.animation = anime(this.config);
  41618. // Include the delay before each start event.
  41619. if (this.data.delay) {
  41620. setTimeout(this.beginAnimation, this.data.delay);
  41621. return;
  41622. }
  41623. this.beginAnimation();
  41624. },
  41625. /**
  41626. * rawProperty: true and type: color;
  41627. */
  41628. updateConfigForRawColor: function () {
  41629. var config = this.config;
  41630. var data = this.data;
  41631. var el = this.el;
  41632. var from;
  41633. var key;
  41634. var to;
  41635. if (this.waitComponentInitRawProperty(this.updateConfigForRawColor)) {
  41636. return;
  41637. }
  41638. from = data.from === '' ? getRawProperty(el, data.property) : data.from;
  41639. to = data.to;
  41640. // Use r/g/b vector for color type.
  41641. this.setColorConfig(from, to);
  41642. from = this.fromColor;
  41643. to = this.toColor;
  41644. this.targetsArray.length = 0;
  41645. this.targetsArray.push(from);
  41646. config.targets = this.targetsArray;
  41647. for (key in to) { config[key] = to[key]; }
  41648. config.update = (function () {
  41649. var lastValue = {};
  41650. return function (anim) {
  41651. var value;
  41652. value = anim.animatables[0].target;
  41653. // For animation timeline.
  41654. if (value.r === lastValue.r &&
  41655. value.g === lastValue.g &&
  41656. value.b === lastValue.b) { return; }
  41657. setRawProperty(el, data.property, value, data.type);
  41658. };
  41659. })();
  41660. },
  41661. /**
  41662. * Stuff property into generic `property` key.
  41663. */
  41664. updateConfigForDefault: function () {
  41665. var config = this.config;
  41666. var data = this.data;
  41667. var el = this.el;
  41668. var from;
  41669. var isBoolean;
  41670. var isNumber;
  41671. var to;
  41672. if (this.waitComponentInitRawProperty(this.updateConfigForDefault)) {
  41673. return;
  41674. }
  41675. if (data.from === '') {
  41676. // Infer from.
  41677. from = isRawProperty(data)
  41678. ? getRawProperty(el, data.property)
  41679. : getComponentProperty(el, data.property);
  41680. } else {
  41681. // Explicit from.
  41682. from = data.from;
  41683. }
  41684. to = data.to;
  41685. isNumber = !isNaN(from || to);
  41686. if (isNumber) {
  41687. from = parseFloat(from);
  41688. to = parseFloat(to);
  41689. } else {
  41690. from = from ? from.toString() : from;
  41691. to = to ? to.toString() : to;
  41692. }
  41693. // Convert booleans to integer to allow boolean flipping.
  41694. isBoolean = data.to === 'true' || data.to === 'false' ||
  41695. data.to === true || data.to === false;
  41696. if (isBoolean) {
  41697. from = data.from === 'true' || data.from === true ? 1 : 0;
  41698. to = data.to === 'true' || data.to === true ? 1 : 0;
  41699. }
  41700. this.targets.aframeProperty = from;
  41701. config.targets = this.targets;
  41702. config.aframeProperty = to;
  41703. config.update = (function () {
  41704. var lastValue;
  41705. return function (anim) {
  41706. var value;
  41707. value = anim.animatables[0].target.aframeProperty;
  41708. // Need to do a last value check for animation timeline since all the tweening
  41709. // begins simultaenously even if the value has not changed. Also better for perf
  41710. // anyways.
  41711. if (value === lastValue) { return; }
  41712. lastValue = value;
  41713. if (isBoolean) { value = value >= 1; }
  41714. if (isRawProperty(data)) {
  41715. setRawProperty(el, data.property, value, data.type);
  41716. } else {
  41717. setComponentProperty(el, data.property, value);
  41718. }
  41719. };
  41720. })();
  41721. },
  41722. /**
  41723. * Extend x/y/z/w onto the config.
  41724. * Update vector by modifying object3D.
  41725. */
  41726. updateConfigForVector: function () {
  41727. var config = this.config;
  41728. var data = this.data;
  41729. var el = this.el;
  41730. var key;
  41731. var from;
  41732. var to;
  41733. // Parse coordinates.
  41734. from = data.from !== ''
  41735. ? utils.coordinates.parse(data.from) // If data.from defined, use that.
  41736. : getComponentProperty(el, data.property); // If data.from not defined, get on the fly.
  41737. to = utils.coordinates.parse(data.to);
  41738. if (data.property === PROP_ROTATION) {
  41739. toRadians(from);
  41740. toRadians(to);
  41741. }
  41742. // Set to and from.
  41743. this.targetsArray.length = 0;
  41744. this.targetsArray.push(from);
  41745. config.targets = this.targetsArray;
  41746. for (key in to) { config[key] = to[key]; }
  41747. // If animating object3D transformation, run more optimized updater.
  41748. if (data.property === PROP_POSITION || data.property === PROP_ROTATION ||
  41749. data.property === PROP_SCALE) {
  41750. config.update = (function () {
  41751. var lastValue = {};
  41752. return function (anim) {
  41753. var value = anim.animatables[0].target;
  41754. if (data.property === PROP_SCALE) {
  41755. value.x = Math.max(0.0001, value.x);
  41756. value.y = Math.max(0.0001, value.y);
  41757. value.z = Math.max(0.0001, value.z);
  41758. }
  41759. // For animation timeline.
  41760. if (value.x === lastValue.x &&
  41761. value.y === lastValue.y &&
  41762. value.z === lastValue.z) { return; }
  41763. lastValue.x = value.x;
  41764. lastValue.y = value.y;
  41765. lastValue.z = value.z;
  41766. el.object3D[data.property].set(value.x, value.y, value.z);
  41767. };
  41768. })();
  41769. return;
  41770. }
  41771. // Animating some vector.
  41772. config.update = (function () {
  41773. var lastValue = {};
  41774. return function (anim) {
  41775. var value = anim.animatables[0].target;
  41776. // Animate rotation through radians.
  41777. // For animation timeline.
  41778. if (value.x === lastValue.x &&
  41779. value.y === lastValue.y &&
  41780. value.z === lastValue.z) { return; }
  41781. lastValue.x = value.x;
  41782. lastValue.y = value.y;
  41783. lastValue.z = value.z;
  41784. setComponentProperty(el, data.property, value);
  41785. };
  41786. })();
  41787. },
  41788. /**
  41789. * Update the config before each run.
  41790. */
  41791. updateConfig: function () {
  41792. var propType;
  41793. // Route config type.
  41794. propType = getPropertyType(this.el, this.data.property);
  41795. if (isRawProperty(this.data) && this.data.type === TYPE_COLOR) {
  41796. this.updateConfigForRawColor();
  41797. } else if (propType === 'vec2' || propType === 'vec3' || propType === 'vec4') {
  41798. this.updateConfigForVector();
  41799. } else {
  41800. this.updateConfigForDefault();
  41801. }
  41802. },
  41803. /**
  41804. * Wait for component to initialize.
  41805. */
  41806. waitComponentInitRawProperty: function (cb) {
  41807. var componentName;
  41808. var data = this.data;
  41809. var el = this.el;
  41810. var self = this;
  41811. if (data.from !== '') { return false; }
  41812. if (!data.property.startsWith(STRING_COMPONENTS)) { return false; }
  41813. componentName = splitDot(data.property)[1];
  41814. if (el.components[componentName]) { return false; }
  41815. el.addEventListener('componentinitialized', function wait (evt) {
  41816. if (evt.detail.name !== componentName) { return; }
  41817. cb();
  41818. // Since the config was created async, create the animation now since we missed it
  41819. // earlier.
  41820. self.animation = anime(self.config);
  41821. el.removeEventListener('componentinitialized', wait);
  41822. });
  41823. return true;
  41824. },
  41825. /**
  41826. * Make sure two animations on the same property don't fight each other.
  41827. * e.g., animation__mouseenter="property: material.opacity"
  41828. * animation__mouseleave="property: material.opacity"
  41829. */
  41830. stopRelatedAnimations: function () {
  41831. var component;
  41832. var componentName;
  41833. for (componentName in this.el.components) {
  41834. component = this.el.components[componentName];
  41835. if (componentName === this.attrName) { continue; }
  41836. if (component.name !== 'animation') { continue; }
  41837. if (!component.animationIsPlaying) { continue; }
  41838. if (component.data.property !== this.data.property) { continue; }
  41839. component.animationIsPlaying = false;
  41840. }
  41841. },
  41842. addEventListeners: function () {
  41843. var data = this.data;
  41844. var el = this.el;
  41845. addEventListeners(el, data.startEvents, this.onStartEvent);
  41846. addEventListeners(el, data.pauseEvents, this.pauseAnimation);
  41847. addEventListeners(el, data.resumeEvents, this.resumeAnimation);
  41848. },
  41849. removeEventListeners: function () {
  41850. var data = this.data;
  41851. var el = this.el;
  41852. removeEventListeners(el, data.startEvents, this.onStartEvent);
  41853. removeEventListeners(el, data.pauseEvents, this.pauseAnimation);
  41854. removeEventListeners(el, data.resumeEvents, this.resumeAnimation);
  41855. },
  41856. setColorConfig: function (from, to) {
  41857. colorHelperFrom.set(from);
  41858. colorHelperTo.set(to);
  41859. from = this.fromColor;
  41860. to = this.toColor;
  41861. from.r = colorHelperFrom.r;
  41862. from.g = colorHelperFrom.g;
  41863. from.b = colorHelperFrom.b;
  41864. to.r = colorHelperTo.r;
  41865. to.g = colorHelperTo.g;
  41866. to.b = colorHelperTo.b;
  41867. }
  41868. });
  41869. /**
  41870. * Given property name, check schema to see what type we are animating.
  41871. * We just care whether the property is a vector.
  41872. */
  41873. function getPropertyType (el, property) {
  41874. var component;
  41875. var componentName;
  41876. var split;
  41877. var propertyName;
  41878. split = property.split('.');
  41879. componentName = split[0];
  41880. propertyName = split[1];
  41881. component = el.components[componentName] || components[componentName];
  41882. // Primitives.
  41883. if (!component) { return null; }
  41884. // Dynamic schema. We only care about vectors anyways.
  41885. if (propertyName && !component.schema[propertyName]) { return null; }
  41886. // Multi-prop.
  41887. if (propertyName) { return component.schema[propertyName].type; }
  41888. // Single-prop.
  41889. return component.schema.type;
  41890. }
  41891. /**
  41892. * Convert object to radians.
  41893. */
  41894. function toRadians (obj) {
  41895. obj.x = THREE.Math.degToRad(obj.x);
  41896. obj.y = THREE.Math.degToRad(obj.y);
  41897. obj.z = THREE.Math.degToRad(obj.z);
  41898. }
  41899. function addEventListeners (el, eventNames, handler) {
  41900. var i;
  41901. for (i = 0; i < eventNames.length; i++) {
  41902. el.addEventListener(eventNames[i], handler);
  41903. }
  41904. }
  41905. function removeEventListeners (el, eventNames, handler) {
  41906. var i;
  41907. for (i = 0; i < eventNames.length; i++) {
  41908. el.removeEventListener(eventNames[i], handler);
  41909. }
  41910. }
  41911. function getRawProperty (el, path) {
  41912. var i;
  41913. var split;
  41914. var value;
  41915. split = splitDot(path);
  41916. value = el;
  41917. for (i = 0; i < split.length; i++) {
  41918. value = value[split[i]];
  41919. }
  41920. if (value === undefined) {
  41921. console.log(el);
  41922. throw new Error('[animation] property (' + path + ') could not be found');
  41923. }
  41924. return value;
  41925. }
  41926. function setRawProperty (el, path, value, type) {
  41927. var i;
  41928. var split;
  41929. var propertyName;
  41930. var targetValue;
  41931. if (path.startsWith('object3D.rotation')) {
  41932. value = THREE.Math.degToRad(value);
  41933. }
  41934. // Walk.
  41935. split = splitDot(path);
  41936. targetValue = el;
  41937. for (i = 0; i < split.length - 1; i++) { targetValue = targetValue[split[i]]; }
  41938. propertyName = split[split.length - 1];
  41939. // Raw color.
  41940. if (type === TYPE_COLOR) {
  41941. if ('r' in targetValue[propertyName]) {
  41942. targetValue[propertyName].r = value.r;
  41943. targetValue[propertyName].g = value.g;
  41944. targetValue[propertyName].b = value.b;
  41945. } else {
  41946. targetValue[propertyName].x = value.r;
  41947. targetValue[propertyName].y = value.g;
  41948. targetValue[propertyName].z = value.b;
  41949. }
  41950. return;
  41951. }
  41952. targetValue[propertyName] = value;
  41953. }
  41954. function splitDot (path) {
  41955. if (path in splitCache) { return splitCache[path]; }
  41956. splitCache[path] = path.split('.');
  41957. return splitCache[path];
  41958. }
  41959. function isRawProperty (data) {
  41960. return data.isRawProperty || data.property.startsWith(STRING_COMPONENTS) ||
  41961. data.property.startsWith(STRING_OBJECT3D);
  41962. }
  41963. },{"../core/component":103,"../lib/three":151,"../utils":176,"super-animejs":35}],53:[function(_dereq_,module,exports){
  41964. var registerComponent = _dereq_('../core/component').registerComponent;
  41965. var THREE = _dereq_('../lib/three');
  41966. /**
  41967. * Camera component.
  41968. * Pairs along with camera system to handle tracking the active camera.
  41969. */
  41970. module.exports.Component = registerComponent('camera', {
  41971. schema: {
  41972. active: {default: true},
  41973. far: {default: 10000},
  41974. fov: {default: 80, min: 0},
  41975. near: {default: 0.005, min: 0},
  41976. spectator: {default: false},
  41977. zoom: {default: 1, min: 0}
  41978. },
  41979. /**
  41980. * Initialize three.js camera and add it to the entity.
  41981. * Add reference from scene to this entity as the camera.
  41982. */
  41983. init: function () {
  41984. var camera;
  41985. var el = this.el;
  41986. // Create camera.
  41987. camera = this.camera = new THREE.PerspectiveCamera();
  41988. el.setObject3D('camera', camera);
  41989. },
  41990. /**
  41991. * Update three.js camera.
  41992. */
  41993. update: function (oldData) {
  41994. var data = this.data;
  41995. var camera = this.camera;
  41996. // Update properties.
  41997. camera.aspect = data.aspect || (window.innerWidth / window.innerHeight);
  41998. camera.far = data.far;
  41999. camera.fov = data.fov;
  42000. camera.near = data.near;
  42001. camera.zoom = data.zoom;
  42002. camera.updateProjectionMatrix();
  42003. this.updateActiveCamera(oldData);
  42004. this.updateSpectatorCamera(oldData);
  42005. },
  42006. updateActiveCamera: function (oldData) {
  42007. var data = this.data;
  42008. var el = this.el;
  42009. var system = this.system;
  42010. // Active property did not change.
  42011. if (oldData && oldData.active === data.active || data.spectator) { return; }
  42012. // If `active` property changes, or first update, handle active camera with system.
  42013. if (data.active && system.activeCameraEl !== el) {
  42014. // Camera enabled. Set camera to this camera.
  42015. system.setActiveCamera(el);
  42016. } else if (!data.active && system.activeCameraEl === el) {
  42017. // Camera disabled. Set camera to another camera.
  42018. system.disableActiveCamera();
  42019. }
  42020. },
  42021. updateSpectatorCamera: function (oldData) {
  42022. var data = this.data;
  42023. var el = this.el;
  42024. var system = this.system;
  42025. // spectator property did not change.
  42026. if (oldData && oldData.spectator === data.spectator) { return; }
  42027. // If `spectator` property changes, or first update, handle spectator camera with system.
  42028. if (data.spectator && system.spectatorCameraEl !== el) {
  42029. // Camera enabled. Set camera to this camera.
  42030. system.setSpectatorCamera(el);
  42031. } else if (!data.spectator && system.spectatorCameraEl === el) {
  42032. // Camera disabled. Set camera to another camera.
  42033. system.disableSpectatorCamera();
  42034. }
  42035. },
  42036. /**
  42037. * Remove camera on remove (callback).
  42038. */
  42039. remove: function () {
  42040. this.el.removeObject3D('camera');
  42041. }
  42042. });
  42043. },{"../core/component":103,"../lib/three":151}],54:[function(_dereq_,module,exports){
  42044. /* global THREE */
  42045. var registerComponent = _dereq_('../core/component').registerComponent;
  42046. var utils = _dereq_('../utils/');
  42047. var bind = utils.bind;
  42048. var EVENTS = {
  42049. CLICK: 'click',
  42050. FUSING: 'fusing',
  42051. MOUSEENTER: 'mouseenter',
  42052. MOUSEDOWN: 'mousedown',
  42053. MOUSELEAVE: 'mouseleave',
  42054. MOUSEUP: 'mouseup'
  42055. };
  42056. var STATES = {
  42057. FUSING: 'cursor-fusing',
  42058. HOVERING: 'cursor-hovering',
  42059. HOVERED: 'cursor-hovered'
  42060. };
  42061. var CANVAS_EVENTS = {
  42062. DOWN: ['mousedown', 'touchstart'],
  42063. UP: ['mouseup', 'touchend']
  42064. };
  42065. var CANVAS_HOVER_CLASS = 'a-mouse-cursor-hover';
  42066. /**
  42067. * Cursor component. Applies the raycaster component specifically for starting the raycaster
  42068. * from the camera and pointing from camera's facing direction, and then only returning the
  42069. * closest intersection. Cursor can be fine-tuned by setting raycaster properties.
  42070. *
  42071. * @member {object} fuseTimeout - Timeout to trigger fuse-click.
  42072. * @member {Element} cursorDownEl - Entity that was last mousedowned during current click.
  42073. * @member {object} intersection - Attributes of the current intersection event, including
  42074. * 3D- and 2D-space coordinates. See: http://threejs.org/docs/api/core/Raycaster.html
  42075. * @member {Element} intersectedEl - Currently-intersected entity. Used to keep track to
  42076. * emit events when unintersecting.
  42077. */
  42078. module.exports.Component = registerComponent('cursor', {
  42079. dependencies: ['raycaster'],
  42080. schema: {
  42081. downEvents: {default: []},
  42082. fuse: {default: utils.device.isMobile()},
  42083. fuseTimeout: {default: 1500, min: 0},
  42084. mouseCursorStylesEnabled: {default: true},
  42085. upEvents: {default: []},
  42086. rayOrigin: {default: 'entity', oneOf: ['mouse', 'entity']}
  42087. },
  42088. init: function () {
  42089. var self = this;
  42090. this.fuseTimeout = undefined;
  42091. this.cursorDownEl = null;
  42092. this.intersectedEl = null;
  42093. this.canvasBounds = document.body.getBoundingClientRect();
  42094. // Debounce.
  42095. this.updateCanvasBounds = utils.debounce(function updateCanvasBounds () {
  42096. self.canvasBounds = self.el.sceneEl.canvas.getBoundingClientRect();
  42097. }, 500);
  42098. this.eventDetail = {};
  42099. this.intersectedEventDetail = {cursorEl: this.el};
  42100. // Bind methods.
  42101. this.onCursorDown = bind(this.onCursorDown, this);
  42102. this.onCursorUp = bind(this.onCursorUp, this);
  42103. this.onIntersection = bind(this.onIntersection, this);
  42104. this.onIntersectionCleared = bind(this.onIntersectionCleared, this);
  42105. this.onMouseMove = bind(this.onMouseMove, this);
  42106. },
  42107. update: function (oldData) {
  42108. if (this.data.rayOrigin === oldData.rayOrigin) { return; }
  42109. this.updateMouseEventListeners();
  42110. },
  42111. play: function () {
  42112. this.addEventListeners();
  42113. },
  42114. pause: function () {
  42115. this.removeEventListeners();
  42116. },
  42117. remove: function () {
  42118. var el = this.el;
  42119. el.removeState(STATES.HOVERING);
  42120. el.removeState(STATES.FUSING);
  42121. clearTimeout(this.fuseTimeout);
  42122. if (this.intersectedEl) { this.intersectedEl.removeState(STATES.HOVERED); }
  42123. this.removeEventListeners();
  42124. },
  42125. addEventListeners: function () {
  42126. var canvas;
  42127. var data = this.data;
  42128. var el = this.el;
  42129. var self = this;
  42130. function addCanvasListeners () {
  42131. canvas = el.sceneEl.canvas;
  42132. if (data.downEvents.length || data.upEvents.length) { return; }
  42133. CANVAS_EVENTS.DOWN.forEach(function (downEvent) {
  42134. canvas.addEventListener(downEvent, self.onCursorDown);
  42135. });
  42136. CANVAS_EVENTS.UP.forEach(function (upEvent) {
  42137. canvas.addEventListener(upEvent, self.onCursorUp);
  42138. });
  42139. }
  42140. canvas = el.sceneEl.canvas;
  42141. if (canvas) {
  42142. addCanvasListeners();
  42143. } else {
  42144. el.sceneEl.addEventListener('render-target-loaded', addCanvasListeners);
  42145. }
  42146. data.downEvents.forEach(function (downEvent) {
  42147. el.addEventListener(downEvent, self.onCursorDown);
  42148. });
  42149. data.upEvents.forEach(function (upEvent) {
  42150. el.addEventListener(upEvent, self.onCursorUp);
  42151. });
  42152. el.addEventListener('raycaster-intersection', this.onIntersection);
  42153. el.addEventListener('raycaster-intersection-cleared', this.onIntersectionCleared);
  42154. el.sceneEl.addEventListener('rendererresize', this.updateCanvasBounds);
  42155. window.addEventListener('resize', this.updateCanvasBounds);
  42156. window.addEventListener('scroll', this.updateCanvasBounds);
  42157. this.updateMouseEventListeners();
  42158. },
  42159. removeEventListeners: function () {
  42160. var canvas;
  42161. var data = this.data;
  42162. var el = this.el;
  42163. var self = this;
  42164. canvas = el.sceneEl.canvas;
  42165. if (canvas && !data.downEvents.length && !data.upEvents.length) {
  42166. CANVAS_EVENTS.DOWN.forEach(function (downEvent) {
  42167. canvas.removeEventListener(downEvent, self.onCursorDown);
  42168. });
  42169. CANVAS_EVENTS.UP.forEach(function (upEvent) {
  42170. canvas.removeEventListener(upEvent, self.onCursorUp);
  42171. });
  42172. }
  42173. data.downEvents.forEach(function (downEvent) {
  42174. el.removeEventListener(downEvent, self.onCursorDown);
  42175. });
  42176. data.upEvents.forEach(function (upEvent) {
  42177. el.removeEventListener(upEvent, self.onCursorUp);
  42178. });
  42179. el.removeEventListener('raycaster-intersection', this.onIntersection);
  42180. el.removeEventListener('raycaster-intersection-cleared', this.onIntersectionCleared);
  42181. canvas.removeEventListener('mousemove', this.onMouseMove);
  42182. canvas.removeEventListener('touchstart', this.onMouseMove);
  42183. canvas.removeEventListener('touchmove', this.onMouseMove);
  42184. el.sceneEl.removeEventListener('rendererresize', this.updateCanvasBounds);
  42185. window.removeEventListener('resize', this.updateCanvasBounds);
  42186. window.removeEventListener('scroll', this.updateCanvasBounds);
  42187. },
  42188. updateMouseEventListeners: function () {
  42189. var canvas;
  42190. var el = this.el;
  42191. canvas = el.sceneEl.canvas;
  42192. canvas.removeEventListener('mousemove', this.onMouseMove);
  42193. canvas.removeEventListener('touchmove', this.onMouseMove);
  42194. el.setAttribute('raycaster', 'useWorldCoordinates', false);
  42195. if (this.data.rayOrigin !== 'mouse') { return; }
  42196. canvas.addEventListener('mousemove', this.onMouseMove, false);
  42197. canvas.addEventListener('touchmove', this.onMouseMove, false);
  42198. el.setAttribute('raycaster', 'useWorldCoordinates', true);
  42199. this.updateCanvasBounds();
  42200. },
  42201. onMouseMove: (function () {
  42202. var direction = new THREE.Vector3();
  42203. var mouse = new THREE.Vector2();
  42204. var origin = new THREE.Vector3();
  42205. var rayCasterConfig = {origin: origin, direction: direction};
  42206. return function (evt) {
  42207. var bounds = this.canvasBounds;
  42208. var camera = this.el.sceneEl.camera;
  42209. var left;
  42210. var point;
  42211. var top;
  42212. camera.parent.updateMatrixWorld();
  42213. // Calculate mouse position based on the canvas element
  42214. if (evt.type === 'touchmove' || evt.type === 'touchstart') {
  42215. // Track the first touch for simplicity.
  42216. point = evt.touches.item(0);
  42217. } else {
  42218. point = evt;
  42219. }
  42220. left = point.clientX - bounds.left;
  42221. top = point.clientY - bounds.top;
  42222. mouse.x = (left / bounds.width) * 2 - 1;
  42223. mouse.y = -(top / bounds.height) * 2 + 1;
  42224. origin.setFromMatrixPosition(camera.matrixWorld);
  42225. direction.set(mouse.x, mouse.y, 0.5).unproject(camera).sub(origin).normalize();
  42226. this.el.setAttribute('raycaster', rayCasterConfig);
  42227. if (evt.type === 'touchmove') { evt.preventDefault(); }
  42228. };
  42229. })(),
  42230. /**
  42231. * Trigger mousedown and keep track of the mousedowned entity.
  42232. */
  42233. onCursorDown: function (evt) {
  42234. // Raycast again for touch.
  42235. if (this.data.rayOrigin === 'mouse' && evt.type === 'touchstart') {
  42236. this.onMouseMove(evt);
  42237. this.el.components.raycaster.checkIntersections();
  42238. evt.preventDefault();
  42239. }
  42240. this.twoWayEmit(EVENTS.MOUSEDOWN);
  42241. this.cursorDownEl = this.intersectedEl;
  42242. },
  42243. /**
  42244. * Trigger mouseup if:
  42245. * - Not fusing (mobile has no mouse).
  42246. * - Currently intersecting an entity.
  42247. * - Currently-intersected entity is the same as the one when mousedown was triggered,
  42248. * in case user mousedowned one entity, dragged to another, and mouseupped.
  42249. */
  42250. onCursorUp: function (evt) {
  42251. var data = this.data;
  42252. this.twoWayEmit(EVENTS.MOUSEUP);
  42253. // If intersected entity has changed since the cursorDown, still emit mouseUp on the
  42254. // previously cursorUp entity.
  42255. if (this.cursorDownEl && this.cursorDownEl !== this.intersectedEl) {
  42256. this.intersectedEventDetail.intersection = null;
  42257. this.cursorDownEl.emit(EVENTS.MOUSEUP, this.intersectedEventDetail);
  42258. }
  42259. if ((!data.fuse || data.rayOrigin === 'mouse') &&
  42260. this.intersectedEl && this.cursorDownEl === this.intersectedEl) {
  42261. this.twoWayEmit(EVENTS.CLICK);
  42262. }
  42263. this.cursorDownEl = null;
  42264. if (evt.type === 'touchend') { evt.preventDefault(); }
  42265. },
  42266. /**
  42267. * Handle intersection.
  42268. */
  42269. onIntersection: function (evt) {
  42270. var currentIntersection;
  42271. var cursorEl = this.el;
  42272. var index;
  42273. var intersectedEl;
  42274. var intersection;
  42275. // Select closest object, excluding the cursor.
  42276. index = evt.detail.els[0] === cursorEl ? 1 : 0;
  42277. intersection = evt.detail.intersections[index];
  42278. intersectedEl = evt.detail.els[index];
  42279. // If cursor is the only intersected object, ignore the event.
  42280. if (!intersectedEl) { return; }
  42281. // Already intersecting this entity.
  42282. if (this.intersectedEl === intersectedEl) { return; }
  42283. // Ignore events further away than active intersection.
  42284. if (this.intersectedEl) {
  42285. currentIntersection = this.el.components.raycaster.getIntersection(this.intersectedEl);
  42286. if (currentIntersection && currentIntersection.distance <= intersection.distance) { return; }
  42287. }
  42288. // Unset current intersection.
  42289. this.clearCurrentIntersection(true);
  42290. this.setIntersection(intersectedEl, intersection);
  42291. },
  42292. /**
  42293. * Handle intersection cleared.
  42294. */
  42295. onIntersectionCleared: function (evt) {
  42296. var clearedEls = evt.detail.clearedEls;
  42297. // Check if the current intersection has ended
  42298. if (clearedEls.indexOf(this.intersectedEl) === -1) { return; }
  42299. this.clearCurrentIntersection();
  42300. },
  42301. setIntersection: function (intersectedEl, intersection) {
  42302. var cursorEl = this.el;
  42303. var data = this.data;
  42304. var self = this;
  42305. // Already intersecting.
  42306. if (this.intersectedEl === intersectedEl) { return; }
  42307. // Set new intersection.
  42308. this.intersectedEl = intersectedEl;
  42309. // Hovering.
  42310. cursorEl.addState(STATES.HOVERING);
  42311. intersectedEl.addState(STATES.HOVERED);
  42312. this.twoWayEmit(EVENTS.MOUSEENTER);
  42313. if (this.data.mouseCursorStylesEnabled && this.data.rayOrigin === 'mouse') {
  42314. this.el.sceneEl.canvas.classList.add(CANVAS_HOVER_CLASS);
  42315. }
  42316. // Begin fuse if necessary.
  42317. if (data.fuseTimeout === 0 || !data.fuse) { return; }
  42318. cursorEl.addState(STATES.FUSING);
  42319. this.twoWayEmit(EVENTS.FUSING);
  42320. this.fuseTimeout = setTimeout(function fuse () {
  42321. cursorEl.removeState(STATES.FUSING);
  42322. self.twoWayEmit(EVENTS.CLICK);
  42323. }, data.fuseTimeout);
  42324. },
  42325. clearCurrentIntersection: function (ignoreRemaining) {
  42326. var index;
  42327. var intersection;
  42328. var intersections;
  42329. var cursorEl = this.el;
  42330. // Nothing to be cleared.
  42331. if (!this.intersectedEl) { return; }
  42332. // No longer hovering (or fusing).
  42333. this.intersectedEl.removeState(STATES.HOVERED);
  42334. cursorEl.removeState(STATES.HOVERING);
  42335. cursorEl.removeState(STATES.FUSING);
  42336. this.twoWayEmit(EVENTS.MOUSELEAVE);
  42337. if (this.data.mouseCursorStylesEnabled && this.data.rayOrigin === 'mouse') {
  42338. this.el.sceneEl.canvas.classList.remove(CANVAS_HOVER_CLASS);
  42339. }
  42340. // Unset intersected entity (after emitting the event).
  42341. this.intersectedEl = null;
  42342. // Clear fuseTimeout.
  42343. clearTimeout(this.fuseTimeout);
  42344. // Set intersection to another raycasted element if any.
  42345. if (ignoreRemaining === true) { return; }
  42346. intersections = this.el.components.raycaster.intersections;
  42347. if (intersections.length === 0) { return; }
  42348. // Exclude the cursor.
  42349. index = intersections[0].object.el === cursorEl ? 1 : 0;
  42350. intersection = intersections[index];
  42351. if (!intersection) { return; }
  42352. this.setIntersection(intersection.object.el, intersection);
  42353. },
  42354. /**
  42355. * Helper to emit on both the cursor and the intersected entity (if exists).
  42356. */
  42357. twoWayEmit: function (evtName) {
  42358. var el = this.el;
  42359. var intersectedEl = this.intersectedEl;
  42360. var intersection;
  42361. intersection = this.el.components.raycaster.getIntersection(intersectedEl);
  42362. this.eventDetail.intersectedEl = intersectedEl;
  42363. this.eventDetail.intersection = intersection;
  42364. el.emit(evtName, this.eventDetail);
  42365. if (!intersectedEl) { return; }
  42366. this.intersectedEventDetail.intersection = intersection;
  42367. intersectedEl.emit(evtName, this.intersectedEventDetail);
  42368. }
  42369. });
  42370. },{"../core/component":103,"../utils/":176}],55:[function(_dereq_,module,exports){
  42371. var registerComponent = _dereq_('../core/component').registerComponent;
  42372. var bind = _dereq_('../utils/bind');
  42373. var trackedControlsUtils = _dereq_('../utils/tracked-controls');
  42374. var checkControllerPresentAndSetup = trackedControlsUtils.checkControllerPresentAndSetup;
  42375. var emitIfAxesChanged = trackedControlsUtils.emitIfAxesChanged;
  42376. var onButtonEvent = trackedControlsUtils.onButtonEvent;
  42377. var DAYDREAM_CONTROLLER_MODEL_BASE_URL = 'https://cdn.aframe.io/controllers/google/';
  42378. var DAYDREAM_CONTROLLER_MODEL_OBJ_URL = DAYDREAM_CONTROLLER_MODEL_BASE_URL + 'vr_controller_daydream.obj';
  42379. var DAYDREAM_CONTROLLER_MODEL_OBJ_MTL = DAYDREAM_CONTROLLER_MODEL_BASE_URL + 'vr_controller_daydream.mtl';
  42380. var GAMEPAD_ID_PREFIX = 'Daydream Controller';
  42381. /**
  42382. * Daydream controls.
  42383. * Interface with Daydream controller and map Gamepad events to
  42384. * controller buttons: trackpad, menu, system
  42385. * Load a controller model and highlight the pressed buttons.
  42386. */
  42387. module.exports.Component = registerComponent('daydream-controls', {
  42388. schema: {
  42389. hand: {default: ''}, // This informs the degenerate arm model.
  42390. buttonColor: {type: 'color', default: '#000000'},
  42391. buttonTouchedColor: {type: 'color', default: '#777777'},
  42392. buttonHighlightColor: {type: 'color', default: '#FFFFFF'},
  42393. model: {default: true},
  42394. orientationOffset: {type: 'vec3'},
  42395. armModel: {default: true}
  42396. },
  42397. /**
  42398. * Button IDs:
  42399. * 0 - trackpad
  42400. * 1 - menu (never dispatched on this layer)
  42401. * 2 - system (never dispatched on this layer)
  42402. */
  42403. mapping: {
  42404. axes: {trackpad: [0, 1]},
  42405. buttons: ['trackpad', 'menu', 'system']
  42406. },
  42407. bindMethods: function () {
  42408. this.onModelLoaded = bind(this.onModelLoaded, this);
  42409. this.onControllersUpdate = bind(this.onControllersUpdate, this);
  42410. this.checkIfControllerPresent = bind(this.checkIfControllerPresent, this);
  42411. this.removeControllersUpdateListener = bind(this.removeControllersUpdateListener, this);
  42412. this.onAxisMoved = bind(this.onAxisMoved, this);
  42413. },
  42414. init: function () {
  42415. var self = this;
  42416. this.onButtonChanged = bind(this.onButtonChanged, this);
  42417. this.onButtonDown = function (evt) { onButtonEvent(evt.detail.id, 'down', self); };
  42418. this.onButtonUp = function (evt) { onButtonEvent(evt.detail.id, 'up', self); };
  42419. this.onButtonTouchStart = function (evt) { onButtonEvent(evt.detail.id, 'touchstart', self); };
  42420. this.onButtonTouchEnd = function (evt) { onButtonEvent(evt.detail.id, 'touchend', self); };
  42421. this.controllerPresent = false;
  42422. this.lastControllerCheck = 0;
  42423. this.bindMethods();
  42424. },
  42425. addEventListeners: function () {
  42426. var el = this.el;
  42427. el.addEventListener('buttonchanged', this.onButtonChanged);
  42428. el.addEventListener('buttondown', this.onButtonDown);
  42429. el.addEventListener('buttonup', this.onButtonUp);
  42430. el.addEventListener('touchstart', this.onButtonTouchStart);
  42431. el.addEventListener('touchend', this.onButtonTouchEnd);
  42432. el.addEventListener('model-loaded', this.onModelLoaded);
  42433. el.addEventListener('axismove', this.onAxisMoved);
  42434. this.controllerEventsActive = true;
  42435. },
  42436. removeEventListeners: function () {
  42437. var el = this.el;
  42438. el.removeEventListener('buttonchanged', this.onButtonChanged);
  42439. el.removeEventListener('buttondown', this.onButtonDown);
  42440. el.removeEventListener('buttonup', this.onButtonUp);
  42441. el.removeEventListener('touchstart', this.onButtonTouchStart);
  42442. el.removeEventListener('touchend', this.onButtonTouchEnd);
  42443. el.removeEventListener('model-loaded', this.onModelLoaded);
  42444. el.removeEventListener('axismove', this.onAxisMoved);
  42445. this.controllerEventsActive = false;
  42446. },
  42447. checkIfControllerPresent: function () {
  42448. checkControllerPresentAndSetup(this, GAMEPAD_ID_PREFIX, {hand: this.data.hand});
  42449. },
  42450. play: function () {
  42451. this.checkIfControllerPresent();
  42452. this.addControllersUpdateListener();
  42453. },
  42454. pause: function () {
  42455. this.removeEventListeners();
  42456. this.removeControllersUpdateListener();
  42457. },
  42458. injectTrackedControls: function () {
  42459. var el = this.el;
  42460. var data = this.data;
  42461. el.setAttribute('tracked-controls', {
  42462. armModel: data.armModel,
  42463. hand: data.hand,
  42464. idPrefix: GAMEPAD_ID_PREFIX,
  42465. orientationOffset: data.orientationOffset
  42466. });
  42467. if (!this.data.model) { return; }
  42468. this.el.setAttribute('obj-model', {
  42469. obj: DAYDREAM_CONTROLLER_MODEL_OBJ_URL,
  42470. mtl: DAYDREAM_CONTROLLER_MODEL_OBJ_MTL
  42471. });
  42472. },
  42473. addControllersUpdateListener: function () {
  42474. this.el.sceneEl.addEventListener('controllersupdated', this.onControllersUpdate, false);
  42475. },
  42476. removeControllersUpdateListener: function () {
  42477. this.el.sceneEl.removeEventListener('controllersupdated', this.onControllersUpdate, false);
  42478. },
  42479. onControllersUpdate: function () {
  42480. this.checkIfControllerPresent();
  42481. },
  42482. onModelLoaded: function (evt) {
  42483. var controllerObject3D = evt.detail.model;
  42484. var buttonMeshes;
  42485. if (!this.data.model) { return; }
  42486. buttonMeshes = this.buttonMeshes = {};
  42487. buttonMeshes.menu = controllerObject3D.getObjectByName('AppButton_AppButton_Cylinder.004');
  42488. buttonMeshes.system = controllerObject3D.getObjectByName('HomeButton_HomeButton_Cylinder.005');
  42489. buttonMeshes.trackpad = controllerObject3D.getObjectByName('TouchPad_TouchPad_Cylinder.003');
  42490. // Offset pivot point.
  42491. controllerObject3D.position.set(0, 0, -0.04);
  42492. },
  42493. onAxisMoved: function (evt) {
  42494. emitIfAxesChanged(this, this.mapping.axes, evt);
  42495. },
  42496. onButtonChanged: function (evt) {
  42497. var button = this.mapping.buttons[evt.detail.id];
  42498. if (!button) return;
  42499. // Pass along changed event with button state, using button mapping for convenience.
  42500. this.el.emit(button + 'changed', evt.detail.state);
  42501. },
  42502. updateModel: function (buttonName, evtName) {
  42503. if (!this.data.model) { return; }
  42504. this.updateButtonModel(buttonName, evtName);
  42505. },
  42506. updateButtonModel: function (buttonName, state) {
  42507. var buttonMeshes = this.buttonMeshes;
  42508. if (!buttonMeshes || !buttonMeshes[buttonName]) { return; }
  42509. var color;
  42510. switch (state) {
  42511. case 'down':
  42512. color = this.data.buttonHighlightColor;
  42513. break;
  42514. case 'touchstart':
  42515. color = this.data.buttonTouchedColor;
  42516. break;
  42517. default:
  42518. color = this.data.buttonColor;
  42519. }
  42520. buttonMeshes[buttonName].material.color.set(color);
  42521. }
  42522. });
  42523. },{"../core/component":103,"../utils/bind":170,"../utils/tracked-controls":184}],56:[function(_dereq_,module,exports){
  42524. var registerComponent = _dereq_('../core/component').registerComponent;
  42525. var bind = _dereq_('../utils/bind');
  42526. var trackedControlsUtils = _dereq_('../utils/tracked-controls');
  42527. var checkControllerPresentAndSetup = trackedControlsUtils.checkControllerPresentAndSetup;
  42528. var emitIfAxesChanged = trackedControlsUtils.emitIfAxesChanged;
  42529. var onButtonEvent = trackedControlsUtils.onButtonEvent;
  42530. var GEARVR_CONTROLLER_MODEL_BASE_URL = 'https://cdn.aframe.io/controllers/samsung/';
  42531. var GEARVR_CONTROLLER_MODEL_OBJ_URL = GEARVR_CONTROLLER_MODEL_BASE_URL + 'gear_vr_controller.obj';
  42532. var GEARVR_CONTROLLER_MODEL_OBJ_MTL = GEARVR_CONTROLLER_MODEL_BASE_URL + 'gear_vr_controller.mtl';
  42533. var GAMEPAD_ID_PREFIX = 'Gear VR';
  42534. /**
  42535. * Gear VR controls.
  42536. * Interface with Gear VR controller and map Gamepad events to
  42537. * controller buttons: trackpad, trigger
  42538. * Load a controller model and highlight the pressed buttons.
  42539. */
  42540. module.exports.Component = registerComponent('gearvr-controls', {
  42541. schema: {
  42542. hand: {default: ''}, // This informs the degenerate arm model.
  42543. buttonColor: {type: 'color', default: '#000000'},
  42544. buttonTouchedColor: {type: 'color', default: '#777777'},
  42545. buttonHighlightColor: {type: 'color', default: '#FFFFFF'},
  42546. model: {default: true},
  42547. orientationOffset: {type: 'vec3'},
  42548. armModel: {default: true}
  42549. },
  42550. /**
  42551. * Button IDs:
  42552. * 0 - trackpad
  42553. * 1 - trigger
  42554. */
  42555. mapping: {
  42556. axes: {trackpad: [0, 1]},
  42557. buttons: ['trackpad', 'trigger']
  42558. },
  42559. bindMethods: function () {
  42560. this.onModelLoaded = bind(this.onModelLoaded, this);
  42561. this.onControllersUpdate = bind(this.onControllersUpdate, this);
  42562. this.checkIfControllerPresent = bind(this.checkIfControllerPresent, this);
  42563. this.removeControllersUpdateListener = bind(this.removeControllersUpdateListener, this);
  42564. this.onAxisMoved = bind(this.onAxisMoved, this);
  42565. },
  42566. init: function () {
  42567. var self = this;
  42568. this.onButtonChanged = bind(this.onButtonChanged, this);
  42569. this.onButtonDown = function (evt) { onButtonEvent(evt.detail.id, 'down', self); };
  42570. this.onButtonUp = function (evt) { onButtonEvent(evt.detail.id, 'up', self); };
  42571. this.onButtonTouchStart = function (evt) { onButtonEvent(evt.detail.id, 'touchstart', self); };
  42572. this.onButtonTouchEnd = function (evt) { onButtonEvent(evt.detail.id, 'touchend', self); };
  42573. this.controllerPresent = false;
  42574. this.lastControllerCheck = 0;
  42575. this.bindMethods();
  42576. },
  42577. addEventListeners: function () {
  42578. var el = this.el;
  42579. el.addEventListener('buttonchanged', this.onButtonChanged);
  42580. el.addEventListener('buttondown', this.onButtonDown);
  42581. el.addEventListener('buttonup', this.onButtonUp);
  42582. el.addEventListener('touchstart', this.onButtonTouchStart);
  42583. el.addEventListener('touchend', this.onButtonTouchEnd);
  42584. el.addEventListener('model-loaded', this.onModelLoaded);
  42585. el.addEventListener('axismove', this.onAxisMoved);
  42586. this.controllerEventsActive = true;
  42587. },
  42588. removeEventListeners: function () {
  42589. var el = this.el;
  42590. el.removeEventListener('buttonchanged', this.onButtonChanged);
  42591. el.removeEventListener('buttondown', this.onButtonDown);
  42592. el.removeEventListener('buttonup', this.onButtonUp);
  42593. el.removeEventListener('touchstart', this.onButtonTouchStart);
  42594. el.removeEventListener('touchend', this.onButtonTouchEnd);
  42595. el.removeEventListener('model-loaded', this.onModelLoaded);
  42596. el.removeEventListener('axismove', this.onAxisMoved);
  42597. this.controllerEventsActive = false;
  42598. },
  42599. checkIfControllerPresent: function () {
  42600. checkControllerPresentAndSetup(this, GAMEPAD_ID_PREFIX,
  42601. this.data.hand ? {hand: this.data.hand} : {});
  42602. },
  42603. play: function () {
  42604. this.checkIfControllerPresent();
  42605. this.addControllersUpdateListener();
  42606. },
  42607. pause: function () {
  42608. this.removeEventListeners();
  42609. this.removeControllersUpdateListener();
  42610. },
  42611. injectTrackedControls: function () {
  42612. var el = this.el;
  42613. var data = this.data;
  42614. el.setAttribute('tracked-controls', {
  42615. armModel: data.armModel,
  42616. idPrefix: GAMEPAD_ID_PREFIX,
  42617. orientationOffset: data.orientationOffset
  42618. });
  42619. if (!this.data.model) { return; }
  42620. this.el.setAttribute('obj-model', {
  42621. obj: GEARVR_CONTROLLER_MODEL_OBJ_URL,
  42622. mtl: GEARVR_CONTROLLER_MODEL_OBJ_MTL
  42623. });
  42624. },
  42625. addControllersUpdateListener: function () {
  42626. this.el.sceneEl.addEventListener('controllersupdated', this.onControllersUpdate, false);
  42627. },
  42628. removeControllersUpdateListener: function () {
  42629. this.el.sceneEl.removeEventListener('controllersupdated', this.onControllersUpdate, false);
  42630. },
  42631. onControllersUpdate: function () {
  42632. this.checkIfControllerPresent();
  42633. },
  42634. // No need for onButtonChanged, since Gear VR controller has no analog buttons.
  42635. onModelLoaded: function (evt) {
  42636. var controllerObject3D = evt.detail.model;
  42637. var buttonMeshes;
  42638. if (!this.data.model) { return; }
  42639. buttonMeshes = this.buttonMeshes = {};
  42640. buttonMeshes.trigger = controllerObject3D.children[2];
  42641. buttonMeshes.trackpad = controllerObject3D.children[1];
  42642. },
  42643. onButtonChanged: function (evt) {
  42644. var button = this.mapping.buttons[evt.detail.id];
  42645. if (!button) return;
  42646. // Pass along changed event with button state, using button mapping for convenience.
  42647. this.el.emit(button + 'changed', evt.detail.state);
  42648. },
  42649. onAxisMoved: function (evt) {
  42650. emitIfAxesChanged(this, this.mapping.axes, evt);
  42651. },
  42652. updateModel: function (buttonName, evtName) {
  42653. if (!this.data.model) { return; }
  42654. this.updateButtonModel(buttonName, evtName);
  42655. },
  42656. updateButtonModel: function (buttonName, state) {
  42657. var buttonMeshes = this.buttonMeshes;
  42658. if (!buttonMeshes || !buttonMeshes[buttonName]) { return; }
  42659. var color;
  42660. switch (state) {
  42661. case 'down':
  42662. color = this.data.buttonHighlightColor;
  42663. break;
  42664. case 'touchstart':
  42665. color = this.data.buttonTouchedColor;
  42666. break;
  42667. default:
  42668. color = this.data.buttonColor;
  42669. }
  42670. buttonMeshes[buttonName].material.color.set(color);
  42671. }
  42672. });
  42673. },{"../core/component":103,"../utils/bind":170,"../utils/tracked-controls":184}],57:[function(_dereq_,module,exports){
  42674. var geometries = _dereq_('../core/geometry').geometries;
  42675. var geometryNames = _dereq_('../core/geometry').geometryNames;
  42676. var registerComponent = _dereq_('../core/component').registerComponent;
  42677. var THREE = _dereq_('../lib/three');
  42678. var dummyGeometry = new THREE.Geometry();
  42679. /**
  42680. * Geometry component. Combined with material component to make a mesh in 3D object.
  42681. * Extended with registered geometries.
  42682. */
  42683. module.exports.Component = registerComponent('geometry', {
  42684. schema: {
  42685. buffer: {default: true},
  42686. primitive: {default: 'box', oneOf: geometryNames, schemaChange: true},
  42687. skipCache: {default: false}
  42688. },
  42689. init: function () {
  42690. this.geometry = null;
  42691. },
  42692. /**
  42693. * Talk to geometry system to get or create geometry.
  42694. */
  42695. update: function (previousData) {
  42696. var data = this.data;
  42697. var el = this.el;
  42698. var mesh;
  42699. var system = this.system;
  42700. // Dispose old geometry if we created one.
  42701. if (this.geometry) {
  42702. system.unuseGeometry(previousData);
  42703. this.geometry = null;
  42704. }
  42705. // Create new geometry.
  42706. this.geometry = system.getOrCreateGeometry(data);
  42707. // Set on mesh. If mesh does not exist, create it.
  42708. mesh = el.getObject3D('mesh');
  42709. if (mesh) {
  42710. mesh.geometry = this.geometry;
  42711. } else {
  42712. mesh = new THREE.Mesh();
  42713. mesh.geometry = this.geometry;
  42714. el.setObject3D('mesh', mesh);
  42715. }
  42716. },
  42717. /**
  42718. * Tell geometry system that entity is no longer using the geometry.
  42719. * Unset the geometry on the mesh
  42720. */
  42721. remove: function () {
  42722. this.system.unuseGeometry(this.data);
  42723. this.el.getObject3D('mesh').geometry = dummyGeometry;
  42724. this.geometry = null;
  42725. },
  42726. /**
  42727. * Update geometry component schema based on geometry type.
  42728. */
  42729. updateSchema: function (data) {
  42730. var currentGeometryType = this.oldData && this.oldData.primitive;
  42731. var newGeometryType = data.primitive;
  42732. var schema = geometries[newGeometryType] && geometries[newGeometryType].schema;
  42733. // Geometry has no schema.
  42734. if (!schema) { throw new Error('Unknown geometry schema `' + newGeometryType + '`'); }
  42735. // Nothing has changed.
  42736. if (currentGeometryType && currentGeometryType === newGeometryType) { return; }
  42737. this.extendSchema(schema);
  42738. }
  42739. });
  42740. },{"../core/component":103,"../core/geometry":104,"../lib/three":151}],58:[function(_dereq_,module,exports){
  42741. var registerComponent = _dereq_('../core/component').registerComponent;
  42742. var THREE = _dereq_('../lib/three');
  42743. var utils = _dereq_('../utils/');
  42744. var warn = utils.debug('components:gltf-model:warn');
  42745. /**
  42746. * glTF model loader.
  42747. */
  42748. module.exports.Component = registerComponent('gltf-model', {
  42749. schema: {type: 'model'},
  42750. init: function () {
  42751. var dracoLoader = this.system.getDRACOLoader();
  42752. this.model = null;
  42753. this.loader = new THREE.GLTFLoader();
  42754. if (dracoLoader) {
  42755. this.loader.setDRACOLoader(dracoLoader);
  42756. }
  42757. },
  42758. update: function () {
  42759. var self = this;
  42760. var el = this.el;
  42761. var src = this.data;
  42762. if (!src) { return; }
  42763. this.remove();
  42764. this.loader.load(src, function gltfLoaded (gltfModel) {
  42765. self.model = gltfModel.scene || gltfModel.scenes[0];
  42766. self.model.animations = gltfModel.animations;
  42767. el.setObject3D('mesh', self.model);
  42768. el.emit('model-loaded', {format: 'gltf', model: self.model});
  42769. }, undefined /* onProgress */, function gltfFailed (error) {
  42770. var message = (error && error.message) ? error.message : 'Failed to load glTF model';
  42771. warn(message);
  42772. el.emit('model-error', {format: 'gltf', src: src});
  42773. });
  42774. },
  42775. remove: function () {
  42776. if (!this.model) { return; }
  42777. this.el.removeObject3D('mesh');
  42778. }
  42779. });
  42780. },{"../core/component":103,"../lib/three":151,"../utils/":176}],59:[function(_dereq_,module,exports){
  42781. /* global THREE */
  42782. var registerComponent = _dereq_('../core/component').registerComponent;
  42783. // Found at https://github.com/aframevr/assets.
  42784. var MODEL_URLS = {
  42785. left: 'https://cdn.aframe.io/controllers/hands/leftHand.glb',
  42786. right: 'https://cdn.aframe.io/controllers/hands/rightHand.glb'
  42787. };
  42788. // Poses.
  42789. var ANIMATIONS = {
  42790. open: 'Open',
  42791. // point: grip active, trackpad surface active, trigger inactive.
  42792. point: 'Point',
  42793. // pointThumb: grip active, trigger inactive, trackpad surface inactive.
  42794. pointThumb: 'Point + Thumb',
  42795. // fist: grip active, trigger active, trackpad surface active.
  42796. fist: 'Fist',
  42797. // hold: trigger active, grip inactive.
  42798. hold: 'Hold',
  42799. // thumbUp: grip active, trigger active, trackpad surface inactive.
  42800. thumbUp: 'Thumb Up'
  42801. };
  42802. // Map animation to public events for the API.
  42803. var EVENTS = {};
  42804. EVENTS[ANIMATIONS.fist] = 'grip';
  42805. EVENTS[ANIMATIONS.thumbUp] = 'pistol';
  42806. EVENTS[ANIMATIONS.point] = 'pointing';
  42807. EVENTS[ANIMATIONS.thumb] = 'thumb';
  42808. /**
  42809. * Hand controls component that abstracts 6DoF controls:
  42810. * oculus-touch-controls, vive-controls, windows-motion-controls.
  42811. *
  42812. * Originally meant to be a sample implementation of applications-specific controls that
  42813. * abstracts multiple types of controllers.
  42814. *
  42815. * Auto-detect appropriate controller.
  42816. * Handle common events coming from the detected vendor-specific controls.
  42817. * Translate button events to semantic hand-related event names:
  42818. * (gripclose, gripopen, thumbup, thumbdown, pointup, pointdown)
  42819. * Load hand model with gestures that are applied based on the button pressed.
  42820. *
  42821. * @property {string} Hand mapping (`left`, `right`).
  42822. */
  42823. module.exports.Component = registerComponent('hand-controls', {
  42824. schema: {default: 'left'},
  42825. init: function () {
  42826. var self = this;
  42827. var el = this.el;
  42828. // Current pose.
  42829. this.gesture = ANIMATIONS.open;
  42830. // Active buttons populated by events provided by the attached controls.
  42831. this.pressedButtons = {};
  42832. this.touchedButtons = {};
  42833. this.loader = new THREE.GLTFLoader();
  42834. this.loader.setCrossOrigin('anonymous');
  42835. this.onGripDown = function () { self.handleButton('grip', 'down'); };
  42836. this.onGripUp = function () { self.handleButton('grip', 'up'); };
  42837. this.onTrackpadDown = function () { self.handleButton('trackpad', 'down'); };
  42838. this.onTrackpadUp = function () { self.handleButton('trackpad', 'up'); };
  42839. this.onTrackpadTouchStart = function () { self.handleButton('trackpad', 'touchstart'); };
  42840. this.onTrackpadTouchEnd = function () { self.handleButton('trackpad', 'touchend'); };
  42841. this.onTriggerDown = function () { self.handleButton('trigger', 'down'); };
  42842. this.onTriggerUp = function () { self.handleButton('trigger', 'up'); };
  42843. this.onTriggerTouchStart = function () { self.handleButton('trigger', 'touchstart'); };
  42844. this.onTriggerTouchEnd = function () { self.handleButton('trigger', 'touchend'); };
  42845. this.onGripTouchStart = function () { self.handleButton('grip', 'touchstart'); };
  42846. this.onGripTouchEnd = function () { self.handleButton('grip', 'touchend'); };
  42847. this.onThumbstickDown = function () { self.handleButton('thumbstick', 'down'); };
  42848. this.onThumbstickUp = function () { self.handleButton('thumbstick', 'up'); };
  42849. this.onAorXTouchStart = function () { self.handleButton('AorX', 'touchstart'); };
  42850. this.onAorXTouchEnd = function () { self.handleButton('AorX', 'touchend'); };
  42851. this.onBorYTouchStart = function () { self.handleButton('BorY', 'touchstart'); };
  42852. this.onBorYTouchEnd = function () { self.handleButton('BorY', 'touchend'); };
  42853. this.onSurfaceTouchStart = function () { self.handleButton('surface', 'touchstart'); };
  42854. this.onSurfaceTouchEnd = function () { self.handleButton('surface', 'touchend'); };
  42855. el.addEventListener('controllerconnected', this.onControllerConnected);
  42856. el.addEventListener('controllerdisconnected', this.onControllerDisconnected);
  42857. // Hidden by default.
  42858. el.object3D.visible = false;
  42859. },
  42860. play: function () {
  42861. this.addEventListeners();
  42862. },
  42863. pause: function () {
  42864. this.removeEventListeners();
  42865. },
  42866. tick: function (time, delta) {
  42867. var mesh = this.el.getObject3D('mesh');
  42868. if (!mesh || !mesh.mixer) { return; }
  42869. mesh.mixer.update(delta / 1000);
  42870. },
  42871. addEventListeners: function () {
  42872. var el = this.el;
  42873. el.addEventListener('gripdown', this.onGripDown);
  42874. el.addEventListener('gripup', this.onGripUp);
  42875. el.addEventListener('trackpaddown', this.onTrackpadDown);
  42876. el.addEventListener('trackpadup', this.onTrackpadUp);
  42877. el.addEventListener('trackpadtouchstart', this.onTrackpadTouchStart);
  42878. el.addEventListener('trackpadtouchend', this.onTrackpadTouchEnd);
  42879. el.addEventListener('triggerdown', this.onTriggerDown);
  42880. el.addEventListener('triggerup', this.onTriggerUp);
  42881. el.addEventListener('triggertouchstart', this.onTriggerTouchStart);
  42882. el.addEventListener('triggertouchend', this.onTriggerTouchEnd);
  42883. el.addEventListener('griptouchstart', this.onGripTouchStart);
  42884. el.addEventListener('griptouchend', this.onGripTouchEnd);
  42885. el.addEventListener('thumbstickdown', this.onThumbstickDown);
  42886. el.addEventListener('thumbstickup', this.onThumbstickUp);
  42887. el.addEventListener('abuttontouchstart', this.onAorXTouchStart);
  42888. el.addEventListener('abuttontouchend', this.onAorXTouchEnd);
  42889. el.addEventListener('bbuttontouchstart', this.onBorYTouchStart);
  42890. el.addEventListener('bbuttontouchend', this.onBorYTouchEnd);
  42891. el.addEventListener('xbuttontouchstart', this.onAorXTouchStart);
  42892. el.addEventListener('xbuttontouchend', this.onAorXTouchEnd);
  42893. el.addEventListener('ybuttontouchstart', this.onBorYTouchStart);
  42894. el.addEventListener('ybuttontouchend', this.onBorYTouchEnd);
  42895. el.addEventListener('surfacetouchstart', this.onSurfaceTouchStart);
  42896. el.addEventListener('surfacetouchend', this.onSurfaceTouchEnd);
  42897. },
  42898. removeEventListeners: function () {
  42899. var el = this.el;
  42900. el.removeEventListener('gripdown', this.onGripDown);
  42901. el.removeEventListener('gripup', this.onGripUp);
  42902. el.removeEventListener('trackpaddown', this.onTrackpadDown);
  42903. el.removeEventListener('trackpadup', this.onTrackpadUp);
  42904. el.removeEventListener('trackpadtouchstart', this.onTrackpadTouchStart);
  42905. el.removeEventListener('trackpadtouchend', this.onTrackpadTouchEnd);
  42906. el.removeEventListener('triggerdown', this.onTriggerDown);
  42907. el.removeEventListener('triggerup', this.onTriggerUp);
  42908. el.removeEventListener('triggertouchstart', this.onTriggerTouchStart);
  42909. el.removeEventListener('triggertouchend', this.onTriggerTouchEnd);
  42910. el.removeEventListener('griptouchstart', this.onGripTouchStart);
  42911. el.removeEventListener('griptouchend', this.onGripTouchEnd);
  42912. el.removeEventListener('thumbstickdown', this.onThumbstickDown);
  42913. el.removeEventListener('thumbstickup', this.onThumbstickUp);
  42914. el.removeEventListener('abuttontouchstart', this.onAorXTouchStart);
  42915. el.removeEventListener('abuttontouchend', this.onAorXTouchEnd);
  42916. el.removeEventListener('bbuttontouchstart', this.onBorYTouchStart);
  42917. el.removeEventListener('bbuttontouchend', this.onBorYTouchEnd);
  42918. el.removeEventListener('xbuttontouchstart', this.onAorXTouchStart);
  42919. el.removeEventListener('xbuttontouchend', this.onAorXTouchEnd);
  42920. el.removeEventListener('ybuttontouchstart', this.onBorYTouchStart);
  42921. el.removeEventListener('ybuttontouchend', this.onBorYTouchEnd);
  42922. el.removeEventListener('surfacetouchstart', this.onSurfaceTouchStart);
  42923. el.removeEventListener('surfacetouchend', this.onSurfaceTouchEnd);
  42924. },
  42925. /**
  42926. * Update handler. More like the `init` handler since the only property is the hand, and
  42927. * that won't be changing much.
  42928. */
  42929. update: function (previousHand) {
  42930. var controlConfiguration;
  42931. var el = this.el;
  42932. var hand = this.data;
  42933. var self = this;
  42934. // Get common configuration to abstract different vendor controls.
  42935. controlConfiguration = {
  42936. hand: hand,
  42937. model: false,
  42938. orientationOffset: {x: 0, y: 0, z: hand === 'left' ? 90 : -90}
  42939. };
  42940. // Set model.
  42941. if (hand !== previousHand) {
  42942. this.loader.load(MODEL_URLS[hand], function (gltf) {
  42943. var mesh = gltf.scene.children[0];
  42944. mesh.mixer = new THREE.AnimationMixer(mesh);
  42945. self.clips = gltf.animations;
  42946. el.setObject3D('mesh', mesh);
  42947. mesh.position.set(0, 0, 0);
  42948. mesh.rotation.set(0, 0, 0);
  42949. el.setAttribute('vive-controls', controlConfiguration);
  42950. el.setAttribute('oculus-touch-controls', controlConfiguration);
  42951. el.setAttribute('windows-motion-controls', controlConfiguration);
  42952. });
  42953. }
  42954. },
  42955. remove: function () {
  42956. this.el.removeObject3D('mesh');
  42957. },
  42958. /**
  42959. * Play model animation, based on which button was pressed and which kind of event.
  42960. *
  42961. * 1. Process buttons.
  42962. * 2. Determine gesture (this.determineGesture()).
  42963. * 3. Animation gesture (this.animationGesture()).
  42964. * 4. Emit gesture events (this.emitGestureEvents()).
  42965. *
  42966. * @param {string} button - Name of the button.
  42967. * @param {string} evt - Type of event for the button (i.e., down/up/touchstart/touchend).
  42968. */
  42969. handleButton: function (button, evt) {
  42970. var lastGesture;
  42971. var isPressed = evt === 'down';
  42972. var isTouched = evt === 'touchstart';
  42973. // Update objects.
  42974. if (evt.indexOf('touch') === 0) {
  42975. // Update touch object.
  42976. if (isTouched === this.touchedButtons[button]) { return; }
  42977. this.touchedButtons[button] = isTouched;
  42978. } else {
  42979. // Update button object.
  42980. if (isPressed === this.pressedButtons[button]) { return; }
  42981. this.pressedButtons[button] = isPressed;
  42982. }
  42983. // Determine the gesture.
  42984. lastGesture = this.gesture;
  42985. this.gesture = this.determineGesture();
  42986. // Same gesture.
  42987. if (this.gesture === lastGesture) { return; }
  42988. // Animate gesture.
  42989. this.animateGesture(this.gesture, lastGesture);
  42990. // Emit events.
  42991. this.emitGestureEvents(this.gesture, lastGesture);
  42992. },
  42993. /**
  42994. * Determine which pose hand should be in considering active and touched buttons.
  42995. */
  42996. determineGesture: function () {
  42997. var gesture;
  42998. var isGripActive = this.pressedButtons['grip'];
  42999. var isSurfaceActive = this.pressedButtons['surface'] || this.touchedButtons['surface'];
  43000. var isTrackpadActive = this.pressedButtons['trackpad'] || this.touchedButtons['trackpad'];
  43001. var isTriggerActive = this.pressedButtons['trigger'] || this.touchedButtons['trigger'];
  43002. var isABXYActive = this.touchedButtons['AorX'] || this.touchedButtons['BorY'];
  43003. var isVive = isViveController(this.el.components['tracked-controls']);
  43004. // Works well with Oculus Touch and Windows Motion Controls, but Vive needs tweaks.
  43005. if (isVive) {
  43006. if (isGripActive || isTriggerActive) {
  43007. gesture = ANIMATIONS.fist;
  43008. } else if (isTrackpadActive) {
  43009. gesture = ANIMATIONS.point;
  43010. }
  43011. } else {
  43012. if (isGripActive) {
  43013. if (isSurfaceActive || isABXYActive || isTrackpadActive) {
  43014. gesture = isTriggerActive ? ANIMATIONS.fist : ANIMATIONS.point;
  43015. } else {
  43016. gesture = isTriggerActive ? ANIMATIONS.thumbUp : ANIMATIONS.pointThumb;
  43017. }
  43018. } else if (isTriggerActive) {
  43019. gesture = ANIMATIONS.hold;
  43020. }
  43021. }
  43022. return gesture;
  43023. },
  43024. /**
  43025. * Play corresponding clip to a gesture
  43026. */
  43027. getClip: function (gesture) {
  43028. var clip;
  43029. var i;
  43030. for (i = 0; i < this.clips.length; i++) {
  43031. clip = this.clips[i];
  43032. if (clip.name !== gesture) { continue; }
  43033. return clip;
  43034. }
  43035. },
  43036. /**
  43037. * Play gesture animation.
  43038. *
  43039. * @param {string} gesture - Which pose to animate to. If absent, then animate to open.
  43040. * @param {string} lastGesture - Previous gesture, to reverse back to open if needed.
  43041. */
  43042. animateGesture: function (gesture, lastGesture) {
  43043. if (gesture) {
  43044. this.playAnimation(gesture || ANIMATIONS.open, lastGesture, false);
  43045. return;
  43046. }
  43047. // If no gesture, then reverse the current gesture back to open pose.
  43048. this.playAnimation(lastGesture, lastGesture, true);
  43049. },
  43050. /**
  43051. * Emit `hand-controls`-specific events.
  43052. */
  43053. emitGestureEvents: function (gesture, lastGesture) {
  43054. var el = this.el;
  43055. var eventName;
  43056. if (lastGesture === gesture) { return; }
  43057. // Emit event for lastGesture not inactive.
  43058. eventName = getGestureEventName(lastGesture, false);
  43059. if (eventName) { el.emit(eventName); }
  43060. // Emit event for current gesture now active.
  43061. eventName = getGestureEventName(gesture, true);
  43062. if (eventName) { el.emit(eventName); }
  43063. },
  43064. /**
  43065. * Play hand animation based on button state.
  43066. *
  43067. * @param {string} gesture - Name of the animation as specified by the model.
  43068. * @param {string} lastGesture - Previous pose.
  43069. * @param {boolean} reverse - Whether animation should play in reverse.
  43070. */
  43071. playAnimation: function (gesture, lastGesture, reverse) {
  43072. var clip;
  43073. var fromAction;
  43074. var mesh = this.el.getObject3D('mesh');
  43075. var toAction;
  43076. if (!mesh) { return; }
  43077. // Stop all current animations.
  43078. mesh.mixer.stopAllAction();
  43079. // Grab clip action.
  43080. clip = this.getClip(gesture);
  43081. toAction = mesh.mixer.clipAction(clip);
  43082. toAction.clampWhenFinished = true;
  43083. toAction.loop = THREE.LoopRepeat;
  43084. toAction.repetitions = 0;
  43085. toAction.timeScale = reverse ? -1 : 1;
  43086. toAction.time = reverse ? clip.duration : 0;
  43087. toAction.weight = 1;
  43088. // No gesture to gesture or gesture to no gesture.
  43089. if (!lastGesture || gesture === lastGesture) {
  43090. // Stop all current animations.
  43091. mesh.mixer.stopAllAction();
  43092. // Play animation.
  43093. toAction.play();
  43094. return;
  43095. }
  43096. // Animate or crossfade from gesture to gesture.
  43097. clip = this.getClip(lastGesture);
  43098. fromAction = mesh.mixer.clipAction(clip);
  43099. fromAction.weight = 0.15;
  43100. fromAction.play();
  43101. toAction.play();
  43102. fromAction.crossFadeTo(toAction, 0.15, true);
  43103. }
  43104. });
  43105. /**
  43106. * Suffix gestures based on toggle state (e.g., open/close, up/down, start/end).
  43107. *
  43108. * @param {string} gesture
  43109. * @param {boolean} active
  43110. */
  43111. function getGestureEventName (gesture, active) {
  43112. var eventName;
  43113. if (!gesture) { return; }
  43114. eventName = EVENTS[gesture];
  43115. if (eventName === 'grip') {
  43116. return eventName + (active ? 'close' : 'open');
  43117. }
  43118. if (eventName === 'point' || eventName === 'thumb') {
  43119. return eventName + (active ? 'up' : 'down');
  43120. }
  43121. if (eventName === 'pointing' || eventName === 'pistol') {
  43122. return eventName + (active ? 'start' : 'end');
  43123. }
  43124. return;
  43125. }
  43126. function isViveController (trackedControls) {
  43127. var controllerId = trackedControls && trackedControls.controller &&
  43128. trackedControls.controller.id;
  43129. return controllerId && controllerId.indexOf('OpenVR ') === 0;
  43130. }
  43131. },{"../core/component":103}],60:[function(_dereq_,module,exports){
  43132. _dereq_('./animation');
  43133. _dereq_('./camera');
  43134. _dereq_('./cursor');
  43135. _dereq_('./daydream-controls');
  43136. _dereq_('./gearvr-controls');
  43137. _dereq_('./geometry');
  43138. _dereq_('./gltf-model');
  43139. _dereq_('./hand-controls');
  43140. _dereq_('./laser-controls');
  43141. _dereq_('./light');
  43142. _dereq_('./line');
  43143. _dereq_('./link');
  43144. _dereq_('./look-controls');
  43145. _dereq_('./material');
  43146. _dereq_('./obj-model');
  43147. _dereq_('./oculus-go-controls');
  43148. _dereq_('./oculus-touch-controls');
  43149. _dereq_('./position');
  43150. _dereq_('./raycaster');
  43151. _dereq_('./rotation');
  43152. _dereq_('./scale');
  43153. _dereq_('./shadow');
  43154. _dereq_('./sound');
  43155. _dereq_('./text');
  43156. _dereq_('./tracked-controls');
  43157. _dereq_('./tracked-controls-webvr');
  43158. _dereq_('./tracked-controls-webxr');
  43159. _dereq_('./visible');
  43160. _dereq_('./vive-controls');
  43161. _dereq_('./vive-focus-controls');
  43162. _dereq_('./wasd-controls');
  43163. _dereq_('./windows-motion-controls');
  43164. _dereq_('./scene/background');
  43165. _dereq_('./scene/debug');
  43166. _dereq_('./scene/embedded');
  43167. _dereq_('./scene/inspector');
  43168. _dereq_('./scene/fog');
  43169. _dereq_('./scene/keyboard-shortcuts');
  43170. _dereq_('./scene/pool');
  43171. _dereq_('./scene/screenshot');
  43172. _dereq_('./scene/stats');
  43173. _dereq_('./scene/vr-mode-ui');
  43174. },{"./animation":52,"./camera":53,"./cursor":54,"./daydream-controls":55,"./gearvr-controls":56,"./geometry":57,"./gltf-model":58,"./hand-controls":59,"./laser-controls":61,"./light":62,"./line":63,"./link":64,"./look-controls":65,"./material":66,"./obj-model":67,"./oculus-go-controls":68,"./oculus-touch-controls":69,"./position":70,"./raycaster":71,"./rotation":72,"./scale":73,"./scene/background":74,"./scene/debug":75,"./scene/embedded":76,"./scene/fog":77,"./scene/inspector":78,"./scene/keyboard-shortcuts":79,"./scene/pool":80,"./scene/screenshot":81,"./scene/stats":82,"./scene/vr-mode-ui":83,"./shadow":84,"./sound":85,"./text":86,"./tracked-controls":89,"./tracked-controls-webvr":87,"./tracked-controls-webxr":88,"./visible":90,"./vive-controls":91,"./vive-focus-controls":92,"./wasd-controls":93,"./windows-motion-controls":94}],61:[function(_dereq_,module,exports){
  43175. var registerComponent = _dereq_('../core/component').registerComponent;
  43176. var utils = _dereq_('../utils/');
  43177. registerComponent('laser-controls', {
  43178. schema: {
  43179. hand: {default: 'right'},
  43180. model: {default: true},
  43181. defaultModelColor: {type: 'color', default: 'grey'}
  43182. },
  43183. init: function () {
  43184. var config = this.config;
  43185. var data = this.data;
  43186. var el = this.el;
  43187. var self = this;
  43188. var modelEnabled = this.data.model && !this.el.sceneEl.hasWebXR;
  43189. var controlsConfiguration = {hand: data.hand, model: modelEnabled};
  43190. // Set all controller models.
  43191. el.setAttribute('daydream-controls', controlsConfiguration);
  43192. el.setAttribute('gearvr-controls', controlsConfiguration);
  43193. el.setAttribute('oculus-go-controls', controlsConfiguration);
  43194. el.setAttribute('oculus-touch-controls', controlsConfiguration);
  43195. el.setAttribute('vive-controls', controlsConfiguration);
  43196. el.setAttribute('vive-focus-controls', controlsConfiguration);
  43197. el.setAttribute('windows-motion-controls', controlsConfiguration);
  43198. // WebXR doesn't allow to discriminate between controllers, a default model is used.
  43199. if (this.data.model && this.el.sceneEl.hasWebXR) { this.initDefaultModel(); }
  43200. // Wait for controller to connect, or have a valid pointing pose, before creating ray
  43201. el.addEventListener('controllerconnected', createRay);
  43202. el.addEventListener('controllerdisconnected', hideRay);
  43203. el.addEventListener('controllermodelready', function (evt) {
  43204. createRay(evt);
  43205. self.modelReady = true;
  43206. });
  43207. function createRay (evt) {
  43208. var controllerConfig = config[evt.detail.name];
  43209. if (!controllerConfig) { return; }
  43210. // Show the line unless a particular config opts to hide it, until a controllermodelready
  43211. // event comes through.
  43212. var raycasterConfig = utils.extend({
  43213. showLine: true
  43214. }, controllerConfig.raycaster || {});
  43215. // The controllermodelready event contains a rayOrigin that takes into account
  43216. // offsets specific to the loaded model.
  43217. if (evt.detail.rayOrigin) {
  43218. raycasterConfig.origin = evt.detail.rayOrigin.origin;
  43219. raycasterConfig.direction = evt.detail.rayOrigin.direction;
  43220. raycasterConfig.showLine = true;
  43221. }
  43222. // Only apply a default raycaster if it does not yet exist. This prevents it overwriting
  43223. // config applied from a controllermodelready event.
  43224. if (evt.detail.rayOrigin || !self.modelReady) {
  43225. el.setAttribute('raycaster', raycasterConfig);
  43226. } else {
  43227. el.setAttribute('raycaster', 'showLine', true);
  43228. }
  43229. el.setAttribute('cursor', utils.extend({
  43230. fuse: false
  43231. }, controllerConfig.cursor));
  43232. }
  43233. function hideRay () {
  43234. el.setAttribute('raycaster', 'showLine', false);
  43235. }
  43236. },
  43237. config: {
  43238. 'daydream-controls': {
  43239. cursor: {downEvents: ['trackpaddown', 'triggerdown'], upEvents: ['trackpadup', 'triggerup']}
  43240. },
  43241. 'gearvr-controls': {
  43242. cursor: {downEvents: ['triggerdown'], upEvents: ['triggerup']},
  43243. raycaster: {origin: {x: 0, y: 0.0005, z: 0}}
  43244. },
  43245. 'oculus-go-controls': {
  43246. cursor: {downEvents: ['triggerdown'], upEvents: ['triggerup']},
  43247. raycaster: {origin: {x: 0, y: 0.0005, z: 0}}
  43248. },
  43249. 'oculus-touch-controls': {
  43250. cursor: {downEvents: ['triggerdown'], upEvents: ['triggerup']},
  43251. raycaster: {origin: {x: 0, y: 0, z: 0}}
  43252. },
  43253. 'vive-controls': {
  43254. cursor: {downEvents: ['triggerdown'], upEvents: ['triggerup']}
  43255. },
  43256. 'vive-focus-controls': {
  43257. cursor: {downEvents: ['trackpaddown', 'triggerdown'], upEvents: ['trackpadup', 'triggerup']}
  43258. },
  43259. 'windows-motion-controls': {
  43260. cursor: {downEvents: ['triggerdown'], upEvents: ['triggerup']},
  43261. raycaster: {showLine: false}
  43262. }
  43263. },
  43264. initDefaultModel: function () {
  43265. var modelEl = this.modelEl = document.createElement('a-entity');
  43266. modelEl.setAttribute('geometry', {
  43267. primitive: 'sphere',
  43268. radius: 0.03
  43269. });
  43270. modelEl.setAttribute('material', {color: this.data.color});
  43271. this.el.appendChild(modelEl);
  43272. }
  43273. });
  43274. },{"../core/component":103,"../utils/":176}],62:[function(_dereq_,module,exports){
  43275. var bind = _dereq_('../utils/bind');
  43276. var diff = _dereq_('../utils').diff;
  43277. var debug = _dereq_('../utils/debug');
  43278. var registerComponent = _dereq_('../core/component').registerComponent;
  43279. var THREE = _dereq_('../lib/three');
  43280. var degToRad = THREE.Math.degToRad;
  43281. var warn = debug('components:light:warn');
  43282. /**
  43283. * Light component.
  43284. */
  43285. module.exports.Component = registerComponent('light', {
  43286. schema: {
  43287. angle: {default: 60, if: {type: ['spot']}},
  43288. color: {type: 'color'},
  43289. groundColor: {type: 'color', if: {type: ['hemisphere']}},
  43290. decay: {default: 1, if: {type: ['point', 'spot']}},
  43291. distance: {default: 0.0, min: 0, if: {type: ['point', 'spot']}},
  43292. intensity: {default: 1.0, min: 0, if: {type: ['ambient', 'directional', 'hemisphere', 'point', 'spot']}},
  43293. penumbra: {default: 0, min: 0, max: 1, if: {type: ['spot']}},
  43294. type: {
  43295. default: 'directional',
  43296. oneOf: ['ambient', 'directional', 'hemisphere', 'point', 'spot'],
  43297. schemaChange: true
  43298. },
  43299. target: {type: 'selector', if: {type: ['spot', 'directional']}},
  43300. // Shadows.
  43301. castShadow: {default: false, if: {type: ['point', 'spot', 'directional']}},
  43302. shadowBias: {default: 0, if: {castShadow: true}},
  43303. shadowCameraFar: {default: 500, if: {castShadow: true}},
  43304. shadowCameraFov: {default: 90, if: {castShadow: true}},
  43305. shadowCameraNear: {default: 0.5, if: {castShadow: true}},
  43306. shadowCameraTop: {default: 5, if: {castShadow: true}},
  43307. shadowCameraRight: {default: 5, if: {castShadow: true}},
  43308. shadowCameraBottom: {default: -5, if: {castShadow: true}},
  43309. shadowCameraLeft: {default: -5, if: {castShadow: true}},
  43310. shadowCameraVisible: {default: false, if: {castShadow: true}},
  43311. shadowMapHeight: {default: 512, if: {castShadow: true}},
  43312. shadowMapWidth: {default: 512, if: {castShadow: true}},
  43313. shadowRadius: {default: 1, if: {castShadow: true}}
  43314. },
  43315. /**
  43316. * Notifies scene a light has been added to remove default lighting.
  43317. */
  43318. init: function () {
  43319. var el = this.el;
  43320. this.light = null;
  43321. this.defaultTarget = null;
  43322. this.rendererSystem = this.el.sceneEl.systems.renderer;
  43323. this.system.registerLight(el);
  43324. },
  43325. /**
  43326. * (Re)create or update light.
  43327. */
  43328. update: function (oldData) {
  43329. var data = this.data;
  43330. var diffData = diff(data, oldData);
  43331. var light = this.light;
  43332. var rendererSystem = this.rendererSystem;
  43333. var self = this;
  43334. // Existing light.
  43335. if (light && !('type' in diffData)) {
  43336. var shadowsLoaded = false;
  43337. // Light type has not changed. Update light.
  43338. Object.keys(diffData).forEach(function (key) {
  43339. var value = data[key];
  43340. switch (key) {
  43341. case 'color': {
  43342. light.color.set(value);
  43343. rendererSystem.applyColorCorrection(light.color);
  43344. break;
  43345. }
  43346. case 'groundColor': {
  43347. light.groundColor.set(value);
  43348. rendererSystem.applyColorCorrection(light.groundColor);
  43349. break;
  43350. }
  43351. case 'angle': {
  43352. light.angle = degToRad(value);
  43353. break;
  43354. }
  43355. case 'target': {
  43356. // Reset target if selector is null.
  43357. if (value === null) {
  43358. if (data.type === 'spot' || data.type === 'directional') {
  43359. light.target = self.defaultTarget;
  43360. }
  43361. } else {
  43362. // Target specified, set target to entity's `object3D` when it is loaded.
  43363. if (value.hasLoaded) {
  43364. self.onSetTarget(value, light);
  43365. } else {
  43366. value.addEventListener('loaded', bind(self.onSetTarget, self, value, light));
  43367. }
  43368. }
  43369. break;
  43370. }
  43371. case 'castShadow':
  43372. case 'shadowBias':
  43373. case 'shadowCameraFar':
  43374. case 'shadowCameraFov':
  43375. case 'shadowCameraNear':
  43376. case 'shadowCameraTop':
  43377. case 'shadowCameraRight':
  43378. case 'shadowCameraBottom':
  43379. case 'shadowCameraLeft':
  43380. case 'shadowCameraVisible':
  43381. case 'shadowMapHeight':
  43382. case 'shadowMapWidth':
  43383. case 'shadowRadius':
  43384. if (!shadowsLoaded) {
  43385. self.updateShadow();
  43386. shadowsLoaded = true;
  43387. }
  43388. break;
  43389. default: {
  43390. light[key] = value;
  43391. }
  43392. }
  43393. });
  43394. return;
  43395. }
  43396. // No light yet or light type has changed. Create and add light.
  43397. this.setLight(this.data);
  43398. this.updateShadow();
  43399. },
  43400. setLight: function (data) {
  43401. var el = this.el;
  43402. var newLight = this.getLight(data);
  43403. if (newLight) {
  43404. if (this.light) {
  43405. el.removeObject3D('light');
  43406. }
  43407. this.light = newLight;
  43408. this.light.el = el;
  43409. el.setObject3D('light', this.light);
  43410. // HACK solution for issue #1624
  43411. if (data.type === 'spot' || data.type === 'directional' || data.type === 'hemisphere') {
  43412. el.getObject3D('light').translateY(-1);
  43413. }
  43414. // set and position default lighttarget as a child to enable spotlight orientation
  43415. if (data.type === 'spot') {
  43416. el.setObject3D('light-target', this.defaultTarget);
  43417. el.getObject3D('light-target').position.set(0, 0, -1);
  43418. }
  43419. }
  43420. },
  43421. /**
  43422. * Updates shadow-related properties on the current light.
  43423. */
  43424. updateShadow: function () {
  43425. var el = this.el;
  43426. var data = this.data;
  43427. var light = this.light;
  43428. light.castShadow = data.castShadow;
  43429. // Shadow camera helper.
  43430. var cameraHelper = el.getObject3D('cameraHelper');
  43431. if (data.shadowCameraVisible && !cameraHelper) {
  43432. el.setObject3D('cameraHelper', new THREE.CameraHelper(light.shadow.camera));
  43433. } else if (!data.shadowCameraVisible && cameraHelper) {
  43434. el.removeObject3D('cameraHelper');
  43435. }
  43436. if (!data.castShadow) { return light; }
  43437. // Shadow appearance.
  43438. light.shadow.bias = data.shadowBias;
  43439. light.shadow.radius = data.shadowRadius;
  43440. light.shadow.mapSize.height = data.shadowMapHeight;
  43441. light.shadow.mapSize.width = data.shadowMapWidth;
  43442. // Shadow camera.
  43443. light.shadow.camera.near = data.shadowCameraNear;
  43444. light.shadow.camera.far = data.shadowCameraFar;
  43445. if (light.shadow.camera instanceof THREE.OrthographicCamera) {
  43446. light.shadow.camera.top = data.shadowCameraTop;
  43447. light.shadow.camera.right = data.shadowCameraRight;
  43448. light.shadow.camera.bottom = data.shadowCameraBottom;
  43449. light.shadow.camera.left = data.shadowCameraLeft;
  43450. } else {
  43451. light.shadow.camera.fov = data.shadowCameraFov;
  43452. }
  43453. light.shadow.camera.updateProjectionMatrix();
  43454. if (cameraHelper) { cameraHelper.update(); }
  43455. },
  43456. /**
  43457. * Creates a new three.js light object given data object defining the light.
  43458. *
  43459. * @param {object} data
  43460. */
  43461. getLight: function (data) {
  43462. var angle = data.angle;
  43463. var color = new THREE.Color(data.color);
  43464. this.rendererSystem.applyColorCorrection(color);
  43465. color = color.getHex();
  43466. var decay = data.decay;
  43467. var distance = data.distance;
  43468. var groundColor = new THREE.Color(data.groundColor);
  43469. this.rendererSystem.applyColorCorrection(groundColor);
  43470. groundColor = groundColor.getHex();
  43471. var intensity = data.intensity;
  43472. var type = data.type;
  43473. var target = data.target;
  43474. var light = null;
  43475. switch (type.toLowerCase()) {
  43476. case 'ambient': {
  43477. return new THREE.AmbientLight(color, intensity);
  43478. }
  43479. case 'directional': {
  43480. light = new THREE.DirectionalLight(color, intensity);
  43481. this.defaultTarget = light.target;
  43482. if (target) {
  43483. if (target.hasLoaded) {
  43484. this.onSetTarget(target, light);
  43485. } else {
  43486. target.addEventListener('loaded', bind(this.onSetTarget, this, target, light));
  43487. }
  43488. }
  43489. return light;
  43490. }
  43491. case 'hemisphere': {
  43492. return new THREE.HemisphereLight(color, groundColor, intensity);
  43493. }
  43494. case 'point': {
  43495. return new THREE.PointLight(color, intensity, distance, decay);
  43496. }
  43497. case 'spot': {
  43498. light = new THREE.SpotLight(color, intensity, distance, degToRad(angle), data.penumbra, decay);
  43499. this.defaultTarget = light.target;
  43500. if (target) {
  43501. if (target.hasLoaded) {
  43502. this.onSetTarget(target, light);
  43503. } else {
  43504. target.addEventListener('loaded', bind(this.onSetTarget, this, target, light));
  43505. }
  43506. }
  43507. return light;
  43508. }
  43509. default: {
  43510. warn('%s is not a valid light type. ' +
  43511. 'Choose from ambient, directional, hemisphere, point, spot.', type);
  43512. }
  43513. }
  43514. },
  43515. onSetTarget: function (targetEl, light) {
  43516. light.target = targetEl.object3D;
  43517. },
  43518. /**
  43519. * Remove light on remove (callback).
  43520. */
  43521. remove: function () {
  43522. var el = this.el;
  43523. el.removeObject3D('light');
  43524. if (el.getObject3D('cameraHelper')) {
  43525. el.removeObject3D('cameraHelper');
  43526. }
  43527. }
  43528. });
  43529. },{"../core/component":103,"../lib/three":151,"../utils":176,"../utils/bind":170,"../utils/debug":172}],63:[function(_dereq_,module,exports){
  43530. /* global THREE */
  43531. var registerComponent = _dereq_('../core/component').registerComponent;
  43532. module.exports.Component = registerComponent('line', {
  43533. schema: {
  43534. start: {type: 'vec3', default: {x: 0, y: 0, z: 0}},
  43535. end: {type: 'vec3', default: {x: 0, y: 0, z: 0}},
  43536. color: {type: 'color', default: '#74BEC1'},
  43537. opacity: {type: 'number', default: 1},
  43538. visible: {default: true}
  43539. },
  43540. multiple: true,
  43541. init: function () {
  43542. var data = this.data;
  43543. var geometry;
  43544. var material;
  43545. this.rendererSystem = this.el.sceneEl.systems.renderer;
  43546. material = this.material = new THREE.LineBasicMaterial({
  43547. color: data.color,
  43548. opacity: data.opacity,
  43549. transparent: data.opacity < 1,
  43550. visible: data.visible
  43551. });
  43552. geometry = this.geometry = new THREE.BufferGeometry();
  43553. geometry.addAttribute('position', new THREE.BufferAttribute(new Float32Array(2 * 3), 3));
  43554. this.rendererSystem.applyColorCorrection(material.color);
  43555. this.line = new THREE.Line(geometry, material);
  43556. this.el.setObject3D(this.attrName, this.line);
  43557. },
  43558. update: function (oldData) {
  43559. var data = this.data;
  43560. var geometry = this.geometry;
  43561. var geoNeedsUpdate = false;
  43562. var material = this.material;
  43563. var positionArray = geometry.attributes.position.array;
  43564. // Update geometry.
  43565. if (!isEqualVec3(data.start, oldData.start)) {
  43566. positionArray[0] = data.start.x;
  43567. positionArray[1] = data.start.y;
  43568. positionArray[2] = data.start.z;
  43569. geoNeedsUpdate = true;
  43570. }
  43571. if (!isEqualVec3(data.end, oldData.end)) {
  43572. positionArray[3] = data.end.x;
  43573. positionArray[4] = data.end.y;
  43574. positionArray[5] = data.end.z;
  43575. geoNeedsUpdate = true;
  43576. }
  43577. if (geoNeedsUpdate) {
  43578. geometry.attributes.position.needsUpdate = true;
  43579. geometry.computeBoundingSphere();
  43580. }
  43581. material.color.setStyle(data.color);
  43582. this.rendererSystem.applyColorCorrection(material.color);
  43583. material.opacity = data.opacity;
  43584. material.transparent = data.opacity < 1;
  43585. material.visible = data.visible;
  43586. },
  43587. remove: function () {
  43588. this.el.removeObject3D('line', this.line);
  43589. }
  43590. });
  43591. function isEqualVec3 (a, b) {
  43592. if (!a || !b) { return false; }
  43593. return (a.x === b.x && a.y === b.y && a.z === b.z);
  43594. }
  43595. },{"../core/component":103}],64:[function(_dereq_,module,exports){
  43596. var registerComponent = _dereq_('../core/component').registerComponent;
  43597. var registerShader = _dereq_('../core/shader').registerShader;
  43598. var THREE = _dereq_('../lib/three');
  43599. /**
  43600. * Link component. Connect experiences and traverse between them in VR
  43601. *
  43602. * @member {object} hiddenEls - Store the hidden elements during peek mode.
  43603. */
  43604. module.exports.Component = registerComponent('link', {
  43605. schema: {
  43606. backgroundColor: {default: 'red', type: 'color'},
  43607. borderColor: {default: 'white', type: 'color'},
  43608. highlighted: {default: false},
  43609. highlightedColor: {default: '#24CAFF', type: 'color'},
  43610. href: {default: ''},
  43611. image: {type: 'asset'},
  43612. on: {default: 'click'},
  43613. peekMode: {default: false},
  43614. title: {default: ''},
  43615. titleColor: {default: 'white', type: 'color'},
  43616. visualAspectEnabled: {default: false}
  43617. },
  43618. init: function () {
  43619. this.navigate = this.navigate.bind(this);
  43620. this.previousQuaternion = undefined;
  43621. this.quaternionClone = new THREE.Quaternion();
  43622. // Store hidden elements during peek mode so we can show them again later.
  43623. this.hiddenEls = [];
  43624. },
  43625. update: function (oldData) {
  43626. var data = this.data;
  43627. var el = this.el;
  43628. var backgroundColor;
  43629. var strokeColor;
  43630. if (!data.visualAspectEnabled) { return; }
  43631. this.initVisualAspect();
  43632. backgroundColor = data.highlighted ? data.highlightedColor : data.backgroundColor;
  43633. strokeColor = data.highlighted ? data.highlightedColor : data.borderColor;
  43634. el.setAttribute('material', 'backgroundColor', backgroundColor);
  43635. el.setAttribute('material', 'strokeColor', strokeColor);
  43636. if (data.on !== oldData.on) { this.updateEventListener(); }
  43637. if (oldData.peekMode !== undefined &&
  43638. data.peekMode !== oldData.peekMode) { this.updatePeekMode(); }
  43639. if (!data.image || oldData.image === data.image) { return; }
  43640. el.setAttribute('material', 'pano',
  43641. typeof data.image === 'string' ? data.image : data.image.src);
  43642. },
  43643. /*
  43644. * Toggle all elements and full 360 preview of the linked page.
  43645. */
  43646. updatePeekMode: function () {
  43647. var el = this.el;
  43648. var sphereEl = this.sphereEl;
  43649. if (this.data.peekMode) {
  43650. this.hideAll();
  43651. el.getObject3D('mesh').visible = false;
  43652. sphereEl.setAttribute('visible', true);
  43653. } else {
  43654. this.showAll();
  43655. el.getObject3D('mesh').visible = true;
  43656. sphereEl.setAttribute('visible', false);
  43657. }
  43658. },
  43659. play: function () {
  43660. this.updateEventListener();
  43661. },
  43662. pause: function () {
  43663. this.removeEventListener();
  43664. },
  43665. updateEventListener: function () {
  43666. var el = this.el;
  43667. if (!el.isPlaying) { return; }
  43668. this.removeEventListener();
  43669. el.addEventListener(this.data.on, this.navigate);
  43670. },
  43671. removeEventListener: function () {
  43672. var on = this.data.on;
  43673. if (!on) { return; }
  43674. this.el.removeEventListener(on, this.navigate);
  43675. },
  43676. initVisualAspect: function () {
  43677. var el = this.el;
  43678. var semiSphereEl;
  43679. var sphereEl;
  43680. var textEl;
  43681. if (!this.data.visualAspectEnabled || this.visualAspectInitialized) { return; }
  43682. textEl = this.textEl = this.textEl || document.createElement('a-entity');
  43683. sphereEl = this.sphereEl = this.sphereEl || document.createElement('a-entity');
  43684. semiSphereEl = this.semiSphereEl = this.semiSphereEl || document.createElement('a-entity');
  43685. // Set portal.
  43686. el.setAttribute('geometry', {primitive: 'circle', radius: 1.0, segments: 64});
  43687. el.setAttribute('material', {shader: 'portal', pano: this.data.image, side: 'double'});
  43688. // Set text that displays the link title and URL.
  43689. textEl.setAttribute('text', {
  43690. color: this.data.titleColor,
  43691. align: 'center',
  43692. font: 'kelsonsans',
  43693. value: this.data.title || this.data.href,
  43694. width: 4
  43695. });
  43696. textEl.setAttribute('position', '0 1.5 0');
  43697. el.appendChild(textEl);
  43698. // Set sphere rendered when camera is close to portal to allow user to peek inside.
  43699. semiSphereEl.setAttribute('geometry', {
  43700. primitive: 'sphere',
  43701. radius: 1.0,
  43702. phiStart: 0,
  43703. segmentsWidth: 64,
  43704. segmentsHeight: 64,
  43705. phiLength: 180,
  43706. thetaStart: 0,
  43707. thetaLength: 360
  43708. });
  43709. semiSphereEl.setAttribute('material', {
  43710. shader: 'portal',
  43711. borderEnabled: 0.0,
  43712. pano: this.data.image,
  43713. side: 'back'
  43714. });
  43715. semiSphereEl.setAttribute('rotation', '0 180 0');
  43716. semiSphereEl.setAttribute('position', '0 0 0');
  43717. semiSphereEl.setAttribute('visible', false);
  43718. el.appendChild(semiSphereEl);
  43719. // Set sphere rendered when camera is close to portal to allow user to peek inside.
  43720. sphereEl.setAttribute('geometry', {
  43721. primitive: 'sphere',
  43722. radius: 10,
  43723. segmentsWidth: 64,
  43724. segmentsHeight: 64
  43725. });
  43726. sphereEl.setAttribute('material', {
  43727. shader: 'portal',
  43728. borderEnabled: 0.0,
  43729. pano: this.data.image,
  43730. side: 'back'
  43731. });
  43732. sphereEl.setAttribute('visible', false);
  43733. el.appendChild(sphereEl);
  43734. this.visualAspectInitialized = true;
  43735. },
  43736. navigate: function () {
  43737. window.location = this.data.href;
  43738. },
  43739. /**
  43740. * 1. Swap plane that represents portal with sphere with a hole when the camera is close
  43741. * so user can peek inside portal. Sphere is rendered on oposite side of portal
  43742. * from where user enters.
  43743. * 2. Place the url/title above or inside portal depending on distance to camera.
  43744. * 3. Face portal to camera when far away from user.
  43745. */
  43746. tick: (function () {
  43747. var cameraWorldPosition = new THREE.Vector3();
  43748. var elWorldPosition = new THREE.Vector3();
  43749. var quaternion = new THREE.Quaternion();
  43750. var scale = new THREE.Vector3();
  43751. return function () {
  43752. var el = this.el;
  43753. var object3D = el.object3D;
  43754. var camera = el.sceneEl.camera;
  43755. var cameraPortalOrientation;
  43756. var distance;
  43757. var textEl = this.textEl;
  43758. if (!this.data.visualAspectEnabled) { return; }
  43759. // Update matrices
  43760. object3D.updateMatrixWorld();
  43761. camera.parent.updateMatrixWorld();
  43762. camera.updateMatrixWorld();
  43763. object3D.matrix.decompose(elWorldPosition, quaternion, scale);
  43764. elWorldPosition.setFromMatrixPosition(object3D.matrixWorld);
  43765. cameraWorldPosition.setFromMatrixPosition(camera.matrixWorld);
  43766. distance = elWorldPosition.distanceTo(cameraWorldPosition);
  43767. if (distance > 20) {
  43768. // Store original orientation to be restored when the portal stops facing the camera.
  43769. if (!this.previousQuaternion) {
  43770. this.quaternionClone.copy(quaternion);
  43771. this.previousQuaternion = this.quaternionClone;
  43772. }
  43773. // If the portal is far away from the user, face portal to camera.
  43774. object3D.lookAt(cameraWorldPosition);
  43775. } else {
  43776. // When portal is close to the user/camera.
  43777. cameraPortalOrientation = this.calculateCameraPortalOrientation();
  43778. // If user gets very close to portal, replace with holed sphere they can peek in.
  43779. if (distance < 0.5) {
  43780. // Configure text size and sphere orientation depending side user approaches portal.
  43781. if (this.semiSphereEl.getAttribute('visible') === true) { return; }
  43782. textEl.setAttribute('text', 'width', 1.5);
  43783. if (cameraPortalOrientation <= 0.0) {
  43784. textEl.setAttribute('position', '0 0 0.75');
  43785. textEl.setAttribute('rotation', '0 180 0');
  43786. this.semiSphereEl.setAttribute('rotation', '0 0 0');
  43787. } else {
  43788. textEl.setAttribute('position', '0 0 -0.75');
  43789. textEl.setAttribute('rotation', '0 0 0');
  43790. this.semiSphereEl.setAttribute('rotation', '0 180 0');
  43791. }
  43792. el.getObject3D('mesh').visible = false;
  43793. this.semiSphereEl.setAttribute('visible', true);
  43794. this.peekCameraPortalOrientation = cameraPortalOrientation;
  43795. } else {
  43796. // Calculate wich side the camera is approaching the camera (back / front).
  43797. // Adjust text orientation based on camera position.
  43798. if (cameraPortalOrientation <= 0.0) {
  43799. textEl.setAttribute('rotation', '0 180 0');
  43800. } else {
  43801. textEl.setAttribute('rotation', '0 0 0');
  43802. }
  43803. textEl.setAttribute('text', 'width', 5);
  43804. textEl.setAttribute('position', '0 1.5 0');
  43805. el.getObject3D('mesh').visible = true;
  43806. this.semiSphereEl.setAttribute('visible', false);
  43807. this.peekCameraPortalOrientation = undefined;
  43808. }
  43809. if (this.previousQuaternion) {
  43810. object3D.quaternion.copy(this.previousQuaternion);
  43811. this.previousQuaternion = undefined;
  43812. }
  43813. }
  43814. };
  43815. })(),
  43816. hideAll: function () {
  43817. var el = this.el;
  43818. var hiddenEls = this.hiddenEls;
  43819. var self = this;
  43820. if (hiddenEls.length > 0) { return; }
  43821. el.sceneEl.object3D.traverse(function (object) {
  43822. if (object && object.el && object.el.hasAttribute('link-controls')) { return; }
  43823. if (!object.el || object === el.sceneEl.object3D || object.el === el ||
  43824. object.el === self.sphereEl || object.el === el.sceneEl.cameraEl ||
  43825. object.el.getAttribute('visible') === false || object.el === self.textEl ||
  43826. object.el === self.semiSphereEl) {
  43827. return;
  43828. }
  43829. object.el.setAttribute('visible', false);
  43830. hiddenEls.push(object.el);
  43831. });
  43832. },
  43833. showAll: function () {
  43834. this.hiddenEls.forEach(function (el) { el.setAttribute('visible', true); });
  43835. this.hiddenEls = [];
  43836. },
  43837. /**
  43838. * Calculate whether the camera faces the front or back face of the portal.
  43839. * @returns {number} > 0 if camera faces front of portal, < 0 if it faces back of portal.
  43840. */
  43841. calculateCameraPortalOrientation: (function () {
  43842. var mat4 = new THREE.Matrix4();
  43843. var cameraPosition = new THREE.Vector3();
  43844. var portalNormal = new THREE.Vector3(0, 0, 1);
  43845. var portalPosition = new THREE.Vector3(0, 0, 0);
  43846. return function () {
  43847. var el = this.el;
  43848. var camera = el.sceneEl.camera;
  43849. // Reset tmp variables.
  43850. cameraPosition.set(0, 0, 0);
  43851. portalNormal.set(0, 0, 1);
  43852. portalPosition.set(0, 0, 0);
  43853. // Apply portal orientation to the normal.
  43854. el.object3D.matrixWorld.extractRotation(mat4);
  43855. portalNormal.applyMatrix4(mat4);
  43856. // Calculate portal world position.
  43857. el.object3D.updateMatrixWorld();
  43858. el.object3D.localToWorld(portalPosition);
  43859. // Calculate camera world position.
  43860. camera.parent.parent.updateMatrixWorld();
  43861. camera.parent.updateMatrixWorld();
  43862. camera.updateMatrixWorld();
  43863. camera.localToWorld(cameraPosition);
  43864. // Calculate vector from portal to camera.
  43865. // (portal) -------> (camera)
  43866. cameraPosition.sub(portalPosition).normalize();
  43867. portalNormal.normalize();
  43868. // Side where camera approaches portal is given by sign of dot product of portal normal
  43869. // and portal to camera vectors.
  43870. return Math.sign(portalNormal.dot(cameraPosition));
  43871. };
  43872. })(),
  43873. remove: function () {
  43874. this.removeEventListener();
  43875. }
  43876. });
  43877. /* eslint-disable */
  43878. registerShader('portal', {
  43879. schema: {
  43880. borderEnabled: {default: 1.0, type: 'int', is: 'uniform'},
  43881. backgroundColor: {default: 'red', type: 'color', is: 'uniform'},
  43882. pano: {type: 'map', is: 'uniform'},
  43883. strokeColor: {default: 'white', type: 'color', is: 'uniform'}
  43884. },
  43885. vertexShader: [
  43886. 'vec3 portalPosition;',
  43887. 'varying vec3 vWorldPosition;',
  43888. 'varying float vDistanceToCenter;',
  43889. 'varying float vDistance;',
  43890. 'void main() {',
  43891. 'vDistanceToCenter = clamp(length(position - vec3(0.0, 0.0, 0.0)), 0.0, 1.0);',
  43892. 'portalPosition = (modelMatrix * vec4(0.0, 0.0, 0.0, 1.0)).xyz;',
  43893. 'vDistance = length(portalPosition - cameraPosition);',
  43894. 'vWorldPosition = (modelMatrix * vec4(position, 1.0)).xyz;',
  43895. 'gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);',
  43896. '}'
  43897. ].join('\n'),
  43898. fragmentShader: [
  43899. '#define RECIPROCAL_PI2 0.15915494',
  43900. 'uniform sampler2D pano;',
  43901. 'uniform vec3 strokeColor;',
  43902. 'uniform vec3 backgroundColor;',
  43903. 'uniform float borderEnabled;',
  43904. 'varying float vDistanceToCenter;',
  43905. 'varying float vDistance;',
  43906. 'varying vec3 vWorldPosition;',
  43907. 'void main() {',
  43908. 'vec3 direction = normalize(vWorldPosition - cameraPosition);',
  43909. 'vec2 sampleUV;',
  43910. 'float borderThickness = clamp(exp(-vDistance / 50.0), 0.6, 0.95);',
  43911. 'sampleUV.y = saturate(direction.y * 0.5 + 0.5);',
  43912. 'sampleUV.x = atan(direction.z, -direction.x) * -RECIPROCAL_PI2 + 0.5;',
  43913. 'if (vDistanceToCenter > borderThickness && borderEnabled == 1.0) {',
  43914. 'gl_FragColor = vec4(strokeColor, 1.0);',
  43915. '} else {',
  43916. 'gl_FragColor = mix(texture2D(pano, sampleUV), vec4(backgroundColor, 1.0), clamp(pow((vDistance / 15.0), 2.0), 0.0, 1.0));',
  43917. '}',
  43918. '}'
  43919. ].join('\n')
  43920. });
  43921. /* eslint-enable */
  43922. },{"../core/component":103,"../core/shader":113,"../lib/three":151}],65:[function(_dereq_,module,exports){
  43923. var registerComponent = _dereq_('../core/component').registerComponent;
  43924. var THREE = _dereq_('../lib/three');
  43925. var utils = _dereq_('../utils/');
  43926. var bind = utils.bind;
  43927. var PolyfillControls = _dereq_('../utils').device.PolyfillControls;
  43928. // To avoid recalculation at every mouse movement tick
  43929. var PI_2 = Math.PI / 2;
  43930. /**
  43931. * look-controls. Update entity pose, factoring mouse, touch, and WebVR API data.
  43932. */
  43933. module.exports.Component = registerComponent('look-controls', {
  43934. dependencies: ['position', 'rotation'],
  43935. schema: {
  43936. enabled: {default: true},
  43937. hmdEnabled: {default: true},
  43938. pointerLockEnabled: {default: false},
  43939. reverseMouseDrag: {default: false},
  43940. reverseTouchDrag: {default: false},
  43941. touchEnabled: {default: true}
  43942. },
  43943. init: function () {
  43944. this.previousHMDPosition = new THREE.Vector3();
  43945. this.hmdQuaternion = new THREE.Quaternion();
  43946. this.hmdEuler = new THREE.Euler();
  43947. this.position = new THREE.Vector3();
  43948. // To save / restore camera pose
  43949. this.savedRotation = new THREE.Vector3();
  43950. this.savedPosition = new THREE.Vector3();
  43951. this.polyfillObject = new THREE.Object3D();
  43952. this.polyfillControls = new PolyfillControls(this.polyfillObject);
  43953. this.rotation = {};
  43954. this.deltaRotation = {};
  43955. this.savedPose = null;
  43956. this.pointerLocked = false;
  43957. this.setupMouseControls();
  43958. this.bindMethods();
  43959. this.el.object3D.matrixAutoUpdate = false;
  43960. this.el.object3D.updateMatrix();
  43961. this.savedPose = {
  43962. position: new THREE.Vector3(),
  43963. rotation: new THREE.Euler()
  43964. };
  43965. // Call enter VR handler if the scene has entered VR before the event listeners attached.
  43966. if (this.el.sceneEl.is('vr-mode')) { this.onEnterVR(); }
  43967. },
  43968. update: function (oldData) {
  43969. var data = this.data;
  43970. // Disable grab cursor classes if no longer enabled.
  43971. if (data.enabled !== oldData.enabled) {
  43972. this.updateGrabCursor(data.enabled);
  43973. }
  43974. // Reset pitch and yaw if disabling HMD.
  43975. if (oldData && !data.hmdEnabled && !oldData.hmdEnabled) {
  43976. this.pitchObject.rotation.set(0, 0, 0);
  43977. this.yawObject.rotation.set(0, 0, 0);
  43978. }
  43979. if (oldData && !data.pointerLockEnabled !== oldData.pointerLockEnabled) {
  43980. this.removeEventListeners();
  43981. this.addEventListeners();
  43982. if (this.pointerLocked) { this.exitPointerLock(); }
  43983. }
  43984. },
  43985. tick: function (t) {
  43986. var data = this.data;
  43987. if (!data.enabled) { return; }
  43988. this.updateOrientation();
  43989. },
  43990. play: function () {
  43991. this.addEventListeners();
  43992. },
  43993. pause: function () {
  43994. this.removeEventListeners();
  43995. if (this.pointerLocked) { this.exitPointerLock(); }
  43996. },
  43997. remove: function () {
  43998. this.removeEventListeners();
  43999. if (this.pointerLocked) { this.exitPointerLock(); }
  44000. },
  44001. bindMethods: function () {
  44002. this.onMouseDown = bind(this.onMouseDown, this);
  44003. this.onMouseMove = bind(this.onMouseMove, this);
  44004. this.onMouseUp = bind(this.onMouseUp, this);
  44005. this.onTouchStart = bind(this.onTouchStart, this);
  44006. this.onTouchMove = bind(this.onTouchMove, this);
  44007. this.onTouchEnd = bind(this.onTouchEnd, this);
  44008. this.onEnterVR = bind(this.onEnterVR, this);
  44009. this.onExitVR = bind(this.onExitVR, this);
  44010. this.onPointerLockChange = bind(this.onPointerLockChange, this);
  44011. this.onPointerLockError = bind(this.onPointerLockError, this);
  44012. },
  44013. /**
  44014. * Set up states and Object3Ds needed to store rotation data.
  44015. */
  44016. setupMouseControls: function () {
  44017. this.mouseDown = false;
  44018. this.pitchObject = new THREE.Object3D();
  44019. this.yawObject = new THREE.Object3D();
  44020. this.yawObject.position.y = 10;
  44021. this.yawObject.add(this.pitchObject);
  44022. },
  44023. /**
  44024. * Add mouse and touch event listeners to canvas.
  44025. */
  44026. addEventListeners: function () {
  44027. var sceneEl = this.el.sceneEl;
  44028. var canvasEl = sceneEl.canvas;
  44029. // Wait for canvas to load.
  44030. if (!canvasEl) {
  44031. sceneEl.addEventListener('render-target-loaded', bind(this.addEventListeners, this));
  44032. return;
  44033. }
  44034. // Mouse events.
  44035. canvasEl.addEventListener('mousedown', this.onMouseDown, false);
  44036. window.addEventListener('mousemove', this.onMouseMove, false);
  44037. window.addEventListener('mouseup', this.onMouseUp, false);
  44038. // Touch events.
  44039. canvasEl.addEventListener('touchstart', this.onTouchStart);
  44040. window.addEventListener('touchmove', this.onTouchMove);
  44041. window.addEventListener('touchend', this.onTouchEnd);
  44042. // sceneEl events.
  44043. sceneEl.addEventListener('enter-vr', this.onEnterVR);
  44044. sceneEl.addEventListener('exit-vr', this.onExitVR);
  44045. // Pointer Lock events.
  44046. if (this.data.pointerLockEnabled) {
  44047. document.addEventListener('pointerlockchange', this.onPointerLockChange, false);
  44048. document.addEventListener('mozpointerlockchange', this.onPointerLockChange, false);
  44049. document.addEventListener('pointerlockerror', this.onPointerLockError, false);
  44050. }
  44051. },
  44052. /**
  44053. * Remove mouse and touch event listeners from canvas.
  44054. */
  44055. removeEventListeners: function () {
  44056. var sceneEl = this.el.sceneEl;
  44057. var canvasEl = sceneEl && sceneEl.canvas;
  44058. if (!canvasEl) { return; }
  44059. // Mouse events.
  44060. canvasEl.removeEventListener('mousedown', this.onMouseDown);
  44061. window.removeEventListener('mousemove', this.onMouseMove);
  44062. window.removeEventListener('mouseup', this.onMouseUp);
  44063. // Touch events.
  44064. canvasEl.removeEventListener('touchstart', this.onTouchStart);
  44065. window.removeEventListener('touchmove', this.onTouchMove);
  44066. window.removeEventListener('touchend', this.onTouchEnd);
  44067. // sceneEl events.
  44068. sceneEl.removeEventListener('enter-vr', this.onEnterVR);
  44069. sceneEl.removeEventListener('exit-vr', this.onExitVR);
  44070. // Pointer Lock events.
  44071. document.removeEventListener('pointerlockchange', this.onPointerLockChange, false);
  44072. document.removeEventListener('mozpointerlockchange', this.onPointerLockChange, false);
  44073. document.removeEventListener('pointerlockerror', this.onPointerLockError, false);
  44074. },
  44075. /**
  44076. * Update orientation for mobile, mouse drag, and headset.
  44077. * Mouse-drag only enabled if HMD is not active.
  44078. */
  44079. updateOrientation: (function () {
  44080. var poseMatrix = new THREE.Matrix4();
  44081. return function () {
  44082. var hmdEuler = this.hmdEuler;
  44083. var object3D = this.el.object3D;
  44084. var pitchObject = this.pitchObject;
  44085. var yawObject = this.yawObject;
  44086. var pose;
  44087. var sceneEl = this.el.sceneEl;
  44088. // WebXR API updates applies headset pose to the object3D matrixWorld internally.
  44089. // Reflect values back on position, rotation, scale so setAttribute returns expected values.
  44090. if (sceneEl.is('vr-mode') && sceneEl.hasWebXR) {
  44091. pose = sceneEl.renderer.vr.getCameraPose();
  44092. if (pose) {
  44093. poseMatrix.elements = pose.poseModelMatrix;
  44094. poseMatrix.decompose(object3D.position, object3D.rotation, object3D.scale);
  44095. }
  44096. } else {
  44097. object3D.updateMatrix();
  44098. }
  44099. // In VR mode, THREE is in charge of updating the camera rotation.
  44100. if (sceneEl.is('vr-mode') && sceneEl.checkHeadsetConnected()) { return; }
  44101. // Calculate polyfilled HMD quaternion.
  44102. this.polyfillControls.update();
  44103. hmdEuler.setFromQuaternion(this.polyfillObject.quaternion, 'YXZ');
  44104. // On mobile, do camera rotation with touch events and sensors.
  44105. object3D.rotation.x = hmdEuler.x + pitchObject.rotation.x;
  44106. object3D.rotation.y = hmdEuler.y + yawObject.rotation.y;
  44107. };
  44108. })(),
  44109. /**
  44110. * Translate mouse drag into rotation.
  44111. *
  44112. * Dragging up and down rotates the camera around the X-axis (yaw).
  44113. * Dragging left and right rotates the camera around the Y-axis (pitch).
  44114. */
  44115. onMouseMove: function (event) {
  44116. var direction;
  44117. var movementX;
  44118. var movementY;
  44119. var pitchObject = this.pitchObject;
  44120. var previousMouseEvent = this.previousMouseEvent;
  44121. var yawObject = this.yawObject;
  44122. // Not dragging or not enabled.
  44123. if (!this.data.enabled || (!this.mouseDown && !this.pointerLocked)) { return; }
  44124. // Calculate delta.
  44125. if (this.pointerLocked) {
  44126. movementX = event.movementX || event.mozMovementX || 0;
  44127. movementY = event.movementY || event.mozMovementY || 0;
  44128. } else {
  44129. movementX = event.screenX - previousMouseEvent.screenX;
  44130. movementY = event.screenY - previousMouseEvent.screenY;
  44131. }
  44132. this.previousMouseEvent = event;
  44133. // Calculate rotation.
  44134. direction = this.data.reverseMouseDrag ? 1 : -1;
  44135. yawObject.rotation.y += movementX * 0.002 * direction;
  44136. pitchObject.rotation.x += movementY * 0.002 * direction;
  44137. pitchObject.rotation.x = Math.max(-PI_2, Math.min(PI_2, pitchObject.rotation.x));
  44138. },
  44139. /**
  44140. * Register mouse down to detect mouse drag.
  44141. */
  44142. onMouseDown: function (evt) {
  44143. if (!this.data.enabled) { return; }
  44144. // Handle only primary button.
  44145. if (evt.button !== 0) { return; }
  44146. var sceneEl = this.el.sceneEl;
  44147. var canvasEl = sceneEl && sceneEl.canvas;
  44148. this.mouseDown = true;
  44149. this.previousMouseEvent = evt;
  44150. this.showGrabbingCursor();
  44151. if (this.data.pointerLockEnabled && !this.pointerLocked) {
  44152. if (canvasEl.requestPointerLock) {
  44153. canvasEl.requestPointerLock();
  44154. } else if (canvasEl.mozRequestPointerLock) {
  44155. canvasEl.mozRequestPointerLock();
  44156. }
  44157. }
  44158. },
  44159. /**
  44160. * Shows grabbing cursor on scene
  44161. */
  44162. showGrabbingCursor: function () {
  44163. this.el.sceneEl.canvas.style.cursor = 'grabbing';
  44164. },
  44165. /**
  44166. * Hides grabbing cursor on scene
  44167. */
  44168. hideGrabbingCursor: function () {
  44169. this.el.sceneEl.canvas.style.cursor = '';
  44170. },
  44171. /**
  44172. * Register mouse up to detect release of mouse drag.
  44173. */
  44174. onMouseUp: function () {
  44175. this.mouseDown = false;
  44176. this.hideGrabbingCursor();
  44177. },
  44178. /**
  44179. * Register touch down to detect touch drag.
  44180. */
  44181. onTouchStart: function (evt) {
  44182. if (evt.touches.length !== 1 || !this.data.touchEnabled) { return; }
  44183. this.touchStart = {
  44184. x: evt.touches[0].pageX,
  44185. y: evt.touches[0].pageY
  44186. };
  44187. this.touchStarted = true;
  44188. },
  44189. /**
  44190. * Translate touch move to Y-axis rotation.
  44191. */
  44192. onTouchMove: function (evt) {
  44193. var direction;
  44194. var canvas = this.el.sceneEl.canvas;
  44195. var deltaY;
  44196. var yawObject = this.yawObject;
  44197. if (!this.touchStarted || !this.data.touchEnabled) { return; }
  44198. deltaY = 2 * Math.PI * (evt.touches[0].pageX - this.touchStart.x) / canvas.clientWidth;
  44199. direction = this.data.reverseTouchDrag ? 1 : -1;
  44200. // Limit touch orientaion to to yaw (y axis).
  44201. yawObject.rotation.y -= deltaY * 0.5 * direction;
  44202. this.touchStart = {
  44203. x: evt.touches[0].pageX,
  44204. y: evt.touches[0].pageY
  44205. };
  44206. },
  44207. /**
  44208. * Register touch end to detect release of touch drag.
  44209. */
  44210. onTouchEnd: function () {
  44211. this.touchStarted = false;
  44212. },
  44213. /**
  44214. * Save pose.
  44215. */
  44216. onEnterVR: function () {
  44217. if (!this.el.sceneEl.checkHeadsetConnected()) { return; }
  44218. this.saveCameraPose();
  44219. this.el.object3D.position.set(0, 0, 0);
  44220. this.el.object3D.updateMatrix();
  44221. },
  44222. /**
  44223. * Restore the pose.
  44224. */
  44225. onExitVR: function () {
  44226. if (!this.el.sceneEl.checkHeadsetConnected()) { return; }
  44227. this.restoreCameraPose();
  44228. this.previousHMDPosition.set(0, 0, 0);
  44229. },
  44230. /**
  44231. * Update Pointer Lock state.
  44232. */
  44233. onPointerLockChange: function () {
  44234. this.pointerLocked = !!(document.pointerLockElement || document.mozPointerLockElement);
  44235. },
  44236. /**
  44237. * Recover from Pointer Lock error.
  44238. */
  44239. onPointerLockError: function () {
  44240. this.pointerLocked = false;
  44241. },
  44242. // Exits pointer-locked mode.
  44243. exitPointerLock: function () {
  44244. document.exitPointerLock();
  44245. this.pointerLocked = false;
  44246. },
  44247. /**
  44248. * Toggle the feature of showing/hiding the grab cursor.
  44249. */
  44250. updateGrabCursor: function (enabled) {
  44251. var sceneEl = this.el.sceneEl;
  44252. function enableGrabCursor () { sceneEl.canvas.classList.add('a-grab-cursor'); }
  44253. function disableGrabCursor () { sceneEl.canvas.classList.remove('a-grab-cursor'); }
  44254. if (!sceneEl.canvas) {
  44255. if (enabled) {
  44256. sceneEl.addEventListener('render-target-loaded', enableGrabCursor);
  44257. } else {
  44258. sceneEl.addEventListener('render-target-loaded', disableGrabCursor);
  44259. }
  44260. return;
  44261. }
  44262. if (enabled) {
  44263. enableGrabCursor();
  44264. return;
  44265. }
  44266. disableGrabCursor();
  44267. },
  44268. /**
  44269. * Save camera pose before entering VR to restore later if exiting.
  44270. */
  44271. saveCameraPose: function () {
  44272. var el = this.el;
  44273. this.savedPose.position.copy(el.object3D.position);
  44274. this.savedPose.rotation.copy(el.object3D.rotation);
  44275. this.hasSavedPose = true;
  44276. },
  44277. /**
  44278. * Reset camera pose to before entering VR.
  44279. */
  44280. restoreCameraPose: function () {
  44281. var el = this.el;
  44282. var savedPose = this.savedPose;
  44283. if (!this.hasSavedPose) { return; }
  44284. // Reset camera orientation.
  44285. el.object3D.position.copy(savedPose.position);
  44286. el.object3D.rotation.copy(savedPose.rotation);
  44287. this.hasSavedPose = false;
  44288. }
  44289. });
  44290. },{"../core/component":103,"../lib/three":151,"../utils":176,"../utils/":176}],66:[function(_dereq_,module,exports){
  44291. /* global Promise */
  44292. var utils = _dereq_('../utils/');
  44293. var component = _dereq_('../core/component');
  44294. var THREE = _dereq_('../lib/three');
  44295. var shader = _dereq_('../core/shader');
  44296. var error = utils.debug('components:material:error');
  44297. var registerComponent = component.registerComponent;
  44298. var shaders = shader.shaders;
  44299. var shaderNames = shader.shaderNames;
  44300. /**
  44301. * Material component.
  44302. *
  44303. * @member {object} shader - Determines how material is shaded. Defaults to `standard`,
  44304. * three.js's implementation of PBR. Another standard shading model is `flat` which
  44305. * uses MeshBasicMaterial.
  44306. */
  44307. module.exports.Component = registerComponent('material', {
  44308. schema: {
  44309. alphaTest: {default: 0.0, min: 0.0, max: 1.0},
  44310. depthTest: {default: true},
  44311. depthWrite: {default: true},
  44312. flatShading: {default: false},
  44313. npot: {default: false},
  44314. offset: {type: 'vec2', default: {x: 0, y: 0}},
  44315. opacity: {default: 1.0, min: 0.0, max: 1.0},
  44316. repeat: {type: 'vec2', default: {x: 1, y: 1}},
  44317. shader: {default: 'standard', oneOf: shaderNames, schemaChange: true},
  44318. side: {default: 'front', oneOf: ['front', 'back', 'double']},
  44319. transparent: {default: false},
  44320. vertexColors: {type: 'string', default: 'none', oneOf: ['face', 'vertex']},
  44321. visible: {default: true},
  44322. blending: {default: 'normal', oneOf: ['none', 'normal', 'additive', 'subtractive', 'multiply']}
  44323. },
  44324. init: function () {
  44325. this.material = null;
  44326. },
  44327. /**
  44328. * Update or create material.
  44329. *
  44330. * @param {object|null} oldData
  44331. */
  44332. update: function (oldData) {
  44333. var data = this.data;
  44334. if (!this.shader || data.shader !== oldData.shader) {
  44335. this.updateShader(data.shader);
  44336. }
  44337. this.shader.update(this.data);
  44338. this.updateMaterial(oldData);
  44339. },
  44340. updateSchema: function (data) {
  44341. var currentShader;
  44342. var newShader;
  44343. var schema;
  44344. var shader;
  44345. newShader = data && data.shader;
  44346. currentShader = this.oldData && this.oldData.shader;
  44347. shader = newShader || currentShader;
  44348. schema = shaders[shader] && shaders[shader].schema;
  44349. if (!schema) { error('Unknown shader schema ' + shader); }
  44350. if (currentShader && newShader === currentShader) { return; }
  44351. this.extendSchema(schema);
  44352. this.updateBehavior();
  44353. },
  44354. updateBehavior: function () {
  44355. var key;
  44356. var sceneEl = this.el.sceneEl;
  44357. var schema = this.schema;
  44358. var self = this;
  44359. var tickProperties;
  44360. function tickTime (time, delta) {
  44361. var key;
  44362. for (key in tickProperties) {
  44363. tickProperties[key] = time;
  44364. }
  44365. self.shader.update(tickProperties);
  44366. }
  44367. this.tick = undefined;
  44368. tickProperties = {};
  44369. for (key in schema) {
  44370. if (schema[key].type === 'time') {
  44371. this.tick = tickTime;
  44372. tickProperties[key] = true;
  44373. }
  44374. }
  44375. if (!sceneEl) { return; }
  44376. if (this.tick) {
  44377. sceneEl.addBehavior(this);
  44378. } else {
  44379. sceneEl.removeBehavior(this);
  44380. }
  44381. },
  44382. updateShader: function (shaderName) {
  44383. var data = this.data;
  44384. var Shader = shaders[shaderName] && shaders[shaderName].Shader;
  44385. var shaderInstance;
  44386. if (!Shader) { throw new Error('Unknown shader ' + shaderName); }
  44387. // Get material from A-Frame shader.
  44388. shaderInstance = this.shader = new Shader();
  44389. shaderInstance.el = this.el;
  44390. shaderInstance.init(data);
  44391. this.setMaterial(shaderInstance.material);
  44392. this.updateSchema(data);
  44393. },
  44394. /**
  44395. * Set and update base material properties.
  44396. * Set `needsUpdate` when needed.
  44397. */
  44398. updateMaterial: function (oldData) {
  44399. var data = this.data;
  44400. var material = this.material;
  44401. var oldDataHasKeys;
  44402. // Base material properties.
  44403. material.alphaTest = data.alphaTest;
  44404. material.depthTest = data.depthTest !== false;
  44405. material.depthWrite = data.depthWrite !== false;
  44406. material.opacity = data.opacity;
  44407. material.flatShading = data.flatShading;
  44408. material.side = parseSide(data.side);
  44409. material.transparent = data.transparent !== false || data.opacity < 1.0;
  44410. material.vertexColors = parseVertexColors(data.vertexColors);
  44411. material.visible = data.visible;
  44412. material.blending = parseBlending(data.blending);
  44413. // Check if material needs update.
  44414. for (oldDataHasKeys in oldData) { break; }
  44415. if (oldDataHasKeys &&
  44416. (oldData.alphaTest !== data.alphaTest ||
  44417. oldData.side !== data.side ||
  44418. oldData.vertexColors !== data.vertexColors)) {
  44419. material.needsUpdate = true;
  44420. }
  44421. },
  44422. /**
  44423. * Remove material on remove (callback).
  44424. * Dispose of it from memory and unsubscribe from scene updates.
  44425. */
  44426. remove: function () {
  44427. var defaultMaterial = new THREE.MeshBasicMaterial();
  44428. var material = this.material;
  44429. var object3D = this.el.getObject3D('mesh');
  44430. if (object3D) { object3D.material = defaultMaterial; }
  44431. disposeMaterial(material, this.system);
  44432. },
  44433. /**
  44434. * (Re)create new material. Has side-effects of setting `this.material` and updating
  44435. * material registration in scene.
  44436. *
  44437. * @param {object} data - Material component data.
  44438. * @param {object} type - Material type to create.
  44439. * @returns {object} Material.
  44440. */
  44441. setMaterial: function (material) {
  44442. var el = this.el;
  44443. var mesh;
  44444. var system = this.system;
  44445. if (this.material) { disposeMaterial(this.material, system); }
  44446. this.material = material;
  44447. system.registerMaterial(material);
  44448. // Set on mesh. If mesh does not exist, wait for it.
  44449. mesh = el.getObject3D('mesh');
  44450. if (mesh) {
  44451. mesh.material = material;
  44452. } else {
  44453. el.addEventListener('object3dset', function waitForMesh (evt) {
  44454. if (evt.detail.type !== 'mesh' || evt.target !== el) { return; }
  44455. el.getObject3D('mesh').material = material;
  44456. el.removeEventListener('object3dset', waitForMesh);
  44457. });
  44458. }
  44459. }
  44460. });
  44461. /**
  44462. * Return a three.js constant determining which material face sides to render
  44463. * based on the side parameter (passed as a component property).
  44464. *
  44465. * @param {string} [side=front] - `front`, `back`, or `double`.
  44466. * @returns {number} THREE.FrontSide, THREE.BackSide, or THREE.DoubleSide.
  44467. */
  44468. function parseSide (side) {
  44469. switch (side) {
  44470. case 'back': {
  44471. return THREE.BackSide;
  44472. }
  44473. case 'double': {
  44474. return THREE.DoubleSide;
  44475. }
  44476. default: {
  44477. // Including case `front`.
  44478. return THREE.FrontSide;
  44479. }
  44480. }
  44481. }
  44482. /**
  44483. * Return a three.js constant determining vertex coloring.
  44484. */
  44485. function parseVertexColors (coloring) {
  44486. switch (coloring) {
  44487. case 'face': {
  44488. return THREE.FaceColors;
  44489. }
  44490. case 'vertex': {
  44491. return THREE.VertexColors;
  44492. }
  44493. default: {
  44494. return THREE.NoColors;
  44495. }
  44496. }
  44497. }
  44498. /**
  44499. * Return a three.js constant determining blending
  44500. *
  44501. * @param {string} [blending=normal]
  44502. * - `none`, additive`, `subtractive`,`multiply` or `normal`.
  44503. * @returns {number}
  44504. */
  44505. function parseBlending (blending) {
  44506. switch (blending) {
  44507. case 'none': {
  44508. return THREE.NoBlending;
  44509. }
  44510. case 'additive': {
  44511. return THREE.AdditiveBlending;
  44512. }
  44513. case 'subtractive': {
  44514. return THREE.SubtractiveBlending;
  44515. }
  44516. case 'multiply': {
  44517. return THREE.MultiplyBlending;
  44518. }
  44519. default: {
  44520. return THREE.NormalBlending;
  44521. }
  44522. }
  44523. }
  44524. /**
  44525. * Dispose of material from memory and unsubscribe material from scene updates like fog.
  44526. */
  44527. function disposeMaterial (material, system) {
  44528. material.dispose();
  44529. system.unregisterMaterial(material);
  44530. }
  44531. },{"../core/component":103,"../core/shader":113,"../lib/three":151,"../utils/":176}],67:[function(_dereq_,module,exports){
  44532. var debug = _dereq_('../utils/debug');
  44533. var registerComponent = _dereq_('../core/component').registerComponent;
  44534. var THREE = _dereq_('../lib/three');
  44535. var warn = debug('components:obj-model:warn');
  44536. module.exports.Component = registerComponent('obj-model', {
  44537. schema: {
  44538. mtl: {type: 'model'},
  44539. obj: {type: 'model'}
  44540. },
  44541. init: function () {
  44542. var self = this;
  44543. this.model = null;
  44544. this.objLoader = new THREE.OBJLoader();
  44545. this.mtlLoader = new THREE.MTLLoader(this.objLoader.manager);
  44546. // Allow cross-origin images to be loaded.
  44547. this.mtlLoader.crossOrigin = '';
  44548. this.el.addEventListener('componentinitialized', function (evt) {
  44549. if (!self.model) { return; }
  44550. if (evt.detail.name !== 'material') { return; }
  44551. self.applyMaterial();
  44552. });
  44553. },
  44554. update: function () {
  44555. var data = this.data;
  44556. if (!data.obj) { return; }
  44557. this.resetMesh();
  44558. this.loadObj(data.obj, data.mtl);
  44559. },
  44560. remove: function () {
  44561. if (!this.model) { return; }
  44562. this.resetMesh();
  44563. },
  44564. resetMesh: function () {
  44565. this.el.removeObject3D('mesh');
  44566. },
  44567. loadObj: function (objUrl, mtlUrl) {
  44568. var self = this;
  44569. var el = this.el;
  44570. var mtlLoader = this.mtlLoader;
  44571. var objLoader = this.objLoader;
  44572. var rendererSystem = this.el.sceneEl.systems.renderer;
  44573. var BASE_PATH = mtlUrl.substr(0, mtlUrl.lastIndexOf('/') + 1);
  44574. if (mtlUrl) {
  44575. // .OBJ with an .MTL.
  44576. if (el.hasAttribute('material')) {
  44577. warn('Material component properties are ignored when a .MTL is provided');
  44578. }
  44579. mtlLoader.setResourcePath(BASE_PATH);
  44580. mtlLoader.load(mtlUrl, function (materials) {
  44581. materials.preload();
  44582. objLoader.setMaterials(materials);
  44583. objLoader.load(objUrl, function (objModel) {
  44584. self.model = objModel;
  44585. self.model.traverse(function (object) {
  44586. if (object.isMesh) {
  44587. var material = object.material;
  44588. if (material.color) rendererSystem.applyColorCorrection(material.color);
  44589. if (material.map) rendererSystem.applyColorCorrection(material.map);
  44590. if (material.emissive) rendererSystem.applyColorCorrection(material.emissive);
  44591. if (material.emissiveMap) rendererSystem.applyColorCorrection(material.emissiveMap);
  44592. }
  44593. });
  44594. el.setObject3D('mesh', objModel);
  44595. el.emit('model-loaded', {format: 'obj', model: objModel});
  44596. });
  44597. });
  44598. return;
  44599. }
  44600. // .OBJ only.
  44601. objLoader.load(objUrl, function loadObjOnly (objModel) {
  44602. self.model = objModel;
  44603. self.applyMaterial();
  44604. el.setObject3D('mesh', objModel);
  44605. el.emit('model-loaded', {format: 'obj', model: objModel});
  44606. });
  44607. },
  44608. /**
  44609. * Apply material from material component recursively.
  44610. */
  44611. applyMaterial: function () {
  44612. var material = this.el.components.material;
  44613. if (!material) { return; }
  44614. this.model.traverse(function (child) {
  44615. if (child instanceof THREE.Mesh) {
  44616. child.material = material.material;
  44617. }
  44618. });
  44619. }
  44620. });
  44621. },{"../core/component":103,"../lib/three":151,"../utils/debug":172}],68:[function(_dereq_,module,exports){
  44622. var registerComponent = _dereq_('../core/component').registerComponent;
  44623. var bind = _dereq_('../utils/bind');
  44624. var trackedControlsUtils = _dereq_('../utils/tracked-controls');
  44625. var checkControllerPresentAndSetup = trackedControlsUtils.checkControllerPresentAndSetup;
  44626. var emitIfAxesChanged = trackedControlsUtils.emitIfAxesChanged;
  44627. var onButtonEvent = trackedControlsUtils.onButtonEvent;
  44628. var GAMEPAD_ID_PREFIX = 'Oculus Go';
  44629. var OCULUS_GO_CONTROLLER_MODEL_URL = 'https://cdn.aframe.io/controllers/oculus/go/oculus-go-controller.gltf';
  44630. /**
  44631. * Oculus Go controls.
  44632. * Interface with Oculus Go controller and map Gamepad events to
  44633. * controller buttons: trackpad, trigger
  44634. * Load a controller model and highlight the pressed buttons.
  44635. */
  44636. module.exports.Component = registerComponent('oculus-go-controls', {
  44637. schema: {
  44638. hand: {default: ''}, // This informs the degenerate arm model.
  44639. buttonColor: {type: 'color', default: '#FFFFFF'},
  44640. buttonTouchedColor: {type: 'color', default: '#BBBBBB'},
  44641. buttonHighlightColor: {type: 'color', default: '#7A7A7A'},
  44642. model: {default: true},
  44643. orientationOffset: {type: 'vec3'},
  44644. armModel: {default: true}
  44645. },
  44646. /**
  44647. * Button IDs:
  44648. * 0 - trackpad
  44649. * 1 - trigger
  44650. */
  44651. mapping: {
  44652. axes: {trackpad: [0, 1]},
  44653. buttons: ['trackpad', 'trigger']
  44654. },
  44655. bindMethods: function () {
  44656. this.onModelLoaded = bind(this.onModelLoaded, this);
  44657. this.onControllersUpdate = bind(this.onControllersUpdate, this);
  44658. this.checkIfControllerPresent = bind(this.checkIfControllerPresent, this);
  44659. this.removeControllersUpdateListener = bind(this.removeControllersUpdateListener, this);
  44660. this.onAxisMoved = bind(this.onAxisMoved, this);
  44661. },
  44662. init: function () {
  44663. var self = this;
  44664. this.onButtonChanged = bind(this.onButtonChanged, this);
  44665. this.onButtonDown = function (evt) { onButtonEvent(evt.detail.id, 'down', self); };
  44666. this.onButtonUp = function (evt) { onButtonEvent(evt.detail.id, 'up', self); };
  44667. this.onButtonTouchStart = function (evt) { onButtonEvent(evt.detail.id, 'touchstart', self); };
  44668. this.onButtonTouchEnd = function (evt) { onButtonEvent(evt.detail.id, 'touchend', self); };
  44669. this.controllerPresent = false;
  44670. this.lastControllerCheck = 0;
  44671. this.rendererSystem = this.el.sceneEl.systems.renderer;
  44672. this.bindMethods();
  44673. },
  44674. addEventListeners: function () {
  44675. var el = this.el;
  44676. el.addEventListener('buttonchanged', this.onButtonChanged);
  44677. el.addEventListener('buttondown', this.onButtonDown);
  44678. el.addEventListener('buttonup', this.onButtonUp);
  44679. el.addEventListener('touchstart', this.onButtonTouchStart);
  44680. el.addEventListener('touchend', this.onButtonTouchEnd);
  44681. el.addEventListener('model-loaded', this.onModelLoaded);
  44682. el.addEventListener('axismove', this.onAxisMoved);
  44683. this.controllerEventsActive = true;
  44684. },
  44685. removeEventListeners: function () {
  44686. var el = this.el;
  44687. el.removeEventListener('buttonchanged', this.onButtonChanged);
  44688. el.removeEventListener('buttondown', this.onButtonDown);
  44689. el.removeEventListener('buttonup', this.onButtonUp);
  44690. el.removeEventListener('touchstart', this.onButtonTouchStart);
  44691. el.removeEventListener('touchend', this.onButtonTouchEnd);
  44692. el.removeEventListener('model-loaded', this.onModelLoaded);
  44693. el.removeEventListener('axismove', this.onAxisMoved);
  44694. this.controllerEventsActive = false;
  44695. },
  44696. checkIfControllerPresent: function () {
  44697. checkControllerPresentAndSetup(this, GAMEPAD_ID_PREFIX,
  44698. this.data.hand ? {hand: this.data.hand} : {});
  44699. },
  44700. play: function () {
  44701. this.checkIfControllerPresent();
  44702. this.addControllersUpdateListener();
  44703. },
  44704. pause: function () {
  44705. this.removeEventListeners();
  44706. this.removeControllersUpdateListener();
  44707. },
  44708. injectTrackedControls: function () {
  44709. var el = this.el;
  44710. var data = this.data;
  44711. el.setAttribute('tracked-controls', {
  44712. armModel: data.armModel,
  44713. idPrefix: GAMEPAD_ID_PREFIX,
  44714. orientationOffset: data.orientationOffset
  44715. });
  44716. if (!this.data.model) { return; }
  44717. this.el.setAttribute('gltf-model', OCULUS_GO_CONTROLLER_MODEL_URL);
  44718. },
  44719. addControllersUpdateListener: function () {
  44720. this.el.sceneEl.addEventListener('controllersupdated', this.onControllersUpdate, false);
  44721. },
  44722. removeControllersUpdateListener: function () {
  44723. this.el.sceneEl.removeEventListener('controllersupdated', this.onControllersUpdate, false);
  44724. },
  44725. onControllersUpdate: function () {
  44726. this.checkIfControllerPresent();
  44727. },
  44728. // No need for onButtonChanged, since Oculus Go controller has no analog buttons.
  44729. onModelLoaded: function (evt) {
  44730. var controllerObject3D = evt.detail.model;
  44731. var buttonMeshes;
  44732. if (!this.data.model) { return; }
  44733. buttonMeshes = this.buttonMeshes = {};
  44734. buttonMeshes.trigger = controllerObject3D.getObjectByName('oculus_go_button_trigger');
  44735. buttonMeshes.trackpad = controllerObject3D.getObjectByName('oculus_go_touchpad');
  44736. },
  44737. onButtonChanged: function (evt) {
  44738. var button = this.mapping.buttons[evt.detail.id];
  44739. if (!button) return;
  44740. // Pass along changed event with button state, using button mapping for convenience.
  44741. this.el.emit(button + 'changed', evt.detail.state);
  44742. },
  44743. onAxisMoved: function (evt) {
  44744. emitIfAxesChanged(this, this.mapping.axes, evt);
  44745. },
  44746. updateModel: function (buttonName, evtName) {
  44747. if (!this.data.model) { return; }
  44748. this.updateButtonModel(buttonName, evtName);
  44749. },
  44750. updateButtonModel: function (buttonName, state) {
  44751. var buttonMeshes = this.buttonMeshes;
  44752. if (!buttonMeshes || !buttonMeshes[buttonName]) { return; }
  44753. var color;
  44754. var button;
  44755. switch (state) {
  44756. case 'down':
  44757. color = this.data.buttonHighlightColor;
  44758. break;
  44759. case 'touchstart':
  44760. color = this.data.buttonTouchedColor;
  44761. break;
  44762. default:
  44763. color = this.data.buttonColor;
  44764. }
  44765. button = buttonMeshes[buttonName];
  44766. button.material.color.set(color);
  44767. this.rendererSystem.applyColorCorrection(button.material.color);
  44768. }
  44769. });
  44770. },{"../core/component":103,"../utils/bind":170,"../utils/tracked-controls":184}],69:[function(_dereq_,module,exports){
  44771. var bind = _dereq_('../utils/bind');
  44772. var registerComponent = _dereq_('../core/component').registerComponent;
  44773. var THREE = _dereq_('../lib/three');
  44774. var trackedControlsUtils = _dereq_('../utils/tracked-controls');
  44775. var checkControllerPresentAndSetup = trackedControlsUtils.checkControllerPresentAndSetup;
  44776. var emitIfAxesChanged = trackedControlsUtils.emitIfAxesChanged;
  44777. var onButtonEvent = trackedControlsUtils.onButtonEvent;
  44778. var TOUCH_CONTROLLER_MODEL_BASE_URL = 'https://cdn.aframe.io/controllers/oculus/oculus-touch-controller-';
  44779. var TOUCH_CONTROLLER_MODEL_URL = {
  44780. left: TOUCH_CONTROLLER_MODEL_BASE_URL + 'left.gltf',
  44781. right: TOUCH_CONTROLLER_MODEL_BASE_URL + 'right.gltf'
  44782. };
  44783. var GAMEPAD_ID_PREFIX = 'Oculus Touch';
  44784. var DEFAULT_MODEL_PIVOT_OFFSET = new THREE.Vector3(0, 0, -0.053);
  44785. var RAY_ORIGIN = {
  44786. left: {origin: {x: 0.008, y: -0.004, z: 0}, direction: {x: 0, y: -0.8, z: -1}},
  44787. right: {origin: {x: -0.008, y: -0.004, z: 0}, direction: {x: 0, y: -0.8, z: -1}}
  44788. };
  44789. /**
  44790. * Oculus Touch controls.
  44791. * Interface with Oculus Touch controllers and map Gamepad events to
  44792. * controller buttons: thumbstick, trigger, grip, xbutton, ybutton, surface
  44793. * Load a controller model and highlight the pressed buttons.
  44794. */
  44795. module.exports.Component = registerComponent('oculus-touch-controls', {
  44796. schema: {
  44797. hand: {default: 'left'},
  44798. buttonColor: {type: 'color', default: '#999'}, // Off-white.
  44799. buttonTouchColor: {type: 'color', default: '#8AB'},
  44800. buttonHighlightColor: {type: 'color', default: '#2DF'}, // Light blue.
  44801. model: {default: true},
  44802. orientationOffset: {type: 'vec3', default: {x: 43, y: 0, z: 0}}
  44803. },
  44804. /**
  44805. * Button IDs:
  44806. * 0 - thumbstick (which has separate axismove / thumbstickmoved events)
  44807. * 1 - trigger (with analog value, which goes up to 1)
  44808. * 2 - grip (with analog value, which goes up to 1)
  44809. * 3 - X (left) or A (right)
  44810. * 4 - Y (left) or B (right)
  44811. * 5 - surface (touch only)
  44812. */
  44813. mapping: {
  44814. left: {
  44815. axes: {thumbstick: [0, 1]},
  44816. buttons: ['thumbstick', 'trigger', 'grip', 'xbutton', 'ybutton', 'surface']
  44817. },
  44818. right: {
  44819. axes: {thumbstick: [0, 1]},
  44820. buttons: ['thumbstick', 'trigger', 'grip', 'abutton', 'bbutton', 'surface']
  44821. }
  44822. },
  44823. bindMethods: function () {
  44824. this.onModelLoaded = bind(this.onModelLoaded, this);
  44825. this.onControllersUpdate = bind(this.onControllersUpdate, this);
  44826. this.checkIfControllerPresent = bind(this.checkIfControllerPresent, this);
  44827. this.onAxisMoved = bind(this.onAxisMoved, this);
  44828. },
  44829. init: function () {
  44830. var self = this;
  44831. this.onButtonChanged = bind(this.onButtonChanged, this);
  44832. this.onButtonDown = function (evt) { onButtonEvent(evt.detail.id, 'down', self, self.data.hand); };
  44833. this.onButtonUp = function (evt) { onButtonEvent(evt.detail.id, 'up', self, self.data.hand); };
  44834. this.onButtonTouchStart = function (evt) { onButtonEvent(evt.detail.id, 'touchstart', self, self.data.hand); };
  44835. this.onButtonTouchEnd = function (evt) { onButtonEvent(evt.detail.id, 'touchend', self, self.data.hand); };
  44836. this.controllerPresent = false;
  44837. this.lastControllerCheck = 0;
  44838. this.previousButtonValues = {};
  44839. this.rendererSystem = this.el.sceneEl.systems.renderer;
  44840. this.bindMethods();
  44841. },
  44842. addEventListeners: function () {
  44843. var el = this.el;
  44844. el.addEventListener('buttonchanged', this.onButtonChanged);
  44845. el.addEventListener('buttondown', this.onButtonDown);
  44846. el.addEventListener('buttonup', this.onButtonUp);
  44847. el.addEventListener('touchstart', this.onButtonTouchStart);
  44848. el.addEventListener('touchend', this.onButtonTouchEnd);
  44849. el.addEventListener('axismove', this.onAxisMoved);
  44850. el.addEventListener('model-loaded', this.onModelLoaded);
  44851. this.controllerEventsActive = true;
  44852. },
  44853. removeEventListeners: function () {
  44854. var el = this.el;
  44855. el.removeEventListener('buttonchanged', this.onButtonChanged);
  44856. el.removeEventListener('buttondown', this.onButtonDown);
  44857. el.removeEventListener('buttonup', this.onButtonUp);
  44858. el.removeEventListener('touchstart', this.onButtonTouchStart);
  44859. el.removeEventListener('touchend', this.onButtonTouchEnd);
  44860. el.removeEventListener('axismove', this.onAxisMoved);
  44861. el.removeEventListener('model-loaded', this.onModelLoaded);
  44862. this.controllerEventsActive = false;
  44863. },
  44864. checkIfControllerPresent: function () {
  44865. checkControllerPresentAndSetup(this, GAMEPAD_ID_PREFIX, {
  44866. hand: this.data.hand
  44867. });
  44868. },
  44869. play: function () {
  44870. this.checkIfControllerPresent();
  44871. this.addControllersUpdateListener();
  44872. },
  44873. pause: function () {
  44874. this.removeEventListeners();
  44875. this.removeControllersUpdateListener();
  44876. },
  44877. loadModel: function () {
  44878. var data = this.data;
  44879. if (!data.model) { return; }
  44880. this.el.setAttribute('gltf-model', 'url(' + TOUCH_CONTROLLER_MODEL_URL[data.hand] + ')');
  44881. },
  44882. injectTrackedControls: function () {
  44883. var data = this.data;
  44884. this.el.setAttribute('tracked-controls', {
  44885. id: data.hand === 'right' ? 'Oculus Touch (Right)' : 'Oculus Touch (Left)',
  44886. controller: 0,
  44887. hand: data.hand,
  44888. orientationOffset: data.orientationOffset
  44889. });
  44890. this.loadModel();
  44891. },
  44892. addControllersUpdateListener: function () {
  44893. this.el.sceneEl.addEventListener('controllersupdated', this.onControllersUpdate, false);
  44894. },
  44895. removeControllersUpdateListener: function () {
  44896. this.el.sceneEl.removeEventListener('controllersupdated', this.onControllersUpdate, false);
  44897. },
  44898. onControllersUpdate: function () {
  44899. // Note that due to gamepadconnected event propagation issues, we don't rely on events.
  44900. this.checkIfControllerPresent();
  44901. },
  44902. onButtonChanged: function (evt) {
  44903. var button = this.mapping[this.data.hand].buttons[evt.detail.id];
  44904. var buttonMeshes = this.buttonMeshes;
  44905. var analogValue;
  44906. if (!button) { return; }
  44907. if (button === 'trigger' || button === 'grip') { analogValue = evt.detail.state.value; }
  44908. // Update trigger and/or grip meshes, if any.
  44909. if (buttonMeshes) {
  44910. if (button === 'trigger' && buttonMeshes.trigger) {
  44911. buttonMeshes.trigger.rotation.x = this.originalXRotationTrigger - analogValue * (Math.PI / 26);
  44912. }
  44913. if (button === 'grip' && buttonMeshes.grip) {
  44914. buttonMeshes.grip.position.x = this.originalXPositionGrip + (this.data.hand === 'left' ? -1 : 1) * analogValue * 0.004;
  44915. }
  44916. }
  44917. // Pass along changed event with button state, using the buttom mapping for convenience.
  44918. this.el.emit(button + 'changed', evt.detail.state);
  44919. },
  44920. onModelLoaded: function (evt) {
  44921. var controllerObject3D = evt.detail.model;
  44922. var buttonMeshes;
  44923. if (!this.data.model) { return; }
  44924. buttonMeshes = this.buttonMeshes = {};
  44925. buttonMeshes.grip = controllerObject3D.getObjectByName('buttonHand');
  44926. this.originalXPositionGrip = buttonMeshes.grip.position.x;
  44927. buttonMeshes.thumbstick = controllerObject3D.getObjectByName('stick');
  44928. buttonMeshes.trigger = controllerObject3D.getObjectByName('buttonTrigger');
  44929. this.originalXRotationTrigger = buttonMeshes.trigger.rotation.x;
  44930. buttonMeshes.xbutton = controllerObject3D.getObjectByName('buttonX');
  44931. buttonMeshes.abutton = controllerObject3D.getObjectByName('buttonA');
  44932. buttonMeshes.ybutton = controllerObject3D.getObjectByName('buttonY');
  44933. buttonMeshes.bbutton = controllerObject3D.getObjectByName('buttonB');
  44934. // Offset pivot point
  44935. controllerObject3D.position.copy(DEFAULT_MODEL_PIVOT_OFFSET);
  44936. this.el.emit('controllermodelready', {
  44937. name: 'oculus-touch-controls',
  44938. model: this.data.model,
  44939. rayOrigin: RAY_ORIGIN[this.data.hand]
  44940. });
  44941. },
  44942. onAxisMoved: function (evt) {
  44943. emitIfAxesChanged(this, this.mapping[this.data.hand].axes, evt);
  44944. },
  44945. updateModel: function (buttonName, evtName) {
  44946. if (!this.data.model) { return; }
  44947. this.updateButtonModel(buttonName, evtName);
  44948. },
  44949. updateButtonModel: function (buttonName, state) {
  44950. var button;
  44951. var color = (state === 'up' || state === 'touchend') ? this.data.buttonColor : state === 'touchstart' ? this.data.buttonTouchColor : this.data.buttonHighlightColor;
  44952. var buttonMeshes = this.buttonMeshes;
  44953. if (!this.data.model) { return; }
  44954. if (buttonMeshes && buttonMeshes[buttonName]) {
  44955. button = buttonMeshes[buttonName];
  44956. button.material.color.set(color);
  44957. this.rendererSystem.applyColorCorrection(button.material.color);
  44958. }
  44959. }
  44960. });
  44961. },{"../core/component":103,"../lib/three":151,"../utils/bind":170,"../utils/tracked-controls":184}],70:[function(_dereq_,module,exports){
  44962. var registerComponent = _dereq_('../core/component').registerComponent;
  44963. module.exports.Component = registerComponent('position', {
  44964. schema: {type: 'vec3'},
  44965. update: function () {
  44966. var object3D = this.el.object3D;
  44967. var data = this.data;
  44968. object3D.position.set(data.x, data.y, data.z);
  44969. },
  44970. remove: function () {
  44971. // Pretty much for mixins.
  44972. this.el.object3D.position.set(0, 0, 0);
  44973. }
  44974. });
  44975. },{"../core/component":103}],71:[function(_dereq_,module,exports){
  44976. /* global MutationObserver */
  44977. var registerComponent = _dereq_('../core/component').registerComponent;
  44978. var THREE = _dereq_('../lib/three');
  44979. var utils = _dereq_('../utils/');
  44980. var warn = utils.debug('components:raycaster:warn');
  44981. // Defines selectors that should be 'safe' for the MutationObserver used to
  44982. // refresh the whitelist. Matches classnames, IDs, and presence of attributes.
  44983. // Selectors for the value of an attribute, like [position=0 2 0], cannot be
  44984. // reliably detected and are therefore disallowed.
  44985. var OBSERVER_SELECTOR_RE = /^[\w\s-.,[\]#]*$/;
  44986. // Configuration for the MutationObserver used to refresh the whitelist.
  44987. // Listens for addition/removal of elements and attributes within the scene.
  44988. var OBSERVER_CONFIG = {
  44989. childList: true,
  44990. attributes: true,
  44991. subtree: true
  44992. };
  44993. var EVENTS = {
  44994. INTERSECT: 'raycaster-intersected',
  44995. INTERSECTION: 'raycaster-intersection',
  44996. INTERSECT_CLEAR: 'raycaster-intersected-cleared',
  44997. INTERSECTION_CLEAR: 'raycaster-intersection-cleared'
  44998. };
  44999. /**
  45000. * Raycaster component.
  45001. *
  45002. * Pass options to three.js Raycaster including which objects to test.
  45003. * Poll for intersections.
  45004. * Emit event on origin entity and on target entity on intersect.
  45005. *
  45006. * @member {array} intersectedEls - List of currently intersected entities.
  45007. * @member {array} objects - Cached list of meshes to intersect.
  45008. * @member {number} prevCheckTime - Previous time intersection was checked. To help interval.
  45009. * @member {object} raycaster - three.js Raycaster.
  45010. */
  45011. module.exports.Component = registerComponent('raycaster', {
  45012. schema: {
  45013. autoRefresh: {default: true},
  45014. direction: {type: 'vec3', default: {x: 0, y: 0, z: -1}},
  45015. enabled: {default: true},
  45016. far: {default: 1000},
  45017. interval: {default: 0},
  45018. near: {default: 0},
  45019. objects: {default: ''},
  45020. origin: {type: 'vec3'},
  45021. showLine: {default: false},
  45022. useWorldCoordinates: {default: false}
  45023. },
  45024. multiple: true,
  45025. init: function () {
  45026. this.clearedIntersectedEls = [];
  45027. this.unitLineEndVec3 = new THREE.Vector3();
  45028. this.intersectedEls = [];
  45029. this.intersections = [];
  45030. this.newIntersectedEls = [];
  45031. this.newIntersections = [];
  45032. this.objects = [];
  45033. this.prevCheckTime = undefined;
  45034. this.prevIntersectedEls = [];
  45035. this.rawIntersections = [];
  45036. this.raycaster = new THREE.Raycaster();
  45037. this.updateOriginDirection();
  45038. this.setDirty = this.setDirty.bind(this);
  45039. this.updateLine = this.updateLine.bind(this);
  45040. this.observer = new MutationObserver(this.setDirty);
  45041. this.dirty = true;
  45042. this.lineEndVec3 = new THREE.Vector3();
  45043. this.otherLineEndVec3 = new THREE.Vector3();
  45044. this.lineData = {end: this.lineEndVec3};
  45045. this.getIntersection = this.getIntersection.bind(this);
  45046. this.intersectedDetail = {el: this.el, getIntersection: this.getIntersection};
  45047. this.intersectedClearedDetail = {el: this.el};
  45048. this.intersectionClearedDetail = {clearedEls: this.clearedIntersectedEls};
  45049. this.intersectionDetail = {};
  45050. },
  45051. /**
  45052. * Create or update raycaster object.
  45053. */
  45054. update: function (oldData) {
  45055. var data = this.data;
  45056. var el = this.el;
  45057. var raycaster = this.raycaster;
  45058. // Set raycaster properties.
  45059. raycaster.far = data.far;
  45060. raycaster.near = data.near;
  45061. // Draw line.
  45062. if (data.showLine &&
  45063. (data.far !== oldData.far || data.origin !== oldData.origin ||
  45064. data.direction !== oldData.direction || !oldData.showLine)) {
  45065. // Calculate unit vector for line direction. Can be multiplied via scalar to performantly
  45066. // adjust line length.
  45067. this.unitLineEndVec3.copy(data.origin).add(data.direction).normalize();
  45068. this.drawLine();
  45069. }
  45070. if (!data.showLine && oldData.showLine) {
  45071. el.removeAttribute('line');
  45072. }
  45073. if (data.objects !== oldData.objects && !OBSERVER_SELECTOR_RE.test(data.objects)) {
  45074. warn('[raycaster] Selector "' + data.objects +
  45075. '" may not update automatically with DOM changes.');
  45076. }
  45077. if (!data.objects) {
  45078. warn('[raycaster] For performance, please define raycaster.objects when using ' +
  45079. 'raycaster or cursor components to whitelist which entities to intersect with. ' +
  45080. 'e.g., raycaster="objects: [data-raycastable]".');
  45081. }
  45082. if (data.autoRefresh !== oldData.autoRefresh && el.isPlaying) {
  45083. data.autoRefresh
  45084. ? this.addEventListeners()
  45085. : this.removeEventListeners();
  45086. }
  45087. if (oldData.enabled && !data.enabled) { this.clearAllIntersections(); }
  45088. this.setDirty();
  45089. },
  45090. play: function () {
  45091. this.addEventListeners();
  45092. },
  45093. pause: function () {
  45094. this.removeEventListeners();
  45095. },
  45096. remove: function () {
  45097. if (this.data.showLine) {
  45098. this.el.removeAttribute('line');
  45099. }
  45100. this.clearAllIntersections();
  45101. },
  45102. addEventListeners: function () {
  45103. if (!this.data.autoRefresh) { return; }
  45104. this.observer.observe(this.el.sceneEl, OBSERVER_CONFIG);
  45105. this.el.sceneEl.addEventListener('object3dset', this.setDirty);
  45106. this.el.sceneEl.addEventListener('object3dremove', this.setDirty);
  45107. },
  45108. removeEventListeners: function () {
  45109. this.observer.disconnect();
  45110. this.el.sceneEl.removeEventListener('object3dset', this.setDirty);
  45111. this.el.sceneEl.removeEventListener('object3dremove', this.setDirty);
  45112. },
  45113. /**
  45114. * Mark the object list as dirty, to be refreshed before next raycast.
  45115. */
  45116. setDirty: function () {
  45117. this.dirty = true;
  45118. },
  45119. /**
  45120. * Update list of objects to test for intersection.
  45121. */
  45122. refreshObjects: function () {
  45123. var data = this.data;
  45124. var els;
  45125. // If objects not defined, intersect with everything.
  45126. els = data.objects
  45127. ? this.el.sceneEl.querySelectorAll(data.objects)
  45128. : this.el.sceneEl.querySelectorAll('*');
  45129. this.objects = this.flattenObject3DMaps(els);
  45130. this.dirty = false;
  45131. },
  45132. /**
  45133. * Check for intersections and cleared intersections on an interval.
  45134. */
  45135. tick: function (time) {
  45136. var data = this.data;
  45137. var prevCheckTime = this.prevCheckTime;
  45138. if (!data.enabled) { return; }
  45139. // Only check for intersection if interval time has passed.
  45140. if (prevCheckTime && (time - prevCheckTime < data.interval)) { return; }
  45141. // Update check time.
  45142. this.prevCheckTime = time;
  45143. this.checkIntersections();
  45144. },
  45145. /**
  45146. * Raycast for intersections and emit events for current and cleared inersections.
  45147. */
  45148. checkIntersections: function () {
  45149. var clearedIntersectedEls = this.clearedIntersectedEls;
  45150. var el = this.el;
  45151. var data = this.data;
  45152. var i;
  45153. var intersectedEls = this.intersectedEls;
  45154. var intersection;
  45155. var intersections = this.intersections;
  45156. var newIntersectedEls = this.newIntersectedEls;
  45157. var newIntersections = this.newIntersections;
  45158. var prevIntersectedEls = this.prevIntersectedEls;
  45159. var rawIntersections = this.rawIntersections;
  45160. // Refresh the object whitelist if needed.
  45161. if (this.dirty) { this.refreshObjects(); }
  45162. // Store old previously intersected entities.
  45163. copyArray(this.prevIntersectedEls, this.intersectedEls);
  45164. // Raycast.
  45165. this.updateOriginDirection();
  45166. rawIntersections.length = 0;
  45167. this.raycaster.intersectObjects(this.objects, true, rawIntersections);
  45168. // Only keep intersections against objects that have a reference to an entity.
  45169. intersections.length = 0;
  45170. intersectedEls.length = 0;
  45171. for (i = 0; i < rawIntersections.length; i++) {
  45172. intersection = rawIntersections[i];
  45173. // Don't intersect with own line.
  45174. if (data.showLine && intersection.object === el.getObject3D('line')) {
  45175. continue;
  45176. }
  45177. if (intersection.object.el) {
  45178. intersections.push(intersection);
  45179. intersectedEls.push(intersection.object.el);
  45180. }
  45181. }
  45182. // Get newly intersected entities.
  45183. newIntersections.length = 0;
  45184. newIntersectedEls.length = 0;
  45185. for (i = 0; i < intersections.length; i++) {
  45186. if (prevIntersectedEls.indexOf(intersections[i].object.el) === -1) {
  45187. newIntersections.push(intersections[i]);
  45188. newIntersectedEls.push(intersections[i].object.el);
  45189. }
  45190. }
  45191. // Emit intersection cleared on both entities per formerly intersected entity.
  45192. clearedIntersectedEls.length = 0;
  45193. for (i = 0; i < prevIntersectedEls.length; i++) {
  45194. if (intersectedEls.indexOf(prevIntersectedEls[i]) !== -1) { continue; }
  45195. prevIntersectedEls[i].emit(EVENTS.INTERSECT_CLEAR,
  45196. this.intersectedClearedDetail);
  45197. clearedIntersectedEls.push(prevIntersectedEls[i]);
  45198. }
  45199. if (clearedIntersectedEls.length) {
  45200. el.emit(EVENTS.INTERSECTION_CLEAR, this.intersectionClearedDetail);
  45201. }
  45202. // Emit intersected on intersected entity per intersected entity.
  45203. for (i = 0; i < newIntersectedEls.length; i++) {
  45204. newIntersectedEls[i].emit(EVENTS.INTERSECT, this.intersectedDetail);
  45205. }
  45206. // Emit all intersections at once on raycasting entity.
  45207. if (newIntersections.length) {
  45208. this.intersectionDetail.els = newIntersectedEls;
  45209. this.intersectionDetail.intersections = newIntersections;
  45210. el.emit(EVENTS.INTERSECTION, this.intersectionDetail);
  45211. }
  45212. // Update line length.
  45213. setTimeout(this.updateLine);
  45214. },
  45215. updateLine: function () {
  45216. var el = this.el;
  45217. var intersections = this.intersections;
  45218. var lineLength;
  45219. if (this.data.showLine) {
  45220. if (intersections.length) {
  45221. if (intersections[0].object.el === el && intersections[1]) {
  45222. lineLength = intersections[1].distance;
  45223. } else {
  45224. lineLength = intersections[0].distance;
  45225. }
  45226. }
  45227. this.drawLine(lineLength);
  45228. }
  45229. },
  45230. /**
  45231. * Return the most recent intersection details for a given entity, if any.
  45232. * @param {AEntity} el
  45233. * @return {Object}
  45234. */
  45235. getIntersection: function (el) {
  45236. var i;
  45237. var intersection;
  45238. for (i = 0; i < this.intersections.length; i++) {
  45239. intersection = this.intersections[i];
  45240. if (intersection.object.el === el) { return intersection; }
  45241. }
  45242. return null;
  45243. },
  45244. /**
  45245. * Update origin and direction of raycaster using entity transforms and supplied origin or
  45246. * direction offsets.
  45247. */
  45248. updateOriginDirection: (function () {
  45249. var direction = new THREE.Vector3();
  45250. var originVec3 = new THREE.Vector3();
  45251. // Closure to make quaternion/vector3 objects private.
  45252. return function updateOriginDirection () {
  45253. var el = this.el;
  45254. var data = this.data;
  45255. if (data.useWorldCoordinates) {
  45256. this.raycaster.set(data.origin, data.direction);
  45257. return;
  45258. }
  45259. // Grab the position and rotation. (As a side effect, this updates el.object3D.matrixWorld.)
  45260. el.object3D.getWorldPosition(originVec3);
  45261. // If non-zero origin, translate the origin into world space.
  45262. if (data.origin.x !== 0 || data.origin.y !== 0 || data.origin.z !== 0) {
  45263. originVec3 = el.object3D.localToWorld(originVec3.copy(data.origin));
  45264. }
  45265. // three.js raycaster direction is relative to 0, 0, 0 NOT the origin / offset we
  45266. // provide. Apply the offset to the direction, then rotation from the object,
  45267. // and normalize.
  45268. direction.copy(data.direction).transformDirection(el.object3D.matrixWorld).normalize();
  45269. // Apply offset and direction, in world coordinates.
  45270. this.raycaster.set(originVec3, direction);
  45271. };
  45272. })(),
  45273. /**
  45274. * Create or update line to give raycaster visual representation.
  45275. * Customize the line through through line component.
  45276. * We draw the line in the raycaster component to customize the line to the
  45277. * raycaster's origin, direction, and far.
  45278. *
  45279. * Unlike the raycaster, we create the line as a child of the object. The line will
  45280. * be affected by the transforms of the objects, so we don't have to calculate transforms
  45281. * like we do with the raycaster.
  45282. *
  45283. * @param {number} length - Length of line. Pass in to shorten the line to the intersection
  45284. * point. If not provided, length will default to the max length, `raycaster.far`.
  45285. */
  45286. drawLine: function (length) {
  45287. var data = this.data;
  45288. var el = this.el;
  45289. var endVec3;
  45290. // Switch each time vector so line update triggered and to avoid unnecessary vector clone.
  45291. endVec3 = this.lineData.end === this.lineEndVec3
  45292. ? this.otherLineEndVec3
  45293. : this.lineEndVec3;
  45294. // Treat Infinity as 1000m for the line.
  45295. if (length === undefined) {
  45296. length = data.far === Infinity ? 1000 : data.far;
  45297. }
  45298. // Update the length of the line if given. `unitLineEndVec3` is the direction
  45299. // given by data.direction, then we apply a scalar to give it a length.
  45300. this.lineData.start = data.origin;
  45301. this.lineData.end = endVec3.copy(this.unitLineEndVec3).multiplyScalar(length);
  45302. el.setAttribute('line', this.lineData);
  45303. },
  45304. /**
  45305. * Return A-Frame attachments of each element's object3D group (e.g., mesh).
  45306. * Children are flattened by one level, removing the THREE.Group wrapper,
  45307. * so that non-recursive raycasting remains useful.
  45308. *
  45309. * Only push children defined as component attachemnts (e.g., setObject3D),
  45310. * NOT actual children in the scene graph hierarchy.
  45311. *
  45312. * @param {Array<Element>} els
  45313. * @return {Array<THREE.Object3D>}
  45314. */
  45315. flattenObject3DMaps: function (els) {
  45316. var key;
  45317. var i;
  45318. var objects = this.objects;
  45319. // Push meshes and other attachments onto list of objects to intersect.
  45320. objects.length = 0;
  45321. for (i = 0; i < els.length; i++) {
  45322. if (els[i].isEntity && els[i].object3D) {
  45323. for (key in els[i].object3DMap) {
  45324. objects.push(els[i].getObject3D(key));
  45325. }
  45326. }
  45327. }
  45328. return objects;
  45329. },
  45330. clearAllIntersections: function () {
  45331. var i;
  45332. for (i = 0; i < this.intersectedEls.length; i++) {
  45333. this.intersectedEls[i].emit(EVENTS.INTERSECT_CLEAR,
  45334. this.intersectedClearedDetail);
  45335. }
  45336. copyArray(this.clearedIntersectedEls, this.intersectedEls);
  45337. this.intersectedEls.length = 0;
  45338. this.intersections.length = 0;
  45339. this.el.emit(EVENTS.INTERSECTION_CLEAR, this.intersectionClearedDetail);
  45340. }
  45341. });
  45342. /**
  45343. * Copy contents of one array to another without allocating new array.
  45344. */
  45345. function copyArray (a, b) {
  45346. var i;
  45347. a.length = b.length;
  45348. for (i = 0; i < b.length; i++) {
  45349. a[i] = b[i];
  45350. }
  45351. }
  45352. },{"../core/component":103,"../lib/three":151,"../utils/":176}],72:[function(_dereq_,module,exports){
  45353. var degToRad = _dereq_('../lib/three').Math.degToRad;
  45354. var registerComponent = _dereq_('../core/component').registerComponent;
  45355. module.exports.Component = registerComponent('rotation', {
  45356. schema: {type: 'vec3'},
  45357. /**
  45358. * Updates object3D rotation.
  45359. */
  45360. update: function () {
  45361. var data = this.data;
  45362. var object3D = this.el.object3D;
  45363. object3D.rotation.set(degToRad(data.x), degToRad(data.y), degToRad(data.z));
  45364. object3D.rotation.order = 'YXZ';
  45365. },
  45366. remove: function () {
  45367. // Pretty much for mixins.
  45368. this.el.object3D.rotation.set(0, 0, 0);
  45369. }
  45370. });
  45371. },{"../core/component":103,"../lib/three":151}],73:[function(_dereq_,module,exports){
  45372. var registerComponent = _dereq_('../core/component').registerComponent;
  45373. // Avoids triggering a zero-determinant which makes object3D matrix non-invertible.
  45374. var zeroScale = 0.00001;
  45375. module.exports.Component = registerComponent('scale', {
  45376. schema: {
  45377. type: 'vec3',
  45378. default: {x: 1, y: 1, z: 1}
  45379. },
  45380. update: function () {
  45381. var data = this.data;
  45382. var object3D = this.el.object3D;
  45383. var x = data.x === 0 ? zeroScale : data.x;
  45384. var y = data.y === 0 ? zeroScale : data.y;
  45385. var z = data.z === 0 ? zeroScale : data.z;
  45386. object3D.scale.set(x, y, z);
  45387. },
  45388. remove: function () {
  45389. // Pretty much for mixins.
  45390. this.el.object3D.scale.set(1, 1, 1);
  45391. }
  45392. });
  45393. },{"../core/component":103}],74:[function(_dereq_,module,exports){
  45394. /* global THREE */
  45395. var register = _dereq_('../../core/component').registerComponent;
  45396. module.exports.Component = register('background', {
  45397. schema: {
  45398. color: {type: 'color', default: 'black'},
  45399. transparent: {default: false}
  45400. },
  45401. update: function () {
  45402. var data = this.data;
  45403. var object3D = this.el.object3D;
  45404. if (data.transparent) {
  45405. object3D.background = null;
  45406. return;
  45407. }
  45408. object3D.background = new THREE.Color(data.color);
  45409. }
  45410. });
  45411. },{"../../core/component":103}],75:[function(_dereq_,module,exports){
  45412. var register = _dereq_('../../core/component').registerComponent;
  45413. module.exports.Component = register('debug', {
  45414. schema: {default: true}
  45415. });
  45416. },{"../../core/component":103}],76:[function(_dereq_,module,exports){
  45417. var registerComponent = _dereq_('../../core/component').registerComponent;
  45418. /**
  45419. * Component to embed an a-frame scene within the layout of a 2D page.
  45420. */
  45421. module.exports.Component = registerComponent('embedded', {
  45422. dependencies: ['vr-mode-ui'],
  45423. schema: {default: true},
  45424. update: function () {
  45425. var sceneEl = this.el;
  45426. var enterVREl = sceneEl.querySelector('.a-enter-vr');
  45427. if (this.data === true) {
  45428. if (enterVREl) { enterVREl.classList.add('embedded'); }
  45429. sceneEl.removeFullScreenStyles();
  45430. } else {
  45431. if (enterVREl) { enterVREl.classList.remove('embedded'); }
  45432. sceneEl.addFullScreenStyles();
  45433. }
  45434. }
  45435. });
  45436. },{"../../core/component":103}],77:[function(_dereq_,module,exports){
  45437. var register = _dereq_('../../core/component').registerComponent;
  45438. var THREE = _dereq_('../../lib/three');
  45439. var debug = _dereq_('../../utils/debug');
  45440. var warn = debug('components:fog:warn');
  45441. /**
  45442. * Fog component.
  45443. * Applies only to the scene entity.
  45444. */
  45445. module.exports.Component = register('fog', {
  45446. schema: {
  45447. color: {type: 'color', default: '#000'},
  45448. density: {default: 0.00025},
  45449. far: {default: 1000, min: 0},
  45450. near: {default: 1, min: 0},
  45451. type: {default: 'linear', oneOf: ['linear', 'exponential']}
  45452. },
  45453. update: function () {
  45454. var data = this.data;
  45455. var el = this.el;
  45456. var fog = this.el.object3D.fog;
  45457. if (!el.isScene) {
  45458. warn('Fog component can only be applied to <a-scene>');
  45459. return;
  45460. }
  45461. // (Re)create fog if fog doesn't exist or fog type changed.
  45462. if (!fog || data.type !== fog.name) {
  45463. el.object3D.fog = getFog(data);
  45464. el.systems.material.updateMaterials();
  45465. return;
  45466. }
  45467. // Fog data changed. Update fog.
  45468. Object.keys(this.schema).forEach(function (key) {
  45469. var value = data[key];
  45470. if (key === 'color') { value = new THREE.Color(value); }
  45471. fog[key] = value;
  45472. });
  45473. },
  45474. /**
  45475. * Remove fog on remove (callback).
  45476. */
  45477. remove: function () {
  45478. var fog = this.el.object3D.fog;
  45479. if (!fog) { return; }
  45480. fog.far = 0;
  45481. fog.near = 0.1;
  45482. }
  45483. });
  45484. /**
  45485. * Creates a fog object. Sets fog.name to be able to detect fog type changes.
  45486. *
  45487. * @param {object} data - Fog data.
  45488. * @returns {object} fog
  45489. */
  45490. function getFog (data) {
  45491. var fog;
  45492. if (data.type === 'exponential') {
  45493. fog = new THREE.FogExp2(data.color, data.density);
  45494. } else {
  45495. fog = new THREE.Fog(data.color, data.near, data.far);
  45496. }
  45497. fog.name = data.type;
  45498. return fog;
  45499. }
  45500. },{"../../core/component":103,"../../lib/three":151,"../../utils/debug":172}],78:[function(_dereq_,module,exports){
  45501. (function (process){
  45502. /* global AFRAME */
  45503. var AFRAME_INJECTED = _dereq_('../../constants').AFRAME_INJECTED;
  45504. var pkg = _dereq_('../../../package');
  45505. var registerComponent = _dereq_('../../core/component').registerComponent;
  45506. var utils = _dereq_('../../utils/');
  45507. /**
  45508. * 0.4.2 to 0.4.x
  45509. * Will need to update this when A-Frame goes to 1.x.x.
  45510. */
  45511. function getFuzzyPatchVersion (version) {
  45512. var split = version.split('.');
  45513. split[2] = 'x';
  45514. return split.join('.');
  45515. }
  45516. var INSPECTOR_DEV_URL = 'https://aframe.io/aframe-inspector/dist/aframe-inspector.js';
  45517. var INSPECTOR_RELEASE_URL = 'https://unpkg.com/aframe-inspector@' + getFuzzyPatchVersion(pkg.version) + '/dist/aframe-inspector.min.js';
  45518. var INSPECTOR_URL = process.env.INSPECTOR_VERSION === 'dev' ? INSPECTOR_DEV_URL : INSPECTOR_RELEASE_URL;
  45519. var LOADING_MESSAGE = 'Loading Inspector';
  45520. var LOADING_ERROR_MESSAGE = 'Error loading Inspector';
  45521. module.exports.Component = registerComponent('inspector', {
  45522. schema: {
  45523. url: {default: INSPECTOR_URL}
  45524. },
  45525. init: function () {
  45526. this.firstPlay = true;
  45527. this.onKeydown = this.onKeydown.bind(this);
  45528. this.onMessage = this.onMessage.bind(this);
  45529. this.initOverlay();
  45530. window.addEventListener('keydown', this.onKeydown);
  45531. window.addEventListener('message', this.onMessage);
  45532. },
  45533. play: function () {
  45534. var urlParam;
  45535. if (!this.firstPlay) { return; }
  45536. urlParam = utils.getUrlParameter('inspector');
  45537. if (urlParam !== 'false' && !!urlParam) {
  45538. this.openInspector();
  45539. this.firstPlay = false;
  45540. }
  45541. },
  45542. initOverlay: function () {
  45543. var dotsHTML = '<span class="dots"><span>.</span><span>.</span><span>.</span></span>';
  45544. this.loadingMessageEl = document.createElement('div');
  45545. this.loadingMessageEl.classList.add('a-inspector-loader');
  45546. this.loadingMessageEl.innerHTML = LOADING_MESSAGE + dotsHTML;
  45547. },
  45548. remove: function () {
  45549. this.removeEventListeners();
  45550. },
  45551. /**
  45552. * <ctrl> + <alt> + i keyboard shortcut.
  45553. */
  45554. onKeydown: function (evt) {
  45555. var shortcutPressed = evt.keyCode === 73 && evt.ctrlKey && evt.altKey;
  45556. if (!shortcutPressed) { return; }
  45557. this.openInspector();
  45558. },
  45559. showLoader: function () {
  45560. document.body.appendChild(this.loadingMessageEl);
  45561. },
  45562. hideLoader: function () {
  45563. document.body.removeChild(this.loadingMessageEl);
  45564. },
  45565. /**
  45566. * postMessage. aframe.io uses this to create a button on examples to open Inspector.
  45567. */
  45568. onMessage: function (evt) {
  45569. if (evt.data === 'INJECT_AFRAME_INSPECTOR') { this.openInspector(); }
  45570. },
  45571. openInspector: function (focusEl) {
  45572. var self = this;
  45573. var script;
  45574. // Already injected. Open.
  45575. if (AFRAME.INSPECTOR || AFRAME.inspectorInjected) {
  45576. AFRAME.INSPECTOR.open(focusEl);
  45577. return;
  45578. }
  45579. this.showLoader();
  45580. // Inject.
  45581. script = document.createElement('script');
  45582. script.src = this.data.url;
  45583. script.setAttribute('data-name', 'aframe-inspector');
  45584. script.setAttribute(AFRAME_INJECTED, '');
  45585. script.onload = function () {
  45586. AFRAME.INSPECTOR.open(focusEl);
  45587. self.hideLoader();
  45588. self.removeEventListeners();
  45589. };
  45590. script.onerror = function () {
  45591. self.loadingMessageEl.innerHTML = LOADING_ERROR_MESSAGE;
  45592. };
  45593. document.head.appendChild(script);
  45594. AFRAME.inspectorInjected = true;
  45595. },
  45596. removeEventListeners: function () {
  45597. window.removeEventListener('keydown', this.onKeydown);
  45598. window.removeEventListener('message', this.onMessage);
  45599. }
  45600. });
  45601. }).call(this,_dereq_('_process'))
  45602. },{"../../../package":51,"../../constants":95,"../../core/component":103,"../../utils/":176,"_process":32}],79:[function(_dereq_,module,exports){
  45603. var registerComponent = _dereq_('../../core/component').registerComponent;
  45604. var shouldCaptureKeyEvent = _dereq_('../../utils/').shouldCaptureKeyEvent;
  45605. module.exports.Component = registerComponent('keyboard-shortcuts', {
  45606. schema: {
  45607. enterVR: {default: true},
  45608. exitVR: {default: true}
  45609. },
  45610. init: function () {
  45611. this.onKeyup = this.onKeyup.bind(this);
  45612. },
  45613. update: function (oldData) {
  45614. var data = this.data;
  45615. this.enterVREnabled = data.enterVR;
  45616. },
  45617. play: function () {
  45618. window.addEventListener('keyup', this.onKeyup, false);
  45619. },
  45620. pause: function () {
  45621. window.removeEventListener('keyup', this.onKeyup);
  45622. },
  45623. onKeyup: function (evt) {
  45624. var scene = this.el;
  45625. if (!shouldCaptureKeyEvent(evt)) { return; }
  45626. if (this.enterVREnabled && evt.keyCode === 70) { // f.
  45627. scene.enterVR();
  45628. }
  45629. if (this.enterVREnabled && evt.keyCode === 27) { // escape.
  45630. scene.exitVR();
  45631. }
  45632. }
  45633. });
  45634. },{"../../core/component":103,"../../utils/":176}],80:[function(_dereq_,module,exports){
  45635. var debug = _dereq_('../../utils/debug');
  45636. var registerComponent = _dereq_('../../core/component').registerComponent;
  45637. var warn = debug('components:pool:warn');
  45638. /**
  45639. * Pool component to reuse entities.
  45640. * Avoids creating and destroying the same kind of entities.
  45641. * Helps reduce GC pauses. For example in a game to reuse enemies entities.
  45642. *
  45643. * @member {array} availableEls - Available entities in the pool.
  45644. * @member {array} usedEls - Entities of the pool in use.
  45645. */
  45646. module.exports.Component = registerComponent('pool', {
  45647. schema: {
  45648. container: {default: ''},
  45649. mixin: {default: ''},
  45650. size: {default: 0},
  45651. dynamic: {default: false}
  45652. },
  45653. multiple: true,
  45654. initPool: function () {
  45655. var i;
  45656. this.availableEls = [];
  45657. this.usedEls = [];
  45658. if (!this.data.mixin) {
  45659. warn('No mixin provided for pool component.');
  45660. }
  45661. if (this.data.container) {
  45662. this.container = document.querySelector(this.data.container);
  45663. if (!this.container) {
  45664. warn('Container ' + this.data.container + ' not found.');
  45665. }
  45666. }
  45667. this.container = this.container || this.el;
  45668. for (i = 0; i < this.data.size; ++i) {
  45669. this.createEntity();
  45670. }
  45671. },
  45672. update: function (oldData) {
  45673. var data = this.data;
  45674. if (oldData.mixin !== data.mixin || oldData.size !== data.size) {
  45675. this.initPool();
  45676. }
  45677. },
  45678. /**
  45679. * Add a new entity to the list of available entities.
  45680. */
  45681. createEntity: function () {
  45682. var el;
  45683. el = document.createElement('a-entity');
  45684. el.play = this.wrapPlay(el.play);
  45685. el.setAttribute('mixin', this.data.mixin);
  45686. el.object3D.visible = false;
  45687. el.pause();
  45688. this.container.appendChild(el);
  45689. this.availableEls.push(el);
  45690. },
  45691. /**
  45692. * Play wrapper for pooled entities. When pausing and playing a scene, don't want to play
  45693. * entities that are not in use.
  45694. */
  45695. wrapPlay: function (playMethod) {
  45696. var usedEls = this.usedEls;
  45697. return function () {
  45698. if (usedEls.indexOf(this) === -1) { return; }
  45699. playMethod.call(this);
  45700. };
  45701. },
  45702. /**
  45703. * Used to request one of the available entities of the pool.
  45704. */
  45705. requestEntity: function () {
  45706. var el;
  45707. if (this.availableEls.length === 0) {
  45708. if (this.data.dynamic === false) {
  45709. warn('Requested entity from empty pool: ' + this.attrName);
  45710. return;
  45711. } else {
  45712. warn('Requested entity from empty pool. This pool is dynamic and will resize ' +
  45713. 'automatically. You might want to increase its initial size: ' + this.attrName);
  45714. }
  45715. this.createEntity();
  45716. }
  45717. el = this.availableEls.shift();
  45718. this.usedEls.push(el);
  45719. el.object3D.visible = true;
  45720. return el;
  45721. },
  45722. /**
  45723. * Used to return a used entity to the pool.
  45724. */
  45725. returnEntity: function (el) {
  45726. var index = this.usedEls.indexOf(el);
  45727. if (index === -1) {
  45728. warn('The returned entity was not previously pooled from ' + this.attrName);
  45729. return;
  45730. }
  45731. this.usedEls.splice(index, 1);
  45732. this.availableEls.push(el);
  45733. el.object3D.visible = false;
  45734. el.pause();
  45735. return el;
  45736. }
  45737. });
  45738. },{"../../core/component":103,"../../utils/debug":172}],81:[function(_dereq_,module,exports){
  45739. /* global ImageData, URL */
  45740. var registerComponent = _dereq_('../../core/component').registerComponent;
  45741. var THREE = _dereq_('../../lib/three');
  45742. var VERTEX_SHADER = [
  45743. 'attribute vec3 position;',
  45744. 'attribute vec2 uv;',
  45745. 'uniform mat4 projectionMatrix;',
  45746. 'uniform mat4 modelViewMatrix;',
  45747. 'varying vec2 vUv;',
  45748. 'void main() {',
  45749. ' vUv = vec2( 1.- uv.x, uv.y );',
  45750. ' gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );',
  45751. '}'
  45752. ].join('\n');
  45753. var FRAGMENT_SHADER = [
  45754. 'precision mediump float;',
  45755. 'uniform samplerCube map;',
  45756. 'varying vec2 vUv;',
  45757. '#define M_PI 3.141592653589793238462643383279',
  45758. 'void main() {',
  45759. ' vec2 uv = vUv;',
  45760. ' float longitude = uv.x * 2. * M_PI - M_PI + M_PI / 2.;',
  45761. ' float latitude = uv.y * M_PI;',
  45762. ' vec3 dir = vec3(',
  45763. ' - sin( longitude ) * sin( latitude ),',
  45764. ' cos( latitude ),',
  45765. ' - cos( longitude ) * sin( latitude )',
  45766. ' );',
  45767. ' normalize( dir );',
  45768. ' gl_FragColor = vec4( textureCube( map, dir ).rgb, 1.0 );',
  45769. '}'
  45770. ].join('\n');
  45771. /**
  45772. * Component to take screenshots of the scene using a keboard shortcut (alt+s).
  45773. * It can be configured to either take 360&deg; captures (`equirectangular`)
  45774. * or regular screenshots (`projection`)
  45775. *
  45776. * This is based on https://github.com/spite/THREE.CubemapToEquirectangular
  45777. * To capture an equirectangular projection of the scene a THREE.CubeCamera is used
  45778. * The cube map produced by the CubeCamera is projected on a quad and then rendered to
  45779. * WebGLRenderTarget with an ortographic camera.
  45780. */
  45781. module.exports.Component = registerComponent('screenshot', {
  45782. schema: {
  45783. width: {default: 4096},
  45784. height: {default: 2048},
  45785. camera: {type: 'selector'}
  45786. },
  45787. init: function () {
  45788. var el = this.el;
  45789. var self = this;
  45790. if (el.renderer) {
  45791. setup();
  45792. } else {
  45793. el.addEventListener('render-target-loaded', setup);
  45794. }
  45795. function setup () {
  45796. var gl = el.renderer.getContext();
  45797. if (!gl) { return; }
  45798. self.cubeMapSize = gl.getParameter(gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  45799. self.material = new THREE.RawShaderMaterial({
  45800. uniforms: {map: {type: 't', value: null}},
  45801. vertexShader: VERTEX_SHADER,
  45802. fragmentShader: FRAGMENT_SHADER,
  45803. side: THREE.DoubleSide
  45804. });
  45805. self.quad = new THREE.Mesh(
  45806. new THREE.PlaneBufferGeometry(1, 1),
  45807. self.material
  45808. );
  45809. self.quad.visible = false;
  45810. self.camera = new THREE.OrthographicCamera(-1 / 2, 1 / 2, 1 / 2, -1 / 2, -10000, 10000);
  45811. self.canvas = document.createElement('canvas');
  45812. self.ctx = self.canvas.getContext('2d');
  45813. el.object3D.add(self.quad);
  45814. self.onKeyDown = self.onKeyDown.bind(self);
  45815. }
  45816. },
  45817. getRenderTarget: function (width, height) {
  45818. return new THREE.WebGLRenderTarget(width, height, {
  45819. minFilter: THREE.LinearFilter,
  45820. magFilter: THREE.LinearFilter,
  45821. wrapS: THREE.ClampToEdgeWrapping,
  45822. wrapT: THREE.ClampToEdgeWrapping,
  45823. format: THREE.RGBAFormat,
  45824. type: THREE.UnsignedByteType
  45825. });
  45826. },
  45827. resize: function (width, height) {
  45828. // Resize quad.
  45829. this.quad.scale.set(width, height, 1);
  45830. // Resize camera.
  45831. this.camera.left = -1 * width / 2;
  45832. this.camera.right = width / 2;
  45833. this.camera.top = height / 2;
  45834. this.camera.bottom = -1 * height / 2;
  45835. this.camera.updateProjectionMatrix();
  45836. // Resize canvas.
  45837. this.canvas.width = width;
  45838. this.canvas.height = height;
  45839. },
  45840. play: function () {
  45841. window.addEventListener('keydown', this.onKeyDown);
  45842. },
  45843. /**
  45844. * <ctrl> + <alt> + s = Regular screenshot.
  45845. * <ctrl> + <alt> + <shift> + s = Equirectangular screenshot.
  45846. */
  45847. onKeyDown: function (evt) {
  45848. var shortcutPressed = evt.keyCode === 83 && evt.ctrlKey && evt.altKey;
  45849. if (!this.data || !shortcutPressed) { return; }
  45850. var projection = evt.shiftKey ? 'equirectangular' : 'perspective';
  45851. this.capture(projection);
  45852. },
  45853. /**
  45854. * Capture a screenshot of the scene.
  45855. *
  45856. * @param {string} projection - Screenshot projection (equirectangular or perspective).
  45857. */
  45858. setCapture: function (projection) {
  45859. var el = this.el;
  45860. var size;
  45861. var camera;
  45862. var cubeCamera;
  45863. // Configure camera.
  45864. if (projection === 'perspective') {
  45865. // Quad is only used in equirectangular mode. Hide it in this case.
  45866. this.quad.visible = false;
  45867. // Use scene camera.
  45868. camera = (this.data.camera && this.data.camera.components.camera.camera) || el.camera;
  45869. size = {width: this.data.width, height: this.data.height};
  45870. } else {
  45871. // Use ortho camera.
  45872. camera = this.camera;
  45873. // Create cube camera and copy position from scene camera.
  45874. cubeCamera = new THREE.CubeCamera(el.camera.near, el.camera.far,
  45875. Math.min(this.cubeMapSize, 2048));
  45876. // Copy camera position into cube camera;
  45877. el.camera.getWorldPosition(cubeCamera.position);
  45878. el.camera.getWorldQuaternion(cubeCamera.quaternion);
  45879. // Render scene with cube camera.
  45880. cubeCamera.update(el.renderer, el.object3D);
  45881. this.quad.material.uniforms.map.value = cubeCamera.renderTarget.texture;
  45882. size = {width: this.data.width, height: this.data.height};
  45883. // Use quad to project image taken by the cube camera.
  45884. this.quad.visible = true;
  45885. }
  45886. return {
  45887. camera: camera,
  45888. size: size,
  45889. projection: projection
  45890. };
  45891. },
  45892. /**
  45893. * Maintained for backwards compatibility.
  45894. */
  45895. capture: function (projection) {
  45896. var isVREnabled = this.el.renderer.vr.enabled;
  45897. var renderer = this.el.renderer;
  45898. var params;
  45899. // Disable VR.
  45900. renderer.vr.enabled = false;
  45901. params = this.setCapture(projection);
  45902. this.renderCapture(params.camera, params.size, params.projection);
  45903. // Trigger file download.
  45904. this.saveCapture();
  45905. // Restore VR.
  45906. renderer.vr.enabled = isVREnabled;
  45907. },
  45908. /**
  45909. * Return canvas instead of triggering download (e.g., for uploading blob to server).
  45910. */
  45911. getCanvas: function (projection) {
  45912. var params = this.setCapture(projection);
  45913. this.renderCapture(params.camera, params.size, params.projection);
  45914. return this.canvas;
  45915. },
  45916. renderCapture: function (camera, size, projection) {
  45917. var autoClear = this.el.renderer.autoClear;
  45918. var el = this.el;
  45919. var imageData;
  45920. var output;
  45921. var pixels;
  45922. var renderer = el.renderer;
  45923. // Create rendering target and buffer to store the read pixels.
  45924. output = this.getRenderTarget(size.width, size.height);
  45925. pixels = new Uint8Array(4 * size.width * size.height);
  45926. // Resize quad, camera, and canvas.
  45927. this.resize(size.width, size.height);
  45928. // Render scene to render target.
  45929. renderer.autoClear = true;
  45930. renderer.render(el.object3D, camera, output, true);
  45931. renderer.autoClear = autoClear;
  45932. // Read image pizels back.
  45933. renderer.readRenderTargetPixels(output, 0, 0, size.width, size.height, pixels);
  45934. if (projection === 'perspective') {
  45935. pixels = this.flipPixelsVertically(pixels, size.width, size.height);
  45936. }
  45937. imageData = new ImageData(new Uint8ClampedArray(pixels), size.width, size.height);
  45938. // Hide quad after projecting the image.
  45939. this.quad.visible = false;
  45940. // Copy pixels into canvas.
  45941. this.ctx.putImageData(imageData, 0, 0);
  45942. },
  45943. flipPixelsVertically: function (pixels, width, height) {
  45944. var flippedPixels = pixels.slice(0);
  45945. for (var x = 0; x < width; ++x) {
  45946. for (var y = 0; y < height; ++y) {
  45947. flippedPixels[x * 4 + y * width * 4] = pixels[x * 4 + (height - y) * width * 4];
  45948. flippedPixels[x * 4 + 1 + y * width * 4] = pixels[x * 4 + 1 + (height - y) * width * 4];
  45949. flippedPixels[x * 4 + 2 + y * width * 4] = pixels[x * 4 + 2 + (height - y) * width * 4];
  45950. flippedPixels[x * 4 + 3 + y * width * 4] = pixels[x * 4 + 3 + (height - y) * width * 4];
  45951. }
  45952. }
  45953. return flippedPixels;
  45954. },
  45955. /**
  45956. * Download capture to file.
  45957. */
  45958. saveCapture: function () {
  45959. this.canvas.toBlob(function (blob) {
  45960. var fileName = 'screenshot-' + document.title.toLowerCase() + '-' + Date.now() + '.png';
  45961. var linkEl = document.createElement('a');
  45962. var url = URL.createObjectURL(blob);
  45963. linkEl.href = url;
  45964. linkEl.setAttribute('download', fileName);
  45965. linkEl.innerHTML = 'downloading...';
  45966. linkEl.style.display = 'none';
  45967. document.body.appendChild(linkEl);
  45968. setTimeout(function () {
  45969. linkEl.click();
  45970. document.body.removeChild(linkEl);
  45971. }, 1);
  45972. }, 'image/png');
  45973. }
  45974. });
  45975. },{"../../core/component":103,"../../lib/three":151}],82:[function(_dereq_,module,exports){
  45976. var registerComponent = _dereq_('../../core/component').registerComponent;
  45977. var RStats = _dereq_('../../../vendor/rStats');
  45978. var utils = _dereq_('../../utils');
  45979. _dereq_('../../../vendor/rStats.extras');
  45980. _dereq_('../../lib/rStatsAframe');
  45981. var AFrameStats = window.aframeStats;
  45982. var bind = utils.bind;
  45983. var HIDDEN_CLASS = 'a-hidden';
  45984. var ThreeStats = window.threeStats;
  45985. /**
  45986. * Stats appended to document.body by RStats.
  45987. */
  45988. module.exports.Component = registerComponent('stats', {
  45989. schema: {default: true},
  45990. init: function () {
  45991. var scene = this.el;
  45992. if (utils.getUrlParameter('stats') === 'false') { return; }
  45993. this.stats = createStats(scene);
  45994. this.statsEl = document.querySelector('.rs-base');
  45995. this.hideBound = bind(this.hide, this);
  45996. this.showBound = bind(this.show, this);
  45997. scene.addEventListener('enter-vr', this.hideBound);
  45998. scene.addEventListener('exit-vr', this.showBound);
  45999. },
  46000. update: function () {
  46001. if (!this.stats) { return; }
  46002. return (!this.data) ? this.hide() : this.show();
  46003. },
  46004. remove: function () {
  46005. this.el.removeEventListener('enter-vr', this.hideBound);
  46006. this.el.removeEventListener('exit-vr', this.showBound);
  46007. if (!this.statsEl) { return; } // Scene detached.
  46008. this.statsEl.parentNode.removeChild(this.statsEl);
  46009. },
  46010. tick: function () {
  46011. var stats = this.stats;
  46012. if (!stats) { return; }
  46013. stats('rAF').tick();
  46014. stats('FPS').frame();
  46015. stats().update();
  46016. },
  46017. hide: function () {
  46018. this.statsEl.classList.add(HIDDEN_CLASS);
  46019. },
  46020. show: function () {
  46021. this.statsEl.classList.remove(HIDDEN_CLASS);
  46022. }
  46023. });
  46024. function createStats (scene) {
  46025. var threeStats = new ThreeStats(scene.renderer);
  46026. var aframeStats = new AFrameStats(scene);
  46027. var plugins = scene.isMobile ? [] : [threeStats, aframeStats];
  46028. return new RStats({
  46029. css: [], // Our stylesheet is injected from `src/index.js`.
  46030. values: {
  46031. fps: {caption: 'fps', below: 30}
  46032. },
  46033. groups: [
  46034. {caption: 'Framerate', values: ['fps', 'raf']}
  46035. ],
  46036. plugins: plugins
  46037. });
  46038. }
  46039. },{"../../../vendor/rStats":186,"../../../vendor/rStats.extras":185,"../../core/component":103,"../../lib/rStatsAframe":150,"../../utils":176}],83:[function(_dereq_,module,exports){
  46040. var registerComponent = _dereq_('../../core/component').registerComponent;
  46041. var constants = _dereq_('../../constants/');
  46042. var utils = _dereq_('../../utils/');
  46043. var bind = utils.bind;
  46044. var ENTER_VR_CLASS = 'a-enter-vr';
  46045. var ENTER_VR_BTN_CLASS = 'a-enter-vr-button';
  46046. var HIDDEN_CLASS = 'a-hidden';
  46047. var ORIENTATION_MODAL_CLASS = 'a-orientation-modal';
  46048. /**
  46049. * UI for entering VR mode.
  46050. */
  46051. module.exports.Component = registerComponent('vr-mode-ui', {
  46052. dependencies: ['canvas'],
  46053. schema: {
  46054. enabled: {default: true},
  46055. enterVRButton: {default: ''}
  46056. },
  46057. init: function () {
  46058. var self = this;
  46059. var sceneEl = this.el;
  46060. if (utils.getUrlParameter('ui') === 'false') { return; }
  46061. this.insideLoader = false;
  46062. this.enterVREl = null;
  46063. this.orientationModalEl = null;
  46064. this.bindMethods();
  46065. // Hide/show VR UI when entering/exiting VR mode.
  46066. sceneEl.addEventListener('enter-vr', this.updateEnterVRInterface);
  46067. sceneEl.addEventListener('exit-vr', this.updateEnterVRInterface);
  46068. window.addEventListener('message', function (event) {
  46069. if (event.data.type === 'loaderReady') {
  46070. self.insideLoader = true;
  46071. self.remove();
  46072. }
  46073. });
  46074. // Modal that tells the user to change orientation if in portrait.
  46075. window.addEventListener('orientationchange', this.toggleOrientationModalIfNeeded);
  46076. },
  46077. bindMethods: function () {
  46078. this.onEnterVRButtonClick = bind(this.onEnterVRButtonClick, this);
  46079. this.onModalClick = bind(this.onModalClick, this);
  46080. this.toggleOrientationModalIfNeeded = bind(this.toggleOrientationModalIfNeeded, this);
  46081. this.updateEnterVRInterface = bind(this.updateEnterVRInterface, this);
  46082. },
  46083. /**
  46084. * Exit VR when modal clicked.
  46085. */
  46086. onModalClick: function () {
  46087. this.el.exitVR();
  46088. },
  46089. /**
  46090. * Enter VR when modal clicked.
  46091. */
  46092. onEnterVRButtonClick: function () {
  46093. this.el.enterVR();
  46094. },
  46095. update: function () {
  46096. var data = this.data;
  46097. var sceneEl = this.el;
  46098. if (!data.enabled || this.insideLoader || utils.getUrlParameter('ui') === 'false') {
  46099. return this.remove();
  46100. }
  46101. if (this.enterVREl || this.orientationModalEl) { return; }
  46102. // Add UI if enabled and not already present.
  46103. if (data.enterVRButton) {
  46104. // Custom button.
  46105. this.enterVREl = document.querySelector(data.enterVRButton);
  46106. this.enterVREl.addEventListener('click', this.onEnterVRButtonClick);
  46107. } else {
  46108. this.enterVREl = createEnterVRButton(this.onEnterVRButtonClick);
  46109. sceneEl.appendChild(this.enterVREl);
  46110. }
  46111. this.orientationModalEl = createOrientationModal(this.onModalClick);
  46112. sceneEl.appendChild(this.orientationModalEl);
  46113. this.updateEnterVRInterface();
  46114. },
  46115. remove: function () {
  46116. [this.enterVREl, this.orientationModalEl].forEach(function (uiElement) {
  46117. if (uiElement && uiElement.parentNode) {
  46118. uiElement.parentNode.removeChild(uiElement);
  46119. }
  46120. });
  46121. },
  46122. updateEnterVRInterface: function () {
  46123. this.toggleEnterVRButtonIfNeeded();
  46124. this.toggleOrientationModalIfNeeded();
  46125. },
  46126. toggleEnterVRButtonIfNeeded: function () {
  46127. var sceneEl = this.el;
  46128. if (!this.enterVREl) { return; }
  46129. if (sceneEl.is('vr-mode')) {
  46130. this.enterVREl.classList.add(HIDDEN_CLASS);
  46131. } else {
  46132. this.enterVREl.classList.remove(HIDDEN_CLASS);
  46133. }
  46134. },
  46135. toggleOrientationModalIfNeeded: function () {
  46136. var sceneEl = this.el;
  46137. var orientationModalEl = this.orientationModalEl;
  46138. if (!orientationModalEl || !sceneEl.isMobile) { return; }
  46139. if (!utils.device.isLandscape() && sceneEl.is('vr-mode')) {
  46140. // Show if in VR mode on portrait.
  46141. orientationModalEl.classList.remove(HIDDEN_CLASS);
  46142. } else {
  46143. orientationModalEl.classList.add(HIDDEN_CLASS);
  46144. }
  46145. }
  46146. });
  46147. /**
  46148. * Create a button that when clicked will enter into stereo-rendering mode for VR.
  46149. *
  46150. * Structure: <div><button></div>
  46151. *
  46152. * @param {function} onClick - click event handler
  46153. * @returns {Element} Wrapper <div>.
  46154. */
  46155. function createEnterVRButton (onClick) {
  46156. var vrButton;
  46157. var wrapper;
  46158. // Create elements.
  46159. wrapper = document.createElement('div');
  46160. wrapper.classList.add(ENTER_VR_CLASS);
  46161. wrapper.setAttribute(constants.AFRAME_INJECTED, '');
  46162. vrButton = document.createElement('button');
  46163. vrButton.className = ENTER_VR_BTN_CLASS;
  46164. vrButton.setAttribute('title',
  46165. 'Enter VR mode with a headset or fullscreen mode on a desktop. ' +
  46166. 'Visit https://webvr.rocks or https://webvr.info for more information.');
  46167. vrButton.setAttribute(constants.AFRAME_INJECTED, '');
  46168. // Insert elements.
  46169. wrapper.appendChild(vrButton);
  46170. vrButton.addEventListener('click', function (evt) {
  46171. onClick();
  46172. evt.stopPropagation();
  46173. });
  46174. return wrapper;
  46175. }
  46176. /**
  46177. * Creates a modal dialog to request the user to switch to landscape orientation.
  46178. *
  46179. * @param {function} onClick - click event handler
  46180. * @returns {Element} Wrapper <div>.
  46181. */
  46182. function createOrientationModal (onClick) {
  46183. var modal = document.createElement('div');
  46184. modal.className = ORIENTATION_MODAL_CLASS;
  46185. modal.classList.add(HIDDEN_CLASS);
  46186. modal.setAttribute(constants.AFRAME_INJECTED, '');
  46187. var exit = document.createElement('button');
  46188. exit.setAttribute(constants.AFRAME_INJECTED, '');
  46189. exit.innerHTML = 'Exit VR';
  46190. // Exit VR on close.
  46191. exit.addEventListener('click', onClick);
  46192. modal.appendChild(exit);
  46193. return modal;
  46194. }
  46195. },{"../../constants/":95,"../../core/component":103,"../../utils/":176}],84:[function(_dereq_,module,exports){
  46196. var component = _dereq_('../core/component');
  46197. var THREE = _dereq_('../lib/three');
  46198. var bind = _dereq_('../utils/bind');
  46199. var registerComponent = component.registerComponent;
  46200. /**
  46201. * Shadow component.
  46202. *
  46203. * When applied to an entity, that entity's geometry and any descendants will cast or receive
  46204. * shadows as specified by the `cast` and `receive` properties.
  46205. */
  46206. module.exports.Component = registerComponent('shadow', {
  46207. schema: {
  46208. cast: {default: true},
  46209. receive: {default: true}
  46210. },
  46211. init: function () {
  46212. this.onMeshChanged = bind(this.update, this);
  46213. this.el.addEventListener('object3dset', this.onMeshChanged);
  46214. this.system.setShadowMapEnabled(true);
  46215. },
  46216. update: function () {
  46217. var data = this.data;
  46218. this.updateDescendants(data.cast, data.receive);
  46219. },
  46220. remove: function () {
  46221. var el = this.el;
  46222. el.removeEventListener('object3dset', this.onMeshChanged);
  46223. this.updateDescendants(false, false);
  46224. },
  46225. updateDescendants: function (cast, receive) {
  46226. var sceneEl = this.el.sceneEl;
  46227. this.el.object3D.traverse(function (node) {
  46228. if (!(node instanceof THREE.Mesh)) { return; }
  46229. node.castShadow = cast;
  46230. node.receiveShadow = receive;
  46231. // If scene has already rendered, materials must be updated.
  46232. if (sceneEl.hasLoaded && node.material) {
  46233. var materials = Array.isArray(node.material) ? node.material : [node.material];
  46234. for (var i = 0; i < materials.length; i++) {
  46235. materials[i].needsUpdate = true;
  46236. }
  46237. }
  46238. });
  46239. }
  46240. });
  46241. },{"../core/component":103,"../lib/three":151,"../utils/bind":170}],85:[function(_dereq_,module,exports){
  46242. var registerComponent = _dereq_('../core/component').registerComponent;
  46243. var debug = _dereq_('../utils/debug');
  46244. var THREE = _dereq_('../lib/three');
  46245. var warn = debug('components:sound:warn');
  46246. /**
  46247. * Sound component.
  46248. */
  46249. module.exports.Component = registerComponent('sound', {
  46250. schema: {
  46251. autoplay: {default: false},
  46252. distanceModel: {default: 'inverse', oneOf: ['linear', 'inverse', 'exponential']},
  46253. loop: {default: false},
  46254. maxDistance: {default: 10000},
  46255. on: {default: ''},
  46256. poolSize: {default: 1},
  46257. positional: {default: true},
  46258. refDistance: {default: 1},
  46259. rolloffFactor: {default: 1},
  46260. src: {type: 'audio'},
  46261. volume: {default: 1}
  46262. },
  46263. multiple: true,
  46264. init: function () {
  46265. var self = this;
  46266. this.listener = null;
  46267. this.audioLoader = new THREE.AudioLoader();
  46268. this.pool = new THREE.Group();
  46269. this.loaded = false;
  46270. this.mustPlay = false;
  46271. // Don't pass evt because playSound takes a function as parameter.
  46272. this.playSoundBound = function () { self.playSound(); };
  46273. },
  46274. update: function (oldData) {
  46275. var data = this.data;
  46276. var i;
  46277. var sound;
  46278. var srcChanged = data.src !== oldData.src;
  46279. // Create new sound if not yet created or changing `src`.
  46280. if (srcChanged) {
  46281. if (!data.src) { return; }
  46282. this.setupSound();
  46283. }
  46284. for (i = 0; i < this.pool.children.length; i++) {
  46285. sound = this.pool.children[i];
  46286. if (data.positional) {
  46287. sound.setDistanceModel(data.distanceModel);
  46288. sound.setMaxDistance(data.maxDistance);
  46289. sound.setRefDistance(data.refDistance);
  46290. sound.setRolloffFactor(data.rolloffFactor);
  46291. }
  46292. sound.setLoop(data.loop);
  46293. sound.setVolume(data.volume);
  46294. sound.isPaused = false;
  46295. }
  46296. if (data.on !== oldData.on) {
  46297. this.updateEventListener(oldData.on);
  46298. }
  46299. // All sound values set. Load in `src`.
  46300. if (srcChanged) {
  46301. var self = this;
  46302. this.loaded = false;
  46303. this.audioLoader.load(data.src, function (buffer) {
  46304. for (i = 0; i < self.pool.children.length; i++) {
  46305. sound = self.pool.children[i];
  46306. sound.setBuffer(buffer);
  46307. }
  46308. self.loaded = true;
  46309. // Remove this key from cache, otherwise we can't play it again
  46310. THREE.Cache.remove(data.src);
  46311. if (self.data.autoplay || self.mustPlay) { self.playSound(); }
  46312. self.el.emit('sound-loaded', self.evtDetail, false);
  46313. });
  46314. }
  46315. },
  46316. pause: function () {
  46317. this.stopSound();
  46318. this.removeEventListener();
  46319. },
  46320. play: function () {
  46321. if (this.data.autoplay) { this.playSound(); }
  46322. this.updateEventListener();
  46323. },
  46324. remove: function () {
  46325. var i;
  46326. var sound;
  46327. this.removeEventListener();
  46328. if (this.el.getObject3D(this.attrName)) {
  46329. this.el.removeObject3D(this.attrName);
  46330. }
  46331. try {
  46332. for (i = 0; i < this.pool.children.length; i++) {
  46333. sound = this.pool.children[i];
  46334. sound.disconnect();
  46335. }
  46336. } catch (e) {
  46337. // disconnect() will throw if it was never connected initially.
  46338. warn('Audio source not properly disconnected');
  46339. }
  46340. },
  46341. /**
  46342. * Update listener attached to the user defined on event.
  46343. */
  46344. updateEventListener: function (oldEvt) {
  46345. var el = this.el;
  46346. if (oldEvt) { el.removeEventListener(oldEvt, this.playSoundBound); }
  46347. el.addEventListener(this.data.on, this.playSoundBound);
  46348. },
  46349. removeEventListener: function () {
  46350. this.el.removeEventListener(this.data.on, this.playSoundBound);
  46351. },
  46352. /**
  46353. * Removes current sound object, creates new sound object, adds to entity.
  46354. *
  46355. * @returns {object} sound
  46356. */
  46357. setupSound: function () {
  46358. var el = this.el;
  46359. var i;
  46360. var sceneEl = el.sceneEl;
  46361. var self = this;
  46362. var sound;
  46363. if (this.pool.children.length > 0) {
  46364. this.stopSound();
  46365. el.removeObject3D('sound');
  46366. }
  46367. // Only want one AudioListener. Cache it on the scene.
  46368. var listener = this.listener = sceneEl.audioListener || new THREE.AudioListener();
  46369. sceneEl.audioListener = listener;
  46370. if (sceneEl.camera) {
  46371. sceneEl.camera.add(listener);
  46372. }
  46373. // Wait for camera if necessary.
  46374. sceneEl.addEventListener('camera-set-active', function (evt) {
  46375. evt.detail.cameraEl.getObject3D('camera').add(listener);
  46376. });
  46377. // Create [poolSize] audio instances and attach them to pool
  46378. this.pool = new THREE.Group();
  46379. for (i = 0; i < this.data.poolSize; i++) {
  46380. sound = this.data.positional
  46381. ? new THREE.PositionalAudio(listener)
  46382. : new THREE.Audio(listener);
  46383. this.pool.add(sound);
  46384. }
  46385. el.setObject3D(this.attrName, this.pool);
  46386. for (i = 0; i < this.pool.children.length; i++) {
  46387. sound = this.pool.children[i];
  46388. sound.onEnded = function () {
  46389. this.isPlaying = false;
  46390. self.el.emit('sound-ended', self.evtDetail, false);
  46391. };
  46392. }
  46393. },
  46394. /**
  46395. * Pause all the sounds in the pool.
  46396. */
  46397. pauseSound: function () {
  46398. var i;
  46399. var sound;
  46400. this.isPlaying = false;
  46401. for (i = 0; i < this.pool.children.length; i++) {
  46402. sound = this.pool.children[i];
  46403. if (!sound.source || !sound.source.buffer || !sound.isPlaying || sound.isPaused) {
  46404. continue;
  46405. }
  46406. sound.isPaused = true;
  46407. sound.pause();
  46408. }
  46409. },
  46410. /**
  46411. * Look for an unused sound in the pool and play it if found.
  46412. */
  46413. playSound: function (processSound) {
  46414. var found;
  46415. var i;
  46416. var sound;
  46417. if (!this.loaded) {
  46418. warn('Sound not loaded yet. It will be played once it finished loading');
  46419. this.mustPlay = true;
  46420. return;
  46421. }
  46422. found = false;
  46423. this.isPlaying = true;
  46424. for (i = 0; i < this.pool.children.length; i++) {
  46425. sound = this.pool.children[i];
  46426. if (!sound.isPlaying && sound.buffer && !found) {
  46427. if (processSound) { processSound(sound); }
  46428. sound.play();
  46429. sound.isPaused = false;
  46430. found = true;
  46431. continue;
  46432. }
  46433. }
  46434. if (!found) {
  46435. warn('All the sounds are playing. If you need to play more sounds simultaneously ' +
  46436. 'consider increasing the size of pool with the `poolSize` attribute.', this.el);
  46437. return;
  46438. }
  46439. this.mustPlay = false;
  46440. },
  46441. /**
  46442. * Stop all the sounds in the pool.
  46443. */
  46444. stopSound: function () {
  46445. var i;
  46446. var sound;
  46447. this.isPlaying = false;
  46448. for (i = 0; i < this.pool.children.length; i++) {
  46449. sound = this.pool.children[i];
  46450. if (!sound.source || !sound.source.buffer) { return; }
  46451. sound.stop();
  46452. }
  46453. }
  46454. });
  46455. },{"../core/component":103,"../lib/three":151,"../utils/debug":172}],86:[function(_dereq_,module,exports){
  46456. var createTextGeometry = _dereq_('three-bmfont-text');
  46457. var loadBMFont = _dereq_('load-bmfont');
  46458. var registerComponent = _dereq_('../core/component').registerComponent;
  46459. var coreShader = _dereq_('../core/shader');
  46460. var THREE = _dereq_('../lib/three');
  46461. var utils = _dereq_('../utils/');
  46462. var error = utils.debug('components:text:error');
  46463. var shaders = coreShader.shaders;
  46464. var warn = utils.debug('components:text:warn');
  46465. // 1 to match other A-Frame default widths.
  46466. var DEFAULT_WIDTH = 1;
  46467. // @bryik set anisotropy to 16. Improves look of large amounts of text when viewed from angle.
  46468. var MAX_ANISOTROPY = 16;
  46469. var FONT_BASE_URL = 'https://cdn.aframe.io/fonts/';
  46470. var FONTS = {
  46471. aileronsemibold: FONT_BASE_URL + 'Aileron-Semibold.fnt',
  46472. dejavu: FONT_BASE_URL + 'DejaVu-sdf.fnt',
  46473. exo2bold: FONT_BASE_URL + 'Exo2Bold.fnt',
  46474. exo2semibold: FONT_BASE_URL + 'Exo2SemiBold.fnt',
  46475. kelsonsans: FONT_BASE_URL + 'KelsonSans.fnt',
  46476. monoid: FONT_BASE_URL + 'Monoid.fnt',
  46477. mozillavr: FONT_BASE_URL + 'mozillavr.fnt',
  46478. roboto: FONT_BASE_URL + 'Roboto-msdf.json',
  46479. sourcecodepro: FONT_BASE_URL + 'SourceCodePro.fnt'
  46480. };
  46481. var MSDF_FONTS = ['roboto'];
  46482. var DEFAULT_FONT = 'roboto';
  46483. module.exports.FONTS = FONTS;
  46484. var cache = new PromiseCache();
  46485. var fontWidthFactors = {};
  46486. var textures = {};
  46487. // Regular expression for detecting a URLs with a protocol prefix.
  46488. var protocolRe = /^\w+:/;
  46489. /**
  46490. * SDF-based text component.
  46491. * Based on https://github.com/Jam3/three-bmfont-text.
  46492. *
  46493. * All the stock fonts are for the `sdf` registered shader, an improved version of jam3's
  46494. * original `sdf` shader.
  46495. */
  46496. module.exports.Component = registerComponent('text', {
  46497. multiple: true,
  46498. schema: {
  46499. align: {type: 'string', default: 'left', oneOf: ['left', 'right', 'center']},
  46500. alphaTest: {default: 0.5},
  46501. // `anchor` defaults to center to match geometries.
  46502. anchor: {default: 'center', oneOf: ['left', 'right', 'center', 'align']},
  46503. baseline: {default: 'center', oneOf: ['top', 'center', 'bottom']},
  46504. color: {type: 'color', default: '#FFF'},
  46505. font: {type: 'string', default: DEFAULT_FONT},
  46506. // `fontImage` defaults to the font name as a .png (e.g., mozillavr.fnt -> mozillavr.png).
  46507. fontImage: {type: 'string'},
  46508. // `height` has no default, will be populated at layout.
  46509. height: {type: 'number'},
  46510. letterSpacing: {type: 'number', default: 0},
  46511. // `lineHeight` defaults to font's `lineHeight` value.
  46512. lineHeight: {type: 'number'},
  46513. // `negate` must be true for fonts generated with older versions of msdfgen (white background).
  46514. negate: {type: 'boolean', default: true},
  46515. opacity: {type: 'number', default: 1.0},
  46516. shader: {default: 'sdf', oneOf: shaders},
  46517. side: {default: 'front', oneOf: ['front', 'back', 'double']},
  46518. tabSize: {default: 4},
  46519. transparent: {default: true},
  46520. value: {type: 'string'},
  46521. whiteSpace: {default: 'normal', oneOf: ['normal', 'pre', 'nowrap']},
  46522. // `width` defaults to geometry width if present, else `DEFAULT_WIDTH`.
  46523. width: {type: 'number'},
  46524. // `wrapCount` units are about one default font character. Wrap roughly at this number.
  46525. wrapCount: {type: 'number', default: 40},
  46526. // `wrapPixels` will wrap using bmfont pixel units (e.g., dejavu's is 32 pixels).
  46527. wrapPixels: {type: 'number'},
  46528. // `xOffset` to add padding.
  46529. xOffset: {type: 'number', default: 0},
  46530. // `yOffset` to adjust generated fonts from tools that may have incorrect metrics.
  46531. yOffset: {type: 'number', default: 0},
  46532. // `zOffset` will provide a small z offset to avoid z-fighting.
  46533. zOffset: {type: 'number', default: 0.001}
  46534. },
  46535. init: function () {
  46536. this.shaderData = {};
  46537. this.geometry = createTextGeometry();
  46538. this.createOrUpdateMaterial();
  46539. this.mesh = new THREE.Mesh(this.geometry, this.material);
  46540. this.el.setObject3D(this.attrName, this.mesh);
  46541. },
  46542. update: function (oldData) {
  46543. var data = this.data;
  46544. var font = this.currentFont;
  46545. if (textures[data.font]) {
  46546. this.texture = textures[data.font];
  46547. } else {
  46548. // Create texture per font.
  46549. this.texture = textures[data.font] = new THREE.Texture();
  46550. this.texture.anisotropy = MAX_ANISOTROPY;
  46551. }
  46552. // Update material.
  46553. this.createOrUpdateMaterial();
  46554. // New font. `updateFont` will later change data and layout.
  46555. if (oldData.font !== data.font) {
  46556. this.updateFont();
  46557. return;
  46558. }
  46559. // Update geometry and layout.
  46560. if (font) {
  46561. this.updateGeometry(this.geometry, font);
  46562. this.updateLayout();
  46563. }
  46564. },
  46565. /**
  46566. * Clean up geometry, material, texture, mesh, objects.
  46567. */
  46568. remove: function () {
  46569. this.geometry.dispose();
  46570. this.geometry = null;
  46571. this.el.removeObject3D(this.attrName);
  46572. this.material.dispose();
  46573. this.material = null;
  46574. this.texture.dispose();
  46575. this.texture = null;
  46576. if (this.shaderObject) {
  46577. delete this.shaderObject;
  46578. }
  46579. },
  46580. /**
  46581. * Update the shader of the material.
  46582. */
  46583. createOrUpdateMaterial: function () {
  46584. var data = this.data;
  46585. var hasChangedShader;
  46586. var material = this.material;
  46587. var NewShader;
  46588. var shaderData = this.shaderData;
  46589. var shaderName;
  46590. // Infer shader if using a stock font (or from `-msdf` filename convention).
  46591. shaderName = data.shader;
  46592. if (MSDF_FONTS.indexOf(data.font) !== -1 || data.font.indexOf('-msdf.') >= 0) {
  46593. shaderName = 'msdf';
  46594. } else if (data.font in FONTS && MSDF_FONTS.indexOf(data.font) === -1) {
  46595. shaderName = 'sdf';
  46596. }
  46597. hasChangedShader = (this.shaderObject && this.shaderObject.name) !== shaderName;
  46598. shaderData.alphaTest = data.alphaTest;
  46599. shaderData.color = data.color;
  46600. shaderData.map = this.texture;
  46601. shaderData.opacity = data.opacity;
  46602. shaderData.side = parseSide(data.side);
  46603. shaderData.transparent = data.transparent;
  46604. shaderData.negate = data.negate;
  46605. // Shader has not changed, do an update.
  46606. if (!hasChangedShader) {
  46607. // Update shader material.
  46608. this.shaderObject.update(shaderData);
  46609. // Apparently, was not set on `init` nor `update`.
  46610. material.transparent = shaderData.transparent;
  46611. material.side = shaderData.side;
  46612. return;
  46613. }
  46614. // Shader has changed. Create a shader material.
  46615. NewShader = createShader(this.el, shaderName, shaderData);
  46616. this.material = NewShader.material;
  46617. this.shaderObject = NewShader.shader;
  46618. // Set new shader material.
  46619. this.material.side = shaderData.side;
  46620. if (this.mesh) { this.mesh.material = this.material; }
  46621. },
  46622. /**
  46623. * Load font for geometry, load font image for material, and apply.
  46624. */
  46625. updateFont: function () {
  46626. var data = this.data;
  46627. var el = this.el;
  46628. var fontSrc;
  46629. var geometry = this.geometry;
  46630. var self = this;
  46631. if (!data.font) { warn('No font specified. Using the default font.'); }
  46632. // Make invisible during font swap.
  46633. this.mesh.visible = false;
  46634. // Look up font URL to use, and perform cached load.
  46635. fontSrc = this.lookupFont(data.font || DEFAULT_FONT) || data.font;
  46636. cache.get(fontSrc, function doLoadFont () {
  46637. return loadFont(fontSrc, data.yOffset);
  46638. }).then(function setFont (font) {
  46639. var fontImgSrc;
  46640. if (font.pages.length !== 1) {
  46641. throw new Error('Currently only single-page bitmap fonts are supported.');
  46642. }
  46643. if (!fontWidthFactors[fontSrc]) {
  46644. font.widthFactor = fontWidthFactors[font] = computeFontWidthFactor(font);
  46645. }
  46646. // Update geometry given font metrics.
  46647. self.updateGeometry(geometry, font);
  46648. // Set font and update layout.
  46649. self.currentFont = font;
  46650. self.updateLayout();
  46651. // Look up font image URL to use, and perform cached load.
  46652. fontImgSrc = self.getFontImageSrc();
  46653. cache.get(fontImgSrc, function () {
  46654. return loadTexture(fontImgSrc);
  46655. }).then(function (image) {
  46656. // Make mesh visible and apply font image as texture.
  46657. var texture = self.texture;
  46658. texture.image = image;
  46659. texture.needsUpdate = true;
  46660. textures[data.font] = texture;
  46661. self.texture = texture;
  46662. self.mesh.visible = true;
  46663. el.emit('textfontset', {font: data.font, fontObj: font});
  46664. }).catch(function (err) {
  46665. error(err.message);
  46666. error(err.stack);
  46667. });
  46668. }).catch(function (err) {
  46669. error(err.message);
  46670. error(err.stack);
  46671. });
  46672. },
  46673. getFontImageSrc: function () {
  46674. if (this.data.fontImage) { return this.data.fontImage; }
  46675. var fontSrc = this.lookupFont(this.data.font || DEFAULT_FONT) || this.data.font;
  46676. var imageSrc = this.currentFont.pages[0];
  46677. // If the image URL contains a non-HTTP(S) protocol, assume it's an absolute
  46678. // path on disk and try to infer the path from the font source instead.
  46679. if (imageSrc.match(protocolRe) && imageSrc.indexOf('http') !== 0) {
  46680. return fontSrc.replace(/(\.fnt)|(\.json)/, '.png');
  46681. }
  46682. return THREE.LoaderUtils.extractUrlBase(fontSrc) + imageSrc;
  46683. },
  46684. /**
  46685. * Update layout with anchor, alignment, baseline, and considering any meshes.
  46686. */
  46687. updateLayout: function () {
  46688. var anchor;
  46689. var baseline;
  46690. var el = this.el;
  46691. var data = this.data;
  46692. var geometry = this.geometry;
  46693. var geometryComponent;
  46694. var height;
  46695. var layout;
  46696. var mesh = this.mesh;
  46697. var textRenderWidth;
  46698. var textScale;
  46699. var width;
  46700. var x;
  46701. var y;
  46702. if (!geometry.layout) { return; }
  46703. // Determine width to use (defined width, geometry's width, or default width).
  46704. geometryComponent = el.getAttribute('geometry');
  46705. width = data.width || (geometryComponent && geometryComponent.width) || DEFAULT_WIDTH;
  46706. // Determine wrap pixel count. Either specified or by experimental fudge factor.
  46707. // Note that experimental factor will never be correct for variable width fonts.
  46708. textRenderWidth = computeWidth(data.wrapPixels, data.wrapCount,
  46709. this.currentFont.widthFactor);
  46710. textScale = width / textRenderWidth;
  46711. // Determine height to use.
  46712. layout = geometry.layout;
  46713. height = textScale * (layout.height + layout.descender);
  46714. // Update geometry dimensions to match text layout if width and height are set to 0.
  46715. // For example, scales a plane to fit text.
  46716. if (geometryComponent && geometryComponent.primitive === 'plane') {
  46717. if (!geometryComponent.width) { el.setAttribute('geometry', 'width', width); }
  46718. if (!geometryComponent.height) { el.setAttribute('geometry', 'height', height); }
  46719. }
  46720. // Calculate X position to anchor text left, center, or right.
  46721. anchor = data.anchor === 'align' ? data.align : data.anchor;
  46722. if (anchor === 'left') {
  46723. x = 0;
  46724. } else if (anchor === 'right') {
  46725. x = -1 * layout.width;
  46726. } else if (anchor === 'center') {
  46727. x = -1 * layout.width / 2;
  46728. } else {
  46729. throw new TypeError('Invalid text.anchor property value', anchor);
  46730. }
  46731. // Calculate Y position to anchor text top, center, or bottom.
  46732. baseline = data.baseline;
  46733. if (baseline === 'bottom') {
  46734. y = 0;
  46735. } else if (baseline === 'top') {
  46736. y = -1 * layout.height + layout.ascender;
  46737. } else if (baseline === 'center') {
  46738. y = -1 * layout.height / 2;
  46739. } else {
  46740. throw new TypeError('Invalid text.baseline property value', baseline);
  46741. }
  46742. // Position and scale mesh to apply layout.
  46743. mesh.position.x = x * textScale + data.xOffset;
  46744. mesh.position.y = y * textScale;
  46745. // Place text slightly in front to avoid Z-fighting.
  46746. mesh.position.z = data.zOffset;
  46747. mesh.scale.set(textScale, -1 * textScale, textScale);
  46748. },
  46749. /**
  46750. * Grab font from the constant.
  46751. * Set as a method for test stubbing purposes.
  46752. */
  46753. lookupFont: function (key) {
  46754. return FONTS[key];
  46755. },
  46756. /**
  46757. * Update the text geometry using `three-bmfont-text.update`.
  46758. */
  46759. updateGeometry: (function () {
  46760. var geometryUpdateBase = {};
  46761. var geometryUpdateData = {};
  46762. var newLineRegex = /\\n/g;
  46763. var tabRegex = /\\t/g;
  46764. return function (geometry, font) {
  46765. var data = this.data;
  46766. geometryUpdateData.font = font;
  46767. geometryUpdateData.lineHeight = data.lineHeight && isFinite(data.lineHeight)
  46768. ? data.lineHeight
  46769. : font.common.lineHeight;
  46770. geometryUpdateData.text = data.value.toString().replace(newLineRegex, '\n')
  46771. .replace(tabRegex, '\t');
  46772. geometryUpdateData.width = computeWidth(data.wrapPixels, data.wrapCount,
  46773. font.widthFactor);
  46774. geometry.update(utils.extend(geometryUpdateBase, data, geometryUpdateData));
  46775. };
  46776. })()
  46777. });
  46778. /**
  46779. * Due to using negative scale, we return the opposite side specified.
  46780. * https://github.com/mrdoob/three.js/pull/12787/
  46781. */
  46782. function parseSide (side) {
  46783. switch (side) {
  46784. case 'back': {
  46785. return THREE.FrontSide;
  46786. }
  46787. case 'double': {
  46788. return THREE.DoubleSide;
  46789. }
  46790. default: {
  46791. return THREE.BackSide;
  46792. }
  46793. }
  46794. }
  46795. /**
  46796. * @returns {Promise}
  46797. */
  46798. function loadFont (src, yOffset) {
  46799. return new Promise(function (resolve, reject) {
  46800. loadBMFont(src, function (err, font) {
  46801. if (err) {
  46802. error('Error loading font', src);
  46803. reject(err);
  46804. return;
  46805. }
  46806. // Fix negative Y offsets for Roboto MSDF font from tool. Experimentally determined.
  46807. if (src.indexOf('/Roboto-msdf.json') >= 0) { yOffset = 30; }
  46808. if (yOffset) { font.chars.map(function doOffset (ch) { ch.yoffset += yOffset; }); }
  46809. resolve(font);
  46810. });
  46811. });
  46812. }
  46813. /**
  46814. * @returns {Promise}
  46815. */
  46816. function loadTexture (src) {
  46817. return new Promise(function (resolve, reject) {
  46818. new THREE.ImageLoader().load(src, function (image) {
  46819. resolve(image);
  46820. }, undefined, function () {
  46821. error('Error loading font image', src);
  46822. reject(null);
  46823. });
  46824. });
  46825. }
  46826. function createShader (el, shaderName, data) {
  46827. var shader;
  46828. var shaderObject;
  46829. // Set up Shader.
  46830. shaderObject = new shaders[shaderName].Shader();
  46831. shaderObject.el = el;
  46832. shaderObject.init(data);
  46833. shaderObject.update(data);
  46834. // Get material.
  46835. shader = shaderObject.material;
  46836. // Apparently, was not set on `init` nor `update`.
  46837. shader.transparent = data.transparent;
  46838. return {
  46839. material: shader,
  46840. shader: shaderObject
  46841. };
  46842. }
  46843. /**
  46844. * Determine wrap pixel count. Either specified or by experimental fudge factor.
  46845. * Note that experimental factor will never be correct for variable width fonts.
  46846. */
  46847. function computeWidth (wrapPixels, wrapCount, widthFactor) {
  46848. return wrapPixels || ((0.5 + wrapCount) * widthFactor);
  46849. }
  46850. /**
  46851. * Compute default font width factor to use.
  46852. */
  46853. function computeFontWidthFactor (font) {
  46854. var sum = 0;
  46855. var digitsum = 0;
  46856. var digits = 0;
  46857. font.chars.map(function (ch) {
  46858. sum += ch.xadvance;
  46859. if (ch.id >= 48 && ch.id <= 57) {
  46860. digits++;
  46861. digitsum += ch.xadvance;
  46862. }
  46863. });
  46864. return digits ? digitsum / digits : sum / font.chars.length;
  46865. }
  46866. /**
  46867. * Get or create a promise given a key and promise generator.
  46868. * @todo Move to a utility and use in other parts of A-Frame.
  46869. */
  46870. function PromiseCache () {
  46871. var cache = this.cache = {};
  46872. this.get = function (key, promiseGenerator) {
  46873. if (key in cache) {
  46874. return cache[key];
  46875. }
  46876. cache[key] = promiseGenerator();
  46877. return cache[key];
  46878. };
  46879. }
  46880. },{"../core/component":103,"../core/shader":113,"../lib/three":151,"../utils/":176,"load-bmfont":23,"three-bmfont-text":41}],87:[function(_dereq_,module,exports){
  46881. var registerComponent = _dereq_('../core/component').registerComponent;
  46882. var controllerUtils = _dereq_('../utils/tracked-controls');
  46883. var DEFAULT_CAMERA_HEIGHT = _dereq_('../constants').DEFAULT_CAMERA_HEIGHT;
  46884. var THREE = _dereq_('../lib/three');
  46885. var DEFAULT_HANDEDNESS = _dereq_('../constants').DEFAULT_HANDEDNESS;
  46886. // Vector from eyes to elbow (divided by user height).
  46887. var EYES_TO_ELBOW = {x: 0.175, y: -0.3, z: -0.03};
  46888. // Vector from eyes to elbow (divided by user height).
  46889. var FOREARM = {x: 0, y: 0, z: -0.175};
  46890. // Due to unfortunate name collision, add empty touches array to avoid Daydream error.
  46891. var EMPTY_DAYDREAM_TOUCHES = {touches: []};
  46892. var EVENTS = {
  46893. AXISMOVE: 'axismove',
  46894. BUTTONCHANGED: 'buttonchanged',
  46895. BUTTONDOWN: 'buttondown',
  46896. BUTTONUP: 'buttonup',
  46897. TOUCHSTART: 'touchstart',
  46898. TOUCHEND: 'touchend'
  46899. };
  46900. /**
  46901. * Tracked controls component.
  46902. * Wrap the gamepad API for pose and button states.
  46903. * Select the appropriate controller and apply pose to the entity.
  46904. * Observe button states and emit appropriate events.
  46905. *
  46906. * @property {number} controller - Index of controller in array returned by Gamepad API.
  46907. * Only used if hand property is not set.
  46908. * @property {string} id - Selected controller among those returned by Gamepad API.
  46909. * @property {number} hand - If multiple controllers found with id, choose the one with the
  46910. * given value for hand. If set, we ignore 'controller' property
  46911. */
  46912. module.exports.Component = registerComponent('tracked-controls-webvr', {
  46913. schema: {
  46914. autoHide: {default: true},
  46915. controller: {default: 0},
  46916. id: {type: 'string', default: ''},
  46917. hand: {type: 'string', default: ''},
  46918. idPrefix: {type: 'string', default: ''},
  46919. orientationOffset: {type: 'vec3'},
  46920. // Arm model parameters when not 6DoF.
  46921. armModel: {default: true},
  46922. headElement: {type: 'selector'}
  46923. },
  46924. init: function () {
  46925. // Copy variables back to tracked-controls for backwards compatibility.
  46926. // Some 3rd components rely on them.
  46927. this.axis = this.el.components['tracked-controls'].axis = [0, 0, 0];
  46928. this.buttonStates = this.el.components['tracked-controls'].buttonStates = {};
  46929. this.changedAxes = [];
  46930. this.targetControllerNumber = this.data.controller;
  46931. this.axisMoveEventDetail = {axis: this.axis, changed: this.changedAxes};
  46932. this.deltaControllerPosition = new THREE.Vector3();
  46933. this.controllerQuaternion = new THREE.Quaternion();
  46934. this.controllerEuler = new THREE.Euler();
  46935. this.updateGamepad();
  46936. this.buttonEventDetails = {};
  46937. },
  46938. tick: function (time, delta) {
  46939. var mesh = this.el.getObject3D('mesh');
  46940. // Update mesh animations.
  46941. if (mesh && mesh.update) { mesh.update(delta / 1000); }
  46942. this.updateGamepad();
  46943. this.updatePose();
  46944. this.updateButtons();
  46945. },
  46946. /**
  46947. * Return default user height to use for non-6DOF arm model.
  46948. */
  46949. defaultUserHeight: function () {
  46950. return DEFAULT_CAMERA_HEIGHT;
  46951. },
  46952. /**
  46953. * Return head element to use for non-6DOF arm model.
  46954. */
  46955. getHeadElement: function () {
  46956. return this.data.headElement || this.el.sceneEl.camera.el;
  46957. },
  46958. /**
  46959. * Handle update controller match criteria (such as `id`, `idPrefix`, `hand`, `controller`)
  46960. */
  46961. updateGamepad: function () {
  46962. var data = this.data;
  46963. var controller = controllerUtils.findMatchingControllerWebVR(
  46964. this.system.controllers,
  46965. data.id,
  46966. data.idPrefix,
  46967. data.hand,
  46968. data.controller
  46969. );
  46970. this.controller = controller;
  46971. // Legacy handle to the controller for old components.
  46972. this.el.components['tracked-controls'].controller = controller;
  46973. if (this.data.autoHide) { this.el.object3D.visible = !!this.controller; }
  46974. },
  46975. /**
  46976. * Applies an artificial arm model to simulate elbow to wrist positioning
  46977. * based on the orientation of the controller.
  46978. *
  46979. * @param {object} controllerPosition - Existing vector to update with controller position.
  46980. */
  46981. applyArmModel: function (controllerPosition) {
  46982. // Use controllerPosition and deltaControllerPosition to avoid creating variables.
  46983. var controller = this.controller;
  46984. var controllerEuler = this.controllerEuler;
  46985. var controllerQuaternion = this.controllerQuaternion;
  46986. var deltaControllerPosition = this.deltaControllerPosition;
  46987. var hand;
  46988. var headEl;
  46989. var headObject3D;
  46990. var pose;
  46991. var userHeight;
  46992. headEl = this.getHeadElement();
  46993. headObject3D = headEl.object3D;
  46994. userHeight = this.defaultUserHeight();
  46995. pose = controller.pose;
  46996. hand = (controller ? controller.hand : undefined) || DEFAULT_HANDEDNESS;
  46997. // Use camera position as head position.
  46998. controllerPosition.copy(headObject3D.position);
  46999. // Set offset for degenerate "arm model" to elbow.
  47000. deltaControllerPosition.set(
  47001. EYES_TO_ELBOW.x * (hand === 'left' ? -1 : hand === 'right' ? 1 : 0),
  47002. EYES_TO_ELBOW.y, // Lower than our eyes.
  47003. EYES_TO_ELBOW.z); // Slightly out in front.
  47004. // Scale offset by user height.
  47005. deltaControllerPosition.multiplyScalar(userHeight);
  47006. // Apply camera Y rotation (not X or Z, so you can look down at your hand).
  47007. deltaControllerPosition.applyAxisAngle(headObject3D.up, headObject3D.rotation.y);
  47008. // Apply rotated offset to position.
  47009. controllerPosition.add(deltaControllerPosition);
  47010. // Set offset for degenerate "arm model" forearm. Forearm sticking out from elbow.
  47011. deltaControllerPosition.set(FOREARM.x, FOREARM.y, FOREARM.z);
  47012. // Scale offset by user height.
  47013. deltaControllerPosition.multiplyScalar(userHeight);
  47014. // Apply controller X/Y rotation (tilting up/down/left/right is usually moving the arm).
  47015. if (pose.orientation) {
  47016. controllerQuaternion.fromArray(pose.orientation);
  47017. } else {
  47018. controllerQuaternion.copy(headObject3D.quaternion);
  47019. }
  47020. controllerEuler.setFromQuaternion(controllerQuaternion);
  47021. controllerEuler.set(controllerEuler.x, controllerEuler.y, 0);
  47022. deltaControllerPosition.applyEuler(controllerEuler);
  47023. // Apply rotated offset to position.
  47024. controllerPosition.add(deltaControllerPosition);
  47025. },
  47026. /**
  47027. * Read pose from controller (from Gamepad API), apply transforms, apply to entity.
  47028. */
  47029. updatePose: function () {
  47030. var controller = this.controller;
  47031. var data = this.data;
  47032. var object3D = this.el.object3D;
  47033. var pose;
  47034. var vrDisplay = this.system.vrDisplay;
  47035. var standingMatrix;
  47036. if (!controller) { return; }
  47037. // Compose pose from Gamepad.
  47038. pose = controller.pose;
  47039. if (pose.position) {
  47040. object3D.position.fromArray(pose.position);
  47041. } else {
  47042. // Controller not 6DOF, apply arm model.
  47043. if (data.armModel) { this.applyArmModel(object3D.position); }
  47044. }
  47045. if (pose.orientation) {
  47046. object3D.quaternion.fromArray(pose.orientation);
  47047. }
  47048. // Apply transforms, if 6DOF and in VR.
  47049. if (vrDisplay && pose.position) {
  47050. standingMatrix = this.el.sceneEl.renderer.vr.getStandingMatrix();
  47051. object3D.matrix.compose(object3D.position, object3D.quaternion, object3D.scale);
  47052. object3D.matrix.multiplyMatrices(standingMatrix, object3D.matrix);
  47053. object3D.matrix.decompose(object3D.position, object3D.quaternion, object3D.scale);
  47054. }
  47055. object3D.rotateX(this.data.orientationOffset.x * THREE.Math.DEG2RAD);
  47056. object3D.rotateY(this.data.orientationOffset.y * THREE.Math.DEG2RAD);
  47057. object3D.rotateZ(this.data.orientationOffset.z * THREE.Math.DEG2RAD);
  47058. },
  47059. /**
  47060. * Handle button changes including axes, presses, touches, values.
  47061. */
  47062. updateButtons: function () {
  47063. var buttonState;
  47064. var controller = this.controller;
  47065. var id;
  47066. if (!controller) { return; }
  47067. // Check every button.
  47068. for (id = 0; id < controller.buttons.length; ++id) {
  47069. // Initialize button state.
  47070. if (!this.buttonStates[id]) {
  47071. this.buttonStates[id] = {pressed: false, touched: false, value: 0};
  47072. }
  47073. if (!this.buttonEventDetails[id]) {
  47074. this.buttonEventDetails[id] = {id: id, state: this.buttonStates[id]};
  47075. }
  47076. buttonState = controller.buttons[id];
  47077. this.handleButton(id, buttonState);
  47078. }
  47079. // Check axes.
  47080. this.handleAxes();
  47081. },
  47082. /**
  47083. * Handle presses and touches for a single button.
  47084. *
  47085. * @param {number} id - Index of button in Gamepad button array.
  47086. * @param {number} buttonState - Value of button state from 0 to 1.
  47087. * @returns {boolean} Whether button has changed in any way.
  47088. */
  47089. handleButton: function (id, buttonState) {
  47090. var changed;
  47091. changed = this.handlePress(id, buttonState) |
  47092. this.handleTouch(id, buttonState) |
  47093. this.handleValue(id, buttonState);
  47094. if (!changed) { return false; }
  47095. this.el.emit(EVENTS.BUTTONCHANGED, this.buttonEventDetails[id], false);
  47096. return true;
  47097. },
  47098. /**
  47099. * An axis is an array of values from -1 (up, left) to 1 (down, right).
  47100. * Compare each component of the axis to the previous value to determine change.
  47101. *
  47102. * @returns {boolean} Whether axes changed.
  47103. */
  47104. handleAxes: function () {
  47105. var changed = false;
  47106. var controllerAxes = this.controller.axes;
  47107. var i;
  47108. var previousAxis = this.axis;
  47109. var changedAxes = this.changedAxes;
  47110. // Check if axis changed.
  47111. this.changedAxes.length = 0;
  47112. for (i = 0; i < controllerAxes.length; ++i) {
  47113. changedAxes.push(previousAxis[i] !== controllerAxes[i]);
  47114. if (changedAxes[i]) { changed = true; }
  47115. }
  47116. if (!changed) { return false; }
  47117. this.axis.length = 0;
  47118. for (i = 0; i < controllerAxes.length; i++) {
  47119. this.axis.push(controllerAxes[i]);
  47120. }
  47121. this.el.emit(EVENTS.AXISMOVE, this.axisMoveEventDetail, false);
  47122. return true;
  47123. },
  47124. /**
  47125. * Determine whether a button press has occured and emit events as appropriate.
  47126. *
  47127. * @param {string} id - ID of the button to check.
  47128. * @param {object} buttonState - State of the button to check.
  47129. * @returns {boolean} Whether button press state changed.
  47130. */
  47131. handlePress: function (id, buttonState) {
  47132. var evtName;
  47133. var previousButtonState = this.buttonStates[id];
  47134. // Not changed.
  47135. if (buttonState.pressed === previousButtonState.pressed) { return false; }
  47136. evtName = buttonState.pressed ? EVENTS.BUTTONDOWN : EVENTS.BUTTONUP;
  47137. this.el.emit(evtName, this.buttonEventDetails[id], false);
  47138. previousButtonState.pressed = buttonState.pressed;
  47139. return true;
  47140. },
  47141. /**
  47142. * Determine whether a button touch has occured and emit events as appropriate.
  47143. *
  47144. * @param {string} id - ID of the button to check.
  47145. * @param {object} buttonState - State of the button to check.
  47146. * @returns {boolean} Whether button touch state changed.
  47147. */
  47148. handleTouch: function (id, buttonState) {
  47149. var evtName;
  47150. var previousButtonState = this.buttonStates[id];
  47151. // Not changed.
  47152. if (buttonState.touched === previousButtonState.touched) { return false; }
  47153. evtName = buttonState.touched ? EVENTS.TOUCHSTART : EVENTS.TOUCHEND;
  47154. this.el.emit(evtName, this.buttonEventDetails[id], false, EMPTY_DAYDREAM_TOUCHES);
  47155. previousButtonState.touched = buttonState.touched;
  47156. return true;
  47157. },
  47158. /**
  47159. * Determine whether a button value has changed.
  47160. *
  47161. * @param {string} id - Id of the button to check.
  47162. * @param {object} buttonState - State of the button to check.
  47163. * @returns {boolean} Whether button value changed.
  47164. */
  47165. handleValue: function (id, buttonState) {
  47166. var previousButtonState = this.buttonStates[id];
  47167. // Not changed.
  47168. if (buttonState.value === previousButtonState.value) { return false; }
  47169. previousButtonState.value = buttonState.value;
  47170. return true;
  47171. }
  47172. });
  47173. },{"../constants":95,"../core/component":103,"../lib/three":151,"../utils/tracked-controls":184}],88:[function(_dereq_,module,exports){
  47174. var controllerUtils = _dereq_('../utils/tracked-controls');
  47175. var registerComponent = _dereq_('../core/component').registerComponent;
  47176. module.exports.Component = registerComponent('tracked-controls-webxr', {
  47177. schema: {
  47178. hand: {type: 'string', default: ''}
  47179. },
  47180. init: function () {
  47181. this.addSessionEventListeners = this.addSessionEventListeners.bind(this);
  47182. this.updateController = this.updateController.bind(this);
  47183. this.emitButtonUpEvent = this.emitButtonUpEvent.bind(this);
  47184. this.emitButtonDownEvent = this.emitButtonDownEvent.bind(this);
  47185. this.buttonEventDetails = {id: 'trigger', state: {pressed: false}};
  47186. },
  47187. play: function () {
  47188. var sceneEl = this.el.sceneEl;
  47189. this.updateController();
  47190. this.addSessionEventListeners();
  47191. sceneEl.addEventListener('enter-vr', this.addSessionEventListeners);
  47192. sceneEl.addEventListener('controllersupdated', this.updateController);
  47193. },
  47194. pause: function () {
  47195. var sceneEl = this.el.sceneEl;
  47196. this.removeSessionEventListeners();
  47197. sceneEl.removeEventListener('enter-vr', this.addSessionEventListeners);
  47198. sceneEl.removeEventListener('controllersupdated', this.updateController);
  47199. },
  47200. addSessionEventListeners: function () {
  47201. var sceneEl = this.el.sceneEl;
  47202. if (!sceneEl.xrSession) { return; }
  47203. sceneEl.xrSession.addEventListener('selectstart', this.emitButtonDownEvent);
  47204. sceneEl.xrSession.addEventListener('selectend', this.emitButtonUpEvent);
  47205. },
  47206. removeSessionEventListeners: function () {
  47207. var sceneEl = this.el.sceneEl;
  47208. if (!sceneEl.xrSession) { return; }
  47209. sceneEl.xrSession.addEventListener('selectstart', this.emitButtonDownEvent);
  47210. sceneEl.xrSession.addEventListener('selectend', this.emitButtonUpEvent);
  47211. },
  47212. emitButtonDownEvent: function (evt) {
  47213. if (!this.controller || evt.inputSource.handedness !== this.data.hand) { return; }
  47214. this.buttonEventDetails.state.pressed = true;
  47215. this.el.emit('buttondown', this.buttonEventDetails);
  47216. this.el.emit('buttonchanged', this.buttonEventDetails);
  47217. this.el.emit('triggerdown');
  47218. },
  47219. emitButtonUpEvent: function (evt) {
  47220. if (!this.controller || evt.inputSource.handedness !== this.data.hand) { return; }
  47221. this.buttonEventDetails.state.pressed = false;
  47222. this.el.emit('buttonup', this.buttonEventDetails);
  47223. this.el.emit('buttonchanged', this.buttonEventDetails);
  47224. this.el.emit('triggerup');
  47225. },
  47226. /**
  47227. * Handle update controller match criteria (such as `id`, `idPrefix`, `hand`, `controller`)
  47228. */
  47229. updateController: function () {
  47230. this.controller = controllerUtils.findMatchingControllerWebXR(
  47231. this.system.controllers,
  47232. this.data.hand
  47233. );
  47234. // Legacy handle to the controller for old components.
  47235. this.el.components['tracked-controls'].controller = this.controller;
  47236. if (this.data.autoHide) { this.el.object3D.visible = !!this.controller; }
  47237. },
  47238. tick: function () {
  47239. var pose;
  47240. var sceneEl = this.el.sceneEl;
  47241. var object3D = this.el.object3D;
  47242. if (!this.controller || !sceneEl.frame) { return; }
  47243. pose = sceneEl.frame.getInputPose(this.controller, sceneEl.frameOfReference);
  47244. if (!pose) { return; }
  47245. object3D.matrix.elements = pose.targetRay.transformMatrix;
  47246. object3D.matrix.decompose(object3D.position, object3D.rotation, object3D.scale);
  47247. }
  47248. });
  47249. },{"../core/component":103,"../utils/tracked-controls":184}],89:[function(_dereq_,module,exports){
  47250. var registerComponent = _dereq_('../core/component').registerComponent;
  47251. /**
  47252. * Tracked controls.
  47253. * Abstract controls that decide if the WebVR or WebXR version is going to be applied.
  47254. *
  47255. * @property {number} controller - Index of controller in array returned by Gamepad API.
  47256. * Only used if hand property is not set.
  47257. * @property {string} id - Selected controller among those returned by Gamepad API.
  47258. * @property {number} hand - If multiple controllers found with id, choose the one with the
  47259. * given value for hand. If set, we ignore 'controller' property
  47260. */
  47261. module.exports.Component = registerComponent('tracked-controls', {
  47262. schema: {
  47263. autoHide: {default: true},
  47264. controller: {default: 0},
  47265. id: {type: 'string', default: ''},
  47266. hand: {type: 'string', default: ''},
  47267. idPrefix: {type: 'string', default: ''},
  47268. orientationOffset: {type: 'vec3'},
  47269. // Arm model parameters when not 6DoF.
  47270. armModel: {default: true},
  47271. headElement: {type: 'selector'}
  47272. },
  47273. update: function () {
  47274. var data = this.data;
  47275. var el = this.el;
  47276. if (el.sceneEl.hasWebXR) {
  47277. el.setAttribute('tracked-controls-webxr', data);
  47278. } else {
  47279. el.setAttribute('tracked-controls-webvr', data);
  47280. }
  47281. }
  47282. });
  47283. },{"../core/component":103}],90:[function(_dereq_,module,exports){
  47284. var registerComponent = _dereq_('../core/component').registerComponent;
  47285. /**
  47286. * Visibility component.
  47287. */
  47288. module.exports.Component = registerComponent('visible', {
  47289. schema: {default: true},
  47290. update: function () {
  47291. this.el.object3D.visible = this.data;
  47292. }
  47293. });
  47294. },{"../core/component":103}],91:[function(_dereq_,module,exports){
  47295. var registerComponent = _dereq_('../core/component').registerComponent;
  47296. var bind = _dereq_('../utils/bind');
  47297. var trackedControlsUtils = _dereq_('../utils/tracked-controls');
  47298. var checkControllerPresentAndSetup = trackedControlsUtils.checkControllerPresentAndSetup;
  47299. var emitIfAxesChanged = trackedControlsUtils.emitIfAxesChanged;
  47300. var onButtonEvent = trackedControlsUtils.onButtonEvent;
  47301. var VIVE_CONTROLLER_MODEL_OBJ_URL = 'https://cdn.aframe.io/controllers/vive/vr_controller_vive.obj';
  47302. var VIVE_CONTROLLER_MODEL_OBJ_MTL = 'https://cdn.aframe.io/controllers/vive/vr_controller_vive.mtl';
  47303. var GAMEPAD_ID_PREFIX = 'OpenVR ';
  47304. /**
  47305. * Vive controls.
  47306. * Interface with Vive controllers and map Gamepad events to controller buttons:
  47307. * trackpad, trigger, grip, menu, system
  47308. * Load a controller model and highlight the pressed buttons.
  47309. */
  47310. module.exports.Component = registerComponent('vive-controls', {
  47311. schema: {
  47312. hand: {default: 'left'},
  47313. buttonColor: {type: 'color', default: '#FAFAFA'}, // Off-white.
  47314. buttonHighlightColor: {type: 'color', default: '#22D1EE'}, // Light blue.
  47315. model: {default: true},
  47316. orientationOffset: {type: 'vec3'}
  47317. },
  47318. /**
  47319. * Button IDs:
  47320. * 0 - trackpad
  47321. * 1 - trigger (intensity value from 0.5 to 1)
  47322. * 2 - grip
  47323. * 3 - menu (dispatch but better for menu options)
  47324. * 4 - system (never dispatched on this layer)
  47325. */
  47326. mapping: {
  47327. axes: {trackpad: [0, 1]},
  47328. buttons: ['trackpad', 'trigger', 'grip', 'menu', 'system']
  47329. },
  47330. init: function () {
  47331. var self = this;
  47332. this.controllerPresent = false;
  47333. this.lastControllerCheck = 0;
  47334. this.onButtonChanged = bind(this.onButtonChanged, this);
  47335. this.onButtonDown = function (evt) { onButtonEvent(evt.detail.id, 'down', self); };
  47336. this.onButtonUp = function (evt) { onButtonEvent(evt.detail.id, 'up', self); };
  47337. this.onButtonTouchEnd = function (evt) { onButtonEvent(evt.detail.id, 'touchend', self); };
  47338. this.onButtonTouchStart = function (evt) { onButtonEvent(evt.detail.id, 'touchstart', self); };
  47339. this.previousButtonValues = {};
  47340. this.rendererSystem = this.el.sceneEl.systems.renderer;
  47341. this.bindMethods();
  47342. },
  47343. play: function () {
  47344. this.checkIfControllerPresent();
  47345. this.addControllersUpdateListener();
  47346. },
  47347. pause: function () {
  47348. this.removeEventListeners();
  47349. this.removeControllersUpdateListener();
  47350. },
  47351. bindMethods: function () {
  47352. this.onModelLoaded = bind(this.onModelLoaded, this);
  47353. this.onControllersUpdate = bind(this.onControllersUpdate, this);
  47354. this.checkIfControllerPresent = bind(this.checkIfControllerPresent, this);
  47355. this.removeControllersUpdateListener = bind(this.removeControllersUpdateListener, this);
  47356. this.onAxisMoved = bind(this.onAxisMoved, this);
  47357. },
  47358. addEventListeners: function () {
  47359. var el = this.el;
  47360. el.addEventListener('buttonchanged', this.onButtonChanged);
  47361. el.addEventListener('buttondown', this.onButtonDown);
  47362. el.addEventListener('buttonup', this.onButtonUp);
  47363. el.addEventListener('touchend', this.onButtonTouchEnd);
  47364. el.addEventListener('touchstart', this.onButtonTouchStart);
  47365. el.addEventListener('model-loaded', this.onModelLoaded);
  47366. el.addEventListener('axismove', this.onAxisMoved);
  47367. this.controllerEventsActive = true;
  47368. },
  47369. removeEventListeners: function () {
  47370. var el = this.el;
  47371. el.removeEventListener('buttonchanged', this.onButtonChanged);
  47372. el.removeEventListener('buttondown', this.onButtonDown);
  47373. el.removeEventListener('buttonup', this.onButtonUp);
  47374. el.removeEventListener('touchend', this.onButtonTouchEnd);
  47375. el.removeEventListener('touchstart', this.onButtonTouchStart);
  47376. el.removeEventListener('model-loaded', this.onModelLoaded);
  47377. el.removeEventListener('axismove', this.onAxisMoved);
  47378. this.controllerEventsActive = false;
  47379. },
  47380. /**
  47381. * Once OpenVR returns correct hand data in supporting browsers, we can use hand property.
  47382. * var isPresent = checkControllerPresentAndSetup(this.el.sceneEl, GAMEPAD_ID_PREFIX,
  47383. { hand: data.hand });
  47384. * Until then, use hardcoded index.
  47385. */
  47386. checkIfControllerPresent: function () {
  47387. var data = this.data;
  47388. var controllerIndex = data.hand === 'right' ? 0 : data.hand === 'left' ? 1 : 2;
  47389. checkControllerPresentAndSetup(this, GAMEPAD_ID_PREFIX, {index: controllerIndex});
  47390. },
  47391. injectTrackedControls: function () {
  47392. var el = this.el;
  47393. var data = this.data;
  47394. // If we have an OpenVR Gamepad, use the fixed mapping.
  47395. el.setAttribute('tracked-controls', {
  47396. idPrefix: GAMEPAD_ID_PREFIX,
  47397. // Hand IDs: 1 = right, 0 = left, 2 = anything else.
  47398. controller: data.hand === 'right' ? 1 : data.hand === 'left' ? 0 : 2,
  47399. orientationOffset: data.orientationOffset
  47400. });
  47401. // Load model.
  47402. if (!this.data.model) { return; }
  47403. this.el.setAttribute('obj-model', {
  47404. obj: VIVE_CONTROLLER_MODEL_OBJ_URL,
  47405. mtl: VIVE_CONTROLLER_MODEL_OBJ_MTL
  47406. });
  47407. },
  47408. addControllersUpdateListener: function () {
  47409. this.el.sceneEl.addEventListener('controllersupdated', this.onControllersUpdate, false);
  47410. },
  47411. removeControllersUpdateListener: function () {
  47412. this.el.sceneEl.removeEventListener('controllersupdated', this.onControllersUpdate, false);
  47413. },
  47414. onControllersUpdate: function () {
  47415. this.checkIfControllerPresent();
  47416. },
  47417. /**
  47418. * Rotate the trigger button based on how hard the trigger is pressed.
  47419. */
  47420. onButtonChanged: function (evt) {
  47421. var button = this.mapping.buttons[evt.detail.id];
  47422. var buttonMeshes = this.buttonMeshes;
  47423. var analogValue;
  47424. if (!button) { return; }
  47425. if (button === 'trigger') {
  47426. analogValue = evt.detail.state.value;
  47427. // Update trigger rotation depending on button value.
  47428. if (buttonMeshes && buttonMeshes.trigger) {
  47429. buttonMeshes.trigger.rotation.x = -analogValue * (Math.PI / 12);
  47430. }
  47431. }
  47432. // Pass along changed event with button state, using button mapping for convenience.
  47433. this.el.emit(button + 'changed', evt.detail.state);
  47434. },
  47435. onModelLoaded: function (evt) {
  47436. var buttonMeshes;
  47437. var controllerObject3D = evt.detail.model;
  47438. var self = this;
  47439. if (!this.data.model) { return; }
  47440. // Store button meshes object to be able to change their colors.
  47441. buttonMeshes = this.buttonMeshes = {};
  47442. buttonMeshes.grip = {
  47443. left: controllerObject3D.getObjectByName('leftgrip'),
  47444. right: controllerObject3D.getObjectByName('rightgrip')
  47445. };
  47446. buttonMeshes.menu = controllerObject3D.getObjectByName('menubutton');
  47447. buttonMeshes.system = controllerObject3D.getObjectByName('systembutton');
  47448. buttonMeshes.trackpad = controllerObject3D.getObjectByName('touchpad');
  47449. buttonMeshes.trigger = controllerObject3D.getObjectByName('trigger');
  47450. // Set default colors.
  47451. Object.keys(buttonMeshes).forEach(function (buttonName) {
  47452. self.setButtonColor(buttonName, self.data.buttonColor);
  47453. });
  47454. // Offset pivot point.
  47455. controllerObject3D.position.set(0, -0.015, 0.04);
  47456. },
  47457. onAxisMoved: function (evt) {
  47458. emitIfAxesChanged(this, this.mapping.axes, evt);
  47459. },
  47460. updateModel: function (buttonName, evtName) {
  47461. var color;
  47462. var isTouch;
  47463. if (!this.data.model) { return; }
  47464. isTouch = evtName.indexOf('touch') !== -1;
  47465. // Don't change color for trackpad touch.
  47466. if (isTouch) { return; }
  47467. // Update colors.
  47468. color = evtName === 'up' ? this.data.buttonColor : this.data.buttonHighlightColor;
  47469. this.setButtonColor(buttonName, color);
  47470. },
  47471. setButtonColor: function (buttonName, color) {
  47472. var buttonMeshes = this.buttonMeshes;
  47473. var rendererSystem = this.rendererSystem;
  47474. if (!buttonMeshes) { return; }
  47475. // Need to do both left and right sides for grip.
  47476. if (buttonName === 'grip') {
  47477. buttonMeshes.grip.left.material.color.set(color);
  47478. buttonMeshes.grip.right.material.color.set(color);
  47479. rendererSystem.applyColorCorrection(buttonMeshes.grip.left.material.color);
  47480. rendererSystem.applyColorCorrection(buttonMeshes.grip.right.material.color);
  47481. return;
  47482. }
  47483. buttonMeshes[buttonName].material.color.set(color);
  47484. rendererSystem.applyColorCorrection(buttonMeshes[buttonName].material.color);
  47485. }
  47486. });
  47487. },{"../core/component":103,"../utils/bind":170,"../utils/tracked-controls":184}],92:[function(_dereq_,module,exports){
  47488. var registerComponent = _dereq_('../core/component').registerComponent;
  47489. var bind = _dereq_('../utils/bind');
  47490. var trackedControlsUtils = _dereq_('../utils/tracked-controls');
  47491. var checkControllerPresentAndSetup = trackedControlsUtils.checkControllerPresentAndSetup;
  47492. var emitIfAxesChanged = trackedControlsUtils.emitIfAxesChanged;
  47493. var onButtonEvent = trackedControlsUtils.onButtonEvent;
  47494. var GAMEPAD_ID_PREFIX = 'HTC Vive Focus';
  47495. var VIVE_FOCUS_CONTROLLER_MODEL_URL = 'https://cdn.aframe.io/controllers/vive/focus-controller/focus-controller.gltf';
  47496. /**
  47497. * Vive Focus controls.
  47498. * Interface with Vive Focus controller and map Gamepad events to
  47499. * controller buttons: trackpad, trigger
  47500. * Load a controller model and highlight the pressed buttons.
  47501. */
  47502. module.exports.Component = registerComponent('vive-focus-controls', {
  47503. schema: {
  47504. hand: {default: ''}, // This informs the degenerate arm model.
  47505. buttonTouchedColor: {type: 'color', default: '#BBBBBB'},
  47506. buttonHighlightColor: {type: 'color', default: '#7A7A7A'},
  47507. model: {default: true},
  47508. orientationOffset: {type: 'vec3'},
  47509. armModel: {default: true}
  47510. },
  47511. /**
  47512. * Button IDs:
  47513. * 0 - trackpad
  47514. * 1 - trigger
  47515. */
  47516. mapping: {
  47517. axes: {trackpad: [0, 1]},
  47518. buttons: ['trigger', 'trackpad']
  47519. },
  47520. bindMethods: function () {
  47521. this.onModelLoaded = bind(this.onModelLoaded, this);
  47522. this.onControllersUpdate = bind(this.onControllersUpdate, this);
  47523. this.checkIfControllerPresent = bind(this.checkIfControllerPresent, this);
  47524. this.removeControllersUpdateListener = bind(this.removeControllersUpdateListener, this);
  47525. this.onAxisMoved = bind(this.onAxisMoved, this);
  47526. },
  47527. init: function () {
  47528. var self = this;
  47529. this.onButtonChanged = bind(this.onButtonChanged, this);
  47530. this.onButtonDown = function (evt) { onButtonEvent(evt.detail.id, 'down', self); };
  47531. this.onButtonUp = function (evt) { onButtonEvent(evt.detail.id, 'up', self); };
  47532. this.onButtonTouchStart = function (evt) { onButtonEvent(evt.detail.id, 'touchstart', self); };
  47533. this.onButtonTouchEnd = function (evt) { onButtonEvent(evt.detail.id, 'touchend', self); };
  47534. this.controllerPresent = false;
  47535. this.lastControllerCheck = 0;
  47536. this.bindMethods();
  47537. },
  47538. addEventListeners: function () {
  47539. var el = this.el;
  47540. el.addEventListener('buttonchanged', this.onButtonChanged);
  47541. el.addEventListener('buttondown', this.onButtonDown);
  47542. el.addEventListener('buttonup', this.onButtonUp);
  47543. el.addEventListener('touchstart', this.onButtonTouchStart);
  47544. el.addEventListener('touchend', this.onButtonTouchEnd);
  47545. el.addEventListener('model-loaded', this.onModelLoaded);
  47546. el.addEventListener('axismove', this.onAxisMoved);
  47547. this.controllerEventsActive = true;
  47548. this.addControllersUpdateListener();
  47549. },
  47550. removeEventListeners: function () {
  47551. var el = this.el;
  47552. el.removeEventListener('buttonchanged', this.onButtonChanged);
  47553. el.removeEventListener('buttondown', this.onButtonDown);
  47554. el.removeEventListener('buttonup', this.onButtonUp);
  47555. el.removeEventListener('touchstart', this.onButtonTouchStart);
  47556. el.removeEventListener('touchend', this.onButtonTouchEnd);
  47557. el.removeEventListener('model-loaded', this.onModelLoaded);
  47558. el.removeEventListener('axismove', this.onAxisMoved);
  47559. this.controllerEventsActive = false;
  47560. this.removeControllersUpdateListener();
  47561. },
  47562. checkIfControllerPresent: function () {
  47563. checkControllerPresentAndSetup(this, GAMEPAD_ID_PREFIX,
  47564. this.data.hand ? {hand: this.data.hand} : {});
  47565. },
  47566. play: function () {
  47567. this.checkIfControllerPresent();
  47568. this.addControllersUpdateListener();
  47569. },
  47570. pause: function () {
  47571. this.removeEventListeners();
  47572. this.removeControllersUpdateListener();
  47573. },
  47574. injectTrackedControls: function () {
  47575. var el = this.el;
  47576. var data = this.data;
  47577. el.setAttribute('tracked-controls', {
  47578. armModel: data.armModel,
  47579. idPrefix: GAMEPAD_ID_PREFIX,
  47580. orientationOffset: data.orientationOffset
  47581. });
  47582. if (!this.data.model) { return; }
  47583. this.el.setAttribute('gltf-model', VIVE_FOCUS_CONTROLLER_MODEL_URL);
  47584. },
  47585. addControllersUpdateListener: function () {
  47586. this.el.sceneEl.addEventListener('controllersupdated', this.onControllersUpdate, false);
  47587. },
  47588. removeControllersUpdateListener: function () {
  47589. this.el.sceneEl.removeEventListener('controllersupdated', this.onControllersUpdate, false);
  47590. },
  47591. onControllersUpdate: function () {
  47592. this.checkIfControllerPresent();
  47593. },
  47594. onModelLoaded: function (evt) {
  47595. var controllerObject3D = evt.detail.model;
  47596. var buttonMeshes;
  47597. if (!this.data.model) { return; }
  47598. buttonMeshes = this.buttonMeshes = {};
  47599. buttonMeshes.trigger = controllerObject3D.getObjectByName('BumperKey');
  47600. buttonMeshes.triggerPressed = controllerObject3D.getObjectByName('BumperKey_Press');
  47601. if (buttonMeshes.triggerPressed) {
  47602. buttonMeshes.triggerPressed.visible = false;
  47603. }
  47604. buttonMeshes.trackpad = controllerObject3D.getObjectByName('TouchPad');
  47605. buttonMeshes.trackpadPressed = controllerObject3D.getObjectByName('TouchPad_Press');
  47606. if (buttonMeshes.trackpadPressed) {
  47607. buttonMeshes.trackpadPressed.visible = false;
  47608. }
  47609. },
  47610. // No analog buttons, only emits 0/1 values
  47611. onButtonChanged: function (evt) {
  47612. var button = this.mapping.buttons[evt.detail.id];
  47613. if (!button) return;
  47614. // Pass along changed event with button state, using button mapping for convenience.
  47615. this.el.emit(button + 'changed', evt.detail.state);
  47616. },
  47617. onAxisMoved: function (evt) {
  47618. emitIfAxesChanged(this, this.mapping.axes, evt);
  47619. },
  47620. updateModel: function (buttonName, evtName) {
  47621. if (!this.data.model) { return; }
  47622. this.updateButtonModel(buttonName, evtName);
  47623. },
  47624. updateButtonModel: function (buttonName, state) {
  47625. var buttonMeshes = this.buttonMeshes;
  47626. var pressedName = buttonName + 'Pressed';
  47627. if (!buttonMeshes || !buttonMeshes[buttonName] || !buttonMeshes[pressedName]) {
  47628. return;
  47629. }
  47630. var color;
  47631. switch (state) {
  47632. case 'down':
  47633. color = this.data.buttonHighlightColor;
  47634. break;
  47635. case 'touchstart':
  47636. color = this.data.buttonTouchedColor;
  47637. break;
  47638. }
  47639. if (color) {
  47640. buttonMeshes[pressedName].material.color.set(color);
  47641. }
  47642. buttonMeshes[pressedName].visible = !!color;
  47643. buttonMeshes[buttonName].visible = !color;
  47644. }
  47645. });
  47646. },{"../core/component":103,"../utils/bind":170,"../utils/tracked-controls":184}],93:[function(_dereq_,module,exports){
  47647. var KEYCODE_TO_CODE = _dereq_('../constants').keyboardevent.KEYCODE_TO_CODE;
  47648. var registerComponent = _dereq_('../core/component').registerComponent;
  47649. var THREE = _dereq_('../lib/three');
  47650. var utils = _dereq_('../utils/');
  47651. var bind = utils.bind;
  47652. var shouldCaptureKeyEvent = utils.shouldCaptureKeyEvent;
  47653. var CLAMP_VELOCITY = 0.00001;
  47654. var MAX_DELTA = 0.2;
  47655. var KEYS = [
  47656. 'KeyW', 'KeyA', 'KeyS', 'KeyD',
  47657. 'ArrowUp', 'ArrowLeft', 'ArrowRight', 'ArrowDown'
  47658. ];
  47659. /**
  47660. * WASD component to control entities using WASD keys.
  47661. */
  47662. module.exports.Component = registerComponent('wasd-controls', {
  47663. schema: {
  47664. acceleration: {default: 65},
  47665. adAxis: {default: 'x', oneOf: ['x', 'y', 'z']},
  47666. adEnabled: {default: true},
  47667. adInverted: {default: false},
  47668. enabled: {default: true},
  47669. fly: {default: false},
  47670. wsAxis: {default: 'z', oneOf: ['x', 'y', 'z']},
  47671. wsEnabled: {default: true},
  47672. wsInverted: {default: false}
  47673. },
  47674. init: function () {
  47675. // To keep track of the pressed keys.
  47676. this.keys = {};
  47677. this.easing = 1.1;
  47678. this.velocity = new THREE.Vector3();
  47679. // Bind methods and add event listeners.
  47680. this.onBlur = bind(this.onBlur, this);
  47681. this.onFocus = bind(this.onFocus, this);
  47682. this.onKeyDown = bind(this.onKeyDown, this);
  47683. this.onKeyUp = bind(this.onKeyUp, this);
  47684. this.onVisibilityChange = bind(this.onVisibilityChange, this);
  47685. this.attachVisibilityEventListeners();
  47686. },
  47687. tick: function (time, delta) {
  47688. var data = this.data;
  47689. var el = this.el;
  47690. var velocity = this.velocity;
  47691. if (!velocity[data.adAxis] && !velocity[data.wsAxis] &&
  47692. isEmptyObject(this.keys)) { return; }
  47693. // Update velocity.
  47694. delta = delta / 1000;
  47695. this.updateVelocity(delta);
  47696. if (!velocity[data.adAxis] && !velocity[data.wsAxis]) { return; }
  47697. // Get movement vector and translate position.
  47698. el.object3D.position.add(this.getMovementVector(delta));
  47699. },
  47700. remove: function () {
  47701. this.removeKeyEventListeners();
  47702. this.removeVisibilityEventListeners();
  47703. },
  47704. play: function () {
  47705. this.attachKeyEventListeners();
  47706. },
  47707. pause: function () {
  47708. this.keys = {};
  47709. this.removeKeyEventListeners();
  47710. },
  47711. updateVelocity: function (delta) {
  47712. var acceleration;
  47713. var adAxis;
  47714. var adSign;
  47715. var data = this.data;
  47716. var keys = this.keys;
  47717. var velocity = this.velocity;
  47718. var wsAxis;
  47719. var wsSign;
  47720. adAxis = data.adAxis;
  47721. wsAxis = data.wsAxis;
  47722. // If FPS too low, reset velocity.
  47723. if (delta > MAX_DELTA) {
  47724. velocity[adAxis] = 0;
  47725. velocity[wsAxis] = 0;
  47726. return;
  47727. }
  47728. // https://gamedev.stackexchange.com/questions/151383/frame-rate-independant-movement-with-acceleration
  47729. var scaledEasing = Math.pow(1 / this.easing, delta * 60);
  47730. // Velocity Easing.
  47731. if (velocity[adAxis] !== 0) {
  47732. velocity[adAxis] -= velocity[adAxis] * scaledEasing;
  47733. }
  47734. if (velocity[wsAxis] !== 0) {
  47735. velocity[wsAxis] -= velocity[wsAxis] * scaledEasing;
  47736. }
  47737. // Clamp velocity easing.
  47738. if (Math.abs(velocity[adAxis]) < CLAMP_VELOCITY) { velocity[adAxis] = 0; }
  47739. if (Math.abs(velocity[wsAxis]) < CLAMP_VELOCITY) { velocity[wsAxis] = 0; }
  47740. if (!data.enabled) { return; }
  47741. // Update velocity using keys pressed.
  47742. acceleration = data.acceleration;
  47743. if (data.adEnabled) {
  47744. adSign = data.adInverted ? -1 : 1;
  47745. if (keys.KeyA || keys.ArrowLeft) { velocity[adAxis] -= adSign * acceleration * delta; }
  47746. if (keys.KeyD || keys.ArrowRight) { velocity[adAxis] += adSign * acceleration * delta; }
  47747. }
  47748. if (data.wsEnabled) {
  47749. wsSign = data.wsInverted ? -1 : 1;
  47750. if (keys.KeyW || keys.ArrowUp) { velocity[wsAxis] -= wsSign * acceleration * delta; }
  47751. if (keys.KeyS || keys.ArrowDown) { velocity[wsAxis] += wsSign * acceleration * delta; }
  47752. }
  47753. },
  47754. getMovementVector: (function () {
  47755. var directionVector = new THREE.Vector3(0, 0, 0);
  47756. var rotationEuler = new THREE.Euler(0, 0, 0, 'YXZ');
  47757. return function (delta) {
  47758. var rotation = this.el.getAttribute('rotation');
  47759. var velocity = this.velocity;
  47760. var xRotation;
  47761. directionVector.copy(velocity);
  47762. directionVector.multiplyScalar(delta);
  47763. // Absolute.
  47764. if (!rotation) { return directionVector; }
  47765. xRotation = this.data.fly ? rotation.x : 0;
  47766. // Transform direction relative to heading.
  47767. rotationEuler.set(THREE.Math.degToRad(xRotation), THREE.Math.degToRad(rotation.y), 0);
  47768. directionVector.applyEuler(rotationEuler);
  47769. return directionVector;
  47770. };
  47771. })(),
  47772. attachVisibilityEventListeners: function () {
  47773. window.addEventListener('blur', this.onBlur);
  47774. window.addEventListener('focus', this.onFocus);
  47775. document.addEventListener('visibilitychange', this.onVisibilityChange);
  47776. },
  47777. removeVisibilityEventListeners: function () {
  47778. window.removeEventListener('blur', this.onBlur);
  47779. window.removeEventListener('focus', this.onFocus);
  47780. document.removeEventListener('visibilitychange', this.onVisibilityChange);
  47781. },
  47782. attachKeyEventListeners: function () {
  47783. window.addEventListener('keydown', this.onKeyDown);
  47784. window.addEventListener('keyup', this.onKeyUp);
  47785. },
  47786. removeKeyEventListeners: function () {
  47787. window.removeEventListener('keydown', this.onKeyDown);
  47788. window.removeEventListener('keyup', this.onKeyUp);
  47789. },
  47790. onBlur: function () {
  47791. this.pause();
  47792. },
  47793. onFocus: function () {
  47794. this.play();
  47795. },
  47796. onVisibilityChange: function () {
  47797. if (document.hidden) {
  47798. this.onBlur();
  47799. } else {
  47800. this.onFocus();
  47801. }
  47802. },
  47803. onKeyDown: function (event) {
  47804. var code;
  47805. if (!shouldCaptureKeyEvent(event)) { return; }
  47806. code = event.code || KEYCODE_TO_CODE[event.keyCode];
  47807. if (KEYS.indexOf(code) !== -1) { this.keys[code] = true; }
  47808. },
  47809. onKeyUp: function (event) {
  47810. var code;
  47811. code = event.code || KEYCODE_TO_CODE[event.keyCode];
  47812. delete this.keys[code];
  47813. }
  47814. });
  47815. function isEmptyObject (keys) {
  47816. var key;
  47817. for (key in keys) { return false; }
  47818. return true;
  47819. }
  47820. },{"../constants":95,"../core/component":103,"../lib/three":151,"../utils/":176}],94:[function(_dereq_,module,exports){
  47821. /* global THREE */
  47822. var registerComponent = _dereq_('../core/component').registerComponent;
  47823. var bind = _dereq_('../utils/bind');
  47824. var trackedControlsUtils = _dereq_('../utils/tracked-controls');
  47825. var checkControllerPresentAndSetup = trackedControlsUtils.checkControllerPresentAndSetup;
  47826. var emitIfAxesChanged = trackedControlsUtils.emitIfAxesChanged;
  47827. var onButtonEvent = trackedControlsUtils.onButtonEvent;
  47828. var utils = _dereq_('../utils/');
  47829. var debug = utils.debug('components:windows-motion-controls:debug');
  47830. var warn = utils.debug('components:windows-motion-controls:warn');
  47831. var DEFAULT_HANDEDNESS = _dereq_('../constants').DEFAULT_HANDEDNESS;
  47832. var MODEL_BASE_URL = 'https://cdn.aframe.io/controllers/microsoft/';
  47833. var MODEL_FILENAMES = { left: 'left.glb', right: 'right.glb', default: 'universal.glb' };
  47834. var GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  47835. var GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  47836. /**
  47837. * Windows Motion Controller controls.
  47838. * Interface with Windows Motion Controller controllers and map Gamepad events to
  47839. * controller buttons: trackpad, trigger, grip, menu, thumbstick
  47840. * Load a controller model and transform the pressed buttons.
  47841. */
  47842. module.exports.Component = registerComponent('windows-motion-controls', {
  47843. schema: {
  47844. hand: {default: DEFAULT_HANDEDNESS},
  47845. // It is possible to have multiple pairs of controllers attached (a pair has both left and right).
  47846. // Set this to 1 to use a controller from the second pair, 2 from the third pair, etc.
  47847. pair: {default: 0},
  47848. // If true, loads the controller glTF asset.
  47849. model: {default: true},
  47850. // If true, will hide the model from the scene if no matching gamepad (based on ID & hand) is connected.
  47851. hideDisconnected: {default: true}
  47852. },
  47853. mapping: {
  47854. // A-Frame specific semantic axis names
  47855. axes: {'thumbstick': [0, 1], 'trackpad': [2, 3]},
  47856. // A-Frame specific semantic button names
  47857. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  47858. // A mapping of the semantic name to node name in the glTF model file,
  47859. // that should be transformed by axis value.
  47860. // This array mirrors the browser Gamepad.axes array, such that
  47861. // the mesh corresponding to axis 0 is in this array index 0.
  47862. axisMeshNames: [
  47863. 'THUMBSTICK_X',
  47864. 'THUMBSTICK_Y',
  47865. 'TOUCHPAD_TOUCH_X',
  47866. 'TOUCHPAD_TOUCH_Y'
  47867. ],
  47868. // A mapping of the semantic name to button node name in the glTF model file,
  47869. // that should be transformed by button value.
  47870. buttonMeshNames: {
  47871. 'trigger': 'SELECT',
  47872. 'menu': 'MENU',
  47873. 'grip': 'GRASP',
  47874. 'thumbstick': 'THUMBSTICK_PRESS',
  47875. 'trackpad': 'TOUCHPAD_PRESS'
  47876. },
  47877. pointingPoseMeshName: 'POINTING_POSE'
  47878. },
  47879. bindMethods: function () {
  47880. this.onModelError = bind(this.onModelError, this);
  47881. this.onModelLoaded = bind(this.onModelLoaded, this);
  47882. this.onControllersUpdate = bind(this.onControllersUpdate, this);
  47883. this.checkIfControllerPresent = bind(this.checkIfControllerPresent, this);
  47884. this.onAxisMoved = bind(this.onAxisMoved, this);
  47885. },
  47886. init: function () {
  47887. var self = this;
  47888. var el = this.el;
  47889. this.onButtonChanged = bind(this.onButtonChanged, this);
  47890. this.onButtonDown = function (evt) { onButtonEvent(evt.detail.id, 'down', self); };
  47891. this.onButtonUp = function (evt) { onButtonEvent(evt.detail.id, 'up', self); };
  47892. this.onButtonTouchStart = function (evt) { onButtonEvent(evt.detail.id, 'touchstart', self); };
  47893. this.onButtonTouchEnd = function (evt) { onButtonEvent(evt.detail.id, 'touchend', self); };
  47894. this.onControllerConnected = function () { self.setModelVisibility(true); };
  47895. this.onControllerDisconnected = function () { self.setModelVisibility(false); };
  47896. this.controllerPresent = false;
  47897. this.lastControllerCheck = 0;
  47898. this.previousButtonValues = {};
  47899. this.bindMethods();
  47900. // Cache for submeshes that we have looked up by name.
  47901. this.loadedMeshInfo = {
  47902. buttonMeshes: null,
  47903. axisMeshes: null
  47904. };
  47905. // Pointing poses
  47906. this.rayOrigin = {
  47907. origin: new THREE.Vector3(),
  47908. direction: new THREE.Vector3(0, 0, -1),
  47909. createdFromMesh: false
  47910. };
  47911. el.addEventListener('controllerconnected', this.onControllerConnected);
  47912. el.addEventListener('controllerdisconnected', this.onControllerDisconnected);
  47913. },
  47914. addEventListeners: function () {
  47915. var el = this.el;
  47916. el.addEventListener('buttonchanged', this.onButtonChanged);
  47917. el.addEventListener('buttondown', this.onButtonDown);
  47918. el.addEventListener('buttonup', this.onButtonUp);
  47919. el.addEventListener('touchstart', this.onButtonTouchStart);
  47920. el.addEventListener('touchend', this.onButtonTouchEnd);
  47921. el.addEventListener('axismove', this.onAxisMoved);
  47922. el.addEventListener('model-error', this.onModelError);
  47923. el.addEventListener('model-loaded', this.onModelLoaded);
  47924. this.controllerEventsActive = true;
  47925. },
  47926. removeEventListeners: function () {
  47927. var el = this.el;
  47928. el.removeEventListener('buttonchanged', this.onButtonChanged);
  47929. el.removeEventListener('buttondown', this.onButtonDown);
  47930. el.removeEventListener('buttonup', this.onButtonUp);
  47931. el.removeEventListener('touchstart', this.onButtonTouchStart);
  47932. el.removeEventListener('touchend', this.onButtonTouchEnd);
  47933. el.removeEventListener('axismove', this.onAxisMoved);
  47934. el.removeEventListener('model-error', this.onModelError);
  47935. el.removeEventListener('model-loaded', this.onModelLoaded);
  47936. this.controllerEventsActive = false;
  47937. },
  47938. checkIfControllerPresent: function () {
  47939. checkControllerPresentAndSetup(this, GAMEPAD_ID_PREFIX, {
  47940. hand: this.data.hand,
  47941. index: this.data.pair
  47942. });
  47943. },
  47944. play: function () {
  47945. this.checkIfControllerPresent();
  47946. this.addControllersUpdateListener();
  47947. },
  47948. pause: function () {
  47949. this.removeEventListeners();
  47950. this.removeControllersUpdateListener();
  47951. },
  47952. updateControllerModel: function () {
  47953. // If we do not want to load a model, or, have already loaded the model, emit the controllermodelready event.
  47954. if (!this.data.model || this.rayOrigin.createdFromMesh) {
  47955. this.modelReady();
  47956. return;
  47957. }
  47958. var sourceUrl = this.createControllerModelUrl();
  47959. this.loadModel(sourceUrl);
  47960. },
  47961. /**
  47962. * Helper function that constructs a URL from the controller ID suffix, for future proofed
  47963. * art assets.
  47964. */
  47965. createControllerModelUrl: function (forceDefault) {
  47966. // Determine the device specific folder based on the ID suffix
  47967. var trackedControlsComponent = this.el.components['tracked-controls'];
  47968. var controller = trackedControlsComponent ? trackedControlsComponent.controller : null;
  47969. var device = 'default';
  47970. var hand = this.data.hand;
  47971. var filename;
  47972. if (controller) {
  47973. // Read hand directly from the controller, rather than this.data, as in the case that the controller
  47974. // is unhanded this.data will still have 'left' or 'right' (depending on what the user inserted in to the scene).
  47975. // In this case, we want to load the universal model, so need to get the '' from the controller.
  47976. hand = controller.hand;
  47977. if (!forceDefault) {
  47978. var match = controller.id.match(GAMEPAD_ID_PATTERN);
  47979. device = ((match && match[0]) || device);
  47980. }
  47981. }
  47982. // Hand
  47983. filename = MODEL_FILENAMES[hand] || MODEL_FILENAMES.default;
  47984. // Final url
  47985. return MODEL_BASE_URL + device + '/' + filename;
  47986. },
  47987. injectTrackedControls: function () {
  47988. var data = this.data;
  47989. this.el.setAttribute('tracked-controls', {
  47990. idPrefix: GAMEPAD_ID_PREFIX,
  47991. controller: data.pair,
  47992. hand: data.hand,
  47993. armModel: false
  47994. });
  47995. this.updateControllerModel();
  47996. },
  47997. addControllersUpdateListener: function () {
  47998. this.el.sceneEl.addEventListener('controllersupdated', this.onControllersUpdate, false);
  47999. },
  48000. removeControllersUpdateListener: function () {
  48001. this.el.sceneEl.removeEventListener('controllersupdated', this.onControllersUpdate, false);
  48002. },
  48003. onControllersUpdate: function () {
  48004. this.checkIfControllerPresent();
  48005. },
  48006. onModelError: function (evt) {
  48007. var defaultUrl = this.createControllerModelUrl(true);
  48008. if (evt.detail.src !== defaultUrl) {
  48009. warn('Failed to load controller model for device, attempting to load default.');
  48010. this.loadModel(defaultUrl);
  48011. } else {
  48012. warn('Failed to load default controller model.');
  48013. }
  48014. },
  48015. loadModel: function (url) {
  48016. // The model is loaded by the gltf-model compoent when this attribute is initially set,
  48017. // removed and re-loaded if the given url changes.
  48018. this.el.setAttribute('gltf-model', 'url(' + url + ')');
  48019. },
  48020. onModelLoaded: function (evt) {
  48021. var rootNode = this.controllerModel = evt.detail.model;
  48022. var loadedMeshInfo = this.loadedMeshInfo;
  48023. var i;
  48024. var meshName;
  48025. var mesh;
  48026. var meshInfo;
  48027. debug('Processing model');
  48028. // Reset the caches
  48029. loadedMeshInfo.buttonMeshes = {};
  48030. loadedMeshInfo.axisMeshes = {};
  48031. // Cache our meshes so we aren't traversing the hierarchy per frame
  48032. if (rootNode) {
  48033. // Button Meshes
  48034. for (i = 0; i < this.mapping.buttons.length; i++) {
  48035. meshName = this.mapping.buttonMeshNames[this.mapping.buttons[i]];
  48036. if (!meshName) {
  48037. debug('Skipping unknown button at index: ' + i + ' with mapped name: ' + this.mapping.buttons[i]);
  48038. continue;
  48039. }
  48040. mesh = rootNode.getObjectByName(meshName);
  48041. if (!mesh) {
  48042. warn('Missing button mesh with name: ' + meshName);
  48043. continue;
  48044. }
  48045. meshInfo = {
  48046. index: i,
  48047. value: getImmediateChildByName(mesh, 'VALUE'),
  48048. pressed: getImmediateChildByName(mesh, 'PRESSED'),
  48049. unpressed: getImmediateChildByName(mesh, 'UNPRESSED')
  48050. };
  48051. if (meshInfo.value && meshInfo.pressed && meshInfo.unpressed) {
  48052. loadedMeshInfo.buttonMeshes[this.mapping.buttons[i]] = meshInfo;
  48053. } else {
  48054. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  48055. warn('Missing button submesh under mesh with name: ' + meshName +
  48056. '(VALUE: ' + !!meshInfo.value +
  48057. ', PRESSED: ' + !!meshInfo.pressed +
  48058. ', UNPRESSED:' + !!meshInfo.unpressed +
  48059. ')');
  48060. }
  48061. }
  48062. // Axis Meshes
  48063. for (i = 0; i < this.mapping.axisMeshNames.length; i++) {
  48064. meshName = this.mapping.axisMeshNames[i];
  48065. if (!meshName) {
  48066. debug('Skipping unknown axis at index: ' + i);
  48067. continue;
  48068. }
  48069. mesh = rootNode.getObjectByName(meshName);
  48070. if (!mesh) {
  48071. warn('Missing axis mesh with name: ' + meshName);
  48072. continue;
  48073. }
  48074. meshInfo = {
  48075. index: i,
  48076. value: getImmediateChildByName(mesh, 'VALUE'),
  48077. min: getImmediateChildByName(mesh, 'MIN'),
  48078. max: getImmediateChildByName(mesh, 'MAX')
  48079. };
  48080. if (meshInfo.value && meshInfo.min && meshInfo.max) {
  48081. loadedMeshInfo.axisMeshes[i] = meshInfo;
  48082. } else {
  48083. // If we didn't find the mesh, it simply means this axis won't have transforms applied as mapped axis values change.
  48084. warn('Missing axis submesh under mesh with name: ' + meshName +
  48085. '(VALUE: ' + !!meshInfo.value +
  48086. ', MIN: ' + !!meshInfo.min +
  48087. ', MAX:' + !!meshInfo.max +
  48088. ')');
  48089. }
  48090. }
  48091. this.calculateRayOriginFromMesh(rootNode);
  48092. // Determine if the model has to be visible or not.
  48093. this.setModelVisibility();
  48094. }
  48095. debug('Model load complete.');
  48096. // Look through only immediate children. This will return null if no mesh exists with the given name.
  48097. function getImmediateChildByName (object3d, value) {
  48098. for (var i = 0, l = object3d.children.length; i < l; i++) {
  48099. var obj = object3d.children[i];
  48100. if (obj && obj['name'] === value) {
  48101. return obj;
  48102. }
  48103. }
  48104. return undefined;
  48105. }
  48106. },
  48107. calculateRayOriginFromMesh: (function () {
  48108. var quaternion = new THREE.Quaternion();
  48109. return function (rootNode) {
  48110. var mesh;
  48111. // Calculate the pointer pose (used for rays), by applying the world transform of th POINTER_POSE node
  48112. // in the glTF (assumes that root node is at world origin)
  48113. this.rayOrigin.origin.set(0, 0, 0);
  48114. this.rayOrigin.direction.set(0, 0, -1);
  48115. this.rayOrigin.createdFromMesh = true;
  48116. // Try to read Pointing pose from the source model
  48117. mesh = rootNode.getObjectByName(this.mapping.pointingPoseMeshName);
  48118. if (mesh) {
  48119. var parent = rootNode.parent;
  48120. // We need to read pose transforms accumulated from the root of the glTF, not the scene.
  48121. if (parent) {
  48122. rootNode.parent = null;
  48123. rootNode.updateMatrixWorld(true);
  48124. rootNode.parent = parent;
  48125. }
  48126. mesh.getWorldPosition(this.rayOrigin.origin);
  48127. mesh.getWorldQuaternion(quaternion);
  48128. this.rayOrigin.direction.applyQuaternion(quaternion);
  48129. // Recalculate the world matrices now that the rootNode is re-attached to the parent.
  48130. if (parent) {
  48131. rootNode.updateMatrixWorld(true);
  48132. }
  48133. } else {
  48134. debug('Mesh does not contain pointing origin data, defaulting to none.');
  48135. }
  48136. // Emit event stating that our pointing ray is now accurate.
  48137. this.modelReady();
  48138. };
  48139. })(),
  48140. lerpAxisTransform: (function () {
  48141. var quaternion = new THREE.Quaternion();
  48142. return function (axis, axisValue) {
  48143. var axisMeshInfo = this.loadedMeshInfo.axisMeshes[axis];
  48144. if (!axisMeshInfo) return;
  48145. var min = axisMeshInfo.min;
  48146. var max = axisMeshInfo.max;
  48147. var target = axisMeshInfo.value;
  48148. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  48149. var lerpValue = axisValue * 0.5 + 0.5;
  48150. target.setRotationFromQuaternion(quaternion.copy(min.quaternion).slerp(max.quaternion, lerpValue));
  48151. target.position.lerpVectors(min.position, max.position, lerpValue);
  48152. };
  48153. })(),
  48154. lerpButtonTransform: (function () {
  48155. var quaternion = new THREE.Quaternion();
  48156. return function (buttonName, buttonValue) {
  48157. var buttonMeshInfo = this.loadedMeshInfo.buttonMeshes[buttonName];
  48158. if (!buttonMeshInfo) return;
  48159. var min = buttonMeshInfo.unpressed;
  48160. var max = buttonMeshInfo.pressed;
  48161. var target = buttonMeshInfo.value;
  48162. target.setRotationFromQuaternion(quaternion.copy(min.quaternion).slerp(max.quaternion, buttonValue));
  48163. target.position.lerpVectors(min.position, max.position, buttonValue);
  48164. };
  48165. })(),
  48166. modelReady: function () {
  48167. this.el.emit('controllermodelready', {
  48168. name: 'windows-motion-controls',
  48169. model: this.data.model,
  48170. rayOrigin: this.rayOrigin
  48171. });
  48172. },
  48173. onButtonChanged: function (evt) {
  48174. var buttonName = this.mapping.buttons[evt.detail.id];
  48175. if (buttonName) {
  48176. // Update the button mesh transform
  48177. if (this.loadedMeshInfo && this.loadedMeshInfo.buttonMeshes) {
  48178. this.lerpButtonTransform(buttonName, evt.detail.state.value);
  48179. }
  48180. // Only emit events for buttons that we know how to map from index to name
  48181. this.el.emit(buttonName + 'changed', evt.detail.state);
  48182. }
  48183. },
  48184. onAxisMoved: function (evt) {
  48185. var numAxes = this.mapping.axisMeshNames.length;
  48186. // Only attempt to update meshes if we have valid data.
  48187. if (this.loadedMeshInfo && this.loadedMeshInfo.axisMeshes) {
  48188. for (var axis = 0; axis < numAxes; axis++) {
  48189. // Update the button mesh transform
  48190. this.lerpAxisTransform(axis, evt.detail.axis[axis] || 0.0);
  48191. }
  48192. }
  48193. emitIfAxesChanged(this, this.mapping.axes, evt);
  48194. },
  48195. setModelVisibility: function (visible) {
  48196. var model = this.el.getObject3D('mesh');
  48197. visible = visible !== undefined ? visible : this.modelVisible;
  48198. this.modelVisible = visible;
  48199. if (!model) { return; }
  48200. model.visible = visible;
  48201. }
  48202. });
  48203. },{"../constants":95,"../core/component":103,"../utils/":176,"../utils/bind":170,"../utils/tracked-controls":184}],95:[function(_dereq_,module,exports){
  48204. module.exports = {
  48205. AFRAME_INJECTED: 'aframe-injected',
  48206. DEFAULT_CAMERA_HEIGHT: 1.6,
  48207. DEFAULT_HANDEDNESS: 'right',
  48208. keyboardevent: _dereq_('./keyboardevent')
  48209. };
  48210. },{"./keyboardevent":96}],96:[function(_dereq_,module,exports){
  48211. module.exports = {
  48212. // Tiny KeyboardEvent.code polyfill.
  48213. KEYCODE_TO_CODE: {
  48214. '38': 'ArrowUp',
  48215. '37': 'ArrowLeft',
  48216. '40': 'ArrowDown',
  48217. '39': 'ArrowRight',
  48218. '87': 'KeyW',
  48219. '65': 'KeyA',
  48220. '83': 'KeyS',
  48221. '68': 'KeyD'
  48222. }
  48223. };
  48224. },{}],97:[function(_dereq_,module,exports){
  48225. var ANode = _dereq_('./a-node');
  48226. var bind = _dereq_('../utils/bind');
  48227. var debug = _dereq_('../utils/debug');
  48228. var registerElement = _dereq_('./a-register-element').registerElement;
  48229. var THREE = _dereq_('../lib/three');
  48230. var fileLoader = new THREE.FileLoader();
  48231. var warn = debug('core:a-assets:warn');
  48232. /**
  48233. * Asset management system. Handles blocking on asset loading.
  48234. */
  48235. module.exports = registerElement('a-assets', {
  48236. prototype: Object.create(ANode.prototype, {
  48237. createdCallback: {
  48238. value: function () {
  48239. this.isAssets = true;
  48240. this.fileLoader = fileLoader;
  48241. this.timeout = null;
  48242. }
  48243. },
  48244. attachedCallback: {
  48245. value: function () {
  48246. var self = this;
  48247. var i;
  48248. var loaded = [];
  48249. var mediaEl;
  48250. var mediaEls;
  48251. var imgEl;
  48252. var imgEls;
  48253. var timeout;
  48254. if (!this.parentNode.isScene) {
  48255. throw new Error('<a-assets> must be a child of a <a-scene>.');
  48256. }
  48257. // Wait for <img>s.
  48258. imgEls = this.querySelectorAll('img');
  48259. for (i = 0; i < imgEls.length; i++) {
  48260. imgEl = fixUpMediaElement(imgEls[i]);
  48261. loaded.push(new Promise(function (resolve, reject) {
  48262. // Set in cache because we won't be needing to call three.js loader if we have.
  48263. // a loaded media element.
  48264. THREE.Cache.files[imgEls[i].getAttribute('src')] = imgEl;
  48265. imgEl.onload = resolve;
  48266. imgEl.onerror = reject;
  48267. }));
  48268. }
  48269. // Wait for <audio>s and <video>s.
  48270. mediaEls = this.querySelectorAll('audio, video');
  48271. for (i = 0; i < mediaEls.length; i++) {
  48272. mediaEl = fixUpMediaElement(mediaEls[i]);
  48273. if (!mediaEl.src && !mediaEl.srcObject) {
  48274. warn('Audio/video asset has neither `src` nor `srcObject` attributes.');
  48275. }
  48276. loaded.push(mediaElementLoaded(mediaEl));
  48277. }
  48278. // Trigger loaded for scene to start rendering.
  48279. Promise.all(loaded).then(bind(this.load, this));
  48280. // Timeout to start loading anyways.
  48281. timeout = parseInt(this.getAttribute('timeout'), 10) || 3000;
  48282. this.timeout = setTimeout(function () {
  48283. if (self.hasLoaded) { return; }
  48284. warn('Asset loading timed out in ', timeout, 'ms');
  48285. self.emit('timeout');
  48286. self.load();
  48287. }, timeout);
  48288. }
  48289. },
  48290. detachedCallback: {
  48291. value: function () {
  48292. if (this.timeout) { clearTimeout(this.timeout); }
  48293. }
  48294. },
  48295. load: {
  48296. value: function () {
  48297. ANode.prototype.load.call(this, null, function waitOnFilter (el) {
  48298. return el.isAssetItem && el.hasAttribute('src');
  48299. });
  48300. }
  48301. }
  48302. })
  48303. });
  48304. /**
  48305. * Preload using XHRLoader for any type of asset.
  48306. */
  48307. registerElement('a-asset-item', {
  48308. prototype: Object.create(ANode.prototype, {
  48309. createdCallback: {
  48310. value: function () {
  48311. this.data = null;
  48312. this.isAssetItem = true;
  48313. }
  48314. },
  48315. attachedCallback: {
  48316. value: function () {
  48317. var self = this;
  48318. var src = this.getAttribute('src');
  48319. fileLoader.setResponseType(
  48320. this.getAttribute('response-type') || inferResponseType(src));
  48321. fileLoader.load(src, function handleOnLoad (response) {
  48322. self.data = response;
  48323. /*
  48324. Workaround for a Chrome bug. If another XHR is sent to the same url before the
  48325. previous one closes, the second request never finishes.
  48326. setTimeout finishes the first request and lets the logic triggered by load open
  48327. subsequent requests.
  48328. setTimeout can be removed once the fix for the bug below ships:
  48329. 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
  48330. */
  48331. setTimeout(function load () { ANode.prototype.load.call(self); });
  48332. }, function handleOnProgress (xhr) {
  48333. self.emit('progress', {
  48334. loadedBytes: xhr.loaded,
  48335. totalBytes: xhr.total,
  48336. xhr: xhr
  48337. });
  48338. }, function handleOnError (xhr) {
  48339. self.emit('error', {xhr: xhr});
  48340. });
  48341. }
  48342. }
  48343. })
  48344. });
  48345. /**
  48346. * Create a Promise that resolves once the media element has finished buffering.
  48347. *
  48348. * @param {Element} el - HTMLMediaElement.
  48349. * @returns {Promise}
  48350. */
  48351. function mediaElementLoaded (el) {
  48352. if (!el.hasAttribute('autoplay') && el.getAttribute('preload') !== 'auto') {
  48353. return;
  48354. }
  48355. // If media specifies autoplay or preload, wait until media is completely buffered.
  48356. return new Promise(function (resolve, reject) {
  48357. if (el.readyState === 4) { return resolve(); } // Already loaded.
  48358. if (el.error) { return reject(); } // Error.
  48359. el.addEventListener('loadeddata', checkProgress, false);
  48360. el.addEventListener('progress', checkProgress, false);
  48361. el.addEventListener('error', reject, false);
  48362. function checkProgress () {
  48363. // Add up the seconds buffered.
  48364. var secondsBuffered = 0;
  48365. for (var i = 0; i < el.buffered.length; i++) {
  48366. secondsBuffered += el.buffered.end(i) - el.buffered.start(i);
  48367. }
  48368. // Compare seconds buffered to media duration.
  48369. if (secondsBuffered >= el.duration) {
  48370. // Set in cache because we won't be needing to call three.js loader if we have.
  48371. // a loaded media element.
  48372. // Store video elements only. three.js loader is used for audio elements.
  48373. // See assetParse too.
  48374. if (el.tagName === 'VIDEO') {
  48375. THREE.Cache.files[el.getAttribute('src')] = el;
  48376. }
  48377. resolve();
  48378. }
  48379. }
  48380. });
  48381. }
  48382. /**
  48383. * Automatically add attributes to media elements where convenient.
  48384. * crossorigin, playsinline.
  48385. */
  48386. function fixUpMediaElement (mediaEl) {
  48387. // Cross-origin.
  48388. var newMediaEl = setCrossOrigin(mediaEl);
  48389. // Plays inline for mobile.
  48390. if (newMediaEl.tagName && newMediaEl.tagName.toLowerCase() === 'video') {
  48391. newMediaEl.setAttribute('playsinline', '');
  48392. newMediaEl.setAttribute('webkit-playsinline', '');
  48393. }
  48394. if (newMediaEl !== mediaEl) {
  48395. mediaEl.parentNode.appendChild(newMediaEl);
  48396. mediaEl.parentNode.removeChild(mediaEl);
  48397. }
  48398. return newMediaEl;
  48399. }
  48400. /**
  48401. * Automatically set `crossorigin` if not defined on the media element.
  48402. * If it is not defined, we must create and re-append a new media element <img> and
  48403. * have the browser re-request it with `crossorigin` set.
  48404. *
  48405. * @param {Element} Media element (e.g., <img>, <audio>, <video>).
  48406. * @returns {Element} Media element to be used to listen to for loaded events.
  48407. */
  48408. function setCrossOrigin (mediaEl) {
  48409. var newMediaEl;
  48410. var src;
  48411. // Already has crossorigin set.
  48412. if (mediaEl.hasAttribute('crossorigin')) { return mediaEl; }
  48413. src = mediaEl.getAttribute('src');
  48414. if (src !== null) {
  48415. // Does not have protocol.
  48416. if (src.indexOf('://') === -1) { return mediaEl; }
  48417. // Determine if cross origin is actually needed.
  48418. if (extractDomain(src) === window.location.host) { return mediaEl; }
  48419. }
  48420. warn('Cross-origin element (e.g., <img>) was requested without `crossorigin` set. ' +
  48421. 'A-Frame will re-request the asset with `crossorigin` attribute set. ' +
  48422. 'Please set `crossorigin` on the element (e.g., <img crossorigin="anonymous">)', src);
  48423. mediaEl.crossOrigin = 'anonymous';
  48424. newMediaEl = mediaEl.cloneNode(true);
  48425. return newMediaEl;
  48426. }
  48427. /**
  48428. * Extract domain out of URL.
  48429. *
  48430. * @param {string} url
  48431. * @returns {string}
  48432. */
  48433. function extractDomain (url) {
  48434. // Find and remove protocol (e.g., http, ftp, etc.) to get domain.
  48435. var domain = url.indexOf('://') > -1 ? url.split('/')[2] : url.split('/')[0];
  48436. // Find and remove port number.
  48437. return domain.substring(0, domain.indexOf(':'));
  48438. }
  48439. /**
  48440. * Infer response-type attribute from src.
  48441. * Default is text(default XMLHttpRequest.responseType)
  48442. * but we use arraybuffer for .gltf and .glb files
  48443. * because of THREE.GLTFLoader specification.
  48444. *
  48445. * @param {string} src
  48446. * @returns {string}
  48447. */
  48448. function inferResponseType (src) {
  48449. var dotLastIndex = src.lastIndexOf('.');
  48450. if (dotLastIndex >= 0) {
  48451. var extension = src.slice(dotLastIndex, src.length);
  48452. if (extension === '.gltf' || extension === '.glb') {
  48453. return 'arraybuffer';
  48454. }
  48455. }
  48456. return 'text';
  48457. }
  48458. module.exports.inferResponseType = inferResponseType;
  48459. },{"../lib/three":151,"../utils/bind":170,"../utils/debug":172,"./a-node":101,"./a-register-element":102}],98:[function(_dereq_,module,exports){
  48460. var debug = _dereq_('../utils/debug');
  48461. var registerElement = _dereq_('./a-register-element').registerElement;
  48462. var warn = debug('core:cubemap:warn');
  48463. /**
  48464. * Cubemap element that handles validation and exposes list of URLs.
  48465. * Does not listen to updates.
  48466. */
  48467. module.exports = registerElement('a-cubemap', {
  48468. prototype: Object.create(window.HTMLElement.prototype, {
  48469. /**
  48470. * Calculates this.srcs.
  48471. */
  48472. attachedCallback: {
  48473. value: function () {
  48474. this.srcs = this.validate();
  48475. },
  48476. writable: window.debug
  48477. },
  48478. /**
  48479. * Checks for exactly six elements with [src].
  48480. * Does not check explicitly for <img>s in case user does not want
  48481. * prefetching.
  48482. *
  48483. * @returns {Array|null} - six URLs if valid, else null.
  48484. */
  48485. validate: {
  48486. value: function () {
  48487. var elements = this.querySelectorAll('[src]');
  48488. var i;
  48489. var srcs = [];
  48490. if (elements.length === 6) {
  48491. for (i = 0; i < elements.length; i++) {
  48492. srcs.push(elements[i].getAttribute('src'));
  48493. }
  48494. return srcs;
  48495. }
  48496. // Else if there are not six elements, throw a warning.
  48497. warn(
  48498. '<a-cubemap> did not contain exactly six elements each with a ' +
  48499. '`src` attribute.');
  48500. },
  48501. writable: window.debug
  48502. }
  48503. })
  48504. });
  48505. },{"../utils/debug":172,"./a-register-element":102}],99:[function(_dereq_,module,exports){
  48506. var ANode = _dereq_('./a-node');
  48507. var COMPONENTS = _dereq_('./component').components;
  48508. var registerElement = _dereq_('./a-register-element').registerElement;
  48509. var THREE = _dereq_('../lib/three');
  48510. var utils = _dereq_('../utils/');
  48511. var AEntity;
  48512. var debug = utils.debug('core:a-entity:debug');
  48513. var warn = utils.debug('core:a-entity:warn');
  48514. var MULTIPLE_COMPONENT_DELIMITER = '__';
  48515. var OBJECT3D_COMPONENTS = ['position', 'rotation', 'scale', 'visible'];
  48516. var ONCE = {once: true};
  48517. /**
  48518. * Entity is a container object that components are plugged into to comprise everything in
  48519. * the scene. In A-Frame, they inherently have position, rotation, and scale.
  48520. *
  48521. * To be able to take components, the scene element inherits from the entity definition.
  48522. *
  48523. * @member {object} components - entity's currently initialized components.
  48524. * @member {object} object3D - three.js object.
  48525. * @member {array} states
  48526. * @member {boolean} isPlaying - false if dynamic behavior of the entity is paused.
  48527. */
  48528. var proto = Object.create(ANode.prototype, {
  48529. createdCallback: {
  48530. value: function () {
  48531. this.components = {};
  48532. // To avoid double initializations and infinite loops.
  48533. this.initializingComponents = {};
  48534. this.componentsToUpdate = {};
  48535. this.isEntity = true;
  48536. this.isPlaying = false;
  48537. this.object3D = new THREE.Group();
  48538. this.object3D.el = this;
  48539. this.object3DMap = {};
  48540. this.parentEl = null;
  48541. this.rotationObj = {};
  48542. this.states = [];
  48543. }
  48544. },
  48545. /**
  48546. * Handle changes coming from the browser DOM inspector.
  48547. */
  48548. attributeChangedCallback: {
  48549. value: function (attr, oldVal, newVal) {
  48550. var component = this.components[attr];
  48551. // If the empty string is passed by the component initialization
  48552. // logic we ignore the component update.
  48553. if (component && component.justInitialized && newVal === '') {
  48554. delete component.justInitialized;
  48555. return;
  48556. }
  48557. // When a component is removed after calling el.removeAttribute('material')
  48558. if (!component && newVal === null) { return; }
  48559. this.setEntityAttribute(attr, oldVal, newVal);
  48560. }
  48561. },
  48562. /**
  48563. * Add to parent, load, play.
  48564. */
  48565. attachedCallback: {
  48566. value: function () {
  48567. var assetsEl; // Asset management system element.
  48568. var sceneEl = this.sceneEl;
  48569. var self = this; // Component.
  48570. this.addToParent();
  48571. // Don't .load() scene on attachedCallback.
  48572. if (this.isScene) { return; }
  48573. // Gracefully not error when outside of <a-scene> (e.g., tests).
  48574. if (!sceneEl) {
  48575. this.load();
  48576. return;
  48577. }
  48578. // Wait for asset management system to finish before loading.
  48579. assetsEl = sceneEl.querySelector('a-assets');
  48580. if (assetsEl && !assetsEl.hasLoaded) {
  48581. assetsEl.addEventListener('loaded', function () { self.load(); });
  48582. return;
  48583. }
  48584. this.load();
  48585. }
  48586. },
  48587. /**
  48588. * Tell parent to remove this element's object3D from its object3D.
  48589. * Do not call on scene element because that will cause a call to document.body.remove().
  48590. */
  48591. detachedCallback: {
  48592. value: function () {
  48593. var componentName;
  48594. if (!this.parentEl) { return; }
  48595. // Remove components.
  48596. for (componentName in this.components) {
  48597. this.removeComponent(componentName, false);
  48598. }
  48599. if (this.isScene) { return; }
  48600. this.removeFromParent();
  48601. ANode.prototype.detachedCallback.call(this);
  48602. // Remove cyclic reference.
  48603. this.object3D.el = null;
  48604. }
  48605. },
  48606. getObject3D: {
  48607. value: function (type) {
  48608. return this.object3DMap[type];
  48609. }
  48610. },
  48611. /**
  48612. * Set a THREE.Object3D into the map.
  48613. *
  48614. * @param {string} type - Developer-set name of the type of object, will be unique per type.
  48615. * @param {object} obj - A THREE.Object3D.
  48616. */
  48617. setObject3D: {
  48618. value: function (type, obj) {
  48619. var oldObj;
  48620. var self = this;
  48621. if (!(obj instanceof THREE.Object3D)) {
  48622. throw new Error(
  48623. '`Entity.setObject3D` was called with an object that was not an instance of ' +
  48624. 'THREE.Object3D.'
  48625. );
  48626. }
  48627. // Remove existing object of the type.
  48628. oldObj = this.getObject3D(type);
  48629. if (oldObj) { this.object3D.remove(oldObj); }
  48630. // Set references to A-Frame entity.
  48631. obj.el = this;
  48632. if (obj.children.length) {
  48633. obj.traverse(function bindEl (child) {
  48634. child.el = self;
  48635. });
  48636. }
  48637. // Add.
  48638. this.object3D.add(obj);
  48639. this.object3DMap[type] = obj;
  48640. this.emit('object3dset', {object: obj, type: type});
  48641. }
  48642. },
  48643. /**
  48644. * Remove object from scene and entity object3D map.
  48645. */
  48646. removeObject3D: {
  48647. value: function (type) {
  48648. var obj = this.getObject3D(type);
  48649. if (!obj) {
  48650. warn('Tried to remove `Object3D` of type:', type, 'which was not defined.');
  48651. return;
  48652. }
  48653. this.object3D.remove(obj);
  48654. delete this.object3DMap[type];
  48655. this.emit('object3dremove', {type: type});
  48656. }
  48657. },
  48658. /**
  48659. * Gets or creates an object3D of a given type.
  48660. *
  48661. * @param {string} type - Type of the object3D.
  48662. * @param {string} Constructor - Constructor to use to create the object3D if needed.
  48663. * @returns {object}
  48664. */
  48665. getOrCreateObject3D: {
  48666. value: function (type, Constructor) {
  48667. var object3D = this.getObject3D(type);
  48668. if (!object3D && Constructor) {
  48669. object3D = new Constructor();
  48670. this.setObject3D(type, object3D);
  48671. }
  48672. warn('`getOrCreateObject3D` has been deprecated. Use `setObject3D()` ' +
  48673. 'and `object3dset` event instead.');
  48674. return object3D;
  48675. }
  48676. },
  48677. /**
  48678. * Add child entity.
  48679. *
  48680. * @param {Element} el - Child entity.
  48681. */
  48682. add: {
  48683. value: function (el) {
  48684. if (!el.object3D) {
  48685. throw new Error("Trying to add an element that doesn't have an `object3D`");
  48686. }
  48687. this.object3D.add(el.object3D);
  48688. this.emit('child-attached', {el: el});
  48689. }
  48690. },
  48691. /**
  48692. * Tell parentNode to add this entity to itself.
  48693. */
  48694. addToParent: {
  48695. value: function () {
  48696. var parentNode = this.parentEl = this.parentNode;
  48697. // `!parentNode` check primarily for unit tests.
  48698. if (!parentNode || !parentNode.add || this.attachedToParent) { return; }
  48699. parentNode.add(this);
  48700. this.attachedToParent = true; // To prevent multiple attachments to same parent.
  48701. }
  48702. },
  48703. /**
  48704. * Tell parentNode to remove this entity from itself.
  48705. */
  48706. removeFromParent: {
  48707. value: function () {
  48708. var parentEl = this.parentEl;
  48709. this.parentEl.remove(this);
  48710. this.attachedToParent = false;
  48711. this.parentEl = null;
  48712. parentEl.emit('child-detached', {el: this});
  48713. }
  48714. },
  48715. load: {
  48716. value: function () {
  48717. var self = this;
  48718. if (this.hasLoaded || !this.parentEl) { return; }
  48719. ANode.prototype.load.call(this, function entityLoadCallback () {
  48720. // Check if entity was detached while it was waiting to load.
  48721. if (!self.parentEl) { return; }
  48722. self.updateComponents();
  48723. if (self.isScene || self.parentEl.isPlaying) { self.play(); }
  48724. });
  48725. },
  48726. writable: window.debug
  48727. },
  48728. /**
  48729. * Remove child entity.
  48730. *
  48731. * @param {Element} el - Child entity.
  48732. */
  48733. remove: {
  48734. value: function (el) {
  48735. if (el) {
  48736. this.object3D.remove(el.object3D);
  48737. } else {
  48738. this.parentNode.removeChild(this);
  48739. }
  48740. }
  48741. },
  48742. /**
  48743. * @returns {array} Direct children that are entities.
  48744. */
  48745. getChildEntities: {
  48746. value: function () {
  48747. var children = this.children;
  48748. var childEntities = [];
  48749. for (var i = 0; i < children.length; i++) {
  48750. var child = children[i];
  48751. if (child instanceof AEntity) {
  48752. childEntities.push(child);
  48753. }
  48754. }
  48755. return childEntities;
  48756. }
  48757. },
  48758. /**
  48759. * Initialize component.
  48760. *
  48761. * @param {string} attrName - Attribute name asociated to the component.
  48762. * @param {object} data - Component data
  48763. * @param {boolean} isDependency - True if the component is a dependency.
  48764. */
  48765. initComponent: {
  48766. value: function (attrName, data, isDependency) {
  48767. var component;
  48768. var componentId;
  48769. var componentInfo;
  48770. var componentName;
  48771. var isComponentDefined;
  48772. componentInfo = utils.split(attrName, MULTIPLE_COMPONENT_DELIMITER);
  48773. componentName = componentInfo[0];
  48774. componentId = componentInfo.length > 2
  48775. ? componentInfo.slice(1).join('__')
  48776. : componentInfo[1];
  48777. // Not a registered component.
  48778. if (!COMPONENTS[componentName]) { return; }
  48779. // Component is not a dependency and is undefined.
  48780. // If a component is a dependency, then it is okay to have no data.
  48781. isComponentDefined = checkComponentDefined(this, attrName) ||
  48782. data !== undefined;
  48783. if (!isComponentDefined && !isDependency) { return; }
  48784. // Component already initialized.
  48785. if (attrName in this.components) { return; }
  48786. // Initialize dependencies first
  48787. this.initComponentDependencies(componentName);
  48788. // If component name has an id we check component type multiplic
  48789. if (componentId && !COMPONENTS[componentName].multiple) {
  48790. throw new Error('Trying to initialize multiple ' +
  48791. 'components of type `' + componentName +
  48792. '`. There can only be one component of this type per entity.');
  48793. }
  48794. component = new COMPONENTS[componentName].Component(this, data, componentId);
  48795. if (this.isPlaying) { component.play(); }
  48796. // Components are reflected in the DOM as attributes but the state is not shown
  48797. // hence we set the attribute to empty string.
  48798. // The flag justInitialized is for attributeChangedCallback to not overwrite
  48799. // the component with the empty string.
  48800. if (!this.hasAttribute(attrName)) {
  48801. component.justInitialized = true;
  48802. window.HTMLElement.prototype.setAttribute.call(this, attrName, '');
  48803. }
  48804. debug('Component initialized: %s', attrName);
  48805. },
  48806. writable: window.debug
  48807. },
  48808. /**
  48809. * Initialize dependencies of a component.
  48810. *
  48811. * @param {string} name - Root component name.
  48812. */
  48813. initComponentDependencies: {
  48814. value: function (name) {
  48815. var self = this;
  48816. var component = COMPONENTS[name];
  48817. var dependencies;
  48818. var i;
  48819. // Not a component.
  48820. if (!component) { return; }
  48821. // No dependencies.
  48822. dependencies = COMPONENTS[name].dependencies;
  48823. if (!dependencies) { return; }
  48824. // Initialize dependencies.
  48825. for (i = 0; i < dependencies.length; i++) {
  48826. // Call getAttribute to initialize the data from the DOM.
  48827. self.initComponent(
  48828. dependencies[i],
  48829. window.HTMLElement.prototype.getAttribute.call(self, dependencies[i]) || undefined,
  48830. true
  48831. );
  48832. }
  48833. }
  48834. },
  48835. removeComponent: {
  48836. value: function (name, destroy) {
  48837. var component;
  48838. component = this.components[name];
  48839. if (!component) { return; }
  48840. // Wait for component to initialize.
  48841. if (!component.initialized) {
  48842. this.addEventListener('componentinitialized', function tryRemoveLater (evt) {
  48843. if (evt.detail.name !== name) { return; }
  48844. this.removeComponent(name, destroy);
  48845. this.removeEventListener('componentinitialized', tryRemoveLater);
  48846. });
  48847. return;
  48848. }
  48849. component.pause();
  48850. component.remove();
  48851. // Keep component attached to entity in case of just full entity detach.
  48852. if (destroy) {
  48853. component.destroy();
  48854. delete this.components[name];
  48855. }
  48856. this.emit('componentremoved', component.evtDetail, false);
  48857. },
  48858. writable: window.debug
  48859. },
  48860. /**
  48861. * Initialize or update all components.
  48862. * Build data using initial components, defined attributes, mixins, and defaults.
  48863. * Update default components before the rest.
  48864. *
  48865. * @member {function} getExtraComponents - Can be implemented to include component data
  48866. * from other sources (e.g., implemented by primitives).
  48867. */
  48868. updateComponents: {
  48869. value: function () {
  48870. var data;
  48871. var extraComponents;
  48872. var i;
  48873. var name;
  48874. var componentsToUpdate = this.componentsToUpdate;
  48875. if (!this.hasLoaded) { return; }
  48876. // Gather mixin-defined components.
  48877. for (i = 0; i < this.mixinEls.length; i++) {
  48878. for (name in this.mixinEls[i].componentCache) {
  48879. if (isComponent(name)) { componentsToUpdate[name] = true; }
  48880. }
  48881. }
  48882. // Gather from extra initial component data if defined (e.g., primitives).
  48883. if (this.getExtraComponents) {
  48884. extraComponents = this.getExtraComponents();
  48885. for (name in extraComponents) {
  48886. if (isComponent(name)) { componentsToUpdate[name] = true; }
  48887. }
  48888. }
  48889. // Gather entity-defined components.
  48890. for (i = 0; i < this.attributes.length; ++i) {
  48891. name = this.attributes[i].name;
  48892. if (OBJECT3D_COMPONENTS.indexOf(name) !== -1) { continue; }
  48893. if (isComponent(name)) { componentsToUpdate[name] = true; }
  48894. }
  48895. // object3D components first (position, rotation, scale, visible).
  48896. for (i = 0; i < OBJECT3D_COMPONENTS.length; i++) {
  48897. name = OBJECT3D_COMPONENTS[i];
  48898. if (!this.hasAttribute(name)) { continue; }
  48899. this.updateComponent(name, this.getDOMAttribute(name));
  48900. }
  48901. // Initialize or update rest of components.
  48902. for (name in componentsToUpdate) {
  48903. data = mergeComponentData(this.getDOMAttribute(name),
  48904. extraComponents && extraComponents[name]);
  48905. this.updateComponent(name, data);
  48906. delete componentsToUpdate[name];
  48907. }
  48908. },
  48909. writable: window.debug
  48910. },
  48911. /**
  48912. * Initialize, update, or remove a single component.
  48913. *
  48914. * When initializing, we set the component on `this.components`.
  48915. *
  48916. * @param {string} attr - Component name.
  48917. * @param {object} attrValue - Value of the DOM attribute.
  48918. * @param {boolean} clobber - If new attrValue completely replaces previous properties.
  48919. */
  48920. updateComponent: {
  48921. value: function (attr, attrValue, clobber) {
  48922. var component = this.components[attr];
  48923. if (component) {
  48924. // Remove component.
  48925. if (attrValue === null && !checkComponentDefined(this, attr)) {
  48926. this.removeComponent(attr, true);
  48927. return;
  48928. }
  48929. // Component already initialized. Update component.
  48930. component.updateProperties(attrValue, clobber);
  48931. return;
  48932. }
  48933. // Component not yet initialized. Initialize component.
  48934. this.initComponent(attr, attrValue, false);
  48935. }
  48936. },
  48937. /**
  48938. * If `attr` is a component name, detach the component from the entity.
  48939. *
  48940. * If `propertyName` is given, reset the component property value to its default.
  48941. *
  48942. * @param {string} attr - Attribute name, which could also be a component name.
  48943. * @param {string} propertyName - Component prop name, if resetting an individual prop.
  48944. */
  48945. removeAttribute: {
  48946. value: function (attr, propertyName) {
  48947. var component = this.components[attr];
  48948. // Remove component.
  48949. if (component && propertyName === undefined) {
  48950. this.removeComponent(attr, true);
  48951. }
  48952. // Reset component property value.
  48953. if (component && propertyName !== undefined) {
  48954. component.resetProperty(propertyName);
  48955. return;
  48956. }
  48957. // Remove mixins.
  48958. if (attr === 'mixin') {
  48959. this.mixinUpdate('');
  48960. }
  48961. window.HTMLElement.prototype.removeAttribute.call(this, attr);
  48962. }
  48963. },
  48964. /**
  48965. * Start dynamic behavior associated with entity such as dynamic components and animations.
  48966. * Tell all children entities to also play.
  48967. */
  48968. play: {
  48969. value: function () {
  48970. var entities;
  48971. var i;
  48972. var key;
  48973. // Already playing.
  48974. if (this.isPlaying || !this.hasLoaded) { return; }
  48975. this.isPlaying = true;
  48976. // Wake up all components.
  48977. for (key in this.components) { this.components[key].play(); }
  48978. // Tell all child entities to play.
  48979. entities = this.getChildEntities();
  48980. for (i = 0; i < entities.length; i++) { entities[i].play(); }
  48981. this.emit('play');
  48982. },
  48983. writable: true
  48984. },
  48985. /**
  48986. * Pause dynamic behavior associated with entity such as dynamic components and animations.
  48987. * Tell all children entities to also pause.
  48988. */
  48989. pause: {
  48990. value: function () {
  48991. var entities;
  48992. var i;
  48993. var key;
  48994. if (!this.isPlaying) { return; }
  48995. this.isPlaying = false;
  48996. // Sleep all components.
  48997. for (key in this.components) { this.components[key].pause(); }
  48998. // Tell all child entities to pause.
  48999. entities = this.getChildEntities();
  49000. for (i = 0; i < entities.length; i++) { entities[i].pause(); }
  49001. this.emit('pause');
  49002. },
  49003. writable: true
  49004. },
  49005. /**
  49006. * Deals with updates on entity-specific attributes (i.e., components and mixins).
  49007. *
  49008. * @param {string} attr
  49009. * @param {string} oldVal
  49010. * @param {string|object} newVal
  49011. */
  49012. setEntityAttribute: {
  49013. value: function (attr, oldVal, newVal) {
  49014. if (COMPONENTS[attr] || this.components[attr]) {
  49015. this.updateComponent(attr, newVal);
  49016. return;
  49017. }
  49018. if (attr === 'mixin') {
  49019. // Ignore if `<a-node>` code is just updating computed mixin in the DOM.
  49020. if (newVal === this.computedMixinStr) { return; }
  49021. this.mixinUpdate(newVal, oldVal);
  49022. }
  49023. }
  49024. },
  49025. /**
  49026. * When mixins updated, trigger init or optimized-update of relevant components.
  49027. */
  49028. mixinUpdate: {
  49029. value: (function () {
  49030. var componentsUpdated = [];
  49031. return function (newMixins, oldMixins) {
  49032. var component;
  49033. var mixinEl;
  49034. var mixinIds;
  49035. var i;
  49036. var self = this;
  49037. if (!this.hasLoaded) {
  49038. this.addEventListener('loaded', function () {
  49039. self.mixinUpdate(newMixins, oldMixins);
  49040. }, ONCE);
  49041. return;
  49042. }
  49043. oldMixins = oldMixins || this.getAttribute('mixin');
  49044. mixinIds = this.updateMixins(newMixins, oldMixins);
  49045. // Loop over current mixins.
  49046. componentsUpdated.length = 0;
  49047. for (i = 0; i < this.mixinEls.length; i++) {
  49048. for (component in this.mixinEls[i].componentCache) {
  49049. if (componentsUpdated.indexOf(component) === -1) {
  49050. if (this.components[component]) {
  49051. // Update. Just rebuild data.
  49052. this.components[component].handleMixinUpdate();
  49053. } else {
  49054. // Init. buildData will gather mixin values.
  49055. this.initComponent(component, null);
  49056. }
  49057. componentsUpdated.push(component);
  49058. }
  49059. }
  49060. }
  49061. // Loop over old mixins to call for data rebuild.
  49062. for (i = 0; i < mixinIds.oldMixinIds.length; i++) {
  49063. mixinEl = document.getElementById(mixinIds.oldMixinIds[i]);
  49064. if (!mixinEl) { continue; }
  49065. for (component in mixinEl.componentCache) {
  49066. if (componentsUpdated.indexOf(component) === -1) {
  49067. if (this.components[component]) {
  49068. if (this.getDOMAttribute(component)) {
  49069. // Update component if explicitly defined.
  49070. this.components[component].handleMixinUpdate();
  49071. } else {
  49072. // Remove component if not explicitly defined.
  49073. this.removeComponent(component, true);
  49074. }
  49075. }
  49076. }
  49077. }
  49078. }
  49079. };
  49080. })()
  49081. },
  49082. /**
  49083. * setAttribute can:
  49084. *
  49085. * 1. Set a single property of a multi-property component.
  49086. * 2. Set multiple properties of a multi-property component.
  49087. * 3. Replace properties of a multi-property component.
  49088. * 4. Set a value for a single-property component, mixin, or normal HTML attribute.
  49089. *
  49090. * @param {string} attrName - Component or attribute name.
  49091. * @param {*} arg1 - Can be a value, property name, CSS-style property string, or
  49092. * object of properties.
  49093. * @param {*|bool} arg2 - If arg1 is a property name, this should be a value. Otherwise,
  49094. * it is a boolean indicating whether to clobber previous values (defaults to false).
  49095. */
  49096. setAttribute: {
  49097. value: (function () {
  49098. var singlePropUpdate = {};
  49099. return function (attrName, arg1, arg2) {
  49100. var newAttrValue;
  49101. var clobber;
  49102. var componentName;
  49103. var delimiterIndex;
  49104. var isDebugMode;
  49105. var key;
  49106. delimiterIndex = attrName.indexOf(MULTIPLE_COMPONENT_DELIMITER);
  49107. componentName = delimiterIndex > 0 ? attrName.substring(0, delimiterIndex) : attrName;
  49108. // Not a component. Normal set attribute.
  49109. if (!COMPONENTS[componentName]) {
  49110. if (attrName === 'mixin') { this.mixinUpdate(arg1); }
  49111. ANode.prototype.setAttribute.call(this, attrName, arg1);
  49112. return;
  49113. }
  49114. // Initialize component first if not yet initialized.
  49115. if (!this.components[attrName] && this.hasAttribute(attrName)) {
  49116. this.updateComponent(
  49117. attrName,
  49118. window.HTMLElement.prototype.getAttribute.call(this, attrName));
  49119. }
  49120. // Determine new attributes from the arguments
  49121. if (typeof arg2 !== 'undefined' &&
  49122. typeof arg1 === 'string' &&
  49123. arg1.length > 0 &&
  49124. typeof utils.styleParser.parse(arg1) === 'string') {
  49125. // Update a single property of a multi-property component
  49126. for (key in singlePropUpdate) { delete singlePropUpdate[key]; }
  49127. newAttrValue = singlePropUpdate;
  49128. newAttrValue[arg1] = arg2;
  49129. clobber = false;
  49130. } else {
  49131. // Update with a value, object, or CSS-style property string, with the possiblity
  49132. // of clobbering previous values.
  49133. newAttrValue = arg1;
  49134. clobber = (arg2 === true);
  49135. }
  49136. // Update component
  49137. this.updateComponent(attrName, newAttrValue, clobber);
  49138. // In debug mode, write component data up to the DOM.
  49139. isDebugMode = this.sceneEl && this.sceneEl.getAttribute('debug');
  49140. if (isDebugMode) { this.components[attrName].flushToDOM(); }
  49141. };
  49142. })(),
  49143. writable: window.debug
  49144. },
  49145. /**
  49146. * Reflect component data in the DOM (as seen from the browser DOM Inspector).
  49147. *
  49148. * @param {bool} recursive - Also flushToDOM on the children.
  49149. **/
  49150. flushToDOM: {
  49151. value: function (recursive) {
  49152. var components = this.components;
  49153. var child;
  49154. var children = this.children;
  49155. var i;
  49156. var key;
  49157. // Flush entity's components to DOM.
  49158. for (key in components) {
  49159. components[key].flushToDOM();
  49160. }
  49161. // Recurse.
  49162. if (!recursive) { return; }
  49163. for (i = 0; i < children.length; ++i) {
  49164. child = children[i];
  49165. if (!child.flushToDOM) { continue; }
  49166. child.flushToDOM(recursive);
  49167. }
  49168. }
  49169. },
  49170. /**
  49171. * If `attr` is a component, returns ALL component data including applied mixins and
  49172. * defaults.
  49173. *
  49174. * If `attr` is not a component, fall back to HTML getAttribute.
  49175. *
  49176. * @param {string} attr
  49177. * @returns {object|string} Object if component, else string.
  49178. */
  49179. getAttribute: {
  49180. value: function (attr) {
  49181. // If component, return component data.
  49182. var component;
  49183. if (attr === 'position') { return this.object3D.position; }
  49184. if (attr === 'rotation') { return getRotation(this); }
  49185. if (attr === 'scale') { return this.object3D.scale; }
  49186. if (attr === 'visible') { return this.object3D.visible; }
  49187. component = this.components[attr];
  49188. if (component) { return component.data; }
  49189. return window.HTMLElement.prototype.getAttribute.call(this, attr);
  49190. },
  49191. writable: window.debug
  49192. },
  49193. /**
  49194. * If `attr` is a component, returns JUST the component data defined on the entity.
  49195. * Like a partial version of `getComputedAttribute` as returned component data
  49196. * does not include applied mixins or defaults.
  49197. *
  49198. * If `attr` is not a component, fall back to HTML getAttribute.
  49199. *
  49200. * @param {string} attr
  49201. * @returns {object|string} Object if component, else string.
  49202. */
  49203. getDOMAttribute: {
  49204. value: function (attr) {
  49205. // If cached value exists, return partial component data.
  49206. var component = this.components[attr];
  49207. if (component) { return component.attrValue; }
  49208. return window.HTMLElement.prototype.getAttribute.call(this, attr);
  49209. },
  49210. writable: window.debug
  49211. },
  49212. addState: {
  49213. value: function (state) {
  49214. if (this.is(state)) { return; }
  49215. this.states.push(state);
  49216. this.emit('stateadded', state);
  49217. }
  49218. },
  49219. removeState: {
  49220. value: function (state) {
  49221. var stateIndex = this.states.indexOf(state);
  49222. if (stateIndex === -1) { return; }
  49223. this.states.splice(stateIndex, 1);
  49224. this.emit('stateremoved', state);
  49225. }
  49226. },
  49227. /**
  49228. * Checks if the element is in a given state. e.g. el.is('alive');
  49229. * @type {string} state - Name of the state we want to check
  49230. */
  49231. is: {
  49232. value: function (state) {
  49233. return this.states.indexOf(state) !== -1;
  49234. }
  49235. },
  49236. /**
  49237. * Open Inspector to this entity.
  49238. */
  49239. inspect: {
  49240. value: function () {
  49241. this.sceneEl.components.inspector.openInspector(this);
  49242. }
  49243. },
  49244. /**
  49245. * Clean up memory and return memory to object pools.
  49246. */
  49247. destroy: {
  49248. value: function () {
  49249. var key;
  49250. if (this.parentNode) {
  49251. warn('Entity can only be destroyed if detached from scenegraph.');
  49252. return;
  49253. }
  49254. for (key in this.components) {
  49255. this.components[key].destroy();
  49256. }
  49257. }
  49258. }
  49259. });
  49260. /**
  49261. * Check if a component is *defined* for an entity, including defaults and mixins.
  49262. * Does not check whether the component has been *initialized* for an entity.
  49263. *
  49264. * @param {string} el - Entity.
  49265. * @param {string} name - Component name.
  49266. * @returns {boolean}
  49267. */
  49268. function checkComponentDefined (el, name) {
  49269. // Check if element contains the component.
  49270. if (el.components[name] && el.components[name].attrValue) { return true; }
  49271. return isComponentMixedIn(name, el.mixinEls);
  49272. }
  49273. /**
  49274. * Check if any mixins contains a component.
  49275. *
  49276. * @param {string} name - Component name.
  49277. * @param {array} mixinEls - Array of <a-mixin>s.
  49278. */
  49279. function isComponentMixedIn (name, mixinEls) {
  49280. var i;
  49281. var inMixin = false;
  49282. for (i = 0; i < mixinEls.length; ++i) {
  49283. inMixin = mixinEls[i].hasAttribute(name);
  49284. if (inMixin) { break; }
  49285. }
  49286. return inMixin;
  49287. }
  49288. /**
  49289. * Given entity defined value, merge in extra data if necessary.
  49290. * Handle both single and multi-property components.
  49291. *
  49292. * @param {string} attrValue - Entity data.
  49293. * @param extraData - Entity data from another source to merge in.
  49294. */
  49295. function mergeComponentData (attrValue, extraData) {
  49296. // Extra data not defined, just return attrValue.
  49297. if (!extraData) { return attrValue; }
  49298. // Merge multi-property data.
  49299. if (extraData.constructor === Object) {
  49300. return utils.extend(extraData, utils.styleParser.parse(attrValue || {}));
  49301. }
  49302. // Return data, precendence to the defined value.
  49303. return attrValue || extraData;
  49304. }
  49305. function isComponent (componentName) {
  49306. if (componentName.indexOf(MULTIPLE_COMPONENT_DELIMITER) !== -1) {
  49307. componentName = utils.split(componentName, MULTIPLE_COMPONENT_DELIMITER)[0];
  49308. }
  49309. if (!COMPONENTS[componentName]) { return false; }
  49310. return true;
  49311. }
  49312. function getRotation (entityEl) {
  49313. var radToDeg = THREE.Math.radToDeg;
  49314. var rotation = entityEl.object3D.rotation;
  49315. var rotationObj = entityEl.rotationObj;
  49316. rotationObj.x = radToDeg(rotation.x);
  49317. rotationObj.y = radToDeg(rotation.y);
  49318. rotationObj.z = radToDeg(rotation.z);
  49319. return rotationObj;
  49320. }
  49321. AEntity = registerElement('a-entity', {prototype: proto});
  49322. module.exports = AEntity;
  49323. },{"../lib/three":151,"../utils/":176,"./a-node":101,"./a-register-element":102,"./component":103}],100:[function(_dereq_,module,exports){
  49324. var ANode = _dereq_('./a-node');
  49325. var registerElement = _dereq_('./a-register-element').registerElement;
  49326. var components = _dereq_('./component').components;
  49327. var utils = _dereq_('../utils');
  49328. var MULTIPLE_COMPONENT_DELIMITER = '__';
  49329. /**
  49330. * @member {object} componentCache - Cache of pre-parsed values. An object where the keys
  49331. * are component names and the values are already parsed by the component.
  49332. */
  49333. module.exports = registerElement('a-mixin', {
  49334. prototype: Object.create(ANode.prototype, {
  49335. createdCallback: {
  49336. value: function () {
  49337. this.componentCache = {};
  49338. this.id = this.getAttribute('id');
  49339. this.isMixin = true;
  49340. }
  49341. },
  49342. attributeChangedCallback: {
  49343. value: function (attr, oldVal, newVal) {
  49344. this.cacheAttribute(attr, newVal);
  49345. this.updateEntities();
  49346. }
  49347. },
  49348. attachedCallback: {
  49349. value: function () {
  49350. this.sceneEl = this.closestScene();
  49351. this.cacheAttributes();
  49352. this.updateEntities();
  49353. this.load();
  49354. }
  49355. },
  49356. /**
  49357. * setAttribute that parses and caches component values.
  49358. */
  49359. setAttribute: {
  49360. value: function (attr, value) {
  49361. window.HTMLElement.prototype.setAttribute.call(this, attr, value);
  49362. this.cacheAttribute(attr, value);
  49363. }
  49364. },
  49365. /**
  49366. * If `attr` is a component, then parse the value using the schema and store it.
  49367. */
  49368. cacheAttribute: {
  49369. value: function (attr, value) {
  49370. var component;
  49371. var componentName;
  49372. // Get component data.
  49373. componentName = utils.split(attr, MULTIPLE_COMPONENT_DELIMITER)[0];
  49374. component = components[componentName];
  49375. if (!component) { return; }
  49376. if (value === undefined) {
  49377. value = window.HTMLElement.prototype.getAttribute.call(this, attr);
  49378. }
  49379. this.componentCache[attr] = component.parseAttrValueForCache(value);
  49380. }
  49381. },
  49382. /**
  49383. * If `attr` is a component, then grab pre-parsed value from the cache.
  49384. * Else do a normal getAttribute.
  49385. */
  49386. getAttribute: {
  49387. value: function (attr) {
  49388. return this.componentCache[attr] ||
  49389. window.HTMLElement.prototype.getAttribute.call(this, attr);
  49390. }
  49391. },
  49392. /**
  49393. * Parse and cache every component defined on the mixin.
  49394. */
  49395. cacheAttributes: {
  49396. value: function () {
  49397. var attributes = this.attributes;
  49398. var attrName;
  49399. var i;
  49400. for (i = 0; i < attributes.length; i++) {
  49401. attrName = attributes[i].name;
  49402. this.cacheAttribute(attrName);
  49403. }
  49404. }
  49405. },
  49406. /**
  49407. * For entities that already have been loaded by the time the mixin was attached, tell
  49408. * those entities to register the mixin and refresh their component data.
  49409. */
  49410. updateEntities: {
  49411. value: function () {
  49412. var entity;
  49413. var entities;
  49414. var i;
  49415. if (!this.sceneEl) { return; }
  49416. entities = this.sceneEl.querySelectorAll('[mixin~=' + this.id + ']');
  49417. for (i = 0; i < entities.length; i++) {
  49418. entity = entities[i];
  49419. if (!entity.hasLoaded || entity.isMixin) { continue; }
  49420. entity.mixinUpdate(this.id);
  49421. }
  49422. }
  49423. }
  49424. })
  49425. });
  49426. },{"../utils":176,"./a-node":101,"./a-register-element":102,"./component":103}],101:[function(_dereq_,module,exports){
  49427. /* global CustomEvent */
  49428. var registerElement = _dereq_('./a-register-element').registerElement;
  49429. var isNode = _dereq_('./a-register-element').isNode;
  49430. var utils = _dereq_('../utils/');
  49431. var warn = utils.debug('core:a-node:warn');
  49432. var error = utils.debug('core:a-node:error');
  49433. /**
  49434. * Base class for A-Frame that manages loading of objects.
  49435. *
  49436. * Nodes can be modified using mixins.
  49437. * Nodes emit a `loaded` event when they and their children have initialized.
  49438. */
  49439. module.exports = registerElement('a-node', {
  49440. prototype: Object.create(window.HTMLElement.prototype, {
  49441. createdCallback: {
  49442. value: function () {
  49443. this.computedMixinStr = '';
  49444. this.hasLoaded = false;
  49445. this.isNode = true;
  49446. this.mixinEls = [];
  49447. },
  49448. writable: window.debug
  49449. },
  49450. attachedCallback: {
  49451. value: function () {
  49452. var mixins;
  49453. this.sceneEl = this.closestScene();
  49454. if (!this.sceneEl) {
  49455. warn('You are attempting to attach <' + this.tagName + '> outside of an A-Frame ' +
  49456. 'scene. Append this element to `<a-scene>` instead.');
  49457. }
  49458. this.hasLoaded = false;
  49459. this.emit('nodeready', undefined, false);
  49460. if (!this.isMixin) {
  49461. mixins = this.getAttribute('mixin');
  49462. if (mixins) { this.updateMixins(mixins); }
  49463. }
  49464. },
  49465. writable: window.debug
  49466. },
  49467. /**
  49468. * Handle mixin.
  49469. */
  49470. attributeChangedCallback: {
  49471. value: function (attr, oldVal, newVal) {
  49472. // Ignore if `<a-node>` code is just updating computed mixin in the DOM.
  49473. if (newVal === this.computedMixinStr) { return; }
  49474. if (attr === 'mixin' && !this.isMixin) {
  49475. this.updateMixins(newVal, oldVal);
  49476. }
  49477. }
  49478. },
  49479. /**
  49480. * Returns the first scene by traversing up the tree starting from and
  49481. * including receiver element.
  49482. */
  49483. closestScene: {
  49484. value: function closest () {
  49485. var element = this;
  49486. while (element) {
  49487. if (element.isScene) { break; }
  49488. element = element.parentElement;
  49489. }
  49490. return element;
  49491. }
  49492. },
  49493. /**
  49494. * Returns first element matching a selector by traversing up the tree starting
  49495. * from and including receiver element.
  49496. *
  49497. * @param {string} selector - Selector of element to find.
  49498. */
  49499. closest: {
  49500. value: function closest (selector) {
  49501. var matches = this.matches || this.mozMatchesSelector ||
  49502. this.msMatchesSelector || this.oMatchesSelector || this.webkitMatchesSelector;
  49503. var element = this;
  49504. while (element) {
  49505. if (matches.call(element, selector)) { break; }
  49506. element = element.parentElement;
  49507. }
  49508. return element;
  49509. }
  49510. },
  49511. detachedCallback: {
  49512. value: function () {
  49513. this.hasLoaded = false;
  49514. }
  49515. },
  49516. /**
  49517. * Wait for children to load, if any.
  49518. * Then emit `loaded` event and set `hasLoaded`.
  49519. */
  49520. load: {
  49521. value: function (cb, childFilter) {
  49522. var children;
  49523. var childrenLoaded;
  49524. var self = this;
  49525. if (this.hasLoaded) { return; }
  49526. // Default to waiting for all nodes.
  49527. childFilter = childFilter || isNode;
  49528. // Wait for children to load (if any), then load.
  49529. children = this.getChildren();
  49530. childrenLoaded = children.filter(childFilter).map(function (child) {
  49531. return new Promise(function waitForLoaded (resolve) {
  49532. if (child.hasLoaded) { return resolve(); }
  49533. child.addEventListener('loaded', resolve);
  49534. });
  49535. });
  49536. Promise.all(childrenLoaded).then(function emitLoaded () {
  49537. self.hasLoaded = true;
  49538. if (cb) { cb(); }
  49539. self.emit('loaded', undefined, false);
  49540. }).catch(function (err) {
  49541. error('Failure loading node: ', err);
  49542. });
  49543. },
  49544. writable: true
  49545. },
  49546. getChildren: {
  49547. value: function () {
  49548. return Array.prototype.slice.call(this.children, 0);
  49549. }
  49550. },
  49551. /**
  49552. * Unregister old mixins and listeners.
  49553. * Register new mixins and listeners.
  49554. * Registering means to update `this.mixinEls` with listeners.
  49555. */
  49556. updateMixins: {
  49557. value: (function () {
  49558. var newMixinIdArray = [];
  49559. var oldMixinIdArray = [];
  49560. var mixinIds = {};
  49561. return function (newMixins, oldMixins) {
  49562. var i;
  49563. var newMixinIds;
  49564. var oldMixinIds;
  49565. newMixinIdArray.length = 0;
  49566. oldMixinIdArray.length = 0;
  49567. newMixinIds = newMixins ? utils.split(newMixins.trim(), /\s+/) : newMixinIdArray;
  49568. oldMixinIds = oldMixins ? utils.split(oldMixins.trim(), /\s+/) : oldMixinIdArray;
  49569. mixinIds.newMixinIds = newMixinIds;
  49570. mixinIds.oldMixinIds = oldMixinIds;
  49571. // Unregister old mixins.
  49572. for (i = 0; i < oldMixinIds.length; i++) {
  49573. if (newMixinIds.indexOf(oldMixinIds[i]) === -1) {
  49574. this.unregisterMixin(oldMixinIds[i]);
  49575. }
  49576. }
  49577. // Register new mixins.
  49578. this.computedMixinStr = '';
  49579. this.mixinEls.length = 0;
  49580. for (i = 0; i < newMixinIds.length; i++) {
  49581. this.registerMixin(document.getElementById(newMixinIds[i]));
  49582. }
  49583. // Update DOM. Keep track of `computedMixinStr` to not recurse back here after
  49584. // update.
  49585. if (this.computedMixinStr) {
  49586. this.computedMixinStr = this.computedMixinStr.trim();
  49587. window.HTMLElement.prototype.setAttribute.call(this, 'mixin',
  49588. this.computedMixinStr);
  49589. }
  49590. return mixinIds;
  49591. };
  49592. })()
  49593. },
  49594. /**
  49595. * From mixin ID, add mixin element to `mixinEls`.
  49596. *
  49597. * @param {Element} mixinEl
  49598. */
  49599. registerMixin: {
  49600. value: function (mixinEl) {
  49601. var compositedMixinIds;
  49602. var i;
  49603. var mixin;
  49604. if (!mixinEl) { return; }
  49605. // Register composited mixins (if mixin has mixins).
  49606. mixin = mixinEl.getAttribute('mixin');
  49607. if (mixin) {
  49608. compositedMixinIds = utils.split(mixin.trim(), /\s+/);
  49609. for (i = 0; i < compositedMixinIds.length; i++) {
  49610. this.registerMixin(document.getElementById(compositedMixinIds[i]));
  49611. }
  49612. }
  49613. // Register mixin.
  49614. this.computedMixinStr = this.computedMixinStr + ' ' + mixinEl.id;
  49615. this.mixinEls.push(mixinEl);
  49616. }
  49617. },
  49618. setAttribute: {
  49619. value: function (attr, newValue) {
  49620. if (attr === 'mixin') { this.updateMixins(newValue); }
  49621. window.HTMLElement.prototype.setAttribute.call(this, attr, newValue);
  49622. }
  49623. },
  49624. unregisterMixin: {
  49625. value: function (mixinId) {
  49626. var i;
  49627. var mixinEls = this.mixinEls;
  49628. var mixinEl;
  49629. for (i = 0; i < mixinEls.length; ++i) {
  49630. mixinEl = mixinEls[i];
  49631. if (mixinId === mixinEl.id) {
  49632. mixinEls.splice(i, 1);
  49633. break;
  49634. }
  49635. }
  49636. }
  49637. },
  49638. /**
  49639. * Emit a DOM event.
  49640. *
  49641. * @param {string} name - Name of event.
  49642. * @param {object} [detail={}] - Custom data to pass as `detail` to the event.
  49643. * @param {boolean} [bubbles=true] - Whether the event should bubble.
  49644. * @param {object} [extraData] - Extra data to pass to the event, if any.
  49645. */
  49646. emit: {
  49647. value: (function () {
  49648. var data = {};
  49649. return function (name, detail, bubbles, extraData) {
  49650. if (bubbles === undefined) { bubbles = true; }
  49651. data.bubbles = !!bubbles;
  49652. data.detail = detail;
  49653. // If extra data is present, we need to create a new object.
  49654. if (extraData) { data = utils.extend({}, extraData, data); }
  49655. this.dispatchEvent(new CustomEvent(name, data));
  49656. };
  49657. })(),
  49658. writable: window.debug
  49659. }
  49660. })
  49661. });
  49662. },{"../utils/":176,"./a-register-element":102}],102:[function(_dereq_,module,exports){
  49663. /*
  49664. ------------------------------------------------------------
  49665. ------------- WARNING WARNING WARNING WARNING --------------
  49666. ------------------------------------------------------------
  49667. This module wraps registerElement to deal with components that inherit from
  49668. `ANode` and `AEntity`. It's a pass through in any other case.
  49669. It wraps some of the prototype methods of the created element to make sure
  49670. that the corresponding functions in the base prototypes (`AEntity` and `ANode`)
  49671. are also invoked. The method in the base prototype is always called before the one
  49672. in the derived prototype.
  49673. */
  49674. // Polyfill `document.registerElement`.
  49675. _dereq_('document-register-element');
  49676. var ANode; // Must declare before AEntity. Initialized at the bottom.
  49677. var AEntity;
  49678. var knownTags = module.exports.knownTags = {};
  49679. function addTagName (tagName) {
  49680. knownTags[tagName.toLowerCase()] = true;
  49681. }
  49682. /**
  49683. * Return whether the element type is one of our known registered ones.
  49684. *
  49685. * @param {string} node - The name of the tag to register.
  49686. * @returns {boolean} Whether the tag name matches that of our registered custom elements.
  49687. */
  49688. module.exports.isNode = function (node) {
  49689. return node.tagName.toLowerCase() in knownTags || node.isNode;
  49690. };
  49691. /**
  49692. * @param {string} tagName - The name of the tag to register.
  49693. * @param {object} obj - The prototype of the new element.
  49694. * @returns {object} The prototype of the new element.
  49695. */
  49696. module.exports.registerElement = function (tagName, obj) {
  49697. var proto = Object.getPrototypeOf(obj.prototype);
  49698. var newObj = obj;
  49699. var isANode = ANode && proto === ANode.prototype;
  49700. var isAEntity = AEntity && proto === AEntity.prototype;
  49701. if (isANode || isAEntity) { addTagName(tagName); }
  49702. // Wrap if element inherits from `ANode`.
  49703. if (isANode) {
  49704. newObj = wrapANodeMethods(obj.prototype);
  49705. newObj = {prototype: Object.create(proto, newObj)};
  49706. }
  49707. // Wrap if element inherits from `AEntity`.
  49708. if (isAEntity) {
  49709. newObj = wrapAEntityMethods(obj.prototype);
  49710. newObj = {prototype: Object.create(proto, newObj)};
  49711. }
  49712. // Give all functions their proper name.
  49713. Object.getOwnPropertyNames(newObj.prototype).forEach(function (propName) {
  49714. var propVal = newObj.prototype[propName];
  49715. if (typeof propVal === 'function') {
  49716. propVal.displayName = propName;
  49717. }
  49718. });
  49719. return document.registerElement(tagName, newObj);
  49720. };
  49721. /**
  49722. * Wrap some obj methods to call those on `ANode` base prototype.
  49723. *
  49724. * @param {object} obj - Object that contains the methods that will be wrapped.
  49725. * @return {object} An object with the same properties as the input parameter but
  49726. * with some of methods wrapped.
  49727. */
  49728. function wrapANodeMethods (obj) {
  49729. var newObj = {};
  49730. var ANodeMethods = [
  49731. 'attachedCallback',
  49732. 'attributeChangedCallback',
  49733. 'createdCallback',
  49734. 'detachedCallback'
  49735. ];
  49736. wrapMethods(newObj, ANodeMethods, obj, ANode.prototype);
  49737. copyProperties(obj, newObj);
  49738. return newObj;
  49739. }
  49740. /**
  49741. * This wraps some of the obj methods to call those on `AEntity` base prototype.
  49742. *
  49743. * @param {object} obj - The objects that contains the methods that will be wrapped.
  49744. * @return {object} - An object with the same properties as the input parameter but
  49745. * with some of methods wrapped.
  49746. */
  49747. function wrapAEntityMethods (obj) {
  49748. var newObj = {};
  49749. var ANodeMethods = [
  49750. 'attachedCallback',
  49751. 'attributeChangedCallback',
  49752. 'createdCallback',
  49753. 'detachedCallback'
  49754. ];
  49755. var AEntityMethods = [
  49756. 'attachedCallback',
  49757. 'attributeChangedCallback',
  49758. 'createdCallback',
  49759. 'detachedCallback'
  49760. ];
  49761. wrapMethods(newObj, ANodeMethods, obj, ANode.prototype);
  49762. wrapMethods(newObj, AEntityMethods, obj, AEntity.prototype);
  49763. // Copies the remaining properties into the new object.
  49764. copyProperties(obj, newObj);
  49765. return newObj;
  49766. }
  49767. /**
  49768. * Wrap a list a methods to ensure that those in the base prototype are called
  49769. * before the derived one.
  49770. *
  49771. * @param {object} targetObj - Object that will contain the wrapped methods.
  49772. * @param {array} methodList - List of methods from the derivedObj that will be wrapped.
  49773. * @param {object} derivedObject - Object that inherits from the baseObj.
  49774. * @param {object} baseObj - Object that derivedObj inherits from.
  49775. */
  49776. function wrapMethods (targetObj, methodList, derivedObj, baseObj) {
  49777. methodList.forEach(function (methodName) {
  49778. wrapMethod(targetObj, methodName, derivedObj, baseObj);
  49779. });
  49780. }
  49781. module.exports.wrapMethods = wrapMethods;
  49782. /**
  49783. * Wrap one method to ensure that the one in the base prototype is called before
  49784. * the one in the derived one.
  49785. *
  49786. * @param {object} obj - Object that will contain the wrapped method.
  49787. * @param {string} methodName - The name of the method that will be wrapped.
  49788. * @param {object} derivedObject - Object that inherits from the baseObj.
  49789. * @param {object} baseObj - Object that derivedObj inherits from.
  49790. */
  49791. function wrapMethod (obj, methodName, derivedObj, baseObj) {
  49792. var derivedMethod = derivedObj[methodName];
  49793. var baseMethod = baseObj[methodName];
  49794. // Derived prototype does not define method, no need to wrap.
  49795. if (!derivedMethod || !baseMethod) { return; }
  49796. // Derived prototype doesn't override the one in the base one, no need to wrap.
  49797. if (derivedMethod === baseMethod) { return; }
  49798. // Wrap to ensure the base method is called before the one in the derived prototype.
  49799. obj[methodName] = {
  49800. value: function wrappedMethod () {
  49801. baseMethod.apply(this, arguments);
  49802. return derivedMethod.apply(this, arguments);
  49803. },
  49804. writable: window.debug
  49805. };
  49806. }
  49807. /**
  49808. * It copies the properties from source to destination object if they don't
  49809. * exist already.
  49810. *
  49811. * @param {object} source - The object where properties are copied from.
  49812. * @param {type} destination - The object where properties are copied to.
  49813. */
  49814. function copyProperties (source, destination) {
  49815. var props = Object.getOwnPropertyNames(source);
  49816. props.forEach(function (prop) {
  49817. var desc;
  49818. if (!destination[prop]) {
  49819. desc = Object.getOwnPropertyDescriptor(source, prop);
  49820. destination[prop] = {value: source[prop], writable: desc.writable};
  49821. }
  49822. });
  49823. }
  49824. ANode = _dereq_('./a-node');
  49825. AEntity = _dereq_('./a-entity');
  49826. },{"./a-entity":99,"./a-node":101,"document-register-element":11}],103:[function(_dereq_,module,exports){
  49827. /* global Node */
  49828. var schema = _dereq_('./schema');
  49829. var scenes = _dereq_('./scene/scenes');
  49830. var systems = _dereq_('./system');
  49831. var utils = _dereq_('../utils/');
  49832. var components = module.exports.components = {}; // Keep track of registered components.
  49833. var parseProperties = schema.parseProperties;
  49834. var parseProperty = schema.parseProperty;
  49835. var processSchema = schema.process;
  49836. var isSingleProp = schema.isSingleProperty;
  49837. var stringifyProperties = schema.stringifyProperties;
  49838. var stringifyProperty = schema.stringifyProperty;
  49839. var styleParser = utils.styleParser;
  49840. var warn = utils.debug('core:component:warn');
  49841. var aframeScript = document.currentScript;
  49842. var upperCaseRegExp = new RegExp('[A-Z]+');
  49843. // Object pools by component, created upon registration.
  49844. var objectPools = {};
  49845. /**
  49846. * Component class definition.
  49847. *
  49848. * Components configure appearance, modify behavior, or add functionality to
  49849. * entities. The behavior and appearance of an entity can be changed at runtime
  49850. * by adding, removing, or updating components. Entities do not share instances
  49851. * of components.
  49852. *
  49853. * @member {object} el - Reference to the entity element.
  49854. * @member {string} attrValue - Value of the corresponding HTML attribute.
  49855. * @member {object} data - Component data populated by parsing the
  49856. * mapped attribute of the component plus applying defaults and mixins.
  49857. */
  49858. var Component = module.exports.Component = function (el, attrValue, id) {
  49859. var self = this;
  49860. this.el = el;
  49861. this.id = id;
  49862. this.attrName = this.name + (id ? '__' + id : '');
  49863. this.evtDetail = {id: this.id, name: this.name};
  49864. this.initialized = false;
  49865. this.isSingleProperty = isSingleProp(this.schema);
  49866. this.isSinglePropertyObject = this.isSingleProperty &&
  49867. isObject(parseProperty(undefined, this.schema)) &&
  49868. !(this.schema.default instanceof window.HTMLElement);
  49869. this.isObjectBased = !this.isSingleProperty || this.isSinglePropertyObject;
  49870. this.el.components[this.attrName] = this;
  49871. this.objectPool = objectPools[this.name];
  49872. eventsBind(this, this.events);
  49873. // Store component data from previous update call.
  49874. this.attrValue = undefined;
  49875. if (this.isObjectBased) {
  49876. this.nextData = this.objectPool.use();
  49877. // Drop any properties added by dynamic schemas in previous use
  49878. utils.objectPool.removeUnusedKeys(this.nextData, this.schema);
  49879. this.oldData = this.objectPool.use();
  49880. utils.objectPool.removeUnusedKeys(this.oldData, this.schema);
  49881. this.previousOldData = this.objectPool.use();
  49882. utils.objectPool.removeUnusedKeys(this.previousOldData, this.schema);
  49883. this.parsingAttrValue = this.objectPool.use();
  49884. utils.objectPool.removeUnusedKeys(this.parsingAttrValue, this.schema);
  49885. } else {
  49886. this.nextData = undefined;
  49887. this.oldData = undefined;
  49888. this.previousOldData = undefined;
  49889. this.parsingAttrValue = undefined;
  49890. }
  49891. // Last value passed to updateProperties.
  49892. this.throttledEmitComponentChanged = utils.throttle(function emitChange () {
  49893. el.emit('componentchanged', self.evtDetail, false);
  49894. }, 200);
  49895. this.updateProperties(attrValue);
  49896. };
  49897. Component.prototype = {
  49898. /**
  49899. * Contains the type schema and defaults for the data values.
  49900. * Data is coerced into the types of the values of the defaults.
  49901. */
  49902. schema: {},
  49903. /**
  49904. * Init handler. Similar to attachedCallback.
  49905. * Called during component initialization and is only run once.
  49906. * Components can use this to set initial state.
  49907. */
  49908. init: function () { /* no-op */ },
  49909. /**
  49910. * Map of event names to binded event handlers that will be lifecycle-handled.
  49911. * Will be detached on pause / remove.
  49912. * Will be attached on play.
  49913. */
  49914. events: {},
  49915. /**
  49916. * Update handler. Similar to attributeChangedCallback.
  49917. * Called whenever component's data changes.
  49918. * Also called on component initialization when the component receives initial data.
  49919. *
  49920. * @param {object} prevData - Previous attributes of the component.
  49921. */
  49922. update: function (prevData) { /* no-op */ },
  49923. updateSchema: undefined,
  49924. /**
  49925. * Tick handler.
  49926. * Called on each tick of the scene render loop.
  49927. * Affected by play and pause.
  49928. *
  49929. * @param {number} time - Scene tick time.
  49930. * @param {number} timeDelta - Difference in current render time and previous render time.
  49931. */
  49932. tick: undefined,
  49933. /**
  49934. * Tock handler.
  49935. * Called on each tock of the scene render loop.
  49936. * Affected by play and pause.
  49937. *
  49938. * @param {number} time - Scene tick time.
  49939. * @param {number} timeDelta - Difference in current render time and previous render time.
  49940. * @param {object} camera - Camera used to render the last frame.
  49941. */
  49942. tock: undefined,
  49943. /**
  49944. * Called to start any dynamic behavior (e.g., animation, AI, events, physics).
  49945. */
  49946. play: function () { /* no-op */ },
  49947. /**
  49948. * Called to stop any dynamic behavior (e.g., animation, AI, events, physics).
  49949. */
  49950. pause: function () { /* no-op */ },
  49951. /**
  49952. * Remove handler. Similar to detachedCallback.
  49953. * Called whenever component is removed from the entity (i.e., removeAttribute).
  49954. * Components can use this to reset behavior on the entity.
  49955. */
  49956. remove: function () { /* no-op */ },
  49957. /**
  49958. * Parses each property based on property type.
  49959. * If component is single-property, then parses the single property value.
  49960. *
  49961. * @param {string} value - HTML attribute value.
  49962. * @param {boolean} silent - Suppress warning messages.
  49963. * @returns {object} Component data.
  49964. */
  49965. parse: function (value, silent) {
  49966. var schema = this.schema;
  49967. if (this.isSingleProperty) { return parseProperty(value, schema); }
  49968. return parseProperties(styleParser.parse(value), schema, true, this.name, silent);
  49969. },
  49970. /**
  49971. * Stringify properties if necessary.
  49972. *
  49973. * Only called from `Entity.setAttribute` for properties whose parsers accept a non-string
  49974. * value (e.g., selector, vec3 property types).
  49975. *
  49976. * @param {object} data - Complete component data.
  49977. * @returns {string}
  49978. */
  49979. stringify: function (data) {
  49980. var schema = this.schema;
  49981. if (typeof data === 'string') { return data; }
  49982. if (this.isSingleProperty) { return stringifyProperty(data, schema); }
  49983. data = stringifyProperties(data, schema);
  49984. return styleParser.stringify(data);
  49985. },
  49986. /**
  49987. * Update the cache of the pre-parsed attribute value.
  49988. *
  49989. * @param {string} value - New data.
  49990. * @param {boolean } clobber - Whether to wipe out and replace previous data.
  49991. */
  49992. updateCachedAttrValue: function (value, clobber) {
  49993. var newAttrValue;
  49994. var tempObject;
  49995. var property;
  49996. if (value === undefined) { return; }
  49997. // If null value is the new attribute value, make the attribute value falsy.
  49998. if (value === null) {
  49999. if (this.isObjectBased && this.attrValue) {
  50000. this.objectPool.recycle(this.attrValue);
  50001. }
  50002. this.attrValue = undefined;
  50003. return;
  50004. }
  50005. if (value instanceof Object && !(value instanceof window.HTMLElement)) {
  50006. // If value is an object, copy it to our pooled newAttrValue object to use to update
  50007. // the attrValue.
  50008. tempObject = this.objectPool.use();
  50009. newAttrValue = utils.extend(tempObject, value);
  50010. } else {
  50011. newAttrValue = this.parseAttrValueForCache(value);
  50012. }
  50013. // Merge new data with previous `attrValue` if updating and not clobbering.
  50014. if (this.isObjectBased && !clobber && this.attrValue) {
  50015. for (property in this.attrValue) {
  50016. if (newAttrValue[property] === undefined) {
  50017. newAttrValue[property] = this.attrValue[property];
  50018. }
  50019. }
  50020. }
  50021. // Update attrValue.
  50022. if (this.isObjectBased && !this.attrValue) {
  50023. this.attrValue = this.objectPool.use();
  50024. }
  50025. utils.objectPool.clearObject(this.attrValue);
  50026. this.attrValue = extendProperties(this.attrValue, newAttrValue, this.isObjectBased);
  50027. utils.objectPool.clearObject(tempObject);
  50028. },
  50029. /**
  50030. * Given an HTML attribute value parses the string based on the component schema.
  50031. * To avoid double parsings of strings into strings we store the original instead
  50032. * of the parsed one
  50033. *
  50034. * @param {string} value - HTML attribute value
  50035. */
  50036. parseAttrValueForCache: function (value) {
  50037. var parsedValue;
  50038. if (typeof value !== 'string') { return value; }
  50039. if (this.isSingleProperty) {
  50040. parsedValue = this.schema.parse(value);
  50041. /**
  50042. * To avoid bogus double parsings. Cached values will be parsed when building
  50043. * component data. For instance when parsing a src id to its url, we want to cache
  50044. * original string and not the parsed one (#monster -> models/monster.dae)
  50045. * so when building data we parse the expected value.
  50046. */
  50047. if (typeof parsedValue === 'string') { parsedValue = value; }
  50048. } else {
  50049. // Parse using the style parser to avoid double parsing of individual properties.
  50050. utils.objectPool.clearObject(this.parsingAttrValue);
  50051. parsedValue = styleParser.parse(value, this.parsingAttrValue);
  50052. }
  50053. return parsedValue;
  50054. },
  50055. /**
  50056. * Write cached attribute data to the entity DOM element.
  50057. *
  50058. * @param {boolean} isDefault - Whether component is a default component. Always flush for
  50059. * default components.
  50060. */
  50061. flushToDOM: function (isDefault) {
  50062. var attrValue = isDefault ? this.data : this.attrValue;
  50063. if (attrValue === null || attrValue === undefined) { return; }
  50064. window.HTMLElement.prototype.setAttribute.call(this.el, this.attrName,
  50065. this.stringify(attrValue));
  50066. },
  50067. /**
  50068. * Apply new component data if data has changed (from setAttribute).
  50069. *
  50070. * @param {string} attrValue - HTML attribute value.
  50071. * If undefined, use the cached attribute value and continue updating properties.
  50072. * @param {boolean} clobber - The previous component data is overwritten by the atrrValue
  50073. */
  50074. updateProperties: function (attrValue, clobber) {
  50075. var el = this.el;
  50076. // Just cache the attribute if the entity has not loaded
  50077. // Components are not initialized until the entity has loaded
  50078. if (!el.hasLoaded) {
  50079. this.updateCachedAttrValue(attrValue);
  50080. return;
  50081. }
  50082. // Parse the attribute value.
  50083. // Cache current attrValue for future updates. Updates `this.attrValue`.
  50084. // `null` means no value on purpose, do not set a default value, let mixins take over.
  50085. if (attrValue !== null) {
  50086. attrValue = this.parseAttrValueForCache(attrValue);
  50087. }
  50088. // Cache current attrValue for future updates.
  50089. this.updateCachedAttrValue(attrValue, clobber);
  50090. if (this.initialized) {
  50091. this.updateComponent(attrValue, clobber);
  50092. this.callUpdateHandler();
  50093. } else {
  50094. this.initComponent();
  50095. }
  50096. },
  50097. initComponent: function () {
  50098. var el = this.el;
  50099. var initialOldData;
  50100. // Build data.
  50101. if (this.updateSchema) { this.updateSchema(this.buildData(this.attrValue, false, true)); }
  50102. this.data = this.buildData(this.attrValue);
  50103. // Component is being already initialized.
  50104. if (el.initializingComponents[this.name]) { return; }
  50105. // Prevent infinite loop in case of init method setting same component on the entity.
  50106. el.initializingComponents[this.name] = true;
  50107. // Initialize component.
  50108. this.init();
  50109. this.initialized = true;
  50110. delete el.initializingComponents[this.name];
  50111. // Store current data as previous data for future updates.
  50112. this.oldData = extendProperties(this.oldData, this.data, this.isObjectBased);
  50113. // For oldData, pass empty object to multiple-prop schemas or object single-prop schema.
  50114. // Pass undefined to rest of types.
  50115. initialOldData = this.isObjectBased ? this.objectPool.use() : undefined;
  50116. this.update(initialOldData);
  50117. if (this.isObjectBased) { this.objectPool.recycle(initialOldData); }
  50118. // Play the component if the entity is playing.
  50119. if (el.isPlaying) { this.play(); }
  50120. el.emit('componentinitialized', this.evtDetail, false);
  50121. },
  50122. /**
  50123. * @param attrValue - Passed argument from setAttribute.
  50124. */
  50125. updateComponent: function (attrValue, clobber) {
  50126. var key;
  50127. var mayNeedSchemaUpdate;
  50128. if (clobber) {
  50129. // Clobber. Rebuild.
  50130. if (this.updateSchema) {
  50131. this.updateSchema(this.buildData(this.attrValue, true, true));
  50132. }
  50133. this.data = this.buildData(this.attrValue, true, false);
  50134. return;
  50135. }
  50136. // Apply new value to this.data in place since direct update.
  50137. if (this.isSingleProperty) {
  50138. if (this.isObjectBased) {
  50139. parseProperty(attrValue, this.schema);
  50140. }
  50141. // Single-property (already parsed).
  50142. this.data = attrValue;
  50143. return;
  50144. }
  50145. parseProperties(attrValue, this.schema, true, this.name);
  50146. // Check if we need to update schema.
  50147. if (this.schemaChangeKeys.length) {
  50148. for (key in attrValue) {
  50149. if (this.schema[key].schemaChange) {
  50150. mayNeedSchemaUpdate = true;
  50151. break;
  50152. }
  50153. }
  50154. }
  50155. if (mayNeedSchemaUpdate) {
  50156. // Rebuild data if need schema update.
  50157. if (this.updateSchema) {
  50158. this.updateSchema(this.buildData(this.attrValue, true, true));
  50159. }
  50160. this.data = this.buildData(this.attrValue, true, false);
  50161. return;
  50162. }
  50163. // Normal update.
  50164. for (key in attrValue) {
  50165. if (attrValue[key] === undefined) { continue; }
  50166. this.data[key] = attrValue[key];
  50167. }
  50168. },
  50169. /**
  50170. * Check if component should fire update and fire update lifecycle handler.
  50171. */
  50172. callUpdateHandler: function () {
  50173. var hasComponentChanged;
  50174. // Store the previous old data before we calculate the new oldData.
  50175. if (this.previousOldData instanceof Object) {
  50176. utils.objectPool.clearObject(this.previousOldData);
  50177. }
  50178. if (this.isObjectBased) {
  50179. copyData(this.previousOldData, this.oldData);
  50180. } else {
  50181. this.previousOldData = this.oldData;
  50182. }
  50183. hasComponentChanged = !utils.deepEqual(this.oldData, this.data);
  50184. // Don't update if properties haven't changed.
  50185. // Always update rotation, position, scale.
  50186. if (!this.isPositionRotationScale && !hasComponentChanged) { return; }
  50187. // Store current data as previous data for future updates.
  50188. // Reuse `this.oldData` object to try not to allocate another one.
  50189. if (this.oldData instanceof Object) { utils.objectPool.clearObject(this.oldData); }
  50190. this.oldData = extendProperties(this.oldData, this.data, this.isObjectBased);
  50191. // Update component with the previous old data.
  50192. this.update(this.previousOldData);
  50193. this.throttledEmitComponentChanged();
  50194. },
  50195. handleMixinUpdate: function () {
  50196. this.data = this.buildData(this.attrValue);
  50197. this.callUpdateHandler();
  50198. },
  50199. /**
  50200. * Reset value of a property to the property's default value.
  50201. * If single-prop component, reset value to component's default value.
  50202. *
  50203. * @param {string} propertyName - Name of property to reset.
  50204. */
  50205. resetProperty: function (propertyName) {
  50206. if (this.isObjectBased) {
  50207. if (!(propertyName in this.attrValue)) { return; }
  50208. delete this.attrValue[propertyName];
  50209. this.data[propertyName] = this.schema[propertyName].default;
  50210. } else {
  50211. this.attrValue = this.schema.default;
  50212. this.data = this.schema.default;
  50213. }
  50214. this.updateProperties(this.attrValue);
  50215. },
  50216. /**
  50217. * Extend schema of component given a partial schema.
  50218. *
  50219. * Some components might want to mutate their schema based on certain properties.
  50220. * e.g., Material component changes its schema based on `shader` to account for different
  50221. * uniforms
  50222. *
  50223. * @param {object} schemaAddon - Schema chunk that extend base schema.
  50224. */
  50225. extendSchema: function (schemaAddon) {
  50226. var extendedSchema;
  50227. // Clone base schema.
  50228. extendedSchema = utils.extend({}, components[this.name].schema);
  50229. // Extend base schema with new schema chunk.
  50230. utils.extend(extendedSchema, schemaAddon);
  50231. this.schema = processSchema(extendedSchema);
  50232. this.el.emit('schemachanged', this.evtDetail);
  50233. },
  50234. /**
  50235. * Build component data from the current state of the entity.data.
  50236. *
  50237. * Precedence:
  50238. * 1. Defaults data
  50239. * 2. Mixin data.
  50240. * 3. Attribute data.
  50241. *
  50242. * Finally coerce the data to the types of the defaults.
  50243. *
  50244. * @param {object} newData - Element new data.
  50245. * @param {boolean} clobber - The previous data is completely replaced by the new one.
  50246. * @param {boolean} silent - Suppress warning messages.
  50247. * @return {object} The component data
  50248. */
  50249. buildData: function (newData, clobber, silent) {
  50250. var componentDefined;
  50251. var data;
  50252. var defaultValue;
  50253. var key;
  50254. var mixinData;
  50255. var nextData = this.nextData;
  50256. var schema = this.schema;
  50257. var i;
  50258. var mixinEls = this.el.mixinEls;
  50259. var previousData;
  50260. // Whether component has a defined value. For arrays, treat empty as not defined.
  50261. componentDefined = newData && newData.constructor === Array
  50262. ? newData.length
  50263. : newData !== undefined && newData !== null;
  50264. if (this.isObjectBased) { utils.objectPool.clearObject(nextData); }
  50265. // 1. Gather default values (lowest precendence).
  50266. if (this.isSingleProperty) {
  50267. if (this.isObjectBased) {
  50268. // If object-based single-prop, then copy over the data to our pooled object.
  50269. data = copyData(nextData, schema.default);
  50270. } else {
  50271. // If is plain single-prop, copy by value the default.
  50272. data = isObjectOrArray(schema.default)
  50273. ? utils.clone(schema.default)
  50274. : schema.default;
  50275. }
  50276. } else {
  50277. // Preserve previously set properties if clobber not enabled.
  50278. previousData = !clobber && this.attrValue;
  50279. // Clone default value if object so components don't share object
  50280. data = previousData instanceof Object
  50281. ? copyData(nextData, previousData)
  50282. : nextData;
  50283. // Apply defaults.
  50284. for (key in schema) {
  50285. defaultValue = schema[key].default;
  50286. if (data[key] !== undefined) { continue; }
  50287. // Clone default value if object so components don't share object
  50288. data[key] = isObjectOrArray(defaultValue)
  50289. ? utils.clone(defaultValue)
  50290. : defaultValue;
  50291. }
  50292. }
  50293. // 2. Gather mixin values.
  50294. for (i = 0; i < mixinEls.length; i++) {
  50295. mixinData = mixinEls[i].getAttribute(this.attrName);
  50296. if (!mixinData) { continue; }
  50297. data = extendProperties(data, mixinData, this.isObjectBased);
  50298. }
  50299. // 3. Gather attribute values (highest precendence).
  50300. if (componentDefined) {
  50301. if (this.isSingleProperty) {
  50302. // If object-based, copy the value to not modify the original.
  50303. if (isObject(newData)) {
  50304. copyData(this.parsingAttrValue, newData);
  50305. return parseProperty(this.parsingAttrValue, schema);
  50306. }
  50307. return parseProperty(newData, schema);
  50308. }
  50309. data = extendProperties(data, newData, this.isObjectBased);
  50310. } else {
  50311. // Parse and coerce using the schema.
  50312. if (this.isSingleProperty) { return parseProperty(data, schema); }
  50313. }
  50314. return parseProperties(data, schema, undefined, this.name, silent);
  50315. },
  50316. /**
  50317. * Attach events from component-defined events map.
  50318. */
  50319. eventsAttach: function () {
  50320. var eventName;
  50321. // Safety detach to prevent double-registration.
  50322. this.eventsDetach();
  50323. for (eventName in this.events) {
  50324. this.el.addEventListener(eventName, this.events[eventName]);
  50325. }
  50326. },
  50327. /**
  50328. * Detach events from component-defined events map.
  50329. */
  50330. eventsDetach: function () {
  50331. var eventName;
  50332. for (eventName in this.events) {
  50333. this.el.removeEventListener(eventName, this.events[eventName]);
  50334. }
  50335. },
  50336. /**
  50337. * Release and free memory.
  50338. */
  50339. destroy: function () {
  50340. this.objectPool.recycle(this.attrValue);
  50341. this.objectPool.recycle(this.oldData);
  50342. this.objectPool.recycle(this.parsingAttrValue);
  50343. this.attrValue = this.oldData = this.parsingAttrValue = undefined;
  50344. }
  50345. };
  50346. function eventsBind (component, events) {
  50347. var eventName;
  50348. for (eventName in events) {
  50349. events[eventName] = events[eventName].bind(component);
  50350. }
  50351. }
  50352. // For testing.
  50353. if (window.debug) {
  50354. var registrationOrderWarnings = module.exports.registrationOrderWarnings = {};
  50355. }
  50356. /**
  50357. * Register a component to A-Frame.
  50358. *
  50359. * @param {string} name - Component name.
  50360. * @param {object} definition - Component schema and lifecycle method handlers.
  50361. * @returns {object} Component.
  50362. */
  50363. module.exports.registerComponent = function (name, definition) {
  50364. var NewComponent;
  50365. var propertyName;
  50366. var proto = {};
  50367. var schema;
  50368. var schemaIsSingleProp;
  50369. // Warning if component is statically registered after the scene.
  50370. if (document.currentScript && document.currentScript !== aframeScript) {
  50371. scenes.forEach(function checkPosition (sceneEl) {
  50372. // Okay to register component after the scene at runtime.
  50373. if (sceneEl.hasLoaded) { return; }
  50374. // Check that component is declared before the scene.
  50375. if (document.currentScript.compareDocumentPosition(sceneEl) ===
  50376. Node.DOCUMENT_POSITION_FOLLOWING) { return; }
  50377. warn('The component `' + name + '` was registered in a <script> tag after the scene. ' +
  50378. 'Component <script> tags in an HTML file should be declared *before* the scene ' +
  50379. 'such that the component is available to entities during scene initialization.');
  50380. // For testing.
  50381. if (window.debug) { registrationOrderWarnings[name] = true; }
  50382. });
  50383. }
  50384. if (upperCaseRegExp.test(name) === true) {
  50385. warn('The component name `' + name + '` contains uppercase characters, but ' +
  50386. 'HTML will ignore the capitalization of attribute names. ' +
  50387. 'Change the name to be lowercase: `' + name.toLowerCase() + '`');
  50388. }
  50389. if (name.indexOf('__') !== -1) {
  50390. throw new Error('The component name `' + name + '` is not allowed. ' +
  50391. 'The sequence __ (double underscore) is reserved to specify an id' +
  50392. ' for multiple components of the same type');
  50393. }
  50394. // Format definition object to prototype object.
  50395. Object.keys(definition).forEach(function (key) {
  50396. proto[key] = {
  50397. value: definition[key],
  50398. writable: true
  50399. };
  50400. });
  50401. if (components[name]) {
  50402. throw new Error('The component `' + name + '` has been already registered. ' +
  50403. 'Check that you are not loading two versions of the same component ' +
  50404. 'or two different components of the same name.');
  50405. }
  50406. NewComponent = function (el, attr, id) {
  50407. Component.call(this, el, attr, id);
  50408. };
  50409. NewComponent.prototype = Object.create(Component.prototype, proto);
  50410. NewComponent.prototype.name = name;
  50411. NewComponent.prototype.isPositionRotationScale =
  50412. name === 'position' || name === 'rotation' || name === 'scale';
  50413. NewComponent.prototype.constructor = NewComponent;
  50414. NewComponent.prototype.system = systems && systems.systems[name];
  50415. NewComponent.prototype.play = wrapPlay(NewComponent.prototype.play);
  50416. NewComponent.prototype.pause = wrapPause(NewComponent.prototype.pause);
  50417. schema = utils.extend(processSchema(NewComponent.prototype.schema,
  50418. NewComponent.prototype.name));
  50419. schemaIsSingleProp = isSingleProp(NewComponent.prototype.schema);
  50420. // Keep track of keys that may potentially change the schema.
  50421. if (!schemaIsSingleProp) {
  50422. NewComponent.prototype.schemaChangeKeys = [];
  50423. for (propertyName in schema) {
  50424. if (schema[propertyName].schemaChange) {
  50425. NewComponent.prototype.schemaChangeKeys.push(propertyName);
  50426. }
  50427. }
  50428. }
  50429. // Create object pool for class of components.
  50430. objectPools[name] = utils.objectPool.createPool();
  50431. components[name] = {
  50432. Component: NewComponent,
  50433. dependencies: NewComponent.prototype.dependencies,
  50434. isSingleProp: schemaIsSingleProp,
  50435. multiple: NewComponent.prototype.multiple,
  50436. name: name,
  50437. parse: NewComponent.prototype.parse,
  50438. parseAttrValueForCache: NewComponent.prototype.parseAttrValueForCache,
  50439. schema: schema,
  50440. stringify: NewComponent.prototype.stringify,
  50441. type: NewComponent.prototype.type
  50442. };
  50443. return NewComponent;
  50444. };
  50445. /**
  50446. * Clone component data.
  50447. * Clone only the properties that are plain objects while keeping a reference for the rest.
  50448. *
  50449. * @param data - Component data to clone.
  50450. * @returns Cloned data.
  50451. */
  50452. function copyData (dest, sourceData) {
  50453. var parsedProperty;
  50454. var key;
  50455. for (key in sourceData) {
  50456. if (sourceData[key] === undefined) { continue; }
  50457. parsedProperty = sourceData[key];
  50458. dest[key] = isObjectOrArray(parsedProperty)
  50459. ? utils.clone(parsedProperty)
  50460. : parsedProperty;
  50461. }
  50462. return dest;
  50463. }
  50464. /**
  50465. * Object extending with checking for single-property schema.
  50466. *
  50467. * @param dest - Destination object or value.
  50468. * @param source - Source object or value
  50469. * @param {boolean} isObjectBased - Whether values are objects.
  50470. * @returns Overridden object or value.
  50471. */
  50472. function extendProperties (dest, source, isObjectBased) {
  50473. var key;
  50474. if (isObjectBased && source.constructor === Object) {
  50475. for (key in source) {
  50476. if (source[key] === undefined) { continue; }
  50477. if (source[key] && source[key].constructor === Object) {
  50478. dest[key] = utils.clone(source[key]);
  50479. } else {
  50480. dest[key] = source[key];
  50481. }
  50482. }
  50483. return dest;
  50484. }
  50485. return source;
  50486. }
  50487. /**
  50488. * Checks if a component has defined a method that needs to run every frame.
  50489. */
  50490. function hasBehavior (component) {
  50491. return component.tick || component.tock;
  50492. }
  50493. /**
  50494. * Wrapper for defined pause method.
  50495. * Pause component by removing tick behavior and calling user's pause method.
  50496. *
  50497. * @param pauseMethod {function}
  50498. */
  50499. function wrapPause (pauseMethod) {
  50500. return function pause () {
  50501. var sceneEl = this.el.sceneEl;
  50502. if (!this.isPlaying) { return; }
  50503. pauseMethod.call(this);
  50504. this.isPlaying = false;
  50505. this.eventsDetach();
  50506. // Remove tick behavior.
  50507. if (!hasBehavior(this)) { return; }
  50508. sceneEl.removeBehavior(this);
  50509. };
  50510. }
  50511. /**
  50512. * Wrapper for defined play method.
  50513. * Play component by adding tick behavior and calling user's play method.
  50514. *
  50515. * @param playMethod {function}
  50516. */
  50517. function wrapPlay (playMethod) {
  50518. return function play () {
  50519. var sceneEl = this.el.sceneEl;
  50520. var shouldPlay = this.el.isPlaying && !this.isPlaying;
  50521. if (!this.initialized || !shouldPlay) { return; }
  50522. playMethod.call(this);
  50523. this.isPlaying = true;
  50524. this.eventsAttach();
  50525. // Add tick behavior.
  50526. if (!hasBehavior(this)) { return; }
  50527. sceneEl.addBehavior(this);
  50528. };
  50529. }
  50530. function isObject (value) {
  50531. return value && value.constructor === Object && !(value instanceof window.HTMLElement);
  50532. }
  50533. function isObjectOrArray (value) {
  50534. return value && (value.constructor === Object || value.constructor === Array) &&
  50535. !(value instanceof window.HTMLElement);
  50536. }
  50537. },{"../utils/":176,"./scene/scenes":110,"./schema":112,"./system":114}],104:[function(_dereq_,module,exports){
  50538. var schema = _dereq_('./schema');
  50539. var processSchema = schema.process;
  50540. var geometries = module.exports.geometries = {}; // Registered geometries.
  50541. var geometryNames = module.exports.geometryNames = []; // Names of registered geometries.
  50542. var THREE = _dereq_('../lib/three');
  50543. /**
  50544. * Geometry class definition.
  50545. *
  50546. * Geometries extend the geometry component API to create and register geometry types.
  50547. */
  50548. var Geometry = module.exports.Geometry = function () {};
  50549. Geometry.prototype = {
  50550. /**
  50551. * Contains the type schema and defaults for the data values.
  50552. * Data is coerced into the types of the values of the defaults.
  50553. */
  50554. schema: {},
  50555. /**
  50556. * Init handler. Similar to attachedCallback.
  50557. * Called during shader initialization and is only run once.
  50558. */
  50559. init: function (data) {
  50560. this.geometry = new THREE.Geometry();
  50561. return this.geometry;
  50562. },
  50563. /**
  50564. * Update handler. Similar to attributeChangedCallback.
  50565. * Called whenever the associated geometry data changes.
  50566. *
  50567. * @param {object} data - New geometry data.
  50568. */
  50569. update: function (data) { /* no-op */ }
  50570. };
  50571. /**
  50572. * Registers a geometry to A-Frame.
  50573. *
  50574. * @param {string} name - Geometry name.
  50575. * @param {object} definition - Geometry property and methods.
  50576. * @returns {object} Geometry.
  50577. */
  50578. module.exports.registerGeometry = function (name, definition) {
  50579. var NewGeometry;
  50580. var proto = {};
  50581. // Format definition object to prototype object.
  50582. Object.keys(definition).forEach(function expandDefinition (key) {
  50583. proto[key] = {
  50584. value: definition[key],
  50585. writable: true
  50586. };
  50587. });
  50588. if (geometries[name]) {
  50589. throw new Error('The geometry `' + name + '` has been already registered');
  50590. }
  50591. NewGeometry = function () { Geometry.call(this); };
  50592. NewGeometry.prototype = Object.create(Geometry.prototype, proto);
  50593. NewGeometry.prototype.name = name;
  50594. NewGeometry.prototype.constructor = NewGeometry;
  50595. geometries[name] = {
  50596. Geometry: NewGeometry,
  50597. schema: processSchema(NewGeometry.prototype.schema)
  50598. };
  50599. geometryNames.push(name);
  50600. return NewGeometry;
  50601. };
  50602. },{"../lib/three":151,"./schema":112}],105:[function(_dereq_,module,exports){
  50603. var coordinates = _dereq_('../utils/coordinates');
  50604. var debug = _dereq_('debug');
  50605. var error = debug('core:propertyTypes:warn');
  50606. var warn = debug('core:propertyTypes:warn');
  50607. var propertyTypes = module.exports.propertyTypes = {};
  50608. var nonCharRegex = /[,> .[\]:]/;
  50609. var urlRegex = /\url\((.+)\)/;
  50610. // Built-in property types.
  50611. registerPropertyType('audio', '', assetParse);
  50612. registerPropertyType('array', [], arrayParse, arrayStringify);
  50613. registerPropertyType('asset', '', assetParse);
  50614. registerPropertyType('boolean', false, boolParse);
  50615. registerPropertyType('color', '#FFF', defaultParse, defaultStringify);
  50616. registerPropertyType('int', 0, intParse);
  50617. registerPropertyType('number', 0, numberParse);
  50618. registerPropertyType('map', '', assetParse);
  50619. registerPropertyType('model', '', assetParse);
  50620. registerPropertyType('selector', null, selectorParse, selectorStringify);
  50621. registerPropertyType('selectorAll', null, selectorAllParse, selectorAllStringify);
  50622. registerPropertyType('src', '', srcParse);
  50623. registerPropertyType('string', '', defaultParse, defaultStringify);
  50624. registerPropertyType('time', 0, intParse);
  50625. registerPropertyType('vec2', {x: 0, y: 0}, vecParse, coordinates.stringify);
  50626. registerPropertyType('vec3', {x: 0, y: 0, z: 0}, vecParse, coordinates.stringify);
  50627. registerPropertyType('vec4', {x: 0, y: 0, z: 0, w: 1}, vecParse, coordinates.stringify);
  50628. /**
  50629. * Register a parser for re-use such that when someone uses `type` in the schema,
  50630. * `schema.process` will set the property `parse` and `stringify`.
  50631. *
  50632. * @param {string} type - Type name.
  50633. * @param [defaultValue=null] -
  50634. * Default value to use if component does not define default value.
  50635. * @param {function} [parse=defaultParse] - Parse string function.
  50636. * @param {function} [stringify=defaultStringify] - Stringify to DOM function.
  50637. */
  50638. function registerPropertyType (type, defaultValue, parse, stringify) {
  50639. if ('type' in propertyTypes) {
  50640. error('Property type ' + type + ' is already registered.');
  50641. return;
  50642. }
  50643. propertyTypes[type] = {
  50644. default: defaultValue,
  50645. parse: parse || defaultParse,
  50646. stringify: stringify || defaultStringify
  50647. };
  50648. }
  50649. module.exports.registerPropertyType = registerPropertyType;
  50650. function arrayParse (value) {
  50651. if (Array.isArray(value)) { return value; }
  50652. if (!value || typeof value !== 'string') { return []; }
  50653. return value.split(',').map(trim);
  50654. function trim (str) { return str.trim(); }
  50655. }
  50656. function arrayStringify (value) {
  50657. return value.join(', ');
  50658. }
  50659. /**
  50660. * For general assets.
  50661. *
  50662. * @param {string} value - Can either be `url(<value>)`, an ID selector to an asset, or
  50663. * just string.
  50664. * @returns {string} Parsed value from `url(<value>)`, src from `<someasset src>`, or
  50665. * just string.
  50666. */
  50667. function assetParse (value) {
  50668. var el;
  50669. var parsedUrl;
  50670. // If an element was provided (e.g. canvas or video), just return it.
  50671. if (typeof value !== 'string') { return value; }
  50672. // Wrapped `url()` in case of data URI.
  50673. parsedUrl = value.match(urlRegex);
  50674. if (parsedUrl) { return parsedUrl[1]; }
  50675. // ID.
  50676. if (value.charAt(0) === '#') {
  50677. el = document.getElementById(value.substring(1));
  50678. if (el) {
  50679. // Pass through media elements. If we have the elements, we don't have to call
  50680. // three.js loaders which would re-request the assets.
  50681. if (el.tagName === 'CANVAS' || el.tagName === 'VIDEO' || el.tagName === 'IMG') {
  50682. return el;
  50683. }
  50684. return el.getAttribute('src');
  50685. }
  50686. warn('"' + value + '" asset not found.');
  50687. return;
  50688. }
  50689. // Non-wrapped url().
  50690. return value;
  50691. }
  50692. function defaultParse (value) {
  50693. return value;
  50694. }
  50695. function defaultStringify (value) {
  50696. if (value === null) { return 'null'; }
  50697. return value.toString();
  50698. }
  50699. function boolParse (value) {
  50700. return value !== 'false' && value !== false;
  50701. }
  50702. function intParse (value) {
  50703. return parseInt(value, 10);
  50704. }
  50705. function numberParse (value) {
  50706. return parseFloat(value, 10);
  50707. }
  50708. function selectorParse (value) {
  50709. if (!value) { return null; }
  50710. if (typeof value !== 'string') { return value; }
  50711. if (value[0] === '#' && !nonCharRegex.test(value)) {
  50712. // When selecting element by ID only, use getElementById for better performance.
  50713. // Don't match like #myId .child.
  50714. return document.getElementById(value.substring(1));
  50715. }
  50716. return document.querySelector(value);
  50717. }
  50718. function selectorAllParse (value) {
  50719. if (!value) { return null; }
  50720. if (typeof value !== 'string') { return value; }
  50721. return Array.prototype.slice.call(document.querySelectorAll(value), 0);
  50722. }
  50723. function selectorStringify (value) {
  50724. if (value.getAttribute) {
  50725. return '#' + value.getAttribute('id');
  50726. }
  50727. return defaultStringify(value);
  50728. }
  50729. function selectorAllStringify (value) {
  50730. if (value instanceof Array) {
  50731. return value.map(function (element) {
  50732. return '#' + element.getAttribute('id');
  50733. }).join(', ');
  50734. }
  50735. return defaultStringify(value);
  50736. }
  50737. function srcParse (value) {
  50738. warn('`src` property type is deprecated. Use `asset` instead.');
  50739. return assetParse(value);
  50740. }
  50741. function vecParse (value) {
  50742. return coordinates.parse(value, this.default);
  50743. }
  50744. /**
  50745. * Validate the default values in a schema to match their type.
  50746. *
  50747. * @param {string} type - Property type name.
  50748. * @param defaultVal - Property type default value.
  50749. * @returns {boolean} Whether default value is accurate given the type.
  50750. */
  50751. function isValidDefaultValue (type, defaultVal) {
  50752. if (type === 'audio' && typeof defaultVal !== 'string') { return false; }
  50753. if (type === 'array' && !Array.isArray(defaultVal)) { return false; }
  50754. if (type === 'asset' && typeof defaultVal !== 'string') { return false; }
  50755. if (type === 'boolean' && typeof defaultVal !== 'boolean') { return false; }
  50756. if (type === 'color' && typeof defaultVal !== 'string') { return false; }
  50757. if (type === 'int' && typeof defaultVal !== 'number') { return false; }
  50758. if (type === 'number' && typeof defaultVal !== 'number') { return false; }
  50759. if (type === 'map' && typeof defaultVal !== 'string') { return false; }
  50760. if (type === 'model' && typeof defaultVal !== 'string') { return false; }
  50761. if (type === 'selector' && typeof defaultVal !== 'string' &&
  50762. defaultVal !== null) { return false; }
  50763. if (type === 'selectorAll' && typeof defaultVal !== 'string' &&
  50764. defaultVal !== null) { return false; }
  50765. if (type === 'src' && typeof defaultVal !== 'string') { return false; }
  50766. if (type === 'string' && typeof defaultVal !== 'string') { return false; }
  50767. if (type === 'time' && typeof defaultVal !== 'number') { return false; }
  50768. if (type === 'vec2') { return isValidDefaultCoordinate(defaultVal, 2); }
  50769. if (type === 'vec3') { return isValidDefaultCoordinate(defaultVal, 3); }
  50770. if (type === 'vec4') { return isValidDefaultCoordinate(defaultVal, 4); }
  50771. return true;
  50772. }
  50773. module.exports.isValidDefaultValue = isValidDefaultValue;
  50774. /**
  50775. * Checks if default coordinates are valid.
  50776. *
  50777. * @param possibleCoordinates
  50778. * @param {number} dimensions - 2 for 2D Vector, 3 for 3D vector.
  50779. * @returns {boolean} Whether coordinates are parsed correctly.
  50780. */
  50781. function isValidDefaultCoordinate (possibleCoordinates, dimensions) {
  50782. if (possibleCoordinates === null) { return true; }
  50783. if (typeof possibleCoordinates !== 'object') { return false; }
  50784. if (Object.keys(possibleCoordinates).length !== dimensions) {
  50785. return false;
  50786. } else {
  50787. var x = possibleCoordinates.x;
  50788. var y = possibleCoordinates.y;
  50789. var z = possibleCoordinates.z;
  50790. var w = possibleCoordinates.w;
  50791. if (typeof x !== 'number' || typeof y !== 'number') { return false; }
  50792. if (dimensions > 2 && typeof z !== 'number') { return false; }
  50793. if (dimensions > 3 && typeof w !== 'number') { return false; }
  50794. }
  50795. return true;
  50796. }
  50797. module.exports.isValidDefaultCoordinate = isValidDefaultCoordinate;
  50798. },{"../utils/coordinates":171,"debug":8}],106:[function(_dereq_,module,exports){
  50799. /* global Promise, screen */
  50800. var initMetaTags = _dereq_('./metaTags').inject;
  50801. var initWakelock = _dereq_('./wakelock');
  50802. var loadingScreen = _dereq_('./loadingScreen');
  50803. var re = _dereq_('../a-register-element');
  50804. var scenes = _dereq_('./scenes');
  50805. var systems = _dereq_('../system').systems;
  50806. var THREE = _dereq_('../../lib/three');
  50807. var utils = _dereq_('../../utils/');
  50808. // Require after.
  50809. var AEntity = _dereq_('../a-entity');
  50810. var ANode = _dereq_('../a-node');
  50811. var initPostMessageAPI = _dereq_('./postMessage');
  50812. var bind = utils.bind;
  50813. var isIOS = utils.device.isIOS();
  50814. var isMobile = utils.device.isMobile();
  50815. var isWebXRAvailable = utils.device.isWebXRAvailable;
  50816. var registerElement = re.registerElement;
  50817. var warn = utils.debug('core:a-scene:warn');
  50818. /**
  50819. * Scene element, holds all entities.
  50820. *
  50821. * @member {array} behaviors - Component instances that have registered themselves to be
  50822. updated on every tick.
  50823. * @member {object} camera - three.js Camera object.
  50824. * @member {object} canvas
  50825. * @member {bool} isScene - Differentiates as scene entity as opposed to other entites.
  50826. * @member {bool} isMobile - Whether browser is mobile (via UA detection).
  50827. * @member {object} object3D - Root three.js Scene object.
  50828. * @member {object} renderer
  50829. * @member {bool} renderStarted
  50830. * @member {object} systems - Registered instantiated systems.
  50831. * @member {number} time
  50832. */
  50833. module.exports.AScene = registerElement('a-scene', {
  50834. prototype: Object.create(AEntity.prototype, {
  50835. createdCallback: {
  50836. value: function () {
  50837. this.clock = new THREE.Clock();
  50838. this.isIOS = isIOS;
  50839. this.isMobile = isMobile;
  50840. this.hasWebXR = isWebXRAvailable;
  50841. this.isScene = true;
  50842. this.object3D = new THREE.Scene();
  50843. var self = this;
  50844. this.object3D.onAfterRender = function (renderer, scene, camera) {
  50845. // THREE may swap the camera used for the rendering if in VR, so we pass it to tock
  50846. if (self.isPlaying) { self.tock(self.time, self.delta, camera); }
  50847. };
  50848. this.render = bind(this.render, this);
  50849. this.systems = {};
  50850. this.systemNames = [];
  50851. this.time = this.delta = 0;
  50852. this.behaviors = {tick: [], tock: []};
  50853. this.hasLoaded = false;
  50854. this.isPlaying = false;
  50855. this.originalHTML = this.innerHTML;
  50856. // Default components.
  50857. this.setAttribute('inspector', '');
  50858. this.setAttribute('keyboard-shortcuts', '');
  50859. this.setAttribute('screenshot', '');
  50860. this.setAttribute('vr-mode-ui', '');
  50861. }
  50862. },
  50863. addFullScreenStyles: {
  50864. value: function () {
  50865. document.documentElement.classList.add('a-fullscreen');
  50866. }
  50867. },
  50868. removeFullScreenStyles: {
  50869. value: function () {
  50870. document.documentElement.classList.remove('a-fullscreen');
  50871. }
  50872. },
  50873. attachedCallback: {
  50874. value: function () {
  50875. var self = this;
  50876. // Renderer initialization
  50877. setupCanvas(this);
  50878. this.setupRenderer();
  50879. this.resize();
  50880. this.addFullScreenStyles();
  50881. initPostMessageAPI(this);
  50882. initMetaTags(this);
  50883. initWakelock(this);
  50884. // Handler to exit VR (e.g., Oculus Browser back button).
  50885. this.onVRPresentChangeBound = bind(this.onVRPresentChange, this);
  50886. window.addEventListener('vrdisplaypresentchange', this.onVRPresentChangeBound);
  50887. // Bind functions.
  50888. this.enterVRBound = function () { self.enterVR(); };
  50889. this.exitVRBound = function () { self.exitVR(); };
  50890. this.exitVRTrueBound = function () { self.exitVR(true); };
  50891. this.pointerRestrictedBound = function () { self.pointerRestricted(); };
  50892. this.pointerUnrestrictedBound = function () { self.pointerUnrestricted(); };
  50893. if (!isWebXRAvailable) {
  50894. // Exit VR on `vrdisplaydeactivate` (e.g. taking off Rift headset).
  50895. window.addEventListener('vrdisplaydeactivate', this.exitVRBound);
  50896. // Exit VR on `vrdisplaydisconnect` (e.g. unplugging Rift headset).
  50897. window.addEventListener('vrdisplaydisconnect', this.exitVRTrueBound);
  50898. // Register for mouse restricted events while in VR
  50899. // (e.g. mouse no longer available on desktop 2D view)
  50900. window.addEventListener('vrdisplaypointerrestricted', this.pointerRestrictedBound);
  50901. // Register for mouse unrestricted events while in VR
  50902. // (e.g. mouse once again available on desktop 2D view)
  50903. window.addEventListener('vrdisplaypointerunrestricted',
  50904. this.pointerUnrestrictedBound);
  50905. }
  50906. // Camera set up by camera system.
  50907. this.addEventListener('cameraready', function () {
  50908. self.attachedCallbackPostCamera();
  50909. });
  50910. this.initSystems();
  50911. }
  50912. },
  50913. attachedCallbackPostCamera: {
  50914. value: function () {
  50915. var resize;
  50916. var self = this;
  50917. resize = bind(this.resize, this);
  50918. window.addEventListener('load', resize);
  50919. window.addEventListener('resize', function () {
  50920. // Workaround for a Webkit bug (https://bugs.webkit.org/show_bug.cgi?id=170595)
  50921. // where the window does not contain the correct viewport size
  50922. // after an orientation change. The window size is correct if the operation
  50923. // is postponed a few milliseconds.
  50924. // self.resize can be called directly once the bug above is fixed.
  50925. if (self.isIOS) {
  50926. setTimeout(resize, 100);
  50927. } else {
  50928. resize();
  50929. }
  50930. });
  50931. this.play();
  50932. // Add to scene index.
  50933. scenes.push(this);
  50934. },
  50935. writable: window.debug
  50936. },
  50937. /**
  50938. * Initialize all systems.
  50939. */
  50940. initSystems: {
  50941. value: function () {
  50942. var name;
  50943. // Initialize camera system first.
  50944. this.initSystem('camera');
  50945. for (name in systems) {
  50946. if (name === 'camera') { continue; }
  50947. this.initSystem(name);
  50948. }
  50949. }
  50950. },
  50951. /**
  50952. * Initialize a system.
  50953. */
  50954. initSystem: {
  50955. value: function (name) {
  50956. if (this.systems[name]) { return; }
  50957. this.systems[name] = new systems[name](this);
  50958. this.systemNames.push(name);
  50959. }
  50960. },
  50961. /**
  50962. * Shut down scene on detach.
  50963. */
  50964. detachedCallback: {
  50965. value: function () {
  50966. // Remove from scene index.
  50967. var sceneIndex = scenes.indexOf(this);
  50968. scenes.splice(sceneIndex, 1);
  50969. window.removeEventListener('vrdisplaypresentchange', this.onVRPresentChangeBound);
  50970. window.removeEventListener('vrdisplayactivate', this.enterVRBound);
  50971. window.removeEventListener('vrdisplaydeactivate', this.exitVRBound);
  50972. window.removeEventListener('vrdisplayconnect', this.enterVRBound);
  50973. window.removeEventListener('vrdisplaydisconnect', this.exitVRTrueBound);
  50974. window.removeEventListener('vrdisplaypointerrestricted', this.pointerRestrictedBound);
  50975. window.removeEventListener('vrdisplaypointerunrestricted', this.pointerUnrestrictedBound);
  50976. }
  50977. },
  50978. /**
  50979. * Add ticks and tocks.
  50980. *
  50981. * @param {object} behavior - A component.
  50982. */
  50983. addBehavior: {
  50984. value: function (behavior) {
  50985. var behaviorArr;
  50986. var behaviors = this.behaviors;
  50987. var behaviorType;
  50988. // Check if behavior has tick and/or tock and add the behavior to the appropriate list.
  50989. for (behaviorType in behaviors) {
  50990. if (!behavior[behaviorType]) { continue; }
  50991. behaviorArr = this.behaviors[behaviorType];
  50992. if (behaviorArr.indexOf(behavior) === -1) {
  50993. behaviorArr.push(behavior);
  50994. }
  50995. }
  50996. }
  50997. },
  50998. /**
  50999. * For tests.
  51000. */
  51001. getPointerLockElement: {
  51002. value: function () {
  51003. return document.pointerLockElement;
  51004. },
  51005. writable: window.debug
  51006. },
  51007. /**
  51008. * For tests.
  51009. */
  51010. checkHeadsetConnected: {
  51011. value: utils.device.checkHeadsetConnected,
  51012. writable: window.debug
  51013. },
  51014. /**
  51015. * Call `requestPresent` if WebVR or WebVR polyfill.
  51016. * Call `requestFullscreen` on desktop.
  51017. * Handle events, states, fullscreen styles.
  51018. *
  51019. * @returns {Promise}
  51020. */
  51021. enterVR: {
  51022. value: function () {
  51023. var self = this;
  51024. var vrDisplay;
  51025. var vrManager = self.renderer.vr;
  51026. // Don't enter VR if already in VR.
  51027. if (this.is('vr-mode')) { return Promise.resolve('Already in VR.'); }
  51028. // Has VR.
  51029. if (this.checkHeadsetConnected() || this.isMobile) {
  51030. vrDisplay = utils.device.getVRDisplay();
  51031. vrManager.enabled = true;
  51032. vrManager.setDevice(vrDisplay);
  51033. if (this.hasWebXR) {
  51034. // XR API.
  51035. if (this.xrSession) {
  51036. this.xrSession.removeEventListener('end', this.exitVRBound);
  51037. }
  51038. vrDisplay.requestSession({
  51039. immersive: true,
  51040. exclusive: true
  51041. }).then(function requestSuccess (xrSession) {
  51042. self.xrSession = xrSession;
  51043. vrManager.setSession(xrSession);
  51044. xrSession.addEventListener('end', self.exitVRBound);
  51045. xrSession.requestFrameOfReference('stage').then(function (frameOfReference) {
  51046. self.frameOfReference = frameOfReference;
  51047. });
  51048. enterVRSuccess();
  51049. });
  51050. } else {
  51051. if (vrDisplay.isPresenting &&
  51052. !window.hasNativeWebVRImplementation) {
  51053. enterVRSuccess();
  51054. return Promise.resolve();
  51055. }
  51056. var rendererSystem = this.getAttribute('renderer');
  51057. var presentationAttributes = {
  51058. highRefreshRate: rendererSystem.highRefreshRate,
  51059. foveationLevel: rendererSystem.foveationLevel
  51060. };
  51061. return vrDisplay.requestPresent([{
  51062. source: this.canvas,
  51063. attributes: presentationAttributes
  51064. }]).then(enterVRSuccess, enterVRFailure);
  51065. }
  51066. return Promise.resolve();
  51067. }
  51068. // No VR.
  51069. enterVRSuccess();
  51070. return Promise.resolve();
  51071. // Callback that happens on enter VR success or enter fullscreen (any API).
  51072. function enterVRSuccess () {
  51073. self.addState('vr-mode');
  51074. self.emit('enter-vr', {target: self});
  51075. // Lock to landscape orientation on mobile.
  51076. if (self.isMobile && screen.orientation && screen.orientation.lock) {
  51077. screen.orientation.lock('landscape');
  51078. }
  51079. self.addFullScreenStyles();
  51080. // On mobile, the polyfill handles fullscreen.
  51081. // TODO: 07/16 Chromium builds break when `requestFullscreen`ing on a canvas
  51082. // that we are also `requestPresent`ing. Until then, don't fullscreen if headset
  51083. // connected.
  51084. if (!self.isMobile && !self.checkHeadsetConnected()) {
  51085. requestFullscreen(self.canvas);
  51086. }
  51087. self.renderer.setAnimationLoop(self.render);
  51088. self.resize();
  51089. }
  51090. function enterVRFailure (err) {
  51091. if (err && err.message) {
  51092. throw new Error('Failed to enter VR mode (`requestPresent`): ' + err.message);
  51093. } else {
  51094. throw new Error('Failed to enter VR mode (`requestPresent`).');
  51095. }
  51096. }
  51097. },
  51098. writable: true
  51099. },
  51100. /**
  51101. * Call `exitPresent` if WebVR / WebXR or WebVR polyfill.
  51102. * Handle events, states, fullscreen styles.
  51103. *
  51104. * @returns {Promise}
  51105. */
  51106. exitVR: {
  51107. value: function () {
  51108. var self = this;
  51109. var vrDisplay;
  51110. var vrManager = this.renderer.vr;
  51111. // Don't exit VR if not in VR.
  51112. if (!this.is('vr-mode')) { return Promise.resolve('Not in VR.'); }
  51113. // Handle exiting VR if not yet already and in a headset or polyfill.
  51114. if (this.checkHeadsetConnected() || this.isMobile) {
  51115. vrManager.enabled = false;
  51116. vrDisplay = utils.device.getVRDisplay();
  51117. if (this.hasWebXR) {
  51118. this.xrSession.removeEventListener('end', this.exitVRBound);
  51119. this.xrSession.end();
  51120. vrManager.setSession(null);
  51121. } else {
  51122. if (vrDisplay.isPresenting) {
  51123. return vrDisplay.exitPresent().then(exitVRSuccess, exitVRFailure);
  51124. }
  51125. }
  51126. } else {
  51127. exitFullscreen();
  51128. }
  51129. // Handle exiting VR in all other cases (2D fullscreen, external exit VR event).
  51130. exitVRSuccess();
  51131. return Promise.resolve();
  51132. function exitVRSuccess () {
  51133. self.removeState('vr-mode');
  51134. // Lock to landscape orientation on mobile.
  51135. if (self.isMobile && screen.orientation && screen.orientation.unlock) {
  51136. screen.orientation.unlock();
  51137. }
  51138. // Exiting VR in embedded mode, no longer need fullscreen styles.
  51139. if (self.hasAttribute('embedded')) { self.removeFullScreenStyles(); }
  51140. self.resize();
  51141. if (self.isIOS) { utils.forceCanvasResizeSafariMobile(self.canvas); }
  51142. self.emit('exit-vr', {target: self});
  51143. }
  51144. function exitVRFailure (err) {
  51145. if (err && err.message) {
  51146. throw new Error('Failed to exit VR mode (`exitPresent`): ' + err.message);
  51147. } else {
  51148. throw new Error('Failed to exit VR mode (`exitPresent`).');
  51149. }
  51150. }
  51151. },
  51152. writable: true
  51153. },
  51154. pointerRestricted: {
  51155. value: function () {
  51156. if (this.canvas) {
  51157. var pointerLockElement = this.getPointerLockElement();
  51158. if (pointerLockElement && pointerLockElement !== this.canvas && document.exitPointerLock) {
  51159. // Recreate pointer lock on the canvas, if taken on another element.
  51160. document.exitPointerLock();
  51161. }
  51162. if (this.canvas.requestPointerLock) {
  51163. this.canvas.requestPointerLock();
  51164. }
  51165. }
  51166. }
  51167. },
  51168. pointerUnrestricted: {
  51169. value: function () {
  51170. var pointerLockElement = this.getPointerLockElement();
  51171. if (pointerLockElement && pointerLockElement === this.canvas && document.exitPointerLock) {
  51172. document.exitPointerLock();
  51173. }
  51174. }
  51175. },
  51176. /**
  51177. * Handle `vrdisplaypresentchange` event for exiting VR through other means than
  51178. * `<ESC>` key. For example, GearVR back button on Oculus Browser.
  51179. */
  51180. onVRPresentChange: {
  51181. value: function (evt) {
  51182. // Polyfill places display inside the detail property
  51183. var display = evt.display || evt.detail.display;
  51184. // Entering VR.
  51185. if (display.isPresenting) {
  51186. this.enterVR();
  51187. return;
  51188. }
  51189. // Exiting VR.
  51190. this.exitVR();
  51191. }
  51192. },
  51193. /**
  51194. * Wraps Entity.getAttribute to take into account for systems.
  51195. * If system exists, then return system data rather than possible component data.
  51196. */
  51197. getAttribute: {
  51198. value: function (attr) {
  51199. var system = this.systems[attr];
  51200. if (system) { return system.data; }
  51201. return AEntity.prototype.getAttribute.call(this, attr);
  51202. }
  51203. },
  51204. /**
  51205. * `getAttribute` used to be `getDOMAttribute` and `getComputedAttribute` used to be
  51206. * what `getAttribute` is now. Now legacy code.
  51207. */
  51208. getComputedAttribute: {
  51209. value: function (attr) {
  51210. warn('`getComputedAttribute` is deprecated. Use `getAttribute` instead.');
  51211. this.getAttribute(attr);
  51212. }
  51213. },
  51214. /**
  51215. * Wraps Entity.getDOMAttribute to take into account for systems.
  51216. * If system exists, then return system data rather than possible component data.
  51217. */
  51218. getDOMAttribute: {
  51219. value: function (attr) {
  51220. var system = this.systems[attr];
  51221. if (system) { return system.data; }
  51222. return AEntity.prototype.getDOMAttribute.call(this, attr);
  51223. }
  51224. },
  51225. /**
  51226. * Wrap Entity.setAttribute to take into account for systems.
  51227. * If system exists, then skip component initialization checks and do a normal
  51228. * setAttribute.
  51229. */
  51230. setAttribute: {
  51231. value: function (attr, value, componentPropValue) {
  51232. var system = this.systems[attr];
  51233. if (system) {
  51234. ANode.prototype.setAttribute.call(this, attr, value);
  51235. system.updateProperties(value);
  51236. return;
  51237. }
  51238. AEntity.prototype.setAttribute.call(this, attr, value, componentPropValue);
  51239. }
  51240. },
  51241. /**
  51242. * @param {object} behavior - A component.
  51243. */
  51244. removeBehavior: {
  51245. value: function (behavior) {
  51246. var behaviorArr;
  51247. var behaviorType;
  51248. var behaviors = this.behaviors;
  51249. var index;
  51250. // Check if behavior has tick and/or tock and remove the behavior from the appropriate
  51251. // array.
  51252. for (behaviorType in behaviors) {
  51253. if (!behavior[behaviorType]) { continue; }
  51254. behaviorArr = this.behaviors[behaviorType];
  51255. index = behaviorArr.indexOf(behavior);
  51256. if (index !== -1) { behaviorArr.splice(index, 1); }
  51257. }
  51258. }
  51259. },
  51260. resize: {
  51261. value: function () {
  51262. var camera = this.camera;
  51263. var canvas = this.canvas;
  51264. var embedded;
  51265. var isVRPresenting;
  51266. var size;
  51267. var vrDevice;
  51268. vrDevice = this.renderer.vr.getDevice();
  51269. isVRPresenting = this.renderer.vr.enabled && vrDevice && vrDevice.isPresenting;
  51270. // Do not update renderer, if a camera or a canvas have not been injected.
  51271. // In VR mode, three handles canvas resize based on the dimensions returned by
  51272. // the getEyeParameters function of the WebVR API. These dimensions are independent of
  51273. // the window size, therefore should not be overwritten with the window's width and
  51274. // height, // except when in fullscreen mode.
  51275. if (!camera || !canvas || (this.is('vr-mode') && (this.isMobile || isVRPresenting))) {
  51276. return;
  51277. }
  51278. // Update camera.
  51279. embedded = this.getAttribute('embedded') && !this.is('vr-mode');
  51280. size = getCanvasSize(canvas, embedded, this.maxCanvasSize, this.is('vr-mode'));
  51281. camera.aspect = size.width / size.height;
  51282. camera.updateProjectionMatrix();
  51283. // Notify renderer of size change.
  51284. this.renderer.setSize(size.width, size.height, false);
  51285. this.emit('rendererresize', null, false);
  51286. },
  51287. writable: true
  51288. },
  51289. setupRenderer: {
  51290. value: function () {
  51291. var self = this;
  51292. var renderer;
  51293. var rendererAttr;
  51294. var rendererAttrString;
  51295. var rendererConfig;
  51296. rendererConfig = {
  51297. alpha: true,
  51298. antialias: !isMobile,
  51299. canvas: this.canvas,
  51300. logarithmicDepthBuffer: false
  51301. };
  51302. this.maxCanvasSize = {height: 1920, width: 1920};
  51303. if (this.hasAttribute('renderer')) {
  51304. rendererAttrString = this.getAttribute('renderer');
  51305. rendererAttr = utils.styleParser.parse(rendererAttrString);
  51306. if (rendererAttr.precision) {
  51307. rendererConfig.precision = rendererAttr.precision + 'p';
  51308. }
  51309. if (rendererAttr.antialias && rendererAttr.antialias !== 'auto') {
  51310. rendererConfig.antialias = rendererAttr.antialias === 'true';
  51311. }
  51312. if (rendererAttr.logarithmicDepthBuffer && rendererAttr.logarithmicDepthBuffer !== 'auto') {
  51313. rendererConfig.logarithmicDepthBuffer = rendererAttr.logarithmicDepthBuffer === 'true';
  51314. }
  51315. if (rendererAttr.alpha) {
  51316. rendererConfig.alpha = rendererAttr.alpha === 'true';
  51317. }
  51318. this.maxCanvasSize = {
  51319. width: rendererAttr.maxCanvasWidth
  51320. ? parseInt(rendererAttr.maxCanvasWidth)
  51321. : this.maxCanvasSize.width,
  51322. height: rendererAttr.maxCanvasHeight
  51323. ? parseInt(rendererAttr.maxCanvasHeight)
  51324. : this.maxCanvasSize.height
  51325. };
  51326. }
  51327. renderer = this.renderer = new THREE.WebGLRenderer(rendererConfig);
  51328. renderer.setPixelRatio(window.devicePixelRatio);
  51329. renderer.sortObjects = false;
  51330. if (this.camera) { renderer.vr.setPoseTarget(this.camera.el.object3D); }
  51331. this.addEventListener('camera-set-active', function () {
  51332. renderer.vr.setPoseTarget(self.camera.el.object3D);
  51333. });
  51334. loadingScreen.setup(this, getCanvasSize);
  51335. },
  51336. writable: window.debug
  51337. },
  51338. /**
  51339. * Handler attached to elements to help scene know when to kick off.
  51340. * Scene waits for all entities to load.
  51341. */
  51342. play: {
  51343. value: function () {
  51344. var self = this;
  51345. var sceneEl = this;
  51346. if (this.renderStarted) {
  51347. AEntity.prototype.play.call(this);
  51348. return;
  51349. }
  51350. this.addEventListener('loaded', function () {
  51351. var renderer = this.renderer;
  51352. var vrDisplay;
  51353. var vrManager = this.renderer.vr;
  51354. AEntity.prototype.play.call(this); // .play() *before* render.
  51355. if (sceneEl.renderStarted) { return; }
  51356. sceneEl.resize();
  51357. // Kick off render loop.
  51358. if (sceneEl.renderer) {
  51359. if (window.performance) { window.performance.mark('render-started'); }
  51360. loadingScreen.remove();
  51361. vrDisplay = utils.device.getVRDisplay();
  51362. if (vrDisplay && vrDisplay.isPresenting) {
  51363. vrManager.setDevice(vrDisplay);
  51364. vrManager.enabled = true;
  51365. sceneEl.enterVR();
  51366. }
  51367. renderer.setAnimationLoop(this.render);
  51368. sceneEl.renderStarted = true;
  51369. sceneEl.emit('renderstart');
  51370. }
  51371. });
  51372. // setTimeout to wait for all nodes to attach and run their callbacks.
  51373. setTimeout(function () {
  51374. AEntity.prototype.load.call(self);
  51375. });
  51376. }
  51377. },
  51378. /**
  51379. * Wrap `updateComponent` to not initialize the component if the component has a system
  51380. * (aframevr/aframe#2365).
  51381. */
  51382. updateComponent: {
  51383. value: function (componentName) {
  51384. if (componentName in systems) { return; }
  51385. AEntity.prototype.updateComponent.apply(this, arguments);
  51386. }
  51387. },
  51388. /**
  51389. * Behavior-updater meant to be called from scene render.
  51390. * Abstracted to a different function to facilitate unit testing (`scene.tick()`) without
  51391. * needing to render.
  51392. */
  51393. tick: {
  51394. value: function (time, timeDelta) {
  51395. var i;
  51396. var systems = this.systems;
  51397. // Components.
  51398. for (i = 0; i < this.behaviors.tick.length; i++) {
  51399. if (!this.behaviors.tick[i].el.isPlaying) { continue; }
  51400. this.behaviors.tick[i].tick(time, timeDelta);
  51401. }
  51402. // Systems.
  51403. for (i = 0; i < this.systemNames.length; i++) {
  51404. if (!systems[this.systemNames[i]].tick) { continue; }
  51405. systems[this.systemNames[i]].tick(time, timeDelta);
  51406. }
  51407. }
  51408. },
  51409. /**
  51410. * Behavior-updater meant to be called after scene render for post processing purposes.
  51411. * Abstracted to a different function to facilitate unit testing (`scene.tock()`) without
  51412. * needing to render.
  51413. */
  51414. tock: {
  51415. value: function (time, timeDelta, camera) {
  51416. var i;
  51417. var systems = this.systems;
  51418. // Components.
  51419. for (i = 0; i < this.behaviors.tock.length; i++) {
  51420. if (!this.behaviors.tock[i].el.isPlaying) { continue; }
  51421. this.behaviors.tock[i].tock(time, timeDelta, camera);
  51422. }
  51423. // Systems.
  51424. for (i = 0; i < this.systemNames.length; i++) {
  51425. if (!systems[this.systemNames[i]].tock) { continue; }
  51426. systems[this.systemNames[i]].tock(time, timeDelta, camera);
  51427. }
  51428. }
  51429. },
  51430. /**
  51431. * The render loop.
  51432. *
  51433. * Updates animations.
  51434. * Updates behaviors.
  51435. * Renders with request animation frame.
  51436. */
  51437. render: {
  51438. value: function (time, frame) {
  51439. var renderer = this.renderer;
  51440. this.frame = frame;
  51441. this.delta = this.clock.getDelta() * 1000;
  51442. this.time = this.clock.elapsedTime * 1000;
  51443. if (this.isPlaying) { this.tick(this.time, this.delta); }
  51444. renderer.render(this.object3D, this.camera);
  51445. },
  51446. writable: true
  51447. }
  51448. })
  51449. });
  51450. /**
  51451. * Return the canvas size where the scene will be rendered.
  51452. * Will be always the window size except when the scene is embedded.
  51453. * The parent size (less than max size) will be returned in that case.
  51454. *
  51455. * @param {object} canvasEl - the canvas element
  51456. * @param {boolean} embedded - Is the scene embedded?
  51457. * @param {object} max - Max size parameters
  51458. * @param {boolean} isVR - If in VR
  51459. */
  51460. function getCanvasSize (canvasEl, embedded, maxSize, isVR) {
  51461. if (embedded) {
  51462. return {
  51463. height: canvasEl.parentElement.offsetHeight,
  51464. width: canvasEl.parentElement.offsetWidth
  51465. };
  51466. }
  51467. return getMaxSize(maxSize, isVR);
  51468. }
  51469. /**
  51470. * Return the canvas size. Will be the window size unless that size is greater than the
  51471. * maximum size (1920x1920 by default). The constrained size will be returned in that case,
  51472. * maintaining aspect ratio
  51473. *
  51474. * @param {object} maxSize - Max size parameters (width and height).
  51475. * @param {boolean} isVR - If in VR.
  51476. * @returns {object} Width and height.
  51477. */
  51478. function getMaxSize (maxSize, isVR) {
  51479. var aspectRatio;
  51480. var size;
  51481. var pixelRatio = window.devicePixelRatio;
  51482. size = {height: document.body.offsetHeight, width: document.body.offsetWidth};
  51483. if (!maxSize || isVR || (maxSize.width === -1 && maxSize.height === -1)) {
  51484. return size;
  51485. }
  51486. if (size.width * pixelRatio < maxSize.width &&
  51487. size.height * pixelRatio < maxSize.height) {
  51488. return size;
  51489. }
  51490. aspectRatio = size.width / size.height;
  51491. if ((size.width * pixelRatio) > maxSize.width && maxSize.width !== -1) {
  51492. size.width = Math.round(maxSize.width / pixelRatio);
  51493. size.height = Math.round(maxSize.width / aspectRatio / pixelRatio);
  51494. }
  51495. if ((size.height * pixelRatio) > maxSize.height && maxSize.height !== -1) {
  51496. size.height = Math.round(maxSize.height / pixelRatio);
  51497. size.width = Math.round(maxSize.height * aspectRatio / pixelRatio);
  51498. }
  51499. return size;
  51500. }
  51501. function requestFullscreen (canvas) {
  51502. var requestFullscreen =
  51503. canvas.requestFullscreen ||
  51504. canvas.webkitRequestFullscreen ||
  51505. canvas.mozRequestFullScreen || // The capitalized `S` is not a typo.
  51506. canvas.msRequestFullscreen;
  51507. // Hide navigation buttons on Android.
  51508. requestFullscreen.apply(canvas, [{navigationUI: 'hide'}]);
  51509. }
  51510. function exitFullscreen () {
  51511. var fullscreenEl =
  51512. document.fullscreenElement ||
  51513. document.webkitFullscreenElement ||
  51514. document.mozFullScreenElement;
  51515. if (!fullscreenEl) { return; }
  51516. if (document.exitFullscreen) {
  51517. document.exitFullscreen();
  51518. } else if (document.mozCancelFullScreen) {
  51519. document.mozCancelFullScreen();
  51520. } else if (document.webkitExitFullscreen) {
  51521. document.webkitExitFullscreen();
  51522. }
  51523. }
  51524. function setupCanvas (sceneEl) {
  51525. var canvasEl;
  51526. canvasEl = document.createElement('canvas');
  51527. canvasEl.classList.add('a-canvas');
  51528. // Mark canvas as provided/injected by A-Frame.
  51529. canvasEl.dataset.aframeCanvas = true;
  51530. sceneEl.appendChild(canvasEl);
  51531. document.addEventListener('fullscreenchange', onFullScreenChange);
  51532. document.addEventListener('mozfullscreenchange', onFullScreenChange);
  51533. document.addEventListener('webkitfullscreenchange', onFullScreenChange);
  51534. // Prevent overscroll on mobile.
  51535. canvasEl.addEventListener('touchmove', function (event) { event.preventDefault(); });
  51536. // Set canvas on scene.
  51537. sceneEl.canvas = canvasEl;
  51538. sceneEl.emit('render-target-loaded', {target: canvasEl});
  51539. // For unknown reasons a synchronous resize does not work on desktop when
  51540. // entering/exiting fullscreen.
  51541. setTimeout(bind(sceneEl.resize, sceneEl), 0);
  51542. function onFullScreenChange () {
  51543. var fullscreenEl =
  51544. document.fullscreenElement ||
  51545. document.mozFullScreenElement ||
  51546. document.webkitFullscreenElement;
  51547. // No fullscren element === exit fullscreen
  51548. if (!fullscreenEl) { sceneEl.exitVR(); }
  51549. document.activeElement.blur();
  51550. document.body.focus();
  51551. }
  51552. }
  51553. module.exports.setupCanvas = setupCanvas; // For testing.
  51554. },{"../../lib/three":151,"../../utils/":176,"../a-entity":99,"../a-node":101,"../a-register-element":102,"../system":114,"./loadingScreen":107,"./metaTags":108,"./postMessage":109,"./scenes":110,"./wakelock":111}],107:[function(_dereq_,module,exports){
  51555. /* global THREE */
  51556. var utils = _dereq_('../../utils/');
  51557. var styleParser = utils.styleParser;
  51558. var sceneEl;
  51559. var titleEl;
  51560. var getSceneCanvasSize;
  51561. var ATTR_NAME = 'loading-screen';
  51562. var LOADER_TITLE_CLASS = 'a-loader-title';
  51563. module.exports.setup = function setup (el, getCanvasSize) {
  51564. sceneEl = el;
  51565. getSceneCanvasSize = getCanvasSize;
  51566. var loaderAttribute = sceneEl.hasAttribute(ATTR_NAME) ? styleParser.parse(sceneEl.getAttribute(ATTR_NAME)) : undefined;
  51567. var dotsColor = loaderAttribute && loaderAttribute.dotsColor || 'white';
  51568. var backgroundColor = loaderAttribute && loaderAttribute.backgroundColor || '#24CAFF';
  51569. var loaderEnabled = loaderAttribute === undefined || loaderAttribute.enabled === true || loaderAttribute.enabled === undefined; // true default
  51570. var loaderScene;
  51571. var sphereGeometry;
  51572. var sphereMaterial;
  51573. var sphereMesh1;
  51574. var sphereMesh2;
  51575. var sphereMesh3;
  51576. var camera;
  51577. var clock;
  51578. var time;
  51579. var render;
  51580. if (!loaderEnabled) { return; }
  51581. // Setup Scene.
  51582. loaderScene = new THREE.Scene();
  51583. sphereGeometry = new THREE.SphereGeometry(0.20, 36, 18, 0, 2 * Math.PI, 0, Math.PI);
  51584. sphereMaterial = new THREE.MeshBasicMaterial({color: dotsColor});
  51585. sphereMesh1 = new THREE.Mesh(sphereGeometry, sphereMaterial);
  51586. sphereMesh2 = sphereMesh1.clone();
  51587. sphereMesh3 = sphereMesh1.clone();
  51588. camera = new THREE.PerspectiveCamera(80, window.innerWidth / window.innerHeight, 0.0005, 10000);
  51589. clock = new THREE.Clock();
  51590. time = 0;
  51591. render = function () {
  51592. sceneEl.renderer.render(loaderScene, camera);
  51593. time = clock.getElapsedTime() % 4;
  51594. sphereMesh1.visible = time >= 1;
  51595. sphereMesh2.visible = time >= 2;
  51596. sphereMesh3.visible = time >= 3;
  51597. };
  51598. loaderScene.background = new THREE.Color(backgroundColor);
  51599. loaderScene.add(camera);
  51600. sphereMesh1.position.set(-1, 0, -15);
  51601. sphereMesh2.position.set(0, 0, -15);
  51602. sphereMesh3.position.set(1, 0, -15);
  51603. camera.add(sphereMesh1);
  51604. camera.add(sphereMesh2);
  51605. camera.add(sphereMesh3);
  51606. setupTitle();
  51607. // Delay 200ms to avoid loader flashes.
  51608. setTimeout(function () {
  51609. if (sceneEl.hasLoaded) { return; }
  51610. resize(camera);
  51611. titleEl.style.display = 'block';
  51612. window.addEventListener('resize', function () { resize(camera); });
  51613. sceneEl.renderer.setAnimationLoop(render);
  51614. }, 200);
  51615. };
  51616. module.exports.remove = function remove () {
  51617. window.removeEventListener('resize', resize);
  51618. if (!titleEl) { return; }
  51619. // Hide title.
  51620. titleEl.style.display = 'none';
  51621. };
  51622. function resize (camera) {
  51623. var size = getSceneCanvasSize(sceneEl.canvas, false, sceneEl.maxCanvasSize, sceneEl.is('vr-mode'));
  51624. camera.aspect = size.width / size.height;
  51625. camera.updateProjectionMatrix();
  51626. // Notify renderer of size change.
  51627. sceneEl.renderer.setSize(size.width, size.height, false);
  51628. }
  51629. function setupTitle () {
  51630. titleEl = document.createElement('div');
  51631. titleEl.className = LOADER_TITLE_CLASS;
  51632. titleEl.innerHTML = document.title;
  51633. titleEl.style.display = 'none';
  51634. sceneEl.appendChild(titleEl);
  51635. }
  51636. },{"../../utils/":176}],108:[function(_dereq_,module,exports){
  51637. var constants = _dereq_('../../constants/');
  51638. var extend = _dereq_('../../utils').extend;
  51639. var MOBILE_HEAD_TAGS = module.exports.MOBILE_HEAD_TAGS = [
  51640. 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'}),
  51641. // W3C-standardised meta tags.
  51642. Meta({name: 'mobile-web-app-capable', content: 'yes'}),
  51643. Meta({name: 'theme-color', content: 'black'})
  51644. ];
  51645. var MOBILE_IOS_HEAD_TAGS = [
  51646. // iOS-specific meta tags for fullscreen when pinning to homescreen.
  51647. Meta({name: 'apple-mobile-web-app-capable', content: 'yes'}),
  51648. Meta({name: 'apple-mobile-web-app-status-bar-style', content: 'black'}),
  51649. Link({rel: 'apple-touch-icon', href: 'https://aframe.io/images/aframe-logo-152.png'})
  51650. ];
  51651. function Meta (attrs) {
  51652. return {
  51653. tagName: 'meta',
  51654. attributes: attrs,
  51655. exists: function () { return document.querySelector('meta[name="' + attrs.name + '"]'); }
  51656. };
  51657. }
  51658. function Link (attrs) {
  51659. return {
  51660. tagName: 'link',
  51661. attributes: attrs,
  51662. exists: function () { return document.querySelector('link[rel="' + attrs.rel + '"]'); }
  51663. };
  51664. }
  51665. /**
  51666. * Injects the necessary metatags in the document for mobile support:
  51667. * 1. Prevent the user to zoom in the document.
  51668. * 2. Ensure that window.innerWidth and window.innerHeight have the correct
  51669. * values and the canvas is properly scaled.
  51670. * 3. To allow fullscreen mode when pinning a web app on the home screen on
  51671. * iOS.
  51672. * Adapted from https://www.reddit.com/r/web_design/comments/3la04p/
  51673. *
  51674. * @param {object} scene - Scene element
  51675. * @returns {Array}
  51676. */
  51677. module.exports.inject = function injectHeadTags (scene) {
  51678. var headEl = document.head;
  51679. var headScriptEl = headEl.querySelector('script');
  51680. var tag;
  51681. var headTags = [];
  51682. MOBILE_HEAD_TAGS.forEach(createAndInjectTag);
  51683. if (scene.isIOS) {
  51684. MOBILE_IOS_HEAD_TAGS.forEach(createAndInjectTag);
  51685. }
  51686. return headTags;
  51687. function createAndInjectTag (tagObj) {
  51688. if (!tagObj || tagObj.exists()) { return; }
  51689. tag = createTag(tagObj);
  51690. if (!tag) { return; }
  51691. if (headScriptEl) {
  51692. headScriptEl.parentNode.insertBefore(tag, headScriptEl);
  51693. } else {
  51694. headEl.appendChild(tag);
  51695. }
  51696. headTags.push(tag);
  51697. }
  51698. };
  51699. function createTag (tagObj) {
  51700. if (!tagObj || !tagObj.tagName) { return; }
  51701. var meta = document.createElement(tagObj.tagName);
  51702. meta.setAttribute(constants.AFRAME_INJECTED, '');
  51703. return extend(meta, tagObj.attributes);
  51704. }
  51705. },{"../../constants/":95,"../../utils":176}],109:[function(_dereq_,module,exports){
  51706. var bind = _dereq_('../../utils/bind');
  51707. var isIframed = _dereq_('../../utils/').isIframed;
  51708. /**
  51709. * Provides a post message API for scenes contained
  51710. * in an iframe.
  51711. */
  51712. module.exports = function initPostMessageAPI (scene) {
  51713. // Handles fullscreen behavior when inside an iframe.
  51714. if (!isIframed()) { return; }
  51715. // postMessage API handler
  51716. window.addEventListener('message', bind(postMessageAPIHandler, scene));
  51717. };
  51718. function postMessageAPIHandler (event) {
  51719. var scene = this;
  51720. if (!event.data) { return; }
  51721. switch (event.data.type) {
  51722. case 'vr': {
  51723. switch (event.data.data) {
  51724. case 'enter':
  51725. scene.enterVR();
  51726. break;
  51727. case 'exit':
  51728. scene.exitVR();
  51729. break;
  51730. }
  51731. }
  51732. }
  51733. }
  51734. },{"../../utils/":176,"../../utils/bind":170}],110:[function(_dereq_,module,exports){
  51735. /*
  51736. Scene index for keeping track of created scenes.
  51737. */
  51738. module.exports = [];
  51739. },{}],111:[function(_dereq_,module,exports){
  51740. var Wakelock = _dereq_('../../../vendor/wakelock/wakelock');
  51741. module.exports = function initWakelock (scene) {
  51742. if (!scene.isMobile) { return; }
  51743. var wakelock = scene.wakelock = new Wakelock();
  51744. scene.addEventListener('enter-vr', function () { wakelock.request(); });
  51745. scene.addEventListener('exit-vr', function () { wakelock.release(); });
  51746. };
  51747. },{"../../../vendor/wakelock/wakelock":189}],112:[function(_dereq_,module,exports){
  51748. var utils = _dereq_('../utils/');
  51749. var PropertyTypes = _dereq_('./propertyTypes');
  51750. var debug = utils.debug;
  51751. var isValidDefaultValue = PropertyTypes.isValidDefaultValue;
  51752. var propertyTypes = PropertyTypes.propertyTypes;
  51753. var warn = debug('core:schema:warn');
  51754. /**
  51755. * A schema is classified as a schema for a single property if:
  51756. * - `type` is defined on the schema as a string.
  51757. * - OR `default` is defined on the schema, as a reserved keyword.
  51758. * - OR schema is empty.
  51759. */
  51760. function isSingleProperty (schema) {
  51761. if ('type' in schema) {
  51762. return typeof schema.type === 'string';
  51763. }
  51764. return 'default' in schema;
  51765. }
  51766. module.exports.isSingleProperty = isSingleProperty;
  51767. /**
  51768. * Build step to schema to use `type` to inject default value, parser, and stringifier.
  51769. *
  51770. * @param {object} schema
  51771. * @param {string} componentName
  51772. * @returns {object} Schema.
  51773. */
  51774. module.exports.process = function (schema, componentName) {
  51775. var propName;
  51776. // For single property schema, run processPropDefinition over the whole schema.
  51777. if (isSingleProperty(schema)) {
  51778. return processPropertyDefinition(schema, componentName);
  51779. }
  51780. // For multi-property schema, run processPropDefinition over each property definition.
  51781. for (propName in schema) {
  51782. schema[propName] = processPropertyDefinition(schema[propName], componentName);
  51783. }
  51784. return schema;
  51785. };
  51786. /**
  51787. * Inject default value, parser, stringifier for single property.
  51788. *
  51789. * @param {object} propDefinition
  51790. * @param {string} componentName
  51791. */
  51792. function processPropertyDefinition (propDefinition, componentName) {
  51793. var defaultVal = propDefinition.default;
  51794. var isCustomType;
  51795. var propType;
  51796. var typeName = propDefinition.type;
  51797. // Type inference.
  51798. if (!propDefinition.type) {
  51799. if (defaultVal !== undefined &&
  51800. (typeof defaultVal === 'boolean' || typeof defaultVal === 'number')) {
  51801. // Type inference.
  51802. typeName = typeof defaultVal;
  51803. } else if (Array.isArray(defaultVal)) {
  51804. typeName = 'array';
  51805. } else {
  51806. // Fall back to string.
  51807. typeName = 'string';
  51808. }
  51809. } else if (propDefinition.type === 'bool') {
  51810. typeName = 'boolean';
  51811. } else if (propDefinition.type === 'float') {
  51812. typeName = 'number';
  51813. }
  51814. propType = propertyTypes[typeName];
  51815. if (!propType) {
  51816. warn('Unknown property type for component `' + componentName + '`: ' + typeName);
  51817. }
  51818. // Fill in parse and stringify using property types.
  51819. isCustomType = !!propDefinition.parse;
  51820. propDefinition.parse = propDefinition.parse || propType.parse;
  51821. propDefinition.stringify = propDefinition.stringify || propType.stringify;
  51822. // Fill in type name.
  51823. propDefinition.type = typeName;
  51824. // Check that default value exists.
  51825. if ('default' in propDefinition) {
  51826. // Check that default values are valid.
  51827. if (!isCustomType && !isValidDefaultValue(typeName, defaultVal)) {
  51828. warn('Default value `' + defaultVal + '` does not match type `' + typeName +
  51829. '` in component `' + componentName + '`');
  51830. }
  51831. } else {
  51832. // Fill in default value.
  51833. propDefinition.default = propType.default;
  51834. }
  51835. return propDefinition;
  51836. }
  51837. module.exports.processPropertyDefinition = processPropertyDefinition;
  51838. /**
  51839. * Parse propData using schema. Use default values if not existing in propData.
  51840. *
  51841. * @param {object} propData - Unparsed properties.
  51842. * @param {object} schema - Property types definition.
  51843. * @param {boolean} getPartialData - Whether to return full component data or just the data
  51844. * with keys in `propData`.
  51845. * @param {string } componentName - Name of the component, used for the property warning.
  51846. * @param {boolean} silent - Suppress warning messages.
  51847. */
  51848. module.exports.parseProperties = (function () {
  51849. var propNames = [];
  51850. return function (propData, schema, getPartialData, componentName, silent) {
  51851. var i;
  51852. var propName;
  51853. var propDefinition;
  51854. var propValue;
  51855. propNames.length = 0;
  51856. for (propName in (getPartialData ? propData : schema)) {
  51857. if (getPartialData && propData[propName] === undefined) { continue; }
  51858. propNames.push(propName);
  51859. }
  51860. if (propData === null || typeof propData !== 'object') { return propData; }
  51861. // Validation errors.
  51862. for (propName in propData) {
  51863. if (propData[propName] !== undefined && !schema[propName] && !silent) {
  51864. warn('Unknown property `' + propName +
  51865. '` for component/system `' + componentName + '`.');
  51866. }
  51867. }
  51868. for (i = 0; i < propNames.length; i++) {
  51869. propName = propNames[i];
  51870. propDefinition = schema[propName];
  51871. propValue = propData[propName];
  51872. if (!(schema[propName])) { return; }
  51873. propData[propName] = parseProperty(propValue, propDefinition);
  51874. }
  51875. return propData;
  51876. };
  51877. })();
  51878. /**
  51879. * Deserialize a single property.
  51880. */
  51881. function parseProperty (value, propDefinition) {
  51882. // Use default value if value is falsy.
  51883. if (value === undefined || value === null || value === '') {
  51884. value = propDefinition.default;
  51885. if (Array.isArray(value)) { value = value.slice(); }
  51886. }
  51887. // Invoke property type parser.
  51888. return propDefinition.parse(value, propDefinition.default);
  51889. }
  51890. module.exports.parseProperty = parseProperty;
  51891. /**
  51892. * Serialize a group of properties.
  51893. */
  51894. module.exports.stringifyProperties = function (propData, schema) {
  51895. var propName;
  51896. var propDefinition;
  51897. var propValue;
  51898. var stringifiedData = {};
  51899. var value;
  51900. for (propName in propData) {
  51901. propDefinition = schema[propName];
  51902. propValue = propData[propName];
  51903. value = propValue;
  51904. if (typeof value === 'object') {
  51905. value = stringifyProperty(propValue, propDefinition);
  51906. if (!propDefinition) { warn('Unknown component property: ' + propName); }
  51907. }
  51908. stringifiedData[propName] = value;
  51909. }
  51910. return stringifiedData;
  51911. };
  51912. /**
  51913. * Serialize a single property.
  51914. */
  51915. function stringifyProperty (value, propDefinition) {
  51916. // This function stringifies but it's used in a context where
  51917. // there's always second stringification pass. By returning the original
  51918. // value when it's not an object we save one unnecessary call
  51919. // to JSON.stringify.
  51920. if (typeof value !== 'object') { return value; }
  51921. // if there's no schema for the property we use standar JSON stringify
  51922. if (!propDefinition || value === null) { return JSON.stringify(value); }
  51923. return propDefinition.stringify(value);
  51924. }
  51925. module.exports.stringifyProperty = stringifyProperty;
  51926. },{"../utils/":176,"./propertyTypes":105}],113:[function(_dereq_,module,exports){
  51927. var schema = _dereq_('./schema');
  51928. var processSchema = schema.process;
  51929. var shaders = module.exports.shaders = {}; // Keep track of registered shaders.
  51930. var shaderNames = module.exports.shaderNames = []; // Keep track of the names of registered shaders.
  51931. var THREE = _dereq_('../lib/three');
  51932. var utils = _dereq_('../utils');
  51933. // A-Frame properties to three.js uniform types.
  51934. var propertyToThreeMapping = {
  51935. array: 'v3',
  51936. color: 'v3',
  51937. int: 'i',
  51938. number: 'f',
  51939. map: 't',
  51940. time: 'f',
  51941. vec2: 'v2',
  51942. vec3: 'v3',
  51943. vec4: 'v4'
  51944. };
  51945. /**
  51946. * Shader class definition.
  51947. *
  51948. * Shaders extend the material component API so you can create your own library
  51949. * of customized materials
  51950. *
  51951. */
  51952. var Shader = module.exports.Shader = function () {};
  51953. Shader.prototype = {
  51954. /**
  51955. * Contains the type schema and defaults for the data values.
  51956. * Data is coerced into the types of the values of the defaults.
  51957. */
  51958. schema: {},
  51959. vertexShader:
  51960. 'void main() {' +
  51961. 'gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);' +
  51962. '}',
  51963. fragmentShader:
  51964. 'void main() {' +
  51965. 'gl_FragColor = vec4(1.0, 0.0, 1.0, 1.0);' +
  51966. '}',
  51967. /**
  51968. * Init handler. Similar to attachedCallback.
  51969. * Called during shader initialization and is only run once.
  51970. */
  51971. init: function (data) {
  51972. this.attributes = this.initVariables(data, 'attribute');
  51973. this.uniforms = this.initVariables(data, 'uniform');
  51974. this.material = new (this.raw ? THREE.RawShaderMaterial : THREE.ShaderMaterial)({
  51975. // attributes: this.attributes,
  51976. uniforms: this.uniforms,
  51977. vertexShader: this.vertexShader,
  51978. fragmentShader: this.fragmentShader
  51979. });
  51980. return this.material;
  51981. },
  51982. initVariables: function (data, type) {
  51983. var key;
  51984. var schema = this.schema;
  51985. var variables = {};
  51986. var varType;
  51987. for (key in schema) {
  51988. if (schema[key].is !== type) { continue; }
  51989. varType = propertyToThreeMapping[schema[key].type];
  51990. variables[key] = {
  51991. type: varType,
  51992. value: undefined // Let updateVariables handle setting these.
  51993. };
  51994. }
  51995. return variables;
  51996. },
  51997. /**
  51998. * Update handler. Similar to attributeChangedCallback.
  51999. * Called whenever the associated material data changes.
  52000. *
  52001. * @param {object} data - New material data.
  52002. */
  52003. update: function (data) {
  52004. this.updateVariables(data, 'attribute');
  52005. this.updateVariables(data, 'uniform');
  52006. },
  52007. updateVariables: function (data, type) {
  52008. var key;
  52009. var materialKey;
  52010. var schema = this.schema;
  52011. var variables;
  52012. variables = type === 'uniform' ? this.uniforms : this.attributes;
  52013. for (key in data) {
  52014. if (!schema[key] || schema[key].is !== type) { continue; }
  52015. if (schema[key].type === 'map') {
  52016. // If data unchanged, get out early.
  52017. if (!variables[key] || variables[key].value === data[key]) { continue; }
  52018. // Special handling is needed for textures.
  52019. materialKey = '_texture_' + key;
  52020. // We can't actually set the variable correctly until we've loaded the texture.
  52021. this.setMapOnTextureLoad(variables, key, materialKey);
  52022. // Kick off the texture update now that handler is added.
  52023. utils.material.updateMapMaterialFromData(materialKey, key, this, data);
  52024. continue;
  52025. }
  52026. variables[key].value = this.parseValue(schema[key].type, data[key]);
  52027. variables[key].needsUpdate = true;
  52028. }
  52029. },
  52030. parseValue: function (type, value) {
  52031. var color;
  52032. switch (type) {
  52033. case 'vec2': {
  52034. return new THREE.Vector2(value.x, value.y);
  52035. }
  52036. case 'vec3': {
  52037. return new THREE.Vector3(value.x, value.y, value.z);
  52038. }
  52039. case 'vec4': {
  52040. return new THREE.Vector4(value.x, value.y, value.z, value.w);
  52041. }
  52042. case 'color': {
  52043. color = new THREE.Color(value);
  52044. return new THREE.Vector3(color.r, color.g, color.b);
  52045. }
  52046. case 'map': {
  52047. return THREE.ImageUtils.loadTexture(value);
  52048. }
  52049. default: {
  52050. return value;
  52051. }
  52052. }
  52053. },
  52054. setMapOnTextureLoad: function (variables, key, materialKey) {
  52055. var self = this;
  52056. this.el.addEventListener('materialtextureloaded', function () {
  52057. variables[key].value = self.material[materialKey];
  52058. variables[key].needsUpdate = true;
  52059. });
  52060. }
  52061. };
  52062. /**
  52063. * Registers a shader to A-Frame.
  52064. *
  52065. * @param {string} name - shader name.
  52066. * @param {object} definition - shader property and methods.
  52067. * @returns {object} Shader.
  52068. */
  52069. module.exports.registerShader = function (name, definition) {
  52070. var NewShader;
  52071. var proto = {};
  52072. // Format definition object to prototype object.
  52073. Object.keys(definition).forEach(function (key) {
  52074. proto[key] = {
  52075. value: definition[key],
  52076. writable: true
  52077. };
  52078. });
  52079. if (shaders[name]) {
  52080. throw new Error('The shader ' + name + ' has been already registered');
  52081. }
  52082. NewShader = function () { Shader.call(this); };
  52083. NewShader.prototype = Object.create(Shader.prototype, proto);
  52084. NewShader.prototype.name = name;
  52085. NewShader.prototype.constructor = NewShader;
  52086. shaders[name] = {
  52087. Shader: NewShader,
  52088. schema: processSchema(NewShader.prototype.schema)
  52089. };
  52090. shaderNames.push(name);
  52091. return NewShader;
  52092. };
  52093. },{"../lib/three":151,"../utils":176,"./schema":112}],114:[function(_dereq_,module,exports){
  52094. var components = _dereq_('./component');
  52095. var schema = _dereq_('./schema');
  52096. var utils = _dereq_('../utils/');
  52097. var parseProperties = schema.parseProperties;
  52098. var parseProperty = schema.parseProperty;
  52099. var processSchema = schema.process;
  52100. var isSingleProp = schema.isSingleProperty;
  52101. var styleParser = utils.styleParser;
  52102. var systems = module.exports.systems = {}; // Keep track of registered systems.
  52103. /**
  52104. * System class definition.
  52105. *
  52106. * Systems provide global scope and services to a group of instantiated components of the
  52107. * same class. They can also help abstract logic away from components such that components
  52108. * only have to worry about data.
  52109. *
  52110. * For example, a physics component that creates a physics world that oversees
  52111. * all entities with a physics or rigid body component.
  52112. *
  52113. * TODO: Have the System prototype reuse the Component prototype. Most code is copied
  52114. * and some pieces are missing from the Component facilities (e.g., attribute caching,
  52115. * setAttribute behavior).
  52116. *
  52117. * @member {string} name - Name that system is registered under.
  52118. * @member {Element} sceneEl - Handle to the scene element where system applies to.
  52119. */
  52120. var System = module.exports.System = function (sceneEl) {
  52121. var component = components && components.components[this.name];
  52122. // Set reference to scene.
  52123. this.el = sceneEl;
  52124. this.sceneEl = sceneEl;
  52125. // Set reference to matching component (if exists).
  52126. if (component) { component.Component.prototype.system = this; }
  52127. // Process system configuration.
  52128. this.buildData();
  52129. this.init();
  52130. this.update({});
  52131. };
  52132. System.prototype = {
  52133. /**
  52134. * Schema to configure system.
  52135. */
  52136. schema: {},
  52137. /**
  52138. * Init handler. Called during scene initialization and is only run once.
  52139. * Systems can use this to set initial state.
  52140. */
  52141. init: function () { /* no-op */ },
  52142. /**
  52143. * Update handler. Called during scene attribute updates.
  52144. * Systems can use this to dynamically update their state.
  52145. */
  52146. update: function (oldData) { /* no-op */ },
  52147. /**
  52148. * Build data and call update handler.
  52149. *
  52150. * @private
  52151. */
  52152. updateProperties: function (rawData) {
  52153. var oldData = this.data;
  52154. if (!Object.keys(schema).length) { return; }
  52155. this.buildData(rawData);
  52156. this.update(oldData);
  52157. },
  52158. /**
  52159. * Parse data.
  52160. */
  52161. buildData: function (rawData) {
  52162. var schema = this.schema;
  52163. if (!Object.keys(schema).length) { return; }
  52164. rawData = rawData || window.HTMLElement.prototype.getAttribute.call(this.sceneEl, this.name);
  52165. if (isSingleProp(schema)) {
  52166. this.data = parseProperty(rawData, schema);
  52167. } else {
  52168. this.data = parseProperties(styleParser.parse(rawData) || {}, schema);
  52169. }
  52170. },
  52171. /**
  52172. * Tick handler.
  52173. * Called on each tick of the scene render loop.
  52174. * Affected by play and pause.
  52175. *
  52176. * @param {number} time - Scene tick time.
  52177. * @param {number} timeDelta - Difference in current render time and previous render time.
  52178. */
  52179. tick: undefined,
  52180. /**
  52181. * Tock handler.
  52182. * Called on each tock of the scene render loop.
  52183. * Affected by play and pause.
  52184. *
  52185. * @param {number} time - Scene tick time.
  52186. * @param {number} timeDelta - Difference in current render time and previous render time.
  52187. */
  52188. tock: undefined,
  52189. /**
  52190. * Called to start any dynamic behavior (e.g., animation, AI, events, physics).
  52191. */
  52192. play: function () { /* no-op */ },
  52193. /**
  52194. * Called to stop any dynamic behavior (e.g., animation, AI, events, physics).
  52195. */
  52196. pause: function () { /* no-op */ }
  52197. };
  52198. /**
  52199. * Registers a system to A-Frame.
  52200. *
  52201. * @param {string} name - Component name.
  52202. * @param {object} definition - Component property and methods.
  52203. * @returns {object} Component.
  52204. */
  52205. module.exports.registerSystem = function (name, definition) {
  52206. var i;
  52207. var NewSystem;
  52208. var proto = {};
  52209. var scenes = utils.findAllScenes(document);
  52210. // Format definition object to prototype object.
  52211. Object.keys(definition).forEach(function (key) {
  52212. proto[key] = {
  52213. value: definition[key],
  52214. writable: true
  52215. };
  52216. });
  52217. if (systems[name]) {
  52218. throw new Error('The system `' + name + '` has been already registered. ' +
  52219. 'Check that you are not loading two versions of the same system ' +
  52220. 'or two different systems of the same name.');
  52221. }
  52222. NewSystem = function (sceneEl) { System.call(this, sceneEl); };
  52223. NewSystem.prototype = Object.create(System.prototype, proto);
  52224. NewSystem.prototype.name = name;
  52225. NewSystem.prototype.constructor = NewSystem;
  52226. NewSystem.prototype.schema = utils.extend(processSchema(NewSystem.prototype.schema));
  52227. systems[name] = NewSystem;
  52228. // Initialize systems for existing scenes
  52229. for (i = 0; i < scenes.length; i++) { scenes[i].initSystem(name); }
  52230. };
  52231. },{"../utils/":176,"./component":103,"./schema":112}],115:[function(_dereq_,module,exports){
  52232. _dereq_('./pivot');
  52233. },{"./pivot":116}],116:[function(_dereq_,module,exports){
  52234. var registerComponent = _dereq_('../../core/component').registerComponent;
  52235. var THREE = _dereq_('../../lib/three');
  52236. var originalPosition = new THREE.Vector3();
  52237. var originalRotation = new THREE.Vector3();
  52238. /**
  52239. * Wrap el.object3D within an outer group. Apply pivot to el.object3D as position.
  52240. */
  52241. registerComponent('pivot', {
  52242. dependencies: ['position'],
  52243. schema: {type: 'vec3'},
  52244. init: function () {
  52245. var data = this.data;
  52246. var el = this.el;
  52247. var originalParent = el.object3D.parent;
  52248. var originalGroup = el.object3D;
  52249. var outerGroup = new THREE.Group();
  52250. originalPosition.copy(originalGroup.position);
  52251. originalRotation.copy(originalGroup.rotation);
  52252. // Detach current group from parent.
  52253. originalParent.remove(originalGroup);
  52254. outerGroup.add(originalGroup);
  52255. // Set new group as the outer group.
  52256. originalParent.add(outerGroup);
  52257. // Set outer group as new object3D.
  52258. el.object3D = outerGroup;
  52259. // Apply pivot to original group.
  52260. originalGroup.position.set(-1 * data.x, -1 * data.y, -1 * data.z);
  52261. // Offset the pivot so that world position not affected.
  52262. // And restore position onto outer group.
  52263. outerGroup.position.set(data.x + originalPosition.x, data.y + originalPosition.y,
  52264. data.z + originalPosition.z);
  52265. // Transfer rotation to outer group.
  52266. outerGroup.rotation.copy(originalGroup.rotation);
  52267. originalGroup.rotation.set(0, 0, 0);
  52268. }
  52269. });
  52270. },{"../../core/component":103,"../../lib/three":151}],117:[function(_dereq_,module,exports){
  52271. /**
  52272. * Common mesh defaults, mappings, and transforms.
  52273. */
  52274. var components = _dereq_('../../core/component').components;
  52275. var shaders = _dereq_('../../core/shader').shaders;
  52276. var utils = _dereq_('../../utils/');
  52277. var materialMappings = {};
  52278. Object.keys(components.material.schema).forEach(addMapping);
  52279. Object.keys(shaders.standard.schema).forEach(addMapping);
  52280. function addMapping (prop) {
  52281. // To hyphenated.
  52282. var htmlAttrName = prop.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();
  52283. if (prop === 'fog') { htmlAttrName = 'material-fog'; }
  52284. if (prop === 'visible') { htmlAttrName = 'material-visible'; }
  52285. materialMappings[htmlAttrName] = 'material.' + prop;
  52286. }
  52287. module.exports = function getMeshMixin () {
  52288. return {
  52289. defaultComponents: {material: {}},
  52290. mappings: utils.extend({}, materialMappings)
  52291. };
  52292. };
  52293. },{"../../core/component":103,"../../core/shader":113,"../../utils/":176}],118:[function(_dereq_,module,exports){
  52294. _dereq_('./primitives/a-camera');
  52295. _dereq_('./primitives/a-cursor');
  52296. _dereq_('./primitives/a-curvedimage');
  52297. _dereq_('./primitives/a-gltf-model');
  52298. _dereq_('./primitives/a-image');
  52299. _dereq_('./primitives/a-light');
  52300. _dereq_('./primitives/a-link');
  52301. _dereq_('./primitives/a-obj-model');
  52302. _dereq_('./primitives/a-sky');
  52303. _dereq_('./primitives/a-sound');
  52304. _dereq_('./primitives/a-text');
  52305. _dereq_('./primitives/a-video');
  52306. _dereq_('./primitives/a-videosphere');
  52307. _dereq_('./primitives/meshPrimitives');
  52308. },{"./primitives/a-camera":120,"./primitives/a-cursor":121,"./primitives/a-curvedimage":122,"./primitives/a-gltf-model":123,"./primitives/a-image":124,"./primitives/a-light":125,"./primitives/a-link":126,"./primitives/a-obj-model":127,"./primitives/a-sky":128,"./primitives/a-sound":129,"./primitives/a-text":130,"./primitives/a-video":131,"./primitives/a-videosphere":132,"./primitives/meshPrimitives":133}],119:[function(_dereq_,module,exports){
  52309. var AEntity = _dereq_('../../core/a-entity');
  52310. var components = _dereq_('../../core/component').components;
  52311. var registerElement = _dereq_('../../core/a-register-element').registerElement;
  52312. var utils = _dereq_('../../utils/');
  52313. var debug = utils.debug;
  52314. var setComponentProperty = utils.entity.setComponentProperty;
  52315. var log = debug('extras:primitives:debug');
  52316. var warn = debug('extras:primitives:warn');
  52317. var primitives = module.exports.primitives = {};
  52318. module.exports.registerPrimitive = function registerPrimitive (name, definition) {
  52319. name = name.toLowerCase();
  52320. log('Registering <%s>', name);
  52321. // Deprecation warning for defaultAttributes usage.
  52322. if (definition.defaultAttributes) {
  52323. warn("The 'defaultAttributes' object is deprecated. Use 'defaultComponents' instead.");
  52324. }
  52325. var primitive = registerElement(name, {
  52326. prototype: Object.create(AEntity.prototype, {
  52327. defaultComponentsFromPrimitive: {
  52328. value: definition.defaultComponents || definition.defaultAttributes || {}
  52329. },
  52330. deprecated: {value: definition.deprecated || null},
  52331. deprecatedMappings: {value: definition.deprecatedMappings || {}},
  52332. mappings: {value: definition.mappings || {}},
  52333. createdCallback: {
  52334. value: function () {
  52335. if (definition.deprecated) { console.warn(definition.deprecated); }
  52336. this.resolveMappingCollisions();
  52337. }
  52338. },
  52339. /**
  52340. * If a mapping collides with a registered component name
  52341. * it renames the mapping to componentname-property
  52342. */
  52343. resolveMappingCollisions: {
  52344. value: function () {
  52345. var mappings = this.mappings;
  52346. var self = this;
  52347. Object.keys(mappings).forEach(function resolveCollision (key) {
  52348. var newAttribute;
  52349. if (key !== key.toLowerCase()) { warn('Mapping keys should be specified in lower case. The mapping key ' + key + ' may not be recognized'); }
  52350. if (components[key]) {
  52351. newAttribute = mappings[key].replace('.', '-');
  52352. mappings[newAttribute] = mappings[key];
  52353. delete mappings[key];
  52354. console.warn('The primitive ' + self.tagName.toLowerCase() + ' has a mapping collision. ' +
  52355. 'The attribute ' + key + ' has the same name as a registered component and' +
  52356. ' has been renamed to ' + newAttribute);
  52357. }
  52358. });
  52359. }
  52360. },
  52361. getExtraComponents: {
  52362. value: function () {
  52363. var attr;
  52364. var data;
  52365. var i;
  52366. var mapping;
  52367. var mixins;
  52368. var path;
  52369. var self = this;
  52370. // Gather component data from default components.
  52371. data = utils.clone(this.defaultComponentsFromPrimitive);
  52372. // Factor in mixins to overwrite default components.
  52373. mixins = this.getAttribute('mixin');
  52374. if (mixins) {
  52375. mixins = mixins.trim().split(' ');
  52376. mixins.forEach(function applyMixin (mixinId) {
  52377. var mixinComponents = self.sceneEl.querySelector('#' + mixinId).componentCache;
  52378. Object.keys(mixinComponents).forEach(function setComponent (name) {
  52379. data[name] = extend(data[name], mixinComponents[name]);
  52380. });
  52381. });
  52382. }
  52383. // Gather component data from mappings.
  52384. for (i = 0; i < this.attributes.length; i++) {
  52385. attr = this.attributes[i];
  52386. mapping = this.mappings[attr.name];
  52387. if (mapping) {
  52388. path = utils.entity.getComponentPropertyPath(mapping);
  52389. if (path.constructor === Array) {
  52390. data[path[0]] = data[path[0]] || {};
  52391. data[path[0]][path[1]] = attr.value.trim();
  52392. } else {
  52393. data[path] = attr.value.trim();
  52394. }
  52395. continue;
  52396. }
  52397. }
  52398. return data;
  52399. /**
  52400. * For the base to be extensible, both objects must be pure JavaScript objects.
  52401. * The function assumes that base is undefined, or null or a pure object.
  52402. */
  52403. function extend (base, extension) {
  52404. if (isUndefined(base)) {
  52405. return copy(extension);
  52406. }
  52407. if (isUndefined(extension)) {
  52408. return copy(base);
  52409. }
  52410. if (isPureObject(base) && isPureObject(extension)) {
  52411. return utils.extendDeep(base, extension);
  52412. }
  52413. return copy(extension);
  52414. }
  52415. function isUndefined (value) {
  52416. return typeof value === 'undefined';
  52417. }
  52418. function copy (value) {
  52419. if (isPureObject(value)) {
  52420. return utils.extendDeep({}, value);
  52421. }
  52422. return value;
  52423. }
  52424. function isPureObject (value) {
  52425. return value !== null && value.constructor === Object;
  52426. }
  52427. }
  52428. },
  52429. /**
  52430. * Sync to attribute to component property whenever mapped attribute changes.
  52431. * If attribute is mapped to a component property, set the component property using
  52432. * the attribute value.
  52433. */
  52434. attributeChangedCallback: {
  52435. value: function (attr, oldVal, value) {
  52436. var componentName = this.mappings[attr];
  52437. if (attr in this.deprecatedMappings) {
  52438. console.warn(this.deprecatedMappings[attr]);
  52439. }
  52440. if (!attr || !componentName) { return; }
  52441. // Set value.
  52442. setComponentProperty(this, componentName, value);
  52443. }
  52444. }
  52445. })
  52446. });
  52447. // Store.
  52448. primitives[name] = primitive;
  52449. return primitive;
  52450. };
  52451. /**
  52452. * Add component mappings using schema.
  52453. */
  52454. function addComponentMapping (componentName, mappings) {
  52455. var schema = components[componentName].schema;
  52456. Object.keys(schema).map(function (prop) {
  52457. // Hyphenate where there is camelCase.
  52458. var attrName = prop.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();
  52459. // If there is a mapping collision, prefix with component name and hyphen.
  52460. if (mappings[attrName] !== undefined) { attrName = componentName + '-' + prop; }
  52461. mappings[attrName] = componentName + '.' + prop;
  52462. });
  52463. }
  52464. /**
  52465. * Helper to define a primitive, building mappings using a component schema.
  52466. */
  52467. function definePrimitive (tagName, defaultComponents, mappings) {
  52468. // If no initial mappings provided, start from empty map.
  52469. mappings = mappings || {};
  52470. // From the default components, add mapping automagically.
  52471. Object.keys(defaultComponents).map(function buildMappings (componentName) {
  52472. addComponentMapping(componentName, mappings);
  52473. });
  52474. // Register the primitive.
  52475. module.exports.registerPrimitive(tagName, utils.extendDeep({}, null, {
  52476. defaultComponents: defaultComponents,
  52477. mappings: mappings
  52478. }));
  52479. }
  52480. module.exports.definePrimitive = definePrimitive;
  52481. },{"../../core/a-entity":99,"../../core/a-register-element":102,"../../core/component":103,"../../utils/":176}],120:[function(_dereq_,module,exports){
  52482. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  52483. registerPrimitive('a-camera', {
  52484. defaultComponents: {
  52485. 'camera': {},
  52486. 'look-controls': {},
  52487. 'wasd-controls': {},
  52488. 'position': {x: 0, y: 1.6, z: 0}
  52489. },
  52490. mappings: {
  52491. active: 'camera.active',
  52492. far: 'camera.far',
  52493. fov: 'camera.fov',
  52494. 'look-controls-enabled': 'look-controls.enabled',
  52495. near: 'camera.near',
  52496. 'pointer-lock-enabled': 'look-controls.pointerLockEnabled',
  52497. 'wasd-controls-enabled': 'wasd-controls.enabled',
  52498. 'reverse-mouse-drag': 'look-controls.reverseMouseDrag',
  52499. zoom: 'camera.zoom'
  52500. }
  52501. });
  52502. },{"../primitives":119}],121:[function(_dereq_,module,exports){
  52503. var getMeshMixin = _dereq_('../getMeshMixin');
  52504. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  52505. var utils = _dereq_('../../../utils/');
  52506. registerPrimitive('a-cursor', utils.extendDeep({}, getMeshMixin(), {
  52507. defaultComponents: {
  52508. cursor: {},
  52509. geometry: {
  52510. primitive: 'ring',
  52511. radiusOuter: 0.016,
  52512. radiusInner: 0.01,
  52513. segmentsTheta: 32
  52514. },
  52515. material: {
  52516. color: '#000',
  52517. shader: 'flat',
  52518. opacity: 0.8
  52519. },
  52520. position: {
  52521. x: 0,
  52522. y: 0,
  52523. z: -1
  52524. }
  52525. },
  52526. mappings: {
  52527. far: 'raycaster.far',
  52528. fuse: 'cursor.fuse',
  52529. 'fuse-timeout': 'cursor.fuseTimeout',
  52530. interval: 'raycaster.interval',
  52531. objects: 'raycaster.objects'
  52532. }
  52533. }));
  52534. },{"../../../utils/":176,"../getMeshMixin":117,"../primitives":119}],122:[function(_dereq_,module,exports){
  52535. var getMeshMixin = _dereq_('../getMeshMixin');
  52536. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  52537. var utils = _dereq_('../../../utils/');
  52538. registerPrimitive('a-curvedimage', utils.extendDeep({}, getMeshMixin(), {
  52539. defaultComponents: {
  52540. geometry: {
  52541. height: 1,
  52542. primitive: 'cylinder',
  52543. radius: 2,
  52544. segmentsRadial: 48,
  52545. thetaLength: 270,
  52546. openEnded: true,
  52547. thetaStart: 0
  52548. },
  52549. material: {
  52550. color: '#FFF',
  52551. shader: 'flat',
  52552. side: 'double',
  52553. transparent: true,
  52554. repeat: '-1 1'
  52555. }
  52556. },
  52557. mappings: {
  52558. height: 'geometry.height',
  52559. 'open-ended': 'geometry.openEnded',
  52560. radius: 'geometry.radius',
  52561. segments: 'geometry.segmentsRadial',
  52562. start: 'geometry.thetaStart',
  52563. 'theta-length': 'geometry.thetaLength',
  52564. 'theta-start': 'geometry.thetaStart',
  52565. 'width': 'geometry.thetaLength'
  52566. }
  52567. }));
  52568. },{"../../../utils/":176,"../getMeshMixin":117,"../primitives":119}],123:[function(_dereq_,module,exports){
  52569. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  52570. registerPrimitive('a-gltf-model', {
  52571. mappings: {
  52572. src: 'gltf-model'
  52573. }
  52574. });
  52575. },{"../primitives":119}],124:[function(_dereq_,module,exports){
  52576. var getMeshMixin = _dereq_('../getMeshMixin');
  52577. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  52578. var utils = _dereq_('../../../utils/');
  52579. registerPrimitive('a-image', utils.extendDeep({}, getMeshMixin(), {
  52580. defaultComponents: {
  52581. geometry: {
  52582. primitive: 'plane'
  52583. },
  52584. material: {
  52585. color: '#FFF',
  52586. shader: 'flat',
  52587. side: 'double',
  52588. transparent: true
  52589. }
  52590. },
  52591. mappings: {
  52592. height: 'geometry.height',
  52593. width: 'geometry.width'
  52594. }
  52595. }));
  52596. },{"../../../utils/":176,"../getMeshMixin":117,"../primitives":119}],125:[function(_dereq_,module,exports){
  52597. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  52598. registerPrimitive('a-light', {
  52599. defaultComponents: {
  52600. light: {}
  52601. },
  52602. mappings: {
  52603. angle: 'light.angle',
  52604. color: 'light.color',
  52605. 'ground-color': 'light.groundColor',
  52606. decay: 'light.decay',
  52607. distance: 'light.distance',
  52608. intensity: 'light.intensity',
  52609. penumbra: 'light.penumbra',
  52610. type: 'light.type',
  52611. target: 'light.target'
  52612. }
  52613. });
  52614. },{"../primitives":119}],126:[function(_dereq_,module,exports){
  52615. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  52616. registerPrimitive('a-link', {
  52617. defaultComponents: {
  52618. link: {
  52619. visualAspectEnabled: true
  52620. }
  52621. },
  52622. mappings: {
  52623. href: 'link.href',
  52624. image: 'link.image',
  52625. title: 'link.title'
  52626. }
  52627. });
  52628. },{"../primitives":119}],127:[function(_dereq_,module,exports){
  52629. var meshMixin = _dereq_('../getMeshMixin')();
  52630. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  52631. var utils = _dereq_('../../../utils/');
  52632. registerPrimitive('a-obj-model', utils.extendDeep({}, meshMixin, {
  52633. defaultComponents: {
  52634. 'obj-model': {}
  52635. },
  52636. mappings: {
  52637. src: 'obj-model.obj',
  52638. mtl: 'obj-model.mtl'
  52639. }
  52640. }));
  52641. },{"../../../utils/":176,"../getMeshMixin":117,"../primitives":119}],128:[function(_dereq_,module,exports){
  52642. var getMeshMixin = _dereq_('../getMeshMixin');
  52643. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  52644. var utils = _dereq_('../../../utils/');
  52645. var meshPrimitives = _dereq_('./meshPrimitives');
  52646. registerPrimitive('a-sky', utils.extendDeep({}, getMeshMixin(), {
  52647. defaultComponents: {
  52648. geometry: {
  52649. primitive: 'sphere',
  52650. radius: 5000,
  52651. segmentsWidth: 64,
  52652. segmentsHeight: 32
  52653. },
  52654. material: {
  52655. color: '#FFF',
  52656. side: 'back',
  52657. shader: 'flat',
  52658. npot: true
  52659. },
  52660. scale: '-1 1 1'
  52661. },
  52662. mappings: utils.extendDeep({}, meshPrimitives['a-sphere'].prototype.mappings)
  52663. }));
  52664. },{"../../../utils/":176,"../getMeshMixin":117,"../primitives":119,"./meshPrimitives":133}],129:[function(_dereq_,module,exports){
  52665. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  52666. registerPrimitive('a-sound', {
  52667. defaultComponents: {
  52668. sound: {}
  52669. },
  52670. mappings: {
  52671. src: 'sound.src',
  52672. on: 'sound.on',
  52673. autoplay: 'sound.autoplay',
  52674. loop: 'sound.loop',
  52675. volume: 'sound.volume'
  52676. }
  52677. });
  52678. },{"../primitives":119}],130:[function(_dereq_,module,exports){
  52679. // <a-text> using `definePrimitive` helper.
  52680. var definePrimitive = _dereq_('../primitives').definePrimitive;
  52681. definePrimitive('a-text', {text: {anchor: 'align', width: 5}});
  52682. },{"../primitives":119}],131:[function(_dereq_,module,exports){
  52683. var getMeshMixin = _dereq_('../getMeshMixin');
  52684. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  52685. var utils = _dereq_('../../../utils/');
  52686. registerPrimitive('a-video', utils.extendDeep({}, getMeshMixin(), {
  52687. defaultComponents: {
  52688. geometry: {
  52689. primitive: 'plane'
  52690. },
  52691. material: {
  52692. color: '#FFF',
  52693. shader: 'flat',
  52694. side: 'double',
  52695. transparent: true
  52696. }
  52697. },
  52698. mappings: {
  52699. height: 'geometry.height',
  52700. width: 'geometry.width'
  52701. }
  52702. }));
  52703. },{"../../../utils/":176,"../getMeshMixin":117,"../primitives":119}],132:[function(_dereq_,module,exports){
  52704. var getMeshMixin = _dereq_('../getMeshMixin');
  52705. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  52706. var utils = _dereq_('../../../utils/');
  52707. registerPrimitive('a-videosphere', utils.extendDeep({}, getMeshMixin(), {
  52708. defaultComponents: {
  52709. geometry: {
  52710. primitive: 'sphere',
  52711. radius: 5000,
  52712. segmentsWidth: 64,
  52713. segmentsHeight: 32
  52714. },
  52715. material: {
  52716. color: '#FFF',
  52717. shader: 'flat',
  52718. side: 'back',
  52719. npot: true
  52720. },
  52721. scale: '-1 1 1'
  52722. },
  52723. mappings: {
  52724. radius: 'geometry.radius',
  52725. 'segments-height': 'geometry.segmentsHeight',
  52726. 'segments-width': 'geometry.segmentsWidth'
  52727. }
  52728. }));
  52729. },{"../../../utils/":176,"../getMeshMixin":117,"../primitives":119}],133:[function(_dereq_,module,exports){
  52730. /**
  52731. * Automated mesh primitive registration.
  52732. */
  52733. var getMeshMixin = _dereq_('../getMeshMixin');
  52734. var geometries = _dereq_('../../../core/geometry').geometries;
  52735. var geometryNames = _dereq_('../../../core/geometry').geometryNames;
  52736. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  52737. var utils = _dereq_('../../../utils/');
  52738. // For testing.
  52739. var meshPrimitives = module.exports = {};
  52740. // Generate primitive for each geometry type.
  52741. geometryNames.forEach(function registerMeshPrimitive (geometryName) {
  52742. var geometry = geometries[geometryName];
  52743. var geometryHyphened = unCamelCase(geometryName);
  52744. // Generate mappings.
  52745. var mappings = {};
  52746. Object.keys(geometry.schema).forEach(function createMapping (property) {
  52747. mappings[unCamelCase(property)] = 'geometry.' + property;
  52748. });
  52749. // Register.
  52750. var tagName = 'a-' + geometryHyphened;
  52751. var primitive = registerPrimitive(tagName, utils.extendDeep({}, getMeshMixin(), {
  52752. defaultComponents: {geometry: {primitive: geometryName}},
  52753. mappings: mappings
  52754. }));
  52755. meshPrimitives[tagName] = primitive;
  52756. });
  52757. /**
  52758. * camelCase to hyphened-string.
  52759. */
  52760. function unCamelCase (str) {
  52761. return str.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();
  52762. }
  52763. },{"../../../core/geometry":104,"../../../utils/":176,"../getMeshMixin":117,"../primitives":119}],134:[function(_dereq_,module,exports){
  52764. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  52765. var THREE = _dereq_('../lib/three');
  52766. registerGeometry('box', {
  52767. schema: {
  52768. depth: {default: 1, min: 0},
  52769. height: {default: 1, min: 0},
  52770. width: {default: 1, min: 0},
  52771. segmentsHeight: {default: 1, min: 1, max: 20, type: 'int'},
  52772. segmentsWidth: {default: 1, min: 1, max: 20, type: 'int'},
  52773. segmentsDepth: {default: 1, min: 1, max: 20, type: 'int'}
  52774. },
  52775. init: function (data) {
  52776. this.geometry = new THREE.BoxGeometry(
  52777. data.width, data.height, data.depth,
  52778. data.segmentsWidth, data.segmentsHeight, data.segmentsDepth);
  52779. }
  52780. });
  52781. },{"../core/geometry":104,"../lib/three":151}],135:[function(_dereq_,module,exports){
  52782. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  52783. var THREE = _dereq_('../lib/three');
  52784. var degToRad = THREE.Math.degToRad;
  52785. registerGeometry('circle', {
  52786. schema: {
  52787. radius: {default: 1, min: 0},
  52788. segments: {default: 32, min: 3, type: 'int'},
  52789. thetaLength: {default: 360, min: 0},
  52790. thetaStart: {default: 0}
  52791. },
  52792. init: function (data) {
  52793. this.geometry = new THREE.CircleGeometry(
  52794. data.radius, data.segments, degToRad(data.thetaStart), degToRad(data.thetaLength));
  52795. }
  52796. });
  52797. },{"../core/geometry":104,"../lib/three":151}],136:[function(_dereq_,module,exports){
  52798. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  52799. var THREE = _dereq_('../lib/three');
  52800. var degToRad = THREE.Math.degToRad;
  52801. registerGeometry('cone', {
  52802. schema: {
  52803. height: {default: 1, min: 0},
  52804. openEnded: {default: false},
  52805. radiusBottom: {default: 1, min: 0},
  52806. radiusTop: {default: 0.01, min: 0},
  52807. segmentsHeight: {default: 18, min: 1, type: 'int'},
  52808. segmentsRadial: {default: 36, min: 3, type: 'int'},
  52809. thetaLength: {default: 360, min: 0},
  52810. thetaStart: {default: 0}
  52811. },
  52812. init: function (data) {
  52813. this.geometry = new THREE.CylinderGeometry(
  52814. data.radiusTop, data.radiusBottom, data.height, data.segmentsRadial,
  52815. data.segmentsHeight, data.openEnded, degToRad(data.thetaStart),
  52816. degToRad(data.thetaLength));
  52817. }
  52818. });
  52819. },{"../core/geometry":104,"../lib/three":151}],137:[function(_dereq_,module,exports){
  52820. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  52821. var THREE = _dereq_('../lib/three');
  52822. var degToRad = THREE.Math.degToRad;
  52823. registerGeometry('cylinder', {
  52824. schema: {
  52825. height: {default: 1, min: 0},
  52826. openEnded: {default: false},
  52827. radius: {default: 1, min: 0},
  52828. segmentsHeight: {default: 18, min: 1, type: 'int'},
  52829. segmentsRadial: {default: 36, min: 3, type: 'int'},
  52830. thetaLength: {default: 360, min: 0},
  52831. thetaStart: {default: 0}
  52832. },
  52833. init: function (data) {
  52834. this.geometry = new THREE.CylinderGeometry(
  52835. data.radius, data.radius, data.height, data.segmentsRadial, data.segmentsHeight,
  52836. data.openEnded, degToRad(data.thetaStart), degToRad(data.thetaLength));
  52837. }
  52838. });
  52839. },{"../core/geometry":104,"../lib/three":151}],138:[function(_dereq_,module,exports){
  52840. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  52841. var THREE = _dereq_('../lib/three');
  52842. registerGeometry('dodecahedron', {
  52843. schema: {
  52844. detail: {default: 0, min: 0, max: 5, type: 'int'},
  52845. radius: {default: 1, min: 0}
  52846. },
  52847. init: function (data) {
  52848. this.geometry = new THREE.DodecahedronGeometry(data.radius, data.detail);
  52849. }
  52850. });
  52851. },{"../core/geometry":104,"../lib/three":151}],139:[function(_dereq_,module,exports){
  52852. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  52853. var THREE = _dereq_('../lib/three');
  52854. registerGeometry('icosahedron', {
  52855. schema: {
  52856. detail: {default: 0, min: 0, max: 5, type: 'int'},
  52857. radius: {default: 1, min: 0}
  52858. },
  52859. init: function (data) {
  52860. this.geometry = new THREE.IcosahedronGeometry(data.radius, data.detail);
  52861. }
  52862. });
  52863. },{"../core/geometry":104,"../lib/three":151}],140:[function(_dereq_,module,exports){
  52864. _dereq_('./box.js');
  52865. _dereq_('./circle.js');
  52866. _dereq_('./cone.js');
  52867. _dereq_('./cylinder.js');
  52868. _dereq_('./dodecahedron.js');
  52869. _dereq_('./icosahedron.js');
  52870. _dereq_('./octahedron.js');
  52871. _dereq_('./plane.js');
  52872. _dereq_('./ring.js');
  52873. _dereq_('./sphere.js');
  52874. _dereq_('./tetrahedron.js');
  52875. _dereq_('./torus.js');
  52876. _dereq_('./torusKnot.js');
  52877. _dereq_('./triangle.js');
  52878. },{"./box.js":134,"./circle.js":135,"./cone.js":136,"./cylinder.js":137,"./dodecahedron.js":138,"./icosahedron.js":139,"./octahedron.js":141,"./plane.js":142,"./ring.js":143,"./sphere.js":144,"./tetrahedron.js":145,"./torus.js":146,"./torusKnot.js":147,"./triangle.js":148}],141:[function(_dereq_,module,exports){
  52879. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  52880. var THREE = _dereq_('../lib/three');
  52881. registerGeometry('octahedron', {
  52882. schema: {
  52883. detail: {default: 0, min: 0, max: 5, type: 'int'},
  52884. radius: {default: 1, min: 0}
  52885. },
  52886. init: function (data) {
  52887. this.geometry = new THREE.OctahedronGeometry(data.radius, data.detail);
  52888. }
  52889. });
  52890. },{"../core/geometry":104,"../lib/three":151}],142:[function(_dereq_,module,exports){
  52891. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  52892. var THREE = _dereq_('../lib/three');
  52893. registerGeometry('plane', {
  52894. schema: {
  52895. height: {default: 1, min: 0},
  52896. width: {default: 1, min: 0},
  52897. segmentsHeight: {default: 1, min: 1, max: 20, type: 'int'},
  52898. segmentsWidth: {default: 1, min: 1, max: 20, type: 'int'}
  52899. },
  52900. init: function (data) {
  52901. this.geometry = new THREE.PlaneGeometry(data.width, data.height, data.segmentsWidth, data.segmentsHeight);
  52902. }
  52903. });
  52904. },{"../core/geometry":104,"../lib/three":151}],143:[function(_dereq_,module,exports){
  52905. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  52906. var THREE = _dereq_('../lib/three');
  52907. var degToRad = THREE.Math.degToRad;
  52908. registerGeometry('ring', {
  52909. schema: {
  52910. radiusInner: {default: 0.8, min: 0},
  52911. radiusOuter: {default: 1.2, min: 0},
  52912. segmentsPhi: {default: 10, min: 1, type: 'int'},
  52913. segmentsTheta: {default: 32, min: 3, type: 'int'},
  52914. thetaLength: {default: 360, min: 0},
  52915. thetaStart: {default: 0}
  52916. },
  52917. init: function (data) {
  52918. this.geometry = new THREE.RingGeometry(
  52919. data.radiusInner, data.radiusOuter, data.segmentsTheta, data.segmentsPhi,
  52920. degToRad(data.thetaStart), degToRad(data.thetaLength));
  52921. }
  52922. });
  52923. },{"../core/geometry":104,"../lib/three":151}],144:[function(_dereq_,module,exports){
  52924. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  52925. var THREE = _dereq_('../lib/three');
  52926. var degToRad = THREE.Math.degToRad;
  52927. registerGeometry('sphere', {
  52928. schema: {
  52929. radius: {default: 1, min: 0},
  52930. phiLength: {default: 360},
  52931. phiStart: {default: 0, min: 0},
  52932. thetaLength: {default: 180, min: 0},
  52933. thetaStart: {default: 0},
  52934. segmentsHeight: {default: 18, min: 2, type: 'int'},
  52935. segmentsWidth: {default: 36, min: 3, type: 'int'}
  52936. },
  52937. init: function (data) {
  52938. this.geometry = new THREE.SphereGeometry(
  52939. data.radius, data.segmentsWidth, data.segmentsHeight, degToRad(data.phiStart),
  52940. degToRad(data.phiLength), degToRad(data.thetaStart), degToRad(data.thetaLength));
  52941. }
  52942. });
  52943. },{"../core/geometry":104,"../lib/three":151}],145:[function(_dereq_,module,exports){
  52944. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  52945. var THREE = _dereq_('../lib/three');
  52946. registerGeometry('tetrahedron', {
  52947. schema: {
  52948. detail: {default: 0, min: 0, max: 5, type: 'int'},
  52949. radius: {default: 1, min: 0}
  52950. },
  52951. init: function (data) {
  52952. this.geometry = new THREE.TetrahedronGeometry(data.radius, data.detail);
  52953. }
  52954. });
  52955. },{"../core/geometry":104,"../lib/three":151}],146:[function(_dereq_,module,exports){
  52956. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  52957. var THREE = _dereq_('../lib/three');
  52958. var degToRad = THREE.Math.degToRad;
  52959. registerGeometry('torus', {
  52960. schema: {
  52961. arc: {default: 360},
  52962. radius: {default: 1, min: 0},
  52963. radiusTubular: {default: 0.2, min: 0},
  52964. segmentsRadial: {default: 36, min: 2, type: 'int'},
  52965. segmentsTubular: {default: 32, min: 3, type: 'int'}
  52966. },
  52967. init: function (data) {
  52968. this.geometry = new THREE.TorusGeometry(
  52969. data.radius, data.radiusTubular * 2, data.segmentsRadial, data.segmentsTubular,
  52970. degToRad(data.arc));
  52971. }
  52972. });
  52973. },{"../core/geometry":104,"../lib/three":151}],147:[function(_dereq_,module,exports){
  52974. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  52975. var THREE = _dereq_('../lib/three');
  52976. registerGeometry('torusKnot', {
  52977. schema: {
  52978. p: {default: 2, min: 1},
  52979. q: {default: 3, min: 1},
  52980. radius: {default: 1, min: 0},
  52981. radiusTubular: {default: 0.2, min: 0},
  52982. segmentsRadial: {default: 8, min: 3, type: 'int'},
  52983. segmentsTubular: {default: 100, min: 3, type: 'int'}
  52984. },
  52985. init: function (data) {
  52986. this.geometry = new THREE.TorusKnotGeometry(
  52987. data.radius, data.radiusTubular * 2, data.segmentsTubular, data.segmentsRadial,
  52988. data.p, data.q);
  52989. }
  52990. });
  52991. },{"../core/geometry":104,"../lib/three":151}],148:[function(_dereq_,module,exports){
  52992. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  52993. var THREE = _dereq_('../lib/three');
  52994. var quaternion = new THREE.Quaternion();
  52995. var rotateVector = new THREE.Vector3(0, 0, 1);
  52996. var uvMinVector = new THREE.Vector2();
  52997. var uvMaxVector = new THREE.Vector2();
  52998. var uvScaleVector = new THREE.Vector2();
  52999. registerGeometry('triangle', {
  53000. schema: {
  53001. vertexA: {type: 'vec3', default: {x: 0, y: 0.5, z: 0}},
  53002. vertexB: {type: 'vec3', default: {x: -0.5, y: -0.5, z: 0}},
  53003. vertexC: {type: 'vec3', default: {x: 0.5, y: -0.5, z: 0}}
  53004. },
  53005. init: function (data) {
  53006. var geometry;
  53007. var normal;
  53008. var triangle;
  53009. var uvA;
  53010. var uvB;
  53011. var uvC;
  53012. triangle = new THREE.Triangle();
  53013. triangle.a.set(data.vertexA.x, data.vertexA.y, data.vertexA.z);
  53014. triangle.b.set(data.vertexB.x, data.vertexB.y, data.vertexB.z);
  53015. triangle.c.set(data.vertexC.x, data.vertexC.y, data.vertexC.z);
  53016. normal = triangle.getNormal(new THREE.Vector3());
  53017. // Rotate the 3D triangle to be parallel to XY plane.
  53018. quaternion.setFromUnitVectors(normal, rotateVector);
  53019. uvA = triangle.a.clone().applyQuaternion(quaternion);
  53020. uvB = triangle.b.clone().applyQuaternion(quaternion);
  53021. uvC = triangle.c.clone().applyQuaternion(quaternion);
  53022. // Compute UVs.
  53023. // Normalize x/y values of UV so they are within 0 to 1.
  53024. uvMinVector.set(Math.min(uvA.x, uvB.x, uvC.x), Math.min(uvA.y, uvB.y, uvC.y));
  53025. uvMaxVector.set(Math.max(uvA.x, uvB.x, uvC.x), Math.max(uvA.y, uvB.y, uvC.y));
  53026. uvScaleVector.set(0, 0).subVectors(uvMaxVector, uvMinVector);
  53027. uvA = new THREE.Vector2().subVectors(uvA, uvMinVector).divide(uvScaleVector);
  53028. uvB = new THREE.Vector2().subVectors(uvB, uvMinVector).divide(uvScaleVector);
  53029. uvC = new THREE.Vector2().subVectors(uvC, uvMinVector).divide(uvScaleVector);
  53030. geometry = this.geometry = new THREE.Geometry();
  53031. geometry.vertices.push(triangle.a);
  53032. geometry.vertices.push(triangle.b);
  53033. geometry.vertices.push(triangle.c);
  53034. geometry.faces.push(new THREE.Face3(0, 1, 2, normal));
  53035. geometry.faceVertexUvs[0] = [[uvA, uvB, uvC]];
  53036. }
  53037. });
  53038. },{"../core/geometry":104,"../lib/three":151}],149:[function(_dereq_,module,exports){
  53039. // Polyfill `Promise`.
  53040. window.Promise = window.Promise || _dereq_('promise-polyfill');
  53041. // WebVR polyfill
  53042. // Check before the polyfill runs.
  53043. window.hasNativeWebVRImplementation = !!window.navigator.getVRDisplays ||
  53044. !!window.navigator.getVRDevices;
  53045. window.hasNativeWebXRImplementation = navigator.xr !== undefined;
  53046. // If native WebXR or WebVR are defined WebVRPolyfill does not initialize.
  53047. if (!window.hasNativeWebXRImplementation && !window.hasNativeWebVRImplementation) {
  53048. var isIOSOlderThan10 = _dereq_('./utils/isIOSOlderThan10');
  53049. // Workaround for iOS Safari canvas sizing issues in stereo (webvr-polyfill/issues/102).
  53050. // Only for iOS on versions older than 10.
  53051. var bufferScale = isIOSOlderThan10(window.navigator.userAgent) ? 1 / window.devicePixelRatio : 1;
  53052. var WebVRPolyfill = _dereq_('webvr-polyfill');
  53053. var polyfillConfig = {
  53054. BUFFER_SCALE: bufferScale,
  53055. CARDBOARD_UI_DISABLED: true,
  53056. ROTATE_INSTRUCTIONS_DISABLED: true
  53057. };
  53058. window.webvrpolyfill = new WebVRPolyfill(polyfillConfig);
  53059. }
  53060. var utils = _dereq_('./utils/');
  53061. var debug = utils.debug;
  53062. if (utils.isIE11) {
  53063. // Polyfill `CustomEvent`.
  53064. _dereq_('custom-event-polyfill');
  53065. // Polyfill String.startsWith.
  53066. _dereq_('../vendor/starts-with-polyfill');
  53067. }
  53068. var error = debug('A-Frame:error');
  53069. var warn = debug('A-Frame:warn');
  53070. if (window.document.currentScript && window.document.currentScript.parentNode !==
  53071. window.document.head && !window.debug) {
  53072. warn('Put the A-Frame <script> tag in the <head> of the HTML *before* the scene to ' +
  53073. 'ensure everything for A-Frame is properly registered before they are used from ' +
  53074. 'HTML.');
  53075. }
  53076. // Error if not using a server.
  53077. if (window.location.protocol === 'file:') {
  53078. error(
  53079. 'This HTML file is currently being served via the file:// protocol. ' +
  53080. 'Assets, textures, and models WILL NOT WORK due to cross-origin policy! ' +
  53081. 'Please use a local or hosted server: ' +
  53082. 'https://aframe.io/docs/0.5.0/introduction/getting-started.html#using-a-local-server.');
  53083. }
  53084. _dereq_('present'); // Polyfill `performance.now()`.
  53085. // CSS.
  53086. if (utils.device.isBrowserEnvironment) {
  53087. _dereq_('./style/aframe.css');
  53088. _dereq_('./style/rStats.css');
  53089. }
  53090. // Required before `AEntity` so that all components are registered.
  53091. var AScene = _dereq_('./core/scene/a-scene').AScene;
  53092. var components = _dereq_('./core/component').components;
  53093. var registerComponent = _dereq_('./core/component').registerComponent;
  53094. var registerGeometry = _dereq_('./core/geometry').registerGeometry;
  53095. var registerPrimitive = _dereq_('./extras/primitives/primitives').registerPrimitive;
  53096. var registerShader = _dereq_('./core/shader').registerShader;
  53097. var registerSystem = _dereq_('./core/system').registerSystem;
  53098. var shaders = _dereq_('./core/shader').shaders;
  53099. var systems = _dereq_('./core/system').systems;
  53100. // Exports THREE to window so three.js can be used without alteration.
  53101. var THREE = window.THREE = _dereq_('./lib/three');
  53102. var pkg = _dereq_('../package');
  53103. _dereq_('./components/index'); // Register standard components.
  53104. _dereq_('./geometries/index'); // Register standard geometries.
  53105. _dereq_('./shaders/index'); // Register standard shaders.
  53106. _dereq_('./systems/index'); // Register standard systems.
  53107. var ANode = _dereq_('./core/a-node');
  53108. var AEntity = _dereq_('./core/a-entity'); // Depends on ANode and core components.
  53109. _dereq_('./core/a-assets');
  53110. _dereq_('./core/a-cubemap');
  53111. _dereq_('./core/a-mixin');
  53112. // Extras.
  53113. _dereq_('./extras/components/');
  53114. _dereq_('./extras/primitives/');
  53115. console.log('A-Frame Version: 0.9.2 (Date 2019-05-06, Commit #f57a1fa)');
  53116. console.log('three Version (https://github.com/supermedium/three.js):',
  53117. pkg.dependencies['super-three']);
  53118. console.log('WebVR Polyfill Version:', pkg.dependencies['webvr-polyfill']);
  53119. module.exports = window.AFRAME = {
  53120. AComponent: _dereq_('./core/component').Component,
  53121. AEntity: AEntity,
  53122. ANode: ANode,
  53123. ANIME: _dereq_('super-animejs'),
  53124. AScene: AScene,
  53125. components: components,
  53126. coreComponents: Object.keys(components),
  53127. geometries: _dereq_('./core/geometry').geometries,
  53128. registerComponent: registerComponent,
  53129. registerElement: _dereq_('./core/a-register-element').registerElement,
  53130. registerGeometry: registerGeometry,
  53131. registerPrimitive: registerPrimitive,
  53132. registerShader: registerShader,
  53133. registerSystem: registerSystem,
  53134. primitives: {
  53135. getMeshMixin: _dereq_('./extras/primitives/getMeshMixin'),
  53136. primitives: _dereq_('./extras/primitives/primitives').primitives
  53137. },
  53138. scenes: _dereq_('./core/scene/scenes'),
  53139. schema: _dereq_('./core/schema'),
  53140. shaders: shaders,
  53141. systems: systems,
  53142. THREE: THREE,
  53143. utils: utils,
  53144. version: pkg.version
  53145. };
  53146. },{"../package":51,"../vendor/starts-with-polyfill":187,"./components/index":60,"./core/a-assets":97,"./core/a-cubemap":98,"./core/a-entity":99,"./core/a-mixin":100,"./core/a-node":101,"./core/a-register-element":102,"./core/component":103,"./core/geometry":104,"./core/scene/a-scene":106,"./core/scene/scenes":110,"./core/schema":112,"./core/shader":113,"./core/system":114,"./extras/components/":115,"./extras/primitives/":118,"./extras/primitives/getMeshMixin":117,"./extras/primitives/primitives":119,"./geometries/index":140,"./lib/three":151,"./shaders/index":153,"./style/aframe.css":158,"./style/rStats.css":159,"./systems/index":163,"./utils/":176,"./utils/isIOSOlderThan10":178,"custom-event-polyfill":7,"present":31,"promise-polyfill":33,"super-animejs":35,"webvr-polyfill":46}],150:[function(_dereq_,module,exports){
  53147. window.aframeStats = function (scene) {
  53148. var _rS = null;
  53149. var _scene = scene;
  53150. var _values = {
  53151. te: {
  53152. caption: 'Entities'
  53153. },
  53154. lt: {
  53155. caption: 'Load Time'
  53156. }
  53157. };
  53158. var _groups = [ {
  53159. caption: 'A-Frame',
  53160. values: [ 'te', 'lt' ]
  53161. } ];
  53162. function _update () {
  53163. _rS('te').set(getEntityCount());
  53164. if (window.performance.getEntriesByName) {
  53165. _rS('lt').set(window.performance.getEntriesByName('render-started')[0].startTime.toFixed(0));
  53166. }
  53167. }
  53168. function getEntityCount () {
  53169. var elements = _scene.querySelectorAll('*');
  53170. Array.prototype.slice.call(elements).filter(function (el) {
  53171. return el.isEntity;
  53172. });
  53173. return elements.length;
  53174. }
  53175. function _start () {}
  53176. function _end () {}
  53177. function _attach (r) {
  53178. _rS = r;
  53179. }
  53180. return {
  53181. update: _update,
  53182. start: _start,
  53183. end: _end,
  53184. attach: _attach,
  53185. values: _values,
  53186. groups: _groups,
  53187. fractions: []
  53188. };
  53189. };
  53190. if (typeof module === 'object') {
  53191. module.exports = {
  53192. aframeStats: window.aframeStats
  53193. };
  53194. }
  53195. },{}],151:[function(_dereq_,module,exports){
  53196. (function (global){
  53197. var THREE = global.THREE = _dereq_('super-three');
  53198. // Allow cross-origin images to be loaded.
  53199. // This should not be on `THREE.Loader` nor `THREE.ImageUtils`.
  53200. // Must be on `THREE.TextureLoader`.
  53201. if (THREE.TextureLoader) {
  53202. THREE.TextureLoader.prototype.crossOrigin = 'anonymous';
  53203. }
  53204. // This is for images loaded from the model loaders.
  53205. if (THREE.ImageLoader) {
  53206. THREE.ImageLoader.prototype.crossOrigin = 'anonymous';
  53207. }
  53208. // In-memory caching for XHRs (for images, audio files, textures, etc.).
  53209. if (THREE.Cache) {
  53210. THREE.Cache.enabled = true;
  53211. }
  53212. // TODO: Eventually include these only if they are needed by a component.
  53213. _dereq_('super-three/examples/js/loaders/DRACOLoader'); // THREE.DRACOLoader
  53214. _dereq_('super-three/examples/js/loaders/GLTFLoader'); // THREE.GLTFLoader
  53215. _dereq_('super-three/examples/js/loaders/OBJLoader'); // THREE.OBJLoader
  53216. _dereq_('super-three/examples/js/loaders/MTLLoader'); // THREE.MTLLoader
  53217. THREE.DRACOLoader.prototype.crossOrigin = 'anonymous';
  53218. THREE.GLTFLoader.prototype.crossOrigin = 'anonymous';
  53219. THREE.MTLLoader.prototype.crossOrigin = 'anonymous';
  53220. THREE.OBJLoader.prototype.crossOrigin = 'anonymous';
  53221. module.exports = THREE;
  53222. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  53223. },{"super-three":36,"super-three/examples/js/loaders/DRACOLoader":37,"super-three/examples/js/loaders/GLTFLoader":38,"super-three/examples/js/loaders/MTLLoader":39,"super-three/examples/js/loaders/OBJLoader":40}],152:[function(_dereq_,module,exports){
  53224. var registerShader = _dereq_('../core/shader').registerShader;
  53225. var THREE = _dereq_('../lib/three');
  53226. var utils = _dereq_('../utils/');
  53227. /**
  53228. * Flat shader using THREE.MeshBasicMaterial.
  53229. */
  53230. module.exports.Shader = registerShader('flat', {
  53231. schema: {
  53232. color: {type: 'color'},
  53233. fog: {default: true},
  53234. height: {default: 256},
  53235. offset: {type: 'vec2', default: {x: 0, y: 0}},
  53236. repeat: {type: 'vec2', default: {x: 1, y: 1}},
  53237. src: {type: 'map'},
  53238. width: {default: 512},
  53239. wireframe: {default: false},
  53240. wireframeLinewidth: {default: 2}
  53241. },
  53242. /**
  53243. * Initializes the shader.
  53244. * Adds a reference from the scene to this entity as the camera.
  53245. */
  53246. init: function (data) {
  53247. this.rendererSystem = this.el.sceneEl.systems.renderer;
  53248. this.materialData = {color: new THREE.Color()};
  53249. this.textureSrc = null;
  53250. getMaterialData(data, this.materialData);
  53251. this.rendererSystem.applyColorCorrection(this.materialData.color);
  53252. this.material = new THREE.MeshBasicMaterial(this.materialData);
  53253. utils.material.updateMap(this, data);
  53254. },
  53255. update: function (data) {
  53256. this.updateMaterial(data);
  53257. utils.material.updateMap(this, data);
  53258. },
  53259. /**
  53260. * Updating existing material.
  53261. *
  53262. * @param {object} data - Material component data.
  53263. */
  53264. updateMaterial: function (data) {
  53265. var key;
  53266. getMaterialData(data, this.materialData);
  53267. this.rendererSystem.applyColorCorrection(this.materialData.color);
  53268. for (key in this.materialData) {
  53269. this.material[key] = this.materialData[key];
  53270. }
  53271. }
  53272. });
  53273. /**
  53274. * Builds and normalize material data, normalizing stuff along the way.
  53275. *
  53276. * @param {object} data - Material data.
  53277. * @param {object} materialData - Object to reuse.
  53278. * @returns {object} Updated material data.
  53279. */
  53280. function getMaterialData (data, materialData) {
  53281. materialData.color.set(data.color);
  53282. materialData.fog = data.fog;
  53283. materialData.wireframe = data.wireframe;
  53284. materialData.wireframeLinewidth = data.wireframeLinewidth;
  53285. return materialData;
  53286. }
  53287. },{"../core/shader":113,"../lib/three":151,"../utils/":176}],153:[function(_dereq_,module,exports){
  53288. _dereq_('./flat');
  53289. _dereq_('./standard');
  53290. _dereq_('./sdf');
  53291. _dereq_('./msdf');
  53292. _dereq_('./ios10hls');
  53293. },{"./flat":152,"./ios10hls":154,"./msdf":155,"./sdf":156,"./standard":157}],154:[function(_dereq_,module,exports){
  53294. var registerShader = _dereq_('../core/shader').registerShader;
  53295. /**
  53296. * Custom shader for iOS 10 HTTP Live Streaming (HLS).
  53297. * For more information on HLS, see https://datatracker.ietf.org/doc/draft-pantos-http-live-streaming/
  53298. */
  53299. module.exports.Shader = registerShader('ios10hls', {
  53300. schema: {
  53301. src: {type: 'map', is: 'uniform'},
  53302. opacity: {type: 'number', is: 'uniform', default: 1}
  53303. },
  53304. vertexShader: [
  53305. 'varying vec2 vUV;',
  53306. 'void main(void) {',
  53307. ' gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);',
  53308. ' vUV = uv;',
  53309. '}'
  53310. ].join('\n'),
  53311. fragmentShader: [
  53312. 'uniform sampler2D src;',
  53313. 'uniform float opacity;',
  53314. 'varying vec2 vUV;',
  53315. 'void main() {',
  53316. ' vec2 offset = vec2(0, 0);',
  53317. ' vec2 repeat = vec2(1, 1);',
  53318. ' vec4 color = texture2D(src, vec2(vUV.x / repeat.x + offset.x, (1.0 - vUV.y) / repeat.y + offset.y)).bgra;',
  53319. ' gl_FragColor = vec4(color.rgb, opacity);',
  53320. '}'
  53321. ].join('\n')
  53322. });
  53323. },{"../core/shader":113}],155:[function(_dereq_,module,exports){
  53324. var registerShader = _dereq_('../core/shader').registerShader;
  53325. /**
  53326. * Multi-channel signed distance field.
  53327. * Used by text component.
  53328. */
  53329. module.exports.Shader = registerShader('msdf', {
  53330. schema: {
  53331. alphaTest: {type: 'number', is: 'uniform', default: 0.5},
  53332. color: {type: 'color', is: 'uniform', default: 'white'},
  53333. map: {type: 'map', is: 'uniform'},
  53334. negate: {type: 'boolean', is: 'uniform', default: true},
  53335. opacity: {type: 'number', is: 'uniform', default: 1.0}
  53336. },
  53337. raw: true,
  53338. vertexShader: [
  53339. 'attribute vec2 uv;',
  53340. 'attribute vec3 position;',
  53341. 'uniform mat4 projectionMatrix;',
  53342. 'uniform mat4 modelViewMatrix;',
  53343. 'varying vec2 vUV;',
  53344. 'void main(void) {',
  53345. ' gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);',
  53346. ' vUV = uv;',
  53347. '}'
  53348. ].join('\n'),
  53349. fragmentShader: [
  53350. '#ifdef GL_OES_standard_derivatives',
  53351. '#extension GL_OES_standard_derivatives: enable',
  53352. '#endif',
  53353. 'precision highp float;',
  53354. 'uniform bool negate;',
  53355. 'uniform float alphaTest;',
  53356. 'uniform float opacity;',
  53357. 'uniform sampler2D map;',
  53358. 'uniform vec3 color;',
  53359. 'varying vec2 vUV;',
  53360. 'float median(float r, float g, float b) {',
  53361. ' return max(min(r, g), min(max(r, g), b));',
  53362. '}',
  53363. // FIXME: Experimentally determined constants.
  53364. '#define BIG_ENOUGH 0.001',
  53365. '#define MODIFIED_ALPHATEST (0.02 * isBigEnough / BIG_ENOUGH)',
  53366. 'void main() {',
  53367. ' vec3 sample = texture2D(map, vUV).rgb;',
  53368. ' if (negate) { sample = 1.0 - sample; }',
  53369. ' float sigDist = median(sample.r, sample.g, sample.b) - 0.5;',
  53370. ' float alpha = clamp(sigDist / fwidth(sigDist) + 0.5, 0.0, 1.0);',
  53371. ' float dscale = 0.353505;',
  53372. ' vec2 duv = dscale * (dFdx(vUV) + dFdy(vUV));',
  53373. ' float isBigEnough = max(abs(duv.x), abs(duv.y));',
  53374. // When texel is too small, blend raw alpha value rather than supersampling.
  53375. // FIXME: Experimentally determined constant.
  53376. ' // Do modified alpha test.',
  53377. ' if (isBigEnough > BIG_ENOUGH) {',
  53378. ' float ratio = BIG_ENOUGH / isBigEnough;',
  53379. ' alpha = ratio * alpha + (1.0 - ratio) * (sigDist + 0.5);',
  53380. ' }',
  53381. ' // Do modified alpha test.',
  53382. ' if (alpha < alphaTest * MODIFIED_ALPHATEST) { discard; return; }',
  53383. ' gl_FragColor = vec4(color.xyz, alpha * opacity);',
  53384. '}'
  53385. ].join('\n')
  53386. });
  53387. },{"../core/shader":113}],156:[function(_dereq_,module,exports){
  53388. var registerShader = _dereq_('../core/shader').registerShader;
  53389. /**
  53390. * Signed distance field.
  53391. * Used by text component.
  53392. */
  53393. module.exports.Shader = registerShader('sdf', {
  53394. schema: {
  53395. alphaTest: {type: 'number', is: 'uniform', default: 0.5},
  53396. color: {type: 'color', is: 'uniform', default: 'white'},
  53397. map: {type: 'map', is: 'uniform'},
  53398. opacity: {type: 'number', is: 'uniform', default: 1.0}
  53399. },
  53400. raw: true,
  53401. vertexShader: [
  53402. 'attribute vec2 uv;',
  53403. 'attribute vec3 position;',
  53404. 'uniform mat4 projectionMatrix;',
  53405. 'uniform mat4 modelViewMatrix;',
  53406. 'varying vec2 vUV;',
  53407. 'void main(void) {',
  53408. ' gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);',
  53409. ' vUV = uv;',
  53410. '}'
  53411. ].join('\n'),
  53412. fragmentShader: [
  53413. '#ifdef GL_OES_standard_derivatives',
  53414. '#extension GL_OES_standard_derivatives: enable',
  53415. '#endif',
  53416. 'precision highp float;',
  53417. 'uniform float alphaTest;',
  53418. 'uniform float opacity;',
  53419. 'uniform sampler2D map;',
  53420. 'uniform vec3 color;',
  53421. 'varying vec2 vUV;',
  53422. '#ifdef GL_OES_standard_derivatives',
  53423. ' float contour(float width, float value) {',
  53424. ' return smoothstep(0.5 - value, 0.5 + value, width);',
  53425. ' }',
  53426. '#else',
  53427. ' float aastep(float value, float afwidth) {',
  53428. ' return smoothstep(0.5 - afwidth, 0.5 + afwidth, value);',
  53429. ' }',
  53430. '#endif',
  53431. // FIXME: Experimentally determined constants.
  53432. '#define BIG_ENOUGH 0.001',
  53433. '#define MODIFIED_ALPHATEST (0.02 * isBigEnough / BIG_ENOUGH)',
  53434. '#define ALL_SMOOTH 0.4',
  53435. '#define ALL_ROUGH 0.02',
  53436. '#define DISCARD_ALPHA (alphaTest / (2.2 - 1.2 * ratio))',
  53437. 'void main() {',
  53438. // When we have derivatives and can get texel size for supersampling.
  53439. ' #ifdef GL_OES_standard_derivatives',
  53440. ' vec2 uv = vUV;',
  53441. ' vec4 texColor = texture2D(map, uv);',
  53442. ' float dist = texColor.a;',
  53443. ' float width = fwidth(dist);',
  53444. ' float alpha = contour(dist, width);',
  53445. ' float dscale = 0.353505;',
  53446. ' vec2 duv = dscale * (dFdx(uv) + dFdy(uv));',
  53447. ' float isBigEnough = max(abs(duv.x), abs(duv.y));',
  53448. // When texel is too small, blend raw alpha value rather than supersampling.
  53449. // FIXME: experimentally determined constant
  53450. ' if (isBigEnough > BIG_ENOUGH) {',
  53451. ' float ratio = BIG_ENOUGH / isBigEnough;',
  53452. ' alpha = ratio * alpha + (1.0 - ratio) * dist;',
  53453. ' }',
  53454. // Otherwise do weighted supersampling.
  53455. // FIXME: why this weighting?
  53456. ' if (isBigEnough <= BIG_ENOUGH) {',
  53457. ' vec4 box = vec4 (uv - duv, uv + duv);',
  53458. ' alpha = (alpha + 0.5 * (',
  53459. ' contour(texture2D(map, box.xy).a, width)',
  53460. ' + contour(texture2D(map, box.zw).a, width)',
  53461. ' + contour(texture2D(map, box.xw).a, width)',
  53462. ' + contour(texture2D(map, box.zy).a, width)',
  53463. ' )) / 3.0;',
  53464. ' }',
  53465. // Do modified alpha test.
  53466. ' if (alpha < alphaTest * MODIFIED_ALPHATEST) { discard; return; }',
  53467. ' #else',
  53468. // When we don't have derivatives, use approximations.
  53469. ' vec4 texColor = texture2D(map, vUV);',
  53470. ' float value = texColor.a;',
  53471. // FIXME: if we understood font pixel dimensions, this could probably be improved
  53472. ' float afwidth = (1.0 / 32.0) * (1.4142135623730951 / (2.0 * gl_FragCoord.w));',
  53473. ' float alpha = aastep(value, afwidth);',
  53474. // Use gl_FragCoord.w to guess when we should blend.
  53475. // FIXME: If we understood font pixel dimensions, this could probably be improved.
  53476. ' 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);',
  53477. ' if (alpha < alphaTest) { if (ratio >= 1.0) { discard; return; } alpha = 0.0; }',
  53478. ' alpha = alpha * ratio + (1.0 - ratio) * value;',
  53479. ' if (ratio < 1.0 && alpha <= DISCARD_ALPHA) { discard; return; }',
  53480. ' #endif',
  53481. ' gl_FragColor = vec4(color, opacity * alpha);',
  53482. '}'
  53483. ].join('\n')
  53484. });
  53485. },{"../core/shader":113}],157:[function(_dereq_,module,exports){
  53486. var registerShader = _dereq_('../core/shader').registerShader;
  53487. var THREE = _dereq_('../lib/three');
  53488. var utils = _dereq_('../utils/');
  53489. var CubeLoader = new THREE.CubeTextureLoader();
  53490. var texturePromises = {};
  53491. /**
  53492. * Standard (physically-based) shader using THREE.MeshStandardMaterial.
  53493. */
  53494. module.exports.Shader = registerShader('standard', {
  53495. schema: {
  53496. ambientOcclusionMap: {type: 'map'},
  53497. ambientOcclusionMapIntensity: {default: 1},
  53498. ambientOcclusionTextureOffset: {type: 'vec2'},
  53499. ambientOcclusionTextureRepeat: {type: 'vec2', default: {x: 1, y: 1}},
  53500. color: {type: 'color'},
  53501. displacementMap: {type: 'map'},
  53502. displacementScale: {default: 1},
  53503. displacementBias: {default: 0.5},
  53504. displacementTextureOffset: {type: 'vec2'},
  53505. displacementTextureRepeat: {type: 'vec2', default: {x: 1, y: 1}},
  53506. emissive: {type: 'color', default: '#000'},
  53507. emissiveIntensity: {default: 1},
  53508. envMap: {default: ''},
  53509. fog: {default: true},
  53510. height: {default: 256},
  53511. metalness: {default: 0.0, min: 0.0, max: 1.0},
  53512. metalnessMap: {type: 'map'},
  53513. metalnessTextureOffset: {type: 'vec2'},
  53514. metalnessTextureRepeat: {type: 'vec2', default: {x: 1, y: 1}},
  53515. normalMap: {type: 'map'},
  53516. normalScale: {type: 'vec2', default: {x: 1, y: 1}},
  53517. normalTextureOffset: {type: 'vec2'},
  53518. normalTextureRepeat: {type: 'vec2', default: {x: 1, y: 1}},
  53519. offset: {type: 'vec2', default: {x: 0, y: 0}},
  53520. repeat: {type: 'vec2', default: {x: 1, y: 1}},
  53521. roughness: {default: 0.5, min: 0.0, max: 1.0},
  53522. roughnessMap: {type: 'map'},
  53523. roughnessTextureOffset: {type: 'vec2'},
  53524. roughnessTextureRepeat: {type: 'vec2', default: {x: 1, y: 1}},
  53525. sphericalEnvMap: {type: 'map'},
  53526. src: {type: 'map'},
  53527. width: {default: 512},
  53528. wireframe: {default: false},
  53529. wireframeLinewidth: {default: 2}
  53530. },
  53531. /**
  53532. * Initializes the shader.
  53533. * Adds a reference from the scene to this entity as the camera.
  53534. */
  53535. init: function (data) {
  53536. this.rendererSystem = this.el.sceneEl.systems.renderer;
  53537. this.materialData = {color: new THREE.Color(), emissive: new THREE.Color()};
  53538. getMaterialData(data, this.materialData);
  53539. this.rendererSystem.applyColorCorrection(this.materialData.color);
  53540. this.rendererSystem.applyColorCorrection(this.materialData.emissive);
  53541. this.material = new THREE.MeshStandardMaterial(this.materialData);
  53542. utils.material.updateMap(this, data);
  53543. if (data.normalMap) { utils.material.updateDistortionMap('normal', this, data); }
  53544. if (data.displacementMap) { utils.material.updateDistortionMap('displacement', this, data); }
  53545. if (data.ambientOcclusionMap) { utils.material.updateDistortionMap('ambientOcclusion', this, data); }
  53546. if (data.metalnessMap) { utils.material.updateDistortionMap('metalness', this, data); }
  53547. if (data.roughnessMap) { utils.material.updateDistortionMap('roughness', this, data); }
  53548. this.updateEnvMap(data);
  53549. },
  53550. update: function (data) {
  53551. this.updateMaterial(data);
  53552. utils.material.updateMap(this, data);
  53553. if (data.normalMap) { utils.material.updateDistortionMap('normal', this, data); }
  53554. if (data.displacementMap) { utils.material.updateDistortionMap('displacement', this, data); }
  53555. if (data.ambientOcclusionMap) { utils.material.updateDistortionMap('ambientOcclusion', this, data); }
  53556. if (data.metalnessMap) { utils.material.updateDistortionMap('metalness', this, data); }
  53557. if (data.roughnessMap) { utils.material.updateDistortionMap('roughness', this, data); }
  53558. this.updateEnvMap(data);
  53559. },
  53560. /**
  53561. * Updating existing material.
  53562. *
  53563. * @param {object} data - Material component data.
  53564. * @returns {object} Material.
  53565. */
  53566. updateMaterial: function (data) {
  53567. var key;
  53568. var material = this.material;
  53569. getMaterialData(data, this.materialData);
  53570. this.rendererSystem.applyColorCorrection(this.materialData.color);
  53571. this.rendererSystem.applyColorCorrection(this.materialData.emissive);
  53572. for (key in this.materialData) {
  53573. material[key] = this.materialData[key];
  53574. }
  53575. },
  53576. /**
  53577. * Handle environment cubemap. Textures are cached in texturePromises.
  53578. */
  53579. updateEnvMap: function (data) {
  53580. var self = this;
  53581. var material = this.material;
  53582. var envMap = data.envMap;
  53583. var sphericalEnvMap = data.sphericalEnvMap;
  53584. // No envMap defined or already loading.
  53585. if ((!envMap && !sphericalEnvMap) || this.isLoadingEnvMap) {
  53586. material.envMap = null;
  53587. material.needsUpdate = true;
  53588. return;
  53589. }
  53590. this.isLoadingEnvMap = true;
  53591. // if a spherical env map is defined then use it.
  53592. if (sphericalEnvMap) {
  53593. this.el.sceneEl.systems.material.loadTexture(sphericalEnvMap, {src: sphericalEnvMap}, function textureLoaded (texture) {
  53594. self.isLoadingEnvMap = false;
  53595. texture.mapping = THREE.SphericalReflectionMapping;
  53596. material.envMap = texture;
  53597. utils.material.handleTextureEvents(self.el, texture);
  53598. material.needsUpdate = true;
  53599. });
  53600. return;
  53601. }
  53602. // Another material is already loading this texture. Wait on promise.
  53603. if (texturePromises[envMap]) {
  53604. texturePromises[envMap].then(function (cube) {
  53605. self.isLoadingEnvMap = false;
  53606. material.envMap = cube;
  53607. utils.material.handleTextureEvents(self.el, cube);
  53608. material.needsUpdate = true;
  53609. });
  53610. return;
  53611. }
  53612. // Material is first to load this texture. Load and resolve texture.
  53613. texturePromises[envMap] = new Promise(function (resolve) {
  53614. utils.srcLoader.validateCubemapSrc(envMap, function loadEnvMap (urls) {
  53615. CubeLoader.load(urls, function (cube) {
  53616. // Texture loaded.
  53617. self.isLoadingEnvMap = false;
  53618. material.envMap = cube;
  53619. utils.material.handleTextureEvents(self.el, cube);
  53620. resolve(cube);
  53621. });
  53622. });
  53623. });
  53624. }
  53625. });
  53626. /**
  53627. * Builds and normalize material data, normalizing stuff along the way.
  53628. *
  53629. * @param {object} data - Material data.
  53630. * @param {object} materialData - Object to use.
  53631. * @returns {object} Updated materialData.
  53632. */
  53633. function getMaterialData (data, materialData) {
  53634. materialData.color.set(data.color);
  53635. materialData.emissive.set(data.emissive);
  53636. materialData.emissiveIntensity = data.emissiveIntensity;
  53637. materialData.fog = data.fog;
  53638. materialData.metalness = data.metalness;
  53639. materialData.roughness = data.roughness;
  53640. materialData.wireframe = data.wireframe;
  53641. materialData.wireframeLinewidth = data.wireframeLinewidth;
  53642. if (data.normalMap) { materialData.normalScale = data.normalScale; }
  53643. if (data.ambientOcclusionMap) {
  53644. materialData.aoMapIntensity = data.ambientOcclusionMapIntensity;
  53645. }
  53646. if (data.displacementMap) {
  53647. materialData.displacementScale = data.displacementScale;
  53648. materialData.displacementBias = data.displacementBias;
  53649. }
  53650. return materialData;
  53651. }
  53652. },{"../core/shader":113,"../lib/three":151,"../utils/":176}],158:[function(_dereq_,module,exports){
  53653. 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-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-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-vr-button,.a-enter-vr-modal,.a-enter-vr-modal a{color:#fff}.a-enter-vr-button{background:url(data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%20245.82%20141.73%22%3E%3Cdefs%3E%3Cstyle%3E.a%7Bfill%3A%23fff%3Bfill-rule%3Aevenodd%3B%7D%3C%2Fstyle%3E%3C%2Fdefs%3E%3Ctitle%3Emask%3C%2Ftitle%3E%3Cpath%20class%3D%22a%22%20d%3D%22M175.56%2C111.37c-22.52%2C0-40.77-18.84-40.77-42.07S153%2C27.24%2C175.56%2C27.24s40.77%2C18.84%2C40.77%2C42.07S198.08%2C111.37%2C175.56%2C111.37ZM26.84%2C69.31c0-23.23%2C18.25-42.07%2C40.77-42.07s40.77%2C18.84%2C40.77%2C42.07-18.26%2C42.07-40.77%2C42.07S26.84%2C92.54%2C26.84%2C69.31ZM27.27%2C0C11.54%2C0%2C0%2C12.34%2C0%2C28.58V110.9c0%2C16.24%2C11.54%2C30.83%2C27.27%2C30.83H99.57c2.17%2C0%2C4.19-1.83%2C5.4-3.7L116.47%2C118a8%2C8%2C0%2C0%2C1%2C12.52-.18l11.51%2C20.34c1.2%2C1.86%2C3.22%2C3.61%2C5.39%2C3.61h72.29c15.74%2C0%2C27.63-14.6%2C27.63-30.83V28.58C245.82%2C12.34%2C233.93%2C0%2C218.19%2C0H27.27Z%22%2F%3E%3C%2Fsvg%3E) 50% 50%/70% 70% no-repeat rgba(0,0,0,.35);border:0;bottom:0;cursor:pointer;min-width:50px;min-height:30px;padding-right:5%;padding-top:4%;position:absolute;right:0;transition:background-color .05s ease;-webkit-transition:background-color .05s ease;z-index:9999}.a-enter-vr-button:active,.a-enter-vr-button:hover{background-color:#666}[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}"; (_dereq_("browserify-css").createStyle(css, { "href": "src/style/aframe.css"})); module.exports = css;
  53654. },{"browserify-css":4}],159:[function(_dereq_,module,exports){
  53655. 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;
  53656. },{"browserify-css":4}],160:[function(_dereq_,module,exports){
  53657. var constants = _dereq_('../constants/');
  53658. var registerSystem = _dereq_('../core/system').registerSystem;
  53659. var DEFAULT_CAMERA_ATTR = 'data-aframe-default-camera';
  53660. /**
  53661. * Camera system. Manages which camera is active among multiple cameras in scene.
  53662. *
  53663. * @member {object} activeCameraEl - Active camera entity.
  53664. */
  53665. module.exports.System = registerSystem('camera', {
  53666. init: function () {
  53667. this.activeCameraEl = null;
  53668. this.render = this.render.bind(this);
  53669. this.unwrapRender = this.unwrapRender.bind(this);
  53670. this.wrapRender = this.wrapRender.bind(this);
  53671. this.initialCameraFound = false;
  53672. this.numUserCameras = 0;
  53673. this.numUserCamerasChecked = 0;
  53674. this.setupInitialCamera();
  53675. },
  53676. /**
  53677. * Setup initial camera, either searching for camera or
  53678. * creating a default camera if user has not added one during the initial scene traversal.
  53679. * We want sceneEl.camera to be ready, set, and initialized before the rest of the scene
  53680. * loads.
  53681. *
  53682. * Default camera offset height is at average eye level (~1.6m).
  53683. */
  53684. setupInitialCamera: function () {
  53685. var cameraEls;
  53686. var i;
  53687. var sceneEl = this.sceneEl;
  53688. var self = this;
  53689. // Camera already defined or the one defined it is an spectator one.
  53690. if (sceneEl.camera && !sceneEl.camera.el.getAttribute('camera').spectator) {
  53691. sceneEl.emit('cameraready', {cameraEl: sceneEl.camera.el});
  53692. return;
  53693. }
  53694. // Search for initial user-defined camera.
  53695. cameraEls = sceneEl.querySelectorAll('a-camera, [camera]');
  53696. // No user cameras, create default one.
  53697. if (!cameraEls.length) {
  53698. this.createDefaultCamera();
  53699. return;
  53700. }
  53701. this.numUserCameras = cameraEls.length;
  53702. for (i = 0; i < cameraEls.length; i++) {
  53703. cameraEls[i].addEventListener('object3dset', function (evt) {
  53704. if (evt.detail.type !== 'camera') { return; }
  53705. self.checkUserCamera(this);
  53706. });
  53707. // Load camera and wait for camera to initialize.
  53708. if (cameraEls[i].isNode) {
  53709. cameraEls[i].load();
  53710. } else {
  53711. cameraEls[i].addEventListener('nodeready', function () {
  53712. this.load();
  53713. });
  53714. }
  53715. }
  53716. },
  53717. /**
  53718. * Check if a user-defined camera entity is appropriate to be initial camera.
  53719. * (active + non-spectator).
  53720. *
  53721. * Keep track of the number of cameras we checked and whether we found one.
  53722. */
  53723. checkUserCamera: function (cameraEl) {
  53724. var cameraData;
  53725. var sceneEl = this.el.sceneEl;
  53726. this.numUserCamerasChecked++;
  53727. // Already found one.
  53728. if (this.initialCameraFound) { return; }
  53729. // Check if camera is appropriate for being the initial camera.
  53730. cameraData = cameraEl.getAttribute('camera');
  53731. if (!cameraData.active || cameraData.spectator) {
  53732. // No user cameras eligible, create default camera.
  53733. if (this.numUserCamerasChecked === this.numUserCameras) {
  53734. this.createDefaultCamera();
  53735. }
  53736. return;
  53737. }
  53738. this.initialCameraFound = true;
  53739. sceneEl.camera = cameraEl.getObject3D('camera');
  53740. sceneEl.emit('cameraready', {cameraEl: cameraEl});
  53741. },
  53742. createDefaultCamera: function () {
  53743. var defaultCameraEl;
  53744. var sceneEl = this.sceneEl;
  53745. // Set up default camera.
  53746. defaultCameraEl = document.createElement('a-entity');
  53747. defaultCameraEl.setAttribute('camera', {active: true});
  53748. defaultCameraEl.setAttribute('position', {
  53749. x: 0,
  53750. y: constants.DEFAULT_CAMERA_HEIGHT,
  53751. z: 0
  53752. });
  53753. defaultCameraEl.setAttribute('wasd-controls', '');
  53754. defaultCameraEl.setAttribute('look-controls', '');
  53755. defaultCameraEl.setAttribute(constants.AFRAME_INJECTED, '');
  53756. defaultCameraEl.addEventListener('object3dset', function (evt) {
  53757. if (evt.detail.type !== 'camera') { return; }
  53758. sceneEl.camera = evt.detail.object;
  53759. sceneEl.emit('cameraready', {cameraEl: defaultCameraEl});
  53760. });
  53761. sceneEl.appendChild(defaultCameraEl);
  53762. },
  53763. /**
  53764. * Set a different active camera.
  53765. * When we choose a (sort of) random scene camera as the replacement, set its `active` to
  53766. * true. The camera component will call `setActiveCamera` and handle passing the torch to
  53767. * the new camera.
  53768. */
  53769. disableActiveCamera: function () {
  53770. var cameraEls;
  53771. var newActiveCameraEl;
  53772. cameraEls = this.sceneEl.querySelectorAll('[camera]');
  53773. newActiveCameraEl = cameraEls[cameraEls.length - 1];
  53774. newActiveCameraEl.setAttribute('camera', 'active', true);
  53775. },
  53776. /**
  53777. * Set active camera to be used by renderer.
  53778. * Removes the default camera (if present).
  53779. * Disables all other cameras in the scene.
  53780. *
  53781. * @param {Element} newCameraEl - Entity with camera component.
  53782. */
  53783. setActiveCamera: function (newCameraEl) {
  53784. var cameraEl;
  53785. var cameraEls;
  53786. var i;
  53787. var newCamera;
  53788. var previousCamera = this.activeCameraEl;
  53789. var sceneEl = this.sceneEl;
  53790. // Same camera.
  53791. newCamera = newCameraEl.getObject3D('camera');
  53792. if (!newCamera || newCameraEl === this.activeCameraEl) { return; }
  53793. // Grab the default camera.
  53794. var defaultCameraWrapper = sceneEl.querySelector('[' + DEFAULT_CAMERA_ATTR + ']');
  53795. var defaultCameraEl = defaultCameraWrapper &&
  53796. defaultCameraWrapper.querySelector('[camera]');
  53797. // Remove default camera if new camera is not the default camera.
  53798. if (newCameraEl !== defaultCameraEl) { removeDefaultCamera(sceneEl); }
  53799. // Make new camera active.
  53800. this.activeCameraEl = newCameraEl;
  53801. this.activeCameraEl.play();
  53802. sceneEl.camera = newCamera;
  53803. // Disable current camera
  53804. if (previousCamera) {
  53805. previousCamera.setAttribute('camera', 'active', false);
  53806. }
  53807. // Disable other cameras in the scene
  53808. cameraEls = sceneEl.querySelectorAll('[camera]');
  53809. for (i = 0; i < cameraEls.length; i++) {
  53810. cameraEl = cameraEls[i];
  53811. if (!cameraEl.isEntity || newCameraEl === cameraEl) { continue; }
  53812. cameraEl.setAttribute('camera', 'active', false);
  53813. cameraEl.pause();
  53814. }
  53815. sceneEl.emit('camera-set-active', {cameraEl: newCameraEl});
  53816. },
  53817. /**
  53818. * Set spectator camera to render the scene on a 2D display.
  53819. *
  53820. * @param {Element} newCameraEl - Entity with camera component.
  53821. */
  53822. setSpectatorCamera: function (newCameraEl) {
  53823. var newCamera;
  53824. var previousCamera = this.spectatorCameraEl;
  53825. var sceneEl = this.sceneEl;
  53826. var spectatorCameraEl;
  53827. // Same camera.
  53828. newCamera = newCameraEl.getObject3D('camera');
  53829. if (!newCamera || newCameraEl === this.spectatorCameraEl) { return; }
  53830. // Disable current camera
  53831. if (previousCamera) {
  53832. previousCamera.setAttribute('camera', 'spectator', false);
  53833. }
  53834. spectatorCameraEl = this.spectatorCameraEl = newCameraEl;
  53835. sceneEl.addEventListener('enter-vr', this.wrapRender);
  53836. sceneEl.addEventListener('exit-vr', this.unwrapRender);
  53837. spectatorCameraEl.setAttribute('camera', 'active', false);
  53838. spectatorCameraEl.play();
  53839. sceneEl.emit('camera-set-spectator', {cameraEl: newCameraEl});
  53840. },
  53841. /**
  53842. * Disables current spectator camera.
  53843. */
  53844. disableSpectatorCamera: function () {
  53845. this.spectatorCameraEl = undefined;
  53846. },
  53847. /**
  53848. * Wrap the render method of the renderer to render
  53849. * the spectator camera after vrDisplay.submitFrame.
  53850. */
  53851. wrapRender: function () {
  53852. if (!this.spectatorCameraEl) { return; }
  53853. this.originalRender = this.sceneEl.renderer.render;
  53854. this.sceneEl.renderer.render = this.render;
  53855. },
  53856. unwrapRender: function () {
  53857. if (!this.originalRender) { return; }
  53858. this.sceneEl.renderer.render = this.originalRender;
  53859. this.originalRender = undefined;
  53860. },
  53861. render: function (scene, camera) {
  53862. var isVREnabled;
  53863. var sceneEl = this.sceneEl;
  53864. var spectatorCamera;
  53865. isVREnabled = sceneEl.renderer.vr.enabled;
  53866. this.originalRender.call(sceneEl.renderer, scene, camera);
  53867. if (!this.spectatorCameraEl || sceneEl.isMobile || !isVREnabled) { return; }
  53868. spectatorCamera = this.spectatorCameraEl.components.camera.camera;
  53869. sceneEl.renderer.vr.enabled = false;
  53870. this.originalRender.call(sceneEl.renderer, scene, spectatorCamera);
  53871. sceneEl.renderer.vr.enabled = isVREnabled;
  53872. }
  53873. });
  53874. /**
  53875. * Remove injected default camera from scene, if present.
  53876. *
  53877. * @param {Element} sceneEl
  53878. */
  53879. function removeDefaultCamera (sceneEl) {
  53880. var defaultCamera;
  53881. var camera = sceneEl.camera;
  53882. if (!camera) { return; }
  53883. // Remove default camera if present.
  53884. defaultCamera = sceneEl.querySelector('[' + DEFAULT_CAMERA_ATTR + ']');
  53885. if (!defaultCamera) { return; }
  53886. sceneEl.removeChild(defaultCamera);
  53887. }
  53888. },{"../constants/":95,"../core/system":114}],161:[function(_dereq_,module,exports){
  53889. var geometries = _dereq_('../core/geometry').geometries;
  53890. var registerSystem = _dereq_('../core/system').registerSystem;
  53891. var THREE = _dereq_('../lib/three');
  53892. /**
  53893. * System for geometry component.
  53894. * Handle geometry caching.
  53895. *
  53896. * @member {object} cache - Mapping of stringified component data to THREE.Geometry objects.
  53897. * @member {object} cacheCount - Keep track of number of entities using a geometry to
  53898. * know whether to dispose on removal.
  53899. */
  53900. module.exports.System = registerSystem('geometry', {
  53901. init: function () {
  53902. this.cache = {};
  53903. this.cacheCount = {};
  53904. },
  53905. /**
  53906. * Reset cache. Mainly for testing.
  53907. */
  53908. clearCache: function () {
  53909. this.cache = {};
  53910. this.cacheCount = {};
  53911. },
  53912. /**
  53913. * Attempt to retrieve from cache.
  53914. *
  53915. * @returns {Object|null} A geometry if it exists, else null.
  53916. */
  53917. getOrCreateGeometry: function (data) {
  53918. var cache = this.cache;
  53919. var cachedGeometry;
  53920. var hash;
  53921. // Skip all caching logic.
  53922. if (data.skipCache) { return createGeometry(data); }
  53923. // Try to retrieve from cache first.
  53924. hash = this.hash(data);
  53925. cachedGeometry = cache[hash];
  53926. incrementCacheCount(this.cacheCount, hash);
  53927. if (cachedGeometry) { return cachedGeometry; }
  53928. // Create geometry.
  53929. cachedGeometry = createGeometry(data);
  53930. // Cache and return geometry.
  53931. cache[hash] = cachedGeometry;
  53932. return cachedGeometry;
  53933. },
  53934. /**
  53935. * Let system know that an entity is no longer using a geometry.
  53936. */
  53937. unuseGeometry: function (data) {
  53938. var cache = this.cache;
  53939. var cacheCount = this.cacheCount;
  53940. var geometry;
  53941. var hash;
  53942. if (data.skipCache) { return; }
  53943. hash = this.hash(data);
  53944. if (!cache[hash]) { return; }
  53945. decrementCacheCount(cacheCount, hash);
  53946. // Another entity is still using this geometry. No need to do anything.
  53947. if (cacheCount[hash] > 0) { return; }
  53948. // No more entities are using this geometry. Dispose.
  53949. geometry = cache[hash];
  53950. geometry.dispose();
  53951. delete cache[hash];
  53952. delete cacheCount[hash];
  53953. },
  53954. /**
  53955. * Use JSON.stringify to turn component data into hash.
  53956. * Should be deterministic within a single browser engine.
  53957. * If not, then look into json-stable-stringify.
  53958. */
  53959. hash: function (data) {
  53960. return JSON.stringify(data);
  53961. }
  53962. });
  53963. /**
  53964. * Create geometry using component data.
  53965. *
  53966. * @param {object} data - Component data.
  53967. * @returns {object} Geometry.
  53968. */
  53969. function createGeometry (data) {
  53970. var geometryType = data.primitive;
  53971. var GeometryClass = geometries[geometryType] && geometries[geometryType].Geometry;
  53972. var geometryInstance = new GeometryClass();
  53973. if (!GeometryClass) { throw new Error('Unknown geometry `' + geometryType + '`'); }
  53974. geometryInstance.init(data);
  53975. return toBufferGeometry(geometryInstance.geometry, data.buffer);
  53976. }
  53977. /**
  53978. * Decreate count of entity using a geometry.
  53979. */
  53980. function decrementCacheCount (cacheCount, hash) {
  53981. cacheCount[hash]--;
  53982. }
  53983. /**
  53984. * Increase count of entity using a geometry.
  53985. */
  53986. function incrementCacheCount (cacheCount, hash) {
  53987. cacheCount[hash] = cacheCount[hash] === undefined ? 1 : cacheCount[hash] + 1;
  53988. }
  53989. /**
  53990. * Transform geometry to BufferGeometry if `doBuffer`.
  53991. *
  53992. * @param {object} geometry
  53993. * @param {boolean} doBuffer
  53994. * @returns {object} Geometry.
  53995. */
  53996. function toBufferGeometry (geometry, doBuffer) {
  53997. var bufferGeometry;
  53998. if (!doBuffer) { return geometry; }
  53999. bufferGeometry = new THREE.BufferGeometry().fromGeometry(geometry);
  54000. bufferGeometry.metadata = {type: geometry.type, parameters: geometry.parameters || {}};
  54001. geometry.dispose(); // Dispose no longer needed non-buffer geometry.
  54002. return bufferGeometry;
  54003. }
  54004. },{"../core/geometry":104,"../core/system":114,"../lib/three":151}],162:[function(_dereq_,module,exports){
  54005. var registerSystem = _dereq_('../core/system').registerSystem;
  54006. var THREE = _dereq_('../lib/three');
  54007. /**
  54008. * glTF model system.
  54009. *
  54010. * Configures glTF loading options. Models using glTF compression require that a Draco decoder be
  54011. * provided externally.
  54012. *
  54013. * @param {string} dracoDecoderPath - Base path from which to load Draco decoder library.
  54014. */
  54015. module.exports.System = registerSystem('gltf-model', {
  54016. schema: {
  54017. dracoDecoderPath: {default: ''}
  54018. },
  54019. init: function () {
  54020. var path = this.data.dracoDecoderPath;
  54021. THREE.DRACOLoader.setDecoderPath(path);
  54022. this.dracoLoader = path ? new THREE.DRACOLoader() : null;
  54023. },
  54024. update: function () {
  54025. var path;
  54026. if (this.dracoLoader) { return; }
  54027. path = this.data.dracoDecoderPath;
  54028. THREE.DRACOLoader.setDecoderPath(path);
  54029. this.dracoLoader = path ? new THREE.DRACOLoader() : null;
  54030. },
  54031. getDRACOLoader: function () {
  54032. return this.dracoLoader;
  54033. }
  54034. });
  54035. },{"../core/system":114,"../lib/three":151}],163:[function(_dereq_,module,exports){
  54036. _dereq_('./camera');
  54037. _dereq_('./geometry');
  54038. _dereq_('./gltf-model');
  54039. _dereq_('./light');
  54040. _dereq_('./material');
  54041. _dereq_('./renderer');
  54042. _dereq_('./shadow');
  54043. _dereq_('./tracked-controls-webvr');
  54044. _dereq_('./tracked-controls-webxr');
  54045. },{"./camera":160,"./geometry":161,"./gltf-model":162,"./light":164,"./material":165,"./renderer":166,"./shadow":167,"./tracked-controls-webvr":168,"./tracked-controls-webxr":169}],164:[function(_dereq_,module,exports){
  54046. var registerSystem = _dereq_('../core/system').registerSystem;
  54047. var bind = _dereq_('../utils/bind');
  54048. var constants = _dereq_('../constants/');
  54049. var DEFAULT_LIGHT_ATTR = 'data-aframe-default-light';
  54050. /**
  54051. * Light system.
  54052. *
  54053. * Prescribes default lighting if not specified (one ambient, one directional).
  54054. * Removes default lighting from the scene when a new light is added.
  54055. *
  54056. * @param {bool} defaultLights - Whether default lighting are defined.
  54057. * @param {bool} userDefinedLights - Whether user lighting is defined.
  54058. */
  54059. module.exports.System = registerSystem('light', {
  54060. schema: {
  54061. defaultLightsEnabled: {default: true}
  54062. },
  54063. init: function () {
  54064. this.defaultLights = false;
  54065. this.userDefinedLights = false;
  54066. // Wait for all entities to fully load before checking for existence of lights.
  54067. // Since entities wait for <a-assets> to load, any lights attaching to the scene
  54068. // will do so asynchronously.
  54069. this.sceneEl.addEventListener('loaded', bind(this.setupDefaultLights, this));
  54070. },
  54071. /**
  54072. * Notify scene that light has been added and to remove the default.
  54073. *
  54074. * @param {object} el - element holding the light component.
  54075. */
  54076. registerLight: function (el) {
  54077. if (!el.hasAttribute(DEFAULT_LIGHT_ATTR)) {
  54078. // User added a light, remove default lights through DOM.
  54079. this.removeDefaultLights();
  54080. this.userDefinedLights = true;
  54081. }
  54082. },
  54083. removeDefaultLights: function () {
  54084. var defaultLights;
  54085. var sceneEl = this.sceneEl;
  54086. if (!this.defaultLights) { return; }
  54087. defaultLights = document.querySelectorAll('[' + DEFAULT_LIGHT_ATTR + ']');
  54088. for (var i = 0; i < defaultLights.length; i++) {
  54089. sceneEl.removeChild(defaultLights[i]);
  54090. }
  54091. this.defaultLights = false;
  54092. },
  54093. /**
  54094. * Prescibe default lights to the scene.
  54095. * Does so by injecting markup such that this state is not invisible.
  54096. * These lights are removed if the user adds any lights.
  54097. */
  54098. setupDefaultLights: function () {
  54099. var sceneEl = this.sceneEl;
  54100. var ambientLight;
  54101. var directionalLight;
  54102. if (this.userDefinedLights || this.defaultLights || !this.data.defaultLightsEnabled) {
  54103. return;
  54104. }
  54105. ambientLight = document.createElement('a-entity');
  54106. ambientLight.setAttribute('light', {color: '#BBB', type: 'ambient'});
  54107. ambientLight.setAttribute(DEFAULT_LIGHT_ATTR, '');
  54108. ambientLight.setAttribute(constants.AFRAME_INJECTED, '');
  54109. sceneEl.appendChild(ambientLight);
  54110. directionalLight = document.createElement('a-entity');
  54111. directionalLight.setAttribute('light', {color: '#FFF', intensity: 0.6, castShadow: true});
  54112. directionalLight.setAttribute('position', {x: -0.5, y: 1, z: 1});
  54113. directionalLight.setAttribute(DEFAULT_LIGHT_ATTR, '');
  54114. directionalLight.setAttribute(constants.AFRAME_INJECTED, '');
  54115. sceneEl.appendChild(directionalLight);
  54116. this.defaultLights = true;
  54117. }
  54118. });
  54119. },{"../constants/":95,"../core/system":114,"../utils/bind":170}],165:[function(_dereq_,module,exports){
  54120. var registerSystem = _dereq_('../core/system').registerSystem;
  54121. var THREE = _dereq_('../lib/three');
  54122. var utils = _dereq_('../utils/');
  54123. var isHLS = _dereq_('../utils/material').isHLS;
  54124. var bind = utils.bind;
  54125. var debug = utils.debug;
  54126. var error = debug('components:texture:error');
  54127. var TextureLoader = new THREE.TextureLoader();
  54128. var warn = debug('components:texture:warn');
  54129. TextureLoader.setCrossOrigin('anonymous');
  54130. /**
  54131. * System for material component.
  54132. * Handle material registration, updates (for fog), and texture caching.
  54133. *
  54134. * @member {object} materials - Registered materials.
  54135. * @member {object} textureCounts - Number of times each texture is used. Tracked
  54136. * separately from textureCache, because the cache (1) is populated in
  54137. * multiple places, and (2) may be cleared at any time.
  54138. * @member {object} textureCache - Texture cache for:
  54139. * - Images: textureCache has mapping of src -> repeat -> cached three.js texture.
  54140. * - Videos: textureCache has mapping of videoElement -> cached three.js texture.
  54141. */
  54142. module.exports.System = registerSystem('material', {
  54143. init: function () {
  54144. this.materials = {};
  54145. this.textureCounts = {};
  54146. this.textureCache = {};
  54147. this.sceneEl.addEventListener(
  54148. 'materialtextureloaded',
  54149. bind(this.onMaterialTextureLoaded, this)
  54150. );
  54151. },
  54152. clearTextureCache: function () {
  54153. this.textureCache = {};
  54154. },
  54155. /**
  54156. * Determine whether `src` is a image or video. Then try to load the asset, then call back.
  54157. *
  54158. * @param {string, or element} src - Texture URL or element.
  54159. * @param {string} data - Relevant texture data used for caching.
  54160. * @param {function} cb - Callback to pass texture to.
  54161. */
  54162. loadTexture: function (src, data, cb) {
  54163. var self = this;
  54164. // Canvas.
  54165. if (src.tagName === 'CANVAS') {
  54166. this.loadCanvas(src, data, cb);
  54167. return;
  54168. }
  54169. // Video element.
  54170. if (src.tagName === 'VIDEO') {
  54171. if (!src.src && !src.srcObject && !src.childElementCount) {
  54172. warn('Video element was defined with neither `source` elements nor `src` / `srcObject` attributes.');
  54173. }
  54174. this.loadVideo(src, data, cb);
  54175. return;
  54176. }
  54177. utils.srcLoader.validateSrc(src, loadImageCb, loadVideoCb);
  54178. function loadImageCb (src) { self.loadImage(src, data, cb); }
  54179. function loadVideoCb (src) { self.loadVideo(src, data, cb); }
  54180. },
  54181. /**
  54182. * High-level function for loading image textures (THREE.Texture).
  54183. *
  54184. * @param {Element|string} src - Texture source.
  54185. * @param {object} data - Texture data.
  54186. * @param {function} cb - Callback to pass texture to.
  54187. */
  54188. loadImage: function (src, data, handleImageTextureLoaded) {
  54189. var hash = this.hash(data);
  54190. var textureCache = this.textureCache;
  54191. // Texture already being loaded or already loaded. Wait on promise.
  54192. if (textureCache[hash]) {
  54193. textureCache[hash].then(handleImageTextureLoaded);
  54194. return;
  54195. }
  54196. // Texture not yet being loaded. Start loading it.
  54197. textureCache[hash] = loadImageTexture(src, data);
  54198. textureCache[hash].then(handleImageTextureLoaded);
  54199. },
  54200. /**
  54201. * High-level function for loading canvas textures (THREE.Texture).
  54202. *
  54203. * @param {Element|string} src - Texture source.
  54204. * @param {object} data - Texture data.
  54205. * @param {function} cb - Callback to pass texture to.
  54206. */
  54207. loadCanvas: function (src, data, cb) {
  54208. var texture;
  54209. texture = new THREE.CanvasTexture(src);
  54210. setTextureProperties(texture, data);
  54211. cb(texture);
  54212. },
  54213. /**
  54214. * Load video texture (THREE.VideoTexture).
  54215. * Which is just an image texture that RAFs + needsUpdate.
  54216. * Note that creating a video texture is synchronous unlike loading an image texture.
  54217. * Made asynchronous to be consistent with image textures.
  54218. *
  54219. * @param {Element|string} src - Texture source.
  54220. * @param {object} data - Texture data.
  54221. * @param {function} cb - Callback to pass texture to.
  54222. */
  54223. loadVideo: function (src, data, cb) {
  54224. var hash;
  54225. var texture;
  54226. var textureCache = this.textureCache;
  54227. var videoEl;
  54228. var videoTextureResult;
  54229. function handleVideoTextureLoaded (result) {
  54230. result.texture.needsUpdate = true;
  54231. cb(result.texture, result.videoEl);
  54232. }
  54233. // Video element provided.
  54234. if (typeof src !== 'string') {
  54235. // Check cache before creating texture.
  54236. videoEl = src;
  54237. hash = this.hashVideo(data, videoEl);
  54238. if (textureCache[hash]) {
  54239. textureCache[hash].then(handleVideoTextureLoaded);
  54240. return;
  54241. }
  54242. // If not in cache, fix up the attributes then start to create the texture.
  54243. fixVideoAttributes(videoEl);
  54244. }
  54245. // Only URL provided. Use video element to create texture.
  54246. videoEl = videoEl || createVideoEl(src, data.width, data.height);
  54247. // Generated video element already cached. Use that.
  54248. hash = this.hashVideo(data, videoEl);
  54249. if (textureCache[hash]) {
  54250. textureCache[hash].then(handleVideoTextureLoaded);
  54251. return;
  54252. }
  54253. // Create new video texture.
  54254. texture = new THREE.VideoTexture(videoEl);
  54255. texture.minFilter = THREE.LinearFilter;
  54256. setTextureProperties(texture, data);
  54257. // If iOS and video is HLS, do some hacks.
  54258. if (this.sceneEl.isIOS &&
  54259. isHLS(videoEl.src || videoEl.getAttribute('src'),
  54260. videoEl.type || videoEl.getAttribute('type'))) {
  54261. // Actually BGRA. Tell shader to correct later.
  54262. texture.format = THREE.RGBAFormat;
  54263. texture.needsCorrectionBGRA = true;
  54264. // Apparently needed for HLS. Tell shader to correct later.
  54265. texture.flipY = false;
  54266. texture.needsCorrectionFlipY = true;
  54267. }
  54268. // Cache as promise to be consistent with image texture caching.
  54269. videoTextureResult = {texture: texture, videoEl: videoEl};
  54270. textureCache[hash] = Promise.resolve(videoTextureResult);
  54271. handleVideoTextureLoaded(videoTextureResult);
  54272. },
  54273. /**
  54274. * Create a hash of the material properties for texture cache key.
  54275. */
  54276. hash: function (data) {
  54277. if (data.src.tagName) {
  54278. // Since `data.src` can be an element, parse out the string if necessary for the hash.
  54279. data = utils.extendDeep({}, data);
  54280. data.src = data.src.src;
  54281. }
  54282. return JSON.stringify(data);
  54283. },
  54284. hashVideo: function (data, videoEl) {
  54285. return calculateVideoCacheHash(data, videoEl);
  54286. },
  54287. /**
  54288. * Keep track of material in case an update trigger is needed (e.g., fog).
  54289. *
  54290. * @param {object} material
  54291. */
  54292. registerMaterial: function (material) {
  54293. this.materials[material.uuid] = material;
  54294. },
  54295. /**
  54296. * Stop tracking material, and dispose of any textures not being used by
  54297. * another material component.
  54298. *
  54299. * @param {object} material
  54300. */
  54301. unregisterMaterial: function (material) {
  54302. delete this.materials[material.uuid];
  54303. // If any textures on this material are no longer in use, dispose of them.
  54304. var textureCounts = this.textureCounts;
  54305. Object.keys(material)
  54306. .filter(function (propName) {
  54307. return material[propName] && material[propName].isTexture;
  54308. })
  54309. .forEach(function (mapName) {
  54310. textureCounts[material[mapName].uuid]--;
  54311. if (textureCounts[material[mapName].uuid] <= 0) {
  54312. material[mapName].dispose();
  54313. }
  54314. });
  54315. },
  54316. /**
  54317. * Trigger update to all registered materials.
  54318. */
  54319. updateMaterials: function (material) {
  54320. var materials = this.materials;
  54321. Object.keys(materials).forEach(function (uuid) {
  54322. materials[uuid].needsUpdate = true;
  54323. });
  54324. },
  54325. /**
  54326. * Track textures used by material components, so that they can be safely
  54327. * disposed when no longer in use. Textures must be registered here, and not
  54328. * through registerMaterial(), because textures may not be attached at the
  54329. * time the material is registered.
  54330. *
  54331. * @param {Event} e
  54332. */
  54333. onMaterialTextureLoaded: function (e) {
  54334. if (!this.textureCounts[e.detail.texture.uuid]) {
  54335. this.textureCounts[e.detail.texture.uuid] = 0;
  54336. }
  54337. this.textureCounts[e.detail.texture.uuid]++;
  54338. }
  54339. });
  54340. /**
  54341. * Calculates consistent hash from a video element using its attributes.
  54342. * If the video element has an ID, use that.
  54343. * Else build a hash that looks like `src:myvideo.mp4;height:200;width:400;`.
  54344. *
  54345. * @param data {object} - Texture data such as repeat.
  54346. * @param videoEl {Element} - Video element.
  54347. * @returns {string}
  54348. */
  54349. function calculateVideoCacheHash (data, videoEl) {
  54350. var i;
  54351. var id = videoEl.getAttribute('id');
  54352. var hash;
  54353. var videoAttributes;
  54354. if (id) { return id; }
  54355. // Calculate hash using sorted video attributes.
  54356. hash = '';
  54357. videoAttributes = data || {};
  54358. for (i = 0; i < videoEl.attributes.length; i++) {
  54359. videoAttributes[videoEl.attributes[i].name] = videoEl.attributes[i].value;
  54360. }
  54361. Object.keys(videoAttributes).sort().forEach(function (name) {
  54362. hash += name + ':' + videoAttributes[name] + ';';
  54363. });
  54364. return hash;
  54365. }
  54366. /**
  54367. * Load image texture.
  54368. *
  54369. * @private
  54370. * @param {string|object} src - An <img> element or url to an image file.
  54371. * @param {object} data - Data to set texture properties like `repeat`.
  54372. * @returns {Promise} Resolves once texture is loaded.
  54373. */
  54374. function loadImageTexture (src, data) {
  54375. return new Promise(doLoadImageTexture);
  54376. function doLoadImageTexture (resolve, reject) {
  54377. var isEl = typeof src !== 'string';
  54378. function resolveTexture (texture) {
  54379. setTextureProperties(texture, data);
  54380. texture.needsUpdate = true;
  54381. resolve(texture);
  54382. }
  54383. // Create texture from an element.
  54384. if (isEl) {
  54385. resolveTexture(new THREE.Texture(src));
  54386. return;
  54387. }
  54388. // Request and load texture from src string. THREE will create underlying element.
  54389. // Use THREE.TextureLoader (src, onLoad, onProgress, onError) to load texture.
  54390. TextureLoader.load(
  54391. src,
  54392. resolveTexture,
  54393. function () { /* no-op */ },
  54394. function (xhr) {
  54395. error('`$s` could not be fetched (Error code: %s; Response: %s)', xhr.status,
  54396. xhr.statusText);
  54397. }
  54398. );
  54399. }
  54400. }
  54401. /**
  54402. * Set texture properties such as repeat and offset.
  54403. *
  54404. * @param {object} data - With keys like `repeat`.
  54405. */
  54406. function setTextureProperties (texture, data) {
  54407. var offset = data.offset || {x: 0, y: 0};
  54408. var repeat = data.repeat || {x: 1, y: 1};
  54409. var npot = data.npot || false;
  54410. // To support NPOT textures, wrap must be ClampToEdge (not Repeat),
  54411. // and filters must not use mipmaps (i.e. Nearest or Linear).
  54412. if (npot) {
  54413. texture.wrapS = THREE.ClampToEdgeWrapping;
  54414. texture.wrapT = THREE.ClampToEdgeWrapping;
  54415. texture.magFilter = THREE.LinearFilter;
  54416. texture.minFilter = THREE.LinearFilter;
  54417. }
  54418. // Don't bother setting repeat if it is 1/1. Power-of-two is required to repeat.
  54419. if (repeat.x !== 1 || repeat.y !== 1) {
  54420. texture.wrapS = THREE.RepeatWrapping;
  54421. texture.wrapT = THREE.RepeatWrapping;
  54422. texture.repeat.set(repeat.x, repeat.y);
  54423. }
  54424. // Don't bother setting offset if it is 0/0.
  54425. if (offset.x !== 0 || offset.y !== 0) {
  54426. texture.offset.set(offset.x, offset.y);
  54427. }
  54428. }
  54429. /**
  54430. * Create video element to be used as a texture.
  54431. *
  54432. * @param {string} src - Url to a video file.
  54433. * @param {number} width - Width of the video.
  54434. * @param {number} height - Height of the video.
  54435. * @returns {Element} Video element.
  54436. */
  54437. function createVideoEl (src, width, height) {
  54438. var videoEl = document.createElement('video');
  54439. videoEl.width = width;
  54440. videoEl.height = height;
  54441. // Support inline videos for iOS webviews.
  54442. videoEl.setAttribute('playsinline', '');
  54443. videoEl.setAttribute('webkit-playsinline', '');
  54444. videoEl.autoplay = true;
  54445. videoEl.loop = true;
  54446. videoEl.crossOrigin = 'anonymous';
  54447. videoEl.addEventListener('error', function () {
  54448. warn('`$s` is not a valid video', src);
  54449. }, true);
  54450. videoEl.src = src;
  54451. return videoEl;
  54452. }
  54453. /**
  54454. * Fixes a video element's attributes to prevent developers from accidentally passing the
  54455. * wrong attribute values to commonly misused video attributes.
  54456. *
  54457. * <video> does not treat `autoplay`, `controls`, `crossorigin`, `loop`, and `preload` as
  54458. * as booleans. Existence of those attributes will mean truthy.
  54459. *
  54460. * For example, translates <video loop="false"> to <video>.
  54461. *
  54462. * @see https://developer.mozilla.org/docs/Web/HTML/Element/video#Attributes
  54463. * @param {Element} videoEl - Video element.
  54464. * @returns {Element} Video element with the correct properties updated.
  54465. */
  54466. function fixVideoAttributes (videoEl) {
  54467. videoEl.autoplay = videoEl.hasAttribute('autoplay') && videoEl.getAttribute('autoplay') !== 'false';
  54468. videoEl.controls = videoEl.hasAttribute('controls') && videoEl.getAttribute('controls') !== 'false';
  54469. if (videoEl.getAttribute('loop') === 'false') {
  54470. videoEl.removeAttribute('loop');
  54471. }
  54472. if (videoEl.getAttribute('preload') === 'false') {
  54473. videoEl.preload = 'none';
  54474. }
  54475. videoEl.crossOrigin = videoEl.crossOrigin || 'anonymous';
  54476. // To support inline videos in iOS webviews.
  54477. videoEl.setAttribute('playsinline', '');
  54478. videoEl.setAttribute('webkit-playsinline', '');
  54479. return videoEl;
  54480. }
  54481. },{"../core/system":114,"../lib/three":151,"../utils/":176,"../utils/material":179}],166:[function(_dereq_,module,exports){
  54482. var registerSystem = _dereq_('../core/system').registerSystem;
  54483. var utils = _dereq_('../utils/');
  54484. var THREE = _dereq_('../lib/three');
  54485. var debug = utils.debug;
  54486. var warn = debug('components:renderer:warn');
  54487. /**
  54488. * Determines state of various renderer properties.
  54489. */
  54490. module.exports.System = registerSystem('renderer', {
  54491. schema: {
  54492. antialias: {default: 'auto', oneOf: ['true', 'false', 'auto']},
  54493. highRefreshRate: {default: false},
  54494. logarithmicDepthBuffer: {default: 'auto', oneOf: ['true', 'false', 'auto']},
  54495. maxCanvasWidth: {default: 1920},
  54496. maxCanvasHeight: {default: 1920},
  54497. physicallyCorrectLights: {default: false},
  54498. precision: {default: 'high', oneOf: ['high', 'medium', 'low']},
  54499. sortObjects: {default: false},
  54500. colorManagement: {default: false},
  54501. gammaOutput: {default: false},
  54502. alpha: {default: true},
  54503. foveationLevel: {default: 0}
  54504. },
  54505. init: function () {
  54506. var data = this.data;
  54507. var sceneEl = this.el;
  54508. // This is the rendering engine, such as THREE.js so copy over any persistent properties from the rendering system.
  54509. var renderer = sceneEl.renderer;
  54510. renderer.sortObjects = data.sortObjects;
  54511. renderer.physicallyCorrectLights = data.physicallyCorrectLights;
  54512. if (data.colorManagement || data.gammaOutput) {
  54513. renderer.gammaOutput = true;
  54514. renderer.gammaFactor = 2.2;
  54515. if (data.gammaOutput) {
  54516. warn('Property `gammaOutput` is deprecated. Use `renderer="colorManagement: true;"` instead.');
  54517. }
  54518. }
  54519. if (sceneEl.hasAttribute('antialias')) {
  54520. warn('Component `antialias` is deprecated. Use `renderer="antialias: true"` instead.');
  54521. }
  54522. if (sceneEl.hasAttribute('logarithmicDepthBuffer')) {
  54523. warn('Component `logarithmicDepthBuffer` is deprecated. Use `renderer="logarithmicDepthBuffer: true"` instead.');
  54524. }
  54525. },
  54526. applyColorCorrection: function (colorOrTexture) {
  54527. if (!this.data.colorManagement || !colorOrTexture) {
  54528. return;
  54529. } else if (colorOrTexture.isColor) {
  54530. colorOrTexture.convertSRGBToLinear();
  54531. } else if (colorOrTexture.isTexture) {
  54532. colorOrTexture.encoding = THREE.sRGBEncoding;
  54533. }
  54534. }
  54535. });
  54536. },{"../core/system":114,"../lib/three":151,"../utils/":176}],167:[function(_dereq_,module,exports){
  54537. var registerSystem = _dereq_('../core/system').registerSystem;
  54538. var THREE = _dereq_('../lib/three');
  54539. var SHADOW_MAP_TYPE_MAP = {
  54540. basic: THREE.BasicShadowMap,
  54541. pcf: THREE.PCFShadowMap,
  54542. pcfsoft: THREE.PCFSoftShadowMap
  54543. };
  54544. /**
  54545. * Shadow system.
  54546. *
  54547. * Enabled automatically when one or more shadow components are added to the scene, the system sets
  54548. * options on the WebGLRenderer for configuring shadow appearance.
  54549. */
  54550. module.exports.System = registerSystem('shadow', {
  54551. schema: {
  54552. enabled: {default: true},
  54553. autoUpdate: {default: true},
  54554. type: {default: 'pcf', oneOf: ['basic', 'pcf', 'pcfsoft']}
  54555. },
  54556. init: function () {
  54557. var sceneEl = this.sceneEl;
  54558. var data = this.data;
  54559. this.shadowMapEnabled = false;
  54560. if (!sceneEl.renderer) { return; } // For tests.
  54561. sceneEl.renderer.shadowMap.type = SHADOW_MAP_TYPE_MAP[data.type];
  54562. sceneEl.renderer.shadowMap.autoUpdate = data.autoUpdate;
  54563. this.setShadowMapEnabled(this.shadowMapEnabled);
  54564. },
  54565. update: function (prevData) {
  54566. if (prevData.enabled !== this.data.enabled) {
  54567. this.setShadowMapEnabled(this.data.enabled);
  54568. }
  54569. },
  54570. /**
  54571. * Enables/disables the renderer shadow map.
  54572. * @param {boolean} enabled
  54573. */
  54574. setShadowMapEnabled: function (enabled) {
  54575. var renderer = this.sceneEl.renderer;
  54576. this.shadowMapEnabled = this.data.enabled && enabled;
  54577. if (renderer) {
  54578. renderer.shadowMap.enabled = this.shadowMapEnabled;
  54579. }
  54580. }
  54581. });
  54582. },{"../core/system":114,"../lib/three":151}],168:[function(_dereq_,module,exports){
  54583. var registerSystem = _dereq_('../core/system').registerSystem;
  54584. var utils = _dereq_('../utils');
  54585. /**
  54586. * Tracked controls system.
  54587. * Maintain list with available tracked controllers.
  54588. */
  54589. module.exports.System = registerSystem('tracked-controls-webvr', {
  54590. init: function () {
  54591. var self = this;
  54592. this.controllers = [];
  54593. this.isChrome = navigator.userAgent.indexOf('Chrome') !== -1;
  54594. this.updateControllerList();
  54595. this.throttledUpdateControllerList = utils.throttle(this.updateControllerList, 500, this);
  54596. if (!navigator.getVRDisplays) { return; }
  54597. this.sceneEl.addEventListener('enter-vr', function () {
  54598. navigator.getVRDisplays().then(function (displays) {
  54599. if (displays.length) { self.vrDisplay = displays[0]; }
  54600. });
  54601. });
  54602. },
  54603. tick: function () {
  54604. if (this.isChrome) {
  54605. // Retrieve new controller handlers with updated state (pose, buttons...)
  54606. this.updateControllerList();
  54607. } else {
  54608. this.throttledUpdateControllerList();
  54609. }
  54610. },
  54611. /**
  54612. * Update controller list.
  54613. */
  54614. updateControllerList: function () {
  54615. var controllers = this.controllers;
  54616. var gamepad;
  54617. var gamepads;
  54618. var i;
  54619. var prevCount;
  54620. gamepads = navigator.getGamepads && navigator.getGamepads();
  54621. if (!gamepads) { return; }
  54622. prevCount = controllers.length;
  54623. controllers.length = 0;
  54624. for (i = 0; i < gamepads.length; ++i) {
  54625. gamepad = gamepads[i];
  54626. if (gamepad && gamepad.pose) {
  54627. controllers.push(gamepad);
  54628. }
  54629. }
  54630. if (controllers.length !== prevCount) {
  54631. this.el.emit('controllersupdated', undefined, false);
  54632. }
  54633. }
  54634. });
  54635. },{"../core/system":114,"../utils":176}],169:[function(_dereq_,module,exports){
  54636. var registerSystem = _dereq_('../core/system').registerSystem;
  54637. var utils = _dereq_('../utils');
  54638. /**
  54639. * Tracked controls system.
  54640. * Maintain list with available tracked controllers.
  54641. */
  54642. module.exports.System = registerSystem('tracked-controls-webxr', {
  54643. init: function () {
  54644. this.controllers = [];
  54645. this.throttledUpdateControllerList = utils.throttle(this.updateControllerList, 500, this);
  54646. },
  54647. tick: function () {
  54648. this.throttledUpdateControllerList();
  54649. },
  54650. updateControllerList: function () {
  54651. var oldControllersLength = this.controllers.length;
  54652. if (!this.el.xrSession) { return; }
  54653. this.controllers = this.el.xrSession.getInputSources();
  54654. if (oldControllersLength === this.controllers.length) { return; }
  54655. this.el.emit('controllersupdated', undefined, false);
  54656. }
  54657. });
  54658. },{"../core/system":114,"../utils":176}],170:[function(_dereq_,module,exports){
  54659. /**
  54660. * Faster version of Function.prototype.bind
  54661. * @param {Function} fn - Function to wrap.
  54662. * @param {Object} ctx - What to bind as context.
  54663. * @param {...*} arguments - Arguments to pass through.
  54664. */
  54665. module.exports = function bind (fn, ctx/* , arg1, arg2 */) {
  54666. return (function (prependedArgs) {
  54667. return function bound () {
  54668. // Concat the bound function arguments with those passed to original bind
  54669. var args = prependedArgs.concat(Array.prototype.slice.call(arguments, 0));
  54670. return fn.apply(ctx, args);
  54671. };
  54672. })(Array.prototype.slice.call(arguments, 2));
  54673. };
  54674. },{}],171:[function(_dereq_,module,exports){
  54675. /* global THREE */
  54676. var debug = _dereq_('./debug');
  54677. var extend = _dereq_('object-assign');
  54678. var warn = debug('utils:coordinates:warn');
  54679. // Order of coordinates parsed by coordinates.parse.
  54680. var COORDINATE_KEYS = ['x', 'y', 'z', 'w'];
  54681. // Coordinate string regex. Handles negative, positive, and decimals.
  54682. var regex = /^\s*((-?\d*\.{0,1}\d+(e-?\d+)?)\s+){2,3}(-?\d*\.{0,1}\d+(e-?\d+)?)\s*$/;
  54683. module.exports.regex = regex;
  54684. var OBJECT = 'object';
  54685. var whitespaceRegex = /\s+/g;
  54686. /**
  54687. * Parses coordinates from an "x y z" string.
  54688. * Example: "3 10 -5" to {x: 3, y: 10, z: -5}.
  54689. *
  54690. * @param {string} val - An "x y z" string.
  54691. * @param {string} defaults - fallback value.
  54692. * @returns {object} An object with keys [x, y, z].
  54693. */
  54694. function parse (value, defaultVec) {
  54695. var coordinate;
  54696. var defaultVal;
  54697. var key;
  54698. var i;
  54699. var vec;
  54700. var x;
  54701. var y;
  54702. var z;
  54703. var w;
  54704. if (value && value instanceof Object) {
  54705. x = value.x === undefined ? defaultVec && defaultVec.x : value.x;
  54706. y = value.y === undefined ? defaultVec && defaultVec.y : value.y;
  54707. z = value.z === undefined ? defaultVec && defaultVec.z : value.z;
  54708. w = value.w === undefined ? defaultVec && defaultVec.w : value.w;
  54709. if (x !== undefined && x !== null) { value.x = parseIfString(x); }
  54710. if (y !== undefined && y !== null) { value.y = parseIfString(y); }
  54711. if (z !== undefined && z !== null) { value.z = parseIfString(z); }
  54712. if (w !== undefined && w !== null) { value.w = parseIfString(w); }
  54713. return value;
  54714. }
  54715. if (value === null || value === undefined) {
  54716. return typeof defaultVec === OBJECT ? extend({}, defaultVec) : defaultVec;
  54717. }
  54718. coordinate = value.trim().split(whitespaceRegex);
  54719. vec = {};
  54720. for (i = 0; i < COORDINATE_KEYS.length; i++) {
  54721. key = COORDINATE_KEYS[i];
  54722. if (coordinate[i]) {
  54723. vec[key] = parseFloat(coordinate[i], 10);
  54724. } else {
  54725. defaultVal = defaultVec && defaultVec[key];
  54726. if (defaultVal === undefined) { continue; }
  54727. vec[key] = parseIfString(defaultVal);
  54728. }
  54729. }
  54730. return vec;
  54731. }
  54732. module.exports.parse = parse;
  54733. /**
  54734. * Stringify coordinates from an object with keys [x y z].
  54735. * Example: {x: 3, y: 10, z: -5} to "3 10 -5".
  54736. *
  54737. * @param {object|string} data - An object with keys [x y z].
  54738. * @returns {string} An "x y z" string.
  54739. */
  54740. function stringify (data) {
  54741. var str;
  54742. if (typeof data !== OBJECT) { return data; }
  54743. str = data.x + ' ' + data.y;
  54744. if (data.z != null) { str += ' ' + data.z; }
  54745. if (data.w != null) { str += ' ' + data.w; }
  54746. return str;
  54747. }
  54748. module.exports.stringify = stringify;
  54749. /**
  54750. * @returns {bool}
  54751. */
  54752. function isCoordinates (value) {
  54753. return regex.test(value);
  54754. }
  54755. module.exports.isCoordinates = isCoordinates;
  54756. module.exports.isCoordinate = function (value) {
  54757. warn('`AFRAME.utils.isCoordinate` has been renamed to `AFRAME.utils.isCoordinates`');
  54758. return isCoordinates(value);
  54759. };
  54760. function parseIfString (val) {
  54761. if (val !== null && val !== undefined && val.constructor === String) {
  54762. return parseFloat(val, 10);
  54763. }
  54764. return val;
  54765. }
  54766. /**
  54767. * Convert {x, y, z} object to three.js Vector3.
  54768. */
  54769. module.exports.toVector3 = function (vec3) {
  54770. return new THREE.Vector3(vec3.x, vec3.y, vec3.z);
  54771. };
  54772. },{"./debug":172,"object-assign":25}],172:[function(_dereq_,module,exports){
  54773. (function (process){
  54774. var debugLib = _dereq_('debug');
  54775. var extend = _dereq_('object-assign');
  54776. var settings = {
  54777. colors: {
  54778. debug: 'gray',
  54779. error: 'red',
  54780. info: 'gray',
  54781. warn: 'orange'
  54782. }
  54783. };
  54784. /**
  54785. * Monkeypatches `debug` so we can colorize error/warning messages.
  54786. *
  54787. * (See issue: https://github.com/visionmedia/debug/issues/137)
  54788. */
  54789. var debug = function (namespace) {
  54790. var d = debugLib(namespace);
  54791. d.color = getDebugNamespaceColor(namespace);
  54792. return d;
  54793. };
  54794. extend(debug, debugLib);
  54795. /**
  54796. * Returns the type of the namespace (e.g., `error`, `warn`).
  54797. *
  54798. * @param {String} namespace
  54799. * The debug logger's namespace (e.g., `components:geometry:warn`).
  54800. * @returns {String} The type of the namespace (e.g., `warn`).
  54801. * @api private
  54802. */
  54803. function getDebugNamespaceType (namespace) {
  54804. var chunks = namespace.split(':');
  54805. return chunks[chunks.length - 1]; // Return the last one
  54806. }
  54807. /**
  54808. * Returns the color of the namespace (e.g., `orange`).
  54809. *
  54810. * @param {String} namespace
  54811. * The debug logger's namespace (e.g., `components:geometry:warn`).
  54812. * @returns {String} The color of the namespace (e.g., `orange`).
  54813. * @api private
  54814. */
  54815. function getDebugNamespaceColor (namespace) {
  54816. var type = getDebugNamespaceType(namespace);
  54817. var color = settings.colors && settings.colors[type];
  54818. return color || null;
  54819. }
  54820. /**
  54821. * Returns `localStorage` if possible.
  54822. *
  54823. * This is necessary because Safari throws when a user disables
  54824. * cookies or `localStorage` and you attempt to access it.
  54825. *
  54826. * @returns {localStorage}
  54827. * @api private
  54828. */
  54829. function storage () {
  54830. try {
  54831. return window.localStorage;
  54832. } catch (e) {
  54833. }
  54834. }
  54835. /**
  54836. * To enable console logging, type this in the Console of your Dev Tools:
  54837. *
  54838. * localStorage.logs = 1
  54839. *
  54840. * To disable console logging:
  54841. *
  54842. * localStorage.logs = 0
  54843. *
  54844. */
  54845. var ls = storage();
  54846. if (ls && (parseInt(ls.logs, 10) || ls.logs === 'true')) {
  54847. debug.enable('*');
  54848. } else {
  54849. debug.enable('*:error,*:info,*:warn');
  54850. }
  54851. if (process.browser) { window.logs = debug; }
  54852. module.exports = debug;
  54853. }).call(this,_dereq_('_process'))
  54854. },{"_process":32,"debug":8,"object-assign":25}],173:[function(_dereq_,module,exports){
  54855. (function (process){
  54856. var error = _dereq_('debug')('device:error');
  54857. var vrDisplay;
  54858. // Catch vrdisplayactivate early to ensure we can enter VR mode after the scene loads.
  54859. window.addEventListener('vrdisplayactivate', function (evt) {
  54860. var canvasEl;
  54861. // WebXR takes priority if available.
  54862. if (navigator.xr) { return; }
  54863. canvasEl = document.createElement('canvas');
  54864. vrDisplay = evt.display;
  54865. // Request present immediately. a-scene will be allowed to enter VR without user gesture.
  54866. vrDisplay.requestPresent([{source: canvasEl}]).then(function () {}, function () {});
  54867. });
  54868. // Support both WebVR and WebXR APIs.
  54869. if (navigator.xr) {
  54870. navigator.xr.requestDevice().then(function (device) {
  54871. if (!device) { return; }
  54872. device.supportsSession({immersive: true, exclusive: true}).then(function () {
  54873. var sceneEl = document.querySelector('a-scene');
  54874. vrDisplay = device;
  54875. if (sceneEl) { sceneEl.emit('displayconnected', {vrDisplay: vrDisplay}); }
  54876. });
  54877. }).catch(function (err) {
  54878. error('WebXR Request Device: ' + err.message);
  54879. });
  54880. } else {
  54881. if (navigator.getVRDisplays) {
  54882. navigator.getVRDisplays().then(function (displays) {
  54883. var sceneEl = document.querySelector('a-scene');
  54884. vrDisplay = displays.length && displays[0];
  54885. if (sceneEl) { sceneEl.emit('displayconnected', {vrDisplay: vrDisplay}); }
  54886. });
  54887. }
  54888. }
  54889. module.exports.isWebXRAvailable = navigator.xr !== undefined;
  54890. function getVRDisplay () { return vrDisplay; }
  54891. module.exports.getVRDisplay = getVRDisplay;
  54892. /**
  54893. * Determine if a headset is connected by checking if a vrDisplay is available.
  54894. */
  54895. function checkHeadsetConnected () { return !!getVRDisplay(); }
  54896. module.exports.checkHeadsetConnected = checkHeadsetConnected;
  54897. /**
  54898. * Checks if browser is mobile and not stand-alone dedicated vr device.
  54899. * @return {Boolean} True if mobile browser detected.
  54900. */
  54901. var isMobile = (function () {
  54902. var _isMobile = false;
  54903. (function (a) {
  54904. // eslint-disable-next-line no-useless-escape
  54905. 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))) {
  54906. _isMobile = true;
  54907. }
  54908. if (isIOS() || isTablet() || isR7()) {
  54909. _isMobile = true;
  54910. }
  54911. if (isMobileVR()) {
  54912. _isMobile = false;
  54913. }
  54914. })(window.navigator.userAgent || window.navigator.vendor || window.opera);
  54915. return function () { return _isMobile; };
  54916. })();
  54917. module.exports.isMobile = isMobile;
  54918. /**
  54919. * Detect tablet devices.
  54920. * @param {string} mockUserAgent - Allow passing a mock user agent for testing.
  54921. */
  54922. function isTablet (mockUserAgent) {
  54923. var userAgent = mockUserAgent || window.navigator.userAgent;
  54924. return /ipad|Nexus (7|9)|xoom|sch-i800|playbook|tablet|kindle/i.test(userAgent);
  54925. }
  54926. module.exports.isTablet = isTablet;
  54927. function isIOS () {
  54928. return /iPad|iPhone|iPod/.test(window.navigator.platform);
  54929. }
  54930. module.exports.isIOS = isIOS;
  54931. /**
  54932. * Detect browsers in Stand-Alone headsets
  54933. */
  54934. function isMobileVR () {
  54935. return /(OculusBrowser)|(SamsungBrowser)|(Mobile VR)/i.test(window.navigator.userAgent);
  54936. }
  54937. module.exports.isMobileVR = isMobileVR;
  54938. function isR7 () {
  54939. return /R7 Build/.test(window.navigator.userAgent);
  54940. }
  54941. module.exports.isR7 = isR7;
  54942. /**
  54943. * Checks mobile device orientation.
  54944. * @return {Boolean} True if landscape orientation.
  54945. */
  54946. module.exports.isLandscape = function () {
  54947. var orientation = window.orientation;
  54948. if (isR7()) { orientation += 90; }
  54949. return orientation === 90 || orientation === -90;
  54950. };
  54951. /**
  54952. * Check if running in a browser or spoofed browser (bundler).
  54953. * We need to check a node api that isn't mocked on either side.
  54954. * `require` and `module.exports` are mocked in browser by bundlers.
  54955. * `window` is mocked in node.
  54956. * `process` is also mocked by browserify, but has custom properties.
  54957. */
  54958. module.exports.isBrowserEnvironment = !!(!process || process.browser);
  54959. /**
  54960. * Check if running in node on the server.
  54961. */
  54962. module.exports.isNodeEnvironment = !module.exports.isBrowserEnvironment;
  54963. /**
  54964. * Update an Object3D pose if a polyfilled vrDisplay is present.
  54965. */
  54966. module.exports.PolyfillControls = function PolyfillControls (object) {
  54967. var frameData;
  54968. var vrDisplay = window.webvrpolyfill && window.webvrpolyfill.getPolyfillDisplays()[0];
  54969. if (window.VRFrameData) { frameData = new window.VRFrameData(); }
  54970. this.update = function () {
  54971. var pose;
  54972. if (!vrDisplay) { return; }
  54973. vrDisplay.getFrameData(frameData);
  54974. pose = frameData.pose;
  54975. if (pose.orientation !== null) {
  54976. object.quaternion.fromArray(pose.orientation);
  54977. }
  54978. if (pose.position !== null) {
  54979. object.position.fromArray(pose.position);
  54980. } else {
  54981. object.position.set(0, 0, 0);
  54982. }
  54983. };
  54984. };
  54985. }).call(this,_dereq_('_process'))
  54986. },{"_process":32,"debug":8}],174:[function(_dereq_,module,exports){
  54987. /**
  54988. * Split a delimited component property string (e.g., `material.color`) to an object
  54989. * containing `component` name and `property` name. If there is no delimiter, just return the
  54990. * string back.
  54991. *
  54992. * Cache arrays from splitting strings via delimiter to save on memory.
  54993. *
  54994. * @param {string} str - e.g., `material.opacity`.
  54995. * @param {string} delimiter - e.g., `.`.
  54996. * @returns {array} e.g., `['material', 'opacity']`.
  54997. */
  54998. var propertyPathCache = {};
  54999. function getComponentPropertyPath (str, delimiter) {
  55000. delimiter = delimiter || '.';
  55001. if (!propertyPathCache[delimiter]) { propertyPathCache[delimiter] = {}; }
  55002. if (str.indexOf(delimiter) !== -1) {
  55003. propertyPathCache[delimiter][str] = str.split(delimiter);
  55004. } else {
  55005. propertyPathCache[delimiter][str] = str;
  55006. }
  55007. return propertyPathCache[delimiter][str];
  55008. }
  55009. module.exports.getComponentPropertyPath = getComponentPropertyPath;
  55010. module.exports.propertyPathCache = propertyPathCache;
  55011. /**
  55012. * Get component property using encoded component name + component property name with a
  55013. * delimiter.
  55014. */
  55015. module.exports.getComponentProperty = function (el, name, delimiter) {
  55016. var splitName;
  55017. delimiter = delimiter || '.';
  55018. if (name.indexOf(delimiter) !== -1) {
  55019. splitName = getComponentPropertyPath(name, delimiter);
  55020. if (splitName.constructor === String) {
  55021. return el.getAttribute(splitName);
  55022. }
  55023. return el.getAttribute(splitName[0])[splitName[1]];
  55024. }
  55025. return el.getAttribute(name);
  55026. };
  55027. /**
  55028. * Set component property using encoded component name + component property name with a
  55029. * delimiter.
  55030. */
  55031. module.exports.setComponentProperty = function (el, name, value, delimiter) {
  55032. var splitName;
  55033. delimiter = delimiter || '.';
  55034. if (name.indexOf(delimiter) !== -1) {
  55035. splitName = getComponentPropertyPath(name, delimiter);
  55036. if (splitName.constructor === String) {
  55037. el.setAttribute(splitName, value);
  55038. } else {
  55039. el.setAttribute(splitName[0], splitName[1], value);
  55040. }
  55041. return;
  55042. }
  55043. el.setAttribute(name, value);
  55044. };
  55045. },{}],175:[function(_dereq_,module,exports){
  55046. module.exports = function forceCanvasResizeSafariMobile (canvasEl) {
  55047. var width = canvasEl.style.width;
  55048. var height = canvasEl.style.height;
  55049. // Taken from webvr-polyfill (https://github.com/borismus/webvr-polyfill/blob/85f657cd502ec9417bf26b87c3cb2afa6a70e079/src/util.js#L200)
  55050. // iOS only workaround for https://bugs.webkit.org/show_bug.cgi?id=152556
  55051. // By changing the size 1 pixel and restoring the previous value
  55052. // we trigger a size recalculation cycle.
  55053. canvasEl.style.width = (parseInt(width, 10) + 1) + 'px';
  55054. canvasEl.style.height = (parseInt(height, 10) + 1) + 'px';
  55055. setTimeout(function () {
  55056. canvasEl.style.width = width;
  55057. canvasEl.style.height = height;
  55058. }, 200);
  55059. };
  55060. },{}],176:[function(_dereq_,module,exports){
  55061. /* global location */
  55062. /* Centralized place to reference utilities since utils is exposed to the user. */
  55063. var debug = _dereq_('./debug');
  55064. var deepAssign = _dereq_('deep-assign');
  55065. var device = _dereq_('./device');
  55066. var objectAssign = _dereq_('object-assign');
  55067. var objectPool = _dereq_('./object-pool');
  55068. var warn = debug('utils:warn');
  55069. module.exports.bind = _dereq_('./bind');
  55070. module.exports.coordinates = _dereq_('./coordinates');
  55071. module.exports.debug = debug;
  55072. module.exports.device = device;
  55073. module.exports.entity = _dereq_('./entity');
  55074. module.exports.forceCanvasResizeSafariMobile = _dereq_('./forceCanvasResizeSafariMobile');
  55075. module.exports.isIE11 = _dereq_('./is-ie11');
  55076. module.exports.material = _dereq_('./material');
  55077. module.exports.objectPool = objectPool;
  55078. module.exports.split = _dereq_('./split').split;
  55079. module.exports.styleParser = _dereq_('./styleParser');
  55080. module.exports.trackedControls = _dereq_('./tracked-controls');
  55081. module.exports.checkHeadsetConnected = function () {
  55082. warn('`utils.checkHeadsetConnected` has moved to `utils.device.checkHeadsetConnected`');
  55083. return device.checkHeadsetConnected(arguments);
  55084. };
  55085. module.exports.isGearVR = module.exports.device.isGearVR = function () {
  55086. warn('`utils.isGearVR` has been deprecated, use `utils.device.isMobileVR`');
  55087. };
  55088. module.exports.isIOS = function () {
  55089. warn('`utils.isIOS` has moved to `utils.device.isIOS`');
  55090. return device.isIOS(arguments);
  55091. };
  55092. module.exports.isOculusGo = module.exports.device.isOculusGo = function () {
  55093. warn('`utils.isOculusGo` has been deprecated, use `utils.device.isMobileVR`');
  55094. };
  55095. module.exports.isMobile = function () {
  55096. warn('`utils.isMobile has moved to `utils.device.isMobile`');
  55097. return device.isMobile(arguments);
  55098. };
  55099. /**
  55100. * Returns throttle function that gets called at most once every interval.
  55101. *
  55102. * @param {function} functionToThrottle
  55103. * @param {number} minimumInterval - Minimal interval between calls (milliseconds).
  55104. * @param {object} optionalContext - If given, bind function to throttle to this context.
  55105. * @returns {function} Throttled function.
  55106. */
  55107. module.exports.throttle = function (functionToThrottle, minimumInterval, optionalContext) {
  55108. var lastTime;
  55109. if (optionalContext) {
  55110. functionToThrottle = module.exports.bind(functionToThrottle, optionalContext);
  55111. }
  55112. return function () {
  55113. var time = Date.now();
  55114. var sinceLastTime = typeof lastTime === 'undefined' ? minimumInterval : time - lastTime;
  55115. if (typeof lastTime === 'undefined' || (sinceLastTime >= minimumInterval)) {
  55116. lastTime = time;
  55117. functionToThrottle.apply(null, arguments);
  55118. }
  55119. };
  55120. };
  55121. /**
  55122. * Returns throttle function that gets called at most once every interval.
  55123. * Uses the time/timeDelta timestamps provided by the global render loop for better perf.
  55124. *
  55125. * @param {function} functionToThrottle
  55126. * @param {number} minimumInterval - Minimal interval between calls (milliseconds).
  55127. * @param {object} optionalContext - If given, bind function to throttle to this context.
  55128. * @returns {function} Throttled function.
  55129. */
  55130. module.exports.throttleTick = function (functionToThrottle, minimumInterval, optionalContext) {
  55131. var lastTime;
  55132. if (optionalContext) {
  55133. functionToThrottle = module.exports.bind(functionToThrottle, optionalContext);
  55134. }
  55135. return function (time, delta) {
  55136. var sinceLastTime = typeof lastTime === 'undefined' ? delta : time - lastTime;
  55137. if (typeof lastTime === 'undefined' || (sinceLastTime >= minimumInterval)) {
  55138. lastTime = time;
  55139. functionToThrottle(time, sinceLastTime);
  55140. }
  55141. };
  55142. };
  55143. /**
  55144. * Returns debounce function that gets called only once after a set of repeated calls.
  55145. *
  55146. * @param {function} functionToDebounce
  55147. * @param {number} wait - Time to wait for repeated function calls (milliseconds).
  55148. * @param {boolean} immediate - Calls the function immediately regardless of if it should be waiting.
  55149. * @returns {function} Debounced function.
  55150. */
  55151. module.exports.debounce = function (func, wait, immediate) {
  55152. var timeout;
  55153. return function () {
  55154. var context = this;
  55155. var args = arguments;
  55156. var later = function () {
  55157. timeout = null;
  55158. if (!immediate) func.apply(context, args);
  55159. };
  55160. var callNow = immediate && !timeout;
  55161. clearTimeout(timeout);
  55162. timeout = setTimeout(later, wait);
  55163. if (callNow) func.apply(context, args);
  55164. };
  55165. };
  55166. /**
  55167. * Mix the properties of source object(s) into a destination object.
  55168. *
  55169. * @param {object} dest - The object to which properties will be copied.
  55170. * @param {...object} source - The object(s) from which properties will be copied.
  55171. */
  55172. module.exports.extend = objectAssign;
  55173. module.exports.extendDeep = deepAssign;
  55174. module.exports.clone = function (obj) {
  55175. return JSON.parse(JSON.stringify(obj));
  55176. };
  55177. /**
  55178. * Checks if two values are equal.
  55179. * Includes objects and arrays and nested objects and arrays.
  55180. * Try to keep this function performant as it will be called often to see if a component
  55181. * should be updated.
  55182. *
  55183. * @param {object} a - First object.
  55184. * @param {object} b - Second object.
  55185. * @returns {boolean} Whether two objects are deeply equal.
  55186. */
  55187. var deepEqual = (function () {
  55188. var arrayPool = objectPool.createPool(function () { return []; });
  55189. return function (a, b) {
  55190. var key;
  55191. var keysA;
  55192. var keysB;
  55193. var i;
  55194. var valA;
  55195. var valB;
  55196. // If not objects or arrays, compare as values.
  55197. if (a === undefined || b === undefined || a === null || b === null ||
  55198. !(a && b && (a.constructor === Object && b.constructor === Object) ||
  55199. (a.constructor === Array && b.constructor === Array))) {
  55200. return a === b;
  55201. }
  55202. // Different number of keys, not equal.
  55203. keysA = arrayPool.use();
  55204. keysB = arrayPool.use();
  55205. keysA.length = 0;
  55206. keysB.length = 0;
  55207. for (key in a) { keysA.push(key); }
  55208. for (key in b) { keysB.push(key); }
  55209. if (keysA.length !== keysB.length) {
  55210. arrayPool.recycle(keysA);
  55211. arrayPool.recycle(keysB);
  55212. return false;
  55213. }
  55214. // Return `false` at the first sign of inequality.
  55215. for (i = 0; i < keysA.length; ++i) {
  55216. valA = a[keysA[i]];
  55217. valB = b[keysA[i]];
  55218. // Check nested array and object.
  55219. if ((typeof valA === 'object' || typeof valB === 'object') ||
  55220. (Array.isArray(valA) && Array.isArray(valB))) {
  55221. if (valA === valB) { continue; }
  55222. if (!deepEqual(valA, valB)) {
  55223. arrayPool.recycle(keysA);
  55224. arrayPool.recycle(keysB);
  55225. return false;
  55226. }
  55227. } else if (valA !== valB) {
  55228. arrayPool.recycle(keysA);
  55229. arrayPool.recycle(keysB);
  55230. return false;
  55231. }
  55232. }
  55233. arrayPool.recycle(keysA);
  55234. arrayPool.recycle(keysB);
  55235. return true;
  55236. };
  55237. })();
  55238. module.exports.deepEqual = deepEqual;
  55239. /**
  55240. * Computes the difference between two objects.
  55241. *
  55242. * @param {object} a - First object to compare (e.g., oldData).
  55243. * @param {object} b - Second object to compare (e.g., newData).
  55244. * @returns {object}
  55245. * Difference object where set of keys note which values were not equal, and values are
  55246. * `b`'s values.
  55247. */
  55248. module.exports.diff = (function () {
  55249. var keys = [];
  55250. return function (a, b, targetObject) {
  55251. var aVal;
  55252. var bVal;
  55253. var bKey;
  55254. var diff;
  55255. var key;
  55256. var i;
  55257. var isComparingObjects;
  55258. diff = targetObject || {};
  55259. // Collect A keys.
  55260. keys.length = 0;
  55261. for (key in a) { keys.push(key); }
  55262. if (!b) { return diff; }
  55263. // Collect B keys.
  55264. for (bKey in b) {
  55265. if (keys.indexOf(bKey) === -1) {
  55266. keys.push(bKey);
  55267. }
  55268. }
  55269. for (i = 0; i < keys.length; i++) {
  55270. key = keys[i];
  55271. aVal = a[key];
  55272. bVal = b[key];
  55273. isComparingObjects = aVal && bVal &&
  55274. aVal.constructor === Object && bVal.constructor === Object;
  55275. if ((isComparingObjects && !deepEqual(aVal, bVal)) ||
  55276. (!isComparingObjects && aVal !== bVal)) {
  55277. diff[key] = bVal;
  55278. }
  55279. }
  55280. return diff;
  55281. };
  55282. })();
  55283. /**
  55284. * Returns whether we should capture this keyboard event for keyboard shortcuts.
  55285. * @param {Event} event Event object.
  55286. * @returns {Boolean} Whether the key event should be captured.
  55287. */
  55288. module.exports.shouldCaptureKeyEvent = function (event) {
  55289. if (event.metaKey) { return false; }
  55290. return document.activeElement === document.body;
  55291. };
  55292. /**
  55293. * Splits a string into an array based on a delimiter.
  55294. *
  55295. * @param {string=} [str=''] Source string
  55296. * @param {string=} [delimiter=' '] Delimiter to use
  55297. * @returns {array} Array of delimited strings
  55298. */
  55299. module.exports.splitString = function (str, delimiter) {
  55300. if (typeof delimiter === 'undefined') { delimiter = ' '; }
  55301. // First collapse the whitespace (or whatever the delimiter is).
  55302. var regex = new RegExp(delimiter, 'g');
  55303. str = (str || '').replace(regex, delimiter);
  55304. // Then split.
  55305. return str.split(delimiter);
  55306. };
  55307. /**
  55308. * Extracts data from the element given an object that contains expected keys.
  55309. *
  55310. * @param {Element} Source element.
  55311. * @param {Object} [defaults={}] Object of default key-value pairs.
  55312. * @returns {Object}
  55313. */
  55314. module.exports.getElData = function (el, defaults) {
  55315. defaults = defaults || {};
  55316. var data = {};
  55317. Object.keys(defaults).forEach(copyAttribute);
  55318. function copyAttribute (key) {
  55319. if (el.hasAttribute(key)) {
  55320. data[key] = el.getAttribute(key);
  55321. }
  55322. }
  55323. return data;
  55324. };
  55325. /**
  55326. * Retrieves querystring value.
  55327. * @param {String} name Name of querystring key.
  55328. * @return {String} Value
  55329. */
  55330. module.exports.getUrlParameter = function (name) {
  55331. // eslint-disable-next-line no-useless-escape
  55332. name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
  55333. var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
  55334. var results = regex.exec(location.search);
  55335. return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
  55336. };
  55337. /**
  55338. * Detects whether context is within iframe.
  55339. */
  55340. module.exports.isIframed = function () {
  55341. return window.top !== window.self;
  55342. };
  55343. /**
  55344. * Finds all elements under the element that have the isScene
  55345. * property set to true
  55346. */
  55347. module.exports.findAllScenes = function (el) {
  55348. var matchingElements = [];
  55349. var allElements = el.getElementsByTagName('*');
  55350. for (var i = 0, n = allElements.length; i < n; i++) {
  55351. if (allElements[i].isScene) {
  55352. // Element exists with isScene set.
  55353. matchingElements.push(allElements[i]);
  55354. }
  55355. }
  55356. return matchingElements;
  55357. };
  55358. // Must be at bottom to avoid circular dependency.
  55359. module.exports.srcLoader = _dereq_('./src-loader');
  55360. },{"./bind":170,"./coordinates":171,"./debug":172,"./device":173,"./entity":174,"./forceCanvasResizeSafariMobile":175,"./is-ie11":177,"./material":179,"./object-pool":180,"./split":181,"./src-loader":182,"./styleParser":183,"./tracked-controls":184,"deep-assign":10,"object-assign":25}],177:[function(_dereq_,module,exports){
  55361. // https://stackoverflow.com/a/17907562
  55362. function getInternetExplorerVersion () {
  55363. var version = -1;
  55364. var userAgent = navigator.userAgent;
  55365. var re;
  55366. if (navigator.appName === 'Microsoft Internet Explorer') {
  55367. re = new RegExp('MSIE ([0-9]{1,}[\\.0-9]{0,})');
  55368. if (re.exec(userAgent) != null) { version = parseFloat(RegExp.$1); }
  55369. } else if (navigator.appName === 'Netscape') {
  55370. re = new RegExp('Trident/.*rv:([0-9]{1,}[\\.0-9]{0,})');
  55371. if (re.exec(userAgent) != null) { version = parseFloat(RegExp.$1); }
  55372. }
  55373. return version;
  55374. }
  55375. module.exports = getInternetExplorerVersion() === 11;
  55376. },{}],178:[function(_dereq_,module,exports){
  55377. /**
  55378. * Check if device is iOS and older than version 10.
  55379. */
  55380. module.exports = function isIOSOlderThan10 (userAgent) {
  55381. return /(iphone|ipod|ipad).*os.(7_|8_|9_)/i.test(userAgent);
  55382. };
  55383. },{}],179:[function(_dereq_,module,exports){
  55384. var THREE = _dereq_('../lib/three');
  55385. var HLS_MIMETYPES = ['application/x-mpegurl', 'application/vnd.apple.mpegurl'];
  55386. var COLOR_MAPS = new Set([
  55387. 'emissiveMap',
  55388. 'envMap',
  55389. 'map',
  55390. 'specularMap'
  55391. ]);
  55392. /**
  55393. * Update `material` texture property (usually but not always `map`)
  55394. * from `data` property (usually but not always `src`)
  55395. *
  55396. * @param {object} shader - A-Frame shader instance.
  55397. * @param {object} data
  55398. */
  55399. module.exports.updateMapMaterialFromData = function (materialName, dataName, shader, data) {
  55400. var el = shader.el;
  55401. var material = shader.material;
  55402. var rendererSystem = el.sceneEl.systems.renderer;
  55403. var src = data[dataName];
  55404. // Because a single material / shader may have multiple textures,
  55405. // we need to remember the source value for this data property
  55406. // to avoid redundant operations which can be expensive otherwise
  55407. // (e.g. video texture loads).
  55408. if (!shader.materialSrcs) { shader.materialSrcs = {}; }
  55409. if (!src) {
  55410. // Forget the prior material src.
  55411. delete shader.materialSrcs[materialName];
  55412. // Remove the texture.
  55413. setMap(null);
  55414. return;
  55415. }
  55416. // Don't process if material src hasn't changed.
  55417. if (src === shader.materialSrcs[materialName]) { return; }
  55418. // Remember the new src for this texture (there may be multiple).
  55419. shader.materialSrcs[materialName] = src;
  55420. // If the new material src is already a texture, just use it.
  55421. if (src instanceof THREE.Texture) { setMap(src); } else {
  55422. // Load texture for the new material src.
  55423. // (And check if we should still use it once available in callback.)
  55424. el.sceneEl.systems.material.loadTexture(src,
  55425. {src: src, repeat: data.repeat, offset: data.offset, npot: data.npot},
  55426. checkSetMap);
  55427. }
  55428. function checkSetMap (texture) {
  55429. // If the source has been changed, don't use loaded texture.
  55430. if (shader.materialSrcs[materialName] !== src) { return; }
  55431. setMap(texture);
  55432. }
  55433. function setMap (texture) {
  55434. material[materialName] = texture;
  55435. if (texture && COLOR_MAPS.has(materialName)) {
  55436. rendererSystem.applyColorCorrection(texture);
  55437. }
  55438. material.needsUpdate = true;
  55439. handleTextureEvents(el, texture);
  55440. }
  55441. };
  55442. /**
  55443. * Update `material.map` given `data.src`. For standard and flat shaders.
  55444. *
  55445. * @param {object} shader - A-Frame shader instance.
  55446. * @param {object} data
  55447. */
  55448. module.exports.updateMap = function (shader, data) {
  55449. return module.exports.updateMapMaterialFromData('map', 'src', shader, data);
  55450. };
  55451. /**
  55452. * Updates the material's maps which give the illusion of extra geometry.
  55453. *
  55454. * @param {string} longType - The friendly name of the map from the component e.g. ambientOcclusionMap becomes aoMap in THREE.js
  55455. * @param {object} shader - A-Frame shader instance
  55456. * @param {object} data
  55457. */
  55458. module.exports.updateDistortionMap = function (longType, shader, data) {
  55459. var shortType = longType;
  55460. if (longType === 'ambientOcclusion') { shortType = 'ao'; }
  55461. var el = shader.el;
  55462. var material = shader.material;
  55463. var rendererSystem = el.sceneEl.systems.renderer;
  55464. var src = data[longType + 'Map'];
  55465. var info = {};
  55466. info.src = src;
  55467. // Pass through the repeat and offset to be handled by the material loader.
  55468. info.offset = data[longType + 'TextureOffset'];
  55469. info.repeat = data[longType + 'TextureRepeat'];
  55470. info.wrap = data[longType + 'TextureWrap'];
  55471. if (src) {
  55472. if (src === shader[longType + 'TextureSrc']) { return; }
  55473. // Texture added or changed.
  55474. shader[longType + 'TextureSrc'] = src;
  55475. el.sceneEl.systems.material.loadTexture(src, info, setMap);
  55476. return;
  55477. }
  55478. // Texture removed.
  55479. if (!material.map) { return; }
  55480. setMap(null);
  55481. function setMap (texture) {
  55482. var slot = shortType + 'Map';
  55483. material[slot] = texture;
  55484. if (texture && COLOR_MAPS.has(slot)) {
  55485. rendererSystem.applyColorCorrection(texture);
  55486. }
  55487. material.needsUpdate = true;
  55488. handleTextureEvents(el, texture);
  55489. }
  55490. };
  55491. /**
  55492. * Emit event on entities on texture-related events.
  55493. *
  55494. * @param {Element} el - Entity.
  55495. * @param {object} texture - three.js Texture.
  55496. */
  55497. function handleTextureEvents (el, texture) {
  55498. if (!texture) { return; }
  55499. el.emit('materialtextureloaded', {src: texture.image, texture: texture});
  55500. // Video events.
  55501. if (!texture.image || texture.image.tagName !== 'VIDEO') { return; }
  55502. texture.image.addEventListener('loadeddata', function emitVideoTextureLoadedDataAll () {
  55503. // Check to see if we need to use iOS 10 HLS shader.
  55504. // Only override the shader if it is stock shader that we know doesn't correct.
  55505. if (!el.components || !el.components.material) { return; }
  55506. if (texture.needsCorrectionBGRA && texture.needsCorrectionFlipY &&
  55507. ['standard', 'flat'].indexOf(el.components.material.data.shader) !== -1) {
  55508. el.setAttribute('material', 'shader', 'ios10hls');
  55509. }
  55510. el.emit('materialvideoloadeddata', {src: texture.image, texture: texture});
  55511. });
  55512. texture.image.addEventListener('ended', function emitVideoTextureEndedAll () {
  55513. // Works for non-looping videos only.
  55514. el.emit('materialvideoended', {src: texture.image, texture: texture});
  55515. });
  55516. }
  55517. module.exports.handleTextureEvents = handleTextureEvents;
  55518. /**
  55519. * Given video element src and type, guess whether stream is HLS.
  55520. *
  55521. * @param {string} src - src from video element (generally URL to content).
  55522. * @param {string} type - type from video element (generally MIME type if present).
  55523. */
  55524. module.exports.isHLS = function (src, type) {
  55525. if (type && HLS_MIMETYPES.includes(type.toLowerCase())) { return true; }
  55526. if (src && src.toLowerCase().indexOf('.m3u8') > 0) { return true; }
  55527. return false;
  55528. };
  55529. },{"../lib/three":151}],180:[function(_dereq_,module,exports){
  55530. /*
  55531. Adapted deePool by Kyle Simpson.
  55532. MIT License: http://getify.mit-license.org
  55533. */
  55534. var EMPTY_SLOT = Object.freeze(Object.create(null));
  55535. // Default object factory.
  55536. function defaultObjectFactory () { return {}; }
  55537. /**
  55538. * Create a new pool.
  55539. */
  55540. module.exports.createPool = function createPool (objectFactory) {
  55541. var objPool = [];
  55542. var nextFreeSlot = null; // Pool location to look for a free object to use.
  55543. objectFactory = objectFactory || defaultObjectFactory;
  55544. function use () {
  55545. var objToUse;
  55546. if (nextFreeSlot === null || nextFreeSlot === objPool.length) {
  55547. grow(objPool.length || 5);
  55548. }
  55549. objToUse = objPool[nextFreeSlot];
  55550. objPool[nextFreeSlot++] = EMPTY_SLOT;
  55551. clearObject(objToUse);
  55552. return objToUse;
  55553. }
  55554. function recycle (obj) {
  55555. if (!(obj instanceof Object)) { return; }
  55556. if (nextFreeSlot === null || nextFreeSlot === -1) {
  55557. objPool[objPool.length] = obj;
  55558. return;
  55559. }
  55560. objPool[--nextFreeSlot] = obj;
  55561. }
  55562. function grow (count) {
  55563. var currentLength;
  55564. var i;
  55565. count = count === undefined ? objPool.length : count;
  55566. if (count > 0 && nextFreeSlot == null) {
  55567. nextFreeSlot = 0;
  55568. }
  55569. if (count > 0) {
  55570. currentLength = objPool.length;
  55571. objPool.length += Number(count);
  55572. for (i = currentLength; i < objPool.length; i++) {
  55573. // Add new obj to pool.
  55574. objPool[i] = objectFactory();
  55575. }
  55576. }
  55577. return objPool.length;
  55578. }
  55579. function size () {
  55580. return objPool.length;
  55581. }
  55582. return {
  55583. grow: grow,
  55584. pool: objPool,
  55585. recycle: recycle,
  55586. size: size,
  55587. use: use
  55588. };
  55589. };
  55590. function clearObject (obj) {
  55591. var key;
  55592. if (!obj || obj.constructor !== Object) { return; }
  55593. for (key in obj) { obj[key] = undefined; }
  55594. }
  55595. module.exports.clearObject = clearObject;
  55596. function removeUnusedKeys (obj, schema) {
  55597. var key;
  55598. if (!obj || obj.constructor !== Object) { return; }
  55599. for (key in obj) {
  55600. if (!(key in schema)) {
  55601. delete obj[key];
  55602. }
  55603. }
  55604. }
  55605. module.exports.removeUnusedKeys = removeUnusedKeys;
  55606. },{}],181:[function(_dereq_,module,exports){
  55607. /**
  55608. * String split with cached result.
  55609. */
  55610. module.exports.split = (function () {
  55611. var splitCache = {};
  55612. return function (str, delimiter) {
  55613. if (!(delimiter in splitCache)) { splitCache[delimiter] = {}; }
  55614. if (str in splitCache[delimiter]) { return splitCache[delimiter][str]; }
  55615. splitCache[delimiter][str] = str.split(delimiter);
  55616. return splitCache[delimiter][str];
  55617. };
  55618. })();
  55619. },{}],182:[function(_dereq_,module,exports){
  55620. /* global Image, XMLHttpRequest */
  55621. var debug = _dereq_('./debug');
  55622. var warn = debug('utils:src-loader:warn');
  55623. /**
  55624. * Validate a texture, either as a selector or as a URL.
  55625. * Detects whether `src` is pointing to an image or video and invokes the appropriate
  55626. * callback.
  55627. *
  55628. * `src` will be passed into the callback
  55629. *
  55630. * @params {string|Element} src - URL or media element.
  55631. * @params {function} isImageCb - callback if texture is an image.
  55632. * @params {function} isVideoCb - callback if texture is a video.
  55633. */
  55634. function validateSrc (src, isImageCb, isVideoCb) {
  55635. checkIsImage(src, function isAnImageUrl (isImage) {
  55636. if (isImage) {
  55637. isImageCb(src);
  55638. return;
  55639. }
  55640. isVideoCb(src);
  55641. });
  55642. }
  55643. /**
  55644. * Validates six images as a cubemap, either as selector or comma-separated
  55645. * URLs.
  55646. *
  55647. * @param {string} src - A selector or comma-separated image URLs. Image URLs
  55648. must be wrapped by `url()`.
  55649. * @param {string} src - A selector or comma-separated image URLs. Image URLs
  55650. must be wrapped by `url()`.
  55651. */
  55652. function validateCubemapSrc (src, cb) {
  55653. var aCubemap;
  55654. var cubemapSrcRegex = '';
  55655. var i;
  55656. var urls;
  55657. var validatedUrls = [];
  55658. for (i = 0; i < 5; i++) {
  55659. cubemapSrcRegex += '(url\\((?:[^\\)]+)\\),\\s*)';
  55660. }
  55661. cubemapSrcRegex += '(url\\((?:[^\\)]+)\\)\\s*)';
  55662. urls = src.match(new RegExp(cubemapSrcRegex));
  55663. // `src` is a comma-separated list of URLs.
  55664. // In this case, re-use validateSrc for each side of the cube.
  55665. function isImageCb (url) {
  55666. validatedUrls.push(url);
  55667. if (validatedUrls.length === 6) {
  55668. cb(validatedUrls);
  55669. }
  55670. }
  55671. if (urls) {
  55672. for (i = 1; i < 7; i++) {
  55673. validateSrc(parseUrl(urls[i]), isImageCb);
  55674. }
  55675. return;
  55676. }
  55677. // `src` is a query selector to <a-cubemap> containing six $([src])s.
  55678. aCubemap = validateAndGetQuerySelector(src);
  55679. if (!aCubemap) { return; }
  55680. if (aCubemap.tagName === 'A-CUBEMAP' && aCubemap.srcs) {
  55681. return cb(aCubemap.srcs);
  55682. }
  55683. // Else if aCubeMap is not a <a-cubemap>.
  55684. warn('Selector "%s" does not point to <a-cubemap>', src);
  55685. }
  55686. /**
  55687. * Parses src from `url(src)`.
  55688. * @param {string} src - String to parse.
  55689. * @return {string} The parsed src, if parseable.
  55690. */
  55691. function parseUrl (src) {
  55692. var parsedSrc = src.match(/\url\((.+)\)/);
  55693. if (!parsedSrc) { return; }
  55694. return parsedSrc[1];
  55695. }
  55696. /**
  55697. * Call back whether `src` is an image.
  55698. *
  55699. * @param {string|Element} src - URL or element that will be tested.
  55700. * @param {function} onResult - Callback with whether `src` is an image.
  55701. */
  55702. function checkIsImage (src, onResult) {
  55703. var request;
  55704. if (src.tagName) {
  55705. onResult(src.tagName === 'IMG');
  55706. return;
  55707. }
  55708. request = new XMLHttpRequest();
  55709. // Try to send HEAD request to check if image first.
  55710. request.open('HEAD', src);
  55711. request.addEventListener('load', function (event) {
  55712. var contentType;
  55713. if (request.status >= 200 && request.status < 300) {
  55714. contentType = request.getResponseHeader('Content-Type');
  55715. if (contentType == null) {
  55716. checkIsImageFallback(src, onResult);
  55717. } else {
  55718. if (contentType.startsWith('image')) {
  55719. onResult(true);
  55720. } else {
  55721. onResult(false);
  55722. }
  55723. }
  55724. } else {
  55725. checkIsImageFallback(src, onResult);
  55726. }
  55727. request.abort();
  55728. });
  55729. request.send();
  55730. }
  55731. function checkIsImageFallback (src, onResult) {
  55732. var tester = new Image();
  55733. tester.addEventListener('load', onLoad);
  55734. function onLoad () { onResult(true); }
  55735. tester.addEventListener('error', onError);
  55736. function onError () { onResult(false); }
  55737. tester.src = src;
  55738. }
  55739. /**
  55740. * Query and validate a query selector,
  55741. *
  55742. * @param {string} selector - DOM selector.
  55743. * @return {object|null|undefined} Selected DOM element if exists.
  55744. null if query yields no results.
  55745. undefined if `selector` is not a valid selector.
  55746. */
  55747. function validateAndGetQuerySelector (selector) {
  55748. try {
  55749. var el = document.querySelector(selector);
  55750. if (!el) {
  55751. warn('No element was found matching the selector: "%s"', selector);
  55752. }
  55753. return el;
  55754. } catch (e) { // Capture exception if it's not a valid selector.
  55755. warn('"%s" is not a valid selector', selector);
  55756. return undefined;
  55757. }
  55758. }
  55759. module.exports = {
  55760. parseUrl: parseUrl,
  55761. validateSrc: validateSrc,
  55762. validateCubemapSrc: validateCubemapSrc
  55763. };
  55764. },{"./debug":172}],183:[function(_dereq_,module,exports){
  55765. /**
  55766. * Utils for parsing style-like strings (e.g., "primitive: box; width: 5; height: 4.5").
  55767. * Some code adapted from `style-attr` (https://github.com/joshwnj/style-attr)
  55768. * by Josh Johnston (MIT License).
  55769. */
  55770. var DASH_REGEX = /-([a-z])/g;
  55771. /**
  55772. * Deserialize style-like string into an object of properties.
  55773. *
  55774. * @param {string} value - HTML attribute value.
  55775. * @param {object} obj - Reused object for object pooling.
  55776. * @returns {object} Property data.
  55777. */
  55778. module.exports.parse = function (value, obj) {
  55779. var parsedData;
  55780. if (typeof value !== 'string') { return value; }
  55781. parsedData = styleParse(value, obj);
  55782. // The style parser returns an object { "" : "test"} when fed a string
  55783. if (parsedData['']) { return value; }
  55784. return transformKeysToCamelCase(parsedData);
  55785. };
  55786. /**
  55787. * Serialize an object of properties into a style-like string.
  55788. *
  55789. * @param {object} data - Property data.
  55790. * @returns {string}
  55791. */
  55792. module.exports.stringify = function (data) {
  55793. if (typeof data === 'string') { return data; }
  55794. return styleStringify(data);
  55795. };
  55796. /**
  55797. * Converts string from hyphen to camelCase.
  55798. *
  55799. * @param {string} str - String to camelCase.
  55800. * @return {string} CamelCased string.
  55801. */
  55802. function toCamelCase (str) {
  55803. return str.replace(DASH_REGEX, upperCase);
  55804. }
  55805. module.exports.toCamelCase = toCamelCase;
  55806. /**
  55807. * Converts object's keys from hyphens to camelCase (e.g., `max-value` to
  55808. * `maxValue`).
  55809. *
  55810. * @param {object} obj - The object to camelCase keys.
  55811. * @return {object} The object with keys camelCased.
  55812. */
  55813. function transformKeysToCamelCase (obj) {
  55814. var camelKey;
  55815. var key;
  55816. for (key in obj) {
  55817. camelKey = toCamelCase(key);
  55818. if (key === camelKey) { continue; }
  55819. obj[camelKey] = obj[key];
  55820. delete obj[key];
  55821. }
  55822. return obj;
  55823. }
  55824. module.exports.transformKeysToCamelCase = transformKeysToCamelCase;
  55825. /**
  55826. * Split a string into chunks matching `<key>: <value>`
  55827. */
  55828. var getKeyValueChunks = (function () {
  55829. var chunks = [];
  55830. var hasUnclosedUrl = /url\([^)]+$/;
  55831. return function getKeyValueChunks (raw) {
  55832. var chunk = '';
  55833. var nextSplit;
  55834. var offset = 0;
  55835. var sep = ';';
  55836. chunks.length = 0;
  55837. while (offset < raw.length) {
  55838. nextSplit = raw.indexOf(sep, offset);
  55839. if (nextSplit === -1) { nextSplit = raw.length; }
  55840. chunk += raw.substring(offset, nextSplit);
  55841. // data URIs can contain semicolons, so make sure we get the whole thing
  55842. if (hasUnclosedUrl.test(chunk)) {
  55843. chunk += ';';
  55844. offset = nextSplit + 1;
  55845. continue;
  55846. }
  55847. chunks.push(chunk.trim());
  55848. chunk = '';
  55849. offset = nextSplit + 1;
  55850. }
  55851. return chunks;
  55852. };
  55853. })();
  55854. /**
  55855. * Convert a style attribute string to an object.
  55856. *
  55857. * @param {object} str - Attribute string.
  55858. * @param {object} obj - Object to reuse as a base, else a new one will be allocated.
  55859. */
  55860. function styleParse (str, obj) {
  55861. var chunks;
  55862. var i;
  55863. var item;
  55864. var pos;
  55865. var key;
  55866. var val;
  55867. obj = obj || {};
  55868. chunks = getKeyValueChunks(str);
  55869. for (i = 0; i < chunks.length; i++) {
  55870. item = chunks[i];
  55871. if (!item) { continue; }
  55872. // Split with `.indexOf` rather than `.split` because the value may also contain colons.
  55873. pos = item.indexOf(':');
  55874. key = item.substr(0, pos).trim();
  55875. val = item.substr(pos + 1).trim();
  55876. obj[key] = val;
  55877. }
  55878. return obj;
  55879. }
  55880. /**
  55881. * Convert an object into an attribute string
  55882. **/
  55883. function styleStringify (obj) {
  55884. var key;
  55885. var keyCount = 0;
  55886. var i = 0;
  55887. var str = '';
  55888. for (key in obj) { keyCount++; }
  55889. for (key in obj) {
  55890. str += (key + ': ' + obj[key]);
  55891. if (i < keyCount - 1) { str += '; '; }
  55892. i++;
  55893. }
  55894. return str;
  55895. }
  55896. function upperCase (str) { return str[1].toUpperCase(); }
  55897. },{}],184:[function(_dereq_,module,exports){
  55898. var DEFAULT_HANDEDNESS = _dereq_('../constants').DEFAULT_HANDEDNESS;
  55899. var AXIS_LABELS = ['x', 'y', 'z', 'w'];
  55900. var NUM_HANDS = 2; // Number of hands in a pair. Should always be 2.
  55901. /**
  55902. * Called on controller component `.play` handlers.
  55903. * Check if controller matches parameters and inject tracked-controls component.
  55904. * Handle event listeners.
  55905. * Generate controllerconnected or controllerdisconnected events.
  55906. *
  55907. * @param {object} component - Tracked controls component.
  55908. * @param {object} idPrefix - Prefix to match in gamepad id if any.
  55909. * @param {object} queryObject - Map of values to match.
  55910. */
  55911. module.exports.checkControllerPresentAndSetup = function (component, idPrefix, queryObject) {
  55912. var el = component.el;
  55913. var controller;
  55914. var hasWebXR = el.sceneEl.hasWebXR;
  55915. var isControllerPresent = hasWebXR ? isControllerPresentWebXR : isControllerPresentWebVR;
  55916. var isPresent;
  55917. controller = isControllerPresent(component, idPrefix, queryObject);
  55918. isPresent = !!controller;
  55919. // If component was previously paused and now playing, re-add event listeners.
  55920. // Handle the event listeners here since this helper method is control of calling
  55921. // `.addEventListeners` and `.removeEventListeners`.
  55922. if (component.controllerPresent && !component.controllerEventsActive && !hasWebXR) {
  55923. component.addEventListeners();
  55924. }
  55925. // Nothing changed, no need to do anything.
  55926. if (isPresent === component.controllerPresent) { return isPresent; }
  55927. component.controllerPresent = isPresent;
  55928. // Update controller presence.
  55929. if (isPresent) {
  55930. component.injectTrackedControls();
  55931. if (!hasWebXR) { component.addEventListeners(); }
  55932. el.emit('controllerconnected', {name: component.name, component: component});
  55933. } else {
  55934. component.removeEventListeners();
  55935. el.emit('controllerdisconnected', {name: component.name, component: component});
  55936. }
  55937. };
  55938. /**
  55939. * Enumerate controller (that have pose) and check if they match parameters for WebVR
  55940. *
  55941. * @param {object} component - Tracked controls component.
  55942. * @param {object} idPrefix - Prefix to match in gamepad id if any.
  55943. * @param {object} queryObject - Map of values to match.
  55944. */
  55945. function isControllerPresentWebVR (component, idPrefix, queryObject) {
  55946. var gamepads;
  55947. var sceneEl = component.el.sceneEl;
  55948. var trackedControlsSystem;
  55949. var filterControllerIndex = queryObject.index || 0;
  55950. if (!idPrefix) { return false; }
  55951. trackedControlsSystem = sceneEl && sceneEl.systems['tracked-controls-webvr'];
  55952. if (!trackedControlsSystem) { return false; }
  55953. gamepads = trackedControlsSystem.controllers;
  55954. if (!gamepads.length) { return false; }
  55955. return !!findMatchingControllerWebVR(gamepads, null, idPrefix, queryObject.hand,
  55956. filterControllerIndex);
  55957. }
  55958. /**
  55959. *
  55960. * @param {object} component - Tracked controls component.
  55961. */
  55962. function isControllerPresentWebXR (component, idPrefix, queryObject) {
  55963. var controllers;
  55964. var sceneEl = component.el.sceneEl;
  55965. var trackedControlsSystem = sceneEl && sceneEl.systems['tracked-controls-webxr'];
  55966. if (!trackedControlsSystem) { return false; }
  55967. controllers = trackedControlsSystem.controllers;
  55968. if (!controllers || !controllers.length) { return false; }
  55969. return findMatchingControllerWebXR(controllers, queryObject.hand);
  55970. }
  55971. module.exports.isControllerPresentWebVR = isControllerPresentWebVR;
  55972. module.exports.isControllerPresentWebXR = isControllerPresentWebXR;
  55973. /**
  55974. * Walk through the given controllers to find any where the device ID equals
  55975. * filterIdExact, or startsWith filterIdPrefix.
  55976. * A controller where this considered true is considered a 'match'.
  55977. *
  55978. * For each matching controller:
  55979. * If filterHand is set, and the controller:
  55980. * is handed, we further verify that controller.hand equals filterHand.
  55981. * is unhanded (controller.hand is ''), we skip until we have found a
  55982. * number of matching controllers that equals filterControllerIndex
  55983. * If filterHand is not set, we skip until we have found the nth matching
  55984. * controller, where n equals filterControllerIndex
  55985. *
  55986. * The method should be called with one of: [filterIdExact, filterIdPrefix] AND
  55987. * one or both of: [filterHand, filterControllerIndex]
  55988. *
  55989. * @param {object} controllers - Array of gamepads to search
  55990. * @param {string} filterIdExact - If set, used to find controllers with id === this value
  55991. * @param {string} filterIdPrefix - If set, used to find controllers with id startsWith this value
  55992. * @param {object} filterHand - If set, further filters controllers with matching 'hand' property
  55993. * @param {object} filterControllerIndex - Find the nth matching controller,
  55994. * where n equals filterControllerIndex. defaults to 0.
  55995. */
  55996. function findMatchingControllerWebVR (controllers, filterIdExact, filterIdPrefix, filterHand,
  55997. filterControllerIndex) {
  55998. var controller;
  55999. var i;
  56000. var matchingControllerOccurence = 0;
  56001. var targetControllerMatch = filterControllerIndex || 0;
  56002. for (i = 0; i < controllers.length; i++) {
  56003. controller = controllers[i];
  56004. // Determine if the controller ID matches our criteria.
  56005. if (filterIdPrefix && !controller.id.startsWith(filterIdPrefix)) {
  56006. continue;
  56007. }
  56008. if (!filterIdPrefix && controller.id !== filterIdExact) { continue; }
  56009. // If the hand filter and controller handedness are defined we compare them.
  56010. if (filterHand && controller.hand && filterHand !== controller.hand) { continue; }
  56011. // If we have detected an unhanded controller and the component was asking
  56012. // for a particular hand, we need to treat the controllers in the array as
  56013. // pairs of controllers. This effectively means that we need to skip
  56014. // NUM_HANDS matches for each controller number, instead of 1.
  56015. if (filterHand && !controller.hand) {
  56016. targetControllerMatch = NUM_HANDS * filterControllerIndex + ((filterHand === DEFAULT_HANDEDNESS) ? 0 : 1);
  56017. }
  56018. // We are looking for the nth occurence of a matching controller
  56019. // (n equals targetControllerMatch).
  56020. if (matchingControllerOccurence === targetControllerMatch) { return controller; }
  56021. ++matchingControllerOccurence;
  56022. }
  56023. return undefined;
  56024. }
  56025. function findMatchingControllerWebXR (controllers, handedness) {
  56026. var i;
  56027. var controllerHandedness;
  56028. for (i = 0; i < controllers.length; i++) {
  56029. controllerHandedness = controllers[i].handedness;
  56030. if (!handedness || (controllerHandedness === '' && handedness === 'right') ||
  56031. controllers[i].handedness === handedness) {
  56032. return controllers[i];
  56033. }
  56034. }
  56035. return undefined;
  56036. }
  56037. module.exports.findMatchingControllerWebVR = findMatchingControllerWebVR;
  56038. module.exports.findMatchingControllerWebXR = findMatchingControllerWebXR;
  56039. /**
  56040. * Emit specific `moved` event(s) if axes changed based on original axismoved event.
  56041. *
  56042. * @param {object} component - Controller component in use.
  56043. * @param {array} axesMapping - For example `{thumbstick: [0, 1]}`.
  56044. * @param {object} evt - Event to process.
  56045. */
  56046. module.exports.emitIfAxesChanged = function (component, axesMapping, evt) {
  56047. var axes;
  56048. var buttonType;
  56049. var changed;
  56050. var detail;
  56051. var j;
  56052. for (buttonType in axesMapping) {
  56053. axes = axesMapping[buttonType];
  56054. changed = false;
  56055. for (j = 0; j < axes.length; j++) {
  56056. if (evt.detail.changed[axes[j]]) { changed = true; }
  56057. }
  56058. if (!changed) { continue; }
  56059. // Axis has changed. Emit the specific moved event with axis values in detail.
  56060. detail = {};
  56061. for (j = 0; j < axes.length; j++) {
  56062. detail[AXIS_LABELS[j]] = evt.detail.axis[axes[j]];
  56063. }
  56064. component.el.emit(buttonType + 'moved', detail);
  56065. }
  56066. };
  56067. /**
  56068. * Handle a button event and reemits the events.
  56069. *
  56070. * @param {string} id - id of the button.
  56071. * @param {string} evtName - name of the reemitted event
  56072. * @param {object} component - reference to the component
  56073. * @param {string} hand - handedness of the controller: left or right.
  56074. */
  56075. module.exports.onButtonEvent = function (id, evtName, component, hand) {
  56076. var mapping = hand ? component.mapping[hand] : component.mapping;
  56077. var buttonName = mapping.buttons[id];
  56078. component.el.emit(buttonName + evtName);
  56079. if (component.updateModel) {
  56080. component.updateModel(buttonName, evtName);
  56081. }
  56082. };
  56083. },{"../constants":95}],185:[function(_dereq_,module,exports){
  56084. window.glStats = function () {
  56085. var _rS = null;
  56086. var _totalDrawArraysCalls = 0,
  56087. _totalDrawElementsCalls = 0,
  56088. _totalUseProgramCalls = 0,
  56089. _totalFaces = 0,
  56090. _totalVertices = 0,
  56091. _totalPoints = 0,
  56092. _totalBindTexures = 0;
  56093. function _h ( f, c ) {
  56094. return function () {
  56095. c.apply( this, arguments );
  56096. f.apply( this, arguments );
  56097. };
  56098. }
  56099. WebGLRenderingContext.prototype.drawArrays = _h( WebGLRenderingContext.prototype.drawArrays, function () {
  56100. _totalDrawArraysCalls++;
  56101. if ( arguments[ 0 ] == this.POINTS ) _totalPoints += arguments[ 2 ];
  56102. else _totalVertices += arguments[ 2 ];
  56103. } );
  56104. WebGLRenderingContext.prototype.drawElements = _h( WebGLRenderingContext.prototype.drawElements, function () {
  56105. _totalDrawElementsCalls++;
  56106. _totalFaces += arguments[ 1 ] / 3;
  56107. _totalVertices += arguments[ 1 ];
  56108. } );
  56109. WebGLRenderingContext.prototype.useProgram = _h( WebGLRenderingContext.prototype.useProgram, function () {
  56110. _totalUseProgramCalls++;
  56111. } );
  56112. WebGLRenderingContext.prototype.bindTexture = _h( WebGLRenderingContext.prototype.bindTexture, function () {
  56113. _totalBindTexures++;
  56114. } );
  56115. var _values = {
  56116. allcalls: {
  56117. over: 3000,
  56118. caption: 'Calls (hook)'
  56119. },
  56120. drawelements: {
  56121. caption: 'drawElements (hook)'
  56122. },
  56123. drawarrays: {
  56124. caption: 'drawArrays (hook)'
  56125. }
  56126. };
  56127. var _groups = [ {
  56128. caption: 'WebGL',
  56129. values: [ 'allcalls', 'drawelements', 'drawarrays', 'useprogram', 'bindtexture', 'glfaces', 'glvertices', 'glpoints' ]
  56130. } ];
  56131. var _fractions = [ {
  56132. base: 'allcalls',
  56133. steps: [ 'drawelements', 'drawarrays' ]
  56134. } ];
  56135. function _update () {
  56136. _rS( 'allcalls' ).set( _totalDrawArraysCalls + _totalDrawElementsCalls );
  56137. _rS( 'drawElements' ).set( _totalDrawElementsCalls );
  56138. _rS( 'drawArrays' ).set( _totalDrawArraysCalls );
  56139. _rS( 'bindTexture' ).set( _totalBindTexures );
  56140. _rS( 'useProgram' ).set( _totalUseProgramCalls );
  56141. _rS( 'glfaces' ).set( _totalFaces );
  56142. _rS( 'glvertices' ).set( _totalVertices );
  56143. _rS( 'glpoints' ).set( _totalPoints );
  56144. }
  56145. function _start () {
  56146. _totalDrawArraysCalls = 0;
  56147. _totalDrawElementsCalls = 0;
  56148. _totalUseProgramCalls = 0;
  56149. _totalFaces = 0;
  56150. _totalVertices = 0;
  56151. _totalPoints = 0;
  56152. _totalBindTexures = 0;
  56153. }
  56154. function _end () {}
  56155. function _attach ( r ) {
  56156. _rS = r;
  56157. }
  56158. return {
  56159. update: _update,
  56160. start: _start,
  56161. end: _end,
  56162. attach: _attach,
  56163. values: _values,
  56164. groups: _groups,
  56165. fractions: _fractions
  56166. };
  56167. };
  56168. window.threeStats = function ( renderer ) {
  56169. var _rS = null;
  56170. var _values = {
  56171. 'renderer.info.memory.geometries': {
  56172. caption: 'Geometries'
  56173. },
  56174. 'renderer.info.memory.textures': {
  56175. caption: 'Textures'
  56176. },
  56177. 'renderer.info.programs': {
  56178. caption: 'Programs'
  56179. },
  56180. 'renderer.info.render.calls': {
  56181. caption: 'Calls'
  56182. },
  56183. 'renderer.info.render.triangles': {
  56184. caption: 'Triangles',
  56185. over: 1000
  56186. },
  56187. 'renderer.info.render.points': {
  56188. caption: 'Points'
  56189. }
  56190. };
  56191. var _groups = [ {
  56192. caption: 'Three.js - Memory',
  56193. values: [ 'renderer.info.memory.geometries', 'renderer.info.programs', 'renderer.info.memory.textures' ]
  56194. }, {
  56195. caption: 'Three.js - Render',
  56196. values: [ 'renderer.info.render.calls', 'renderer.info.render.triangles', 'renderer.info.render.points' ]
  56197. } ];
  56198. var _fractions = [];
  56199. function _update () {
  56200. _rS( 'renderer.info.memory.geometries' ).set( renderer.info.memory.geometries );
  56201. _rS( 'renderer.info.programs' ).set( renderer.info.programs.length );
  56202. _rS( 'renderer.info.memory.textures' ).set( renderer.info.memory.textures );
  56203. _rS( 'renderer.info.render.calls' ).set( renderer.info.render.calls );
  56204. _rS( 'renderer.info.render.triangles' ).set( renderer.info.render.triangles );
  56205. _rS( 'renderer.info.render.points' ).set( renderer.info.render.points );
  56206. }
  56207. function _start () {}
  56208. function _end () {}
  56209. function _attach ( r ) {
  56210. _rS = r;
  56211. }
  56212. return {
  56213. update: _update,
  56214. start: _start,
  56215. end: _end,
  56216. attach: _attach,
  56217. values: _values,
  56218. groups: _groups,
  56219. fractions: _fractions
  56220. };
  56221. };
  56222. /*
  56223. * From https://github.com/paulirish/memory-stats.js
  56224. */
  56225. window.BrowserStats = function () {
  56226. var _rS = null;
  56227. var _usedJSHeapSize = 0,
  56228. _totalJSHeapSize = 0;
  56229. if ( window.performance && !performance.memory ) {
  56230. performance.memory = {
  56231. usedJSHeapSize: 0,
  56232. totalJSHeapSize: 0
  56233. };
  56234. }
  56235. if ( performance.memory.totalJSHeapSize === 0 ) {
  56236. console.warn( 'totalJSHeapSize === 0... performance.memory is only available in Chrome .' );
  56237. }
  56238. var _values = {
  56239. memory: {
  56240. caption: 'Used Memory',
  56241. average: true,
  56242. avgMs: 1000,
  56243. over: 22
  56244. },
  56245. total: {
  56246. caption: 'Total Memory'
  56247. }
  56248. };
  56249. var _groups = [ {
  56250. caption: 'Browser',
  56251. values: [ 'memory', 'total' ]
  56252. } ];
  56253. var _fractions = [ {
  56254. base: 'total',
  56255. steps: [ 'memory' ]
  56256. } ];
  56257. var log1024 = Math.log( 1024 );
  56258. function _size ( v ) {
  56259. var precision = 100; //Math.pow(10, 2);
  56260. var i = Math.floor( Math.log( v ) / log1024 );
  56261. return Math.round( v * precision / Math.pow( 1024, i ) ) / precision; // + ' ' + sizes[i];
  56262. }
  56263. function _update () {
  56264. _usedJSHeapSize = _size( performance.memory.usedJSHeapSize );
  56265. _totalJSHeapSize = _size( performance.memory.totalJSHeapSize );
  56266. _rS( 'memory' ).set( _usedJSHeapSize );
  56267. _rS( 'total' ).set( _totalJSHeapSize );
  56268. }
  56269. function _start () {
  56270. _usedJSHeapSize = 0;
  56271. }
  56272. function _end () {}
  56273. function _attach ( r ) {
  56274. _rS = r;
  56275. }
  56276. return {
  56277. update: _update,
  56278. start: _start,
  56279. end: _end,
  56280. attach: _attach,
  56281. values: _values,
  56282. groups: _groups,
  56283. fractions: _fractions
  56284. };
  56285. };
  56286. if (typeof module === 'object') {
  56287. module.exports = {
  56288. glStats: window.glStats,
  56289. threeStats: window.threeStats,
  56290. BrowserStats: window.BrowserStats
  56291. };
  56292. }
  56293. },{}],186:[function(_dereq_,module,exports){
  56294. // performance.now() polyfill from https://gist.github.com/paulirish/5438650
  56295. 'use strict';
  56296. ( function () {
  56297. if ( 'performance' in window == false ) {
  56298. window.performance = {};
  56299. }
  56300. var performance = window.performance;
  56301. if ( 'now' in performance == false ) {
  56302. var nowOffset = Date.now();
  56303. if ( performance.timing && performance.timing.navigationStart ) {
  56304. nowOffset = performance.timing.navigationStart;
  56305. }
  56306. performance.now = function now () {
  56307. return Date.now() - nowOffset;
  56308. };
  56309. }
  56310. if( !performance.mark ) {
  56311. performance.mark = function(){}
  56312. }
  56313. if( !performance.measure ) {
  56314. performance.measure = function(){}
  56315. }
  56316. } )();
  56317. window.rStats = function rStats ( settings ) {
  56318. function iterateKeys ( array, callback ) {
  56319. var keys = Object.keys( array );
  56320. for ( var j = 0, l = keys.length; j < l; j++ ) {
  56321. callback( keys[ j ] );
  56322. }
  56323. }
  56324. function importCSS ( url ) {
  56325. var element = document.createElement( 'link' );
  56326. element.href = url;
  56327. element.rel = 'stylesheet';
  56328. element.type = 'text/css';
  56329. document.getElementsByTagName( 'head' )[ 0 ].appendChild( element );
  56330. }
  56331. var _settings = settings || {};
  56332. var _colours = _settings.colours || [ '#850700', '#c74900', '#fcb300', '#284280', '#4c7c0c' ];
  56333. var _cssFont = 'https://fonts.googleapis.com/css?family=Roboto+Condensed:400,700,300';
  56334. var _cssRStats = ( _settings.CSSPath ? _settings.CSSPath : '' ) + 'rStats.css';
  56335. var _css = _settings.css || [ _cssFont, _cssRStats ];
  56336. _css.forEach(function (uri) {
  56337. importCSS( uri );
  56338. });
  56339. if ( !_settings.values ) _settings.values = {};
  56340. var _base, _div, _elHeight = 10, _elWidth = 200;
  56341. var _perfCounters = {};
  56342. function Graph ( _dom, _id, _defArg ) {
  56343. var _def = _defArg || {};
  56344. var _canvas = document.createElement( 'canvas' ),
  56345. _ctx = _canvas.getContext( '2d' ),
  56346. _max = 0,
  56347. _current = 0;
  56348. var c = _def.color ? _def.color : '#666666';
  56349. var _dotCanvas = document.createElement( 'canvas' ),
  56350. _dotCtx = _dotCanvas.getContext( '2d' );
  56351. _dotCanvas.width = 1;
  56352. _dotCanvas.height = 2 * _elHeight;
  56353. _dotCtx.fillStyle = '#444444';
  56354. _dotCtx.fillRect( 0, 0, 1, 2 * _elHeight );
  56355. _dotCtx.fillStyle = c;
  56356. _dotCtx.fillRect( 0, _elHeight, 1, _elHeight );
  56357. _dotCtx.fillStyle = '#ffffff';
  56358. _dotCtx.globalAlpha = 0.5;
  56359. _dotCtx.fillRect( 0, _elHeight, 1, 1 );
  56360. _dotCtx.globalAlpha = 1;
  56361. var _alarmCanvas = document.createElement( 'canvas' ),
  56362. _alarmCtx = _alarmCanvas.getContext( '2d' );
  56363. _alarmCanvas.width = 1;
  56364. _alarmCanvas.height = 2 * _elHeight;
  56365. _alarmCtx.fillStyle = '#444444';
  56366. _alarmCtx.fillRect( 0, 0, 1, 2 * _elHeight );
  56367. _alarmCtx.fillStyle = '#b70000';
  56368. _alarmCtx.fillRect( 0, _elHeight, 1, _elHeight );
  56369. _alarmCtx.globalAlpha = 0.5;
  56370. _alarmCtx.fillStyle = '#ffffff';
  56371. _alarmCtx.fillRect( 0, _elHeight, 1, 1 );
  56372. _alarmCtx.globalAlpha = 1;
  56373. function _init () {
  56374. _canvas.width = _elWidth;
  56375. _canvas.height = _elHeight;
  56376. _canvas.style.width = _canvas.width + 'px';
  56377. _canvas.style.height = _canvas.height + 'px';
  56378. _canvas.className = 'rs-canvas';
  56379. _dom.appendChild( _canvas );
  56380. _ctx.fillStyle = '#444444';
  56381. _ctx.fillRect( 0, 0, _canvas.width, _canvas.height );
  56382. }
  56383. function _draw ( v, alarm ) {
  56384. _current += ( v - _current ) * 0.1;
  56385. _max *= 0.99;
  56386. if ( _current > _max ) _max = _current;
  56387. _ctx.drawImage( _canvas, 1, 0, _canvas.width - 1, _canvas.height, 0, 0, _canvas.width - 1, _canvas.height );
  56388. if ( alarm ) {
  56389. _ctx.drawImage( _alarmCanvas, _canvas.width - 1, _canvas.height - _current * _canvas.height / _max - _elHeight );
  56390. } else {
  56391. _ctx.drawImage( _dotCanvas, _canvas.width - 1, _canvas.height - _current * _canvas.height / _max - _elHeight );
  56392. }
  56393. }
  56394. _init();
  56395. return {
  56396. draw: _draw
  56397. };
  56398. }
  56399. function StackGraph ( _dom, _num ) {
  56400. var _canvas = document.createElement( 'canvas' ),
  56401. _ctx = _canvas.getContext( '2d' );
  56402. function _init () {
  56403. _canvas.width = _elWidth;
  56404. _canvas.height = _elHeight * _num;
  56405. _canvas.style.width = _canvas.width + 'px';
  56406. _canvas.style.height = _canvas.height + 'px';
  56407. _canvas.className = 'rs-canvas';
  56408. _dom.appendChild( _canvas );
  56409. _ctx.fillStyle = '#444444';
  56410. _ctx.fillRect( 0, 0, _canvas.width, _canvas.height );
  56411. }
  56412. function _draw ( v ) {
  56413. _ctx.drawImage( _canvas, 1, 0, _canvas.width - 1, _canvas.height, 0, 0, _canvas.width - 1, _canvas.height );
  56414. var th = 0;
  56415. iterateKeys( v, function ( j ) {
  56416. var h = v[ j ] * _canvas.height;
  56417. _ctx.fillStyle = _colours[ j ];
  56418. _ctx.fillRect( _canvas.width - 1, th, 1, h );
  56419. th += h;
  56420. } );
  56421. }
  56422. _init();
  56423. return {
  56424. draw: _draw
  56425. };
  56426. }
  56427. function PerfCounter ( id, group ) {
  56428. var _id = id,
  56429. _time,
  56430. _value = 0,
  56431. _total = 0,
  56432. _averageValue = 0,
  56433. _accumValue = 0,
  56434. _accumStart = performance.now(),
  56435. _accumSamples = 0,
  56436. _dom = document.createElement( 'div' ),
  56437. _spanId = document.createElement( 'span' ),
  56438. _spanValue = document.createElement( 'div' ),
  56439. _spanValueText = document.createTextNode( '' ),
  56440. _def = _settings ? _settings.values[ _id.toLowerCase() ] : null,
  56441. _graph = new Graph( _dom, _id, _def ),
  56442. _started = false;
  56443. _spanId.className = 'rs-counter-id';
  56444. _spanId.textContent = ( _def && _def.caption ) ? _def.caption : _id;
  56445. _spanValue.className = 'rs-counter-value';
  56446. _spanValue.appendChild( _spanValueText );
  56447. _dom.appendChild( _spanId );
  56448. _dom.appendChild( _spanValue );
  56449. if ( group ) group.div.appendChild( _dom );
  56450. else _div.appendChild( _dom );
  56451. _time = performance.now();
  56452. function _average ( v ) {
  56453. if ( _def && _def.average ) {
  56454. _accumValue += v;
  56455. _accumSamples++;
  56456. var t = performance.now();
  56457. if ( t - _accumStart >= ( _def.avgMs || 1000 ) ) {
  56458. _averageValue = _accumValue / _accumSamples;
  56459. _accumValue = 0;
  56460. _accumStart = t;
  56461. _accumSamples = 0;
  56462. }
  56463. }
  56464. }
  56465. function _start () {
  56466. _time = performance.now();
  56467. if( _settings.userTimingAPI ) performance.mark( _id + '-start' );
  56468. _started = true;
  56469. }
  56470. function _end () {
  56471. _value = performance.now() - _time;
  56472. if( _settings.userTimingAPI ) {
  56473. performance.mark( _id + '-end' );
  56474. if( _started ) {
  56475. performance.measure( _id, _id + '-start', _id + '-end' );
  56476. }
  56477. }
  56478. _average( _value );
  56479. }
  56480. function _tick () {
  56481. _end();
  56482. _start();
  56483. }
  56484. function _draw () {
  56485. var v = ( _def && _def.average ) ? _averageValue : _value;
  56486. _spanValueText.nodeValue = Math.round( v * 100 ) / 100;
  56487. var a = ( _def && ( ( _def.below && _value < _def.below ) || ( _def.over && _value > _def.over ) ) );
  56488. _graph.draw( _value, a );
  56489. _dom.className = a ? 'rs-counter-base alarm' : 'rs-counter-base';
  56490. }
  56491. function _frame () {
  56492. var t = performance.now();
  56493. var e = t - _time;
  56494. _total++;
  56495. if ( e > 1000 ) {
  56496. if ( _def && _def.interpolate === false ) {
  56497. _value = _total;
  56498. } else {
  56499. _value = _total * 1000 / e;
  56500. }
  56501. _total = 0;
  56502. _time = t;
  56503. _average( _value );
  56504. }
  56505. }
  56506. function _set ( v ) {
  56507. _value = v;
  56508. _average( _value );
  56509. }
  56510. return {
  56511. set: _set,
  56512. start: _start,
  56513. tick: _tick,
  56514. end: _end,
  56515. frame: _frame,
  56516. value: function () {
  56517. return _value;
  56518. },
  56519. draw: _draw
  56520. };
  56521. }
  56522. function sample () {
  56523. var _value = 0;
  56524. function _set ( v ) {
  56525. _value = v;
  56526. }
  56527. return {
  56528. set: _set,
  56529. value: function () {
  56530. return _value;
  56531. }
  56532. };
  56533. }
  56534. function _perf ( idArg ) {
  56535. var id = idArg.toLowerCase();
  56536. if ( id === undefined ) id = 'default';
  56537. if ( _perfCounters[ id ] ) return _perfCounters[ id ];
  56538. var group = null;
  56539. if ( _settings && _settings.groups ) {
  56540. iterateKeys( _settings.groups, function ( j ) {
  56541. var g = _settings.groups[ parseInt( j, 10 ) ];
  56542. if ( !group && g.values.indexOf( id.toLowerCase() ) !== -1 ) {
  56543. group = g;
  56544. }
  56545. } );
  56546. }
  56547. var p = new PerfCounter( id, group );
  56548. _perfCounters[ id ] = p;
  56549. return p;
  56550. }
  56551. function _init () {
  56552. if ( _settings.plugins ) {
  56553. if ( !_settings.values ) _settings.values = {};
  56554. if ( !_settings.groups ) _settings.groups = [];
  56555. if ( !_settings.fractions ) _settings.fractions = [];
  56556. for ( var j = 0; j < _settings.plugins.length; j++ ) {
  56557. _settings.plugins[ j ].attach( _perf );
  56558. iterateKeys( _settings.plugins[ j ].values, function ( k ) {
  56559. _settings.values[ k ] = _settings.plugins[ j ].values[ k ];
  56560. } );
  56561. _settings.groups = _settings.groups.concat( _settings.plugins[ j ].groups );
  56562. _settings.fractions = _settings.fractions.concat( _settings.plugins[ j ].fractions );
  56563. }
  56564. } else {
  56565. _settings.plugins = {};
  56566. }
  56567. _base = document.createElement( 'div' );
  56568. _base.className = 'rs-base';
  56569. _div = document.createElement( 'div' );
  56570. _div.className = 'rs-container';
  56571. _div.style.height = 'auto';
  56572. _base.appendChild( _div );
  56573. document.body.appendChild( _base );
  56574. if ( !_settings ) return;
  56575. if ( _settings.groups ) {
  56576. iterateKeys( _settings.groups, function ( j ) {
  56577. var g = _settings.groups[ parseInt( j, 10 ) ];
  56578. var div = document.createElement( 'div' );
  56579. div.className = 'rs-group';
  56580. g.div = div;
  56581. var h1 = document.createElement( 'h1' );
  56582. h1.textContent = g.caption;
  56583. h1.addEventListener( 'click', function ( e ) {
  56584. this.classList.toggle( 'hidden' );
  56585. e.preventDefault();
  56586. }.bind( div ) );
  56587. _div.appendChild( h1 );
  56588. _div.appendChild( div );
  56589. } );
  56590. }
  56591. if ( _settings.fractions ) {
  56592. iterateKeys( _settings.fractions, function ( j ) {
  56593. var f = _settings.fractions[ parseInt( j, 10 ) ];
  56594. var div = document.createElement( 'div' );
  56595. div.className = 'rs-fraction';
  56596. var legend = document.createElement( 'div' );
  56597. legend.className = 'rs-legend';
  56598. var h = 0;
  56599. iterateKeys( _settings.fractions[ j ].steps, function ( k ) {
  56600. var p = document.createElement( 'p' );
  56601. p.textContent = _settings.fractions[ j ].steps[ k ];
  56602. p.style.color = _colours[ h ];
  56603. legend.appendChild( p );
  56604. h++;
  56605. } );
  56606. div.appendChild( legend );
  56607. div.style.height = h * _elHeight + 'px';
  56608. f.div = div;
  56609. var graph = new StackGraph( div, h );
  56610. f.graph = graph;
  56611. _div.appendChild( div );
  56612. } );
  56613. }
  56614. }
  56615. function _update () {
  56616. iterateKeys( _settings.plugins, function ( j ) {
  56617. _settings.plugins[ j ].update();
  56618. } );
  56619. iterateKeys( _perfCounters, function ( j ) {
  56620. _perfCounters[ j ].draw();
  56621. } );
  56622. if ( _settings && _settings.fractions ) {
  56623. iterateKeys( _settings.fractions, function ( j ) {
  56624. var f = _settings.fractions[ parseInt( j, 10 ) ];
  56625. var v = [];
  56626. var base = _perfCounters[ f.base.toLowerCase() ];
  56627. if ( base ) {
  56628. base = base.value();
  56629. iterateKeys( _settings.fractions[ j ].steps, function ( k ) {
  56630. var s = _settings.fractions[ j ].steps[ parseInt( k, 10 ) ].toLowerCase();
  56631. var val = _perfCounters[ s ];
  56632. if ( val ) {
  56633. v.push( val.value() / base );
  56634. }
  56635. } );
  56636. }
  56637. f.graph.draw( v );
  56638. } );
  56639. }
  56640. /*if( _height != _div.clientHeight ) {
  56641. _height = _div.clientHeight;
  56642. _base.style.height = _height + 2 * _elHeight + 'px';
  56643. console.log( _base.clientHeight );
  56644. }*/
  56645. }
  56646. _init();
  56647. return function ( id ) {
  56648. if ( id ) return _perf( id );
  56649. return {
  56650. element: _base,
  56651. update: _update
  56652. };
  56653. };
  56654. }
  56655. if (typeof module === 'object') {
  56656. module.exports = window.rStats;
  56657. }
  56658. },{}],187:[function(_dereq_,module,exports){
  56659. // https://stackoverflow.com/a/36213464
  56660. if (!String.prototype.startsWith) {
  56661. String.prototype.startsWith = function(searchString, position){
  56662. position = position || 0;
  56663. return this.substr(position, searchString.length) === searchString;
  56664. };
  56665. }
  56666. },{}],188:[function(_dereq_,module,exports){
  56667. /*
  56668. * Copyright 2015 Google Inc. All Rights Reserved.
  56669. * Licensed under the Apache License, Version 2.0 (the "License");
  56670. * you may not use this file except in compliance with the License.
  56671. * You may obtain a copy of the License at
  56672. *
  56673. * http://www.apache.org/licenses/LICENSE-2.0
  56674. *
  56675. * Unless required by applicable law or agreed to in writing, software
  56676. * distributed under the License is distributed on an "AS IS" BASIS,
  56677. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  56678. * See the License for the specific language governing permissions and
  56679. * limitations under the License.
  56680. */
  56681. var Util = {};
  56682. Util.base64 = function(mimeType, base64) {
  56683. return 'data:' + mimeType + ';base64,' + base64;
  56684. };
  56685. Util.isMobile = function() {
  56686. var check = false;
  56687. (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);
  56688. return check;
  56689. };
  56690. Util.isIOS = function() {
  56691. return /(iPad|iPhone|iPod)/g.test(navigator.userAgent);
  56692. };
  56693. Util.isIFrame = function() {
  56694. try {
  56695. return window.self !== window.top;
  56696. } catch (e) {
  56697. return true;
  56698. }
  56699. };
  56700. Util.appendQueryParameter = function(url, key, value) {
  56701. // Determine delimiter based on if the URL already GET parameters in it.
  56702. var delimiter = (url.indexOf('?') < 0 ? '?' : '&');
  56703. url += delimiter + key + '=' + value;
  56704. return url;
  56705. };
  56706. // From http://goo.gl/4WX3tg
  56707. Util.getQueryParameter = function(name) {
  56708. name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
  56709. var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
  56710. results = regex.exec(location.search);
  56711. return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
  56712. };
  56713. Util.isLandscapeMode = function() {
  56714. return (window.orientation == 90 || window.orientation == -90);
  56715. };
  56716. module.exports = Util;
  56717. },{}],189:[function(_dereq_,module,exports){
  56718. /*
  56719. * Copyright 2015 Google Inc. All Rights Reserved.
  56720. * Licensed under the Apache License, Version 2.0 (the "License");
  56721. * you may not use this file except in compliance with the License.
  56722. * You may obtain a copy of the License at
  56723. *
  56724. * http://www.apache.org/licenses/LICENSE-2.0
  56725. *
  56726. * Unless required by applicable law or agreed to in writing, software
  56727. * distributed under the License is distributed on an "AS IS" BASIS,
  56728. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  56729. * See the License for the specific language governing permissions and
  56730. * limitations under the License.
  56731. */
  56732. var Util = _dereq_('./util.js');
  56733. /**
  56734. * Android and iOS compatible wakelock implementation.
  56735. *
  56736. * Refactored thanks to dkovalev@.
  56737. */
  56738. function AndroidWakeLock() {
  56739. var video = document.createElement('video');
  56740. video.addEventListener('ended', function() {
  56741. video.play();
  56742. });
  56743. this.request = function() {
  56744. if (video.paused) {
  56745. // Base64 version of videos_src/no-sleep-60s.webm.
  56746. video.src = Util.base64('video/webm', 'GkXfowEAAAAAAAAfQoaBAUL3gQFC8oEEQvOBCEKChHdlYm1Ch4ECQoWBAhhTgGcBAAAAAAAH4xFNm3RALE27i1OrhBVJqWZTrIHfTbuMU6uEFlSua1OsggEwTbuMU6uEHFO7a1OsggfG7AEAAAAAAACkAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAVSalmAQAAAAAAAEUq17GDD0JATYCNTGF2ZjU2LjQwLjEwMVdBjUxhdmY1Ni40MC4xMDFzpJAGSJTMbsLpDt/ySkipgX1fRImIQO1MAAAAAAAWVK5rAQAAAAAAADuuAQAAAAAAADLXgQFzxYEBnIEAIrWcg3VuZIaFVl9WUDmDgQEj44OEO5rKAOABAAAAAAAABrCBsLqBkB9DtnUBAAAAAAAAo+eBAKOmgQAAgKJJg0IAAV4BHsAHBIODCoAACmH2MAAAZxgz4dPSTFi5JACjloED6ACmAECSnABMQAADYAAAWi0quoCjloEH0ACmAECSnABNwAADYAAAWi0quoCjloELuACmAECSnABNgAADYAAAWi0quoCjloEPoACmAECSnABNYAADYAAAWi0quoCjloETiACmAECSnABNIAADYAAAWi0quoAfQ7Z1AQAAAAAAAJTnghdwo5aBAAAApgBAkpwATOAAA2AAAFotKrqAo5aBA+gApgBAkpwATMAAA2AAAFotKrqAo5aBB9AApgBAkpwATIAAA2AAAFotKrqAo5aBC7gApgBAkpwATEAAA2AAAFotKrqAo5aBD6AApgDAkpwAQ2AAA2AAAFotKrqAo5aBE4gApgBAkpwATCAAA2AAAFotKrqAH0O2dQEAAAAAAACU54Iu4KOWgQAAAKYAQJKcAEvAAANgAABaLSq6gKOWgQPoAKYAQJKcAEtgAANgAABaLSq6gKOWgQfQAKYAQJKcAEsAAANgAABaLSq6gKOWgQu4AKYAQJKcAEqAAANgAABaLSq6gKOWgQ+gAKYAQJKcAEogAANgAABaLSq6gKOWgROIAKYAQJKcAEnAAANgAABaLSq6gB9DtnUBAAAAAAAAlOeCRlCjloEAAACmAECSnABJgAADYAAAWi0quoCjloED6ACmAECSnABJIAADYAAAWi0quoCjloEH0ACmAMCSnABDYAADYAAAWi0quoCjloELuACmAECSnABI4AADYAAAWi0quoCjloEPoACmAECSnABIoAADYAAAWi0quoCjloETiACmAECSnABIYAADYAAAWi0quoAfQ7Z1AQAAAAAAAJTngl3Ao5aBAAAApgBAkpwASCAAA2AAAFotKrqAo5aBA+gApgBAkpwASAAAA2AAAFotKrqAo5aBB9AApgBAkpwAR8AAA2AAAFotKrqAo5aBC7gApgBAkpwAR4AAA2AAAFotKrqAo5aBD6AApgBAkpwAR2AAA2AAAFotKrqAo5aBE4gApgBAkpwARyAAA2AAAFotKrqAH0O2dQEAAAAAAACU54J1MKOWgQAAAKYAwJKcAENgAANgAABaLSq6gKOWgQPoAKYAQJKcAEbgAANgAABaLSq6gKOWgQfQAKYAQJKcAEagAANgAABaLSq6gKOWgQu4AKYAQJKcAEaAAANgAABaLSq6gKOWgQ+gAKYAQJKcAEZAAANgAABaLSq6gKOWgROIAKYAQJKcAEYAAANgAABaLSq6gB9DtnUBAAAAAAAAlOeCjKCjloEAAACmAECSnABF4AADYAAAWi0quoCjloED6ACmAECSnABFwAADYAAAWi0quoCjloEH0ACmAECSnABFoAADYAAAWi0quoCjloELuACmAECSnABFgAADYAAAWi0quoCjloEPoACmAMCSnABDYAADYAAAWi0quoCjloETiACmAECSnABFYAADYAAAWi0quoAfQ7Z1AQAAAAAAAJTngqQQo5aBAAAApgBAkpwARUAAA2AAAFotKrqAo5aBA+gApgBAkpwARSAAA2AAAFotKrqAo5aBB9AApgBAkpwARQAAA2AAAFotKrqAo5aBC7gApgBAkpwARQAAA2AAAFotKrqAo5aBD6AApgBAkpwAROAAA2AAAFotKrqAo5aBE4gApgBAkpwARMAAA2AAAFotKrqAH0O2dQEAAAAAAACU54K7gKOWgQAAAKYAQJKcAESgAANgAABaLSq6gKOWgQPoAKYAQJKcAESAAANgAABaLSq6gKOWgQfQAKYAwJKcAENgAANgAABaLSq6gKOWgQu4AKYAQJKcAERgAANgAABaLSq6gKOWgQ+gAKYAQJKcAERAAANgAABaLSq6gKOWgROIAKYAQJKcAEQgAANgAABaLSq6gB9DtnUBAAAAAAAAlOeC0vCjloEAAACmAECSnABEIAADYAAAWi0quoCjloED6ACmAECSnABEAAADYAAAWi0quoCjloEH0ACmAECSnABD4AADYAAAWi0quoCjloELuACmAECSnABDwAADYAAAWi0quoCjloEPoACmAECSnABDoAADYAAAWi0quoCjloETiACmAECSnABDgAADYAAAWi0quoAcU7trAQAAAAAAABG7j7OBALeK94EB8YIBd/CBAw==');
  56747. video.play();
  56748. }
  56749. };
  56750. this.release = function() {
  56751. video.pause();
  56752. video.src = '';
  56753. };
  56754. }
  56755. function iOSWakeLock() {
  56756. var timer = null;
  56757. this.request = function() {
  56758. if (!timer) {
  56759. timer = setInterval(function() {
  56760. window.location.href = '/';
  56761. setTimeout(window.stop, 0);
  56762. }, 15000);
  56763. }
  56764. }
  56765. this.release = function() {
  56766. if (timer) {
  56767. clearInterval(timer);
  56768. timer = null;
  56769. }
  56770. }
  56771. }
  56772. function getWakeLock() {
  56773. var userAgent = navigator.userAgent || navigator.vendor || window.opera;
  56774. if (userAgent.match(/iPhone/i) || userAgent.match(/iPod/i)) {
  56775. return iOSWakeLock;
  56776. } else {
  56777. return AndroidWakeLock;
  56778. }
  56779. }
  56780. module.exports = getWakeLock();
  56781. },{"./util.js":188}]},{},[149])(149)
  56782. });
  56783. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("buffer").Buffer,require("timers").setImmediate)
  56784. },{"buffer":6,"timers":8}],5:[function(require,module,exports){
  56785. 'use strict'
  56786. exports.byteLength = byteLength
  56787. exports.toByteArray = toByteArray
  56788. exports.fromByteArray = fromByteArray
  56789. var lookup = []
  56790. var revLookup = []
  56791. var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array
  56792. var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
  56793. for (var i = 0, len = code.length; i < len; ++i) {
  56794. lookup[i] = code[i]
  56795. revLookup[code.charCodeAt(i)] = i
  56796. }
  56797. // Support decoding URL-safe base64 strings, as Node.js does.
  56798. // See: https://en.wikipedia.org/wiki/Base64#URL_applications
  56799. revLookup['-'.charCodeAt(0)] = 62
  56800. revLookup['_'.charCodeAt(0)] = 63
  56801. function getLens (b64) {
  56802. var len = b64.length
  56803. if (len % 4 > 0) {
  56804. throw new Error('Invalid string. Length must be a multiple of 4')
  56805. }
  56806. // Trim off extra bytes after placeholder bytes are found
  56807. // See: https://github.com/beatgammit/base64-js/issues/42
  56808. var validLen = b64.indexOf('=')
  56809. if (validLen === -1) validLen = len
  56810. var placeHoldersLen = validLen === len
  56811. ? 0
  56812. : 4 - (validLen % 4)
  56813. return [validLen, placeHoldersLen]
  56814. }
  56815. // base64 is 4/3 + up to two characters of the original data
  56816. function byteLength (b64) {
  56817. var lens = getLens(b64)
  56818. var validLen = lens[0]
  56819. var placeHoldersLen = lens[1]
  56820. return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
  56821. }
  56822. function _byteLength (b64, validLen, placeHoldersLen) {
  56823. return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
  56824. }
  56825. function toByteArray (b64) {
  56826. var tmp
  56827. var lens = getLens(b64)
  56828. var validLen = lens[0]
  56829. var placeHoldersLen = lens[1]
  56830. var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen))
  56831. var curByte = 0
  56832. // if there are placeholders, only get up to the last complete 4 chars
  56833. var len = placeHoldersLen > 0
  56834. ? validLen - 4
  56835. : validLen
  56836. for (var i = 0; i < len; i += 4) {
  56837. tmp =
  56838. (revLookup[b64.charCodeAt(i)] << 18) |
  56839. (revLookup[b64.charCodeAt(i + 1)] << 12) |
  56840. (revLookup[b64.charCodeAt(i + 2)] << 6) |
  56841. revLookup[b64.charCodeAt(i + 3)]
  56842. arr[curByte++] = (tmp >> 16) & 0xFF
  56843. arr[curByte++] = (tmp >> 8) & 0xFF
  56844. arr[curByte++] = tmp & 0xFF
  56845. }
  56846. if (placeHoldersLen === 2) {
  56847. tmp =
  56848. (revLookup[b64.charCodeAt(i)] << 2) |
  56849. (revLookup[b64.charCodeAt(i + 1)] >> 4)
  56850. arr[curByte++] = tmp & 0xFF
  56851. }
  56852. if (placeHoldersLen === 1) {
  56853. tmp =
  56854. (revLookup[b64.charCodeAt(i)] << 10) |
  56855. (revLookup[b64.charCodeAt(i + 1)] << 4) |
  56856. (revLookup[b64.charCodeAt(i + 2)] >> 2)
  56857. arr[curByte++] = (tmp >> 8) & 0xFF
  56858. arr[curByte++] = tmp & 0xFF
  56859. }
  56860. return arr
  56861. }
  56862. function tripletToBase64 (num) {
  56863. return lookup[num >> 18 & 0x3F] +
  56864. lookup[num >> 12 & 0x3F] +
  56865. lookup[num >> 6 & 0x3F] +
  56866. lookup[num & 0x3F]
  56867. }
  56868. function encodeChunk (uint8, start, end) {
  56869. var tmp
  56870. var output = []
  56871. for (var i = start; i < end; i += 3) {
  56872. tmp =
  56873. ((uint8[i] << 16) & 0xFF0000) +
  56874. ((uint8[i + 1] << 8) & 0xFF00) +
  56875. (uint8[i + 2] & 0xFF)
  56876. output.push(tripletToBase64(tmp))
  56877. }
  56878. return output.join('')
  56879. }
  56880. function fromByteArray (uint8) {
  56881. var tmp
  56882. var len = uint8.length
  56883. var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes
  56884. var parts = []
  56885. var maxChunkLength = 16383 // must be multiple of 3
  56886. // go through the array every three bytes, we'll deal with trailing stuff later
  56887. for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
  56888. parts.push(encodeChunk(
  56889. uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)
  56890. ))
  56891. }
  56892. // pad the end with zeros, but make sure to not forget the extra bytes
  56893. if (extraBytes === 1) {
  56894. tmp = uint8[len - 1]
  56895. parts.push(
  56896. lookup[tmp >> 2] +
  56897. lookup[(tmp << 4) & 0x3F] +
  56898. '=='
  56899. )
  56900. } else if (extraBytes === 2) {
  56901. tmp = (uint8[len - 2] << 8) + uint8[len - 1]
  56902. parts.push(
  56903. lookup[tmp >> 10] +
  56904. lookup[(tmp >> 4) & 0x3F] +
  56905. lookup[(tmp << 2) & 0x3F] +
  56906. '='
  56907. )
  56908. }
  56909. return parts.join('')
  56910. }
  56911. },{}],6:[function(require,module,exports){
  56912. (function (Buffer){
  56913. /*!
  56914. * The buffer module from node.js, for the browser.
  56915. *
  56916. * @author Feross Aboukhadijeh <https://feross.org>
  56917. * @license MIT
  56918. */
  56919. /* eslint-disable no-proto */
  56920. 'use strict'
  56921. var base64 = require('base64-js')
  56922. var ieee754 = require('ieee754')
  56923. exports.Buffer = Buffer
  56924. exports.SlowBuffer = SlowBuffer
  56925. exports.INSPECT_MAX_BYTES = 50
  56926. var K_MAX_LENGTH = 0x7fffffff
  56927. exports.kMaxLength = K_MAX_LENGTH
  56928. /**
  56929. * If `Buffer.TYPED_ARRAY_SUPPORT`:
  56930. * === true Use Uint8Array implementation (fastest)
  56931. * === false Print warning and recommend using `buffer` v4.x which has an Object
  56932. * implementation (most compatible, even IE6)
  56933. *
  56934. * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
  56935. * Opera 11.6+, iOS 4.2+.
  56936. *
  56937. * We report that the browser does not support typed arrays if the are not subclassable
  56938. * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array`
  56939. * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support
  56940. * for __proto__ and has a buggy typed array implementation.
  56941. */
  56942. Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport()
  56943. if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' &&
  56944. typeof console.error === 'function') {
  56945. console.error(
  56946. 'This browser lacks typed array (Uint8Array) support which is required by ' +
  56947. '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.'
  56948. )
  56949. }
  56950. function typedArraySupport () {
  56951. // Can typed array instances can be augmented?
  56952. try {
  56953. var arr = new Uint8Array(1)
  56954. arr.__proto__ = { __proto__: Uint8Array.prototype, foo: function () { return 42 } }
  56955. return arr.foo() === 42
  56956. } catch (e) {
  56957. return false
  56958. }
  56959. }
  56960. Object.defineProperty(Buffer.prototype, 'parent', {
  56961. enumerable: true,
  56962. get: function () {
  56963. if (!Buffer.isBuffer(this)) return undefined
  56964. return this.buffer
  56965. }
  56966. })
  56967. Object.defineProperty(Buffer.prototype, 'offset', {
  56968. enumerable: true,
  56969. get: function () {
  56970. if (!Buffer.isBuffer(this)) return undefined
  56971. return this.byteOffset
  56972. }
  56973. })
  56974. function createBuffer (length) {
  56975. if (length > K_MAX_LENGTH) {
  56976. throw new RangeError('The value "' + length + '" is invalid for option "size"')
  56977. }
  56978. // Return an augmented `Uint8Array` instance
  56979. var buf = new Uint8Array(length)
  56980. buf.__proto__ = Buffer.prototype
  56981. return buf
  56982. }
  56983. /**
  56984. * The Buffer constructor returns instances of `Uint8Array` that have their
  56985. * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
  56986. * `Uint8Array`, so the returned instances will have all the node `Buffer` methods
  56987. * and the `Uint8Array` methods. Square bracket notation works as expected -- it
  56988. * returns a single octet.
  56989. *
  56990. * The `Uint8Array` prototype remains unmodified.
  56991. */
  56992. function Buffer (arg, encodingOrOffset, length) {
  56993. // Common case.
  56994. if (typeof arg === 'number') {
  56995. if (typeof encodingOrOffset === 'string') {
  56996. throw new TypeError(
  56997. 'The "string" argument must be of type string. Received type number'
  56998. )
  56999. }
  57000. return allocUnsafe(arg)
  57001. }
  57002. return from(arg, encodingOrOffset, length)
  57003. }
  57004. // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97
  57005. if (typeof Symbol !== 'undefined' && Symbol.species != null &&
  57006. Buffer[Symbol.species] === Buffer) {
  57007. Object.defineProperty(Buffer, Symbol.species, {
  57008. value: null,
  57009. configurable: true,
  57010. enumerable: false,
  57011. writable: false
  57012. })
  57013. }
  57014. Buffer.poolSize = 8192 // not used by this implementation
  57015. function from (value, encodingOrOffset, length) {
  57016. if (typeof value === 'string') {
  57017. return fromString(value, encodingOrOffset)
  57018. }
  57019. if (ArrayBuffer.isView(value)) {
  57020. return fromArrayLike(value)
  57021. }
  57022. if (value == null) {
  57023. throw TypeError(
  57024. 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +
  57025. 'or Array-like Object. Received type ' + (typeof value)
  57026. )
  57027. }
  57028. if (isInstance(value, ArrayBuffer) ||
  57029. (value && isInstance(value.buffer, ArrayBuffer))) {
  57030. return fromArrayBuffer(value, encodingOrOffset, length)
  57031. }
  57032. if (typeof value === 'number') {
  57033. throw new TypeError(
  57034. 'The "value" argument must not be of type number. Received type number'
  57035. )
  57036. }
  57037. var valueOf = value.valueOf && value.valueOf()
  57038. if (valueOf != null && valueOf !== value) {
  57039. return Buffer.from(valueOf, encodingOrOffset, length)
  57040. }
  57041. var b = fromObject(value)
  57042. if (b) return b
  57043. if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null &&
  57044. typeof value[Symbol.toPrimitive] === 'function') {
  57045. return Buffer.from(
  57046. value[Symbol.toPrimitive]('string'), encodingOrOffset, length
  57047. )
  57048. }
  57049. throw new TypeError(
  57050. 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +
  57051. 'or Array-like Object. Received type ' + (typeof value)
  57052. )
  57053. }
  57054. /**
  57055. * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
  57056. * if value is a number.
  57057. * Buffer.from(str[, encoding])
  57058. * Buffer.from(array)
  57059. * Buffer.from(buffer)
  57060. * Buffer.from(arrayBuffer[, byteOffset[, length]])
  57061. **/
  57062. Buffer.from = function (value, encodingOrOffset, length) {
  57063. return from(value, encodingOrOffset, length)
  57064. }
  57065. // Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug:
  57066. // https://github.com/feross/buffer/pull/148
  57067. Buffer.prototype.__proto__ = Uint8Array.prototype
  57068. Buffer.__proto__ = Uint8Array
  57069. function assertSize (size) {
  57070. if (typeof size !== 'number') {
  57071. throw new TypeError('"size" argument must be of type number')
  57072. } else if (size < 0) {
  57073. throw new RangeError('The value "' + size + '" is invalid for option "size"')
  57074. }
  57075. }
  57076. function alloc (size, fill, encoding) {
  57077. assertSize(size)
  57078. if (size <= 0) {
  57079. return createBuffer(size)
  57080. }
  57081. if (fill !== undefined) {
  57082. // Only pay attention to encoding if it's a string. This
  57083. // prevents accidentally sending in a number that would
  57084. // be interpretted as a start offset.
  57085. return typeof encoding === 'string'
  57086. ? createBuffer(size).fill(fill, encoding)
  57087. : createBuffer(size).fill(fill)
  57088. }
  57089. return createBuffer(size)
  57090. }
  57091. /**
  57092. * Creates a new filled Buffer instance.
  57093. * alloc(size[, fill[, encoding]])
  57094. **/
  57095. Buffer.alloc = function (size, fill, encoding) {
  57096. return alloc(size, fill, encoding)
  57097. }
  57098. function allocUnsafe (size) {
  57099. assertSize(size)
  57100. return createBuffer(size < 0 ? 0 : checked(size) | 0)
  57101. }
  57102. /**
  57103. * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
  57104. * */
  57105. Buffer.allocUnsafe = function (size) {
  57106. return allocUnsafe(size)
  57107. }
  57108. /**
  57109. * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
  57110. */
  57111. Buffer.allocUnsafeSlow = function (size) {
  57112. return allocUnsafe(size)
  57113. }
  57114. function fromString (string, encoding) {
  57115. if (typeof encoding !== 'string' || encoding === '') {
  57116. encoding = 'utf8'
  57117. }
  57118. if (!Buffer.isEncoding(encoding)) {
  57119. throw new TypeError('Unknown encoding: ' + encoding)
  57120. }
  57121. var length = byteLength(string, encoding) | 0
  57122. var buf = createBuffer(length)
  57123. var actual = buf.write(string, encoding)
  57124. if (actual !== length) {
  57125. // Writing a hex string, for example, that contains invalid characters will
  57126. // cause everything after the first invalid character to be ignored. (e.g.
  57127. // 'abxxcd' will be treated as 'ab')
  57128. buf = buf.slice(0, actual)
  57129. }
  57130. return buf
  57131. }
  57132. function fromArrayLike (array) {
  57133. var length = array.length < 0 ? 0 : checked(array.length) | 0
  57134. var buf = createBuffer(length)
  57135. for (var i = 0; i < length; i += 1) {
  57136. buf[i] = array[i] & 255
  57137. }
  57138. return buf
  57139. }
  57140. function fromArrayBuffer (array, byteOffset, length) {
  57141. if (byteOffset < 0 || array.byteLength < byteOffset) {
  57142. throw new RangeError('"offset" is outside of buffer bounds')
  57143. }
  57144. if (array.byteLength < byteOffset + (length || 0)) {
  57145. throw new RangeError('"length" is outside of buffer bounds')
  57146. }
  57147. var buf
  57148. if (byteOffset === undefined && length === undefined) {
  57149. buf = new Uint8Array(array)
  57150. } else if (length === undefined) {
  57151. buf = new Uint8Array(array, byteOffset)
  57152. } else {
  57153. buf = new Uint8Array(array, byteOffset, length)
  57154. }
  57155. // Return an augmented `Uint8Array` instance
  57156. buf.__proto__ = Buffer.prototype
  57157. return buf
  57158. }
  57159. function fromObject (obj) {
  57160. if (Buffer.isBuffer(obj)) {
  57161. var len = checked(obj.length) | 0
  57162. var buf = createBuffer(len)
  57163. if (buf.length === 0) {
  57164. return buf
  57165. }
  57166. obj.copy(buf, 0, 0, len)
  57167. return buf
  57168. }
  57169. if (obj.length !== undefined) {
  57170. if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) {
  57171. return createBuffer(0)
  57172. }
  57173. return fromArrayLike(obj)
  57174. }
  57175. if (obj.type === 'Buffer' && Array.isArray(obj.data)) {
  57176. return fromArrayLike(obj.data)
  57177. }
  57178. }
  57179. function checked (length) {
  57180. // Note: cannot use `length < K_MAX_LENGTH` here because that fails when
  57181. // length is NaN (which is otherwise coerced to zero.)
  57182. if (length >= K_MAX_LENGTH) {
  57183. throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
  57184. 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes')
  57185. }
  57186. return length | 0
  57187. }
  57188. function SlowBuffer (length) {
  57189. if (+length != length) { // eslint-disable-line eqeqeq
  57190. length = 0
  57191. }
  57192. return Buffer.alloc(+length)
  57193. }
  57194. Buffer.isBuffer = function isBuffer (b) {
  57195. return b != null && b._isBuffer === true &&
  57196. b !== Buffer.prototype // so Buffer.isBuffer(Buffer.prototype) will be false
  57197. }
  57198. Buffer.compare = function compare (a, b) {
  57199. if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength)
  57200. if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength)
  57201. if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
  57202. throw new TypeError(
  57203. 'The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array'
  57204. )
  57205. }
  57206. if (a === b) return 0
  57207. var x = a.length
  57208. var y = b.length
  57209. for (var i = 0, len = Math.min(x, y); i < len; ++i) {
  57210. if (a[i] !== b[i]) {
  57211. x = a[i]
  57212. y = b[i]
  57213. break
  57214. }
  57215. }
  57216. if (x < y) return -1
  57217. if (y < x) return 1
  57218. return 0
  57219. }
  57220. Buffer.isEncoding = function isEncoding (encoding) {
  57221. switch (String(encoding).toLowerCase()) {
  57222. case 'hex':
  57223. case 'utf8':
  57224. case 'utf-8':
  57225. case 'ascii':
  57226. case 'latin1':
  57227. case 'binary':
  57228. case 'base64':
  57229. case 'ucs2':
  57230. case 'ucs-2':
  57231. case 'utf16le':
  57232. case 'utf-16le':
  57233. return true
  57234. default:
  57235. return false
  57236. }
  57237. }
  57238. Buffer.concat = function concat (list, length) {
  57239. if (!Array.isArray(list)) {
  57240. throw new TypeError('"list" argument must be an Array of Buffers')
  57241. }
  57242. if (list.length === 0) {
  57243. return Buffer.alloc(0)
  57244. }
  57245. var i
  57246. if (length === undefined) {
  57247. length = 0
  57248. for (i = 0; i < list.length; ++i) {
  57249. length += list[i].length
  57250. }
  57251. }
  57252. var buffer = Buffer.allocUnsafe(length)
  57253. var pos = 0
  57254. for (i = 0; i < list.length; ++i) {
  57255. var buf = list[i]
  57256. if (isInstance(buf, Uint8Array)) {
  57257. buf = Buffer.from(buf)
  57258. }
  57259. if (!Buffer.isBuffer(buf)) {
  57260. throw new TypeError('"list" argument must be an Array of Buffers')
  57261. }
  57262. buf.copy(buffer, pos)
  57263. pos += buf.length
  57264. }
  57265. return buffer
  57266. }
  57267. function byteLength (string, encoding) {
  57268. if (Buffer.isBuffer(string)) {
  57269. return string.length
  57270. }
  57271. if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) {
  57272. return string.byteLength
  57273. }
  57274. if (typeof string !== 'string') {
  57275. throw new TypeError(
  57276. 'The "string" argument must be one of type string, Buffer, or ArrayBuffer. ' +
  57277. 'Received type ' + typeof string
  57278. )
  57279. }
  57280. var len = string.length
  57281. var mustMatch = (arguments.length > 2 && arguments[2] === true)
  57282. if (!mustMatch && len === 0) return 0
  57283. // Use a for loop to avoid recursion
  57284. var loweredCase = false
  57285. for (;;) {
  57286. switch (encoding) {
  57287. case 'ascii':
  57288. case 'latin1':
  57289. case 'binary':
  57290. return len
  57291. case 'utf8':
  57292. case 'utf-8':
  57293. return utf8ToBytes(string).length
  57294. case 'ucs2':
  57295. case 'ucs-2':
  57296. case 'utf16le':
  57297. case 'utf-16le':
  57298. return len * 2
  57299. case 'hex':
  57300. return len >>> 1
  57301. case 'base64':
  57302. return base64ToBytes(string).length
  57303. default:
  57304. if (loweredCase) {
  57305. return mustMatch ? -1 : utf8ToBytes(string).length // assume utf8
  57306. }
  57307. encoding = ('' + encoding).toLowerCase()
  57308. loweredCase = true
  57309. }
  57310. }
  57311. }
  57312. Buffer.byteLength = byteLength
  57313. function slowToString (encoding, start, end) {
  57314. var loweredCase = false
  57315. // No need to verify that "this.length <= MAX_UINT32" since it's a read-only
  57316. // property of a typed array.
  57317. // This behaves neither like String nor Uint8Array in that we set start/end
  57318. // to their upper/lower bounds if the value passed is out of range.
  57319. // undefined is handled specially as per ECMA-262 6th Edition,
  57320. // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
  57321. if (start === undefined || start < 0) {
  57322. start = 0
  57323. }
  57324. // Return early if start > this.length. Done here to prevent potential uint32
  57325. // coercion fail below.
  57326. if (start > this.length) {
  57327. return ''
  57328. }
  57329. if (end === undefined || end > this.length) {
  57330. end = this.length
  57331. }
  57332. if (end <= 0) {
  57333. return ''
  57334. }
  57335. // Force coersion to uint32. This will also coerce falsey/NaN values to 0.
  57336. end >>>= 0
  57337. start >>>= 0
  57338. if (end <= start) {
  57339. return ''
  57340. }
  57341. if (!encoding) encoding = 'utf8'
  57342. while (true) {
  57343. switch (encoding) {
  57344. case 'hex':
  57345. return hexSlice(this, start, end)
  57346. case 'utf8':
  57347. case 'utf-8':
  57348. return utf8Slice(this, start, end)
  57349. case 'ascii':
  57350. return asciiSlice(this, start, end)
  57351. case 'latin1':
  57352. case 'binary':
  57353. return latin1Slice(this, start, end)
  57354. case 'base64':
  57355. return base64Slice(this, start, end)
  57356. case 'ucs2':
  57357. case 'ucs-2':
  57358. case 'utf16le':
  57359. case 'utf-16le':
  57360. return utf16leSlice(this, start, end)
  57361. default:
  57362. if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
  57363. encoding = (encoding + '').toLowerCase()
  57364. loweredCase = true
  57365. }
  57366. }
  57367. }
  57368. // This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package)
  57369. // to detect a Buffer instance. It's not possible to use `instanceof Buffer`
  57370. // reliably in a browserify context because there could be multiple different
  57371. // copies of the 'buffer' package in use. This method works even for Buffer
  57372. // instances that were created from another copy of the `buffer` package.
  57373. // See: https://github.com/feross/buffer/issues/154
  57374. Buffer.prototype._isBuffer = true
  57375. function swap (b, n, m) {
  57376. var i = b[n]
  57377. b[n] = b[m]
  57378. b[m] = i
  57379. }
  57380. Buffer.prototype.swap16 = function swap16 () {
  57381. var len = this.length
  57382. if (len % 2 !== 0) {
  57383. throw new RangeError('Buffer size must be a multiple of 16-bits')
  57384. }
  57385. for (var i = 0; i < len; i += 2) {
  57386. swap(this, i, i + 1)
  57387. }
  57388. return this
  57389. }
  57390. Buffer.prototype.swap32 = function swap32 () {
  57391. var len = this.length
  57392. if (len % 4 !== 0) {
  57393. throw new RangeError('Buffer size must be a multiple of 32-bits')
  57394. }
  57395. for (var i = 0; i < len; i += 4) {
  57396. swap(this, i, i + 3)
  57397. swap(this, i + 1, i + 2)
  57398. }
  57399. return this
  57400. }
  57401. Buffer.prototype.swap64 = function swap64 () {
  57402. var len = this.length
  57403. if (len % 8 !== 0) {
  57404. throw new RangeError('Buffer size must be a multiple of 64-bits')
  57405. }
  57406. for (var i = 0; i < len; i += 8) {
  57407. swap(this, i, i + 7)
  57408. swap(this, i + 1, i + 6)
  57409. swap(this, i + 2, i + 5)
  57410. swap(this, i + 3, i + 4)
  57411. }
  57412. return this
  57413. }
  57414. Buffer.prototype.toString = function toString () {
  57415. var length = this.length
  57416. if (length === 0) return ''
  57417. if (arguments.length === 0) return utf8Slice(this, 0, length)
  57418. return slowToString.apply(this, arguments)
  57419. }
  57420. Buffer.prototype.toLocaleString = Buffer.prototype.toString
  57421. Buffer.prototype.equals = function equals (b) {
  57422. if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
  57423. if (this === b) return true
  57424. return Buffer.compare(this, b) === 0
  57425. }
  57426. Buffer.prototype.inspect = function inspect () {
  57427. var str = ''
  57428. var max = exports.INSPECT_MAX_BYTES
  57429. str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim()
  57430. if (this.length > max) str += ' ... '
  57431. return '<Buffer ' + str + '>'
  57432. }
  57433. Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
  57434. if (isInstance(target, Uint8Array)) {
  57435. target = Buffer.from(target, target.offset, target.byteLength)
  57436. }
  57437. if (!Buffer.isBuffer(target)) {
  57438. throw new TypeError(
  57439. 'The "target" argument must be one of type Buffer or Uint8Array. ' +
  57440. 'Received type ' + (typeof target)
  57441. )
  57442. }
  57443. if (start === undefined) {
  57444. start = 0
  57445. }
  57446. if (end === undefined) {
  57447. end = target ? target.length : 0
  57448. }
  57449. if (thisStart === undefined) {
  57450. thisStart = 0
  57451. }
  57452. if (thisEnd === undefined) {
  57453. thisEnd = this.length
  57454. }
  57455. if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
  57456. throw new RangeError('out of range index')
  57457. }
  57458. if (thisStart >= thisEnd && start >= end) {
  57459. return 0
  57460. }
  57461. if (thisStart >= thisEnd) {
  57462. return -1
  57463. }
  57464. if (start >= end) {
  57465. return 1
  57466. }
  57467. start >>>= 0
  57468. end >>>= 0
  57469. thisStart >>>= 0
  57470. thisEnd >>>= 0
  57471. if (this === target) return 0
  57472. var x = thisEnd - thisStart
  57473. var y = end - start
  57474. var len = Math.min(x, y)
  57475. var thisCopy = this.slice(thisStart, thisEnd)
  57476. var targetCopy = target.slice(start, end)
  57477. for (var i = 0; i < len; ++i) {
  57478. if (thisCopy[i] !== targetCopy[i]) {
  57479. x = thisCopy[i]
  57480. y = targetCopy[i]
  57481. break
  57482. }
  57483. }
  57484. if (x < y) return -1
  57485. if (y < x) return 1
  57486. return 0
  57487. }
  57488. // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
  57489. // OR the last index of `val` in `buffer` at offset <= `byteOffset`.
  57490. //
  57491. // Arguments:
  57492. // - buffer - a Buffer to search
  57493. // - val - a string, Buffer, or number
  57494. // - byteOffset - an index into `buffer`; will be clamped to an int32
  57495. // - encoding - an optional encoding, relevant is val is a string
  57496. // - dir - true for indexOf, false for lastIndexOf
  57497. function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {
  57498. // Empty buffer means no match
  57499. if (buffer.length === 0) return -1
  57500. // Normalize byteOffset
  57501. if (typeof byteOffset === 'string') {
  57502. encoding = byteOffset
  57503. byteOffset = 0
  57504. } else if (byteOffset > 0x7fffffff) {
  57505. byteOffset = 0x7fffffff
  57506. } else if (byteOffset < -0x80000000) {
  57507. byteOffset = -0x80000000
  57508. }
  57509. byteOffset = +byteOffset // Coerce to Number.
  57510. if (numberIsNaN(byteOffset)) {
  57511. // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
  57512. byteOffset = dir ? 0 : (buffer.length - 1)
  57513. }
  57514. // Normalize byteOffset: negative offsets start from the end of the buffer
  57515. if (byteOffset < 0) byteOffset = buffer.length + byteOffset
  57516. if (byteOffset >= buffer.length) {
  57517. if (dir) return -1
  57518. else byteOffset = buffer.length - 1
  57519. } else if (byteOffset < 0) {
  57520. if (dir) byteOffset = 0
  57521. else return -1
  57522. }
  57523. // Normalize val
  57524. if (typeof val === 'string') {
  57525. val = Buffer.from(val, encoding)
  57526. }
  57527. // Finally, search either indexOf (if dir is true) or lastIndexOf
  57528. if (Buffer.isBuffer(val)) {
  57529. // Special case: looking for empty string/buffer always fails
  57530. if (val.length === 0) {
  57531. return -1
  57532. }
  57533. return arrayIndexOf(buffer, val, byteOffset, encoding, dir)
  57534. } else if (typeof val === 'number') {
  57535. val = val & 0xFF // Search for a byte value [0-255]
  57536. if (typeof Uint8Array.prototype.indexOf === 'function') {
  57537. if (dir) {
  57538. return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)
  57539. } else {
  57540. return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)
  57541. }
  57542. }
  57543. return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)
  57544. }
  57545. throw new TypeError('val must be string, number or Buffer')
  57546. }
  57547. function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
  57548. var indexSize = 1
  57549. var arrLength = arr.length
  57550. var valLength = val.length
  57551. if (encoding !== undefined) {
  57552. encoding = String(encoding).toLowerCase()
  57553. if (encoding === 'ucs2' || encoding === 'ucs-2' ||
  57554. encoding === 'utf16le' || encoding === 'utf-16le') {
  57555. if (arr.length < 2 || val.length < 2) {
  57556. return -1
  57557. }
  57558. indexSize = 2
  57559. arrLength /= 2
  57560. valLength /= 2
  57561. byteOffset /= 2
  57562. }
  57563. }
  57564. function read (buf, i) {
  57565. if (indexSize === 1) {
  57566. return buf[i]
  57567. } else {
  57568. return buf.readUInt16BE(i * indexSize)
  57569. }
  57570. }
  57571. var i
  57572. if (dir) {
  57573. var foundIndex = -1
  57574. for (i = byteOffset; i < arrLength; i++) {
  57575. if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
  57576. if (foundIndex === -1) foundIndex = i
  57577. if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
  57578. } else {
  57579. if (foundIndex !== -1) i -= i - foundIndex
  57580. foundIndex = -1
  57581. }
  57582. }
  57583. } else {
  57584. if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength
  57585. for (i = byteOffset; i >= 0; i--) {
  57586. var found = true
  57587. for (var j = 0; j < valLength; j++) {
  57588. if (read(arr, i + j) !== read(val, j)) {
  57589. found = false
  57590. break
  57591. }
  57592. }
  57593. if (found) return i
  57594. }
  57595. }
  57596. return -1
  57597. }
  57598. Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
  57599. return this.indexOf(val, byteOffset, encoding) !== -1
  57600. }
  57601. Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
  57602. return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
  57603. }
  57604. Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
  57605. return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
  57606. }
  57607. function hexWrite (buf, string, offset, length) {
  57608. offset = Number(offset) || 0
  57609. var remaining = buf.length - offset
  57610. if (!length) {
  57611. length = remaining
  57612. } else {
  57613. length = Number(length)
  57614. if (length > remaining) {
  57615. length = remaining
  57616. }
  57617. }
  57618. var strLen = string.length
  57619. if (length > strLen / 2) {
  57620. length = strLen / 2
  57621. }
  57622. for (var i = 0; i < length; ++i) {
  57623. var parsed = parseInt(string.substr(i * 2, 2), 16)
  57624. if (numberIsNaN(parsed)) return i
  57625. buf[offset + i] = parsed
  57626. }
  57627. return i
  57628. }
  57629. function utf8Write (buf, string, offset, length) {
  57630. return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
  57631. }
  57632. function asciiWrite (buf, string, offset, length) {
  57633. return blitBuffer(asciiToBytes(string), buf, offset, length)
  57634. }
  57635. function latin1Write (buf, string, offset, length) {
  57636. return asciiWrite(buf, string, offset, length)
  57637. }
  57638. function base64Write (buf, string, offset, length) {
  57639. return blitBuffer(base64ToBytes(string), buf, offset, length)
  57640. }
  57641. function ucs2Write (buf, string, offset, length) {
  57642. return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
  57643. }
  57644. Buffer.prototype.write = function write (string, offset, length, encoding) {
  57645. // Buffer#write(string)
  57646. if (offset === undefined) {
  57647. encoding = 'utf8'
  57648. length = this.length
  57649. offset = 0
  57650. // Buffer#write(string, encoding)
  57651. } else if (length === undefined && typeof offset === 'string') {
  57652. encoding = offset
  57653. length = this.length
  57654. offset = 0
  57655. // Buffer#write(string, offset[, length][, encoding])
  57656. } else if (isFinite(offset)) {
  57657. offset = offset >>> 0
  57658. if (isFinite(length)) {
  57659. length = length >>> 0
  57660. if (encoding === undefined) encoding = 'utf8'
  57661. } else {
  57662. encoding = length
  57663. length = undefined
  57664. }
  57665. } else {
  57666. throw new Error(
  57667. 'Buffer.write(string, encoding, offset[, length]) is no longer supported'
  57668. )
  57669. }
  57670. var remaining = this.length - offset
  57671. if (length === undefined || length > remaining) length = remaining
  57672. if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
  57673. throw new RangeError('Attempt to write outside buffer bounds')
  57674. }
  57675. if (!encoding) encoding = 'utf8'
  57676. var loweredCase = false
  57677. for (;;) {
  57678. switch (encoding) {
  57679. case 'hex':
  57680. return hexWrite(this, string, offset, length)
  57681. case 'utf8':
  57682. case 'utf-8':
  57683. return utf8Write(this, string, offset, length)
  57684. case 'ascii':
  57685. return asciiWrite(this, string, offset, length)
  57686. case 'latin1':
  57687. case 'binary':
  57688. return latin1Write(this, string, offset, length)
  57689. case 'base64':
  57690. // Warning: maxLength not taken into account in base64Write
  57691. return base64Write(this, string, offset, length)
  57692. case 'ucs2':
  57693. case 'ucs-2':
  57694. case 'utf16le':
  57695. case 'utf-16le':
  57696. return ucs2Write(this, string, offset, length)
  57697. default:
  57698. if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
  57699. encoding = ('' + encoding).toLowerCase()
  57700. loweredCase = true
  57701. }
  57702. }
  57703. }
  57704. Buffer.prototype.toJSON = function toJSON () {
  57705. return {
  57706. type: 'Buffer',
  57707. data: Array.prototype.slice.call(this._arr || this, 0)
  57708. }
  57709. }
  57710. function base64Slice (buf, start, end) {
  57711. if (start === 0 && end === buf.length) {
  57712. return base64.fromByteArray(buf)
  57713. } else {
  57714. return base64.fromByteArray(buf.slice(start, end))
  57715. }
  57716. }
  57717. function utf8Slice (buf, start, end) {
  57718. end = Math.min(buf.length, end)
  57719. var res = []
  57720. var i = start
  57721. while (i < end) {
  57722. var firstByte = buf[i]
  57723. var codePoint = null
  57724. var bytesPerSequence = (firstByte > 0xEF) ? 4
  57725. : (firstByte > 0xDF) ? 3
  57726. : (firstByte > 0xBF) ? 2
  57727. : 1
  57728. if (i + bytesPerSequence <= end) {
  57729. var secondByte, thirdByte, fourthByte, tempCodePoint
  57730. switch (bytesPerSequence) {
  57731. case 1:
  57732. if (firstByte < 0x80) {
  57733. codePoint = firstByte
  57734. }
  57735. break
  57736. case 2:
  57737. secondByte = buf[i + 1]
  57738. if ((secondByte & 0xC0) === 0x80) {
  57739. tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)
  57740. if (tempCodePoint > 0x7F) {
  57741. codePoint = tempCodePoint
  57742. }
  57743. }
  57744. break
  57745. case 3:
  57746. secondByte = buf[i + 1]
  57747. thirdByte = buf[i + 2]
  57748. if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
  57749. tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)
  57750. if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
  57751. codePoint = tempCodePoint
  57752. }
  57753. }
  57754. break
  57755. case 4:
  57756. secondByte = buf[i + 1]
  57757. thirdByte = buf[i + 2]
  57758. fourthByte = buf[i + 3]
  57759. if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
  57760. tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)
  57761. if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
  57762. codePoint = tempCodePoint
  57763. }
  57764. }
  57765. }
  57766. }
  57767. if (codePoint === null) {
  57768. // we did not generate a valid codePoint so insert a
  57769. // replacement char (U+FFFD) and advance only 1 byte
  57770. codePoint = 0xFFFD
  57771. bytesPerSequence = 1
  57772. } else if (codePoint > 0xFFFF) {
  57773. // encode to utf16 (surrogate pair dance)
  57774. codePoint -= 0x10000
  57775. res.push(codePoint >>> 10 & 0x3FF | 0xD800)
  57776. codePoint = 0xDC00 | codePoint & 0x3FF
  57777. }
  57778. res.push(codePoint)
  57779. i += bytesPerSequence
  57780. }
  57781. return decodeCodePointsArray(res)
  57782. }
  57783. // Based on http://stackoverflow.com/a/22747272/680742, the browser with
  57784. // the lowest limit is Chrome, with 0x10000 args.
  57785. // We go 1 magnitude less, for safety
  57786. var MAX_ARGUMENTS_LENGTH = 0x1000
  57787. function decodeCodePointsArray (codePoints) {
  57788. var len = codePoints.length
  57789. if (len <= MAX_ARGUMENTS_LENGTH) {
  57790. return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
  57791. }
  57792. // Decode in chunks to avoid "call stack size exceeded".
  57793. var res = ''
  57794. var i = 0
  57795. while (i < len) {
  57796. res += String.fromCharCode.apply(
  57797. String,
  57798. codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
  57799. )
  57800. }
  57801. return res
  57802. }
  57803. function asciiSlice (buf, start, end) {
  57804. var ret = ''
  57805. end = Math.min(buf.length, end)
  57806. for (var i = start; i < end; ++i) {
  57807. ret += String.fromCharCode(buf[i] & 0x7F)
  57808. }
  57809. return ret
  57810. }
  57811. function latin1Slice (buf, start, end) {
  57812. var ret = ''
  57813. end = Math.min(buf.length, end)
  57814. for (var i = start; i < end; ++i) {
  57815. ret += String.fromCharCode(buf[i])
  57816. }
  57817. return ret
  57818. }
  57819. function hexSlice (buf, start, end) {
  57820. var len = buf.length
  57821. if (!start || start < 0) start = 0
  57822. if (!end || end < 0 || end > len) end = len
  57823. var out = ''
  57824. for (var i = start; i < end; ++i) {
  57825. out += toHex(buf[i])
  57826. }
  57827. return out
  57828. }
  57829. function utf16leSlice (buf, start, end) {
  57830. var bytes = buf.slice(start, end)
  57831. var res = ''
  57832. for (var i = 0; i < bytes.length; i += 2) {
  57833. res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256))
  57834. }
  57835. return res
  57836. }
  57837. Buffer.prototype.slice = function slice (start, end) {
  57838. var len = this.length
  57839. start = ~~start
  57840. end = end === undefined ? len : ~~end
  57841. if (start < 0) {
  57842. start += len
  57843. if (start < 0) start = 0
  57844. } else if (start > len) {
  57845. start = len
  57846. }
  57847. if (end < 0) {
  57848. end += len
  57849. if (end < 0) end = 0
  57850. } else if (end > len) {
  57851. end = len
  57852. }
  57853. if (end < start) end = start
  57854. var newBuf = this.subarray(start, end)
  57855. // Return an augmented `Uint8Array` instance
  57856. newBuf.__proto__ = Buffer.prototype
  57857. return newBuf
  57858. }
  57859. /*
  57860. * Need to make sure that buffer isn't trying to write out of bounds.
  57861. */
  57862. function checkOffset (offset, ext, length) {
  57863. if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
  57864. if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
  57865. }
  57866. Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
  57867. offset = offset >>> 0
  57868. byteLength = byteLength >>> 0
  57869. if (!noAssert) checkOffset(offset, byteLength, this.length)
  57870. var val = this[offset]
  57871. var mul = 1
  57872. var i = 0
  57873. while (++i < byteLength && (mul *= 0x100)) {
  57874. val += this[offset + i] * mul
  57875. }
  57876. return val
  57877. }
  57878. Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
  57879. offset = offset >>> 0
  57880. byteLength = byteLength >>> 0
  57881. if (!noAssert) {
  57882. checkOffset(offset, byteLength, this.length)
  57883. }
  57884. var val = this[offset + --byteLength]
  57885. var mul = 1
  57886. while (byteLength > 0 && (mul *= 0x100)) {
  57887. val += this[offset + --byteLength] * mul
  57888. }
  57889. return val
  57890. }
  57891. Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
  57892. offset = offset >>> 0
  57893. if (!noAssert) checkOffset(offset, 1, this.length)
  57894. return this[offset]
  57895. }
  57896. Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
  57897. offset = offset >>> 0
  57898. if (!noAssert) checkOffset(offset, 2, this.length)
  57899. return this[offset] | (this[offset + 1] << 8)
  57900. }
  57901. Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
  57902. offset = offset >>> 0
  57903. if (!noAssert) checkOffset(offset, 2, this.length)
  57904. return (this[offset] << 8) | this[offset + 1]
  57905. }
  57906. Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
  57907. offset = offset >>> 0
  57908. if (!noAssert) checkOffset(offset, 4, this.length)
  57909. return ((this[offset]) |
  57910. (this[offset + 1] << 8) |
  57911. (this[offset + 2] << 16)) +
  57912. (this[offset + 3] * 0x1000000)
  57913. }
  57914. Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
  57915. offset = offset >>> 0
  57916. if (!noAssert) checkOffset(offset, 4, this.length)
  57917. return (this[offset] * 0x1000000) +
  57918. ((this[offset + 1] << 16) |
  57919. (this[offset + 2] << 8) |
  57920. this[offset + 3])
  57921. }
  57922. Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
  57923. offset = offset >>> 0
  57924. byteLength = byteLength >>> 0
  57925. if (!noAssert) checkOffset(offset, byteLength, this.length)
  57926. var val = this[offset]
  57927. var mul = 1
  57928. var i = 0
  57929. while (++i < byteLength && (mul *= 0x100)) {
  57930. val += this[offset + i] * mul
  57931. }
  57932. mul *= 0x80
  57933. if (val >= mul) val -= Math.pow(2, 8 * byteLength)
  57934. return val
  57935. }
  57936. Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
  57937. offset = offset >>> 0
  57938. byteLength = byteLength >>> 0
  57939. if (!noAssert) checkOffset(offset, byteLength, this.length)
  57940. var i = byteLength
  57941. var mul = 1
  57942. var val = this[offset + --i]
  57943. while (i > 0 && (mul *= 0x100)) {
  57944. val += this[offset + --i] * mul
  57945. }
  57946. mul *= 0x80
  57947. if (val >= mul) val -= Math.pow(2, 8 * byteLength)
  57948. return val
  57949. }
  57950. Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
  57951. offset = offset >>> 0
  57952. if (!noAssert) checkOffset(offset, 1, this.length)
  57953. if (!(this[offset] & 0x80)) return (this[offset])
  57954. return ((0xff - this[offset] + 1) * -1)
  57955. }
  57956. Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
  57957. offset = offset >>> 0
  57958. if (!noAssert) checkOffset(offset, 2, this.length)
  57959. var val = this[offset] | (this[offset + 1] << 8)
  57960. return (val & 0x8000) ? val | 0xFFFF0000 : val
  57961. }
  57962. Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
  57963. offset = offset >>> 0
  57964. if (!noAssert) checkOffset(offset, 2, this.length)
  57965. var val = this[offset + 1] | (this[offset] << 8)
  57966. return (val & 0x8000) ? val | 0xFFFF0000 : val
  57967. }
  57968. Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
  57969. offset = offset >>> 0
  57970. if (!noAssert) checkOffset(offset, 4, this.length)
  57971. return (this[offset]) |
  57972. (this[offset + 1] << 8) |
  57973. (this[offset + 2] << 16) |
  57974. (this[offset + 3] << 24)
  57975. }
  57976. Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
  57977. offset = offset >>> 0
  57978. if (!noAssert) checkOffset(offset, 4, this.length)
  57979. return (this[offset] << 24) |
  57980. (this[offset + 1] << 16) |
  57981. (this[offset + 2] << 8) |
  57982. (this[offset + 3])
  57983. }
  57984. Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
  57985. offset = offset >>> 0
  57986. if (!noAssert) checkOffset(offset, 4, this.length)
  57987. return ieee754.read(this, offset, true, 23, 4)
  57988. }
  57989. Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
  57990. offset = offset >>> 0
  57991. if (!noAssert) checkOffset(offset, 4, this.length)
  57992. return ieee754.read(this, offset, false, 23, 4)
  57993. }
  57994. Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
  57995. offset = offset >>> 0
  57996. if (!noAssert) checkOffset(offset, 8, this.length)
  57997. return ieee754.read(this, offset, true, 52, 8)
  57998. }
  57999. Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
  58000. offset = offset >>> 0
  58001. if (!noAssert) checkOffset(offset, 8, this.length)
  58002. return ieee754.read(this, offset, false, 52, 8)
  58003. }
  58004. function checkInt (buf, value, offset, ext, max, min) {
  58005. if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance')
  58006. if (value > max || value < min) throw new RangeError('"value" argument is out of bounds')
  58007. if (offset + ext > buf.length) throw new RangeError('Index out of range')
  58008. }
  58009. Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
  58010. value = +value
  58011. offset = offset >>> 0
  58012. byteLength = byteLength >>> 0
  58013. if (!noAssert) {
  58014. var maxBytes = Math.pow(2, 8 * byteLength) - 1
  58015. checkInt(this, value, offset, byteLength, maxBytes, 0)
  58016. }
  58017. var mul = 1
  58018. var i = 0
  58019. this[offset] = value & 0xFF
  58020. while (++i < byteLength && (mul *= 0x100)) {
  58021. this[offset + i] = (value / mul) & 0xFF
  58022. }
  58023. return offset + byteLength
  58024. }
  58025. Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
  58026. value = +value
  58027. offset = offset >>> 0
  58028. byteLength = byteLength >>> 0
  58029. if (!noAssert) {
  58030. var maxBytes = Math.pow(2, 8 * byteLength) - 1
  58031. checkInt(this, value, offset, byteLength, maxBytes, 0)
  58032. }
  58033. var i = byteLength - 1
  58034. var mul = 1
  58035. this[offset + i] = value & 0xFF
  58036. while (--i >= 0 && (mul *= 0x100)) {
  58037. this[offset + i] = (value / mul) & 0xFF
  58038. }
  58039. return offset + byteLength
  58040. }
  58041. Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
  58042. value = +value
  58043. offset = offset >>> 0
  58044. if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)
  58045. this[offset] = (value & 0xff)
  58046. return offset + 1
  58047. }
  58048. Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
  58049. value = +value
  58050. offset = offset >>> 0
  58051. if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
  58052. this[offset] = (value & 0xff)
  58053. this[offset + 1] = (value >>> 8)
  58054. return offset + 2
  58055. }
  58056. Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
  58057. value = +value
  58058. offset = offset >>> 0
  58059. if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
  58060. this[offset] = (value >>> 8)
  58061. this[offset + 1] = (value & 0xff)
  58062. return offset + 2
  58063. }
  58064. Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
  58065. value = +value
  58066. offset = offset >>> 0
  58067. if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
  58068. this[offset + 3] = (value >>> 24)
  58069. this[offset + 2] = (value >>> 16)
  58070. this[offset + 1] = (value >>> 8)
  58071. this[offset] = (value & 0xff)
  58072. return offset + 4
  58073. }
  58074. Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
  58075. value = +value
  58076. offset = offset >>> 0
  58077. if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
  58078. this[offset] = (value >>> 24)
  58079. this[offset + 1] = (value >>> 16)
  58080. this[offset + 2] = (value >>> 8)
  58081. this[offset + 3] = (value & 0xff)
  58082. return offset + 4
  58083. }
  58084. Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
  58085. value = +value
  58086. offset = offset >>> 0
  58087. if (!noAssert) {
  58088. var limit = Math.pow(2, (8 * byteLength) - 1)
  58089. checkInt(this, value, offset, byteLength, limit - 1, -limit)
  58090. }
  58091. var i = 0
  58092. var mul = 1
  58093. var sub = 0
  58094. this[offset] = value & 0xFF
  58095. while (++i < byteLength && (mul *= 0x100)) {
  58096. if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
  58097. sub = 1
  58098. }
  58099. this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
  58100. }
  58101. return offset + byteLength
  58102. }
  58103. Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
  58104. value = +value
  58105. offset = offset >>> 0
  58106. if (!noAssert) {
  58107. var limit = Math.pow(2, (8 * byteLength) - 1)
  58108. checkInt(this, value, offset, byteLength, limit - 1, -limit)
  58109. }
  58110. var i = byteLength - 1
  58111. var mul = 1
  58112. var sub = 0
  58113. this[offset + i] = value & 0xFF
  58114. while (--i >= 0 && (mul *= 0x100)) {
  58115. if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
  58116. sub = 1
  58117. }
  58118. this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
  58119. }
  58120. return offset + byteLength
  58121. }
  58122. Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
  58123. value = +value
  58124. offset = offset >>> 0
  58125. if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)
  58126. if (value < 0) value = 0xff + value + 1
  58127. this[offset] = (value & 0xff)
  58128. return offset + 1
  58129. }
  58130. Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
  58131. value = +value
  58132. offset = offset >>> 0
  58133. if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
  58134. this[offset] = (value & 0xff)
  58135. this[offset + 1] = (value >>> 8)
  58136. return offset + 2
  58137. }
  58138. Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
  58139. value = +value
  58140. offset = offset >>> 0
  58141. if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
  58142. this[offset] = (value >>> 8)
  58143. this[offset + 1] = (value & 0xff)
  58144. return offset + 2
  58145. }
  58146. Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
  58147. value = +value
  58148. offset = offset >>> 0
  58149. if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
  58150. this[offset] = (value & 0xff)
  58151. this[offset + 1] = (value >>> 8)
  58152. this[offset + 2] = (value >>> 16)
  58153. this[offset + 3] = (value >>> 24)
  58154. return offset + 4
  58155. }
  58156. Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
  58157. value = +value
  58158. offset = offset >>> 0
  58159. if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
  58160. if (value < 0) value = 0xffffffff + value + 1
  58161. this[offset] = (value >>> 24)
  58162. this[offset + 1] = (value >>> 16)
  58163. this[offset + 2] = (value >>> 8)
  58164. this[offset + 3] = (value & 0xff)
  58165. return offset + 4
  58166. }
  58167. function checkIEEE754 (buf, value, offset, ext, max, min) {
  58168. if (offset + ext > buf.length) throw new RangeError('Index out of range')
  58169. if (offset < 0) throw new RangeError('Index out of range')
  58170. }
  58171. function writeFloat (buf, value, offset, littleEndian, noAssert) {
  58172. value = +value
  58173. offset = offset >>> 0
  58174. if (!noAssert) {
  58175. checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
  58176. }
  58177. ieee754.write(buf, value, offset, littleEndian, 23, 4)
  58178. return offset + 4
  58179. }
  58180. Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
  58181. return writeFloat(this, value, offset, true, noAssert)
  58182. }
  58183. Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
  58184. return writeFloat(this, value, offset, false, noAssert)
  58185. }
  58186. function writeDouble (buf, value, offset, littleEndian, noAssert) {
  58187. value = +value
  58188. offset = offset >>> 0
  58189. if (!noAssert) {
  58190. checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
  58191. }
  58192. ieee754.write(buf, value, offset, littleEndian, 52, 8)
  58193. return offset + 8
  58194. }
  58195. Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
  58196. return writeDouble(this, value, offset, true, noAssert)
  58197. }
  58198. Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
  58199. return writeDouble(this, value, offset, false, noAssert)
  58200. }
  58201. // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
  58202. Buffer.prototype.copy = function copy (target, targetStart, start, end) {
  58203. if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer')
  58204. if (!start) start = 0
  58205. if (!end && end !== 0) end = this.length
  58206. if (targetStart >= target.length) targetStart = target.length
  58207. if (!targetStart) targetStart = 0
  58208. if (end > 0 && end < start) end = start
  58209. // Copy 0 bytes; we're done
  58210. if (end === start) return 0
  58211. if (target.length === 0 || this.length === 0) return 0
  58212. // Fatal error conditions
  58213. if (targetStart < 0) {
  58214. throw new RangeError('targetStart out of bounds')
  58215. }
  58216. if (start < 0 || start >= this.length) throw new RangeError('Index out of range')
  58217. if (end < 0) throw new RangeError('sourceEnd out of bounds')
  58218. // Are we oob?
  58219. if (end > this.length) end = this.length
  58220. if (target.length - targetStart < end - start) {
  58221. end = target.length - targetStart + start
  58222. }
  58223. var len = end - start
  58224. if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') {
  58225. // Use built-in when available, missing from IE11
  58226. this.copyWithin(targetStart, start, end)
  58227. } else if (this === target && start < targetStart && targetStart < end) {
  58228. // descending copy from end
  58229. for (var i = len - 1; i >= 0; --i) {
  58230. target[i + targetStart] = this[i + start]
  58231. }
  58232. } else {
  58233. Uint8Array.prototype.set.call(
  58234. target,
  58235. this.subarray(start, end),
  58236. targetStart
  58237. )
  58238. }
  58239. return len
  58240. }
  58241. // Usage:
  58242. // buffer.fill(number[, offset[, end]])
  58243. // buffer.fill(buffer[, offset[, end]])
  58244. // buffer.fill(string[, offset[, end]][, encoding])
  58245. Buffer.prototype.fill = function fill (val, start, end, encoding) {
  58246. // Handle string cases:
  58247. if (typeof val === 'string') {
  58248. if (typeof start === 'string') {
  58249. encoding = start
  58250. start = 0
  58251. end = this.length
  58252. } else if (typeof end === 'string') {
  58253. encoding = end
  58254. end = this.length
  58255. }
  58256. if (encoding !== undefined && typeof encoding !== 'string') {
  58257. throw new TypeError('encoding must be a string')
  58258. }
  58259. if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
  58260. throw new TypeError('Unknown encoding: ' + encoding)
  58261. }
  58262. if (val.length === 1) {
  58263. var code = val.charCodeAt(0)
  58264. if ((encoding === 'utf8' && code < 128) ||
  58265. encoding === 'latin1') {
  58266. // Fast path: If `val` fits into a single byte, use that numeric value.
  58267. val = code
  58268. }
  58269. }
  58270. } else if (typeof val === 'number') {
  58271. val = val & 255
  58272. }
  58273. // Invalid ranges are not set to a default, so can range check early.
  58274. if (start < 0 || this.length < start || this.length < end) {
  58275. throw new RangeError('Out of range index')
  58276. }
  58277. if (end <= start) {
  58278. return this
  58279. }
  58280. start = start >>> 0
  58281. end = end === undefined ? this.length : end >>> 0
  58282. if (!val) val = 0
  58283. var i
  58284. if (typeof val === 'number') {
  58285. for (i = start; i < end; ++i) {
  58286. this[i] = val
  58287. }
  58288. } else {
  58289. var bytes = Buffer.isBuffer(val)
  58290. ? val
  58291. : Buffer.from(val, encoding)
  58292. var len = bytes.length
  58293. if (len === 0) {
  58294. throw new TypeError('The value "' + val +
  58295. '" is invalid for argument "value"')
  58296. }
  58297. for (i = 0; i < end - start; ++i) {
  58298. this[i + start] = bytes[i % len]
  58299. }
  58300. }
  58301. return this
  58302. }
  58303. // HELPER FUNCTIONS
  58304. // ================
  58305. var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g
  58306. function base64clean (str) {
  58307. // Node takes equal signs as end of the Base64 encoding
  58308. str = str.split('=')[0]
  58309. // Node strips out invalid characters like \n and \t from the string, base64-js does not
  58310. str = str.trim().replace(INVALID_BASE64_RE, '')
  58311. // Node converts strings with length < 2 to ''
  58312. if (str.length < 2) return ''
  58313. // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
  58314. while (str.length % 4 !== 0) {
  58315. str = str + '='
  58316. }
  58317. return str
  58318. }
  58319. function toHex (n) {
  58320. if (n < 16) return '0' + n.toString(16)
  58321. return n.toString(16)
  58322. }
  58323. function utf8ToBytes (string, units) {
  58324. units = units || Infinity
  58325. var codePoint
  58326. var length = string.length
  58327. var leadSurrogate = null
  58328. var bytes = []
  58329. for (var i = 0; i < length; ++i) {
  58330. codePoint = string.charCodeAt(i)
  58331. // is surrogate component
  58332. if (codePoint > 0xD7FF && codePoint < 0xE000) {
  58333. // last char was a lead
  58334. if (!leadSurrogate) {
  58335. // no lead yet
  58336. if (codePoint > 0xDBFF) {
  58337. // unexpected trail
  58338. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  58339. continue
  58340. } else if (i + 1 === length) {
  58341. // unpaired lead
  58342. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  58343. continue
  58344. }
  58345. // valid lead
  58346. leadSurrogate = codePoint
  58347. continue
  58348. }
  58349. // 2 leads in a row
  58350. if (codePoint < 0xDC00) {
  58351. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  58352. leadSurrogate = codePoint
  58353. continue
  58354. }
  58355. // valid surrogate pair
  58356. codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000
  58357. } else if (leadSurrogate) {
  58358. // valid bmp char, but last char was a lead
  58359. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  58360. }
  58361. leadSurrogate = null
  58362. // encode utf8
  58363. if (codePoint < 0x80) {
  58364. if ((units -= 1) < 0) break
  58365. bytes.push(codePoint)
  58366. } else if (codePoint < 0x800) {
  58367. if ((units -= 2) < 0) break
  58368. bytes.push(
  58369. codePoint >> 0x6 | 0xC0,
  58370. codePoint & 0x3F | 0x80
  58371. )
  58372. } else if (codePoint < 0x10000) {
  58373. if ((units -= 3) < 0) break
  58374. bytes.push(
  58375. codePoint >> 0xC | 0xE0,
  58376. codePoint >> 0x6 & 0x3F | 0x80,
  58377. codePoint & 0x3F | 0x80
  58378. )
  58379. } else if (codePoint < 0x110000) {
  58380. if ((units -= 4) < 0) break
  58381. bytes.push(
  58382. codePoint >> 0x12 | 0xF0,
  58383. codePoint >> 0xC & 0x3F | 0x80,
  58384. codePoint >> 0x6 & 0x3F | 0x80,
  58385. codePoint & 0x3F | 0x80
  58386. )
  58387. } else {
  58388. throw new Error('Invalid code point')
  58389. }
  58390. }
  58391. return bytes
  58392. }
  58393. function asciiToBytes (str) {
  58394. var byteArray = []
  58395. for (var i = 0; i < str.length; ++i) {
  58396. // Node's code seems to be doing this and not & 0x7F..
  58397. byteArray.push(str.charCodeAt(i) & 0xFF)
  58398. }
  58399. return byteArray
  58400. }
  58401. function utf16leToBytes (str, units) {
  58402. var c, hi, lo
  58403. var byteArray = []
  58404. for (var i = 0; i < str.length; ++i) {
  58405. if ((units -= 2) < 0) break
  58406. c = str.charCodeAt(i)
  58407. hi = c >> 8
  58408. lo = c % 256
  58409. byteArray.push(lo)
  58410. byteArray.push(hi)
  58411. }
  58412. return byteArray
  58413. }
  58414. function base64ToBytes (str) {
  58415. return base64.toByteArray(base64clean(str))
  58416. }
  58417. function blitBuffer (src, dst, offset, length) {
  58418. for (var i = 0; i < length; ++i) {
  58419. if ((i + offset >= dst.length) || (i >= src.length)) break
  58420. dst[i + offset] = src[i]
  58421. }
  58422. return i
  58423. }
  58424. // ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass
  58425. // the `instanceof` check but they should be treated as of that type.
  58426. // See: https://github.com/feross/buffer/issues/166
  58427. function isInstance (obj, type) {
  58428. return obj instanceof type ||
  58429. (obj != null && obj.constructor != null && obj.constructor.name != null &&
  58430. obj.constructor.name === type.name)
  58431. }
  58432. function numberIsNaN (obj) {
  58433. // For IE11 support
  58434. return obj !== obj // eslint-disable-line no-self-compare
  58435. }
  58436. }).call(this,require("buffer").Buffer)
  58437. },{"base64-js":5,"buffer":6,"ieee754":7}],7:[function(require,module,exports){
  58438. exports.read = function (buffer, offset, isLE, mLen, nBytes) {
  58439. var e, m
  58440. var eLen = (nBytes * 8) - mLen - 1
  58441. var eMax = (1 << eLen) - 1
  58442. var eBias = eMax >> 1
  58443. var nBits = -7
  58444. var i = isLE ? (nBytes - 1) : 0
  58445. var d = isLE ? -1 : 1
  58446. var s = buffer[offset + i]
  58447. i += d
  58448. e = s & ((1 << (-nBits)) - 1)
  58449. s >>= (-nBits)
  58450. nBits += eLen
  58451. for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {}
  58452. m = e & ((1 << (-nBits)) - 1)
  58453. e >>= (-nBits)
  58454. nBits += mLen
  58455. for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {}
  58456. if (e === 0) {
  58457. e = 1 - eBias
  58458. } else if (e === eMax) {
  58459. return m ? NaN : ((s ? -1 : 1) * Infinity)
  58460. } else {
  58461. m = m + Math.pow(2, mLen)
  58462. e = e - eBias
  58463. }
  58464. return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
  58465. }
  58466. exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
  58467. var e, m, c
  58468. var eLen = (nBytes * 8) - mLen - 1
  58469. var eMax = (1 << eLen) - 1
  58470. var eBias = eMax >> 1
  58471. var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)
  58472. var i = isLE ? 0 : (nBytes - 1)
  58473. var d = isLE ? 1 : -1
  58474. var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0
  58475. value = Math.abs(value)
  58476. if (isNaN(value) || value === Infinity) {
  58477. m = isNaN(value) ? 1 : 0
  58478. e = eMax
  58479. } else {
  58480. e = Math.floor(Math.log(value) / Math.LN2)
  58481. if (value * (c = Math.pow(2, -e)) < 1) {
  58482. e--
  58483. c *= 2
  58484. }
  58485. if (e + eBias >= 1) {
  58486. value += rt / c
  58487. } else {
  58488. value += rt * Math.pow(2, 1 - eBias)
  58489. }
  58490. if (value * c >= 2) {
  58491. e++
  58492. c /= 2
  58493. }
  58494. if (e + eBias >= eMax) {
  58495. m = 0
  58496. e = eMax
  58497. } else if (e + eBias >= 1) {
  58498. m = ((value * c) - 1) * Math.pow(2, mLen)
  58499. e = e + eBias
  58500. } else {
  58501. m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
  58502. e = 0
  58503. }
  58504. }
  58505. for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
  58506. e = (e << mLen) | m
  58507. eLen += mLen
  58508. for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
  58509. buffer[offset + i - d] |= s * 128
  58510. }
  58511. },{}],8:[function(require,module,exports){
  58512. (function (setImmediate,clearImmediate){
  58513. var nextTick = require('process/browser.js').nextTick;
  58514. var apply = Function.prototype.apply;
  58515. var slice = Array.prototype.slice;
  58516. var immediateIds = {};
  58517. var nextImmediateId = 0;
  58518. // DOM APIs, for completeness
  58519. exports.setTimeout = function() {
  58520. return new Timeout(apply.call(setTimeout, window, arguments), clearTimeout);
  58521. };
  58522. exports.setInterval = function() {
  58523. return new Timeout(apply.call(setInterval, window, arguments), clearInterval);
  58524. };
  58525. exports.clearTimeout =
  58526. exports.clearInterval = function(timeout) { timeout.close(); };
  58527. function Timeout(id, clearFn) {
  58528. this._id = id;
  58529. this._clearFn = clearFn;
  58530. }
  58531. Timeout.prototype.unref = Timeout.prototype.ref = function() {};
  58532. Timeout.prototype.close = function() {
  58533. this._clearFn.call(window, this._id);
  58534. };
  58535. // Does not start the time, just sets up the members needed.
  58536. exports.enroll = function(item, msecs) {
  58537. clearTimeout(item._idleTimeoutId);
  58538. item._idleTimeout = msecs;
  58539. };
  58540. exports.unenroll = function(item) {
  58541. clearTimeout(item._idleTimeoutId);
  58542. item._idleTimeout = -1;
  58543. };
  58544. exports._unrefActive = exports.active = function(item) {
  58545. clearTimeout(item._idleTimeoutId);
  58546. var msecs = item._idleTimeout;
  58547. if (msecs >= 0) {
  58548. item._idleTimeoutId = setTimeout(function onTimeout() {
  58549. if (item._onTimeout)
  58550. item._onTimeout();
  58551. }, msecs);
  58552. }
  58553. };
  58554. // That's not how node.js implements it but the exposed api is the same.
  58555. exports.setImmediate = typeof setImmediate === "function" ? setImmediate : function(fn) {
  58556. var id = nextImmediateId++;
  58557. var args = arguments.length < 2 ? false : slice.call(arguments, 1);
  58558. immediateIds[id] = true;
  58559. nextTick(function onNextTick() {
  58560. if (immediateIds[id]) {
  58561. // fn.call() is faster so we optimize for the common use-case
  58562. // @see http://jsperf.com/call-apply-segu
  58563. if (args) {
  58564. fn.apply(null, args);
  58565. } else {
  58566. fn.call(null);
  58567. }
  58568. // Prevent ids from leaking
  58569. exports.clearImmediate(id);
  58570. }
  58571. });
  58572. return id;
  58573. };
  58574. exports.clearImmediate = typeof clearImmediate === "function" ? clearImmediate : function(id) {
  58575. delete immediateIds[id];
  58576. };
  58577. }).call(this,require("timers").setImmediate,require("timers").clearImmediate)
  58578. },{"process/browser.js":9,"timers":8}],9:[function(require,module,exports){
  58579. // shim for using process in browser
  58580. var process = module.exports = {};
  58581. // cached from whatever global is present so that test runners that stub it
  58582. // don't break things. But we need to wrap it in a try catch in case it is
  58583. // wrapped in strict mode code which doesn't define any globals. It's inside a
  58584. // function because try/catches deoptimize in certain engines.
  58585. var cachedSetTimeout;
  58586. var cachedClearTimeout;
  58587. function defaultSetTimout() {
  58588. throw new Error('setTimeout has not been defined');
  58589. }
  58590. function defaultClearTimeout () {
  58591. throw new Error('clearTimeout has not been defined');
  58592. }
  58593. (function () {
  58594. try {
  58595. if (typeof setTimeout === 'function') {
  58596. cachedSetTimeout = setTimeout;
  58597. } else {
  58598. cachedSetTimeout = defaultSetTimout;
  58599. }
  58600. } catch (e) {
  58601. cachedSetTimeout = defaultSetTimout;
  58602. }
  58603. try {
  58604. if (typeof clearTimeout === 'function') {
  58605. cachedClearTimeout = clearTimeout;
  58606. } else {
  58607. cachedClearTimeout = defaultClearTimeout;
  58608. }
  58609. } catch (e) {
  58610. cachedClearTimeout = defaultClearTimeout;
  58611. }
  58612. } ())
  58613. function runTimeout(fun) {
  58614. if (cachedSetTimeout === setTimeout) {
  58615. //normal enviroments in sane situations
  58616. return setTimeout(fun, 0);
  58617. }
  58618. // if setTimeout wasn't available but was latter defined
  58619. if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
  58620. cachedSetTimeout = setTimeout;
  58621. return setTimeout(fun, 0);
  58622. }
  58623. try {
  58624. // when when somebody has screwed with setTimeout but no I.E. maddness
  58625. return cachedSetTimeout(fun, 0);
  58626. } catch(e){
  58627. try {
  58628. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  58629. return cachedSetTimeout.call(null, fun, 0);
  58630. } catch(e){
  58631. // 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
  58632. return cachedSetTimeout.call(this, fun, 0);
  58633. }
  58634. }
  58635. }
  58636. function runClearTimeout(marker) {
  58637. if (cachedClearTimeout === clearTimeout) {
  58638. //normal enviroments in sane situations
  58639. return clearTimeout(marker);
  58640. }
  58641. // if clearTimeout wasn't available but was latter defined
  58642. if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
  58643. cachedClearTimeout = clearTimeout;
  58644. return clearTimeout(marker);
  58645. }
  58646. try {
  58647. // when when somebody has screwed with setTimeout but no I.E. maddness
  58648. return cachedClearTimeout(marker);
  58649. } catch (e){
  58650. try {
  58651. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  58652. return cachedClearTimeout.call(null, marker);
  58653. } catch (e){
  58654. // 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.
  58655. // Some versions of I.E. have different rules for clearTimeout vs setTimeout
  58656. return cachedClearTimeout.call(this, marker);
  58657. }
  58658. }
  58659. }
  58660. var queue = [];
  58661. var draining = false;
  58662. var currentQueue;
  58663. var queueIndex = -1;
  58664. function cleanUpNextTick() {
  58665. if (!draining || !currentQueue) {
  58666. return;
  58667. }
  58668. draining = false;
  58669. if (currentQueue.length) {
  58670. queue = currentQueue.concat(queue);
  58671. } else {
  58672. queueIndex = -1;
  58673. }
  58674. if (queue.length) {
  58675. drainQueue();
  58676. }
  58677. }
  58678. function drainQueue() {
  58679. if (draining) {
  58680. return;
  58681. }
  58682. var timeout = runTimeout(cleanUpNextTick);
  58683. draining = true;
  58684. var len = queue.length;
  58685. while(len) {
  58686. currentQueue = queue;
  58687. queue = [];
  58688. while (++queueIndex < len) {
  58689. if (currentQueue) {
  58690. currentQueue[queueIndex].run();
  58691. }
  58692. }
  58693. queueIndex = -1;
  58694. len = queue.length;
  58695. }
  58696. currentQueue = null;
  58697. draining = false;
  58698. runClearTimeout(timeout);
  58699. }
  58700. process.nextTick = function (fun) {
  58701. var args = new Array(arguments.length - 1);
  58702. if (arguments.length > 1) {
  58703. for (var i = 1; i < arguments.length; i++) {
  58704. args[i - 1] = arguments[i];
  58705. }
  58706. }
  58707. queue.push(new Item(fun, args));
  58708. if (queue.length === 1 && !draining) {
  58709. runTimeout(drainQueue);
  58710. }
  58711. };
  58712. // v8 likes predictible objects
  58713. function Item(fun, array) {
  58714. this.fun = fun;
  58715. this.array = array;
  58716. }
  58717. Item.prototype.run = function () {
  58718. this.fun.apply(null, this.array);
  58719. };
  58720. process.title = 'browser';
  58721. process.browser = true;
  58722. process.env = {};
  58723. process.argv = [];
  58724. process.version = ''; // empty string to avoid regexp issues
  58725. process.versions = {};
  58726. function noop() {}
  58727. process.on = noop;
  58728. process.addListener = noop;
  58729. process.once = noop;
  58730. process.off = noop;
  58731. process.removeListener = noop;
  58732. process.removeAllListeners = noop;
  58733. process.emit = noop;
  58734. process.prependListener = noop;
  58735. process.prependOnceListener = noop;
  58736. process.listeners = function (name) { return [] }
  58737. process.binding = function (name) {
  58738. throw new Error('process.binding is not supported');
  58739. };
  58740. process.cwd = function () { return '/' };
  58741. process.chdir = function (dir) {
  58742. throw new Error('process.chdir is not supported');
  58743. };
  58744. process.umask = function() { return 0; };
  58745. },{}]},{},[2]);